branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>burgess666/LibrarySystem<file_sep>/library/login.php
<?php
require_once "conn.php";
session_start();
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$rows = mysql_num_rows($result);
if($rows == 1)
{
$_SESSION['loggedInUser'] = $username;
$_SESSION['loggedPass'] = $password;
header("location:home.php");
}
else
{
echo "No user found!";
die(mysql_error());
}
?><file_sep>/library/conn.php
<?php
//connect to database
mysql_connect('localhost', '', '') or die(mysql_error());
mysql_select_db("library_system") or die(mysql_error());
if(mysqli_connect_errno())
{
printf("Connection failed: %s\n",mysqli_connect_error());
exit();
}
?> | 216bd3acec11da1b7cee1e67f188d49655b59fac | [
"PHP"
]
| 2 | PHP | burgess666/LibrarySystem | e0eef29eb68429651a0ffc9e97d6f26c51ed222f | 190d4cc8e3259e3562582d91fb4f419a8dcb63ec |
refs/heads/main | <repo_name>cyberflax/cyberflaxlabs<file_sep>/service/admin.py
from django.contrib import admin
from . models import service,ServiceSubMenu,subservices,sub_expertise,subproject,headbanner,expertise,sub_expertise_icon,WhatWeDo,serviceFact,sub_benifit,sub_serviceWeOffer,devLifecycle,engagement,expertiseWithTitleIcon,middleimage,bottomdiv
class headbannerAdmin(admin.ModelAdmin):
list_display = ('service','sub_service')
class subprojectAdmin(admin.ModelAdmin):
list_display = ('services','project_type','name')
class sub_expertiseAdmin(admin.ModelAdmin):
list_display = ('subservices','expertise')
class sub_serviceWeOfferAdmin(admin.ModelAdmin):
list_display = ('services','subservices')
class sub_benifitAdmin(admin.ModelAdmin):
list_display = ('services','subservices')
class ServiceSubMenuAdmin(admin.ModelAdmin):
list_display = ('Service','Submenu')
class expertiseAdmin(admin.ModelAdmin):
list_display = ('services','Select_type')
class sub_expertise_iconAdmin(admin.ModelAdmin):
list_display = ('services','subservices')
class expertiseWithTitleIconAdmin(admin.ModelAdmin):
list_display = ('services','subservices')
class WhatWeDoAdmin(admin.ModelAdmin):
list_display = ('services','subservices')
class serviceFactAdmin(admin.ModelAdmin):
list_display = ('services','subservices')
class devLifecycleAdmin(admin.ModelAdmin):
list_display = ('services','subservices')
class engagementAdmin(admin.ModelAdmin):
list_display = ('services','subservices')
class middleimageAdmin(admin.ModelAdmin):
list_display = ('services','subservices')
class bottomdivAdmin(admin.ModelAdmin):
list_display = ('services','subservices')
# Register your models here.
admin.site.register(service)
admin.site.register(ServiceSubMenu,ServiceSubMenuAdmin)
admin.site.register(middleimage,middleimageAdmin)
admin.site.register(subservices)
admin.site.register(expertise,expertiseAdmin)
admin.site.register(bottomdiv,bottomdivAdmin)
admin.site.register(sub_expertise_icon, sub_expertise_iconAdmin)
admin.site.register(WhatWeDo,WhatWeDoAdmin)
admin.site.register(devLifecycle,devLifecycleAdmin)
admin.site.register(sub_serviceWeOffer,sub_serviceWeOfferAdmin)
admin.site.register(sub_benifit,sub_benifitAdmin)
admin.site.register(serviceFact,serviceFactAdmin)
admin.site.register(expertiseWithTitleIcon,expertiseWithTitleIconAdmin)
admin.site.register(engagement,engagementAdmin)
admin.site.register(sub_expertise,sub_expertiseAdmin)
admin.site.register(subproject,subprojectAdmin)
admin.site.register(headbanner,headbannerAdmin)<file_sep>/ourwork/urls.py
from django.contrib import admin
from django.urls import path,include
from . import views
from . models import ourwork_cat
urlpatterns = [
path('', views.work, name = 'service'),
path('<slug:num1>/', views.work, name = 'service'),
]<file_sep>/InspironHome/admin.py
from django.contrib import admin
# Register your models here.
from .models import project,ourwork,homebanner
admin.site.register(project)
admin.site.register(homebanner)
<file_sep>/blog/admin.py
from django.contrib import admin
from . models import blog,catagory,News
# Register your models here.
admin.site.register(catagory)
admin.site.register(blog)
admin.site.register(News)<file_sep>/InspironHome/views.py
from django.shortcuts import render
from .models import project,homebanner
from service.models import service,ServiceSubMenu
def index(request):
Service = service.objects.all()
Project = project.objects.all()
banners = homebanner.objects.all()
responce = {
'title':'HOME PAGE',
'home':'active',
'service': Service,
'projects':Project,
'banners': banners
}
return render(request , 'index.html',responce)
def about(request):
# qry = 'inspiron'
# ob = service.objects.values('id','content')
# for i in ob:
# if qry in i['content'].lower():
# a= i['content'].lower().replace(qry, 'Cyberflax')
# sub = service.objects.get(id = i['id'])
# sub.content= a
# sub.save()
# else:
# print("false")
a= search()
responce = {
'title':'ABOUT PAGE',
'about':'active',
}
return render(request , 'about.html',responce)
def search():
# qry = 'inspiron'
# s= []
# for item in s:
# ob = item._meta.get_fields()
# for i in ob :
# c=i
# i = str(i)
# if '<' in i:
# continue
# res = i.rfind('.')
# if res != -1:
# i = (i[res+1:])
# ser = item.objects.values(i,"id")
# for a in ser:
# b= str(a[i])
# if qry in b.lower():
# b= b.lower().replace(qry, 'Cyberflax')
# print('true',i)
# else:
# pass
return 'res'<file_sep>/ourwork/admin.py
from django.contrib import admin
from .models import ourwork_cat,headbanner,Work
# Register your models here.
@admin.register(Work)
class WorkAdmin(admin.ModelAdmin):
list_display = ['catagory','projectTitle','content']
admin.site.register(ourwork_cat)
admin.site.register(headbanner)
<file_sep>/contact/urls.py
from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
path('', views.contact, name = 'contact'),
]<file_sep>/contact/views.py
from django.shortcuts import render
from . models import OurContact,contactReq
from service.models import service
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.core.mail import send_mail
from InspironHome.settings import EMAIL_HOST_USER
from google.googlecontact import upcontact
# Create your views here.
def contact(request):
if request.method == "POST":
name = request.POST['txtName']
email = request.POST['txtEmail']
Phone = request.POST['txtPhone']
intrest = request.POST['txtKnow']
Message = request.POST['txtMessage']
if intrest == 'others':
Service = "others"
else:
Service = service.objects.get(id = intrest).title
Contact = contactReq(name = name , email = email , Phone = Phone , intrest = Service , Message = Message)
Contact.save()
upcontact(name , Phone , email)
subject = 'You Have Contact | InspironLabs'
html_message = render_to_string('contact/email.html', {'name': name , 'phone':Phone , 'email':email , "massage": Message,'intrest': Service})
plain_message = strip_tags(html_message)
from_email = EMAIL_HOST_USER
# to = '<EMAIL>'
to = '<EMAIL>'
send_mail(subject, plain_message, from_email, [to], html_message=html_message)
Contact = OurContact.objects.all()
res = {
'title': 'contact',
'contact' : Contact,
}
return render(request, 'contact/contact.html',res)<file_sep>/InspironHome/context_processors.py
from service.models import service,ServiceSubMenu,subservices,sub_serviceWeOffer
from .models import ourwork
from ourwork.models import ourwork_cat
def alltimefunc(request):
services = service.objects.values('id','title')
work = ourwork_cat.objects.values('title')
for ser in services:
sObject = service.objects.get(id = ser['id'])
dropdown = ServiceSubMenu.objects.filter(Service=sObject)
if len(dropdown)>0:
ser.update({'dropdown':dropdown})
dic1 = []
dic2 = []
for item in services:
try:
a= item['dropdown']
dic1.append(item)
except Exception as e:
dic2.append(item)
dic1.extend(dic2)
services= dic1
responce= {
'services':services,
'ourwork':work
}
return responce<file_sep>/blog/urls.py
from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
path('', views.Blog, name = 'blog'),
path('<int:num>', views.Blog, name = 'blog'),
path('news/', views.news, name = 'blog'),
path('news<int:num>/', views.news, name = 'blog'),
]<file_sep>/contact/admin.py
from django.contrib import admin
from . models import OurContact,contactReq
# Register your models here.
class contactReqAdmin(admin.ModelAdmin):
list_display = ('name','email','intrest','Phone')
admin.site.register(OurContact)
admin.site.register(contactReq,contactReqAdmin)<file_sep>/requirements.txt
asgiref==3.3.1
cachetools==4.2.1
certifi==2020.12.5
chardet==4.0.0
dj-database-url==0.5.0
Django==3.1.7
google-api-core==1.26.0
google-api-python-client==1.12.8
google-auth==1.27.0
google-auth-httplib2==0.0.4
googleapis-common-protos==1.52.0
gunicorn==20.0.4
httplib2==0.19.0
idna==2.10
oauth2client==4.1.3
packaging==20.9
Pillow==8.1.0
protobuf==3.15.1
psycopg2==2.8.6
pyasn1==0.4.8
pyasn1-modules==0.2.8
pyparsing==2.4.7
python-dotenv==0.15.0
pytz==2021.1
requests==2.25.1
rsa==4.7.1
six==1.15.0
sqlparse==0.4.1
uritemplate==3.0.1
urllib3==1.26.3
whitenoise==5.2.0
mysqlclient==1.4.6
<file_sep>/blog/models.py
from django.db import models
import datetime
# Create your models here.
class catagory(models.Model):
catagory = models.CharField(max_length=50)
def __str__(self):
return self.catagory
class blog(models.Model):
blog_title = models.CharField(max_length=50)
blog_content = models.CharField(max_length=5000)
blog_time = models.DateTimeField(auto_now=True)
blog_share = models.IntegerField(default=0)
blog_views = models.IntegerField(default=0)
blog_owner = models.CharField(max_length=50)
blog_image = models.ImageField(upload_to = 'wesiteblog/images', default= "")
blog_catagory = models.ForeignKey(catagory, on_delete=models.CASCADE)
def __str__(self):
return self.blog_owner
class News(models.Model):
blog_title = models.CharField(max_length=50)
blog_content = models.CharField(max_length=5000)
blog_time = models.DateTimeField(auto_now=True)
blog_share = models.IntegerField(default=0)
blog_views = models.IntegerField(default=0)
blog_owners = models.CharField(max_length=50)
blog_image = models.ImageField(upload_to = 'wesiteblog/images', default= "")
blog_catagory = models.ForeignKey(catagory, on_delete=models.CASCADE)
def __str__(self):
return self.blog_owners<file_sep>/service/urls.py
from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
path('<slug:num1>/', views.handle, name = 'service'),
path('<slug:num1>/<slug:num2>', views.handle, name = 'service'),
]<file_sep>/InspironHome/templatetags/poll_extras.py
from django import template
register = template.Library()
@register.filter
def repspace(value):
val = value.replace('/','__')
value = val.replace(' ','_')
return value<file_sep>/ourwork/views.py
from django.shortcuts import render,redirect
from . models import headbanner,Work,ourwork_cat
import random
# Create your views here
def work(request ,num1= 0):
if type(num1)==str:
num1 = num1.replace('__','/')
try:
num1 = ourwork_cat.objects.get(title = num1.replace('_',' ')).id
except Exception as a:
return redirect('home')
color = ['casecolor1','bgsoiltracker ','bgdealer ','bgorbit ','hireux','jaccbg ','hawnk ','tayaar ','wepass ']
Banner = headbanner.objects.filter(catagory= num1)
WOrk = Work.objects.filter(catagory= num1)
rep = []
for i in WOrk:
rep.append([i,random.choice(color)])
res = {
'title':ourwork_cat.objects.get(id=num1).title,
'banner':Banner,
'color': random.choice(color),
'work':rep,
}
return render(request,'ourwork/base.html',res)
return render(request,'ourwork/base.html',res)
<file_sep>/service/models.py
from django.db import models
# Create your models here.
class service(models.Model):
icon = models.ImageField(upload_to = 'media/ourwork',default= '')
title = models.CharField(max_length=50)
content = models.CharField(max_length=5000)
def __str__(self):
return self.title
class ServiceSubMenu(models.Model):
Service = models.ForeignKey(service, on_delete=models.CASCADE)
Submenu = models.CharField(max_length=50)
def __str__(self):
return str(self.Submenu)
class subservices(models.Model):
service = models.ForeignKey(service, on_delete=models.CASCADE)
sub_service = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
tagline = models.CharField(max_length=500)
tag_content = models.CharField(max_length=5000)
Optionalicon = models.FileField(upload_to = 'media/subservice',blank=True)
def __str__(self):
return str(self.sub_service)
class expertise(models.Model):
services = models.ForeignKey(service, on_delete=models.CASCADE,default=1)
Select_type = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
title = models.CharField(max_length=500)
expertise = models.CharField(max_length=500 ,blank=True)
def __str__(self):
return str(self.Select_type)
class sub_expertise(models.Model):
services = models.ForeignKey(service, on_delete=models.CASCADE,default=1)
subservices = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
expertise = models.CharField(max_length=500)
class sub_expertise_icon(models.Model):
services = models.ForeignKey(service, on_delete=models.CASCADE,default=1)
subservices = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
icon = models.FileField(upload_to = 'media/subexpertise',default= '')
title = models.CharField(max_length=500,blank=True)
def __str__(self):
return str(self.subservices )
class subproject(models.Model):
services = models.ForeignKey(service, on_delete=models.CASCADE,default=1)
project_type = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
img = models.ImageField(upload_to = 'media/subproject',default= '')
name = models.CharField(max_length=50)
class headbanner(models.Model):
service = models.ForeignKey(service, on_delete=models.CASCADE)
sub_service = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
banner = models.ImageField(upload_to = 'media/subservice',default= '')
banner_icon = models.ImageField(upload_to = 'media/subservice',default= '')
banner_title = models.CharField(max_length=100)
banner_content = models.CharField(max_length=500)
def __str__(self):
return str(self.sub_service)
class WhatWeDo(models.Model):
services = models.ForeignKey(service, on_delete=models.CASCADE,default=1)
subservices = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
icon = models.FileField(upload_to = 'media/whatwedo',default= '')
title = models.CharField(max_length=100)
content = models.CharField(max_length=500)
def __str__(self):
return str(self.subservices)
class serviceFact(models.Model):
services = models.ForeignKey(service, on_delete=models.CASCADE,default=1)
subservices = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
icon = models.FileField(upload_to = 'media/fact',default= '')
content = models.CharField(max_length=500)
class sub_benifit(models.Model):
services = models.ForeignKey(service, on_delete=models.CASCADE,default=1)
subservices = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
icon = models.FileField(upload_to = 'media/fact',default= '')
content = models.CharField(max_length=500)
def __str__(self):
return str(self.subservices)
class sub_serviceWeOffer(models.Model):
services = models.ForeignKey(service, on_delete=models.CASCADE,default=1)
subservices = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
icon = models.FileField(upload_to = 'media/serviceoffer',default= '')
title = models.CharField(max_length=100)
content = models.CharField(max_length=500)
def __str__(self):
return str(self.subservices)
class devLifecycle(models.Model):
services = models.ForeignKey(service, on_delete=models.CASCADE,default=1)
subservices = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.CharField(max_length=5000)
icon = models.FileField(upload_to = 'media/fact',default= '')
def __str__(self):
return str(self.subservices)
class engagement(models.Model):
services = models.ForeignKey(service, on_delete=models.CASCADE,default=1)
subservices = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.CharField(max_length=5000)
icon = models.FileField(upload_to = 'media/fact',default= '')
def __str__(self):
return str(self.subservices)
class expertiseWithTitleIcon(models.Model):
services = models.ForeignKey(service, on_delete=models.CASCADE,default=1)
subservices = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
icon = models.FileField(upload_to = 'media/expertise',default= '' )
title = models.CharField(max_length=100)
content = models.CharField(max_length=5000,blank= True)
def __str__(self):
return str(self.subservices)
class middleimage(models.Model):
services = models.ForeignKey(service, on_delete=models.CASCADE,default=1)
subservices = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
img = models.ImageField(upload_to = 'media/middle',default= '')
def __str__(self):
return str(self.subservices)
class bottomdiv(models.Model):
services = models.ForeignKey(service, on_delete=models.CASCADE,default=1)
subservices = models.ForeignKey(ServiceSubMenu, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
img = models.ImageField(upload_to = 'media/middle',default= '')
content = models.CharField(max_length=5000)<file_sep>/blog/views.py
from django.shortcuts import render
from . models import blog,catagory,News
# Create your views here.
def Blog(request,num=0):
if num == 0:
Blogs= blog.objects.all()
responce={
'title':'BLOGS',
'blog': 'active',
'blogs':Blogs
}
return render(request,'blog/blog.html',responce)
Blogs= blog.objects.get(id= num)
Blogss= blog.objects.all()[:3]
responce= {
'title': Blogs.blog_title,
'bl':'active',
'blog':Blogs ,
'blogs':Blogss
}
return render(request,'blog/post.html',responce)
def news(request, num=0):
if num == 0:
NEWS = News.objects.all()
responce={
'title':'News',
'news': 'active',
'blogs':NEWS
}
return render(request,'blog/news1.html',responce)
Blogs= News.objects.get(id= num)
Blogss= blog.objects.all()[:3]
responce= {
'title': Blogs.blog_title,
'blog':Blogs ,
'ne': 'active',
'blogs':Blogss
}
return render(request,'blog/post.html',responce)
<file_sep>/InspironHome/models.py
from django.db import models
# Create your models here.
class project(models.Model):
icon = models.ImageField(upload_to = 'project/ourwork',default= '')
title = models.CharField(max_length=70)
content = models.CharField(max_length=5000)
def __str__(self):
return self.title
class ourwork(models.Model):
title = models.CharField(max_length=50)
def __str__(self):
return self.title
class homebanner(models.Model):
banner = models.ImageField(upload_to = 'media/subservice',default= '')
banner_icon = models.ImageField(upload_to = 'media/subservice',default= '')
banner_title = models.CharField(max_length=100)
banner_content = models.CharField(max_length=500)
def __str__(self):
return str(self.banner_title)<file_sep>/contact/models.py
from django.db import models
# Create your models here.
class OurContact(models.Model):
projectEnq = models.CharField(max_length= 50)
genralEnq = models.CharField(max_length= 50)
carrerEnq = models.CharField(max_length= 50)
patnershipEnq = models.CharField(max_length= 50)
locationTitle = models.CharField(max_length= 50)
location = models.CharField(max_length= 500)
Enq = models.CharField(max_length= 50)
def __str__(self):
return self.projectEnq
class contactReq(models.Model):
name = models.CharField(max_length= 50)
email = models.CharField(max_length= 50)
Phone = models.CharField(max_length= 50)
intrest = models.CharField(max_length= 50)
Message = models.CharField(max_length= 5000)
def __str__(self):
return self.name<file_sep>/service/views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import service,ServiceSubMenu,headbanner,subservices,subproject,expertise,sub_expertise,sub_expertise_icon,sub_benifit,WhatWeDo,serviceFact,sub_serviceWeOffer,ServiceSubMenu,devLifecycle,engagement,expertiseWithTitleIcon,middleimage,bottomdiv
from random import randint
# Create your views here.
def services(request , num1=0):
return render(request,'service/service.html')
def handle(request,num1,num2= 0):
if type(num1)==str:
num1 = num1.replace('__','/')
try:
num1 = service.objects.get(title = num1.replace('_',' ')).id
except Exception as a:
return redirect('home')
if type(num2)==str:
num2 = num2.replace('__','/')
try:
num2 = ServiceSubMenu.objects.get(Submenu = num2.replace('_',' ')).id
except Exception as a:
return redirect('home')
cats=[]
if num2 == 0:
Service = ServiceSubMenu.objects.filter(Service=num1)
cats= []
if len(Service)>0:
cat= []
for i in Service:
banner = headbanner.objects.get(service=num1, sub_service= i.id)
up = {}
up['id'] = i.id
up['title'] = str(i.Submenu)
up['content'] = banner.banner_content
up['icon'] = banner.banner_icon
cat.append(up)
cats = [Service[0].Service,cat]
Service = ServiceSubMenu.objects.filter(Submenu='none')
num2= Service[0].id
title = service.objects.get(id=num1).title
else:
title = ServiceSubMenu.objects.get(id=num2).Submenu
banner = headbanner.objects.filter(service = num1 , sub_service= num2)
Subservice = subservices.objects.filter(service = num1 , sub_service = num2)
Subproject = subproject.objects.filter(services=num1,project_type = num2)
Sub_expertise = sub_expertise.objects.filter(services=num1,subservices = num2)
Expertise = expertise.objects.filter(services=num1,Select_type = num2)
Sub_expertise_icon= []
ExpertiseWithTitleIcon=[]
if len(Expertise)>0:
Sub_expertise_icon = sub_expertise_icon.objects.filter(services=num1,subservices =num2)
ExpertiseWithTitleIcon = expertiseWithTitleIcon.objects.filter(services=num1,subservices = num2)
whatWeDo = WhatWeDo.objects.filter(services=num1,subservices = num2)
ServiceFact = serviceFact.objects.filter(services=num1,subservices = num2)
Sub_benifit = sub_benifit.objects.filter(services=num1,subservices = num2)
Sub_serviceWeOffer = sub_serviceWeOffer.objects.filter(services=num1,subservices = num2)
DevLifecycle=[]
DevLifecycle = devLifecycle.objects.filter(services=num1,subservices = num2)
Engagement = engagement.objects.filter(services=num1,subservices = num2)
Middleimage = middleimage.objects.filter(services=num1,subservices = num2)
Bottomdiv = bottomdiv.objects.filter(services=num1,subservices = num2)
res = str(num1)+' '+str(num2)
res = {
'title': title,
'ourservice':'active',
'responce':res,
'banner':banner,
'sub_service': Subservice,
'Subproject': Subproject,
'expertise': [Sub_expertise,len(Sub_expertise)//2 +1 , Expertise , Sub_expertise_icon,ExpertiseWithTitleIcon],
'whatwedo' : whatWeDo,
'fact': ServiceFact,
'Benefits':Sub_benifit,
'serviceweoffer':[Sub_serviceWeOffer,randint(0, 1)],
'devLifecycle':DevLifecycle,
'engagement':Engagement,
'middleimage':Middleimage,
'bottomdiv':Bottomdiv,
'cat':cats
}
return render(request, 'service/subservice.html',res)<file_sep>/ourwork/models.py
from django.db import models
# Create your models here.
class ourwork_cat(models.Model):
title = models.CharField(max_length= 100)
def __str__(self):
return self.title
class headbanner (models.Model):
catagory = models.ForeignKey(ourwork_cat, on_delete=models.CASCADE,default=1)
title = models.CharField(max_length= 100)
content = models.CharField(max_length= 5000)
projecticon = models.ImageField(upload_to="ourwork/projecticon")
projectimage = models.ImageField(upload_to="ourwork/projectimage")
projectTitle = models.CharField(max_length= 200)
projectsource = models.ImageField(upload_to="ourwork/projectsource")
sourceLink= models.CharField(max_length= 500)
projectlink= models.CharField(max_length= 500,blank = True)
def __str__(self):
return str(self.catagory)
class Work(models.Model):
catagory = models.ForeignKey(ourwork_cat, on_delete=models.CASCADE,default=1)
projectimage = models.FileField(upload_to="ourwork/projectimage" , blank = True)
projecticon = models.FileField(upload_to="ourwork/projecticon",blank = True)
projectTitle = models.CharField(max_length= 200,blank = True)
content = models.CharField(max_length= 5000,blank = True)
projectsource = models.FileField(upload_to="ourwork/projectsource",blank = True)
sourceLink= models.CharField(max_length= 500,blank = True)
projectsource1 = models.FileField(upload_to="ourwork/projectsource",blank = True)
sourceLink1= models.CharField(max_length= 500,blank = True)
projectlink= models.CharField(max_length= 500,blank = True)
def __str__(self):
return str(self.catagory) | cdf5a835220106956a6b62428f115a5170e52765 | [
"Python",
"Text"
]
| 22 | Python | cyberflax/cyberflaxlabs | e6e82e726eb681ecd19fe02cfa7d79d4c7f72ede | 03270d43c2a1c5eee53ce8ba53e26b6a1acc4bc1 |
refs/heads/main | <repo_name>thehumfree/item-movement<file_sep>/users/profile.php
<?php
include("head.php");
$pid = $_SESSION["id"];
$uquery = "SELECT * FROM users WHERE id = $pid";
$user = $conn->query($uquery);
if($user->num_rows > 0){
while($row = $user->fetch_assoc()){
$fname = $row["first_name"];
$lname = $row["last_name"];
$email = $row["email"];
$role = $row["role"];
}
}
//updating profile
if(isset($_POST["update"]) || !empty($_POST["update"])){
$fname=$_POST["fname"];
$lname=$_POST["lname"];
$email=$_POST["email"];
$role=ucfirst($_POST["role"]);
$update_query = "UPDATE users SET first_name='$fname', last_name='$lname', email='$email', role='$role' WHERE id = $pid";
$sql = $conn->query($update_query);
if($sql){
$_SESSION["fname"] = $fname;
$_SESSION["lname"] = $lname;
$_SESSION["role"] = $role;
$_SESSION["email"] = $email;
header("Location:profile.php");
}
}
?>
<div class="container mt-5">
<div class="row">
<div class="col-lg-4 pb-5">
<!-- Account Sidebar-->
<div class="author-card pb-3">
<div class="author-card-profile">
<div class="author-card-avatar"><img src="https://bootdey.com/img/Content/avatar/avatar1.png" alt=""></div>
</div>
</div>
</div>
<!-- Profile Settings-->
<div class="col-lg-8 pb-5">
<form class="row" action="" method="post">
<div class="col-md-6">
<div class="form-group">
<label for="account-fn">First Name</label>
<input class="form-control" type="text" id="account-fn" name="fname" value="<?php echo $fname; ?>" required="">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="account-ln">Last Name</label>
<input class="form-control" type="text" id="account-ln" name="lname" value="<?php echo $lname; ?>" required="">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="account-email">E-mail Address</label>
<input class="form-control" type="email" id="account-email" name="email" value="<?php echo $email; ?>" required="">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="account-phone">Role</label>
<input class="form-control" type="text" name="role" id="account-phone" value="<?php echo $role; ?>" required="">
</div>
</div>
<div class="col-12">
<hr class="mt-2 mb-3">
<div class="d-flex flex-wrap justify-content-between align-items-center">
<button class="btn btn-style-1 btn-dark" type="submit" name="update" data-toast="" data-toast-position="topRight" data-toast-type="success" data-toast-icon="fe-icon-check-circle" data-toast-title="Success!" data-toast-message="Your profile updated successfuly.">Update Profile</button>
</div>
</div>
</form>
</div>
</div>
</div>
<?php include("foot.php"); ?><file_sep>/admin/includes/functions.php
<?php
include("db.php");
//login system function
function login($email, $password){
global $conn;
$email = trim($email);
$password = trim($password);
$query ="SELECT * FROM users WHERE email = '$email'";
$sql= $conn->query($query);
if($sql->num_rows > 0){
$row = $sql->fetch_assoc();
$verify = password_verify($password, $row["user_password"]);
if($verify){
$_SESSION["id"] = $row["id"];
$_SESSION["fname"] = $row["first_name"];
$_SESSION["lname"] = $row["last_name"];
$_SESSION["email"] = $row["email"];
$_SESSION["role"] = $row["role"];
if($_SESSION["role"] == "Admin"){
header("Location:admin/index.php");
}else{
header("Location:users/index.php");
}
}else{
echo "<script type='text/javascript'>
alert('Wrong Password!!');
window.location.href = 'login.php';
</script>";
}
}else{
$_SESSION["id"] = false;
echo "<script type='text/javascript'>
alert('Login was not successful! No user found');
</script>";
}
}
//register a new user account
function registerUser($first, $last, $email, $password, $role){
global $conn;
$first = $conn->real_escape_string($first);
$last = $conn->real_escape_string($last);
$email = $conn->real_escape_string($email);
$password = $conn->real_escape_string($password);
$hashpassword = password_hash($password, PASSWORD_DEFAULT);
$role = $role;
//checks if user exist using the email
$check = "SELECT * FROM users WHERE email = '$email'";
$sqlcheck = $conn->query($check);
//if user exist, echo message and redirect back to register page
if($sqlcheck->num_rows >0){
echo "<script type='text/javascript'>
alert('Email Address already exist!');
window.location.href = 'register.php';
</script>";
}else{
//if user doesnt exist carry on with registration
$query ="INSERT INTO users(first_name, last_name, email, user_password, role) ";
$query.="VALUE('$first', '$last', '$email', '$hashpassword', '$role')";
$sql= $conn->query($query);
if($sql){
echo "<script type='text/javascript'>
alert('Registration was successful! press ok to be redirected to login page');
window.location.href = 'login.php';
</script>";
}else{
header("Location:./register.php");
}
}
}
//create an item
function createItem($matcode){
global $conn;
$matcode = $matcode;
$check_query ="SELECT * FROM material_movement WHERE material_id ='$matcode' LIMIT 1";
$check = $conn->query($check_query);
if($check->num_rows >0){
$message="Material Code already exist";
}else{
$materialtype= $_POST['mtype'];
if($materialtype=="4"){
$materialtypeother=$_POST["mtype_other"];
}else{
$materialtypeother="";
}
$productname= $_POST["pname"];
$productserial= $_POST["pserial"];
$materiallocation= "1";
$materiallocationother="";
$materialdestination= "1";
$materialdestinationother="";
$authorisedby= $_POST["authby"];
$assignedto= $_POST["assto"];
$dateofmovement= $_POST["dom"];
$query ="INSERT into material_movement ";
$query.="(material_id, material_type, product_name, product_serial, current_location, device_destination, authorised_by, assigned_to, movement_date, material_type_other, current_location_other, destination_location_other) ";
$query.="VALUES ('$matcode','$materialtype', '$productname', '$productserial', '$materiallocation', '$materialdestination', '$authorisedby', '$assignedto', '$dateofmovement', '$materialtypeother', '$materiallocationother', '$materialdestinationother')";
$insert=$conn->query($query);
if(!$insert){
die("failed insert".$conn->error);
}else{
#header("Location:./preview.php");
}
}
}
//editing page retrieval from database
function editPage(){
global $conn;
$query = "SELECT * FROM material_movement";
$sql=$conn->query($query);
if($sql->num_rows>0){
while($row = $sql->fetch_assoc()){
$id = $row["id"];
$matid = $row["material_id"];
$mattype=$row["material_type"];
$proname=$row["product_name"];
$proserial=$row["product_serial"];
$curlocation=$row["current_location"];
$deslocation=$row["device_destination"];
$authby=$row["authorised_by"];
$assto=$row["assigned_to"];
$date = $row["movement_date"];
$mattypeother=$row["material_type_other"];
$curlocationother = $row["current_location_other"];
$deslocationother= $row["destination_location_other"];
if($mattype==4){
$matname = $mattypeother;
}else{
//displaying from another table
$matquery="SELECT * FROM material_type WHERE id =$mattype";
$matsql=$conn->query($matquery);
while($row = $matsql->fetch_assoc()){
$matname=$row["material_type"];
}
}
if($curlocation==3){
$clocname= $curlocationother;
}else{
//displaying from another table
$clocquery="SELECT * FROM base_basestation WHERE id =$curlocation";
$clocsql=$conn->query($clocquery);
while($row = $clocsql->fetch_assoc()){
$clocname=$row["station_location"];
}
}
if($deslocation==3){
$dlocname= $deslocationother;
}else{
//displaying from current location table
$dlocquery="SELECT * FROM base_basestation WHERE id =$deslocation";
$dlocsql=$conn->query($dlocquery);
while($row = $dlocsql->fetch_assoc()){
$dlocname=$row["station_location"];
}
}
echo "<tr>
<td>$matid</td>
<td>$matname</td>
<td>$proname</td>
<td>$proserial</td>
<td>$clocname</td>
<td>$dlocname</td>
<td>$authby</td>
<td>$assto</td>
<td>$date</td>
<td><a href='./editDevice.php?eid=$id'><i class='far fa-edit'></i></a></td>
<td><a href='./editPage.php?did=$id'><i class='far fa-trash-alt'></i></a></td>
</tr>";
}
}
}
//Editing individual item from edit button
function editDevice($id){
global $conn;
$id = $id;
$query = "SELECT * FROM material_movement WHERE id = $id";
$sql=$conn->query($query);
if($sql->num_rows>0){
while($row = $sql->fetch_assoc()){
$id = $row["id"];
global $matcode;
global $mattype;
global $proname;
global $proserial;
global $curlocation;
global $deslocation;
global $authby;
global $assto;
global $date;
global $matother;
global $curlother;
global $desother;
global $matalt;
global $curlalt;
global $desalt;
$matcode= $row["material_id"];
$mattype=$row["material_type"];
$proname=$row["product_name"];
$proserial=$row["product_serial"];
$curlocation=$row["current_location"];
$deslocation=$row["device_destination"];
$authby=$row["authorised_by"];
$assto=$row["assigned_to"];
$date = $row["movement_date"];
$matother=$row["material_type_other"];
$curlother = $row["current_location_other"];
$desother = $row["destination_location_other"];
if($mattype==4){
$matalt=$matother;
}else{
$matalt="";
}
if($curlocation==3){
$curlalt=$curlother;
}else{
$curlalt="";
}
if($deslocation==3){
$desalt=$desother;
}else{
$desalt="";
}
}
}
}
//update individual item
function updateDevice($id){
global $conn;
$id = $id;
$materialtype=$_POST["mtype"];
if($materialtype=="4"){
$materialtypeother=$_POST["mtype_other"];
}else{
$materialtypeother="";
}
$productname= $_POST["pname"];
$productserial= $_POST["pserial"];
$materiallocation= $_POST["mloc"];
if($materiallocation=="3"){
$materiallocationother=$_POST["mloc_other"];
}else{
$materiallocationother="";
}
$materialdestination= $_POST["mdes"];
if($materialdestination=="3"){
$materialdestinationother=$_POST["mdes_other"];
}else{
$materialdestinationother="";
}
$authorisedby= $_POST["authby"];
$assignedto= $_POST["assto"];
$dateofmovement= $_POST["dom"];
//update query to sql
$query="UPDATE material_movement SET ";
$query.="material_type='$materialtype', ";
$query.="product_name='$productname', ";
$query.="product_serial='$productserial', ";
$query.="current_location='$materiallocation', ";
$query.="device_destination='$materialdestination', ";
$query.="authorised_by='$authorisedby', ";
$query.="assigned_to='$assignedto', ";
$query.="movement_date='$dateofmovement', ";
$query.="material_type_other='$materialtypeother', ";
$query.="current_location_other='$materiallocationother', ";
$query.="destination_location_other='$materialdestinationother' ";
$query.="WHERE id = $id";
$sql = $conn->query($query);
if($sql){
header("Location:./editPage.php");
}
}
?><file_sep>/admin/preview.php
<?php
include("includes/head.php");
?>
<!-- Begin Page Content -->
<div class="container">
<div class="row">
<div class="col-md-12">
<table id="mytable" class="table table-striped table-hover table-sm">
<thead class="thead-dark">
<tr>
<th>Material Code</th>
<th>Material Type</th>
<th>Product Name</th>
<th>Product Serial No</th>
<th>Current Location</th>
<th>Destination Location</th>
<th>Authorised By</th>
<th>Assigned To</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM material_movement";
$sql=$conn->query($query);
if($sql->num_rows>0){
while($row = $sql->fetch_assoc()){
$id = $row["id"];
$matid = $row["material_id"];
$mattype=$row["material_type"];
$proname=$row["product_name"];
$proserial=$row["product_serial"];
$curlocation=$row["current_location"];
$deslocation=$row["device_destination"];
$authby=$row["authorised_by"];
$assto=$row["assigned_to"];
$date = $row["movement_date"];
$mattypeother=$row["material_type_other"];
$curlocationother = $row["current_location_other"];
$deslocationother= $row["destination_location_other"];
if($mattype==4){
$matname = $mattypeother;
}else{
//displaying from another table
$matquery="SELECT * FROM material_type WHERE id =$mattype";
$matsql=$conn->query($matquery);
while($row = $matsql->fetch_assoc()){
$matname=$row["material_type"];
}
}
if($curlocation==3){
$clocname= $curlocationother;
}else{
//displaying from another table
$clocquery="SELECT * FROM base_basestation WHERE id =$curlocation";
$clocsql=$conn->query($clocquery);
while($row = $clocsql->fetch_assoc()){
$clocname=$row["station_location"];
}
}
if($deslocation==3){
$dlocname= $deslocationother;
}else{
//displaying from current location table
$dlocquery="SELECT * FROM base_basestation WHERE id =$deslocation";
$dlocsql=$conn->query($dlocquery);
while($row = $dlocsql->fetch_assoc()){
$dlocname=$row["station_location"];
}
}
?>
<tr>
<td><?php echo $matid ?></td>
<td><?php echo $matname ?></td>
<td><?php echo $proname ?></td>
<td><?php echo $proserial ?></td>
<td><?php echo $clocname ?></td>
<td><?php echo $dlocname ?></td>
<td><?php echo $authby ?></td>
<td><?php echo $assto ?></td>
<td><?php echo $date ?></td>
</tr>
<?php }
}
?>
</tbody>
</table>
</div>
</div>
</div>
<!-- End of Main Content -->
<script type="text/javascript">
$(document).ready( function () {
$('#mytable').DataTable({
responsive: true,
});
} );
</script>
<?php include("includes/foot.php"); ?><file_sep>/login.php
<?php session_start();
//including the database file
include("admin/includes/db.php");
//including the function files
include("admin/includes/functions.php");
//login system validation
if(isset($_POST["login"])){
login($_POST["email"],$_POST["passwrd"]);
}//end of login system
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Signin Template · Bootstrap</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.5/examples/sign-in/">
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
@media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link href="css/signin.css" rel="stylesheet">
<link rel="shortcut icon" type="image/x-icon" href="images/hubspot.ico" />
</head>
<body class="text-center">
<form class="form-signin" action="" method="post">
<img class="mb-4" src="images/hubspot.svg" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" name="email" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="<PASSWORD>" name="passwrd" required>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" name="login">Sign in</button>
<div class="text-center">
<a class="small" href="./register.php">Dont have an account? Sign up!</a>
</div>
</form>
</body>
</html>
<file_sep>/admin/register_item.php
<?php
include("includes/head.php");
?>
<?php
//To register item into database
$message = "";
if(isset($_POST["register"])){
createItem($_POST["matcode"]);
}
?>
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800">Register Device</h1>
</div>
<div class="col">
<?php echo $message ?>
<form role="form" action="" method="post">
<div class="form-row">
<!--first field -->
<div class="form-group col-md-6">
<label><b>Item Code</b></label>
<input type="text" class="form-control col-7" name="matcode" required/>
</div>
<!--second field-->
<div class="form-group col-md-6">
<label><b>Product Name</b></label>
<input type="text" class="form-control col-7" name="pname" required/>
</div>
<!--third field-->
<div class="form-group col-md-6">
<label><b>Product Serial Number</b></label>
<input type="text" class="form-control col-7" name="pserial" required/>
</div>
</div><br />
<div class="form-row">
<!--third field-->
<div class="form-group col-md-6">
<label><b>Material Type</b></label>
<!--picking data as select option from database -->
<select class="form-control col-3" name="mtype" id="material" required>
<?php
$query="SELECT * FROM material_type";
$sql=$conn->query($query);
if($sql->num_rows>0){
while($row = $sql->fetch_assoc()){
$id = $row["id"];
$mattype= $row["material_type"];
echo"<option value='$id'>$mattype</option>";
}
}
?>
</select><br />
<div class="mtog" id="matother">
<span><i>Specify the Material Type</i></span>
<input type="text" name="mtype_other" class="form-control col-7" />
</div>
</div>
<!--fifth field-->
<div class="form-group col-md-6">
<label><b>Authorised By*</b></label>
<input type="text" class="form-control col-7" name="authby" required/>
</div>
</div><br />
<div class="form-row">
<!--fifth field-->
<div class="form-group col-md-6">
<label><b>Assigned To*</b></label>
<input type="text" class="form-control col-7" name="assto" required/>
</div>
<!--sixth field-->
<div class="form-group col-md-6">
<label><b>Date of Movement*</b></label>
<input type="date" class="form-control col-7" name="dom" required/>
</div>
</div><br /><br />
<div class="d-flex justify-content-center">
<input type="submit" name="register" class="btn btn-success" />
</div>
</form>
</div>
</div>
<!-- End of Main Content -->
<?php include("includes/foot.php"); ?>
<file_sep>/admin/editPage.php
<?php
include("includes/head.php");
?>
<!-- Begin Page Content -->
<div class="container">
<div class="row">
<div class="col-md-12">
<table id="mytable" class="table table-striped table-hover responsive" style="width:100%">
<thead class="thead-dark">
<tr>
<th>Material Code</th>
<th>Material Type</th>
<th>Product Name</th>
<th>Product Serial No</th>
<th>Current Location</th>
<th>Destination Location</th>
<th>Authorised By</th>
<th>Assigned To</th>
<th>Date</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
//preview items in an editable manner
editPage();
?>
</tbody>
</table>
</div>
</div>
</div>
<!-- End of Main Content -->
<script type="text/javascript">
$(document).ready( function () {
$('#mytable').DataTable({
responsive: true
});
} );
</script>
<?php
if(isset($_GET["did"])){
$did = $_GET["did"];
$query = "DELETE FROM material_movement WHERE id ={$did}";
$sqlDelete = $conn->query($query);
header("Location:editPage.php");
}
include("includes/foot.php");
?><file_sep>/admin/index.php
<?php
include("includes/head.php");
?>
<div class="background-container">
<img class="img-anime" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/1231630/moon2.png" alt="">
<div class="stars"></div>
<div class="twinkling"></div>
<div class="clouds"></div>
<?php include("includes/foot.php"); ?><file_sep>/admin/includes/head.php
<?php
session_start();
ob_start();
include("db.php");
include_once("functions.php");
if(!$_SESSION["id"]){
header("Location:../login.php");
}else{
$activePage = basename($_SERVER['PHP_SELF'], ".php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>HOOP TELECOMS</title>
<!-- favicon -->
<link rel="shortcut icon" type="image/x-icon" href="../images/hubspot.ico" />
<!-- Custom fonts for this template-->
<link rel="stylesheet" href="../addons/fontawesome-free/css/all.css" />
<script type="text/javascript" src="../addons/fontawesome-free/js/all.js"></script>
<!-- Start of datatable css and javascript -->
<script type="text/javascript" src="../addons/datatables.js"></script>
<link rel="stylesheet" href="../addons/datatables.css" />
<!-- End datatable css and javascript -->
<!-- Start of bootstrap css and javascript -->
<link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css" />
<script type="text/javascript" src="../js/bootstrap.min.js"></script>
<!-- End of datatable css and javascript -->
<!-- Adds the css if page is homepage -->
<link rel="stylesheet" type="text/css" href="<?= ($activePage == 'index') ? '../css/anime.css' : '' ?>" />
<style>
body{
padding-top: 4.5rem;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
/* for the material type(mouse hover and click for other input*/
$("#material").on({
mouseenter:
(function () {
if ($(this).val() == 4) {
$("#matother").show();
} else {
$("#matother").hide();
}
}),
click:
(function () {
if ($(this).val() == 4) {
$("#matother").show();
} else {
$("#matother").hide();
}
})});
/* for the current location (mouse hover and click for other input*/
$("#curloc").on({
mouseenter:
(function () {
if ($(this).val() == 3) {
$("#curlother").show();
} else {
$("#curlother").hide();
}
}),
click:
(function () {
if ($(this).val() == 3) {
$("#curlother").show();
} else {
$("#curlother").hide();
}
})});
/* for the destination location (mouse hover and click for other input*/
$("#desloc").on({
mouseenter:
(function () {
if ($(this).val() == 3) {
$("#deslother").show();
} else {
$("#deslother").hide();
}
}),
click:
(function () {
if ($(this).val() == 3) {
$("#deslother").show();
} else {
$("#deslother").hide();
}
})});
});
</script>
<style type="text/css">
#matother{
display: none;
}
#curlother{
display: none;
}
#deslother{
display: none;
}
</style>
</head>
<body>
<?php include("nav.php");
?>
<file_sep>/users/index.php
<?php include("head.php");
?>
<div class="background-container">
<img class="img-anime" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/1231630/moon2.png" alt="">
<div class="stars"></div>
<div class="twinkling"></div>
<div class="clouds"></div>
<?php include("foot.php"); ?><file_sep>/users/head.php
<?php
session_start();
ob_start();
include("../admin/includes/db.php");
include_once("../admin/includes/functions.php");
if(!$_SESSION["id"]){
header("Location:../login.php");
}else{
$activePage = basename($_SERVER['PHP_SELF'], ".php");
$user = $_SESSION["fname"]." ". $_SESSION["lname"];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>HOOP TELECOMS</title>
<!-- favicon -->
<link rel="shortcut icon" type="image/x-icon" href="../images/hubspot.ico" />
<!-- Custom fonts for this template-->
<link rel="stylesheet" href="../addons/fontawesome-free/css/all.css" />
<script type="text/javascript" src="../addons/fontawesome-free/js/all.js"></script>
<!-- Start of datatable css and javascript -->
<script type="text/javascript" src="../addons/datatables.js"></script>
<link rel="stylesheet" href="../addons/datatables.css" />
<!-- End datatable css and javascript -->
<!-- Start of bootstrap css and javascript -->
<link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css" />
<script type="text/javascript" src="../js/bootstrap.min.js"></script>
<!-- End of datatable css and javascript -->
<!-- Adds the css if page is homepage -->
<link rel="stylesheet" type="text/css" href="<?= ($activePage == 'index') ? '../css/anime.css' : '' ?>" />
<style>
body{
padding-top: 4.5rem;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="./index.php">Hoop Telecoms</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item <?= ($activePage == 'index') ? 'active' : '' ?>">
<a class="nav-link" href="./index.php">Home</a>
</li>
<li class="nav-item <?= ($activePage == 'preview') ? 'active' : '' ?>">
<a class="nav-link" href="./preview.php">Database</a>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item dropdown">
<a class="nav-link" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="mr-2 d-none d-lg-inline text-white small"> <?php echo $user ?></span>
<img class="img-profile rounded-circle" width="30px" height="30px" src="https://bootdey.com/img/Content/avatar/avatar1.png">
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="./profile.php">
<i class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i>
Profile
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="../logout.php" data-toggle="modal" data-target="#logoutModal">
<i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
Logout
</a>
</div>
</li>
</ul>
</div>
</nav>
<br><file_sep>/admin/includes/nav.php
<?php
$user = $_SESSION["fname"]." ". $_SESSION["lname"];
$activePage = basename($_SERVER['PHP_SELF'], ".php");
?>
<nav class="navbar navbar-expand-lg navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="./index.php">Hoop Telecoms</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item <?= ($activePage == 'index') ? 'active' : '' ?>">
<a class="nav-link" href="./index.php">Home</a>
</li>
<li class="nav-item <?= ($activePage == 'register_item') ? 'active' : '' ?>">
<a class="nav-link" href="./register_item.php">Create Item</a>
</li>
<li class="nav-item <?= ($activePage == 'editPage') ? 'active' : '' ?>">
<a class="nav-link" href="./editPage.php">Alter Item</a>
</li>
<li class="nav-item <?= ($activePage == 'preview') ? 'active' : '' ?>">
<a class="nav-link" href="./preview.php">Database</a>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item dropdown">
<a class="nav-link" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="mr-2 d-none d-lg-inline text-white small"> <?php echo $user ?></span>
<img class="img-profile rounded-circle" width="30px" height="30px" src="https://bootdey.com/img/Content/avatar/avatar1.png">
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="./profile.php">
<i class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i>
Profile
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="../logout.php" data-toggle="modal" data-target="#logoutModal">
<i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
Logout
</a>
</div>
</li>
</ul>
</div>
</nav>
<br><file_sep>/register.php
<?php session_start();
//importing function file
include_once("admin/includes/functions.php");
//register a user
if(isset($_POST["register"])){
registerUser($_POST["fname"], $_POST["lname"], $_POST["emailadd"], $_POST["passwrd"], $_POST["role"]);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Signin Template · Bootstrap</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.5/examples/sign-in/">
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
@media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link href="css/signin.css" rel="stylesheet">
<link rel="shortcut icon" type="image/x-icon" href="images/hubspot.ico" />
</head>
<body class="text-center">
<form class="form-signin" action="" method="post">
<img class="mb-4" src="images/hubspot.svg" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal">Create Account</h1>
<label for="Fname" class="sr-only">First Name</label>
<input type="text" id="Fname" class="form-control" placeholder="<NAME>" name="fname" required>
<label for="Lname" class="sr-only">Last Name</label>
<input type="text" id="Lname" class="form-control" placeholder="Last Name" name="lname" required>
<label for="Email" class="sr-only">Email Address</label>
<input type="email" id="Email" class="form-control" placeholder="Email Address" name="emailadd" required>
<label for="passwrd" class="sr-only">Password</label>
<input type="<PASSWORD>" id="passwrd" class="form-control" placeholder="<PASSWORD>" name="passwrd" required>
<label for="rPasswrd" class="sr-only">Retype Password</label>
<input type="password" id="rPassword" class="form-control" placeholder="Repeat Password" name="rpasswrd" required>
<input type="text" class="form-control" name="role" value="Admin" hidden>
<button class="btn btn-lg btn-primary btn-block" type="submit" onclick="return Validate()" name="register">Create Account</button>
<div class="text-center">
<a class="small" href="./login.php">Already have an account? Login!</a>
</div>
</form>
<script>
function Validate(){
var pass = document.getElementById("passwrd").value;
var conpass = document.getElementById("rPassword").value;
if(pass != conpass){
alert("Password doesnt match!!");
return false;
}
return true;
}
</script>
</body>
</html>
<file_sep>/admin/editDevice.php
<?php
include("includes/head.php");
?>
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800">Edit Item</h1>
</div>
<?php
//getting the data from database to display on editable form
if(isset($_GET["eid"])){
editDevice($_GET["eid"]);
}
//updating the edited item
if(isset($_POST["update"])){
updateDevice($_GET["eid"]);
}
?>
<div class="col">
<form role="form" action="" method="post">
<div class="form-row">
<!--first field -->
<div class="form-group col-md-6">
<label><b>Item Code</b></label>
<input type="text" class="form-control col-7" name="matcode" value="<?php echo $matcode; ?>" disabled/>
</div>
<div class="form-group col-md-6">
<label><b>Product Name</b></label>
<input type="text" class="form-control col-7" name="pname" value="<?php echo $proname ?>" required/>
</div>
<!--second field-->
<div class="form-group col-md-6">
<label><b>Product Serial Number</b></label>
<input type="text" class="form-control col-7" name="pserial" value="<?php echo $proserial ?>" required/>
</div>
</div><br />
<div class="form-row">
<!--third field-->
<div class="form-group col-md-6">
<label><b>Material Type</b></label>
<!--picking data as select option from database -->
<select class="form-control col-3" name="mtype" id="material" required>
<?php
$query="SELECT * FROM material_type";
$sql=$conn->query($query);
if($sql->num_rows>0){
while($row = $sql->fetch_assoc()){
$mid = $row["id"];
$matname= $row["material_type"];
?>
<option value="<?php echo $mid; ?>" <?php if($mid==$mattype){echo "selected";} ?>><?php echo $matname;?></option>
<?php }
}
?>
</select><br />
<div class="mtog" id="matother">
<span><i>Specify the Material Type</i></span>
<input type="text" name="mtype_other" class="form-control col-7" value="<?php echo $matalt; ?>"/>
</div>
</div>
<!--fourth field-->
<div class="form-group col-md-6">
<label><b>Current Location*</b></label>
<!--picking data as select option from database -->
<select class="form-control col-2" name="mloc" id="curloc" required>
<?php
$query="SELECT * FROM base_basestation";
$sql=$conn->query($query);
if($sql->num_rows>0){
while($row = $sql->fetch_assoc()){
$mid = $row["id"];
$location= $row["station_location"];
?>
<option value="<?php echo $mid; ?>" <?php if($mid==$curlocation){echo "selected";} ?>><?php echo $location;?></option>
<?php }
}
?>
</select><br />
<div id="curlother">
<span><i>Specify the Current Location</i></span>
<input type="text" name="mloc_other" class="form-control col-7" value="<?php echo $curlalt; ?>"/>
</div>
</div>
</div><br />
<div class="form-row">
<!--fifth field -->
<div class="form-group col-md-6">
<label><b>Device Destination*</b></label>
<!--picking data as select option from database -->
<select class="form-control col-2" name="mdes" id="desloc" required>
<?php
$query="SELECT * FROM base_basestation";
$sql=$conn->query($query);
if($sql->num_rows>0){
while($row = $sql->fetch_assoc()){
$mid = $row["id"];
$location= $row["station_location"];
?>
<option value="<?php echo $mid; ?>" <?php if($mid==$deslocation){echo "selected";} ?>><?php echo $location;?></option>
<?php }
}
?>
</select><br />
<div id="deslother">
<span><i>Specify the Destination Location</i></span>
<input type="text" name="mdes_other" class="form-control col-7" value="<?php echo $desalt; ?>"/>
</div>
</div>
<!--sixth field-->
<div class="form-group col-md-6">
<label><b>Authorised By*</b></label>
<input type="text" class="form-control col-7" name="authby" value="<?php echo $authby ?>" required/>
</div>
</div><br />
<div class="form-row">
<!--seventh field-->
<div class="form-group col-md-6">
<label><b>Assigned To*</b></label>
<input type="text" class="form-control col-7" name="assto" value="<?php echo $assto ?>" required/>
</div>
<!--eighth field-->
<div class="form-group col-md-6">
<label><b>Date of Movement*</b></label>
<input type="date" class="form-control col-7" name="dom" value="<?php echo $date ?>" required/>
</div>
</div><br /><br />
<div class="d-flex justify-content-center">
<input type="submit" name="update" class="btn btn-success" />
</div>
</form>
</div>
</div>
<!-- End of Main Content -->
<?php include("includes/foot.php"); ?>
| ae4246a87e299a9e4e79db1dac60649085fb6ce1 | [
"PHP"
]
| 13 | PHP | thehumfree/item-movement | e42c44e8ee43a9c3b02e5532e1406edd4bdeedff | b169a1ad2883799cbea7c7ae72fec784ab58e958 |
refs/heads/master | <repo_name>pravi-m/ItVLabsDev<file_sep>/src/app/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import { Reason } from '../app.component';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
public reasonList;
constructor() {
this.reasonList = reasons;
}
ngOnInit() {
}
}
var reasons : Reason[]=[
{"imgUrl":"../../assets/images/6.png","reason":"Practice any Big Data ecosystem tools","description":"Big Data eco system has many tools, such as Hadoop, Map Reduce, Spark, Hive, Pig, Sqoop, Flume, Kafka etc. Big Data labs will provide lab to explore and learn an Big Data technology."},
{"imgUrl":"../../assets/images/4.png","reason":"Access from any where","description":"Lab is powered by multi node cluster with all the necessary components. It is accessible from any where using internet. Also lab is scalable based up on the usage."},
{"imgUrl":"../../assets/images/5.png","reason":"Prepare for certifications","description":"There are many free or low cost certification courses available at itversity and IT Versity's YouTube channel. Enroll for Big Data labs at affordable cost. It is well integrated with the content to practice for all the courses from your location at your own pace."},
{"imgUrl":"../../assets/images/7.png","reason":"Learning Support","description":"Support will be provided in case of any issues through emails, groups or forums as well as regular live sessions. Also there will be live courses based on the demand of users."}
];
| d9bd5decc84644835e51726e55da735bd0b3678d | [
"TypeScript"
]
| 1 | TypeScript | pravi-m/ItVLabsDev | a42044284206e5668e7d988b2460cf2633b90867 | 32be0bfd67118ba40258103bb45ee2d547d82195 |
refs/heads/master | <file_sep>DROP TABLE IF EXISTS user_roles;
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS dishes;
DROP TABLE IF EXISTS restaurants;
DROP SEQUENCE IF EXISTS global_seq;
CREATE SEQUENCE global_seq START WITH 100000;
CREATE TABLE restaurants
(
id INTEGER PRIMARY KEY DEFAULT nextval('global_seq'),
name VARCHAR NOT NULL,
votes INTEGER DEFAULT 0
);
CREATE UNIQUE INDEX restaurants_unique_name_idx ON restaurants (name);
CREATE TABLE users
(
id INTEGER PRIMARY KEY DEFAULT nextval('global_seq'),
name VARCHAR NOT NULL,
email VARCHAR NOT NULL,
password VARCHAR NOT NULL,
registered TIMESTAMP DEFAULT now() NOT NULL,
vote_date TIMESTAMP DEFAULT 'yesterday' NOT NULL,
restaurant_id INTEGER ,
FOREIGN KEY (restaurant_id) REFERENCES restaurants (id)
);
CREATE UNIQUE INDEX users_unique_email_idx ON users (email);
CREATE TABLE user_roles
(
user_id INTEGER NOT NULL,
role VARCHAR,
CONSTRAINT user_roles_idx UNIQUE (user_id, role),
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
);
CREATE TABLE dishes
(
id INTEGER PRIMARY KEY DEFAULT nextval('global_seq'),
name VARCHAR NOT NULL,
price INTEGER NOT NULL,
restaurant_id INTEGER NOT NULL,
FOREIGN KEY (restaurant_id) REFERENCES restaurants (id) ON DELETE CASCADE
);
<file_sep>package ru.restaurantvote.web;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import ru.restaurantvote.service.RestaurantService;
public class RestaurantControllerTest extends AbstractControllerTest {
@Autowired
private RestaurantService service;
@Test
void getAll() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get(REST_URL))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
void get() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get(REST_URL + "/100001"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.restaurantvote</groupId>
<artifactId>restaurantvote</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>Restaurant Voting System</name>
<url>http://www.example.com</url>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring.version>5.1.8.RELEASE</spring.version>
<spring-data-jpa.version>2.1.9.RELEASE</spring-data-jpa.version>
<jackson-json.version>2.9.9</jackson-json.version>
<tomcat.version>9.0.21</tomcat.version>
<!--DB-->
<postgresql.version>42.2.6</postgresql.version>
<!--ORM-->
<hibernate.version>5.4.3.Final</hibernate.version>
<hibernate-validator.version>6.0.17.Final</hibernate-validator.version>
<javax-el.version>3.0.1-b11</javax-el.version>
<!--Test-->
<junit.jupiter.version>5.5.1</junit.jupiter.version>
<hamcrest.version>1.3</hamcrest.version>
<!-- Logging -->
<logback.version>1.2.3</logback.version>
<slf4j.version>1.7.25</slf4j.version>
</properties>
<dependencies>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<!-- ORM-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>${tomcat.version}</version>
<scope>provided</scope>
</dependency>
<!--http://hibernate.org/validator/documentation/getting-started/#unified-expression-language-el-->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>${javax-el.version}</version>
<scope>provided</scope>
</dependency>
<!-- Web-->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>${tomcat.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--JSON-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-json.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5</artifactId>
<version>${jackson-json.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson-json.version}</version>
</dependency>
<!-- Test-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.12.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>restaurantvote</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>package ru.restaurantvote.model;
import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "restaurants", uniqueConstraints = {@UniqueConstraint(columnNames = "name", name = "restaurants_unique_name_idx")})
public class Restaurant extends AbstractBaseEntity {
@Column(name = "votes", nullable = false, columnDefinition = "int default 0")
private int votes;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "restaurant")
private List<Dish> lunchMenu;
public Restaurant() {
}
public Restaurant(Integer id, String name, int votes) {
super(id, name);
this.votes = votes;
}
public int getVotes() {
return votes;
}
public void setVotes(int votes) {
this.votes = votes;
}
public void setLunchMenu(List<Dish> lunchMenu) {
this.lunchMenu = lunchMenu;
}
public List<Dish> getLunchMenu() {
return lunchMenu;
}
}
<file_sep>package ru.restaurantvote.service;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import ru.restaurantvote.RestaurantTestData;
import static ru.restaurantvote.RestaurantTestData.*;
class RestaurantServiceTest extends AbstractServiceTest {
@Autowired
private RestaurantService service;
@Test
void getAll() {
assertMatch(service.getAll(), RESTAURANTS);
}
}<file_sep>package ru.restaurantvote;
import org.assertj.core.api.Assertions;
import ru.restaurantvote.model.Restaurant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.*;
public class RestaurantTestData {
public static final int RESTAURANT_ID = 100001;
public static final Restaurant RESTAURANT1 = new Restaurant(RESTAURANT_ID, "Perchini", 0);
public static final Restaurant RESTAURANT2 = new Restaurant(RESTAURANT_ID + 1, "USSR", 0);
public static final Restaurant RESTAURANT3 = new Restaurant(RESTAURANT_ID + 2, "KFC", 0);
public static final List<Restaurant> RESTAURANTS = Arrays.asList(RESTAURANT1, RESTAURANT2, RESTAURANT3);
public static void assertMatch(Iterable<Restaurant> actual, Iterable<Restaurant> expected) {
assertThat(actual).isEqualTo(expected);
}
}
<file_sep>package ru.restaurantvote.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.restaurantvote.model.Dish;
import ru.restaurantvote.repository.DishRepository;
import java.util.List;
@Service
public class DishService {
@Autowired
private DishRepository repository;
public List<Dish> getAll(int restId) {
return repository.getAll(restId);
}
public Dish get(int id) {
return repository.get(id);
}
public boolean delete(int id) {
return repository.delete(id) != 0;
}
public Dish create(Dish dish) {
return repository.save(dish);
}
public void update(Dish dish) {
repository.save(dish);
}
}
<file_sep>package ru.restaurantvote.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import ru.restaurantvote.model.Restaurant;
import ru.restaurantvote.repository.RestaurantRepository;
import java.util.List;
@Service
public class RestaurantService {
@Autowired
private RestaurantRepository repository;
public List<Restaurant> getAll() {
return repository.getAll();
}
public boolean delete(int id) {
return repository.delete(id) != 0;
}
public Restaurant create(Restaurant restaurant) {
Assert.notNull(restaurant, "restaurant must not be null");
return repository.save(restaurant);
}
public void update(Restaurant restaurant) {
repository.save(restaurant);
}
public Restaurant get(int id) {
return repository.getOne(id);
}
}
<file_sep>DELETE FROM user_roles;
DELETE FROM users;
DELETE FROM dishes;
DELETE FROM restaurants;
ALTER SEQUENCE global_seq RESTART WITH 100000;
INSERT INTO users (name, email, password) VALUES
('User', '<EMAIL>', 'user123');
INSERT INTO user_roles (role, user_id) VALUES
('ROLE_USER', 100000);
INSERT INTO restaurants (name) VALUES
('Perchini'),
('USSR'),
('KFC');
INSERT INTO dishes (name, price, restaurant_id) VALUES
('soup', 100, 100001),
('beef', 200, 100001),
('Cheburek', 80, 100002),
('Borsch', 150, 100002),
('Vedro', 500, 100003),
('Burger', 200, 100003);<file_sep>package ru.restaurantvote.util;
import ru.restaurantvote.model.AbstractBaseEntity;
public class ValidationUtil {
public static void checkNew(AbstractBaseEntity entity) {
if (!entity.isNew()) {
throw new IllegalArgumentException(entity + " must be new (id=null)");
}
}
public static void assureIdConsistent(AbstractBaseEntity entity, int id) {
if(entity.isNew()) {
entity.setId(id);
} else if (entity.id() != id) {
throw new IllegalArgumentException(entity + "must be with id=" + id);
}
}
}
| 7b52e105a8bc5f64119f65c0e37ec5579bff29f0 | [
"Java",
"SQL",
"Maven POM"
]
| 10 | SQL | ValdisWallace/restaurantvote | a06745d9733eb761ec2c80bc82b8061d48bb7ca2 | 4365b0157c0c9ee32915eab1b877c52d722f1e98 |
refs/heads/master | <file_sep>var React = require('react');
var Colour = require('./colour');
var Selections = require('./selections');
var Input = require('./input');
module.exports = React.createClass({
displayName: "Play",
getInitialState: function(){
return {selections: ['green']};
},
remove_selection: function(colour){
var selections = this.state.selections.filter(function(selection){
return selection !== colour;
});
this.setState({selections: selections});
},
add_selection: function(selection){
var selections = this.state.selections.concat([selection]);
this.setState({selections: selections});
},
render: function(){
return(
<div className="wrapper">
<Colour colour="#FFF000"/>
<Selections selections={this.state.selections} onRemove={this.remove_selection}/>
<Input colour_determined={this.add_selection}/>
</div>
);
}
});
<file_sep>var React = require('react');
var average_rgb = require('./average_rgb');
var rgb_to_h = require('./rgb_to_h');
var canvas_video = require('./canvas_video');
module.exports = React.createClass({
displayName: "Input",
getInitialState: function(){
return {colour:"goldenrod"};
},
componentDidMount: function(){
canvas_video.start();
this.loop();
},
componentWillUnmount: function(){
canvas_video.stop();
},
loop: function(){
this.setState({ colour: this.calculate_rgb() });
setTimeout(this.loop, 500);
},
add_selection: function(){
this.props.colour_determined(this.state.colour);
},
calculate_rgb: function(){
var context = canvas_video.get_context();
var rgb = average_rgb(context);
return "rgb(" + rgb.r + ", " + rgb.g + ", " + rgb.b + " )";
},
render: function(){
var style = { backgroundColor: this.state.colour };
console.log(style);
return(
<div className="input" onClick={this.add_selection} style={style} />
);
}
});
<file_sep>var React = require('react');
var socket = io();
module.exports = React.createClass({
displayName: "Join",
getInitialState: function(){
return {code: false, name: '', state: 'not joined', colour: 'orange'}
},
submit_code: function(){
var code = this.refs.code.getDOMNode().value;
var name = this.refs.name.getDOMNode().value;
localStorage.setItem('code', code);
this.setState({code: code, name: name, state: 'joined', colour: 'aliceblue'}, function(){
socket.emit('join', this.state);
});
},
render: function(){
if(this.state.state === 'joined'){
return(
<div className="wrapper" style={{background: this.state.colour}}>
<p>You have joined {this.state.code}</p>
<p>Please wait for your controller ot start the game</p>
</div>
);
}else{
return(
<div className="wrapper" style={{background: this.state.colour}}>
<h1>Join a game</h1>
<p>Someone gave you a join code, enter it below to join the game!</p>
<input type="text" ref="name" placeholder="Enter name"/>
<input type="text" ref="code" placeholder="Enter code"/>
<button onClick={this.submit_code}>Submit</button>
</div>
);
}
}
});
<file_sep>var React = require('react');
module.exports = React.createClass({
displayName: "Colour",
render: function(){
return(
<div className="colour" style={{backgroundColour: this.props.colour}} />
);
}
});
<file_sep>
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var MongoClient = require('mongodb').MongoClient;
var app = express();
var http = require('http').createServer(app);
var path = require('path');
var io = require('socket.io')(http);
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/join', routes.index);
app.get('/create', routes.index);
app.get('/play', routes.index);
http.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var generate_code = function(){
return "foo" + (Math.ceil(Math.random() * 10000));
};
var generate_colour = function(){
return "hsl(" + Math.round(360 * Math.random()) + ", 60%, 50%)";
};
var code;
var players = [];
io.on('connection', function(socket){
socket.on('create_game', function(){
code = generate_code();
socket.emit('code_created', code);
console.log('code generated');
});
socket.on('start_game', function(){
console.log('game started');
socket.broadcast.emit('play_game', code);
setTimeout(function(){
socket.emit('end');
});
});
socket.on('join', function(player){
players.push(player);
socket.broadcast.emit('new_player', player);
console.log('player joined: ' + player.name);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
<file_sep>var React = require('react');
var socket = io();
var Player = require('./player');
module.exports = React.createClass({
displayName: "Create",
getInitialState: function(){
return {code: false, players: []};
},
componentDidMount: function(){
socket.on('code_created', this.code_created);
socket.on('new_player', this.new_player);
socket.emit('create_game');
},
componentWillUnMount: function(){
socket.off('code_created', this.code_created);
socket.off('new_player', this.new_player);
},
new_player: function(player){
var players = this.state.players.concat([player]);
this.setState({players: players});
},
code_created: function(code){
this.setState({code: code});
},
show_code: function(){
if(this.state.code){
return(
<p>{this.state.code}</p>
);
}else{
return(<p>Fetching code...</p>)
}
},
start_game: function(){
socket.emit('start_game', this.state);
},
show_players: function(){
return(this.state.players.map(function(player, index){
return(<Player player={player} />);
}, this));
},
show_start_btn: function(){
if(this.state.players.length > 0){
return(<button onClick={this.start_game}>Start!</button>);
}
},
render: function(){
return(
<div className="wrapper">
<h1>Create a game</h1>
<p>This is your control panel screen, please leave this open while you play on other devices!</p>
{this.show_code()}
{this.show_players()}
{this.show_start_btn()}
</div>
);
}
});
<file_sep>var React = require('react');
module.exports = React.createClass({
displayName: "Selections",
remove: function(selection){
this.props.onRemove(selection);
},
generate_selections: function(){
return this.props.selections.map(function(selection, index){
return(<div key={index} className="selection" onClick={this.remove.bind(this, selection)} style={{backgroundColor: selection}} />);
}, this);
},
render: function(){
var selections = this.generate_selections();
return(
<div className="selections">
{selections}
</div>
);
}
});
<file_sep>
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
exports.game = function(req, res){
res.render('new_game', { code: 'abcdef' });
};
<file_sep>var context, video, local_stream;
var stream_video = function(video){
var videoObj = { "video": true };
var errBack = function(error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
local_stream = stream;
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
local_stream = stream;
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
else if(navigator.mozGetUserMedia) { // Firefox-prefixed
navigator.mozGetUserMedia(videoObj, function(stream){
local_stream = stream;
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
};
module.exports.start = function(){
var canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 480;
context = canvas.getContext("2d");
video = document.createElement("video");
stream_video(video);
};
module.exports.stop = function(){
video.stop();
local_stream.stop();
};
module.exports.get_context = function(){
context.drawImage(video, 0, 0, 640, 480);
return context;
};
<file_sep>var React = require('react');
module.exports = React.createClass({
displayName: "Player",
render: function(){
return(
<div className="player">
<h1>{this.props.player.name}</h1>
<p>{this.props.player.state}</p>
<p>{this.props.player.colour}</p>
</div>
);
}
})
<file_sep>module.exports = function (context) {
var rgb = {r:102,g:102,b:102}, // Set a base colour as a fallback for non-compliant browsers
pixelInterval = 5, // Rather than inspect every single pixel in the image inspect every 5th pixel
count = 0,
i = -4,
data, length;
// return the base colour for non-compliant browsers
if (!context) { return rgb; }
var height = 640;
var width = 480;
try {
data = context.getImageData(0, 0, width, height);
} catch(e) {
// catch errors - usually due to cross domain security issues
alert(e);
return rgb;
}
data = data.data;
length = data.length;
while ((i += pixelInterval * 4) < length) {
count++;
rgb.r += data[i];
rgb.g += data[i+1];
rgb.b += data[i+2];
}
// floor the average values to give correct rgb values (ie: round number values)
rgb.r = Math.floor(rgb.r/count);
rgb.g = Math.floor(rgb.g/count);
rgb.b = Math.floor(rgb.b/count);
return rgb;
};
| 18fbe47f60d87ea3e603ee82bcb1bf40905a281b | [
"JavaScript"
]
| 11 | JavaScript | atleastimtrying/gtc | f518266e2cc1dd13cfe8d2bc024793efe9ec5c92 | 835eb24bbfb8be21cb289bd65285dfbcf9e0981b |
refs/heads/master | <repo_name>FredG71/Euler<file_sep>/Problem15/main.cpp
#include <cstdio>
#include <cstdint>
/* This problem makes use of the binomial theorem, and pascal triangles. Given a binomial coeffcient (n,k), the value of the binomial coefficient for
(n,k) such that n >= 0 ^ k >= 0, x = n! / ( n - k)!k!, see http://mathworld.wolfram.com/BinomialCoefficient.html for more information.*/
inline double factorial( double n)
{
return n > 0 ? n * factorial(n - 1) : 1;
}
double Problem15( double nDown, double nRight)
{
return factorial(nDown + nRight) / (factorial(nDown) * factorial(nDown));
}
int main()
{
printf("%f\n", LatticePath( 20, 20 ));
}<file_sep>/Problem4/main.cpp
#include <cstdio>
#include <cstdint>
/* Given the fact that a six digit palindrome (which is the product we should obtain) is divisible by 11;
if we let x be a 6 digit palindrome then x has the form abccba, thus
x = 10^5a + 10^4b + 10^3c + 10^2c + 10^b + a, where 10 is congruent to -1 modulo 11, such that
10^v is congruent to (-1)^v modulo 1 (*1), hence n is congruent to -a + b - c + c -b + a which is congruent
to 0 modulo 11. We'll make use of that, as noted above the six digit palindrome is divisible by 11,
so we can factor out 11 from this, thus 11( 9091a + 910b + 100c ) = pq, considering that 11 is a prime number,
p or q has to be a multiple of 11, we can loop only through the multiples of 11.*/
bool IsPalindrome(int32_t nNumber)
{
register int32_t __nNumber__ = nNumber;
register int32_t nRetVal = 0;
if (nNumber < 10)
return true;
else if (nNumber % 10 == 0)
return false;
while (nNumber > 0)
{
nRetVal = (nRetVal * 10) + (nNumber % 10);
nNumber = nNumber / 10;
}
return __nNumber__ == nRetVal;
}
int32_t GetPalindrome()
{
register uint32_t i, j, nProduct, nDecrement, nRetVal;
i = j = nProduct = nDecrement = nRetVal = {};
for (i = 999; i > 100; i--)
{
if (i % 11 == 0)
{
j = 999;
nDecrement = 1;
}
else
{
j = 990;
nDecrement = 11;
}
while (j >= i)
{
nProduct = i * j;
if (nProduct < nRetVal)
break;
if (IsPalindrome(nProduct))
nRetVal = nProduct;
// END IF
j -= nDecrement;
}
}
return nRetVal;
}
int main(int argc, char** argv)
{
printf("%i\n", GetPalindrome());
}<file_sep>/Problem1/main.cpp
#include <cstdio>
#include <cstdint>
/* Given the set A that contains the multiples of 3 and the set B that contains the multiples of 5, we
we seek the sum of the multiples of 3 or 5.
The multiples of 3 are an arithmetic sequence with d = 3, where d is the common difference, the multiples of
5 are also an arithmetic sequence but with d = 5.
given f(x) -> N( n1 + Nj ) / 2 = S. Where N is the number of multiples, n1 is the first multiple of the
arithemtic series, and Nj is the last multiple, S is the resulting sum. To solve for N, the explicit formula is used,
thus g(x) -> n1 + ( N - 1 ) * D = J. Where n1 is the first factor, N is the number of such factors (which we want
to solve for) D is the common difference, and J is the last factor.
Case: Sum of multiples of 3, we'll make use of g(x) to solve for N and finally f(x) to get S, thus
3 + ( N - 1 ) * 3 = 999 - where 999 is a multiple of 3 below 1000.
Solving for N we get 3 + 3N - 3 = 999; N = 333.
Substituting in f(x). f(x) -> 333 * ( 3 + 999 ) / 2 = 166833
Doing the same for the multiples of 5 we get.
f(x) -> 199 * ( 5 + 995 ) / 2 = 99500.
Accounting for the fact that the multiples of 15 are also multiples of 3 and 5 (intersection).
Solve for N using g(x) then finally use f(x). 66 * ( 15 + 990 ) / 2 = 33165
Thus assigning A to the first result, B to the second result and C to the third result, we're given
X = A + B - C
X = 166833 + 99500 - 33165
= 233168
*/
uint32_t FirstProblem()
{
return((333 * (3 + 999) >> 1) + (199 * (5 + 995) >> 1) - (66 * ( 15 + 990 ) >> 1));
}
int main()
{
printf("%i\n", FirstProblem());
}<file_sep>/Problem45/Main.cpp
/* Triangular, pentagonal and hexagonal numbers are a divergent series. Let T stand for the triangular numbers, P for the pentagonal numbers,
and H for the hexagonal numbers, in this problem we only need to generate triangular numbers as we're solving
for T = P = H, which makes use of the simplest Faulhaber formula 1st degree. We'll make use of the triangular, pentagonal and hexagonal (perfect square) quadratic
formulas. */
#include <cmath>
#include <cstdio>
unsigned long long int Problem45(unsigned long long int nNumber)
{
if( ( fmod( (sqrt( 8 * nNumber + 1 ) - 1 ) / 2, 1 ) == 0 ) &&
( fmod( (sqrt( 8 * nNumber + 1 ) + 1 ) / 4, 1 ) == 0 ) &&
( fmod( (sqrt( 24 * nNumber + 1 ) + 1 ) / 6, 1 ) == 0 )) return nNumber;
//END IF
else
return 0;
return 0;
}
int main()
{
for (unsigned int i = 286; i < 80000; ++i)
{
unsigned long long int retVal = Problem45(i * ( i + 1 ) / 2);
if ( retVal != 0 )
printf("%lld\t%i\n", retVal, i);
}
}<file_sep>/Problem3/main.cpp
#include <cstdio>
#include <cmath>
#include <cstdlib>
/* This problem has been solved using the Pollard Monte Carlo factorization method
http://mathworld.wolfram.com/PollardRhoFactorizationMethod.html, which is fine
for < 100 digits, the algorithm itself makes use of the birthday paradox etc. IsPrime makes use of Wilson's therom
(implementation is on the relevant wikipedia page) see Primality test.
which may be a bit slow, http://en.wikipedia.org/wiki/Wilson%27s_theorem
gcd makes use of the Euclidian algorithm. */
namespace Pollard{
__int64 __Predicate = 1;
}
__int64 BParadox(__int64 __Predicate)
{
return __Predicate * __Predicate + Pollard::__Predicate;
}
__int64 gcd(__int64 A, __int64 B)
{
if (A % B == 0)
return B;
return gcd(B, A % B);
}
__int64 PollardRho(__int64 nNumber)
{
__int64 x1 = 2, x2 = 2, nDivisor = 0;
if (nNumber % 2 == 0)
return 2;
do{
x1 = BParadox(x1) % nNumber;
x2 = BParadox(BParadox(x2)) % nNumber;
nDivisor = gcd(_abs64(x1 - x2), nNumber);
} while (nDivisor == 1);
return nDivisor;
}
bool IsPrime(__int64 nPrimeNumber)
{
if (nPrimeNumber <= 3)
return nPrimeNumber > 1;
else if (nPrimeNumber % 2 == 0 || nPrimeNumber % 3 == 0)
return false;
else
{
for (int i = 5; i * i <= nPrimeNumber; i += 6)
{
if (nPrimeNumber % i == 0 || nPrimeNumber % (i + 2) == 0)
return false;
}
return true;
}
}
__int64 __fastcall GetFactor(__int64 nBigDigit)
{
static __int64 nLargestFactor = 0;
if (nBigDigit == 1)
return 0;
if (IsPrime(nBigDigit))
{
nLargestFactor = nBigDigit;
return 0;
}
__int64 nDivisor = PollardRho(nBigDigit);
GetFactor(nDivisor);
GetFactor(nBigDigit / nDivisor);
return nLargestFactor;
}
int main()
{
printf("%i\n", GetFactor(600851475143));
}<file_sep>/Problem9/main.cpp
#include <cstdio>
#include <cmath>
#include <cstdint>
/* This problem makes use of Euclid's formula, namely a = m^2 - n^2, b = 2mn, c = m^2 + n^2.
In this case, m * ( m + n ) = 500
sqrt( 500 ) = ~22, http://en.wikipedia.org/wiki/Pythagorean_triple
*/
uint32_t gcd(uint32_t A, uint32_t B)
{
if (A % B == 0)
return B;
return gcd(B, A % B);
}
uint32_t Problem9()
{
uint32_t a, b, c, m, n, d;
a = b = c = n = d = {};
uint32_t nParity;
uint32_t nHalf = static_cast<uint32_t>(sqrt( 1000 / 2 ));
for (m = 2; m <= nHalf; m++)
{
if ((1000 / 2) % m == 0)
{
if (m % 2 == 0)
nParity = m + 1;
else
nParity = m + 2;
}
for (; nParity < 2 * m && nParity <= 1000 / (2 * m); )
{
if (1000 / (2 * m) % nParity == 0 && gcd(nParity, m) == 1)
{
d = 1000 / 2 / ( nParity * m );
n = nParity - m;
a = d * ( m * m - n * n );
b = 2 * d * n * m;
c = d * ( m * m + n * n );
goto End;
}
nParity += 2;
}
}
End:
return a * b * c;
}
int main()
{
printf( "%i\n", Problem9());
}<file_sep>/Problem17/Main.cpp
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdint>
/* Uses a table that contains the words used for the numbers, the GetNumberDigit stores an array of indices that contains the index into the
consecutive words, by extracting each digit using the modulo operation, i.e. n mod nx10^y where y is the unit, we can combine the needed
words together, note that no explicit string concatenation occurs, i.e. the strings are never concatenated, 0xFFFFFFFF denotes the end of the
array of indices. */
char* NumberLetterTable[]{
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen",
"twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety",
"hundred",
"thousand",
"and",
};
void GetNumberDigit(uint32_t nIndex, /*__out__*/ uint32_t* IndexArray)
{
if (nIndex < 0 || nIndex > 1000)
__asm int 1;
if (nIndex <= 10)
{
IndexArray[0] = nIndex - 1;
IndexArray[1] = 0xFFFFFFFF;
}
else if (nIndex > 10)
{
if (nIndex % 10 != 0 && nIndex < 20)
{
IndexArray[0] = ( ( nIndex % 10 ) + 10 ) - 1;
IndexArray[1] = 0xFFFFFFFF;
}
else if (nIndex % 10 == 0 && nIndex >= 20)
{
IndexArray[0] = ((nIndex / 10) + 17);
IndexArray[1] = 0xFFFFFFFF;
}
else if (nIndex % 10 != 0 && nIndex >= 20)
{
IndexArray[0] = (( nIndex / 10 ) + 17);
IndexArray[1] = ( nIndex % 10 ) - 1;
IndexArray[2] = 0xFFFFFFFF;
}
if (nIndex >= 100)
{
if (nIndex % 100 == 0)
{
IndexArray[0] = (nIndex / 100) - 1;
IndexArray[1] = 27;
IndexArray[2] = 0xFFFFFFFF;
}
else if (nIndex % 100 > 0)
{
IndexArray[0] = ( nIndex / 100 ) - 1;
IndexArray[1] = 27;
IndexArray[2] = 29;
if (nIndex % 100 < 10)
{
IndexArray[3] = ( nIndex % 100 ) - 1;
IndexArray[4] = 0xFFFFFFFF;
}
else if (nIndex % 100 >= 10)
{
if ((nIndex % 100) % 10 == 0)
{
if ((nIndex % 100) / 10 == 1)
{
IndexArray[3] = ((nIndex % 100) / 10) + 8;
IndexArray[4] = 0xFFFFFFFF;
}
else if ((nIndex % 100) / 10 > 1)
{
IndexArray[3] = ((nIndex % 100) / 10) + 17;
IndexArray[4] = 0xFFFFFFFF;
}
}
else if ((nIndex % 100) % 10 > 0)
{
if ((nIndex % 100) / 10 == 1)
{
IndexArray[3] = ( nIndex % 100 ) - 1;
IndexArray[4] = 0xFFFFFFFF;
}
else if ((nIndex % 100 / 10 > 1))
{
IndexArray[3] = ( ( nIndex % 100 ) / 10 ) + 17;
if ((nIndex % 100) % 10 == 0)
{
IndexArray[4] = 0xFFFFFFFF;
}
else if ((nIndex % 100) % 10 > 0)
{
IndexArray[4] = (( nIndex % 100 ) % 10 ) - 1;
IndexArray[5] = 0xFFFFFFFF;
}
}
}
}
}
}
if (nIndex == 1000)
{
IndexArray[0] = 0;
IndexArray[1] = 28;
IndexArray[2] = 0xFFFFFFFF;
}
}
}
int main()
{
uint32_t nCounter = 0;
unsigned int* Array = new uint32_t[25];
uint32_t j = 0;
for (uint32_t i = 1; i <= 1000; ++i)
{
GetNumberDigit( i, Array );
while (Array[j] != -1)
{
nCounter += strlen(NumberLetterTable[Array[j]]);
++j;
}
j = 0;
}
printf("%i\n", nCounter );
delete[] Array;
}
<file_sep>/Problem6/main.cpp
#include <cstdio>
#include <cstdint>
/* Considering that the sequence { 1 + 2 .. + .. + .. oo } is a divergent series, we'll make use of the well known
formula n( n + 1 ) / 2. The sequence { 1^2 .. 2^2 .. + .. oo } is slightly more complex, while we note that the
"second order" series has a common difference of 3, we'll make use of Faulhaber's formula, which
expresses the sum stated above as a (e+2)th degrees polynomial function of n (note that higher degree polynomials
are implied but needn't be mentioned), thus we arrive at n( n + 1 )(2n + 1 ) / 6. For the formulas
of sums of higher or lower degrees see http://mathworld.wolfram.com/FaulhabersFormula.html */
uint32_t SquareOfSum(uint32_t nLast)
{
return ( ((nLast * nLast + nLast) * 1 >> 1) * ((nLast * nLast + nLast) * 1 >> 1) );
}
uint32_t SumOfSquares(uint32_t nLast)
{
return ( (2 * nLast * nLast * nLast) + (3 * nLast * nLast) + nLast ) * 1 / 6;
}
uint32_t SixthProblem( uint32_t nNumber )
{
return(SquareOfSum(nNumber) - SumOfSquares(nNumber));
}
int main()
{
printf("%i\n", SixthProblem(100));
}<file_sep>/Problem2/main.cpp
#include <cstdio>
#include <cstdint>
#include <cmath>
/*
Given the sequence of fibonacci numbers, Binet's Fibonacci Number Formula will be used to solve this problem
see http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html for the formula.
In the sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
We note that the even valued numbers have a common difference of 3, i.e. D = 3.
Using: f(x) -> Phi^n - (-Phi)^-n / sqrt(5).
Where n is the nTH fibonacci number, we'll scale n by 3 to skip the 3 numbers and simply get the even valued
fibonacci numbers.
Thus substituting in f(x) -> Phi^3n - ( -Phi ) ^ -3n / sqrt(5) = X.
Where phi is the golden ratio, i.e ( 1 + sqrt(5) ) / 2.
Solving for i:
Logarithm10(n) + Logarithm10(5) / 2 = i * Logarithm10(Phi), such that
i = (Logarithm10(n) + Logarithm10(5)/2) / Logarithm10(Phi)), which we'll make use of below.
*/
const double dGoldenRatio = (1 + sqrt(5)) / 2;
const uint32_t Index = floor(log(4000000 * sqrt(5)) / log( dGoldenRatio ) + 1/2);
/*@param N: Nth fibonacci number.
@return: The Nth fibonacci number*/
double Binet(uint32_t N)
{
double _Binet = pow(dGoldenRatio, 3 * N) - pow(1 - dGoldenRatio, 3 * N);
return round(_Binet / sqrt(5));
}
int main()
{
uint32_t nIndex = 0;
uint32_t nCounter = Index / 3;
double Sum = 0;
do{
Sum += Binet( nIndex );
} while ( nIndex++ < nCounter );
printf( "%f\n", Sum );
}<file_sep>/Problem12/main.cpp
#include <cstdio>
#include <cstring>
#include <cstdint>
#include <iostream>
#include <cstdlib>
#include <cmath>
/* Makes use of the fact that the number of factors is the product of the numbers of consecutive equal primes + 1, i.e.
given a number x part of the set of integers (*only what's relevant), then the number x can be written as a product of prime factors
such that x = p1^a * p2^b * p3^c. Given the number 28 in this example, the prime factors are 2, 2, 7. Thus 28 can be written as the product
2 * 2 * 7 = 28, the number of divisors in this case, is the number of consecutive prime factors + 1, thus given a function f(x) that returns
the number of divisors of x, f(28) -> ( 2 + 1 ) ( 1 + 1 ) = 6, the same principle follows for the triangle numbers, the formula for the divergent series
n( n + 1 ) / 2 is also used.*/
uint32_t pSieveArray[20];
uint32_t nPrimeFactors[500];
uint32_t nPrimeFactorsSize = 0;
void InitSieve(int32_t nMax)
{
for (uint32_t k = 1; k <= ceil(ceil(sqrt(nMax)) / 2); k++)
{
if (((pSieveArray[(k) >> 5] >> ((k)& 31)) & 1) == 0)
{
for (uint32_t j = 2 * k + 1, i = 2 * k * (k + 1); i <ceil(nMax / 2); i += j)
pSieveArray[i >> 5] |= 1 << (i & 31);
}
}
}
uint32_t IsPrime(uint32_t nNumber)
{
if ((nNumber == 2) || (nNumber > 2 && (nNumber & 1) == 1 &&
((pSieveArray[((nNumber - 1) >> 1) >> 5] >> (((nNumber - 1) >> 1) & 31)) & 1) == 0))
return nNumber;
//END IF
else
return 0;
}
uint32_t GetFactorSum(uint32_t nNumber)
{
register uint32_t nCounter = 1; // First number is always equal
register uint32_t nRetVal = 1;
memset(nPrimeFactors, 0, 499);
nPrimeFactorsSize = 0;
for (uint32_t i = 2; i <= nNumber;)
{
if (IsPrime(i))
{
if (nNumber % i == 0)
{
nNumber /= i;
nPrimeFactors[nPrimeFactorsSize] = i;
nPrimeFactorsSize++;
}
else
++i;
}
else
++i;
}
for (uint32_t i = 0; i < nPrimeFactorsSize; ++i)
{
if (nPrimeFactors[i] == nPrimeFactors[i + 1])
nCounter += 1;
else if (nPrimeFactors[i] != nPrimeFactors[i + 1])
{
nRetVal *= (nCounter + 1);
nCounter = 1;
}
}
return nRetVal;
}
uint32_t Problem12()
{
for (uint32_t i = 0; i < 12376; ++i)
{
register uint32_t j = GetFactorSum(i * (i + 1) / 2);
if (j >= 500)
{
return (i * (i + 1) / 2);
}
}
return 0;
}
int main(int argc, char *argv[])
{
InitSieve(500);
printf("%u\n", Problem12());
}<file_sep>/Problem8/main.cpp
#include <cstdio>
#include <cstdlib>
#include <cstring>
/* Uses a brute force approach by multiplying each adjacent 13 digits, uses memmove to cut up the string into
a string of length 13, and multiplies each digit, multiplication is skipped if a digit is 0, as x(0) = 0 for all x.*/
char Product[14];
char* BigNumber = "73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
62229893423380308135336276614282806444486645238749\
30358907296290491560440772390713810515859307960866\
70172427121883998797908792274921901699720888093776\
65727333001053367881220235421809751254540594752243\
52584907711670556013604839586446706324415722155397\
53697817977846174064955149290862569321978468622482\
83972241375657056057490261407972968652414535100474\
82166370484403199890008895243450658541227588666881\
16427171479924442928230863465674813919123162824586\
17866458359124566529476545682848912883142607690042\
24219022671055626321111109370544217506941658960408\
07198403850962455444362981230987879927244284909188\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450";
void GetProduct(char* szTarget )
{
__int64 nProduct = 1;
static __int64 nOldProduct;
for (int i = 0; i < 13; i++)
{
if (szTarget[i] - '0' == 0)
return;
nProduct *= szTarget[i] - '0';
}
if (nProduct < nOldProduct)
return;
printf("Product: %I64u\n", nProduct);
nOldProduct = nProduct;
}
void Dissect()
{
static int nIndex = 0;
for (int i = 0; i < 200; i++)
{
memmove(Product, &BigNumber[nIndex], 13);
nIndex += 1;
GetProduct(Product);
}
}
int main()
{
Dissect();
}
<file_sep>/Problem458/Main.cpp
/* This problem makes use of modular matrix exponentiation by recursion http://en.wikipedia.org/wiki/Matrix_exponential, http://en.wikipedia.org/wiki/Modular_exponentiation#Matrices
*/
#include <cstdio>
long long int M[6 * 6] = {
1, 1, 1, 1, 1, 1,
6, 1, 1, 1, 1, 1,
0, 5, 1, 1, 1, 1,
0, 0, 4, 1, 1, 1,
0, 0, 0, 3, 1, 1,
0, 0, 0, 0, 2, 1
};
long long int nRetVal[6 * 6];
const long long int nMod = 1000000000;
void MatrixExponentationMod(long long int nDegrees, long long int nModulus)
{
long long int nTemp[6 * 6];
if (!nDegrees)
{
for (long long int i = 0; i < 6; i++)
{
for (long long int j = 0; j < 6; ++j)
nRetVal[i * 6 + j] = 0;
//END FOR
nRetVal[i * 6 + i] = 1;
}
return;
}
MatrixExponentationMod(nDegrees >> 1, nMod);
for (long long int i = 0; i<6; i++)
{
for (long long int j = 0; j < 6; ++j)
{
nTemp[i * 6 + j] = 0;
for (long long int nDegrees = 0; nDegrees<6; nDegrees++)
nTemp[i * 6 + j] = (nTemp[i * 6 + j] + (nRetVal[i * 6 + nDegrees] * nRetVal[nDegrees * 6 + j]) % nModulus) % nModulus;
// END FOR
}
}
for (long long int i = 0; i < 6; ++i)
{
for (long long int j = 0; j < 6; ++j)
nRetVal[i * 6 + j] = nTemp[i * 6 + j];
//END FOR
}
if ((nDegrees & 2 - 1) == 1)
{
for (long long int i = 0; i < 6; ++i)
{
for (long long int j = 0; j < 6; ++j)
{
nTemp[i * 6 + j] = 0;
for (long long int nDegrees = 0; nDegrees < 6; ++nDegrees)
nTemp[i * 6 + j] = (nTemp[i * 6 + j] + (nRetVal[i * 6 + nDegrees] * M[nDegrees * 6 + j]) % nModulus) % nModulus;
//END FOR
}
}
for (long long int i = 0; i < 6; ++i)
for (long long int j = 0; j < 6; ++j)
nRetVal[i * 6 + j] = nTemp[i * 6 + j];
//END FOR
}
}
int main(void)
{
MatrixExponentationMod(999999999999, nMod);
long long int nRet = 0;
for (long long int i = 0; i < 6; ++i)
{
nRet += nRetVal[i * 6 + 0] * 7;
nRet %= nMod;
}
printf("%lld\n", nRet);
}<file_sep>/Problem7/main.cpp
#include <cstdio>
#include <cstring>
#include <cstdint>
#include <cmath>
/* This problem uses the Sieve of Eratosthenes, however the array is scaled by ~0.015625, and "ceil'd",
We loop through the array and count the number of primes, until we reach the 10001th prime, while the
approximation n ln n was thought of, and so was
ln n + ln ln n - 1 + ( ln ln n - 2 ) / ln n - ( ln ln n ) ^2 - 6 ln ln n + 11 / 2 ( ln n ) ^ 2
+ o ( 1 / ( ln n ) ^ 2. The sieve was chosen, although the bounds (Rosser's theorem) could have been
used, for simplicity it hasn't*/
uint32_t pSieveArray[1641];
void InitSieve(int32_t nMax)
{
for (uint32_t k = 1; k <= ceil(ceil(sqrt(nMax)) / 2); k++)
{
if (((pSieveArray[(k) >> 5] >> ((k) & 31)) & 1) == 0)
{
for (uint32_t j = 2 * k + 1, i = 2 * k * (k + 1); i <ceil(nMax / 2); i += j)
pSieveArray[i >> 5] |= 1 << (i & 31);
}
}
}
uint32_t IsPrime(uint32_t nNumber)
{
if ((nNumber == 2) || (nNumber > 2 && (nNumber & 1) == 1 &&
((pSieveArray[((nNumber - 1) >> 1) >> 5] >> (((nNumber - 1) >> 1) & 31)) & 1) == 0))
return nNumber;
//END IF
else
return 0;
}
int main()
{
InitSieve(105000);
for (uint32_t i = 0, j = 0; i <= 105000; i++)
{
if (IsPrime(i))
{
j += 1;
if ( j == 10001 )
printf("Prime: %i, n: %i\n", i, j);
}
}
}<file_sep>/Problem5/main.cpp
#include <cstdio>
#include <cstdint>
/* To solve this problem, we'll simply reverse what's being asked. By making use of the LCM we can easily solve
this simple problem, given the fact that 2520 is the smallest number that can be divided by 1 to 10 without any
remainder this implies that 2520 = "1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10", note that this is in quotes to emphasise
that this isn't actually true, as noted on the first problem, for a number j there exists a number i that evenly divides
j, we do not want to include this number twice, thus for 2520 we note this can also be represented as
9 * 8 * 7 * 5. By making use of the same process for the number x, we seek a number x, such that
{ 1 ... 20 | x }
Solving for x, we arrive at x = 19 * 17 * 16 * 13 * 11 * 9 * 7 * 5
x = 232 792 560
*/
uint32_t FifthProblem()
{
return (19 * 17 * 16 * 13 * 11 * 9 * 7 * 5);
}
int main(int argc, char** argv)
{
printf("%i\n", FifthProblem());
}<file_sep>/Problem18/main.cpp
/* Makes use of Dijkstra's algorithm */
#include <cstdio>
int Triangle[] = { 75, 95, 64, 17, 47, 82, 18, 35, 87, 10, 20, 4, 82, 47, 65,
19, 1, 23, 75, 3, 34, 88, 2, 77, 73, 7, 63, 67, 99, 65, 4,
28, 6, 16, 70, 92, 41, 41, 26, 56, 83, 40, 80, 70, 33, 41,
48, 72, 33, 47, 32, 37, 16, 94, 29, 53, 71, 44, 65, 25, 43,
91, 52, 97, 51, 14, 70, 11, 33, 28, 77, 73, 17, 78, 39, 68,
17, 57, 91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48,
63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31,
4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23
};
const int max(int a, int b)
{
return a > b ? a : b;
}
void Problem18()
{
register int nCurrentLine = 13;
register int nIndex = 0;
int nSize = 120 - 15;
for (; nCurrentLine >= 0; --nCurrentLine)
{
for (nIndex = 0; nIndex <= nCurrentLine; ++nIndex)
{
register int i = nSize - nCurrentLine + nIndex - 1;
register int nSubTri1 = Triangle[i + nCurrentLine + 1], nSubTri2 = Triangle[ i + nCurrentLine + 2 ];
Triangle[i] += max( nSubTri1, nSubTri2 );
}
nSize -= nCurrentLine + 1;
}
printf("%i\n", Triangle[0]);
}
int main()
{
Problem18();
}<file_sep>/Problem16/main.cpp
#include <cstdio>
#include <cmath>
#include <gmp.h>
#include <cstdint>
#pragma comment( lib, "gmp.lib")
/* The number 2^1000 is a number that has 302 digits (this can be found using logarithms), instead of using the mathematical algorithm for
calculating the sum of a given digit (digit sum), Σ(log_b(x))[n=0] -> ( x mod b^n+1 - x mod b ^ n), the mpz_get_str procedure is used,
which transforms the number stored in an mpz_t into a string, each element from the string is converted into an integer and summed. */
uint32_t SumDigit(mpz_t nNumber)
{
uint32_t nRetVal = 0;
char* szBuffer = mpz_get_str( NULL, 10, nNumber );
for (uint32_t i = 0; i < strlen(szBuffer); ++i)
nRetVal += (uint32_t)(szBuffer[i] - '0');
return nRetVal;
}
void Problem16()
{
mpz_t RetVal;
mpz_t Base;
mpz_init_set_ui(Base, 2);
mpz_init_set_ui(RetVal, 0);
mpz_pow_ui(RetVal, Base, 1000);
printf("%i\n", SumDigit(RetVal));
mpz_clear( RetVal );
mpz_clear( Base );
}
int main()
{
Problem16();
}<file_sep>/Problem443/main.cpp
/* Makes use of the fact that some numbers in the sequence given by g(n) -> 3n. The procedure starts with a number n such that
g(n) -> 3n and it finds the next in the sequence such that this proposition holds etc. */
#include <cstdio>
signed long long int Sequence( signed long long int nLast )
{
signed long long int nDividend = 2 * nLast - 1;
for (signed long long int nDivisor = 3; nDivisor * nDivisor <= nDividend; nDivisor += 2)
{
if (nDividend % nDivisor == 0)
return nLast + 1 + ( nDivisor - 3 ) / 2;
}
return nDividend;
}
signed long long int Problem443(signed long long int nLast)
{
signed long long int nStart = 9;
signed long long x = Sequence( nStart );
signed long long nDividend = 0;
for (; x <= nLast;)
{
nStart = x;
x = Sequence( x );
}
return 3 * nStart + ( nLast - nStart );
}
int main()
{
printf("%lld\n", Problem443(1e15));
}<file_sep>/Problem10/main.cpp
#include <cstdio>
#include <cstring>
#include <cstdint>
#include <cmath>
/* This uses the same functions than problem 7, except for the fact that it has been changed to a type
of long long, as a sum of primes below 2 000 000, surely exceeds INT_MAX.*/
__int64 pSieveArray[31250];
void InitSieve(__int64 nMax)
{
for (uint32_t k = 1; k <= ceil(ceil(sqrt(nMax)) / 2); k++)
{
if (((pSieveArray[(k) >> 5] >> ((k)& 31)) & 1) == 0)
{
for (uint32_t j = 2 * k + 1, i = 2 * k * (k + 1); i <ceil(nMax / 2); i += j)
pSieveArray[i >> 5] |= 1i64 << (i & 31);
}
}
}
__int64 IsPrime(__int64 nNumber)
{
if ((nNumber == 2) || (nNumber > 2 && (nNumber & 1) == 1 &&
((pSieveArray[((nNumber - 1) >> 1) >> 5] >> (((nNumber - 1) >> 1) & 31)) & 1) == 0))
return nNumber;
//END IF
else
return 0;
}
__int64 Problem10()
{
__int64 nSum = 0;
for (uint32_t i = 0, j = 0; i <= 2000000; i++)
nSum += IsPrime(i) ? i : 0;
//END FOR
return nSum;
}
int main()
{
InitSieve(2000000);
printf("Sum: %I64u\n", Problem10());
}<file_sep>/Problem14/main.cpp
#include <cstdio>
#include <cstdint>
/* Brute force implementation, basic optimizations have been included */
inline uint64_t Collatz(uint64_t nNumber)
{
uint64_t nRetVal = 0;
while (nNumber > 1)
{
while ((nNumber & 1) == 1)
nNumber = (3 * nNumber + 1) / 2, nRetVal += 2;
while ((nNumber & 1) == 0)
nNumber /= 2, nRetVal++;
}
return nRetVal;
}
int main()
{
uint64_t nMaxChain = 0;
uint64_t nNumber = 0;
uint64_t nChain = 0;
for (int i = 1000000; i > 0; i -= 9)
{
nChain = Collatz(i);
if (nChain > nMaxChain)
{
nMaxChain = nChain;
nNumber = i;
}
nChain = Collatz(i + 1);
if (nChain > nMaxChain)
{
nMaxChain = nChain;
nNumber = i + 1;
}
nChain = Collatz(i + 3);
if (nChain > nMaxChain)
{
nMaxChain = nChain;
nNumber = i + 3;
}
nChain = Collatz(i + 4);
if (nChain > nMaxChain)
{
nMaxChain = nChain;
nNumber = i + 4;
}
nChain = Collatz(i + 5);
if (nChain > nMaxChain)
{
nMaxChain = nChain;
nNumber = i + 5;
}
nChain = Collatz(i + 6);
if (nChain > nMaxChain)
{
nMaxChain = nChain;
nNumber = i + 6;
}
}
printf("%i\n", nNumber);
} | ff436f0909d10162217001352ad6f5eafa04e263 | [
"C++"
]
| 19 | C++ | FredG71/Euler | 7a5cc0ec15ee9e0bd471af851af75b2383ef8226 | 012491c68080970f05aca98b64070f57cf1c8787 |
refs/heads/master | <repo_name>ndsorrowchi/EbuzFinal<file_sep>/src/java/DataAccess/ProductDA.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DataAccess;
import BeanModel.BookListModel;
import BeanModel.BookModel;
import java.util.ArrayList;
import Utils.DBUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
*
* @author chiming
*/
public class ProductDA {
private ProductDA(){}
//==================
public static final BookModel getById(int bid) throws Exception{
if(bid==-1)
{
return null;
}
//select most purchased item purchased by the users who has bought the current item
String sql = "select book.bid,book.bookname,book.QUANTITY,book.PRICE,book.CATEGORY from book\n" +
"where book.bid=?";
Connection con = DBUtils.getConnFromPool();
try{
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, bid);
ResultSet rs = ps.executeQuery();
if(rs.next()){
int id=rs.getInt(1);
String bname=rs.getString(2);
int quantity=rs.getInt(3);
java.math.BigDecimal bi=rs.getBigDecimal(4);
String category = rs.getString(5);
return new BookModel(id,bname,quantity,bi.toPlainString(),category);
}
else
{
return null;
}
}catch(Exception e)
{
throw e;
}
finally{con.close();}
}
public static final BookListModel getRecommendation(int bid) throws Exception{
if(bid==-1)
{
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
return new BookListModel("recommendation",arr);
}
//select most purchased item purchased by the users who has bought the current item
String sql = "select book.bid,book.bookname,book.QUANTITY,book.PRICE,book.CATEGORY from book,\n" +
"(select O.bid, count(O.bid) as Relativity\n" +
"from Orders O, Book B, (select distinct uid from Orders where bid=?) V\n" +
"where O.uid=V.uid and O.bid!=? and B.bid=O.bid\n" +
"group by (O.bid)\n" +
"order by Relativity desc\n" +
"fetch first 10 rows only) as R\n" +
"where R.bid=book.bid";
Connection con = DBUtils.getConnFromPool();
try{
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, bid);
ps.setInt(2, bid);
ResultSet rs = ps.executeQuery();
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
while(rs.next()){
int id=rs.getInt(1);
String bname=rs.getString(2);
int quantity=rs.getInt(3);
java.math.BigDecimal bi=rs.getBigDecimal(4);
String category = rs.getString(5);
arr.add(new BookModel(id,bname,quantity,bi.toPlainString(),category));
}
return new BookListModel("recommendation",arr);
}catch(Exception e)
{
throw e;
}
finally{con.close();}
}
public static final BookListModel getTopSelling() throws Exception{
//top selling 10 items
String sql = "select book.BID,book.BOOKNAME,book.QUANTITY,book.PRICE,book.CATEGORY from\n" +
"book,(\n" +
"SELECT bid,sum(quantity) as totalsales FROM orders\n" +
"group by bid\n" +
"order by totalsales desc\n" +
"fetch first 10 rows only) as T\n" +
"where T.bid=book.bid";
Connection con = DBUtils.getConnFromPool();
try{
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
while(rs.next()){
int bid=rs.getInt(1);
String bname=rs.getString(2);
int quantity=rs.getInt(3);
java.math.BigDecimal bi=rs.getBigDecimal(4);
String category = rs.getString(5);
arr.add(new BookModel(bid,bname,quantity,bi.toPlainString(),category));
}
return new BookListModel("top-selling",arr);
}catch(Exception e)
{
throw e;
}
finally{con.close();}
}
public static final BookListModel getSearchResult(String keywords) throws Exception{
if(keywords==null)
{
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
return new BookListModel("keyword-search",arr);
}
String splitted[]=keywords.split("\\s+");
String head = "select book.BID,book.BOOKNAME,book.QUANTITY,book.PRICE,book.CATEGORY, Temp.relativity\n" +
"from book, (\n" +
"select T.bid, count (T.bid) as relativity from\n" +
"(\n";
String tail = ") T\n" +
"group by (T.bid)\n" +
"order by (relativity) desc) as Temp\n" +
"where Temp.bid=book.bid\n" +
"order by (Temp.relativity) desc";
String sql="";
StringBuilder sb = new StringBuilder();
if(splitted.length>0)
{
for(int i=0;i<splitted.length;i++)
{
if(splitted[i]==null || splitted[i].length()==0)
continue;
String temp = "select bid from BOOK\n" +
"where lower(bookname) like '%"+splitted[i].toLowerCase()+"%'";
if(i!=splitted.length-1)
{
temp+="\n Union All \n ";
}
sb.append(temp);
}
sql=head+sb.toString()+tail;
}
else//no keywords means all
{
sql="select * from book";
}
Connection con = DBUtils.getConnFromPool();
try{
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
while(rs.next()){
int bid=rs.getInt(1);
String bname=rs.getString(2);
int quantity=rs.getInt(3);
java.math.BigDecimal bi=rs.getBigDecimal(4);
String category = rs.getString(5);
arr.add(new BookModel(bid,bname,quantity,bi.toPlainString(),category));
}
return new BookListModel("keyword-search",arr);
}catch(Exception e)
{
throw e;
}
finally{con.close();}
}
public static final BookListModel getSearchResult(String keywords, int rowsPerPage, int pageNumber) throws Exception{
if(keywords==null||rowsPerPage<1||pageNumber<1)
{
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
return new BookListModel("keyword-search",arr);
}
String splitted[]=keywords.split("\\s+");
String head = "select book.BID,book.BOOKNAME,book.QUANTITY,book.PRICE,book.CATEGORY, Temp.relativity\n" +
"from book, (\n" +
"select T.bid, count (T.bid) as relativity from\n" +
"(\n";
String tail = ") T\n" +
"group by (T.bid)\n" +
"order by (relativity) desc) as Temp\n" +
"where Temp.bid=book.bid\n" +
"order by (Temp.relativity) desc";
String sql="";
StringBuilder sb = new StringBuilder();
if(splitted.length>0)
{
for(int i=0;i<splitted.length;i++)
{
if(splitted[i]==null || splitted[i].length()==0)
continue;
String temp = "select bid from BOOK\n" +
"where lower(bookname) like '%"+splitted[i].toLowerCase()+"%'";
if(i!=splitted.length-1)
{
temp+="\n Union All \n ";
}
sb.append(temp);
}
sql=head+sb.toString()+tail;
}
else//no keywords means all
{
sql="select * from book";
}
String limitClause = "\n offset ? rows fetch first ? rows only";
Connection con = DBUtils.getConnFromPool();
try{
PreparedStatement ps = con.prepareStatement(sql+limitClause);
ps.setInt(1, pageNumber * rowsPerPage);
ps.setInt(2, rowsPerPage);
ResultSet rs = ps.executeQuery();
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
while(rs.next()){
int bid=rs.getInt(1);
String bname=rs.getString(2);
int quantity=rs.getInt(3);
java.math.BigDecimal bi=rs.getBigDecimal(4);
String category = rs.getString(5);
arr.add(new BookModel(bid,bname,quantity,bi.toPlainString(),category));
}
return new BookListModel("keyword-search",arr);
}catch(Exception e)
{
throw e;
}
finally{con.close();}
}
public static final BookListModel getAll() throws Exception{
String sql = "select * from book";
Connection con = DBUtils.getConnFromPool();
try{
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
while(rs.next()){
int bid=rs.getInt(1);
String bname=rs.getString(2);
int quantity=rs.getInt(3);
java.math.BigDecimal bi=rs.getBigDecimal(4);
String category = rs.getString(5);
arr.add(new BookModel(bid,bname,quantity,bi.toPlainString(),category));
}
return new BookListModel("all",arr);
}catch(Exception e)
{
throw e;
}
finally{con.close();}
}
public static final BookListModel getAll(int rowsPerPage, int pageNumber) throws Exception{
if(rowsPerPage<1||pageNumber<1)
{
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
return new BookListModel("all",arr);
}
String sql = "select * from book";
Connection con = DBUtils.getConnFromPool();
String limitClause = "\n offset ? rows fetch first ? rows only";
try{
PreparedStatement ps = con.prepareStatement(sql+limitClause);
ps.setInt(1, pageNumber * rowsPerPage);
ps.setInt(2, rowsPerPage);
ResultSet rs = ps.executeQuery();
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
while(rs.next()){
int bid=rs.getInt(1);
String bname=rs.getString(2);
int quantity=rs.getInt(3);
java.math.BigDecimal bi=rs.getBigDecimal(4);
String category = rs.getString(5);
arr.add(new BookModel(bid,bname,quantity,bi.toPlainString(),category));
}
return new BookListModel("all",arr);
}catch(Exception e)
{
throw e;
}
finally{con.close();}
}
public static final BookListModel getFromCategory(String input_category) throws Exception{
//top selling 6 items
String sql = "select * from book";
if(input_category!=null && !input_category.replaceAll("\\s+", "").equals(""))
{
sql = String.format("select * from book where category='%s'",input_category);
}
Connection con = DBUtils.getConnFromPool();
try{
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
while(rs.next()){
int bid=rs.getInt(1);
String bname=rs.getString(2);
int quantity=rs.getInt(3);
java.math.BigDecimal bi=rs.getBigDecimal(4);
String category = rs.getString(5);
arr.add(new BookModel(bid,bname,quantity,bi.toPlainString(),category));
}
return new BookListModel("category",arr);
}catch(Exception e)
{
throw e;
}
finally{con.close();}
}
public static final BookListModel getFromCategory(String input_category, int rowsPerPage, int pageNumber) throws Exception{
if(rowsPerPage<1||pageNumber<1)
{
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
return new BookListModel("category",arr);
}
String sql = "select * from book";
String limitClause = "\n offset ? rows fetch first ? rows only";
if(input_category!=null && !input_category.replaceAll("\\s+", "").equals(""))
{
sql = String.format("select * from book where category='%s'",input_category);
}
Connection con = DBUtils.getConnFromPool();
try{
PreparedStatement ps = con.prepareStatement(sql+limitClause);
ps.setInt(1, pageNumber * rowsPerPage);
ps.setInt(2, rowsPerPage);
ResultSet rs = ps.executeQuery();
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
while(rs.next()){
int bid=rs.getInt(1);
String bname=rs.getString(2);
int quantity=rs.getInt(3);
java.math.BigDecimal bi=rs.getBigDecimal(4);
String category = rs.getString(5);
arr.add(new BookModel(bid,bname,quantity,bi.toPlainString(),category));
}
return new BookListModel("category",arr);
}catch(Exception e)
{
throw e;
}
finally{con.close();}
}
public static final BookListModel getComboSearchResult(String keywords, String category) throws Exception{
if(keywords==null)
{
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
return new BookListModel("complex-search",arr);
}
String categoryClause="";
if(category!=null && !category.replaceAll("\\s+", "").equals("") && !category.replaceAll("\\s+", "").toLowerCase().equals("all"))
{
categoryClause = String.format("category='%s'",category);
}
String splitted[]=keywords.split("\\s+");
String head = "select book.BID,book.BOOKNAME,book.QUANTITY,book.PRICE,book.CATEGORY, Temp.relativity\n" +
"from book, (\n" +
"select T.bid, count (T.bid) as relativity from\n" +
"(\n";
String tail = ") T\n" +
"group by (T.bid)\n" +
"order by (relativity) desc) as Temp\n" +
"where Temp.bid=book.bid\n" +
"order by (Temp.relativity) desc";
String sql="";
StringBuilder sb = new StringBuilder();
if(splitted.length>0)
{
for(int i=0;i<splitted.length;i++)
{
if(splitted[i]==null || splitted[i].length()==0)
continue;
String temp = "select bid from BOOK\n" +
"where "+categoryClause+" AND lower(bookname) like '%"+splitted[i].toLowerCase()+"%'";
if(i!=splitted.length-1)
{
temp+="\n Union All \n ";
}
sb.append(temp);
}
sql=head+sb.toString()+tail;
}
else//no keywords means all
{
sql="select * from book where "+categoryClause;
}
Connection con = DBUtils.getConnFromPool();
try{
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
while(rs.next()){
int bid=rs.getInt(1);
String bname=rs.getString(2);
int quantity=rs.getInt(3);
java.math.BigDecimal bi=rs.getBigDecimal(4);
String _category = rs.getString(5);
arr.add(new BookModel(bid,bname,quantity,bi.toPlainString(),_category));
}
return new BookListModel("complex-search",arr);
}catch(Exception e)
{
throw e;
}
finally{con.close();}
}
public static final BookListModel getComboSearchResult(String keywords, String category, int rowsPerPage, int pageNumber) throws Exception{
if(keywords==null||rowsPerPage<1||pageNumber<1)
{
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
return new BookListModel("complex-search",arr);
}
String categoryClause="";
if(category!=null && !category.replaceAll("\\s+", "").equals("") && !category.replaceAll("\\s+", "").toLowerCase().equals("all"))
{
categoryClause = String.format("category='%s'",category);
}
String splitted[]=keywords.split("\\s+");
String head = "select book.BID,book.BOOKNAME,book.QUANTITY,book.PRICE,book.CATEGORY, Temp.relativity\n" +
"from book, (\n" +
"select T.bid, count (T.bid) as relativity from\n" +
"(\n";
String tail = ") T\n" +
"group by (T.bid)\n" +
"order by (relativity) desc) as Temp\n" +
"where Temp.bid=book.bid\n" +
"order by (Temp.relativity) desc";
String sql="";
StringBuilder sb = new StringBuilder();
if(splitted.length>0)
{
for(int i=0;i<splitted.length;i++)
{
if(splitted[i]==null || splitted[i].length()==0)
continue;
String temp = "select bid from BOOK\n" +
"where "+categoryClause+" AND lower(bookname) like '%"+splitted[i].toLowerCase()+"%'";
if(i!=splitted.length-1)
{
temp+="\n Union All \n ";
}
sb.append(temp);
}
sql=head+sb.toString()+tail;
}
else//no keywords means all
{
sql="select * from book where "+categoryClause;
}
String limitClause = "\n offset ? rows fetch first ? rows only";
Connection con = DBUtils.getConnFromPool();
try{
PreparedStatement ps = con.prepareStatement(sql+limitClause);
ps.setInt(1, pageNumber * rowsPerPage);
ps.setInt(2, rowsPerPage);
ResultSet rs = ps.executeQuery();
ArrayList<BookModel> arr = new ArrayList<BookModel> ();
while(rs.next()){
int bid=rs.getInt(1);
String bname=rs.getString(2);
int quantity=rs.getInt(3);
java.math.BigDecimal bi=rs.getBigDecimal(4);
String _category = rs.getString(5);
arr.add(new BookModel(bid,bname,quantity,bi.toPlainString(),_category));
}
return new BookListModel("complex-search",arr);
}catch(Exception e)
{
throw e;
}
finally{con.close();}
}
}
<file_sep>/src/java/BeanModel/BookListModel.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package BeanModel;
import java.io.Serializable;
import java.util.ArrayList;
/**
*
* @author chiming
*/
public class BookListModel extends Object implements Serializable{
private String type;
private ArrayList<BookModel> list;
public BookListModel(){type=null;list=null;}
public BookListModel(String name, ArrayList<BookModel> li){type=name;list=li;}
public String getType(){return type;}
public ArrayList<BookModel> getList(){return list;}
public void setType(String str){type=str;}
public void setList(ArrayList<BookModel> li){list=li;}
}
<file_sep>/src/java/BeanModel/UserListModel.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package BeanModel;
import java.io.Serializable;
import java.util.ArrayList;
/**
*
* @author chiming
*/
public class UserListModel extends Object implements Serializable {
private ArrayList<UserBean> list;
public UserListModel(){}
public UserListModel(ArrayList<UserBean> userslist)
{
this.list=userslist;
}
public ArrayList<UserBean> getList(){return this.list;}
public void setList(ArrayList<UserBean> userslist){this.list=userslist;}
}
<file_sep>/src/java/Utils/MyContextListener.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Utils;
import java.sql.SQLException;
import java.util.logging.Level;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.logging.Logger;
/**
*
* @author chiming
*/
public class MyContextListener implements ServletContextListener {
private static final Logger log = Logger.getLogger(MyContextListener.class.getName());
@Override
public void contextInitialized(ServletContextEvent sce) {
log.info("OnInitialized() called");
EnvSingleton.getInstance();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
log.info("OnDestroyed() called");
}
}
<file_sep>/src/java/CustomerPart/CartController.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package CustomerPart;
import BeanModel.BookModel;
import BeanModel.ShoppingCart;
import BeanModel.ShoppingCartItem;
import DataAccess.ProductDA;
import Utils.ConvertUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author chiming
*/
@WebServlet(name = "CartController", urlPatterns = {"/CartController"})
public class CartController extends HttpServlet {
private HashMap<String,String> Commands= new HashMap<String, String>(){{
put("addtocart","AddToCart");
put("increment","Increment");
put("decrement","Decrement");
put("clear","ClearCart");
put("remove","Remove");
}};
private String successJson="{\"status\":\"success\"}";
private String failJson="{\"status\":\"fail\"}";
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
HttpSession session=request.getSession();
ShoppingCart sc=(ShoppingCart) session.getAttribute("cart");
if(sc==null)
{
sc=new ShoppingCart();
session.setAttribute("cart", sc);
}
boolean good=false;
String command = request.getParameter("command");
if(command!=null&&Commands.get(command.toLowerCase())!=null)
{
command=Commands.get(command.toLowerCase());
if(command.equals("AddToCart"))
{
if(request.getParameter("bid")!=null)
{
String bid=(String)request.getParameter("bid");
int id=Integer.parseInt(bid);
BookModel bm=ProductDA.getById(id);
if(bm!=null)
{
sc.addItem(bm);
out.println(this.successJson);
good=true;
}
}
}
else if(command.equals("Increment"))
{
if(request.getParameter("bid")!=null)
{
String bid=(String)request.getParameter("bid");
int id=Integer.parseInt(bid);
ShoppingCartItem ci=sc.findById(id);
if(ci!=null)
{
ci.incrementQuantity();
out.println(this.successJson);
good=true;
}
}
}
else if(command.equals("Decrement"))
{
if(request.getParameter("bid")!=null)
{
String bid=(String)request.getParameter("bid");
int id=Integer.parseInt(bid);
ShoppingCartItem ci=sc.findById(id);
if(ci!=null)
{
if(ci.getQuantity()>1)
{
ci.decrementQuantity();
out.println(this.successJson);
good=true;
}
}
}
}
else if(command.equals("Remove"))
{
if(request.getParameter("bid")!=null)
{
String bid=(String)request.getParameter("bid");
int id=Integer.parseInt(bid);
ShoppingCartItem ci=sc.findById(id);
if(ci!=null)
{
sc.remove(ci.getProduct());
out.println(this.successJson);
good=true;
}
}
}
else{
sc.clear();
out.println(this.successJson);
good=true;
}
}
if(!good)
{
response.setStatus(400);
out.println(failJson);
}
} catch (Exception ex) {
Logger.getLogger(CartController.class.getName()).log(Level.SEVERE, null, ex);
try (PrintWriter out = response.getWriter()) {
response.setStatus(400);
out.println(ConvertUtils.getExceptionJson(ex));
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/src/java/BeanModel/UserBean.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package BeanModel;
import java.io.Serializable;
/**
*
* @author chiming
*/
public class UserBean extends Object implements Serializable{
private int uid;
private String email;
private String nickname;
public UserBean(){uid=-1;email=null;nickname=null;}
public UserBean(int id, String eid, String name){uid=id;email=eid;nickname=name;}
public int getUid(){return uid;}
public String getEmail(){return email;}
public String getNickname(){return nickname;}
public void setUid(int id){uid=id;}
public void setEmail(String eid){email=eid;}
public void setNickname(String name){nickname=name;}
}
<file_sep>/src/java/BeanModel/BookModel.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package BeanModel;
import java.io.Serializable;
import java.math.BigDecimal;
/**
*
* @author chiming
*/
public class BookModel extends Object implements Serializable{
private int bid;
private String name;
private int quantity;
private String price;
private String category;
public BookModel(){bid=-1;name=null;quantity=-1;price=null;category=null;}
public BookModel(int id, String title, int stock, String theprice, String thecategory)
{bid=id;name=title;quantity=stock;price=theprice;category=thecategory;}
public int getBid(){return bid;}
public String getName(){return name;}
public int getQuantity(){return quantity;}
public String getPrice(){return price;}
public String getCategory(){return category;}
public void setBid(int id){bid=id;}
public void setName(String title){name=title;}
public void setQuantity(int stock){quantity=stock;}
public void setPrice(String val){price=val;}
public void setCategory(String type){category=type;}
}
<file_sep>/web/include/handlelogin.js
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
function dologin()
{
jQuery.ajax({
type: "Get",
url: "UserLogin?email=" + encodeURIComponent(document.getElementById("username").value)+"&password="+encodeURIComponent(document.getElementById("password").value),
dataType: "html",
success: function (response) {
var jsonobj=response;
console.log(jsonobj);
var obj=JSON.parse(jsonobj);
if(obj.status=="fail")
{
alert("Cannot Sign in. Please check your input.");
return;
}
var userid=obj.userid;
var nickname=obj.nickname;
var dialog=document.getElementById("myModal").children[0];
var greeting=document.getElementById("user-greeting");
greeting.innerHTML="Hi, "+nickname;
greeting.setAttribute("data-uid",""+userid);
var content="<div class=\"modal-content\">\n" +
"<div class=\"modal-header\" style=\"padding:35px 50px;\">\n" +
" <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button>\n" +
" <h4><span class=\"glyphicon glyphicon-lock\"></span> Hi, "+nickname+" </h4>\n" +
"</div>\n" +
"<div class=\"modal-body\" style=\"padding:20px 50px;\">\n" +
" <div>\n" +
" <p class=\"text-warning lead\">You are signed in.</p>\n" +
" <a class=\"btn btn-danger\" href=\"UserLogout\"><span class=\"glyphicon glyphicon-off\"></span> Sign Out</a>\n" +
" </div>\n" +
" </div>\n" +
"<div id =\"modal-footer\" class=\"modal-footer\">\n" +
" <button type=\"submit\" class=\"btn btn-default btn-default pull-right\" data-dismiss=\"modal\"><span class=\"glyphicon glyphicon-remove\"></span> Close</button>\n" +
"</div>\n" +
"</div> ";
dialog.innerHTML=content;
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("login fail");
console.log(xhr.status);
console.log(thrownError);
console.log(xhr.responseText);
var err=JSON.parse(xhr.responseText);
alert(err.message);
}
});
}
function onAdd(btn){
var id=btn.getAttribute("data-bid");
jQuery.ajax({
type: "POST",
url: "CartController",
dataType: "html",
data: "command=addtocart&bid=" + id,
success: function (response) {
console.log(response);
var real=JSON.parse(response);
if(real.status=="success")
{
//alert("Add to your cart");
btn.innerHTML='<span class="glyphicon glyphicon-ok"></span> Added to cart';
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
console.log(xhr.responseText);
}
});
}<file_sep>/src/java/CustomerPart/UserLogin.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package CustomerPart;
import BeanModel.UserBean;
import BeanModel.UserLoginModel;
import DataAccess.CustomerDA;
import Utils.ConvertUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author chiming
*/
public class UserLogin extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain;charset=UTF-8");
//RequestDispatcher rderr = getServletContext().getRequestDispatcher("/error.jsp");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
try {
HttpSession session = request.getSession(false);
if(session==null)
{
throw new NullPointerException("No session tracked. You can only access here via the official website.");
}
String id = request.getParameter("email");
String pwd = request.getParameter("password");
UserLoginModel model=ConvertUtils.validateUser(id, pwd);
UserBean bn = CustomerDA.Login(model);
if(bn!=null)
{
session.setAttribute("userbean", bn);
}
else{
throw new NullPointerException("Invalid Input. Please check and try later.");
}
out.println("{\"status\":\"success\",\"message\":\"You are successfully signed in.\",\"nickname\":\""+bn.getNickname()+"\",\"userid\":"+bn.getUid()+"}");
//Logger.getLogger(UserRegister.class.getName()).log(Level.INFO, "{\"status\":\"success\",\"message\":\"You are successfully signed in.\",\"nickname\":\""+bn.getNickname()+"\",\"userid\":"+bn.getUid()+"}");
//RequestDispatcher rd = getServletContext().getRequestDispatcher("/UserHome");
//rd.forward(request, response);
} catch (Exception ex) {
Logger.getLogger(UserRegister.class.getName()).log(Level.SEVERE, null, ex);
//String errorMessage=ex.getClass().getSimpleName()+ ex.getCause()==null?ex.getMessage():ex.getCause().getMessage();
response.setStatus(400);
//request.setAttribute("errmsg", errorMessage);
//rderr.forward(request, response);
out.println("{\"status\":\"fail\",\"message\":\"Sign in failed. Please make sure the input is correct. Otherwise please call service at (412)XXX-XXXX.\"}");
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/src/java/DataAccess/EmployeeDA.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DataAccess;
import BeanModel.*;
import Utils.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
*
* @author chiming
*/
public class EmployeeDA{
private EmployeeDA(){}
//==================
public static final EmplBean Login(EmplLoginModel model) throws Exception{
if(model==null)
{return null;}
String sql = "Select nickname,email from Employee where eid=? and pwd=?";
Connection con = DBUtils.getConnFromPool();
try{
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, model.getId());
ps.setString(2, model.getPassword());
ResultSet rs = ps.executeQuery();
if(rs.next()){
String nickname = rs.getString(1);
return new EmplBean(model.getId(),nickname);
}else{
return null;
}
}catch(Exception e)
{
throw e;
}
finally{con.close();}
}
}
<file_sep>/src/java/CustomerPart/CheckRegistered.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package CustomerPart;
import DataAccess.CustomerDA;
import Utils.ConvertUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
/**
*
* @author chiming
*/
public class CheckRegistered extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
StringBuilder sb=new StringBuilder();
BufferedReader br=request.getReader();
String str;
while( (str = br.readLine()) != null ){
sb.append(str);
}
JSONObject obj = new JSONObject(sb.toString());
try{
int count=CustomerDA.CheckExist(ConvertUtils.validateUser(obj.getString("useremail"), "ee"));
JSONObject ret=new JSONObject();
ret.put("count", count);
out.println(ret.toString());
} catch (SQLException sqle) {
String responseText=ConvertUtils.getExceptionJson(sqle);
Logger.getLogger(CheckRegistered.class.getName()).log(Level.SEVERE, null, sqle);
response.setStatus(400);
out.println(responseText);
} catch (Exception ex) {
String responseText=ConvertUtils.getExceptionJson(ex);
response.setStatus(400);
out.println(responseText);
Logger.getLogger(CheckRegistered.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/src/java/BeanModel/FaqModel.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package BeanModel;
import java.io.Serializable;
/**
*
* @author chiming
*/
public class FaqModel extends Object implements Serializable{
private String title;
private String content;
public FaqModel(){title=null;content=null;}
public FaqModel(String _title,String _content){title=_title;content=_content;}
public String getTitle(){return title;}
public void setTitle(String _title){title=_title;}
public String getContent(){return content;}
public void setContent(String _content){content=_content;}
}
<file_sep>/web/include/handlecart.js
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
function decrement(btn){
var div=btn.parentElement;
var td=div.parentElement;
var tr=td.parentElement;
if(tr==null)
return;
var id=tr.getAttribute("data-bid");
jQuery.ajax({
type: "POST",
url: "CartController",
dataType: "html",
data: "command=decrement&bid=" + id,
success: function (response) {
console.log(response);
var real=JSON.parse(response);
if(real.status=="success")
{
var quantity=tr.children[2].textContent;
var price=tr.children[3].textContent;
var total=tr.children[4];
var qty=parseInt(quantity)-1;
var ppu=parseFloat(price);
tr.children[2].textContent=qty.toString();
var tot=qty*ppu;
total.textContent=tot.toFixed(2);
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
console.log(xhr.responseText);
}
});
}
function increment(btn){
var div=btn.parentElement;
var td=div.parentElement;
var tr=td.parentElement;
if(tr==null)
return;
var id=tr.getAttribute("data-bid");
jQuery.ajax({
type: "POST",
url: "CartController",
dataType: "html",
data: "command=increment&bid=" + id,
success: function (response) {
console.log(response);
var real=JSON.parse(response);
if(real.status=="success")
{
var quantity=tr.children[2].textContent;
var price=tr.children[3].textContent;
var total=tr.children[4];
var qty=parseInt(quantity)+1;
var ppu=parseFloat(price);
tr.children[2].textContent=qty.toString();
var tot=qty*ppu;
total.textContent=tot.toFixed(2);
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
console.log(xhr.responseText);
}
});
}
function removeItem(btn){
var td=btn.parentElement;;
var tr=td.parentElement;
if(tr==null)
return;
var id=tr.getAttribute("data-bid");
jQuery.ajax({
type: "POST",
url: "CartController",
dataType: "html",
data: "command=remove&bid=" + id,
success: function (response) {
console.log(response);
var real=JSON.parse(response);
if(real.status=="success")
{
var tbody=tr.parentElement;
tbody.removeChild(tr);
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
console.log(xhr.responseText);
}
});
}
function onCheckout()
{
var span=document.getElementById("user-greeting");
if(span.getAttribute("data-uid")!="-1")
{
window.location.href = "confirmation.jsp";
}
else if(null!=document.getElementById("txt-empty-cart"))
{
alert("No items in cart");
}
else
{
alert("please login first then check out");
}
}
function onClear(){
jQuery.ajax({
type: "POST",
url: "CartController",
dataType: "html",
data: "command=clear",
success: function (response) {
console.log(response);
var real=JSON.parse(response);
if(real.status=="success")
{
location.reload(true);
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
console.log(xhr.responseText);
}
});
}
<file_sep>/src/java/BeanModel/MessageModel.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package BeanModel;
import java.io.Serializable;
/**
*
* @author chiming
*/
public class MessageModel extends Object implements Serializable{
private int uid;
private int eid;
private int direction;
private String message;
private long time;
public MessageModel(){eid=uid=-1;direction=-1;message=null;time=0;}
public MessageModel(int uid, int eid, int direction, String message, long time)
{
this.uid=uid;
this.eid=eid;
this.direction=direction;
this.message=message;
this.time=time;
}
public int getUid(){return uid;}
public void setUid(int fromid){uid=fromid;}
public int getEid(){return eid;}
public void setEid(int toid){eid=toid;}
public int getDirection(){return direction;}
public void setDirection(int dir){direction=dir;}
public String getMessage(){return message;}
public void setMessage(String msg){message=msg;}
public long getTime(){return time;}
public void setTime(long timestamp){time=timestamp;}
}
| 7aca9dcda3e3713983d75ed4a90f467991db1387 | [
"JavaScript",
"Java"
]
| 14 | Java | ndsorrowchi/EbuzFinal | be35a3d00f2a95e957bd7ba5429e698ec288deac | 950e713f68ecb715b57dd4a84bdc2fa79e4ece3c |
refs/heads/master | <repo_name>jjbaird87/BioAccessCloud<file_sep>/BioAccessTest_Production/Login.cs
using System;
using System.Collections.Generic;
using System.Linq;
using BioAccessTest_Production.BioAccessCloudBasic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BioAccessTest_Production
{
[TestClass]
public class Login
{
[TestMethod]
public void SuccessfulLogin()
{
var client = new BioAccessCloudBasicClient();
var login = client.Login("jjbaird87", "biomaster");
Assert.AreEqual(true, login.LoginSuccessful);
Assert.AreNotSame("", login.SessionId);
}
[TestMethod]
public void FailedLogin_IncorrectUsername()
{
var client = new BioAccessCloudBasicClient();
var login = client.Login("manish", "biomaster");
Assert.AreEqual("Username not found", login.ErrorMessage);
}
[TestMethod]
public void FailedLogin_PasswordIncorrect()
{
var client = new BioAccessCloudBasicClient();
var login = client.Login("jjbaird87", "wow");
Assert.AreEqual("Password incorrect", login.ErrorMessage);
}
[TestMethod]
public void GetSites()
{
var client = new BioAccessCloudBasicClient();
var sites = client.GetSitesPerCustomer(2);
foreach (var site in sites)
{
Console.WriteLine(site.SiteName);
Console.ReadLine();
}
Assert.AreNotEqual(0,sites.Count());
}
[TestMethod]
public void GetEmployeesPerSite()
{
var client = new BioAccessCloudBasicClient();
var employees = client.GetEmployeesPerSite(5, true, "MorphoPkMat");
var count = employees.Count();
Assert.AreNotSame(0, employees.Count());
}
[TestMethod]
public void CreateDummyTransaction()
{
var client = new BioAccessCloudBasicClient();
var transactions = new List<DataStructuresAttendanceTransactionInBac>();
transactions.Add(new DataStructuresAttendanceTransactionInBac
{
TransactionDateTime = "2014/01/01 02:00:00",
Downloaded = false,
Emei = "00000",
EmployeeId = 2013,
InOut = 1,
Latitude = 0.765675,
Longitude = 0.786876
});
client.InsertNewTransactions(transactions);
Assert.AreEqual(0,0);
}
}
}
<file_sep>/BioAccess_TEst/Employee.cs
using System;
using BioAccess_TEst.BioAccessCloudBasic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BioAccess_TEst
{
[TestClass]
public class Employee
{
[TestMethod]
public void GetEmployee()
{
var client = new BioAccessCloudBasicClient();
var employees = client.GetEmployeesPerSite(1, null, null);
client.Close();
Assert.AreNotEqual(0, employees.Count);
}
[TestMethod]
public void GetEmployeePerSite()
{
var client = new BioAccessCloudBasicClient();
var employees = client.GetEmployeesPerSite(5, null, null);
client.Close();
Assert.AreNotEqual(0, employees.Count);
}
[TestMethod]
public void GetEmployeePerSiteOnlyDefaultFingers()
{
var client = new BioAccessCloudBasicClient();
var employees = client.GetEmployeesPerSite(5, true, "MorphoPkMat");
client.Close();
Assert.AreNotEqual(2, employees[0].Templates.Count);
}
}
}
<file_sep>/WCFServiceWebRole1/BioAccessCloudBasic.svc.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.ServiceModel;
using Microsoft.WindowsAzure.Storage.Table;
using WCFServiceWebRole1.Data;
namespace WCFServiceWebRole1
{
public class BioAccessCloudBasic : IBioAccessCloudBasic
{
#region Login
//Login
public DataStructures.LoginResponse Login(string userName, string password)
{
try
{
var response = new DataStructures.LoginResponse { RequestCompleted = DateTime.Now };
var ctx = new BioAccessCloudEntities();
var loginEntity = (from p in ctx.Customers select p).Where(i => i.UserName == userName).ToList();
if (loginEntity.Count() != 0)
{
if (password == loginEntity[0].Password)
{
response.CustomerId = loginEntity[0].Customer_ID;
response.ErrorMessage = "";
response.LoginSuccessful = true;
response.SessionId = OperationContext.Current.SessionId;
}
else
{
response.ErrorMessage = "Password incorrect";
response.LoginSuccessful = false;
}
}
else
{
response.ErrorMessage = "Username not found";
response.LoginSuccessful = false;
}
return response;
}
catch (Exception ex)
{
var response = new DataStructures.LoginResponse
{
RequestCompleted = DateTime.Now,
ErrorMessage = ex.Message,
LoginSuccessful = false
};
return response;
}
}
#endregion
#region Sites
//Sites
public List<DataStructures.SiteBac> GetSitesPerCustomer(int customerId)
{
var ctx = new BioAccessCloudEntities();
var sites = (from p in ctx.Sites select p).Where(i => i.Customer_ID == customerId).ToList();
return sites.Select(site => new DataStructures.SiteBac
{
SiteId = site.Site_ID,
SiteName = site.SiteName,
Latitude = site.Latitude,
Longitude = site.Longitude
}).ToList();
}
public string CreateUpdateSites(ref IEnumerable<DataStructures.SiteBac> sites, int customerId)
{
var ctx = new BioAccessCloudEntities();
var siteBacs = sites as IList<DataStructures.SiteBac> ?? sites.ToList();
foreach (var site in siteBacs)
{
//Determine add or edit
if (ctx.Sites.Any(x => x.BioAccess_ID == site.BioAccessId))
{
//Already exists and needs to be updated
var localSite = ctx.Sites.First(x => x.BioAccess_ID == site.BioAccessId);
localSite.SiteName = site.SiteName;
localSite.Latitude = site.Latitude;
localSite.Longitude = site.Longitude;
localSite.Customer_ID = site.CustomerId;
localSite.BioAccess_ID = site.BioAccessId;
ctx.SaveChanges();
site.SiteId = localSite.Site_ID;
}
else
{
//Does not exist and new site needs to be created
var localSite = new Site
{
SiteName = site.SiteName,
Customer_ID = site.CustomerId,
Latitude = site.Latitude,
Longitude = site.Longitude,
BioAccess_ID = site.BioAccessId
};
ctx.Sites.Add(localSite);
ctx.SaveChanges();
site.SiteId = localSite.Site_ID;
}
}
FindAndDeleteUnusedSites(siteBacs, ctx, customerId);
return "";
}
private static void FindAndDeleteUnusedSites(IEnumerable<DataStructures.SiteBac> sites, BioAccessCloudEntities ctx, int customerId)
{
var siteBacs = sites as IList<DataStructures.SiteBac> ?? sites.ToList();
var siteList = siteBacs.Select(site => site.SiteId).ToList();
var toDelete =
(from e in ctx.Sites
where !siteList.Contains(e.Site_ID) && e.Customer_ID == customerId
select e);
var deleteList = toDelete.ToList().Select(site => site.Site_ID).ToList();
//REMOVE GROUPS
DeleteGroupsForSites(deleteList);
//REMOVE SITE
ctx.Sites.RemoveRange(toDelete);
ctx.SaveChanges();
}
private static void DeleteGroupsForSites(List< int> siteIds)
{
var ctx = new BioAccessCloudEntities();
var toDelete = (from e in ctx.Groups where siteIds.Contains(e.Site_ID) select e);
//REMOVE GROUP ASSIGNMENTS
var groupList = toDelete.ToList().Select(group => group.Group_ID).ToList();
RemoveGroupAssignmentsGroups(groupList);
ctx.Groups.RemoveRange(toDelete);
ctx.SaveChanges();
}
private static void RemoveGroupAssignmentsGroups(List<int> groupIds)
{
var ctx = new BioAccessCloudEntities();
var toDelete = (from e in ctx.EmployeeGroups where groupIds.Contains(e.Group_ID) select e);
ctx.EmployeeGroups.RemoveRange(toDelete);
ctx.SaveChanges();
}
#endregion
#region Employees
//Employees
public List<DataStructures.EmployeeBac> GetEmployeesPerSite(int siteId, bool? terminalTemplates, string templateType)
{
try
{
var ctx = new BioAccessCloudEntities();
var employees =
(from p in ctx.Employees select p).Where(x => x.EmployeeGroups.Any(i => i.Group.Site_ID == siteId));
if (templateType != null)
employees = employees.Where(x => x.Templates.Any(c => c.TemplateType.Description == templateType));
var lstEmployees = employees.ToList();
var employeelist = EmployeeBacs(lstEmployees, terminalTemplates, templateType);
return employeelist;
}
catch (Exception ex)
{
throw;
}
}
private static List<DataStructures.EmployeeBac> EmployeeBacs(IEnumerable<Employee> employees, bool? terminalTemplates, string templateType)
{
var employeelist = employees.Select(employee => new DataStructures.EmployeeBac
{
Active = employee.Active,
CustomerId = employee.Customer_ID,
EmployeeId = employee.Employee_ID,
EmployeeNo = employee.Employee_Number,
Name = employee.Name,
Surname = employee.Surname,
BioAccessId = employee.BioAccess_ID,
RsaId = employee.RSA_ID,
Templates = TemplateBacs(employee.Templates, terminalTemplates, templateType)
}).ToList();
return employeelist;
}
public List<DataStructures.EmployeeBac> GetEmployeesPerCustomer(int customerId, int? employeeId)
{
var ctx = new BioAccessCloudEntities();
var employees =
(from p in ctx.Employees select p).Where(x => x.Customer_ID == customerId);
if (employeeId != null)
employees = employees.Where(x => x.Employee_ID == employeeId);
return EmployeeBacs(employees, null, null);
}
public List<DataStructures.EmployeeBac> GetEmployeesPerGroup(int groupId)
{
var ctx = new BioAccessCloudEntities();
var employees =
(from p in ctx.Employees select p).Where(x => x.EmployeeGroups.Any(c => c.Group_ID == groupId)).ToList();
return EmployeeBacs(employees, null, null);
}
public string CreateUpdateEmployees(ref IEnumerable<DataStructures.EmployeeBac> employees, int customerId)
{
var ctx = new BioAccessCloudEntities();
var enumerable = employees as IList<DataStructures.EmployeeBac> ?? employees.ToList();
foreach (var employee in enumerable)
{
//Determine add or edit
if (ctx.Employees.Any(x => x.BioAccess_ID == employee.BioAccessId))
{
//Already exists and needs to be updated
var localEmployee = ctx.Employees.First(x => x.BioAccess_ID == employee.BioAccessId);
localEmployee.Name = employee.Name;
localEmployee.Surname = employee.Surname;
localEmployee.Employee_Number = employee.EmployeeNo;
localEmployee.Active = employee.Active;
localEmployee.Customer_ID = employee.CustomerId;
localEmployee.RSA_ID = employee.RsaId;
localEmployee.BioAccess_ID = employee.BioAccessId;
ctx.SaveChanges();
employee.EmployeeId = localEmployee.Employee_ID;
}
else
{
//Does not exist and new site needs to be created
var localEmployee = new Employee
{
Employee_Number = employee.EmployeeNo,
Name = employee.Name,
Surname = employee.Surname,
Active = employee.Active,
Customer_ID = employee.CustomerId,
RSA_ID = employee.RsaId,
BioAccess_ID = employee.BioAccessId
};
ctx.Employees.Add(localEmployee);
ctx.SaveChanges();
employee.EmployeeId = localEmployee.Employee_ID;
}
}
FindAndDeleteUnusedEmployees(enumerable, ctx, customerId);
return "";
}
private static void FindAndDeleteUnusedEmployees(IEnumerable<DataStructures.EmployeeBac> employees, BioAccessCloudEntities ctx, int customerId)
{
var employeeBacs = employees as IList<DataStructures.EmployeeBac> ?? employees.ToList();
var employeeList = employeeBacs.Select(employee => employee.EmployeeId).ToList();
var toDelete =
(from e in ctx.Employees
where !employeeList.Contains(e.Employee_ID) && e.Customer_ID == customerId
select e);
var deleteList = toDelete.ToList().Select(employee => employee.Employee_ID).ToList();
//REMOVE GROUP ASSIGNMENTS
RemoveGroupAssignmentsForEmployees(deleteList);
//REMOVE TEMPLATES
RemoveTemplatesForEmployees(deleteList);
//REMOVE EMPLOYEE
ctx.Employees.RemoveRange(toDelete);
ctx.SaveChanges();
}
private static void RemoveGroupAssignmentsForEmployees(List<int> employeeIds)
{
var ctx = new BioAccessCloudEntities();
var toDelete = (from e in ctx.EmployeeGroups where employeeIds.Contains(e.Employee_ID) select e);
ctx.EmployeeGroups.RemoveRange(toDelete);
ctx.SaveChanges();
}
private static void RemoveTemplatesForEmployees(List<int> employeeIds)
{
var ctx = new BioAccessCloudEntities();
var toDelete = (from e in ctx.Templates where employeeIds.Contains(e.Employee_ID) select e);
ctx.Templates.RemoveRange(toDelete);
ctx.SaveChanges();
}
#endregion
#region Templates
private static List<DataStructures.TemplateBac> TemplateBacs(IEnumerable<Template> templates,
bool? terminalTemplates, string templateType)
{
var templateList = new List<DataStructures.TemplateBac>();
foreach (var template in templates)
{
if (terminalTemplates != null)
{
if (template.TerminalFP != terminalTemplates)
continue;
}
if (templateType != null)
{
if (templateType != template.TemplateType.Description)
continue;
}
var correctSize = new byte[template.TemplateSize];
Array.Copy(template.Template1, correctSize, template.TemplateSize);
var item = new DataStructures.TemplateBac
{
BioAccessId = template.BioAccess_ID,
EmployeeId = template.Employee_ID,
FingerNumber = template.FingerNumber,
Base64Template = Convert.ToBase64String(correctSize),
Template = correctSize,
TemplateSize = template.TemplateSize,
TemplateId = template.Template_ID,
TemplateType = template.TemplateType.Description,
TerminalFp = template.TerminalFP
};
templateList.Add(item);
}
return templateList;
}
public string CreateUpdateTemplates(IEnumerable<DataStructures.TemplateBac> templates, int customerId)
{
var ctx = new BioAccessCloudEntities();
var templateBacs = templates as IList<DataStructures.TemplateBac> ?? templates.ToList();
foreach (var template in templateBacs)
{
//Get template Type
var template1 = template;
var templateType =
ctx.TemplateTypes.First(x => x.Description == template1.TemplateType)
.TemplateType_ID;
if (ctx.Templates.Any(x => x.BioAccess_ID == template.BioAccessId))
{
//Already exists - UPDATE
var localTemplate = ctx.Templates.First(x => x.BioAccess_ID == template.BioAccessId);
localTemplate.Employee_ID = template.EmployeeId;
localTemplate.FingerNumber = template.FingerNumber;
localTemplate.Template1 = template.Template;
localTemplate.TemplateSize = template.TemplateSize;
localTemplate.TemplateType_ID = templateType;
localTemplate.TerminalFP = template.TerminalFp;
ctx.SaveChanges();
template.TemplateId = localTemplate.Template_ID;
}
else
{
//Create structure
var localTemplate = new Template
{
FingerNumber = template.FingerNumber,
Template1 = template.Template,
TemplateSize = template.TemplateSize,
TemplateType_ID = templateType,
Employee_ID = template.EmployeeId,
BioAccess_ID = template.BioAccessId,
TerminalFP = template.TerminalFp
};
ctx.Templates.Add(localTemplate);
ctx.SaveChanges();
template.TemplateId = localTemplate.Template_ID;
}
}
FindAndDeleteUnusedTemplates(templateBacs, ctx, customerId);
//Commit after all transactions have been completed
return "";
}
private static void FindAndDeleteUnusedTemplates(IEnumerable<DataStructures.TemplateBac> templates, BioAccessCloudEntities ctx, int customerId)
{
//Find unSynced templates for a customer and delete them!
var templateList = templates.Select(template => template.TemplateId).ToList();
var toDelete =
(from e in ctx.Templates
where !templateList.Contains(e.Template_ID) && e.Employee.Customer_ID == customerId
select e);
ctx.Templates.RemoveRange(toDelete);
ctx.SaveChanges();
}
public List<DataStructures.TemplateTypeBac> GetTemplateTypes()
{
var ctx = new BioAccessCloudEntities();
var templateTypes = (from p in ctx.TemplateTypes select p).ToList();
var output = templateTypes.Select(templateType => new DataStructures.TemplateTypeBac
{
TemplateTypeId = templateType.TemplateType_ID,
Description = templateType.Description
}).ToList();
return output;
}
#endregion
#region Groups
//Groups
public string CreateUpdateGroups(ref IEnumerable<DataStructures.GroupBac> groups, int customerId)
{
var ctx = new BioAccessCloudEntities();
var groupBacs = groups as IList<DataStructures.GroupBac> ?? groups.ToList();
foreach (var group in groupBacs)
{
//Determine add or edit
if (ctx.Groups.Any(x => x.BioAccess_ID == group.BioAccessId))
{
//Already exists and needs to be updated
var localGroup = ctx.Groups.First(x => x.BioAccess_ID == group.BioAccessId);
localGroup.Name = group.GroupName;
localGroup.Site_ID = group.SiteId;
localGroup.Customer_ID = group.CustomerId;
localGroup.BioAccess_ID = group.BioAccessId;
ctx.SaveChanges();
group.GroupId = localGroup.Group_ID;
}
else
{
//Does not exist and new site needs to be created
var localGroup = new Group
{
Name = group.GroupName,
Site_ID = group.SiteId,
Customer_ID = group.CustomerId,
BioAccess_ID = group.BioAccessId
};
ctx.Groups.Add(localGroup);
ctx.SaveChanges();
group.GroupId = localGroup.Group_ID;
}
}
FindAndDeleteUnusedGroups(groupBacs, ctx, customerId);
return "";
}
private static void FindAndDeleteUnusedGroups(IEnumerable<DataStructures.GroupBac> groups, BioAccessCloudEntities ctx, int customerId)
{
var groupBacs = groups as IList<DataStructures.GroupBac> ?? groups.ToList();
var groupList = groupBacs.Select(group => group.GroupId).ToList();
var toDelete =
(from e in ctx.Groups
where !groupList.Contains(e.Group_ID) && e.Customer_ID == customerId
select e);
var deleteList = toDelete.ToList().Select(group => group.Group_ID).ToList();
//REMOVE GROUP ASSIGNMENTS
RemoveGroupAssignmentsGroups(deleteList);
//REMOVE GROUPS
ctx.Groups.RemoveRange(toDelete);
ctx.SaveChanges();
}
public string CreateUpdateGroupRelations(IEnumerable<DataStructures.EmployeeGroupBac> employeeGroups, int customerId)
{
var ctx = new BioAccessCloudEntities();
//DELETE Groups for Customer ID
var deleteItems =
ctx.EmployeeGroups.Where(x => x.Group.BioAccess_ID != null && x.Group.Customer_ID == customerId);
foreach (var employeeGroup in deleteItems)
{
ctx.EmployeeGroups.Remove(employeeGroup);
}
ctx.SaveChanges();
foreach (var employeeGroup in employeeGroups)
{
var localGroup = new EmployeeGroup
{
Employee_ID = employeeGroup.EmployeeId,
Group_ID = employeeGroup.GroupId
};
ctx.EmployeeGroups.Add(localGroup);
}
//Commit after all transactions have been completed
ctx.SaveChanges();
return "";
}
#endregion
#region Transactions
public List<DataStructures.AttendanceTransactionBac> GetTransactions(int customerId, DateTime? startDate, DateTime? endDate, bool? downloaded)
{
var ctx = new BioAccessCloudEntities();
var transactions =
(from p in ctx.AttendanceTransactions select p).Where(x => x.Employee.Customer_ID == customerId);
if (startDate != null)
transactions = transactions.Where(x => x.TransactionDate >= startDate);
if (endDate != null)
transactions = transactions.Where(x => x.TransactionDate <= endDate);
if (downloaded != null)
transactions = transactions.Where(x => x.Downloaded == downloaded);
var lstTransactions = transactions.ToList();
var transactionList = lstTransactions.Select(transaction => new DataStructures.AttendanceTransactionBac
{
AttendanceTransactionId = transaction.AttendanceTransaction_ID,
Downloaded = transaction.Downloaded,
Emei = transaction.EMEI,
Employee = EmployeeBacs(new List<Employee>() {transaction.Employee}, null, null)[0],
EmployeeId = transaction.Employee_ID,
InOut = transaction.InOut,
Latitude = transaction.Latitude,
Longitude = transaction.Longitude,
TransactionDateTime = transaction.TransactionDate
}).ToList();
return transactionList;
}
public string UpdateDownloadedTxPerCustomer(int customerId)
{
var ctx = new BioAccessCloudEntities();
var transactions = ctx.AttendanceTransactions.Where(x => x.Employee.Customer_ID == customerId).ToList();
transactions.ForEach(a => a.Downloaded = true);
ctx.SaveChanges();
return "";
}
public string InsertNewTransactions(IEnumerable<DataStructures.AttendanceTransactionInBac> transactions)
{
var ctx = new BioAccessCloudEntities();
var lstTransactions = transactions.Select(transaction => new AttendanceTransaction
{
Downloaded = false,
EMEI = transaction.Emei,
Employee_ID = transaction.EmployeeId,
InOut = transaction.InOut,
Latitude = transaction.Latitude,
Longitude = transaction.Longitude,
TransactionDate =
DateTime.ParseExact(transaction.TransactionDateTime, "yyyy/MM/dd HH:mm:ss",
CultureInfo.InvariantCulture)
}).ToList();
ctx.AttendanceTransactions.AddRange(lstTransactions);
ctx.SaveChanges();
return "";
}
public string InsertNewTransaction(int employeeId, string transactionDate, short inOut, double latitude,
double longitude, String emei)
{
var ctx = new BioAccessCloudEntities();
var localTransaction = new AttendanceTransaction
{
Downloaded = false,
EMEI = emei,
Employee_ID = employeeId,
InOut = inOut,
Latitude = latitude,
Longitude = longitude,
TransactionDate =
DateTime.ParseExact(transactionDate, "yyyy/MM/dd HH:mm:ss",
CultureInfo.InvariantCulture)
};
ctx.AttendanceTransactions.Add(localTransaction);
ctx.SaveChanges();
return "";
}
#endregion
}
}
<file_sep>/WCFServiceWebRole1/DataStructures.cs
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace WCFServiceWebRole1
{
public static class DataStructures
{
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class LoginResponse
{
[DataMember]
public bool LoginSuccessful { get; set; }
[DataMember]
public int CustomerId { get; set; }
[DataMember]
public string ErrorMessage { get; set; }
[DataMember]
public DateTime RequestCompleted { get; set; }
[DataMember]
public string SessionId { get; set; }
}
[DataContract]
public class SiteBac
{
[DataMember]
public int SiteId { get; set; }
[DataMember]
public string SiteName { get; set; }
[DataMember]
public string Latitude { get; set; }
[DataMember]
public string Longitude { get; set; }
[DataMember]
public int CustomerId { get; set; }
[DataMember]
public Guid? BioAccessId { get; set; }
}
[DataContract]
public class GroupBac
{
[DataMember]
public int GroupId { get; set; }
[DataMember]
public string GroupName { get; set; }
[DataMember]
public int SiteId { get; set; }
[DataMember]
public int CustomerId { get; set; }
[DataMember]
public Guid? BioAccessId { get; set; }
}
[DataContract]
public class TemplateBac
{
[DataMember]
public int TemplateId { get; set; }
[DataMember]
public short? FingerNumber { get; set; }
[DataMember]
public byte[] Template { get; set; }
[DataMember]
public string Base64Template { get; set; }
[DataMember]
public int TemplateSize { get; set; }
[DataMember]
public string TemplateType { get; set; }
[DataMember]
public int EmployeeId { get; set; }
[DataMember]
public Guid? BioAccessId { get; set; }
[DataMember]
public bool? TerminalFp { get; set; }
}
[DataContract]
public class EmployeeGroupBac
{
[DataMember]
public int EmployeeGroupId { get; set; }
[DataMember]
public int GroupId { get; set; }
[DataMember]
public int EmployeeId { get; set; }
}
[DataContract]
public class EmployeeBac
{
[DataMember]
public int EmployeeId { get; set; }
[DataMember]
public string EmployeeNo { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Surname { get; set; }
[DataMember]
public bool Active { get; set; }
[DataMember]
public int CustomerId { get; set; }
[DataMember]
public string RsaId { get; set; }
[DataMember]
public Guid? BioAccessId { get; set; }
[DataMember]
public List<TemplateBac> Templates { get; set; }
}
[DataContract]
public class TemplateTypeBac
{
[DataMember]
public int TemplateTypeId { get; set; }
[DataMember]
public string Description { get; set; }
}
[DataContract]
public class AttendanceTransactionBac
{
[DataMember]
public int AttendanceTransactionId { get; set; }
[DataMember]
public DateTime TransactionDateTime { get; set; }
[DataMember]
public double Latitude { get; set; }
[DataMember]
public double Longitude { get; set; }
[DataMember]
public EmployeeBac Employee { get; set; }
[DataMember]
public int EmployeeId { get; set; }
[DataMember]
public string Emei { get; set; }
[DataMember]
public short InOut { get; set; }
[DataMember]
public bool Downloaded { get; set; }
}
[DataContract]
public class AttendanceTransactionInBac
{
[DataMember]
public string TransactionDateTime { get; set; }
[DataMember]
public double Latitude { get; set; }
[DataMember]
public double Longitude { get; set; }
[DataMember]
public int EmployeeId { get; set; }
[DataMember]
public string EmployeeNo { get; set; }
[DataMember]
public string Emei { get; set; }
[DataMember]
public short InOut { get; set; }
[DataMember]
public bool Downloaded { get; set; }
}
}
}<file_sep>/BioAccess_TEst/Sites.cs
using System.Collections.Generic;
using BioAccess_TEst.BioAccessCloudBasic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BioAccess_TEst
{
[TestClass]
public class Sites
{
[TestMethod]
public void GetSites()
{
var client = new BioAccessCloudBasicClient();
var sites = client.GetSitesPerCustomer(1);
client.Close();
Assert.AreNotEqual(0, sites.Count);
}
[TestMethod]
public void CreateDummyTransaction()
{
var client = new BioAccessCloudBasicClient();
var transactions = new List<DataStructuresAttendanceTransactionInBac>();
transactions.Add(new DataStructuresAttendanceTransactionInBac
{
TransactionDateTime = "2014/01/01 02:00:00",
Downloaded = false,
Emei = "00000",
EmployeeId = 2013,
InOut = 1,
Latitude = 0.765675,
Longitude = 0.786876
});
client.InsertNewTransactions(transactions);
Assert.AreEqual(0, 0);
}
}
}
<file_sep>/WCFServiceWebRole1/IBioAccessCloudBasic.cs
using System;
using System.Collections.Generic;
using System.ServiceModel;
namespace WCFServiceWebRole1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IBioAccessCloudBasic
{
[OperationContract]
DataStructures.LoginResponse Login(string userName, string password);
[OperationContract]
List<DataStructures.TemplateTypeBac> GetTemplateTypes();
[OperationContract]
List<DataStructures.SiteBac> GetSitesPerCustomer(int customerId);
[OperationContract]
List<DataStructures.EmployeeBac> GetEmployeesPerSite(int siteId, bool? terminalTemplates, string templateType);
[OperationContract]
List<DataStructures.EmployeeBac> GetEmployeesPerCustomer(int customerId, int? employeeId);
[OperationContract]
string CreateUpdateSites(ref IEnumerable<DataStructures.SiteBac> sites, int customerId);
[OperationContract]
string CreateUpdateGroups(ref IEnumerable<DataStructures.GroupBac> groups, int customerId);
[OperationContract]
string CreateUpdateGroupRelations(IEnumerable<DataStructures.EmployeeGroupBac> employeeGroups, int customerId);
[OperationContract]
string CreateUpdateTemplates(IEnumerable<DataStructures.TemplateBac> templates, int customerId);
[OperationContract]
string CreateUpdateEmployees(ref IEnumerable<DataStructures.EmployeeBac> employees, int customerId);
[OperationContract]
List<DataStructures.EmployeeBac> GetEmployeesPerGroup(int groupId);
[OperationContract]
List<DataStructures.AttendanceTransactionBac> GetTransactions(int customerId, DateTime? startDate,
DateTime? endDate, bool? downloaded);
[OperationContract]
string InsertNewTransactions(IEnumerable<DataStructures.AttendanceTransactionInBac> transactions);
[OperationContract]
string InsertNewTransaction(int employeeId, string transactionDate, short inOut, double latitude,
double longitude, String emei);
[OperationContract]
string UpdateDownloadedTxPerCustomer(int customerId);
}
}
<file_sep>/BioAccess_TEst/Login.cs
using BioAccess_TEst.BioAccessCloudBasic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BioAccess_TEst
{
[TestClass]
public class Login
{
[TestMethod]
public void SuccessfulLogin()
{
var client = new BioAccessCloudBasicClient();
var login = client.Login("jjbaird87", "biomaster");
Assert.AreEqual(true, login.LoginSuccessful);
Assert.AreNotSame("", login.SessionId);
Assert.AreEqual(1, login.CustomerId);
}
[TestMethod]
public void FailedLogin_IncorrectUsername()
{
var client = new BioAccessCloudBasicClient();
var login = client.Login("manish", "biomaster");
Assert.AreEqual("Username not found", login.ErrorMessage);
}
[TestMethod]
public void FailedLogin_PasswordIncorrect()
{
var client = new BioAccessCloudBasicClient();
var login = client.Login("jjbaird87", "wow");
Assert.AreEqual("Password incorrect", login.ErrorMessage);
}
}
}
<file_sep>/BioAccess_TEst/TemplateTypes.cs
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using BioAccess_TEst.BioAccessCloudBasic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BioAccess_TEst
{
[TestClass]
public class TemplateTypes
{
[TestMethod]
public void GetTemplateTypes()
{
var client = new BioAccessCloudBasicClient();
var types = client.GetTemplateTypes();
client.Close();
Assert.AreNotEqual(types.Count, 0);
var iso = types.Find(i => i.Description == "Iso");
Assert.AreNotEqual(null,iso);
}
}
}
| 4531eca09bfad657221a8dc4bf797002ecd7db27 | [
"C#"
]
| 8 | C# | jjbaird87/BioAccessCloud | adaf2f1259ae99ef41b31c68f71d27c8f382c582 | 6f56566a023e3d09e14a7dc3e95c747762d8f7ea |
refs/heads/master | <file_sep>FROM node:12.15-alpine
ARG VERSION
LABEL maintainer="<NAME> <<EMAIL>>"
LABEL version=$VERSION
ARG TIME_ZONE
RUN ln -snf /usr/share/zoneinfo/$TIME_ZONE /etc/localtime && echo $TIME_ZONE > /etc/timezone
RUN npm i -g @nestjs/cli
USER node
<file_sep>import {SignUpRequest} from "./requests/sign-un.request";
import {SignedUp} from "../graphql.schema";
export interface AuthServiceInterface {
signUp(request: SignUpRequest): Promise<SignedUp>;
}
<file_sep>import { ClientOptions, Transport } from '@nestjs/microservices';
import { join } from 'path';
import {Logger} from "@nestjs/common";
const logger = new Logger("COJFIFFF");
logger.log(join(__dirname, './protos/services.proto'));
const protoDir = join(__dirname, './protos');
export const microserviceOptions: ClientOptions = {
transport: Transport.GRPC,
options: {
url: '127.0.0.1:5000',
package: 'auth',
protoPath: [join(__dirname, '../auth/protos/services.proto')],
loader: {
keepCase: true,
longs: Number,
enums: String,
defaults: false,
arrays: true,
objects: true,
includeDirs: [protoDir],
},
},
};<file_sep>.DEFAULT_GOAL := help
USERNAME_LOCAL = "$(shell whoami)"
UID_LOCAL = "$(shell id -u)"
GID_LOCAL = "$(shell id -g)"
TIME_ZONE ?= America/Lima
CLI_VERSION = 1.0.0
CLI_IMAGE = gateway_cli
APP_IMAGE = gateway_app
APP_VERSION = 0.1.0
NETWORK = auth
build_cli_image: ## Build cli image: make build_cli_image
docker build --force-rm -t ${CLI_IMAGE}:${CLI_VERSION} docker/cli
npm_cli: ## Execute npm with COMMAND: make npm_cli COMMAND="run start:prod"
docker run --rm -it \
-v $$PWD/app:/app \
-v $$PWD/logs:/home/node/.npm/_logs/ \
-w="/app" ${FLAGS} \
${CLI_IMAGE}:${CLI_VERSION} sh -c "npm ${COMMAND}"
create_network:
docker network create --driver bridge ${NETWORK} || true
build_app_image: ## Build app image: make build_app_image
docker build --force-rm --rm \
--build-arg VERSION=${APP_VERSION} \
--build-arg TIME_ZONE=${TIME_ZONE} \
-t ${APP_IMAGE}:${APP_VERSION} -f docker/app/Dockerfile .
up: create_network build_app_image ## Up application: make up
IMAGE=${APP_IMAGE}:${APP_VERSION} \
NETWORK=${NETWORK} \
docker-compose -f docker/docker-compose.yml up -d --build && \
docker image prune --filter label=stage=intermediate -f
down:
IMAGE=${APP_IMAGE}:${APP_VERSION} \
NETWORK=${NETWORK} \
docker-compose -f docker/docker-compose.yml down
## Help ##
help:
@printf "\033[31m%-25s %-50s %s\033[0m\n" "Target" "Help" "Usage"; \
printf "\033[31m%-25s %-50s %s\033[0m\n" "------" "----" "-----"; \
grep -hE '^\S+:.*## .*$$' $(MAKEFILE_LIST) | sed -e 's/:.*##\s*/:/' | sort | awk 'BEGIN {FS = ":"}; {printf "\033[32m%-25s\033[0m %-49s \033[34m%s\033[0m\n", $$1, $$2, $$3}'<file_sep>import { Args, Mutation, Resolver } from '@nestjs/graphql';
import {SignUpRequest} from "./requests/sign-un.request";
import {SignedUp} from "../graphql.schema";
import {Inject, Logger} from "@nestjs/common";
import {AuthServiceInterface} from "./grpc.interface";
import {ClientGrpc} from "@nestjs/microservices";
const logger = new Logger('AuthResolver');
@Resolver('Auth')
export class AuthResolvers {
private authService: AuthServiceInterface;
constructor(@Inject('AUTH_PACKAGE') private readonly client: ClientGrpc) {}
onModuleInit(): any {
this.authService = this.client.getService<AuthServiceInterface>('AuthService');
logger.log("CLIENTTTTTT")
logger.log(this.client)
logger.log("SERVICCCCEEEEE")
logger.log(this.authService)
}
@Mutation('signUp')
async signUp(@Args('signUpInput') args: SignUpRequest): Promise<SignedUp> {
logger.log("signUpInput");
logger.log(args);
logger.log(this.authService);
return await this.authService.signUp(args);
}
}<file_sep>import { Module } from '@nestjs/common';
import {AuthResolvers} from "./auth.resolvers";
import {ClientsModule, Transport} from "@nestjs/microservices";
import {join} from "path";
@Module({
imports: [
ClientsModule.register([
{
name: 'AUTH_PACKAGE',
transport: Transport.GRPC,
options: {
url: '127.0.0.1:5000',
package: 'auth',
protoPath: join(__dirname, 'protos/services.proto'),
loader: {
keepCase: true,
longs: Number,
enums: String,
defaults: false,
arrays: true,
objects: true,
},
},
},
]),
],
providers: [AuthResolvers],
})
export class AuthModule {}<file_sep>import { Module } from '@nestjs/common';
import {GraphQLModule} from "@nestjs/graphql";
import {AuthModule} from "./auth/auth.module";
import {ClientsModule} from "@nestjs/microservices";
@Module({
imports: [
AuthModule,
GraphQLModule.forRoot({
debug: true,
playground: false,
typePaths: ['./**/*.graphql'],
})
]
})
export class AppModule {}
<file_sep>FROM node:12.15-alpine AS build
LABEL stage=intermediate
COPY ./app /usr/src/app
WORKDIR /usr/src/app
RUN npm install --only-prod && npm run build
FROM node:12.15-alpine
ARG VERSION
LABEL maintainer="<NAME> <<EMAIL>>"
LABEL version=$VERSION
#RUN apk update && apk upgrade
ARG TIME_ZONE
RUN ln -snf /usr/share/zoneinfo/$TIME_ZONE /etc/localtime && echo $TIME_ZONE > /etc/timezone
COPY --from=build /usr/src/app/dist /usr/src/app/dist
COPY --from=build /usr/src/app/node_modules /usr/src/app/node_modules
ENTRYPOINT ["node", "--max-old-space-size=4096", "/usr/src/app/dist/main"]
| 469f663cd5ee65a771d708ae43a54fca65aff1ea | [
"TypeScript",
"Makefile",
"Dockerfile"
]
| 8 | Dockerfile | JamieYnonan/nestjs-graphql-grpc-client | f3e8fd3881ccb99fecdd6320e74b923449993cf1 | 00f8143b97a6eea13a5fba1b9e4bfa712f93cd1f |
refs/heads/master | <repo_name>Adityaraj1711/Codingwebsite<file_sep>/requirements.txt
dj-database-url==0.5.0
dj-static==0.0.6
Django==1.10.5
gunicorn==19.9.0
psycopg2==2.7.5
static3==0.7.0
whitenoise==3.3.1
<file_sep>/README.md
# Codingwebsite
<h2>
A full website for contest registeration of a coding competition.
</h2>
<p>
The website uses a very interactive and responsive design built over a variety of modules.<hr>The backend is supported by django framework of python and the frontend is very interactive
with html, and javascripts also include particles.js.
</p>
<file_sep>/testmv/Scripts/django-admin.py
#!f:\heroku\codingwebsite\testmv\scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| 89f885c12331acfdc6bf744a969da3c1863a79fa | [
"Markdown",
"Python",
"Text"
]
| 3 | Text | Adityaraj1711/Codingwebsite | 7361884602c1d1a3fb3bf23bd1da2235cd79f88c | e2be3bc639bbc18c9839df7363510251fb66bada |
refs/heads/master | <repo_name>PratikBinga/CallerAPI_Latest<file_sep>/DocSignCallingAPI/Controllers/FileUploadController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace DocSignCallingAPI.Controllers
{
public class FileUploadController : System.Web.Mvc.Controller
{
// GET: FileUpload
public System.Web.Mvc.ActionResult Index()
{
return View();
}
///// <summary>
///// Http post to handle file uploads
///// </summary>
///// <param name="files"></param>
///// <returns></returns>
//[System.Web.Http.HttpPost]
//public async Task<IActionResult> UploadFile(List<IFormFile> files)
//{
// long size = files.Sum(f => f.Length);
// var filePath = "";
// foreach (var formFile in files)
// {
// filePath = Path.Combine(
// Directory.GetCurrentDirectory(), "UploadedFiles",
// formFile.FileName);
// if (formFile.Length > 0)
// {
// using (var stream = new FileStream(filePath, FileMode.Create))
// {
// await formFile.CopyToAsync(stream);
// }
// }
// }
// return Ok(new { count = files.Count, size, filePath });
//}
}
}<file_sep>/DocSignCallingAPI/Models/PayLoadData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DocSignCallingAPI.Models
{
public class PayLoadData
{
public string docBase64 { get; set; }
public string UsernameFile { get; set; }
}
}<file_sep>/DocSignCallingAPI/Controllers/SignedDocumentRecvdController.cs
using DocSignCallingAPI.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace DocSignCallingAPI.Controllers
{
[RoutePrefix("api/[controller]/[action]")]
public class SignedDocumentRecvdController : ApiController
{
[HttpPost]
public IHttpActionResult ReciveSignedDoc([FromBody] PayLoadData payLoadData)
{
//var addr = new System.Net.Mail.MailAddress(email.Split('@')[0]);
// var addr = new System.Net.Mail.MailAddress(email);
//string directorypath = Server.MapPath("~/App_Data/" + "Files/");
string directorypath = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/" + "Files/");
if (!Directory.Exists(directorypath))
{
Directory.CreateDirectory(directorypath);
}
var serverpath = directorypath + payLoadData.UsernameFile + ".pdf";
System.IO.File.WriteAllBytes(serverpath, Convert.FromBase64String(payLoadData.docBase64));
// return View(serverpath);
return Ok();
}
[HttpGet]
public IHttpActionResult Welcome()
{
//return Content("WElocme");
return Ok(new { Name = "Sanjay", Age = "30", City = "Pune" });
}
}
}
<file_sep>/DocSignCallingAPI/Models/DocuSignRequestData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DocSignCallingAPI.Models
{
public class DocuSignRequestData
{
public string recipients { get; set; }
public string fileData { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public string returnUrl { get; set; }
public string Description { get; set; }
}
}<file_sep>/DocSignCallingAPI/Controllers/DocuSignController.cs
using DocSignCallingAPI.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace DocSignCallingAPI.Controllers
{
[Route("api/[controller]/[action]")]
public class DocuSignController : Controller
{
public ActionResult SendDocumentforSign()
{
return View();
}
[HttpPost]
public ActionResult SendDocumentforSign(Recipient recipient, HttpPostedFileBase UploadDocument)
{
byte[] fileBytes;
using (Stream inputStream = UploadDocument.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
fileBytes = memoryStream.ToArray();
}
var DocumentBase64 = System.Convert.ToBase64String(fileBytes);
DocuSignRequestData inputModel = new DocuSignRequestData();
inputModel.fileData = DocumentBase64;
inputModel.Email = recipient.Email;
inputModel.Name = recipient.Name;
inputModel.Description = recipient.Description;
//Note: be replcaed by actual webhook URL of caller API.
inputModel.returnUrl = "http://callerapi.azurewebsites.net/api/SignedDocumentRecvd/ReciveSignedDoc";
using (var client = new HttpClient())
{
//var res = await client.PostAsync("https://localhost:44349/api/DocuSignPost/SendDocumentforSign", new StringContent(JsonConvert.SerializeObject(inputModel), Encoding.UTF8, "application/json"));
HttpResponseMessage res = client.PostAsync("https://dssapi.azurewebsites.net/api/DocuSignPost/SendDocumentforSign", new StringContent(JsonConvert.SerializeObject(inputModel), Encoding.UTF8, "application/json")).Result;
// HttpResponseMessage res = client.PostAsync("https://localhost:44349/api/DocuSignPost/SendDocumentforSign", new StringContent(JsonConvert.SerializeObject(inputModel), Encoding.UTF8, "application/json")).Result;
Task<string> responseesult = res.Content.ReadAsStringAsync();
DocuSignResponse obj = JsonConvert.DeserializeObject<DocuSignResponse>(responseesult.Result.ToString());
if (obj != null && !string.IsNullOrEmpty(obj.EnvelopeId))
{
ViewBag.SucMessage = "Document sent successully";
}
try
{
res.EnsureSuccessStatusCode();
//res.Result.EnsureSuccessStatusCode();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
return View();
}
[HttpGet]
public ContentResult GetDocumentStatus(string EnvelopeId)
{
string resultMessage = "";
using (var client = new HttpClient())
{
//var res = await client.PostAsync("https://localhost:44349/api/DocuSignPost/GetDocumentStatus", new StringContent(JsonConvert.SerializeObject(inputModel), Encoding.UTF8, "application/json"));
//HttpResponseMessage res = client.GetAsync("https://dssapi.azurewebsites.net/api/DocuSignPost/GetDocumentStatus", new StringContent(JsonConvert.SerializeObject(inputModel), Encoding.UTF8, "application/json")).Result;
HttpResponseMessage res = client.GetAsync("https://localhost:44349/api/DocuSignPost/GetDocumentStatus?EnvelopeId=" + EnvelopeId).Result;
Task<string> responseesult = res.Content.ReadAsStringAsync();
ViewBag.SucMessage = responseesult.Result.ToString();
resultMessage = responseesult.Result.ToString();
}
return Content(resultMessage);
}
}
}
<file_sep>/DocSignCallingAPI/Models/FileUploadRequest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DocSignCallingAPI.Models
{
public class FileUploadRequest
{
public string CallingApplication { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Action { get; set; }
public string ResponseAction { get; set; }
public List<SupportedFileType> SupportedFile { get; set; }
public List<ActionDataType> ActionData { get; set; }
public List<ResponseActionDataType> ResponseActionData { get; set; }
}
public class ActionDataType
{
public long ProjectId { get; set; }
}
public class ResponseActionDataType
{
public long ProjectId { get; set; }
}
public class SupportedFileType
{
public string FileFormat { get; set; }
}
}<file_sep>/DocSignCallingAPI/Models/DocuSignResponse.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DocSignCallingAPI.Models
{
public class DocuSignResponse
{
public int Status { get; set; }
public string EnvelopeId { get; set; }
public string Message { get; set; }
}
} | 0ecf656bd45a87b7009e60f55840df065542e63d | [
"C#"
]
| 7 | C# | PratikBinga/CallerAPI_Latest | a51f60c524a4b35ffd1514e40f844ad62e8dc824 | 9b4416b399cd292b786d3eed26d4f9a2f202b77f |
refs/heads/master | <repo_name>JuicyPasta/Hackathon<file_sep>/README.md
# Hackathon
172.16.17.32
packathon<file_sep>/custom_modules/professors.js
var http = require('http');
module.exports = function getLyrics (input,callback){
var teachers = [];
var request = http.request(input,function(res){
res.setEncoding('utf8');
res.on('data', function (data) {
var reg1 = new RegExp("<a class=\"nav2\" href=[^>]+>[^<]+</a>");
var reg2 = new RegExp("<a class=\"blknav\" href=[^>]+>[^<]+</a>");
var arr1 = reg1.exec(data);
var arr2 = reg2.exec(data);
// <a class="blknav" href="http://polyratings.com/eval.phtml?profid=2390"><NAME></a>
var arr = []
if (arr1 != null && arr2 != null){
arr = arr1.concat(arr2);
}else if (arr1 != null){
arr = arr1;
}else if (arr2 != null){
arr = arr2;
}
//console.log(arr1)
for (var a=0,b=arr.length; a<b; a+=1){
var line = arr[a];
var rag1 = new RegExp ("http://[^\"]+");
var link = rag1.exec(line)[0];
var rag2 = new RegExp (">[^<]+");
var name = rag2.exec(line)[0].substring(1);
if (name != "OpenRatings"){
var thing = {'name' : name, 'professorID' : link};
teachers.push(thing);
}else{
console.log(teachers);
callback(teachers);
}
}
});
});
request.on('error', function(e) {
return console.log('problem with request: ' + e.message);
});
request.end();
} | 40d2f7c3616a20aafb5ea4c3b61f92515db29bd1 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | JuicyPasta/Hackathon | 4da3c53316b666c52e1b834a5b09c7ea3dc3a979 | c80b1dbae83397ccd7190fdda64d38d3942b8863 |
refs/heads/main | <file_sep>
$(document).ready(function(){
const tokenObject = new TokenParser();
try{
if(tokenObject.isAuthenticated())
{
$("#btnLoginHeader").hide();
$("#loginInformation").show();
$("#loginInformation").text("Hoş geldiniz");
window.location.href = "/ShowApplications.html";
}
$("#btnBasvuru").click(function(e){
if(window.localStorage.getItem("login"))
{
window.location.href = "/ShowApplications.html";
}
else
{
window.location.href = "/Login.html";
}
});
}
catch(ex)
{
console.log(ex);
}
$("#btnLogin").click(function(e){
$.ajax({
url: "http://localhost:8080/login",
type: "POST",
data: JSON.stringify({ "username": $("#txtUserName").val(),"password":<PASSWORD>").val() }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
/*var tokenObject = new JwtToken(result);
//console.log(result);
console.log(tokenObject.getTokenExpDate())*/
window.document.cookie = "jwt=" + result;
/* window.localStorage.setItem("token",result);
window.localStorage.setItem("login",true);*/
console.log(result);
Swal.fire({
icon: 'success',
title: 'Giriş Başarılı.',
showConfirmButton: false,
timer: 1500
})
//.then(() => location.reload());
$("#btnLoginHeader").hide();
$("#loginInformation").show();
$("#loginInformation").text("Hoş geldiniz");
setTimeout(function(){
window.location.href = "/ShowApplications.html";
}, 2000);
},
error: function (xhr, textStatus, errorThrown) {
window.localStorage.setItem("login",false);
Swal.fire({
title: 'HATA!',
text: 'Giriş Hatalı.',
icon: 'error',
showConfirmButton: false,
timer: 1500
})//.then(() => location.reload());
}
});
});
}); <file_sep># Frontend-API-Request-and-Post
It is basically request and post to an API service that written by Java Spring Boot.
Html, Css, Javascript, JSON, jQuery, bootstrap, cookie is used.<file_sep>$(document).ready(function(){
let token = new TokenParser();
try{
if(token.isAuthenticated())
{
$("#btnLoginHeader").hide();
$("#loginInformation").show();
$("#loginInformation").text("Hoş geldiniz");
}
else
{
window.location.href = "/Login.html";
}
}
catch(ex)
{
console.log(ex);
window.location.href = "/Login.html";
}
var value = $.ajax({
url: "http://localhost:8080/api/applications",
async:false,
type: "GET",
headers: {
"Authorization": 'Bearer ' + getToken()
}
}).responseText;
buildTable(JSON.parse(value));
var table = $('#applications').DataTable();
$("#btnApplyFilter").click(function(e){
//search?ageStart=1&ageFinish=44&militaryStatus=yaptı&gender=erkek
if($("#txtAgeStart").val() != null && $("#txtAgeFinish").val() != null && $('#drpMilitaryStatus :selected').text() != null && $('#drpGender :selected').text() != null)
{
var query = "search?ageStart=" + $("#txtAgeStart").val() + "&ageFinish="+ $("#txtAgeFinish").val() + "&militaryStatus=" + $('#drpMilitaryStatus :selected').text().toLowerCase() + "&gender="+ $('#drpGender :selected').text().toLowerCase();
//console.log(query);
var value = $.ajax({
url: "http://localhost:8080/api/applications/" + query,
async:false,
type: "GET",
headers: {
"Authorization": 'Bearer ' + getToken()
}
}).responseText;
//console.log("GELEN VERI: " + value);
generateTable();
buildTable(JSON.parse(value));
$("#exampleModal .close").click()
$('#applications').DataTable();
}
});
});
function generateTable(){
var table = $('#applications').DataTable();
table.destroy();
//$('#applications').empty();
try{
var dmy = `<table class="table table-striped" id="applications"><thead>
<th>ID</th>
<th>Ad</th>
<th>Soyad</th>
<th>Yas</th>
<th>Cinsiyet</th>
<th>Eğitim</th>
<th>İl</th>
<th>İlçe</th>
<th>Askerlik Durumu</th>
<th>Programlama Dilleri</th>
<th>Sertifikalara</th>
<th>Email</th>
<th>Telefon</th>
</thead>
<tbody id="myTable">
</tbody>
</table>`
var table = document.getElementById('applications')
table.innerHTML = dmy;
}
catch(ex)
{
console.log(ex);
}
}
function buildTable(data){
var table = document.getElementById('myTable')
try{
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${data[i].applicationID}</td>
<td>${data[i].name}</td>
<td>${data[i].surname}</td>
<td>${data[i].age}</td>
<td>${data[i].gender}</td>
<td>${data[i].education}</td>
<td>${data[i].city}</td>
<td>${data[i].district}</td>
<td>${data[i].militaryStatus}</td>
<td>${data[i].programmingLanguages}</td>
<td>${data[i].certificates}</td>
<td>${data[i].email}</td>
<td>${data[i].phone}</td>
</tr>`
table.innerHTML += row
}
}
catch(ex)
{
console.log(ex);
}
}
function getCookieData(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function getToken() {
var _st = getCookieData("jwt");
return (_st != null) ? _st : "";
}<file_sep>class TokenParser{
constructor() {
}
parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
}
getTokenExpDate() {
return this.parseJwt(this.getToken()).exp;
}
getCookieData(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
getToken() {
var _st = this.getCookieData("jwt");
return (_st != null) ? _st : "";
}
asd()
{
return "sa";
}
isAuthenticated () {
if(this.token !== null && this.getTokenExpDate() >= new Date().getTime() / 1000 ) {
return true;
}
return false;
}
} | eee10d73fe0d93ff6632404c38a0d8fadc67a0bc | [
"JavaScript",
"Markdown"
]
| 4 | JavaScript | ahmetoguz1/Frontend-API-Request-and-Post | 705153c7f9070fd51fe1f9ca42bcdb960956185f | 975ed22136132330620e6dafb2cb2bb28057f630 |
refs/heads/master | <repo_name>nolia/CheesePagination<file_sep>/app/src/main/java/com/nolia/pagination/MainActivity.java
package com.nolia.pagination;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
/**
* @author <NAME>
*/
public class MainActivity extends ListActivity {
public static final int PAGE_SIZE = 20;
private View mProgressView;
private Loader mLoader;
private ArrayAdapter<String> mAdapter;
private AbsListView.OnScrollListener mScrollListener = new AbsListView.OnScrollListener() {
public boolean needToLoadMore = false;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (needToLoadMore && mIsLoadingAvailable) {
needToLoadMore = false;
doLoad();
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {// we reached last list item - loading footer
if (mIsLoadingAvailable) {
needToLoadMore = true;
} else {
needToLoadMore = false;
}
} else {
needToLoadMore = false;
}
}
};
private Data.Callback mCallback = new Data.Callback() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onGetData(final Data data) {
if (mAdapter == null) {
mAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
mProgressView.animate().alpha(0).withEndAction(new Runnable() {
@Override
public void run() {
mProgressView.setVisibility(View.GONE);
setListAdapter(mAdapter);
getListView().setOnScrollListener(mScrollListener);
if (canLoadMore(data)) {
getListView().addFooterView(mLoadingFooter);
}
}
}).start();
}
mAdapter.addAll(data.items);
// process data
mIsLoadingAvailable = canLoadMore(data);
mNextStart = data.firstItemIndex + data.items.length;
if (!mIsLoadingAvailable && mLoadingFooter.getParent() != null) {
Log.e("MainActivity", "Removing footer !");
getListView().removeFooterView(mLoadingFooter);
}
}
};
private boolean mIsLoadingAvailable;
private int mNextStart = 0;
private boolean canLoadMore(Data data) {
return data.items.length + data.firstItemIndex < data.totalCount;
}
private ProgressBar mLoadingFooter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressView = findViewById(R.id.progress);
mLoadingFooter = new ProgressBar(this);
mLoadingFooter.setIndeterminate(true);
mLoader = new Loader();
doLoad();
}
private void doLoad() {
mLoader.loadNext(mNextStart, PAGE_SIZE, mCallback);
}
}
<file_sep>/app/src/main/java/com/nolia/pagination/Loader.java
package com.nolia.pagination;
import android.os.Handler;
import android.os.Looper;
/**Fake data loader
*
* @author <NAME>
*/
public class Loader {
public static final int LOAD_DELAY = 2000;
public static final int MAX_ITEMS = 1000;
private Handler mHandler = new Handler(Looper.getMainLooper());
public void loadNext(int start, int pageSize, final Data.Callback callback) {
if (pageSize > MAX_ITEMS) {
pageSize = MAX_ITEMS;
}
final Data data = new Data();
data.firstItemIndex = start;
data.totalCount = MAX_ITEMS;
data.items = new String[pageSize];
for (int i = 0; i < pageSize; i++) {
data.items[i] = Data.CHEESES[ (start + i) % Data.CHEESES.length ];
}
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
callback.onGetData(data);
}
}, LOAD_DELAY);
}
}
<file_sep>/README.md
CheesePagination
================
Android pagination example on Cheese :{
| 9aeabce64379b998bf4cc8a387d27a333032226b | [
"Markdown",
"Java"
]
| 3 | Java | nolia/CheesePagination | dfee1baf1cde136b5df08e4017b68efbdd4bb080 | e36293b576ad52d0053d33f304d4b87707224241 |
refs/heads/main | <repo_name>aolwyn/Shakespearean-Insult-Generator<file_sep>/insultgenerator_19ahb.cpp
//#include "library.h"
#include <stdlib.h>
#include <string>
#include <vector>
#include <time.h>
#include <fstream>
#include <iostream>
#include <algorithm>
#include "insultgenerator_19ahb.h"
//sort using <algorithm> or <sort> ??? both work
using namespace std;
InsultGenerator::InsultGenerator() {}
//goal: generate and save between 1 - 10000 insults.
//classes: file exception, NumInsultsOutOfBounds,
//main is InsultGenerator
/*Stuff:
* initialize() - load all source phrases from txt file into the attributes
* talkToMe() - returns a single insult, generated at random
* generate(int __) - generates requested number of unique insults, returns vector of strings
* generateAndSave() - generates the requested # of insults & saves them to the filename supplied in alphabetical order
*/
//error class for invalid file
FileException::FileException(const string& m) : message(m) {}
string& FileException::what() {
return message;
}
//error class for insult outside of bounds
NumInsultsOutOfBounds::NumInsultsOutOfBounds(const string& m) : message(m) {}
string& NumInsultsOutOfBounds::what() {
return message;
}
void InsultGenerator::initialize()
{
string line;
ifstream fileIn("../InsultsSource.txt"); //attempt to read in the files from source
if(fileIn.fail()) //fail check, if you can't read in files print an error message
{
throw FileException("Not a valid file.");
return; //wont actually return anything (void,) but was getting a random error for some reason without it
}//close reading failure check
//while(!fileIn.eof()) //while not at end of file, alternate way of doing this
while(fileIn >> line) //while there's stuff to still read in
{
//fileIn >> line; //read in data into a string
rawData.push_back(line); //push above string into the vector that hold all inputs
}//end while(!fileInAgain.eof())
for( int i = 0; i < rawData.size(); i+=3) //separate the three words into their individual columns.
{
column1.push_back(rawData[i]);
column2.push_back(rawData[i+1]);
column3.push_back(rawData[i+2]);
}//close for loop
fileIn.close(); //close file after finished tasks
}//close initialize()
string InsultGenerator::talkToMe()
{
int word1 = rand() % column1.size(); //take random elements from within the range
int word2 = rand() % column2.size();
int word3 = rand() % column3.size();
string insult = "Thou " + column1[word1] + " " + column2[word2] + column3[word3] + " !"; //put the full sentence together
return insult; //return the result
}//close talkToMe()
vector<string> InsultGenerator::generate(int numberOfInputs)
{
srand(time(0)); //need this otherwise you just get the same random thing from rand() each time?
if (numberOfInputs < 1 || numberOfInputs > 10000) //out of bounds check
{
throw NumInsultsOutOfBounds("Not a valid number. Choose a number between 1 and 10,000.");
return vector<string>();
}//close if exception check
vector<string>generatedInsults; //new vector for the generated things
for(int i = 0; i< numberOfInputs; i++)
{
generatedInsults.push_back(talkToMe()); //send insults to the new vector while not at requested amount
}//end for loop
vector<string> returnedInsults( generatedInsults.begin(), generatedInsults.end()); //for returning, this vector is to be sorted
sort(returnedInsults.begin(), returnedInsults.end()); //function for sorting. this will sort everything from start -> end alphabetically
return returnedInsults; // return the sorted, generated insults
}//close generate()
void InsultGenerator::generateAndSave(string file, int numResults) {
if(numResults < 0 || numResults > 10000) //insult out of bounds check
{
throw NumInsultsOutOfBounds("Not a valid number. Choose a number between 1 and 10,000.");
}//close if
vector<string> insultsToGive; //create temporary vector for insults
insultsToGive = generate(numResults); //feed in wanted # of insults
ofstream outputFile(file); //create the output file thing
for(const auto &a : insultsToGive) outputFile << a <<"\n"; //read into file the stuff generated
}//close generateAndSave()
<file_sep>/insultgenerator_19ahb.h
//
//
#ifndef INC_320_ASSIGNMENT_1_INSULTGENERATOR_H
#define INC_320_ASSIGNMENT_1_INSULTGENERATOR_H
#include <string>
#include <vector>
using namespace std;
class InsultGenerator {
public:
InsultGenerator();
void initialize();
string talkToMe();
vector<string> generate(int numberOfInputs);
void generateAndSave(string file, int numResults);
private: //make the vectors private so other things can't access them. don't want privacy leak
vector<string> rawData;
vector<string> column1;
vector<string> column2;
vector<string> column3;
};
//class for file exception, throws the error message when you try to read an invalid file
class FileException
{
public:
FileException(const string& m);
string& what();
private: //strings are mutable in C++, need to privatize them
string message;
};
//class for out of bounds, throws the associated error message when you try feeding in a wrong
//amount of inputs (or in this case, insults)
class NumInsultsOutOfBounds
{
public:
NumInsultsOutOfBounds(const string& m);
string& what();
private:
string message;
};
#endif //INC_320_ASSIGNMENT_1_INSULTGENERATOR_H
<file_sep>/TestInsultGenerator.cpp
/*
* TestInsultGenerator.cpp
*
* Author: <NAME>
* A testing program for CISC320 assignment 1.
*/
#include <iostream>
#include <string>
#include <vector>
#include <time.h>
#include "InsultGenerator_19ahb.h"
using namespace std;
int main() {
InsultGenerator ig;
vector<string> insults;
clock_t start=0, finish=0;
// The initialize() method should load all the source phrases from the InsultsSource.txt file into the attributes.
// If the file cannot be read, the method should throw an exception.
try {
ig.initialize();
} catch (FileException& e) {
cerr << e.what() << endl;
return 1;
}
// talkToMe() returns a single insult, generated at random.
cout << "A single insult:" << endl;
cout << ig.talkToMe() << endl;
// Check number to generate limits.
try {
insults = ig.generate(-100);
} catch (NumInsultsOutOfBounds& e) {
cerr << e.what() << endl;
}
try {
insults = ig.generate(40000);
} catch (NumInsultsOutOfBounds& e) {
cerr << e.what() << endl;
}
// generate() generates the requested number of unique insults.
cout << "\n100 insults, all different:" << endl;
insults = ig.generate(100);
if (insults.size() > 0)
for (int i = 0; i < 100; i++)
cout << insults[i] << endl;
else
cerr << "Insults could not be generated!" << endl;
// generateAndSave() generates the requested number of unique insults and saves them to the filename
// supplied. If the file cannot be written, the method should throw an exception. Note that the
// insults in the file should be in alphabetical order!
// Check the number to generate limits first:
try {
ig.generateAndSave("Nothing.txt", 40000);
} catch (NumInsultsOutOfBounds& e) {
cerr << e.what() << endl;
}
cout << "\nSaving 1000 unique insults to a file...";
try {
ig.generateAndSave("SavedInsults.txt", 1000);
} catch (FileException& e) {
cerr << e.what() << endl;
return 1;
}
cout << "done." << endl;
// Test ability to generate the maximum number of insults and how long it takes.
try {
start = clock();
insults = ig.generate(10000);
finish = clock();
} catch (NumInsultsOutOfBounds& e) {
cerr << e.what() << endl;
}
cout << "\n" << insults.size() << " insults generated." << endl;
cout << (1e3 * (finish - start)/CLOCKS_PER_SEC) << " msec to complete." << endl;
return 0;
} // end main
<file_sep>/README.md
# Shakespearean-Insult-Generator
C++ shakespearean insult generator, created for an assignment for the course CMPE320.
| 743d9fbadbe19aebc744b15c9f4e04e2d5ab8156 | [
"Markdown",
"C++"
]
| 4 | C++ | aolwyn/Shakespearean-Insult-Generator | 26a7f12dc541c5a6aded39206e32aeaec99bf274 | 7bd125cd0d852e2ba13f2747f5665a09f531d12d |
refs/heads/master | <file_sep>var gplay = require('google-play-scraper');
var shit=[];
gplay.reviews({
appId: 'in.scroll.android',
page: 1,
sort: gplay.sort.RATING
}).then(function(response){
shit=shit.concat(response);
console.log(JSON.stringify(shit));
});
// }).then(console.log, console.log);<file_sep>var gplay = require('google-play-scraper');
var i;
var yay=[];
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var rem=500;
for (i = 0; i < 500; i++) {
gplay.reviews({
// appId: 'com.mobstac.thehindu',
// appId: 'in.scroll.android',
// appId: 'com.july.ndtv',
// appId: 'com.republicworld',
page: i,
sort: gplay.sort.NEWEST
}).then(function(response){
yay=yay.concat(response);
--rem;
if (rem<=0){
console.log(JSON.stringify(yay));
}
});
sleep(10000);
}
<file_sep>var parser = require('really-relaxed-json').createParser();
var json = parser.stringToValue('[ { id: 'gp:AOqpTOFF_5QXTeI_p4h-iXUEBIVSuR01CxxY0ILpMU93d6_9iMZSIPUh6vkr6soaBjPaBimydl7rOvBLEAkzv98',
userName: 'Amin M',
userImage: 'https://lh3.googleusercontent.com/a-/AAuE7mCtjyVGtCSQdUTZKJ7tiZpSQ_f1Vf_vX5ZfBYgoRg=w96-h96-p',
date: 'May 6, 2017',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRkZfNVFYVGVJX3A0aC1pWFVFQklWU3VSMDFDeHhZMElMcE1VOTNkNl85aU1aU0lQVWg2dmtyNnNvYUJqUGFCaW15ZGw3ck92QkxFQWt6djk4',
score: 5,
title: '',
text: 'Nonbaised in the age of biased presentation of news and views.Its contents give satisfaction',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOEufxrjVHSx3bCwaxD66_kRgUNB--1UuFyX6jYplQBBek6QuIUpyuSj4h_vA1OxDLU9A2UN5NyspeRPXkQ',
userName: 'Akshay Verma',
userImage: 'https://lh6.googleusercontent.com/-X89Ay9Bei5o/AAAAAAAAAAI/AAAAAAAAAAA/ACevoQMgU-aHZuDm3Vncmbs4_8G8YkY2kQ/w96-h96-p/photo.jpg',
date: 'December 2, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRXVmeHJqVkhTeDNiQ3dheEQ2Nl9rUmdVTkItLTFVdUZ5WDZqWXBsUUJCZWs2UXVJVXB5dVNqNGhfdkExT3hETFU5QTJVTjVOeXNwZVJQWGtR',
score: 5,
title: 'Best in class.',
text: 'Best in class. Have some glitches now and then when articles don\'t load for no reason. But the content and the writing style makes me scroll fan. Also that it just sends important news to be sent through notification is awesome.',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOGXwsb3xpUOjNDNcIlDZeEdGVX0Cc7NwgzaiHPfzw4fU0wuhM_DkOGPgd08DloLgRo442VAbFcPXzYshnI',
userName: '<NAME>',
userImage: 'https://lh3.googleusercontent.com/a-/AAuE7mCCmJ3pGLzFTpdsuicJtxCaKe-RWjDwg7sUgGW9ONU=w96-h96-p',
date: 'January 9, 2017',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPR1h3c2IzeHBVT2pORE5jSWxEWmVFZEdWWDBDYzdOd2d6YWlIUGZ6dzRmVTB3dWhNX0RrT0dQZ2QwOERsb0xnUm80NDJWQWJGY1BYellzaG5J',
score: 5,
title: 'Awesome app',
text: 'Awesome app Useful for Civil Service Aspirants. .Covers High National International news',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOH2jlKdm2OSYV5kML_IxK4IqIWomo3ke6<KEY>',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'July 9, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPSDJqbEtkbTJPU1lWNWtNTF9JeEs0SXFJV29tbzNrZTZENDlEaFFqdVVFMVpoaTZ5VHZlTHhqM192VW5GNEFCOUxxcXo2UVdXUDBrZ2thZnNr',
score: 5,
title: '',
text: 'The best in news',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOH2NXC1nF0_ZU12917CeN3w0OJoLyWaa3Att7ixpx0v6UrkAcGSYbmNzQAUp0EPV3Ss3XrR6Cs1OMxvzz4',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'January 6, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPSDJOWEMxbkYwX1pVMTI5MTdDZU4<KEY>',
score: 5,
title: '',
text: 'Best',
replyDate: 'January 14, 2016',
replyText: 'We\'re glad you like the app, Pankaj.' },
{ id: 'gp:AO<KEY>',
userName: '<NAME>',
userImage: 'https://lh3.googleusercontent.com/-eV-szJvzXM0/AAAAAAAAAAI/AAAAAAAAAAA/ACevoQMgeLBPSfOgBMERoudLgkgse6tK5w/w96-h96-p/photo.jpg',
date: 'January 15, 2017',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPSG5lT0hlczlqWkE4cm0waTZxYXJBRWxHaVh2S0oteWV4R2xvMWhtN1VYWm5uSm1EU24wQTFKQVp5VGdKNW9zMTZ1a0tSZGhpWkRNazIyYWNn',
score: 5,
title: 'THE BEST.',
text: 'THE BEST. Nothing more to say.',
replyDate: 'February 8, 2017',
replyText: 'Thank you. :)' },
{ id: 'gp:<KEY>',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'March 5, 2015',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=<KEY>',
score: 5,
title: 'Was waiting for it.',
text: 'Was waiting for it. Really good coverage of news',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOEH7f_RNMnrD19ouzlOf2chb2dqpcRkorppwfkPAeaJ2fjcRJyun_SQwWJI-8_sekMDp424FL0vfOmD3OU',
userName: 'Aman Kumar',
userImage: 'https://lh3.googleusercontent.com/a-/AAuE7mAn6cVE4hCrEF5S500LzfZH_RZMkMCxY1zyd2s42g=w96-h96-p',
date: 'October 20, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRUg<KEY>T21EM09V',
score: 5,
title: '',
text: 'Brave and unbiased',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOHWeZvQZfleiuk3wWrKv2gH3O2IqxzmPgdbFXN8cHkCZTydOjW2w94S7XCTPOp19MOCBeWN_e7k6_h2O60',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'December 10, 2015',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPSFdlWnZRWmZsZWl1azN3V3JLdjJnSDNPMklxeHptUGdkYkZYTjhjSGtDWlR5ZE9qVzJ3OTRTN1hDVFBPcDE5TU9DQmVXTl9lN2s2X2gyTzYw',
score: 5,
title: 'Creative and fast and amazing app for me.....',
text: 'Creative and fast and amazing app for me..... It provides me fast surfing for NEWS and also absolute news to me........ AWESOME APP FOR NEWS EVER..... For feedback-- you should add night mode option for night reading.......',
replyDate: 'December 14, 2015',
replyText: 'Thanks for the kind words Yogesh. We\'re happy you like the app. We\'re considering adding in night mode in one of the later updates. Stay tuned!' },
{ id: 'gp:AOqpTOGNZKDiZ5z3PlzkicZPpWwGx0Qt0JnSi8rUENsLj5LbaojIeEiQREZczjEFo9BFHljYsKiyFnxEi1EXq64',
userName: '<NAME>',
userImage: 'https://lh3.googleusercontent.com/a-/AAuE7mBJ3pSOPFsSWz4XiQynQpNuPX5NwFsnHpkozrqw=w96-h96-p',
date: 'January 26, 2018',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPR05aS0RpWjV6M1BsemtpY1pQcFd3R3gwUXQwSm5TaThyVUVOc0xqNUxiYW9qSWVFaVFSRVpjempFRm<KEY>0tpeUZ<KEY>TY0',
score: 5,
title: '',
text: 'The best source for news in India',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOG0Opdfq2HApe1KcakTOgoeQTamnGid5KUrLMT1HeF2ahuUMQKXv1tXIxGC9Ko_MazDZMfX1dU1H5-mLO0',
userName: 'Bhavani Rajan',
userImage: 'https://lh3.googleusercontent.com/a-/AAuE7mAaskEheWCeA8NS4P4t3sQFkD-WxSziL096O0Xl3w=w96-h96-p',
date: 'September 1, 2017',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRzBPcGRmcTJIQXBlMUtjYWtUT2dvZVFUYW1uR2lkNUtVckxNVDFIZUYyYWh1VU1RS1h2MXRYSXhHQzlLb19NYXpEWk1mWDFkVTFINS1tTE8w',
score: 5,
title: '',
text: 'Wonderful app ive seen so far...!!!!!',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOFuIGqn0FVXPkwktlb4qNQ-Bwo6DQya_hpeUYOAaUzmpbOj_4bRUtfVe_DNH524YnfQR9bcJ75m1RG9ML0',
userName: '<NAME>',
userImage: 'https://lh3.googleusercontent.com/a-/AAuE7mAmM2uT5fCdvNUfZo74D4TCxrXRcd3kt0ky7tTkMg=w96-h96-p',
date: 'August 15, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRnVJR3FuMEZWWFBrd2t0bGI0cU5RLUJ3bzZEUXlhX2hwZVVZT0FhVXptcGJPal80YlJVdGZWZV9ETkg1MjRZbmZRUjliY0o3NW0xUkc5TUww',
score: 5,
title: '',
text: 'New face of news',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOF9mq4MoJvq7GbU7G4Ma-NKN3_J8uVKAme725ZogKDqkwG5TQdAlc2e1DsCz0YAc4Wj2sxd0IBuWmTBIf0',
userName: 'Ankur Jalan',
userImage: 'https://lh3.googleusercontent.com/a-/AAuE7mA6VFDsucbE4KzCCnxNarsPTxTigrnxTycasr0-7A=w96-h96-p',
date: 'October 29, 2017',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRjltcTRNb0p2cTdHYlU3RzRN<KEY>',
score: 5,
title: '',
text: 'Great jourlanism work. I love your articles. I was a reader from the website now switching to app. Just like to say Democracy dies in darkness, but news and article like this hold my believe upon the saying that press is a main pillar for democracy. Thank you for you great effort.',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOGISRo35tE7OjAe5kpeA1GKMMAiGhQItKycHds_YczuWlNMRIooaWwJ3VgPY91S4Hmy0dd8gxw9_Q6DseE',
userName: 'sreyas dharmapurikar',
userImage: 'https://lh3.googleusercontent.com/-4N3DNmbc3Q0/AAAAAAAAAAI/AAAAAAAAAAA/ACevoQOf2notnA4_X8oIrFzixWBlPDsfiA/w96-h96-p/photo.jpg',
date: 'December 7, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPR0lTUm8zNXRFN09qQWU1a3BlQTFHS01NQWlHaFFJdEt5Y0hkc19ZY3p1V2xOTVJJb29hV3dKM1ZnUFk5MVM0SG15MGRkOGd4dzlfUTZEc2VF',
score: 5,
title: '',
text: 'Best...',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOHfZhNWCG4dOAlEEgVV1BqXvsrCfbt6C-Xck6lVrZ6sR_l8R8asdSFcgaObpRlfCeeIdgqnPZtII-B1WlA',
userName: 'Aabid Shafi',
userImage: 'https://lh4.googleusercontent.com/-WV9Dlk8cuok/AAAAAAAAAAI/AAAAAAAAAAA/ACevoQMojOluIblPkNrK9-CN0ZUX-SEGew/w96-h96-p/photo.jpg',
date: 'August 18, 2017',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPSGZaaE5XQ0c0ZE9BbEVFZ1ZWMUJxWHZzckNmYnQ2Qy1YY2s2bFZyWjZzUl9sOFI4YXNkU0ZjZ2FPYnBSbGZDZWVJZGdxblBadElJLUIxV2xB',
score: 5,
title: '',
text: 'This is ✋ down one of the best news app not just interms of UI but also the content.',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOGNvM4ySioIA0-ByXHkMBytTMP0qCuK62XqTBOrWiovYnRcYFFTPUfeVhrDmH_kAUyWq9x0Nv64MzuUMa0',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'May 14, 2015',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPR052TTR5U2lvSUEwLUJ5WEhrTUJ5dFRNUDBxQ3VLNjJYcVRCT3JX<KEY>',
score: 5,
title: 'Awesome',
text: 'Awesome It is great and I would say a missing piece from news summary world of android app market.',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AO<KEY>',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'January 22, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPR1hiN21MSmNwYTZwUzRwV05IbGFFbGJzNFJ5T3lIdjdpUVJYZUNNa1F4MXExaE5VZVVhdmVYNmhySHduVVNwcHJ0ZHZsUzhpLXNCZnZWNm1V',
score: 5,
title: 'New age journalism..',
text: 'New age journalism.. It\'s a combination of both newspaper and TV.. Keep it up guys...',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AO<KEY>uit<KEY>sedN9I8eeb<KEY>',
userName: '<NAME>',
userImage: 'https://lh3.googleusercontent.com/-k4BeD4leftM/AAAAAAAAAAI/AAAAAAAAAAA/ACevoQM_rJq6j4R8Z_1fGwndXUbSdm7hzA/w96-h96-p/photo.jpg',
date: 'August 9, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRUhiWVZ2MElpdUt0dWl<KEY>MFdCV<KEY>jl<KEY>CL<KEY>',
score: 5,
title: '',
text: 'Best news app ever in India',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOGAydLFc-NGO5AYoksOiqeH8uFMFuFLGvSuOmFFYvmv29rVBsX_J6LSBsa9Pj-GDeP4BH3hSXviu9ausOI',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'November 24, 2015',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPR0F5ZExGYy1OR081QVlva3NPaXFlSDh1Rk1GdUZMR3ZTdU9tRkZZdm12MjlyVkJzWF9KNkxTQnNhOVBqLUdEZVA0QkgzaFNYdml1OWF1c09J',
score: 5,
title: 'Night mode',
text: 'Night mode Would love more, the already awesome app if, you could add a mode for reading in the night. Thanks in advance.',
replyDate: 'November 24, 2015',
replyText: 'Thanks for the feedback Vinodh. We\'ll speak with the design team on the possibility of having night mode in one of the future updates. Stay tuned!\n\nHave a wonderful day!' },
{ id: 'gp:<KEY>',
userName: 'md imran',
userImage: 'https://lh3.googleusercontent.com/a-/AAuE7mB4AQ5djCmC_SyxWYBRwSb_E7DNZsoj01mJs5wveg=w96-h96-p',
date: 'November 27, 2017',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPR1Q4bDlCV1R3WXVPelFJM3pGelJQZC1NV1RMdFNFclJDUFAyckN4dWZFVUcxMUNZaDVtU2VQWVJhUWtRVlAteEZmRDZad254Y2hrYjBsMDdV',
score: 5,
title: '',
text: 'You r not like govt lab dog news. Journalists do not have any Dhram or rastra (religions and nation)there duty is to bring truth from hiding object from powerfully people .',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:<KEY>',
userName: 'Shivkumar Patil',
userImage: 'https://lh6.googleusercontent.com/-MpRz-u8VpxU/AAAAAAAAAAI/AAAAAAAAAAA/ACevoQM6pnynFwtd6GmOqrll7IBhzeLqoQ/w96-h96-p/photo.jpg',
date: 'January 9, 2018',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRlZ5aVlrdExHcVpwNFA5REJkT2NQeFhNRVlsZDRnMm01YTljdGdKcHVlczFtcDNSLWd1d0RuV1dTZ3ZRMUdHRzdtNGw3bWxKcFlXTjRDTVpF',
score: 5,
title: '',
text: 'Best don\'t be biased forever.. Do you job faithfully..',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOHyQ7Qu3Ijr4UVSJt2F_TGKti_kbQP-an1vjhdVLcwMSrGfnlBveeqeyu-NSbJSiogVUHqoqZ5zNIoufSU',
userName: '',
userImage: 'https://lh4.googleusercontent.com/-ItB_5HoUnUI/AAAAAAAAAAI/AAAAAAAAAAA/EvVn5R_y7CU/w96-h96-p/photo.jpg',
date: 'September 3, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPSHlRN1F1M0lqcjRVVlNKdDJGX1RHS3RpX2tiUVAtYW4xdmpoZFZMY3dNU3JHZm5sQnZlZXFleXUtTlNiSlNpb2dWVUhxb3FaNXpOSW91ZlNV',
score: 5,
title: 'Best',
text: 'Best Apps',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTO<KEY>',
userName: 'Waqas Aziz',
userImage: 'https://lh3.googleusercontent.com/a-/AAuE7mAL8XpDtvFqLEAtD2epZdzgMgPvVOPN39zWRKLLaA=w96-h96-p',
date: 'May 12, 2017',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRmw4RDBOVHlrNWo1U0dtZ2pkR1VTQnk5UG80NFlFR0dCR2pRdlUyWUVwM1Z2TmpRaVdlaGZFRkpGeGMwMEhiR3RzY1MtQUVFemJQQ0NfTnZv',
score: 5,
title: '',
text: 'journalism at its best..',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOENIyO3o53HyHFdQg2Rmt4QFQ_2TzNk5q7fGOA-pYRr2jjViCQxFnj2-U4URnBhZZJh641j3BTl7J8XTkM',
userName: 'shubham shukla',
userImage: 'https://lh3.googleusercontent.com/a-/AAuE7mDfKzSstHBCDniB0yb9kGm0w74PsYWAgfR7lUxDRw=w96-h96-p',
date: 'October 17, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRU5JeU8zbzUzSHlIRmRRZzJSbXQ0UUZRXzJUek5rNXE3ZkdPQS1wWVJyMmpqV<KEY>',
score: 5,
title: 'Great app',
text: 'Great app Love to see news with morning tea',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:<KEY>',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'April 5, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=<KEY>',
score: 5,
title: 'Worth a read,Everytime!',
text: 'Worth a read,Everytime! Finally a place to read D "Real News" and not the heaps of drama being sold around in d form of "News"',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:<KEY>',
userName: 'Gagan<NAME>',
userImage: 'https://lh3.googleusercontent.com/a-/AAuE7mDfL01m1ubCLrWN272BxxA9wmXRzfxlV6512s1Z=w96-h96-p',
date: 'December 30, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=<KEY>',
score: 5,
title: 'Simply awesome...',
text: 'Simply awesome... Nice presentation',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOE1Hw7PRVvlKKp88jkDrbzlOFYz9Sl7g9uWDnYF6sMLaOW3DCNVuJ3sUCWUqjf7WtZoHZBIXgdk4gFDOLM',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'March 3, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRTFIdzdQUlZ2bEtLcDg4amt<KEY>CSVhnZGs0Z0ZET0xN',
score: 5,
title: '',
text: 'Detailed and reliable articles',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOHl07uJDe1C8HXITKcOSgQv_6hQSVzMznAefbto2aiBrgzxzbZcuFM--QNpRqAtBba0sE8oO09hOo6j_OA',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'April 27, 2015',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPSGwwN3VKRGUxQzhIWElUS2NPU2dRdl82aFFTVnpNem5BZWZidG8yYWlCcmd6eHpiWmN1Rk0tLVFOcFJxQXRCYmEwc0U4b08wOWhPbzZqX09B',
score: 5,
title: '',
text: 'This app deserves that award',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOE5SV8WeSXXDSa2CJcH4y-vCxGR7v8oUDOVnaw-eurAhWfNifqkN8OUdhxWuIIyPCbZ0BIJRYXtRPmk9kY',
userName: '<NAME>',
userImage: 'https://lh3.googleusercontent.com/a-/AAuE7mBP8moaXtOi4atPLq1czMGumkt66kzJ2Fnmc6Kc=w96-h96-p',
date: 'May 15, 2017',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRTVTVjhXZVNYWERTYTJDSmNINHktdkN4R1I3djhvVURPVm5hdy1ldXJBaFdmTmlmcWtOOE9VZGh4V3VJSXlQQ2JaMEJJSlJZWHRSUG1rOWtZ',
score: 5,
title: '',
text: 'Please make satyagrah.scroll app also.thanks',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOHUSb6rBkRzyHHCL90VvcTxlImnAtex9hKoEet1JVSiwKAaxVk6VQfY79zeoWXKkVXyt1CJ_HkIW1mP7VY',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'November 15, 2015',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPSFVTYjZyQmtSenlISENMOTBWdmNUeGxJbW5BdGV4OWhLb0VldDFKVlNpd0tBYXhWazZWUWZZNzl6ZW9XWEtrVlh5dDFDSl9Ia0lXMW1QN1ZZ',
score: 5,
title: 'Excellent app with great stories',
text: 'Excellent app with great stories This scroll-in app has won my heart,Excellent app',
replyDate: 'November 15, 2015',
replyText: 'Thanks Akshad. You made our day. Thanks for the feedback.' },
{ id: 'gp:AOqpTOGHbh3rcoyD93wLkWeSEDfpEkUNRJSz8-WeiNXXETzd6t2vXuj1ijgkxLQJ_slShP6G8gZ5GzKGoYxVChQ',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'October 12, 2015',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPR0<KEY>amd<KEY>',
score: 5,
title: '',
text: 'Loved ur app. The GUI is simple and clean. Keep rocking! Hope you\'d soon incorporate the remaining sections from the main website.',
replyDate: 'October 12, 2015',
replyText: 'Hey Alex,\n\nWe\'re happy you like the app. We\'re a few days away from releasing a major update. Amongst many new features & design changes, the update will also include SocialWire, Roving Correspondent, Video! We hope you\'ll like it too!\n\nHere\'s our blog post about it : http://blog.scroll.in/designing-scroll-for-android/\n\nHave a great day!' },
{ id: 'gp:AOqpTOGMNPR8NcNIaZdgTa93QNOCcjEvv8cxlW1LqLzk5MtDoHKnjEjUR6UOc0C8XqQ0SOWCmt69HQlQIwOd1jU',
userName: 'joshua dsouza',
userImage: 'https://lh6.googleusercontent.com/-JR1ANn8I4eE/AAAAAAAAAAI/AAAAAAAAAAA/ACevoQMeQaYLnr7pv0Uo57pqPz_y3pgVEQ/w96-h96-p/photo.jpg',
date: 'June 11, 2017',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPR01OUFI4TmNOSWFaZGdUYTkzUU5PQ2NqRXZ2OGN4bFcxTHFMems1TXREb0hLbmpFalVSNlVPYzBDOFhxUTBTT1dDbXQ2OUhRbFFJd09kMWpV',
score: 5,
title: '',
text: 'The most beautiful news app ever. The articles aren\'t biased. Very crisp. And covers everything. The videos are lovely too. Great job guys continue doing the good job.',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOF1bifQrZyHXVu3QkNrGnWTbenbPKpp7M5dpDlt-yGDonOjihZ74eG4jnv9APzSw55pEQXwcwlBHN1cqoY',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'August 9, 2015',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRjFiaWZRclp5SFhWdTNRa05yR25XVGJlbmJQS3BwN001ZHBEbHQteUdEb25PamloWjc0ZU<KEY>',
score: 5,
title: 'Great articles but do maintain neutrality',
text: 'Great articles but do maintain neutrality Scroll is losing credibility due to total anti bjp stance... Please have a more comprehensive mix of articles..',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOE2LOzXys5-1FNmi2Byk0wD6ldKkqNlcakO8N6JkdHjNZkbBpxczQRnjpll8WXIaDoXt3fv0Z1u0zqNnGw',
userName: '<NAME>',
userImage: 'https://lh3.googleusercontent.com/a-/AAuE7mArLiIpz7aSsJJklST0qJYB7DQE7HWaWZ0AYSWWVw=w96-h96-p',
date: 'February 12, 2017',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRTJMT3pYeXM1LTFGTm1pMkJ5azB3RDZsZEtrcU5sY2FrTzhONkprZEhqTlprYkJweGN6UVJuanBsbDhXWElhRG9YdDNmdjBaMXUwenFObkd3',
score: 5,
title: '',
text: 'Very informative & thought provoking',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOFlo5Zp5prQPl4aFCTJqxdt4bRKnZTO0MEBxkH3J242LwPv3S92aVbhtmMPHDGuHHoNq5SEboUvpBvJv0w',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'January 11, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRmxvNVpwNXByUVBsNGFGQ1RKcXhkdDRiUktuWlRPME1FQnhrSDNKMjQyTHdQdjNTOTJhVmJodG1NUEhER3VISG9OcTVTRWJvVXZwQnZKdjB3',
score: 5,
title: '',
text: 'I love reading news articles and find this app to be prefect. The content is really good and an amazing app overall.',
replyDate: 'January 14, 2016',
replyText: 'Thanks for the feedback Rishabh.' },
{ id: 'gp:AOqpTOHjTDMOyA1Z88DfExNCRIu-DmYUHpTuDDlXEKUdZsWTa5cA9VQvHVW3KsaZw-yT9hVhdemvh9hCuDUBUvU',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'June 29, 2016',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPSGpURE1PeUExWjg4RGZFeE5DUkl1LURtWVVIcFR1RERsWEVLVWRac1dUYTVjQTlWUXZIVlczS3NhWncteVQ5aFZoZGVtdmg5aEN1RFVCVXZV',
score: 5,
title: '',
text: 'Like it.',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOEm5Lp0tQQWG7_GdEhnJ3sOwwizRJCymDk5it2fLBVPi3R04GxHsKkPLJQume5UIThfREBQzOu3ggAaQ4w',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'November 9, 2015',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRW01THAwdFFRV0c3X0dkRWhuSjNzT3d3aXpSSkN5bURrNWl0MmZMQlZQaTNSMDRHeEhzS2tQTEpRdW1lNVVJVGhmUkVCUXpPdTNnZ0FhUTR3',
score: 5,
title: 'Great',
text: 'Great Loved the new design.. Also now it doesn\'t take forever to load.. I hope offline compatibility is added soon... Also if links in Daily fix load in the background automatically on opening it makes the entire experience even more fluid.. I hope this is applied inn your future updates.. Good going!!!',
replyDate: 'November 10, 2015',
replyText: 'Thanks a lot Babar! We\'re extremely glad you liked the new update. We\'re working to add Saved articles in subsequent updates. We\'ll see what we can do about the Daily Fix links. Have a great day.' },
{ id: 'gp:AOqpTOEErtTsdwfroCiUtnBBELx9Y9K8OVM5sTqOQCbe0_QHjByM01aWTQAGENGls1GR9eVMi4U0ra0yUR1bKy8',
userName: 'max x',
userImage: 'https://lh5.googleusercontent.com/-nKkdkCva5uQ/AAAAAAAAAAI/AAAAAAAAAAA/ACevoQP48yLMGK8dXmuoLpgICNf5oDFmAA/w96-h96-p/photo.jpg',
date: 'May 2, 2017',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRUVydFRzZHdmcm9DaVV0bkJCRUx4OVk5SzhPVk01c1RxT1FDYmUwX1FIakJ5TTAxYVdUUUFHRU5HbHMxR1I5ZVZNaTRVMHJhMHlVUjFiS3k4',
score: 5,
title: '',
text: 'Unbiased news unlike today media',
replyDate: undefined,
replyText: undefined },
{ id: 'gp:AOqpTOEoWtO_0zMuYBNwJwIS9_tm1cubykU_53ZCFDFNPvNIpX0p1HjUlGp689Tc2jSngXWxhr3JLeAHAUB2dcI',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'November 12, 2015',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRW9XdE9fMHpNdVlCTndKd0lTOV90bTFjdWJ5a1VfNTNaQ0ZERk5Qdk5JcFgwcDFIalVsR3A2ODlUYzJqU25nWFd4aHIzSkxlQUhBVUIyZGNJ',
score: 5,
title: 'Great App',
text: 'Great App Very informative',
replyDate: 'November 13, 2015',
replyText: 'Thanks for the feedback Navdeep. We\'re happy you like the app!' },
{ id: '<KEY>',
userName: 'A Google User',
userImage: 'https://lh3.ggpht.com/EGemoI2NTXmTsBVtJqk8jxF9rh8ApRWfsIMQSt2uE4OcpQqbFu7f7NbTK05lx80nuSijCz7sc3a277R67g=w96-h96-p',
date: 'May 27, 2015',
url: 'https://play.google.com/store/apps/details?id=in.scroll.android&reviewId=Z3A6QU9xcFRPRl9aSVRwc3c1LWExb1E1Ri1SdklIYmowWnV3eV9FbGcxckNRcENOVXR3OXlSaE5TeEZxQjZTT2ducmZTeDZEVTRSZ0dmWTRLTm1Oc0tQdkkw',
score: 5,
title: 'Real stuff!!',
text: 'Real stuff!! No fake !! Not paid media!! Great job guys!!!',
replyDate: undefined,
replyText: undefined } ]');
console.log(json.toString()); | e7b6d36980bd4fa1da596dc34ce1459715392773 | [
"JavaScript"
]
| 3 | JavaScript | nanavatisneha/indian_news_app_review | fef0951ebb495217b9fcaf814de67bfc86de0fe8 | 9b4f647d0d090adecb84b412dae09fc5d58b993d |
refs/heads/master | <file_sep>require "stat_scraper/version"
module StatScraper
class Error < StandardError; end
# Your code goes here...
end
| be91ad0ffc1d7d226156cb0bb5ae9082e9fa8481 | [
"Ruby"
]
| 1 | Ruby | legomyrego/learn-co-sandbox | ec344a96ef1ba0e91795447e1aa899cb682fb148 | fac165d6b29ed5bf067a1731dba8ff235e610729 |
refs/heads/master | <file_sep>[](https://components.studio/edit/YqSjex925s7Qm0dpv69L)
# Engage Component - Button
> Created with [Components.studio](https://components.studio)
<file_sep>import React from "react";
export default class MyCounter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
console.log("here");
}
increment() {
this.setState({ count: this.state.count + 1 });
this.props.handler({ yo: "yo" });
}
decrement() {
this.setState({ count: this.state.count - 1 });
this.props.handler({ yo: "yo" });
}
render() {
const styles = `.my-counter * {
font-size: 200%;
}
.my-counter span {
width: 4rem;
display: inline-block;
text-align: center;
}
.my-counter button {
width: 4rem;
height: 4rem;
border: none;
border-radius: 5px;
background-color: steelblue;
color: white;
}`;
return (
<div className="my-counter">
<style>{styles}</style>
<button onClick={() => this.decrement()}>-</button>
<span>{this.state.count}</span>
<button onClick={() => this.increment()}>+</button>
</div>
);
}
}
<file_sep>import React from "react";
import MyCounter from "./index.js";
export default {
parameters: {
layout: "centered",
},
};
function handler(ev) {
console.log(ev);
}
export const story1 = () => <MyCounter handler={handler}></MyCounter>;
| 2a123dfa1554f200678acdd5217413f56370c9e3 | [
"Markdown",
"JavaScript"
]
| 3 | Markdown | gschleic/reactcso-kdhkp6g8-fork-kdhkqlhf | 465cd763ccd6d7f6849627c46fb7d9973ec1f379 | 59ec23a34c9a644afb913079b00a8e3733d5b6a3 |
refs/heads/master | <file_sep>import time
def monitor_process_progress(status_queue,progress_callback):
current_progress=0
while current_progress<100:
print('asd')
if not status_queue.empty():
current_progress=status_queue.get()
progress_callback.emit(current_progress)
# if isinstance(current_progress,int):
# progress_callback.emit(current_progress)
# else:
# progress_callback.emit(str(current_progress[1]))
# return
if not isinstance(current_progress,int) or current_progress==100:
return
time.sleep(2)
progress_callback.emit(100)<file_sep>import os
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
#from ui.qtsrc.main_window import Ui_MainWindow
from ui.qtsrc.mainWindows_compact import Ui_MainWindow
from PyQt5.QtWidgets import QFileDialog
import time
class UiWrapper(Ui_MainWindow):
# def __init__(self):
# pass
def connect_ui_signals(self):
self.books_radio.clicked.connect(self.slot_books_radio_clicked)
self.songs_radio.clicked.connect(self.slot_songs_radio_clicked)
self.browse_input_button.clicked.connect(self.slot_browse_input_button_clicked)
self.browse_output_button.clicked.connect(self.slot_browse_output_button_clicked)
def slot_browse_input_button_clicked(self):
file_chosen, _ = QFileDialog.getOpenFileName(self, 'Select input file')
if file_chosen != "":
self.input_path_label.setText(file_chosen)
def slot_browse_output_button_clicked(self):
file_chosen = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
if file_chosen != "":
self.output_path_label.setText(file_chosen)
def slot_books_radio_clicked(self):
self.booksUi()
def slot_songs_radio_clicked(self):
self.songsUi()
def booksUi(self):
_translate = QtCore.QCoreApplication.translate
# self.attribute_checkBox_1.setText(_translate("MainWindow", self.widget_titles['books']['attributes'][0]))
# self.attribute_checkBox_2.setText(_translate("MainWindow", self.widget_titles['books']['attributes'][1]))
# self.attribute_checkBox_3.setText(_translate("MainWindow", self.widget_titles['books']['attributes'][2]))
# self.attribute_checkBox_4.setText(_translate("MainWindow", self.widget_titles['books']['attributes'][3]))
self.source_checkBox_1.setText(_translate("MainWindow", self.widget_titles['books']['sources'][0]))
self.source_checkBox_2.setVisible(False)
#self.source_checkBox_2.setText(_translate("MainWindow", self.widget_titles['books']['sources'][1]))
def songsUi(self):
_translate = QtCore.QCoreApplication.translate
# self.attribute_checkBox_1.setText(_translate("MainWindow", self.widget_titles['songs']['attributes'][0]))
# self.attribute_checkBox_2.setText(_translate("MainWindow", self.widget_titles['songs']['attributes'][1]))
# self.attribute_checkBox_3.setText(_translate("MainWindow", self.widget_titles['songs']['attributes'][2]))
# self.attribute_checkBox_4.setText(_translate("MainWindow", self.widget_titles['songs']['attributes'][3]))
self.source_checkBox_1.setText(_translate("MainWindow", self.widget_titles['songs']['sources'][0]))
self.source_checkBox_2.setVisible(True)
self.source_checkBox_2.setText(_translate("MainWindow", self.widget_titles['songs']['sources'][1]))
def update_progress_bar(self,percentage):
self.progressBar.setValue(percentage)
def set_button_group(self):
self.type_button_group = QtWidgets.QButtonGroup()
self.type_button_group.addButton(self.books_radio,0)
self.type_button_group.addButton(self.songs_radio,1)
self.source_button_group = QtWidgets.QButtonGroup()
self.source_button_group.addButton(self.source_checkBox_1, 0)
self.source_button_group.addButton(self.source_checkBox_2, 1)
self.attribute_button_group = QtWidgets.QButtonGroup()
# self.attribute_button_group.addButton(self.attribute_checkBox_1, 0)
# self.attribute_button_group.addButton(self.attribute_checkBox_2, 1)
# self.attribute_button_group.addButton(self.attribute_checkBox_3, 2)
# self.attribute_button_group.addButton(self.attribute_checkBox_4, 3)
def initialize_widget_values(self):
self.progressBar.setValue(0)
def initialize_Ui(self):
self.widget_titles={
'songs':{
'sources':['Youtube','Last.fm'],
'attributes':['View/Play Count', 'Duration', 'Thumbs Up','Thumbs Down']
},
'books': {
'sources': ['Amazon', 'Google Books'],
'attributes': ['Paper Copy Price', 'Paper Price Variance', 'Electronic Copy Price', 'Electronic Price Variance']
}
}
self.cwd=os.getcwd()
self.setupUi(self)
self.initialize_widget_values()
self.connect_ui_signals()
self.songs_radio.setChecked(True)
self.songsUi()
self.current_color=[80,0,0]
def apply_current_color(self):
for c_pos in range(len(self.current_color)):
if self.current_color[c_pos] >= 255:
self.current_color[c_pos] = 253
elif self.current_color[c_pos] < 0:
self.current_color[c_pos] = 0
self.left_frame.setStyleSheet("background-color: rgb(" + str(int(self.current_color[0])) + ", " + str(
int(self.current_color[1])) + ", " + str(int(self.current_color[2])) + ")")
def change_color(self,target_color,progress_callback):
steps=10
dr=(target_color[0]-self.current_color[0])/steps
dg=(target_color[1]-self.current_color[1])/steps
db=(target_color[2]-self.current_color[2])/steps
for i in range(steps):
self.current_color[0]+=dr
self.current_color[1]+=dg
self.current_color[2]+=db
self.apply_current_color()
time.sleep(0.05)
# breathing_steps=30
# try:
# while breathing and control_flag[0]:
# delta_brightness=2
# for i in range(breathing_steps):
# self.current_color[0]+=delta_brightness
# self.current_color[1]+=delta_brightness
# self.current_color[2]+=delta_brightness
# self.apply_current_color()
# time.sleep(0.1)
# delta_brightness=-1
# for i in range(breathing_steps):
# self.current_color[0] += delta_brightness
# self.current_color[1] += delta_brightness
# self.current_color[2] += delta_brightness
# self.apply_current_color()
# time.sleep(0.1)
# except Exception as e:
# print(e)<file_sep># Law-School-Copyright
This repository is owned by Team RightAfterDeadline at Texas A&M University
Instructor: Dr. Walker
Team Member: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
Welcome to the Law-School-Copyright wiki!
### Dependencies:
`pip install requests-cache`
`pip install pandas`
`pip install xlrd`
`pip install PyQt5`
`pip install google_auth_oauthlib`
`pip install google-api-python-client`
`pip install openpyxl`
`pip install scrapy`
`pip install xlsxwriter`<file_sep>import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import pickle
import urllib
import requests
import os
import json
import re
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
# Converts youtube's PT time to a default colon seperated form
def _js_parseInt(string):
return str(''.join([x for x in string if x.isdigit()]))
def formatTime(duration):
match = re.match('PT(\d+H)?(\d+M)?(\d+S)?', duration).groups()
hours = _js_parseInt(match[0]) if match[0] else str(0)
minutes = _js_parseInt(match[1]) if match[1] else str(0)
seconds = _js_parseInt(match[2]) if match[2] else str(0)
if hours == str(0):
return minutes + ":" + seconds
else:
return hours + ":" + minutes + ":" + seconds
# Gets the views, duration, likes, and dislikes from a video.
# Performs a YT api call which uses about 5 units per request
# Called onto every video
def get_video_stats(youtube, vidId, key):
# Two different requests
req1 = youtube.videos().list(part='snippet,contentDetails', id=vidId)
res1 = req1.execute()
# https://www.googleapis.com/youtube/v3/videos?part=statistics&id=IDIDID&key=KEYKEYKEY&part=contentDetails
req2 = urllib.request.urlopen("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" + vidId + "&key=" + key + "&part=contentDetails")
res2 = json.load(req2)
# Set values
duration = res1['items'][0]['contentDetails']['duration']
views = res2['items'][0]['statistics']['viewCount']
dislikes = None; likes = None
try:
if res2['items'][0]['statistics']['dislikeCount']:
dislikes = res2['items'][0]['statistics']['dislikeCount']
except KeyError:
dislikes = None
try:
if res2['items'][0]['statistics']['likeCount']:
likes = res2['items'][0]['statistics']['likeCount']
except KeyError:
likes = None
return (views, duration, likes, dislikes)
# Grabs/gets the credentials in order to use the YT api
# There should be a pickle file which does this automatically
def get_credentials():
if os.path.exists("api_keys/yt_picklefile"):
with open("api_keys/yt_picklefile", 'rb') as f:
credentials = pickle.load(f)
else:
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file("api_keys/yt_secret.json", ["https://www.googleapis.com/auth/youtube.force-ssl"])
credentials = flow.run_console()
with open("api_keys/yt_picklefile", 'wb') as f:
pickle.dump(credentials, f)
return credentials
# Fill the dataframe here after querying YT results
# There's a good chance you'll hit the quota right now
# If there's a error, save whatever has been scraped
def process_dataframe(df,current_finished_count,total_records,progress_callback):
try:
# Sets up youtube API portion here
youtube = googleapiclient.discovery.build("youtube", "v3", credentials=get_credentials())
index=0
# Get key
f = open("api_keys/yt_apikey", "r")
apikey = f.read()
f.close()
for i in df.index:
# Get video ID of top result
#print(df)
query = df['title'][i] + " " + df['artist'][i]
request = youtube.search().list(part="snippet", maxResults=3, q=query)
response = request.execute()
print(query)
# Get top 3 results
vidId1 = response['items'][0]['id']['videoId']
stats1 = get_video_stats(youtube, vidId1, apikey)
df.at[i,'Title 1'] = response['items'][0]['snippet']['title']
df.at[i,'videoID 1'] = response['items'][0]['id']['videoId']
df.at[i,'Views 1'] = stats1[0]
df.at[i,'Duration 1'] = formatTime(stats1[1])
df.at[i,'ikeCount 1'] = stats1[2]
df.at[i,'dilikeCount 1'] = stats1[3]
vidId2 = response['items'][1]['id']['videoId']
stats2 = get_video_stats(youtube, vidId2, apikey)
df.at[i,'Title 2'] = response['items'][1]['snippet']['title']
df.at[i,'videoID 2'] = response['items'][1]['id']['videoId']
df.at[i,'Views 2'] = stats2[0]
df.at[i,'Duration 2'] = formatTime(stats2[1])
df.at[i,'ikeCount 2'] = stats2[2]
df.at[i,'dilikeCount 2'] = stats2[3]
vidId3 = response['items'][2]['id']['videoId']
stats3 = get_video_stats(youtube, vidId3, apikey)
df.at[i,'Title 3'] = response['items'][2]['snippet']['title']
df.at[i,'videoID 3'] = response['items'][2]['id']['videoId']
df.at[i,'Views 3'] = stats3[0]
df.at[i,'Duration 3'] = formatTime(stats3[1])
df.at[i,'ikeCount 3'] = stats3[2]
df.at[i,'dilikeCount 3'] = stats3[3]
index+=1
progress_callback.emit(int(100 * (index+current_finished_count) / total_records))
except Exception as e: print(e)
return df
# Takes a dictionary where keys are sheet names (Excel file)
# Values are pandas dataframes
def get_youtube_data(sheets,output_path, progress_callback):
i=0
total_records=0
for sheet_name in sheets:
total_records+=sheets[sheet_name].shape[0]
writer = pd.ExcelWriter(os.path.join(output_path, 'youtube_output.xlsx'), engine='xlsxwriter')
current_finished_count=0
for key, value in sheets.items():
#sheets[key] = process_dataframe(value)
process_dataframe(value,current_finished_count,total_records,progress_callback).to_excel(writer, sheet_name=key)
current_finished_count+=value.shape[0]
progress_callback.emit(int((i+1)*100/len(sheets)))
i+=1
writer.save()
progress_callback.emit(100)
return sheets
<file_sep>import requests
import json
import pandas as pd
import xlsxwriter
import time
import os
def load_data_from_excel(csv_input):
request_query = []
req = {}
data = pd.read_excel(r''+csv_input)
if 'Title' in data and 'Artist' in data:
data = data.rename(columns={'Title': 'title', 'Artist': 'artist'})
df = pd.DataFrame(data, columns=['title', 'artist'])
# print(df)
for index, row in df.iterrows():
req['method'] = 'track.getInfo'
req['autocorrect'] = 1
req['track'] = row['title'][1:-1]
req['artist'] = row['artist']
request_query.append(req)
req = {}
return request_query
def convert(millis):
# millis = int(millis)
seconds = (millis / 1000) % 60
seconds = int(seconds)
minutes = (millis / (1000 * 60)) % 60
minutes = int(minutes)
# hours = (millis / (1000 * 60 * 60)) % 24
return ("%02d:%02d" % (minutes, seconds))
# seconds = seconds % (24 * 3600)
# hour = seconds // 3600
# seconds %= 3600
# minutes = seconds // 60
# seconds %= 60
# return "%d:%02d:%02d" % (hour, minutes, seconds)
def count_listeners(data_json):
# print(jprint(data_json))
out_p = {}
if 'track' in data_json:
count = data_json['track']['playcount']
listener = data_json['track']['listeners']
duration = convert(int(data_json['track']['duration']))
# for each in data_json['track']['playcount']['track']:
# count = count + int(each['listeners'])
# # print(each['listeners'], each['name'])
# print('count is', count, "listener is", listener, 'duration is', duration)
out_p['playcount'] = int(count)
out_p['listeners'] = int(listener)
out_p['duration'] = duration
else:
# print("not found")
out_p['playcount'] = -1
out_p['listeners'] = -1
out_p['duration'] = -1
return out_p
def lastfm_get(payload):
ys = 'ca791ebdea3b7ba81ff4bd70cff59124423'
ys=ys[1:-2]
USER_AGENT = 'law-school-copyright'
# define headers and URL
headers = {'user-agent': USER_AGENT}
url = 'http://ws.audioscrobbler.com/2.0/'
# Add API key and format to the payload
payload['api_key'] = ys
payload['format'] = 'json'
response = requests.get(url, headers=headers, params=payload)
# print(payload['artist'], payload['track'])
text = response.json()
out_dict = count_listeners(text)
return out_dict
def jprint(obj):
# create a formatted string of the Python JSON object
text = json.dumps(obj, sort_keys=True, indent=4)
return text
def perform_last_fm(data, current_finished_count,total_records):
if 'Title' in data and 'Artist' in data:
data = data.rename(columns={'Title': 'title', 'Artist': 'artist'})
df = pd.DataFrame(data, columns=['title', 'artist'])
# print(df)
request_query = []
req = {}
for index, row in df.iterrows():
req['method'] = 'track.getInfo'
req['autocorrect'] = 1
# print('track,', row['title'])
req['track'] = row['title'][1:-1]
req['artist'] = row['artist']
request_query.append(req)
req = {}
out_query = []
out_dict = {}
i = 0
for each in request_query:
out_dict['artist'] = each['artist']
out_dict['track'] = each['track']
# print(each)
max_retry=10
current_retry=0
is_api_success=False
while not is_api_success and current_retry<max_retry:
is_api_success=True
try:
api_result=lastfm_get(each)
except Exception as e:
print(e)
is_api_success=False
time.sleep(1)
current_retry+=1
out_dict.update(api_result)
out_query.append(out_dict)
out_dict = {}
i += 1
# print(out_query)
out_df = pd.DataFrame(out_query)
# print(out_df)
# print(out_df.dtypes)
for index, row in out_df.iterrows():
if row['playcount'] == -1:
print(row)
return out_df
def perform_last_fm_s(data):
#1/0
out_put = {}
total_records = 0
for sheet_name in data:
total_records+=data[sheet_name].shape[0]
writer = pd.ExcelWriter(os.path.join('new_', 'last_fm_output.xlsx'), engine='xlsxwriter')
current_finished_count=0
for each in data:
# print(data[each])
out_df = (perform_last_fm(data[each],current_finished_count,total_records))
out_df.to_excel(writer, sheet_name=each)
current_finished_count+=data[each].shape[0]
writer.save()
return 'Finished'
asd = {
# 'method': 'artist.getTopTags',
# 'artist': 'The Beach Boys'
'method': 'track.getInfo',
'autocorrect': 1,
'track': "Señorita",
'artist': '<NAME> and <NAME>'}
dsa = {
# 'method': 'artist.getTopTags',
# 'artist': 'The Beach Boys'
'method': 'track.getInfo',
'autocorrect': 1,
'track': "Let It Be Me",
'artist': '<NAME>'}
# intake is a dict
#
# aasd = [asd, dsa]
# for each in aasd:
# # print(each)
# if '&' in each['artist']:
# # each['duplicate'] = each['artist']
# print(each['artist'][0:each['artist'].find("&")-1])
# print(each['artist'][each['artist'].find('&')+2:])
# # print(lastfm_get(each))
# print()
if 'and' in asd['artist']:
print(asd['artist'].find('and'))
<file_sep>from PyQt5.QtWidgets import *
from controller import controller
import sys
import scrapy
from scrapy import signals
from scrapy.crawler import CrawlerProcess
import traceback, sys
import multiprocessing
if __name__ == "__main__":
multiprocessing.freeze_support()
app = QApplication(sys.argv)
main_window = controller()
main_window.show()
sys.exit(app.exec_())<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainWindows.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 400)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/resources/images/icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.left_frame = QtWidgets.QFrame(self.centralwidget)
self.left_frame.setGeometry(QtCore.QRect(-1, -1, 201, 501))
self.left_frame.setStyleSheet("background-color: rgb(80, 0, 0);")
self.left_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.left_frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.left_frame.setObjectName("left_frame")
self.title_label = QtWidgets.QLabel(self.left_frame)
self.title_label.setGeometry(QtCore.QRect(10, 20, 181, 41))
self.title_label.setStyleSheet("font: 25 22pt \"Segoe UI Light\";")
self.title_label.setObjectName("title_label")
self.title_line = QtWidgets.QLabel(self.left_frame)
self.title_line.setGeometry(QtCore.QRect(10, 40, 181, 31))
self.title_line.setObjectName("title_line")
self.type_group = QtWidgets.QGroupBox(self.left_frame)
self.type_group.setGeometry(QtCore.QRect(30, 90, 151, 111))
self.type_group.setStyleSheet("font: 25 10pt \"Segoe UI Light\";\n"
"color:rgb(255,255,255);")
self.type_group.setObjectName("type_group")
self.books_radio = QtWidgets.QRadioButton(self.type_group)
self.books_radio.setGeometry(QtCore.QRect(30, 70, 82, 21))
self.books_radio.setStyleSheet("font: 25 12pt \"Segoe UI Light\";\n"
"color:rgb(255,255,255);")
self.books_radio.setObjectName("books_radio")
self.songs_radio = QtWidgets.QRadioButton(self.type_group)
self.songs_radio.setGeometry(QtCore.QRect(30, 30, 111, 21))
self.songs_radio.setStyleSheet("font: 25 12pt \"Segoe UI Light\";\n"
"color:rgb(255,255,255);")
self.songs_radio.setObjectName("songs_radio")
self.title_line.raise_()
self.title_label.raise_()
self.type_group.raise_()
self.right_frame = QtWidgets.QFrame(self.centralwidget)
self.right_frame.setGeometry(QtCore.QRect(199, -1, 601, 501))
self.right_frame.setStyleSheet("background-color: rgb(214, 210, 196);")
self.right_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.right_frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.right_frame.setObjectName("right_frame")
self.io_title_label = QtWidgets.QLabel(self.right_frame)
self.io_title_label.setGeometry(QtCore.QRect(30, 30, 91, 21))
self.io_title_label.setStyleSheet("font: 10pt \"Segoe UI\";")
self.io_title_label.setObjectName("io_title_label")
self.holine = QtWidgets.QLabel(self.right_frame)
self.holine.setGeometry(QtCore.QRect(30, 40, 561, 20))
self.holine.setObjectName("holine")
self.settings_frame = QtWidgets.QFrame(self.right_frame)
self.settings_frame.setGeometry(QtCore.QRect(0, 120, 611, 181))
self.settings_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.settings_frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.settings_frame.setObjectName("settings_frame")
self.attributes_groupBox = QtWidgets.QGroupBox(self.settings_frame)
self.attributes_groupBox.setGeometry(QtCore.QRect(30, 110, 531, 51))
self.attributes_groupBox.setObjectName("attributes_groupBox")
self.layoutWidget = QtWidgets.QWidget(self.attributes_groupBox)
self.layoutWidget.setGeometry(QtCore.QRect(10, 20, 511, 20))
self.layoutWidget.setObjectName("layoutWidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.layoutWidget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.attribute_checkBox_1 = QtWidgets.QCheckBox(self.layoutWidget)
self.attribute_checkBox_1.setObjectName("attribute_checkBox_1")
self.horizontalLayout.addWidget(self.attribute_checkBox_1)
self.attribute_checkBox_2 = QtWidgets.QCheckBox(self.layoutWidget)
self.attribute_checkBox_2.setObjectName("attribute_checkBox_2")
self.horizontalLayout.addWidget(self.attribute_checkBox_2)
self.attribute_checkBox_3 = QtWidgets.QCheckBox(self.layoutWidget)
self.attribute_checkBox_3.setObjectName("attribute_checkBox_3")
self.horizontalLayout.addWidget(self.attribute_checkBox_3)
self.attribute_checkBox_4 = QtWidgets.QCheckBox(self.layoutWidget)
self.attribute_checkBox_4.setObjectName("attribute_checkBox_4")
self.horizontalLayout.addWidget(self.attribute_checkBox_4)
self.source_groupBox = QtWidgets.QGroupBox(self.settings_frame)
self.source_groupBox.setGeometry(QtCore.QRect(30, 50, 531, 51))
self.source_groupBox.setObjectName("source_groupBox")
self.layoutWidget1 = QtWidgets.QWidget(self.source_groupBox)
self.layoutWidget1.setGeometry(QtCore.QRect(10, 20, 511, 20))
self.layoutWidget1.setObjectName("layoutWidget1")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.layoutWidget1)
self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.source_checkBox_1 = QtWidgets.QCheckBox(self.layoutWidget1)
self.source_checkBox_1.setObjectName("source_checkBox_1")
self.horizontalLayout_2.addWidget(self.source_checkBox_1)
self.source_checkBox_2 = QtWidgets.QCheckBox(self.layoutWidget1)
self.source_checkBox_2.setObjectName("source_checkBox_2")
self.horizontalLayout_2.addWidget(self.source_checkBox_2)
self.settings_title_label = QtWidgets.QLabel(self.settings_frame)
self.settings_title_label.setGeometry(QtCore.QRect(30, 10, 91, 21))
self.settings_title_label.setStyleSheet("font: 10pt \"Segoe UI\";")
self.settings_title_label.setObjectName("settings_title_label")
self.holine2 = QtWidgets.QLabel(self.settings_frame)
self.holine2.setGeometry(QtCore.QRect(30, 20, 561, 20))
self.holine2.setObjectName("holine2")
self.holine2.raise_()
self.attributes_groupBox.raise_()
self.source_groupBox.raise_()
self.settings_title_label.raise_()
self.input_path_label = QtWidgets.QLabel(self.right_frame)
self.input_path_label.setGeometry(QtCore.QRect(60, 70, 391, 16))
self.input_path_label.setObjectName("input_path_label")
self.browse_input_button = QtWidgets.QPushButton(self.right_frame)
self.browse_input_button.setGeometry(QtCore.QRect(470, 70, 75, 23))
self.browse_input_button.setStyleSheet("background-color: rgb(255, 255, 255);")
self.browse_input_button.setObjectName("browse_input_button")
self.start_button = QtWidgets.QPushButton(self.right_frame)
self.start_button.setGeometry(QtCore.QRect(420, 320, 75, 23))
self.start_button.setStyleSheet("background-color: rgb(255, 255, 255);")
self.start_button.setObjectName("start_button")
self.progressBar = QtWidgets.QProgressBar(self.right_frame)
self.progressBar.setGeometry(QtCore.QRect(60, 320, 331, 23))
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName("progressBar")
self.output_path_label = QtWidgets.QLabel(self.right_frame)
self.output_path_label.setGeometry(QtCore.QRect(60, 100, 391, 16))
self.output_path_label.setObjectName("output_path_label")
self.browse_output_button = QtWidgets.QPushButton(self.right_frame)
self.browse_output_button.setGeometry(QtCore.QRect(470, 100, 75, 23))
self.browse_output_button.setStyleSheet("background-color: rgb(255, 255, 255);")
self.browse_output_button.setObjectName("browse_output_button")
self.holine.raise_()
self.io_title_label.raise_()
self.settings_frame.raise_()
self.input_path_label.raise_()
self.browse_input_button.raise_()
self.start_button.raise_()
self.progressBar.raise_()
self.output_path_label.raise_()
self.browse_output_button.raise_()
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Data Scraper"))
self.title_label.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" color:#ffffff;\">Data Scraper</span></p></body></html>"))
self.title_line.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:18pt; font-weight:600; color:#ffffff;\">_________________</span></p></body></html>"))
self.type_group.setTitle(_translate("MainWindow", "Type"))
self.books_radio.setText(_translate("MainWindow", "Books"))
self.songs_radio.setText(_translate("MainWindow", "Songs"))
self.io_title_label.setText(_translate("MainWindow", "Input/Output"))
self.holine.setText(_translate("MainWindow", "__________________________________________________________________________________________"))
self.attributes_groupBox.setTitle(_translate("MainWindow", "Scraping Attributes"))
self.attribute_checkBox_1.setText(_translate("MainWindow", "View/Play Count"))
self.attribute_checkBox_2.setText(_translate("MainWindow", "Duration"))
self.attribute_checkBox_3.setText(_translate("MainWindow", "Thumbs Up"))
self.attribute_checkBox_4.setText(_translate("MainWindow", "Thumbs Down"))
self.source_groupBox.setTitle(_translate("MainWindow", "Scraping Source"))
self.source_checkBox_1.setText(_translate("MainWindow", "Youtube"))
self.source_checkBox_2.setText(_translate("MainWindow", "Spotify"))
self.settings_title_label.setText(_translate("MainWindow", "Settings"))
self.holine2.setText(_translate("MainWindow", "__________________________________________________________________________________________"))
self.input_path_label.setText(_translate("MainWindow", "Please select input xlsx file..."))
self.browse_input_button.setText(_translate("MainWindow", "Browse.."))
self.start_button.setText(_translate("MainWindow", "Start"))
self.output_path_label.setText(_translate("MainWindow", "Please select output directory..."))
self.browse_output_button.setText(_translate("MainWindow", "Browse.."))
import ui.qtsrc.resources_rc
<file_sep>import scrapy
# from amazonscrap.items import AmazonscrapItem
from scrapy import signals
from scrapy.crawler import CrawlerProcess
import pandas as pd
# to run : scrapy crawl book-scraper
import traceback, sys
import time
class BooksSpider(scrapy.Spider):
name = "book-scraper"
def start_requests(self):
search_base_p1 = 'https://www.amazon.com/s?k='
search_base_p2 = '&i=stripbooks&ref=nb_sb_noss_2'
self.search_base_p1=search_base_p1
self.search_base_p2=search_base_p2
book_names = []
book_ranks=[]
df=current_df[0]
if 'title' in df.columns:
book_names=df['title'].str.replace('\xa0','').tolist()
elif 'Title' in df.columns:
book_names=df['Title'].str.replace('\xa0','').tolist()
if 'rank' in df.columns:
book_ranks=df['rank'].tolist()
elif 'Rank' in df.columns:
book_ranks=df['Rank'].tolist()
print(book_names)
# book_names=['Pride and Prejudice', '<NAME>', 'The Picture of Dorian Gray', 'Wuthering Heights', 'Crime and Punishment',
# 'Frankenstein', 'The Count of Monte Cristo', "Alice's Adventures in Wonderland & Through the Looking-Glass",
# 'Dracula', 'Les Misérables']
# #legacy code
# book_names = ['What Every BODY Is Saying: An Ex-FBI Agent’s Guide to Speed-Reading People',
# 'Louder Than Words: Take Your Career from Average to Exceptional with the Hidden Power of Nonverbal Intelligence']
#for names in book_names:
for pos in range(len(book_names)):
names=book_names[pos]
rank=book_ranks[pos]
if len(names)==0:
continue
print(search_base_p1 + names + search_base_p2)
yield scrapy.Request(url=search_base_p1 + names.replace(' ','%20') + search_base_p2, callback=self.parse,cb_kwargs={'current_book':names,'current_rank':rank})
def parse(self, response, current_book,current_rank):
i=0
#print('##'+current_book)
while True:
if i>20:
print('============================================\nPlease check book name and search again\n',i)
scrape_result[current_book] = {'Rank':current_rank}
return 0
print('___________searching','data-index="'+str(i))
search_label = 'data-index="'+str(i)+'"'
book_link = response.css('div['+search_label+']')
sponsored_book = book_link.css('div[class="a-row a-spacing-micro"]').get()
book_link = book_link.css('a[class="a-link-normal a-text-normal"]')
if book_link.get() is not None and sponsored_book is None:
found_book_name = book_link.css('span[class="a-size-medium a-color-base a-text-normal"]').get()
if found_book_name:
found_book_name_s = found_book_name.find('>')
found_book_name_e = found_book_name.find('<', found_book_name_s+1)
found_book_name = found_book_name[found_book_name_s+1:found_book_name_e]
print('found book_________________________',i,found_book_name)
break
i+=1
sponsored_book = None
i=0
book_link = book_link.get()
link_pos = book_link.find('href')
link_start = book_link.find('"',link_pos+1)
link_end = book_link.find('"',link_start+1)
book_page = book_link[link_start+1:link_end]
base_link = "https://www.amazon.com/"
book_page = base_link + book_page
yield scrapy.Request(book_page, callback=self.parse_book, cb_kwargs={'current_book':current_book,'current_rank':current_rank})
def parse_book(self, response, current_book,current_rank):
print('@@@'+response.url)
book = {}
title = response.css('span[class="a-size-extra-large"]::text').get()
if title == None:
title = response.css('title::text')[0].get()
title = title.lstrip()
title = title.rstrip()
# prices = response.css('[class="a-unordered-list a-nostyle a-button-list a-horizontal"]')
prices = response.css('a[class="a-button-text"]')
all_prices = {}
for p in prices:
if '$' in p.get():
book_type = p.css('span::text').get()
bt = ''
for c in book_type:
if c not in [' ','\n']:
bt += c
book_type = bt
html_data = p.get()
price_idx = html_data.find('$')
price = html_data[price_idx:html_data.find('<',price_idx)]
price = price[:price.find('\n')]
all_prices[book_type] = price
# # Commented out due to incorrect behavior, please validate this part.
# if len(all_prices)==0:
# new_url = response.url
# new_url_change_pos = new_url.find('com')
# new_url = new_url[0:new_url_change_pos]+'in'+new_url[new_url_change_pos+3:]
# yield scrapy.Request(new_url, callback=self.parse_book, cb_kwargs={'current_book':current_book})
else:
print('====================================\n',title,'\n',all_prices)
print('====================================')
all_prices['BookNameFound']=title
all_prices['rank']=current_rank
scrape_result[current_book] = all_prices
return book
@staticmethod
def get_book_id(response):
url = response.request.url
url = url.split("/")
return url[-2]
def spider_opened(self):
print("\n\n\nSpider Opened")
print(self.start_urls)
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = super(BooksSpider, cls).from_crawler(crawler, *args, **kwargs)
crawler.signals.connect(spider.spider_opened, signal=signals.spider_opened)
return spider
@staticmethod
def escape(text):
text = text.replace("'","''")
return text
current_df=[]
scrape_result={}
def start_crawler(df_dict, output_path,progress_queue):
print('asd')
progress_queue.put(1)
tmp_r=[k for k in scrape_result]
for key in tmp_r: del scrape_result[key]
while len(current_df)>0:
current_df.pop()
print(df_dict)
writer = pd.ExcelWriter(output_path+'/amazonoutput.xlsx', engine='xlsxwriter')
sheet_i=0
for sheet_name in df_dict:
if df_dict[sheet_name].shape[0]>0:
try:
current_df.append(df_dict[sheet_name])
process = CrawlerProcess({
'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})
process.crawl(BooksSpider)
process.start() # the script will block here until the crawling is finished
print('##########################')
print(current_df[0].columns)
print(scrape_result)
dfo = pd.DataFrame(index=range(current_df[0].shape[0]),columns=['Title','BookNameFound','Paperback','Audiobook','Hardcover','Kindle'])
i=0
for current_book_name in scrape_result:
rank=int(scrape_result[current_book_name]['rank'])-1
dfo.loc[rank,'Title']=current_book_name
for book_price_type in scrape_result[current_book_name]:
if book_price_type not in dfo.columns:
continue
else:
dfo.loc[rank,book_price_type]=scrape_result[current_book_name][book_price_type].strip().replace('$','')
i+=1
#dfo.to_csv(output_path+'/amzout.csv')
dfo.to_excel(writer, sheet_name=sheet_name)
#clear up
tmp_r=[k for k in scrape_result]
for key in tmp_r: del scrape_result[key]
current_df.pop()
except Exception as e:
print(e)
while not progress_queue.empty():
progress_queue.get()
sheet_i+=1
progress_percentage=int(100*sheet_i/len(df_dict))
if progress_percentage==100:
progress_percentage-=1
progress_queue.put(progress_percentage)
time.sleep(5)
try:
writer.save()
except:
traceback.print_exc()
exctype, value = sys.exc_info()[:2]
while not progress_queue.empty():
progress_queue.get()
progress_queue.put((exctype, value))
while not progress_queue.empty():
progress_queue.get()
#progress_percentage = int(100 * sheet_i / len(df_dict))
progress_queue.put(100)
<file_sep>import pandas as pd
def read_spreadsheet(file_path):
"""
Read given spreadsheet as a dictionary of dataframes
:param file_path: path to spreadsheet (.csv or .xlsx or .xls)
:return: a dictionary of sheets in spreadsheet where key is sheet name and
value is data in that sheet stored as a pandas dataframe
"""
"""
Example returned dictionary:
{'sheet1name': dataframeObject1, 'sheet2name':'dataframeObject2'
"""
if file_path.endswith('csv'):
dftmp = pd.read_csv(file_path)
col_rename = {}
for col_name in dftmp.columns:
col_rename[col_name] = col_name.lower()
dftmp = dftmp.rename(columns=col_rename)
return {'csv':dftmp}
excel_file = pd.ExcelFile(file_path)
result = {}
for sheet_name in excel_file.sheet_names:
dftmp = pd.read_excel(excel_file, sheet_name)
col_rename = {}
for col_name in dftmp.columns:
col_rename[col_name] = col_name.lower()
dftmp = dftmp.rename(columns=col_rename)
result[sheet_name] = dftmp
return result
<file_sep>import requests
import json
class spotifyAPI:
def __init__(self):
self.creds = {
'client_id': 'f4027d8eec9f4f5c9b9febfdb0a0f87b',
'client_secret': '584c419c5fce45798e504ee8ce0b9969',
'grant_type': 'client_credentials',
}
self.tokenURL = 'https://accounts.spotify.com/api/token'
self.token = ''
self.refreshToken()
self.searchURL = 'https://api.spotify.com/v1/search'
self.lastQuery = ''
self.lastResult = ''
#access token expires after 3600 seconds, or one hour.
def refreshToken(self):
intermediate = requests.post(self.tokenURL, data=self.creds)
self.token = intermediate.json()['access_token']
def query(self,queryString):
self.lastQuery = queryString
self.lastResult = requests.get(
self.searchURL,
headers={ 'Authorization': 'Bearer ' + self.token },
params={ 'q': queryString, 'type': 'track' }
)
#Below is for testing only
#myAPI = spotifyAPI()
#myAPI.query('Take me home, Country Roads')
#print(myAPI.lastResult.json())
#Below is trash old code used for debugging
#creds = {
# 'client_id': 'f4027d8eec9f4f5c9b9febfdb0a0f87b',
# 'client_secret': '584c419c5fce45798e504ee8ce0b9969',
# 'grant_type': 'client_credentials',
#}
#
#url = 'https://accounts.spotify.com/api/token'
#
#x = requests.post(url, data=creds)
#
#aut = x.json()['access_token']
#
#searchUrl = "https://api.spotify.com/v1/search"
#
#x2 = requests.get(
# searchUrl,
# headers={ 'Authorization': 'Bearer ' + aut },
# params={ 'q': 'Take me home, country roads', 'type': 'track', 'artist': '<NAME>' })
#print(x2)
#print(x2.text)
#print('8')
#print(x2.json())<file_sep># Application name law-school-copyright
# API key <KEY>
# Shared secret b3efda8cad1b0041281caffe3430a0c9
# Registered to law-school-copy
# To use this, please supply a csv file and then run it
# please pip install xlrd, pandas, requests-cache
import requests
import json
import pandas as pd
import xlsxwriter
import time
import os
def load_data_from_excel(csv_input):
request_query = []
req = {}
data = pd.read_excel(r''+csv_input)
if 'Title' in data and 'Artist' in data:
data = data.rename(columns={'Title': 'title', 'Artist': 'artist'})
df = pd.DataFrame(data, columns=['title', 'artist'])
# print(df)
for index, row in df.iterrows():
req['method'] = 'track.getInfo'
req['autocorrect'] = 1
req['track'] = row['title'][1:-1]
req['artist'] = row['artist']
request_query.append(req)
req = {}
return request_query
def convert(millis):
# millis = int(millis)
seconds = (millis / 1000) % 60
seconds = int(seconds)
minutes = (millis / (1000 * 60)) % 60
minutes = int(minutes)
# hours = (millis / (1000 * 60 * 60)) % 24
return ("%02d:%02d" % (minutes, seconds))
def count_listeners(data_json):
# print(jprint(data_json))
out_p = {}
if 'track' in data_json:
count = data_json['track']['playcount']
listener = data_json['track']['listeners']
duration = convert(int(data_json['track']['duration']))
# for each in data_json['track']['playcount']['track']:
# count = count + int(each['listeners'])
# # print(each['listeners'], each['name'])
# print('count is', count, "listener is", listener, 'duration is', duration)
out_p['playcount'] = int(count)
out_p['listeners'] = int(listener)
out_p['duration'] = duration
else:
# print("not found")
out_p['playcount'] = -1
out_p['listeners'] = -1
out_p['duration'] = -1
return out_p
def lastfm_get(payload):
ys = 'ca791ebdea3b7ba81ff4bd70cff59124423'
ys=ys[1:-2]
USER_AGENT = 'law-school-copyright'
# define headers and URL
headers = {'user-agent': USER_AGENT}
url = 'http://ws.audioscrobbler.com/2.0/'
# Add API key and format to the payload
payload['api_key'] = ys
payload['format'] = 'json'
response = requests.get(url, headers=headers, params=payload)
# print(payload['artist'], payload['track'])
text = response.json()
if 'track' not in text:
if '&' in payload['artist']:
payload['artist'] = payload['artist'][0:payload['artist'].find('&')-1]
if 'and' in payload['artist']:
payload['artist'] = payload['artist'][0:payload['artist'].find('and')-1]
if 'featuring' in payload['artist']:
payload['artist'] = payload['artist'][0:payload['artist'].find('featuring')-1]
response = requests.get(url, headers=headers, params=payload)
text = response.json()
out_dict = count_listeners(text)
return out_dict
def jprint(obj):
# create a formatted string of the Python JSON object
text = json.dumps(obj, sort_keys=True, indent=4)
return text
def perform_last_fm(data, current_finished_count,total_records,progress_callback):
if 'Title' in data and 'Artist' in data:
data = data.rename(columns={'Title': 'title', 'Artist': 'artist'})
df = pd.DataFrame(data, columns=['title', 'artist'])
# print(df)
request_query = []
req = {}
for index, row in df.iterrows():
req['method'] = 'track.getInfo'
req['autocorrect'] = 1
# print('track,', row['title'])
req['track'] = row['title'][1:-1]
req['artist'] = row['artist']
request_query.append(req)
req = {}
out_query = []
out_dict = {}
i = 0
for each in request_query:
if __name__ != "__main__":
progress_callback.emit(int(100 * (i+current_finished_count) / total_records))
out_dict['artist'] = each['artist']
out_dict['track'] = each['track']
# print(each)
max_retry=10
current_retry=0
is_api_success=False
while not is_api_success and current_retry<max_retry:
is_api_success=True
try:
api_result=lastfm_get(each)
except Exception as e:
print(e)
is_api_success=False
time.sleep(1)
current_retry+=1
out_dict.update(api_result)
out_query.append(out_dict)
out_dict = {}
i += 1
# print(out_query)
out_df = pd.DataFrame(out_query)
# print(out_df)
# print(out_df.dtypes)
for index, row in out_df.iterrows():
if row['playcount'] == -1:
print(row)
return out_df
def perform_last_fm_s(data, output_path, progress_callback):
#1/0
out_put = {}
total_records = 0
for sheet_name in data:
total_records+=data[sheet_name].shape[0]
writer = pd.ExcelWriter(os.path.join(output_path,'new_new_last_fm_output.xlsx'), engine='xlsxwriter')
current_finished_count=0
for each in data:
# print(data[each])
out_df = (perform_last_fm(data[each],current_finished_count,total_records, progress_callback))
out_df.to_excel(writer, sheet_name=each)
current_finished_count += data[each].shape[0]
if __name__ != "__main__":
progress_callback.emit(100)
writer.save()
return 'Finished'
#
# asd = {
# # 'method': 'artist.getTopTags',
# # 'artist': 'The Beach Boys'
# 'method': 'track.getInfo',
# 'autocorrect': 1,
# 'track': "The End of the World",
# 'artist': '<NAME>'}
# dsa = {
# # 'method': 'artist.getTopTags',
# # 'artist': 'The Beach Boys'
# 'method': 'track.getInfo',
# 'autocorrect': 1,
# 'track': "Surfin\' U.S.A.",
# 'artist': 'The Beach Boys'}
# # intake is a dict
#
# aasd = [asd, dsa]
# for each in aasd:
# print(each)
# r = lastfm_get(each)
if __name__ == "__main__":
data = pd.read_excel(r'Year-end Hot 100 1963-2019.xlsx', sheet_name=None)
# for each in data:
# print(data[each])
perform_last_fm_s(data)
# perform_last_fm(data)
# request_query = load_data_from_excel()
# for each in request_query:
# print(each)
# r = lastfm_get(each)
# print(jprint(r.json()))
#
# name = text['results']['trackmatches']
# # print(name)
# count = 0
# for each in name['track']:
# count = count + int(each['listeners'])
# print(each['listeners'], each['name'])
# name = text['toptags']['@attr']['artist']
# print(name)
# count = 0
# for each in text['toptags']['tag']:
# print(each)
# count += each['count']
#
<file_sep>from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from ui.qtsrc.ui_wrapper import UiWrapper
from modules.spreadsheet_reader import read_spreadsheet
import sys
import time
import os
from modules.thread_worker import Worker
from yt_scrape.myYT import get_youtube_data
from amazon_books_scrape.amazonscrap.spiders.book_scrapper import start_crawler
#from last_fm.last_fm_main import perform_last_fm_s
from last_fm.last_fm_sup import perform_last_fm_s
from multiprocessing import Process, Queue
import pandas as pd
from modules.process_progress_monitor import monitor_process_progress
class controller(QMainWindow, UiWrapper):
def __init__(self, parent=None):
super(controller, self).__init__(parent)
self.initialize_Ui()
self.connect_logic_signals()
self.threadpool = QThreadPool()
self.is_running_multiple=False
self.percentages=[-1,-1]
#self.color_change_flag=[True]
def connect_logic_signals(self):
self.start_button.clicked.connect(self.slot_start_button_clicked)
def test_func(self,progress_callback):
for i in range(20):
time.sleep(1)
progress_callback.emit((i+1) * 5)
return None
def book_progress_callback(self,info_in):
print(info_in)
if isinstance(info_in,int):
self.update_progress_bar(info_in)
else:
print('bpc',info_in)
QMessageBox.information(self, 'Error', 'Info: ' + str(info_in))
def thread_finished(self):
self.clear_percentage_history()
self.change_color_worker([138, 201, 38])
#time.sleep(1)
QMessageBox.information(self, 'Info', 'Scraping Finished.')
def empty_callback(self):
pass
def clear_percentage_history(self):
self.percentages=[-1,-1]
def update_progress(self,scraper_type,percentage):
if scraper_type=='Youtube':
self.percentages[0]=percentage
elif scraper_type=='Last.fm':
self.percentages[1]=percentage
result=0
count=0
for i in self.percentages:
if i>-1:
result+=i
count+=1
self.update_progress_bar(int(result/count))
def yt_update_progress_bar(self, percentage):
self.update_progress('Youtube',percentage)
def lastfm_update_progress_bar(self, percentage):
self.update_progress('Last.fm',percentage)
def error_pop_up(self,error_info):
print(error_info)
self.change_color_worker([255, 0, 0])
#time.sleep(1)
self.clear_percentage_history()
QMessageBox.warning(self, 'Error', 'Error: '+str(error_info[0])+str(error_info[1]))
def change_color_worker(self,target_color):
#self.color_change_flag[0]=True
worker_color = Worker(self.change_color, target_color)
worker_color.signals.result.connect(self.empty_callback)
worker_color.signals.finished.connect(self.empty_callback)
worker_color.signals.progress.connect(self.empty_callback)
worker_color.signals.error.connect(self.error_pop_up)
self.threadpool.start(worker_color)
def slot_start_button_clicked(self):
# self.change_color_worker([255,159,28])
# return
# df_dict = read_spreadsheet('sample_data\\bk.xlsm')
# progress_queue = Queue()
# p = Process(target=start_crawler, args=(df_dict, 'sample_data', progress_queue))
# p.start()
# print('p')
# worker_monitor = Worker(monitor_process_progress, progress_queue)
# worker_monitor.signals.result.connect(self.empty_callback)
# worker_monitor.signals.finished.connect(self.empty_callback)
# worker_monitor.signals.progress.connect( self.book_progress_callback)
# worker_monitor.signals.error.connect(self.error_pop_up)
# self.threadpool.start(worker_monitor)
# return
# print('Start Clicked')
# df_dict = read_spreadsheet('sample_data\\songs.xlsx')
# worker_fm = Worker(perform_last_fm_s, df_dict,'')
# worker_fm.signals.result.connect(self.empty_callback)
# worker_fm.signals.finished.connect(self.thread_finished)
# worker_fm.signals.progress.connect(self.update_progress_bar)
# worker_fm.signals.error.connect(self.error_pop_up)
# self.threadpool.start(worker_fm)
# return
self.update_progress_bar(0)
ui_input=self.get_all_input_information()
print(ui_input)
if self.validate_input_info(ui_input):
self.change_color_worker([255, 159, 28])
#time.sleep(1)
df_dict=read_spreadsheet(self.get_all_input_information()['input_file_path'])
if ui_input['type']=='books':
#os.system(r'cd amazon_books_scrape\amazonscrap\ & scrapy crawl book-scraper')
#kw={'ttr':'asd', 'progress_callback':}
progress_queue=Queue()
p = Process(target=start_crawler, args=(df_dict, ui_input['output_file_path'],progress_queue))
p.start()
worker_monitor = Worker(monitor_process_progress, progress_queue)
worker_monitor.signals.result.connect(self.empty_callback)
worker_monitor.signals.finished.connect(self.thread_finished)
worker_monitor.signals.progress.connect(self.update_progress_bar)
worker_monitor.signals.error.connect(self.error_pop_up)
self.threadpool.start(worker_monitor)
#self.update_progress_bar(100)
#p.join()
elif ui_input['type']=='songs':
if 'Youtube' in ui_input['sources']:
print('youtube')
worker_yt = Worker(get_youtube_data, df_dict, ui_input['output_file_path'])
worker_yt.signals.result.connect(self.empty_callback)
worker_yt.signals.finished.connect(self.thread_finished)
worker_yt.signals.progress.connect(self.update_progress_bar)
worker_yt.signals.error.connect(self.error_pop_up)
self.threadpool.start(worker_yt)
if 'Last.fm' in ui_input['sources']:
print('last.fm')
worker_fm = Worker(perform_last_fm_s, df_dict, ui_input['output_file_path'])
worker_fm.signals.result.connect(self.empty_callback) # handled by scraper itself
worker_fm.signals.finished.connect(self.thread_finished)
worker_fm.signals.progress.connect(self.update_progress_bar)
worker_fm.signals.error.connect(self.error_pop_up)
self.threadpool.start(worker_fm)
def test_worker(self,progress_callback):
for i in range(0,10):
time.sleep(1)
progress_callback.emit((i+1)*10)
def validate_input_info(self,ui_input):
if not os.path.isfile(ui_input['input_file_path']):
QMessageBox.warning(self, 'Error', "Input file is not selected or not valid.")
return False
if not os.path.isdir(ui_input['output_file_path']):
QMessageBox.warning(self, 'Error', "Output path is not selected or not valid.")
return False
if ui_input['sources']==[]:
QMessageBox.warning(self, 'Error', "Please select scraping source.")
return False
return True
def get_all_input_information(self):
"""
Get user specified information
:return: a dictionary of all information specified by user on UI
"""
result={}
if self.books_radio.isChecked():
result['type']='books'
else:
result['type']='songs'
result['input_file_path']=self.input_path_label.text()
result['output_file_path']=self.output_path_label.text()
result['sources']=[]
if self.source_checkBox_1.isChecked():
result['sources'].append(self.widget_titles[result['type']]['sources'][0])
if self.source_checkBox_2.isChecked():
result['sources'].append(self.widget_titles[result['type']]['sources'][1])
# result['attributes']=[]
# if self.attribute_checkBox_1.isChecked():
# result['sources'].append(self.widget_titles[result['type']]['attributes'][0])
# if self.attribute_checkBox_2.isChecked():
# result['sources'].append(self.widget_titles[result['type']]['attributes'][1])
# if self.attribute_checkBox_3.isChecked():
# result['sources'].append(self.widget_titles[result['type']]['attributes'][2])
# if self.attribute_checkBox_4.isChecked():
# result['sources'].append(self.widget_titles[result['type']]['attributes'][3])
return result
| c4ef20726d9b073cecd297927b1e978925d4fc9b | [
"Markdown",
"Python"
]
| 12 | Python | Innoversa/Law-School-Copyright | 62ff0d0678623034a5d7390027f26e2faf5f890d | 30c19b1c8d322d955683cd89866d136a450ecf46 |
refs/heads/master | <file_sep><?php
namespace Dhairya\TestGraph\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use Magento\Framework\Model\ResourceModel\PredefinedId;
class TestGraph extends AbstractDb
{
/**
* Provides possibility of saving entity with predefined/pre-generated id
*/
use PredefinedId;
/**#@+
* Constants related to specific db layer
*/
private const TABLE_NAME = 'test_graph';
/**#@-*/
/**
* @inheritdoc
*/
protected function _construct()
{
$this->_init(self::TABLE_NAME, 'entity_id');
}
}<file_sep># How to create a GraphQL Endpoint for Magento 2.3
In this Magento 2 GraphQL module, I will show how to build a GraphQL API endpoint extend them with a custom filter logic.
## Test for your new Endpoint (Client Sample Call)
I recommend as Testing client tool to use Altair GraphQL Client
If you like Postman here you a tutorial how to us it: https://learning.getpostman.com/docs/postman/sending-api-requests/graphql/
### Simple GraphQL-Query without an filter:
```sql
{
testGraph {
total_count
items {
name
description
}
}
}
```
### GraphQL-Query with an filter:
```sql
{
testGraph(
filter: {
name: {
eq: "Brick and Mortar 2"
}
}
) {
total_count
items {
name
description
}
}
}
```
### GraphQL-Query with an filter and change page size:
```sql
{
testGraph(
filter: {
name: {
like: "Brick and Mortar 1%"
}
},
pageSize: 100,
currentPage: 1
) {
total_count
items {
name
description
}
}
}
```
<file_sep><?php
declare(strict_types=1);
namespace Dhairya\TestGraph\Api\Data;
/**
* Represents a store and properties
*
* @api
*/
interface TestGraphInterface
{
/**
* Constants for keys of data array. Identical to the name of the getter in snake case
*/
const NAME = 'name';
const DESC = 'description';
/**#@-*/
public function getName(): ?string;
public function setName(?string $name): void;
public function getDescription(): ?string;
public function setDescription(?string $desc): void;
}<file_sep><?php
declare(strict_types=1);
namespace Dhairya\TestGraph\Setup\Patch\Data;
use Dhairya\TestGraph\Api\Data\TestGraphInterface;
use Dhairya\TestGraph\Api\Data\TestGraphInterfaceFactory;
use Dhairya\TestGraph\Api\TestGraphRepositoryInterface;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
class InitializeTestGraph implements DataPatchInterface
{
/**
* @var ModuleDataSetupInterface
*/
private $moduleDataSetup;
/**
* @var TestGraphInterfaceFactory
*/
private $testGraphInterfaceFactory;
/**
* @var TestGraphRepositoryInterface
*/
private $testGraphRepository;
/**
* @var DataObjectHelper
*/
private $dataObjectHelper;
/**
* EnableSegmentation constructor.
*
* @param ModuleDataSetupInterface $moduleDataSetup
*/
public function __construct(
ModuleDataSetupInterface $moduleDataSetup,
TestGraphInterfaceFactory $testGraphInterfaceFactory,
TestGraphRepositoryInterface $testGraphRepository,
DataObjectHelper $dataObjectHelper
) {
$this->moduleDataSetup = $moduleDataSetup;
$this->testGraphInterfaceFactory = $testGraphInterfaceFactory;
$this->testGraphRepository = $testGraphRepository;
$this->dataObjectHelper = $dataObjectHelper;
}
/**
* {@inheritdoc}
*/
public static function getDependencies()
{
return [];
}
/**
* {@inheritdoc}
* @throws Exception
* @throws Exception
*/
public function apply()
{
$this->moduleDataSetup->startSetup();
$max = 50;
for ($i = 1; $i <= $max; $i++) {
$storeData = [
TestGraphInterface::NAME => 'Brick and Mortar ' . $i,
TestGraphInterface::DESC => 'Test Description' . $i
];
/** @var testGraphInterface $store */
$store = $this->testGraphInterfaceFactory->create();
$this->dataObjectHelper->populateWithArray($store, $storeData, testGraphInterface::class);
$this->testGraphRepository->save($store);
}
$this->moduleDataSetup->endSetup();
}
/**
* {@inheritdoc}
*/
public function getAliases()
{
return [];
}
}
<file_sep><?php
declare(strict_types=1);
namespace Dhairya\TestGraph\Model\Resolver;
use Dhairya\TestGraph\Api\TestGraphRepositoryInterface;
//use Dhairya\TestGraph\Model\Store\GetList;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\Resolver\Argument\SearchCriteria\Builder as SearchCriteriaBuilder;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
class TestGraph implements ResolverInterface
{
/**
* @var TestGraphRepositoryInterface
*/
private $testGraphRepository;
/**
* @var SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;
/**
* PickUpStoresList constructor.
* @param TestGraphRepositoryInterface $testGraphRepository
* @param SearchCriteriaBuilder $searchCriteriaBuilder
*/
public function __construct(TestGraphRepositoryInterface $testGraphRepository, SearchCriteriaBuilder $searchCriteriaBuilder)
{
$this->testGraphRepository = $testGraphRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
}
/**
* @inheritdoc
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
$this->vaildateArgs($args);
$searchCriteria = $this->searchCriteriaBuilder->build('test_graph', $args);
$searchCriteria->setCurrentPage($args['currentPage']);
$searchCriteria->setPageSize($args['pageSize']);
$searchResult = $this->testGraphRepository->getList($searchCriteria);
return [
'total_count' => $searchResult->getTotalCount(),
'items' => $searchResult->getItems(),
];
}
/**
* @param array $args
* @throws GraphQlInputException
*/
private function vaildateArgs(array $args): void
{
if (isset($args['currentPage']) && $args['currentPage'] < 1) {
throw new GraphQlInputException(__('currentPage value must be greater than 0.'));
}
if (isset($args['pageSize']) && $args['pageSize'] < 1) {
throw new GraphQlInputException(__('pageSize value must be greater than 0.'));
}
}
}<file_sep><?php
declare(strict_types=1);
namespace Dhairya\TestGraph\Model\ResourceModel;
use Dhairya\TestGraph\Model\ResourceModel\TestGraph as ResourceModel;
use Dhairya\TestGraph\Model\TestGraph as Model;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
/**
* @inheritdoc
*/
protected function _construct()
{
$this->_init(Model::class, ResourceModel::class);
}
}<file_sep><?php
declare(strict_types=1);
namespace Dhairya\TestGraph\Model;
use Dhairya\TestGraph\Api\Data\TestGraphInterface;
use Dhairya\TestGraph\Model\ResourceModel\TestGraph as ResourceModel;
use Magento\Framework\Model\AbstractExtensibleModel;
class TestGraph extends AbstractExtensibleModel implements TestGraphInterface
{
protected function _construct()
{
$this->_init(ResourceModel::class);
}
public function getName(): ?string
{
return $this->getData(self::NAME);
}
public function setName(?string $name): void
{
$this->setData(self::NAME, $name);
}
public function getDescription(): ?string
{
return $this->getData(self::DESC);
}
public function setDescription(?string $desc): void
{
$this->setData(self::DESC, $desc);
}
}
<file_sep><?php
declare(strict_types=1);
namespace Dhairya\TestGraph\Model;
use Dhairya\TestGraph\Api\Data\TestGraphInterface;
use Dhairya\TestGraph\Api\TestGraphRepositoryInterface;
use Dhairya\TestGraph\Model\ResourceModel\TestGraph as ResourceModel;
use Dhairya\TestGraph\Model\ResourceModel\Collection;
use Dhairya\TestGraph\Model\ResourceModel\CollectionFactory;
use Magento\Framework\Api\Search\SearchCriteriaBuilder;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\Api\SearchCriteriaInterface;
use Magento\Framework\Api\SearchResultsInterface;
use Magento\Framework\Api\SearchResultsInterfaceFactory;
use Magento\Framework\Exception\CouldNotSaveException;
class TestGraphRepository implements TestGraphRepositoryInterface
{
/**
* @var CollectionFactory
*/
private $collectionFactory;
/**
* @var CollectionProcessorInterface
*/
private $collectionProcessor;
/**
* @var SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;
/**
* @var SearchResultsInterfaceFactory
*/
private $searchResultsInterfaceFactory;
/**
* @var ResourceModel
*/
private $resourceModel;
public function __construct(
CollectionFactory $collectionFactory,
CollectionProcessorInterface $collectionProcessor,
SearchCriteriaBuilder $searchCriteriaBuilder,
SearchResultsInterfaceFactory $searchResultsInterfaceFactory,
ResourceModel $resourceModel
) {
$this->collectionFactory = $collectionFactory;
$this->collectionProcessor = $collectionProcessor;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->searchResultsInterfaceFactory = $searchResultsInterfaceFactory;
$this->resourceModel = $resourceModel;
}
/**
* @inheritDoc
*/
public function getList(SearchCriteriaInterface $searchCriteria = null): SearchResultsInterface
{
/** @var Collection $collection */
$collection = $this->collectionFactory->create();
if (null === $searchCriteria) {
$searchCriteria = $this->searchCriteriaBuilder->create();
} else {
$this->collectionProcessor->process($searchCriteria, $collection);
}
/** @var SearchResultsInterface $searchResult */
$searchResult = $this->searchResultsInterfaceFactory->create();
$searchResult->setItems($collection->getItems());
$searchResult->setTotalCount($collection->getSize());
$searchResult->setSearchCriteria($searchCriteria);
return $searchResult;
}
/**
* @inheritDoc
*/
public function save(TestGraphInterface $graph): void
{
try {
$this->resourceModel->save($graph);
} catch (\Exception $e) {
throw new CouldNotSaveException(__('Could not save Source'), $e);
}
}
}<file_sep><?php
declare(strict_types=1);
namespace Dhairya\TestGraph\Api;
use Dhairya\TestGraph\Api\Data\TestGraphInterface;
use Magento\Framework\Api\SearchCriteriaInterface;
use Magento\Framework\Api\SearchResultsInterface;
/**
* @api
*/
interface TestGraphRepositoryInterface
{
/**
* Save the data.
*
* @param \Magento\InventoryApi\Api\Data\SourceInterface $source
* @return void
* @throws \Magento\Framework\Exception\CouldNotSaveException
*/
public function save(TestGraphInterface $store): void;
/**
* Find Stores by given SearchCriteria
* SearchCriteria is not required because load all stores is useful case
*
* @param \Magento\Framework\Api\SearchCriteriaInterface|null $searchCriteria
* @return \Magento\Framework\Api\SearchResultsInterface
*/
public function getList(SearchCriteriaInterface $searchCriteria = null): SearchResultsInterface;
} | 28214d694f682fbb2db1fda79f329bb88224c7ea | [
"Markdown",
"PHP"
]
| 9 | PHP | dhairya-shah/magento2-graphql | ae85c047282ff29aa6b6fb4620699e386e840c08 | 9ca3de88f956016423023a1b89ad594f84f31439 |
refs/heads/master | <file_sep>1.This application is done for Buildit @ Wipro Digital Mobile Engineer exercise
application Hosted : https://github.com/sethrockey/Rockeywipro
Technology Used and tool used:
1. Android Studio 3.3
2.Kotlin
3.retrofit
4.GSON
5.Dagger
Application Build on SDK Version 28 and Min SDk Version is 21
OpenWeather Api used for reterival of weather application.
How to run this Project:
1. Download the project from github and extract from ZiP file
2. Open in the Android studio and wait till gradle sync. successfully.
3. Run the application in Min sdk version 21.
For the reviewer information:
This is the first time i used kotlin for building any android application .Before that i was using kotlin for writing unit test in my current project.
I want to take this excersie as opportunity to implement this application in kotlin.
Explanantion to do more if time permit:
1.Unit test but couldn't able to do. But yes, I can write it if i get more time.
2. We can modilfy the UI
3. We can also MVVM to make it for light weight and lossely coupled.
<file_sep>package com.example.weatherfinal.data
data class ForecastItemViewModel(
val degreeDay: String,
val icon: String = "01d",
val date: Long = System.currentTimeMillis(),
val description: String = "No description"
)<file_sep>package com.example.weatherfinal.ui
import com.example.weatherfinal.api.OpenWeatherAPI
import com.example.weatherfinal.data.ForecastItemViewModel
import com.example.weatherfinal.data.WeatherResponse
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.MockitoAnnotations
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainPresenterTest {
@Mock
lateinit var view: MainView
@InjectMocks
lateinit var api:OpenWeatherAPI
@Mock
lateinit var response: WeatherResponse
@Mock
val forecasts = mutableListOf<ForecastItemViewModel>()
lateinit var presenter: MainPresenter
@Before
fun setUp(){
MockitoAnnotations.initMocks(this)
presenter = MainPresenter(view)
}
@Test
fun `get daily forecast test`(){
presenter.getForecastForFiveDays("London")
}
}<file_sep>package com.example.weatherfinal.ui
import com.example.weatherfinal.data.ForecastItemViewModel
interface MainView {
fun showSpinner()
fun hideSpinner()
fun updateForecast(forecasts: List<ForecastItemViewModel>)
fun showErrorToast(errorType: ErrorTypes)
}<file_sep>package com.example.weatherfinal.data
import com.google.gson.annotations.SerializedName
data class WeatherResponse (@SerializedName("city") var city : City,
@SerializedName("list") var forecast : List<ForecastDetail>)<file_sep>package com.example.weatherfinal.ui
import android.os.Build
import com.example.weatherfinal.BuildConfig
import com.example.weatherfinal.api.OpenWeatherAPI
import com.example.weatherfinal.data.ForecastDetail
import com.example.weatherfinal.data.ForecastItemViewModel
import com.example.weatherfinal.data.WeatherResponse
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import javax.inject.Inject
class MainPresenter(val view: MainView) {
@Inject
lateinit var api: OpenWeatherAPI
fun getForecastForFiveDays(cityName: String) {
view.showSpinner()
api.dailyForecast(cityName, 5).enqueue(object : Callback<WeatherResponse> {
override fun onResponse(call: Call<WeatherResponse>, response: Response<WeatherResponse>) {
response.body()?.let {
createListForView(it)
view.hideSpinner()
} ?: view.showErrorToast(ErrorTypes.NO_RESULT_FOUND)
}
override fun onFailure(call: Call<WeatherResponse>?, t: Throwable) {
view.showErrorToast(ErrorTypes.CALL_ERROR)
t.printStackTrace()
}
})
}
private fun createListForView(weatherResponse: WeatherResponse) {
val forecasts = mutableListOf<ForecastItemViewModel>()
for (forecastDetail : ForecastDetail in weatherResponse.forecast) {
val dayTemp = forecastDetail.temperature.dayTemperature
val forecastItem = ForecastItemViewModel(degreeDay = dayTemp.toString(),
date = forecastDetail.date,
icon = forecastDetail.description[0].icon,
description = forecastDetail.description[0].description)
forecasts.add(forecastItem)
}
view.updateForecast(forecasts)
}
}<file_sep>package com.example.weatherfinal.injection.component
import com.example.weatherfinal.injection.module.OpenWeatherAPIModule
import com.example.weatherfinal.ui.MainPresenter
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = arrayOf(OpenWeatherAPIModule::class))
interface OpenWeatherAPIComponent {
fun inject(presenter: MainPresenter);
}<file_sep>package com.example.weatherfinal.ui
enum class ErrorTypes {
MISSING_API_KEY, NO_RESULT_FOUND, CALL_ERROR
} | 17ba4c1432ca9b0b4002cb0bf2acffe015c42666 | [
"Markdown",
"Kotlin"
]
| 8 | Markdown | sethrockey/Rockeywipro | 1feb1d23f898d7473818dc80f7ae76e51b07fa2c | 810b00daf6cced0c34f348a56c6bdbc6e92e983e |
refs/heads/master | <repo_name>vkorchagova/RKDG1D<file_sep>/src/Flux/Flux.h
#ifndef FLUX_H_
#define FLUX_H_
#include <vector>
#include "defs.h"
#include "Problem.h"
#include "ProblemGas1D.h"
#include "ProblemMHD1D.h"
using namespace std;
class Flux
{
private:
//”казатели на векторы конв. потоков на трех €чейках
vector<double> *ptr_leftfluxR, *ptr_myflux, *ptr_myfluxL, *ptr_myfluxR, *ptr_rightfluxL;
//”казатели на векторы решени€ в трех €чейках
const vector<vector<double>> *ptr_mysol, *ptr_leftsol, *ptr_rightsol;
protected:
//”казатель на объект с общими параметрами
const BaseParams* ptrprm;
//”казатель на объект задача
Problem* ptrprb;
ProblemGas1D* ptrprb_toGas;
ProblemMHD1D* ptrprb_toMHD;
//ќбертка дл€ вызова одноименной функции из класса Problem
double side_val(const vector<vector<double>>& sol, var q, side sd) const
{
return ptrprb->side_val(sol, q, sd);
}
vector<double> gauss_val(const vector<vector<double>>& sol, double Lcoord) const
{
return ptrprb->gauss_val(sol, Lcoord);
}
//—сылки на векторы конв. потоков на трех €чейках
vector<double>& myfluxL() { return *ptr_myfluxL; };
vector<double>& myfluxR() { return *ptr_myfluxR; };
vector<double>& myflux() { return *ptr_myflux; };
vector<double>& leftfluxR() { return *ptr_leftfluxR; };
vector<double>& rightfluxL() { return *ptr_rightfluxL; };
//—сылки на векторы решени€ на трех €чейках
const vector<vector<double>>& mysol() { return *ptr_mysol; };
const vector<vector<double>>& leftsol() { return *ptr_leftsol; };
const vector<vector<double>>& rightsol() { return *ptr_rightsol; };
//¬»–“”јЋ№Ќјя ‘”Ќ ÷»я — –≈јЋ»«ј÷»≈…
//”становка приватных указателей (чтобы работали вышеперечисленные ссылки):
// - на конв. потоки в своей €чейке
// - на предельные (слева и справа) потоки в фиктивных €чейках
// - на решение в своей €чейке и в соседних €чейках
virtual void setlocsolflux(const vector<vector<vector<double>>>& SOL, const int cell);
public:
// онструктор (prm - объект, содержащий параметры задачи)
Flux(const BaseParams& prm, Problem& prb);
//ƒеструктор
~Flux();
//¬»–“”јЋ№Ќјя ‘”Ќ ÷»я
//«аполнение приращений решений (DU) и наклонов (DV) на всех €чейках сетки
//рассчитываетс€ по решению (UU) и наклонам (VV) на всех €чейках сетки
//найденна€ скорость изменени€ решени€ и наклонов умножаетс€ на cft
//(дл€ реализации €вного метода Ёйлера следует положить cft = ptrprm->tau)
virtual void step(const vector<vector<vector<double>>>& SOL, \
vector<vector<vector<double>>>& DSOL, \
const double cft) = 0;
};
#endif
<file_sep>/src/Flux/FluxHLLC.h
#ifndef FLUXHLLC_H_
#define FLUXHLLC_H_
#include <vector>
#include <cmath>
#include <algorithm>
#include "Flux.h"
#include "ProblemGas1D.h"
using namespace std;
#define HLLC FluxHLLC
class FluxHLLC :
public Flux
{
private:
//Собственные числа на всей сетке (между i-й и (i-1)-й ячейками)
vector<vector<double>> L;
//Способ вычисления скорости на границе ячеек
SoundVelType SoundVel;
//Потоки HLLС на левом и правом конце ячейки
vector<double> hllcL, hllcR;
//HLLC-решения "со звездочкой"
vector<double> UastL, UastR;
//Временные переменные: векторы - HLLC-скачок решения на границах i-й ячейки
vector<double> LdUast, RdUast;
void getUast(const int cell, const double Sast, \
const vector<vector<double>>& leftsol, \
const vector<vector<double>>& mysol, \
vector<double>& Uast);
double getSast(const int cell, \
const vector<vector<double>>& leftsol, \
const vector<vector<double>>& mysol);
public:
//Конструктор (prm - объект, содержащий параметры задачи)
FluxHLLC(const BaseParams& prm, Problem& prb, SoundVelType soundvel);
//Деструктор
~FluxHLLC();
void step(const vector<vector<vector<double>>>& SOL, \
vector<vector<vector<double>>>& DSOL, \
const double cft);
};
#endif<file_sep>/src/Boundary/BoundaryWall.h
#ifndef BOUNDARYWALL_H_
#define BOUNDARYWALL_H_
#include <vector>
#include "Boundary.h"
#define Wall BoundaryWall
class BoundaryWall :
public Boundary
{
protected:
public:
BoundaryWall(const BaseParams& prm, const Problem& prb);
~BoundaryWall();
//–≈јЋ»«ј÷»я ¬»–“”јЋ№Ќќ… ‘”Ќ ÷»»
//—обственно, происходит формирование √” путем создани€ решени€ в фиктивной €чейке
//заполнение значений новых решений U и наклонов V
//на левой (nx) и правой (nx+1) фиктивных €чейках
//рассчитываетс€ по решению (UU) и наклонам (VV) на всех €чейках сетки
void FillVirtualCells(const vector<vector<vector<double>>>& SOL) const;
};
#endif<file_sep>/src/numvector/numvector.h
/*!
\file
\brief Описание класса numvector
\author <NAME>
\author <NAME>
\author <NAME>
\version 1.0
\date 1 декабря 2017 г.
*/
#ifndef NUMVECTOR_H_
#define NUMVECTOR_H_
#include <vector>
#include <set>
/*!
\brief Шаблонный класс, определяющий вектор фиксированной длины
\n Фактически представляет собой массив, для которого определено большое количество различных операций.
\n Для доступа к элементам массива используется оператор []
\tparam T тип элементов вектора
\tparam n длина вектора
\author <NAME>
\author <NAME>
\author <NAME>
\version 1.0
\date 1 декабря 2017 г.
*/
template<typename T, int n>
class numvector
{
protected:
/// Собственно, вектор с данными
T r[n];
public:
/// \brief Перегрузка оператора "[]" доступа к элементу
///
/// \tparam T тип данных
/// \param[in] j номер элемента, к которому происходит обращение
/// \return Ссылка на элемент
T& operator[](int j) { return r[j]; }
/// \brief Перегрузка оператора "[]" доступа к элементу
///
/// \tparam T тип данных
/// \param[in] j номер элемента, к которому происходит обращение
/// \return Константная ссылка на элемент
const T& operator[](int j) const { return r[j]; }
/// \brief Перегрузка оператора "=" присваивания
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \param[in] vec константная ссылка на присваиваемый вектор
/// \return ссылка на самого себя
numvector<T, n>& operator=(const numvector<T, n>& vec)
{
for (int i = 0; i < n; ++i)
r[i] = vec.r[i];
return *this;
}//operator=
/// \brief Перегрузка оператора "*" скалярного умножения
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \param[in] y константная ссылка на второй множитель
/// \return результат вычисления скалярного произведения
double operator* (const numvector<T, n>& y) const
{
T res = 0;
for (int j = 0; j < n; ++j)
res += r[j] * y[j];
return res;
}//operator*
/// \brief Перегрузка оператора "^" векторного произведения
///
/// Определен только для трехмерных векторов
///
/// \tparam T тип данных
/// \param[in] y константная ссылка на второй множитель
/// \return результат вычисления векторного произведения
numvector<T, 3> operator^ (const numvector<T, 3>& y) const
{
return{ r[1] * y[2] - r[2] * y[1], r[2] * y[0] - r[0] * y[2], r[0] * y[1] - r[1] * y[0] };
}//operator^
/// \brief Перегрузка оператора "^" вычисления третьей компоненты векторного произведения
///
/// Определен только для двумерных векторов
///
/// \tparam T тип данных
/// \param[in] y константная ссылка на второй множитель
/// \return результат вычисления третьей компоненты векторного произведения двух двумерных векторов
T operator^ (const numvector<T, 2>& y) const
{
return r[0] * y[1] - r[1] * y[0];
}//operator^
/// \brief Перегрузка оператора "*=" домножения вектора на действительное число
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \param[in] m числовой множитель, приводится к типу double
/// \return ссылка на самого себя после домножения на число
numvector<T, n>& operator*=(const double m)
{
for (int i = 0; i < n; ++i)
r[i] *= m;
return *this;
}//operator*=
/// \brief Перегрузка оператора "/=" деления вектора на действительное число
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \param[in] m числовой делитель, приводится к типу double
/// \return ссылка на самого себя после деления на число
numvector<T, n>& operator/=(const double m)
{
for (int i = 0; i < n; ++i)
r[i] /= m;
return *this;
}//operator/=
/// \brief Перегрузка оператора "+=" прибавления другого вектора
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \param[in] y константная ссылка на прибавляемый вектор
/// \return ссылка на самого себя после сложения с другим вектором
numvector<T, n>& operator+=(const numvector<T, n>& y)
{
for (int i = 0; i < n; ++i)
r[i] += y[i];
return *this;
}//operator+=
/// \brief Перегрузка оператора "-=" вычитания другого вектора
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \param[in] y константная ссылка на вычитаемый вектор
/// \return ссылка на самого себя после вычитания другого вектора
numvector<T, n>& operator-=(const numvector<T, n>& y)
{
for (int i = 0; i < n; ++i)
r[i] -= y[i];
return *this;
}//operator-=
/// \brief Перегрузка оператора "+" сложения двух векторов
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \param[in] y константная ссылка на прибавляемый вектор
/// \return результат сложения двух векторов
numvector<T, n> operator+(const numvector<T, n>& y) const
{
numvector<T, n> res(*this);
for (int i = 0; i < n; ++i)
res[i] += y[i];
return res;
}//operator+
/// \brief Перегрузка оператора "-" вычитания двух векторов
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \param[in] y константная ссылка на вычитаемый вектор
/// \return результат вычитания двух векторов
numvector<T, n> operator-(const numvector<T, n>& y) const
{
numvector<T, n> res(*this);
for (int i = 0; i < n; ++i)
res[i] -= y[i];
return res;
}//operator-
/// \brief Перегрузка оператора "*" умножения вектора справа на число
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \param[in] m число-множитель, приводится к типу double
/// \return результат вычитания двух векторов
numvector<T, n> operator*(const double m) const
{
numvector<T, n> res(*this);
res *= m;
return res;
}//operator*
/// \brief Перегрузка оператора "-" унарного минуса
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \return противоположный вектор
numvector<T, n> operator-() const
{
numvector<T, n> res(0);
for (int i = 0; i < n; ++i)
res[i] = -(*this)[i];
return res;
}//operator*
/// \brief Вычисление размерности вектора (числа элементов в нем)
///
/// \return размерность вектора (число элементов в нем)
int size() const { return n; }
/// \brief Вычисление нормы (длины) вектора
///
/// Корень из скалярного квадрата вектора
///
/// \return норма (длина) вектора
double length() const { return sqrt(*this * *this); }
/// \brief Вычисление квадрата нормы (длины) вектора
///
/// Скалярный квадрат вектора
///
/// \return квадрат нормы (длины) вектора
double length2() const { return (*this * *this); }
/// \brief Вычисление орта вектора или вектора заданной длины, коллинеарного данному
///
/// Если в качестве новой длины указано отрицательное число --- вектор будет противоположно направленным
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \param[in] newlen длина получаемого вектора (по умолчанию 1.0)
///
/// \return вектор, коллинеарный исходному, заданной длины (по умолчанию 1.0)
numvector<T, n> unit(double newlen = 1.0) const
{
numvector<T, n> res(*this);
double ilen = newlen / this->length();
res *= ilen;
return res;
}//unit()
/// \brief Нормирование вектора на заданную длину
///
/// Если в качестве новой длины указано отрицательное число --- у вектора будет изменено направление
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \param[in] newlen новая длина вектора (по умолчанию 1.0)
void normalize(double newlen = 1.0)
{
double ilen = newlen / this->length();
*this *= ilen;
//return (*this);
}//normalize()
/// \brief Проверка вхождения элемента в вектор
///
/// \param[in] s проверяемый элемент
///
/// \return позиция первого вхождения элемента s; если не входит --- возвращает (-1), приведенный к типу size_t
size_t member(T s)
{
for (int i = 0; i < n; ++i)
if (r[i] == s)
return i;
return (-1);
}//member(...)
/// \brief Построение множества std::set на основе вектора
///
/// \return множество типа std::set, состоящее из тех же элементов, что исходный вектор
std::set<T> toSet() const
{
set<T> newset;
for (size_t i = 0; i < n; ++i)
newset.insert(r[i]);
return newset;
}//toSet()
/// \brief "Вращение" вектора на несколько позиций влево
///
/// Исходный вектор при этом не изменяется
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \param[in] k количество позиций, на которые производится "вращение"
///
/// \return вектор, полученный "вращением" исходного на k позиций влево
numvector<T, n> rotateLeft(size_t k) const
{
numvector<T, n> res;
for (int i = 0; i < n; ++i)
res[i] = r[(i + k) % n];
return res;
}//rotateLeft(...)
/// \brief Геометрический поворот двумерного вектора на 90 градусов
///
/// Исходный вектор при этом не изменяется
/// \n Эквивалентно умножению слева на орт третьей оси, т.е. \f$ \vec k \times \vec r \f$
///
/// \tparam T тип данных
///
/// \return новый двумерный вектор, полученный поворотом исходного на 90 градусов
numvector<T, 2> kcross() const
{
return { -r[1], r[0] };
}//kcross()
/// Пустой конструктор
numvector() { };
/// \brief Конструктор, инициализирующий весь вектор одной и той же константой
///
/// \tparam T тип данных
/// \param[in] z значение, которым инициализируются все компоненты вектора
numvector(const T z)
{
for (int i = 0; i < n; ++i)
r[i] = z;
}//numvector(...)
/// \brief Конструктор копирования
///
/// \tparam T тип данных
/// \tparam n длина вектора
/// \param[in] vec константная ссылка на копируемый вектор
numvector(const numvector<T, n>& vec)
{
for (int i = 0; i < n; ++i)
r[i] = vec.r[i];
}//numvector(...)
/// \brief Конструктор инициализации списком
///
/// \tparam T тип данных
/// \param[in] z константная ссылка на список инициализации
/// \warning Длина списка инициализации не проверяется, от него берутся только необходимое число первых элементов
numvector(const std::initializer_list<T>& z)
{
//if (z.size() > n) exit(0);
//for (size_t i = 0; i < z.size(); ++i)
// r[i] = *(z.begin() + i);
//for (size_t i = z.size(); i < n; ++i)
// r[i] = 0;
for (size_t i = 0; i < n; ++i)
r[i] = *(z.begin() + i);
}//numvector(...)
}; //class numvector
/// \brief Перегрузка оператора "*" умножения вектора слева на число
///
/// \tparam T тип данных вектора
/// \tparam n длина вектора
/// \param[in] m число-множитель, которое приводится к типу double
/// \param[in] x константная ссылка на умножаемый вектор
/// \return результат умножения вектора на число
template<typename T, int n>
inline numvector<T, n> operator*(const double m, const numvector<T, n>& x)
{
numvector<T, n> res(x);
res *= m;
return res;
}//operator*
/// \brief Умножение квадратной матрицы на вектор
///
/// \tparam T тип данных вектора и матрицы
/// \tparam n длина вектора и размерность матрицы
/// \param[in] A константная ссылка на матрицу
/// \param[in] x константная ссылка на вектор
/// \return вектор --- результат умножения матрицы на вектор
template<typename T, int n>
inline numvector<T, n> dot(const numvector<numvector<T, n>, n>& A, const numvector<T, n>& x)
{
numvector<T, n> res;
for (int i = 0; i < n; ++i)
res[i] = A[i] * x;
return res;
}//dot(...)
/// \brief Быстрое вычисление векторного произведения
///
/// Определено только для трехмерных векторов
/// \n Оптимизировано за счет отсутствия вызова конструктора, предполагает наличие трех уже созданных векторов
///
/// \tparam T тип данных
/// \param[in] x константная ссылка на первый множитель
/// \param[in] y константная ссылка на второй множитель
/// \param[out] z ссылка на результат векторного умножения
template<typename T>
inline void cross(const numvector<T, 3>& x, const numvector<T, 3>& y, numvector<T, 3>& z)
{
z = { x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0] };
}//cross(...)
/// \brief Вычисление третьей компоненты векторного произведения
///
/// Определено для векторов любой размерности, используются только первые 2 компоненты исходных векторов
///
/// \tparam T тип данных
/// \tparam n размерность исходных векторов
/// \param[in] x константная ссылка на первый множитель
/// \param[in] y константная ссылка на второй множитель
/// \return третья компонента вектороного произведения
template<typename T, int n>
inline double cross3(const numvector<T, n>& x, const numvector<T, n>& y)
{
return (x[0] * y[1] - x[1] * y[0]);
}//cross3(...)
/// \brief Вычисление квадрата расстояния между двумя точками
///
/// \tparam T тип данных
/// \tparam n размерность векторов
/// \param[in] x константная ссылка на радиус-вектор первой точки
/// \param[in] y константная ссылка на радиус-вектор второй точки
/// \return квадрат расстояния между точками
template<typename T, int n>
inline double dist2(const numvector<T, n>& x, const numvector<T, n>& y)
{
T res = 0;
for (int j = 0; j < n; ++j)
res += (x[j] - y[j])*(x[j] - y[j]);
return res;
}//dist2(...)
/// \brief Вычисление расстояния между двумя точками
///
/// \tparam T тип данных
/// \tparam n размерность векторов
/// \param[in] x константная ссылка на радиус-вектор первой точки
/// \param[in] y константная ссылка на радиус-вектор второй точки
/// \return расстояние между точками
template<typename T, int n>
inline double dist(const numvector<T, n>& x, const numvector<T, n>& y)
{
return sqrt(dist2(x, y));
}//dist(...)
/// \brief Перегрузка оператора "<<" вывода в поток
///
/// Выводит в поток вектор, элементы которого записаны в фигурных скобках и разделены запятой с пробелом
///
/// \tparam T тип данных
/// \tparam n размерность вектора
/// \param[in,out] str ссылка на поток вывода
/// \param[in] x константная ссылка на вектор
/// \return ссылка на поток вывода
template<typename T, int n>
std::ostream& operator<< (std::ostream& str, const numvector<T,n>& x)
{
str << "{ ";
for (int j = 0; j < n - 1; ++j)
str << x[j] << ", ";
str << x[n - 1];
str << " }";
return str;
}//operator<<
/// \brief Приведение вектора к вектору другой размерности
///
/// - если новая размерность меньше старой --- лишние элементы "отбрасываются"
/// - если новая размерность больше сиарой --- новые элементы заполняются нулями
///
/// \tparam T тип данных
/// \tparam n размерность исходного вектора
/// \tparam p размерность нового вектора
/// \param[in] r константная ссылка на исходный вектор
/// \return вектор новой размерности
template<typename T, int n, int p>
numvector<T, p> toOtherLength(const numvector<T, n>& r)
{
numvector<T, p> res;
for (int i = 0; i < min(p, n); ++i)
res[i] = r[i];
for (int i = min(p, n); i < p; ++i)
res[i] = 0;
return res;
}//toOtherLength(...)
#endif<file_sep>/main.cpp
// RKDG-1D.cpp: определяет точку входа для консольного приложения.
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include "defs.h"
#include "Params.h"
#include "Mesh1D.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
//Инициализируем параметры задачи
//Params prm(LeftTriangle);
Params prm(Sod);
//Params prm(BrioWu);
//Params prm(Lax);
//Params prm(Rarefaction);
//Params prm(leftWoodward);
//Params prm(rightWoodward);
//Params prm(Shock);
//Params prm(TestSmallTravelingWave);
//Инициализируем сетку и сохраняем решение в начальный момент времени
Mesh1D mesh(prm);
//Собственно цикл по времени
do
{
mesh.TimeStepping();
}
while (!mesh.finished());
return 0;
}
<file_sep>/src/Indicator/IndicatorHarten.cpp
#include "IndicatorHarten.h"
//КОНСТРУКТОР индикатора Хартена
IndicatorHarten::IndicatorHarten(const BaseParams& prm, const Problem& prb, const var val, const double alpha) : Indicator(prm, prb)
{
sens = val;
mult = alpha;
}//IndicatorHarten::IndicatorHarten
//ДЕСТРУКТОР индикатора Хартена
IndicatorHarten::~IndicatorHarten()
{};
//Вычисление индикаторной функции
void IndicatorHarten::calc_indicator(const vector<vector<double>>& UU, \
const vector<vector<double>>& VV, \
vector<double>& Ind) const
{
bool a1, a2, a3, a4;
int nx = ptrprm->nx;
double h = ptrprm->h;
//Временная переенная: предварительно рассчитанное значение индикаторной функции
vector<double> preind(nx);
for (int cell = 1; cell < nx - 1; ++cell)
{
double x1 = (UU[cell - 1][sens] + 2.0*VV[cell - 1][sens] - UU[cell][sens]);
double x2 = (UU[cell + 1][sens] - 2.0*VV[cell + 1][sens] - UU[cell][sens]);
a1 = x1* \
x2 < -1e-7;
a2 = (fabs(VV[cell][sens]) > mult*fabs(VV[cell - 1][sens])) || \
(mult*fabs(VV[cell][sens]) < fabs(VV[cell - 1][sens]));
a3 = (fabs(VV[cell + 1][sens]) > mult*fabs(VV[cell][sens])) || \
(mult*fabs(VV[cell + 1][sens]) < fabs(VV[cell][sens]));
a4 = a1 && (a2 || a3);
preind[cell] = (a4) ? 1.0 : 0.0;
}
preind[0] = 1.0;
preind[nx - 1] = 1.0;
for (int cell = 1; cell < nx - 1; ++cell)
Ind[cell] = 2.0*(preind[cell - 1] + preind[cell] + preind[cell + 1]);
Ind[0] = 1.0;
Ind[nx - 1] = 1.0;
} | 41f41b46f807a69309cea031491bf62b03724f10 | [
"C++"
]
| 6 | C++ | vkorchagova/RKDG1D | a770223f169166b9b4882cd1284e75e7d94955fc | 2423fa0a4b14f01f905f66387e31ff9b31f851a5 |
refs/heads/master | <file_sep>#!/bin/sh
FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -e '\.py$')
for f in $FILES
do
# auto pep8 correction
autopep8 --in-place $f
autoflake --in-place --remove-all-unused-imports $f
autoflake --in-place --remove-unused-variables $f
done | 46f9fbf9c11eec9b302e45684c51e4138bcac540 | [
"Shell"
]
| 1 | Shell | 1pedro/git-hooks | dcda653052cf089a4cd1cda46d2be723a6aacfe6 | 314df0cb590feda65b1add7ea4fabbbcc4734e55 |
refs/heads/master | <repo_name>davara13/EjercicioEnClase3<file_sep>/src/ejercicionenclase3/Cuenta.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ejercicionenclase3;
/**
*
* @author david
*/
public class Cuenta {
private int numeroDeCuenta;
private double cuentaCorriente;
private Fecha fechaDeCreacion;
private String nomCliente;
private Movimiento[] movimientos;
public Cuenta(int numeroDeCuenta, double cuentaCorriente, Fecha fechaDeCreacion, String nomCliente){
this.cuentaCorriente=cuentaCorriente;
this.fechaDeCreacion= fechaDeCreacion;
this.nomCliente=nomCliente;
this.numeroDeCuenta=numeroDeCuenta;
this.movimientos= new Movimiento[5];
}
public int getNumeroDeCuenta(){
return numeroDeCuenta;
}
public void setNumeroDeCuenta(int ndc){
this.numeroDeCuenta=ndc;
}
public double getCuentaCorriente() {
return cuentaCorriente;
}
public void setCuentaCorriente(double cuentaCorriente) {
this.cuentaCorriente = cuentaCorriente;
}
public Fecha getFechaDeCreacion() {
return fechaDeCreacion;
}
public void setFechaDeCreacion(Fecha fechaDeCreacion) {
this.fechaDeCreacion = fechaDeCreacion;
}
public String getNomCliente() {
return nomCliente;
}
public void setNomCliente(String nomCliente) {
this.nomCliente = nomCliente;
}
public Movimiento[] getMovimientos() {
return movimientos;
}
public void setMovimientos(Movimiento[] movimientos) {
this.movimientos = movimientos;
}
}
<file_sep>/test/ejercicionenclase3/MovimientoTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ejercicionenclase3;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author david
*/
public class MovimientoTest {
public MovimientoTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getFecha method, of class Movimiento.
*/
@Test
public void testGetFecha() {
System.out.println("getFecha");
Movimiento instance = null;
int expResult = 0;
int result = instance.getFecha();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setFecha method, of class Movimiento.
*/
@Test
public void testSetFecha() {
System.out.println("setFecha");
int fecha = 0;
Movimiento instance = null;
instance.setFecha(fecha);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setSaldoAnterior method, of class Movimiento.
*/
@Test
public void testSetSaldoAnterior() {
System.out.println("setSaldoAnterior");
double saldoAnterior = 0.0;
Movimiento instance = null;
instance.setSaldoAnterior(saldoAnterior);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setCantidad method, of class Movimiento.
*/
@Test
public void testSetCantidad() {
System.out.println("setCantidad");
double cantidad = 0.0;
Movimiento instance = null;
instance.setCantidad(cantidad);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setTipo method, of class Movimiento.
*/
@Test
public void testSetTipo() {
System.out.println("setTipo");
Tipo tipo = null;
Movimiento instance = null;
instance.setTipo(tipo);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
| 4590c683df48c98f6b480003089ef944d50f18b1 | [
"Java"
]
| 2 | Java | davara13/EjercicioEnClase3 | 235ca35050c8e40d468eadc533c2fc9088bc4232 | 73193e5318e70c38d73b859adf7f35af900f97f4 |
refs/heads/master | <file_sep>#pragma once
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <vector>
using namespace std;
using namespace cv;
struct lineInfo
{
Vec4f line;
int ends[2];
};
class PositionPattern
{
public:
PositionPattern(vector<Point> &contour, int width);
Vec4i detectTimePattern(PositionPattern &rect2, const Mat &binaryImage, Mat& drawingLine, float thresh = 5);
bool getBoundingLine(Vec4f &bounding);
Point2f getBoundingPoint();
bool findTimePatternPairs(const PositionPattern &rect2, vector<vector<Point2f>> &minDistanceCorners);
Point2f operator[] (int x) const;
vector<int>& getTimePatternSidePoint();
int getTimePatternPoint();
void setTimePatternPoint(int index);
bool isEmpty() const;
int getSize() const;
int getWidth() const;
int getNumOfTimePatternPoint() const;
void addNumOfTimePatternPoint();
~PositionPattern();
private:
vector<Point2f> corners;
vector<lineInfo> lines;
vector<int> timePatternSidePoint;
int timePatternPoint;
int numOfTimePatternPoint;
int width;
};
Vec2f twoPt2vec2f(cv::Point pt1, Point pt2);
vector<Point2f> lineToPointPair(Vec2f line);
Point2f computeIntersect(const Vec2f line1, const Vec2f line2);
Point2f computeIntersect(const Vec4f &line1, const Vec4f &line2);
inline float computeDistance(const Point &i, const Point &j);
inline float computeDistance(const Point2f &i, const Point2f &j);
bool DescendingSize(vector<Point> &i, vector<Point> &j);
bool DescendingSlope(Vec4f &i, Vec4f &j);
/* don't check empty */
/* assume same index */
bool DescendingFistVal(vector<int> &i, vector<int> &j);
float computeMean(const std::vector<int> &numbers);
float computeVariance(const std::vector<int> &numbers);
bool findTimePatternPairs(const vector<Point2f> &rect1, const vector<Point2f> &rect2, vector<vector<Point2f>> &minDistanceCorners);
bool detectTimePattern(const Mat &binaryImage, Point2f startPt, Point2f endPt, float thresh = 10);<file_sep>#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/cuda.hpp"
#include <vector>
#include <math.h>
#include <chrono>
#include "PositionPattern.h"
//#include "zbar.h"
using namespace cv;
using namespace std;
//using namespace zbar;
int thresh = 50;
RNG rng(12345);
int erodeVvalue;
#define SIZE_LIMIT 800
Mat drawingCont(cv::Size size, std::vector<vector<Point> > &contours, std::vector<Vec4i> &hierarchy)
{
Mat drawCont = Mat::zeros(size, CV_8UC1);
for (int i = 0; i < contours.size(); i++)
{
drawContours(drawCont, contours, i, (255, 255, 255), 1, LINE_AA, hierarchy, 0, Point());
}
imshow("contours"+to_string(contours.size()), drawCont);
return drawCont;
}
int main(int argc, char const *argv[]) {
/*auto start = std::chrono::steady_clock::now();*/
RNG rng;
/* read image */
Mat image = imread("test4.jpg");
if (!image.data)
{
//cout << "confirm picture" << endl;
system("pause");
return 0;
}
if (image.cols > 800)
{
if (image.cols > image.rows)
resize(image, image, Size(800, static_cast<float>(image.rows) / image.cols * 800), 0, 0, INTER_LINEAR);
else
resize(image, image, Size(static_cast<float>(image.cols) / image.rows * 800, 800), 0, 0, INTER_LINEAR);
}
else if (image.rows > 800)
{
if (image.cols > image.rows)
resize(image, image, Size(800, static_cast<float>(image.rows) / image.cols * 800), 0, 0, INTER_LINEAR);
else
resize(image, image, Size(static_cast<float>(image.cols) / image.rows * 800, 800), 0, 0, INTER_LINEAR);
}
else if (image.cols < 800)
{
if (image.cols > image.rows)
resize(image, image, Size(800, static_cast<float>(image.rows) / image.cols * 800), 0, 0, INTER_LINEAR);
else
resize(image, image, Size(static_cast<float>(image.cols) / image.rows * 800, 800), 0, 0, INTER_LINEAR);
}
else if (image.rows < 800)
{
if (image.cols > image.rows)
resize(image, image, Size(800, static_cast<float>(image.rows) / image.cols * 800), 0, 0, INTER_LINEAR);
else
resize(image, image, Size(static_cast<float>(image.cols) / image.rows * 800, 800), 0, 0, INTER_LINEAR);
}
Mat imageGray;
cvtColor(image, imageGray, CV_RGB2GRAY);
//imshow("gray", imageGray);
/* threshold */
Mat adapThresh = Mat::zeros(imageGray.size(), CV_8UC1);
//threshold(imageGray, adapThresh, 130, 255, THRESH_BINARY);
//threshold(imageGray, adapThresh, 70, 255, THRESH_OTSU);
adaptiveThreshold(imageGray, adapThresh, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 25, 0);
imshow("adaptive threshold", adapThresh);
/* find contours */
vector<Vec4i> hierarchy;
vector<vector<Point> > contours;
//Mat canny_output;
//Canny(imageGray, canny_output, thresh, thresh * 2, 3);
findContours(adapThresh, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
//drawingCont(imageGray.size(), contours, hierarchy);
Mat drawing = Mat::zeros(imageGray.size(), CV_8UC1);
/* find contours with 3 layer*/
vector<vector<Point> > contours_filter;
vector<int> contours_index;
for (int i = 0; i < contours.size(); i++)
{
int k = i;
int numOfHier = 0;
while (hierarchy[k][2] != -1) {
k = hierarchy[k][2];
++numOfHier;
}
if (numOfHier >= 2)
{
contours_filter.push_back(contours[i]);
contours_index.push_back(i);
//cout << i << " contour size: " << contours[i].size() << endl;
drawContours(drawing, contours, i, (255, 255, 255), 1, LINE_AA, hierarchy, 0, Point());
}
}
drawing = drawingCont(imageGray.size(), contours_filter, hierarchy).clone();
/* find corners */
vector<PositionPattern*>posPat;
posPat.reserve(contours_filter.size());
int coutour_count = 0;
for (int k=0 ; k<contours_filter.size() ; k++)
{
posPat.push_back(new PositionPattern(contours_filter[k], (arcLength(contours_filter[k], true) - arcLength(contours[hierarchy[contours_index[k]][2]], true))/8));
if ((*(posPat.end() - 1))->isEmpty())
{
delete (*(posPat.end() - 1));
posPat.pop_back();
}
else
{
++coutour_count;
}
}
if (posPat.empty())
return 0;
for (PositionPattern* p_posPat : posPat)
{
if (p_posPat)
{
for (int i = 0; i < p_posPat->getSize(); i++)
{
circle(drawing, (*p_posPat)[i], 3, (255, 255, 255), 2);
}
}
}
imshow("corners", drawing);
Mat patternImg = drawing.clone();
/* find time pattern */
vector<vector<int>> QRCode_group;
for (int i = 0; i < posPat.size() - 1; i++)
{
Mat drawing_time_pattern = imageGray.clone();
for (int j = i + 1; j < posPat.size(); j++)
{
Vec4i timePattern = posPat[i]->detectTimePattern(*(posPat[j]), adapThresh, drawing_time_pattern, 5);
//line(drawing_time_pattern, Point(timePattern[0], timePattern[1]), Point(timePattern[2], timePattern[3]), Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)), 3, 8, 0);
if (timePattern[0] != 0 && timePattern[1] != 0 && timePattern[2] != 0 && timePattern[3] != 0)
{
line(patternImg, Point(timePattern[0], timePattern[1]), Point(timePattern[2], timePattern[3]), Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)), 3, 8, 0);
if (QRCode_group.empty())
{
QRCode_group.push_back(vector<int>());
QRCode_group[0].push_back(i);
QRCode_group[0].push_back(j);
}
else
{
bool findQRCode = false;
for (vector<int>& QRCode : QRCode_group)
{
if (!findQRCode)
{
if (find(QRCode.begin(), QRCode.end(), i) != QRCode.end())
{
QRCode.push_back(j);
findQRCode = true;
}
else if (find(QRCode.begin(), QRCode.end(), j) != QRCode.end())
{
QRCode.push_back(i);
findQRCode = true;
}
}
}
if (!findQRCode)
{
QRCode_group.push_back(vector<int>());
QRCode_group[QRCode_group.size() - 1].push_back(i);
QRCode_group[QRCode_group.size() - 1].push_back(j);
}
}
}
}
imshow(to_string(i), drawing_time_pattern);
}
imshow("time pattern", patternImg);
cout << "QRCode group size: " << QRCode_group.size() << endl;
Mat drawing_ImageLine = image.clone();
if (!QRCode_group.empty())
{
for (vector<int> QRCode : QRCode_group)
{
cout << "QRCODE SIZE: " << QRCode.size() <<endl;
if (QRCode.size() == 3)
{
vector<Vec4f> findIntersect;
findIntersect.reserve(2);
vector<Point2f> boundingCorners;
for (int index : QRCode)
{
Vec4f temp;
if (posPat[index]->getBoundingLine(temp))
{
findIntersect.push_back(temp);
}
boundingCorners.push_back(posPat[index]->getBoundingPoint());
}
cout << "corners size: " << boundingCorners.size() << endl;
cout << "findIntersect size: " << findIntersect.size() << endl;
if (findIntersect.size() == 2)
{
boundingCorners.push_back(computeIntersect(findIntersect[0], findIntersect[1]) );
}
cout << "corners size: " << boundingCorners.size() <<endl;
if (boundingCorners.size() == 4)
{
Mat drawing_corners = imageGray.clone();
/* sort */
for (int i = 0; i < 4; i++)
{
if (boundingCorners[i].y < boundingCorners[0].y)
swap(boundingCorners[0], boundingCorners[i]);
}
for (int j = 1; j < 4; j++)
{
if (boundingCorners[j].y < boundingCorners[1].y)
swap(boundingCorners[1], boundingCorners[j]);
}
if (boundingCorners[1].x < boundingCorners[0].x)
swap(boundingCorners[1], boundingCorners[0]);
if (boundingCorners[3].x > boundingCorners[2].x)
swap(boundingCorners[3], boundingCorners[2]);
Point2f srcPoints[4] = { boundingCorners[0], boundingCorners[1], boundingCorners[2], boundingCorners[3] };
int width = posPat[QRCode[0]]->getWidth();
srcPoints[0].x -= width;
srcPoints[0].y -= width;
srcPoints[1].x += width;
srcPoints[1].y -= width;
srcPoints[2].x += width;
srcPoints[2].y += width;
srcPoints[3].x -= width;
srcPoints[3].y += width;
for (int m = 0; m < 4 ; m++)
{
if (srcPoints[m].x < 0)
srcPoints[m].x = 0;
if (srcPoints[m].y < 0)
srcPoints[m].y = 0;
}
Scalar ranColor(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
line(drawing_ImageLine, srcPoints[0], srcPoints[1], ranColor, 2, 8, 0);
line(drawing_ImageLine, srcPoints[1], srcPoints[2], ranColor, 2, 8, 0);
line(drawing_ImageLine, srcPoints[2], srcPoints[3], ranColor, 2, 8, 0);
line(drawing_ImageLine, srcPoints[3], srcPoints[0], ranColor, 2, 8, 0);
/* transform */
Point2f dstPoints[4];
Mat outPic = Mat::zeros(Size(300, 300), CV_8UC3);
dstPoints[0] = Point2f(0, 0);
dstPoints[1] = Point2f(outPic.cols, 0);
dstPoints[2] = Point2f(outPic.cols, outPic.rows);
dstPoints[3] = Point2f(0, outPic.rows);
Mat transMat = getPerspectiveTransform(srcPoints, dstPoints);
warpPerspective(imageGray, outPic, transMat, outPic.size(), INTER_LINEAR);
imshow("transform", outPic);
cout << outPic.size();
imwrite("./after_transform.jpg", outPic);
}
}
}
}
imshow("image", drawing_ImageLine);
///* detection QR Code */
//ImageScanner scanner;
//scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);
//int width = imageGray.cols;
//int height = imageGray.rows;
//uchar *raw = (uchar *)imageGray.data;
//Image imageZbar(width, height, "Y800", raw, width * height);
//scanner.scan(imageZbar);
//Image::SymbolIterator symbol = imageZbar.symbol_begin();
//if (imageZbar.symbol_begin() == imageZbar.symbol_end())
//{
// //cout << "detection failed" << endl;
//}
//for (; symbol != imageZbar.symbol_end(); ++symbol)
//{
// cout << "type:" << endl << symbol->get_type_name() << endl << endl;
// cout << "data:" << endl << symbol->get_data() << endl << endl;
//}
////imshow("Source Image", image);
//imageZbar.set_data(NULL, 0);
/*auto end = std::chrono::steady_clock::now();
std::cout << endl << "that took " << std::chrono::duration_cast<chrono::milliseconds>(end - start).count()
<< " milliseconds\n";*/
waitKey();
}<file_sep>#include "PositionPattern.h"
#include <iostream>
#include <math.h>
#include <algorithm>
PositionPattern::PositionPattern(vector<Point> &contour, int width) :
numOfTimePatternPoint(0),
width(width)
{
if (!contour.empty())
{
vector<Point> polyContour;
approxPolyDP(contour, polyContour, 3, true);
vector<Point> hull;
convexHull(Mat(polyContour), hull, true);
vector<vector<Point>> lineSegments(hull.size());
if (hull.size() <= 6)
{
for (int i = 0; i < hull.size(); i++)
{
vector<Point>::iterator start = find(contour.begin(), contour.end(), hull[i]);
vector<Point>::iterator end;
if (i == hull.size() - 1)
end = find(contour.begin(), contour.end(), hull[0]);
else
end = find(contour.begin(), contour.end(), hull[i + 1]);
if (start != contour.end() && end != contour.end())
{
int numOfPoint = abs(end - start) + 1;
int numOfPoint_inv = contour.size() - numOfPoint + 2;
if (numOfPoint_inv > numOfPoint)
{
lineSegments[i].resize(numOfPoint);
if (start > end)
swap(start, end);
copy(start, end + 1, lineSegments[i].begin());
}
else
{
lineSegments[i].resize(numOfPoint_inv);
if (start < end)
swap(start, end);
copy(start, contour.end(), lineSegments[i].begin());
copy(contour.begin(), end + 1, lineSegments[i].begin() + (contour.end() - start));
}
}
}
/* show segment */
//for (int j = 0; j < lineSegments.size(); j++)
//{
// Mat drawing = Mat::zeros(size, CV_8UC1);
// for (Point pt : lineSegments[j])
// circle(drawing, pt, 5, (255, 255, 255), 2);
// imshow(to_string(contour.size())+"<<<<<<<<<<" + to_string(j) + " line segment: ", drawing);
//}
if (lineSegments.size() >= 4)
{
if (lineSegments.size() > 4)
{
sort(lineSegments.begin(), lineSegments.end(), DescendingSize);
lineSegments.erase(lineSegments.begin() + 4, lineSegments.end());
}
/* fitting line */
vector<Vec4f> boundingLine(4);
for (int k = 0; k < lineSegments.size(); k++)
{
fitLine(lineSegments[k], boundingLine[k], cv::DIST_L1, 0, 0.01, 0.01);
}
/* drawing */
//Mat drawing = Mat::zeros(size, CV_8UC1);
//for (Vec4f line : boundingLine)
//{
// cv::Point point0;
// point0.x = line[2];
// point0.y = line[3];
// double k = line[1] / line[0];
// cv::Point point1, point2;
// point1.x = 0;
// point1.y = k * (0 - point0.x) + point0.y;
// point2.x = 640;
// point2.y = k * (640 - point0.x) + point0.y;
// cv::line(drawing, point1, point2, cv::Scalar(255, 255, 255), 2, 8, 0);
//}
//imshow(to_string(contour.size()) + " line", drawing);
sort(boundingLine.begin(), boundingLine.end(), DescendingSlope);
this->corners.resize(4);
for (int i = 0; i < 2; i++)
{
corners[0 + 2 * i] = computeIntersect(boundingLine[i], boundingLine[2]);
//if corners.
corners[1 + 2 * i] = computeIntersect(boundingLine[i], boundingLine[3]);
}
lines.resize(4);
lines[0].line = boundingLine[0];
lines[0].ends[0] = 0;
lines[0].ends[1] = 1;
lines[1].line = boundingLine[1];
lines[1].ends[0] = 2;
lines[1].ends[1] = 3;
lines[2].line = boundingLine[2];
lines[2].ends[0] = 0;
lines[2].ends[1] = 2;
lines[3].line = boundingLine[3];
lines[3].ends[0] = 1;
lines[3].ends[1] = 3;
/* draw corners */
/* for (Point pt : corners)
circle(drawContour, pt, 5, (255, 255, 255), 2);
imshow("corners", drawContour);*/
}
}
}
}
PositionPattern::~PositionPattern()
{
}
/* for minDistanceCorners[a][b]
a = 0 and a = 1 are 2 diferent pairs
b = 0 comes from rect1(this)
b = 1 comes from rect2.
*/
bool PositionPattern::findTimePatternPairs(const PositionPattern &rect2, vector<vector<Point2f>> &minDistanceCorners)
{
if (!(this->isEmpty()) && !(rect2.isEmpty()))
{
if (this->getSize() > 2 && rect2.getSize() > 2)
{
minDistanceCorners.resize(2);
minDistanceCorners[0].resize(2);
minDistanceCorners[1].resize(2);
float temp = 1E6;
float minDistance = 1E6;
int rect1_index, rect2_index;
Point2f pt1;
Point2f pt2;
for (int i = 0; i < lines.size(); i++)
{
for (int j = 0; j < rect2.lines.size(); j++)
{
Point2f pt1((corners[lines[i].ends[0]].x + corners[lines[i].ends[1]].x) / 2, (corners[lines[i].ends[0]].y + corners[lines[i].ends[1]].y) / 2);
Point2f pt2((rect2[rect2.lines[j].ends[0]].x + rect2[rect2.lines[j].ends[1]].x) / 2, (rect2[rect2.lines[j].ends[0]].y + rect2[rect2.lines[j].ends[1]].y) / 2);
temp = computeDistance(pt1, pt2);
if (temp < minDistance)
{
minDistance = temp;
rect1_index = i;
rect2_index = j;
}
}
}
float closePtDist = 1E6;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
float temp = computeDistance(corners[lines[rect1_index].ends[i]], rect2[rect2.lines[rect2_index].ends[j]]);
if (temp < closePtDist)
{
closePtDist = temp;
minDistanceCorners[1][0] = corners[lines[rect1_index].ends[i]];
minDistanceCorners[1][1] = rect2[rect2.lines[rect2_index].ends[j]];
minDistanceCorners[0][0] = corners[lines[rect1_index].ends[1-i]];
minDistanceCorners[0][1] = rect2[rect2.lines[rect2_index].ends[1-j]];
}
}
}
return true;
}
}
return false;
}
Vec4i PositionPattern::detectTimePattern(PositionPattern &rect2, const Mat &binaryImage, Mat& drawingLine, float thresh)
{
vector<vector<Point2f>> minDistanceCorners;
if (findTimePatternPairs(rect2, minDistanceCorners))
{
for(int twoPair = 0; twoPair<2 ; twoPair++)
{
Point2f rect1_side[2], rect2_side[2];
if (!twoPair)
{
rect1_side[0] = minDistanceCorners[0][0];
rect1_side[1] = minDistanceCorners[1][0];
rect2_side[0] = minDistanceCorners[0][1];
rect2_side[1] = minDistanceCorners[1][1];
}
else
{
rect1_side[1] = minDistanceCorners[0][0];
rect1_side[0] = minDistanceCorners[1][0];
rect2_side[0] = minDistanceCorners[0][1];
rect2_side[1] = minDistanceCorners[1][1];
}
for (int a = 0; a < 2; a++)
{
Point2f timePatternA(rect1_side[a].x + (rect1_side[1 - a].x - rect1_side[a].x) / 14, rect1_side[a].y + (rect1_side[1 - a].y - rect1_side[a].y) / 14);
Point2f timePatternB(rect2_side[a].x + (rect2_side[1 - a].x - rect2_side[a].x) / 14, rect2_side[a].y + (rect2_side[1 - a].y - rect2_side[a].y) / 14);
/* 50 is to length filter*/
if (timePatternA.x > 0 && timePatternA.y > 0 && timePatternB.x > 0 && timePatternB.y > 0 && computeDistance(timePatternA, timePatternB) > 50)
{
/* get vale along line except start & end */
cv::LineIterator lit(binaryImage, timePatternA, timePatternB, 8);
vector<Point> linePts;
linePts.reserve(lit.count);
for (int i = 0; i < lit.count; i++, lit++)
{
linePts.push_back(lit.pos());
//cout << static_cast<int>(adapThresh.at<uchar>(pts[i])) <<",";
}
if (!linePts.empty())
{
unsigned char contColor = binaryImage.at<unsigned char>(*linePts.begin());
int count = 0;
vector<int> pattern;
pattern.reserve(20);
for (Point pt : linePts)
{
if (pt.x > 0 && pt.y > 0)
{
if ((binaryImage.at<unsigned char>(pt)) == contColor)
{
++count;
}
else
{
pattern.push_back(count);
count = 1;
contColor = binaryImage.at<unsigned char>(pt);
}
}
}
if (count > 1)
pattern.push_back(count);
if (!pattern.empty())
pattern.pop_back();
if (!pattern.empty())
pattern.erase(pattern.begin());
line(drawingLine, timePatternA, timePatternB, cv::Scalar(128, 128, 128), 3, 8, 0);
float var = computeVariance(pattern);
cout << var << endl;
if (var < thresh)
{
/* search and save corners index in vector */
for (int j = 0; j < corners.size(); j++)
{
if ((static_cast<int>(rect1_side[a].x) == static_cast<int>(corners[j].x)) && ((static_cast<int>(rect1_side[a].y) == static_cast<int>(corners[j].y))))
{
++numOfTimePatternPoint;
timePatternPoint = j;
if (find(timePatternSidePoint.begin(), timePatternSidePoint.end(), j) == timePatternSidePoint.end())
timePatternSidePoint.push_back(j);
}
if ((static_cast<int>(rect1_side[1 - a].x) == static_cast<int>(corners[j].x)) && ((static_cast<int>(rect1_side[1 - a].y) == static_cast<int>(corners[j].y))))
{
if (find(timePatternSidePoint.begin(), timePatternSidePoint.end(), j) == timePatternSidePoint.end())
timePatternSidePoint.push_back(j);
}
}
for (int j = 0; j < rect2.getSize(); j++)
{
if ((static_cast<int>(rect2_side[a].x) == static_cast<int>(rect2[j].x)) && ((static_cast<int>(rect2_side[a].y) == static_cast<int>(rect2[j].y))))
{
rect2.addNumOfTimePatternPoint();
rect2.setTimePatternPoint(j);
if (find(rect2.getTimePatternSidePoint().begin(), rect2.getTimePatternSidePoint().end(), j) == rect2.getTimePatternSidePoint().end())
rect2.getTimePatternSidePoint().push_back(j);
}
if ((static_cast<int>(rect2_side[1 - a].x) == static_cast<int>(rect2[j].x)) && ((static_cast<int>(rect2_side[1 - a].y) == static_cast<int>(rect2[j].y))))
{
if (find(rect2.getTimePatternSidePoint().begin(), rect2.getTimePatternSidePoint().end(), j) == rect2.getTimePatternSidePoint().end())
rect2.getTimePatternSidePoint().push_back(j);
}
}
Vec4i result(rect1_side[a].x, rect1_side[a].y, rect2_side[a].x, rect2_side[a].y);
return result;
}
}
}
}
}
}
Vec4i result(0, 0, 0, 0);
return result;
}
bool PositionPattern::getBoundingLine(Vec4f &bounding)
{
if (numOfTimePatternPoint == 1)
{
for (lineInfo line : lines)
{
if (timePatternSidePoint.size() == 2)
{
if ((line.ends[0] != timePatternSidePoint[0]) && (line.ends[0] != timePatternSidePoint[1]) && (line.ends[1] != timePatternSidePoint[0]) && (line.ends[1] != timePatternSidePoint[1]))
{
bounding = line.line;
return true;
}
}
}
}
else
{
return false;
}
}
void PositionPattern::setTimePatternPoint(int index)
{
timePatternPoint = index;
}
int PositionPattern::getWidth() const
{
return width;
}
Point2f PositionPattern::getBoundingPoint()
{
if (numOfTimePatternPoint == 1)
{
vector<int> index;
for (int i = 0; i < lines.size(); i++)
{
if ((lines[i].ends[0] != timePatternPoint) && (lines[i].ends[1] != timePatternPoint))
{
if (index.empty())
{
index.push_back(lines[i].ends[0]);
index.push_back(lines[i].ends[1]);
}
else
{
if (index[0] == lines[i].ends[0])
return corners[index[0]];
if (index[0] == lines[i].ends[1])
return corners[index[0]];
if (index[1] == lines[i].ends[0])
return corners[index[1]];
if (index[1] == lines[i].ends[1])
return corners[index[1]];
}
}
}
}
else if (numOfTimePatternPoint == 2)
{
for (int i = 0; i < corners.size(); i++)
{
bool findCorners = false;
for (int j = 0; j < timePatternSidePoint.size(); j++)
{
if (timePatternSidePoint[j] == i)
findCorners = true;
}
if (!findCorners)
return corners[i];
}
}
else
{
return Point2f(0, 0);
}
}
int PositionPattern::getNumOfTimePatternPoint() const
{
return numOfTimePatternPoint;
}
void PositionPattern::addNumOfTimePatternPoint()
{
++numOfTimePatternPoint;
}
int PositionPattern::getSize() const
{
return corners.size();
}
bool PositionPattern::isEmpty() const
{
return corners.empty();
}
Point2f PositionPattern::operator[] (int x) const
{
return corners[x];
}
vector<int>& PositionPattern::getTimePatternSidePoint()
{
return timePatternSidePoint;
}
int PositionPattern::getTimePatternPoint()
{
return timePatternPoint;
}
Vec2f twoPt2vec2f(cv::Point pt1, Point pt2)
{
if (pt1 != pt2 || pt1 != Point(0, 0) || pt2 != Point(0, 0))
{
int y = abs(pt1.y - pt2.y);
int x = abs(pt1.x - pt2.x);
double theta = atan(static_cast<double>(x) / static_cast<double>(y));
if (pt1.y >= pt2.y)
{
if (pt1.x >= pt2.x)
theta = CV_PI - theta;
else
theta = -CV_PI + theta;
}
else
{
if (pt1.x < pt2.x)
theta = CV_PI - theta;
else
theta = -CV_PI + theta;
}
double pt1ToO, pt2ToO, pt1ToPt2;
pt1ToO = sqrt(pt1.x*pt1.x + pt1.y*pt1.y);
pt2ToO = sqrt(pt2.x*pt2.x + pt2.y*pt2.y);
pt1ToPt2 = sqrt((pt2.x - pt1.x)*(pt2.x - pt1.x) + (pt2.y - pt1.y)*(pt2.y - pt1.y));
double angleOf2Line = acos((pt1ToPt2*pt1ToPt2 + pt2ToO * pt2ToO - pt1ToO * pt1ToO) / (2 * pt1ToPt2*pt2ToO));
double verDist = pt2ToO * sin(angleOf2Line);
if (fabs(theta) < CV_PI / 4. || fabs(theta) > 3.*CV_PI / 4.)
{
verDist = -verDist;
}
if (fabs(fabs(theta) - CV_PI) < DBL_EPSILON)
{
theta = 0;
verDist = fabs(verDist);
}
Vec2f output(verDist, theta);
return output;
}
else
{
Vec2f output(0, 0);
return output;
}
}
vector<Point2f> lineToPointPair(Vec2f line)
{
vector<Point2f> points;
float r = line[0], t = line[1];
double cos_t = cos(t), sin_t = sin(t);
double x0 = r * cos_t, y0 = r * sin_t;
double alpha = 1000;
points.push_back(Point2f(x0 + alpha * (-sin_t), y0 + alpha * cos_t));
points.push_back(Point2f(x0 - alpha * (-sin_t), y0 - alpha * cos_t));
return points;
}
Point2f computeIntersect(const Vec2f line1, const Vec2f line2)
{
vector<Point2f> p1 = lineToPointPair(line1);
vector<Point2f> p2 = lineToPointPair(line2);
float denom = (p1[0].x - p1[1].x)*(p2[0].y - p2[1].y) - (p1[0].y - p1[1].y)*(p2[0].x - p2[1].x);
Point2f intersect(((p1[0].x*p1[1].y - p1[0].y*p1[1].x)*(p2[0].x - p2[1].x) -
(p1[0].x - p1[1].x)*(p2[0].x*p2[1].y - p2[0].y*p2[1].x)) / denom,
((p1[0].x*p1[1].y - p1[0].y*p1[1].x)*(p2[0].y - p2[1].y) -
(p1[0].y - p1[1].y)*(p2[0].x*p2[1].y - p2[0].y*p2[1].x)) / denom);
return intersect;
}
Point2f computeIntersect(const Vec4f &line1, const Vec4f &line2)
{
float x, y;
float x1 = line1[2];
float y1 = line1[3];
float x2 = line2[2];
float y2 = line2[3];
if (fabs(line1[0]) <= FLT_EPSILON || fabs(line2[0]) <= FLT_EPSILON)
{
if (fabs(line1[0]) <= FLT_EPSILON && fabs(line2[0]) <= FLT_EPSILON)
{
return Point2f(0, 0);
}
else if (fabs(line1[0]) <= FLT_EPSILON)
{
float m2 = line2[1] / line2[0];
x = x1;
y = m2 * (x - x2) + y2;
}
else
{
float m1 = line1[1] / line1[0];
x = x2;
y = m1 * (x - x1) + y1;
}
}
else
{
float m1 = line1[1] / line1[0];
float m2 = line2[1] / line2[0];
if (m1 < m2 + FLT_EPSILON && m1 > m2 - FLT_EPSILON)
{
return Point2f(0, 0);
}
x = (m2*x2 - y2 - m1 * x1 + y1) / (m2 - m1);
y = m1 * (x - x1) + y1;
}
if (x > 0 && y > 0)
{
return Point2f(x, y);
}
else
{
return Point2f(0, 0);
}
}
inline float computeDistance(const Point &i, const Point &j)
{
return sqrt((j.y - i.y)*(j.y - i.y) + (j.x - i.x)*((j.x - i.x)));
}
inline float computeDistance(const Point2f &i, const Point2f &j)
{
return sqrt((j.y - i.y)*(j.y - i.y) + (j.x - i.x)*((j.x - i.x)));
}
bool DescendingSize(vector<Point> &i, vector<Point> &j)
{
return (i.size() > j.size());
}
bool DescendingSlope(Vec4f &i, Vec4f &j)
{
if (fabs(i[0]) <= FLT_EPSILON && fabs(j[0]) <= FLT_EPSILON)
return i[1] > 0;
else if (fabs(i[0]) <= FLT_EPSILON)
return i[1] > 0;
else if (fabs(j[0]) <= FLT_EPSILON)
return j[1] < 0;
return fabs(i[1] / i[0]) > fabs(j[1] / j[0]);
}
/* don't check empty */
/* assume same index */
bool DescendingFistVal(vector<int> &i, vector<int> &j)
{
if (i[0] == j[1])
swap(j[0], j[1]);
if (i[1] == j[0])
swap(i[0], i[1]);
return (*i.begin() > *j.begin());
}
float computeMean(const std::vector<int> &numbers)
{
if (numbers.empty())
return 0;
float total = 0;
for (int number : numbers) {
total += number;
}
//cout << "mean: " << total / numbers.size() << endl;
return (total / numbers.size());
}
float computeVariance(const std::vector<int> &numbers)
{
float mean = computeMean(numbers);
float result = 0;
for (int number : numbers)
{
result += (number - mean)*(number - mean);
}
//cout << "var: " << result / (numbers.size() - 1) << endl;
return result / (numbers.size() - 1);
}
| 4b62b44b8b2fd67cfe5d37eaf10710126a7e0f91 | [
"C++"
]
| 3 | C++ | klcheungaj/qrcode | 5401c6d75eaa0e1b26c5f61735fbbfdd94e2c88f | 59f58d4791bd92e4d82b86c3661f3f073bf6f4c7 |
refs/heads/master | <repo_name>HarunChowdhury/Upload-Image-Project<file_sep>/README.md
# Upload-Image-Project<file_sep>/Image Upload Project/FileUploadExample/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FileUploadExample.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult Upload(HttpPostedFileBase file)
{
string path = Server.MapPath("~/Images/" + file.FileName);
ViewBag.Path = "File Uploaded Successfully! Wow";
file.SaveAs(path);
return View();
}
}
} | 85a0181a6628c787d67c6d867f3749615c50e517 | [
"Markdown",
"C#"
]
| 2 | Markdown | HarunChowdhury/Upload-Image-Project | 31f20bb4e96ff43c7358e5fb9acdfd7792051d15 | 90372935d2beab1121ee91835484daa2f138d929 |
refs/heads/main | <file_sep>const mongoose = require("mongoose");
const UserSchema = mongoose.Schema({
aire: {
type: Number,
},
co2: {
type: Number,
},
gas: {
type: Number,
},
temperatura: {
type: Number,
},
luminicidad: {
type: Number,
},
});
module.exports = mongoose.model("User", UserSchema);
<file_sep>const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(cors());
app.use(bodyParser.json());
//modelo de la base de datos
const modelTemp = require("./config/models/Modeltemp");
///base de datos
const conectarDB = require("./config/db");
conectarDB();
app.get('/arduino', async(req,res)=>{
try {
const mostrar = await modelTemp.find({}).sort({ _id: -1 }).limit(1);
res.json(mostrar)
} catch (error) {
res.json({message:error})
}
})
app.get("/", (req, resp) => {
resp.send("HOLa mundo como se encuentran hoy");
});
const port = process.env.PORT || 4000;
app.listen(port, "0.0.0.0", () => {
console.log(`el puerto esta funcionando ${port}`);
});
| 037926354b076a8ae0ff18b9d071b206f50ef36c | [
"JavaScript"
]
| 2 | JavaScript | isaac372/ArduinoP | 9b735c0332382a92ff5adfce4a1288c89a5fd728 | 12003ee461d383a03a11822fe963d2c75ec4359a |
refs/heads/main | <repo_name>johnpaster/sbmconverter<file_sep>/README.md
# sbmconverter
This is a python script dedicated for converting songs, adding fade effect, formatting the file name to be played by Simple Battle Music Addon in Garry's mod.
Addon link: https://steamcommunity.com/workshop/filedetails/?id=2085721189
Requirements:
0. Python (You must include it in the path)
1. Pydub (pip install pydub)
2. FFMPEG. Already packaged with the release version. However, if you feel unsafe you may download the script straight from the repository and download the ffmpeg executables from their official site. https://ffmpeg.org/download.html
Usage:
Download the release, open the sbmconvert.py script, close the script and drop songs into the songs folder, open the script again and wait until it's done, after that check in songs_converted and use the files as you please.
<file_sep>/smbconvert.py
from pydub import AudioSegment
from math import ceil
import ctypes
from glob import glob
from pathlib import Path
def clamp(n, minn, maxn):
return max(min(maxn, n), minn)
def cleanup(filepath, file):
cleanedup = "songs_converted/" + filepath.replace("songs\\", "").replace(".mp3", "").replace(".flac", "").replace(".wav", "").replace(".ogg", "").replace(".", "").replace(",", "").replace("_", "").replace("'", "") + " _" + str(ceil((len(file) / 1000.0))).zfill(3) # GMOD can't open some files if they have some forbidden characters. Some workshop uploads tools don't like them too. So I've did this awfulness. Oh and I need to make it fit for SBM.
return cleanedup
def edit(file):
loadedsong = AudioSegment.from_file(file)
fadetime = ceil(clamp((len(loadedsong)) * 0.02, 0, 7000))
editedsong = loadedsong.fade_in(fadetime).fade_out(fadetime).set_frame_rate(44100)
return editedsong
def main():
print("SBM Auto Converter: convert lots of songs automatically to the type SBM accepts! Made by John aka downline.")
convertedfilesnumber = 0
if not Path(str(Path.cwd()) + "/songs").is_dir() or not Path(str(Path.cwd()) + "/songs_converted").is_dir():
Path(str(Path.cwd()) + "/songs").mkdir(parents=True, exist_ok=True)
Path(str(Path.cwd()) + "/songs_converted").mkdir(parents=True, exist_ok=True)
print("Created the previously missing directories for songs.")
print("Drop your songs in there and restart the script! " + str(Path.cwd()) + "\songs")
else:
if len(glob('songs/*')) == 0:
print("No songs found. Drop them into the songs folder! " + str(Path.cwd()) + "\songs")
else:
for i in glob("songs/*"):
try:
print("Working...")
initializedfile = edit(i)
savepath = cleanup(i, initializedfile)
initializedfile.export(savepath + ".ogg", format="ogg")
print("Saved: " + savepath)
convertedfilesnumber += 1
except Exception as e:
print("Unexpected error. ", e)
continue
if convertedfilesnumber == len(glob('songs/*')):
print("Ran out of files.")
ctypes.windll.user32.FlashWindow(ctypes.windll.kernel32.GetConsoleWindow(), True )
return input()
main()
| 4e3a04fd20603d55be4365562a9fce36bb6be142 | [
"Markdown",
"Python"
]
| 2 | Markdown | johnpaster/sbmconverter | 883c817c631b440349fd06a99a30045df70c63ec | a3065513d2060a36944a56301adeb899c22150fe |
refs/heads/main | <file_sep>#!/bin/bash
#homework 1 part 1
#bash
for file in $@
do
cat $@
done
<file_sep>#!/bin/bash
#1)
echo "find all the files in /bin, /sbin, /usr/bin and /usr/sbin that are setuid and owned by root."
find /bin /sbin /usr/bin /usr/sbin -user root -perm -4000
echo ""
read -p "Hit any key to continue."
#2)
echo "find all files across the entire system that have setuid or setgid enabled(regarless of owner)"
find / -perm /6000
echo ""
read -p "Hit any key to continue."
#3)
echo "find all files in /var that have changed in the last 20 minutes."
find /var -mmin -20
echo ""
read -p "Hit any key to continue."
#4)
echo "find the files in /var that are regular files of 0 length"
find /var -type f -size 0
echo ""
read -p "Hit any key to continue."
#5)
echo "find all file in /dev that are not regular files and also not directories"
find /dev -not -type f -and ! -type d -exec ls -l {} \;
echo ""
read -p "Hit any key to continue."
#6)
echo "find all directories in /home that not owned by root"
echo "change their permissions to that have 711 permissions"
find /home -type d ! -user root -exec chmod 711 {} \;
echo ""
read -p "Hit any key to continue."
#7)
echo "find all regular files in /home that are not by root"
echo "change their permissions to that have 755 permissions"
find /home -type f ! -user root -exec chmod 755 {} \;
echo ""
read -p "Hit any key to continue."
#8)
echo "find all file in /etc that have changed in the last 5 days"
find /etc -mtime -5
<file_sep>#!/bin/bash
while IFS=: read -r out1 a out2 b c d e;
do
echo -n "$out1 $out2 $(id -ng $out1)
"
done < /etc/passwd
<file_sep>#!/bin/sh
# learn from https://www.runoob.com/linux/linux-command-manual.html
# and https://www.tecmint.com/linux-commands-cheat-sheet/
#1)dd
# Copy a file
# converting and formatting according to flags provided on the command line
# Example Convert all the English letters in the list.txt to uppercase, and then convert it to the list_1.txt file
dd if=list.txt of=list_1.txt conv=ucase
#2)find
# search for files in a directory as well as its sub-directories
# It searches for files by attributes
# Example list all general files in the subdirectories of the current directory
find . -type f
#3)file
# recognizing the type of data contained in a file
# Example Display file type, but donot display the file name
file -b list.txt
#4)fuser
# shows which processes are using a file
# Example To list the process numbers of local processes using the /etc/passwd file
fuser /etc/passwd
#5)grep
# search through files or plaintext which matches the specified search criteria
# Example find the list.txt that have test
grep test list.txt
#6)host
# lookups the DNS name, convert names to IP addresses and vice versa
# Example lookup the DNS for google
host www.google.com
#7)ldd
# lists dynamic dependencies, show shared object dependencies
# Example
ldd /bin/bash
#8)lsof
# displays information related to files opened by processes
# Example View the occupancy of server 8000 port
lsof -i:8000
#9)mount
# mounts a storage device and spread throughout different devices in one big tree
# Example
mount list.txt /Hw1
#10)ps
# shows useful information about active processes running on a system
# Example Display root process user information
ps -u root
#11)pkill
# send the signals to processes and kill a process
# Example End all php-fpm processes
pkill -9 php-fpm
#12)netstat
# displays useful information concerning the Linux networking subsystem
# Example Show detailed network status
netstat -a
#13)renice
# changes the priority of running proceses
# Example
renice +1 987 -u root -p 32
#14)rsync
# Sync and copy files remotely
# Example
rsync -a list.txt /Hw1
#15)time
# runs programs and summarizes system resource usage
# check how long time should need for the order
# Example
time date
#16)ssh
# an application for remotely accessing and running commands on a remote machine
# Example from cs100
ssh <EMAIL>
#17)stat
# stat is used to show a file or file system status like this
# Example show list.txt status
stat list.txt
#18)strace
# trace system calls and signals.
# Example
strace ls
#19)uname
# displays system information
# Example show all the system information
uname -a
#20)wget
# a simple utility used to download files from the Web in a non-interactive
# Example from Lab4
wget http://ftp.gnu.org/gnu/emacs/emacs-24.4.tar.gz
<file_sep>#!/usr/bin/python
#homework 1 part 3
#python
import sys
if len(sys.argv) >1:
for file in sys.argv[1:]:
contents = open(file, 'r').read()
sys.stdout.write(contents)
<file_sep>#!/bin/sh
find ../usr/src/kernels -name '*.h' -exec grep -i 'magic' {} \; | wc -l
<file_sep>#! /bin/bash
FILE="../full/path/to/lab2-test"
LOG="../../var/log/CS183/uptime.log"
if [ -e "$FILE" ]; then
if [ "$(tail -n 1 $LOG | grep -m 1 "found" | wc -l)" -eq 0 ]; then
echo "$(date "+%m-%d-%y %T") - File \"$FILE\" has been found" >> $LOG
fi
else
if [ "$(tail -n 1 $LOG | grep -m 1 "lost" | wc -l)" -eq 0 ]; then
echo "$(date "+%m-%d-%y %T") - File \"$FILE\" has been lost" >> $LOG
fi
fi
| 887dc62f04c6db59decce2c49e380f7a92debd53 | [
"Python",
"Shell"
]
| 7 | Shell | AyinDJ/CS183Lab2 | 4c69a206c87eee9b587748fdfded22b53bb7a4d4 | 5e26067c5bca69842f43a43fac9ab516debf0ca3 |
refs/heads/main | <repo_name>utkarsh-n/Simply-Math<file_sep>/README.md
# Simply-Math
## Simply Math is a lightweight yet powerful app to help increase your mathematical expertise.
### Functions include
- Addition
- Subtraction
- Division
- Multiplication
- Square Roots
- Squares
### Tables from 1-20 are included as well, to help you master and memorize your basic multiplication.
<file_sep>/app/src/main/java/com/example/youdothemath/Practice.java
package com.example.youdothemath;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class Practice extends Activity implements OnClickListener {
//level names
String[] levelNames = {"Beginner", "Intermediate", "Pro"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practice);
//retrieve references
Button additionBtn = (Button) findViewById(R.id.addition_btn);
Button subtractionBtn = (Button) findViewById(R.id.subtraction_btn);
Button multiplicationBtn = (Button) findViewById(R.id.multiplication_btn);
Button divisionBtn = (Button) findViewById(R.id.division_btn);
Button allBtn = (Button) findViewById(R.id.all_btn);
Button sqrtBtn = (Button) findViewById(R.id.sqrt_btn);
ImageView home = (ImageView) findViewById(R.id.ok_btn);
//listen for clicks
additionBtn.setOnClickListener(this);
subtractionBtn.setOnClickListener(this);
multiplicationBtn.setOnClickListener(this);
divisionBtn.setOnClickListener(this);
allBtn.setOnClickListener(this);
home.setOnClickListener(this);
sqrtBtn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.getId()==R.id.addition_btn){
//play button
Intent additionIntent = new Intent(this, Addition.class);
this.startActivity(additionIntent);
}
else if(view.getId()==R.id.subtraction_btn){
//how to play button
Intent subtractionIntent = new Intent(this, Subtraction.class);
this.startActivity(subtractionIntent);
}
else if(view.getId()==R.id.multiplication_btn){
//high scores button
Intent multiplicationIntent = new Intent(this, Multiplication.class);
this.startActivity(multiplicationIntent);
}
else if(view.getId()==R.id.division_btn){
//about button
Intent divisionIntent = new Intent(this, Division.class);
this.startActivity(divisionIntent);
}
else if(view.getId()==R.id.all_btn){
//about button
Intent allIntent = new Intent(this, All.class);
this.startActivity(allIntent);
}
else if(view.getId()==R.id.ok_btn){
//home button
Intent mainactivityIntent = new Intent(this, MainActivity.class);
this.startActivity(mainactivityIntent);
}
else if(view.getId()==R.id.sqrt_btn){
//home button
Intent sqrtIntent = new Intent(this, SquareRoot.class);
this.startActivity(sqrtIntent);
}
}
private void startPlay(int chosenLevel){
//start gameplay
Intent playIntent = new Intent(this, PlayGame.class);
playIntent.putExtra("level", chosenLevel);
this.startActivity(playIntent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
| babd29a456cea13687f11effa2ecc0af47d8c8e6 | [
"Markdown",
"Java"
]
| 2 | Markdown | utkarsh-n/Simply-Math | 315bd6098d51df9dee195f924f51a77f7e5fea97 | fc80e1f15c86a23728898adb26e4f050289ffed7 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Nov 26 16:33:18 2017
@author: paul
"""
from scipy.linalg import cho_factor, cho_solve
import numpy as np
"""
Covariance matrix without considering sigma_J parameter
"""
def covariance_base(t, alpha, lambda_p, lambda_e, tau):
dt = t[None, :] - t[:, None]
kernel = (alpha**2)*np.exp(-0.5*(np.sin((np.pi*dt)/tau)**2/lambda_p**2 + dt**2/lambda_e**2))
return kernel
"""
Covariance matrix composed of a quasi periodic kernel, sigma_J, and sigma_model
"""
def covariance_matrix(t, alpha, lambda_p, lambda_e, tau, sigma_J, sigma_model):
dt = t[None, :] - t[:, None]
kernel = (alpha**2)*np.exp(-0.5*(np.sin((np.pi*dt)/tau)**2/lambda_p**2 + dt**2/lambda_e**2))
sigma_diag = np.diag(sigma_J**2 + sigma_model**2, k=0)
return kernel + sigma_diag
"""
Multi-Normal likelihood function centered at model predictions
: param array-like r: residuals vector, which is calculated as data - model
: param array-like cov: covariance matrix, modelling the problem.
"""
def log_likelihood(r, cov):
#use cho_solve and cho_factor instead of slogdet to improve performance.
chol=cho_factor(cov)
cholsolve = cho_solve(chol, r)
(sign, logdet) = np.linalg.slogdet(cov)
return -.5*(np.dot(r.T, cholsolve) + logdet) -.5*len(r)*np.log(2*np.pi) <file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 12:02:24 2017
@author: paul
"""
from __future__ import division
import numpy as np
"""
# utilizar como parametros a K y T, no a "a" el semieje mayor de la elipse.
# K sale sencillamente de las mediciones.
# K, T y a están relacionados, con lo cual en mi funcion solo pondré dos de ellos.
#t0 tiempo de periastro
#T período
#K amplitud
# Vz valor en cero de la velocidad
# E anomalia eccentrica
#compute mean longitude
lambda1 = M + w1
#compute K
K = m1/(m1 + m2)*(n*a*sin(I)/np.sqrt(1 - e**2))
"""
def dx(f, x):
return abs(f(x))
def newton_raphson_method(g, dg, E0, d):
delta = dx(g, E0)
while np.any(delta > d):
E0 = E0 - g(E0)/dg(E0)
delta = dx(g, E0)
# =============================================================================
# print delta
# =============================================================================
return E0
def solve_kepler(t, P, t0, e, d):
# compute n, the planet's mean motion, given the period T.
n = 2*np.pi/P
# compute M, the mean anomaly at a given time.
M = n*(t-t0)
# =============================================================================
# print P, e, e
# =============================================================================
# define kepler equation, equal to zero, and his derivative.
g = lambda E: E - e*np.sin(E) - M
dg = lambda E: 1 - e*np.cos(E)
# use Newton-Raphson method to compute E.
E1 = newton_raphson_method(g, dg, M, d)
return E1
def radial_velocity( w, e, C, K, E1):
# find f using trascendental equation which relates f with E.
f = 2*np.arctan2(np.sqrt(1+e)*np.sin(E1/2), np.sqrt(1-e)*np.cos(E1/2))
# finally compute radial velocity. C is another parameter.
vr = C + K*(np.cos(w + f) + e*np.cos(w))
return vr
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Nov 26 11:32:56 2017
@author: paul
"""
from __future__ import division
import numpy as np
def period_prior(P, P_max, P_min):
"""
Compute the log period_prior, known as truncated Jeffrey`s prior.
: param int-like P: a number which moves between P_min = 1.25 days and P_max = 10e4 days.
: param int-like P_max: a number equals to 10e4 days
: param int-like P_min: a number equals to 1.25 days
"""
if np.all(P<=P_max) and np.all(P>=P_min):
log_term = np.log(P_max/P_min)
return np.log(1/(P*log_term))
else:
return -np.inf
def semi_amplitude_prior(K, K_max, K_0):
"""
Compute the log semi_amplitude_prior, a truncated modified Jeffrey's Prior.
: param int-like K: a number which moves between 0 m/s and K_max = 999 m/s
: param int-like K_max: a number equals to 999 m/s
: param int-like K_0: a number equals to 1 m/s
"""
if np.all(K>0) and np.all(K<=K_max):
linear_term = 1 + K/K_0
log_term = np.log(1 + K_max/K_0)
return np.log(1/(K_0*linear_term*log_term))
else:
return -np.inf
def eccentricity_prior(e, e_max, sigma_e):
"""
Compute the log eccentricity_prior, a truncated Rayleight distribution.
: param int-like e: a number which moves between 0 e_max = 1
: param int-like e_max: a number equals to 1
: param int-like sigma_e: a number equals to .2
"""
if np.all(e>=0) and np.all(e<e_max):
linear_term = e/sigma_e**2
exp_term = np.exp(-e**2/(2*sigma_e**2))
exp_const_term = 1 - np.exp(-e_max**2/(2*sigma_e**2))
return np.log((linear_term*exp_term)/exp_const_term)
else:
return -np.inf
def argument_pericenter_prior(w):
"""
Compute the log argument_pericenter_prior, a truncated Rayleight distribution.
: param int-like w: a number which moves between 0 and 2*np.pi radians
"""
if np.all(w>=-np.pi) and np.all(w<np.pi):
return np.log(1/(2*np.pi))
else:
return -np.inf
def mean_annomaly_prior(M):
"""
Compute the log mean_annomaly_prior.
: param int-like M: a number which moves between 0 and 2*np.pi radians
"""
if np.all(M>=-np.pi) and np.all(M<np.pi):
return np.log(1/(2*np.pi))
else:
return -np.inf
def white_noise_prior(sigma_J, sigma_Jmax, sigma_J0):
"""
Compute the log white_noise_prior.
: param int-like sigma_J: a number which moves between 0 m/s and sigma_Jmax = 99 m/s
: param int-like sigma_Jmax: a number which equals to 99 m/s
: param int-like sigma_J0: a number which equals to 0 m/s
:
"""
if np.all(sigma_J>0) and np.all(sigma_J<=sigma_Jmax):
linear_term = 1 + sigma_J/sigma_J0
log_term = np.log(1 + sigma_Jmax/sigma_J0)
return np.log(1/(sigma_J0*linear_term*log_term))
else:
return -np.inf
def offset_prior(C, C_max):
"""
Compute the log offset_prior.
: param int-like C: a number which moves between -C_max = 1000 m/s and C_max = 1000 m/s
: param int-like C_max: a number which equals to 1000 m/s
"""
if np.all(C>=-C_max) and np.all(C<=C_max):
return np.log(1/(2*C_max))
else:
return -np.inf
| 13885a0589079f9052dd7b1eedfd77b5781c1e89 | [
"Python"
]
| 3 | Python | martinanastasio/KeplerianFunctions | 58f51029b8c3cddbb0daa535d1675a79df9d9ea9 | c8cfb97438c9607190e97f2df6112b9a837a23dc |
refs/heads/master | <repo_name>GlennColpaert/digital-twins-samples<file_sep>/AdtSampleApp/SampleClientApp/Program.cs
using Microsoft.Identity.Client;
using Azure.Identity;
using Microsoft.Rest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Azure.DigitalTwins.Core;
using Azure.DigitalTwins.Core.Serialization;
using Azure.DigitalTwins.Core.Models;
using System.Runtime.InteropServices;
using Azure;
namespace SampleClientApp
{
public class Program
{
// Properties to establish connection
// Please copy the file serviceConfig.json.TEMPLATE to serviceConfig.json
// and set up these values in the config file
private static string clientId;
private static string tenantId;
private static string adtInstanceUrl;
const string adtAppId = "https://digitaltwins.azure.net";
private static DigitalTwinsClient client;
static string[] scopes = new[] { adtAppId + "/.default" };
static async Task Main()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
int width = Math.Min(Console.LargestWindowWidth, 150);
int height = Math.Min(Console.LargestWindowHeight, 40);
Console.SetWindowSize(width, height);
}
try
{
// Read configuration data from the
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("serviceConfig.json", false, true)
.Build();
clientId = config["clientId"];
tenantId = config["tenantId"];
adtInstanceUrl = config["instanceUrl"];
} catch (Exception e)
{
Log.Error($"Could not read service configuration file serviceConfig.json");
Log.Alert($"Please copy serviceConfig.json.TEMPLATE to serviceConfig.json");
Log.Alert($"and edit to reflect your service connection settings.");
Log.Alert($"Make sure that 'Copy always' or 'Copy if newer' is set for serviceConfig.json in VS file properties");
Environment.Exit(0);
}
Log.Ok("Authenticating...");
try
{
var credential = new InteractiveBrowserCredential(tenantId, clientId);
client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential);
// force authentication to happen here
// ignoring the RequestFailedException to allow authentication
try
{
Utilities.IgnoreRequestFailedException(() => client.GetDigitalTwin(""));
}
catch (Exception e)
{
Log.Error($"Authentication or client creation error: {e.Message}");
Log.Alert($"Have you checked that the configuration in serviceConfig.json is correct?");
Environment.Exit(0);
}
} catch(Exception e)
{
Log.Error($"Authentication or client creation error: {e.Message}");
Log.Alert($"Have you checked that the configuration in serviceConfig.json is correct?");
Environment.Exit(0);
}
Log.Ok($"Service client created – ready to go");
CommandLoop CommandLoopInst = new CommandLoop(client);
await CommandLoopInst.CliCommandInterpreter();
}
}
}
<file_sep>/AdtSampleApp/SampleFunctionsApp/ProcessHubToDTEvents.cs
// Default URL for triggering event grid function in the local environment.
// http://localhost:7071/runtime/webhooks/EventGrid?functionName={functionname}
using Microsoft.Azure.EventGrid.Models;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Extensions.Logging;
using Microsoft.Rest;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Linq;
using Azure;
using Azure.Identity;
using Azure.DigitalTwins.Core;
using System.Net.Http;
using Azure.Core.Pipeline;
namespace SampleFunctionsApp
{
/*
* This class processes telemetry events from IoT Hub, reads temperature of a device,
* sets the "Temperature" property of the device with the value of the telemetry,
* Finds the room that contains the device and sets the room Temperature property
* to the latest telemetry value.
*/
public class ProcessHubToDTEvents
{
const string adtAppId = "https://digitaltwins.azure.net";
private static string adtInstanceUrl = Environment.GetEnvironmentVariable("ADT_SERVICE_URL");
private static HttpClient httpClient = new HttpClient();
[FunctionName("ProcessHubToDTEvents")]
public async void Run([EventGridTrigger]EventGridEvent eventGridEvent, ILogger log)
{
// After this is deployed, you need to turn the Managed Identity Status to "On",
// Grab Object Id of the function and assigned "Azure Digital Twins Owner (Preview)" role to this function identity
// in order for this function to be authorized on ADT APIs.
log.LogInformation(eventGridEvent.Data.ToString());
DigitalTwinsClient client = null;
try
{
// Authenticate on ADT APIs
ManagedIdentityCredential cred = new ManagedIdentityCredential(adtAppId);
client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred, new DigitalTwinsClientOptions { Transport = new HttpClientTransport(httpClient) });
log.LogInformation($"ADT service client connection created.");
if (client != null)
{
if (eventGridEvent != null && eventGridEvent.Data != null)
{
#region Open this region for message format information
// Telemetry message format
//{
// "properties": { },
// "systemProperties":
// {
// "iothub-connection-device-id": "thermostat1",
// "iothub-connection-auth-method": "{\"scope\":\"device\",\"type\":\"sas\",\"issuer\":\"iothub\",\"acceptingIpFilterRule\":null}",
// "iothub-connection-auth-generation-id": "637199981642612179",
// "iothub-enqueuedtime": "2020-03-18T18:35:08.269Z",
// "iothub-message-source": "Telemetry"
// },
// "body": "eyJUZW1wZXJhdHVyZSI6NzAuOTI3MjM0MDg3MTA1NDg5fQ=="
//}
#endregion
// Reading deviceId from message headers
log.LogInformation(eventGridEvent.Data.ToString());
JObject job = (JObject)JsonConvert.DeserializeObject(eventGridEvent.Data.ToString());
string deviceId = (string)job["systemProperties"]["iothub-connection-device-id"];
log.LogInformation($"Found device: {deviceId}");
// Extracting temperature from device telemetry
byte[] body = System.Convert.FromBase64String(job["body"].ToString());
var value = System.Text.ASCIIEncoding.ASCII.GetString(body);
var bodyProperty = (JObject)JsonConvert.DeserializeObject(value);
var temperature = bodyProperty["Temperature"];
log.LogInformation($"Device Temperature is:{temperature}");
// Update device Temperature property
await AdtUtilities.UpdateTwinProperty(client, deviceId, "/Temperature", temperature, log);
}
}
}
catch (Exception e)
{
log.LogError($"Error: {e.Message}");
}
}
}
}
<file_sep>/DeviceSimulator/DeviceSimulator/AzureIoTHub.cs
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Common.Exceptions;
using Microsoft.ServiceBus.Messaging;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Devices = Microsoft.Azure.Devices;
namespace DeviceSimulator
{
public static class AzureIoTHub
{
/// <summary>
/// Please replace with correct connection string value
/// The connection string could be got from Azure IoT Hub -> Shared access policies -> iothubowner -> Connection String:
/// </summary>
private const string connectionString = "<your-hub-connection-string>";
/// <summary>
/// Please replace with correct device connection string
/// The device connect string could be got from Azure IoT Hub -> Devices -> {your device name } -> Connection string
/// </summary>
private const string deviceConnectionString = "<your-device-connection-string>";
private const string iotHubD2cEndpoint = "messages/events";
public static async Task<string> CreateDeviceIdentityAsync(string deviceName)
{
var registryManager = Devices.RegistryManager.CreateFromConnectionString(connectionString);
Devices.Device device;
try
{
device = await registryManager.AddDeviceAsync(new Devices.Device(deviceName));
}
catch (DeviceAlreadyExistsException)
{
device = await registryManager.GetDeviceAsync(deviceName);
}
return device.Authentication.SymmetricKey.PrimaryKey;
}
public static async Task SendDeviceToCloudMessageAsync(CancellationToken cancelToken)
{
var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString);
double avgTemperature = 70; // m/s
Random rand = new Random();
while (true)
{
if (cancelToken.IsCancellationRequested)
break;
double currentTemperature = avgTemperature + rand.NextDouble() * 4 - 3;
var telemetryDataPoint = new
{
Temperature = currentTemperature
};
var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
var message = new Message(Encoding.ASCII.GetBytes(messageString));
await deviceClient.SendEventAsync(message);
Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
await Task.Delay(5000);
}
}
public static async Task<string> ReceiveCloudToDeviceMessageAsync()
{
var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString);
while (true)
{
var receivedMessage = await deviceClient.ReceiveAsync();
if (receivedMessage != null)
{
var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
await deviceClient.CompleteAsync(receivedMessage);
return messageData;
}
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
public static async Task ReceiveMessagesFromDeviceAsync(CancellationToken cancelToken)
{
EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, iotHubD2cEndpoint);
var d2cPartitions = eventHubClient.GetRuntimeInformation().PartitionIds;
await Task.WhenAll(d2cPartitions.Select(partition => ReceiveMessagesFromDeviceAsync(eventHubClient, partition, cancelToken)));
}
private static async Task ReceiveMessagesFromDeviceAsync(EventHubClient eventHubClient, string partition, CancellationToken ct)
{
var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);
while (true)
{
if (ct.IsCancellationRequested)
break;
EventData eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(2));
if (eventData == null) continue;
string data = Encoding.UTF8.GetString(eventData.GetBytes());
Console.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);
}
}
}
}
<file_sep>/AdtSampleApp/SampleClientApp/Utilities.cs
using Azure;
using System;
using System.Collections.Generic;
using System.Text;
namespace SampleClientApp
{
public static class Utilities
{
public static bool IgnoreRequestFailedException(Action operation)
{
if (operation == null)
return false;
try
{
operation.Invoke();
}
catch (RequestFailedException)
{
return false;
}
return true;
}
}
}
| 879677d3ce1f580e4357bb5f872a667f8743fc37 | [
"C#"
]
| 4 | C# | GlennColpaert/digital-twins-samples | 40d6da6f89f4ec8827bcccfb73b12e1470d2b496 | b493a90ae1f7c91825d64df9030f10d8f35993a8 |
refs/heads/main | <repo_name>EfratKenig/Python_WiFi_Access_Point_Connect<file_sep>/Access_Point_Connect.py
import subprocess
import os
import ctypes, sys
def parse_to_dict(APs_str):
for outer_ind in range(len(APs_str)):
APs_str[outer_ind] = (APs_str[outer_ind]).split(' :')
for inner_ind in range(len(APs_str[outer_ind])):
APs_str[outer_ind][inner_ind] = APs_str[outer_ind][inner_ind].strip()
if ' ' in APs_str[outer_ind][inner_ind]:
new_list = APs_str[outer_ind][inner_ind] = APs_str[outer_ind][inner_ind].split(' ')
if '' in new_list:
new_list.remove('')
# '\n' means a start of new value in the dictionary
parsed_dict = {}
for ap_ind, ap in enumerate(APs_str[:-1]): # -1 because of the redundant last one
AP_name = ((APs_str[ap_ind])[1])[0].strip('\n').strip()
parsed_dict[AP_name] = {}
for attr_ind, attr in enumerate(APs_str[ap_ind]):
if isinstance(attr, list):
# needs to take 2nd item as a new attr in the dictionary
if isinstance((APs_str[ap_ind])[attr_ind + 1], list):
(parsed_dict[AP_name])[attr[1].strip()] = ((APs_str[ap_ind])[attr_ind + 1])[0].strip('\n')
return parsed_dict
def find_all_APs():
"""runs a command that that shows all availabale access points,
returns the command output as a list"""
networks = subprocess.check_output(['netsh', 'wlan', 'show', 'networks', 'mode=Bssid'])
networks = networks.decode('utf-8')
networks = networks.replace('\r', '').split("\n\n")[1::]
return networks
def create_connection(name, password):
"""creates a new connection"""
connection = """<?xml version=\"1.0\"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>""" + name + """</name>
<SSIDConfig>
<SSID>
<name>""" + name + """</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>passPhrase</keyType>
<protected>false</protected>
<keyMaterial>""" + password + """</keyMaterial>
</sharedKey>
</security>
</MSM>
</WLANProfile>"""
cmd = "netsh wlan add profile filename=\"" + name + ".xml\""
with open(name + ".xml", 'w') as xml_file:
xml_file.write(connection)
os.system(cmd)
def connect(name):
cmd = 'netsh wlan connect name="' + name + '"'
os.system(cmd)
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
def signal_to_rssi(sig):
return (sig / 2) - 100
def main():
"""
flow:
1: find all available networks
2: find fastest of all
3: ask for password if needed
4: (try to) connect
5: check status and return
"""
# find all available networks:
all_APs_list = find_all_APs()
for AP in all_APs_list:
print(AP, end='\n\n')
# find fastest access point:
parsed_dict = parse_to_dict(all_APs_list)
best_rssi = (-100,)
for key in parsed_dict:
cur_rssi = signal_to_rssi(int(parsed_dict[key]['Signal'].strip()[:-1]))
if key == "DIRECT-A9-HP DeskJet 5200 series":
continue
if cur_rssi >= best_rssi[0]:
best_rssi = (cur_rssi, key)
if cur_rssi == 0:
break
print("\n\nBest Access Point:\n"+str(best_rssi[1]))
for key in parsed_dict[best_rssi[1]]:
print("\t"+key+": "+str(parsed_dict[best_rssi[1]][key]))
if parsed_dict[best_rssi[1]]['Authentication'] != 'Open':
# ask for password if needed:
pwd = input("Enter your password\n")
create_connection(best_rssi[1], pwd)
if connect(best_rssi[1]) == 0:
return "Connected Successfully"
if __name__ == "__main__":
# check admin permissions:
if is_admin():
main()
else:
# grant permission and run
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
main()
| 729179232c4cd9d465806199d1b49d5df32d9ed3 | [
"Python"
]
| 1 | Python | EfratKenig/Python_WiFi_Access_Point_Connect | fedc6c95137ef4ceb456b05f35e4ad4bcc1a4eb0 | 851db143576577acfb214ba5bc8aa6337c3e985c |
refs/heads/master | <repo_name>vasanth-seven/ipl_data_visualization<file_sep>/ipl/teamWinbyVenue.js
const teamWinbyVenue=(matches)=>{
let result={}
for(let match of matches){
let venue=match.venue;
let winner=match.winner;
if(result[venue]){
if(result[venue][winner]){
result[venue][winner]+=1;
}
else{
result[venue][winner]=1;
}
}
else{
result[venue]={}
result[venue][winner]=1;
}
}
return result
}
module.exports= teamWinbyVenue;<file_sep>/index.js
const fs = require("fs");
const csv = require("csvtojson");
const path=require("path")
const matchesPlayedPerYear = require("./ipl/matchesPlayedPerYear");
const matchesWonPerYear = require("./ipl/matchesWonPerYear");
const extras = require("./ipl/extras");
const economical=require("./ipl/topEconomicalBowler");
const teamWinbyVenue=require("./ipl/teamWinbyVenue");
const MATCHES_FILE_PATH = "./csv_data/matches.csv";
const JSON_OUTPUT_FILE_PATH = "./public/data.json";
const DELIVERIES_FILE_PATH = "./csv_data/deliveries.csv";
function main() {
csv()
.fromFile(MATCHES_FILE_PATH)
.then((matches) => {
csv()
.fromFile(DELIVERIES_FILE_PATH)
.then((deliveries) => {
//MATCHES PLAYED PER YEAR
let result = matchesPlayedPerYear(matches);
//number of matches won by each team over all the years of IPL
let result2 = matchesWonPerYear(matches);
//For the year 2016, plot the extra runs conceded by each team.
let result3=extras(matches,deliveries);
//Top economical bowlers of 2015
let result4=economical(matches,deliveries);
//matches won by each team per venue
let result5=teamWinbyVenue(matches);
saveJson(result,result2,result3,result4,result5);
});
});
}
function saveJson(result,result2,result3,result4,result5) {
const jsonData = {
matchesPlayedPerYear: result,
matchesWonPerYear: result2,
extraRunsIn2016: result3,
economicalBowlersEachYear:result4,
teamWinsperVenue:result5
};
const jsonString = JSON.stringify(jsonData);
fs.writeFile(JSON_OUTPUT_FILE_PATH, jsonString, "utf8", (err) => {
if (err) {
console.error(err);
}
});
}
// function saveMatchesWonPerYear(result) {
// const jsonData = {
// };
// // const jsonString = JSON.stringify(jsonData);
// fs.readFile(JSON_OUTPUT_FILE_PATH, "utf8", (err, data) => {
// if (err) {
// console.error(err);
// } else {
// obj = JSON.parse(data);
// obj = { ...obj, ...jsonData };
// json = JSON.stringify(obj);
// fs.writeFile(JSON_OUTPUT_FILE_PATH, json, "utf8", (err) => {
// if (err) {
// console.error(err);
// }
// });
// }
// });
// }
main();
<file_sep>/README.md
# ipl_data_visualization
ipl data visualization
## Install
## Demo https://vasanth-ipl-data-visualization.netlify.app/
**1: Install Node**
https://nodejs.org/en/download/
**2: Install git**
Linux: https://git-scm.com/downloads
Windows: https://gitforwindows.org/
Watch [this tutorial on YouTube](https://www.youtube.com/watch?v=rWboGsc6CqI) if required. Feel free to refer to other tutorials as well.
**3: Install VSCode**
https://code.visualstudio.com/download
**4: Clone this repository**
```sh
git clone https://github.com/codebantai/ipl_data_visualization.git
```
**5: Install npm packages**
```sh
npm install
```
**6: Prepare data**
```
npm run ipl
```
**7: Start server**
```
npm run start
```
**8: Visualize results on your browser**
Open http://127.0.0.1:8080
---
<file_sep>/ipl/extras.js
const extras = (matches, deliveries) => {
let int=parseInt;
let id_of_2016 = [];
let result = {};
for (let match of matches) {
let season = match.season;
let id = match.id;
if (season == 2016) id_of_2016.push(id);
}
for (let delivery of deliveries) {
let id = delivery.match_id;
let extraRuns = delivery.extra_runs;
let bowlingTeam = delivery.bowling_team;
if (id_of_2016.includes(id)) {
if (result[bowlingTeam]) {
result[bowlingTeam] += int(extraRuns);
} else {
result[bowlingTeam] = int(extraRuns);
}
}
}
return result;
};
module.exports = extras;
<file_sep>/ipl/topEconomicalBowler.js
const economical = (matches, deliveries) => {
let result={}
let int=parseInt;
let years=[]
for (let match of matches) {
let season = match.season;
if(!years.includes(season))years.push(season)
}
for(let year of years){
let tempResult={}
let obj = {};
// console.log(year)
let idEachYear=[]
for (let match of matches) {
let id = match.id;
let season = match.season;
if (season == year) idEachYear.push(id);
}
// console.log idEachYear)
for(let delivery of deliveries){
let bowler=delivery.bowler;
let totalRuns=delivery.total_runs;
let id=delivery.match_id;
if (idEachYear.includes(id)){
if(bowler in obj){
obj[bowler][0]+=1
obj[bowler][1]+=int(totalRuns);
}
else{
obj[bowler]=[]
obj[bowler][0]=1;
obj[bowler][1]=int(totalRuns);
}
}
}
for(let bowler in obj){
tempResult[bowler]=parseFloat((obj[bowler][1]/(obj[bowler][0]/6)).toFixed(2))
}
result[year] = Object.fromEntries(Object.entries(tempResult).sort((a,b) => a[1]-b[1]).slice(0,10))
}
return result
}
module.exports = economical; | 5b87692e2bc89f4934cb75a90ea2b90180d4c697 | [
"JavaScript",
"Markdown"
]
| 5 | JavaScript | vasanth-seven/ipl_data_visualization | a6e3cc28eedd6c439bdfa02d2948deab00f81503 | 07cfaa6cd8ab5ec7d2fc970898acdd1e87db5b1d |
refs/heads/master | <repo_name>malykhinvi/rush<file_sep>/README.md
This is a Rush monorepo example.
All packages are installed using npm, which has [a known issue](https://github.com/microsoft/rushstack/issues/886) with the npm v6.
It is better to migrate to PNPM (see [here](https://rushjs.io/pages/maintainer/package_managers/) why)
<file_sep>/libraries/ui-kit/Button.js
import React from 'react';
const Button = (props) => {
return props.children + '1asdfsdf'
}
export default Button; | d198d5fa28b516bf75142588d8ae5f4f1ba388c2 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | malykhinvi/rush | aa834aaf6b77be88bbf94d713ba82338c10ae2d0 | 923bf8a324f8098801ee89473311ff660c2603dd |
refs/heads/master | <file_sep>#coding:utf-8
# 简单分析:
# 这份代码和特征主要考虑了用户最近一段时间的行为,
# 设计了一个权值银子去计算用户在最近一段时间的访问特征
# 因此,可能时间窗口的特征过于强,反而对于很多统计特征的表达并不好
# 当前这份代码,线下线上成绩约等于 0.80625 - 0.8206 附近
# 不可考究是否过拟合或者其他,需要等B榜验证成绩
import pandas as pd
import numpy as np
np.random.seed(42)
import pickle
import warnings
warnings.filterwarnings('ignore')
import lightgbm as lgb
# 数据采样粒度为day
import os
import time
start_time = time.time()
# 读取原始数据
def read_data():
reshape_data_user_set = []
if os.path.exists('../cache/user_info_register_and_day.pkl'):
print('read user_info_register_and_day from pkl')
user_info_register_and_day = pickle.load(open('../cache/user_info_register_and_day.pkl','rb'))
else:
user_register_log = pd.read_csv('../data/user_register_log.txt', sep='\t', header=None,
dtype={0: np.str, 1: np.int, 2: np.int, 3: np.int})
user_register_log.columns = ['user_id', 'register_day', 'register_type', 'device_type']
reshape_data_1 = user_register_log[user_register_log['register_day']<22]
reshape_data_2 = user_register_log[user_register_log['register_day']>24]
# 随机采样
reshape_data_3 = user_register_log[user_register_log['register_day']==22].sample(frac=1)
reshape_data_4 = user_register_log[user_register_log['register_day']==23].sample(frac=1)
reshape_data_5 = user_register_log[user_register_log['register_day']==24].sample(frac=1)
reshape_data = pd.concat([reshape_data_1,reshape_data_2])
reshape_data = pd.concat([reshape_data,reshape_data_3])
reshape_data = pd.concat([reshape_data,reshape_data_4])
reshape_data = pd.concat([reshape_data,reshape_data_5])
reshape_data = reshape_data.reset_index(drop=True)
reshape_data_user_set = set(reshape_data['user_id'].unique())
# 根据用户注册信息补全到30号包括30号的用户行为信息
user_info_register_and_day = pd.DataFrame()
days = []
register_days = []
user_ids = []
register_types = []
device_types = []
for i in reshape_data.values:
day = int(i[1])
register_day = int(i[1])
user_id = i[0]
register_type = i[2]
device_type = i[3]
for j in range(day, 30 + 1):
days.append(j)
register_days.append(register_day)
user_ids.append(user_id)
register_types.append(register_type)
device_types.append(device_type)
del user_register_log
user_info_register_and_day['user_id'] = user_ids
user_info_register_and_day['register_day'] = register_days
user_info_register_and_day['register_type'] = register_types
user_info_register_and_day['device_type'] = device_types
user_info_register_and_day['day'] = days
pickle.dump(user_info_register_and_day,open('../cache/user_info_register_and_day.pkl','wb'))
if os.path.exists('../cache/app_launch_log.pkl'):
print('read app_launch_log from pkl')
app_launch_log = pickle.load(open('../cache/app_launch_log.pkl','rb'))
else:
app_launch_log = pd.read_csv('../data/app_launch_log.txt', sep='\t', header=None,
dtype={0: np.str, 1: np.int})
app_launch_log.columns = ['user_id', 'day']
app_launch_log = app_launch_log[app_launch_log['user_id'].isin(reshape_data_user_set)].reset_index(drop=True)
app_launch_log['app_launch_log_flag'] = 1
pickle.dump(app_launch_log, open('../cache/app_launch_log.pkl', 'wb'))
if os.path.exists('../cache/video_create_log.pkl'):
print('read video_create_log from pkl')
video_create_log = pickle.load(open('../cache/video_create_log.pkl','rb'))
else:
video_create_log = pd.read_csv('../data/video_create_log.txt', sep='\t', header=None,
dtype={0: np.str, 1: np.int})
video_create_log.columns = ['user_id', 'day']
video_create_log = video_create_log[video_create_log['user_id'].isin(reshape_data_user_set)].reset_index(drop=True)
video_create_log['video_flag'] = 1
pickle.dump(video_create_log, open('../cache/video_create_log.pkl', 'wb'))
if os.path.exists('../cache/user_activity_log.pkl'):
print('read user_activity_log from pkl')
user_activity_log = pickle.load(open('../cache/user_activity_log.pkl','rb'))
else:
user_activity_log = pd.read_csv('../data/user_activity_log.txt', sep='\t', header=None,
dtype={0: np.str, 1: np.int, 2: np.int, 3: np.int, 4: np.int, 5: np.int})
user_activity_log.columns = ['user_id', 'day', 'page', 'video_id', 'author_id', 'action_type']
user_activity_log = user_activity_log[user_activity_log['user_id'].isin(reshape_data_user_set)].reset_index(drop=True)
user_activity_log['user_activity_log_flag'] = 1
pickle.dump(user_activity_log, open('../cache/user_activity_log.pkl', 'wb'))
return user_info_register_and_day,app_launch_log,video_create_log,user_activity_log
# 获取数据的标签轴
def get_label(data_set,end_time,time_wide):
'''
:param data_set: user_info_register_and_day,app_launch_log,video_create_log,user_activity_log 活跃日志提取用户
:param end_time: 结束的日期
:param time_wide: 时间往前偏移量
:return: 用户集合 begin_time
'''
date_range = [x+1 for x in range(end_time-time_wide,end_time)]
register_date = date_range[0]
# 创建四个用户集合
register_user_set = set()
# 1.筛选 end_tiem - time_wide 之前注册的用户
register_user = data_set[0][data_set[0]['register_day'] < register_date]
if sorted(register_user['register_day'].unique())[-1] < register_date:
register_user_set = set(register_user['user_id'].unique())
print(sorted(register_user['register_day'].unique())[-1], 'day before register_user user number', len(register_user_set))
# 2.1 获取活跃用户的集合
app_launch_user = data_set[1][data_set[1]['day'].isin(date_range)]
# if (sorted(app_launch_user['day'].unique())== date_range):
app_launch_user_set = set(app_launch_user['user_id'].unique())
print(sorted(app_launch_user['day'].unique())[-1], sorted(app_launch_user['day'].unique())[0],
'day before app_launch_user user number', len(app_launch_user_set))
# 2.2 获取活跃用户的集合
video_create_log = data_set[2][data_set[2]['day'].isin(date_range)]
# if (video_create_log['day'].unique()== date_range):
video_create_user_set = set(video_create_log['user_id'].unique())
print(sorted(video_create_log['day'].unique())[-1], sorted(video_create_log['day'].unique())[0],
'day before video_create_log user number', len(video_create_user_set))
# 2.3 获取活跃用户的集合
user_activity_log = data_set[3][data_set[3]['day'].isin(date_range)]
# if (user_activity_log['day'].unique()== date_range):
user_activity_user_set = set(user_activity_log['user_id'].unique())
print(sorted(user_activity_log['day'].unique())[-1], sorted(user_activity_log['day'].unique())[0],
'day before user_activity_log user number', len(user_activity_user_set))
user_set = register_user_set & (app_launch_user_set | video_create_user_set | user_activity_user_set)
print('the future 7 day activate user',len(user_set))
return user_set,register_date - 1
# 线下成绩计算公式
def get_score(pre_user,true_user,day=0.0):
pre_user_set = set(pre_user)
true_user_set = set(true_user)
print(len(pre_user_set))
print(len(true_user_set))
try:
precision = len(pre_user_set&true_user_set)* 1.0 / len(pre_user_set)
recall = len(pre_user_set&true_user_set)* 1.0 / len(true_user_set)
print('%f precision %f'%(day,precision))
print('%f recall %f'%(day,recall))
F1_Score = (2.0 * precision * recall) / (precision + recall)
print('%f F1 %f'%(day,F1_Score))
return F1_Score
except:
print('0 user')
return 0
# 计算样本数据在真实值的概率
def get_xx_cover_radio(label,train_data):
print(u'all data of user',len(set(train_data)))
print(u'day user of data',len(set(label)))
train_data_in_label = len(set(label)&set(train_data)) * 1.0 / len(set(label))
get_score(set(train_data),set(label))
print(train_data_in_label)
# 获取样本
def get_sample(data_set,sample_time,true_user_set,time_wide=0):
date_range = [x for x in range(sample_time-time_wide,sample_time+1)]
print(date_range)
sample_user_basic_info = data_set[0][data_set[0]['day'].isin(date_range)]
sample_user_basic_info.loc[sample_user_basic_info['user_id'].isin(list(true_user_set)),'target'] = 1
sample_user_basic_info['target'] = sample_user_basic_info['target'].fillna(0)
# 计算覆盖和全集F1
get_xx_cover_radio(true_user_set,sample_user_basic_info['user_id'])
return sample_user_basic_info
from itertools import groupby
def get_max_seq_l(l):
l = sorted(l)
fun = lambda x: x[1] - x[0]
max_seq_tmp = []
for k, g in groupby(enumerate(l), fun):
max_seq_tmp.append([v for i, v in g])
return ([x for x in range(max(max_seq_tmp)[0],30+1)][-1] - max(max_seq_tmp)[-1])
from scipy.stats import mode
def get_mode(data):
# print(mode(data)[0][0])
return mode(data)[0][0]
# 获取特征
def make_feat(data_set,sample):
'''
:param data_set:
:param sample:
:return:
data_set = [user_info_register_and_day, app_launch_log, video_create_log, user_activity_log]
'''
# 简单的数据采样分析
# register_day register_type device_type 0
# 18147 24 3 1 1107
# 18178 24 4 1 21
# -----------------------------------------------------
# register_day register_type device_type 0
# 18908 25 3 1 8
# -----------------------------------------------------
# register_day register_type device_type 0
# 19704 26 3 1 4
# 83 223
feat_sample = sample.copy()
sample_date = sample['day'].unique()[0]
print('sample_data', sample['day'].unique())
sample_copy = pd.DataFrame()
days = []
register_days = []
user_ids = []
register_types = []
device_types = []
# 重构 sample data
for i in sample.values:
register_day = int(i[1])
user_id = i[0]
register_type = i[2]
device_type = i[3]
for j in range(max(sample_date - 14,register_day), sample_date + 1):
days.append(j)
register_days.append(register_day)
user_ids.append(user_id)
register_types.append(register_type)
device_types.append(device_type)
sample_copy['user_id'] = user_ids
sample_copy['register_day'] = register_days
sample_copy['register_type'] = register_types
sample_copy['device_type'] = device_types
sample_copy['day'] = days
sample_copy['user_id'] = sample_copy['user_id'].astype(str)
print('-------------------------------------------')
print('reshape_sample_data_shape',sample_copy.shape)
print('-------------------------------------------')
sample['user_id'] = sample['user_id'].astype(str)
data_set[1]['user_id'] = data_set[1]['user_id'].astype(str)
data_set[2]['user_id'] = data_set[2]['user_id'].astype(str)
data_set[3]['user_id'] = data_set[3]['user_id'].astype(str)
data_set[0]['user_id'] = data_set[0]['user_id'].astype(str)
sample = pd.merge(sample_copy,sample,on=['user_id','register_day','register_type','device_type','day'],how='left',copy=False)
# 采取半个月的用户历史特征
time_scale = [x for x in range(sample_date - 14, sample_date + 1)]
print('特征采集范围',sorted(time_scale),len(time_scale))
launch_feat_ = data_set[1][data_set[1]['day'].isin(time_scale)]
sample = pd.merge(sample, launch_feat_, on=['user_id','day'], how='left', copy=False)
sample['app_launch_log_flag'] = sample['app_launch_log_flag'].fillna(0)
# bug 但是提分了,用户每天可能多次启动APP进行拍摄,直接与启动日志拼接,比去重后分数有所提高
# 考虑到发生这样的bug,认为每次拍摄行为,应该是出发一次启动APP的日志
video_create_feat_ = data_set[2][data_set[2]['day'].isin(time_scale)]
video_create_feat_copy = data_set[2][data_set[2]['day'].isin(time_scale)]
# video_create_feat_ = video_create_feat_.groupby(['user_id', 'day'])['video_flag'].sum().reset_index()
# video_create_feat_.columns = ['user_id', 'day', 'video_flag']
sample = pd.merge(sample, video_create_feat_, on=['user_id', 'day'], how='left', copy=False)
sample['video_flag'] = sample['video_flag'].fillna(0)
user_activity_feat_ = data_set[3][data_set[3]['day'].isin(time_scale)][['user_id','day','user_activity_log_flag']].drop_duplicates()
user_activity_feat_copy = data_set[3][data_set[3]['day'].isin(time_scale)]
# 提取用户序列行为的特征集合
# print(user_activity_feat_copy.columns)
user_activity_feat_f = user_activity_feat_copy.copy()
user_activity_feat_f['video_id'] = user_activity_feat_f['video_id'].astype(str)
user_video_seq_f = user_activity_feat_f.groupby(['user_id'])['video_id'].apply(lambda x:' '.join(list(set(x)))).reset_index()
user_video_seq_f.columns = ['user_id','video_seq_']
sample = pd.merge(sample, user_activity_feat_, on=['user_id', 'day'], how='left', copy=False)
sample['user_activity_log_flag'] = sample['user_activity_log_flag'].fillna(0)
# 以下为增加权重系数的特征组合
# 增加权重系数
sample['weight'] = sample_date + 1 - sample['day']
sample['weight'] = 1 / sample['weight']
sample['app_launch_log_flag'] = sample['app_launch_log_flag'] * sample['weight']
sample['video_flag'] = sample['video_flag'] * sample['weight']
sample['user_activity_log_flag'] = sample['user_activity_log_flag'] * sample['weight']
print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^')
print('before sample shape',sample.shape)
print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^')
###############################################################################
# 最近 7 天的用户行为 和 权重
sample_copy['day'] = sample_copy['day'].astype(int)
sample_copy_seven = sample_copy[sample_copy['day'] >= (sample_date - 7)]
print(sample_copy_seven.shape)
time_scale_seven = [x for x in range(sample_date - 7, sample_date + 1)]
launch_feat_seven = data_set[1][data_set[1]['day'].isin(time_scale_seven)]
launch_feat_seven = launch_feat_seven.sort_values(['user_id','day'])
sample_seven_s = pd.merge(sample_copy_seven, launch_feat_seven, on=['user_id', 'day'], how='left', copy=False)
sample_seven_s['app_launch_log_flag'] = sample_seven_s['app_launch_log_flag'].fillna(0)
video_create_feat_7 = data_set[2][data_set[2]['day'].isin(time_scale_seven)]
# video_create_feat_7 = video_create_feat_7.groupby(['user_id', 'day'])['video_flag'].sum().reset_index()
# video_create_feat_7.columns = ['user_id', 'day', 'video_flag']
sample_seven_s = pd.merge(sample_seven_s, video_create_feat_7, on=['user_id', 'day'], how='left', copy=False)
sample_seven_s['video_flag'] = sample_seven_s['video_flag'].fillna(0)
user_activity_feat_7 = data_set[3][data_set[3]['day'].isin(time_scale_seven)][['user_id', 'day', 'user_activity_log_flag']].drop_duplicates()
sample_seven_s = pd.merge(sample_seven_s, user_activity_feat_7, on=['user_id', 'day'], how='left', copy=False)
sample_seven_s['user_activity_log_flag'] = sample_seven_s['user_activity_log_flag'].fillna(0)
sample_seven = sample_seven_s[['user_id','day','app_launch_log_flag','video_flag','user_activity_log_flag']]
sample_seven['weight'] = sample_date + 1 - sample_seven['day']
sample_seven['weight'] = 1 / sample_seven['weight']
sample_seven['app_launch_log_flag'] = sample_seven['app_launch_log_flag'] * sample_seven['weight']
sample_seven['video_flag'] = sample_seven['video_flag'] * sample_seven['weight']
sample_seven['user_activity_log_flag'] = sample_seven['user_activity_log_flag'] * sample_seven['weight']
print(sample_seven.shape)
###############################################################################
# 3 days
sample_copy_3 = sample_copy[sample_copy['day'] >= (sample_date - 3)]
print(sample_copy_3.shape)
time_scale_3 = [x for x in range(sample_date - 3, sample_date + 1)]
launch_feat_3 = data_set[1][data_set[1]['day'].isin(time_scale_3)]
launch_feat_3 = launch_feat_3.sort_values(['user_id','day'])
sample_seven_s3 = pd.merge(sample_copy_3, launch_feat_3, on=['user_id', 'day'], how='left', copy=False)
sample_seven_s3['app_launch_log_flag'] = sample_seven_s3['app_launch_log_flag'].fillna(0)
video_create_feat_3 = data_set[2][data_set[2]['day'].isin(time_scale_3)]
# video_create_feat_3 = video_create_feat_3.groupby(['user_id', 'day'])['video_flag'].sum().reset_index()
# video_create_feat_3.columns = ['user_id', 'day', 'video_flag']
sample_seven_s3 = pd.merge(sample_seven_s3, video_create_feat_3, on=['user_id', 'day'], how='left', copy=False)
sample_seven_s3['video_flag'] = sample_seven_s3['video_flag'].fillna(0)
user_activity_feat_3 = data_set[3][data_set[3]['day'].isin(time_scale_3)][
['user_id', 'day', 'user_activity_log_flag']].drop_duplicates()
sample_seven_s3 = pd.merge(sample_seven_s3, user_activity_feat_3, on=['user_id', 'day'], how='left', copy=False)
sample_seven_s3['user_activity_log_flag'] = sample_seven_s3['user_activity_log_flag'].fillna(0)
sample_seven_s3 = sample_seven_s3[['user_id','day','app_launch_log_flag','video_flag','user_activity_log_flag']]
sample_seven_s3['weight'] = sample_date + 1 - sample_seven_s3['day']
sample_seven_s3['weight'] = 1 / sample_seven_s3['weight']
sample_seven_s3['app_launch_log_flag'] = sample_seven_s3['app_launch_log_flag'] * sample_seven_s3['weight']
sample_seven_s3['video_flag'] = sample_seven_s3['video_flag'] * sample_seven_s3['weight']
sample_seven_s3['user_activity_log_flag'] = sample_seven_s3['user_activity_log_flag'] * sample_seven_s3['weight']
print(sample_seven_s3.shape)
###############################################################################
# 1.增加时间权重特征
# 1.1.窗口内用户 user_activity_log_flag 的频次
user_activate_c_feat_in_windows = sample.groupby(['user_id'])['user_activity_log_flag'].sum().reset_index()
user_activate_c_feat_in_windows.columns = ['user_id', 'windows_user_activity_feat']
# 1.2.窗口内用户video_flag的频次
user_video_feat_in_windows = sample.groupby(['user_id'])['video_flag'].sum().reset_index()
user_video_feat_in_windows.columns = ['user_id', 'windows_create_video_feat']
# 1.3.用户在一个窗口期内的访问日访问频次特征
user_activate_feat_in_windows = sample.groupby(['user_id'])['app_launch_log_flag'].sum().reset_index()
user_activate_feat_in_windows.columns = ['user_id','windows_launch_feat']
# 1.4 windows 7 特征统计
user_activate_7_feat_in_windows = sample_seven.groupby(['user_id'])['app_launch_log_flag'].sum().reset_index()
user_activate_7_feat_in_windows.columns = ['user_id', 'windows_7_launch_feat']
# 1.6 windows 3
user_activate_3_feat_in_windows = sample_seven_s3.groupby(['user_id'])['app_launch_log_flag'].sum().reset_index()
user_activate_3_feat_in_windows.columns = ['user_id', 'windows_3_launch_feat']
# user_log_3_feat_in_windows = sample_seven_s3.groupby(['user_id'])['user_activity_log_flag'].sum().reset_index()
# user_log_3_feat_in_windows.columns = ['user_id', 'user_activity_log_flag']
# feat_sample = pd.merge(feat_sample,user_log_3_feat_in_windows,on='user_id',how='left',copy=False)
feat_sample = pd.merge(feat_sample,user_activate_feat_in_windows,on='user_id',how='left',copy=False)
del user_activate_feat_in_windows
feat_sample = pd.merge(feat_sample,user_video_feat_in_windows,on='user_id',how='left',copy=False)
del user_video_feat_in_windows
feat_sample = pd.merge(feat_sample,user_activate_c_feat_in_windows,on='user_id',how='left',copy=False)
del user_activate_c_feat_in_windows
# 最近7天行为
feat_sample = pd.merge(feat_sample,user_activate_7_feat_in_windows,on='user_id',how='left',copy=False)
del user_activate_7_feat_in_windows
# 最近3天行为
feat_sample = pd.merge(feat_sample,user_activate_3_feat_in_windows,on='user_id',how='left',copy=False)
del user_activate_3_feat_in_windows
# 1.4. 二次特征组合
feat_sample['bayes_f1'] = feat_sample['windows_create_video_feat'] / (feat_sample['windows_launch_feat'] + 0.00001)
feat_sample['bayes_f2'] = feat_sample['windows_user_activity_feat'] / (feat_sample['windows_launch_feat'] + 0.00001)
feat_sample['bayes_f3'] = feat_sample['windows_7_launch_feat'] / (feat_sample['windows_launch_feat'] + 0.00001)
feat_sample['bayes_f4'] = (feat_sample['windows_launch_feat'] - feat_sample['windows_7_launch_feat']) / (feat_sample['windows_launch_feat'] + 0.00001)
# add feat 用户最近一次启动的时间的时间差
user_current_launch_app_time_gap = launch_feat_.groupby(['user_id']).day.max().reset_index()
user_current_launch_app_time_gap['current_onec_launch'] = sample_date - user_current_launch_app_time_gap['day'] + 1
feat_sample = pd.merge(feat_sample, user_current_launch_app_time_gap[['user_id', 'current_onec_launch']],on=['user_id'], how='left', copy=False)
feat_sample['current_onec_launch'] = feat_sample['current_onec_launch'].fillna(17 + 1)
#
# user_current_launch_app_time_gap = launch_feat_.groupby(['user_id']).day.min().reset_index()
# user_current_launch_app_time_gap['last_onec_launch'] =user_current_launch_app_time_gap['day']
# feat_sample = pd.merge(feat_sample, user_current_launch_app_time_gap[['user_id', 'last_onec_launch']],
# on=['user_id'], how='left', copy=False)
# feat_sample['last_onec_launch'] = feat_sample['last_onec_launch'].fillna(-1)
# action page 特征
user_action_f_ = pd.concat([user_activity_feat_copy,pd.get_dummies(user_activity_feat_copy['page'],prefix='page')],axis=1)
user_action_f_ = pd.concat([user_action_f_,pd.get_dummies(user_activity_feat_copy['action_type'],prefix='action_type')],axis=1)
# 视频不同行为的特征
# 视频的统计特征 用户对视频统计特征的统计 action
video_windwos_feat_ = user_action_f_.groupby(['video_id'])[['action_type_0', 'action_type_1', 'action_type_2',
'action_type_3', 'action_type_4', 'action_type_5']].mean().reset_index()
video_windwos_feat_ = pd.merge(user_action_f_[['user_id','video_id']].copy(),video_windwos_feat_,on=['video_id'],how='left',copy=False)
video_windwos_feat_ = video_windwos_feat_.groupby(['user_id'])[['action_type_0', 'action_type_1', 'action_type_2',
'action_type_3', 'action_type_4','action_type_5']].mean().reset_index()
feat_sample = pd.merge(feat_sample,video_windwos_feat_,on=['user_id'],how='left',copy=False)
del video_windwos_feat_
# 用户习惯访问页页面的特征
video_page_windwos_feat_ = user_action_f_.groupby(['user_id'])[['page_0', 'page_1', 'page_2',
'page_3', 'page_4'
]].mean().reset_index()
feat_sample = pd.merge(feat_sample, video_page_windwos_feat_, on=['user_id'], how='left',copy=False)
del video_page_windwos_feat_
# 用户启动app的时间差特征
# launch_feat_1 = launch_feat_.copy()
#
# launch_feat_ = launch_feat_.sort_values(['user_id','day'])
# launch_feat_['time_launch_diff'] = launch_feat_.groupby(['user_id']).day.diff(-1).apply(np.abs)
# launch_feat_ = launch_feat_[['user_id','time_launch_diff']].dropna()
# launch_feat_ = launch_feat_.groupby(['user_id'])['time_launch_diff'].agg({
# 'time_launch_diff_max':np.max,
# 'time_launch_diff_std':np.std,
# 'time_launch_diff_median':np.median,
# }).reset_index()
#
# feat_sample = pd.merge(feat_sample, launch_feat_, on=['user_id'], how='left')
# del launch_feat_
#
# # 上2次的访问时间差
# launch_feat_1 = launch_feat_1.sort_values(['user_id', 'day'])
# launch_feat_1['time_launch_diff'] = launch_feat_1.groupby(['user_id']).day.diff(-2).apply(np.abs)
# launch_feat_1 = launch_feat_1[['user_id', 'time_launch_diff']].dropna()
# launch_feat_1 = launch_feat_1.groupby(['user_id'])['time_launch_diff'].agg({
# 'time_launch_diff_max1': np.max,
# 'time_launch_diff_std1': np.std,
# 'time_launch_diff_median1': np.median
# }).reset_index()
#
# feat_sample = pd.merge(feat_sample, launch_feat_1, on=['user_id'], how='left')
# 用户 video nunique 特征
user_activity_f_video = user_activity_feat_copy.groupby(['user_id'])['video_id'].nunique().reset_index()
user_activity_f_video.columns = ['user_id','nunique_video']
feat_sample = pd.merge(feat_sample, user_activity_f_video, on=['user_id'], how='left')
# 用户 author nunique 特征
user_activity_f_author = user_activity_feat_copy.groupby(['user_id'])['author_id'].nunique().reset_index()
user_activity_f_author.columns = ['user_id', 'nunique_author']
feat_sample = pd.merge(feat_sample, user_activity_f_author, on=['user_id'], how='left',copy=False)
# 用户重复观看作品的次数特征
# xtmp = user_activity_feat_copy.groupby(['user_id','author_id']).size().reset_index()
# xtmp.columns = ['user_id','author_id','rep_author']
# xtmp = xtmp.sort_values(['rep_author','user_id'])
#
# xtmp = xtmp.groupby(['user_id'])['rep_author'].agg({
# 'rep_author_mean':np.mean,
# 'rep_author_std':np.std,
# })
#
# feat_sample = pd.merge(feat_sample, xtmp, on=['user_id'], how='left',copy=False)
# windows内的视频每天被多少人观看 除去当前用户本身
# authored_user = user_activity_feat_copy.groupby(['video_id'])['user_id'].nunique().reset_index()
# authored_user.columns = ['video_id','user_nunique']
# authored_user = pd.merge(user_activity_feat_copy[['user_id','video_id']],authored_user,on=['video_id'],how='left',copy=False)
# authored_user['user_nunique'] = authored_user['user_nunique'] - 1
# authored_user = authored_user.groupby(['user_id'])['user_nunique'].agg({
# 'user_nunique_mean':np.mean,
# 'user_nunique_std':np.std,
# }).reset_index()
#
# feat_sample = pd.merge(feat_sample,authored_user,on=['user_id'],how='left',copy=False)
# del user_action_f_
#
# feat_sample = pd.merge(feat_sample,user_video_seq_f,on=['user_id'],how='left',copy=False)
# 注册类型的平均访问时间特征
# register_launch_feat = feat_sample.groupby(['register_type']).windows_launch_feat.agg({
# 'register_type_mean':np.mean,
# # 'register_type_median':np.median
# }).reset_index()
# # register_launch_feat.columns = ['register_type','register_launch_feat']
#
# feat_sample = pd.merge(feat_sample,register_launch_feat,on=['register_type'],how='left',copy=False)
# register_launch_feat = feat_sample.groupby(['device_type']).windows_launch_feat.mean().reset_index()
# register_launch_feat.columns = ['device_type', 'register_launch_feat']
#
# feat_sample = pd.merge(feat_sample, register_launch_feat, on=['device_type'], how='left', copy=False)
# #
# user_create_video_times = video_create_feat_copy.groupby(['user_id']).size().reset_index()
# user_create_video_times.columns = ['user_id','user_create_video_times']
# feat_sample = pd.merge(feat_sample,user_create_video_times,on=['user_id'],how='left',copy=False)
#
# user_current_launch_app_time_gap = sample[sample['app_launch_log_flag'] >= 1].groupby(['user_id']).day.max().reset_index()
# user_current_launch_app_time_gap['current_onec_launch'] = sample_date - user_current_launch_app_time_gap['day'] + 1
# feat_sample = pd.merge(feat_sample, user_current_launch_app_time_gap[['user_id', 'current_onec_launch']],on=['user_id'], how='left', copy=False)
# feat_sample['current_onec_launch'] = feat_sample['current_onec_launch'].fillna(sample_date+1)
#
# 用户观看的视频频次
# user_video_size_ = user_activity_feat_copy.groupby(['user_id'])['video_id'].size().reset_index()
# user_video_size_.columns = ['user_id', 'user_video_size_']
# feat_sample = pd.merge(feat_sample, user_video_size_, on=['user_id'], how='left', copy=False)
# 用户每天观看视频的频次
# user_video_size = user_activity_feat_copy.groupby(['user_id', 'day'])['video_id'].size().reset_index()
# user_video_size.columns = ['user_id', 'day', 'user_video_size']
# user_video_size = user_video_size.groupby(['user_id']).user_video_size.agg({
# 'user_video_size_mean': np.mean,
# # 'user_video_size_std': np.std,
# }).reset_index()
# feat_sample = pd.merge(feat_sample, user_video_size, on=['user_id'], how='left', copy=False)
# 用户每天视频的重复次数
# user_video_day_size = user_activity_feat_copy.groupby(['user_id', 'day', 'video_id']).size().reset_index()
# user_video_day_size.columns = ['user_id', 'day', 'video_id', 'user_video_day_size']
# user_video_day_size = user_video_day_size.groupby(['user_id']).user_video_day_size.agg({
# 'user_video_day_size_mean': np.mean,
# 'user_video_day_size_std': np.std,
# }).reset_index()
# feat_sample = pd.merge(feat_sample, user_video_day_size, on=['user_id'], how='left', copy=False)
# for day in [1, 2, 3, 5, 7, 14, 21]:
# tmp = user_activity_feat_copy[user_activity_feat_copy['day'] > sample_date - day]
# print(sorted(tmp['day'].unique()))
# day_tmp = tmp.groupby(['user_id'])['video_id'].size().reset_index()
# day_tmp.columns = ['user_id', 'video_id_before_%d' % (day)]
# feat_sample = pd.merge(feat_sample, day_tmp, on=['user_id'], how='left', copy=False)
# feat_sample['video_id_before_%d' % (day)] = feat_sample['video_id_before_%d' % (day)].fillna(0)
print(len(feat_sample['user_id'].unique()),feat_sample.shape)
return feat_sample
def make_category_feat(train_val_test):
return train_val_test
def get_train_val_test():
user_info_register_and_day, app_launch_log, video_create_log, user_activity_log = read_data()
data_set = [user_info_register_and_day, app_launch_log, video_create_log, user_activity_log]
# 1.提交数据的样本集合
print('===================sub sample===================')
sub_sample = get_sample(data_set, 30, set(data_set[0][data_set[0]['day']==30]['user_id']))
# 特征
sub_sample = make_feat(data_set,sub_sample)
# 2.线下验证/训练数据集
train_val = pd.DataFrame()
# 构造三组样本
# 样本区间
# 特征区间 9 样本标签 7
# 样本 0 22-30 | 31-37
# 样本 1 15-23 | 24-30
# 样本 2 08-16 | 17-23
# 样本 3 01-09 | 10-16
# 样本 1 2 3
label_dict = {}
lllll = [7,7]
for c, i in enumerate([0, 7]):
print('===================windows %d==================='%(i))
true_user_set, sample_day = get_label(data_set, 30-i, lllll[c])
sample_and_basic_user_info = get_sample(data_set,sample_day,true_user_set)
# 特征
sample_and_basic_user_info = make_feat(data_set, sample_and_basic_user_info)
label_dict[30 - i - lllll[c]] = true_user_set
train_val = pd.concat([train_val,sample_and_basic_user_info],axis=0)
#
print('train_val',train_val['day'].unique())
print('sub_sample',sub_sample['day'].unique())
#
train_val_test = pd.concat([train_val,sub_sample],axis=0)
train_val_test = make_category_feat(train_val_test)
return train_val_test,label_dict
feat_data,label_dict = get_train_val_test()
# print('save label and feat')
# f = open('../tmp/label_dict_label','w')
# f.write(str(label_dict))
# f.close()
# feat_data.to_csv('../tmp/feat_data.csv',index=False)
#
# print('load cultures feat form file 901')
# feat_data = feat_data.reset_index(drop=True)
# tmp = pd.read_csv('../tmp/xxxxx.csv')
#
# feat_data = pd.concat([feat_data,tmp],axis=1)
print(feat_data.shape)
# del feat_data['video_seq_']
del feat_data['register_day']
print(feat_data.dtypes)
##################################################################
print('split val and train and test for all data',feat_data.shape)
sub = feat_data[feat_data['day']==30]
to_sub = feat_data[feat_data['day']!=30]
val = feat_data[feat_data['day'].isin([23])]
train = feat_data[~feat_data['day'].isin([23,30])]
# print(train['day'].unique())
# train_user_id = train[train['day']==16]['user_id'].unique()
# train_ext = train[train['day']!=16]
# train_ext = train_ext[~train_ext['user_id'].isin(train_user_id)]
# print('ext_feat',train_ext.shape)
# print('16_day_shape',train[train['day']==16].shape)
# train = pd.concat([train_ext,train[train['day']==16]])
# print('all_data',train.shape)
print('sample ratdio')
print(train[train['target']==1].shape[0],train.shape[0])
print(val[val['target']==1].shape[0],val.shape[0])
print(sub[sub['target']==1].shape[0],sub.shape[0])
print(sub['day'].unique(),sub.shape)
print(val['day'].unique(),val.shape)
print(train['day'].unique(),train.shape)
del sub['day'],val['day'],train['day'],to_sub['day']
y_train = train.pop('target')
train_user_index = train.pop('user_id')
X_train = train.values
print(train.columns)
y_test = val.pop('target')
val_user_index = val.pop('user_id')
X_test = val[train.columns].values
y_sub = sub.pop('target')
sub_user_index = sub.pop('user_id')
X_sub = sub[train.columns].values
y_to_sub = to_sub.pop('target')
to_sub_user_index = to_sub.pop('user_id')
X_to_sub = to_sub[train.columns].values
# create dataset for lightgbm
lgb_train = lgb.Dataset(X_train, y_train)
lgb_train_2 = lgb.Dataset(X_to_sub, y_to_sub)
lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)
lgb_eval_2 = lgb.Dataset(X_to_sub, y_to_sub, reference=lgb_train_2)
# specify your configurations as a dict
params = {
'boosting_type': 'gbdt',
'objective': 'binary',
'metric': {'binary_logloss'},
'num_leaves': 8,
'learning_rate': 0.05,
'feature_fraction': 0.9,
'bagging_fraction': 0.8,
'bagging_freq': 5,
'verbose': -1,
'two_round':'true',
'seed':42
}
print('Start training...')
# train
gbm = lgb.train(params,
lgb_train,
num_boost_round=30000,
valid_sets=lgb_eval,
verbose_eval=250,
early_stopping_rounds=250,
)
y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration)
print('Feature importances:', list(gbm.feature_importance()))
imp = pd.DataFrame()
imp['col'] = list(train.columns)
imp['feat'] = list(gbm.feature_importance())
val_df = pd.DataFrame()
val_df['user_id'] = list(val_user_index.values)
val_df['y_pred'] = list(y_pred)
val_df = val_df.sort_values('y_pred',ascending=False)
select_dict = {}
for i in range(10):
print((i + 1.0) / 10)
select_dict[(i+1.0)/10] = get_score(set(val_df[val_df['y_pred']>(i+1.0)/10]['user_id']),label_dict[23],(i+1.0)/10)
select_dict_zip = zip(select_dict.keys(),select_dict.values())
select_dict_sort = sorted(select_dict_zip,key=lambda x:x[1],reverse=True)[0]
print('beat values',select_dict_sort[0])
print('beat score',round(select_dict_sort[1],6))
print(int(gbm.best_iteration * 1.1))
print(int(gbm.best_iteration))
print('predict_2')
gbm_2 = lgb.train(params,
lgb_train_2,
num_boost_round= int(gbm.best_iteration * 1.1),
valid_sets=lgb_eval_2,
verbose_eval=50,
)
import datetime
submit = gbm_2.predict(X_sub, num_iteration=gbm_2.best_iteration)
sub_df = pd.DataFrame()
sub_df['user_id'] = list(sub_user_index.values)
sub_df['y_pred'] = list(submit)
print('sub_values',select_dict_sort[0])
sub_df = sub_df[sub_df['y_pred']>select_dict_sort[0]]['user_id']
sub_df = pd.DataFrame(sub_df).drop_duplicates()
sub_df.to_csv('../submit/%s_%s.csv'%(str(datetime.datetime.now().date()).replace('-',''),str(round(select_dict_sort[1],6)).split('.')[1]),index=False,header=None)
print('save model')
gbm.save_model('../model/model_%s_%s.txt'%(str(datetime.datetime.now().date()).replace('-',''),str(round(select_dict_sort[1],6)).split('.')[1]))
print(time.time()-start_time)
# 采取固定提交策略
| c773ca065cf70e09abe5cb252755d7c9f87077c4 | [
"Python"
]
| 1 | Python | xuke16/baseline_ks | 33b0c19eb4ecb038bc7977ab95cf5e87d8e73624 | 72e67575ecf06e3eb995f69215ceb66c04d2eff6 |
refs/heads/master | <file_sep>const Discord = require('discord.js');
const client = new Discord.Client();
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
if (message.content === 'ping') {
message.reply('pong');
}
console.log(message);
});
client.on('presenceUpdate', function(oldMember, newMember) {
console.log(oldMember.presence, '=>', newMember.presence);
});
client.login(process.env.DISCORD_TOKEN);
app.listen(process.env.PORT || 5000);
| 3c524dd369a964b81feda32328bbb0b2ab3b1776 | [
"JavaScript"
]
| 1 | JavaScript | jow31/projet_chatbox | 0e831cf5aceffe691cbd0be6dbc74b1cbdf31a19 | d9069d4c341d9438e178ca86a29ff33b6efeee6c |
refs/heads/master | <repo_name>MechMK1/mechmk1.me<file_sep>/README.md
# mechmk1.me
Public webpages for mechmk1.me
<file_sep>/upload.mechmk1.me/upload.php
<?php
function getFileName($dir, $filename)
{
if(!file_exists($dir . $filename))
return $filename;
$path_parts = pathinfo($dir . $filename);
$ext = $path_parts['extension'];
$fn = $path_parts['filename'];
for ($i = 1; $i < 1337; $i++)
{
if(!empty($ext))
{
$newname = sprintf('%s (%u).%s', $fn, $i, $ext);
}
else
{
$newname = sprintf('%s (%u)', $fn, $i);
}
if(!file_exists($dir . $newname))
return $newname;
}
throw new RuntimeException('No suitable file location found');
}
header('Content-type:application/json;charset=utf-8');
try
{
//If this is not a POST request, we throw an error and quit
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
throw new RuntimeException('Not a POST request.');
}
//PHP thinks everything is an error. This means if everything is OK, 'error' is set to UPLOAD_ERR_OK.
//What the fuck, PHP. Was 'error' == NULL not good enough for you?
//Anyways, if 'error' doesn't exist or is an array(?) we quit.
if (!isset($_FILES['file']['error']) || is_array($_FILES['file']['error']))
{
throw new RuntimeException('Invalid parameters.');
}
//Switch based on the error message
switch ($_FILES['file']['error'])
{
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
//Set the filepath to /var/www/upload and the format to uniqid()+filename
$dir = '/var/www/filebox.mechmk1.me/Uploads/';
//$filename = sprintf('%s+%s', uniqid(), $_FILES['file']['name']);
$filename = getFileName($dir, $_FILES['file']['name']);
$filepath = $dir . $filename;
//Try to save the uploaded files. If it succeeds, yay. If not, throw an exception
if (!move_uploaded_file($_FILES['file']['tmp_name'], $filepath))
{
throw new RuntimeException('Failed to move uploaded file.');
}
// All good, send the response
echo json_encode([
'status' => 'ok',
'path' => $filename
]);
}
catch (RuntimeException $e) {
// Something went wrong, send the err message as JSON
http_response_code(400);
echo json_encode([
'status' => 'error',
'message' => $e->getMessage()
]);
}
| 763e76fb07876f009405ad278880836b9c9dd5fa | [
"Markdown",
"PHP"
]
| 2 | Markdown | MechMK1/mechmk1.me | b781e65a6b1d9b9a97be8cb67b77084e72b11efe | 3e92575e59e8be9e013e85c6163ec39b8810e087 |
refs/heads/master | <repo_name>FernandoHen/Lab6mapas<file_sep>/src/Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Cartas cards = new Cartas("linkedhash");
boolean cont = true;
System.out.println("Selccione implementacion a utilizar (Opcion incorrecta utilizara implementacion default): ");
System.out.println("1. HashMap");
System.out.println("2. TreeMap");
System.out.println("3. LinkedHashMap");
String map = sc.nextLine();
switch(map) {
case "1":
cards = new Cartas("hash");
break;
case "2":
cards = new Cartas("tree");
break;
case "3":
cards = new Cartas("linkedhash");
break;
default:
cards = new Cartas("");
break;
}
while(true) {
System.out.println("Ingrese ruta del archivo de cartas: ");
String filePath = sc.nextLine();
try {
cards.addCartas(filePath);
break;
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
while(cont) {
System.out.println("Ingrese una opcion: ");
System.out.println("1. Agregar una carta a la coleccion.");
System.out.println("2. Cambiar tipo de carta.");
System.out.println("3. Mostrar coleccion de cartas.");
System.out.println("4. Mostrar coleccion de cartas ordenadas por tipo.");
System.out.println("5. Mostrar cartas disponibles.");
System.out.println("6. Mostrar cartas disponibles ordenadas por tipo.");
String opt = sc.nextLine();
switch(opt) {
case "1":
System.out.println("Ingrese el nombre de la carta a agregar a la coleccion: ");
System.out.println((cards.addCardToCollection(sc.nextLine()) ? "Agregada exitosamente" : "Error al agregar carta!"));
break;
case "2":
System.out.println("Ingrese el nombre de la carta a agregar a cambiar tipo: ");
String nombre = sc.nextLine();
System.out.println("Ingrese nuevo tipo de carta: ");
String tipo = sc.nextLine();
System.out.println((cards.cambiarTipoCarta(nombre, tipo) ? "Cambio exitoso!" : "Error al realizar cambio."));
break;
case "3":
System.out.println("Cartas en la coleccion: ");
for(Carta c : cards.getColeccionCartas()) {
System.out.println(c);
}
break;
case "4":
System.out.println("Cartas en la coleccion: ");
for(Carta c : cards.getColeccionOrdenada()) {
System.out.println(c);
}
break;
case "5":
System.out.println("Cartas disponibles: ");
for(Carta c : cards.getCartasDisponiblesArray()) {
System.out.println(c);
}
break;
case "6":
System.out.println("Cartas disponibles: ");
for(Carta c : cards.getCartasDisponiblesOrdenada()) {
System.out.println(c);
}
break;
default:
System.out.println("Opcion invalida, intente de nuevo!");
break;
}
System.out.println("Continuar?... s/n");
switch(sc.nextLine().toLowerCase()) {
case "s":
cont = true;
break;
default:
cont = false;
break;
}
}
sc.close();
}
}
<file_sep>/src/Cartas.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.AbstractMap;
/**
* Cartas
* @author <NAME> 171001
* @author <NAME> 17699
*
*/
public class Cartas {
private AbstractMap<String, Carta> cartasDisponibles;
private AbstractMap<String, Carta> coleccion;
public Cartas(String tipo) {
this.setMaps(tipo);
}
/**
* @return the cartasDisponibles
*/
public AbstractMap<String, Carta> getCartasDisponibles() {
return cartasDisponibles;
}
/**
* @param cartasDisponibles the cartasDisponibles to set
*/
public void setCartasDisponibles(AbstractMap<String, Carta> cartasDisponibles) {
this.cartasDisponibles = cartasDisponibles;
}
/**
* Definir el tipo de implementacion de los mapas de esta clase
* @param tipo tipo deimplementacion del mapa
*/
public void setMaps(String tipo) {
this.cartasDisponibles = MapFactory.getMap(tipo);
this.coleccion = MapFactory.getMap(tipo);
}
/**
* Agregar las cartas del archivo de texto al mapa de cartas disponibles
* @param filePath Direccion del archivo de texto donde se leeran las cartas
* @throws Exception En caso de error se retornara una Exception
*/
public void addCartas(String filePath) throws Exception {
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
while((line = reader.readLine()) != null) {
String[] cartas = line.split("\\|");
if(cartas[1].toLowerCase().equals("monstruo") || cartas[1].toLowerCase().equals("trampa") ||cartas[1].toLowerCase().equals("hechizo")) {
Carta carta = new Carta(cartas[0], cartas[1], 0);
this.cartasDisponibles.put(carta.getNombre(), carta);
}
}
reader.close();
} catch (Exception e) {
throw e;
}
}
/**
* @param nombreCarta
* @return
*/
public boolean addCardToCollection(String nombreCarta) {
if(this.cartasDisponibles.containsKey(nombreCarta)){
if(this.coleccion.containsKey(nombreCarta)) {
Carta carta = this.coleccion.remove(nombreCarta);
carta.setCant((carta.getCant() + 1));
this.coleccion.put(carta.getNombre(), carta);
}else {
this.coleccion.put(this.cartasDisponibles.get(nombreCarta).getNombre(), this.cartasDisponibles.get(nombreCarta));
}
return true;
}else {
return false;
}
}
/**
* @param nombreCarta
* @param nuevoTipo
* @return
*/
public boolean cambiarTipoCarta(String nombreCarta, String nuevoTipo) {
if(this.cartasDisponibles.containsKey(nombreCarta)) {
if(nuevoTipo.toLowerCase().equals("hechizo") || nuevoTipo.toLowerCase().equals("trampa") || nuevoTipo.toLowerCase().equals("monstruo")) {
Carta temp = this.cartasDisponibles.remove(nombreCarta);
temp.setTipo(nuevoTipo);
this.cartasDisponibles.put(temp.getNombre(), temp);
if(this.coleccion.containsKey(nombreCarta)) {
temp.setCant(this.coleccion.remove(nombreCarta).getCant());;
this.coleccion.put(temp.getNombre(), temp);
}
return true;
}else {
return false;
}
}else {
return false;
}
}
/**
* @return coleccion de cartas
*/
public Carta[] getColeccionCartas() {
Carta[] cartas = new Carta[this.coleccion.size()];
this.coleccion.values().toArray(cartas);
return cartas;
}
/**
* @return coleccion de cartas
*/
public Carta[] getColeccionOrdenada() {
QuickSort<Carta> sort = new QuickSort<Carta>();
Carta[] cartas = new Carta[this.coleccion.size()];
this.coleccion.values().toArray(cartas);
cartas = sort.sort((Carta[]) cartas, 0, (cartas.length - 1));
return cartas;
}
/**
* @return coleccion de cartas
*/
public Carta[] getCartasDisponiblesArray() {
Carta[] cartas = new Carta[this.cartasDisponibles.size()];
this.cartasDisponibles.values().toArray(cartas);
return cartas;
}
/**
* @return coleccion de cartas
*/
public Carta[] getCartasDisponiblesOrdenada() {
QuickSort<Carta> sort = new QuickSort<Carta>();
Carta[] cartas = new Carta[this.cartasDisponibles.size()];
this.cartasDisponibles.values().toArray(cartas);
cartas = sort.sort((Carta[]) cartas, 0, (cartas.length - 1));
return cartas;
}
}
| 5b53880feddb344a04995b71bce00ffcb06c28ee | [
"Java"
]
| 2 | Java | FernandoHen/Lab6mapas | bb5018de1139ec1861c2cc4d1aa291598e1b9069 | 9657938a7567f02fe621ab44bc14dc0c7556f954 |
refs/heads/master | <file_sep>t=(1,2,3,3,3,3)
t=t+(2,)
print(t.index(3))
print(t.count(3))<file_sep>l1=list(map(str,input().split()))
f"""or i in range(0,len(l1)):
s=l1[i]
for j in range(0,len(s)):
if(s[j]=="."):
a=j+1
l1[i]=s[a:]
print(l1)"""
for i in range(len(l1)):
pos=l1[i].index('.')
str=l1[i]
l1[i]=str[pos+1:]
print(l1)<file_sep>a="ABCD"
def upper1(a):
if(a.isupper()):
return True
else:
return False
<file_sep>l=list(map(int,input().split()))
i=0
for i in range(0,len(l)):
if(i%2==0):
x=l[i]
for k in range(0,x):
print("*",end='')
else:
x=l[i]
for k in range(0,x):
print("+",end='')
print("")
<file_sep>n=input()
n=list(n)
num=0
dig=0
special=0
for i in range(0,len(n)):
if(ord(n[i])>64 and ord(n[i])<123):
num+=1
elif(ord(n[i])>47 and ord(n[i])<58):
dig+=1
else:
print(n[i])
special+=1
print(num,special,dig)<file_sep>q=[]
f=0
r=0
while(r==0 and f<4):
x=input()
q.append(x)
f=f+1
print(q)<file_sep>l=list(map(int,input().split()))
cl=[]
vl=[]
c=1
for i in range(0,len(l)):
c=1
for j in range(i+1,len(l)):
if(l[i]==l[j]):
c=c+1
vl.append(l[i])
cl.append(c)
print(vl)
print(cl)
x={}
for i in range(0,len(vl)):
if l[i] not in x:
x[vl[i]]=cl[i]
print(x)
f=1
e=0
for i in x:
if(x[i]==1):
f=f+1
if(f>3):
print(i)<file_sep>l1=input().split()
l2=[0]*len(l1)
l3=[]
for i in range(0,len(l1)):
for j in range(i+1,len(l1)):
if(l1[i]==l1[j]):
l2[i]+=1
for i in range(0,len(l2)):
if(l2[i]==0):
l3.append(l1[i])
print(l3)<file_sep>n=input()
#input().split()
"""if we give n=input().split()
wont work for guvi but
will work for g*u*v*i then give input().split(*)"""
#it will not work str obj doesnt support assignment
"""for i in range(0,len(n)):
n[i]=n[i].upper()
print(n)"""
#only char gets upper
"""for i in n:
print(i.upper())"""
#to make entire list
n=list(n)
for i in range(0,len(n)):
n[i]=n[i].upper()
a="".join(map(str,n))
print(a)
<file_sep>d={}
d["1"]="A"
d[input()]=input()
d[6]=4
print(d)<file_sep>n=int(input())
for i in range(1,n+1):
for j in range(1,i+1):
print("*",end='')
print("")
n=int(input())
i=1
while(n>0):
i=i+1
print("*"*n)
n=n-1<file_sep>p=input()
n=ord(p)
l=int(input())
for i in range(65,n+1):
print(chr(i),end='')
for j in range(1,l+1):
print(j,end='')
print("")<file_sep>l=list(map(int,input().split()))
vl=[]
cl=[]
for i in range(0,len(l)):
c=1
for j in range(i+1,len(l)):
if(l[i]==l[j]):
c=c+1
vl.append(l[i])
cl.append(c)
print(cl)
print(vl)
n=int(input())
d=[]
for i in range(0,len(cl)):
if(cl[i]>1):
if vl[i] not in d:
d.append(vl[i])
print(d[n-1])
<file_sep>n=input()
a=n[::-1]
if(a==n):
print("palindrome")
else:
print("not palindrome")<file_sep>n=input()
x=n.split()
a=[]
for i in range(len(x)-1,-1,-1):
a.append(x[i])
print(a)<file_sep>m=int(input())
n=int(input())
if(m>n):
ma=m
else:
ma=n
lcf=1
a=[]
for i in range(1,10):
for j in range(1,10):
if(m*i == n*j):
lcf=m*i
a.append(lcf)
print(a[0])<file_sep>n=int(input())
s=0
temp=n
while(n>0):
a=n%10
s=s*10+a
n=n//10
print(temp,s)
if(temp==s):
print("True")
else:
print("False")<file_sep>s=input()
l=[]
for i in range(len(s)-1,-1,-1):
l.append(s[i])
x=''.join(map(str,l))
print(x)
<file_sep>n=int(input())
l=[]
while(n>0):
a=n%10
l.append(a)
n=n//10
c=0
vl=[]
cl=[]
for i in range(0,len(l)):
c=1
for j in range(i+1,len(l)):
if(l[i]==l[j]):
c=c+1
vl.append(l[i])
cl.append(c)
print(vl,cl)
<file_sep>import time,socket,sys
print("\n welcome")
print("intialising...")
time.sleep(1)
s=socket.socket()
shost=socket.gethostname()
ip=socket.gethostbyname(shost)
print(shost,"(",ip,")\n")
host=input(str("enter server address"))
name=input(str("enter your name.."))
port=5000
print("n trying to conect to",host)
time.sleep(1)
s.connect((host,port))
print("\n connectred ..\n")
s.send(name.encode())
s_name=s.recv(1024)
s_name=s_name.decode()
print(s_name,"hass connected")
while True:
message=s.recv(1024)
message=message.decode()
print(s_name,":",message)
message=input(str("me:"))
s.send(message.encode())
<file_sep>n=int(input())
f1=0
f=1
f2=1
print(f1)
print(f2)
for i in range(1,n):
f=f1+f2
f1=f2
f2=f
print(f)<file_sep>def a(x):
for i in fruits:
if(x==i):
return True
x='c'
fruits=['a','b']
res=a(x)
print(res)
<file_sep>class p:
def __init__(self,a,b):
self.m=a
self.n=b
def hi(self,m,n):
return m+n
p1=p(2,3)
print(p1.hi(3,4))<file_sep>s=" hi how are you "
a=s.rstrip(" ")
print(a)<file_sep>a=input()
def isalpa1(a):
for i in range(0,len(a)):
c=0
for j in a:
if(j>'A' and j<'z'):
c=c+1
if(c==len(a)):
return True
else:
return False
x=isalpa1(a)
print(x)<file_sep>n=input()
x=input()
n=list(n)
for i in range(0,len(n)):
if(n[i]==x):
print(i,x)
<file_sep>a=int(input())
t=0
p=0
for j in range(1,5):
c=input("name:")
m1=int(input("math:"))
m2=int(input("science:"))
m3=int(input("social science:"))
m4=int(input("english:"))
m5=int(input("cs:"))
t=m1+m2+m3+m4+m5
p=float((t/125)*100)
print("sum:",t)
print(p)
if(p>=90):
print("iit")
elif(p>=80 and p<90):
print("anna university")
elif(p>=70 and p<80):
print("mgit")
elif(p<70):
print("rejected")
<file_sep>class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.insert(0,item)
def pop(self):
return self.items.pop(0)
s=Stack()
s.push('a')
s.push('b')
print(s.pop())
<file_sep>a=list(map(int,input().split()))
s=list(map(int,input().split()))
n=int(input())
for j in range(1,n+1):
temp=a[0]
for i in range(0,len(a)-1):
a[i]=a[i+1]
l=len(a)-1
a[l]=temp
print(a,s)
if(a==s):
print(j)
break<file_sep>n=input()
n=n.lower()
print(n)
'''n=input()
n=list(n)
for i in range(0,len(n)):
n[i]=n[i].lower()
a=''.join(map(str,n))
print(a)'''<file_sep>a=['a','e','i','o','u']
n=input()
n=list(n)
vowel=0
con=0
for i in range(0,len(n)):
if(n[i] in a):
vowel+=1
else:
con+=1
print(vowel,con)<file_sep>n=input()
n=n[::-1]
n=list(n)
for i in range(0,2):
n[i]=n[i].upper()
n=''.join(map(str,n))
print(n)
'''Sample Input :
jennyfer
Sample Output :
Refynnej'''<file_sep>s=input()
a=s.lstrip(" ")
print(a)<file_sep>n=int(input())
for i in range(1,n+1):
for j in range(2,11):
r=i*j
print(i,"*",j,"=",r)
<file_sep>c=0
p=[]
for i in range(1,100):
for j in range(2,i+1):
if(i%j==0):
break
else:
if i not in p:
p.append(i)
print(p)
s=0
for i in range(0,len(p)):
s=s+p[i]
print(s)<file_sep>def a(x,y):
print("first",x,y)
def a(x):
print("second",x)
a(2,3)
#error
a(2)
#prints 2 call second function<file_sep>print(range(0,5))
#range(0,5)
print(list(range(0,5)))
#[0,1,2,3,4]
print(l(range(0,5)))
#error<file_sep>s1 = [];
s2 = [];
def eq(x):
s1.append(x)
def dq():
if (len(s2) == 0):
if (len(s1) == 0):
return 'Cannot dequeue because queue is empty'
while (len(s1) > 0):
p = s1.pop()
s2.append(p)
return s2.pop()
eq('a');
eq('b');
eq('c');
dq();
print(s1)
print(s2)<file_sep>s=input()
i=input()
a=s.find(i)
print(a,i)
s=s.replace(s[a],'i',1)
print(s)<file_sep>s=input().split()
x=input()
c=1
for i in range(0,len(s)):
if(s[i]==x):
c=c+1
print(i)
print(c)<file_sep>l=list(map(int,input().split()))
count=[]
c=1
cl=[]
vl=[]
for i in range(0,len(l)):
for j in range(i+1,len(l)):
if (l[i] == l[j]):
c=c+1
cl.append(c)
vl.append(l[i])
c=1
print(l)
print(cl)
print(vl)
<file_sep>m=int(input())
c=0
for i in range(1,m):
if(m%i==0):
c=c+1
if(c>1):
print("not prime")
else:
print("prime")
<file_sep>a=int(input())
t=0
for i in range(0,a):
for j in range(0,5):
c=input("name:")
m1=int(input("math:"))
m2=int(input("science:"))
m3=int(input("social science:"))
m4=int(input("english:"))
m5=int(input("cs:"))
t=m1+m2+m3+m4+m5
p=(t/125)*100
print("sum:",t)
print("percentage",p)
<file_sep>s=0
for i in range(1,100):
if(i%2==1):
s=s+i
print(s)<file_sep>a=[10,20,30,40,50]
n=1
for j in range(1,n+1):
temp=a[0]
for i in range(0,4):
a[i]=a[i+1]
l=len(a)-1
a[l]=temp
print(a)<file_sep>n=input()
n=list(n)
c=0
s=['a','e','i','o','u']
for i in range(0,len(n)):
if n[i] in s:
c+=1
if(c>1):
print("yes")
else:
print("no")<file_sep>l=list()
s=0
a=0
for i in range(0,4):
a=int(input("enter marks for"+i+" 4 subjects"))
l.append(a)
s=s+a
print("the subject marks:",l)
print("the sum of all subjects:",s)
a=s/4
print("the average is:",a)<file_sep>l1=[1,2,3,4,5]
l2=[2,3,4,6,8]
for (i,j) in zip(l1,l2):
if(i!=j):
count=1
if(count==1):
print("different")
else:
print("same")
l1=list(map(int,input().split()))
l2=list(map(int,input().split()))
l=len(l1)
s=0
for i in range(0,l):
if(l1[i]!=l2[i]):
i=i+1
s=s+1
print(s)
if(s>0):
print("d")
else:
print("s")
<file_sep>n=int(input())
p=int(input())
for i in range(0,p+1):
res=n**i
print(n,"**",i,":",res)<file_sep>a=int(input())
b=int(input())
p=int(input())
d=b-a
if(d>5):
e=d-5
print(e)
price=(e*8)+100
if(p==1):
price=price+(price*0.25)
else:
price=100
if(p==1):
price=price+(price*0.25)
print(price)<file_sep>n=input()
l=len(n)-1
a=list(n)
t=a[0]
a[0]=a[l]
a[l]=t
n=''.join(map(str,a))
print(n)<file_sep>s = "Python is fun"
print(s.partition('is '))
#('', 'h', 'ihowhello')
a="hihowhello"
print(a.partition('h'))<file_sep>n1=input()
n2=input()
n=n1+n2
print(n)<file_sep>n=['a','c','e']
l=[]
for i in n:
a=ord(i)
a=chr(a+1)
l.append(a)
print(l)<file_sep>m=int(input())
n=int(input())
if(m<n):
mi=m
else:
mi=n
gcd=0
for i in range(1,mi+1):
if(m%i==0 and n%i==0):
if(i>gcd):
gcd=i
print(gcd)
<file_sep>s="string***"
#strip
print(s.rstrip("*"))
print(s.lstrip("str"))
print(s.strip("***"))
print(s.strip("str"))
#replace
a=s.replace("***","")
print(a)
x="this***is***test"
print(s.replace("***"," "))<file_sep>print("a",end='*') #op:a*
print() #op:
print("") #op:
print("x") #op:x
print("1","2",sep=',',end="&&&") #op:1,2&&&
print()
print("1","2",sep='',end="&&&") #op:12&&&<file_sep>import time,socket,sys,errno
print("\n welcome")
print("intialising...")
time.sleep(1)
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host=socket.gethostname()
ip=socket.gethostbyname(host)
port=5000
s.bind((host,port))
print(host,"(",ip,")\n")
name=input(str("enter your name.."))
s.listen(1)
print("\n waititng")
conn,addr=s.accept()
print("received from",addr[0],"(",addr[1])
s_name=conn.recv(1024)
s_name=s_name.decode()
print(s_name,"hass connected")
conn.send(name.encode())
while True:
message=input(str("me:"))
conn.send(message.encode())
message=conn.recv(1024)
message=message.decode()
print(s_name,":",message)
<file_sep>r=0
n=int(input())
while(n>0):
a=n%10
r=(r*10)+a
n=n//10
print(r)
<file_sep>n=input()
r=0
l=len(n)
n=int(n)
temp=n
while(n>0):
x=n%10
r=(r*10)+x
n=n//10
print(r)
print(temp)
if(temp==r):
print("palindrome")
else:
print("not palindrome")<file_sep>a="ABvD"
r=[]
def upper1(a):
for i in range(0,len(a)):
if(ord(a[i])>=96 and ord(a[i])<123):
r.append("l")
elif(ord(a[i])>64 and ord(a[i])<91):
r.append("u")
print(r)
u=0
l=0
for i in range(0,len(r)):
if (r[i]=='u'):
u=u+1
else:
l=l+1
print(u,l)
if(u==len(r)):
return True
else:
return False
res=upper1(a)
print(res)<file_sep>l=list()
s=0
av=0
for i in range(0,4):
a=int(input("enter marks subject %d :",%(i)))
l.append(a)
s=s+a
print("the subject marks:",l)
print("the sum of all subjects:",s)
av=s/4
print("the average is:",av)<file_sep>n=input()
n=n.upper()
print(n)
'''n=input()
n=list(n)
for i in range(0,len(n)):
n[i]=n[i].upper()
a=''.join(map(str,n))
print(a)'''<file_sep>n=input()
n=list(n)
for i in range(0,len(n)):
if(ord(n[i])>96 and ord(n[i])<123):
n[i]=n[i].upper()
else:
n[i]=n[i].lower()
a=''.join(map(str,n))
print(a)<file_sep>l=list()
s=0
a=0
for i in range(0,4):
a=int(input("subject %d"%i))
for j in range(0,5):
b=int(input("subject %d"%j))
l.push(a)
l.push(b)
s=s+l[i]
print(l)
print(s)
a=s/4
print(a)<file_sep>s=set()
s.add("a")
s.add("b")
print(s)
s.clear()
print(s)
s={'a','b','c','hi'}
s1=s.copy()
print(s1,type(s1))
s2={'a','b','d','e'}
print(s1.difference(s2))
s1.difference_update(s2)
print(s1)
s.discard("hi")
print(s)
print(s.intersection(s2))
print(s.intersection_update(s2))
s={'a','b','c'}
s2={'c','d','e'}
print(s.isdisjoint(s2))
print(s.issubset(s2))
print(s.issuperset(s2))
s.pop()
print(s)
s.remove('b')
print(s)
print(s.symmetric_difference(s2))
a=s.symmetric_difference_update(s2)
print(s)<file_sep>n=int(input())
s=1
while(n>0):
a=n%10
s=s*a
n=n//10
print(s)<file_sep>l=[]
l2=[]
def push(a,b):
a.append(b)
def pop(a):
return a.pop()
push(l,'a')
push(l,'b')
push(l2,'1')
pop(l)
pop(l2)
print(l)
print(l2)<file_sep>s=0
for i in range(1,100):
if(i%2==0):
s=s+i
print(s)<file_sep>n=ord('a')
while(n<123):
print(chr(n))
n=n+1
<file_sep>n=input()
l=len(n)
n=int(n)
temp=n
t=0
while(n>0):
a=n%10
t=a**l+t
n=n//10
print(t)
print(temp)
if(t==temp):
print("a")
else:
print("na")<file_sep>n=input()
l=len(n)-1
n=list(n)
print("sum: ",int(n[0])+int(n[l]))<file_sep>a=input()
def isnewupper(a,i):
for i in range(0,len(a)):
x=1
y=1
for j in a:
if(j>'A' and j<'Z'):
x=x+1
else:
y=y+1
if(x==len(a)):
return True
else:
return False
res=isnewupper(a)
print(res)<file_sep>s=input().split()
x=input()
for i in range(len(s)-1,-1,-1):
if(s[i]==x):
a=s[i]
print(a)
s.pop(i)
break
s=' '.join(map(str,s))
print(s)<file_sep>l1=list(map(str,input().split()))
l2=list(map(str,input().split()))
l3=list(map(str,input().split()))
for i in range(0,len(l1)):
if(l2[i]=="M"):
a="Mr"+l1[i]
l1[i]=a
elif(l2[i]=="F"):
if(l3[i]=="M"):
a="MRs"+l1[i]
l1[i]=a
else:
a="Ms"+l1[i]
l1[i]=a
else:
break
print(l1)<file_sep>n1=input()
n2=input()
if(len(n1)==len(n2)):
x=len(n1)
else:
print("cant be compared")
c=0
for i in range(0,x):
if(n1[i]!=n2[i]):
c=c+1
if(c>1):
print("not equal")
else:
print("no")
<file_sep># your code goes here-
n=int(input())
l=list(map(int,input().split()))
cl=[]
vl=[]
for i in range(0,n):
c=1
for j in range(i+1,n):
if(l[i]==l[j]):
c=c+1
cl.append(c)
vl.append(l[i])
x={}
for i in range(0,len(cl)):
if vl[i] not in x:
x[vl[i]]=cl[i]
f=1
e=0
for i in x:
if(x[i]==1):
f=f+1
if(f>3):
print(i)
break
if(x[i]!=1):
e=e+1
if(e==len(x)-1):
print("none")
<file_sep>s=input()
s=s.replace(" ","")
print(s)<file_sep>n=1
while(n<100):
if(n%2==0):
print(n)
n=n+1<file_sep>n=input()
l=len(n)-1
n=list(n)
print(n[0],n[l])<file_sep>str=input()
a=0
j=len(str)-1
for i in range(0,len(str)):
if(i<j):
if(str[i]!=str[j]):
a=1
break
j=j-1
if(a==1):
print("np")
else:
print("p")
<file_sep>tup=(1,)
tup=tup+(2,)
print(tup)
<file_sep>n=input()
a=list(n)
c=1
for i in range(0,len(a)):
if(a[i]==' '):
c=c+1
print(c)<file_sep>n=input()
n=list(n)
c1=0
c2=0
for i in range(0,len(n)):
if(n[i]=='{'):
c1+=1
elif(n[i]=='}'):
c1+=1
elif(n[i]=='('):
c2+=1
elif(n[i]==')'):
c2+=1
if(c1%2==0 and c2%2==0):
print("1")
else:
print("0")
<file_sep>l=list(map(int,input().split()))
for i in range(0,len(l)):
if(i%2==0):
print("*"*l[i])
else:
print("+"*l[i])
<file_sep>stack=[]
stack.append(input())
stack.append(input())
stack.append(input())
stack.pop()
print(stack)
stack.pop()
print(stack)<file_sep>n=input()
n=list(n)
l=len(n)
if(l%2==0):
l=int(l//2)-1
n[l]="*"
n[l+1]="*"
else:
l=int(l/2)
n[l]="*"
n=''.join(map(str,n))
print(n)<file_sep>n=input()
n=list(n)
c=1
a=[]
b=[]
for i in range(0,len(n)):
x=n[i]
for j in range(i+1,len(n)):
if(x==n[j]):
c=c+1
if n[i] not in a:
a.append(n[i])
b.append(c)
c=1
print(a)
print(b)
ma=b[0]
y=0
for i in range(1,len(b)):
if(ma>b[i]):
ma=ma
i=i+1
y=b[i]
y
else:
ma=b[i]
i=i+1
print(ma,y)<file_sep>n=input()
n=list(n)
for i in n:
print(i)<file_sep>d={}
d[input()]=input()
print(d)
d.clear()
print(d)
d={'a':1,'b':2,'c':3,'d':4}
x=d.copy()
print(d,type(d))
x=('a','b')
y=1
d=dict.fromkeys(x,y)
print(d)
print(d.get('1'))
print(d.get('a'))
print(d.items())
print(d.keys())
d.pop("a")
print(d)
d={'a':1,'b':2,'c':3}
print(d)
d.popitem()
print(d)
x=d.setdefault('a')
print(x)
d.update({'a':3})
print(d)
print(d.values())<file_sep>l=[]
l.append(2)
l.append(3)
print(l)
x=l.copy()
print(type(x))
print(x)
l.clear()
print(l)
l=[2,2,3,4,'a']
print(l.count('a'))
x=(5,)
l.extend(x)
print(l)
print(l.index(5))
l.insert(5,'b')
print(l)
l.pop(1)
print(l)
l.insert(1,2)
l.remove(2)
print(l)
l.reverse()
print(l)
l=[3,1,5,8,1,2,9]
l.sort()
print(l)
<file_sep>n=input()
a=n.find(input())
n=list(n)
n.pop(a)
x=''.join(map(str,n))
print(x)<file_sep>l=list(map(int,input().split()))
count=[]
c=1
for i in range(0,len(l)):
for j in range(i+1,len(l)):
if (l[i] == l[j]):
c=c+1
if(c>1):
break
print(l[i],c)
<file_sep>n=input()
x=input()
n=list(n)
c=0
for i in range(0,len(n)):
if(n[i]==x):
c=c+1
print(i)
print("count :",c) <file_sep>
n=int(input())
l=list(map(int,input().split()))
cl=[]
vl=[]
for i in range(0,n):
c=1
for j in range(i+1,n):
if(l[i]==l[j]):
c=c+1
cl.append(c)
vl.append(l[i])
x={}
for i in range(0,len(cl)):
if vl[i] not in x:
x[vl[i]]=cl[i]
print(x)
f=1
for i in x:
if(x[i]==1):
f=f+1
if(f>3):
print(i)
break
print(f)<file_sep>l1=list(map(int,input().split()))
l2=list(map(int,input().split()))
for i in l2:
l1.append(i)
print(l1)<file_sep>class p:
def __init__(self,age=0):
self.age=age
def get_age(self):
return self.age
def set_age(self,n):
self.age=n
p1=p()
p1.set_age(21)
print(p1.age)<file_sep>a=list(map(int,input().split()))
n=int(input())
def rot(a,n):
for j in range(1,n+1):
temp=a[0]
for i in range(0,4):
a[i]=a[i+1]
l=len(a)-1
a[l]=temp
print(a)
rot(a,n)<file_sep>s=input()
x=input()
y=input()
s=s.replace(x,y)
print(s)<file_sep>n=input()
n=list(n)
s=0
for i in n:
s=s+ord(i)
if(s%8==0):
print("1")
else:
print("0")<file_sep>s=input()
a=s.rfind(input())
x=input()
s=list(s)
s[a]=x
s=''.join(map(str,s))
print(s)<file_sep>a=input()
s=0
c=0
l=len(a)
a=int(a)
y=a
for i in range(0,l):
x=a%10
c=x**l
a=a//10
s=s+c
if(s==y):
print("yes")
else:
print("no")
<file_sep>n=input()
n=list(n)
c=1
a=[]
for i in range(0,len(n)):
x=n[i]
for j in range(i+1,len(n)):
if(x==n[j]):
c=c+1
if n[i] not in a:
a.append(n[i])
a.append(c)
c=1
print(a)<file_sep>n=input()
s=0
for i in range(0,len(n)):
if(n[i]>='0' and n[i]<='9'):
s=s+int(n[i])
print(s)<file_sep>l=list(map(int,input().split()))
cl=[]
vl=[]
c=1
for i in range(0,len(l)):
c=1
for j in range(i+1,len(l)):
if(l[i]==l[j]):
c=c+1
vl.append(l[i])
cl.append(c)
print(vl)
print(cl)
p=0
d=[]
for i in range(0,len(cl)):
if(cl[i]>1):
if vl[i] not in d:
d.append(vl[i])
print(d)
print(d[2])
<file_sep>s=" hi how are you "
a=s.strip(" ")
print(a)<file_sep>n=input()
x=input()
n=list(n)
for i in range(0,len(n)):
if(n[i]==x):
a=i
print(a,x)
'''n=input()
print(n.rfind('o'))'''
#op:12 | b963c9d513e0817661cb8416f7267422e60f4a56 | [
"Python"
]
| 107 | Python | Aishwaryakotharu/GUVI | 20c01438fb72cc297932b97f4f5fd3fb4238cf65 | c8efaa98fcb491f83713482f4e6863825f0f55bd |
refs/heads/master | <file_sep>import { Component } from '@angular/core';
declare var $:any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Happy Anniversary!';
flip0(): void {
$('.ui.centered.card.0').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.august').transition('horizontal flip');
}
});
}
flipaugust(): void {
$('.ui.centered.card.august').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180824_174426').transition('horizontal flip');
}
});
}
flip180824_174426(): void {
$('.ui.centered.card.180824_174426').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180828_103105').transition('horizontal flip');
}
});
}
flip180828_103105(): void {
$('.ui.centered.card.180828_103105').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180828_204637').transition('horizontal flip');
}
});
}
flip180828_204637(): void {
$('.ui.centered.card.180828_204637').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180829_181630').transition('horizontal flip');
}
});
}
flip180829_181630(): void {
$('.ui.centered.card.180829_181630').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180830_120726').transition('horizontal flip');
}
});
}
flip180830_120726(): void {
$('.ui.centered.card.180830_120726').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180830_124958').transition('horizontal flip');
}
});
}
flip180830_124958(): void {
$('.ui.centered.card.180830_124958').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.september').transition('horizontal flip');
}
});
}
flipseptember(): void {
$('.ui.centered.card.september').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180903_174402').transition('horizontal flip');
}
});
}
flip180903_174402(): void {
$('.ui.centered.card.180903_174402').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180903_192022').transition('horizontal flip');
}
});
}
flip180903_192022(): void {
$('.ui.centered.card.180903_192022').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180910_150412').transition('horizontal flip');
}
});
}
flip180910_150412(): void {
$('.ui.centered.card.180910_150412').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180914_203735').transition('horizontal flip');
}
});
}
flip180912_201815(): void {
$('.ui.centered.card.180912_201815').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180913_161529').transition('horizontal flip');
}
});
}
flip180913_161529(): void {
$('.ui.centered.card.180913_161529').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180913_212844').transition('horizontal flip');
}
});
}
flip180913_212844(): void {
$('.ui.centered.card.180913_212844').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180916_164504').transition('horizontal flip');
}
});
}
flip180914_203735(): void {
$('.ui.centered.card.180914_203735').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180912_201815').transition('horizontal flip');
}
});
}
flip180916_164504(): void {
$('.ui.centered.card.180916_164504').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180917_185120').transition('horizontal flip');
}
});
}
flip180917_185120(): void {
$('.ui.centered.card.180917_185120').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180918_165049').transition('horizontal flip');
}
});
}
flip180918_165049(): void {
$('.ui.centered.card.180918_165049').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180924_190956').transition('horizontal flip');
}
});
}
flip180924_190956(): void {
$('.ui.centered.card.180924_190956').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180927_210636').transition('horizontal flip');
}
});
}
flip180927_210636(): void {
$('.ui.centered.card.180927_210636').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.october').transition('horizontal flip');
}
});
}
flipoctober(): void {
$('.ui.centered.card.october').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181006_181525').transition('horizontal flip');
}
});
}
flip181006_181525(): void {
$('.ui.centered.card.181006_181525').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181006_213338').transition('horizontal flip');
}
});
}
flip181006_213338(): void {
$('.ui.centered.card.181006_213338').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181010_142503').transition('horizontal flip');
}
});
}
flip181010_142503(): void {
$('.ui.centered.card.181010_142503').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181016_205939').transition('horizontal flip');
}
});
}
flip181016_205939(): void {
$('.ui.centered.card.181016_205939').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181019_162524').transition('horizontal flip');
}
});
}
flip181019_162524(): void {
$('.ui.centered.card.181019_162524').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181022_190640').transition('horizontal flip');
}
});
}
flip181022_190640(): void {
$('.ui.centered.card.181022_190640').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181026_201734').transition('horizontal flip');
}
});
}
flip181026_201734(): void {
$('.ui.centered.card.181026_201734').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181031_131910').transition('horizontal flip');
}
});
}
flip181031_131910(): void {
$('.ui.centered.card.181031_131910').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.november').transition('horizontal flip');
}
});
}
flipnovember(): void {
$('.ui.centered.card.november').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181115_190341').transition('horizontal flip');
}
});
}
flip181115_190341(): void {
$('.ui.centered.card.181115_190341').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181115_220712').transition('horizontal flip');
}
});
}
flip181115_220712(): void {
$('.ui.centered.card.181115_220712').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181123_205441').transition('horizontal flip');
}
});
}
flip181123_205441(): void {
$('.ui.centered.card.181123_205441').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181124_124259').transition('horizontal flip');
}
});
}
flip181124_124259(): void {
$('.ui.centered.card.181124_124259').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181124_124455').transition('horizontal flip');
}
});
}
flip181124_124455(): void {
$('.ui.centered.card.181124_124455').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181124_134024').transition('horizontal flip');
}
});
}
flip181124_134024(): void {
$('.ui.centered.card.181124_134024').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181128_140814').transition('horizontal flip');
}
});
}
flip181128_140814(): void {
$('.ui.centered.card.181128_140814').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181128_140834').transition('horizontal flip');
}
});
}
flip181128_140834(): void {
$('.ui.centered.card.181128_140834').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.december').transition('horizontal flip');
}
});
}
flipdecember(): void {
$('.ui.centered.card.december').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181205_160641').transition('horizontal flip');
}
});
}
flip181205_160641(): void {
$('.ui.centered.card.181205_160641').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181210_181722').transition('horizontal flip');
}
});
}
flip181210_181722(): void {
$('.ui.centered.card.181210_181722').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181214_221814').transition('horizontal flip');
}
});
}
flip181214_221814(): void {
$('.ui.centered.card.181214_221814').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181217_152228').transition('horizontal flip');
}
});
}
flip181217_152228(): void {
$('.ui.centered.card.181217_152228').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.181219_192508').transition('horizontal flip');
}
});
}
flip181219_192508(): void {
$('.ui.centered.card.181219_192508').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.january').transition('horizontal flip');
}
});
}
flipjanuary(): void {
$('.ui.centered.card.january').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190107_155738').transition('horizontal flip');
}
});
}
flip190107_155738(): void {
$('.ui.centered.card.190107_155738').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190116_172852').transition('horizontal flip');
}
});
}
flip190116_172852(): void {
$('.ui.centered.card.190116_172852').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190121_205111').transition('horizontal flip');
}
});
}
flip190121_205111(): void {
$('.ui.centered.card.190121_205111').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190122_114413').transition('horizontal flip');
}
});
}
flip190122_114413(): void {
$('.ui.centered.card.190122_114413').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190124_181354').transition('horizontal flip');
}
});
}
flip190124_181354(): void {
$('.ui.centered.card.190124_181354').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190129_122228').transition('horizontal flip');
}
});
}
flip190129_122228(): void {
$('.ui.centered.card.190129_122228').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190130_130132').transition('horizontal flip');
}
});
}
flip190130_130132(): void {
$('.ui.centered.card.190130_130132').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190130_161625').transition('horizontal flip');
}
});
}
flip190130_161625(): void {
$('.ui.centered.card.190130_161625').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190130_174127').transition('horizontal flip');
}
});
}
flip190130_174127(): void {
$('.ui.centered.card.190130_174127').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.february').transition('horizontal flip');
}
});
}
flipfebruary(): void {
$('.ui.centered.card.february').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190214_130804').transition('horizontal flip');
}
});
}
flip190214_130804(): void {
$('.ui.centered.card.190214_130804').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190215_213445').transition('horizontal flip');
}
});
}
flip190215_213445(): void {
$('.ui.centered.card.190215_213445').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190215_222945').transition('horizontal flip');
}
});
}
flip190215_222945(): void {
$('.ui.centered.card.190215_222945').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190219_172209').transition('horizontal flip');
}
});
}
flip190219_172209(): void {
$('.ui.centered.card.190219_172209').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190222_125553').transition('horizontal flip');
}
});
}
flip190222_125553(): void {
$('.ui.centered.card.190222_125553').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190226_160900').transition('horizontal flip');
}
});
}
flip190226_160900(): void {
$('.ui.centered.card.190226_160900').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.march').transition('horizontal flip');
}
});
}
flipmarch(): void {
$('.ui.centered.card.march').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190304_123150').transition('horizontal flip');
}
});
}
flip190304_123150(): void {
$('.ui.centered.card.190304_123150').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190304_230224').transition('horizontal flip');
}
});
}
flip190304_230224(): void {
$('.ui.centered.card.190304_230224').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190314_184422').transition('horizontal flip');
}
});
}
flip190314_184422(): void {
$('.ui.centered.card.190314_184422').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190318_143415').transition('horizontal flip');
}
});
}
flip190318_143415(): void {
$('.ui.centered.card.190318_143415').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190325_130100').transition('horizontal flip');
}
});
}
flip190325_130100(): void {
$('.ui.centered.card.190325_130100').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190330_215429').transition('horizontal flip');
}
});
}
flip190330_215429(): void {
$('.ui.centered.card.190330_215429').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.april').transition('horizontal flip');
}
});
}
flipapril(): void {
$('.ui.centered.card.april').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190408_133454').transition('horizontal flip');
}
});
}
flip190408_133454(): void {
$('.ui.centered.card.190408_133454').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190421_143036').transition('horizontal flip');
}
});
}
flip190421_143036(): void {
$('.ui.centered.card.190421_143036').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.may').transition('horizontal flip');
}
});
}
flipmay(): void {
$('.ui.centered.card.may').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190501_162947').transition('horizontal flip');
}
});
}
flip190501_162947(): void {
$('.ui.centered.card.190501_162947').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190508_171048').transition('horizontal flip');
}
});
}
flip190508_171048(): void {
$('.ui.centered.card.190508_171048').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190508_190647').transition('horizontal flip');
}
});
}
flip190508_190647(): void {
$('.ui.centered.card.190508_190647').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190517_170130').transition('horizontal flip');
}
});
}
flip190517_170130(): void {
$('.ui.centered.card.190517_170130').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190521_131139').transition('horizontal flip');
}
});
}
flip190521_131139(): void {
$('.ui.centered.card.190521_131139').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190521_131200').transition('horizontal flip');
}
});
}
flip190521_131200(): void {
$('.ui.centered.card.190521_131200').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190523_185323').transition('horizontal flip');
}
});
}
flip190523_185323(): void {
$('.ui.centered.card.190523_185323').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190523_192148').transition('horizontal flip');
}
});
}
flip190523_192148(): void {
$('.ui.centered.card.190523_192148').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190529_135821').transition('horizontal flip');
}
});
}
flip190529_135821(): void {
$('.ui.centered.card.190529_135821').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190531_160917').transition('horizontal flip');
}
});
}
flip190531_160917(): void {
$('.ui.centered.card.190531_160917').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190531_174252').transition('horizontal flip');
}
});
}
flip190531_174252(): void {
$('.ui.centered.card.190531_174252').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190531_185812').transition('horizontal flip');
}
});
}
flip190531_185812(): void {
$('.ui.centered.card.190531_185812').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.june').transition('horizontal flip');
}
});
}
flipjune(): void {
$('.ui.centered.card.june').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190603_211606').transition('horizontal flip');
}
});
}
flip190603_211606(): void {
$('.ui.centered.card.190603_211606').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190623_134809').transition('horizontal flip');
}
});
}
flip190623_134809(): void {
$('.ui.centered.card.190623_134809').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190623_154356').transition('horizontal flip');
}
});
}
flip190623_154356(): void {
$('.ui.centered.card.190623_154356').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190623_165438').transition('horizontal flip');
}
});
}
flip190623_165438(): void {
$('.ui.centered.card.190623_165438').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190630_100351').transition('horizontal flip');
}
});
}
flip190630_100351(): void {
$('.ui.centered.card.190630_100351').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.july').transition('horizontal flip');
}
});
}
flipjuly(): void {
$('.ui.centered.card.july').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190701_155906').transition('horizontal flip');
}
});
}
flip190701_155906(): void {
$('.ui.centered.card.190701_155906').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190701_160705').transition('horizontal flip');
}
});
}
flip190701_160705(): void {
$('.ui.centered.card.190701_160705').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190719_141659').transition('horizontal flip');
}
});
}
flip190719_141659(): void {
$('.ui.centered.card.190719_141659').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190719_215748').transition('horizontal flip');
}
});
}
flip190719_215748(): void {
$('.ui.centered.card.190719_215748').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190726_202000').transition('horizontal flip');
}
});
}
flip190726_202000(): void {
$('.ui.centered.card.190726_202000').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190727_155014').transition('horizontal flip');
}
});
}
flip190727_155014(): void {
$('.ui.centered.card.190727_155014').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190727_161151').transition('horizontal flip');
}
});
}
flip190727_161151(): void {
$('.ui.centered.card.190727_161151').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.190729_174242').transition('horizontal flip');
}
});
}
flip190729_174242(): void {
$('.ui.centered.card.190729_174242').transition({
animation: 'horizontal flip',
onComplete: function(){
$('.ui.centered.card.180824_174426').transition('horizontal flip');
}
});
}
}
| 01ed2da4d5656e52affecc939fb4c77c845c0127 | [
"TypeScript"
]
| 1 | TypeScript | jjccrraa/anniversari | d5ad84189e89c07a126a70e93edcfcd2c135cfbf | 6a738cfb35ff5c6c2cda01dc7a528fc286ede728 |
refs/heads/master | <repo_name>nathipg/locadora-albuns<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/servicos/TipoEmprestimoServices.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package locadoraAlbuns.servicos;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import locadoraAlbuns.dao.TipoEmprestimoDAO;
import locadoraAlbuns.entidades.TipoEmprestimo;
/**
*
* @author CaueSJ
*/
public class TipoEmprestimoServices {
public List<TipoEmprestimo> getTodos() {
List<TipoEmprestimo> lista = new ArrayList<TipoEmprestimo>();
TipoEmprestimoDAO dao = null;
try {
dao = new TipoEmprestimoDAO();
lista = dao.listarTodos();
} catch ( SQLException exc ) {
exc.printStackTrace();
} finally {
if ( dao != null ) {
try {
dao.fecharConexao();
} catch ( SQLException exc ) {
exc.printStackTrace();
}
}
}
return lista;
}
}<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/dao/TipoEmprestimoDAO.java
package locadoraAlbuns.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import locadoraAlbuns.entidades.TipoEmprestimo;
/**
*
* @author nathipg
*/
public class TipoEmprestimoDAO extends DAO<TipoEmprestimo> {
public TipoEmprestimoDAO() throws SQLException {
}
@Override
public void salvar(TipoEmprestimo obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"INSERT INTO tipo_emprestimo "
+ " ( dias_duracao, valor ) "
+ "VALUES( ?, ? );" );
stmt.setInt( 1, obj.getDiasDuracao() );
stmt.setDouble( 2, obj.getValor() );
stmt.executeUpdate();
stmt.close();
}
@Override
public void atualizar(TipoEmprestimo obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"UPDATE tipo_emprestimo "
+ "SET"
+ " dias_duracao = ?,"
+ "valor = ?"
+ "WHERE"
+ " id = ?;" );
stmt.setInt( 1, obj.getDiasDuracao() );
stmt.setDouble( 2, obj.getValor() );
stmt.setInt( 3, obj.getId() );
stmt.executeUpdate();
stmt.close();
}
@Override
public void excluir(TipoEmprestimo obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"DELETE FROM tipo_emprestimo "
+ "WHERE"
+ " id = ?;" );
stmt.setInt( 1, obj.getId() );
stmt.executeUpdate();
stmt.close();
}
@Override
public List<TipoEmprestimo> listarTodos() throws SQLException {
List<TipoEmprestimo> lista = new ArrayList<TipoEmprestimo>();
PreparedStatement stmt = getConnection().prepareStatement(
"SELECT "
+ " tipo_emprestimo.id, "
+ " tipo_emprestimo.dias_duracao, "
+ " tipo_emprestimo.valor "
+ "FROM tipo_emprestimo;" );
ResultSet rs = stmt.executeQuery();
while ( rs.next() ) {
TipoEmprestimo tipoEmprestimo = new TipoEmprestimo();
tipoEmprestimo.setId( rs.getInt( "id" ) );
tipoEmprestimo.setDiasDuracao( rs.getInt( "dias_duracao" ) );
tipoEmprestimo.setValor( rs.getDouble( "valor" ) );
lista.add( tipoEmprestimo );
}
rs.close();
stmt.close();
return lista;
}
@Override
public TipoEmprestimo obterPorId(int id) throws SQLException {
TipoEmprestimo tipoEmprestimo = null;
PreparedStatement stmt = getConnection().prepareStatement(
"SELECT "
+ " tipo_emprestimo.id, "
+ " tipo_emprestimo.dias_duracao, "
+ " tipo_emprestimo.valor "
+ "FROM tipo_emprestimo "
+ "WHERE tipo_emprestimo.id = ?;");
stmt.setInt( 1, id );
ResultSet rs = stmt.executeQuery();
if ( rs.next() ) {
tipoEmprestimo = new TipoEmprestimo();
tipoEmprestimo.setId( rs.getInt( "id" ) );
tipoEmprestimo.setDiasDuracao( rs.getInt( "dias_duracao" ) );
tipoEmprestimo.setValor( rs.getDouble( "valor" ) );
}
rs.close();
stmt.close();
return tipoEmprestimo;
}
}
<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/entidades/Banda.java
package locadoraAlbuns.entidades;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author nathipg
*/
public class Banda {
private int id;
private String nome;
private String foto;
private String dataFormacao;
private String descricao;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getFoto() {
return foto;
}
public void setFoto(String foto) {
this.foto = foto;
}
public String getDataFormacao() {
return dataFormacao;
}
public void setDataFormacao(String dataFormacao) {
this.dataFormacao = dataFormacao;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/dao/MusicoDAO.java
package locadoraAlbuns.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import locadoraAlbuns.entidades.Musico;
/**
*
* @author cauesj
*/
public class MusicoDAO extends DAO<Musico> {
public MusicoDAO() throws SQLException {
}
@Override
public void salvar(Musico obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"INSERT INTO musico "
+ "( nome, "
+ " foto, "
+ " data_nascimento, "
+ " bio ) "
+ "VALUES( ?, ?, ?, ? ); " );
stmt.setString( 1, obj.getNome() );
stmt.setString( 2, obj.getFoto() );
stmt.setString( 3, obj.getDataNascimento() );
stmt.setString( 4, obj.getBio() );
stmt.executeUpdate();
stmt.close();
}
@Override
public void atualizar(Musico obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"UPDATE musico "
+ "SET "
+ " nome = ?, "
+ " foto = ?, "
+ " data_nascimento = ?, "
+ " bio = ? "
+ "WHERE "
+ " id = ?;" );
stmt.setString( 1, obj.getNome() );
stmt.setString( 2, obj.getFoto() );
stmt.setString( 3, obj.getDataNascimento() );
stmt.setString( 4, obj.getBio() );
stmt.setInt( 5, obj.getId() );
stmt.executeUpdate();
stmt.close();
}
@Override
public void excluir(Musico obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"DELETE FROM musico "
+ "WHERE musico.id = ?;" );
stmt.setInt( 1, obj.getId() );
stmt.executeUpdate();
stmt.close();
}
@Override
public List<Musico> listarTodos() throws SQLException {
List<Musico> lista = new ArrayList<Musico>();
PreparedStatement stmt = getConnection().prepareStatement(
"SELECT "
+ " musico.id, "
+ " musico.nome, "
+ " musico.foto, "
+ " musico.data_nascimento, "
+ " musico.bio "
+ "FROM musico " );
ResultSet rs = stmt.executeQuery();
while ( rs.next() ) {
Musico musico = new Musico();
musico.setId( rs.getInt( "id" ) );
musico.setNome( rs.getString( "nome" ) );
musico.setFoto( rs.getString( "foto" ) );
musico.setDataNascimento(rs.getString( "data_nascimento" ) );
musico.setBio(rs.getString( "bio" ) );
lista.add( musico );
}
rs.close();
stmt.close();
return lista;
}
@Override
public Musico obterPorId(int id) throws SQLException {
Musico musico = null;
PreparedStatement stmt = getConnection().prepareStatement(
"SELECT "
+ " musico.id, "
+ " musico.nome, "
+ " musico.foto, "
+ " musico.data_nascimento, "
+ " musico.bio "
+ "FROM musico "
+ "WHERE musico.id = ?;" );
stmt.setInt( 1, id );
ResultSet rs = stmt.executeQuery();
if ( rs.next() ) {
musico = new Musico();
musico.setId( rs.getInt( "id" ) );
musico.setNome( rs.getString( "nome" ) );
musico.setFoto( rs.getString( "foto" ) );
musico.setDataNascimento( rs.getString( "data_nascimento" ) );
musico.setBio( rs.getString( "bio" ) );
}
rs.close();
stmt.close();
return musico;
}
}<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/dao/FaixaDAO.java
package locadoraAlbuns.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import locadoraAlbuns.entidades.Faixa;
/**
*
* @author cauesj
*/
public class FaixaDAO extends DAO<Faixa> {
public FaixaDAO() throws SQLException {
}
@Override
public void salvar(Faixa obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"INSERT INTO faixa"
+ "( nome,"
+ " duracao,"
+ " id_album ) "
+ "VALUES( ?, ?, ? );" );
stmt.setString( 1, obj.getNome() );
stmt.setString( 2, obj.getDuracao() );
stmt.setInt( 3, obj.getAlbum().getId() );
stmt.executeUpdate();
stmt.close();
}
@Override
public void atualizar(Faixa obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"UPDATE faixa "
+ "SET"
+ " nome = ?,"
+ " duracao = ?,"
+ " id_album = ?"
+ "WHERE"
+ " id = ?;" );
stmt.setString( 1, obj.getNome() );
stmt.setString( 2, obj.getDuracao() );
stmt.setInt( 3, obj.getAlbum().getId() );
stmt.setInt( 4, obj.getId() );
stmt.executeUpdate();
stmt.close();
}
@Override
public void excluir(Faixa obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"DELETE FROM faixa "
+ "WHERE faixa.id = ?" );
stmt.setInt( 1, obj.getId() );
stmt.executeUpdate();
stmt.close();
}
@Override
public List<Faixa> listarTodos() throws SQLException {
List<Faixa> lista = new ArrayList<Faixa>();
PreparedStatement stmt = getConnection().prepareStatement(
"SELECT "
+ " faixa.id,"
+ " faixa.nome,"
+ " faixa.duracao,"
+ " faixa.id_album"
+ "FROM faixa;" );
ResultSet rs = stmt.executeQuery();
while ( rs.next() ) {
Faixa faixa = new Faixa();
faixa.setId( rs.getInt( "id" ) );
faixa.setNome( rs.getString( "nome" ) );
lista.add( faixa );
}
rs.close();
stmt.close();
return lista;
}
@Override
public Faixa obterPorId(int id) throws SQLException {
Faixa faixa = null;
PreparedStatement stmt = getConnection().prepareStatement(
"SELECT "
+ " faixa.id, "
+ " faixa.nome,"
+ " faixa.duracao,"
+ " faixa.id_album"
+ "FROM faixa "
+ "WHERE faixa.id = ?; ");
stmt.setInt( 1, id );
ResultSet rs = stmt.executeQuery();
if ( rs.next() ) {
faixa = new Faixa();
faixa.setId( rs.getInt( "id" ) );
faixa.setNome( rs.getString( "nome" ) );
}
rs.close();
stmt.close();
return faixa;
}
}<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/controladores/MusicoServlet.java
package locadoraAlbuns.controladores;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import locadoraAlbuns.dao.MusicoDAO;
import locadoraAlbuns.entidades.Musico;
/**
* Servlet para tratar Musicos.
*
* @author nathipg
*/
public class MusicoServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String acao = request.getParameter( "acao" );
MusicoDAO dao = null;
RequestDispatcher disp = null;
try {
dao = new MusicoDAO();
if ( acao.equals( "criar" ) ) {
String nome = request.getParameter( "nome" );
String dataNascimento = request.getParameter( "dataNascimento" );
String bio = request.getParameter( "bio" );
Musico musico = new Musico();
musico.setNome( nome );
musico.setDataNascimento( dataNascimento );
musico.setBio( bio );
dao.salvar( musico );
disp = request.getRequestDispatcher( "/formularios/musicos/listagem.jsp" );
} else if ( acao.equals( "alterar" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
String nome = request.getParameter( "nome" );
String dataNascimento = request.getParameter( "dataNascimento" );
String bio = request.getParameter( "bio" );
Musico musico = new Musico();
musico.setId( id );
musico.setNome( nome );
musico.setDataNascimento( dataNascimento );
musico.setBio( bio );
dao.atualizar( musico );
disp = request.getRequestDispatcher( "/formularios/musicos/listagem.jsp" );
} else if ( acao.equals( "excluir" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
Musico musico = new Musico();
musico.setId( id );
dao.excluir( musico );
disp = request.getRequestDispatcher( "/formularios/musicos/listagem.jsp" );
} else if ( acao.equals( "prepAlteracao" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
Musico musico = dao.obterPorId( id );
request.setAttribute( "musico", musico );
disp = request.getRequestDispatcher( "/formularios/musicos/alterar.jsp" );
} else if ( acao.equals( "prepExclusao" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
Musico musico = dao.obterPorId( id );
request.setAttribute( "musico", musico );
disp = request.getRequestDispatcher( "/formularios/musicos/excluir.jsp" );
}
} catch ( SQLException exc ) {
exc.printStackTrace();
} finally {
if ( dao != null ) {
try {
dao.fecharConexao();
} catch ( SQLException exc ) {
exc.printStackTrace();
}
}
}
if ( disp != null ) {
disp.forward( request, response );
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/entidades/Telefone.java
package locadoraAlbuns.entidades;
/**
*
* @author nathipg
*/
public class Telefone {
private int id;
private String telefone;
private Usuario usuario;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
}
<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/dao/TelefoneDAO.java
package locadoraAlbuns.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import locadoraAlbuns.entidades.Telefone;
import locadoraAlbuns.entidades.Usuario;
/**
*
* @author nathipg
*/
public class TelefoneDAO extends DAO<Telefone> {
public TelefoneDAO() throws SQLException {
}
@Override
public void salvar(Telefone obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"INSERT INTO telefone "
+ "( telefone, id_usuario ) "
+ "VALUES( ?, ? );" );
stmt.setString( 1, obj.getTelefone() );
stmt.setInt( 2, obj.getUsuario().getId() );
stmt.executeUpdate();
stmt.close();
}
@Override
public void atualizar(Telefone obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"UPDATE telefone "
+ "SET"
+ " telefone = ?, "
+ " id_usuario = ? "
+ "WHERE"
+ " id = ?;" );
stmt.setString( 1, obj.getTelefone() );
stmt.setInt( 2, obj.getUsuario().getId() );
stmt.setInt( 3, obj.getId() );
stmt.executeUpdate();
stmt.close();
}
@Override
public void excluir(Telefone obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"DELETE FROM telefone "
+ "WHERE"
+ " id = ?;" );
stmt.setInt( 1, obj.getId() );
stmt.executeUpdate();
stmt.close();
}
@Override
public List<Telefone> listarTodos() throws SQLException {
List<Telefone> lista = new ArrayList<Telefone>();
PreparedStatement stmt = getConnection().prepareStatement(
"SELECT "
+ " telefone.id, "
+ " telefone.telefone, "
+ " telefone.id_usuario, "
+ " usuario.nome, "
+ " usuario.cpf, "
+ " usuario.email, "
+ " usuario.endereco "
+ "FROM telefone"
+ " INNER JOIN usuario "
+ " ON usuario.id = telefone.id_usuario;" );
ResultSet rs = stmt.executeQuery();
while ( rs.next() ) {
Telefone telefone = new Telefone();
Usuario usuario = new Usuario();
usuario.setId( rs.getInt( "id_usuario" ) );
usuario.setNome( rs.getString( "nome" ) );
usuario.setCpf( rs.getString( "cpf" ) );
usuario.setEmail( rs.getString( "email" ) );
usuario.setEndereco( rs.getString( "endereco" ) );
telefone.setId( rs.getInt( "id" ) );
telefone.setTelefone( rs.getString( "telefone" ) );
telefone.setUsuario( usuario );
lista.add( telefone );
}
rs.close();
stmt.close();
return lista;
}
@Override
public Telefone obterPorId(int id) throws SQLException {
Telefone telefone = null;
PreparedStatement stmt = getConnection().prepareStatement(
"SELECT "
+ " telefone.id, "
+ " telefone.telefone, "
+ " telefone.id_usuario, "
+ " usuario.nome, "
+ " usuario.cpf, "
+ " usuario.email, "
+ " usuario.endereco "
+ "FROM telefone"
+ " INNER JOIN usuario "
+ " ON usuario.id = telefone.id_usuario "
+ "WHERE telefone.id = ?;");
stmt.setInt( 1, id );
ResultSet rs = stmt.executeQuery();
if ( rs.next() ) {
telefone = new Telefone();
Usuario usuario = new Usuario();
usuario.setId( rs.getInt( "id_usuario" ) );
usuario.setNome( rs.getString( "nome" ) );
usuario.setCpf( rs.getString( "cpf" ) );
usuario.setEmail( rs.getString( "email" ) );
usuario.setEndereco( rs.getString( "endereco" ) );
telefone.setId( rs.getInt( "id" ) );
telefone.setTelefone( rs.getString( "telefone" ) );
telefone.setUsuario( usuario );
}
rs.close();
stmt.close();
return telefone;
}
}
<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/controladores/BandaServlet.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package locadoraAlbuns.controladores;
import locadoraAlbuns.dao.BandaDAO;
import locadoraAlbuns.entidades.Banda;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author CaueSJ
*/
public class BandaServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
* @throws java.sql.SQLException
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
request.setCharacterEncoding("UTF-8");
String acao = request.getParameter( "acao" );
BandaDAO dao = null;
RequestDispatcher disp = null;
try {
dao = new BandaDAO();
if ( acao.equals( "criar" ) ) {
String nome = request.getParameter( "nome" );
String dataFormacao = request.getParameter( "dataFormacao" );
String descricao = request.getParameter( "descricao" );
Banda banda = new Banda();
banda.setNome( nome );
banda.setDataFormacao( dataFormacao );
banda.setDescricao( descricao );
dao.salvar( banda );
disp = request.getRequestDispatcher( "/formularios/bandas/listagem.jsp" );
} else if ( acao.equals( "alterar" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
String nome = request.getParameter( "nome" );
String dataFormacao = request.getParameter( "dataFormacao" );
String descricao = request.getParameter( "descricao" );
Banda banda = new Banda();
banda.setId( id );
banda.setNome( nome );
banda.setDataFormacao( dataFormacao );
banda.setDescricao( descricao );
dao.atualizar( banda );
disp = request.getRequestDispatcher(
"/formularios/bandas/listagem.jsp" );
} else if ( acao.equals( "excluir" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
Banda banda = new Banda();
banda.setId( id );
dao.excluir( banda );
disp = request.getRequestDispatcher(
"/formularios/bandas/listagem.jsp" );
} else if ( acao.equals( "prepAlteracao" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
Banda banda = dao.obterPorId( id );
request.setAttribute( "banda", banda );
disp = request.getRequestDispatcher(
"/formularios/bandas/alterar.jsp" );
} else if ( acao.equals( "prepExclusao" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
Banda banda = dao.obterPorId( id );
request.setAttribute( "banda", banda );
disp = request.getRequestDispatcher(
"/formularios/bandas/excluir.jsp" );
}
} catch ( SQLException exc ) {
exc.printStackTrace();
} finally {
if ( dao != null ) {
try {
dao.fecharConexao();
} catch ( SQLException exc ) {
exc.printStackTrace();
}
}
}
if ( disp != null ) {
disp.forward( request, response );
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(BandaServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(BandaServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/README.md
# locadoraAlbuns
É uma locadora de álbuns
<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/controladores/AlbumServlet.java
package locadoraAlbuns.controladores;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import locadoraAlbuns.dao.BandaDAO;
import locadoraAlbuns.dao.AlbumDAO;
import locadoraAlbuns.dao.MusicoDAO;
import locadoraAlbuns.dao.GeneroDAO;
import locadoraAlbuns.entidades.Banda;
import locadoraAlbuns.entidades.Album;
import locadoraAlbuns.entidades.Musico;
import locadoraAlbuns.entidades.Genero;
/**
* Servlet para tratar Albums.
*
* @author nathipg
*/
public class AlbumServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String acao = request.getParameter( "acao" );
AlbumDAO dao = null;
BandaDAO daoBanda = null;
MusicoDAO daoMusico = null;
GeneroDAO daoGenero = null;
RequestDispatcher disp = null;
try {
dao = new AlbumDAO();
daoBanda = new BandaDAO();
daoMusico = new MusicoDAO();
daoGenero = new GeneroDAO();
if ( acao.equals( "criar" ) ) {
String nome = request.getParameter( "nome" );
String dataLancamento = request.getParameter( "dataLancamento" );
int idBanda = Integer.parseInt( request.getParameter( "idBanda" ) );
int idMusico = Integer.parseInt( request.getParameter( "idMusico" ) );
int idGenero = Integer.parseInt( request.getParameter( "idGenero" ) );
Banda banda = daoBanda.obterPorId(idBanda);
Musico musico = daoMusico.obterPorId(idMusico);
Genero genero = daoGenero.obterPorId(idGenero);
Album album = new Album();
album.setNome( nome );
album.setFoto( "" );
album.setDataLancamento( dataLancamento );
album.setBanda( banda );
album.setMusico( musico );
album.setGenero( genero );
dao.salvar( album );
disp = request.getRequestDispatcher( "/formularios/albums/listagem.jsp" );
} else if ( acao.equals( "alterar" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
String nome = request.getParameter( "nome" );
String dataLancamento = request.getParameter( "dataLancamento" );
int idBanda = Integer.parseInt( request.getParameter( "idBanda" ) );
int idMusico = Integer.parseInt( request.getParameter( "idMusico" ) );
int idGenero = Integer.parseInt( request.getParameter( "idGenero" ) );
Banda banda = daoBanda.obterPorId(idBanda);
Musico musico = daoMusico.obterPorId(idMusico);
Genero genero = daoGenero.obterPorId(idGenero);
Album album = new Album();
album.setId( id );
album.setNome( nome );
album.setDataLancamento( dataLancamento );
album.setBanda( banda );
album.setMusico( musico );
album.setGenero( genero );
dao.atualizar( album );
disp = request.getRequestDispatcher( "/formularios/albums/listagem.jsp" );
} else if ( acao.equals( "excluir" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
Album album = new Album();
album.setId( id );
dao.excluir( album );
disp = request.getRequestDispatcher( "/formularios/albums/listagem.jsp" );
} else if ( acao.equals( "prepAlteracao" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
System.out.println(id);
Album album = dao.obterPorId( id );
request.setAttribute( "album", album );
disp = request.getRequestDispatcher( "/formularios/albums/alterar.jsp" );
} else if ( acao.equals( "prepExclusao" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
Album album = dao.obterPorId( id );
request.setAttribute( "album", album );
disp = request.getRequestDispatcher( "/formularios/albums/excluir.jsp" );
}
} catch ( SQLException exc ) {
exc.printStackTrace();
} finally {
if ( dao != null ) {
try {
dao.fecharConexao();
} catch ( SQLException exc ) {
exc.printStackTrace();
}
}
}
if ( disp != null ) {
disp.forward( request, response );
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/servicos/AlbumServices.java
package locadoraAlbuns.servicos;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import locadoraAlbuns.dao.AlbumDAO;
import locadoraAlbuns.entidades.Album;
/**
*
* @author nathipg
*/
public class AlbumServices {
public List<Album> getTodos() {
List<Album> lista = new ArrayList<Album>();
AlbumDAO dao = null;
try {
dao = new AlbumDAO();
lista = dao.listarTodos();
} catch ( SQLException exc ) {
exc.printStackTrace();
} finally {
if ( dao != null ) {
try {
dao.fecharConexao();
} catch ( SQLException exc ) {
exc.printStackTrace();
}
}
}
return lista;
}
}
<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/dao/FormacaoDAO.java
package locadoraAlbuns.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import locadoraAlbuns.entidades.Banda;
import locadoraAlbuns.entidades.Formacao;
import locadoraAlbuns.entidades.Musico;
/**
*
* @author cauesj
*/
public class FormacaoDAO extends DAO<Formacao> {
public FormacaoDAO() throws SQLException {
}
@Override
public void salvar(Formacao obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"INSERT INTO formacao "
+ "( id_banda, "
+ " id_musico, "
+ " inicio, "
+ " fim ) "
+ "VALUES( ?, ?, ?, ? ); " );
stmt.setInt( 1, obj.getBanda().getId() );
stmt.setInt( 2, obj.getMusico().getId() );
stmt.setString( 3, obj.getInicio() );
stmt.setString( 4, obj.getFim() );
stmt.executeUpdate();
stmt.close();
}
@Override
public void atualizar(Formacao obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"UPDATE formacao "
+ "SET "
+ " id_banda = ?, "
+ " id_musico = ?, "
+ " inicio = ?, "
+ " fim = ? "
+ "WHERE "
+ " id_banda = ? "
+ " AND id_musico = ?; " );
stmt.setInt( 1, obj.getBanda().getId() );
stmt.setInt( 2, obj.getMusico().getId() );
stmt.setString( 3, obj.getInicio() );
stmt.setString( 4, obj.getFim() );
stmt.setInt( 5, obj.getBanda().getId() );
stmt.setInt( 6, obj.getMusico().getId() );
stmt.executeUpdate();
stmt.close();
}
@Override
public void excluir(Formacao obj) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(
"DELETE FROM formacao "
+ "WHERE formacao.id_banda = ? "
+ "AND formacao.id_musico = ? " );
stmt.setInt( 1, obj.getBanda().getId() );
stmt.setInt( 2, obj.getMusico().getId() );
stmt.executeUpdate();
stmt.close();
}
@Override
public List<Formacao> listarTodos() throws SQLException {
List<Formacao> lista = new ArrayList<Formacao>();
PreparedStatement stmt = getConnection().prepareStatement(
"SELECT "
+ " banda.nome AS banda_nome, "
+ " musico.nome AS musico_nome, "
+ " formacao.id_banda, "
+ " formacao.id_musico, "
+ " formacao.inicio, "
+ " formacao.fim "
+ "FROM formacao "
+ " INNER JOIN banda "
+ " ON banda.id = formacao.id_banda "
+ " INNER JOIN musico "
+ " ON musico.id = formacao.id_musico; " );
ResultSet rs = stmt.executeQuery();
while ( rs.next() ) {
Formacao formacao = new Formacao();
Banda banda = new Banda();
Musico musico = new Musico();
banda.setId( rs.getInt("id_banda") );
banda.setNome( rs.getString("banda_nome") );
musico.setId( rs.getInt("id_musico") );
musico.setNome( rs.getString("musico_nome") );
formacao.setBanda( banda );
formacao.setMusico( musico );
formacao.setInicio( rs.getString("inicio") );
formacao.setFim( rs.getString("fim") );
lista.add( formacao );
}
rs.close();
stmt.close();
return lista;
}
public Formacao obterPorId(int id) throws SQLException {
Formacao formacao = null;
PreparedStatement stmt = getConnection().prepareStatement(
"SELECT "
+ " banda.nome AS banda_nome, "
+ " musico.nome AS musico_nome, "
+ " formacao.id_banda, "
+ " formacao.id_musico, "
+ " formacao.inicio, "
+ " formacao.fim "
+ "FROM formacao "
+ " INNER JOIN banda "
+ " ON banda.id = formacao.id_banda "
+ " INNER JOIN musico "
+ " ON musico.id = formacao.id_musico "
+ "WHERE formacao.id_banda = ?; " );
stmt.setInt( 1, id );
ResultSet rs = stmt.executeQuery();
if ( rs.next() ) {
formacao = new Formacao();
Banda banda = new Banda();
Musico musico = new Musico();
banda.setId( rs.getInt("id_banda") );
banda.setNome( rs.getString("banda_nome") );
musico.setId( rs.getInt("id_musico") );
musico.setNome( rs.getString("musico_nome") );
formacao.setBanda( banda );
formacao.setMusico( musico );
formacao.setInicio( rs.getString("inicio") );
formacao.setFim( rs.getString("fim") );
}
rs.close();
stmt.close();
return formacao;
}
public Formacao obterPorId(int idBanda, int idMusico) throws SQLException {
Formacao formacao = null;
PreparedStatement stmt = getConnection().prepareStatement(
"SELECT "
+ " banda.nome AS banda_nome, "
+ " musico.nome AS musico_nome, "
+ " formacao.id_banda, "
+ " formacao.id_musico, "
+ " formacao.inicio, "
+ " formacao.fim "
+ "FROM formacao "
+ " INNER JOIN banda "
+ " ON banda.id = formacao.id_banda "
+ " INNER JOIN musico "
+ " ON musico.id = formacao.id_musico "
+ "WHERE formacao.id_banda = ? AND formacao.id_musico = ?; " );
stmt.setInt( 1, idBanda );
stmt.setInt( 2, idMusico );
ResultSet rs = stmt.executeQuery();
if ( rs.next() ) {
formacao = new Formacao();
Banda banda = new Banda();
Musico musico = new Musico();
banda.setId( rs.getInt("id_banda") );
banda.setNome( rs.getString("banda_nome") );
musico.setId( rs.getInt("id_musico") );
musico.setNome( rs.getString("musico_nome") );
formacao.setBanda( banda );
formacao.setMusico( musico );
formacao.setInicio( rs.getString("inicio") );
formacao.setFim( rs.getString("fim") );
}
rs.close();
stmt.close();
return formacao;
}
}<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/entidades/Album.java
package locadoraAlbuns.entidades;
/**
*
* @author nathipg
*/
public class Album {
private int id;
private String nome;
private String foto;
private String dataLancamento;
private Genero genero;
private Banda banda;
private Musico musico;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getFoto() {
return foto;
}
public void setFoto(String foto) {
this.foto = foto;
}
public String getDataLancamento() {
return dataLancamento;
}
public void setDataLancamento(String dataLancamento) {
this.dataLancamento = dataLancamento;
}
public Genero getGenero() {
return genero;
}
public void setGenero(Genero genero) {
this.genero = genero;
}
public Banda getBanda() {
return banda;
}
public void setBanda(Banda banda) {
this.banda = banda;
}
public Musico getMusico() {
return musico;
}
public void setMusico(Musico musico) {
this.musico = musico;
}
}
<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/controladores/EmprestimoServlet.java
package locadoraAlbuns.controladores;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import locadoraAlbuns.dao.UsuarioDAO;
import locadoraAlbuns.dao.EmprestimoDAO;
import locadoraAlbuns.dao.AlbumDAO;
import locadoraAlbuns.dao.TipoEmprestimoDAO;
import locadoraAlbuns.entidades.Usuario;
import locadoraAlbuns.entidades.Emprestimo;
import locadoraAlbuns.entidades.Album;
import locadoraAlbuns.entidades.TipoEmprestimo;
/**
* Servlet para tratar Emprestimos.
*
* @author nathipg
*/
public class EmprestimoServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String acao = request.getParameter( "acao" );
EmprestimoDAO dao = null;
UsuarioDAO daoUsuario = null;
AlbumDAO daoAlbum = null;
TipoEmprestimoDAO daoTipoEmprestimo = null;
RequestDispatcher disp = null;
try {
dao = new EmprestimoDAO();
daoUsuario = new UsuarioDAO();
daoAlbum = new AlbumDAO();
daoTipoEmprestimo = new TipoEmprestimoDAO();
if ( acao.equals( "criar" ) ) {
String inicio = request.getParameter( "inicio" );
String fim = request.getParameter( "fim" );
int idUsuario = Integer.parseInt( request.getParameter( "idUsuario" ) );
int idAlbum = Integer.parseInt( request.getParameter( "idAlbum" ) );
int idTipoEmprestimo = Integer.parseInt( request.getParameter( "idTipoEmprestimo" ) );
Usuario usuario = daoUsuario.obterPorId(idUsuario);
Album album = daoAlbum.obterPorId(idAlbum);
TipoEmprestimo tipoEmprestimo = daoTipoEmprestimo.obterPorId(idTipoEmprestimo);
Emprestimo emprestimo = new Emprestimo();
emprestimo.setInicio( inicio );
emprestimo.setFim( fim );
emprestimo.setUsuario( usuario );
emprestimo.setAlbum( album );
emprestimo.setTipoEmprestimo( tipoEmprestimo );
dao.salvar( emprestimo );
disp = request.getRequestDispatcher( "/formularios/emprestimos/listagem.jsp" );
} else if ( acao.equals( "alterar" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
String inicio = request.getParameter( "inicio" );
String fim = request.getParameter( "fim" );
int idUsuario = Integer.parseInt( request.getParameter( "idUsuario" ) );
int idAlbum = Integer.parseInt( request.getParameter( "idAlbum" ) );
int idTipoEmprestimo = Integer.parseInt( request.getParameter( "idTipoEmprestimo" ) );
Usuario usuario = daoUsuario.obterPorId(idUsuario);
Album album = daoAlbum.obterPorId(idAlbum);
TipoEmprestimo tipoEmprestimo = daoTipoEmprestimo.obterPorId(idTipoEmprestimo);
Emprestimo emprestimo = new Emprestimo();
emprestimo.setId( id );
emprestimo.setInicio( inicio );
emprestimo.setFim( fim );
emprestimo.setUsuario( usuario );
emprestimo.setAlbum( album );
emprestimo.setTipoEmprestimo( tipoEmprestimo );
dao.atualizar( emprestimo );
disp = request.getRequestDispatcher( "/formularios/emprestimos/listagem.jsp" );
} else if ( acao.equals( "excluir" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
Emprestimo emprestimo = new Emprestimo();
emprestimo.setId( id );
dao.excluir( emprestimo );
disp = request.getRequestDispatcher( "/formularios/emprestimos/listagem.jsp" );
} else if ( acao.equals( "prepAlteracao" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
Emprestimo emprestimo = dao.obterPorId( id );
request.setAttribute( "emprestimo", emprestimo );
disp = request.getRequestDispatcher( "/formularios/emprestimos/alterar.jsp" );
} else if ( acao.equals( "prepExclusao" ) ) {
int id = Integer.parseInt( request.getParameter( "id" ) );
Emprestimo emprestimo = dao.obterPorId( id );
request.setAttribute( "emprestimo", emprestimo );
disp = request.getRequestDispatcher( "/formularios/emprestimos/excluir.jsp" );
}
} catch ( SQLException exc ) {
exc.printStackTrace();
} finally {
if ( dao != null ) {
try {
dao.fecharConexao();
} catch ( SQLException exc ) {
exc.printStackTrace();
}
}
}
if ( disp != null ) {
disp.forward( request, response );
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/locadoraAlbuns/src/java/locadoraAlbuns/servicos/BandaServices.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package locadoraAlbuns.servicos;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import locadoraAlbuns.dao.BandaDAO;
import locadoraAlbuns.entidades.Banda;
/**
*
* @author CaueSJ
*/
public class BandaServices {
public List<Banda> getTodos() {
List<Banda> lista = new ArrayList<Banda>();
BandaDAO dao = null;
try {
dao = new BandaDAO();
lista = dao.listarTodos();
} catch ( SQLException exc ) {
exc.printStackTrace();
} finally {
if ( dao != null ) {
try {
dao.fecharConexao();
} catch ( SQLException exc ) {
exc.printStackTrace();
}
}
}
return lista;
}
}
| c49541fcb9a59dfe6fc63e0478ee4f2084e8d743 | [
"Markdown",
"Java"
]
| 16 | Java | nathipg/locadora-albuns | 88d00ea6ae29432589a0cbf92b7a939012892e22 | 2ba5e92d6501822031cc030c1dd33eb22a75c8d0 |
refs/heads/main | <repo_name>JunaidNayeem/Iternity-Foundation-DSA-Internship<file_sep>/task4.cpp
//Bubble Sort Implementation in Ascending Order
#include <iostream>
using namespace std;
//Bubble sort Algorithm
void bubbleSort(int arr[], int n){
bool flag = false;
for (int i=0; i<n-1;i++){
for(int j = 0; j<n-i-1; j++){
if(arr[j]>arr[j+1]){
flag = true;
swap(arr[j],arr[j+1]);
}
}
if(flag==false)
return;
}
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
bubbleSort(arr, n);
for(int i=0; i<n; i++){
cout<<arr[i]<<" ";
}
return 0;
}
//Selection Sort Implementation in Descending Order
#include <iostream>
using namespace std;
void selectionSort(int arr[],int n)
{
int i,j,min,temp;
for(i=0;i<n;i++){
min=i;
for(j=i+1;j<n;j++)
{
if(arr[j]>arr[min]){
min=j;
}
}
temp=arr[i];
arr[i]=arr[min];
arr[min]=temp;
}
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
selectionSort(arr,n);
for(int i=0; i<n; i++){
cout<<arr[i]<<" ";
}
return 0;
}
// Count Sort Implementation in Ascending Order
#include <iostream>
using namespace std;
void countSort(int arr[],int n){
int k = arr[0];
for(int i=0; i<n; i++){
k = max(k, arr[i]);
}
int count[k]={0};
for(int i=0; i<n; i++){
count[arr[i]]++;
}
for(int i=1; i<=k; i++){
count[i]+=count[i-1];
}
int output[n];
for(int i=n-1; i>=0; i--){
output[--count[arr[i]]]=arr[i];
}
for(int i=0; i<n; i++){
arr[i]=output[i];
}
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
countSort(arr,n);
for(int i=0; i<n; i++){
cout<<arr[i]<<" ";
}
return 0;
}
<file_sep>/Task6.cpp
//1. Detect cycle in a linked list.
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node *next;
node(int val){
data=val;
next=NULL;
}
};
void insert(node *&head, int val){
node *n=new node(val);
if(head==NULL){
head=n;
return;
}
node *temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=n;
}
void display(node *head){
node *temp=head;
while(temp!=NULL){
cout<<temp->data<<"->";
temp=temp->next;
}
cout<<"NULL"<<endl;
}
void createCycle(node *&head, int pos){
node *temp=head;
node *cycleNode;
int count=0;
while(temp->next!=NULL){
if(count==pos){
cycleNode=temp;
}
count++;
temp=temp->next;
}
temp->next=cycleNode;
}
bool detectCycle(node *head){
bool flag=false;
node *walk=head;
node *run=head;
while(run!=NULL && run->next!=NULL){
run=run->next;
if(run==walk){
flag=true;
break;
}
walk=walk->next;
run=run->next;
}
return flag;
}
void removeCycle(node *&head){
node *walk=head;
node *run=head;
do{
walk=walk->next;
run=run->next->next;
}while(walk!=run);
int point;
run=head;
while(run->next!=walk->next){
run=run->next;
walk=walk->next;
}
point=run->data;
cout<<"Point at which Cycle Starts :"<<point<<endl;
walk->next=NULL;
}
int main(){
node *head=NULL;
insert(head,1);
insert(head,2);
insert(head,3);
insert(head,4);
insert(head,5);
insert(head,6);
display(head);
createCycle(head,3);
if(detectCycle(head)==true){
cout<<"The given List is Cyclic"<<endl;
}
else{
cout<<"The given List is not Cyclic"<<endl;
}
removeCycle(head);
display(head);
if(detectCycle(head)==true){
cout<<"The given List is Cyclic"<<endl;
}
else{
cout<<"The given List is not Cyclic"<<endl;
}
return 0;
}
//return start of the cycle
#include<bits/stdc++.h>
using namespace std;
#define vi vector<int>
#define itr(i,a,b) for(int i=a;i<b;i++)
void heapify(vi &a, int n, int i){
int maxInx=i;
int l=2*i+1;
int r=2*i+2;
if(l<n && a[l]>a[maxInx])
maxInx=l;
if(r<n && a[r]>a[maxInx])
maxInx=r;
if(maxInx != i){
swap(a[i],a[maxInx]);
heapify(a,n,maxInx);
}
}
void heapSort(vi &a){
int n=a.size();
for(int i=n/2-1; i>=0; i--){
heapify(a,n,i);
}
for(int i=n-1; i>0; i--){
swap(a[0],a[i]);
heapify(a,i,0);
}
}
int main(){
int n;
cin>>n;
vi a(n);
itr(i,0,n){
cin>>a[i];
}
heapSort(a);
itr(i,0,n){
cout<<a[i]<<" ";
}
return 0;
}
//Imolementation of Radix Sort
#include<bits/stdc++.h>
using namespace std;
#define vi vector<int>
#define itr(i,a,b) for(int i=a;i<b;i++)
int getMax(vi &a){
int n=a.size();
int mx=a[0];
itr(i,0,n)
mx=max(a[i],mx);
return mx;
}
void countSort(vi &a, int n, int pos){
vi b(n),count(10);
int i;
count[10]={0};
itr(i,0,n){
++count[(a[i]/pos)%10];
}
itr(i,1,10){
count[i]+=count[i-1];
}
//making output array
for(i=n-1;i>=0;i--){
b[--count[(a[i]/pos)%10]]=a[i];
}
itr(i,0,n){
a[i]=b[i];
}
}
void radixSort(vi &a){
int n=a.size();
int mx=getMax(a);
int pos;
for(pos=1; mx/pos>0; pos*=10){
countSort(a,n,pos);
}
}
int main(){
int n;
cin>>n;
vi s(n);
itr(i,0,n){
cin>>s[i];
}
radixSort(s);
itr(i,0,n)
cout<<s[i]<<" ";
return 0;
}
//Implementation of Doubly LinkedList
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node *next;
node *prev;
node(int val){
data=val;
next=NULL;
prev=NULL;
}
};
void insertAtHead(node *&head, int val){
node *n=new node(val);
n->next=head;
if(head!=NULL)
head->prev=n;
head=n;
}
void insert(node *&head, int val){
node *n=new node(val);
node *temp=head;
if(head==NULL){
n->next=head;
if(head!=NULL)
head->prev=n;
head=n;
return;
}
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=n;
n->prev=temp;
}
void display(node *head){
node *temp=head;
cout<<"NULL <-> ";
while(temp!=NULL){
cout<<temp->data<<" <-> ";
temp=temp->next;
}
cout<<"NULL"<<endl;
}
void deletion(node *&head, int pos){
node *temp=head;
int count=1;
if(pos==1){
head=head->next;
head->prev=NULL;
delete temp;
return;
}
while(temp!=NULL && count!=pos){
temp=temp->next;
count++;
}
temp->prev->next=temp->next;
if(temp->next!=NULL)
temp->next->prev=temp->prev;
delete temp;
}
int main(){
node *head=NULL;
insert(head,1);
insert(head,2);
insert(head,3);
insert(head,4);
insert(head,5);
insert(head,6);
insertAtHead(head,7);
display(head);
int pos;
cout<<"Enter the position of node you want to delete :";
cin>>pos;
deletion(head,pos);
display(head);
return 0;
}
//Sort Doubly Linkedlist
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node *next;
node *prev;
node(int val){
data=val;
next=NULL;
prev=NULL;
}
};
void insertAtHead(node *&head, int val){
node *n=new node(val);
n->next=head;
if(head!=NULL)
head->prev=n;
head=n;
}
void insert(node *&head, int val){
node *n=new node(val);
node *temp=head;
if(head==NULL){
n->next=head;
if(head!=NULL)
head->prev=n;
head=n;
return;
}
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=n;
n->prev=temp;
}
void display(node *head){
node *temp=head;
cout<<"NULL <-> ";
while(temp!=NULL){
cout<<temp->data<<" <-> ";
temp=temp->next;
}
cout<<"NULL"<<endl;
}
void sort(node *&head){
node *currPtr=head;
node *indexPtr;
int temp;
if(head==NULL){
return;
}
while(currPtr->next!=NULL){
indexPtr=currPtr->next;
while(indexPtr!=NULL){
if(currPtr->data>indexPtr->data){
temp=currPtr->data;
currPtr->data=indexPtr->data;
indexPtr->data=temp;
}
indexPtr=indexPtr->next;
}
currPtr=currPtr->next;
}
}
int main(){
node *head=NULL;
insert(head,3);
insert(head,5);
insert(head,1);
insert(head,4);
insert(head,2);
insert(head,6);
insertAtHead(head,7);
cout<<"Unsorted Doubly Linked List : "<<endl;
display(head);
sort(head);
cout<<"Sorted Doubly Linked List : "<<endl;
display(head);
return 0;
}
//Implementation of Circular LinkedList
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;
node(int val){
data=val;
next=NULL;
}
};
//inset at Head
void insertAtHead(node *&head, int val){
node *n=new node(val);
if(head==NULL){
n->next=n;
head=n;
return;
}
node *temp=head;
while (temp->next!=head){
temp=temp->next;
}
temp->next=n;
n->next=head;
head=n;
}
//insert Function
void insert(node * &head, int val){
node *n=new node(val);
if(head==NULL){
n->next=n;
head=n;
return;
}
node *temp=head;
while (temp->next!=head){
temp=temp->next;
}
temp->next=n;
n->next=head;
}
void deleteAthead(node *&head){
node *temp=head;
while(temp!=head){
temp=temp->next;
}
node *todelete=head;
temp->next=head->next;
head=head->next;
delete todelete;
}
///deletion function
void deletion(node *&head, int pos){
int count=1;
if(pos==1){
deleteAthead(head);
return;
}
node *todelete;
node *temp=head;
while(count!=pos-1){
count++;
temp=temp->next;
}
todelete=temp->next;
temp->next=temp->next->next;
delete todelete;
}
void display(node *head){
node *temp=head;
do{
cout<<temp->data<<"->";
temp=temp->next;
}while(temp!=head);
cout<<head->data<<endl;
}
int main(){
node *head=NULL;
insert(head,1);
insert(head,2);
insert(head,3);
insert(head,4);
insert(head,5);
insert(head,6);
display(head);
deletion(head,4);
display(head);
//display(newNode);
return 0;
}
//9
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;
node(int val){
data=val;
next=NULL;
}
};
//insert Function
void insert(node * &head, int val){
node *n=new node(val);
if(head==NULL){
head=n;
return;
}
node *temp=head;
while (temp->next!=NULL){
temp=temp->next;
}
temp->next=n;
}
//to return require new node
node *nodeSum(node *head1, node *head2){
node *sumNode=NULL;
node *temp1=head1;
node *temp2=head2;
long long int sum,carry=0;
while(temp1!=NULL && temp2!=NULL){
cout<<temp1->data<<" + "<<temp2->data<<" = ";
if(temp1==NULL)
sum=temp2->data+carry;
else if(head2==NULL)
sum=temp1->data+carry;
else
sum=temp1->data+temp2->data+carry;
if(sum>=10){
sum=sum-10;
carry=1;
}
else
carry=0;
cout<<sum<<endl;
insert(sumNode,sum);
if(temp1!=NULL)
temp1=temp1->next;
if(temp2!=NULL)
temp2=temp2->next;
}
return sumNode;
}
void display(node *head){
node *temp=head;
while(temp!=NULL){
cout<<temp->data<<"->";
temp=temp->next;
}
cout<<"NULL"<<endl;
}
int main(){
node *head1=NULL;
node *head2=NULL;
insert(head1,2);
insert(head1,4);
insert(head1,3);
insert(head1,9);
insert(head1,9);
insert(head1,9);
insert(head1,9);
insert(head2,5);
insert(head2,6);
insert(head2,4);
insert(head2,9);
display(head1);
display(head2);
node *sN=nodeSum(head1,head2);
display(sN);
return 0;
}
<file_sep>/Task2.cpp
// 1. Find length of an array
#include<iostream>
using namespace std;
int main(){
int arr[]={1,4,8,9,3,2};
int length_of_Array = sizeof(arr)/sizeof(arr[0]);//finding the size of array
cout<<length_of_Array<<endl;
return 0;
}
// 2. Reverse the array
#include<iostream>
using namespace std;
int main(){
int n,l=0,h;
cin>>n;
h=n-1;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
//Reversing the Array
while(l<h){
int temp=arr[l];
arr[l]=arr[h];
arr[h]=temp;
l++;
h--;
}
for(int i=0; i<n; i++){
cout<<arr[i]<<" ";
}
return 0;
}
// 3. Find the maximum and minimum element in an array
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int max=0,min;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
for(int i=0; i<n; i++){
if(max<arr[i]){
max=arr[i];
}
if(min>arr[i]){
min=arr[i];
}
}
cout<<"Maximum Element in Array :"<<max<<endl;
cout<<"Minimum Element in Array :"<<min<<endl;
return 0;
}
// 4. Find the "Kth" max and min element of an array
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int n;
cin>>n;
int k;
cin>>k;
int max,min;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
sort(arr, arr + n);
max = arr[n-k];
min = arr[k-1];
cout<<"Maximum Kth Element in the Array :"<<max<<endl;
cout<<"Minimum Kth Element in the Array :"<<min<<endl;
return 0;
}
// 4. Find the "Kth" max and min element of an array
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int n;
cin>>n;
int k;
cin>>k;
int max,min;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
sort(arr, arr + n);
max = arr[n-k];
min = arr[k-1];
cout<<"Maximum Kth Element in the Array :"<<max<<endl;
cout<<"Minimum Kth Element in the Array :"<<min<<endl;
return 0;
}
// 6. Move all the negative elements to one side of the array
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int arr[n];
int count = 0;
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=0;i<n;i++){
if(arr[i]<0)
{
int temp = arr[i];
arr[i] = arr[count];
arr[count] = temp;
count++;
}
}
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
return 0;
}
// 7. Find the Union and Intersection of the two sorted arrays.
#include<iostream>
using namespace std;
int printIntersection(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while (i < m && j < n)
{
if (arr1[i] < arr2[j])
i++;
else if (arr2[j] < arr1[i])
j++;
else
{
cout << arr2[j] << " ";
i++;
j++;
}
}
}
int printUnion(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while (i < m && j < n)
{
if (arr1[i] < arr2[j])
cout << arr1[i++] << " ";
else if (arr2[j] < arr1[i])
cout << arr2[j++] << " ";
else
{
cout << arr2[j++] << " ";
i++;
}
}
while(i < m)
cout << arr1[i++] << " ";
while(j < n)
cout << arr2[j++] << " ";
}
int main(){
int m;
cin>>m;
int arr1[m];
for(int i=0;i<m;i++){
cin>>arr1[i];
}
int n;
cin>>n;
int arr2[n];
int count = 0;
for(int i=0;i<n;i++){
cin>>arr2[i];
}
cout<<"Union elements in The Array :";
printUnion(arr1, arr2, m, n);
cout<<"Intersected elements in The Array :";
printIntersection(arr1, arr2, m, n);
return 0;
}
// 8. Given an array of digits check if the array is palindrome or not.
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int arr[n],l=0,h=n-1;
int count = 0;
bool flag=0;
for(int i=0;i<n;i++){
cin>>arr[i];
}
while(l<h){
if(arr[l]==arr[h]){
flag=1;
l++;
h--;
}
else
flag=0;
break;
}
if(flag==1)
cout<<"It is the Pallindrome Array";
else
cout<<"It is Not the Pallindrome Array";
return 0;
}
<file_sep>/README.md
# Iternity-Foundation-DSA-Internship
All the works and task during internship will be posted here
| 1408bf98e77628c108ae82e3a1382a26afa85c7a | [
"Markdown",
"C++"
]
| 4 | C++ | JunaidNayeem/Iternity-Foundation-DSA-Internship | b022cc00719673ec451b164837652ba3cc186dba | 1c2edefa24077f5c419a6fb7035a25b49f30e619 |
refs/heads/master | <repo_name>potaesm/pyqt5-face-recognition-app<file_sep>/FaceRecognitionApp.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'FaceRecognitionApp.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 520)
MainWindow.setMinimumSize(QtCore.QSize(800, 520))
MainWindow.setMaximumSize(QtCore.QSize(800, 520))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Active, QtGui.QIcon.Off)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Active, QtGui.QIcon.On)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Selected, QtGui.QIcon.On)
MainWindow.setWindowIcon(icon)
MainWindow.setToolTip("")
MainWindow.setStatusTip("")
MainWindow.setWhatsThis("")
MainWindow.setAccessibleName("")
MainWindow.setAccessibleDescription("")
MainWindow.setWindowFilePath("")
MainWindow.setDocumentMode(False)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
self.layoutWidget.setGeometry(QtCore.QRect(10, 20, 781, 482))
self.layoutWidget.setObjectName("layoutWidget")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.layoutWidget)
self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.imageLabel = QtWidgets.QLabel(self.layoutWidget)
self.imageLabel.setMinimumSize(QtCore.QSize(640, 480))
self.imageLabel.setMaximumSize(QtCore.QSize(640, 480))
self.imageLabel.setStyleSheet("background-color: rgb(112, 112, 112);")
self.imageLabel.setText("")
self.imageLabel.setObjectName("imageLabel")
self.horizontalLayout_2.addWidget(self.imageLabel)
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.toggleCameraButton = QtWidgets.QPushButton(self.layoutWidget)
self.toggleCameraButton.setObjectName("toggleCameraButton")
self.verticalLayout.addWidget(self.toggleCameraButton)
self.captureButton = QtWidgets.QPushButton(self.layoutWidget)
self.captureButton.setObjectName("captureButton")
self.verticalLayout.addWidget(self.captureButton)
self.chooseCompareImageButton = QtWidgets.QPushButton(self.layoutWidget)
self.chooseCompareImageButton.setObjectName("chooseCompareImageButton")
self.verticalLayout.addWidget(self.chooseCompareImageButton)
self.CompareButton = QtWidgets.QPushButton(self.layoutWidget)
self.CompareButton.setObjectName("CompareButton")
self.verticalLayout.addWidget(self.CompareButton)
spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.resultTitleLabel = QtWidgets.QLabel(self.layoutWidget)
self.resultTitleLabel.setObjectName("resultTitleLabel")
self.horizontalLayout.addWidget(self.resultTitleLabel)
self.resultLabel = QtWidgets.QLabel(self.layoutWidget)
self.resultLabel.setObjectName("resultLabel")
self.horizontalLayout.addWidget(self.resultLabel)
self.verticalLayout.addLayout(self.horizontalLayout)
self.horizontalLayout_2.addLayout(self.verticalLayout)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Face Recognition App"))
self.toggleCameraButton.setText(_translate("MainWindow", "Turn On"))
self.captureButton.setText(_translate("MainWindow", "Capture"))
self.chooseCompareImageButton.setText(_translate("MainWindow", "Choose Image"))
self.CompareButton.setText(_translate("MainWindow", "Compare"))
self.resultTitleLabel.setText(_translate("MainWindow", "Result:"))
self.resultLabel.setText(_translate("MainWindow", "False"))
import resource_rc
<file_sep>/FaceRecognitionApp-generated.py
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QMessageBox, QFileDialog, QSystemTrayIcon, QStyle, QAction, qApp, QMenu
import resource
import cv2
import tempfile
import requests
import os
# noinspection PyAttributeOutsideInit
class UiMainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.screenSize = QtWidgets.QDesktopWidget().screenGeometry(-1)
self.setupUi()
# self.setWindowFlags(QtCore.Qt.ToolTip | QtCore.Qt.WindowStaysOnTopHint)
self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint)
self.__toggleCam = False
self.__onCaptureClicked = False
self.__onCompareImageClicked = False
self.__compareImagePath = ""
# Init QSystemTrayIcon
self.trayIcon = QSystemTrayIcon(self)
self.trayIcon.setIcon(self.style().standardIcon(QStyle.SP_ComputerIcon))
showAction = QAction("Show", self)
quitAction = QAction("Exit", self)
hideAction = QAction("Hide", self)
showAction.triggered.connect(self.showMainWindow)
hideAction.triggered.connect(self.hide)
quitAction.triggered.connect(qApp.quit)
trayMenu = QMenu()
trayMenu.addAction(showAction)
trayMenu.addAction(hideAction)
trayMenu.addAction(quitAction)
self.trayIcon.setContextMenu(trayMenu)
def changeEvent(self, event):
if event.type() == QtCore.QEvent.WindowStateChange:
if event.oldState() == QtCore.Qt.WindowMinimized:
self.trayIcon.hide()
# self.trayIcon.showMessage("Tray Program", "Application was minimized to Tray", QSystemTrayIcon.Information, 2000)
print("WindowMaximized")
elif event.oldState() == QtCore.Qt.WindowNoState or self.windowState() == QtCore.Qt.WindowMinimized:
self.hide()
self.trayIcon.show()
print("WindowMinimized")
def closeEvent(self, event):
reply = QMessageBox.question(self, "Quit", "Are you sure to quit?", QMessageBox.No | QMessageBox.Yes)
if reply == QMessageBox.Yes:
self.__toggleCam = False
event.accept()
else:
event.ignore()
def hideMainWindowToTray(self):
self.hide()
self.trayIcon.show()
def showMainWindow(self):
self.showNormal()
self.trayIcon.hide()
def setupUi(self):
self.setObjectName("MainWindow")
self.resize(self.screenSize.width(), self.screenSize.height())
# self.resize(800, 520)
# self.setMinimumSize(QtCore.QSize(800, 520))
# self.setMaximumSize(QtCore.QSize(800, 520))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Disabled, QtGui.QIcon.Off)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Disabled, QtGui.QIcon.On)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Active, QtGui.QIcon.Off)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Active, QtGui.QIcon.On)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Selected, QtGui.QIcon.Off)
icon.addPixmap(QtGui.QPixmap(":/src/Themes/eyeIcon.png"), QtGui.QIcon.Selected, QtGui.QIcon.On)
self.setWindowIcon(icon)
self.setToolTip("")
self.setStatusTip("")
self.setWhatsThis("")
self.setAccessibleName("")
self.setAccessibleDescription("")
self.setWindowFilePath("")
self.setDocumentMode(False)
self.centralwidget = QtWidgets.QWidget(self)
self.centralwidget.setObjectName("centralwidget")
self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
self.layoutWidget.setGeometry(QtCore.QRect(10, 20, 781, 482))
self.layoutWidget.setObjectName("layoutWidget")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.layoutWidget)
self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.imageLabel = QtWidgets.QLabel(self.layoutWidget)
self.imageLabel.setMinimumSize(QtCore.QSize(640, 480))
self.imageLabel.setMaximumSize(QtCore.QSize(640, 480))
self.imageLabel.setStyleSheet("background-color: rgb(112, 112, 112);")
self.imageLabel.setText("")
self.imageLabel.setObjectName("imageLabel")
self.horizontalLayout_2.addWidget(self.imageLabel)
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.toggleCameraButton = QtWidgets.QPushButton(self.layoutWidget)
self.toggleCameraButton.setObjectName("toggleCameraButton")
self.verticalLayout.addWidget(self.toggleCameraButton)
self.captureButton = QtWidgets.QPushButton(self.layoutWidget)
self.captureButton.setObjectName("captureButton")
self.verticalLayout.addWidget(self.captureButton)
self.chooseCompareImageButton = QtWidgets.QPushButton(self.layoutWidget)
self.chooseCompareImageButton.setObjectName("chooseCompareImageButton")
self.verticalLayout.addWidget(self.chooseCompareImageButton)
self.compareButton = QtWidgets.QPushButton(self.layoutWidget)
self.compareButton.setObjectName("compareButton")
self.verticalLayout.addWidget(self.compareButton)
self.minimizeButton = QtWidgets.QPushButton(self.layoutWidget)
self.minimizeButton.setObjectName("minimizeButton")
self.verticalLayout.addWidget(self.minimizeButton)
self.quitButton = QtWidgets.QPushButton(self.layoutWidget)
self.quitButton.setObjectName("quitButton")
self.verticalLayout.addWidget(self.quitButton)
spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.resultTitleLabel = QtWidgets.QLabel(self.layoutWidget)
self.resultTitleLabel.setObjectName("resultTitleLabel")
self.horizontalLayout.addWidget(self.resultTitleLabel)
self.resultLabel = QtWidgets.QLabel(self.layoutWidget)
self.resultLabel.setObjectName("resultLabel")
self.resultLabel.setWordWrap(True)
self.horizontalLayout.addWidget(self.resultLabel)
self.verticalLayout.addLayout(self.horizontalLayout)
self.horizontalLayout_2.addLayout(self.verticalLayout)
self.setCentralWidget(self.centralwidget)
self.toggleCameraButton.clicked.connect(self.displayImage)
self.captureButton.clicked.connect(self.captureImage)
self.chooseCompareImageButton.clicked.connect(self.chooseImageToCompare)
self.compareButton.clicked.connect(self.compareImage)
self.minimizeButton.clicked.connect(self.hideMainWindowToTray)
self.quitButton.clicked.connect(self.close)
self.retranslateUi()
QtCore.QMetaObject.connectSlotsByName(self)
def retranslateUi(self):
_translate = QtCore.QCoreApplication.translate
self.setWindowTitle(_translate("MainWindow", "Face Recognition App"))
self.toggleCameraButton.setText(_translate("MainWindow", "Turn On"))
self.captureButton.setText(_translate("MainWindow", "Capture"))
self.chooseCompareImageButton.setText(_translate("MainWindow", "Choose Image"))
self.compareButton.setText(_translate("MainWindow", "Compare"))
self.minimizeButton.setText(_translate("MainWindow", "Minimize"))
self.quitButton.setText(_translate("MainWindow", "Quit"))
self.resultTitleLabel.setText(_translate("MainWindow", "Result:"))
self.resultLabel.setText(_translate("MainWindow", "False"))
def captureImage(self):
if self.__toggleCam:
self.__onCaptureClicked = True
def destroyImage(self):
self.toggleCameraButton.setText("Turn On")
self.imageLabel.setText(" ")
cv2.destroyAllWindows()
def saveImage(self, img):
path = QFileDialog.getSaveFileName()
cv2.imwrite(path[0], img)
def chooseImageToCompare(self):
path = QFileDialog.getOpenFileName()
self.__compareImagePath = os.path.normpath(path[0])
print(self.__compareImagePath)
def compareImage(self):
if self.__toggleCam:
self.__onCompareImageClicked = True
def sendCompareRequest(self, img):
with tempfile.TemporaryDirectory() as tmpDirName:
filePath = tmpDirName + ".jpg"
cv2.imwrite(filePath, img)
imgName = os.path.basename(filePath)
compareImgName = os.path.basename(self.__compareImagePath)
proxy_dict = {}
# proxy_dict = {"http": "http://10.186.208.15:8080"}
imageFileDescriptor = open(filePath, 'rb')
compareImageFileDescriptor = open(self.__compareImagePath, 'rb')
print(compareImageFileDescriptor, imageFileDescriptor)
# Single file
# files = {'img': (imgName, imageFileDescriptor, 'multipart/form-data', {'Expires': '0'})}
# Multiple files
files = [
("imgs", (imgName, imageFileDescriptor, 'multipart/form-data', {'Expires': '0'})),
("imgs", (compareImgName, compareImageFileDescriptor, 'multipart/form-data', {'Expires': '0'}))
]
response = requests.request("POST", "https://node-js-face-api.herokuapp.com/compare", files=files,
proxies=proxy_dict)
# self.resultLabel.setText(response.text)
self.resultLabel.setText(response.text)
# print(response.text)
imageFileDescriptor.close()
if os.path.exists(filePath):
os.remove(filePath)
def displayImage(self):
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
self.__toggleCam = not self.__toggleCam
if not self.__toggleCam:
self.destroyImage()
else:
self.toggleCameraButton.setText("Turn Off")
captureImage = None
while cap.isOpened() and not self.__onCaptureClicked and not self.__onCompareImageClicked and self.__toggleCam:
ret, img = cap.read()
if ret:
captureImage = img
qformat = QImage.Format_Indexed8
if len(img.shape) == 3:
if (img.shape[2]) == 4:
qformat = QImage.Format_RGBA888
else:
qformat = QImage.Format_RGB888
img = QImage(img, img.shape[1], img.shape[0], qformat)
img = img.rgbSwapped()
self.imageLabel.setPixmap(QPixmap.fromImage(img))
cv2.waitKey()
if self.__onCaptureClicked:
self.__toggleCam = False
self.__onCaptureClicked = False
self.destroyImage()
self.saveImage(captureImage)
if self.__onCompareImageClicked:
self.__toggleCam = False
self.__onCompareImageClicked = False
self.destroyImage()
self.sendCompareRequest(captureImage)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = UiMainWindow()
mainWindow.show()
sys.exit(app.exec_())
| ad8fb71a3e476dacaa83d74c5c5e5572c684df89 | [
"Python"
]
| 2 | Python | potaesm/pyqt5-face-recognition-app | cdba33913f59d54c354e6bee7b76c03b53c23ea3 | 4d96b9ce0a14ce86acd33ce871dead58caecd392 |
refs/heads/main | <file_sep>#!/bin/bash
dispdir=$(pwd) # run this script in the directory, where lastdir is located (so either in disp_pos or disp_neg)
lastdir=$1 # provide path to starting point WITHOUT LEADING ZEROS! (e.g. 0003 -> 3)
stopdir=$2 # defines number of displacements to make (=stopdir-lastdir), WITHOUT LEADING ZEROS
displacement=$3 # Angstrom
config_file=$4 # path to config file
source $config_file
#catch signal
trap ". $helper_files/action_before_death.sh $dispdir $config_file" SIGUSR1
#trap "touch ./signal" SIGUSR1
# set Intel environment
module load intel
module load openmpi
module load mkl
#set turbo path
. $turbopath
export PARA_ARCH=SMP
#export SMPCPUS=$cpus_per_task
cpus_per_task=$(head -n 1 ../complexity)
export SMPCPUS=$cpus_per_task
export OMP_NUM_THREADS=$cpus_per_task
ulimit -s unlimited
ulimit -a > mylimits.out
jobgen=$helper_files/jobgen.py
lastdirfp=$dispdir/$(printf "%04d" $lastdir)
if [ ! -d "$lastdirfp" ]; then
echo "Path" $lastdirfp "not found!"
exit 1
fi
echo "starting from" $lastdirfp
echo "displacement:" $displacement "Angstrom"
# read lead limits, prepare variables, relax structures in 0000, cd to 0000
cd $(printf "%04d" $lastdir)
#check if prerelax (unfix sulfur, relax, align along z again and fix sulfur again) is wanted.
if [ "$prerelax" == "T" ]; then
echo "Prerelaxation...."
define < $helper_files/build_calc > define.out
#save fixed atoms, remove fix command from coord file
awk '{print $5}' coord > fixed
grep -irn "f" fixed | cut -f1 -d: > fixed_lines
awk '{print $1,$2,$3,$4}' coord > coord_unfixed
rm -r coord
cp coord_unfixed coord
rm -r coord_unfixed
#relax
jobex -ri -c $relax_iterations -level $relax_level > jobex_prerelax.log
#fix again
paste coord fixed > coord_fixed_again
rm -r coord
cp coord_fixed_again coord
rm -r coord_fixed_again
#align anchors along z again and update limits
python3 $helper_files/align_anchor_update_limits.py $dispdir/$(printf "%04d" $lastdir) $config_file
fi
jobex -ri -c $relax_iterations -level $relax_level > jobex.log
file=GEO_OPT_FAILED
if test -f "$file" ; then
echo "Geo opt failed"
file=../../KILL_SIGNAL_SET
if test -f "$file" ; then
echo "Kill signal set"
else
. $helper_files/action_before_death.sh $dispdir $config_file
exit 0
fi
fi
file=GEO_OPT_CONVERGED
if test -f "$file" ; then
ls
echo "geo opt converged... starting dft"
t2x coord > coord.xyz
ridft -> ridft.out
fi
lower=$(sed '1q;d' limits )
upper=$(sed '2q;d' limits )
cd $dispdir
disphalf=$(echo $displacement/2|bc -l)
currentdir=$lastdir
echo $displacement
while [ $currentdir -lt $stopdir ]
do
file=../KILL_SIGNAL_SET
if test -f "$file"; then
exit 0
fi
currentdir=$[$lastdir+1]
# zero padding
printf -v zpcurrentdir "%04d" $currentdir
printf -v zplastdir "%04d" $lastdir
echo "copying" $zplastdir "to" $zpcurrentdir
rm -rf $zpcurrentdir
cp -r $zplastdir $zpcurrentdir
echo "displacing atoms with block limits" $lower "and" $upper
python3 $jobgen -fixed_atoms $zplastdir/coord $zpcurrentdir/coord $displacement
lower=$(echo $lower - $disphalf|bc -l)
upper=$(echo $upper + $disphalf|bc -l)
# save new limits for further post processing
cd $zpcurrentdir
rm limits
echo $lower >> limits
echo $upper >> limits
echo "starting turbomole calculation in" $zpcurrentdir
jobex -ri -c $relax_iterations -level $relax_level > jobex.log
file=GEO_OPT_FAILED
if test -f "$file" ; then
echo "Geo opt failed"
file=../../KILL_SIGNAL_SET
if test -f "$file" ; then
echo "Kill signal set"
else
. $helper_files/action_before_death.sh $dispdir $config_file
exit 0
fi
fi
#remove!
touch GEO_OPT_CONVERGED
file=GEO_OPT_CONVERGED
if test -f "$file" ; then
ls
echo "geo opt converged... starting dft"
ridft -> ridft.out
fi
cd $dispdir
lastdir=$currentdir
done
cd $dispdir
#notify the world when calc completed
parent=$(basename ${PWD%})
if [ "$parent" = "disp_pos" ]; then
echo "This was disp_pos"
touch ../DISP_POS_DONE
fi
if [ "$parent" = "disp_neg" ]; then
echo "This was disp_neg"
touch ../DISP_NEG_DONE
fi
#generation_individual
filename=$(basename ${PWD%/*/*})_$(basename ${PWD%/*})
#if calc for pos and neg displacement are ready -> evaluation
file=../DISP_POS_DONE
if test -f "$file"; then
file=../DISP_NEG_DONE
if test -f "$file"; then
file=../KILL_SIGNAL_SET
if test -f "$file"; then
echo "kill signal has been set"
else
echo "now evaluate everything"
#all the evaluation scripts
#stiffness evaluation
GRANDDADDY="$(cd ../; pwd)"
. $helper_files/eval_stiffness.sh $GRANDDADDY $filename $config_file
#T estimation
#take number of occupied orbital from 0000/ridft.out
line=$(grep -o " number of occupied orbitals : .*" ./0000/ridft.out)
homo=${line//$"number of occupied orbitals :"}
python3 $helper_files/eval_propagator.py ../ $filename $homo $config_file
python3 $helper_files/eval_propagator_map.py ../ $filename $homo $config_file 3.0 2000
python3 $helper_files/breaking_ana.py ../ $filename
. $helper_files/collect_coord.sh ../ ./stretching.xyz tmp_coord.xyz
#now everything is done
echo "i reached the end...tell everyone"
touch ../../${filename}_DONE
fi
fi
fi
#check if calculations of all individuals are ready but only if kill signal has not been set
num_finished=$(ls ../../ -1f | grep _DONE | wc -l)
if [ "$num_finished" -eq "$population_size" ]; then
file=../KILL_SIGNAL_SET
if test -f "$file"; then
echo "kill signal has been set"
else
echo "Everybody seems to be ready"
#eval fitness
python3 $genetic_algorithm_path/src/helper_files/eval_fitness.py $calculation_path"/generation_data/"$(basename ${PWD%/*/*}) $config_file
#invoke next generation
python3 $genetic_algorithm_path/src/genetic/invoke_next_generation.py $config_file $calculation_path
#plot fitness values
python3 $genetic_algorithm_path/src/helper_files/plot_fitness_values.py $calculation_path $config_file $calculation_path
fi
fi
<file_sep>import numpy as np
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import tmoutproc as top
import sys
import configparser
def find_fixed_atoms(coord):
"""
Finds index of fixed atoms in coord file stored in coord. index_left<index_right from building procedure
Args:
param1 (np.ndarray): coord file loaded with top.read_coord_file
Returns:
(index_left, index_right)
"""
index_1=-1
index_2=-1
for i in range(0,coord.shape[1]):
#if line has fixed symbol
if(coord[4,i]=="f"):
if(index_1==-1):
index_1=i
if(index_1!=-1):
index_2=i
if(index_1!=-1 and index_2!=-1):
min=np.min((index_1,index_2))
max=np.max((index_1,index_2))
return(min,max)
else:
print("fixed atoms not foud")
return (-1,-1)
def align_z_along_fixed_ends(coord, fixed_beginning, fixed_end):
"""
Align molecule z axis along fixed ends. This is done by rotation about the axis given by curl(vec(fixed_beginning->fixed_end), e_z) by the angle between vec(fixed_beginning-fixed_end) and e_z
Args:
param1 (List of np.ndarray): coord file loaded with top.load_coord_file
param2 (int): index of fixed beginning (left)
param3 (int): index fixed end (right)
Returns:
int : (List of np.ndarray): coord file
"""
#calculate vec(fixed_beginning->fixed_end)
x_left = coord[0,fixed_beginning]
y_left = coord[1,fixed_beginning]
z_left = coord[2,fixed_beginning]
#shift to orgin
for j in range(0, len(coord)):
coord[0,j] = coord[0,j]-x_left
coord[1,j] = coord[1,j]-y_left
coord[2,j] = coord[2,j]-z_left
print("shift")
print(coord)
x_left = 0.0
y_left = 0.0
z_left = 0.0
x_right = coord[0,fixed_end]
y_right = coord[1,fixed_end]
z_right = coord[2,fixed_end]
molecule_axis = [x_right-x_left, y_right-y_left,z_right-z_left]
#calculate rotation angel
angle = np.arccos(molecule_axis[2]/np.linalg.norm(molecule_axis))
theta = angle
if(angle != 0):
#calculate rotation axis
rotation_axis = np.cross(molecule_axis, [0.0,0.0,1.0])
rotation_axis = 1.0/np.linalg.norm(rotation_axis)*rotation_axis
u = rotation_axis
#print("rotation axis " + str(rotation_axis))
#calculate rotation_matrix
rotation_matrix = [[np.cos(theta) + u[0]**2 * (1-np.cos(theta)), u[0] * u[1] * (1-np.cos(theta)) - u[2] * np.sin(theta), u[0] * u[2] * (1 - np.cos(theta)) + u[1] * np.sin(theta)],
[u[0] * u[1] * (1-np.cos(theta)) + u[2] * np.sin(theta), np.cos(theta) + u[1]**2 * (1-np.cos(theta)), u[1] * u[2] * (1 - np.cos(theta)) - u[0] * np.sin(theta)],
[u[0] * u[2] * (1-np.cos(theta)) - u[1] * np.sin(theta), u[1] * u[2] * (1-np.cos(theta)) + u[0] * np.sin(theta), np.cos(theta) + u[2]**2 * (1-np.cos(theta))]]
for j in range(0, len(coord)):
vector_to_rotate = [coord[0,j],coord[1,j],coord[2,j]]
rotated_vector = np.asmatrix(rotation_matrix)*np.asmatrix(vector_to_rotate).T
coord[0,j] = round(rotated_vector[0,0],5)
coord[1,j] = round(rotated_vector[1,0],5)
coord[2,j] = round(rotated_vector[2,0],5)
return coord
else:
return coord
def write_limits(path,coord,fixed_beginning, fixed_end, config_path):
"""
write limits for stretching. Done by extracting the z-coordinate of endings and adding 0.1Ang
Args:
param1 (string): path where limits file is sotred
param2 (np.ndArray): coord file loaded with top.load_coord_file
param3 (int): index of fixed beginning (left)
param4 (int): index fixed end (right)
param5 (string): path to config file
Returns:
"""
#load ang to bohr factor
cfg = configparser.ConfigParser()
cfg.read(config_path)
ang2Bohr = float(cfg.get('Building Procedure', 'ang2Bohr'))
lower_limit = float(coord[fixed_beginning][2])/ang2Bohr
upper_limit = float(coord[fixed_end][2])/ang2Bohr
if(upper_limit==lower_limit):
print("Faulty limits!")
return
if(upper_limit<lower_limit):
upper_limit = a
upper_limit = lower_limit
lower_limit = a
file = open(path+"/limits", "w")
file.write(str(lower_limit-0.1) + "\n")
file.write(str(upper_limit+0.1))
if __name__ == '__main__':
#argv[1] : calc path: where coord and fixed file is located and where result is stored
#argv[2] : config path
#load coord file
coord = top.read_coord_file(sys.argv[1]+ "/coord")
#find achors
fixed_index = find_fixed_atoms(coord)
#rotate and shift
coord = align_z_along_fixed_ends(coord, fixed_index[0], fixed_index[1])
#write coord file
top.write_coord_file(sys.argv[1]+ "/coord", coord)
#write limits
write_limits(sys.argv[1], coord, fixed_index[0], fixed_index[1], sys.argv[2])
<file_sep>import run_generation as rg
import sys
if __name__ == '__main__':
# argv[1] = config path
# argv[2] = calculation_path
rg.next_generation(sys.argv[1], sys.argv[2])
<file_sep>import numpy as np
import matplotlib
from matplotlib import cm
from matplotlib.colors import LogNorm
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import matplotlib.pyplot as plt
import tmoutproc as top
import os.path
from multiprocessing import Pool
from functools import partial
import sys
import configparser
har2eV = 27.2114
def eval_T(disp_index, para):
"""
evaluates zeroth order Greens function to estimate the Transmission in wide band limit. Function is used in multiprocessing
Args:
param1 (int): disp_index. Specifies which index in dir list should be processed
param2 (tuple): params
Returns:
(float:estimate for t, int: processed displacement index)
"""
directories = para[0]
min_displacement=para[1]
n_occupied = para[2]
E_min = para[3]
E_max = para[4]
n_E_steps = para[5]
E = np.linspace(E_min, E_max, n_E_steps)
directory = directories[disp_index+min_displacement]
try:
eigenvalues, eigenvectors = top.read_mos_file(directory + "/mos")
except ValueError as e:
print("error " + str(e))
return 0.0, float(disp_index)
coord = top.read_coord_file(directory + "/coord")
s_range = top.find_c_range_atom("s", 1, coord)
r_range = top.find_c_range_atom("s", 2, coord)
eigenvectors = np.asmatrix(eigenvectors)
delta = 1E-9
T_est = list()
numerator = np.asarray([(eigenvectors[r_range[0]:r_range[1],i])*np.transpose(eigenvectors[s_range[0]:s_range[1],i]) for i in range(0,len(eigenvalues))])
denominator = np.asarray([(E - eigenvalues[i] + 1.0j* delta) for i in range(0,len(eigenvalues))])
for j, energy in enumerate(E):
G0_sr = [np.asmatrix(numerator[i]/denominator[i][j]) for i in range(0,len(eigenvalues))]
G0_sr = np.asmatrix(np.sum(G0_sr, axis=0))
T_est_ = np.real(np.trace(G0_sr * np.conj(np.transpose(G0_sr))))
T_est.append(T_est_)
return T_est, float(disp_index)
def plot_T_vs_d_energy_resolved(calc_path, molecule_name, n_occupied, config_path, e_range=5, n_E_steps=1000):
"""
evaluates zeroth order Greens function to estimate the Transmission in wide band limit. T estimate is plotted vs displacement.
Args:
param1 (String): Path to turbomole calculation
param2 (String): molecule name generation_individual
param3 (int): occupied mos -> define fermi energy
param4 (String): Path to config file
param5 (float): Energy range from fermi energy (optional)
param6 (float): n_energy_steps (optional)
Returns:
"""
print("config path " + str(config_path))
#process disp_neg
list_neg = os.listdir(calc_path + "/disp_neg/")
list_neg = sorted(list_neg, reverse=True)
list_neg = [calc_path + "/disp_neg/" + s for s in list_neg if (os.path.isdir(calc_path + "/disp_neg/" + s)) and (s != '0000')]
list_neg = [s for s in list_neg if os.path.exists(s+"/GEO_OPT_CONVERGED")]
#process disp_pos
list_pos = os.listdir(calc_path + "/disp_pos/")
list_pos = sorted(list_pos)
list_pos = [calc_path + "/disp_pos/" + s for s in list_pos if os.path.isdir(calc_path + "/disp_pos/" + s)]
list_pos = [s for s in list_pos if os.path.exists(s+"/GEO_OPT_CONVERGED")]
#all folder which will be processed
folders = list(list_neg)
folders.extend(list_pos)
#determine Fermi energy
try:
eigenvalues, eigenvectors = top.read_mos_file(list_pos[0] + "/mos")
e_f = (eigenvalues[n_occupied - 1] + eigenvalues[n_occupied]) / 2.
print(f"Fermi energy={e_f}")
except ValueError as e:
print("error " + str(e))
disp_indices = np.linspace(-len(list_neg), len(list_pos),len(list_pos)+len(list_neg), False, dtype=int)
min_disp = len(list_neg)
E_min = e_f-e_range/har2eV
E_max = e_f+e_range/har2eV
eingabe = (folders, min_disp, n_occupied, E_min, E_max, n_E_steps)
cfg = configparser.ConfigParser()
cfg.read(config_path)
displacement = float(cfg.get('Turbomole Calculations', 'displacement_per_step'))
#multiprocessing
p = Pool(16)
result = p.map(partial(eval_T, para=eingabe), disp_indices)
T_est, disp = [], []
E = np.linspace(E_min, E_max, n_E_steps)
for x, y in result:
T_est.extend(x)
disp.append(float(y)*displacement)
T_est = np.reshape(T_est, (-1, len(E)))
fig, ax1 = plt.subplots(1)
cs = ax1.imshow(T_est.T, origin='lower', extent=[min(disp), max(disp), (E_min-e_f)*har2eV, (E_max-e_f)*har2eV], norm=LogNorm(),
aspect='auto', interpolation='None', cmap='jet', vmax=np.max(T_est)*1E-5)
plt.xlabel(r'Displacement $\AA$', fontsize=20)
plt.ylabel('Energy (eV)', fontsize=20)
cb = fig.colorbar(cs, ax=ax1)
cb.ax.tick_params(labelsize=15)
cb.set_label(r"$|\mathrm{G_{l,r}^{r/a}}|^2$", fontsize=20)
plt.tick_params(axis="x", labelsize=15)
plt.tick_params(axis="y", labelsize=15)
plt.savefig(calc_path + "/" + molecule_name + "_T_estimate_map.pdf", bbox_inches='tight')
plt.savefig(calc_path + "/" + molecule_name + "_T_estimate_map.svg", bbox_inches='tight')
#Seebeck coeff
dE = np.abs(E[0] - E[1])
S = np.gradient(T_est.T, dE, axis=0)
S = np.array(S)
S = -S / T_est.T
S_median = np.median(S)
fig, ax1 = plt.subplots(1)
cmap = cm.get_cmap('jet')
cmap.set_under('white')
cs = ax1.imshow(S, origin='lower',
extent=[min(disp), max(disp), (E_min - e_f) * har2eV, (E_max - e_f) * har2eV],
aspect='auto', interpolation='None', cmap=cmap, vmin = 0, vmax=S_median+1E3)
plt.xlabel(r'Displacement $\AA$', fontsize=20)
plt.ylabel('Energy (eV)', fontsize=20)
cb = fig.colorbar(cs, ax=ax1)
cb.ax.tick_params(labelsize=15)
cb.set_label(r"$\left[\mathrm{|G_{l,r}|^2}\right]^\prime/\left[\mathrm{|G_{l,r}|^2}\right]$", fontsize=20)
plt.tick_params(axis="x", labelsize=15)
plt.tick_params(axis="y", labelsize=15)
plt.savefig(calc_path + "/" + molecule_name + "_S_estimate_map.pdf", bbox_inches='tight')
plt.savefig(calc_path + "/" + molecule_name + "_S_estimate_map.svg", bbox_inches='tight')
if __name__ == '__main__':
#argv[1] : calc path: where disp_pos and disp_neg is located
#argv[2] : moleculename (prefix of plot files)
#argv[3] : occupied orbitals (e_f = (E_homo+E_lumo)/2)
#argv[4] : config_path
# argv[5] : e_range in eV (optional)
# argv[6] : n_E_steps (optional)
print(len(sys.argv))
if(len(sys.argv)==5):
plot_T_vs_d_energy_resolved(sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4])
elif(len(sys.argv)==6):
plot_T_vs_d_energy_resolved(sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4], float(sys.argv[5]))
elif(len(sys.argv)==7):
plot_T_vs_d_energy_resolved(sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4], float(sys.argv[5]), int(sys.argv[6]))
else:
print("Check your call")
<file_sep>import sys
import tmoutproc as top
"""
This script can be used to strech coord file for stretching trajectories.
@author: <NAME>
"""
def strech_on_z_coord(coord, disp, lower, upper):
"""
Displaces atoms with z_coord < lower -disp/2 and atoms with z_coord>lower +disp/s. All coordinates between lower
and upper are proportionally stretched, like on a rubber band
Args:
coord (np.ndarray): Coord file from top
disp (float): displacement in Bohr
lower (float): Lower cut in Bohr
upper (float): Upper cut in Bohr
Returns:
coord (np.ndarray): Stretched coord file
"""
assert lower < upper, "Limits are not reasonable"
for i in range(0, coord.shape[1]):
if (coord[2,i] < lower):
coord[2,i] -= disp / 2
elif (coord[2,i] > upper):
coord[2,i] += disp / 2
else: # stretch all atom coordinates in between limits
norm = (2 * coord[2,i] - upper - lower) / (upper - lower)
coord[2,i] += norm * disp / 2
return coord
def stretch_on_indices(coord, disp, lower_index, upper_index):
"""
Displaces atoms with z_coord <= z_coord[lower_index] -disp/2 and atoms with z_coord >= z_coord[lower_index] +disp/s.
All coordinates between lower and upper are proportionally stretched, like on a rubber band
Args:
coord (np.ndarray): Coord file from top
disp (float): displacement in Bohr
lower (int): Index of lower atom
upper (int): Index of uppper atom
Returns:
coord (np.ndarray): Stretched coord file
"""
lower = coord[2,lower_index]
upper = coord[2, upper_index]
assert lower < upper, "Indices are not reasonable"
for i in range(0, coord.shape[1]):
old = coord[2,i]
if (coord[2,i] <= lower):
coord[2,i] -= disp / 2
elif (coord[2,i] >= upper):
coord[2,i] += disp / 2
else: # stretch all atom coordinates in between limits
norm = (2 * coord[2,i] - upper - lower) / (upper - lower)
coord[2,i] += norm * disp / 2
print(coord[2,i], old, coord[2,i])
return coord
def find_fixed_atoms(coord):
"""
Finds the first two fixed atoms in coord file
Args:
coord: coord file from top
Returns:
fixed_atoms (list): List with indices of fixed atoms
"""
fixed_atoms = []
for i in range(0, coord.shape[1]):
if(coord[4,i] == "f"):
fixed_atoms.append(i)
if(len(fixed_atoms)==2):
break
return fixed_atoms
def find_atom_index_by_type(coord, type):
"""
Finds the first two atoms of type type in coord file
Args:
coord: coord file from top
type (String): Atom type to be found
Returns:
fixed_atoms (list): List with indices of fixed atoms
"""
atoms = []
for i in range(0, coord.shape[1]):
if(coord[3,i] == type):
atoms.append(i)
if(len(atoms)==2):
break
return atoms
if __name__ == '__main__':
coord_in_file_path = sys.argv[2]
coord_out_file_path = sys.argv[3]
disp = float(sys.argv[4]) * top.ANG2BOHR
coord_in_file = top.read_coord_file(coord_in_file_path)
#cuts are defined by zcoord
if(sys.argv[1] == "-zcoord"):
lower = float(sys.argv[5]) * top.ANG2BOHR
upper = float(sys.argv[6]) * top.ANG2BOHR
coord = strech_on_z_coord(coord_in_file, disp, lower, upper)
#cuts are defined by two fixed atoms. There can be only two fixed atoms. Mode is made for isolated molecules
elif(sys.argv[1] == "-fixed_atoms"):
fixed_atoms = find_fixed_atoms(coord_in_file)
assert len(fixed_atoms)==2, "Not two fixed atoms"
coord = stretch_on_indices(coord_in_file, disp, fixed_atoms[0], fixed_atoms[1])
#cuts are defined by two atoms of type sys.argv[5]
elif(sys.argv[1] == "-type"):
type = str(sys.argv[5])
atoms = find_atom_index_by_type(coord_in_file, type)
assert len(atoms)==2, "Not two atoms"
coord = stretch_on_indices(coord_in_file, disp, atoms[0], atoms[1])
else:
print("Usage")
print("jobgen.py [-zcoord] coords_in coords_out displacement[Ang] lower[Ang] upper[Ang]")
print("or")
print("jobgen.py [-fixed_sulfur] coords_in coords_out displacement[Ang]")
print("or")
print("jobgen.py [-type] coords_in coords_out displacement[Ang] type")
top.write_coord_file(coord_out_file_path, coord)<file_sep>Genetic Algorithm
==============
This code is part of "Designing Mechanosensitive Molecules from Building Blocks: A Genetic Algorithm-Based
Approach"
# TOC
* [Requirements](#Requirements)
* [Usage](#Usage)
* [Preparation](#Preparation)
* [Config file](#Config file)
* [Flow Chart](#Flow Chart)
* [Evolution](#Evolution)
* [Standalone evaluation of molecules](#Standalone evaluation of molecules)
* [Stretching for molecules build from building blocks](#Stretching for molecules build from building blocks)
* [Stretching for arbitrary isolated molecules](#Stretching for arbitrary isolated molecules)
Requirements
------------
* tmoutproc library from [here](https://github.com/blaschma/tmoutproc). Tested with version 0.1
* Queuing system slurm or GE
* Python 3.x
* [Turbomole](https://www.turbomole.org/). Version >7.5
# Usage
## Preparation
* Create directory where the evulution runs
* Generate directory "generation_data" in it
* Create config file (see next part)
* Run evolution: python3 PATH_TO_CODE/genetic/run_evolution.py <config_path> <calculation_path>
## Config file
(With exemplary values. Adjust that to your calculations)
````
[Basics]
genetic_algorithm_path=PATH TO GENETIC ALGORITHM
turbopath=PATH TO TURBOMOLE
helper_files=PATH TO HELPER FILES
intel_path=PATH TO INTEL Routines
archive_archive_path=PATH TO ARCHIVE OF MOLECULES
calculation_path=PATH TO CURRENT CALCULATION
queuing=(SLURM or GE)
[Genetic Algorithm]
population_size=24
generation_limit=20
evaluation_methods_path=default
genome_length=7
insert_mutation_prob=0.5
coupling_mutation_prob=0.5
block_mutation_prob=0.5
truncate_mutation_prob=0.5
n_tournament_selection=2
[Building Procedure]
CC_bond_lengt=1.58
conjugation_angle=0.45
building_block_path=
generation_data_path=generation_data
ang2Bohr=1.889725989
har2Ev=27.211
[Turbomole Calculations]
partition=epyc,alcc1
cpus_per_task=8
displacement_per_step=0.1
num_stretching_steps_pos=30
num_stretching_steps_neg=30
mem_per_cpu=15G
max_time=05:30:00
kill_time=5700
relax_level=xtb
relax_iterations=730
prerelax= #T or false
define_input=build_calc
````
## Flow Chart
Overview of program sequence:

The programm will create a folder structure similar to this:

## Evolution
Evolution loop implemented in the algorithm:

## Standalone evaluation of molecules
### Stretching for molecules build from building blocks
You can bypass the evolution and evaluate molecules directly build from building blocks by running directly
genome_to_molecule.py.
### Stretching for arbitrary isolated molecules
You can bypass the evolution and evaluate arbitrary molecules by running directly set_up_turbo_calculations.sh.
Generate folder structure as shown in the structure above. Place coord, coord.xyz, complexity and limits file, prepare
config file and rund set_up_turbo_calculations.sh.
***
<NAME> [<EMAIL>](<EMAIL>)<file_sep>#!/bin/bash
origin_path=$(pwd)
echo "action_before_death"
dispdir=$1
config_file=$2
echo $config_file
source $config_file
cd $dispdir
#set kill notification
touch ../KILL_SIGNAL_SET
cd $dispdir
#notify the world when calc completed
parent=$(basename ${PWD%})
touch ../DISP_POS_DONE
touch ../DISP_NEG_DONE
#generation_individual
filename=$(basename ${PWD%/*/*})_$(basename ${PWD%/*})
file=../DISP_POS_DONE
if test -f "$file"; then
file=../DISP_NEG_DONE
if test -f "$file"; then
#copy error files
parentdir="$(dirname "$dispdir")"
cp -a $helper_files/error_files/. $parentdir
touch ../../${filename}_DONE
fi
fi
#check if calculations of all individuals are ready
num_finished=$(ls ../../ -1f | grep _DONE | wc -l)
if [ "$num_finished" -eq "$population_size" ]; then
echo "Everybody seems to be ready"
#eval fitness
python3 $genetic_algorithm_path/src/helper_files/eval_fitness.py $calculation_path"/generation_data/"$(basename ${PWD%/*/*}) $config_file
#invoke next generation
python3 $genetic_algorithm_path/src/genetic/invoke_next_generation.py $config_file $calculation_path
fi
cd $origin_path<file_sep>from typing import List, Callable, Tuple
import copy
Genome = List[int]
Population = List[Genome]
FitnessFunc = Callable[[Genome, int, int], float]
PopulateFunc = Callable[[], Population]
SelectionFunc = Callable[[Population, FitnessFunc],Tuple[Genome, Genome]]
CrossoverFunc = Callable[[Genome,Genome], Tuple[Genome, Genome]]
MutationFunc = Callable[[Genome], Genome]
#"""
def run_evolution(
populate_func: PopulateFunc,
fitness_func: FitnessFunc,
fitness_limit: int,
selection_func : SelectionFunc,
crossover_func : CrossoverFunc,
mutation_func: MutationFunc,
generation_limit: int = 100
) -> Tuple[Population, int]:
#list of fitness_values
fitness_value = list()
#initialize first population
population = populate_func()
#geration loop
for i in range(generation_limit):
print("generation " + str(i))
#evaluate pupulation
population = sorted(
population,
key = lambda genome: fitness_func(genome)
)
fitness_value.append(fitness_func(population[0]))
#check if fittness_limit is exceeded
"""
if fitness_func(population[0]) >= fitness_limit:
break
"""
#take best individuals of generation and..
next_generation = population[0:2]
#...fill generation with mutated and cross over children
for j in range(int(len(population)/2)-1):
#select parent according to selection function
parents = selection_func(population, fitness_func)
#combine features of parents to generate offspring
offspring_a, offspring_b = crossover_func(parents[0], parents[1])
#mutate offspring
offspring_a = mutation_func(offspring_a)
offspring_b = mutation_func(offspring_b)
#add offspring to generation
next_generation += [offspring_a, offspring_b]
population = next_generation
#sort final population
population = sorted(
population,
key = lambda genome: fitness_func(genome)
)
return population, i,fitness_value
def run_generation(
populate_func: PopulateFunc,
fitness_func: FitnessFunc,
selection_func : SelectionFunc,
crossover_func : CrossoverFunc,
mutation_func: MutationFunc,
population : Population,
fitness_limit: int,
generation_limit: int,
population_size:int,
generation: int,
fitness_value
) :
#list of fitness_values
#initialize first population
if(generation == 0):
population = populate_func()
print("populated population " +str(population))
#invoke fitness evaluation
population_for_fitness_eval = copy.deepcopy(population)
for i in range(0, population_size):
fitness_func(population_for_fitness_eval[i],generation,i)
print("population after fitness_func " +str(population))
return population, ""
#sort population
zipped_lists = zip(fitness_value, population)
sorted_pairs = sorted(zipped_lists, reverse=True)
tuples = zip(*sorted_pairs)
fitness_value, population = [ list(tuple) for tuple in tuples]
#check if fittness_limit is exceeded
"""
if fitness_func(population[0]) >= fitness_limit:
break
"""
#family register
family_register=""
#take best individuals of generation and..
next_generation = population[0:2]
family_register += str(population[0]) + "\n"
family_register += str(population[1]) + "\n"
#...fill generation with mutated and cross over children
for j in range(int(len(population)/2)-1):
#select parent according to selection function
parents = selection_func(population, fitness_value)#->todo too inefficent
#combine features of parents to generate offspring
print("parents[0] " + str(parents[0]) + " parents[1] " + str(parents[1]))
offspring_a, offspring_b = crossover_func(parents[0], parents[1])
offspring_a_save = str(offspring_a)
offspring_b_save = str(offspring_b)
#mutate offspring
print("offspring_a " + str(offspring_a))
print("offspring_b " + str(offspring_b))
offspring_a = mutation_func(offspring_a)
offspring_b = mutation_func(offspring_b)
#handle family register
offspring_a_mutation=""
if(str(offspring_a)!=offspring_a_save):
offspring_a_mutation=str(offspring_a)
offspring_b_mutation=""
if(str(offspring_b)!=offspring_b_save):
offspring_b_mutation=str(offspring_b)
family_register+=offspring_a_save + " parents " + str(parents[0]) + "&" + str(parents[1]) + " mutation " + str(offspring_a_mutation) + "\n"
family_register+=offspring_b_save + " parents " + str(parents[0]) + "&" + str(parents[1]) + " mutation " + str(offspring_b_mutation) + "\n"
#add offspring to generation
next_generation += [offspring_a, offspring_b]
population = next_generation
#reduce overlap by symmetry (no difference in 7-1 and 7-0 or small anchor)
for i in range(len(population)):
for j in range(len(population[i])-1):
if(population[i][j] == 7):
population[i][j+1] = 0
population[i][0] = 0
#find unique individuals
individuals = list()
for i in range(len(population)):
if((population[i] in individuals)==False):
individuals.append(population[i])
unique_individuals = len(individuals)
print("individuals " + str(individuals))
#fill rest of generation randomly
missing_individuals = population_size-unique_individuals
individuals_to_add = populate_func()[0:missing_individuals]
print("unique_individuals " + str(unique_individuals))
family_register += "unique_individuals " + str(unique_individuals) + "\n"
print(len(individuals_to_add))
population = individuals
population+=individuals_to_add
#invoke evaluation of new population
population_for_fitness_eval = copy.deepcopy(population)
for i in range(0, population_size):
fitness_func(population_for_fitness_eval[i],generation,i)
return population, family_register
<file_sep>import configparser
import os
import os.path
from os import path
import sys
import sys
import genetic_algorithm as ga
from functools import partial
def run_generation(generation : int, config_path, calculation_path):
"""
Runs evolution. Inits calculation dirs and invokes evaluation of first generation
Args:
param1 (int) : number of generation
param2 (String) : Path to config file
param3 (String) : Path to calculation
Returns:
error codes (int)
"""
#load specification from config file
cfg = configparser.ConfigParser()
cfg.read(config_path)
population_size = int(cfg.get('Genetic Algorithm', 'population_size'))
generation_limit = int(cfg.get('Genetic Algorithm', 'generation_limit'))
genome_length = int(cfg.get('Genetic Algorithm', 'genome_length'))
evaluation_methods_path = cfg.get('Genetic Algorithm', 'evaluation_methods_path')
genetic_algorithm_path = cfg.get('Basics', 'genetic_algorithm_path')
#check if default setting for evaluation methods
if(evaluation_methods_path == "default"):
#make sure problem_specification path is found
sys.path.append(os.path.realpath(genetic_algorithm_path + "/src/"))
sys.path.append(os.path.realpath('..'))
from problem_specification import bbEV
ev = bbEV.bbEv(generation, 0, config_path, calculation_path) #-> todo individual processing
pass
#load specific evaluation methods
elif(evaluation_methods_path == "tournament"):
#make sure problem_specification path is found
sys.path.append(os.path.realpath(genetic_algorithm_path + "/src/"))
sys.path.append(os.path.realpath('..'))
from problem_specification import bbEV_tournament
ev = bbEV_tournament.bbEv_tournament(generation, 0, config_path, calculation_path) #-> todo individual processing
pass
#load specific evaluation methods
elif(evaluation_methods_path == "tournament_f_symmetry"):
#make sure problem_specification path is found
sys.path.append(os.path.realpath(genetic_algorithm_path + "/src/"))
sys.path.append(os.path.realpath('..'))
from problem_specification import bbEV_tournament_f_symmetry
ev = bbEV_tournament_f_symmetry.bbEv_tournament_f_symmetry(generation, 0, config_path, calculation_path) #-> todo individual processing
pass
#first generation
if(generation == 0):
population, family_register = ga.run_generation(
populate_func=partial(
ev.generate_population, size=population_size, genome_length=genome_length
),
fitness_func=ev.fitness,
selection_func=ev.selection_pair,
crossover_func=ev.crossover,
mutation_func=ev.mutation,
population=0,
fitness_limit=5,
generation_limit=generation_limit,
population_size=population_size,
generation=generation,
fitness_value=0)
print("Generation zero " + str(generation))
#every other generation
else:
#generation-1 because prevois generation should be read
population, fitness_value = read_population(generation-1,config_path, calculation_path)
print(fitness_value)
population, family_register = ga.run_generation(
populate_func=partial(
ev.generate_population, size=population_size, genome_length=genome_length
),
fitness_func=ev.fitness,
selection_func=ev.selection_pair,
crossover_func=ev.crossover,
mutation_func=ev.mutation,
population=population,
fitness_limit=5,
generation_limit=generation_limit,
population_size=population_size,
generation=generation,
fitness_value=fitness_value)
#print(population)
#print(fitness_value)
print("after run " + str(population))
write_generation(population,generation, config_path, calculation_path)
write_genomes_to_archive(population, generation, calculation_path, config_path)
write_family_register(family_register, generation, calculation_path)
def write_genomes_to_archive(population, generation, calculation_path, config_path):
"""
Writes genomes to archive. First of all it is checked if genome is already in archige
Args:
param1 (Polulation): population
param2 (int): generation
param3 (String): path to population
param4 (String): path to config file
Returns:
"""
#find existing archive
cfg = configparser.ConfigParser()
cfg.read(config_path)
archive_path = cfg.get('Basics', 'archive_archive_path')
print(archive_path)
if(os.path.exists(archive_path)==False):
print("create file")
f = open(archive_path, "w")
f.close()
#read existing archinve
archive_file = open(archive_path, "r")
archive_population = list()
archive_paths = list()
for line in archive_file:
if(len(line)<3):
continue
line = line.strip().split(" ")
tmp = line[0].replace("[", "").replace("]", "")
tmp = tmp.split(",")
tmp = [int(tmp[i]) for i in range(0,len(tmp))]
archive_population.append(tmp)
archive_paths.append(line[1])
archive_file.close()
#check which file to add and add the file
archive_file = open(archive_path, "a")
for i in range(len(population)):
print(population[i])
print(archive_population)
if (population[i] in archive_population) == False:
#print("adding to archive " + str(population[i]))
path_of_individual = calculation_path + "/generation_data/"+ str(generation) + "/" + str(i)
archive_file.write(str(population[i]) + " " + path_of_individual + "\n")
archive_file.close()
def write_generation(population, generation, config_path, calculation_path):
"""
write current generation to calculation_path/current_generation.dat and to generation_data/generation/generation_summary.dat.
First file contains only information about the population. The second file contains the fittness value, too. In addition a file
calculation_path/generation.dat which contains the current number of generations
Args:
param1 (Population): population to write
param2 (int): Generation
param3 (String): Path to config file
param4 (String): Path to calculation
Returns:
"""
try:
first_file_path = calculation_path + "/curr_population.dat"
second_file_path = calculation_path + "/generation_data/" + str(generation)
first_file = open(first_file_path, "w")
generation_file = open(calculation_path + "/generation.dat", "w")
if(path.exists(second_file_path) == False):
os.mkdir(second_file_path)
second_file = open(second_file_path + "/summary.dat", "w")
except OSError as e:
print("log file cannot be opened " + str(e))
return 1
for i in range(0, len(population)):
first_file.write(str(population[i]).replace('[', "").replace("]", "")+ "\n")
#second_file.write(str(fitness_value[i]) + " " + str(population[i]).replace('[', "").replace("]", "")+ "\n")
second_file.write(str(population[i]).replace('[', "").replace("]", "")+ "\n")
generation_file.write(str(generation))
generation_file.close()
first_file.close()
second_file.close()
def read_population(generation, config_path, calculation_path):
"""
read current generation individuals and their fitness from calculation path
Args:
param1 (int): number of generation which should be read
param2 (String): Path to config file
param3 (String): Path to calculation
Returns:
(population, fitness_values)
"""
try:
filename_population = calculation_path + "/curr_population.dat"
file_population = open(filename_population)
filename_fitness = calculation_path + "/generation_data/" + str(generation) + "/fitness.dat"
file_fitness = open(filename_fitness)
except OSError as e:
print("Cannot open file " + str(e))
return -1,-1
#read population
population = list()
for line in file_population:
#print(line)
tmp = line.strip().split(", ")
tmp = [int(tmp[i]) for i in range(0,len(tmp))]
population.append(tmp)
#read fitness values
fitness_value = list()
for line in file_fitness:
#print(line)
try:
tmp = float(line)
except ValueError as e:
print("Faulty fitness file " + str(e))
return -1,-1
fitness_value.append(tmp)
return population, fitness_value
def write_family_register(family_register, generation, calculation_path):
"""
Invokes the next generation. The number of generation is read from calculation_path/generation.dat
Args:
param1 (String): family_register (created during evolution)
param2 (int): generation
param3 (String): Path to calculation
Returns:
"""
#find number of unique individuals and write to file if possible
n_unique = -1
try:
index = family_register.find("individuals")
print("individuals")
print(family_register[index+len("individuals"): len(family_register)-1])
n_unique = int(family_register[index+len("individuals"): len(family_register)-1])
except ValueError as e:
print("Can not find or cast number of unique_individuals " + str(e))
if(n_unique != -1):
unique_individuals_path = calculation_path + "/generation_data/" + str(generation) + "/" + str(generation) + "_n_unique.dat"
try:
unique_individuals_file = open(unique_individuals_path, "w")
unique_individuals_file.write(str(n_unique))
unique_individuals_file.close()
except OSError as e:
print("Cannot open file " + str(e))
family_register_path = calculation_path + "/generation_data/" + str(generation) + "/" + str(generation) + "_family_register.dat"
try:
family_register_file = open(family_register_path, "w")
family_register_file.write(family_register)
family_register_file.close()
except OSError as e:
print("Cannot open file " + str(e))
def next_generation(config_path, calculation_path):
"""
Invokes the next generation. The number of generation is read from calculation_path/generation.dat
Args:
param1 (String): Path to config file
param2 (String): Path to calculation
Returns:
"""
try:
filename = calculation_path + "/generation.dat"
file = open(filename)
for line in file:
generation = int(line)
except (OSError,ValueError) as e:
print("generation file cannot be found or generation file is faulty " + str(e))
#check if generation limit is reached
cfg = configparser.ConfigParser()
cfg.read(config_path)
generation_limit = int(cfg.get('Genetic Algorithm', 'generation_limit'))
if(generation>=generation_limit):
print("Generation limit reached")
return 0
#check if generation was correctly processed
file_to_check = calculation_path + "/generation_data/" + str(generation) + "/fitness.dat"
if(os.path.exists(file_to_check) == False):
print("Generation " + str(generation) + " was not processed correctly")
return -1
#increase number of genrations
generation += 1
run_generation(generation, config_path, calculation_path)
if __name__ == '__main__':
main
<file_sep>import configparser
import os
import os.path
import sys
from os import path
import run_generation as rg
def run_evolution(config_path, calculation_path):
"""
Runs evolution. Inits calculation dirs and invokes evaluation of first generation
Args:
param1 (String) : Path to config file
param2 (String) : Path to calculation
Returns:
error codes (int)
"""
#check config file
if(path.exists(config_path) == False):
print("Faulty config file")
return -1
generation_data_path = calculation_path + "/" "generation_data"
#create calculation files
try:
#create generation dir
if(path.exists(generation_data_path) == False):
os.mkdir(calculation_path)
generation_zero_path = generation_data_path + "/0"
os.mkdir(generation_zero_path)
except OSError:
print ("Creation of the directory %s failed" % generation_data_path)
return -1
rg.run_generation(0, config_path, calculation_path)
if __name__ == '__main__':
config_path = sys.argv[1]
calculation_path = sys.argv[2]
run_evolution(config_path, calculation_path)
<file_sep>#collects specified .xyz files from stretching trace
path=$1 #path to dir where disp_pos and disp_neg is located
output_xyz=$2 #file where .xyz trajectory is stored
xyz_name=$3 #names of xyz_file to collect
start_dir=$(pwd)
cd $path
path=$(pwd)
touch $path/$output_xyz
#process disp_neg
cd disp_neg
old_dir=$(pwd)
#store subdirs in array
dirs=( $( ls -1p | grep / | sed 's/^\(.*\)/\1/') )
for ((i=${#dirs[@]}-1; i>=0; i--));
do
cd ${dirs[$i]}
echo $(pwd)
t2x coord > tmp_coord.xyz
cat $xyz_name >> $path/$output_xyz
cd $old_dir
done
cd ..
#process disp_pos
cd disp_pos
old_dir=$(pwd)
#store subdirs in array
dirs=( $( ls -1p | grep / | sed 's/^\(.*\)/\1/') )
arraylength=${#dirs[@]}
for (( i=1; i<${arraylength}; i++ )); # list directories in the form "/tmp/dirname/"
do
cd ${dirs[$i]}
echo $(pwd)
t2x coord > tmp_coord.xyz
cat $xyz_name >> $path/$output_xyz
cd $old_dir
done
cd $start_dir
<file_sep>#this script collects the total energy and saves it to file
# $1 directory to process
# $2 filename
# $3 config file
config_file=$3 # path to config file
source $config_file
# set Intel environment
INTEL=$intel_path
. $INTEL/bin/compilervars.sh intel64
exec 3<> ../$2_totalEnergy.dat
#collects total energy in given directory ($1)
start_dir=$(pwd)
#go to start dir
cd $1
#process disp_pos
echo "processing disp_pos"
#cd $start_dir/$1
cd "disp_pos"
old_dir=$(pwd)
for dir in ./*/ # list directories in the form "/tmp/dirname/"
do
dir=${dir%*/} # remove the trailing "/"
echo ${dir##*/} # print everything after the final "/"
cd $dir
converged=GEO_OPT_CONVERGED
if test -f "$converged"; then
#echo "Geo Opt converged"
FILE=ridft.out
if test -f "$FILE"; then
#echo "$FILE exists."
#find total energy in ridft.out
line=$(grep -o "total energy =.*" ridft.out)
#echo $line
totalEnergy=${line//$"total energy ="}
#echo $totalEnergy
totalEnergy=${totalEnergy//$"|"}
#echo $totalEnergy
#echo $dir
displacement=${dir//$"./"}
echo "$displacement $totalEnergy" >&3
fi
else
echo "Geo Opt not converged"
fi
cd $old_dir
done
echo "processing disp_neg"
#go back to startdir
cd $1
#cd $start_dir/$1
cd "disp_neg"
old_dir=$(pwd)
for dir in ./*/ # list directories in the form "/tmp/dirname/"
do
dir=${dir%*/} # remove the trailing "/"
echo ${dir##*/} # print everything after the final "/"
cd $dir
converged=GEO_OPT_CONVERGED
if test -f "$converged"; then
#echo "Geo Opt converged"
FILE=ridft.out
if test -f "$FILE"; then
#echo "$FILE exists."
#find total energy in ridft.out
line=$(grep -o "total energy =.*" ridft.out)
#echo $line
totalEnergy=${line//$"total energy ="}
#echo $totalEnergy
totalEnergy=${totalEnergy//$"|"}
#echo $totalEnergy
#echo $dir
displacement=${dir//$"./"}
echo "-$displacement $totalEnergy" >&3
fi
else
echo "Geo Opt not converged"
fi
cd $old_dir
done
cd ..
cd $start_dir
num_atoms=$(wc -l < $1/coord)
#now all the evaluation is done
python3 $helper_files/eval_stiffness.py $1/$2 $num_atoms
<file_sep>import os
import numpy as np
import tmoutproc as top
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import matplotlib.pyplot as plt
from more_itertools import sort_together
from scipy.optimize import curve_fit
import sys
__har2eV__ = 27.2114
__eV2J__ = 1.60218e-19
__bohr2Ang__ = 0.529177
F_breaking = 1.5E-9
def calculate_s_s_dist(path, filename, write_out=False):
"""
Calculates distance of Sulfur atoms (fixed) in Angstroms for stretching procedure and stores it under {gen}_{ind}_s_s_dist.dat
path: where disp_pos and disp_neg is located
filename: prefix for output file
"""
s_s_dist = list()
dirs = list()
rootdir = f'{path}/disp_neg'
subdirs = [x[0] for x in os.walk(rootdir) if "transport" not in x[0]]
subdirs = sorted(subdirs)[1:len(subdirs)]
subdirs = subdirs[::-1]
for j in range(0,len(subdirs)-1):
dirs.append(subdirs[j])
coord = top.read_coord_file(subdirs[j] + "/coord")
lower = -1
upper = -1
for i in range(0,len(coord)):
#if(len(coord[i]) == 5 and coord[i][4] == 'f'):
if (len(coord[i]) == 4 and coord[i][3] == 's'):
if(lower==-1):
lower = float(coord[i][2])
else:
upper = float(coord[i][2])
s_s_dist.append(np.abs(upper-lower)/1.889725989)
break
len_disp_neg = len(subdirs)
assert len(s_s_dist)==len_disp_neg-1, "Not all anchors found"
rootdir = f'{path}/disp_pos'
subdirs = [x[0] for x in os.walk(rootdir) if "transport" not in x[0]]
subdirs = sorted(subdirs)[1:len(subdirs)]
found = list()
for j in range(0,len(subdirs)):
dirs.append(subdirs[j])
coord = top.read_coord_file(subdirs[j] + "/coord")
lower = -1
upper = -1
for i in range(0,len(coord)):
#if(len(coord[i]) == 5 and coord[i][4] == 'f'):
if (len(coord[i]) == 4 and coord[i][3] == 's'):
if(lower==-1):
lower = float(coord[i][2])
else:
upper = float(coord[i][2])
s_s_dist.append(np.abs(upper-lower)/1.889725989)
found.append(subdirs[j])
break
assert len(s_s_dist) == len_disp_neg + len(subdirs) - 1, "Not all anchors found"
if(write_out == True):
top.write_plot_data(f"{path}/{filename}_s_s_dist.dat", (s_s_dist, s_s_dist), "dirs, s-s distance (ang)")
return np.array(s_s_dist)
def calc_junction_extent(path, filename, write_out=False):
"""
Calculates maximum extent of junction in z direction
Args:
path: path to calculation (where disp_pos and disp_neg is located)
filename: prefix for output file
write_out: Write_out of displacement data
Returns:
"""
s_s_dist = list()
dirs = list()
rootdir = f'{path}/disp_neg'
subdirs = [x[0] for x in os.walk(rootdir) if "transport" not in x[0]]
subdirs = sorted(subdirs)[1:len(subdirs)]
subdirs = subdirs[::-1]
for j in range(0,len(subdirs)-1):
dirs.append(subdirs[j])
coord = top.read_coord_file(subdirs[j] + "/coord")
z_coord = list()
for i in range(0,coord.shape[1]):
if(coord[3,i] != 'h'):
z_coord.append(coord[2,i])
s_s_dist.append(np.abs(np.max(z_coord) - np.min(z_coord))*__bohr2Ang__)
rootdir = f'{path}/disp_pos'
subdirs = [x[0] for x in os.walk(rootdir) if "transport" not in x[0]]
subdirs = sorted(subdirs)[1:len(subdirs)]
for j in range(0,len(subdirs)):
dirs.append(subdirs[j])
coord = top.read_coord_file(subdirs[j] + "/coord")
z_coord = list()
for i in range(0,coord.shape[1]):
if(coord[3,i] != 'h'):
z_coord.append(coord[2,i])
s_s_dist.append(np.abs(np.max(z_coord) - np.min(z_coord))*__bohr2Ang__)
if(write_out == True):
top.write_plot_data(f"{path}/{filename}_junction_extent.dat", (s_s_dist, s_s_dist), "dirs, s-s distance (ang)")
return np.array(s_s_dist)
def breaking_ana(path, filename):
"""
Calculates the force generated by the molecule. Therefore, the maximum extend of the junction is normalized to get the Displacement data. The total energy is taken from a prepared file (containing total energy from dft calculation)
Args:
path: path to calculation (where disp_pos and disp_neg is located)
filename: Prefix for filename
Returns:
"""
#load energy and sort according to stretching step
energy_data = top.read_plot_data(f"{path}/{filename}_totalEnergy.dat")
stretching_step, energy = sort_together([energy_data[0, :], energy_data[1, :]])
stretching_step = np.asarray(stretching_step, int)
energy = np.asarray(energy, float)
#remove doulbe entry for 0:
#check if there are two entries for zero
tmp = sorted(np.abs(stretching_step))
if(tmp[0] == 0 and tmp[1] == 0):
stretching_step = list(stretching_step)
energy = list(energy)
zero_index_to_remove = np.argmin(np.abs(stretching_step))
energy.pop(zero_index_to_remove)
stretching_step.pop(zero_index_to_remove)
stretching_step = np.asarray(stretching_step)
energy = np.asarray(energy)
#load s_s dist
#s_s_dist = calculate_s_s_dist(path, gen, ind)
s_s_dist = calc_junction_extent(path, filename, write_out=True)
#find energy_minimum, shift energy and convert to
min_energy_index = np.argmin(energy)
min_disp_index = np.argmin(np.abs(stretching_step))
energy = energy - energy[min_energy_index]
energy = energy*__har2eV__*__eV2J__
#normalize s_s_dist and convert to si
s_s_dist = s_s_dist * 1E-10
shift = s_s_dist[min_energy_index]
s_s_dist = s_s_dist - shift
#fit to harmonic approx
def harmonic_approximation(x, k):
return 0.5 * k * x ** 2
try:
popt_symmetric, pcov_symmetric = curve_fit(harmonic_approximation, s_s_dist, energy)
popt_asymmetric, pcov_asymmetric = curve_fit(harmonic_approximation, s_s_dist[min_energy_index:], energy[min_energy_index:])
except RuntimeError:
print("Fit to wrong model")
energy_fitted_symmetric = harmonic_approximation(s_s_dist, popt_symmetric)
energy_fitted_asymmetric = harmonic_approximation(s_s_dist[min_energy_index:], popt_asymmetric)
breaking_dist_symmetric = F_breaking / (popt_symmetric)
breaking_dist_asymmetric = F_breaking / (popt_asymmetric)
print(f"Breaking dist sym = {breaking_dist_symmetric-s_s_dist[min_disp_index]}")
print(f"Force constant sym (N/m) = {popt_symmetric}")
print(f"Breaking dist asym = {breaking_dist_asymmetric-s_s_dist[min_disp_index]}")
print(f"Force constant sym (N/m) = {popt_asymmetric}")
with open(f"{path}/{filename}_breaking_ana.dat", 'w') as f:
f.write(f"Breaking dist sym = {breaking_dist_symmetric}\n")
f.write(f"Force constant sym (N/m) = {popt_symmetric}\n")
f.write(f"Breaking dist asym = {breaking_dist_asymmetric}\n")
f.write(f"Force constant asym (N/m) = {popt_asymmetric}\n")
numerical_force = np.gradient(energy, np.mean(np.diff(s_s_dist)))
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot((s_s_dist-s_s_dist[min_disp_index])*1E10, energy, label="data", color="g", lw=0.1, marker="x")
ax1.plot((s_s_dist-s_s_dist[min_disp_index])*1E10, energy_fitted_symmetric, label="fit (sym)", color="g", ls="--")
ax1.plot((s_s_dist[min_energy_index:] - s_s_dist[min_disp_index]) * 1E10, energy_fitted_asymmetric, label="fit (asym)", color="orange", ls="--")
ax1.set_xlabel(r"Displacement ($\AA$)", fontsize=15)
ax1.set_ylabel("Energy (J)", fontsize=15)
ax1.tick_params(axis="x", labelsize=12)
ax1.tick_params(axis="y", labelsize=12)
ax1.grid()
ax2.plot((s_s_dist-s_s_dist[min_disp_index])*1E10, numerical_force*1E9, label="data", color="g")
ax2.plot((s_s_dist-s_s_dist[min_disp_index])*1E10, popt_symmetric * s_s_dist * 1E9, label="fit (sym)", color="g", ls="--")
ax2.plot((s_s_dist[min_energy_index:] - s_s_dist[min_disp_index]) * 1E10, popt_asymmetric * s_s_dist[min_energy_index:] * 1E9, label="fit (asym)", color="orange",
ls="--")
ax2.axhline(F_breaking*1E9, color="black", ls="--", label=r"$\mathrm{F_{max}^{Au-S}}$")
ax2.legend(fontsize = 12)
ax2.grid()
ax2.set_xlabel(r"Displacement ($\AA$)", fontsize=15)
ax2.set_ylabel("Force (nN)", fontsize=15)
ax2.tick_params(axis="x", labelsize=12)
ax2.tick_params(axis="y", labelsize=12)
plt.tight_layout()
plt.savefig(f"{path}/{filename}_breaking_ana.pdf", bbox_inches='tight')
plt.savefig(f"{path}/{filename}_breaking_ana.svg", bbox_inches='tight')
#plt.show()
if __name__ == '__main__':
path = sys.argv[1]
filename = sys.argv[2]
breaking_ana(path, filename)<file_sep>import tmoutproc as top
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import matplotlib.pyplot as plt
import numpy as np
import sys
from scipy.optimize import curve_fit
def load_and_plot(molecule_name,n_atoms):
"""
loads total energy file and plots it vs displacement. fit is also done and written to STIFFNESS file
param1 (String) : molecule_name
param2 (int) : n_atoms for normalization
Returns:
"""
#num atoms is 3 smaller beacuse keywords are counted, too
n_atoms = n_atoms -3
#load data
try:
data = top.read_plot_data(molecule_name + "_totalEnergy.dat")
except ValueError as e:
print(e)
file = open(molecule_name + "_stiffness.dat", "w")
error_value_fit = -100
error_value_std = 1000
file.write("a b c std(a) std(b) std(c) -> a(x-b)**2+c (first line:normalized, second line: not normalized)" + "\n")
file.write(str(error_value_fit) + " " + str(error_value_fit) + " " + str(error_value_fit) + " " + str(error_value_std) + " " + str(error_value_std) + " " + str(error_value_std) + "\n")
file.write(str(error_value_fit) + " " + str(error_value_fit) + " " + str(error_value_fit) + " " + str(error_value_std) + " " + str(error_value_std) + " " + str(error_value_std))
file.close()
else:
zipped_lists = zip(data[0], data[1])
sorted_pairs = sorted(zipped_lists)
tuples = zip(*sorted_pairs)
disp, energy = [ list(tuple) for tuple in tuples]
disp = np.asarray(disp, dtype = float)
energy = np.asarray(energy, dtype = float)
#plotting and fitting
interesting_energy_minimum = np.min(energy)
energy = energy-interesting_energy_minimum
disp = disp*0.1
energy_normalized = energy * (1./float(n_atoms)+0.0)
def func(x, a,b,c):
return a * (x-b)**2 +c
try:
popt_normalized, pcov_normalized = curve_fit(func, disp, energy_normalized)
popt, pcov = curve_fit(func, disp, energy)
except RuntimeError:
print("Fit to wrong model")
fit = [-100,-100,-100]
std = [1000,1000,1000]
file = open(molecule_name + "_stiffness.dat", "w")
file.write("a b c std(a) std(b) std(c) -> a(x-b)**2+c (first line:normalized, second line: not normalized)" + "\n")
file.write(str(fit[0]) + " " + str(fit[1]) + " " + str(fit[2]) + " " + str(std[0]) + " " + str(std[1]) + " " + str(std[2]) + "\n")
file.write(str(fit[0]) + " " + str(fit[1]) + " " + str(fit[2]) + " " + str(std[0]) + " " + str(std[1]) + " " + str(std[2]))
file.close()
else:
fit_normalized = popt_normalized
fit = popt
fitted_data_normalized = fit_normalized[0] * (disp-fit_normalized[1])**2+fit_normalized[2]
std_normalized = np.sqrt(np.diag(pcov_normalized))
std=np.sqrt(np.diag(pcov))
print("a=" + str(fit_normalized[0]))
#write fit data to file
file = open(molecule_name + "_stiffness.dat", "w")
file.write("a b c std(a) std(b) std(c) -> a(x-b)**2+c (first line:normalized, second line: not normalized)" + "\n")
file.write(str(fit_normalized[0]) + " " + str(fit_normalized[1]) + " " + str(fit_normalized[2]) + " " + str(std_normalized[0]) + " " + str(std_normalized[1]) + " " + str(std_normalized[2]) + "\n")
file.write(str(fit[0]) + " " + str(fit[1]) + " " + str(fit[2]) + " " + str(std[0]) + " " + str(std[1]) + " " + str(std[2]))
file.close()
plt.plot(disp, energy_normalized)
plt.plot(disp, fitted_data_normalized, '--')
plt.title("a=" + str(fit_normalized[0]) + " std=" + str(std_normalized))
plt.ylabel('($(E-E_0)/N$) [H]',fontsize=20)
plt.xlabel('Displacement [$\mathrm{\AA}$]',fontsize=20)
plt.savefig(molecule_name + "_totalEnergy.pdf", bbox_inches='tight')
plt.savefig(molecule_name + "_totalEnergy.svg", bbox_inches='tight')
if __name__ == '__main__':
#sys.argv[1]: path/moleculename
#sys.argv[2]: n_atoms +3 -> because of counting of keywords
load_and_plot(sys.argv[1],int(sys.argv[2]))
<file_sep>import numpy as np
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import matplotlib.pyplot as plt
import tmoutproc as top
import os.path
from multiprocessing import Pool
from functools import partial
import sys
import configparser
from scipy.optimize import curve_fit
def eval_T(disp_index, para):
"""
evaluates zeroth order Greens function to estimate the Transmission in wide band limit. Function is used in multiprocessing
Args:
param1 (int): disp_index. Specifies which index in dir list should be processed
param2 (tuple): param2[0] list of directories, param2[1] minimal displacement, param2[2] n_occupied
Returns:
(float:estimate for t, int: processed displacement index)
"""
directories = para[0]
min_displacement=para[1]
n_occupied = para[2]
directory = directories[disp_index+min_displacement]
print("directory " + str(directory))
try:
eigenvalues, eigenvectors = top.read_mos_file(directory + "/mos")
except ValueError as e:
print("error " + str(e))
return 0.0, float(disp_index)
coord = top.read_coord_file(directory + "/coord")
s_range = top.find_c_range_atom("s", 1, coord)
r_range = top.find_c_range_atom("s", 2, coord)
e_f = (eigenvalues[n_occupied-1]+eigenvalues[n_occupied])/2.
eigenvectors = np.asmatrix(eigenvectors)
denominator_list = list()
numerator_list = list()
G0_sr = 0
delta = 1E-12
for i in range(0,len(eigenvalues)):
numerator = (eigenvectors[r_range[0]:r_range[1],i])*np.transpose(eigenvectors[s_range[0]:s_range[1],i])
denominator = e_f - eigenvalues[i] + 1.0j* delta
denominator_list.append(denominator)
numerator_list.append(numerator)
tmp = numerator/denominator
G0_sr += tmp
T_est = np.real(np.trace(G0_sr*np.conj(np.transpose(G0_sr))))
return T_est, float(disp_index)
def plot_T_vs_d(calc_path, molecule_name, n_occupied, config_path):
"""
evaluates zeroth order Greens function to estimate the Transmission in wide band limit. T estimate is plotted vs displacement.
Args:
param1 (String): Path to turbomole calculation
param2 (String): molecule name generation_individual
param3 (int): occupied mos -> define fermi energy
param4 (String): Path to config file
Returns:
"""
print("config path " + str(config_path))
#process disp_neg
list_neg = os.listdir(calc_path + "/disp_neg/")
list_neg = sorted(list_neg, reverse=True)
list_neg = [calc_path + "/disp_neg/" + s for s in list_neg if (os.path.isdir(calc_path + "/disp_neg/" + s)) and (s != '0000')]
list_neg = [s for s in list_neg if os.path.exists(s+"/GEO_OPT_CONVERGED")]
#process disp_pos
list_pos = os.listdir(calc_path + "/disp_pos/")
list_pos = sorted(list_pos)
list_pos = [calc_path + "/disp_pos/" + s for s in list_pos if os.path.isdir(calc_path + "/disp_pos/" + s)]
list_pos = [s for s in list_pos if os.path.exists(s+"/GEO_OPT_CONVERGED")]
#all folder which will be processed
folders = list(list_neg)
folders.extend(list_pos)
disp_indices = np.linspace(-len(list_neg), len(list_pos),len(list_pos)+len(list_neg), False, dtype=int)
p = Pool(16)
min_disp = len(list_neg)
eingabe = (folders, min_disp, n_occupied)
cfg = configparser.ConfigParser()
cfg.read(config_path)
displacement = float(cfg.get('Turbomole Calculations', 'displacement_per_step'))
#multiprocessing
result = p.map(partial(eval_T, para=eingabe), disp_indices)
T_est, disp = [], []
for x, y in result:
T_est.append(x)
disp.append(float(y)*displacement)
#fit data
minimum = np.argmin(T_est)
min_disp = disp[minimum]
min_T_est = T_est[minimum]
max_T_est = 1
def func(x, a):
return (max_T_est-np.exp(-a*np.abs(x-min_disp)+np.log(max_T_est-min_T_est)))
try:
popt, pcov = curve_fit(func, disp, T_est)
print(pcov)
print(disp)
print("minimum " + str(disp[minimum]))
if(minimum==len(disp)-1 or minimum==0):
print("min T_value at at the edge")
print(disp)
popt[0] = 0
except RuntimeError:
print("Fit to wrong model")
fitted_data = func(np.asarray(disp), popt[0])
plt.plot(disp, T_est)
plt.xlabel('Displacement [$\mathrm{\AA}$]',fontsize=20)
plt.ylabel('$\mathrm{T}_{\mathrm{estimate}}$',fontsize=20)
plt.savefig(calc_path + "/" + molecule_name + "_T_estimate.pdf", bbox_inches='tight')
plt.savefig(calc_path + "/" + molecule_name + "_T_estimate.svg", bbox_inches='tight')
plt.yscale("log")
plt.savefig(calc_path + "/" + molecule_name + "_T_estimate_log.pdf", bbox_inches='tight')
plt.savefig(calc_path + "/" + molecule_name + "_T_estimate_log.svg", bbox_inches='tight')
top.write_plot_data(calc_path + "/" + molecule_name + "_T_estimate.dat",(disp,T_est), "disp, T_est")
plt.plot(disp, fitted_data)
plt.savefig(calc_path + "/" + molecule_name + "_T_estimate_log_fit.pdf", bbox_inches='tight')
plt.savefig(calc_path + "/" + molecule_name + "_T_estimate_log_fit.svg", bbox_inches='tight')
file = open(calc_path + "/" + molecule_name + "_T_estimate_params.dat", "w")
file.write(str(float(popt[0])))
file.write("\n")
file.write(str(float(pcov[0])))
file.write("\n")
file.write(str(min_T_est))
file.write("\n")
file.write(str(min_disp))
file.close()
def plot_energy_levels(calc_path, molecule_name, n_occupied, config_path):
"""
Plots energy levels homo-4 ... Lumo+4 vs displacement
Args:
param1 (String): Path to turbomole calculation
param2 (String): molecule name generation_individual
param3 (int): occupied mos -> define fermi energy
param4 (String): Path to config file
Returns:
"""
print("plot energy levels")
number_occupied = n_occupied
#process disp_neg
list_neg = os.listdir(calc_path + "/disp_neg/")
list_neg = sorted(list_neg, reverse=True)
list_neg = [calc_path + "/disp_neg/" + s for s in list_neg if (os.path.isdir(calc_path + "/disp_neg/" + s)) and (s != '0000')]
list_neg = [s for s in list_neg if os.path.exists(s+"/GEO_OPT_CONVERGED")]
#process disp_pos
list_pos = os.listdir(calc_path + "/disp_pos/")
list_pos = sorted(list_pos)
list_pos = [calc_path + "/disp_pos/" + s for s in list_pos if os.path.isdir(calc_path + "/disp_pos/" + s)]
list_pos = [s for s in list_pos if os.path.exists(s+"/GEO_OPT_CONVERGED")]
#process disp_pos]
reference_dir = list_pos[0]
folders = list(list_neg)
folders.extend(list_pos)
displacement = list()
disp_indices = np.linspace(-len(list_neg), len(list_pos),len(list_pos)+len(list_neg), False, dtype=int)
homo_list = list()
homo_list_m1 = list()
homo_list_m2 = list()
homo_list_m3 = list()
homo_list_m4 = list()
lumo_list = list()
lumo_list_p1 = list()
lumo_list_p2 = list()
lumo_list_p3 = list()
lumo_list_p4 = list()
e_fermi_list = list()
cfg = configparser.ConfigParser()
cfg.read(config_path)
har2Ev = float(cfg.get('Building Procedure', 'har2Ev'))
disp_per_step = float(cfg.get('Turbomole Calculations', 'displacement_per_step'))
for i in range(0, len(folders)):
directory = folders[i]
print(directory)
eigenvalues, eigenvectors = top.read_mos_file(directory + "/mos")
homo_list_m1.append(float(eigenvalues[number_occupied-1-1])*har2Ev)
homo_list_m2.append(float(eigenvalues[number_occupied-1-2])*har2Ev)
homo_list_m3.append(float(eigenvalues[number_occupied-1-3])*har2Ev)
homo_list_m4.append(float(eigenvalues[number_occupied-1-4])*har2Ev)
homo_list.append(float(eigenvalues[number_occupied-1])*har2Ev)
lumo_list_p1.append(float(eigenvalues[number_occupied+1])*har2Ev)
lumo_list_p2.append(float(eigenvalues[number_occupied+2])*har2Ev)
lumo_list_p3.append(float(eigenvalues[number_occupied+3])*har2Ev)
lumo_list_p4.append(float(eigenvalues[number_occupied+4])*har2Ev)
lumo_list.append(float(eigenvalues[number_occupied])*har2Ev)
e_fermi_list.append((float(eigenvalues[number_occupied-1])+float(eigenvalues[number_occupied]))*har2Ev/2.0)
displacement.append(float(disp_indices[i])*disp_per_step)
fig, ax = plt.subplots(1)
ax.plot(displacement, lumo_list_p4, label="$E_{lumo+4}$")
ax.plot(displacement, lumo_list_p3, label="$E_{lumo+3}$")
ax.plot(displacement, lumo_list_p2, label="$E_{lumo+2}$")
ax.plot(displacement, lumo_list_p1, label="$E_{lumo+1}$")
ax.plot(displacement, lumo_list, label="$E_{lumo}$", color="blue")
ax.plot(displacement, e_fermi_list, label="$E_{f}$", color="black", linestyle='dashed')
ax.plot(displacement, homo_list, label="$E_{homo}$", color="green")
ax.plot(displacement, homo_list_m1, label="$E_{homo-1}$")
ax.plot(displacement, homo_list_m2, label="$E_{homo-2}$")
ax.plot(displacement, homo_list_m3, label="$E_{homo-3}$")
ax.plot(displacement, homo_list_m4, label="$E_{homo-4}$")
print(displacement)
print(homo_list_m4)
ax.set_xlabel('Displacement ($\mathrm{\AA}$)',fontsize=20)
ax.set_ylabel('Energy (eV)',fontsize=20)
#ax.set_yscale('log')
ax.legend(loc=2)
plt.savefig(calc_path + "/" + molecule_name + "_energy_levels.pdf", bbox_inches='tight')
plt.savefig(calc_path + "/" + molecule_name + "_energy_levels.svg", bbox_inches='tight')
top.write_plot_data(calc_path + "/" + molecule_name + "_energy_levels.dat", (np.round(displacement,2), homo_list_m4, homo_list_m3,homo_list_m2,homo_list_m1,homo_list, lumo_list,lumo_list_p1,lumo_list_p2,lumo_list_p3,lumo_list_p4), "displacement, homo-4 (eV) , ... , lumo +4")
if __name__ == '__main__':
#argv[1] : calc path: where disp_pos and disp_neg is located
#argv[2] : moleculename (prefix of plot files)
#argv[3] : occupied orbitals (e_f = (E_homo+E_lumo)/2)
#argv[4] : config_path
plot_T_vs_d(sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4])
plot_energy_levels(sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4])<file_sep>import numpy as np
from random import choices, randint, randrange, random
from typing import List, Callable, Tuple
from collections import namedtuple
import tmoutproc as top
import configparser
import os
import os.path
from os import path
import subprocess
import shutil
Genome = List[int]
Point = namedtuple("Point", ['x','y', 'z'])
Angle = float
Building_Block = namedtuple('Building_Block', ['abbrev', 'num_atoms','origin', 'para_pos','para_angle', 'meta_pos','meta_angle', 'ortho_pos','ortho_angle','fixed_left','complexity', 'path'])
Coupling = namedtuple('Coupling', ['abbrev'])
def process_block_to_add(coupling_point: Point, coupling_angle : Angle, conjugation_angle : Angle, cc_bond_length:float, block_to_add: Building_Block):
"""
Adds block_to_add to left_block. Method takes care of right alignment, shifting and rotation of block_to_add.
Args:
param1 (Point): coupling point
param2 (Angle): coupling angle
param3 (Angle): conjugation angle
param4 (float): c-c bond length (Angstrom)
param5 (Building_Block): block to be added
Returns:
np.ndarray: ([atom/x/y/z, line])
"""
#load data for block_to_add
coord_xyz = top.read_xyz_file(block_to_add.path)
coord_xyz_save = np.copy(coord_xyz)
#rotate around z axis for conjugation, rotate around y for right orientation,shift to coupling point and shift by c-c bond length in right direction
for i in range(0,coord_xyz.shape[1]):
#conjugation x' = cos(phi)*x-sin(phi)*y
coord_xyz[1,i] = coord_xyz_save[1,i]*np.cos(conjugation_angle)-np.sin(conjugation_angle)*coord_xyz_save[2,i]
#conjugation y' = sin(phi)*x+cos(phi)*y
coord_xyz[2,i] = coord_xyz_save[1,i]*np.sin(conjugation_angle)+np.cos(conjugation_angle)*coord_xyz_save[2,i]
coord_xyz_save = np.copy(coord_xyz)
#rotation around y: x' = cos(phi)*x+sin(phi)*z
coord_xyz[1,i] = coord_xyz_save[1,i]*np.cos(coupling_angle)+np.sin(coupling_angle)*coord_xyz_save[3,i]
#rotation around y: z' = cos(phi)*z-sin(phi)*x
coord_xyz[3,i] = -coord_xyz_save[1,i]*np.sin(coupling_angle)+np.cos(coupling_angle)*coord_xyz_save[3,i]
#shift to coupling point x -> x+x_c
coord_xyz[1,i] = coord_xyz[1,i]+coupling_point.x
#shift to coupling point y -> y+y_c
coord_xyz[2,i] = coord_xyz[2,i]+coupling_point.y
#shift to coupling point z -> z+z_c
coord_xyz[3,i] = coord_xyz[3,i]+coupling_point.z
#shift by C-C bond length in e_c direction sin=-0.866 cos=-0.499
coord_xyz[1,i] = coord_xyz[1,i]+cc_bond_length*np.sin(coupling_angle)
#shift by C-C bond length in e_c direction
coord_xyz[3,i] = coord_xyz[3,i]+cc_bond_length*np.cos(coupling_angle)
return coord_xyz
def construction_loop(genome : Genome, building_blocks, config_path, xyz_file_path):
"""
Construction loop Genome -> proper xyz file
Args:
param1 (Genome): Genome to build
Returns:
"""
def determine_coupling_index(genome: Genome, index:int, building_blocks=building_blocks):
"""
determines coupling index (atom and corresponding line in xyz file of building block refered in genome[index]) and coupling angle
Args:
param1 (Genome): Genome to build
param2 (int): index which block is processed and used as coupling point. Must be even -> odd indices are couplings
Returns:
(int,float): corresponding line in xyz file of building block refered in genome[index], coupling angle
"""
if(index > len(genome)-2 or index < 0):
raise ValueError("index is out of proper range")
# coupling after building_block of interest
i = index + 1
#para
if(genome[i]==0):
coupling_index = building_blocks[genome[index]].para_pos
coupling_angle = building_blocks[genome[index]].para_angle
#meta
elif(genome[i]==1):
coupling_index = building_blocks[genome[index]].meta_pos
coupling_angle = building_blocks[genome[index]].meta_angle
#ortho
elif(genome[i]==2):
coupling_index = building_blocks[genome[index]].ortho_pos
coupling_angle = building_blocks[genome[index]].ortho_angle
else:
raise ValueError("coupling seems to be funny")
return coupling_index, coupling_angle
def write_file_parts_to_file(xyz_file_parts, path, fixed_beginning, fixed_end,complexity, config_path):
"""
write xyz file parts to proper xyz file and turbomole coord file. Complexity is written to file
Args:
param1 (List of np.ndarray): List of xyz files
param2 (String): path
param3 (int): fixed_beginning (index of atom in first block which should be fixed)
param4 (int): fixed_end (index of atom in last block which should be fixed)
param5 (int): complexity of whole molecule
param6 (String): path to config file
Returns:
"""
#load ang to bohr factor
cfg = configparser.ConfigParser()
cfg.read(config_path, encoding='utf-8')
#write complexity to file
with open(path+"/complexity", "w") as file_complexity:
file_complexity.write(str(complexity))
file_complexity.close()
concat_xyz = np.concatenate(xyz_file_parts, axis=1)
top.write_xyz_file(path+"/coord.xyz", concat_xyz)
coord = top.x2t(concat_xyz)
#fix right atoms
coord[4,fixed_beginning] = "f"
fixed_end = sum(np.array([xyz_file_parts[i].shape[1] for i in range(0,len(xyz_file_parts)-1)]))+fixed_end
coord[4, fixed_end] = "f"
top.write_coord_file(path+"/coord", coord)
lower_limit = np.min(concat_xyz[3,:]) + 0.1
upper_limit = np.max(concat_xyz[3, :]) - 0.1
with open(path+"/limits", "w") as limits:
limits.write(str(lower_limit) + "\n")
limits.write(str(upper_limit))
def determine_nearest_neighbor(datContent, coupling_index, atom_type):
"""
determines nearest neighbor of atom with index coupling index in dat content of atom type atom_type
Args:
param1 (List of np.ndarray): List of xyz files
param2 (int): coupling_inxex
param3 (string): atom_type of nearest neighbour
Returns:
int : index of nearest neighbour
"""
intersting_atoms = list()
intersting_atoms_distance = list()
for i in range(0, len(datContent[1,:])):
if(datContent[0,i]==atom_type):
intersting_atoms.append(i)
distance = (float(datContent[1,i])-float(datContent[1,coupling_index]))**2+(float(datContent[2,i])-float(datContent[2,coupling_index]))**2+(float(datContent[3,i])-float(datContent[3,coupling_index]))**2
intersting_atoms_distance.append(distance)
intersting_atoms = [x for _,x in sorted(zip(intersting_atoms_distance,intersting_atoms))]
return intersting_atoms[0]
def align_z_along_fixed_ends(xyz_file_parts, fixed_beginning, fixed_end):
"""
Align molecule z axis along fixed ends. This is done by rotation about the axis given by curl(vec(fixed_beginning->fixed_end), e_z) by the angle between vec(fixed_beginning-fixed_end) and e_z
Args:
param1 (List of np.ndarray): List of xyz files
param2 (int): index in xyz_file_parts[0] of fixed beginning
param3 (int): index in xyz_file_parts[-1] of fixed end
Returns:
int : (List of np.ndarray): List of xyz file
"""
molecule_axis = [xyz_file_parts[-1][1,fixed_end],xyz_file_parts[-1][2,fixed_end],xyz_file_parts[-1][3,fixed_end]]
angle = np.arccos(molecule_axis[2]/np.linalg.norm(molecule_axis))
theta = angle
if(angle != 0):
#calculate rotation axis
rotation_axis = np.cross(molecule_axis, [0.0,0.0,1.0])
rotation_axis = 1.0/np.linalg.norm(rotation_axis)*rotation_axis
u = rotation_axis
#calculate rotation_matrix
rotation_matrix = [[np.cos(theta) + u[0]**2 * (1-np.cos(theta)), u[0] * u[1] * (1-np.cos(theta)) - u[2] * np.sin(theta), u[0] * u[2] * (1 - np.cos(theta)) + u[1] * np.sin(theta)],
[u[0] * u[1] * (1-np.cos(theta)) + u[2] * np.sin(theta), np.cos(theta) + u[1]**2 * (1-np.cos(theta)), u[1] * u[2] * (1 - np.cos(theta)) - u[0] * np.sin(theta)],
[u[0] * u[2] * (1-np.cos(theta)) - u[1] * np.sin(theta), u[1] * u[2] * (1-np.cos(theta)) + u[0] * np.sin(theta), np.cos(theta) + u[2]**2 * (1-np.cos(theta))]]
for j in range(0, len(xyz_file_parts)):
for i in range(0, len(xyz_file_parts[j][1,:])):
vector_to_rotate = [round(float(xyz_file_parts[j][1,i]),5),round(float(xyz_file_parts[j][2,i]),5),round(float(xyz_file_parts[j][3,i]),5)]
rotated_vector = np.asmatrix(rotation_matrix)*np.asmatrix(vector_to_rotate).T
xyz_file_parts[j][1,i] = round(rotated_vector[0,0],5)
xyz_file_parts[j][2,i] = round(rotated_vector[1,0],5)
xyz_file_parts[j][3,i] = round(rotated_vector[2,0],5)
return xyz_file_parts
else:
return xyz_file_parts
#load properties from config file
cfg = configparser.ConfigParser()
cfg.read(config_path, encoding='utf-8')
cc_bond_length = float(cfg.get('Building Procedure', 'CC_bond_lengt'))
conjugation_angle_from_file = float(cfg.get('Building Procedure', 'conjugation_angle'))
building_block_path = cfg.get('Building Procedure', 'building_block_path')
#ensure that genome is not empty
if(len(genome) < 1):
print("Genome was emtpy")
# TODO: proper treatment
#add anchor to end -> couplings are missing
#add left anchor
anchor_left, anchor_right = load_anchors_blocks(building_block_path)
building_blocks.append(anchor_left)
#para coupling
genome.insert(0, len(building_blocks)-1)
#add right anchor
building_blocks.append(anchor_right)
#para coupling
genome.append(len(building_blocks)-1)
#data content of every part of xyz file is stored in this list
xyz_file_parts = list()
#first block as initialization directly added to list
coupling_point = Point(x=0.0, y=0.0, z=0.0)
coupling_angle = 0.0
coupling_index = -1
conjugation_angle = 0
additional_angle = 0.0
#indices for fixed atoms in beginning and end of chain
fixed_beginning = 0
fixed_end = 0
#complexity measure of molecule
complexity = 0
for i in range(0, len(genome)):
complexity += building_blocks[genome[i]].complexity
#odd index -> coupling
if(i%2==1):
#conclude coupling point
x_c = float(xyz_file_parts[-1][1,coupling_index])
y_c = float(xyz_file_parts[-1][2,coupling_index])
z_c = float(xyz_file_parts[-1][3,coupling_index])
coupling_point = Point(x=x_c, y=y_c, z=z_c)
#even index -> building block
elif(i%2 == 0):
#handle rotation to process consecutive para or ortho couplings
additional_angle += (-1)**(i/2+1)*np.pi
additional_angle = 0
#first block must not be shifted
if(i == 0):
datContent = process_block_to_add(coupling_point, coupling_angle, conjugation_angle+additional_angle, 0.0, building_blocks[genome[i]])
fixed_beginning = building_blocks[genome[i]].fixed_left
if(building_blocks[genome[i]].fixed_left == -1):
print("Error in first block: fixed atom not properly specified")
else:
datContent = process_block_to_add(coupling_point, coupling_angle, conjugation_angle+additional_angle, cc_bond_length, building_blocks[genome[i]])
#find fix index of last block
if(i == len(genome)-1):
#para_pos is assumed to be right coupling point
fixed_end = building_blocks[genome[i]].para_pos
if(building_blocks[genome[i]].para_pos == -1):
print("Error in last block: fixed atom not properly specified")
#determine index of atom at origin
origin = building_blocks[genome[i]].origin
#if other block will be added -> hydrogen at c coupling atom must be removed
if(i != len(genome)-1):
#determine coupling index and coupling angle
coupling_index, coupling_angle_single = determine_coupling_index(genome,i,building_blocks)
#handle sign to process consecutive para or ortho couplings
#coupling_angle += (coupling_angle_single*(-1)**(i/2+1))
coupling_angle += (coupling_angle_single)
#remove hydrogen or other atom bonded to coupling atom
nearest_neighbour = determine_nearest_neighbor(datContent, coupling_index, "H")
datContent = np.delete(datContent,nearest_neighbour,1)
#update coupling index and fixed beginning
if(coupling_index>nearest_neighbour):
coupling_index -= 1
if(i == 0 and fixed_beginning>nearest_neighbour):
fixed_beginning -=1
#update origin
if(origin>nearest_neighbour):
origin -=1
#hydrogen bonded to C atom at origin must be removed, too (except for first atom)
if(i != 0):
#remove hydrogen or other atom bonded to atom at origin
nearest_neighbour = determine_nearest_neighbor(datContent, origin, "H")
datContent = np.delete(datContent,nearest_neighbour,1)
#update coupling index and fixed ending
if(coupling_index>nearest_neighbour):
coupling_index = coupling_index -1
if(i == len(genome)-1 and fixed_end>nearest_neighbour):
fixed_end -=1
pass
xyz_file_parts.append(datContent)
#alternating conjugation
#conjugation_angle += (-1)**(i/2+1)*conjugation_angle_from_file
conjugation_angle -= conjugation_angle_from_file
#align molecule axis to z
xyz_file_parts= align_z_along_fixed_ends(xyz_file_parts, fixed_beginning, fixed_end)
#write xyz_file_parts to xyz file
write_file_parts_to_file(xyz_file_parts, xyz_file_path, fixed_beginning, fixed_end, complexity, config_path)
def load_building_blocks(path):
"""
load building blocks and set up Building_Block objects
Args:
param1 (path): path to dir where building_blocks are located
Returns:
list(Building_Block)
"""
#TODO : automatization
benzene = Building_Block(abbrev="B", num_atoms=6,origin=0, para_pos=3, para_angle=0, meta_pos=4 , meta_angle = -np.pi/3., ortho_pos=5, ortho_angle=-2.*np.pi/3, fixed_left = -1,complexity=1, path=path+"/benzene.xyz")
napthtalene = Building_Block(abbrev="N", num_atoms=18,origin=0, para_pos=12, para_angle=0., meta_pos=11 , meta_angle = -np.pi/3., ortho_pos=10, ortho_angle=-2.*np.pi/3, fixed_left = -1,complexity=1, path=path+"/naphtalene.xyz")
dbPc1 = Building_Block(abbrev="dbPc1", num_atoms=32,origin=13, para_pos=1, para_angle=0, meta_pos=0 , meta_angle = +np.pi/3., ortho_pos=0, ortho_angle=-2.*np.pi/3, fixed_left = -1,complexity=1, path=path+"/dbPc1_block.xyz")
dbPc4 = Building_Block(abbrev="dbPc4", num_atoms=55,origin=22, para_pos=1, para_angle=0, meta_pos=0 , meta_angle = -np.pi/3., ortho_pos=0, ortho_angle=-2.*np.pi/3, fixed_left = -1,complexity=1, path=path+"/dbPc4.xyz")
dbPc6 = Building_Block(abbrev="dbPc6", num_atoms=52,origin=17, para_pos=0, para_angle=0, meta_pos=1 , meta_angle = -np.pi/3., ortho_pos=0, ortho_angle=-2.*np.pi/3, fixed_left = -1,complexity=1, path=path+"/dbPc6.xyz")
dbPc5 = Building_Block(abbrev="dbPc5", num_atoms=58,origin=12, para_pos=26, para_angle=0, meta_pos=20 , meta_angle = -np.pi/3., ortho_pos=0, ortho_angle=-2.*np.pi/3, fixed_left = -1,complexity=1, path=path+"/dbPc5.xyz")
pseudo_para_naph_PCP = Building_Block(abbrev="pseudo-para_naph_PCP", num_atoms=44,origin=0, para_pos=18, para_angle=0, meta_pos=16 , meta_angle = -np.pi/3, ortho_pos=0, ortho_angle=-2.*np.pi/3, fixed_left = -1,complexity=1, path=path+"/pseudo-para_naph_PCP.xyz")
line =Building_Block(abbrev="line", num_atoms=4,origin=0, para_pos=1, para_angle=0, meta_pos=1 , meta_angle = 0., ortho_pos=0, ortho_angle=-2.*np.pi/3, fixed_left = -1,complexity=1, path=path+"/line.xyz")
#rot=Building_Block(abbrev="line", num_atoms=47,origin=6, para_pos=16, para_angle=0, meta_pos=20 , meta_angle = 0., ortho_pos=0, ortho_angle=-2.*np.pi/3, fixed_left = -1,complexity=2, path=path+"/rot.xyz")
#stacked_anth=Building_Block(abbrev="stacked_anth", num_atoms=62,origin=3, para_pos=22, para_angle=0, meta_pos=30 , meta_angle = 0., ortho_pos=0, ortho_angle=-2.*np.pi/3, fixed_left = -1,complexity=2, path=path+"/stacked_anth.xyz")
building_blocks = [benzene,napthtalene,dbPc1,dbPc4,dbPc6, dbPc5,pseudo_para_naph_PCP, line]
return building_blocks
def load_anchors_blocks(path):
"""
load anchor blocks and set up Building_Block objects.
Args:
param1 (path): path to dir where anchors are located
Returns:
list(Building_Block)
"""
#TODO : automatization
left = Building_Block(abbrev="l", num_atoms=2,origin=0, para_pos=0, para_angle=0, meta_pos=0 , meta_angle = 0., ortho_pos=0, ortho_angle=-2.*np.pi/3, fixed_left = 0,complexity=1, path=path+"/anchor_small_left.xyz")
right = Building_Block(abbrev="r", num_atoms=2,origin=0, para_pos=0, para_angle=0., meta_pos=0 , meta_angle = 0., ortho_pos=0, ortho_angle=-2.*np.pi/3, fixed_left = -1,complexity=1, path=path+"/anchor_small_right.xyz")
anchors = [left,right]
return anchors
def process_genome(generation : int, individual: int, genome:Genome, run_path):
"""
translates genome to xyz file. xyz file will be stored in $data/generation/individual and stretching and other calculations will be invoked. If geome has been processed in a previous generation, the data will be copied from the archive
Args:
param1 (int): generation
param2 (int): individual in generation
param3 (Genome): genome to process
param4 (String): path of current run
Returns:
int : success (0), failure (-1)
"""
#set up config path
config_path = run_path + "/config"
#check where building blocks are stored and generation data should be stored
cfg = configparser.ConfigParser()
cfg.read(config_path, encoding='utf-8')
#TODO: set up correctly
building_block_path = cfg.get('Building Procedure', 'building_block_path')
generation_data_path = run_path + "/" + cfg.get('Building Procedure', 'generation_data_path')
#create generation directory
calc_path = generation_data_path + "/" + str(generation)
try:
#create generation dir
if(path.exists(calc_path) == False):
os.mkdir(calc_path)
except OSError:
print ("Creation of the directory %s failed" % calc_path)
return -1
#check if genome has been processed alreaddy
cfg = configparser.ConfigParser()
cfg.read(config_path, encoding='utf-8')
archive_path = cfg.get('Basics', 'archive_archive_path')
print(archive_path)
if(os.path.exists(archive_path)==False):
print("No archive found")
else:
#read existing archinve
archive_file = open(archive_path, "r")
archive_population = list()
archive_paths = list()
for line in archive_file:
if(len(line)<3):
continue
line = line.strip().split(" ")
tmp = line[0].replace("[", "").replace("]", "")
tmp = tmp.split(",")
tmp = [int(tmp[i]) for i in range(0,len(tmp))]
archive_population.append(tmp)
archive_paths.append(line[1])
archive_file.close()
#genome was procesed
if (genome in archive_population)==True:
print("copying existing genome")
index = archive_population.index(genome)
scr_dir = archive_paths[index] + "/."
print("scr_dir " + str(scr_dir))
dst_dir = generation_data_path + "/" + str(generation)+ "/" +str(individual) + "/"
print("dst_dir " + str(dst_dir))
if(path.exists(dst_dir) == True):
print("Other job running ... Aborting")
raise ValueError('Other job running ... Aborting')
os.system("mkdir " + str(dst_dir))
dst_dir += "."
os.system("cp -R " + scr_dir + " " + dst_dir)
#create DONE file
DONE_file = generation_data_path + "/" + str(generation)+ "/" + str(generation)+ "_" +str(individual) + "_DONE"
os.system("touch " + DONE_file)
return 0
#genome has not been calculated -> init calcs
#create directories for calculations
calc_path = generation_data_path + "/" + str(generation)
try:
#create generation dir
if(path.exists(calc_path) == False):
os.mkdir(calc_path)
#create individual dir
calc_path = generation_data_path + "/" + str(generation)+ "/" + str(individual)
os.mkdir(calc_path)
except OSError:
print ("Creation of the directory %s failed" % calc_path)
return -1
#load building blocks
building_blocks = load_building_blocks(building_block_path)
#construct molecule from genome
construction_loop(genome, building_blocks, config_path, calc_path)
#run next step -> invoke turbomole calculations
set_up_turbo_calculations_path = cfg.get('Basics', 'helper_files') + "/set_up_turbo_calculations.sh"
os.system(set_up_turbo_calculations_path+" "+calc_path+" "+config_path + " " + str(generation) + " " + str(individual))
if __name__ == '__main__':
process_genome(0,2,[0,1,0,2,1,4,0,5,0],"C:/Users/<NAME>/OneDrive - Universität Augsburg/Code/genetic_algorithm/test")
<file_sep>#this script sets up the turbomole calculations.
# $1: path to dir where turbo calc should be initialized. Must be prepared with coord and limits -> genome_to_molecule.py
# $2: path to config file
# $3: generation
# $4: individual
origin=$(pwd)
#load config file
config_file=$2
source $config_file
#set path
path=$1
#set cpus per task
cpus_per_task=$(head -n 1 $path/complexity)
echo $cpus_per_task
# set Intel environment
module load intel
module load openmpi
module load mkl
#set turbo path
source $turbopath
cd $path
#make dirs
mkdir disp_pos
cd disp_pos
#cp $helper_files/run_disp.sh ./
cp $helper_files/jobgen.py ./jobgen.py
cp $helper_files/run_disp.sh ./run_disp.sh
mkdir 0000
cd 0000
cp ../../coord ./
cp ../../limits ./
define < $helper_files/$define_input > define.out
cd ..
if [[ "$queuing" == "SLURM" ]]; then
echo "Using Slurm"
sbatch --job-name=gen$3id$4p --mem-per-cpu=$mem_per_cpu --partition=$partition --time=$max_time --ntasks=1 --cpus-per-task=$cpus_per_task --signal=B:SIGUSR1@$kill_time run_disp.sh 0 $num_stretching_steps_pos $displacement_per_step $config_file
elif [[ "$queuing" == "GE" ]]; then
echo "Using Grid engine (GE)"
qsub -N gen$3id$4p -cwd -q scc -pe openmp $cpus_per_task -l h_vmem=$mem_per_cpu run_disp.sh 0 $num_stretching_steps_pos $displacement_per_step $config_file
else
echo "Unknwon queuing system"
return -1
fi
cd ..
mkdir disp_neg
cd disp_neg
#cp $helper_files/run_disp.sh ./
cp $helper_files/jobgen.py ./jobgen.py
cp $helper_files/run_disp.sh ./run_disp.sh
mkdir 0000
cd 0000
cp ../../coord ./
cp ../../limits ./
define < $helper_files/build_calc > define.out
cd ..
if [[ "$queuing" == "SLURM" ]]; then
echo "Using Slurm"
sbatch --job-name=gen$3id$4n --mem-per-cpu=$mem_per_cpu --partition=$partition --time=$max_time --ntasks=1 --cpus-per-task=$cpus_per_task --signal=B:SIGUSR1@$kill_time run_disp.sh 0 $num_stretching_steps_neg -$displacement_per_step $config_file
elif [[ "$queuing" == "GE" ]]; then
echo "Using Grid engine (GE)"
qsub -N gen$3id$4n -cwd -q scc -pe openmp $cpus_per_task -l h_vmem=$mem_per_cpu run_disp.sh 0 $num_stretching_steps_neg -$displacement_per_step $config_file
else
echo "Unknwon queuing system"
return -1
fi
cd ..
cd $origin
<file_sep>import os
import fnmatch
import os.path
from os import path
import numpy as np
import sys
import tmoutproc as top
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import matplotlib.pyplot as plt
def load_transmission_data(gen_dir):
"""
Loads transmission data of all individuals in given dir.
Args:
param1 (String): dir to process
Returns:
list(np.ndarray) [individual][0=disp, 1=T_est, stretching step]
"""
dirs = os.listdir(gen_dir)
dirs = [int(i) for i in dirs if os.path.isdir(gen_dir + "/" + i)]
dirs = sorted(dirs)
dirs = [str(i) for i in dirs]
T_estimates = list()
T_estimates_params_list = list()
#read stiffness files and append stiffness and std to lists
for i in range(len(dirs)):
for file in os.listdir(gen_dir + "/" + dirs[i]):
if fnmatch.fnmatch(file, '*T_estimate.dat'):
transmission_file = file
if fnmatch.fnmatch(file, '*_T_estimate_params.dat'):
param_file = file
print("transmission file " + str(transmission_file))
transmission_file = gen_dir + "/" + dirs[i] + "/" + transmission_file
dat_Content = top.read_plot_data(transmission_file)
param_file = open(gen_dir + "/" + dirs[i] + "/" + param_file)
T_estimates_params = list()
for line in param_file:
T_estimates_params.append(float(line))
T_estimates.append(dat_Content)
T_estimates_params_list.append(T_estimates_params)
return T_estimates, T_estimates_params_list
def process_T_estimate_data(T_est, gen_path):
"""
Processes T estimate data. Plots of all T_estimates are saved
Args:
param1 (List): T estimates
param2 (String): path to generation data
Returns:
"""
fig, ax = plt.subplots(1)
NUM_COLORS = len(T_est)
cm = plt.get_cmap('nipy_spectral')
ax.set_prop_cycle('color', [cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS)])
with open(gen_path + "/T_est_data.dat", "w") as f:
for i in range(len(T_est)):
if(i != 6 and i!=7 and i!=8 or True):
ax.plot(T_est[i][0,:], (T_est[i][1,:]), label=str(i))
dx = 0.1
dy = np.diff(T_est[i][1,:])/dx
f.write(str(i)+"\n")
f.write("median " + str(np.median(T_est[i][1,:]))+"\n")
f.write("max derivate " + str(np.max(dy))+"\n")
f.write("median derivate " + str(np.median(dy))+"\n")
f.write("avg derivate " + str(np.average(dy))+"\n")
f.write("min derivate " + str(np.min(dy))+"\n")
f.write("max abs derivate " + str((np.max(np.abs(dy))))+"\n")
f.write("median abs derivate " + str(np.median(abs(dy)))+"\n")
f.write("min abs derivate " + str(np.min(abs(dy)))+"\n")
f.write(".-.-.-.-."+"\n")
ax.set_yscale('log')
ax.set_xlabel('Displacement ($\mathrm{\AA}$)',fontsize=20)
ax.set_ylabel('$\mathrm{T}_{\mathrm{estimate}}$',fontsize=20)
ax.legend(loc='lower left', ncol = 6, bbox_to_anchor=(0.,1.02,1.,.102), mode="expand", borderaxespad=0., fontsize=10)
plt.savefig(gen_path + "/T_estimates_summary.pdf", bbox_inches='tight')
def load_stiffness_data(gen_dir):
"""
Loads stiffness of all individuals in given dir.
Args:
param1 (String): dir to process
Returns:
list,list: (stiffness, std_stiffness)
"""
#load list of dirs and ensure it is a dir. Sort them
print("load fitness data ")
print(gen_dir)
dirs = os.listdir(gen_dir)
dirs = [int(i) for i in dirs if os.path.isdir(gen_dir + "/" + i)]
dirs = sorted(dirs)
print(dirs)
dirs = [str(i) for i in dirs]
stiffness = list()
std_stiffness = list()
#read stiffness files and append stiffness and std to lists
for i in range(len(dirs)):
try:
print("open " + str(dirs[i]))
for file in os.listdir(gen_dir + "/" + dirs[i]):
if fnmatch.fnmatch(file, '*_stiffness.dat'):
stiffness_file = file
stiffness_file = open(gen_dir + "/" + dirs[i] + "/" + stiffness_file)
except OSError as e:
print("stiffness file not found " + str(e))
#todo :proper treatment
stiffness.append(100)
std_stiffness.append(100)
continue
return -1
#skip first line
for line in stiffness_file:
stiffness_line = line
stiffness_file.close()
stiffness_line = stiffness_line.strip().split(" ")
stiffness.append(float(stiffness_line[0]))
std_stiffness.append(float(stiffness_line[3]))
return stiffness, std_stiffness
def eval_fittness(stiffness, std_stiffness, T_est, T_estimates_params):
"""
Evaluates stiffness values.
Args:
param1 (List): stiffness values (force constants)
param2 (List): std stiffness values
param3 (List): T_estimates
param4 (List(List)): T_estimates params [individual][0:fit_param, 1: std_fit_param, 2: T_est_min, 3: disp(T_est_min)]
Returns:
np.array: (fitness value)
"""
#evaluate stiffness part
counter = 0
for i in range(len(stiffness)):
#negative stiffness is not possible -> set values to low fittness
print(str(i) + " " + str(stiffness[i]))
if(stiffness[i]<0.0):
print("negative!")
stiffness[i] = 100.0
elif(np.abs(std_stiffness[i]/stiffness[i])>0.20):
print("std to big!")
stiffness[i] = 100.0
else:
#mean+=stiffness[i]
counter+=1.
stiffness = np.asarray(stiffness)
fittness_stiffness = 1/(stiffness+0.005)
#evaluate T_estimate part
min_min_T_est = 5.0
fit_param = list()
min_T_est = list()
median_penalty = list()
for i in range(len(T_estimates_params)):
if(np.isfinite(float(T_estimates_params[i][0]))==True and T_estimates_params[i][2] !=0):
if(np.abs(T_estimates_params[i][1]/(T_estimates_params[i][0]+1E-12)) > 1.0):
fit_param.append(0)
median_penalty.append(0)
else:
if(np.median(T_est[i][1])<1):
beta=1.2
gamma=2.0
nu=1.5
median_penalty.append(1/(1+np.exp(beta*(-np.log(np.median(T_est[i][1])))-gamma)))
fit_param.append((np.sqrt(T_estimates_params[i][0]))/(np.min(T_est[i][1]))*(((np.median(T_est[i][1])))/(np.min(T_est[i][1])))**nu)
else:
fit_param.append(T_estimates_params[i][0])
median_penalty.append(0)
min_T_est.append(T_estimates_params[i][2])
if(T_estimates_params[i][2] < min_min_T_est):
min_min_T_est = T_estimates_params[i][2]
else:
fit_param.append(0)
min_T_est.append(1)
median_penalty.append(0)
fittness_T_est = np.asarray(fit_param)
median_penalty = np.asarray(median_penalty)
print("fittness_T_est")
print(len(fittness_T_est))
print(fittness_T_est)
print("median_penalty")
print(len(median_penalty))
print(median_penalty)
if((len(fittness_stiffness) != len(fittness_T_est)) or (len(fittness_stiffness) != len(median_penalty))):
raise ValueError('Lengths of fitness measures do not match')
return fittness_stiffness,fittness_T_est,median_penalty
def write_fittness(fittness, path):
"""
Write fittness values to file
Args:
param1 (List): fittness
Returns:
"""
with open(path + "/fitness.dat", "w") as file:
for i in range(len(fittness[0])):
print(fittness[2])
file.write(str(fittness[0][i]*fittness[1][i]*fittness[2][i])+"\n")
file.close()
top.write_plot_data(path + "/fittness_contribution", fitness, "stiffness, T_est, median_penalty")
if __name__ == '__main__':
# sys.argv[1] path to process
# sys.argv[2] config path
#"""
#load all data
path=sys.argv[1]
stiffness, std_stiffness = load_stiffness_data(path)
T_est, T_estimates_params_list = load_transmission_data(path)
process_T_estimate_data(T_est, path)
#eval fitness
fitness = eval_fittness(stiffness, std_stiffness, T_est, T_estimates_params_list)
write_fittness(fitness,path)
with open(path + "/T_est_params", "w") as file:
for i in range(len(T_estimates_params_list)):
file.write(str(T_estimates_params_list[i][0]).replace(".", ",")+" "+str(T_estimates_params_list[i][1]).replace(".", ",")+" "+str(T_estimates_params_list[i][2]).replace(".", ",")+" "+str(T_estimates_params_list[i][3]).replace(".", ",") + "\n")
<file_sep>import configparser
from problem_specification.evaluation_methods import evaluation_methods
import numpy as np
from random import choices, randint, randrange, random
from collections import namedtuple
from typing import List, Callable, Tuple
from helper_files import genome_to_molecule as gtm
import copy
class bbEv_tournament_f_symmetry(evaluation_methods.Evaluation):
Genome = List[int]
Population = List[Genome]
FitnessFunc = Callable[[Genome, int, int], int]
PopulateFunc = Callable[[], Population]
SelectionFunc = Callable[[Population, FitnessFunc],Tuple[Genome, Genome]]
CrossoverFunc = Callable[[Genome,Genome], Tuple[Genome, Genome]]
MutationFunc = Callable[[Genome], Genome]
def __init__(self, generation, individual, config_path, calculation_path):
super().__init__(generation, individual)
self.Building_Block = namedtuple('Building_Block', ['abbrev', 'num_atoms', 'para_pos', 'meta_pos', 'ortho_pos', 'path'])
self.Coupling = namedtuple('Coupling', ['abbrev'])
self.generation = generation
self.individual = individual
self.calculation_path = calculation_path
#self.benzene = Building_Block(abbrev="B", num_atoms=6, para_pos=3, meta_pos=4 ,ortho_pos=5, path="./hamiltionians/benzene.txt")
#self.naphthalene = Building_Block(abbrev="N", num_atoms=10, para_pos=7, meta_pos=8 ,ortho_pos=9, path="./hamiltionians/naphthalene.txt")
#self.anthracen = Building_Block(abbrev="A", num_atoms=14, para_pos=11, meta_pos=12 ,ortho_pos=13, path="./hamiltionians/anthracen.txt")
#self.building_blocks = [benzene,naphthalene,anthracen]
#todo : dependency on interchangeable module not good
self.building_blocks=gtm.load_building_blocks("")
self.para = self.Coupling(abbrev="p")
self.meta = self.Coupling(abbrev="m")
#self.ortho = self.Coupling(abbrev="o")
self.couplings = [self.para, self.meta]
self.config_path = config_path
hamiltionians = 0
def force_symmetry(self, genome) -> Genome:
"""
Forces symmetry regarding the building blocks. First genome part (left to center) is assumed to be dominant -> building blocks are symmetrized to right part. Couplings are not changed
Args:
param1 () : maximum length of
Returns:
Genome
"""
genome_symmetrized = list()
n_couplings = len(genome)-int(len(genome)/2)
#symmetry on block in the middle
if(n_couplings%2 == 0):
blocks_to_keep = genome[:int(len(genome)/2)+1][1::2]
blocks_to_keep_ = blocks_to_keep[:len(blocks_to_keep)-1][::-1]
blocks_symmetrized = blocks_to_keep + blocks_to_keep_
for i in range(0,len(genome)):
if(i%2==0):
genome_symmetrized.append(genome[i])
else:
genome_symmetrized.append(blocks_symmetrized.pop(0))
#symmetry on coupling in the middle
else:
blocks_to_keep = genome[:int(len(genome)/2)][1::2]
blocks_to_keep_ = blocks_to_keep[:len(blocks_to_keep)][::-1]
blocks_symmetrized = blocks_to_keep + blocks_to_keep_
for i in range(0,len(genome)):
if(i%2==0):
genome_symmetrized.append(genome[i])
else:
genome_symmetrized.append(blocks_symmetrized.pop(0))
return genome_symmetrized
def generate_genome(self, max_length: int) -> Genome:
"""
Generates genome mit maximum lengt of max_lengt (-> size random). Genome is generated from available couplings and building blocks
Args:
param1 (int) : maximum length of
Returns:
Genome
"""
#coupling must contain at least one block and two couplings
#print("max_length " + str(max_length))
if(max_length <= 1):
print("sorry max_length too small")
return -1
num_building_blocks = randrange(1,max_length)
indices_building_blocks = np.linspace(0,len(self.building_blocks),len(self.building_blocks),endpoint=False,dtype=int)
indices_couplings = np.linspace(0,len(self.couplings),len(self.couplings),endpoint=False,dtype=int)
selected_building_blocks = choices(indices_building_blocks, k=num_building_blocks)
selected_couplings = choices(indices_couplings, k=num_building_blocks+2)
genome=list()
#add coupling to anchor
genome.append(selected_couplings[0])
for i in range(0, num_building_blocks):
genome.append(selected_building_blocks[i])
genome.append(selected_couplings[i+1])
#print("genome " + str(genome))
#reduce overlap by symmetry (no difference in 7-1 and 7-0 small anchors)
for i in range(len(genome)-1):
if(genome[i]==7):
genome[i+1] = 0
genome[0]=0
#force symmetry
genome = self.force_symmetry(genome)
return genome
def generate_population(self, size: int, genome_length: int) -> Population:
print("tournament")
return [self.generate_genome(genome_length) for _ in range(size)]
def fitness(self, genome: Genome, generation: int, individual: int) -> float:
genome_copy = copy.deepcopy(genome)
gtm.process_genome(generation,individual,genome_copy,self.calculation_path)
return random()
def selection_pair(self, population: Population, fitness_value) -> Population:
cfg = configparser.ConfigParser()
cfg.read(self.config_path)
k = int(cfg.get('Genetic Algorithm', 'n_tournament_selection'))
if(k<=2 or k >= len(population)):
print("No suitable choice. Setting to 2")
k = 2
zipped_lists = zip(fitness_value, population)
sorted_pairs = sorted(zipped_lists)
tuples = zip(*sorted_pairs)
fitness_value, population = [ list(tuple) for tuple in tuples]
population.reverse()
print("the chosen one " +str(population[0:k]))
return choices(
population=population[0:k],
k=2
)
def crossover(self, a:Genome, b:Genome) -> Tuple[Genome, Genome]:
#return (a,b)
return self.single_point_crossover(a,b)
def single_point_crossover(self, a:Genome, b:Genome) -> Tuple[Genome, Genome]:
length_a = len(a)
length_b = len(b)
minimim_length = np.min((length_a, length_b))
if(length_a<=1 or length_b<=1):
return a, b
cut = randrange(minimim_length)
offspring1 = a[0:cut] + b[cut:length_b]
offspring2 = b[0:cut] + a[cut:length_a]
offspring1 = self.force_symmetry(offspring1)
offspring2 = self.force_symmetry(offspring2)
return offspring1, offspring2
def mutation(self, genome: Genome, num: int=2, probability: float = 0.5) -> Genome:
method = randrange(4)
if(method == 0):
return self.force_symmetry(self.building_block_mutation(genome, probability))
elif(method == 1):
return self.force_symmetry(self.coupling_mutation(genome, probability))
elif(method == 2):
return self.force_symmetry(self.insert_mutation(genome, probability))
elif(method == 3):
return self.force_symmetry(self.truncate_mutation(genome, probability))
genome = self.force_symmetry(genome)
return genome
def building_block_mutation(self, genome: Genome, probability: float = 0.5) -> Genome:
cfg = configparser.ConfigParser()
cfg.read(self.config_path)
probability = float(cfg.get('Genetic Algorithm', 'block_mutation_prob'))
mutated_genome = list()
if(random()<probability and len(genome)>=3):
new_block = randrange(len(self.building_blocks))
#print("new block " + str(new_block))
block_to_mutate = randrange(int((len(genome)-1)/2))
#print("block to mutate " + str(block_to_mutate))
block_to_mutate = block_to_mutate+block_to_mutate+2
mutated_genome.extend(genome[0:block_to_mutate-1])
mutated_genome.append(new_block)
mutated_genome.extend(genome[block_to_mutate:len(genome)])
print("block mutation!" + str(mutated_genome))
return mutated_genome
return genome
def coupling_mutation(self, genome: Genome, probability: float = 0.5) -> Genome:
cfg = configparser.ConfigParser()
cfg.read(self.config_path)
probability = float(cfg.get('Genetic Algorithm', 'coupling_mutation_prob'))
mutated_genome = list()
if(random()<probability and len(genome)>=3):
new_coupling = randrange(len(self.couplings))
#print("new coupling " + str(new_coupling))
coupling_to_mutate = randrange(0,int((len(genome)+1)/2))
#print("coupling to mutate " + str(coupling_to_mutate))
coupling_to_mutate = coupling_to_mutate+coupling_to_mutate+1
#genome = genome[0:coupling_to_mutate-1] + couplings[new_coupling].abbrev + genome[coupling_to_mutate:len(genome)]
mutated_genome.extend(genome[0:coupling_to_mutate-1])
mutated_genome.append(new_coupling)
mutated_genome.extend(genome[coupling_to_mutate:len(genome)])
print("coupling mutation! " + str(mutated_genome))
return mutated_genome
return genome
def insert_mutation(self, genome: Genome, probability: float = 0.5):
cfg = configparser.ConfigParser()
cfg.read(self.config_path)
probability = float(cfg.get('Genetic Algorithm', 'insert_mutation_prob'))
genome_length = float(cfg.get('Genetic Algorithm', 'genome_length'))
mutated_genome = list()
if(random()<probability and len(genome)/2 < genome_length):
new_coupling = randrange(len(self.couplings))
new_block = new_block = randrange(len(self.building_blocks))
insert_coupling=randrange(0,int((len(genome)+1)/2))
insert_coupling=insert_coupling+insert_coupling+1
to_add_at_end = genome[insert_coupling:len(genome)]
mutated_genome.extend(genome[0:insert_coupling])
mutated_genome.append(new_block)
mutated_genome.append(new_coupling)
mutated_genome.extend(to_add_at_end)
print("insert mutation! " + str(mutated_genome))
return mutated_genome
return genome
def truncate_mutation(self, genome: Genome, probability: float = 0.5):
cfg = configparser.ConfigParser()
cfg.read(self.config_path)
probability = float(cfg.get('Genetic Algorithm', 'truncate_mutation_prob'))
genome_length = float(cfg.get('Genetic Algorithm', 'genome_length'))
mutated_genome = list()
if(random()<probability and len(genome) > 3):
block_to_truncate = randrange(int((len(genome)-1)/2))
block_to_truncate = block_to_truncate+block_to_truncate+2
mutated_genome.extend(genome[0:block_to_truncate-1])
mutated_genome.extend(genome[block_to_truncate+1:len(genome)])
print("truncate mutation!" + str(mutated_genome))
return mutated_genome
return genome<file_sep>from typing import List, Callable, Tuple
class Evaluation:
Genome = List[int]
Population = List[Genome]
FitnessFunc = Callable[[Genome, int, int], int]
PopulateFunc = Callable[[], Population]
SelectionFunc = Callable[[Population, FitnessFunc],Tuple[Genome, Genome]]
CrossoverFunc = Callable[[Genome,Genome], Tuple[Genome, Genome]]
MutationFunc = Callable[[Genome], Genome]
def __init__(self, generation, individual):
pass
self.generation = generation
self.individual = individual
def generate_genome(self, max_length: int) -> Genome:
"""
Generates genome mit maximum lengt of max_lengt (-> size random). Genome is generated from available couplings and building blocks
Args:
param1 (int) : maximum length of
Returns:
Genome
"""
return genome
def generate_population(self, size: int, genome_length: int) -> Population:
"""
Generates population of size size withm genomes of length genome_length
Args:
param1 (int) : population size
param2 (int) : genome_length
Returns:
Genome
"""
return 0
def fitness(self, genome: Genome, generation: int, individual: int) -> float:
"""
Evaluates finess
Args:
param1 (Genome) : genome
param2 (int) : generation
param3 (int) : individual
Returns:
(float) fittness
"""
return 0.0
def selection_pair(self, population: Population, fitness_value) -> Population:
"""
Select pair of population
Args:
param1 (Population) : Population
param2 (Callable) : fitness_function
Returns:
(Population) population
"""
return 0
def mutation(self, genome: Genome, num: int=1, probability: float = 0.5) -> Genome:
"""
Mutation of genome (num of mutations with given probability )
Args:
param1 (Genome) : genome
param2 (int) : number of mutations
param3 (float) : probability of mutation
Returns:
(Genome) population
"""
return 0
def crossover(self, a:Genome, b:Genome) -> Tuple[Genome, Genome]:
"""
Crossover of genome a and b
Args:
param1 (Genome) : genome a
param2 (Genome) : genome b
Returns:
(Genome,Genome)
"""
return ([0],[0])
<file_sep>import os
import fnmatch
import os.path
import numpy as np
import sys
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
def read_population(generation, config_path, calculation_path):
"""
read current generation individuals and their fitness from calculation path
Args:
param1 (int): number of generation which should be read
param2 (String): Path to config file
param3 (String): Path to calculation
Returns:
(population, fitness_values)
"""
try:
filename_population = calculation_path + "/curr_population.dat"
file_population = open(filename_population)
filename_fitness = calculation_path + "/generation_data/" + str(generation) + "/fitness.dat"
file_fitness = open(filename_fitness)
except OSError as e:
print("Cannot open file " + str(e))
return -1,-1, -1
#read n_unique
unique_file = -1
for file in os.listdir(calculation_path + "/generation_data/" + str(generation)):
if fnmatch.fnmatch(file, '*n_unique.dat'):
unique_file = file
if(unique_file != -1):
unique_file = calculation_path + "/generation_data/" + str(generation) + "/" +unique_file
unique_file = open(unique_file, "r")
for line in unique_file:
unique_line = line
n_unique = int(line)
#read population
population = list()
for line in file_population:
tmp = line.strip().split(", ")
tmp = [int(tmp[i]) for i in range(0,len(tmp))]
population.append(tmp)
#read fitness values
fitness_value = list()
for line in file_fitness:
try:
tmp = float(line)
except ValueError as e:
print("Faulty fitness file " + str(e))
return -1,-1
fitness_value.append(tmp)
if(unique_file != -1):
return population, fitness_value, n_unique
else:
return population, fitness_value, -1
def read_generation(config_path, calculation_path):
"""
Invokes the next generation. The number of generation is read from calculation_path/generation.dat
Args:
param1 (String): Path to config file
param2 (String): Path to calculation
Returns:
"""
try:
filename = calculation_path + "/generation.dat"
file = open(filename)
for line in file:
generation = int(line)
except (OSError,ValueError) as e:
print("generation file cannot be found or generation file is faulty " + str(e))
return generation
if __name__ == '__main__':
# sys.argv[1] path to process
# sys.argv[2] config path
# sys.argv[3] figure path
calculation_path = sys.argv[1]
config_path = sys.argv[2]
#how many generations have been calculated
generation = read_generation(config_path, calculation_path)
if(generation == None):
exit()
generations_to_check = np.arange(0, generation)
#load fitness values
fitness_values = list()
fitness_means=list()
std_deviation=list()
n_unique = list()
for i in generations_to_check:
fitness_value = read_population(i, config_path, calculation_path)
fitness_values.append(fitness_value[1])
n_unique.append(fitness_value[2])
if(fitness_value[2]==-1):
fitness_means.append(np.mean(fitness_value[1]))
std_deviation.append(np.std(np.asarray(fitness_value[1])))
else:
fitness_means.append(np.mean(fitness_value[1][0:fitness_value[2]]))
tmp_std = [fitness_value[1][k] for k in range(0,int(len(fitness_value[1])*0.6)) if fitness_value[1][k] > 0]
print(tmp_std)
std_deviation.append(np.std(tmp_std))
print(fitness_means)
print(std_deviation)
fig, ax = plt.subplots(1)
num_individuals = len(fitness_value[1])
#color & plotting stuff
phi = np.linspace(0, 2*np.pi, num_individuals)
rgb_cycle = np.vstack(( # Three sinusoids
.5*(1.+np.cos(phi )), # scaled to [0,1]
.5*(1.+np.cos(phi+2*np.pi/3)), # 120° phase shifted.
.5*(1.+np.cos(phi-2*np.pi/3)))).T # Shape = (60,3)
for xe, ye in zip(generations_to_check, fitness_values):
if(n_unique[xe] == -1):
for i in range(0, len(ye)):
ax.scatter([xe], ye[i], color=rgb_cycle[i], s=num_individuals, marker="x")
else:
for i in range(0, n_unique[xe]):
ax.scatter([xe], ye[i], color=rgb_cycle[i], s=num_individuals, marker="x")
for i in range(n_unique[xe], len(ye)):
ax.scatter([xe], ye[i], color=rgb_cycle[i], s=num_individuals, marker="o")
ax.plot(generations_to_check, fitness_means, color="blue")
ax.plot(generations_to_check, fitness_means-np.asarray(std_deviation), color="blue",linestyle='dashed')
ax.plot(generations_to_check, fitness_means+np.asarray(std_deviation), color="blue",linestyle='dashed')
ax.set_xlabel('Generation',fontsize=20)
ax.set_ylabel('Fitness values',fontsize=20)
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.set_yscale('symlog')
ax.set_ylim((0.0,None))
plt.savefig( sys.argv[3] + "/fitness_values.pdf", bbox_inches='tight') | 9d21421d9005ab4f81ff635a297bc1bf6635f6a1 | [
"Markdown",
"Python",
"Shell"
]
| 21 | Shell | blaschma/ga_mechano_sens | a8f96952b438774eb97afffb45d8191d02cdc476 | a5201916f6eef45c2441b256e4ed202d93491b04 |
refs/heads/master | <file_sep>#ifndef LIST_SORT_H_7YOFEXAH
#define LIST_SORT_H_7YOFEXAH
#include "common.h"
#include "list.h"
enum { QUICK_SORT, MERGE_SORT, INSERT_SORT };
void list_sort(struct list_head *, int);
#define list_get_middle(head, mid) \
do { \
struct list_head *fast, *slow; \
fast = head->next; \
slow = head->next; \
while ((fast->next->next != head) && (fast->next != head)) { \
slow = slow->next; \
fast = fast->next->next; \
} \
mid = slow; \
} while (0);
static void list_split(struct list_head *left,
struct list_head *right,
struct list_head *head)
{
if (list_empty(head) || list_is_singular(head))
return;
struct list_head *mid;
list_get_middle(head, mid);
/* Cut From middle point to tail node*/
list_cut_position(right, mid, head->prev);
list_cut_position(left, head, mid);
}
static void list_merge(struct list_head *left,
struct list_head *right,
struct list_head *head)
{
struct listitem *l = NULL, *r = NULL;
while (1) {
if (list_empty(left)) {
list_splice_tail(right, head);
break;
}
if (list_empty(right)) {
list_splice_tail(left, head);
break;
}
l = list_first_entry(left, struct listitem, list);
r = list_first_entry(right, struct listitem, list);
if (l->i < r->i) {
list_move_tail(left->next, head);
} else {
list_move_tail(right->next, head);
}
}
}
static void list_insert_sorted(struct listitem *entry, struct list_head *head)
{
struct listitem *item = NULL;
if (list_empty(head)) {
list_add(&entry->list, head);
return;
}
list_for_each_entry (item, head, list) {
if (cmpint(&entry->i, &item->i) < 0) {
list_add_tail(&entry->list, &item->list);
return;
}
}
list_add_tail(&entry->list, head);
}
static void list_insertsort(struct list_head *head)
{
struct list_head list_unsorted;
struct listitem *item = NULL, *is = NULL;
INIT_LIST_HEAD(&list_unsorted);
list_splice_init(head, &list_unsorted);
list_for_each_entry_safe (item, is, &list_unsorted, list) {
list_del(&item->list);
list_insert_sorted(item, head);
}
}
static void list_qsort(struct list_head *head)
{
struct list_head list_less, list_greater;
struct listitem *pivot;
struct listitem *item = NULL, *is = NULL;
if (list_empty(head) || list_is_singular(head))
return;
INIT_LIST_HEAD(&list_less);
INIT_LIST_HEAD(&list_greater);
pivot = list_first_entry(head, struct listitem, list);
list_del(&pivot->list);
list_for_each_entry_safe (item, is, head, list) {
if (cmpint(&item->i, &pivot->i) < 0)
list_move_tail(&item->list, &list_less);
else
list_move(&item->list, &list_greater);
}
list_qsort(&list_less);
list_qsort(&list_greater);
list_add(&pivot->list, head);
list_splice(&list_less, head);
list_splice_tail(&list_greater, head);
}
static void list_mergesort(struct list_head *head)
{
if (list_empty(head) || list_is_singular(head)) {
return;
}
struct list_head left, right;
INIT_LIST_HEAD(&left);
INIT_LIST_HEAD(&right);
list_split(&left, &right, head);
list_mergesort(&left);
list_mergesort(&right);
list_merge(&left, &right, head);
}
static void (*list_sort_table[])(struct list_head *head) = {
list_qsort, list_mergesort, list_insertsort};
void list_sort(struct list_head *head, int sort)
{
list_sort_table[sort](head);
}
#endif /* end of include guard: LIST_SORT_H_7YOFEXAH */
| f6cfa8cfe52d6105ea5a160cf43f639d80fa191b | [
"C"
]
| 1 | C | czvkcui/linux-list | 3bbd4c9570469f605791655c5daee09f7371d249 | 58e8fefc96c3b75cff7ad622f0b7826c0457381b |
refs/heads/master | <repo_name>jduggan83/jhipster-multitenancy-test-project<file_sep>/src/main/webapp/app/admin/company-management/company-management.route.ts
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router';
import { JhiPaginationUtil } from 'ng-jhipster';
import { CompanyMgmtComponent } from './company-management.component';
import { CompanyMgmtDetailComponent } from './company-management-detail.component';
import { CompanyDialogComponent } from './company-management-dialog.component';
import { CompanyDeleteDialogComponent } from './company-management-delete-dialog.component';
import { CompanyRouteAccessService } from './../../shared';
@Injectable()
export class CompanyResolvePagingParams implements Resolve<any> {
constructor(private paginationUtil: JhiPaginationUtil) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const page = route.queryParams['page'] ? route.queryParams['page'] : '1';
const sort = route.queryParams['sort'] ? route.queryParams['sort'] : 'id,asc';
return {
page: this.paginationUtil.parsePage(page),
predicate: this.paginationUtil.parsePredicate(sort),
ascending: this.paginationUtil.parseAscending(sort)
};
}
}
export const companyMgmtRoute: Routes = [
{
path: 'company-management',
component: CompanyMgmtComponent,
resolve: {
'pagingParams': CompanyResolvePagingParams
},
data: {
pageTitle: 'companyManagement.home.title'
},
canActivate: [CompanyRouteAccessService]
},
{
path: 'company-management/:id',
component: CompanyMgmtDetailComponent,
data: {
pageTitle: 'companyManagement.home.title'
},
canActivate: [CompanyRouteAccessService]
}
];
export const companyDialogRoute: Routes = [
{
path: 'company-management-new',
component: CompanyDialogComponent,
outlet: 'popup',
canActivate: [CompanyRouteAccessService]
},
{
path: 'company-management/:id/edit',
component: CompanyDialogComponent,
outlet: 'popup',
canActivate: [CompanyRouteAccessService]
},
{
path: 'company-management/:id/delete',
component: CompanyDeleteDialogComponent,
outlet: 'popup',
canActivate: [CompanyRouteAccessService]
}
];
<file_sep>/src/main/webapp/app/entities/machine/machine.model.ts
import { Company } from '../../admin/company-management/company.model';
import { BaseEntity } from './../../shared';
export class Machine implements BaseEntity {
constructor(
public id?: number,
public name?: string,
public company?: Company
) {
}
}
<file_sep>/src/main/java/com/starbucks/inventory/service/MachineService.java
package com.starbucks.inventory.service;
import com.starbucks.inventory.domain.Machine;
import java.util.List;
/**
* Service Interface for managing Machine.
*/
public interface MachineService {
/**
* Save a machine.
*
* @param machine the entity to save
* @return the persisted entity
*/
Machine save(Machine machine);
/**
* Get all the machines.
*
* @return the list of entities
*/
List<Machine> findAll();
/**
* Get the "id" machine.
*
* @param id the id of the entity
* @return the entity
*/
Machine findOne(Long id);
/**
* Delete the "id" machine.
*
* @param id the id of the entity
*/
void delete(Long id);
}
<file_sep>/src/main/webapp/app/admin/company-management/company-management-detail.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Rx';
import { Company } from './company.model';
import { CompanyService } from './company.service';
@Component({
selector: 'jhi-company-mgmt-detail',
templateUrl: './company-management-detail.component.html'
})
export class CompanyMgmtDetailComponent implements OnInit, OnDestroy {
company: Company;
private subscription: Subscription;
constructor(
private companyService: CompanyService,
private route: ActivatedRoute
) {
}
ngOnInit() {
this.subscription = this.route.params.subscribe((params) => {
this.load(params['id']);
});
}
load(id) {
this.companyService.find(id).subscribe((company) => {
this.company = company;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
<file_sep>/src/main/webapp/app/entities/machine/machine.route.ts
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router';
import { UserRouteAccessService } from '../../shared';
import { JhiPaginationUtil } from 'ng-jhipster';
import { MachineComponent } from './machine.component';
import { MachineDetailComponent } from './machine-detail.component';
import { MachinePopupComponent } from './machine-dialog.component';
import { MachineDeletePopupComponent } from './machine-delete-dialog.component';
export const machineRoute: Routes = [
{
path: 'machine',
component: MachineComponent,
data: {
authorities: ['ROLE_USER'],
pageTitle: 'jhipsterApp.machine.home.title'
},
canActivate: [UserRouteAccessService]
}, {
path: 'machine/:id',
component: MachineDetailComponent,
data: {
authorities: ['ROLE_USER'],
pageTitle: 'jhipsterApp.machine.home.title'
},
canActivate: [UserRouteAccessService]
}
];
export const machinePopupRoute: Routes = [
{
path: 'machine-new',
component: MachinePopupComponent,
data: {
authorities: ['ROLE_USER'],
pageTitle: 'jhipsterApp.machine.home.title'
},
canActivate: [UserRouteAccessService],
outlet: 'popup'
},
{
path: 'machine/:id/edit',
component: MachinePopupComponent,
data: {
authorities: ['ROLE_USER'],
pageTitle: 'jhipsterApp.machine.home.title'
},
canActivate: [UserRouteAccessService],
outlet: 'popup'
},
{
path: 'machine/:id/delete',
component: MachineDeletePopupComponent,
data: {
authorities: ['ROLE_USER'],
pageTitle: 'jhipsterApp.machine.home.title'
},
canActivate: [UserRouteAccessService],
outlet: 'popup'
}
];
| f6a0573cc2efec199677c1be4ebbd999146f92db | [
"Java",
"TypeScript"
]
| 5 | TypeScript | jduggan83/jhipster-multitenancy-test-project | 0508bd66a67bcafe6f1e4d1f942623c9c315dda0 | ca76449581b8dadd2f55609066278f78c4532809 |
refs/heads/master | <repo_name>nicl/ign<file_sep>/2/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width" />
<title>nic's layout</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/core.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<header class="clearfix">
<a id="logo" title="Home" href="#">TeamFortress 2</a>
<nav>
<ul>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
<li><a href="#">Item 4</a></li>
<li><a href="#">Item 5</a></li>
</ul>
</nav>
</header>
<div id="main" class="clearfix">
<article class="clearfix">
<h1>Main heading</h1>
<img id="main-image" alt="Home" src="img/tf2.jpg">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit.</p>
</article>
<section>
<h2>Section first</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem.</p>
</section>
<section>
<h2>Section second</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem.</p>
</section>
<section>
<h2>Section third</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem.</p>
</section>
</div>
<footer>
<div class="footer-inner">
© MMIX–MMXI nicolas long
<div id="github">
<a href="https://github.com/nicl">nicl</a>
</div>
</div>
</footer>
</body>
</html>
<file_sep>/3/README.md
README
======
The question
------------
**"You own a license plate manufacturing company. Write a program that takes a population and determines the simplest pattern that will produce enough unique plates. Since all the plates that match the pattern will be generated, find the pattern that produces the least excess plates. Use a combination of letters (A-Z) and numbers (0-9)."**
In fact this question is not perfectly clear as these two sentences conflict:
(1) "Write a program that takes a population and determines the simplest pattern that will produce enough unique plates."
=> suggests that minimizing the number of elements in the pattern is what is important.
(2) "Since all the plates that match the pattern will be generated, find the pattern that produces the least excess plates."
=> suggests best pattern is that which minimises the number of excess plates. (The number of letters and numbers in the pattern is irrelevant here.)
These two requirements can conflict.
Our interpretation
------------------
How should we interpret the question then? Here, we choose to interpret it as (1) and, then in the event of multiple solutions of equal length, choose the one that best meets (2).
###Positions of elements fixed
In the case of (1), the number of plates generated for a given pattern is:
p = 10^x 26^y
where x and y are the numbers of numbers and letters respectively.
Importantly, this assumes that the positions of the letters and numbers in the license plate string are fixed. This is usually the case for license plates in real life. For example, the [pattern for the UK license plate](https://upload.wikimedia.org/wikipedia/commons/thumb/6/6c/British_car_registration_plate_labels.svg/551px-British_car_registration_plate_labels.svg.png) is:
BD51SMR
(Two letters, followed by two numbers, then by three more letters.)
###Positions random
Allowing the positions of the numbers and letters in the string to change complicates things; the number of permutations increases. We can capture this as:
p = 10^x 26^y ((x + y)! / (x! y!))
The second part of the expression, ((x + y)! / (x! y!)), captures the permutations of the letters and numbers combined. The denominator adjusts for the fact that we have permutations involving identical elements.
*Note: This version has not been implemented, but is an easy extension of the method.*
A note on the alternative interpretation
--------------------------
If we decided to make minimizing the number of surplus plates our primary focus (2), the maths becomes more complex. There are infinite real number solutions for x and y to the problem:
min: p - 10^x 26^y ((x + y)! / (x! y!))
So to get integer solutions we cannot simply use differentiation to solve for min values and then round.
I have not yet found a solution to solving this problem. In either case, the favoured interpretation above seems more realistic scenario (we generally prefer shorter license plates).
A note of numbers in PHP
------------------------
The range of integers and floating point numbers in PHP varies according to the
C implementation for your platform.<file_sep>/2/README.md
README
======
The question
------------
**"Create a liquid layout with HTML, CSS, and Javascript. This layout must support the following resolutions: 1024x768, 1680x1050. Explain why you would use a liquid layout."**
What is a liquid layout?
------------------------
Elements in a liquid layout (or at least the parent elements) have their widths defined relative to the viewport. Typically, these are defined in percentages.
This is in contrast to a fixed-width layout, where widths are typically defined in terms of pixels.
Why use a liquid layout (and limitations)
-----------------------------------------
###The web is not print media / Supporting multiple user-agents
The web is not like print-media. A website can be accessed by a wide-variety of devices, with different screen resolutions, pixel densities, and other supported features. Liquid designs are better able to cater for a wider-range of devices than a fixed-width design because, in a limited way, they adapt to the user-agent (namely, the width). In this way, they can make better use of the available screen real estate, avoiding horizontal scrolling or, in the case of a very wide screen, large areas of unused space.
However, liquid layouts represent only a partial attempt to adapt to different user-agents and viewport-sizes. A multi-column layout, even if liquid, will likely be unusable at very low viewport widths unless aspects other than the width also adapt.
Recently, more comprehensive approaches to being 'device-agnostic' have emerged. 'Responsive' and 'Adaptive' designs use CSS media queries (or perhaps Javascript) to adapt or respond to the user-device. So, for example, in the two-column layout mentioned earlier, a more sensible approach might be to collapse down to one column (stacking the old columns vertically, or perhaps hiding some) as the screen approaches narrower resolutions. We may also want to change the text or image sizes - or, perhaps, even serve smaller images (in terms of filesize) if we suspect that lower-resolution devices will in general have slower internet access.*
*This is not necessarily true in the USA/UK anymore, but is almost certainly the case when we consider users from other parts of the world, India and China for example.
Our approach and reasoning behind it
------------------------------------
The 'TF2-inspired' design we have created is both liquid *and* responsive. It uses flexible widths but also uses CSS media-queries to respond to the user-agent by changing the number of columns, image size, and other aspects of the design. It is also HTML5. The colour scheme is inspired by [Solarized](http://ethanschoonover.com/solarized) by <NAME>.
**Alter the width of your browser window to try it out!**
Note: no attempt has been made to support older browsers - in particular, versions of IE before IE9 do not natively support media queries. If IE support was required, we could either provide a separate IE-specific stylesheet, or use a Javascript library such as [css3-mediaqueries-js](http://code.google.com/p/css3-mediaqueries-js/) to replicate the functionality.<file_sep>/3/index.php
<?php
require 'Plates.php';
use Ign\Nic\Plates;
use Exception;
header('Content-Type: text/html; charset=utf-8');
print '<h1>IGN #2 - Car license plates</h1>';
$pop = isset($_GET['population']) ? $_GET['population'] : false;
if ($pop) {
try {
$plates = new Plates($pop);
} catch (Exception $e) {
print $e->getMessage() . "<br/>";
print '<a href="index.php">Back</a>';
}
$pattern = $plates->getPattern($pop);
// give answer
printf('For a population of %d, use %d number(s), and %d letter(s)',
htmlspecialchars($pop, ENT_QUOTES, 'UTF-8'),
$pattern['numbers'],
$pattern['letters']);
}
?>
<form action="index.php" method="get">
<label for="population">Population:</label>
<input type="text" id="population" name="population" value="<?php print htmlspecialchars($pop, ENT_QUOTES, 'UTF-8'); ?>" />
<input name="submit" type="submit" value="Go for it!" />
</form>
<file_sep>/README.md
README
======
This is my application for IGN Code Foo 2012!
<file_sep>/3/Plates.php
<?php
namespace Ign\Nic;
use Exception;
/**
* Class to calculate pattern of letters and numbers required to provide a
* specified number of plates.
*/
class Plates
{
const letters = 26;
const numbers = 10;
protected $population;
protected $upperBound;
protected $patterns = array();
public function __construct($population)
{
if (!is_numeric($population) || $population != (int) $population) {
throw new Exception('Must be an integer population!');
}
$this->population = (int) $population;
}
public function getPattern()
{
$this->setUpperBound()->setPatterns()->sortPatterns();
return $this->patterns[0];
}
/**
* Get the upper bound
*
* The maximum elements required (e.g. assuming using only numbers)
*
* @return Plates
*/
protected function setUpperBound()
{
// special handling for population = 1
if ($this->population === 1) {
$this->upperBound = 1;
}
else {
$this->upperBound = (int) ceil(
(log($this->population) / log(self::numbers)));
}
return $this;
}
/**
* Identify the simplest (smallest) patterns which produce enough plates
*
* @return Plates
*/
protected function setPatterns()
{
// compare solutions for different combinations of letters and numbers
// x represents numbers required, while y is letters required
// upper bound is used to avoid unecessary loops
for ($x = 0; $x <= $this->upperBound; $x += 1) {
for ($y = 0; $x + $y <= $this->upperBound; $y += 1) {
if ($x === 0 && $y === 0) {
$plates = 0;
}
else {
$plates = pow(10, $x) * pow(26, $y);
}
if ($plates >= $this->population ) {
// reset upperBound save iterating over entire set
$this->upperBound = $x + $y;
// store solution
$this->patterns[] = array(
'numbers' => $x,
'letters' => $y,
'plates' => $plates,
'diff' => $plates - $this->population,
);
// don't bother to evaluate more y's for this x
break;
}
}
}
return $this;
}
/**
* Sort the patterns into order of best fit (asc)
*
* @return Plates
*/
protected function sortPatterns()
{
// sort solutions into order of best fit
usort($this->patterns,
function ($a, $b) {
if ($a['diff'] === $b['diff']) {
return 0;
}
else {
return ($a['diff'] < $b['diff'] ? -1 : 1);
}
}
);
return $this;
}
}
<file_sep>/1/README.md
README
======
The question
------------
**"How many ping pong balls would it take to fill an average-sized school bus? Describe each step in your thought process."**
How to solve
------------
###Step 1. What are the dimensions of a ping pong ball?
According to the International Table Tennis Federation (ITTF) a table tennis ball should have a diameter of 40mm (so a radius of 20mm).
###Step 2. How tightly can you pack spheres?
Ping pong balls are not squares; for a given diameter/side, they can be packed together more tightly.
In fact, there are several ways in which spheres can be packed, with different packing densities (the proportion of the total space occupied by the spheres themselves). The problem of finding the sphere packing with the greatest packing density is known as the 'Kepler Problem' and a substantial literature exists for the subject.
According to [this](http://mathworld.wolfram.com/SpherePacking.html) article on Wolfram Alpha - I have not had time to survey the literature in depth myself(!) - the best known packing strategy is 'cubic' or 'hexagonal' close packing.
These approaches yield a packing density of π / (3 √2)
(Or, roughly, 0.7405).
Conversely, the loosest possible density (Gardner, 1966) is supposed to be 0.0555.
###Step 3. What kind of 'average'?
An average can be any measure of central tendency. Three well-known types are the mean, median, and mode.
###Step 4. Find or estimate bus internal volume
Bus volume might be available from a manufacturer's specifications. If not, an estimate would have to be made. We could fill it up with water (if it were water-tight), or attempt a rough estimate by physical measurement with a tape.
Depending on the type of average preferred, we may or may not have to combine estimates.
###Step 5. Calculate
We can calculate a rough answer by combining our knowledge of ping pong and bus dimensions, and sphere packing densities.
((volume of bus) * (packing density)) / (volume of ping pong ball sphere)
Note, the volume of a sphere is:
V = (4/3)πr^3
###Step 6. But how do you close the bus door?
Hahahaha...
An Example
----------
Using:
- ping pong balls of radius of 20mm
- in a bus with internal volume of 10m x 2.5m x 2m (assume we have calculated this)
- and using cubic close packing (packing density = ~0.7405)
Then the answer is:
(10 x 2.5 x 2) * 0.7405 / ((4/3)π0.02^3)
= 1,104,883 (rounded down)<file_sep>/bonus-video/README.md
README
======
Bonus task - video
------------
**"Submit a short video (less than 2 minutes) introducing yourself, showing your passion for IGN, and telling us why you're a good fit for Code-Foo."**
[My Video!](http://www.youtube.com/watch?v=cp-dN0xgsAs&feature=youtu.be)
| 0c3714f9b127b73e0e5c40b2c4a28b035e1628ff | [
"Markdown",
"HTML",
"PHP"
]
| 8 | HTML | nicl/ign | 023d4f8f0ce9b5813b7b00b625c208223e21c5f1 | 3f1bb3c8963879b0d7f91979640f2033f3fd4dde |
refs/heads/master | <repo_name>ksanaforge/corpus-forge<file_sep>/src/kposcal.js
const React=require("react");
const E=React.createElement;
const styles={
button:{background:"silver",color:"black",border:"1px solid"},
label:{color:"silver"},
input:{width:"10em"}
}
const kposFromRange=function(r){
var kpos=r?r.range:'';
if (r.start==r.end) kpos=r.start;
return kpos;
}
class KPosCal extends React.Component {
constructor(props){
super(props);
const address='1p1.0100';
this.state={kpos:0,address};
}
componentWillReceiveProps(nextProps){
if (!this.state.kpos) {
var r=nextProps.cor?nextProps.cor.parseRange(this.state.address):0;
const kpos=kposFromRange(r);
this.setState({kpos});
}
}
fromKPos(e){
var kpos=parseInt(e.target.value,10);
if (isNaN(kpos)) kpos=0;
const address=this.props.cor.stringify(kpos);
this.setState({kpos,address});
}
toKPos(e){
const address=e.target.value;
var r=this.props.cor.parseRange(address)
const kpos=kposFromRange(r);
this.setState({address,kpos});
}
render(){
if (!this.props.cor)return E("span",{},"");
return E("span",{},
E("span",{style:styles.label},"kpos:"),
E("input",{style:styles.input,
onChange:this.fromKPos.bind(this),value:this.state.kpos}),
E("span",{style:styles.label},"address"),
E("input",{style:styles.input,
onChange:this.toKPos.bind(this),value:this.state.address})
)
}
}
module.exports=KPosCal;
<file_sep>/static/bundle.js
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
var createWebCorpus = null;
if (typeof KsanaCorpusBuilder !== "undefined") {
createWebCorpus = KsanaCorpusBuilder.createWebCorpus;
} else {
var KSANACORPUSBUILDER = "ksana-corpus-builder";
createWebCorpus = require(KSANACORPUSBUILDER).createWebCorpus;
}
var start = function start(files, logger, cb) {
createWebCorpus(files, logger, function (err, corpus, written) {
if (err) {
cb(err);
} else {
try {
logger(written + " unicode characters indexed.");
corpus.writeKDB(null, function (bloburl, size) {
logger("ROM ready. " + size + " bytes");
cb(0, bloburl, corpus.id + ".cor", size);
});
} catch (e) {
cb(e.message || e);
}
}
});
};
module.exports = { start: start };
/*
var composes=["第零編"],categories=[], groupid;
const capture=function(){return true;}
const on_compose_close=function(tag,closing,kpos,tpos){
const compose=this.popText();
composes.push(compose);
}
const fileStart=function(fn,i){
const at=fn.lastIndexOf("/");
console.log(fn)
fn=fn.substr(at+1);
groupid=fn.substr(0,fn.length-4);//remove .xml
}
const on_category_close=function(tag,closing,kpos,tpos){
const cat=this.popText();
this.putGroup(groupid+";"+(composes.length-1)+"@"+cat,kpos,tpos);
}
corpus.setHandlers(
{"類":capture,"編":capture},
{"類":on_category_close,"編":on_compose_close},
{fileStart}
);
*/
},{}],2:[function(require,module,exports){
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = require("react");
var E = React.createElement;
var styles = {
button: { background: "silver", color: "black", border: "1px solid" }
};
var Homebar = function (_React$Component) {
_inherits(Homebar, _React$Component);
function Homebar() {
_classCallCheck(this, Homebar);
return _possibleConstructorReturn(this, (Homebar.__proto__ || Object.getPrototypeOf(Homebar)).apply(this, arguments));
}
_createClass(Homebar, [{
key: "componentDidMount",
value: function componentDidMount() {
this.refs.sourcefile.directory = true;
this.refs.sourcefile.webkitdirectory = true;
}
}, {
key: "render",
value: function render() {
return E("span", {}, E("label", {}, E("span", { style: styles.button }, "Open .cor"), E("input", { type: "file", style: { display: "none" },
accept: ".cor", onChange: this.props.openfile })), E("label", {}, E("span", { style: styles.button }, "Build .cor"), E("input", { ref: "sourcefile", type: "file", style: { display: "none" },
multiple: true, onChange: this.props.build })));
}
}]);
return Homebar;
}(React.Component);
module.exports = Homebar;
},{"react":"react"}],3:[function(require,module,exports){
"use strict";
var React = require("react");
var E = React.createElement;
var Main = require("./main");
var ReactDOM = require("react-dom");
ReactDOM.render(E(Main), document.getElementById("root"));
},{"./main":6,"react":"react","react-dom":"react-dom"}],4:[function(require,module,exports){
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = require("react");
var E = React.createElement;
var styles = {
button: { background: "silver", color: "black", border: "1px solid" },
label: { color: "silver" },
input: { width: "10em" }
};
var kposFromRange = function kposFromRange(r) {
var kpos = r ? r.range : '';
if (r.start == r.end) kpos = r.start;
return kpos;
};
var KPosCal = function (_React$Component) {
_inherits(KPosCal, _React$Component);
function KPosCal(props) {
_classCallCheck(this, KPosCal);
var _this = _possibleConstructorReturn(this, (KPosCal.__proto__ || Object.getPrototypeOf(KPosCal)).call(this, props));
var address = '1p1.0100';
_this.state = { kpos: 0, address: address };
return _this;
}
_createClass(KPosCal, [{
key: "componentWillReceiveProps",
value: function componentWillReceiveProps(nextProps) {
if (!this.state.kpos) {
var r = nextProps.cor ? nextProps.cor.parseRange(this.state.address) : 0;
var kpos = kposFromRange(r);
this.setState({ kpos: kpos });
}
}
}, {
key: "fromKPos",
value: function fromKPos(e) {
var kpos = parseInt(e.target.value, 10);
if (isNaN(kpos)) kpos = 0;
var address = this.props.cor.stringify(kpos);
this.setState({ kpos: kpos, address: address });
}
}, {
key: "toKPos",
value: function toKPos(e) {
var address = e.target.value;
var r = this.props.cor.parseRange(address);
var kpos = kposFromRange(r);
this.setState({ address: address, kpos: kpos });
}
}, {
key: "render",
value: function render() {
if (!this.props.cor) return E("span", {}, "");
return E("span", {}, E("span", { style: styles.label }, "kpos:"), E("input", { style: styles.input,
onChange: this.fromKPos.bind(this), value: this.state.kpos }), E("span", { style: styles.label }, "address"), E("input", { style: styles.input,
onChange: this.toKPos.bind(this), value: this.state.address }));
}
}]);
return KPosCal;
}(React.Component);
module.exports = KPosCal;
},{"react":"react"}],5:[function(require,module,exports){
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = require("react");
var E = React.createElement;
var styles = {
log: { color: "green" },
timestamp: { color: "silver" },
error: { color: "red" },
warn: { color: "orange" },
normal: { color: "green" },
container: { height: "95%", overflow: "auto" }
};
var Logger = function (_React$Component) {
_inherits(Logger, _React$Component);
function Logger() {
_classCallCheck(this, Logger);
return _possibleConstructorReturn(this, (Logger.__proto__ || Object.getPrototypeOf(Logger)).apply(this, arguments));
}
_createClass(Logger, [{
key: "renderLog",
value: function renderLog(_log, key) {
var log = _log.slice();
var style = styles.normal;
var timestamp = log.shift();
if (styles[log[0]]) {
style = styles[log.shift()];
}
var logmessage = log.join(" ");
var ts = timestamp.toTimeString().substr(0, 8);
return E("div", { key: key, style: styles.log }, E("span", {}, " ", E("span", { style: style }, logmessage)));
}
}, {
key: "render",
value: function render() {
return E("div", { style: styles.container }, E("div", { style: styles.timestamp }, new Date().toString().replace(/GMT.+/, ""), ",started at: " + this.props.starttime.toString().replace(/GMT.+/, "")), this.props.logs.map(this.renderLog.bind(this)));
}
}]);
return Logger;
}(React.Component);
module.exports = Logger;
},{"react":"react"}],6:[function(require,module,exports){
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = require("react");
var TreeView = require("./treeview");
var E = React.createElement;
var data = require("./manual");
var Homebar = require("./homebar");
var KPosCal = require("./kposcal");
var _openCorpus = null,
closeCorpus = null;
if (typeof KsanaCorpus !== "undefined") {
_openCorpus = KsanaCorpus.openCorpus;
closeCorpus = KsanaCorpus.closeCorpus;
} else {
var KSANACORPUS = "ksana-corpus";
_openCorpus = require(KSANACORPUS).openCorpus;
closeCorpus = require(KSANACORPUS).closeCorpus;
}
var Logger = require("./logger");
var styles = {
treeview: { height: "90%", overflow: "auto" },
download: { color: "yellow" },
label: { color: "white" },
err: { color: "yellow", background: "red" },
button: { background: "silver", color: "black", border: "1px solid" }
};
var builder = require("./builder");
var parseRoute = function parseRoute(route) {
var regex = /[?#&]([^=#]+)=([^&#]*)/g,
params = {},
match;
while (match = regex.exec(route)) {
params[match[1]] = match[2];
}
return params;
};
var Main = function (_React$Component) {
_inherits(Main, _React$Component);
function Main(props) {
_classCallCheck(this, Main);
var _this = _possibleConstructorReturn(this, (Main.__proto__ || Object.getPrototypeOf(Main)).call(this, props));
_this.state = { data: data, objurl: null, err: null, building: false, logs: [] };
return _this;
}
_createClass(Main, [{
key: "componentDidMount",
value: function componentDidMount() {
var hash = window.location.hash;
if (hash.match(/%[0-9A-Fa-f]/)) {
hash = decodeURIComponent(hash);
}
var params = parseRoute(hash);
if (params.c) {
this.openCorpus(params.c);
}
}
}, {
key: "openCorpus",
value: function openCorpus(id) {
var _this2 = this;
_openCorpus(id, function (err, cor) {
cor.get([], function (cache) {
_this2.setState({ data: cache, cor: cor });
});
});
}
}, {
key: "openfile",
value: function openfile(e) {
var id = e.target.files[0];
closeCorpus(id);
this.openCorpus(id);
}
}, {
key: "log",
value: function log() {
var args = Array.prototype.slice.call(arguments);
var logs = this.state.logs;
args.unshift(new Date());
logs.push(args);
this.setState({ logs: logs });
}
}, {
key: "build",
value: function build(e) {
var _this3 = this;
this.setState({ logs: [], starttime: new Date(), building: true, built: false, err: null });
builder.start(e.target.files, this.log.bind(this), function (err, objurl, downloadname, size) {
if (err) {
_this3.setState({ err: err });
return;
}
var path = objurl + "#" + downloadname.replace(/\..+/, "") + "*" + size;
_openCorpus(path, function (err, cor) {
cor.get([], function (cache) {
_this3.setState({ data: cache, cor: cor, built: true });
});
});
_this3.setState({ objurl: objurl, downloadname: downloadname });
});
}
}, {
key: "inspect",
value: function inspect() {
this.setState({ building: false, built: false });
}
}, {
key: "render",
value: function render() {
return E("div", {}, E(Homebar, { openfile: this.openfile.bind(this), build: this.build.bind(this) }), E(KPosCal, { cor: this.state.cor }), this.state.err ? E("span", { style: styles.err }, this.state.err) : null, this.state.objurl && !this.state.building ? E("a", { href: this.state.objurl, style: styles.download,
download: this.state.downloadname }, "download (right click, Save Link As)") : null, this.state.built ? E("button", { onClick: this.inspect.bind(this) }, "Inspect Built Corpus") : null, this.state.building ? E(Logger, { logs: this.state.logs, starttime: this.state.starttime }) : E("div", { style: styles.treeview }, E(TreeView, { cor: this.state.cor, data: this.state.data })));
}
}]);
return Main;
}(React.Component);
module.exports = Main;
},{"./builder":1,"./homebar":2,"./kposcal":4,"./logger":5,"./manual":7,"./treeview":8,"react":"react"}],7:[function(require,module,exports){
"use strict";
module.exports = {
"名稱": "Corpus Forge",
"版本": 20170504,
"語法": {
"分頁": "pb"
},
"版本沿革": {
"20170320": "支援內嵌圖檔",
"20170321": "預載欄位gfields",
"20170415": "支援外部互文標記及svg",
"20170423": "顯示圖檔",
"20170426": "支援四種外部欄位",
"20170504": "Diacritics 正規化"
}
};
},{}],8:[function(require,module,exports){
'use strict';
var React = require("react");
var E = React.createElement;
var MAXNODES = 500;
var grabNode = function grabNode(key, value, parents, fetch, autoopen, cor) {
var nodeType = objType(value);
var theNode;
var aKey = key + Date.now();
if (nodeType === 'Object') {
theNode = E(JSONObjectNode, { data: value, keyName: key, key: aKey, parents: parents, fetch: fetch, autoopen: autoopen, cor: cor });
} else if (nodeType === 'Array') {
theNode = E(JSONArrayNode, { data: value, keyName: key, key: aKey, parents: parents, fetch: fetch, autoopen: autoopen, cor: cor });
} else if (nodeType === 'String') {
var defer = value.charCodeAt(0) == 0xffff;
theNode = E(defer ? JSONDeferNode : JSONStringNode, { keyName: key, value: value, key: aKey, parents: parents, fetch: fetch });
} else if (nodeType === 'Number') {
theNode = E(JSONNumberNode, { keyName: key, value: value, key: aKey, parents: parents, fetch: fetch, cor: cor });
} else if (nodeType === 'Boolean') {
theNode = E(JSONBooleanNode, { keyName: key, value: value, key: aKey, parents: parents, fetch: fetch });
} else if (nodeType === 'Null') {
theNode = E(JSONNullNode, { keyName: key, value: value, key: aKey, parents: parents, fetch: fetch });
} else {
console.error("How did this happen?", nodeType);
}
return theNode;
};
/**
* Returns the type of an object as a string.
*
* @param obj Object The object you want to inspect
* @return String The object's type
*/
var objType = function objType(obj) {
var className = Object.prototype.toString.call(obj).slice(8, -1);
return className;
};
/**
* Mixin for stopping events from propagating and collapsing our tree all
* willy nilly.
*/
var SquashClickEventMixin = {
handleClick: function handleClick(e) {
e.stopPropagation();
}
};
/**
* Mixin for setting intial props and state and handling clicks on
* nodes that can be expanded.
*/
var ExpandedStateHandlerMixin = {
getDefaultProps: function getDefaultProps() {
return { data: [], initialExpanded: false };
},
getInitialState: function getInitialState() {
var keys = this.props.parents.slice();
keys.shift();
keys.push(this.props.keyName);
var close = keys.length;
if (this.props.autoopen) for (var i = 0; i < keys.length; i++) {
if (keys[i] == this.props.autoopen[i]) {
close--;
} else break;
}
var expanded = this.props.initialExpanded || !close;
return {
expanded: expanded,
createdChildNodes: false
};
},
handleClick: function handleClick(e) {
e.stopPropagation();
this.setState({ expanded: !this.state.expanded });
},
componentWillReceiveProps: function componentWillReceiveProps() {
// resets our caches and flags we need to build child nodes again
this.renderedChildren = [];
this.itemString = false;
this.needsChildNodes = true;
}
};
/**
* Array node class. If you have an array, this is what you should use to
* display it.
*/
var JSONArrayNode = React.createClass({
mixins: [ExpandedStateHandlerMixin],
/**
* Returns the child nodes for each element in the array. If we have
* generated them previously, we return from cache, otherwise we create
* them.
*/
getChildNodes: function getChildNodes() {
var childNodes = [];
if (this.state.expanded && this.needsChildNodes) {
var len = this.props.data.length;
if (len > MAXNODES) len = MAXNODES;
var parents = this.props.parents.slice();
parents.push(this.props.keyName);
for (var i = 0; i < len; i += 1) {
childNodes.push(grabNode(i, this.props.data[i], parents, this.props.fetch, this.props.autoopen, this.props.cor));
}
this.needsChildNodes = false;
this.renderedChildren = childNodes;
}
return this.renderedChildren;
},
/**
* flag to see if we still need to render our child nodes
*/
needsChildNodes: true,
/**
* cache store for our child nodes
*/
renderedChildren: [],
/**
* cache store for the number of items string we display
*/
itemString: false,
/**
* Returns the "n Items" string for this node, generating and
* caching it if it hasn't been created yet.
*/
getItemString: function getItemString() {
if (!this.itemString) {
var lenWord = this.props.data.length === 1 ? ' Item' : ' Items';
this.itemString = this.props.data.length + lenWord;
}
return this.itemString;
},
render: function render() {
var childNodes = this.getChildNodes();
var childListStyle = {
display: this.state.expanded ? 'block' : 'none'
};
var cls = "array parentNode";
cls += this.state.expanded ? " expanded" : '';
return E("li", { className: cls, onClick: this.handleClick }, E("label", {}, this.props.keyName + ":"), E("span", {}, this.getItemString()), E("ol", { style: childListStyle }, childNodes));
}
});
/**
* Object node class. If you have an object, this is what you should use to
* display it.
*/
var JSONObjectNode = React.createClass({
mixins: [ExpandedStateHandlerMixin],
/**
* Returns the child nodes for each element in the object. If we have
* generated them previously, we return from cache, otherwise we create
* them.
*/
getChildNodes: function getChildNodes() {
if (this.state.expanded && this.needsChildNodes) {
var obj = this.props.data;
var childNodes = [];
var parents = this.props.parents.slice();
parents.push(this.props.keyName);
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
childNodes.push(grabNode(k, obj[k], parents, this.props.fetch, this.props.autoopen, this.props.cor));
}
}
this.needsChildNodes = false;
this.renderedChildren = childNodes;
}
return this.renderedChildren;
},
/**
* Returns the "n Items" string for this node, generating and
* caching it if it hasn't been created yet.
*/
getItemString: function getItemString() {
if (!this.itemString) {
var obj = this.props.data;
var len = 0;
var lenWord = ' Items';
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
len += 1;
}
}
if (len === 1) {
lenWord = ' Item';
}
this.itemString = len + lenWord;
}
return this.itemString;
},
/**
* cache store for the number of items string we display
*/
itemString: false,
/**
* flag to see if we still need to render our child nodes
*/
needsChildNodes: true,
/**
* cache store for our child nodes
*/
renderedChildren: [],
render: function render() {
var childListStyle = {
display: this.state.expanded ? 'block' : 'none'
};
var cls = "object parentNode";
cls += this.state.expanded ? " expanded" : '';
return E("li", { className: cls, onClick: this.handleClick }, E("label", {}, this.props.keyName + ":"), E("span", {}, this.getItemString()), E("ul", { style: childListStyle }, this.getChildNodes()));
}
});
/**
* String node component
*/
var supportimages = ["jpg", "jpeg", "png"];
var showimage = function showimage(e) {
e.target.src = e.target.dataset.src;
e.stopPropagation();
e.preventDefault();
};
var showsvg = function showsvg(e) {
e.target.innerHTML = e.target.dataset.src;
e.stopPropagation();
e.preventDefault();
};
var resolveStyleConflict = function resolveStyleConflict(svgcontent, id) {
return svgcontent.replace(/st(\d+)/g, function (m, m1) {
return "st" + id + "-" + m1;
});
};
var renderString = function renderString(str, parents) {
var fieldname = "";
if (parents.length > 2) {
fieldname = parents[parents.length - 2];
}
var src = "img/view-icon.png";
if (fieldname == "svg" || fieldname == "figure" || fieldname == "table") {
if (str.indexOf("svg") > -1) {
str = str.replace(/<!--.+?-->\r?\n?/g, "").replace(/<!DOCTYPE.+?>\r?\n/, "").replace(/<\?xml.+>\r?\n/, "");
str = resolveStyleConflict(str, Math.random().toString().substr(2));
return E("div", { style: { background: "gray" }, "data-src": str, onClick: showsvg }, "view SVG");
}
} else if (supportimages.indexOf(fieldname) > -1) {
var data = 'data:img/' + fieldname + ';base64,' + str;
if (str.length < 4000) {
//show small image immediately
return E("img", { src: data });
} else {
return E("img", { "data-src": data, src: src, onClick: showimage });
}
}
return str;
};
var JSONStringNode = React.createClass({
mixins: [SquashClickEventMixin],
render: function render() {
return E("li", { className: "string itemNode" }, E("label", {}, this.props.keyName + ":"), E("span", {}, renderString(this.props.value, this.props.parents)));
}
});
var JSONDeferNode = React.createClass({
mixins: [SquashClickEventMixin],
openNode: function openNode(e) {
var path = this.props.parents.slice();
path.shift();
path.push(this.props.keyName);
this.props.fetch(path);
},
render: function render() {
return E("li", { className: "string itemNode", onClick: this.handleClick }, E("label", {}, this.props.keyName + ":"), E("button", { onClick: this.openNode }, "+"));
}
});
/**
* Number node component
*/
var JSONNumberNode = React.createClass({
mixins: [SquashClickEventMixin],
getInitialState: function getInitialState() {
return { text: '' };
},
getText: function getText(e) {
var addr = e.target.innerHTML;
var r = this.props.cor.parseRange(addr);
if (!r) return;
if (r.start == r.end) {
addr += '-99';
}
this.props.cor.getText(addr, function (text) {
this.setState({ text: text.join("").substr(0, 30) });
}.bind(this));
},
render: function render() {
var label = this.props.value;
var translated = this.props.cor ? this.props.cor.stringify(this.props.value) : "";
if (!parseInt(translated, 10)) {
translated = "";
} else translated = " " + translated;
return E("li", { className: "itemNode",
onClick: this.handleClick }, E("label", {}, this.props.keyName + ":"), translated ? E("span", {
title: this.props.value, className: "kpos",
onClick: this.getText }, translated) : E("span", { className: "number" }, this.props.value), E("span", { className: "ktext" }, this.state.text));
}
});
/**
* Null node component
*/
var JSONNullNode = React.createClass({
mixins: [SquashClickEventMixin],
render: function render() {
return E("li", { className: "null itemNode", onClick: this.handleClick }, E("label", {}, this.props.keyName + ":"), E("span", {}, "null"));
}
});
/**
* Boolean node component
*/
var JSONBooleanNode = React.createClass({
mixins: [SquashClickEventMixin],
render: function render() {
var truthString = this.props.value ? 'true' : 'false';
return E("li", { className: "boolean itemNode", onClick: this.handleClick }, E("label", {}, this.props.keyName + ":"), E("span", {}, truthString));
}
});
/**
* JSONTree component. This is the 'viewer' base. Pass it a `data` prop and it
* will render that data, or pass it a `source` URL prop and it will make
* an XMLHttpRequest for said URL and render that when it loads the data.
*
* You can load new data into it by either changing the `data` prop or calling
* `loadDataFromURL()` on an instance.
*
* The first node it draws will be expanded by default.
*/
var JSONTree = React.createClass({
fetch: function fetch(path) {
var _this = this;
this.props.cor.get(path, function (data) {
var storepoint = _this.state.data;
for (var i = 0; i < path.length; i++) {
if (i < path.length - 1) {
storepoint = storepoint[path[i]];
} else {
storepoint[path[i]] = data;
}
}
_this.setState({ data: _this.state.data, autoopen: path });
});
},
getInitialState: function getInitialState() {
return { data: this.props.data };
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
this.setState({ data: nextProps.data });
},
render: function render() {
var nodeType = objType(this.state.data);
var rootNode;
if (nodeType === 'Object') {
rootNode = E(JSONObjectNode, { data: this.state.data, cor: this.props.cor,
keyName: "/", initialExpanded: true, parents: [], fetch: this.fetch, autoopen: this.state.autoopen });
} else if (nodeType === 'Array') {
rootNode = E(JSONArrayNode, { data: this.state.data, cor: this.props.cor,
initialExpanded: true, keyName: "(root)", parents: [], fetch: this.fetch, autoopen: this.state.autoopen });
} else {
console.error("How did you manage that?");
}
return E("ul", { className: "json_tree" }, rootNode);
}
});
module.exports = JSONTree;
},{"react":"react"}]},{},[3]);
<file_sep>/src/homebar.js
const React=require("react");
const E=React.createElement;
const styles={
button:{background:"silver",color:"black",border:"1px solid"}
}
class Homebar extends React.Component {
componentDidMount(){
this.refs.sourcefile.directory=true;
this.refs.sourcefile.webkitdirectory =true;
}
render(){ return E("span",{},
E("label",{},
E("span",{style:styles.button},"Open .cor"),
E("input",{type:"file",style:{display:"none"},
accept:".cor",onChange:this.props.openfile})
),
E("label",{},
E("span",{style:styles.button},"Build .cor"),
E("input",{ref:"sourcefile",type:"file",style:{display:"none"},
multiple:true,onChange:this.props.build})
)
)}
}
module.exports=Homebar;<file_sep>/src/index.js
const React=require("react");
const E=React.createElement;
const Main=require("./main");
const ReactDOM=require("react-dom");
ReactDOM.render(E(Main),document.getElementById("root"));<file_sep>/src/main.js
const React=require("react");
const TreeView=require("./treeview");
const E=React.createElement;
const data=require("./manual");
const Homebar=require("./homebar");
const KPosCal=require("./kposcal");
var openCorpus=null,closeCorpus=null;
if (typeof KsanaCorpus!=="undefined") {
openCorpus=KsanaCorpus.openCorpus;
closeCorpus=KsanaCorpus.closeCorpus;
}else{
const KSANACORPUS="ksana-corpus";
openCorpus=require(KSANACORPUS).openCorpus;
closeCorpus=require(KSANACORPUS).closeCorpus;
}
const Logger=require("./logger");
const styles={
treeview:{height:"90%",overflow:"auto"},
download:{color:"yellow"},
label:{color:"white"},
err:{color:"yellow",background:"red"},
button:{background:"silver",color:"black",border:"1px solid"}
}
const builder=require("./builder");
const parseRoute=function(route){
var regex = /[?#&]([^=#]+)=([^&#]*)/g, params = {}, match ;
while(match = regex.exec(route)) {
params[match[1]] = match[2];
}
return params;
}
class Main extends React.Component {
constructor(props){
super(props);
this.state={data,objurl:null,err:null,building:false,logs:[]};
}
componentDidMount(){
var hash=window.location.hash;
if (hash.match(/%[0-9A-Fa-f]/)) {
hash=decodeURIComponent(hash);
}
const params=parseRoute(hash);
if (params.c) {
this.openCorpus(params.c)
}
}
openCorpus(id){
openCorpus(id,(err,cor)=>{
cor.get([],cache=>{
this.setState({data:cache,cor})
})
})
}
openfile(e){
const id=e.target.files[0];
closeCorpus(id);
this.openCorpus(id);
}
log(){
var args = Array.prototype.slice.call(arguments);
const logs=this.state.logs;
args.unshift(new Date());
logs.push(args);
this.setState({logs});
}
build(e){
this.setState({logs:[],starttime:new Date(),building:true,built:false,err:null});
builder.start(e.target.files,this.log.bind(this),
(err,objurl,downloadname,size)=>{
if (err) {
this.setState({err});
return;
}
const path=objurl+"#"+downloadname.replace(/\..+/,"")+"*"+size;
openCorpus(path,(err,cor)=>{
cor.get([],cache=>{
this.setState({data:cache,cor,built:true})
})
})
this.setState({objurl,downloadname});
});
}
inspect(){
this.setState({building:false,built:false});
}
render(){
return E("div",{},
E(Homebar,{openfile:this.openfile.bind(this),build:this.build.bind(this)}),
E(KPosCal,{cor:this.state.cor}),
this.state.err?E("span",{style:styles.err},this.state.err):null,
(this.state.objurl&&!this.state.building)?
E("a",{href:this.state.objurl,style:styles.download,
download:this.state.downloadname},"download (right click, Save Link As)"):null,
this.state.built?E("button",{onClick:this.inspect.bind(this)},"Inspect Built Corpus"):null,
this.state.building?
E(Logger,{logs:this.state.logs,starttime:this.state.starttime}):
E("div",{style:styles.treeview},
E(TreeView,{cor:this.state.cor,data:this.state.data}))
)
}
}
module.exports=Main;<file_sep>/src/treeview.js
const React=require("react");
const E=React.createElement;
const MAXNODES=500;
var grabNode = function (key, value, parents, fetch,autoopen,cor) {
var nodeType = objType(value);
var theNode;
var aKey = key + Date.now();
if (nodeType === 'Object') {
theNode = E(JSONObjectNode, {data:value, keyName:key,key:aKey, parents, fetch,autoopen,cor:cor})
} else if (nodeType === 'Array') {
theNode = E(JSONArrayNode, {data:value, keyName:key,key:aKey, parents, fetch,autoopen,cor:cor} )
} else if (nodeType === 'String') {
const defer=value.charCodeAt(0)==0xffff;
theNode = E( defer?JSONDeferNode:JSONStringNode,
{keyName:key,value:value,key:aKey, parents,fetch} )
} else if (nodeType === 'Number') {
theNode = E(JSONNumberNode, {keyName:key,value:value,key:aKey, parents, fetch,cor:cor} )
} else if (nodeType === 'Boolean') {
theNode = E(JSONBooleanNode, {keyName:key,value:value,key:aKey, parents, fetch} )
} else if (nodeType === 'Null') {
theNode = E(JSONNullNode, {keyName:key,value:value,key:aKey, parents, fetch} )
} else {
console.error("How did this happen?", nodeType);
}
return theNode;
};
/**
* Returns the type of an object as a string.
*
* @param obj Object The object you want to inspect
* @return String The object's type
*/
var objType = function (obj) {
var className = Object.prototype.toString.call(obj).slice(8, -1);
return className;
}
/**
* Mixin for stopping events from propagating and collapsing our tree all
* willy nilly.
*/
var SquashClickEventMixin = {
handleClick: function (e) {
e.stopPropagation();
}
};
/**
* Mixin for setting intial props and state and handling clicks on
* nodes that can be expanded.
*/
var ExpandedStateHandlerMixin = {
getDefaultProps: function () {
return {data:[], initialExpanded: false};
},
getInitialState: function () {
const keys=this.props.parents.slice();
keys.shift();
keys.push(this.props.keyName);
var close=keys.length;
if (this.props.autoopen) for (var i=0;i<keys.length;i++) {
if (keys[i]==this.props.autoopen[i]) {
close--;
} else break;
}
var expanded=this.props.initialExpanded || !close;
return {
expanded,
createdChildNodes: false
};
},
handleClick: function (e) {
e.stopPropagation();
this.setState({expanded: !this.state.expanded});
},
componentWillReceiveProps: function () {
// resets our caches and flags we need to build child nodes again
this.renderedChildren = [];
this.itemString = false
this.needsChildNodes= true;
}
};
/**
* Array node class. If you have an array, this is what you should use to
* display it.
*/
var JSONArrayNode = React.createClass({
mixins: [ExpandedStateHandlerMixin],
/**
* Returns the child nodes for each element in the array. If we have
* generated them previously, we return from cache, otherwise we create
* them.
*/
getChildNodes: function () {
var childNodes = [];
if (this.state.expanded && this.needsChildNodes) {
var len=this.props.data.length;
if (len>MAXNODES) len=MAXNODES;
const parents=this.props.parents.slice();
parents.push(this.props.keyName);
for (var i = 0; i < len; i += 1) {
childNodes.push(
grabNode(i, this.props.data[i], parents, this.props.fetch, this.props.autoopen,this.props.cor));
}
this.needsChildNodes = false;
this.renderedChildren = childNodes;
}
return this.renderedChildren;
},
/**
* flag to see if we still need to render our child nodes
*/
needsChildNodes: true,
/**
* cache store for our child nodes
*/
renderedChildren: [],
/**
* cache store for the number of items string we display
*/
itemString: false,
/**
* Returns the "n Items" string for this node, generating and
* caching it if it hasn't been created yet.
*/
getItemString: function () {
if (!this.itemString) {
var lenWord = (this.props.data.length === 1) ? ' Item' : ' Items';
this.itemString = this.props.data.length + lenWord;
}
return this.itemString;
},
render: function () {
var childNodes = this.getChildNodes();
var childListStyle = {
display: (this.state.expanded) ? 'block' : 'none'
};
var cls = "array parentNode";
cls += (this.state.expanded) ? " expanded" : '';
return (
E("li",{className:cls, onClick:this.handleClick},
E("label",{},this.props.keyName+":"),
E("span",{},this.getItemString()),
E("ol",{style:childListStyle},childNodes)
)
);
}
});
/**
* Object node class. If you have an object, this is what you should use to
* display it.
*/
var JSONObjectNode = React.createClass({
mixins: [ExpandedStateHandlerMixin],
/**
* Returns the child nodes for each element in the object. If we have
* generated them previously, we return from cache, otherwise we create
* them.
*/
getChildNodes: function () {
if (this.state.expanded && this.needsChildNodes) {
var obj = this.props.data;
var childNodes = [];
const parents=this.props.parents.slice();
parents.push(this.props.keyName);
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
childNodes.push( grabNode(k, obj[k],parents,this.props.fetch,this.props.autoopen,this.props.cor));
}
}
this.needsChildNodes = false;
this.renderedChildren = childNodes;
}
return this.renderedChildren;
},
/**
* Returns the "n Items" string for this node, generating and
* caching it if it hasn't been created yet.
*/
getItemString: function () {
if (!this.itemString) {
var obj = this.props.data;
var len = 0;
var lenWord = ' Items';
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
len += 1;
}
}
if (len === 1) {
lenWord = ' Item';
}
this.itemString = len + lenWord
}
return this.itemString;
},
/**
* cache store for the number of items string we display
*/
itemString: false,
/**
* flag to see if we still need to render our child nodes
*/
needsChildNodes: true,
/**
* cache store for our child nodes
*/
renderedChildren: [],
render: function () {
var childListStyle = {
display: (this.state.expanded) ? 'block' : 'none'
};
var cls = "object parentNode";
cls += (this.state.expanded) ? " expanded" : '';
return (
E("li", {className:cls,onClick:this.handleClick},
E("label",{},this.props.keyName+":"),
E("span",{},this.getItemString()),
E("ul",{style:childListStyle},
this.getChildNodes()
)
)
);
}
});
/**
* String node component
*/
const supportimages=["jpg","jpeg","png"];
const showimage=function(e){
e.target.src=e.target.dataset.src;
e.stopPropagation()
e.preventDefault();
}
const showsvg=function(e){
e.target.innerHTML=e.target.dataset.src;
e.stopPropagation()
e.preventDefault();
}
const resolveStyleConflict=function(svgcontent,id){
return svgcontent.replace(/st(\d+)/g,function(m,m1){
return "st"+id+"-"+m1;
})
}
const renderString=function(str,parents){
var fieldname="";
if (parents.length>2 ) {
fieldname=parents[parents.length-2];
}
var src="img/view-icon.png";
if (fieldname=="svg" || fieldname=="figure" || fieldname=="table") {
if (str.indexOf("svg")>-1) {
str=str.replace(/<!--.+?-->\r?\n?/g,"")
.replace(/<!DOCTYPE.+?>\r?\n/,"").replace(/<\?xml.+>\r?\n/,"");
str=resolveStyleConflict(str,Math.random().toString().substr(2));
return E("div",{style:{background:"gray"}, "data-src":str,onClick:showsvg},"view SVG");
}
} else if (supportimages.indexOf(fieldname)>-1) {
const data='data:img/'+fieldname+';base64,'+str;
if (str.length<4000) { //show small image immediately
return E("img",{src:data});
} else {
return E("img",{"data-src":data,src,onClick:showimage});
}
}
return str;
}
var JSONStringNode = React.createClass({
mixins: [SquashClickEventMixin],
render: function () {
return (
E("li", {className:"string itemNode"},
E("label",{},this.props.keyName+":"),
E("span",{},renderString(this.props.value,this.props.parents))
)
);
}
});
var JSONDeferNode = React.createClass({
mixins: [SquashClickEventMixin],
openNode(e){
const path=this.props.parents.slice();
path.shift();
path.push(this.props.keyName);
this.props.fetch(path);
},
render: function () {
return (
E("li", {className:"string itemNode",onClick:this.handleClick},
E("label",{},this.props.keyName+":"),
E("button",{onClick:this.openNode},"+")
)
);
}
});
/**
* Number node component
*/
var JSONNumberNode = React.createClass({
mixins: [SquashClickEventMixin],
getInitialState:function(){
return {text:''};
}
,getText:function(e){
var addr=e.target.innerHTML;
const r=this.props.cor.parseRange(addr);
if (!r)return;
if (r.start==r.end) {
addr+='-99';
}
this.props.cor.getText(addr,function(text){
this.setState({text:text.join("").substr(0,30)});
}.bind(this));
}
,render: function () {
var label=this.props.value;
var translated=this.props.cor?this.props.cor.stringify(this.props.value):"";
if (!parseInt(translated,10)) {
translated="";
} else translated=" "+translated;
return (
E("li", {className:"itemNode",
onClick:this.handleClick},
E("label",{},this.props.keyName+":"),
translated?E("span",{
title:this.props.value,className:"kpos",
onClick:this.getText},translated)
:E("span",{className:"number"},this.props.value),
E("span",{className:"ktext"},this.state.text)
)
);
}
});
/**
* Null node component
*/
var JSONNullNode = React.createClass({
mixins: [SquashClickEventMixin],
render: function () {
return (
E("li", {className:"null itemNode",onClick:this.handleClick},
E("label",{},this.props.keyName+":"),
E("span",{},"null")
)
);
}
});
/**
* Boolean node component
*/
var JSONBooleanNode = React.createClass({
mixins: [SquashClickEventMixin],
render: function () {
var truthString = (this.props.value) ? 'true' : 'false';
return (
E("li", {className:"boolean itemNode",onClick:this.handleClick},
E("label",{},this.props.keyName+":"),
E("span",{},truthString)
)
);
}
});
/**
* JSONTree component. This is the 'viewer' base. Pass it a `data` prop and it
* will render that data, or pass it a `source` URL prop and it will make
* an XMLHttpRequest for said URL and render that when it loads the data.
*
* You can load new data into it by either changing the `data` prop or calling
* `loadDataFromURL()` on an instance.
*
* The first node it draws will be expanded by default.
*/
var JSONTree = React.createClass({
fetch:function(path){
this.props.cor.get(path,data=>{
var storepoint=this.state.data;
for (var i=0;i<path.length;i++) {
if (i<path.length-1) {
storepoint=storepoint[path[i]]
} else {
storepoint[path[i]]=data;
}
}
this.setState({data:this.state.data,autoopen:path});
});
},
getInitialState:function(){
return {data:this.props.data};
},
componentWillReceiveProps(nextProps){
this.setState({data:nextProps.data});
},
render: function() {
var nodeType = objType(this.state.data);
var rootNode;
if (nodeType === 'Object') {
rootNode = E(JSONObjectNode,{ data:this.state.data, cor:this.props.cor,
keyName:"/", initialExpanded:true, parents:[], fetch:this.fetch,autoopen:this.state.autoopen} )
} else if (nodeType === 'Array') {
rootNode = E(JSONArrayNode,{ data:this.state.data, cor:this.props.cor,
initialExpanded:true, keyName:"(root)", parents:[], fetch:this.fetch,autoopen:this.state.autoopen});
} else {
console.error("How did you manage that?");
}
return (
E("ul",{className:"json_tree"},rootNode )
);
}
});
module.exports=JSONTree;<file_sep>/src/manual.js
module.exports={
"名稱":"Corpus Forge",
"版本":20170504,
"語法":{
"分頁":"pb"
},
"版本沿革":{
"20170320":"支援內嵌圖檔",
"20170321":"預載欄位gfields",
"20170415":"支援外部互文標記及svg",
"20170423":"顯示圖檔",
"20170426":"支援四種外部欄位",
"20170504":"Diacritics 正規化"
}
}<file_sep>/src/logger.js
const React=require("react");
const E=React.createElement;
const styles={
log:{color:"green"},
timestamp:{color:"silver"},
error:{color:"red"},
warn:{color:"orange"},
normal:{color:"green"},
container:{height:"95%",overflow:"auto"}
}
class Logger extends React.Component {
renderLog(_log,key){
const log=_log.slice();
var style=styles.normal;
var timestamp=log.shift();
if (styles[log[0]]) {
style=styles[log.shift()];
}
const logmessage=log.join(" ");
const ts=timestamp.toTimeString().substr(0,8);
return E("div",{key,style:styles.log},
E("span",{}," ",E("span",{style},logmessage)));
}
render(){
return E("div",{style:styles.container},
E("div",{style:styles.timestamp}
,new Date().toString().replace(/GMT.+/,"")
,",started at: "+this.props.starttime.toString().replace(/GMT.+/,"")),
this.props.logs.map(this.renderLog.bind(this))
);
}
}
module.exports=Logger;<file_sep>/README.md
# Corpus-Forge
==first time setup==
cd buildscript
ksana-bundle
react-bundle
cd ..
==start development==
npm start
==generate release bundle.js==
npm run build
double click index.html
==open corpus automatically with hash tag==
localhost/corpus-forge/#c=corpus-id
===debugging ksana core==
cd buildscript
ksana-bundle-debug.cmd<file_sep>/src/builder.js
var createWebCorpus=null
if (typeof KsanaCorpusBuilder!=="undefined") {
createWebCorpus=KsanaCorpusBuilder.createWebCorpus;
} else {
const KSANACORPUSBUILDER="ksana-corpus-builder";
createWebCorpus=require(KSANACORPUSBUILDER).createWebCorpus;
}
const start=function(files,logger,cb){
createWebCorpus(files,logger,function(err,corpus,written){
if (err) {
cb(err);
} else {
try{
logger(written +" unicode characters indexed.");
corpus.writeKDB(null,function(bloburl,size){
logger("ROM ready. "+size+" bytes");
cb(0,bloburl,corpus.id+".cor",size);
});
} catch(e){
cb(e.message||e);
}
}
});
}
module.exports={start}
/*
var composes=["第零編"],categories=[], groupid;
const capture=function(){return true;}
const on_compose_close=function(tag,closing,kpos,tpos){
const compose=this.popText();
composes.push(compose);
}
const fileStart=function(fn,i){
const at=fn.lastIndexOf("/");
console.log(fn)
fn=fn.substr(at+1);
groupid=fn.substr(0,fn.length-4);//remove .xml
}
const on_category_close=function(tag,closing,kpos,tpos){
const cat=this.popText();
this.putGroup(groupid+";"+(composes.length-1)+"@"+cat,kpos,tpos);
}
corpus.setHandlers(
{"類":capture,"編":capture},
{"類":on_category_close,"編":on_compose_close},
{fileStart}
);
*/ | 98bf82095ccada3bd5d4325b37d989ccf179457c | [
"JavaScript",
"Markdown"
]
| 10 | JavaScript | ksanaforge/corpus-forge | 35c8963554c7b27599ec09cdf03488be3563b8d5 | 5133a1aa6f476905cd762411b2b40cb3c3aa3be1 |
refs/heads/master | <repo_name>anuragrawat19/django_restframework<file_sep>/project-django/cry_pragati/cry_pragati/urls.py
"""cry_pragati URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from usermodel import views
urlpatterns = [
# for list of all the car brand and adding a new brand
url(r'^admin/', admin.site.urls),
# view a particular car brand
url(r'^carbrandlist/$', views.CarBrand.as_view()),
url(r'^carbrandlist/(?P<pk>[0-9]+)/$', views.CarBrandDetails.as_view()),
url(r'^carbrandlist/search/(?P<alpha_bet>\w+)/$', views.FetchCar.as_view()),
url(r'^employees_list/$', views.Employeeslist.as_view()),
url(r'^employees_details/$', views.Employeesdetails.as_view()),
url(r'^designations_list/$', views.DesignationList.as_view()),
url(r'^snippet_list/$', views.Snippet_list.as_view()),
url(r'^snippet_list/(?P<pk>[0-9]+)/$', views.Snippet_list.as_view()),
url(r'^person_tasks/$', views.UserTasklist.as_view()),
]
<file_sep>/project-django/cry_pragati/usermodel/models.py
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
# creating a Snipet model
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(
choices=LANGUAGE_CHOICES, default="python", max_length=100)
style = models.CharField(choices=STYLE_CHOICES,
default="friendly", max_length=100)
def __str__(self):
return self.title
class Meta:
ordering = ['created']
# Create your models here.
class Roles(models.Model):
name = models.CharField(unique=True, max_length=100, error_messages={
"message": "This role already exists "})
code = models.CharField(max_length=8, null=True, blank=True)
class Meta:
db_table = "roles"
verbose_name_plural = "Roles"
def __str__(self):
return "%s " % self.name
class UserRoles(models.Model):
user = models.OneToOneField(User)
role = models.OneToOneField(Roles)
class Meta:
db_table = "userrole"
verbose_name_plural = "UserRoles"
def __str__(self):
return "%s " % self.user
# --------------------------------------------------------------------------------
class Employees(models.Model):
employee_name = models.CharField(max_length=50, blank=False, null=False)
contact = models.BigIntegerField()
salary = models.BigIntegerField()
class Meta:
db_table = "employee"
verbose_name_plural = "Employees"
def __str__(self):
return "%s " % self.employee_name
class EmployeeDesignations(models.Model):
designation = models.OneToOneField(
Employees, on_delete=models.CASCADE, primary_key=True, related_name='designations')
designation_name = models.CharField(max_length=50)
class Meta:
db_table = "employeedesignation"
verbose_name_plural = "EmployeeDesignations"
def __str__(self):
return "%s " % self.designation_name
# -------------------------------------------------------------
# car brands model
class CarBrands(models.Model):
brandname = models.CharField(
max_length=50, null=True, blank=True, unique=True)
headquarters = models.CharField(max_length=100)
coustomer_no = models.BigIntegerField()
class Meta:
db_table = "carbrand"
verbose_name_plural = "Car's Brand"
def __str__(self):
return "%s " % self.brandname
# ---------------------------------------------------------------
# models having many-to-many field
class Students(models.Model):
name = models.CharField(max_length=50)
standard = models.CharField(max_length=50)
sport = models.ManyToManyField("Sports")
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "Students"
class Sports(models.Model):
sport_name = models.CharField(max_length=50)
class Meta:
verbose_name_plural = "Sports"
def __str__(self):
return self.sport_name
# --------------------------------------------------------------------------------
class Persons(models.Model):
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
email = models.EmailField(
max_length=70, unique=True, blank=True, null=True)
class Meta:
db_table = "persons"
verbose_name_plural = "Persons"
def __str__(self):
return self.firstname
STATUS = ((0, 'closed'), (1, 'open'))
class PersonTasks(models.Model):
taskname = models.CharField(max_length=60)
status = models.BigIntegerField(choices=STATUS, default=1)
startdate = models.DateField(auto_now_add=True)
finishdate = models.DateField(blank=True, null=True)
user = models.ForeignKey(
Persons, related_name="tasks", on_delete=models.CASCADE)
class Meta:
db_table = "tasks"
verbose_name_plural = "Person Tasks"
def __str__(self):
return self.taskname
<file_sep>/project-django/cry_pragati/usermodel/migrations/0003_auto_20190804_1049.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-08-04 10:49
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('usermodel', '0002_auto_20190804_1042'),
]
operations = [
migrations.AlterField(
model_name='persontasks',
name='finishdate',
field=models.DateField(blank=True, null=True),
),
migrations.AlterField(
model_name='persontasks',
name='startdate',
field=models.DateField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AlterField(
model_name='persontasks',
name='status',
field=models.BigIntegerField(choices=[(0, 'closed'), (1, 'open')], default=1),
),
]
<file_sep>/project-django/cry_pragati/usermodel/serializer.py
'''writing a serializer for the models so that
state of model objects can be converted into a
native python datatypes that can be easily rendered into JSON,XML'''
from rest_framework import serializers
from .models import CarBrands, EmployeeDesignations, Employees, Snippet, LANGUAGE_CHOICES, STYLE_CHOICES, Persons, PersonTasks
# creating a serializer for Snippet model
# SnippetSerializer using 'serializers'
class SnippetSerializerA(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(max_length=100)
code = serializers.CharField(style={'base_template': 'textarea.html'})
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(
choices=LANGUAGE_CHOICES, default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
def create(self, validate_data):
'''create and return a new Snippet'''
return Snippet.objects.create(**validate_data)
def update(self, instance, validate_data):
''' Update and return an existing snippet'''
instance.title = validate_data.get('title', instance.title)
instance.code = validate_data.get('code', instance.code)
instance.linenos = validate_data.get('linenos', instance.linenos)
instance.language = validate_data.get('language', instance.language)
instance.style = validate_data.get('style', instance.style)
instance.save()
return instance
# SnippetSerializer using 'ModelSerializer'
class SnippetSerializerB(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = "__all__"
# creating a serializer for Roles Model
class CarBrandsSerializer(serializers.ModelSerializer):
class Meta:
model = CarBrands
fields = '__all__'
# creating serializer for list of all the names of employee in Employees Model
class EmployeeNameSerializer(serializers.ModelSerializer):
class Meta:
model = Employees
fields = ["employee_name"]
# creating a serialzer for getting details of all the employees
class EmpDetailSerializer(serializers.ModelSerializer):
def length(self, value):
if len(value) != 10:
raise serializers.ValidationError(
" contact should contain 10 digits only")
designations = serializers.SlugRelatedField(
slug_field="designation_name", read_only=True)
employee_name = serializers.CharField(max_length=50)
contact = serializers.CharField(validators=[length])
# validation for employee_name field that it should contain mr or mrs
def validate_employee_name(self, value):
a = "mr"
if a not in value.lower():
raise serializers.ValidationError(
'this employee name should contain Mr or Mrs')
return value
class Meta:
model = Employees
fields = "__all__"
class EmployeeDesignationsSerializer(serializers.Serializer):
designation_name = serializers.CharField(
required=True, allow_blank=False, max_length=100)
def create(self, validate_data):
'''create and return a new Snippet'''
return EmployeeDesignations.objects.create(**validate_data)
def update(self, instance, validate_data):
''' Update and return an existing snippet'''
instance.designation_name = validate_data.get(
'designaion_name', instance.designation_name)
instance.save()
return instance
# ------------------------------------------------------------------------------------------------------------------------------------------------
class PersonSerializer(serializers.ModelSerializer):
opentasks = serializers.SerializerMethodField("open_task")
def open_task(self, user):
return len(user.tasks.filter(status=1))
class Meta:
model = Persons
fields = "__all__"
<file_sep>/project-django/cry_pragati/usermodel/admin.py
from django.contrib import admin
from usermodel.models import (
Roles,
UserRoles,
CarBrands,
Employees,
EmployeeDesignations,
Students,
Sports,
Snippet,
Persons,
PersonTasks
)
# Register your models here.
admin.site.register(Roles)
admin.site.register(UserRoles)
admin.site.register(CarBrands)
admin.site.register(Employees)
admin.site.register(EmployeeDesignations)
admin.site.register(Students)
admin.site.register(Sports)
admin.site.register(Snippet)
admin.site.register(Persons)
admin.site.register(PersonTasks)
<file_sep>/project-django/cry_pragati/usermodel/views.py
from django.shortcuts import render, get_object_or_404
from rest_framework import status
from django.http import HttpResponse, JsonResponse
# importing the models
from .models import CarBrands, Employees, EmployeeDesignations, Snippet, Persons, PersonTasks
# importing a APIView class based views from rest_framwork
from rest_framework.views import APIView
from rest_framework.response import Response
# for serializing the objects into json form
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from .serializer import * # importing the serializer for each models
from rest_framework.decorators import api_view
# Create your views here.
# creating a view for the Snippet model
class Snippet_list(APIView):
'''List all snippets,or create a new snippet'''
def get(self, request):
snipets = Snippet.objects.all()
seriliazer_class = SnippetSerializerA(snipets, many=True)
return Response({"Snippet_details": seriliazer_class.data})
def post(self, request): # for adding a snippet
seriliazer_class = SnippetSerializerA(data=request.data)
if seriliazer_class.is_valid():
seriliazer_class.save()
return Response({"status": "snippet sucessfully created"}, status=201)
else:
return Response(seriliazer_class.errors)
def put(self, request, pk):
snippet = Snippet.objects.get(pk=pk)
serializer_class = SnippetSerializerA(snippet, request.data)
if serializer_class.is_valid():
serializer_class.save()
return Response("existing snipet of id {} is modified".format(serializer_class.data["id"]))
else:
return Response(serializer_class.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk):
try:
snippet = Snippet.objects.get(pk=pk)
snippet.delete()
return Response("snnipet with id {} is deleted".format(pk))
except Snippet.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
# creating a view for rendering a data of the Car Brands Model
class CarBrand(APIView):
def get(self, request): # for getting a list of all the car models
CarBrand = CarBrands.objects.all()
serialize_class = CarBrandsSerializer(CarBrand, many=True)
return Response({"CarBrands": serialize_class.data})
def post(self, request): # for adding a new car brand
serializer = CarBrandsSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({"status": 2, "message": "Sucessfully created"})
else:
return Response({"status": 0, "error-message": "errors"})
class CarBrandDetails(APIView):
def get(self, request, pk):
state = CarBrands.objects.get(pk=pk)
serializer = CarBrandsSerializer(state)
return Response(serializer.data)
class FetchCar(APIView):
def get(self, request, alpha_bet):
car = CarBrands.objects.filter(brandname__icontains=alpha_bet)
if len(car) == 0:
return Response({"Oops!": "No such car brand is available"})
else:
serializer_class = CarBrandsSerializer(car, many=True)
return Response(serializer_class.data)
class Employeeslist(APIView):
def get(self, request):
Employee = Employees.objects.all()
serialize_class = EmployeeNameSerializer(Employee, many=True)
return Response(serialize_class.data)
# view for the employees details and for adding a new employee
class Employeesdetails(APIView):
def get(self, request):
Employee = Employees.objects.all()
serialize_class = EmpDetailSerializer(Employee, many=True)
return Response(serialize_class.data)
def post(self, request):
serializer_class = EmpDetailSerializer(data=request.data)
if serializer_class.is_valid(raise_exception=True):
serializer_class.save()
return Response("New employee {} is added".format(serializer_class.data["employee_name"]))
else:
return Response(serializer_class.errors, status=status.HTTP_400_BAD_REQUEST)
# view for the list of all the designation and for adding a new employee designation
class DesignationList(APIView):
def get(self, request):
desination = EmployeeDesignations.objects.values(
"designation_name").distinct()
serialize_class = EmployeeDesignationsSerializer(desination, many=True)
return Response({"list of all the designations that this company has": serialize_class.data})
def post(self, request):
serializer_class = EmployeeDesignationsSerializer(data=request.data)
if serializer_class.is_valid():
serializer_class.save()
return Response("New designation {} is added".format(serializer_class.data["designation"]))
# designation_id=request.data.get("designation")
# designation=request.data.get("designation_name")
# new_designation=EmployeeDesignations.objects.create(designation_id=designation_id,designation=designation)
class UserTasklist(APIView):
def get(self, request):
details = Persons.objects.all()
serializer_class = PersonSerializer(details, many=True)
return Response({"person tasks": serializer_class.data})
| 847a723f8cb3194e3893cece4b20bd7aa072cffd | [
"Python"
]
| 6 | Python | anuragrawat19/django_restframework | b1141f3f857d0541808694f92184a6458d5a5d2c | 369baa4250b86b45e61cc82686c09f66098f769b |
refs/heads/master | <file_sep>class Set(object):
def __init__(self):
self.set = []
def __str__(self):
self.set.sort()
return '{' + ', '.join([str(e) for e in self.set]) + '}'
def insert(self, e):
if e not in self.set:
self.set.append(e)
def member(self, e):
return e in self.vals
def remove(self, e):
try:
self.set.remove(e)
except:
raise ValueError(str(e) + ' not found')
a = Set()
a.insert(0)
a.insert(1)
a.insert(2)
print a
a.remove(3)
<file_sep>class Coordinate(object):
foobar = 5
def __init__(self, x, y):
try:
self.x = x
self.y = y
assert type(self.x) == int and type(self.y) == int
except AssertionError:
print '__init()__ only accepts integer arguments.'
def __str__(self):
return '('+str(self.x)+','+str(self.y)+')'
def get_displacement(self, coordinate):
return ((coordinate.x - self.x)**2+(coordinate.x - self.x)**2)**0.5
def get_magnitude(self):
return (self.x**2 + self.y**2)**0.5
p1 = Coordinate(1, 1)
p2 = Coordinate(10, 11)
print p1
print p2
print p1.get_displacement(p2)
<file_sep>class Queue(object):
def __init__(self):
self.vals = []
def insert(self, e):
self.vals.append(e)
def remove(self):
try:
return self.vals.remove(self.vals[0])
except:
raise ValueError(str(e) + ' not in queue.')
| c89d4208f1a126feb33f8da00557aaa6529d037e | [
"Python"
]
| 3 | Python | sprody/glowing-goggles | c49ed34fef68f22958e474964dd17d3c84aa47d8 | e7f81ffd09222734844b975e601c6efa95c417fe |
refs/heads/master | <repo_name>klagan/web-samples-appconfig<file_sep>/readme.md
# Introduction
This is an ASPNETCore sample of using Azure App Configuration.
This sample assumes comfort using Terraform CLI to build the associated infrastructure.
In short:
- ensure Terraform is installed/available
- navigate to the `terraform` folder in a CLI
- run `terraform init`
- run `terraform plan`
- run `terraform apply`
This should be enough to build the associated infrastructure. To tear down the associated infrastructure navigate to the `terraform` folder and run `terraform destroy`
The terraform script will:
- create resource group
- create app configuration
- add sample entries into the app configuration
The terraform script will output
- a command to add the app configuration connection string to the local user secrets
The `add_connectionstring_to_usersecret_manager` output by the terraform command should be run in the aspnetcore code folder.
It will add the app configuration connection string to the local user secrets and appear similar to:
```cli
dotnet user-secrets set ConnectionStrings:AppConfig <connectionstring>
```
Now the application will able to use this local variable to connect to the app configuration and pull the variables.
The app configuration key-value labels are used to illustrate the ability to load the same key with different values based on the label.
---
## Feature management
#### Tag helper
Add the following includes to the page:
```csharp
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Microsoft.FeatureManagement.AspNetCore
```
Then you can use the `feature` tag:
```html
<feature name="BetaFeature">
<h3>Beta feature enabled</h3>
</feature>
```
> (See the example in `views\home\index.cshtml`)
#### Controller/Action
Add this attribute to an action or controller to enable or disable it. 404 is returned if the feature is turned off and and attempt to access the action/controller made
```csharp
[FeatureGate("BetaFeature")]
```
#### Manual
Inject this object to a class:
```csharp
private readonly IFeatureManager _featureManager;
public HomeController(IFeatureManager featureManager)
{
_featureManager = featureManager;
}
```
Use the object to manage the feature:
```csharp
if (await _featureManager.IsEnabledAsync("BetaFeature"))
{
<do something>
}
```
---
## Project details
[Source 1](https://docs.microsoft.com/en-us/azure/azure-app-configuration/quickstart-aspnet-core-app?tabs=core3x)
<br>
[Source 2](https://docs.microsoft.com/en-us/azure/azure-app-configuration/howto-labels-aspnet-core)
<br>
[Source 3](https://dontcodetired.com/blog/post/Using-the-Microsoft-Feature-Toggle-Library-in-ASPNET-Core-(MicrosoftFeatureManagement))
Project requires the following packages:
```dotnetcli
dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore
dotnet add package Microsoft.FeatureManagement.AspNetCore
```
and it is good practice to use user secrets locally:
``` xml
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UserSecretsId>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</UserSecretsId>
</PropertyGroup>
```
You can add secrets to the locsal user secrets vault:
```dotnetcli
dotnet user-secrets set <key> <value>
```
---
<file_sep>/src/web-samples-appconfig/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
namespace web_samples_appconfig
{
public class Program
{
public static void Main(
string[] args
)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(
string[] args
) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureAppConfiguration((
hostingContext,
config
) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(options =>
options
.Connect(settings["ConnectionStrings:AppConfig"])
.UseFeatureFlags()
.Select(KeyFilter.Any, LabelFilter.Null) // load the un-labelled keys
.Select(KeyFilter.Any, "sample") // override with the keys labelled 'sample'
.Select(KeyFilter.Any,
hostingContext.HostingEnvironment
.EnvironmentName)); // override with keys labelled as the current environment
})
.UseStartup<Startup>();
});
}
} | 1ff99961ffa521c2b3a437c2b49d12e6a8956ffd | [
"Markdown",
"C#"
]
| 2 | Markdown | klagan/web-samples-appconfig | 7d745e52c3094afa0a169c0cc9ee880c894777a5 | fedb38233d1dcd9e1ff680181f1709ea9deee8b1 |
refs/heads/main | <repo_name>liambai/hodgkin-huxley<file_sep>/hh_euler.py
import numpy as np
import matplotlib.pyplot as plt
import math
def hh_euler(I, tmax, v, m_0, h_0, n_0):
"""
simulates the Hodgkin-Huxley model of an action potential
I - stimulus current in mA
tmax - max time value in ms
v - initial membrane potential
m_0 - initial value for m, the fraction of open sodium m-gates
h_0 - initial value for h, the fraction of open sodium h-gates
n_0 - initial value for n, the fraction of open potassium n-gates
"""
dt = 0.001
iterations = math.ceil(tmax/dt)
g_Na = 120
v_Na = 115
g_K = 36
v_K = -12
g_L = 0.3
v_L = 10.6
# Initializing variable arrays
t = np.linspace(0,tmax,num=iterations)
V = np.zeros((iterations,1))
m = np.zeros((iterations,1))
h = np.zeros((iterations,1))
n = np.zeros((iterations,1))
V[0]=v
m[0]=m_0
h[0]=h_0
n[0]=n_0
# Euler's method
for i in range(iterations-1):
curr_v = V[i] + 65
V[i+1] = V[i] + dt*(g_Na*m[i]**3*h[i]*(v_Na-(curr_v)) + g_K*n[i]**4*(v_K-(curr_v)) + \
g_L*(v_L-(curr_v)) + I)
m[i+1] = m[i] + dt*(a_M(curr_v)*(1-m[i]) - b_M(curr_v)*m[i])
h[i+1] = h[i] + dt*(a_H(curr_v)*(1-h[i]) - b_H(curr_v)*h[i])
n[i+1] = n[i] + dt*(a_N(curr_v)*(1-n[i]) - b_N(curr_v)*n[i])
return t, V
# alpha and beta functions for the gating variables
def a_M(v):
return 0.1*(25 - v)/(np.exp((25-v)/10) - 1)
def b_M(v):
return 4*np.exp(-1*v/18)
def a_H(v):
return 0.07*np.exp(-1*v/20)
def b_H(v):
return 1/(np.exp((30-v)/10) + 1)
def a_N(v):
return 0.01 * (10 - v)/(np.exp((10-v)/10) - 1)
def b_N(v):
return 0.125*np.exp(-1*v/80)
if __name__ == "__main__":
I_0 = [1, 5, 10, 25]
sub_pos = [(0,0),(0,1),(1,0),(1,1)]
fig, axs = plt.subplots(2, 2, constrained_layout=True)
for i in range(4):
t, V = hh_euler(I_0[i], 100, -65, 0.4, 0.2, 0.5)
pos = sub_pos[i]
axs[pos].plot(t, V)
axs[pos].set(xlabel='t (ms)', ylabel='V (mV)')
axs[pos].set_title(str(I_0[i]) + ' mV Stimulus Current')
axs[pos].set_ylim([-80, 40])
plt.suptitle('Membrane Potential vs. Time for Varying Stimulus Currents', fontsize=18)
plt.show()<file_sep>/README.md
# hodgkin-huxley
Python implementation of the hodgkin–huxley model
| 522a1adaf33820a08ed8f41daca4c889bf11fad3 | [
"Markdown",
"Python"
]
| 2 | Python | liambai/hodgkin-huxley | bfe640de252357d3776dd7ba5a2194b73e12a420 | f32ef4fc672193afbf2d1e37a289bb43873caf7f |
refs/heads/master | <repo_name>ShishirNanoty/Homework4<file_sep>/HW_4.py
myUniqueList = []
myLeftovers = []
print('Original',myUniqueList)
def addleftovers(rejected):
myLeftovers.append(rejected)
def additems(new):
val = False
if not new in myUniqueList:
myUniqueList.append(new)
val = True
else: addleftovers(new)
return val
while True:
x = input('Enter No:')
if x == 'done': break
y = additems(x)
print('Unique',myUniqueList,y)
print('Duplicates',myLeftovers)
print('Done!')
| cad14a33a991107339c9ff35a866ab98a0577b89 | [
"Python"
]
| 1 | Python | ShishirNanoty/Homework4 | 008b6cb4fe9d3869dfb9a24ae0361c54136a18ff | 5c2849774a0af4f6532447ec79c72fe183e11b5b |
refs/heads/master | <file_sep># Grunt the JavaScript Task Runner
- pre-existing static assets
- npm init
- touch Gruntfile.js
- npm install grunt-cli -g
- npm install grunt
- npm install grunt-contrib-concat --save
# Stylesheet Preprocessors
- npm install grunt-contrib-watch --save
- npm install grunt-contrib-less
- npm install grunt-contrib-copy --save
- npm install express --save-dev
- mkdir tasks
- touch tasks/server.js
- install the chrome live-reload extension
-- https://chrome.google.com/webstore/detail/livereload/jnihajbhpnppcggbcgedagnkighmdlei?hl=en
# Thinking about Dependency Management
## CoffeeScript
- npm install grunt-contrib-clean --save
- npm install grunt-contrib-uglify --save
- npm install grunt-open --save-dev
- npm install grunt-contrib-coffee --save
## Bower
- npm install -g bower
- touch .bowerrc
- bower init
- bower install angular#1.2.0-rc.3 --save
- bower install angular-route#1.2.0-rc.3 --save
- bower install base64js --save
- bower install jquery --save
- bower install underscore --save
- bower install https://github.com/searls/extend.js/releases/download/0.1.0/extend.js --save
# Precompiling Templates for MV*
## grunt-angular-templates
- npm install grunt-angular-templates --save
# Optimizing for Developer Happiness
## grunt-concat-sourcemap
- npm install grunt-concat-sourcemap --save
# Alternative Frameworks & Dependency Management Strategies
## Backbone, precompiling handlebars
- npm install grunt-contrib-handlebars --save
- rm -rf bower_modules
- bower install https://raw.github.com/testdouble/backbone-fixins/master/dist/backbone-fixins.js --save
- bower install backbone.stickit#0.6.2 --save
- bower install backbone#0.9.10 --save
- bower install underscore.string#2.3.0 --save
- bower install handlebars#1.0.0 --save
- bower install underscore#1.4.3 --save
- bower install jquery#1.8.2 --save
- bower install https://github.com/searls/extend.js/releases/download/0.1.0/extend.js --save
- bower install base64js --save
## CommonJS, A simple module format
- npm install grunt-browserify --save
- npm install coffeeify --save
## Yeoman
- cd yeoman-workflow
- npm install
- bower install
- grunt server
## Lineman
- cd lineman-workflow
- npm installl
- lineman
## Bonus: Grunt Contrib Imagemin
- cd grunt-workflow
- npm install grunt-contrib-imagemin --save
- grunt imagemin
<file_sep># My Lineman Application
- clone me
- npm install -g lineman
- npm install
- lineman run
<file_sep>/**
* 1. Learn Data Structure Concept
* - Draw it
* - Create the API/operations methods
* 2. Build the Data Structure
* - Pseudocode the implementation
* - Code the data structure constructor
* 3. Utilize the Data Structure
* - Put your data structure to work!
* - Pair it with an algorithm if needed
* 4. Understand the Data Structure
* - What is the time complexity? (coming soon)
* - How can you optimize
*
* To test this? Ask yourself - for instance - oh! I know how to do hashmaps!
* if you can parse your idea through all of these steps, you're good.
*
* Concept: Stacks - "LIFO - last in first out, all you can do is push and pop
*
* Diagram: Stacks - example is the call stack
*
*/
var makeBacon = function(style, n) {
};
var makeEggs = function(style, n) {
var completedEgg;
if (style !== "boiled") {
var crackedEggs = crackEggs(n);
if (style !== "scrambled") {
completedEgg = fryEgg(crackedEggs, style)
} else {
var preppedEggs = whipEggs(crackedEggs);
completedEgg = fryEgg(preppedEggs)
}
}
//... other procedures here
return completedEgg;
};
makeEggs('scrambled', 3);
makeBacon('crispy', 2);<file_sep>window.onload = function() {
Building.prototype.countFloors = function() {
console.log("I have", this.floors, 'floors');
};
function Building(floors) {
//via prototying, creates an empty object that you can start building on.
this.what = "building";
this.floors = floors;
return this;
}
const myHouse = new Building(3);
const myOffice = new Building(8);
myHouse.countFloors();
myOffice.countFloors();
//The results of the shared method depend on the unique instance values which
//are created at call-time inside each function's scope.
//NOTE: There are several methods of creating classes in JavaScript.
//Pseudoclassical is the industry standard and is expected knowledge in an interview
//You may see elements of this style in your favorite JS framework.
};<file_sep>self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, false);
function recieveMessage(evt) {
// do we want to use the origin property?
// if (evt.origin !== "www.somedomain.com") {
// return;
// }
//
var d = evt.data;
var name="";
if(d.hasOwnProperty('name')) {
name = d.name;
switch (name) {
case 'state_data' :
handleSetState(d);
break;
case 'done_click' :
handleDoneBtnClick(d);
break;
case 'display_popup' :
handleMove(d);
break;
default :
handleError(d);
break;
};
}
}
function handleMove(d) {
$widget_id.show();
console.log( 'handle move' );
}
function handleSetState(stateObj) {
//set up the widget to show the state
$widget_id.show();
handshake_complete = true;
};
function handleDoneBtnClick(d) {
//return the Learner response and any useful feeback data
var return_obj = {
"cmi_interaction_status" : learner_response
};
console.log("return Learner Response" + return_obj.cmi_interaction_status );
window.parent.postMessage( return_obj , '*');
};
function handleError(d) {
console.log('Something went wrong...');
};
<file_sep>fem-grunt-workflow
==================
A custom app workflow to teach people how to use Grunt.js
## Getting Started
Pre-requisites:
1. [Node.JS](http://www.nodejs.org)
2. NPM (which comes with Node)
3. some kind of text editor, I use [Sublime Text](http://www.sublimetext.com/2), feel free to use what you feel most comfortable with :)
4. git installed on your machine (if you are on Linux or Mac, this should be fairly straightforward, Windows users you should install http://msysgit.github.io/)
5. (optional) I use a number of aliases in my shell configuration to make working with git easier, feel free to yoink them into yours if you want to: https://gist.github.com/davemo/5329141#file-gitconfig
6. (optional) [git-crawl](https://github.com/magnusstahre/git-stuff): I'll be using this to "crawl" through a commit history for the project we are working on, this makes it much easier to move through commits than having to manually stash and checkout
7. (optional) [rowanj's fork of GitX for OSX](http://rowanj.github.io/gitx/), is a nice Git GUI client, but totally optional; if you have another Git GUI client feel free to use that. (Windows users, https://code.google.com/p/gitextensions/ looks about equivalent).
Alternatively, if you don't want to work on your own machine and would prefer to use a virtualized environment, you can signup for a free account on Nitrous.io, I tried it out the other day and it should work fine for the things we are going to be working on. This environment will come pre-installed with numbers 1 through 4 in the list above.
## Crawling with `next`, `prev` aliases
Put these aliases in your path for easy crawling :)
```shell
$ cat ~/bin/next
#!/usr/bin/env bash
git crawl pdc
```
```shell
$ cat ~/bin/prev
#!/usr/bin/env bash
git co HEAD^1
```
<file_sep>window.PearsonGL = window.PearsonGL || {};
window.PearsonGL.UIModule = window.PearsonGL.UIModule || {};
/*******************************************************************************
* Class: UI Keypad Module
* Description: An Author-able Keypad used in Successmaker to enable the Learner to make inputs with
* the keypad instead of their device keyboard.
* Any product can use the keypad. Use Successmaker Fluidlayout and section.json to copy the setup.
* Any gadget with inputs can use the keypad, but you will need to add that gadget's inputs here so that the
* keypad knows when to hide (blurred input), or show (focused input).
* It is only checking SB - see toggleKeypadVisibility
*
* @author <NAME>
*
******************************************************************************/
/**
* Constructor
*/
PearsonGL.UIModule.productConf = {};
PearsonGL.UIModule.keypadConf = {}
PearsonGL.UIModule.keypadConf.collapsed = false;
PearsonGL.UIModule.keypad = (function() {
var
//DOM refs
$the_page,
$keypad,
$keypad_handle,
$keypad_btns,
$keypad_toggle_collapse,
$storyboard,
//math symbol vars
division = '\xF7',
multiply ='\xD7',
toggle_pos_neg = '+/-', // overline = spacing overscore \u203E
var_x = '𝒙',//'𝒙', U+1D465 //doesn't show up on iPad - \u1D4CD - tried stringFromCharCode and a bunch of char codes - nothing seems to work.
var_y = '𝒚', // U+1D466
less_than ='\x3C',
greater_than ='\x3E',
equal = "=",
decimal = ".",
subtract = "\u2212",
add = "\u002B",
paren_left = "\u0028",
paren_right = "\u0029",
//U+1D46x \u1d464
eventObj = {}, //an object containing keypad values that get passed in the trigger event so that a gadget can handle it.
buttonId, // these keypad buttons have a descriptive id
dataId, // this is the button gadget id that is used as a key input on the keypad
$dragBounds = $(document),
x2 = ($dragBounds.width() - 60), /* @ half the width of a small keypad*/
y2 = ($dragBounds.height() - 100), /* @ 1/3 the height of a small keypad*/
/**
* publicly accessible
*/
exports = {
init: init,
getMathSymbol : getMathSymbol
};
//END VARS
/**
* return the public api (exports)
*/
return exports;
function getMathSymbol(btnID){
var theMathSymbol = "";
switch (btnID) {
case 'kp-division' :
theMathSymbol = division;
break;
case 'kp-multiply' :
theMathSymbol = multiply;
break;
case 'kp-toggle-pos-neg' :
theMathSymbol = toggle_pos_neg;
break;
case 'kp-less-than' :
theMathSymbol = less_than;
break;
case 'kp-greater-than' :
theMathSymbol = greater_than;
break;
case 'kp-var-x' :
theMathSymbol = var_x;
break;
case 'kp-var-y' :
theMathSymbol = var_y;
break;
case 'kp-equal' :
theMathSymbol = equal;
break;
case 'kp-decimal' :
theMathSymbol = decimal;
break;
case 'kp-subtract' :
theMathSymbol = subtract;
break;
case 'kp-add' :
theMathSymbol = add;
break;
case 'kp-paren-left' :
theMathSymbol = paren_left;
break;
case 'kp-paren-right' :
theMathSymbol = paren_right;
break;
case 'kp-delete' :
theMathSymbol = "delete";
break;
}
return theMathSymbol;
};
/**
* initialize - manage DOM elements and other vars used by this component.
* @param opts - all the options you set up when the page loads.
*/
function init(opts) {
$the_page = $(opts.the_page);
$keypad = $the_page.find( ".ui-keypad" );
$keypad_handle = $keypad.find('.ui-keypad-handle');
$keypad_btns = $keypad.find(".keypad-button");
$keypad_toggle_collapse = $keypad.find(".ui-keypad-toggle-collapse");
$storyboard = $the_page.find( ".storyboard-identifier" );
$keypad.hide();
makeKeypad();
/**
* reset the bounds if the window is resized.
*/
$( window ).resize(function() {
if($keypad.length > 0){
x2 = ($dragBounds.width() - ($keypad.width()/2));
y2 = ($dragBounds.height() - $keypad_handle.height());
$keypad.draggable({
containment: [-100, 0, x2, y2 ]
});
}
});
/**
* creates the keypad button events, adds jquery ui for draggable and accordion
*/
function makeKeypad(){
// jquery.ui.draggable to drag the keypad window boundaries
// should be draggable 50% on both sides and up to the header at the bottom of the window
x2 = ($dragBounds.width() - ($keypad.width()/2));
y2 = ($dragBounds.height() - $keypad_handle.height());
/**
* add jquery ui capabilities like draggable and accordion
* @param isActive - accordion property for whether or not the keypad loads in the collapsed state
*/
(function addJQueryUIElements(isActive){
$keypad.draggable({
handle: $keypad_handle,
containment: [-100, 0, x2, y2 ]
});
$keypad.accordion({
header: $keypad_toggle_collapse,
autoHeight: true,
heightStyle: "content",
collapsible: true,
animate: {
easing: "swing",
duration: "200"
}
});
})();
// loop over all the buttons and use unicode/hex values for math symbols.
// the button gadget text label is not using a richtext, so you can't author MathML.
var btnLen = $keypad_btns.length;
var mathSymbol = "";
var btnLabel = $();
for(var i=0; i < btnLen; i++){
var $key_btn = $($keypad_btns[i]);
var btnId = $key_btn.attr('id');
btnLabel = $key_btn.find('.button-text');
if(btnId === "kp-division" || btnId === "kp-multiply" || btnId === "kp-toggle-pos-neg" ||
btnId === "kp-less-than" || btnId === "kp-greater-than" || btnId === "kp-var-x" || btnId === "kp-var-y" || btnId === "kp-delete"){
mathSymbol = getMathSymbol(btnId);
//handle the delete key.
if(btnId!=="kp-delete") {
btnLabel.text(mathSymbol);
}
}
};
//remove default button gadget click events - just using accessibility highlighting.
//events are click for text buttons, mouse-up for image buttons -
$keypad_btns.find("*").off("click mouseup keyup");
var btnId = $(this).attr('id');
var keyVal = "";
var newVal = "";
/**
* custom keypad button click event
* fireEvent to the window along with useful data
* used when click and key-up events occur.
*/
$keypad_btns.on("click" , function(e){
e.preventDefault();
btnId = $(this).attr('id');
keyVal = btnId.substr(3);// key values are 0-9 and some basic math symbols like divide, plus, multiply
//if the 4th item is a letter and not a number, it's a Math symbol. Gets the symbol.
var iD_val = btnId.substr(3, 1);
var isNumber = isFinite(iD_val);
if(btnId.indexOf(0, 4)){
if(!isNumber){
mathSymbol = getMathSymbol(btnId);
keyVal = mathSymbol;
}
};
eventObj = {
type: "keypadPress",
buttonId : btnId,
dataId : $(this).attr('data-id'),
keyVal : keyVal
}
console.log("BUTTON CLICK: BUTTON ID " + eventObj.buttonId + " " + eventObj.keyVal);
$(this).trigger(eventObj);
}).keyup(function (e) {
if (e.keyCode === PearsonGL.utils.keyCode.tab) {
PearsonGL.utils.focusItemOn(this);
} else if(e.keyCode === PearsonGL.utils.keyCode.enter) {
e.preventDefault();
btnId = $(this).attr('id');
keyVal = btnId.substr(3);
//if the 4th item is a letter and not a number, it's a Math symbol. Gets the symbol.
var iD_val = btnId.substr(3, 1);
var isNumber = isFinite(iD_val);
if(btnId.indexOf(0, 4)){
if(!isNumber){
mathSymbol = getMathSymbol(btnId);
keyVal = mathSymbol;
}
};
eventObj = {
type: "keypadPress",
buttonId : btnId,
dataId : $(this).attr('data-id'),
keyVal : keyVal
}
//console.log("TABBED KEYUP: BUTTON ID " + eventObj.buttonId + " " + eventObj.keyVal);
$(this).trigger(eventObj);
}
}).blur(function () {
PearsonGL.utils.focusItemOff(this);
});
$keypad.show();
};
function showKeypad(focusedInput){
var x_pos = focusedInput.offset().left + focusedInput.width() + 20;
var y_pos = focusedInput.offset().top;
$keypad.css({
bottom: "auto",
right: "auto",
left: x_pos,
top: y_pos
});
$keypad.show();
};
/**
* close the keypad if the mouse downs outside....
* check accessibility rules - close box vs click outside to close box.
*/
// $( document ).on( "mousedown", function(e) {
//
// if(e.pageY > 180 || e.pageX > 600){
//
// if ($keypad.is(':visible')
// && !$keypad.is(event.target) && !$keypad.has(event.target).length) {
// $keypad.hide();
// }
// }
// });
/**
* Keypad is used with SB inputs.
* Find the inputs, if the input is focused, show the keypad
*/
function toggleKeypadVisibility(){
//get the text inputs from SB, and check when they get focus
var inputs = $storyboard.find('.enabled.sbinput');
if(inputs && inputs.length > 0){
var focusedInput = $();
var blurredInput = $();
var currentInputID = "";
var blurredInputID = "";
if(inputs.length > 0){
//show the keypad
$(inputs).on( "focus", function(e){
currentInputID = $(this).attr('data-element');
currentInput = focusedInput = $(this);
showKeypad($(this));
});
//hide the keypad
$(inputs).on( "blur", function(){
blurredInput = $(this);
blurredInputID = $(this).attr('data-element')
if(blurredInputID !== currentInputID){
$keypad.hide();
}
});
};
}
};
};
})();
$(document).ready(function(){
//pages.js dispatches PageShowEvent trigger - update the nav selected state each time the page loads.
$(this).on("PageShowEvent", function(e, data){
//scope all gadget dom refs to the visible page...
var $the_page = $('body').find('.page:not(.hidden-page)');
PearsonGL.UIModule.keypad.init({
the_page : $the_page
});
});
});<file_sep>// https://github.com/searls/extend.js
(function(_) {
var makeExtender = function(top) {
return function(name,value) {
var ancestors = name.split('.'),
leaf = ancestors.pop(),
parent = resolveAncestors(ancestors,top);
verifyDistinctness(name,value,parent[leaf]);
if(isExtensible(parent[leaf],value)) {
_(parent[leaf]).extend(value);
} else if(arguments.length > 1) {
parent[leaf] = value;
}
return parent[leaf];
};
};
var isExtensible = function(existing,value) {
return existing && !_(value).isFunction() && !_(existing).isFunction();
};
var resolveAncestors = function(ancestors,top) {
return _(ancestors).reduce(function(ancestor,child) {
ancestor[child] = ancestor[child] || {};
return ancestor[child];
},top);
};
var verifyDistinctness = function(name,value,existing) {
if(_(existing).isFunction() && value && existing !== value) {
throw 'Cannot define a new function "'+name+'", because one is already defined.';
}
};
var originalExtend = window.extend;
window.extend = makeExtender(window);
window.extend.myNamespace = function(namespace) {
namespace.extend = makeExtender(namespace);
return namespace.extend;
};
window.extend.noConflict = function() {
var ourExtend = window.extend;
window.extend = originalExtend;
return ourExtend;
};
})(_);<file_sep>{
"name": "poc",
"version": "1.0.0",
"description": "ec1 grunt task manager",
"author": "<NAME>",
"private": true,
"devDependencies": {
"grunt": "^0.4.5",
"grunt-contrib-clean": "^0.6.0",
"grunt-contrib-concat": "^0.5.1",
"grunt-contrib-copy": "^0.8.0",
"grunt-contrib-jshint": "^0.11.0",
"grunt-contrib-qunit": "^0.5.2",
"grunt-contrib-uglify": "^0.8.0",
"grunt-contrib-watch": "*"
}
}
<file_sep>/**
* Interface: Stacks
*
* 1. Constructor Function
* - Storage
* 2. Methods
* - push(value) //adds value to the front, returns size of stack
* - pop() //removes value from front, returns size of stack
* - size() //returns size of stack as an integer
*/
var Stack = function() {
this.storage = ""; // our storage is a string to make it interesting
};
Stack.prototype.push = function(val) {
this.storage = this.storage.concat("***", val);
};
Stack.prototype.pop = function(val) {
//slice off the last chars up until ***
var str = this.storage.slice(this.storage.lastIndexOf("***") + 3);
//updating the new stack without the last item.
this.storage = this.storage.substring(0, this.storage.lastIndexOf("***"));
//return the last item
return str;
};
Stack.prototype.size = function(val) {
};
var myWeeklyMenu = new Stack();
myWeeklyMenu.push("RedBeans");<file_sep>var x = {
a: 1,
b: 2,
c: 4
};
var checkEslint = function(some, thing) {
return some * thing;
};
checkEslint(x.a, x.c);<file_sep>/**
* Concept: Queues
*
* The First item added Into the queue will be
* the First one taken Out of the queue.
*
* adding an item is enqued, removing one is dequeued
*
* FIFO -
*
* Interface: Queues
*
* 1. Constructor Function
* - Storage
* 2. Methods
* - enqueue(value) // adds value to the back, returns size
* - dequeue(value) // removes value from the front, returns value
* - size() //returns size of queue as an integer
*
*/ | c6738dfef7c1b0517a05fd7873ab5690e9cb6aaa | [
"Markdown",
"JSON",
"JavaScript"
]
| 12 | Markdown | erinmars/devWork | e53e85ac0bb4feaca7c23f1bd8ecc602308a69bb | fa79fcc0bed22e226259a9f6d2a2624ebfd344c4 |
refs/heads/master | <file_sep>from random import randint
print("BIENVENIDO AL CAMPEONATO DE CICLISMO")
#---------------Matriz 1
comp1=["Com 1","Com 2","Com 3","Com 4","Com 5","Com 6","Com 7","Com 8","Com 9","Com 10",]
etapas1=["Etapa 1: ","Etapa 2: ","Etapa 3: ","Etapa 4: ","Etapa 5: "]
matriz1 = []
#Generamos el tiempo aleatorio para los competidores
for i in range(5):
a=[0]*10
matriz1.append(a)
for j in range(10):
matriz1[i][j] = randint(0,20)
#Cabecera
cad2=" "
for i in range(10):
cad2+="\t"+comp1[i]
cad2+="\n\t\t----------------------------------------------"
print(cad2)
for i in range(5):
cad=etapas1[i]+"|\t"
for j in range(10):
cad+=str(matriz1[i][j])+"\t"
print(cad)
print("\n\t\t----------------------------------------------")
tiempo1 = 100
cadena1 = "Tiempo1:\t\t"
for j in range(10):
sumacolumna1 = 0
for i in range(5):
sumacolumna1 = sumacolumna1 + matriz1[i][j]
if sumacolumna1 < tiempo1:
tiempo1 = sumacolumna1
competidor1 = comp1[j]
cadena1+=str(sumacolumna1)+"\t"
print(cadena1+"\nCompetidor que gano en la etapa 1 es: "+ competidor1)
#----------------Matriz 2
comp2=["Com 1","Com 2","Com 3","Com 4","Com 5","Com 6","Com 7","Com 8","Com 9","Com 10",]
etapas2=["Etapa 1: ","Etapa 2: ","Etapa 3: ","Etapa 4: ","Etapa 5: "]
matriz2 = []
#Generamos el tiempo aleatorio para los competidores
for i in range(5):
a=[0]*10
matriz2.append(a)
for j in range(10):
matriz2[i][j] = randint(0,20)
#Cabecera
cad2=" "
for i in range(10):
cad2+="\t"+comp2[i]
cad2+="\n\t\t----------------------------------------------"
print(cad2)
for i in range(5):
cad=etapas2[i]+"|\t"
for j in range(10):
cad+=str(matriz2[i][j])+"\t"
print(cad)
print("\n\t\t----------------------------------------------")
tiempo2 = 100
cadena2 = "Tiempo2:\t\t"
for j in range(10):
sumacolumna2 = 0
for i in range(5):
sumacolumna2 = sumacolumna2 + matriz2[i][j]
if sumacolumna2 < tiempo2:
tiempo2 = sumacolumna2
competidor2 = comp2[j]
cadena2+=str(sumacolumna2)+"\t"
print(cadena2+"\nCompetidor que gano en la etapa 2 es: "+ competidor2)
#----------------Matriz 3
comp3=["Com 1","Com 2","Com 3","Com 4","Com 5","Com 6","Com 7","Com 8","Com 9","Com 10",]
etapas3=["Etapa 1: ","Etapa 2: ","Etapa 3: ","Etapa 4: ","Etapa 5: "]
matriz3 = []
#Generamos el tiempo aleatorio para los competidores
for i in range(5):
a=[0]*10
matriz3.append(a)
for j in range(10):
matriz3[i][j] = randint(0,20)
#Cabecera
cad2=" "
for i in range(10):
cad2+="\t"+comp3[i]
cad2+="\n\t\t----------------------------------------------"
print(cad2)
for i in range(5):
cad=etapas3[i]+"|\t"
for j in range(10):
cad+=str(matriz3[i][j])+"\t"
print(cad)
print("\n\t\t----------------------------------------------")
tiempo3 = 100
cadena3 = "Tiempo3:\t\t"
for j in range(10):
sumacolumna3 = 0
for i in range(5):
sumacolumna3 = sumacolumna3 + matriz3[i][j]
if sumacolumna3 < tiempo3:
tiempo3 = sumacolumna3
competidor3 = comp3[j]
cadena3+=str(sumacolumna3)+"\t"
print(cadena3+"\nCompetidor que gano en la etapa 3 es: "+ competidor3)
#----------------Matriz 4
comp4=["Com 1","Com 2","Com 3","Com 4","Com 5","Com 6","Com 7","Com 8","Com 9","Com 10",]
etapas4=["Etapa 1: ","Etapa 2: ","Etapa 3: ","Etapa 4: ","Etapa 5: "]
matriz4 = []
#Generamos el tiempo aleatorio para los competidores
for i in range(5):
a=[0]*10
matriz4.append(a)
for j in range(10):
matriz4[i][j] = randint(0,20)
#Cabecera
cad2=" "
for i in range(10):
cad2+="\t"+comp4[i]
cad2+="\n\t\t----------------------------------------------"
print(cad2)
for i in range(5):
cad=etapas4[i]+"|\t"
for j in range(10):
cad+=str(matriz4[i][j])+"\t"
print(cad)
print("\n\t\t----------------------------------------------")
tiempo4 = 100
cadena4 = "Tiempo4:\t\t"
for j in range(10):
sumacolumna4 = 0
for i in range(5):
sumacolumna4 = sumacolumna4 + matriz4[i][j]
if sumacolumna4 < tiempo4:
tiempo4 = sumacolumna4
competidor4 = comp4[j]
cadena4+=str(sumacolumna4)+"\t"
print(cadena4+"\nCompetidor que gano en la etapa 4 es: "+ competidor4)
#----------------Matriz 5
comp5=["Com 1","Com 2","Com 3","Com 4","Com 5","Com 6","Com 7","Com 8","Com 9","Com 10",]
etapas5=["Etapa 1: ","Etapa 2: ","Etapa 3: ","Etapa 4: ","Etapa 5: "]
matriz5 = []
#Generamos el tiempo aleatorio para los competidores
for i in range(5):
a=[0]*10
matriz5.append(a)
for j in range(10):
matriz5[i][j] = randint(0,20)
#Cabecera
cad2=" "
for i in range(10):
cad2+="\t"+comp5[i]
cad2+="\n\t\t----------------------------------------------"
print(cad2)
for i in range(5):
cad=etapas5[i]+"|\t"
for j in range(10):
cad+=str(matriz5[i][j])+"\t"
print(cad)
print("\n\t\t----------------------------------------------")
tiempo5 = 100
cadena5 = "Tiempo5:\t\t"
for j in range(10):
sumacolumna5 = 0
for i in range(5):
sumacolumna5 = sumacolumna5 + matriz5[i][j]
if sumacolumna5 < tiempo5:
tiempo5 = sumacolumna5
competidor5 = comp5[j]
cadena5+=str(sumacolumna5)+"\t"
print(cadena5+"\nCompetidor que gano en la etapa 5 es: "+ competidor5)
#----------------Matriz 6
comp6=["Com 1","Com 2","Com 3","Com 4","Com 5","Com 6","Com 7","Com 8","Com 9","Com 10",]
etapas6=["Etapa 1: ","Etapa 2: ","Etapa 3: ","Etapa 4: ","Etapa 5: "]
matriz6 = []
#Generamos el tiempo aleatorio para los competidores
for i in range(5):
a=[0]*10
matriz6.append(a)
for j in range(10):
matriz6[i][j] = randint(0,20)
#Cabecera
cad2=" "
for i in range(10):
cad2+="\t"+comp6[i]
cad2+="\n\t\t----------------------------------------------"
print(cad2)
for i in range(5):
cad=etapas6[i]+"|\t"
for j in range(10):
cad+=str(matriz6[i][j])+"\t"
print(cad)
print("\n\t\t----------------------------------------------")
tiempo6 = 100
cadena6 = "Tiempo6:\t\t"
for j in range(10):
sumacolumna6 = 0
for i in range(5):
sumacolumna6 = sumacolumna6 + matriz6[i][j]
if sumacolumna6 < tiempo6:
tiempo6 = sumacolumna6
competidor6 = comp6[j]
cadena6+=str(sumacolumna6)+"\t"
print(cadena6+"\nCompetidor que gano en la etapa 6 es: "+ competidor6)
#----------------Matriz 7
comp7=["Com 1","Com 2","Com 3","Com 4","Com 5","Com 6","Com 7","Com 8","Com 9","Com 10",]
etapas7=["Etapa 1: ","Etapa 2: ","Etapa 3: ","Etapa 4: ","Etapa 5: "]
matriz7 = []
#Generamos el tiempo aleatorio para los competidores
for i in range(5):
a=[0]*10
matriz7.append(a)
for j in range(10):
matriz7[i][j] = randint(0,20)
#Cabecera
cad2=" "
for i in range(10):
cad2+="\t"+comp7[i]
cad2+="\n\t\t----------------------------------------------"
print(cad2)
for i in range(5):
cad=etapas7[i]+"|\t"
for j in range(10):
cad+=str(matriz7[i][j])+"\t"
print(cad)
print("\n\t\t----------------------------------------------")
tiempo7 = 100
cadena7 = "Tiempo7:\t\t"
for j in range(10):
sumacolumna7 = 0
for i in range(5):
sumacolumna7 = sumacolumna7 + matriz7[i][j]
if sumacolumna7 < tiempo7:
tiempo7 = sumacolumna7
competidor7 = comp7[j]
cadena7+=str(sumacolumna7)+"\t"
print(cadena7+"\nCompetidor que gano en la etapa 7 es: "+ competidor7)
#----------------Matriz 8
comp8=["Com 1","Com 2","Com 3","Com 4","Com 5","Com 6","Com 7","Com 8","Com 9","Com 10",]
etapas8=["Etapa 1: ","Etapa 2: ","Etapa 3: ","Etapa 4: ","Etapa 5: "]
matriz8 = []
#Generamos el tiempo aleatorio para los competidores
for i in range(5):
a=[0]*10
matriz8.append(a)
for j in range(10):
matriz8[i][j] = randint(0,20)
#Cabecera
cad2=" "
for i in range(10):
cad2+="\t"+comp8[i]
cad2+="\n\t\t----------------------------------------------"
print(cad2)
for i in range(5):
cad=etapas8[i]+"|\t"
for j in range(10):
cad+=str(matriz8[i][j])+"\t"
print(cad)
print("\n\t\t----------------------------------------------")
tiempo8 = 100
cadena8 = "Tiempo8:\t\t"
for j in range(10):
sumacolumna8 = 0
for i in range(5):
sumacolumna8 = sumacolumna8 + matriz8[i][j]
if sumacolumna8 < tiempo8:
tiempo8 = sumacolumna8
competidor8 = comp8[j]
cadena8+=str(sumacolumna8)+"\t"
print(cadena8+"\nCompetidor que gano en la etapa 8 es: "+ competidor8)
#----------------Matriz 9
comp9=["Com 1","Com 2","Com 3","Com 4","Com 5","Com 6","Com 7","Com 8","Com 9","Com 10",]
etapas9=["Etapa 1: ","Etapa 2: ","Etapa 3: ","Etapa 4: ","Etapa 5: "]
matriz9 = []
#Generamos el tiempo aleatorio para los competidores
for i in range(5):
a=[0]*10
matriz9.append(a)
for j in range(10):
matriz9[i][j] = randint(0,20)
#Cabecera
cad2=" "
for i in range(10):
cad2+="\t"+comp9[i]
cad2+="\n\t\t----------------------------------------------"
print(cad2)
for i in range(5):
cad=etapas9[i]+"|\t"
for j in range(10):
cad+=str(matriz9[i][j])+"\t"
print(cad)
print("\n\t\t----------------------------------------------")
tiempo9 = 100
cadena9 = "Tiempo9:\t\t"
for j in range(10):
sumacolumna9 = 0
for i in range(5):
sumacolumna9 = sumacolumna9 + matriz9[i][j]
if sumacolumna9 < tiempo9:
tiempo9 = sumacolumna9
competidor9 = comp9[j]
cadena9+=str(sumacolumna9)+"\t"
print(cadena9+"\nCompetidor que gano en la etapa 9 es: "+ competidor9)
#----------------Matriz 10
comp10=["Com 1","Com 2","Com 3","Com 4","Com 5","Com 6","Com 7","Com 8","Com 9","Com 10",]
etapas10=["Etapa 1: ","Etapa 2: ","Etapa 3: ","Etapa 4: ","Etapa 5: "]
matriz10 = []
#Generamos el tiempo aleatorio para los competidores
for i in range(5):
a=[0]*10
matriz10.append(a)
for j in range(10):
matriz10[i][j] = randint(0,20)
#Cabecera
cad2=" "
for i in range(10):
cad2+="\t"+comp10[i]
cad2+="\n\t\t----------------------------------------------"
print(cad2)
for i in range(5):
cad=etapas10[i]+"|\t"
for j in range(10):
cad+=str(matriz10[i][j])+"\t"
print(cad)
print("\n\t\t----------------------------------------------")
tiempo10 = 100
cadena10 = "Tiempo10:\t\t"
for j in range(10):
sumacolumna10 = 0
for i in range(5):
sumacolumna10 = sumacolumna10 + matriz10[i][j]
if sumacolumna10 < tiempo10:
tiempo10 = sumacolumna10
competidor10 = comp10[j]
cadena10+=str(sumacolumna10)+"\t"
print(cadena10+"\nCompetidor que gano en la etapa 10 es: "+ competidor10)
print() | 0da4efe27cef3e8b1a707870bd0f2ae26daf589f | [
"Python"
]
| 1 | Python | CesarAdria21/TS2019 | 26e8c60f865d9494abab96507f640b0dc7d14428 | 5c5cd5cfce92977126b469672824533a98d7246b |
refs/heads/master | <repo_name>huangyoucai90/MPVUE-wxapp.service<file_sep>/src/main/java/com/wx/demo/service/WespaceService.java
package com.wx.demo.service;
import com.wx.demo.entity.Wecomment;
import com.wx.demo.entity.Wespace;
import com.wx.demo.entity.Weup;
import java.util.List;
public interface WespaceService {
List<Wespace> queryWespace();
List<Weup> queryUp(String userId);
boolean insertWespace(String microId, String microDes, String userId, String microTime, String userNickname, String userHead);
boolean deleteWespace(String microId);
boolean upWespace(String microId, String userId);
boolean downWespace(String microId, String userId);
boolean insertComment(String wecommentId, String userId, String userNickname, String wecommentContent, String microId);
boolean upJudge(String microId, String userId);
List<Wecomment> queryComment(String microId);
List<Wespace> queryHot();
List<Wespace> queryMy(String userId);
int queryCommentcount(String microId);
}
<file_sep>/src/main/java/com/wx/demo/service/impl/UserServiceImpl.java
package com.wx.demo.service.impl;
import com.wx.demo.dao.UserDao;
import com.wx.demo.entity.User;
import com.wx.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> queryUser() {
return userDao.queryUser();
}
@Override
public User getUserById(String userId, String userPassword) {
return userDao.queryUserById(userId, userPassword);
}
@Override
public boolean addUser(User user) {
return false;
}
@Transactional
@Override
public boolean updateUser(String userId, String userNickname, String userAcademy, String userQq, String userTelephone) {
int effectedNum = userDao.updateUser(userId, userNickname, userAcademy, userQq, userTelephone);
if (effectedNum > 0)
return true;
else
return false;
}
@Override
public boolean deleteUser(String userId) {
return false;
}
@Override
public boolean updatePassword(String userId, String userPassword) {
int effectedNum = userDao.updatePassword(userId, userPassword);
if(effectedNum > 0)
return true;
else
return false;
}
@Override
public boolean updateUserHead(String userId, String userHead) {
int effectedNum = userDao.updateHead(userId, userHead);
if(effectedNum > 0)
return true;
else
return false;
}
}
<file_sep>/src/main/java/com/wx/demo/entity/Marcomment.java
package com.wx.demo.entity;
public class Marcomment {
private String marcommentId;
private String userId;
private String userNickname;
private String marcommentContent;
private String marketId;
public String getMarcommentId() {
return marcommentId;
}
public void setMarcommentId(String marcommentId) {
this.marcommentId = marcommentId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserNickname() {
return userNickname;
}
public void setUserNickname(String userNickname) {
this.userNickname = userNickname;
}
public String getMarcommentContent() {
return marcommentContent;
}
public void setMarcommentContent(String marcommentContent) {
this.marcommentContent = marcommentContent;
}
public String getMarketId() {
return marketId;
}
public void setMarketId(String marketId) {
this.marketId = marketId;
}
}
<file_sep>/src/main/java/com/wx/demo/service/MarketService.java
package com.wx.demo.service;
import com.wx.demo.entity.Marcomment;
import com.wx.demo.entity.Market;
import com.wx.demo.entity.Marup;
import java.util.List;
public interface MarketService {
List<Market> queryMarket();
boolean insertMarket(String marketId, String marketTheme, String marketDes, String userId, String marketTime, String userNickname, String userHead);
boolean deleteMarket(String marketId);
boolean upMarket(String marketId, String userId);
boolean downMarket(String marketId, String userId);
boolean insertComment(String marcommentId, String userId, String userNickname, String marcommentContent, String marketId);
boolean upJudge(String marketId, String userId);
List<Marcomment> queryComment(String marketId);
List<Market> queryMy(String userId);
int queryCommentcount(String marketId);
boolean updateDeal(String marketId);
boolean updateNotDeal(String marketId);
}
<file_sep>/src/main/java/com/wx/demo/service/UserService.java
package com.wx.demo.service;
import com.wx.demo.entity.User;
import java.util.List;
public interface UserService {
List<User> queryUser();
User getUserById(String userId, String userPassword);
boolean addUser(User user);
boolean updateUser(String userId, String userNickname, String userAcademy, String userQq, String userTelephone);
boolean deleteUser(String userId);
boolean updatePassword(String userId, String userPassword);
boolean updateUserHead(String userId, String userHead);
}
<file_sep>/src/main/java/com/wx/demo/dao/MarketDao.java
package com.wx.demo.dao;
import com.wx.demo.entity.Marcomment;
import com.wx.demo.entity.Market;
import com.wx.demo.entity.Marup;
import java.util.List;
public interface MarketDao {
List<Market> queryMarket();
int insertMarket(String marketId, String marketTheme, String marketDes, String userId, String marketTime, String userNickname, String userHead);
int deleteMarket(String marketId);
int upMarket(String marketd);
int downMarket(String marketId);
int insertUp(String marketId, String userId, int upYes);
int deleteUp(String marketId, String userId);
int insertPicture(String marketId);
int insertComment(String marcommentId, String userId, String userNickname, String marcommentContent, String marketId);
List<Marup> upJudge(String marketId, String userId);
List<Marcomment> queryComment(String marketId);
List<Market> queryMy(String userId);
int queryCommentcount(String marketId);
int updateDeal(String marketId);
int updateNotDeal(String marketId);
}
<file_sep>/README.md
# MPVUE-wxapp.service
MPVUE-wxapp的后台代码,后端基于MYSQL+springboot
#前端
前端采用美团的Mpvue小程序框架。
前端地址:https://github.com/LMGO/MPVUE-wxapp.git
<file_sep>/src/main/java/com/wx/demo/entity/Wecomment.java
package com.wx.demo.entity;
public class Wecomment {
private String wecommentId;
private String userId;
private String userNickname;
private String microId;
private String wecommentContent;
public String getWecommentId() {
return wecommentId;
}
public void setWecommentId(String wecommentId) {
this.wecommentId = wecommentId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserNickname() {
return userNickname;
}
public void setUserNickname(String userNickname) {
this.userNickname = userNickname;
}
public String getMicroId() {
return microId;
}
public void setMicroId(String microId) {
this.microId = microId;
}
public String getWecommentContent() {
return wecommentContent;
}
public void setWecommentContent(String wecommentContent) {
this.wecommentContent = wecommentContent;
}
}
<file_sep>/src/test/java/com/wx/demo/dao/UserDaoTest.java
package com.wx.demo.dao;
import com.wx.demo.entity.User;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserDaoTest {
@Autowired
private UserDao userDao;
@Test
@Ignore
public void queryUser() {
List<User> userList = userDao.queryUser();
assertEquals(1, userList.size());
}
@Test
@Ignore
public void queryUserById() {
User user = userDao.queryUserById("20171120301", "123456789");
assertEquals("李岳哲", user.getUserName());
}
@Test
@Ignore
public void insertUser() {
}
@Test
public void updateUser() {
// User user = new User();
// user.setUserId("20171120301");
// user.setUserNickname("小磊");
// user.setUserQq("1114100345");
// user.setUserTelephone("18687251007");
// user.setUserAcademy("software engineering");
// int effectedNum = userDao.updateUser(user);
// assertEquals(1, effectedNum);
int effectNum = userDao.updateUser("20171120301", "小磊", "软件学院", "1114100345", "18687251007");
assertEquals(1, effectNum);
}
@Test
@Ignore
public void deleteUser() {
}
@Test
@Ignore
public void updatePassword() {
// User user = new User();
// user.setUserPassword("<PASSWORD>");
// user.setUserId("20171120301");
int effectedNum = userDao.updatePassword("<PASSWORD>", "<PASSWORD>");
assertEquals(1, effectedNum);
}
}<file_sep>/src/test/java/com/wx/demo/dao/LostandfoundDaoTest.java
package com.wx.demo.dao;
public class LostandfoundDaoTest {
}
<file_sep>/src/main/java/com/wx/demo/entity/Wespace.java
package com.wx.demo.entity;
import java.sql.Time;
import java.util.Date;
import java.util.List;
public class Wespace {
private String microId;
private String microPict;
private String microDes;
private String userId;
private String microTime;
private String userNickname;
private String userHead;
private boolean islike;
private List<Wecomment> wecomment;
private int microComm;
public boolean isIslike() {
return islike;
}
public void setIslike(boolean islike) {
this.islike = islike;
}
public String getUserHead() {
return userHead;
}
public void setUserHead(String userHead) {
this.userHead = userHead;
}
public int getMicroUp() {
return microUp;
}
public void setMicroUp(int microUp) {
this.microUp = microUp;
}
private int microUp;
public String getUserNickname() {
return userNickname;
}
public void setUserNickname(String userNickname) {
this.userNickname = userNickname;
}
public String getMicroId() {
return microId;
}
public void setMicroId(String microId) {
this.microId = microId;
}
public String getMicroPict() {
return microPict;
}
public void setMicroPict(String microPict) {
this.microPict = microPict;
}
public String getMicroDes() {
return microDes;
}
public void setMicroDes(String microDes) {
this.microDes = microDes;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getMicroTime() {
return microTime;
}
public void setMicroTime(String microTime) {
this.microTime = microTime;
}
public List<Wecomment> getWecomment() {
return wecomment;
}
public void setWecomment(List<Wecomment> wecomment) {
this.wecomment = wecomment;
}
public int getMicroComm() {
return microComm;
}
public void setMicroComm(int microComm) {
this.microComm = microComm;
}
}
| 1d329c84c4515b6570dc360c20832baa7e807eed | [
"Markdown",
"Java"
]
| 11 | Java | huangyoucai90/MPVUE-wxapp.service | 7dd4076b2a2d5eb5c24e77e07c0d214227302e27 | 7aae447a5e46df3a684ecb929840f605d02f7ca7 |
refs/heads/master | <repo_name>michealmouner/BatchEntityImportBundle<file_sep>/src/Model/Configuration/AbstractImportConfiguration.php
<?php
declare(strict_types=1);
namespace JG\BatchEntityImportBundle\Model\Configuration;
use Doctrine\ORM\EntityManagerInterface;
use JG\BatchEntityImportBundle\Model\Matrix\Matrix;
use JG\BatchEntityImportBundle\Model\Matrix\MatrixRecord;
use JG\BatchEntityImportBundle\Utils\ColumnNameHelper;
use Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface;
use Throwable;
abstract class AbstractImportConfiguration implements ImportConfigurationInterface
{
private EntityManagerInterface $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function getFieldsDefinitions(): array
{
return [];
}
public function import(Matrix $matrix): void
{
foreach ($matrix->getRecords() as $record) {
$this->prepareRecord($record);
}
$this->save();
}
protected function prepareRecord(MatrixRecord $record): void
{
$entity = $this->getEntity($record);
$data = $record->getData();
foreach ($data as $name => $value) {
$locale = ColumnNameHelper::getLocale($name);
$fieldName = ColumnNameHelper::underscoreToPascalCase($name);
try {
if ($entity instanceof TranslatableInterface && $locale) {
$entity->translate($locale)->{'set' . $fieldName}($value);
} elseif (!$locale) {
$entity->{'set' . $fieldName}($value);
}
} catch (Throwable $e) {
}
}
$this->em->persist($entity);
if ($entity instanceof TranslatableInterface) {
$entity->mergeNewTranslations();
}
}
protected function save(): void
{
$this->em->flush();
}
protected function getEntity(MatrixRecord $record): object
{
return $record->getEntity() ?: $this->getNewEntity($record);
}
/**
* Creates new entity object. Uses default constructor without any arguments.
* To use constructor with arguments, please override this method.
*/
protected function getNewEntity(MatrixRecord $record): object
{
$class = $this->getEntityClassName();
return new $class();
}
public function allowOverrideEntity(): bool
{
return true;
}
}
<file_sep>/src/Model/Matrix/Matrix.php
<?php
declare(strict_types=1);
namespace JG\BatchEntityImportBundle\Model\Matrix;
use const ARRAY_FILTER_USE_KEY;
use JG\BatchEntityImportBundle\Service\PropertyExistenceChecker;
use Symfony\Component\Validator\Constraints as Assert;
class Matrix
{
/**
* @Assert\NotBlank()
* @Assert\All({
* @Assert\NotBlank(),
* @Assert\Type("string"),
* @Assert\Regex(pattern="/^([\w]+)(:[\w]+)?$/", message="validation.matrix.header.name")
* })
*/
private array $header;
/**
* @var array|MatrixRecord[]
*
* @Assert\NotBlank()
* @Assert\All({
* @Assert\Type(MatrixRecord::class)
* })
*/
private array $records = [];
public function __construct(array $header = [], array $recordsData = [])
{
$this->header = $this->clearHeader($header);
foreach ($recordsData as $data) {
$data = $this->clearRecordData($data);
if ($data) {
$this->records[] = new MatrixRecord($data);
}
}
}
public function getHeader(): array
{
return $this->header;
}
/**
* @return array|MatrixRecord[]
*/
public function getRecords(): array
{
return $this->records;
}
public function getHeaderInfo(string $className): array
{
$info = [];
$checker = new PropertyExistenceChecker($className);
foreach ($this->header as $name) {
$info[$name] = $checker->propertyExists($name);
}
return $info;
}
private function clearHeader(array $header): array
{
return array_values(
array_filter($header, static fn ($e) => !empty(trim((string) $e)))
);
}
private function clearRecordData(array $data): array
{
return array_filter($data, static fn ($key) => !empty(trim((string) $key)), ARRAY_FILTER_USE_KEY);
}
}
<file_sep>/src/Controller/BaseImportControllerTrait.php
<?php
declare(strict_types=1);
namespace JG\BatchEntityImportBundle\Controller;
use Doctrine\ORM\EntityManagerInterface;
use InvalidArgumentException;
use JG\BatchEntityImportBundle\Form\Type\FileImportType;
use JG\BatchEntityImportBundle\Model\Configuration\ImportConfigurationInterface;
use JG\BatchEntityImportBundle\Model\FileImport;
use JG\BatchEntityImportBundle\Model\Matrix\Matrix;
use JG\BatchEntityImportBundle\Model\Matrix\MatrixFactory;
use JG\BatchEntityImportBundle\Model\Matrix\MatrixRecord;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Form\Exception\LogicException;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Traversable;
use UnexpectedValueException;
trait BaseImportControllerTrait
{
protected ?ImportConfigurationInterface $importConfiguration = null;
abstract protected function getImportConfigurationClassName(): string;
abstract protected function redirectToImport(): RedirectResponse;
abstract protected function getSelectFileTemplateName(): string;
abstract protected function getMatrixEditTemplateName(): string;
abstract protected function prepareView(string $view, array $parameters = []): Response;
abstract protected function createMatrixForm(Matrix $matrix, EntityManagerInterface $entityManager): FormInterface;
/**
* @throws InvalidArgumentException
* @throws \LogicException
*/
protected function doImport(Request $request, ValidatorInterface $validator, EntityManagerInterface $entityManager): Response
{
$fileImport = new FileImport();
/** @var FormInterface $form */
$form = $this->createForm(FileImportType::class, $fileImport);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$matrix = MatrixFactory::createFromUploadedFile($fileImport->getFile());
$errors = $validator->validate($matrix);
if (0 === $errors->count()) {
return $this->prepareMatrixEditView($matrix, $entityManager, true);
}
} else {
$errors = $form->getErrors();
}
$this->setErrorAsFlash($errors);
return $this->prepareSelectFileView($form);
}
protected function prepareSelectFileView(FormInterface $form): Response
{
return $this->prepareView(
$this->getSelectFileTemplateName(),
[
'form' => $form->createView(),
]
);
}
protected function prepareMatrixEditView(Matrix $matrix, EntityManagerInterface $entityManager, $manualSubmit = false): Response
{
$form = $this->createMatrixForm($matrix, $entityManager);
if ($manualSubmit) {
$form->submit(['records' => array_map(static fn (MatrixRecord $record) => $record->getData(), $matrix->getRecords())]);
}
return $this->prepareView(
$this->getMatrixEditTemplateName(),
[
'header_info' => $matrix->getHeaderInfo($this->getImportConfiguration($entityManager)->getEntityClassName()),
'data' => $matrix->getRecords(),
'form' => $form->createView(),
'importConfiguration' => $this->getImportConfiguration($entityManager),
]
);
}
/**
* @throws LogicException
*/
protected function doImportSave(Request $request, TranslatorInterface $translator, EntityManagerInterface $entityManager): Response
{
if (!isset($request->get('matrix')['records'])) {
$msg = $translator->trans('error.data.not_found', [], 'BatchEntityImportBundle');
$this->addFlash('error', $msg);
return $this->redirectToImport();
}
$matrix = MatrixFactory::createFromPostData($request->get('matrix')['records']);
$form = $this->createMatrixForm($matrix, $entityManager);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getImportConfiguration($entityManager)->import($matrix);
$msg = $translator->trans('success.import', [], 'BatchEntityImportBundle');
$this->addFlash('success', $msg);
return $this->redirectToImport();
}
return $this->prepareMatrixEditView($matrix, $entityManager);
}
protected function getImportConfiguration(EntityManagerInterface $entityManager): ImportConfigurationInterface
{
if (!$this->importConfiguration) {
$class = $this->getImportConfigurationClassName();
if (!class_exists($class)) {
throw new UnexpectedValueException('Configuration class not found.');
}
$this->importConfiguration = isset($this->container) && $this->container instanceof ContainerInterface && $this->container->has($class) ? $this->container->get($class) : new $class($entityManager);
}
return $this->importConfiguration;
}
protected function setErrorAsFlash(Traversable $violations): void
{
$errors = iterator_to_array($violations);
if ($errors) {
$error = reset($errors);
$this->addFlash('error', $error->getMessage());
}
}
}
<file_sep>/tests/Fixtures/Entity/TestEntity.php
<?php
declare(strict_types=1);
namespace JG\BatchEntityImportBundle\Tests\Fixtures\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class TestEntity extends AbstractEntity
{
private string $testProperty = '';
public function setTestProperty(string $testProperty): void
{
$this->testProperty = $testProperty;
}
public function getTestProperty(): string
{
return $this->testProperty;
}
}
<file_sep>/src/Service/PropertyExistenceChecker.php
<?php
declare(strict_types=1);
namespace JG\BatchEntityImportBundle\Service;
use JG\BatchEntityImportBundle\Utils\ColumnNameHelper;
use Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface;
use ReflectionClass;
class PropertyExistenceChecker
{
private ReflectionClass $reflectionClass;
private ?ReflectionClass $translationReflectionClass = null;
public function __construct($entity)
{
$this->reflectionClass = new ReflectionClass($entity);
if (is_subclass_of($entity, TranslatableInterface::class)) {
$this->translationReflectionClass = new ReflectionClass($this->reflectionClass->newInstanceWithoutConstructor()->translate());
}
}
public function propertyExists(string $name): bool
{
$locale = ColumnNameHelper::getLocale($name);
$name = ColumnNameHelper::underscoreToCamelCase($name);
return $locale
? $this->translationPropertyExists($name)
: $this->reflectionClass->hasProperty($name);
}
private function translationPropertyExists(string $name): bool
{
return $this->translationReflectionClass && $this->translationReflectionClass->hasProperty($name);
}
}
<file_sep>/src/Model/Matrix/MatrixRecord.php
<?php
declare(strict_types=1);
namespace JG\BatchEntityImportBundle\Model\Matrix;
class MatrixRecord
{
private ?object $entity = null;
private array $data;
public function __construct(array $data = [])
{
unset($data['entity']);
$this->data = $data;
}
public function getEntity(): ?object
{
return $this->entity;
}
public function setEntity(?object $entity): void
{
$this->entity = $entity;
}
public function getData(): array
{
return $this->data;
}
public function __isset($name): bool
{
return array_key_exists($name, $this->data);
}
public function __set($name, $value): void
{
$this->data[$name] = $value;
}
public function __get($name)
{
return $this->data[$name];
}
}
<file_sep>/tests/Controller/ImportControllerTraitTest.php
<?php
declare(strict_types=1);
namespace JG\BatchEntityImportBundle\Tests\Controller;
use Doctrine\ORM\EntityManagerInterface;
use JG\BatchEntityImportBundle\Tests\DatabaseLoader;
use JG\BatchEntityImportBundle\Tests\Fixtures\Entity\TranslatableEntity;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ImportControllerTraitTest extends WebTestCase
{
protected KernelBrowser $client;
protected ?EntityManagerInterface $entityManager;
protected function setUp(): void
{
parent::setUp();
$this->client = self::createClient();
$this->entityManager = self::$kernel->getContainer()->get('doctrine.orm.entity_manager');
$databaseLoader = self::$kernel->getContainer()->get(DatabaseLoader::class);
$databaseLoader->reload();
}
public function testControllerWorksOk(): void
{
$repository = $this->entityManager->getRepository(TranslatableEntity::class);
self::assertEmpty($repository->findAll());
$this->client->request('GET', '/jg_batch_entity_import_bundle/import');
self::assertTrue($this->client->getResponse()->isSuccessful());
$uploadedFile = __DIR__ . '/../Fixtures/Resources/test.csv';
$this->client->submitForm('btn-submit', ['file_import[file]' => $uploadedFile]);
self::assertTrue($this->client->getResponse()->isSuccessful());
self::assertEquals('/jg_batch_entity_import_bundle/import', $this->client->getRequest()->getRequestUri());
$this->client->submitForm('btn-submit');
self::assertTrue($this->client->getResponse()->isRedirect('/jg_batch_entity_import_bundle/import'));
$this->client->followRedirect();
self::assertTrue($this->client->getResponse()->isSuccessful());
self::assertStringContainsString('Data has been imported', $this->client->getResponse()->getContent());
self::assertCount(2, $repository->findAll());
/** @var TranslatableEntity|null $item */
$item = $repository->find(2);
self::assertNotEmpty($item);
}
public function testImportFileWrongExtension(): void
{
$this->client->request('GET', '/jg_batch_entity_import_bundle/import');
$uploadedFile = __DIR__ . '/../Fixtures/Resources/test.txt';
$this->client->submitForm('btn-submit', ['file_import[file]' => $uploadedFile]);
self::assertTrue($this->client->getResponse()->isSuccessful());
self::assertStringContainsString('Wrong file extension.', $this->client->getResponse()->getContent());
self::assertStringContainsString('id="file_import_file"', $this->client->getResponse()->getContent());
}
}
<file_sep>/README.md
# BatchEntityImportBundle



Importing entities with preview and edit features for Symfony.
* Data can be **viewed and edited** before saving to database.
* Supports **inserting** new records and **updating** existing ones.
* Supported extensions: **CSV, XLS, XLSX, ODS**.
* Supports translations from **KnpLabs Translatable** extension.
* The code is divided into smaller methods that can be easily replaced if you want to change something.
* Columns names are required and should be added as header (first row).
* If column does not have name provided, will be removed from loaded data.
## Documentation
* [Installation](#installation)
* [Basic configuration class](#basic-configuration-class)
* [Creating controller](#creating-controller)
* [Translations](#translations)
* [Fields definitions](#fields-definitions)
* [Overriding templates](#overriding-templates)
* [Global templates](#global-templates)
* [Controller-specific templates](#controller-specific-templates)
* [Main layout](#main-layout)
* [Additional data](#additional-data)
## Installation
Install package via composer:
```
composer require jgrygierek/batch-entity-import-bundle
```
Add entry to `bundles.php` file:
```
JG\BatchEntityImportBundle\BatchEntityImportBundle::class => ['all' => true],
```
## Basic configuration class
You have to create configuration class. In the simplest case it will contain only class of used entity.
```php
namespace App\Model\ImportConfiguration;
use App\Entity\User;
use JG\BatchEntityImportBundle\Model\Configuration\AbstractImportConfiguration;
class UserImportConfiguration extends AbstractImportConfiguration
{
public function getEntityClassName(): string
{
return User::class;
}
}
```
## Creating controller
Create controller with some required code.
This is just an example, depending on your needs you can inject services in different ways.
```php
namespace App\Controller;
use App\Model\ImportConfiguration\UserImportConfiguration;
use Doctrine\ORM\EntityManagerInterface;
use JG\BatchEntityImportBundle\Controller\ImportControllerTrait;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class ImportController extends AbstractController
{
use ImportControllerTrait;
/**
* @Route("/user/import", name="user_import")
*/
public function import(Request $request, ValidatorInterface $validator, EntityManagerInterface $em): Response
{
return $this->doImport($request, $validator, $em);
}
/**
* @Route("/user/import/save", name="user_import_save")
*/
public function importSave(Request $request, TranslatorInterface $translator, EntityManagerInterface $em): Response
{
return $this->doImportSave($request, $translator, $em);
}
protected function redirectToImport(): RedirectResponse
{
return $this->redirectToRoute('user_import');
}
protected function getMatrixSaveActionUrl(): string
{
return $this->generateUrl('user_import_save');
}
protected function getImportConfigurationClassName(): string
{
return UserImportConfiguration::class;
}
}
```
## Translations
This bundle supports KnpLabs Translatable behavior.
To use this feature, every column with translatable values should be suffixed with locale, for example:
* `name:en`
* `description:pl`
* `title:ru`
If suffix will be added to non-translatable entity, field will be skipped.
If suffix will be added to translatable entity, but field will not be found in translation class, field will be skipped.
## Fields definitions
If you want to change types of rendered fields, instead of using default ones,
you have to override method in your import configuration.
```php
use JG\BatchEntityImportBundle\Model\Form\FormFieldDefinition;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
public function getFieldsDefinitions(): array
{
return [
'age' => new FormFieldDefinition(
IntegerType::class,
[
'attr' => [
'min' => 0,
'max' => 999,
],
]
),
'name' => new FormFieldDefinition(TextType::class),
'description' => new FormFieldDefinition(
TextareaType::class,
[
'attr' => [
'rows' => 2,
],
]
),
];
}
```
## Overriding templates
#### Global templates
You have two ways to override templates globally:
- **Configuration** - just change paths to templates in your configuration file.
Values in this example are default ones and will be used if nothing will be change.
```yaml
batch_entity_import:
templates:
select_file: '@BatchEntityImport/select_file.html.twig'
edit_matrix: '@BatchEntityImport/edit_matrix.html.twig'
layout: '@BatchEntityImport/layout.html.twig'
```
- **Bundle directory** - put your templates in this directory:
```
templates/bundles/BatchEntityImportBundle
```
#### Controller-specific templates
If you have controller-specific templates, you can override them in controller:
```php
protected function getSelectFileTemplateName(): string
{
return 'your/path/to/select_file.html.twig';
}
protected function getMatrixEditTemplateName(): string
{
return 'your/path/to/edit_matrix.html.twig';
}
```
#### Main layout
Block name used in templates is `batch_entity_import_content`, so probably there will be need to override it a bit.
You can create a new file with content similar to the given example. Then just use it instead of original layout file.
```twig
{% extends path/to/your/layout.html.twig %}
{% block your_real_block_name %}
{% block batch_entity_import_content %}{% endblock %}
{% endblock %}
```
Then you just have to override it in bundle directory, or change a path to layout in your configuration.
#### Additional data
If you want to add some specific data to the rendered view, just override these methods in your controller:
```php
protected function prepareSelectFileView(FormInterface $form): Response
{
return $this->prepareView(
$this->getSelectFileTemplateName(),
[
'form' => $form->createView(),
]
);
}
protected function prepareMatrixEditView(Matrix $matrix, EntityManagerInterface $entityManager): Response
{
return $this->prepareView(
$this->getMatrixEditTemplateName(),
[
'header_info' => $matrix->getHeaderInfo($this->getImportConfiguration($entityManager)->getEntityClassName()),
'data' => $matrix->getRecords(),
'form' => $this->createMatrixForm($matrix, $entityManager)->createView(),
]
);
}
```
<file_sep>/src/Model/Form/FormFieldDefinition.php
<?php
declare(strict_types=1);
namespace JG\BatchEntityImportBundle\Model\Form;
class FormFieldDefinition
{
private string $class;
private array $options;
public function __construct(string $class, array $options = [])
{
$this->class = $class;
$this->options = $options;
}
public function getClass(): string
{
return $this->class;
}
public function getOptions(): array
{
return $this->options;
}
}
<file_sep>/src/Utils/ColumnNameHelper.php
<?php
declare(strict_types=1);
namespace JG\BatchEntityImportBundle\Utils;
class ColumnNameHelper
{
public static function underscoreToPascalCase(string $value): string
{
$value = self::removeTranslationSuffix($value);
return str_replace(' ', '', ucwords(str_replace('_', ' ', $value)));
}
public static function underscoreToCamelCase(string $value): string
{
$value = self::removeTranslationSuffix($value);
return lcfirst(self::underscoreToPascalCase($value));
}
public static function removeTranslationSuffix(string $value): string
{
return explode(':', $value)[0];
}
public static function getLocale(string $value): ?string
{
return explode(':', $value)[1] ?? null;
}
}
<file_sep>/tests/DependencyInjection/BatchEntityImportExtensionTest.php
<?php
declare(strict_types=1);
namespace JG\BatchEntityImportBundle\Tests\DependencyInjection;
use JG\BatchEntityImportBundle\DependencyInjection\BatchEntityImportExtension;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;
class BatchEntityImportExtensionTest extends AbstractExtensionTestCase
{
public function testParameters(): void
{
$this->load();
$this->assertContainerBuilderHasParameter('batch_entity_import.templates.select_file', '@BatchEntityImport/select_file.html.twig');
$this->assertContainerBuilderHasParameter('batch_entity_import.templates.edit_matrix', '@BatchEntityImport/edit_matrix.html.twig');
$this->assertContainerBuilderHasParameter('batch_entity_import.templates.layout', '@BatchEntityImport/layout.html.twig');
}
protected function getContainerExtensions(): array
{
return [new BatchEntityImportExtension()];
}
}
<file_sep>/tests/Service/PropertyExistenceCheckerTest.php
<?php
declare(strict_types=1);
namespace JG\BatchEntityImportBundle\Tests\Service;
use Generator;
use JG\BatchEntityImportBundle\Service\PropertyExistenceChecker;
use JG\BatchEntityImportBundle\Tests\Fixtures\Entity\TestEntity;
use JG\BatchEntityImportBundle\Tests\Fixtures\Entity\TranslatableEntity;
use PHPUnit\Framework\TestCase;
use ReflectionException;
class PropertyExistenceCheckerTest extends TestCase
{
private PropertyExistenceChecker $checkerEntity;
private PropertyExistenceChecker $checkerEntityWithTranslations;
/**
* @throws ReflectionException
*/
protected function setUp(): void
{
parent::setUp();
$this->checkerEntity = new PropertyExistenceChecker(new TestEntity());
$this->checkerEntityWithTranslations = new PropertyExistenceChecker(new TranslatableEntity());
}
/**
* @dataProvider dataProviderEntityWithoutTranslations
*/
public function testEntityWithoutTranslationsHasProperty(string $property): void
{
self::assertTrue($this->checkerEntity->propertyExists($property));
}
public function dataProviderEntityWithoutTranslations(): Generator
{
yield ['test_property'];
yield ['testProperty'];
}
/**
* @dataProvider dataProviderEntityWithTranslations
*/
public function testEntityWithTranslationsHasProperty(string $property): void
{
self::assertTrue($this->checkerEntityWithTranslations->propertyExists($property));
}
public function dataProviderEntityWithTranslations(): Generator
{
yield ['test_property'];
yield ['testProperty'];
yield ['test_translation_property:pl'];
yield ['testTranslationProperty:en'];
}
/**
* @dataProvider dataProviderEntityWithoutTranslationsWrongProperty
*/
public function testEntityWithoutTranslationsWithoutProperty(string $property): void
{
self::assertFalse($this->checkerEntity->propertyExists($property));
}
public function dataProviderEntityWithoutTranslationsWrongProperty(): Generator
{
yield ['test_property:pl'];
yield ['testProperty:en'];
yield ['wrong_property'];
yield ['wrongProperty'];
}
/**
* @dataProvider dataProviderEntityWithTranslationsWrongProperty
*/
public function testEntityWithTranslationsWithoutProperty(string $property): void
{
self::assertFalse($this->checkerEntityWithTranslations->propertyExists($property));
}
public function dataProviderEntityWithTranslationsWrongProperty(): Generator
{
yield ['wrong_property'];
yield ['wrongProperty'];
yield ['test_translation_property'];
yield ['testTranslationProperty'];
}
}
<file_sep>/tests/Fixtures/Entity/TranslatableEntity.php
<?php
declare(strict_types=1);
namespace JG\BatchEntityImportBundle\Tests\Fixtures\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslatableTrait;
/**
* @method string getTestTranslationProperty()
*
* @ORM\Entity()
*/
class TranslatableEntity extends AbstractEntity implements TranslatableInterface
{
use TranslatableTrait;
/**
* @ORM\Column(type="string")
*/
private string $testProperty = '';
public function setTestProperty(string $testProperty): void
{
$this->testProperty = $testProperty;
}
public function getTestProperty(): string
{
return $this->testProperty;
}
public function __call($method, $arguments)
{
return $this->proxyCurrentLocaleTranslation($method, $arguments);
}
}
<file_sep>/tests/Model/Configuration/ImportConfigurationTest.php
<?php
declare(strict_types=1);
namespace JG\BatchEntityImportBundle\Tests\Model\Configuration;
use Doctrine\ORM\EntityManagerInterface;
use JG\BatchEntityImportBundle\Model\Matrix\Matrix;
use JG\BatchEntityImportBundle\Tests\DatabaseLoader;
use JG\BatchEntityImportBundle\Tests\Fixtures\Configuration\BaseConfiguration;
use JG\BatchEntityImportBundle\Tests\Fixtures\Configuration\TranslatableEntityBaseConfiguration;
use JG\BatchEntityImportBundle\Tests\Fixtures\Entity\TestEntity;
use JG\BatchEntityImportBundle\Tests\Fixtures\Entity\TranslatableEntity;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ImportConfigurationTest extends WebTestCase
{
protected ?EntityManagerInterface $entityManager;
protected function setUp(): void
{
self::bootKernel();
$this->entityManager = self::$kernel->getContainer()->get('doctrine.orm.entity_manager');
$databaseLoader = self::$kernel->getContainer()->get(DatabaseLoader::class);
$databaseLoader->reload();
}
public function testItemImportedSuccessfully(): void
{
$repository = $this->entityManager->getRepository(TestEntity::class);
self::assertEmpty($repository->find(1));
$matrix = new Matrix(
[
'unknown_column',
'test_property',
],
[
[
'unknown_column' => 'value_1',
'test_property' => 'value_2',
],
[
'unknown_column' => 'value_3',
'test_property' => 'value_4',
],
]
);
$config = new BaseConfiguration($this->entityManager);
$config->import($matrix);
self::assertCount(2, $repository->findAll());
/** @var TestEntity|null $item */
$item = $repository->find(1);
self::assertNotEmpty($item);
self::assertSame('value_2', $item->getTestProperty());
/** @var TestEntity|null $item */
$item = $repository->find(2);
self::assertNotEmpty($item);
self::assertSame('value_4', $item->getTestProperty());
}
public function testTranslatableItemImportedSuccessfully(): void
{
$repository = $this->entityManager->getRepository(TranslatableEntity::class);
self::assertEmpty($repository->find(1));
$matrix = new Matrix(
[
'unknown_column',
'test_property',
'test_translation_property:en',
'test_translation_property:pl',
],
[
[
'unknown_column' => 'value_1',
'test_property' => 'value_2',
'test_translation_property:en' => 'value_3',
'test_translation_property:pl' => 'value_4',
],
[
'unknown_column' => 'value_5',
'test_property' => 'value_6',
'test_translation_property:en' => 'value_7',
'test_translation_property:pl' => 'value_8',
],
]
);
$config = new TranslatableEntityBaseConfiguration($this->entityManager);
$config->import($matrix);
self::assertCount(2, $repository->findAll());
/** @var TranslatableEntity|null $item */
$item = $repository->find(1);
self::assertNotEmpty($item);
self::assertSame('value_2', $item->getTestProperty());
self::assertSame('value_3', $item->translate('en')->getTestTranslationProperty());
self::assertSame('value_4', $item->translate('pl')->getTestTranslationProperty());
/** @var TranslatableEntity|null $item */
$item = $repository->find(2);
self::assertNotEmpty($item);
self::assertSame('value_6', $item->getTestProperty());
self::assertSame('value_7', $item->translate('en')->getTestTranslationProperty());
self::assertSame('value_8', $item->translate('pl')->getTestTranslationProperty());
}
}
| 536f72aa1a71edb7b96265c587d169c100656173 | [
"Markdown",
"PHP"
]
| 14 | PHP | michealmouner/BatchEntityImportBundle | 0503c023b822c63a4a59ba1726aa2e40547e4f84 | 864e647360d2583df2edb72a0b0b1fd28e566816 |
refs/heads/master | <file_sep>export const FIREBASE_CREDENTAILS = {
apiKey: "<KEY>",
authDomain: "fir-crud-afd79.firebaseapp.com",
databaseURL: "https://fir-crud-afd79.firebaseio.com",
projectId: "fir-crud-afd79",
storageBucket: "fir-crud-afd79.appspot.com",
messagingSenderId: "908441077622"
}<file_sep>import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database'
import {Subscription} from 'rxjs/Subscription'
import { ShoppingItem } from '../../models/shopping-item/shopping-item.interface'
@Component({
selector: 'page-edit-shopping-item',
templateUrl: 'edit-shopping-item.html',
})
export class EditShoppingItemPage {
shoppingItemSubscription: Subscription;
shoppingItemRef$: FirebaseObjectObservable<ShoppingItem>;
shoppingItem: ShoppingItem;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private database: AngularFireDatabase
) {
// Capture the shoppingItemId as a NavParrameter
const shoppingItemId = this.navParams.get('shoppingItemId');
// Log shoppingIemId
console.log(shoppingItemId);
// Set the scope of our Firebase Object equal to our selected item
this.shoppingItemRef$ = this.database.object(`shopping-List/${shoppingItemId}`);
// Subscribe to the Object and assign the result to this.shoppingItem
this.shoppingItemSubscription = this.shoppingItemRef$
.subscribe( shoppingItem => this.shoppingItem = shoppingItem)
}
editeShoppingItem(shoppingItem: ShoppingItem){
// Update our Firebase node with new item data
this.shoppingItemRef$.update(shoppingItem);
// Send the user back to the ShoppingListPage
this.navCtrl.pop()
}
ionViewWillLeave(){
// Unsubscrribe from the Observable when leaving the page
this.shoppingItemSubscription.unsubscribe();
}
}
<file_sep>import { Component } from '@angular/core';
import { NavController, NavParams,ActionSheetController } from 'ionic-angular';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import { AddShoppingPage } from '../add-shopping/add-shopping';
import { ShoppingItem } from '../../models/shopping-item/shopping-item.interface';
import { EditShoppingItemPage } from '../edit-shopping-item/edit-shopping-item'
@Component({
selector: 'page-shopping-list',
templateUrl: 'shopping-list.html',
})
export class ShoppingListPage {
shoppingListRef$: FirebaseListObservable<ShoppingItem[]>;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private database: AngularFireDatabase,
private actionSheetCtrl: ActionSheetController
) {
/* Pointing shoppingListRef$ at Firebase -> 'shopping-list' node.
That means not only can we push things from this reference to
the database, but also we have access to everything inside of
that node.
*/
this.shoppingListRef$ = this.database.list('shopping-List')
}
selectShoppingItem(shoppingItem: ShoppingItem) {
/* Display an ActionSheet that gives the user the following
option:
1. Edit the ShoppingItem
2. Delele the ShoppingItem
3. Cancel selection
*/
this.actionSheetCtrl.create({
title: `${shoppingItem.itemName}`,
buttons: [
{
text: 'Edit',
handler: () => {
/* Send the user to the EditShoppingIempage and pass the key
as a parnmeter */
this.navCtrl.push(EditShoppingItemPage,
{ shoppingItemId: shoppingItem.$key});
}
},
{
text: 'Delete',
role: 'destructive',
handler: () => {
// Delete the current ShoppingItem
this.shoppingListRef$.remove(shoppingItem.$key)
}
},
{
text: 'Cancel',
role: 'cancel',
handler: () => {
// Cancel
console.log(shoppingItem)
console.log('The user has select the cancel btn')
}
}
]
}).present();
}
navigateToAddShopingPage() {
// Navigate user to AddShopingPage
this.navCtrl.push(AddShoppingPage)
}
}
| 07a45b1c208ff4971e3374ef638583391a6e2a19 | [
"TypeScript"
]
| 3 | TypeScript | wudtichaikarun/ionic-firebase-crud | 7f30c7948ffce3d707315f10bcb532416c4e1b70 | 0bd46e039f9cbfa219fcf2bec99b9c6de4bc186f |
refs/heads/master | <repo_name>petterkkk/PythonScape<file_sep>/skills.py
import Hitpoints
class Skills(object):
def init(self):
self.hp = Hitpoints.Hitpoints()
def getLevel(self, skill):
if skill == 'Hitpoints':
level = self.hp.getHPLevel()
return level
def getCurrent(self, skill):
if skill == 'Hitpoints':
current = self.hp.getCurrentHP()
return current
<file_sep>/Hitpoints.py
class Hitpoints(object):
def getHPLevel(self):
self.hp_level = 10
return self.hp_level
def getCurrentHP(self):
self.current_hp = 10
return self.current_hp
<file_sep>/GUI.py
import sys, pygame, os
import skills
class GUI(object):
def init(self):
pygame.init()
self.skl = skills.Skills()
self.size = self.width, self.height = 1280, 720
self.screen = pygame.display.set_mode(self.size)
pygame.display.set_caption('RunePython')
self.constants()
self.loadText()
self.loadUI()
def loop(self):
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
self.screen.fill((0,0,0))
self.blitUI()
self.blitText()
#screen.blit(object, (rect))
pygame.display.flip()
def constants(self):
self.UI_PATH = 'UI/'
def loadUI(self):
self.map_container = pygame.image.load(self.UI_PATH + 'UI_MAP_RECT.png')
self.hp_rect_ui = pygame.image.load(self.UI_PATH + 'HP_RECT_UI.png')
self.prayer_rect_ui = pygame.image.load(self.UI_PATH + 'PRAYER_RECT_UI.png')
def blitUI(self):
self.screen.blit(self.map_container, ((self.width - 265), 0))
self.map_container.blit(self.hp_rect_ui, (5,4))
self.map_container.blit(self.prayer_rect_ui, (5, 32))
def loadText(self):
self.UI_FONT = pygame.font.SysFont("monospace", 8)
hplevel = self.skl.getLevel('Hitpoints')
currenthp = self.skl.getCurrent('Hitpoints')
self.hp_label = self.UI_FONT.render(hplevel + '/' + currenthp, 1, (255, 255, 255))
def blitText(self):
self.hp_rect_ui.blit(self.hp_label, (27, 8))
<file_sep>/README.md
# PythonScape
RuneScape project in Python
# TODO:
1) Get the skill-tab working. \n
2) Get the actual game screen up and running - not just the UI. \n
3) ???
<file_sep>/main.py
import sys, os, GUI, skills
class Game(object):
def init(self):
gui.init()
if __name__ == '__main__':
game = Game()
gui = GUI.GUI()
game.init()
while 1:
gui.loop()
| 416ba2713402ae1edb93852a2b2b31ed45b1bc89 | [
"Markdown",
"Python"
]
| 5 | Python | petterkkk/PythonScape | 7c49626a1560540ac2d52b30615531f0a094386c | 23ac8b94492fbddb66916126f8e85a458c5bf238 |
refs/heads/master | <repo_name>forthommel/pps-tbrc<file_sep>/src/VME_TDCV1x90.cpp
#include "VME_TDCV1x90.h"
namespace VME
{
TDCV1x90::TDCV1x90(int32_t bhandle, uint32_t baseaddr) :
GenericBoard<TDCV1x90Register,cvA32_U_DATA>(bhandle, baseaddr),
fVerb(1), fAcquisitionMode(TRIG_MATCH), fDetectionMode(TRAILEAD)
{
fBuffer = (uint32_t*)malloc(32*1024*1024); // 32MB of buffer!
if (fBuffer==NULL) {
throw Exception(__PRETTY_FUNCTION__, "Output buffer has not been allocated!", Fatal);
}
try {
CheckConfiguration();
GetFirmwareRevision();
//std::cout << "Firmware revision = " << ((fw>>4)&0xf) << "." << (fw&0xf) << std::endl;
} catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Wrong configuration!", Fatal);
}
SoftwareReset();
//SoftwareClear();
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::EN_ALL_CHANNEL);
} catch (Exception& e) { e.Dump(); }
SetAcquisitionMode(fAcquisitionMode);
SetDetectionMode(fDetectionMode);
SetLSBTraileadEdge(r25ps);
SetTriggerTimeSubtraction(true);
/*for (unsigned int=0; i<4; i++) {
std::cout << "rc adjust " << i << ": " << GetRCAdjust()
}
SetRCAdjust(0,0);
SetRCAdjust(1,0);
SetRCAdjust(2,0);
SetRCAdjust(3,0);*/
GlobalOffset offs; offs.fine = 0x0; offs.coarse = 0x0;
SetGlobalOffset(offs); // coarse and fine set
//GetGlobalOffset();
//SetBLTEventNumberRegister(1); // FIXME find good value!
SetTDCEncapsulation(true);
SetErrorMarks(true);
SetETTT(true);
//SetWindowWidth(2045); // in units of clock cycles
//SetWindowOffset(-2050); // in units of clock cycles
//SetPairModeResolution(0,0x4);
SetPoI(0xFFFF, 0xFFFF);
//GetResolution();
gEnd = false;
std::stringstream s; s << "TDC with base address 0x" << std::hex << baseaddr << " successfully built!";
PrintInfo(s.str());
GetTriggerConfiguration().Dump();
}
TDCV1x90::~TDCV1x90()
{
free(fBuffer);
fBuffer = NULL;
}
uint32_t
TDCV1x90::GetModel() const
{
uint32_t model = 0x0;
uint16_t data[3];
TDCV1x90Register addr[3] = {kROMBoard0, kROMBoard1, kROMBoard2};
try {
for (int i=0; i<3; i++) {
ReadRegister(addr[i], &(data[i]));
}
model = (((data[2]&0xff) << 16)+((data[1]&0xff) << 8)+(data[0]&0xff));
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o; o << "Debug: Model is " << std::dec << model;
PrintInfo(o.str());
}
return model;
}
uint32_t
TDCV1x90::GetOUI() const
{
uint32_t oui = 0x0;
uint16_t data[3];
TDCV1x90Register addr[3] = {kROMOui0, kROMOui1, kROMOui2};
try {
for (int i=0; i<3; i++) {
ReadRegister(addr[i], &(data[i]));
}
oui = (((data[2]&0xff) << 16)+((data[1]&0xff) << 8)+(data[0]&0xff));
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o;
o << "Debug: OUI manufacturer number is " << std::dec << oui;
PrintInfo(o.str());
}
return oui;
}
uint32_t
TDCV1x90::GetSerialNumber() const
{
uint32_t sn = 0x0;
uint16_t data[2];
TDCV1x90Register addr[2] = {kROMSerNum0, kROMSerNum1};
try {
for (int i=0; i<2; i++) {
ReadRegister(addr[i], &(data[i]));
}
sn = (((data[1]&0xff) << 8)+(data[0]&0xff));
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o; o << "Debug: Serial number is " << std::dec << sn;
PrintInfo(o.str());
}
return sn;
}
uint16_t
TDCV1x90::GetFirmwareRevision() const
{
//FIXME need to clean up
uint32_t fr[2] = { 0, 0 };
uint16_t data;
try {
ReadRegister(kFirmwareRev,&data);
fr[0] = data&0xF;
fr[1] = (data&0xF0)>>4;
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o;
o << "Debug: Firmware revision is " << std::dec << fr[1] << "." << fr[0];
PrintInfo(o.str());
}
return data;
}
void
TDCV1x90::CheckConfiguration() const
{
uint32_t oui;
uint32_t model;
oui = GetOUI();
model = GetModel();
if (oui!=0x0040e6) { // CAEN
std::ostringstream o; o << "Wrong manufacturer identifier: 0x" << std::hex << oui;
throw Exception(__PRETTY_FUNCTION__, o.str(), Fatal);
}
if ((model!=1190) and (model!=1290)) {
std::ostringstream o; o << "Wrong model number: model is " << std::dec << model;
throw Exception(__PRETTY_FUNCTION__, o.str(), Fatal);
}
/*#ifdef DEBUG
std::cout << "[VME] <TDC::CheckConfiguration> Debug:" << std::endl;
std::cout << " OUI manufacturer number is 0x"
<< std::hex << std::setfill('0') << std::setw(6) << oui << std::endl;
std::cout << " Model number is "
<< std::dec << model << std::endl;
std::cout << " Serial number is "
<< std::dec << GetSerNum() << std::endl;
#endif*/
}
void
TDCV1x90::SetTestMode(bool en) const
{
uint16_t word;
word = (en) ? TDCV1x90Opcodes::ENABLE_TEST_MODE : TDCV1x90Opcodes::DISABLE_TEST_MODE;
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, word);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o;
o << "Debug: Test mode enabled? " << en;
PrintInfo(o.str());
}
}
void
TDCV1x90::SetPoI(uint16_t word1, uint16_t word2) const
{
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::WRITE_EN_PATTERN);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, word1);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, word2);
} catch (Exception& e) { e.Dump(); }
//if (fVerb>1) {
std::ostringstream os;
os << "Debug: Pattern of inhibit modified:" << "\n\t";
for (unsigned int i=0; i<16; i++) {
os << "Channel " << i << ": " << ((word1>>i)&0x1) << "\t"
<< "Channel " << (i+16) << ": " << ((word2>>i)&0x1) << "\n\t";
}
PrintInfo(os.str());
//}
}
std::map<unsigned short, bool>
TDCV1x90::GetPoI() const
{
uint16_t word1, word2;
std::map<unsigned short, bool> pattern;
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::READ_EN_PATTERN);
WaitMicro(READ_OK);
ReadRegister(kMicro, &word1);
WaitMicro(READ_OK);
ReadRegister(kMicro, &word2);
} catch (Exception& e) { e.Dump(); }
for (unsigned int i=0; i<16; i++) {
pattern.insert(std::pair<unsigned short, bool>(i, static_cast<bool>((word1>>i)&0x1)));
pattern.insert(std::pair<unsigned short, bool>(i+16, static_cast<bool>((word2>>i)&0x1)));
}
return pattern;
}
void
TDCV1x90::EnableChannel(short channel_id) const
{
uint16_t value = TDCV1x90Opcodes::EN_CHANNEL+(channel_id&0xFF);
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, value);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o; o << "Debug: Channel " << channel_id << " enabled";
PrintInfo(o.str());
}
}
void
TDCV1x90::DisableChannel(short channel_id) const
{
uint16_t value = TDCV1x90Opcodes::DIS_CHANNEL+(channel_id&0xFF);
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, value);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o; o << "Debug: Channel " << channel_id << " disabled";
PrintInfo(o.str());
}
}
void TDCV1x90::SetLSBTraileadEdge(trailead_edge_lsb conf) const
{
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::SET_TR_LEAD_LSB);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, static_cast<uint16_t>(conf));
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::stringstream o; o << "Debug: ";
switch(conf){
case r800ps: o << "800ps"; break;
case r200ps: o << "200ps"; break;
case r100ps: o << "100ps"; break;
case r25ps: o << "25ps"; break;
}
PrintInfo(o.str());
}
}
void
TDCV1x90::SetGlobalOffset(const GlobalOffset& offs) const
{
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::SET_GLOB_OFFS);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, offs.coarse);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, offs.fine);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o;
o << "Debug: " << std::endl
<< "\tcoarse counter offset: " << offs.coarse << std::endl
<< "\t fine counter offset: " << offs.fine;
PrintInfo(o.str());
}
}
GlobalOffset
TDCV1x90::GetGlobalOffset() const
{
GlobalOffset ret;
uint16_t data[2];
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::READ_GLOB_OFFS);
int i;
for(i=0;i<2;i++){
WaitMicro(READ_OK);
ReadRegister(kMicro, &(data[i]));
}
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o;
o << "Debug: " << std::endl
<< "\tcoarse counter offset: " << data[0] << std::endl
<< "\t fine counter offset: " << data[1];
PrintInfo(o.str());
}
ret.fine = data[1];
ret.coarse = data[0];
return ret;
}
void
TDCV1x90::SetRCAdjust(int tdc, uint16_t value) const
{
//FIXME find a better way to insert value for 12 RCs
uint16_t word = value;
uint16_t opcode = TDCV1x90Opcodes::SET_RC_ADJ+(tdc&0x3);
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, opcode);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, word);
} catch (Exception& e) { e.Dump(); }
/*WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::SAVE_RC_ADJ);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, word);*/
if (fVerb>1) {
std::ostringstream o; o << "Debug: TDC " << tdc << ", value " << value;
PrintInfo(o.str());
}
}
uint16_t
TDCV1x90::GetRCAdjust(int tdc) const
{
uint16_t opcode = TDCV1x90Opcodes::READ_RC_ADJ+(tdc&0x3);
uint16_t data;
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, opcode);
WaitMicro(READ_OK);
ReadRegister(kMicro, &data);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o; o << "Debug: value for TDC " << tdc << std::endl;
for(int i=0; i<12; i++) {
o << "\t bit " << std::setw(2) << i << ": ";
char bit = ((data>>i)&0x1);
switch(bit) {
case 0: o << "contact open"; break;
case 1: o << "contact closed"; break;
}
if (i<11) o << std::endl;
}
PrintInfo(o.str());
}
return data;
}
void
TDCV1x90::SetDetectionMode(const DetectionMode& mode)
{
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::SET_DETECTION);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, static_cast<uint16_t>(mode));
} catch (Exception& e) { e.Dump(); }
fDetectionMode = mode;
if (fVerb>1) {
std::ostringstream o; o << "Debug: ";
switch(mode){
case PAIR: o << "pair mode"; break;
case OTRAILING: o << "only trailing"; break;
case OLEADING: o << "only leading"; break;
case TRAILEAD: o << "trailing and leading"; break;
}
PrintInfo(o.str());
}
}
void
TDCV1x90::ReadDetectionMode()
{
uint16_t data;
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::READ_DETECTION);
WaitMicro(READ_OK);
ReadRegister(kMicro, &data);
} catch (Exception& e) { e.Dump(); }
fDetectionMode = static_cast<DetectionMode>(data&0x3);
if (fVerb>1) {
std::ostringstream o; o << "Debug: ";
switch(fDetectionMode){
case PAIR: o << "pair mode"; break;
case OTRAILING: o << "only trailing"; break;
case OLEADING: o << "only leading"; break;
case TRAILEAD: o << "trailing and leading"; break;
}
PrintInfo(o.str());
}
}
void
TDCV1x90::SetWindowWidth(const uint16_t& width)
{
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::SET_WIN_WIDTH);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, width);
} catch (Exception& e) { e.Dump(); return; }
fWindowWidth = width;
}
void
TDCV1x90::SetWindowOffset(const int16_t& offs) const
{
//FIXME warning at sign bit
uint16_t data = offs;
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::SET_WIN_OFFS);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, data);
} catch (Exception& e) { e.Dump(); }
}
uint16_t
TDCV1x90::GetResolution() const
{
uint16_t data;
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::READ_RES);
WaitMicro(READ_OK);
ReadRegister(kMicro, &data);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
const char* pair_lead_res[] = {
"100ps", "200ps", "400ps", "800ps", "1.6ns", "3.12ns", "6.25ns", "12.5ns"
};
const char* pair_width_res[] = {
"100ps", "200ps", "400ps", "800ps", "1.6ns", "3.2ns", "6.25ns", "12.5ns",
"25ns", "50ns", "100ns", "200ns", "400ns", "800ns", "invalid","invalid"
};
const char* trailead_edge_res[] = { "800ps", "200ps", "100ps", "25ps" };
std::ostringstream os; os << " Debug: ";
switch(fDetectionMode) {
case PAIR:
os << "(pair mode) leading edge res.: " << pair_lead_res[data&0x7]
<< ", pulse width res.: " << pair_width_res[(data&0xF00)>>8];
break;
case OLEADING:
case OTRAILING:
case TRAILEAD:
os << "(l/t mode) leading/trailing edge res.: " << trailead_edge_res[data&0x3];
break;
}
PrintInfo(os.str());
}
return data;
}
void
TDCV1x90::SetPairModeResolution(int lead_time_res, int pulse_width_res) const
{
uint16_t data = lead_time_res+0x100*pulse_width_res;
/*(data&0x7)=lead_time_res;
(data&0xf00)=pulse_width_res;*/
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::SET_PAIR_RES);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, data);
} catch (Exception& e) { e.Dump(); }
}
void
TDCV1x90::SetAcquisitionMode(const AcquisitionMode& mode)
{
try {
switch(mode){
case CONT_STORAGE: SetContinuousStorage(); break;
case TRIG_MATCH: SetTriggerMatching(); break;
default:
throw Exception(__PRETTY_FUNCTION__, "Wrong acquisition mode", Fatal);
}
} catch (Exception& e) { throw e; }
}
void
TDCV1x90::SetTriggerMatching()
{
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::TRG_MATCH);
WaitMicro(WRITE_OK);
if (GetAcquisitionMode()!=TRIG_MATCH)
throw Exception(__PRETTY_FUNCTION__, "Error while setting the acquisition mode to trigger matching!", Fatal);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) PrintInfo("Debug: trigger matching mode");
}
void
TDCV1x90::SetContinuousStorage()
{
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::CONT_STOR);
WaitMicro(WRITE_OK);
if (GetAcquisitionMode()!=CONT_STORAGE)
throw Exception(__PRETTY_FUNCTION__, "Error while setting the acquisition mode to continuous storage!", Fatal);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) PrintInfo("Debug: continuous storage mode");
}
void
TDCV1x90::ReadAcquisitionMode()
{
uint16_t data;
/*uint32_t addr = fBaseAddr+0x1002; // Status register
std::cout << "ReadCycle response: " << std::dec << CAENVME_ReadCycle(fHandle,addr,&data,am,cvD16) << std::endl;
std::cout << "isTriggerMatching: value: " << ((data>>3)&0x1) << std::endl;*/
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::READ_ACQ_MOD);
WaitMicro(READ_OK);
ReadRegister(kMicro, &data);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o; o << "Debug: value: " << data << " (";
switch (data) {
case 0: o << "continuous storage"; break;
case 1: o << "trigger matching"; break;
default: o << "wrong answer!"; break;
}
o << ")";
PrintInfo(o.str());
}
switch (data) {
case 0: fAcquisitionMode = CONT_STORAGE; break;
case 1: fAcquisitionMode = TRIG_MATCH; break;
default:
throw Exception(__PRETTY_FUNCTION__, "Invalid acquisition mode read from board!", Fatal);
}
}
bool
TDCV1x90::SoftwareReset() const
{
try { WriteRegister(kModuleReset, static_cast<uint16_t>(0x0)); } catch (Exception& e) { e.Dump(); }
return true;
}
bool
TDCV1x90::SoftwareClear() const
{
try { WriteRegister(kSoftwareClear, static_cast<uint16_t>(0x0)); } catch (Exception& e) { e.Dump(); }
return true;
}
//bool
//TDCV1x90::IsEventFIFOReady()
//{
//std::cout << "[VME] <TDC::ifEventFIFOReady> Debug: is FIFO enabled: "
// << GetControlRegister(EVENT_FIFO_ENABLE) << std::endl;
//SetFIFOSize(7); //FIXME
//ReadFIFOSize();
/*ReadRegister(kEventFIFOStatusRegister,&data);
std::cout << "[VME] <TDC::ifEventFIFOReady> Debug: data: " << data << std::endl;
std::cout << " DATA_READY: " << (data&1) << std::endl;
std::cout << " FULL: " << ((data&2)>>1) << std::endl;
ReadRegister(kEventFIFOStoredRegister,&data2);
std::cout << "[VME] <TDC::ifEventFIFOReady> Debug: data2: " << ((data2&0x7ff)>>11) << std::endl;*/
//}
void
TDCV1x90::SetChannelDeadTime(unsigned short dt) const
{
uint16_t word = (dt&0x3);
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::SET_DEAD_TIME);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, word);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream os;
os << "Debug: Channel dead time set to: ";
switch (word) {
case 0x0: os << "5 ns"; break;
case 0x1: os << "10 ns"; break;
case 0x2: os << "30 ns"; break;
case 0x3: os << "100 ns"; break;
}
PrintInfo(os.str());
}
}
unsigned short
TDCV1x90::GetChannelDeadTime() const
{
uint16_t dt;
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::READ_DEAD_TIME);
WaitMicro(READ_OK);
ReadRegister(kMicro, &dt);
} catch (Exception& e) { e.Dump(); }
return static_cast<unsigned short>(dt&0x3);
}
void
TDCV1x90::SetFIFOSize(const uint16_t& size) const
{
uint16_t word;
switch(size) {
case 2: word=0x0; break;
case 4: word=0x1; break;
case 8: word=0x2; break;
case 16: word=0x3; break;
case 32: word=0x4; break;
case 64: word=0x5; break;
case 128: word=0x6; break;
case 256: word=0x7; break;
default:
throw Exception(__PRETTY_FUNCTION__, "Trying to set a wrong FIFO size.", JustWarning);
}
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::SET_FIFO_SIZE);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, word);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o; o << "Debug: Setting the FIFO size to: " << size << " (" << word << ")";
PrintInfo(o.str());
}
}
uint16_t
TDCV1x90::GetFIFOSize() const
{
uint16_t data;
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::READ_FIFO_SIZE);
WaitMicro(READ_OK);
ReadRegister(kMicro, &data);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o; o << "Debug: READ_FIFO_SIZE: " << std::dec << (1<<(data+1));
PrintInfo(o.str());
}
return (1<<(data+1));
}
void
TDCV1x90::SetTDCEncapsulation(bool mode) const
{
uint16_t opcode;
if (mode) opcode = TDCV1x90Opcodes::EN_HEAD_TRAILER;
else opcode = TDCV1x90Opcodes::DIS_HEAD_TRAILER;
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, opcode);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o; o << "Debug: TDC encapsulation enabled? " << mode;
PrintInfo(o.str());
}
}
bool
TDCV1x90::GetTDCEncapsulation() const
{
uint16_t enc;
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::READ_HEAD_TRAILER);
WaitMicro(READ_OK);
ReadRegister(kMicro, &enc);
} catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o; o << "Debug: READ_HEAD_TRAILER: " << enc;
PrintInfo(o.str());
}
return static_cast<bool>(enc&0x1);
}
uint32_t
TDCV1x90::GetEventCounter() const
{
uint32_t value;
try { ReadRegister(kEventCounter, &value); } catch (Exception& e) { e.Dump(); }
return value&0xFFFFFFFF;
}
uint16_t
TDCV1x90::GetEventStored() const
{
uint16_t value;
try { ReadRegister(kEventStored, &value); } catch (Exception& e) { e.Dump(); }
return value&0xFFFF;
}
void
TDCV1x90::SetErrorMarks(bool mode)
{
uint16_t opcode;
if (mode) opcode = TDCV1x90Opcodes::EN_ERROR_MARK;
else opcode = TDCV1x90Opcodes::DIS_ERROR_MARK;
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, opcode);
} catch (Exception& e) { e.Dump(); return; }
if (fVerb>1) {
std::ostringstream o; o << "Debug: Enabled? " << mode;
PrintInfo(o.str());
}
fErrorMarks = mode;
}
void
TDCV1x90::SetBLTEventNumberRegister(const uint16_t& value) const
{
try { WriteRegister(kBLTEventNumber, value); } catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o; o << "Debug: value: " << value;
PrintInfo(o.str());
}
}
uint16_t
TDCV1x90::GetBLTEventNumberRegister() const
{
uint16_t value;
try { ReadRegister(kBLTEventNumber, &value); } catch (Exception& e) { e.Dump(); }
if (fVerb>1) {
std::ostringstream o; o << "Debug: value: " << value;
PrintInfo(o.str());
}
return value;
}
void
TDCV1x90::SetDLLClock(const DLLMode& dll) const
{
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::SET_DLL_CLOCK);
WaitMicro(WRITE_OK);
WriteRegister(kMicro, static_cast<uint16_t>(dll));
} catch (Exception& e) { e.Dump(); return; }
}
void
TDCV1x90::SetTriggerTimeSubtraction(bool enabled) const
{
uint16_t opcode;
if (enabled) opcode = TDCV1x90Opcodes::EN_SUB_TRG;
else opcode = TDCV1x90Opcodes::DIS_SUB_TRG;
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, opcode);
} catch (Exception& e) { e.Dump(); return; }
}
void
TDCV1x90::SetStatus(const TDCV1x90Status& status) const
{
try { WriteRegister(kStatus, status.GetValue()); } catch (Exception& e) { e.Dump(); }
}
TDCV1x90Status
TDCV1x90::GetStatus() const
{
uint16_t value;
try { ReadRegister(kStatus, &value); } catch (Exception& e) { e.Dump(); }
return TDCV1x90Status(value&0xFFFF);
}
void
TDCV1x90::SetControl(const TDCV1x90Control& control) const
{
try { WriteRegister(kControl, control.GetValue()); } catch (Exception& e) { e.Dump(); }
}
TDCV1x90Control
TDCV1x90::GetControl() const
{
uint16_t value;
try { ReadRegister(kControl, &value); } catch (Exception& e) { e.Dump(); }
return TDCV1x90Control(value&0xFFFF);
}
TDCV1x90TriggerConfig
TDCV1x90::GetTriggerConfiguration() const
{
uint16_t buff[5];
TDCV1x90TriggerConfig conf;
try {
WaitMicro(WRITE_OK);
WriteRegister(kMicro, TDCV1x90Opcodes::READ_TRG_CONF);
for (unsigned short i=0; i<5; i++) {
WaitMicro(READ_OK);
ReadRegister(kMicro,&(buff[i]));
conf.SetWord(i, buff[i]);
}
} catch (Exception& e) {
e.Dump();
}
return conf;
}
TDCEventCollection
TDCV1x90::FetchEvents()
{
if (gEnd)
throw Exception(__PRETTY_FUNCTION__, "Abort state detected... quitting", JustWarning, TDC_ACQ_STOP);
TDCEventCollection ec; ec.clear();
memset(fBuffer, 0, sizeof(uint32_t));
int count = 0;
const int blts = 4096; // size of the transfer in bytes
bool finished;
std::ostringstream o;
// Start Readout (check if BERR is set to 0)
CVErrorCodes ret = CAENVME_BLTReadCycle(fHandle, fBaseAddr+kOutputBuffer, (char*)fBuffer, blts, cvA32_U_BLT, cvD32, &count);
finished = ((ret==cvSuccess)||(ret==cvBusError)||(ret==cvCommError)); //FIXME investigate...
if (finished && gEnd) {
if (fVerb>1) PrintInfo("Debug: Exit requested!");
throw Exception(__PRETTY_FUNCTION__, "Abort state detected... quitting", JustWarning, TDC_ACQ_STOP);
}
switch (fAcquisitionMode) {
case TRIG_MATCH:
for (int i=0; i<count/4; i++) { // FIXME need to use the knowledge of the TDCEvent behaviour there...
TDCEvent ev(fBuffer[i]);
if (ev.GetType()!=TDCEvent::Filler) ec.push_back(ev); // Filter out filler data
}
return ec;
case CONT_STORAGE:
for (int i=0; i<count; i++) {
if (fBuffer[i]==0) continue;
TDCEvent ev(fBuffer[i]);
if (ev.GetType()!=TDCEvent::Filler) ec.push_back(ev); // Filter out filler data
}
return ec;
default:
o.str(""); o << "Wrong acquisition mode: " << fAcquisitionMode;
throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning);
}
}
void
TDCV1x90::abort()
{
if (fVerb>1) {
PrintInfo("Debug: received abort signal");
}
// Raise flag
gEnd = true;
}
bool
TDCV1x90::WaitMicro(const micro_handshake& mode) const
{
uint16_t data = 0x0;
bool status = false;
while (!status) {
ReadRegister(kMicroHandshake, &data);
if (mode==WRITE_OK) status = static_cast<bool>( data &0x1);
else status = static_cast<bool>((data>>1)&0x1);
}
return status;
}
}
<file_sep>/test/gastof_full_occupancy_vs_run.cpp
#include "FileReader.h"
#include "GastofCanvas.h"
#include <dirent.h>
using namespace std;
int main(int argc, char* argv[]) {
if (argc<5) { cerr << "Usage: " << argv[0] << " <board 1 id> <board 2 id> <run id> <trigger start> [trigger stop=-1]" << endl; exit(0); }
int board_ids[2];
board_ids[0] = atoi(argv[1]);
board_ids[1] = atoi(argv[2]);
int run_id = atoi(argv[3]);
int trigger_start = atoi(argv[4]), trigger_stop = -1;
if (argc>5) trigger_stop = atoi(argv[5]);
DQM::GastofCanvas* occ = new DQM::GastofCanvas(Form("occupancy_run%d_triggers%d-%d_allboards", run_id, trigger_start, trigger_stop), "Integrated occup. / trigger");
ostringstream search1, search2, file;
DIR* dir; struct dirent* ent;
cout << "Search in directory: " << getenv("PPS_DATA_PATH") << endl;
VME::TDCEvent e;
int num_triggers;
for (int b=0; b<2; b++) {
search2.str(""); search2 << "_board" << board_ids[b] << ".dat";
for (int sp=0; sp<1000000; sp++) { // we loop over all spills
search1.str(""); search1 << "events_" << run_id << "_" << sp << "_";
bool file_found = false; string filename;
// first we search for the proper file to open
if ((dir=opendir(getenv("PPS_DATA_PATH")))==NULL) return -1;
while ((ent=readdir(dir))!=NULL) {
if (string(ent->d_name).find(search1.str())!=string::npos and
string(ent->d_name).find(search2.str())!=string::npos) {
file_found = true;
filename = ent->d_name;
break;
}
}
closedir(dir);
if (!file_found) {
cout << "Found " << sp << " files in this run" << endl;
break;
}
// then we open it
file.str(""); file << getenv("PPS_DATA_PATH") << "/" << filename;
cout << "Opening file " << file.str() << endl;
try {
FileReader f(file.str());
num_triggers = 0;
while (true) {
if (!f.GetNextEvent(&e)) break;
if (e.GetType()==VME::TDCEvent::GlobalHeader) num_triggers++;
if (num_triggers>trigger_stop and trigger_stop>0) break;
if (num_triggers>=trigger_start and e.GetType()==VME::TDCEvent::TDCMeasurement and !e.IsTrailing()) occ->FillChannel(b, e.GetChannelId(), 1);
}
f.Clear(); // we return to beginning of the file
} catch (Exception& e) { cout << "prout" << endl; e.Dump(); }
}
}
cout << "num events = " << occ->Grid()->GetSumOfWeights() << endl;
cout << "num triggers = " << (num_triggers-trigger_start) << endl;
occ->Grid()->SetMaximum(0.15);
occ->Grid()->Scale(1./(num_triggers-trigger_start));
occ->SetRunInfo(999, run_id, 0, Form("Triggers %d-%d", trigger_start, trigger_stop));
occ->Save(Form("png"));
return 0;
}
<file_sep>/scripts/run_number.py
import sqlite3
import os
from sys import argv
from datetime import datetime
def main(argv):
path = os.getenv('PPS_PATH', '/home/ppstb/pps-tbrc/build/')
conn = sqlite3.connect(path+'/run_infos.db')
c = conn.cursor()
if len(argv)<2:
c.execute('SELECT id,start FROM run ORDER BY id DESC LIMIT 1')
run_id, start_ts = c.fetchone()
print 'Last Run number is:', run_id
else:
run_id = int(argv[1])
c.execute('SELECT start FROM run WHERE id=%i' % (run_id))
start = c.fetchone()
if not start:
print 'Failed to find run %i in the database!' % (run_id)
exit(0)
print 'Run number:', run_id
start_ts = start[0]
print ' -- started on', datetime.fromtimestamp(int(start_ts))
c.execute('SELECT COUNT(*) FROM burst WHERE run_id=%i' % (run_id))
print ' -- %i burst(s) recorded' % c.fetchone()[0]
c.execute('SELECT burst_id,start FROM burst WHERE run_id=%i ORDER BY id DESC LIMIT 1' % (run_id))
try:
last_burst_id, last_burst_start_ts = c.fetchone()
print ' -- last burst: #%i started on %s' % (last_burst_id, datetime.fromtimestamp(int(last_burst_start_ts)))
except TypeError:
print ' -- no burst information retrieved'
c.execute('SELECT tdc_id,tdc_address,tdc_det_mode,tdc_acq_mode,detector FROM tdc_conditions WHERE run_id=%i'%(run_id))
apparatus = c.fetchall()
if len(apparatus)==0:
print ' -- no apparatus information retrieved'
else:
print ' -- apparatus attached:'
for l in apparatus:
if int(l[2])==0: det_mode = 'pair'
elif int(l[2])==1: det_mode = 'trailing only'
elif int(l[2])==2: det_mode = 'leading only'
elif int(l[2])==3: det_mode = 'trailing/leading'
if int(l[3])==0: acq_mode = 'continuous storage'
elif int(l[3])==1: acq_mode = 'trigger matching'
print ' (board%i) %16s on board 0x%08x -- %s mode (%s)' % (l[0], l[4], l[1], acq_mode, det_mode)
if __name__=='__main__':
main(argv)
<file_sep>/test/quartic_occupancy_vs_run.cpp
#include "FileReader.h"
#include "QuarticCanvas.h"
#include <dirent.h>
using namespace std;
int main(int argc, char* argv[]) {
if (argc<4) { cerr << "Usage: " << argv[0] << " <board id> <run id> <trigger start> [trigger stop=-1]" << endl; exit(0); }
const unsigned int num_channels = 32;
int board_id = atoi(argv[1]);
int run_id = atoi(argv[2]);
int trigger_start = atoi(argv[3]), trigger_stop = -1;
if (argc>4) trigger_stop = atoi(argv[4]);
DQM::QuarticCanvas* occ = new DQM::QuarticCanvas(Form("occupancy_run%d_triggers%d-%d_board%d", run_id, trigger_start, trigger_stop, board_id), "Integrated occup. / trigger");
DQM::QuarticCanvas* start = new DQM::QuarticCanvas(Form("leadingedge_run%d_triggers%d-%d_board%d", run_id, trigger_start, trigger_stop, board_id), "Mean lead.edge / trigger");
ostringstream search1, search2, file;
search2 << "_board" << board_id << ".dat";
DIR* dir; struct dirent* ent;
cout << "Search in directory: " << getenv("PPS_DATA_PATH") << endl;
VME::TDCMeasurement m; VME::TDCEvent e;
int num_triggers = 0, num_measurements_per_trigger[num_channels];
double time_lead[num_channels];
for (int sp=1; sp<10000000; sp++) { // we loop over all spills
search1.str(""); search1 << "events_" << run_id << "_" << sp << "_";
bool file_found = false; string filename;
// first we search for the proper file to open
if ((dir=opendir(getenv("PPS_DATA_PATH")))==NULL) return -1;
while ((ent=readdir(dir))!=NULL) {
if (string(ent->d_name).find(search1.str())!=string::npos and
string(ent->d_name).find(search2.str())!=string::npos) {
file_found = true;
filename = ent->d_name;
break;
}
}
closedir(dir);
if (!file_found) {
cout << "Found " << sp << " files in this run" << endl;
break;
}
for (unsigned int i=0; i<num_channels; i++) {
time_lead[i] = 0.;
num_measurements_per_trigger[i] = 0;
}
// then we open it
file.str(""); file << getenv("PPS_DATA_PATH") << "/" << filename;
cout << "Opening file " << file.str() << endl;
try {
FileReader f(file.str());
while (true) {
if (!f.GetNextEvent(&e)) break;
if (e.GetType()==VME::TDCEvent::GlobalHeader) {
for (unsigned int i=0; i<num_channels; i++) {
time_lead[i] = 0.;
num_measurements_per_trigger[i] = 0;
}
num_triggers++;
}
if (num_triggers>trigger_stop and trigger_stop>0) break;
if (num_triggers>=trigger_start and e.GetType()==VME::TDCEvent::TDCMeasurement and !e.IsTrailing()) {
occ->FillChannel(e.GetChannelId(), 1);
unsigned int ch_id = e.GetChannelId();
time_lead[ch_id] += e.GetTime()*25./1024.;
num_measurements_per_trigger[ch_id]++;
}
if (e.GetType()==VME::TDCEvent::GlobalTrailer) {
for (unsigned int i=0; i<num_channels; i++) {
if (num_measurements_per_trigger[i]==0) continue;
cout << "channel " << i << ": " << time_lead[i]/num_measurements_per_trigger[i] << endl;
start->FillChannel(i, time_lead[i]/num_measurements_per_trigger[i]);
}
}
}
//f.Clear(); // we return to beginning of the file
} catch (Exception& e) { e.Dump(); }
}
cout << "num events = " << occ->Grid()->GetSumOfWeights() << endl;
cout << "num triggers = " << (num_triggers-trigger_start) << endl;
occ->Grid()->SetMaximum(0.15);
occ->Grid()->Scale(1./(num_triggers-trigger_start));
occ->SetRunInfo(board_id, run_id, 0, Form("Triggers %d-%d", trigger_start, trigger_stop));
occ->Save(Form("png"));
occ->Grid()->SetMaximum(1.e5);
start->Grid()->Scale(1./(num_triggers-trigger_start));
start->SetRunInfo(board_id, run_id, 0, Form("Triggers %d-%d", trigger_start, trigger_stop));
start->Save(Form("png"));
return 0;
}
<file_sep>/include/VME_TDCV1x90Opcodes.h
#ifndef VMETDCV1x90OPCODES_H
#define VMETDCV1x90OPCODES_H
namespace VME
{
namespace TDCV1x90Opcodes
{
#define Opcode static const unsigned short
// Acquisition mode
Opcode TRG_MATCH (0x0000);
Opcode CONT_STOR (0x0100);
Opcode READ_ACQ_MOD (0x0200);
Opcode SET_KEEP_TOKEN (0x0300);
Opcode CLEAR_KEEP_TOKEN (0x0400);
Opcode LOAD_DEF_CONFIG (0x0500);
Opcode SAVE_USER_CONFIG (0x0600);
Opcode LOAD_USER_CONFIG (0x0700);
Opcode AUTOLOAD_USER_CONF (0x0800);
Opcode AUTOLOAD_DEF_CONFI (0x0900);
// Trigger
Opcode SET_WIN_WIDTH (0x1000);
Opcode SET_WIN_OFFS (0x1100);
Opcode SET_SW_MARGIN (0x1200);
Opcode SET_REJ_MARGIN (0x1300);
Opcode EN_SUB_TRG (0x1400);
Opcode DIS_SUB_TRG (0x1500);
Opcode READ_TRG_CONF (0x1600);
// TDC edge detection & resolution
Opcode SET_DETECTION (0x2200);
Opcode READ_DETECTION (0x2300);
Opcode SET_TR_LEAD_LSB (0x2400);
Opcode SET_PAIR_RES (0x2500);
Opcode READ_RES (0x2600);
Opcode SET_DEAD_TIME (0x2800);
Opcode READ_DEAD_TIME (0x2900);
// TDC readout
Opcode EN_HEAD_TRAILER (0x3000);
Opcode DIS_HEAD_TRAILER (0x3100);
Opcode READ_HEAD_TRAILER (0x3200);
Opcode SET_EVENT_SIZE (0x3300);
Opcode READ_EVENT_SIZE (0x3400);
Opcode EN_ERROR_MARK (0x3500);
Opcode DIS_ERROR_MARK (0x3600);
Opcode EN_ERROR_BYPASS (0x3700);
Opcode DIS_ERROR_BYPASS (0x3800);
Opcode SET_ERROR_TYPES (0x3900);
Opcode READ_ERROR_TYPES (0x3a00);
Opcode SET_FIFO_SIZE (0x3b00);
Opcode READ_FIFO_SIZE (0x3c00);
// Channel enable/disable
Opcode EN_CHANNEL (0x4000); // FIXME channel number must be implemented
Opcode DIS_CHANNEL (0x4100); // FIXME channel number must be implemented
Opcode EN_ALL_CHANNEL (0x4200);
Opcode DIS_ALL_CHANNEL (0x4300);
Opcode WRITE_EN_PATTERN (0x4400);
Opcode READ_EN_PATTERN (0x4500);
Opcode WRITE_EN_PATTERN32 (0x4600);
Opcode READ_EN_PATTERN32 (0x4700);
// Adjust
Opcode SET_GLOB_OFFS (0x5000);
Opcode READ_GLOB_OFFS (0x5100);
Opcode SET_ADJUST_CH (0x5200);
Opcode READ_ADJUST_CH (0x5200);
Opcode SET_RC_ADJ (0x5400);
Opcode READ_RC_ADJ (0x5500);
Opcode SAVE_RC_ADJ (0x5600);
// Miscellaneous
Opcode READ_TDC_ID (0x6000);
Opcode READ_MICRO_REV (0x6100);
Opcode RESET_DLL_PLL (0x6200);
// Advanced
Opcode WRITE_SETUP_REG (0x7000);
Opcode READ_SETUP_REG (0x7100);
Opcode UPDATE_SETUP_REG (0x7200);
Opcode DEFAULT_SETUP_REG (0x7300);
Opcode READ_ERROR_STATUS (0x7400);
Opcode READ_DLL_LOCK (0x7500);
Opcode READ_STATUS_STREAM (0x7600);
Opcode UPDATE_SETUP_TDC (0x7700);
// Debug and test
Opcode WRITE_EEPROM (0xc000);
Opcode READ_EEPROM (0xc100);
Opcode REV_DATE_MICRO_FW (0xc200);
Opcode WRITE_SPARE (0xc300);
Opcode READ_SPARE (0xc400);
Opcode ENABLE_TEST_MODE (0xc500);
Opcode DISABLE_TEST_MODE (0xc600);
Opcode SET_TDC_TSET_OUTPUT(0xc700);
Opcode SET_DLL_CLOCK (0xc800);
Opcode READ_SETUP_SCANPATH(0xc900);
};
}
#endif
<file_sep>/include/VME_CFDV812.h
#ifndef VME_CFDV812_h
#define VME_CFDV812_h
#include "VME_GenericBoard.h"
#include <map>
#define num_cfd_channels 16
namespace VME
{
enum CFDV812Register
{
kV812ThresholdChannel0 = 0x00,
kV812OutputWidthGroup0 = 0x40,
kV812OutputWidthGroup1 = 0x42,
kV812DeadTimeGroup0 = 0x44,
kV812DeadTimeGroup1 = 0x46,
kV812MajorityThreshold = 0x48,
kV812PatternOfInhibit = 0x4a,
kV812TestPulse = 0x4c,
kV812FixedCode = 0xfa,
kV812Info0 = 0xfc,
kV812Info1 = 0xfe
};
/**
* \brief Controller for a CAEN V812 constant fraction discriminator
* \author <NAME> <<EMAIL>>
* \date 22 Jul 2015
*/
class CFDV812 : public GenericBoard<CFDV812Register,cvA24_U_DATA>
{
public:
CFDV812(int32_t bhandle, uint32_t baseaddr);
inline ~CFDV812() {;}
void CheckConfiguration() const;
unsigned short GetFixedCode() const;
unsigned short GetManufacturerId() const;
unsigned short GetModuleType() const;
unsigned short GetModuleVersion() const;
unsigned short GetSerialNumber() const;
/**
* \brief Set the pattern of inhibit (list of enabled channels)
*/
void SetPOI(unsigned short poi) const;
/**
* \brief Set the threshold for one single channel, in units of 1 mV
*/
void SetThreshold(unsigned short channel_id, unsigned short value) const;
/**
* \brief Set the discriminated pulse output width for one group of 8 channels
* \param[in] group_id Group of 8 channels (either 0 for 0-7, or 1 for 8-15)
*/
void SetOutputWidth(unsigned short group_id, unsigned short value) const;
/**
* \brief Set the discrimination dead time for one group of 8 channels
* \param[in] group_id Group of 8 channels (either 0 for 0-7, or 1 for 8-15)
*/
void SetDeadTime(unsigned short group_id, unsigned short value) const;
private:
float OutputWidthCalculator(unsigned short value) const;
float DeadTimeCalculator(unsigned short value) const;
};
/// Mapper from physical VME addresses to pointers to CFD objects
typedef std::map<uint32_t,VME::CFDV812*> CFDCollection;
}
#endif
<file_sep>/test/CMakeLists.txt
# Tests needing a ROOT instance
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} /usr/share/root/cmake)
find_package(ROOT)
if (ROOT_FOUND)
include_directories(${ROOT_INCLUDE_DIR})
link_directories(${ROOT_LIBRARY_DIR})
if(${ROOT_VERSION} LESS 6.0)
set(GCC_COMPILE_FLAGS "-Wno-shadow -fPIC")
else()
set(GCC_COMPILE_FLAGS "-Wno-shadow -fPIC -std=c++11")
endif()
add_definitions(${GCC_COMPILE_FLAGS})
endif()
function(ADD_TEST exec)
add_executable(${exec} ${PROJECT_SOURCE_DIR}/test/${exec}.cpp $<TARGET_OBJECTS:reader_lib>)
target_link_libraries(${exec} ${ROOT_LIBRARIES} ${ROOT_COMPONENT_LIBRARIES})
set_property(TARGET ${exec} PROPERTY EXCLUDE_FROM_ALL true)
endfunction()
if (ROOT_FOUND)
add_test(reader)
add_test(multireader)
add_test(write_tree)
add_test(reader_raw)
add_test(reader_channelid)
add_test(reader_oneedge)
add_test(errors)
add_test(quartic_occupancy_vs_run)
add_test(gastof_occupancy_vs_run)
add_test(gastof_full_occupancy_vs_run)
#add_test(reader_2boards)
add_test(write_tree_sorted)
endif()
add_test(testdb)
set_property(TARGET testdb PROPERTY LINK_FLAGS "-lsqlite3")
<file_sep>/test/reader_raw.cpp
#include <iostream>
#include "FileReader.h"
using namespace std;
using namespace VME;
int
main(int argc, char* argv[])
{
unsigned int channel_id = 0;
if (argc<2) {
cerr << "Usage:\n\t" << argv[0] << " <input file>" << endl;
return -1;
}
if (argc>=3) {
channel_id = atoi(argv[2]);
}
TDCMeasurement m;
TDCEvent e;
FileReader f(argv[1]);
cout << "Run/burst id: " << f.GetRunId() << " / " << f.GetBurstId() << endl;
cout << "Acquisition mode: " << f.GetAcquisitionMode() << endl;
cout << "Detection mode: " << f.GetDetectionMode() << endl;
while (true) {
try {
if (!f.GetNextEvent(&e)) break;
e.Dump();
} catch (Exception& e) { e.Dump(); }
}
return 0;
}
<file_sep>/include/VMEReader.h
#ifndef VMEReader_h
#define VMEReader_h
#include "Client.h"
#include "OnlineDBHandler.h"
#include "VME_BridgeVx718.h"
#include "VME_FPGAUnitV1495.h"
#include "VME_IOModuleV262.h"
#include "VME_CFDV812.h"
#include "VME_CAENETControllerV288.h"
#include "VME_TDCV1x90.h"
#include "NIM_HVModuleN470.h"
#include <map>
#include "tinyxml2.h"
/**
* VME reader object to fetch events on a HPTDC board
* \author <NAME> <<EMAIL>>
* \date 4 May 2015
*/
class VMEReader : public Client
{
public:
/**
* \param[in] device Path to the device (/dev/xxx)
* \param[in] type Bridge model
* \param[in] on_socket Are we trying to connect through the socket?
*/
VMEReader(const char *device, VME::BridgeType type, bool on_socket=true);
virtual ~VMEReader();
/**
* \brief Load an XML configuration file
*/
void ReadXML(const char* filename);
inline void ReadXML(std::string filename) { ReadXML(filename.c_str()); }
enum GlobalAcqMode { ContinuousStorage = 0x0, TriggerStart = 0x1, TriggerMatching = 0x2 };
inline GlobalAcqMode GetGlobalAcquisitionMode() const { return fGlobalAcqMode; }
/**
* \brief Add a TDC to handle
* \param[in] address 32-bit address of the TDC module on the VME bus
* Create a new TDC handler for the VME bus
*/
void AddTDC(uint32_t address);
/**
* \brief Get a TDC on the VME bus
* Return a pointer to the TDC object, given its physical address on the VME bus
*/
inline VME::TDCV1x90* GetTDC(uint32_t address) {
if (fTDCCollection.count(address)==0) return 0;
return fTDCCollection[address];
}
inline size_t GetNumTDC() const { return fTDCCollection.size(); }
inline VME::TDCCollection GetTDCCollection() { return fTDCCollection; }
void AddIOModule(uint32_t address);
inline VME::IOModuleV262* GetIOModule() { return fSG; }
/**
* \brief Add a CFD to handle
* \param[in] address 32-bit address of the CFD module on the VME bus
* Create a new CFD handler for the VME bus
*/
void AddCFD(uint32_t address);
/**
* \brief Get a CFD on the VME bus
* Return a pointer to the CFD object, given its physical address on the VME bus
*/
inline VME::CFDV812* GetCFD(uint32_t address) {
if (fCFDCollection.count(address)==0) return 0;
return fCFDCollection[address];
}
inline size_t GetNumCFD() const { return fCFDCollection.size(); }
inline VME::CFDCollection GetCFDCollection() { return fCFDCollection; }
/**
* \brief Add a multi-purposes FPGA board (CAEN V1495) to the crate controller
* \param[in] address 32-bit address of the TDC module on the VME bus
*/
void AddFPGAUnit(uint32_t address);
/// Return the pointer to the FPGA board connected to this controller (if any ; 0 otherwise)
inline VME::FPGAUnitV1495* GetFPGAUnit(uint32_t address) {
if (fFPGACollection.count(address)==0) return 0;
return fFPGACollection[address];
}
inline VME::FPGAUnitCollection GetFPGAUnitCollection() { return fFPGACollection; }
void NewRun() const;
inline void NewBurst() const {
try {
OnlineDBHandler().NewBurst();
} catch (Exception& e) {
usleep(2000); OnlineDBHandler().NewBurst();
}
}
/// Ask the socket master a run number
unsigned int GetRunNumber() const;
inline unsigned int GetBurstNumber() const { return OnlineDBHandler().GetLastBurst(GetRunNumber()); }
/// Start the bridge's pulse generator [faulty]
inline void StartPulser(double period, double width, unsigned int num_pulses=0) {
try {
fBridge->StartPulser(period, width, num_pulses);
fIsPulserStarted = true;
} catch (Exception& e) { throw e; }
}
/// Stop the bridge's pulse generator [faulty]
inline void StopPulser() {
try {
fBridge->StopPulser();
fIsPulserStarted = false;
} catch (Exception& e) { throw e; }
}
/// Send a single pulse to the output register/plug connected to TDC boards
inline void SendPulse(unsigned short output=0) const {
try {
fBridge->SinglePulse(output);
} catch (Exception& e) { e.Dump(); }
}
/// Send a clear signal to both the TDC boards
inline void SendClear(uint32_t addr) {
VME::FPGAUnitV1495* fFPGA = GetFPGAUnit(addr);
if (!fFPGA) return;
try {
fFPGA->PulseTDCBits(VME::FPGAUnitV1495::kClear);
} catch (Exception& e) { e.Dump(); }
}
/// Add a high voltage module (controlled by a VME-CAENET controller) to the DAQ
void AddHVModule(uint32_t vme_address, uint16_t nim_address);
/// Retrieve the NIM high voltage module
inline NIM::HVModuleN470* GetHVModule() { return fHV; }
/// Set the path to the output file where the DAQ is to write
void SetOutputFile(uint32_t tdc_address, std::string filename);
/// Return the path to the output file the DAQ is currently writing to
inline std::string GetOutputFile(uint32_t tdc_address) {
OutputFiles::iterator it = fOutputFiles.find(tdc_address);
if (it==fOutputFiles.end())
throw Exception(__PRETTY_FUNCTION__, "Failed to retrieve output file", JustWarning);
return it->second;
}
/// Send the path to the output file through the socket
void SendOutputFile(uint32_t tdc_address) const;
void BroadcastNewBurst(unsigned int burst_id) const;
void BroadcastTriggerRate(unsigned int burst_id, unsigned long num_triggers) const;
void BroadcastHVStatus(unsigned short channel_id, const NIM::HVModuleN470ChannelValues& val) const;
void LogHVValues(unsigned short channel_id, const NIM::HVModuleN470ChannelValues& val) const;
inline bool UseSocket() const { return fOnSocket; }
/// Abort data collection for all modules on the bus handled by the bridge
void Abort();
private:
/// The VME bridge object to handle
VME::BridgeVx718* fBridge;
/// A set of pointers to TDC objects indexed by their physical VME address
VME::TDCCollection fTDCCollection;
/// A set of pointers to CFD objects indexed by their physical VME address
VME::CFDCollection fCFDCollection;
/// Pointer to the VME input/output module object
VME::IOModuleV262* fSG;
/// Pointer to the VME general purpose FPGA unit object
VME::FPGAUnitCollection fFPGACollection;
/// Pointer to the VME CAENET controller
VME::CAENETControllerV288* fCAENET;
/// Pointer to the NIM high voltage module (passing through the CAENET controller)
NIM::HVModuleN470* fHV;
/// Are we dealing with socket message passing?
bool fOnSocket;
/// Is the bridge's pulser already started?
bool fIsPulserStarted;
typedef std::map<uint32_t, std::string> OutputFiles;
/// Path to the current output files the DAQ is writing to
/// (indexed by the TDC id)
OutputFiles fOutputFiles;
GlobalAcqMode fGlobalAcqMode;
};
#endif
<file_sep>/include/QuarticCanvas.h
#include "TCanvas.h"
#include "TPaveText.h"
#include "TLegend.h"
#include "TH2.h"
#include "TStyle.h"
#include "TDatime.h"
namespace DQM
{
/**
* \author <NAME> <<EMAIL>>
* \date 3 Aug 2015
*/
class QuarticCanvas : public TCanvas
{
public:
inline QuarticCanvas() :
TCanvas("null"), fLegend(0), fLegendX(.52), fLegendY(.76), fLegendNumEntries(0),
fUpperLabel(0), fLabelsDrawn(false), fBoardId(0), fRunId(0), fSpillId(0), fRunDate(TDatime().AsString()) {;}
inline QuarticCanvas(TString name, unsigned int width=500, unsigned int height=500, TString upper_label="") :
TCanvas(name, "", width, height), fWidth(width), fHeight(height), fLegend(0), fLegendX(.52), fLegendY(.76), fLegendNumEntries(0),
fUpperLabelText(upper_label), fUpperLabel(0), fLabelsDrawn(false),
fBoardId(0), fRunId(0), fSpillId(0), fRunDate(TDatime().AsString()) { Build(); }
inline QuarticCanvas(TString name, TString upper_label) :
TCanvas(name, "", 500, 500), fWidth(500), fHeight(500), fLegend(0), fLegendX(.52), fLegendY(.76), fLegendNumEntries(0),
fUpperLabelText(upper_label), fUpperLabel(0), fLabelsDrawn(false),
fBoardId(0), fRunId(0), fSpillId(0), fRunDate(TDatime().AsString()) { Build(); }
inline virtual ~QuarticCanvas() {
if (fLegend) delete fLegend;
if (fUpperLabel) delete fUpperLabel;
if (fHist) delete fHist;
}
inline void SetRunInfo(unsigned int board_id, unsigned int run_id, unsigned int spill_id, TString date) {
fBoardId = board_id;
fRunId = run_id;
fSpillId = spill_id;
fRunDate = date;
}
inline void SetUpperLabel(TString text) {
fUpperLabelText = text;
fUpperLabel = new TPaveText(.45, .922, .885, .952, "NDC");
fUpperLabel->SetMargin(0.);
fUpperLabel->SetFillColor(kWhite);
fUpperLabel->SetLineColor(kWhite);
fUpperLabel->SetLineWidth(0);
fUpperLabel->SetShadowColor(kWhite);
fUpperLabel->SetTextFont(43);
fUpperLabel->SetTextAlign(33);
fUpperLabel->SetTextSize(18);
fUpperLabel->AddText(fUpperLabelText);
fUpperLabel->Draw();
}
inline void FillChannel(unsigned short channel_id, double content) {
const Coord c = GetCoordinates(channel_id);
fHist->Fill(c.x, c.y, content);
}
inline TH2D* Grid() { return fHist; }
inline void Save(TString ext="png", TString path=".") {
bool valid_ext = true;
valid_ext |= (strcmp(ext, "png")!=0);
valid_ext |= (strcmp(ext, "pdf")!=0);
if (!valid_ext) return;
DrawGrid();
if (!fLabelsDrawn) {
fLabel1 = new TPaveText(.112, .925, .2, .955, "NDC");
fLabel1->AddText("Quartic");
fLabel1->SetMargin(0.);
fLabel1->SetFillColor(kWhite);
fLabel1->SetLineColor(kWhite);
fLabel1->SetLineWidth(0);
fLabel1->SetShadowColor(kWhite);
fLabel1->SetTextFont(63);
fLabel1->SetTextAlign(13);
fLabel1->SetTextSize(22);
fLabel1->Draw();
fLabel2 = new TPaveText(.29, .925, .36, .955, "NDC");
fLabel2->AddText("TB2015");
fLabel2->SetMargin(0.);
fLabel2->SetFillColor(kWhite);
fLabel2->SetLineColor(kWhite);
fLabel2->SetLineWidth(0);
fLabel2->SetShadowColor(kWhite);
fLabel2->SetTextFont(43);
fLabel2->SetTextAlign(13);
fLabel2->SetTextSize(22);
fLabel2->Draw();
if (fBoardId!=0 or fRunId!=0 or fSpillId!=0 or fRunDate!="") {
fLabel3 = new TPaveText(.5, .0, .98, .05, "NDC");
fLabel3->AddText(Form("Board %x, Run %d - Spill %d - %s", fBoardId, fRunId, fSpillId, fRunDate.Data()));
fLabel3->SetMargin(0.);
fLabel3->SetFillColor(kWhite);
fLabel3->SetLineColor(kWhite);
fLabel3->SetLineWidth(0);
fLabel3->SetShadowColor(kWhite);
fLabel3->SetTextFont(43);
fLabel3->SetTextAlign(32);
fLabel3->SetTextSize(16);
fLabel3->Draw();
}
fLabel4 = new TPaveText(.01, .5, .11, .55, "NDC");
fLabel4->AddText("#otimes beam");
fLabel4->SetMargin(0.);
fLabel4->SetFillColor(kWhite);
fLabel4->SetLineColor(kWhite);
fLabel4->SetLineWidth(0);
fLabel4->SetShadowColor(kWhite);
fLabel4->SetTextFont(43);
fLabel4->SetTextAlign(22);
fLabel4->SetTextSize(20);
fLabel4->SetTextAngle(90);
fLabel4->Draw();
if (fLegend->GetNRows()!=0) fLegend->Draw();
SetUpperLabel(fUpperLabelText);
fLabelsDrawn = true;
}
TCanvas::SaveAs(Form("%s/%s.%s", path.Data(), TCanvas::GetName(), ext.Data()));
c1->SetLogz();
TCanvas::SaveAs(Form("%s/%s_logscale.%s", path.Data(), TCanvas::GetName(), ext.Data()));
}
private:
inline void Build() {
fLegend = new TLegend(fLegendX, fLegendY, fLegendX+.35, fLegendY+.12);
fLegend->SetFillColor(kWhite);
fLegend->SetLineColor(kWhite);
fLegend->SetLineWidth(0);
fLegend->SetTextFont(43);
fLegend->SetTextSize(14);
// JH - testing, do we have channels off-scale by 1?
// fHist = new TH2D(Form("hist_%s", TCanvas::GetName()), "", 5, -0.5, 4.5, 4, -0.5, 3.5);
fHist = new TH2D(Form("hist_%s", TCanvas::GetName()), "", 5, 0.5, 5.5, 4, 0.5, 4.5); // LF - indeed...
// JH - end testing
for (unsigned int i=1; i<=5; i++) fHist->GetXaxis()->SetBinLabel(i, Form("%d", i));
for (unsigned int i=1; i<=4; i++) fHist->GetYaxis()->SetBinLabel(i, Form("%d", i));
}
inline void DrawGrid() {
TCanvas::cd();
gStyle->SetOptStat(0);
TCanvas::Divide(1,2);
c1 = (TPad*)TCanvas::GetPad(1);
c2 = (TPad*)TCanvas::GetPad(2);
c1->SetPad(0.,0.,1.,1.);
c2->SetPad(0.,0.,1.,0.);
c1->SetBottomMargin(0.1);
c1->SetLeftMargin(0.1);
c1->SetRightMargin(0.13);
c1->SetTopMargin(0.1);
TCanvas::cd(1);
fHist->Draw("colz");
fHist->SetMarkerStyle(20);
fHist->SetMarkerSize(.87);
fHist->SetTitleFont(43, "XYZ");
fHist->SetTitleSize(22, "XYZ");
//fHist->SetTitleOffset(2., "Y");
fHist->SetLabelFont(43, "XYZ");
fHist->SetLabelSize(24, "XY");
fHist->SetLabelSize(15, "Z");
fHist->SetTitleOffset(1.3, "Y");
c1->SetTicks(1, 1);
//c1->SetGrid(1, 1);
}
struct Coord { unsigned int x; unsigned int y; };
inline Coord GetCoordinates(unsigned short channel_id) const {
Coord out;
out.x = out.y = 0;
switch (channel_id) {
case 0: out.x = 5; out.y = 2; break;
case 1: out.x = 5; out.y = 4; break;
case 4: out.x = 5; out.y = 1; break;
case 5: out.x = 5; out.y = 3; break;
case 8: out.x = 4; out.y = 2; break;
case 9: out.x = 4; out.y = 4; break;
case 12: out.x = 4; out.y = 1; break;
case 13: out.x = 4; out.y = 3; break;
case 16: out.x = 3; out.y = 2; break;
case 17: out.x = 3; out.y = 4; break;
case 20: out.x = 3; out.y = 1; break;
case 21: out.x = 3; out.y = 3; break;
case 24: out.x = 2; out.y = 2; break;
case 25: out.x = 2; out.y = 4; break;
case 26: out.x = 2; out.y = 1; break;
case 27: out.x = 2; out.y = 3; break;
case 28: out.x = 1; out.y = 2; break;
case 29: out.x = 1; out.y = 4; break;
case 30: out.x = 1; out.y = 1; break;
case 31: out.x = 1; out.y = 3; break;
//default:
//std::cout << "unrecognized channel id: " << channel_id << std::endl; break;
}
return out;
}
TPad *c1, *c2;
TH2D* fHist;
double fWidth, fHeight;
TLegend *fLegend;
double fLegendX, fLegendY;
unsigned int fLegendNumEntries;
TPaveText *fLabel1, *fLabel2, *fLabel3, *fLabel4;
TString fUpperLabelText;
TPaveText *fUpperLabel;
bool fLabelsDrawn;
unsigned int fBoardId, fRunId, fSpillId;
TString fRunDate;
};
}
<file_sep>/include/PPSCanvas.h
#include "TCanvas.h"
#include "TPaveText.h"
#include "TLegend.h"
#include "TStyle.h"
#include "TDatime.h"
namespace DQM
{
/**
* \author <NAME> <<EMAIL>>
* \date 3 Aug 2015
*/
class PPSCanvas : public TCanvas
{
public:
inline PPSCanvas() :
TCanvas("null"), fLegend(0), fLegendX(.52), fLegendY(.76), fLegendNumEntries(0),
fUpperLabel(0), fLabelsDrawn(false), fRunId(0), fRunDate(TDatime().AsString()) {;}
inline PPSCanvas(TString name, unsigned int width=500, unsigned int height=500, TString upper_label="") :
TCanvas(name, "", width, height), fWidth(width), fHeight(height), fLegend(0), fLegendX(.52), fLegendY(.76), fLegendNumEntries(0),
fUpperLabelText(upper_label), fUpperLabel(0), fLabelsDrawn(false),
fRunId(0), fRunDate(TDatime().AsString()) { Build(); }
inline PPSCanvas(TString name, TString upper_label) :
TCanvas(name, "", 500, 500), fWidth(500), fHeight(500), fLegend(0), fLegendX(.52), fLegendY(.76), fLegendNumEntries(0),
fUpperLabelText(upper_label), fUpperLabel(0), fLabelsDrawn(false),
fRunId(0), fRunDate(TDatime().AsString()) { Build(); }
inline virtual ~PPSCanvas() {
if (fLegend) delete fLegend;
if (fUpperLabel) delete fUpperLabel;
}
inline void SetRunInfo(unsigned int run_id, TString date) {
fRunId = run_id;
fRunDate = date;
}
inline void SetUpperLabel(TString text) {
fUpperLabelText = text;
fUpperLabel = new TPaveText(.45, .922, .885, .952, "NDC");
fUpperLabel->SetMargin(0.);
fUpperLabel->SetFillColor(kWhite);
fUpperLabel->SetLineColor(kWhite);
fUpperLabel->SetLineWidth(0);
fUpperLabel->SetShadowColor(kWhite);
fUpperLabel->SetTextFont(43);
fUpperLabel->SetTextAlign(33);
fUpperLabel->SetTextSize(18);
fUpperLabel->AddText(fUpperLabelText);
fUpperLabel->Draw();
}
inline TPad* Grid() { return c1; }
inline void Save(TString ext="png", TString path=".") {
bool valid_ext = true;
valid_ext |= (strcmp(ext, "png")!=0);
valid_ext |= (strcmp(ext, "pdf")!=0);
if (!valid_ext) return;
if (!fLabelsDrawn) {
fLabel1 = new TPaveText(.112, .925, .17, .955, "NDC");
fLabel1->AddText("PPS");
fLabel1->SetMargin(0.);
fLabel1->SetFillColor(kWhite);
fLabel1->SetLineColor(kWhite);
fLabel1->SetLineWidth(0);
fLabel1->SetShadowColor(kWhite);
fLabel1->SetTextFont(63);
fLabel1->SetTextAlign(13);
fLabel1->SetTextSize(22);
fLabel1->Draw();
fLabel2 = new TPaveText(.21, .925, .36, .955, "NDC");
fLabel2->AddText("TB2015");
fLabel2->SetMargin(0.);
fLabel2->SetFillColor(kWhite);
fLabel2->SetLineColor(kWhite);
fLabel2->SetLineWidth(0);
fLabel2->SetShadowColor(kWhite);
fLabel2->SetTextFont(43);
fLabel2->SetTextAlign(13);
fLabel2->SetTextSize(22);
fLabel2->Draw();
fLabel3 = new TPaveText(.5, .0, .98, .05, "NDC");
fLabel3->AddText(Form("Run %d - %s", fRunId, fRunDate.Data()));
fLabel3->SetMargin(0.);
fLabel3->SetFillColor(kWhite);
fLabel3->SetLineColor(kWhite);
fLabel3->SetLineWidth(0);
fLabel3->SetShadowColor(kWhite);
fLabel3->SetTextFont(43);
fLabel3->SetTextAlign(32);
fLabel3->SetTextSize(16);
fLabel3->Draw();
if (fLegend->GetNRows()!=0) fLegend->Draw();
SetUpperLabel(fUpperLabelText);
fLabelsDrawn = true;
}
TCanvas::SaveAs(Form("%s/%s.%s", path.Data(), TCanvas::GetName(), ext.Data()));
c1->SetLogy();
TCanvas::SaveAs(Form("%s/%s_logscale.%s", path.Data(), TCanvas::GetName(), ext.Data()));
}
private:
inline void Build() {
fLegend = new TLegend(fLegendX, fLegendY, fLegendX+.35, fLegendY+.12);
fLegend->SetFillColor(kWhite);
fLegend->SetLineColor(kWhite);
fLegend->SetLineWidth(0);
fLegend->SetTextFont(43);
fLegend->SetTextSize(14);
DrawGrid();
}
inline void DrawGrid() {
TCanvas::cd();
gStyle->SetOptStat(0);
TCanvas::Divide(1,2);
c1 = (TPad*)TCanvas::GetPad(1);
c2 = (TPad*)TCanvas::GetPad(2);
c1->SetPad(0.,0.,1.,1.);
c2->SetPad(0.,0.,1.,0.);
c1->SetBottomMargin(0.12);
c1->SetLeftMargin(0.1);
c1->SetRightMargin(0.115);
c1->SetTopMargin(0.1);
TCanvas::cd(1);
c1->SetTicks(1, 1);
//c1->SetGrid(1, 1);
}
TPad *c1, *c2;
double fWidth, fHeight;
TLegend *fLegend;
double fLegendX, fLegendY;
unsigned int fLegendNumEntries;
TPaveText *fLabel1, *fLabel2, *fLabel3;
TString fUpperLabelText;
TPaveText *fUpperLabel;
bool fLabelsDrawn;
unsigned int fRunId;
TString fRunDate;
};
}
<file_sep>/test/write_tree_sorted.cpp
#include "FileReader.h"
#include "QuarticCanvas.h"
#include <dirent.h>
#include "TFile.h"
#include "TTree.h"
#define MAX_MEAS 10000
using namespace std;
int main(int argc, char* argv[]) {
if (argc<4) { cerr << "Usage: " << argv[0] << " <board id> <run id> <trigger start> [trigger stop=-1]" << endl; exit(0); }
const unsigned int num_channels = 32;
int board_id = atoi(argv[1]);
int run_id = atoi(argv[2]);
int trigger_start = atoi(argv[3]), trigger_stop = -1;
if (argc>4) trigger_stop = atoi(argv[4]);
string output = "output_test_sorted.root";
if (argc>5) output = argv[5];
int fNumMeasurements, fNumErrors;
int fRunId, fBurstId;
int fETTT, fTriggerNumber;
int fChannelId[MAX_MEAS];
double fLeadingEdge[MAX_MEAS], fTrailingEdge[MAX_MEAS], fToT[MAX_MEAS];
TFile* f = new TFile(output.c_str(), "recreate");
TTree* t = new TTree("tdc", "List of TDC measurements");
t->Branch("num_measurements", &fNumMeasurements, "num_measurements/I");
t->Branch("num_errors", &fNumErrors, "num_errors/I");
t->Branch("run_id", &fRunId, "run_id/I");
//t->Branch("burst_id", &fBurstId, "burst_id/I"); // need to be clever for this...
t->Branch("channel_id", fChannelId, "channel_id[num_measurements]/I");
t->Branch("leading_edge", fLeadingEdge, "leading_edge[num_measurements]/D");
t->Branch("trailing_edge", fTrailingEdge, "trailing_edge[num_measurements]/D");
t->Branch("tot", fToT, "tot[num_measurements]/D");
t->Branch("ettt", &fETTT, "ettt/I");
t->Branch("trigger_number",&fTriggerNumber,"trigger_number/I");
ostringstream search1, search2, file;
search2 << "_board" << board_id << ".dat";
DIR* dir; struct dirent* ent;
cout << "Search in directory: " << getenv("PPS_DATA_PATH") << endl;
VME::TDCMeasurement m; VME::TDCEvent e;
int num_triggers = 0, num_channel_measurements[num_channels];
double has_leading_per_trigger[num_channels];
for (int sp=1; sp<10000000; sp++) { // we loop over all spills
search1.str(""); search1 << "events_" << run_id << "_" << sp << "_";
bool file_found = false; string filename;
// first we search for the proper file to open
if ((dir=opendir(getenv("PPS_DATA_PATH")))==NULL) return -1;
while ((ent=readdir(dir))!=NULL) {
if (string(ent->d_name).find(search1.str())!=string::npos and
string(ent->d_name).find(search2.str())!=string::npos) {
file_found = true;
filename = ent->d_name;
break;
}
}
closedir(dir);
if (!file_found) {
cout << "Found " << sp << " files in this run" << endl;
break;
}
for (unsigned int i=0; i<num_channels; i++) {
num_channel_measurements[i] = 0;
has_leading_per_trigger[i] = 0;
}
// then we open it
file.str(""); file << getenv("PPS_DATA_PATH") << "/" << filename;
cout << "Opening file " << file.str() << endl;
try {
FileReader f(file.str());
while (true) {
if (!f.GetNextEvent(&e)) break;
if (e.GetType()==VME::TDCEvent::GlobalHeader) {
for (unsigned int i=0; i<num_channels; i++) {
num_channel_measurements[i] = 0;
has_leading_per_trigger[i] = 0;
}
num_triggers++;
fETTT = 0;
if(num_triggers % 1000 == 0)
cout << "Triggers received: " << num_triggers << endl;
fNumMeasurements = fNumErrors = 0;
if (num_triggers>trigger_stop and trigger_stop>0) break;
else if (num_triggers<trigger_start) continue;
// cout << "GlobalHeader, trigger number " << fTriggerNumber << endl;
fTriggerNumber = num_triggers;
}
else if (e.GetType()==VME::TDCEvent::TDCMeasurement) {
unsigned int ch_id = e.GetChannelId();
if (!e.IsTrailing()) {
has_leading_per_trigger[ch_id] = e.GetTime()*25./1024.;
// cout << "\tTDCMeasurement Leading edge: channel " << ch_id << ": " << has_leading_per_trigger[ch_id] << endl;
}
else {
double trailing_time = e.GetTime()*25./1024.;
// cout << "\tTDCMeasurement Trailing edge: channel " << ch_id << ": " << trailing_time << endl;
// cout << "\tTDCMeasurement Trailing edge: channel " << ch_id << ": " << trailing_time-has_leading_per_trigger[ch_id] << endl;
if (has_leading_per_trigger[ch_id]==0.) continue;
fChannelId[fNumMeasurements] = ch_id;
fLeadingEdge[fNumMeasurements] = has_leading_per_trigger[ch_id];
fTrailingEdge[fNumMeasurements] = trailing_time;
fToT[fNumMeasurements] = fTrailingEdge[fNumMeasurements]-fLeadingEdge[fNumMeasurements];
num_channel_measurements[ch_id]++;
fNumMeasurements++;
has_leading_per_trigger[ch_id] = 0.;
}
}
else if (e.GetType()==VME::TDCEvent::ETTT) {
fETTT = e.GetETTT()<<5;
}
else if (e.GetType()==VME::TDCEvent::GlobalTrailer) {
// cout << "GlobalTrailer, trigger number " << fTriggerNumber << endl;
fETTT += e.GetGeo();
for (unsigned int i=0; i<num_channels; i++) {
if (num_channel_measurements[i]==0) continue;
// cout << "GlobalTrailer: channel num. measurements " << i << ": " << num_channel_measurements[i] << endl;
}
if (num_triggers>trigger_stop and trigger_stop>0) break;
else if (num_triggers<trigger_start) continue;
t->Fill();
}
}
// f.Clear(); // we return to beginning of the file
} catch (Exception& e) { e.Dump(); }
}
t->Write();
return 0;
}
<file_sep>/src/VME_CAENETControllerV288.cpp
#include "VME_CAENETControllerV288.h"
namespace VME
{
CAENETControllerV288::CAENETControllerV288(int32_t bhandle, uint32_t baseaddr) :
GenericBoard<CAENETControllerV288Register,cvA24_U_DATA>(bhandle, baseaddr)
{
//Reset();
}
CAENETControllerV288::~CAENETControllerV288()
{;}
void
CAENETControllerV288::Reset() const
{
try {
WriteRegister(kV288ModuleReset, (uint16_t)0x1);
if (GetStatus().GetOperationStatus()!=CAENETControllerV288Status::Valid)
throw Exception(__PRETTY_FUNCTION__, "Wrong status retrieved", JustWarning);
} catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Failed to reset the CAENET/VME interface module", JustWarning);
}
usleep(5000);
}
void
CAENETControllerV288::SendBuffer() const
{
uint16_t word = MSTIDENT;
try {
WriteRegister(kV288Transmission, word);
CAENETControllerV288Answer resp;
if (!WaitForResponse(&resp)) {
std::ostringstream os; os << "Wrong response retrieved: " << resp;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
usleep(50000);
} catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Failed to send buffer through the CAENET interface", JustWarning);
}
}
std::vector<uint16_t>
CAENETControllerV288::FetchBuffer(unsigned int num_words=1) const
{
std::vector<uint16_t> out;
for (unsigned int i=0; i<num_words; i++) {
uint16_t buf;
*this >> buf;
out.push_back(buf);
}
return out;
}
CAENETControllerV288Status
CAENETControllerV288::GetStatus() const
{
uint16_t word = 0x0;
try { ReadRegister(kV288Status, &word); } catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Failed to retrieve the status word", JustWarning);
}
return CAENETControllerV288Status(word);
}
bool
CAENETControllerV288::WaitForResponse(CAENETControllerV288Answer* response, unsigned int max_trials) const
{
uint16_t word = 0x0;
unsigned int i = 0;
do {
ReadRegister(kV288DataBuffer, &word);
if (GetStatus().GetOperationStatus()==CAENETControllerV288Status::Valid and word!=0xff00) {
*response = static_cast<CAENETControllerV288Answer>(word);
return true;
}
} while (i<max_trials or max_trials<0);
return false;
}
}
<file_sep>/test/servesocket.py
#!/usr/bin/env python3
import asyncio
import websockets
@asyncio.coroutine
def hello(websocket, path):
print("starting server")
while websocket.open:
data = yield from websocket.recv()
message = str(data).strip()
# print(message, type(message))
print("< {}".format(message))
if "ADD_CLIENT:1" == message:
reply = "SET_CLIENT_ID:9"
elif "START_ACQUISITION" in message:
reply = "ACQUISITION_STARTED"
elif "STOP_ACQUISITION" in message:
reply = "ACQUISITION_STOPPED"
else:
reply = "Hello {}!".format(message)
if not websocket.open:
break
yield from websocket.send(reply)
print("> {}".format(reply))
start_server = websockets.serve(hello, 'localhost', 1987)
print("a;ldkf")
asyncio.get_event_loop().run_until_complete(start_server)
print("a;ldkf")
asyncio.get_event_loop().run_forever()
print("a;ldkf")
<file_sep>/include/Message.h
#ifndef Message_h
#define Message_h
#include <string>
#include <iostream>
#include "MessageKeys.h"
/**
* Base handler for messages to be transmitted through the socket
* \brief Base socket message type
* \author <NAME> <<EMAIL>>
* \date 6 Apr 2015
*/
class Message
{
public:
/// Void message constructor
inline Message() : fString("") {;}
/// Construct a message from a string
inline Message(const char* msg) : fString(msg) {;}
/// Construct a message from a string
inline Message(std::string msg) : fString(msg) {;}
inline virtual ~Message() {;}
/// Placeholder for the MessageKey retrieval method
inline MessageKey GetKey() const { return INVALID_KEY; }
/// Retrieve the string carried by this message as a whole
inline std::string GetString() const { return fString; }
/// Extract from any message its potential arrival from a WebSocket protocol
inline bool IsFromWeb() const {
if (fString.find("User-Agent")!=std::string::npos) return true;
return false;
}
inline void Dump(std::ostream& os=std::cout) const {
os << "=============== General Message dump ==============" << std::endl
<< " Value: " << fString << std::endl
<< "===================================================" << std::endl;
}
protected:
std::string fString;
};
#endif
<file_sep>/main.cpp
#include "Messenger.h"
#include "Client.h"
#include "FileConstants.h"
#include <iostream>
#include <fstream>
using namespace std;
Messenger* m = 0;
Client* l = 0;
int gEnd = 0;
void CtrlC(int aSig) {
if (gEnd==0) {
cout << endl << "[C-c] Trying a clean exit!" << endl;
if (m) { cout << "Trying to disconnect the messenger" << endl; delete m; }
if (l) { cout << "Trying to disconnect the first client" << endl; delete l; }
exit(0);
}
else if (gEnd>=5) {
cout << endl << "[C-c > 5 times] ... Forcing exit!" << endl;
exit(0);
}
gEnd++;
}
int main(int argc, char* argv[])
{
signal(SIGINT, CtrlC);
// Where to put the logs
ofstream err_log("master.err", ios::binary);
const Logger lr(err_log, cerr);
m = new Messenger(1987);
if (!m->Connect()) {
cout << "Failed to connect the messenger!" << endl;
return -1;
}
while (true) {
try { m->Receive(); } catch (Exception& e) { e.Dump(); }
}
delete m;
return 0;
}
<file_sep>/scripts/hv_status.py
import sqlite3
import os
from sys import argv
from datetime import datetime
def main(argv):
path = os.getenv('PPS_PATH', '/home/ppstb/pps-tbrc/build/')
conn = sqlite3.connect(path+'/run_infos.db')
c = conn.cursor()
if len(argv)<2:
c.execute('SELECT id,start FROM run ORDER BY id DESC LIMIT 1')
run_id, start_ts = c.fetchone()
print 'Last Run number is:', run_id
else:
run_id = int(argv[1])
c.execute('SELECT start FROM run WHERE id=%i' % (run_id))
start = c.fetchone()
if not start:
print 'Failed to find run %i in the database!' % (run_id)
exit(0)
print 'Run number:', run_id
start_ts = start[0]
print ' -- started on', datetime.fromtimestamp(int(start_ts))
c.execute('SELECT channel,v,i FROM hv WHERE run_id=%i'%(run_id))
apparatus = c.fetchall()
if len(apparatus)==0:
print ' -- no HV conditions retrieved'
else:
print ' -- HV conditions:'
for l in apparatus:
print ' (channel %i) Vbias = %d mV / Ic = %d uA' % (l[0], l[1], l[2])
if __name__=='__main__':
main(argv)
<file_sep>/include/OnlineDBHandler.h
#ifndef OnlineDBHandler_h
#define OnlineDBHandler_h
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <sstream>
#include <fstream>
#include <sqlite3.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "Exception.h"
static int callback(void* unused, int argc, char* argv[], char* azcolname[])
{
for (int i=0; i<argc; i++) {
std::cerr << azcolname[i] << " = " << (argv[i] ? argv[i] : "NULL") << std::endl;
}
return 0;
}
/**
* \brief Handler for the run information online database
* \author <NAME> <<EMAIL>>
* \date 3 Aug 2015
*/
class OnlineDBHandler
{
public:
inline OnlineDBHandler(std::string path=std::string(std::getenv("PPS_PATH"))+"/run_infos.db") {
int rc;
bool build_tables;
std::ifstream test(path.c_str());
if (test.good()) { test.close(); build_tables = false; }
else build_tables = true;
rc = sqlite3_open(path.c_str(), &fDB);
std::ostringstream os;
if (rc) {
os << "Cannot open online database file: " << sqlite3_errmsg(fDB);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, 60000);
}
if (build_tables) BuildTables();
}
inline ~OnlineDBHandler() { sqlite3_close(fDB); }
inline void NewRun() {
char* err = 0;
std::string req = "INSERT INTO run (id) VALUES (NULL)";
int rc = sqlite3_exec(fDB, req.c_str(), callback, 0, &err);
if (rc!=SQLITE_OK) {
std::ostringstream os;
os << "Error while trying to add a new run" << "\n\t"
<< "SQLite error: " << err;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, 60100);
}
}
inline void NewBurst() {
char* err = 0;
std::ostringstream req;
unsigned int current_run = GetLastRun();
int last_burst = 0;
try { last_burst = GetLastBurst(current_run); } catch (Exception& e) {
if (e.ErrorNumber()==60103) last_burst = -1;
}
req << "INSERT INTO burst (id, run_id, burst_id) VALUES (NULL, "
<< current_run << ", "
<< last_burst+1 << ");";
int rc = sqlite3_exec(fDB, req.str().c_str(), callback, 0, &err);
if (rc!=SQLITE_OK) {
std::ostringstream os;
os << "Error while trying to add a new burst" << "\n\t"
<< "SQLite error: " << err;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, 60101);
}
}
typedef std::map<unsigned int, unsigned int> RunCollection;
inline RunCollection GetRuns() const {
std::vector< std::vector<int> > out = Select<int>("SELECT id,start FROM run ORDER BY id");
if (out.size()==0) {
throw Exception(__PRETTY_FUNCTION__, "Trying to read runs in an empty database", JustWarning, 60200);
}
RunCollection ret;
for (std::vector< std::vector<int> >::iterator it=out.begin(); it!=out.end(); it++) {
ret.insert(std::pair<unsigned int, unsigned int>(it->at(0), it->at(1)));
}
return ret;
}
/// Retrieve the last run acquired
inline unsigned int GetLastRun() const {
std::vector< std::vector<int> > out = Select<int>("SELECT id FROM run ORDER BY id DESC LIMIT 1");
if (out.size()==1) return out[0][0];
if (out.size()==0) {
throw Exception(__PRETTY_FUNCTION__, "Trying to read the last run of an empty database", JustWarning, 60200);
}
if (out.size()>1) {
throw Exception(__PRETTY_FUNCTION__, "Corrupted database", JustWarning, 60010);
}
return 0;
}
inline int GetLastBurst(unsigned int run) const {
std::ostringstream os;
os << "SELECT burst_id FROM burst WHERE run_id=" << run << " ORDER BY burst_id DESC LIMIT 1";
std::vector< std::vector<int> > out = Select<int>(os.str());
if (out.size()==0) {
std::ostringstream os;
os << "Trying to read the last burst of a non-existant run: " << run;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, 60103);
}
else if (out.size()==1) return out[0][0];
return -1;
}
struct BurstInfo {
unsigned int burst_id;
unsigned int time_start;
};
typedef std::vector<BurstInfo> BurstInfos;
/// Retrieve information on a given run (spill IDs / timestamp)
inline BurstInfos GetRunInfo(unsigned int run) const {
std::ostringstream os;
BurstInfos ret; ret.clear();
os << "SELECT burst_id,start FROM burst WHERE run_id=" << run << " ORDER BY burst_id";
std::vector< std::vector<int> > out = Select<int>(os.str());
for (std::vector< std::vector<int> >::iterator it=out.begin(); it!=out.end(); it++) {
BurstInfo bi;
bi.burst_id = it->at(0);
bi.time_start = it->at(1);
ret.push_back(bi);
}
return ret;
}
inline void SetTDCConditions(unsigned short tdc_id, unsigned long tdc_address, unsigned short tdc_acq_mode, unsigned short tdc_det_mode, std::string detector) {
char* err = 0;
std::ostringstream req;
unsigned int current_run = GetLastRun();
req << "INSERT INTO tdc_conditions (id, run_id, tdc_id, tdc_address, tdc_acq_mode, tdc_det_mode, detector) VALUES (NULL, "
<< current_run << ", "
<< tdc_id << ", "
<< tdc_address << ", "
<< tdc_acq_mode << ", "
<< tdc_det_mode << ", \""
<< detector << "\");";
int rc = sqlite3_exec(fDB, req.str().c_str(), callback, 0, &err);
if (rc!=SQLITE_OK) {
std::ostringstream os;
os << "Error while trying to add a new TDC condition" << "\n\t"
<< "SQLite error: " << err;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, 60110);
}
}
struct TDCConditions {
unsigned int run_id;
unsigned short tdc_id; unsigned long tdc_address;
unsigned short tdc_acq_mode; unsigned short tdc_det_mode;
std::string detector;
bool operator==(const TDCConditions& rhs) const {
return (tdc_id==rhs.tdc_id
and tdc_address==rhs.tdc_address
and tdc_acq_mode==rhs.tdc_acq_mode
and tdc_det_mode==rhs.tdc_det_mode
and detector.compare(rhs.detector)==0); // we leave the run id out of the comparison operator
}
TDCConditions& operator=(const TDCConditions& rhs) {
run_id = rhs.run_id; tdc_id = rhs.tdc_id; tdc_address = rhs.tdc_address;
tdc_acq_mode = rhs.tdc_acq_mode; tdc_det_mode = rhs.tdc_det_mode; detector = rhs.detector;
return *this;
}
};
typedef std::vector<TDCConditions> TDCConditionsCollection;
inline TDCConditionsCollection GetTDCConditions(unsigned int run_id) const {
std::ostringstream os;
os << "SELECT tdc_id,tdc_address,tdc_acq_mode,tdc_det_mode FROM tdc_conditions"
<< " WHERE run_id=" << run_id;
std::vector< std::vector<int> > out = Select<int>(os.str());
if (out.size()==0) {
std::ostringstream s;
s << "No TDC conditions found in run " << run_id;
throw Exception(__PRETTY_FUNCTION__, s.str(), JustWarning);
}
TDCConditionsCollection ret;
for (std::vector< std::vector<int> >::iterator tdc=out.begin(); tdc!=out.end(); tdc++) {
TDCConditions cond;
cond.run_id = run_id;
cond.tdc_id = tdc->at(0);
cond.tdc_address = tdc->at(1);
cond.tdc_acq_mode = tdc->at(2);
cond.tdc_det_mode = tdc->at(3);
// Retrieve the dector name
try {
std::ostringstream s;
s << "SELECT detector FROM tdc_conditions"
<< " WHERE tdc_id=" << cond.tdc_id
<< " AND run_id=" << cond.run_id;
std::vector< std::vector<std::string> > ad = Select<std::string>(s.str());
if (ad.size()==1) cond.detector = (char*)ad[0][0].c_str();
else throw Exception(__PRETTY_FUNCTION__, "");
} catch (Exception& e) {
std::ostringstream s;
s << "Failed to retrieve the detector name in run " << run_id
<< " for TDC with base address 0x" << std::hex << cond.tdc_address;
throw Exception(__PRETTY_FUNCTION__, s.str(), JustWarning);
}
ret.push_back(cond);
}
return ret;
}
inline void SetHVConditions(unsigned short channel_id, unsigned int vmax, unsigned imax) {
char* err = 0;
std::ostringstream req;
unsigned int current_run = GetLastRun();
req << "INSERT INTO hv (id, run_id, channel, v, i) VALUES (NULL, "
<< current_run << ", "
<< channel_id << ", " << vmax << ", " << imax << ");";
int rc = sqlite3_exec(fDB, req.str().c_str(), callback, 0, &err);
if (rc!=SQLITE_OK) {
std::ostringstream os;
os << "Error while trying to add a new HV condition" << "\n\t"
<< "SQLite error: " << err;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, 60120);
}
}
private:
inline void BuildTables() {
int rc; char* err = 0;
std::string req;
// runs table
req = "CREATE TABLE run(" \
"id INTEGER PRIMARY KEY AUTOINCREMENT," \
"start INTEGER DEFAULT (CAST(strftime('%s', 'now') AS INT))" \
");";
rc = sqlite3_exec(fDB, req.c_str(), callback, 0, &err);
if (rc!=SQLITE_OK) {
std::ostringstream os;
os << "Error while trying to build the run table" << "\n\t"
<< "SQLite error: " << err;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, 60001);
}
// bursts table
req = "CREATE TABLE burst(" \
"id INTEGER PRIMARY KEY AUTOINCREMENT," \
"run_id INTEGER NOT NULL," \
"burst_id INTEGER NOT NULL," \
"start INTEGER DEFAULT (CAST(strftime('%s', 'now') AS INT))" \
");";
rc = sqlite3_exec(fDB, req.c_str(), callback, 0, &err);
if (rc!=SQLITE_OK) {
std::ostringstream os;
os << "Error while trying to build the burst table" << "\n\t"
<< "SQLite error: " << err;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, 60002);
}
// TDC run conditions table
req = "CREATE TABLE tdc_conditions(" \
"id INTEGER PRIMARY KEY AUTOINCREMENT," \
"run_id INTEGER NON NULL," \
"tdc_id INTEGER NON NULL," \
"tdc_address INTEGER NON NULL," \
"tdc_acq_mode INTEGER NON NULL," \
"tdc_det_mode INTEGER NON NULL," \
"detector CHAR(50)" \
");";
rc = sqlite3_exec(fDB, req.c_str(), callback, 0, &err);
if (rc!=SQLITE_OK) {
std::ostringstream os;
os << "Error while trying to build the TDC/detectors conditions table" << "\n\t"
<< "SQLite error: " << err;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, 60003);
}
// HV conditions table
req = "CREATE TABLE hv(" \
"id INTEGER PRIMARY KEY AUTOINCREMENT," \
"time INTEGER DEFAULT (CAST(strftime('%s', 'now') AS INT))," \
"run_id INTEGER NOT NULL," \
"channel INTEGER NOT NULL," \
"v INTEGER NOT NULL," \
"i INTEGER NOT NULL" \
");";
rc = sqlite3_exec(fDB, req.c_str(), callback, 0, &err);
if (rc!=SQLITE_OK) {
std::ostringstream os;
os << "Error while trying to build the HV conditions table" << "\n\t"
<< "SQLite error: " << err;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, 60004);
}
}
template<class T> inline std::vector< std::vector<T> > Select(std::string req, int num_fields=-1) const {
if (req.find(';')==std::string::npos) req += ";";
std::vector< std::vector<T> > out;
int rc;
sqlite3_stmt* stmt;
rc = sqlite3_prepare(fDB, req.c_str(), -1, &stmt, NULL);
if (rc!=SQLITE_OK) {
std::ostringstream os;
os << "Error while preparing the DB to select elements" << "\n\t"
<< "SQLite error: " << sqlite3_errmsg(fDB);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, 60010);
}
unsigned int idx = 0;
while (sqlite3_column_value(stmt, 0)) {
std::vector<T> line; line.clear();
if (num_fields<1) num_fields = sqlite3_column_count(stmt);
for (int i=0; i<num_fields; i++) {
std::stringstream data; data.str("");
switch (sqlite3_column_type(stmt, i)) {
case 1: data << (int)sqlite3_column_int(stmt, i); break;
case 2: data << (double)sqlite3_column_double(stmt, i); break;
case 3: data << (char*)sqlite3_column_text(stmt, i); break;
case 4: data << (char*)sqlite3_column_blob(stmt, i); break;
//case 5: data << (char*)sqlite3_column_bytes(stmt, i); break;
default: break;
}
T value; data >> value; line.push_back(value);
}
if (idx>0) out.push_back(line);
if (sqlite3_step(stmt)!=SQLITE_ROW) break;
idx++;
}
sqlite3_finalize(stmt);
return out;
}
sqlite3* fDB;
};
#endif
<file_sep>/scripts/DQMReader.py
#!/usr/bin/env python
# Simple python script for converting binary CTPPS HPTDC data files to human-readable format.
# Based on https://github.com/forthommel/pps-tbrc/src/FileReader.cpp C++ version by <NAME>
import os, string, sys, posix, tokenize, array, getopt, struct, ast
import matplotlib
matplotlib.use("Agg")
import numpy as np
import pylab as P
import matplotlib as mpl
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
class DQMReader:
def __init__(self,input):
#########################
# General script settings
#########################
# Input filename obtined from the server communication. Output file has the same name except for extension
if(input.find(".dat") == -1):
print "File sent to DQM is not in .dat format - exiting"
return
self.inputbinaryfile = input
self.outputplotfile = self.inputbinaryfile.split('.dat')[0] + '_dqm_report.svg'
self.outputtextfile = self.inputbinaryfile.split('.dat')[0] + '_dqm_report.txt'
self.nchannels = 32
self.ngroups = 4
self.verbose = 0
###################
# HPTDC definitions
###################
# AcquisitionMode
self.CONT_STORAGE=0
self.TRIG_MATCH=1
# DetectionMode
self.PAIR=0
self.OTRAILING=1
self.OLEADING=2
self.TRAILEAD=3
# EventTypes - for each TDC event in the file
self.TDCMeasurement = 0x0
self.TDCHeader = 0x1
self.TDCTrailer = 0x3
self.TDCError = 0x4
self.GlobalHeader = 0x8
self.GlobalTrailer = 0x10
self.ETTT = 0x11
self.Filler = 0x18
# Define counters and arrays for DQM plots
self.ntriggers = [0]
self.occupancy = []
self.baroccupancy = []
self.toverthreshold = []
k=0
while k < self.nchannels:
self.occupancy.append(0)
self.toverthreshold.append(0)
self.baroccupancy.append(0)
k=k+1
self.nerrors = [0]
self.grouperrors = []
self.readoutfifooverflowerrors = []
self.l1bufferoverflowerrors = []
k=0
while k < self.ngroups:
self.grouperrors.append(0)
self.readoutfifooverflowerrors.append(0)
self.l1bufferoverflowerrors.append(0)
k=k+1
self.eventsizelimiterrors = [0]
self.triggerfifooverflowerrors = [0]
self.internalchiperrors = [0]
self.channelmapping = {30:1, 26:2, 20:3, 12:4, 4:5, 28:6, 24:7, 16:8, 8:9, 0:10, 31:11, 27:12, 21:13, 13:14, 5:15, 29:16, 25:17, 17:18, 9:19, 1:20, 2:999, 3:999, 6:999, 7:999, 10:999, 11:999, 14:999, 15:999, 18:999, 19:999, 22:999, 23:999 }
def SetNChannelsToPlot(self,nchan):
self.nchannels = nchan
def SetNGroupsToPlot(self,ngrp):
self.ngroups = ngrp
def SetVerbosity(self,level):
self.verbose = level
def SetOutputFileFormat(self,extension):
self.outputplotfile = self.outputplotfile.split('.')[0] + '.' + str(extension)
def SetInputFilename(self,infname):
self.inputbinaryfile = infname
def SetOutputFilename(self,outfname):
self.outputplotfile = outfname
def GetOutputFilename(self):
return self.outputplotfile
def ProcessBinaryFile(self):
self.ReadFile()
self.ProducePlots()
#############################################################
# Main method for analyzing a single binary HPTDC output file
#############################################################
def ReadFile(self):
with open(self.inputbinaryfile, 'rb') as f:
# First read and unpack the file header
byte = f.read(24)
decode = struct.unpack("IIIBII",byte[:24])
magic = decode[0]
run_id = decode[1]
spill_id = decode[2]
num_hptdc = decode[3]
AcquisitionMode = decode[4]
DetectionMode = decode[5]
if(self.verbose == 1):
print "File header"
print "\tmagic = " + str(magic) + " = " + str(hex(magic)) + " = " + str(hex(magic).split("0x")[1].decode("hex"))
print "\trun_id = " + str(run_id)
print "\tspill_id = " + str(spill_id)
print "\tnum_hptdc = " + str(num_hptdc)
print "\tAcquisitionMode = " + str(hex(AcquisitionMode))
print "\tDetectionMode = " + str(hex(DetectionMode))
# Lookup dictionary of time measurements: time = {Channel ID, Leading/Trailing edge}
channeltimemeasurements={}
k = 0
while k < self.nchannels:
channeltimemeasurements[k,1]=0
channeltimemeasurements[k,2]=0
k=k+1
###########################
# Main loop to read in data
###########################
while(f.read(1)):
f.seek(-1,1) # Stupid python tricks - read ahead 1 byte to check for eof
# Read and decode the "type" of this word. The type will determine what other information is present
decode = struct.unpack("I",f.read(4))
type = ((decode[0]) >> 27) & (0x1F)
if(type == self.GlobalHeader):
if(self.verbose == 1):
print "Global Header"
# Reset lookup dictionary for each new event
channeltimemeasurements={}
k = 0
while k < self.nchannels:
channeltimemeasurements[k,1]=0
channeltimemeasurements[k,2]=0
k=k+1
# This word is a global trailer - calculate summary timing information for all channels in this event
if(type == self.GlobalTrailer):
status = ((decode[0]) >> 24) & (0x7)
geo = (decode[0]) & (0x1F)
if(self.verbose == 1):
print "\tTiming measurements for this trigger:"
print"\t\tChannel\tLeading\t\tTrailing\tDifference"
channelflag=0
while channelflag < self.nchannels:
tleading = channeltimemeasurements[channelflag,1] * 25./1024.
ttrailing = channeltimemeasurements[channelflag,2] * 25./1024.
tdifference = (channeltimemeasurements[channelflag,1] - channeltimemeasurements[channelflag,2]) * 25./1024.
self.toverthreshold[channelflag] = self.toverthreshold[channelflag] + tdifference
if(self.verbose == 1):
print "\t\t" + str(channelflag) + ":\t" + str(tleading) + ",\t" + str(ttrailing) + ",\t" + str(tdifference)
channelflag = channelflag+1
if(self.verbose == 1):
print "Global Trailer (status = " + str(status) + ", Geo = " + str(geo) + ")"
if(type == self.TDCHeader):
tdcid = ((decode[0]) >> 24) & (0x3)
eventid = ((decode[0]) >> 12) & (0xFFF)
bunchid = (decode[0]) & (0xFFF)
if(self.verbose == 1):
print "\tTDC ID = " + str(tdcid)
print "\tEvent ID = " + str(eventid)
if(type == self.TDCTrailer):
wordcount = (decode[0]) & (0xFFF)
eventcount = ((decode[0]) >> 5) & (0x3FFFF)
if(self.verbose == 1):
print "\tWord count = " + str(wordcount)
print "\tEvent count = " + str(eventcount)
if(type == self.ETTT):
GetETT = (decode[0]) & (0x3FFFFFF)
if(self.verbose == 1):
print "ETT = " + str(GetETT)
self.ntriggers[0] = self.ntriggers[0] + 1
# This word is an actual TDC measurement - get the timing and leading/trailing edge informations
if(type == self.TDCMeasurement):
istrailing = ((decode[0]) >> 26) & (0x1)
time = (decode[0]) & (0x7FFFF)
if(DetectionMode == self.PAIR):
time = (decode[0]) & (0xFFF)
width = ((decode[0]) >> 12) & (0x7F)
channelid = ((decode[0]) >> 21) & (0x1F)
if(istrailing == 0):
channeltimemeasurements[channelid,1] = time
if(istrailing == 1):
channeltimemeasurements[channelid,2] = time
self.occupancy[channelid] = self.occupancy[channelid]+1
if(self.verbose == 1):
print "\tTDCMeasurement (trailing = " + str(istrailing) + ", time = " + str(time) + ", width = " + str(width) + ", (channel ID = " + str(channelid) + ")"
# This word is an Error - decode it and count each type of error
if(type == self.TDCError):
errorflag = (decode[0]) & (0x7FFF)
self.nerrors[0] = self.nerrors[0] + 1
if(((decode[0]) >> 12) & 0x1):
self.eventsizelimiterrors[0] = self.eventsizelimiterrors[0] + 1
if(((decode[0]) >> 13) & 0x1):
self.triggerfifooverflowerrors[0] = self.triggerfifooverflowerrors[0] + 1
if(((decode[0]) >> 14) & 0x1):
self.internalchiperrors[0] = self.internalchiperrors[0] +1
j = 0
while j < 4:
if(((decode[0]) >> (2+3*j)) & 0x1):
self.grouperrors[j] = self.grouperrors[j] + 1
if(((decode[0]) >> (1+3*j)) & 0x1):
self.l1bufferoverflowerrors[j] = self.l1bufferoverflowerrors[j] + 1
if(((decode[0]) >> (3*j)) & 0x1):
self.readoutfifooverflowerrors[j] = self.readoutfifooverflowerrors[j] + 1
if(self.verbose == 1):
print "Error detected: " + str(errorflag)
print "closing binary file"
####################
# Generate DQM plots
####################
def ProducePlots(self):
print "producing plots"
i = 0
while i < self.nchannels:
if(self.occupancy[i]>0):
self.toverthreshold[i] = self.toverthreshold[i]/self.occupancy[i] # Before normalizing counts
if(self.ntriggers[0]>0):
self.occupancy[i] = self.occupancy[i]/(1.0*self.ntriggers[0])
bar = self.channelmapping[i]
# print "Occupancy of channel " + str(i) + " is " + str(self.occupancy[i])
# print "Mapping channel " + str(i) + " to bar " + str(bar)
if(bar < 21):
self.baroccupancy[bar] = self.occupancy[i]
# print "Occupancy of bar " + str(bar) + " is " + str(self.baroccupancy[bar-1])
i = i + 1
print self.baroccupancy
mpl.rcParams['xtick.labelsize'] = 6
mpl.rcParams['ytick.labelsize'] = 6
plt.subplot(3, 3, 1)
plt.bar(range(0,1),self.ntriggers,width=1.0)
plt.ylabel('Triggered events',fontsize=6)
plt.figtext(0.15, 0.8, "N = " + str(self.ntriggers[0]))
plt.axis([0, 1, 0, max(self.ntriggers)*2],fontsize=6)
frame1 = plt.gca()
frame1.axes.get_xaxis().set_visible(False)
plt.grid(True)
plt.subplot(3, 3, 2)
# plt.bar(range(0,self.nchannels),self.occupancy)
# plt.xlabel('HPTDC Channel',fontsize=6)
# plt.ylabel('Occupancy',fontsize=6)
# plt.axis([0, self.nchannels, 0, max(self.occupancy)*2],fontsize=6)
# plt.grid(True)
plt.bar(range(0,self.nchannels),self.baroccupancy)
plt.xlabel('Quartic bar D_N',fontsize=6)
plt.ylabel('Occupancy',fontsize=6)
plt.axis([0, self.nchannels, 0, max(self.baroccupancy)*1.2],fontsize=6)
plt.grid(True)
plt.subplot(3, 3, 3)
plt.bar(range(0,self.nchannels),self.toverthreshold)
plt.xlabel('HPTDC Channel',fontsize=6)
plt.ylabel('Mean time over threshold [ns]',fontsize=6)
plt.axis([0, self.nchannels, 0, max(self.toverthreshold)*2])
plt.grid(True)
plt.subplot(3, 3, 4)
plt.bar(range(0,1),self.nerrors,width=1.0,color='r')
plt.ylabel('Total errors',fontsize=6)
plt.axis([0, 1, 0, 2])
if(self.nerrors[0]>0):
plt.axis([0, 1, 0, max(self.nerrors)*2])
frame2 = plt.gca()
frame2.axes.get_xaxis().set_visible(False)
plt.grid(True)
plt.subplot(3, 3, 5)
plt.bar(range(0,1),self.eventsizelimiterrors,width=1.0,color='r')
plt.ylabel('Event size errors',fontsize=6)
plt.axis([0, 1, 0, 2])
if(self.eventsizelimiterrors[0]>0):
plt.axis([0, 1, 0, max(self.eventsizelimiterrors)*2])
frame2 = plt.gca()
frame2.axes.get_xaxis().set_visible(False)
plt.grid(True)
plt.subplot(3, 3, 6)
plt.bar(range(0,1),self.triggerfifooverflowerrors,width=1.0,color='r')
plt.ylabel('Trigger FIFO overflow errors',fontsize=6)
plt.axis([0, 1, 0, 2])
if(self.triggerfifooverflowerrors[0]>0):
plt.axis([0, 1, 0, max(self.triggerfifooverflowerrors)*2])
frame2 = plt.gca()
frame2.axes.get_xaxis().set_visible(False)
plt.grid(True)
plt.subplot(3, 3, 7)
plt.bar(range(0,1),self.internalchiperrors,width=1.0,color='r')
plt.ylabel('Internal chip errors',fontsize=6)
plt.axis([0, 1, 0, 2])
if(self.internalchiperrors[0]>0):
plt.axis([0, 1, 0, max(self.internalchiperrors)*2])
frame2 = plt.gca()
frame2.axes.get_xaxis().set_visible(False)
plt.grid(True)
plt.subplot(3, 3, 8)
plt.bar(range(0,self.ngroups),self.readoutfifooverflowerrors,color='r')
plt.ylabel('Readout FIFO overflow errors',fontsize=6)
plt.xlabel('Group',fontsize=6)
plt.axis([0, self.ngroups, 0, 2])
if(max(self.readoutfifooverflowerrors)>0):
plt.axis([0, self.ngroups, 0, max(self.readoutfifooverflowerrors)*2])
frame2 = plt.gca()
plt.grid(True)
plt.subplot(3, 3, 9)
plt.bar(range(0,self.ngroups),self.l1bufferoverflowerrors,color='r')
plt.ylabel('L1 buffer overflow errors',fontsize=6)
plt.xlabel('Group',fontsize=6)
plt.axis([0, self.ngroups, 0, 2])
if(max(self.l1bufferoverflowerrors)>0):
plt.axis([0, self.ngroups, 0, max(self.l1bufferoverflowerrors)*2])
frame2 = plt.gca()
plt.grid(True)
plt.savefig(self.outputplotfile)
# Persistently store DQM results as simple text file
outputtextfilehandle = open(self.outputtextfile, 'w')
outputtextfilehandle.write(str(self.ntriggers)+'\n')
outputtextfilehandle.write(str(self.occupancy)+'\n')
outputtextfilehandle.write(str(self.toverthreshold)+'\n')
outputtextfilehandle.write(str(self.nerrors)+'\n')
outputtextfilehandle.write(str(self.eventsizelimiterrors)+'\n')
outputtextfilehandle.write(str(self.triggerfifooverflowerrors)+'\n')
outputtextfilehandle.write(str(self.internalchiperrors)+'\n')
outputtextfilehandle.write(str(self.readoutfifooverflowerrors)+'\n')
outputtextfilehandle.write(str(self.l1bufferoverflowerrors)+'\n')
outputtextfilehandle.close()
if __name__ == '__main__':
filename = '/home/ppstb/timing_data/events_451_0_1442384408_board3.dat'
if len(sys.argv)>1: filename = sys.argv[1]
reader = DQMReader(filename)
reader.SetVerbosity(1)
reader.ProcessBinaryFile()
# reader.ReadFile()
<file_sep>/include/VME_TDCEvent.h
#ifndef TDCEvent_h
#define TDCEvent_h
#include <vector>
#include "Exception.h"
namespace VME
{
/**
* \brief TDC acquisition mode
* \author <NAME> <<EMAIL>>
* \ingroup HPTDC
*/
enum AcquisitionMode {
CONT_STORAGE,
TRIG_MATCH,
};
enum DetectionMode {
PAIR = 0x0,
OTRAILING = 0x1,
OLEADING = 0x2,
TRAILEAD = 0x3
};
/**
* \brief Error flags handler
* \author <NAME> <<EMAIL>>
* \date 22 Jun 2015
* \ingroup HPTDC
*/
class TDCErrorFlag {
public:
inline TDCErrorFlag(uint16_t ef) : fWord(ef) {;}
//inline TDCErrorFlag(const TDCEvent& ev) : fWord(ev.GetWord()) {;}
inline virtual ~TDCErrorFlag() {;}
inline uint16_t GetWord() const { return fWord; }
inline friend std::ostream& operator<<(std::ostream& os, const TDCErrorFlag& ef) {
os << "Raw error word: ";
for (unsigned int i=0; i<15; i++) {
if (i%5==0) os << " ";
os << ((ef.fWord>>i)&0x1);
}
os << "\n\t";
for (unsigned int i=0; i<4; i++) {
os << "===== Hit error in group " << i << " ========================== " << ef.HasGroupError(i) << "\n\t"
<< " Read-out FIFO overflow: " << ef.HasReadoutFIFOOverflow(i) << "\n\t"
<< " L1 buffer overflow: " << ef.HasL1BufferOverflow(i) << "\n\t";
}
os << "Hits rejected because of programmed event size limit: " << ef.HasReachedEventSizeLimit() << "\n\t"
<< "Event lost (trigger FIFO overflow): " << ef.HasTriggerFIFOOverflow() << "\n\t"
<< "Internal fatal chip error has been detected: " << ef.HasInternalChipError();
return os;
}
inline void Dump() const {
std::ostringstream os; os << this;
PrintInfo(os.str());
}
/**
* \brief Check whether hits have been lost from read-out FIFO overflow in a given group
*/
inline bool HasReadoutFIFOOverflow(unsigned int group_id) const {
return static_cast<bool>((fWord>>(3*group_id))&0x1);
}
/**
* \brief Check whether hits have been lost from L1 buffer overflow in a given group
*/
inline bool HasL1BufferOverflow(unsigned int group_id) const {
return static_cast<bool>((fWord>>(1+3*group_id))&0x1);
}
/**
* \brief Check whether hits have been lost due to error in a given group
*/
inline bool HasGroupError(unsigned int group_id) const {
return static_cast<bool>((fWord>>(2+3*group_id))&0x1);
}
/**
* \brief Hits rejected because of programmed event size limit
*/
inline bool HasReachedEventSizeLimit() const { return static_cast<bool>((fWord>>12)&0x1); }
/**
* \brief Event lost (trigger FIFO overflow)
*/
inline bool HasTriggerFIFOOverflow() const { return static_cast<bool>((fWord>>13)&0x1); }
/**
* \brief Internal fatal chip error has been detected
*/
inline bool HasInternalChipError() const { return static_cast<bool>((fWord>>14)&0x1); }
private:
uint16_t fWord;
};
/**
* Object enabling to decipher any measurement/error/debug event returned by the
* HPTDC chip
* \brief HPTDC event parser
* \author <NAME> <<EMAIL>>
* \date 4 May 2015
* \ingroup HPTDC
*/
class TDCEvent
{
public:
enum EventType {
TDCMeasurement = 0x0,
TDCHeader = 0x1,
TDCTrailer = 0x3,
TDCError = 0x4,
GlobalHeader = 0x8,
GlobalTrailer = 0x10,
ETTT = 0x11,
Filler = 0x18,
Trigger = 0x1f
};
public:
inline TDCEvent() : fWord(0) {;}
inline TDCEvent(const TDCEvent& ev) : fWord(ev.fWord) {;}
inline TDCEvent(const uint32_t& word) : fWord(word) {;}
inline TDCEvent(const EventType& ev) : fWord(static_cast<uint16_t>(ev)<<27) {;}
inline virtual ~TDCEvent() {;}
inline void Dump() const {
std::stringstream ss;
ss << "Event dump\n\t"
<< "Type: 0x" << std::hex << GetType() << std::dec << "\n\t"
<< "Word:\n\t";
for (int i=31; i>=0; i--) {
ss << (unsigned int)((fWord>>i)&0x1);
if (i%4==0) ss << " ";
}
switch (GetType()) {
case TDCMeasurement: ss << "TDC measurement, channel " << GetChannelId() << ", trailing? " << IsTrailing(); break;
case TDCHeader: ss << "TDC header"; break;
case TDCTrailer: ss << "TDC trailer"; break;
case TDCError: ss << "TDC error"; break;
case GlobalHeader: ss << "Global header"; break;
case GlobalTrailer: ss << "Global trailer"; break;
case ETTT: ss << "ETTT"; break;
case Filler: ss << "Filler"; break;
case Trigger: ss << "Trigger"; break;
}
PrintInfo(ss.str());
}
inline void SetWord(const uint32_t& word) { fWord = word; }
inline uint32_t GetWord() const { return fWord; }
/// Type of packet read out from the TDC
inline EventType GetType() const {
return static_cast<EventType>((fWord>>27)&0x1F);
}
/// Programmed identifier of master TDC providing the event
inline unsigned int GetTDCId() const {
if (GetType()!=TDCHeader and GetType()!=TDCTrailer and GetType()!=TDCError) return 0;
return static_cast<unsigned int>((fWord>>24)&0x3);
}
/// Event identifier from event counter
inline uint16_t GetEventId() const {
if (GetType()!=TDCHeader and GetType()!=TDCTrailer) return 0;
return static_cast<uint16_t>((fWord>>12)&0xFFF);
}
/// Total number of words in event (including headers and trailers)
inline uint16_t GetWordCount() const {
if (GetType()!=TDCTrailer) return 0;
return static_cast<uint16_t>(fWord&0xFFF);
}
inline unsigned int GetGeo() const {
if (GetType()!=GlobalTrailer) return 0;
return static_cast<unsigned int>(fWord&0x1F);
}
/// Channel number for
inline unsigned int GetChannelId() const {
if (GetType()!=TDCMeasurement) return 0;
return static_cast<unsigned int>((fWord>>21)&0x1F);
}
/// Total number of events
inline uint32_t GetEventCount() const {
if (GetType()!=TDCTrailer) return 0;
return static_cast<uint32_t>((fWord>>5)&0x3FFFF);
}
/// Bunch identifier of trigger (or trigger time tag)
inline uint16_t GetBunchId() const {
if (GetType()!=TDCHeader) return 0;
return static_cast<uint16_t>(fWord&0xFFF);
}
/// Are we dealing with a trailing or a leading measurement?
inline bool IsTrailing() const {
if (GetType()!=TDCMeasurement) return 0;
return static_cast<bool>((fWord>>26)&0x1);
}
/// Extended trigger time tag
inline uint32_t GetETTT() const {
if (GetType()!=ETTT) return 0;
return static_cast<uint32_t>(fWord&0x3FFFFFF);
}
/**
* \brief Edge measurement in programmed time resolution
* \param[in] pair Are we dealing with a pair measurement? (only for leading time word)
*/
inline uint32_t GetTime(bool pair=false) const {
if (GetType()!=TDCMeasurement) return 0;
if (pair) return static_cast<uint32_t>(fWord&0xFFF);
else return static_cast<uint32_t>(fWord&0x7FFFF);
}
/// Width of pulse in programmed time resolution
inline unsigned int GetWidth() const {
if (GetType()!=TDCMeasurement) return 0;
return static_cast<unsigned int>((fWord>>12)&0x7F);
}
inline unsigned int GetStatus() const {
if (GetType()!=GlobalTrailer) return 0;
return static_cast<unsigned int>((fWord>>24)&0x7);
}
/// Return error flags if an error condition has been detected
inline TDCErrorFlag GetErrorFlags() const {
if (GetType()!=TDCError) return TDCErrorFlag(0);
return TDCErrorFlag(fWord&0x7FFF);
}
private:
uint32_t fWord;
};
typedef std::vector<TDCEvent> TDCEventCollection;
}
#endif
<file_sep>/include/VME_TDCV1x90.h
#ifndef VMETDCV1x90_H
#define VMETDCV1x90_H
#include <cmath>
#include <map>
#include <iomanip>
#include <string.h>
#include <stdio.h>
#include "VME_GenericBoard.h"
#include "VME_TDCEvent.h"
#include "VME_TDCV1x90Opcodes.h"
#define TDC_ACQ_START 20000
#define TDC_ACQ_STOP 20001
namespace VME
{
typedef enum {
MATCH_WIN_WIDTH = 0,
WIN_OFFSET = 1,
EXTRA_SEARCH_WIN_WIDTH = 2,
REJECT_MARGIN = 3,
TRIG_TIME_SUB = 4,
} trig_conf;
typedef enum {
r800ps = 0,
r200ps = 1,
r100ps = 2,
r25ps = 3,
} trailead_edge_lsb;
typedef enum {
WRITE_OK = 0, /*!< \brief Is the TDC ready for writing? */
READ_OK = 1, /*!< \brief Is the TDC ready for reading? */
} micro_handshake;
struct GlobalOffset {
uint16_t coarse;
uint16_t fine;
};
// Event structure (one for each trigger)
struct trailead_t {
uint32_t event_count;
int total_hits[16];
// key -> channel,
// value -> measurement
std::multimap<int32_t,int32_t> leading;
std::multimap<int32_t,int32_t> trailing;
uint32_t ettt;
};
/**
* \brief TDC status register
* \author <NAME> <<EMAIL>>
* \date Jun 2015
*/
class TDCV1x90Status
{
public:
typedef enum {
R_800ps = 0x0,
R_200ps = 0x1,
R_100ps = 0x2,
R_25ps = 0x3
} TDCResolution;
inline TDCV1x90Status(const uint16_t& word) : fWord(word) {;}
virtual inline ~TDCV1x90Status() {;}
inline void Dump() const {
std::ostringstream ss;
ss << "============ TDC Status ============" << "\n\t"
<< "----- FIFO state: ---------------" << "\n\t"
<< "Data ready? " << DataReady() << "\n\t"
<< "FIFO almost full? " << AlmostFull() << "\n\t"
<< "FIFO full? " << Full() << "\n\t"
<< "FIFO purged? " << Purged() << "\n\t"
<< "---------------------------------" << "\n\t"
<< "Trigger matching mode? " << TriggerMatching() << "\n\t"
<< "Pair mode? " << PairMode() << "\n\t"
<< "Resolution: " << Resolution() << "\n\t"
<< "Headers enabled? " << HeadersEnabled() << "\n\t"
<< "Termination? " << TerminationOn() << "\n\t"
<< "----- Error state: --------------" << "\n\t"
<< "Global error: " << Error() << "\n\t";
for (unsigned int i=0; i<4; i++) ss << "\tError " << i << ": " << Error(i) << "\n\t";
ss << "Bus error: " << BusError() << "\n\t"
<< "---------------------------------" << "\n\t"
<< "Trigger lost? " << TriggerLost();
PrintInfo(ss.str());
}
inline uint16_t GetValue() const { return fWord; }
inline bool DataReady() const { return static_cast<bool>(fWord&0x1); }
inline bool AlmostFull() const { return static_cast<bool>((fWord>>1)&0x1); }
inline bool Full() const { return static_cast<bool>((fWord>>2)&0x1); }
inline bool TriggerMatching() const { return static_cast<bool>((fWord>>3)&0x1); }
inline bool HeadersEnabled() const { return static_cast<bool>((fWord>>4)&0x1); }
inline bool TerminationOn() const { return static_cast<bool>((fWord>>5)&0x1); }
inline bool Error(const unsigned int& id) const { return static_cast<bool>((fWord>>(6+id))&0x1); }
inline bool Error() const { return (Error(0) or Error(1) or Error(2) or Error(3)); }
inline bool BusError() const { return static_cast<bool>((fWord>>10)&0x1); }
inline bool Purged() const { return static_cast<bool>((fWord>>11)&0x1); }
inline TDCResolution Resolution() const { return static_cast<TDCResolution>((fWord>>12)&0x3); }
inline bool PairMode() const { return static_cast<bool>((fWord>>14)&0x1); }
inline bool TriggerLost() const { return static_cast<bool>((fWord>>15)&0x1); }
private:
uint16_t fWord;
};
/**
* \brief TDC control register
* \author <NAME> <<EMAIL>>
* \date Jun 2015
*/
class TDCV1x90Control
{
public:
inline TDCV1x90Control(const uint16_t& word) : fWord(word) {;}
inline virtual ~TDCV1x90Control() {;}
inline void Dump() const {
std::ostringstream ss;
ss << "============ TDC Control ============\n\t"
<< "Bus error? " << GetBusError() << "\n\t"
<< "Termination? " << GetTermination() << "\n\t"
<< "Termination (SW)? " << GetSWTermination() << "\n\t"
<< "Empty events? " << GetEmptyEvent() << "\n\t"
<< "Align word sizes to even number? " << GetAlign64() << "\n\t"
<< "Compensation? " << GetCompensation() << "\n\t"
<< "FIFO test? " << GetTestFIFO() << "\n\t"
<< "Compensation (SRAM)? " << GetSRAMCompensation() << "\n\t"
<< "Event FIFO? " << GetEventFIFO() << "\n\t"
<< "ETTT? " << GetETTT() << "\n\t"
<< "MEB access with 16MB address range? " << GetMEBAccess();
PrintInfo(ss.str());
}
inline uint16_t GetValue() const { return fWord; }
inline bool GetBusError() const { return static_cast<bool>(fWord&0x1); }
inline void SetBusError(bool sw) { if (sw==GetBusError()) return; int sign = (sw)?1:-1; fWord+=sign; }
inline bool GetTermination() const { return static_cast<bool>((fWord>>1)&0x1); }
inline void SetTermination(bool sw) { if (sw==GetTermination()) return; int sign = (sw)?1:-1; fWord+=(sign*0x1<<1); }
inline bool GetSWTermination() const { return static_cast<bool>((fWord>>2)&0x1); }
inline void SetSWTermination(bool sw) { if (sw==GetSWTermination()) return; int sign = (sw)?1:-1; fWord+=(sign*0x1<<2); }
inline bool GetEmptyEvent() const { return static_cast<bool>((fWord>>3)&0x1); }
inline void SetEmptyEvent(bool sw) { if (sw==GetEmptyEvent()) return; int sign = (sw)?1:-1; fWord+=(sign*0x1<<3); }
inline bool GetAlign64() const { return static_cast<bool>((fWord>>4)&0x1); }
inline void SetAlign64(bool sw) { if (sw==GetAlign64()) return; int sign = (sw)?1:-1; fWord+=(sign*0x1<<4); }
inline bool GetCompensation() const { return static_cast<bool>((fWord>>5)&0x1); }
inline void SetCompensation(bool sw) { if (sw==GetCompensation()) return; int sign = (sw)?1:-1; fWord+=(sign*0x1<<5); }
inline bool GetTestFIFO() const { return static_cast<bool>((fWord>>6)&0x1); }
inline void SetTestFIFO(bool sw) { if (sw==GetTestFIFO()) return; int sign = (sw)?1:-1; fWord+=(sign*0x1<<6); }
inline bool GetSRAMCompensation() const { return static_cast<bool>((fWord>>7)&0x1); }
inline void SetSRAMCompensation(bool sw) { if (sw==GetSRAMCompensation()) return; int sign = (sw)?1:-1; fWord+=(sign*0x1<<7); }
inline bool GetEventFIFO() const { return static_cast<bool>((fWord>>8)&0x1); }
inline void SetEventFIFO(bool sw) { if (sw==GetEventFIFO()) return; int sign = (sw)?1:-1; fWord+=(sign*0x1<<8); }
inline bool GetETTT() const { return static_cast<bool>((fWord>>9)&0x1); }
inline void SetETTT(bool sw) { if (sw==GetETTT()) return; int sign = (sw)?1:-1; fWord+=(sign*0x1<<9); }
inline bool GetMEBAccess() const { return static_cast<bool>((fWord>>12)&0x1); }
inline void SetMEBAccess(bool sw) { if (sw==GetMEBAccess()) return; int sign = (sw)?1:-1; fWord+=(sign*0x1<<12); }
private:
uint16_t fWord;
};
class TDCV1x90TriggerConfig
{
public:
inline TDCV1x90TriggerConfig() {
for (unsigned int i=0; i<5; i++) { fWords.push_back(0); }
}
inline ~TDCV1x90TriggerConfig() { fWords.clear(); }
inline void SetWord(unsigned int word_id, uint16_t word_content) {
if (word_id<0 or word_id>=fWords.size()) return;
fWords.at(word_id) = word_content;
}
inline void Dump() const {
std::ostringstream os;
os << "Window width: " << GetWindowWidth() << "\n\t"
<< "Window offset: " << GetWindowOffset() << "\n\t"
<< "Extra search window width: " << GetExtraSearchWindowWidth() << "\n\t"
<< "Reject margin: " << GetRejectMargin() << "\n\t"
<< "(all results are quoted in clock cycles)" << "\n\t"
<< "Trigger time subtraction? " << HasTriggerTimeSubtraction();
PrintInfo(os.str());
}
inline unsigned short GetWindowWidth() const { return static_cast<unsigned short>(fWords.at(0)&0xffff); }
inline short GetWindowOffset() const { return static_cast<short>(fWords.at(1)&0xffff); }
inline unsigned short GetExtraSearchWindowWidth() const { return static_cast<unsigned short>(fWords.at(2)&0xffff); }
inline unsigned short GetRejectMargin() const { return static_cast<unsigned short>(fWords.at(3)&0xffff); }
inline bool HasTriggerTimeSubtraction() const { return static_cast<bool>(fWords.at(4)&0xffff); }
private:
std::vector<uint16_t> fWords;
};
enum TDCV1x90Register {
kOutputBuffer = 0x0000, // D32 R
kControl = 0x1000, // D16 R/W
kStatus = 0x1002, // D16 R
kInterruptLevel = 0x100a, // D16 R/W
kInterruptVector = 0x100c, // D16 R/W
kGeoAddress = 0x100e, // D16 R/W
kMCSTBase = 0x1010, // D16 R/W
kMCSTControl = 0x1012, // D16 R/W
kModuleReset = 0x1014, // D16 W
kSoftwareClear = 0x1016, // D16 W
kEventCounter = 0x101c, // D32 R
kEventStored = 0x1020, // D16 R
kBLTEventNumber = 0x1024, // D16 R/W
kFirmwareRev = 0x1026, // D16 R
kMicro = 0x102e, // D16 R/W
kMicroHandshake = 0x1030, // D16 R
kEventFIFO = 0x1038, // D32 R
kEventFIFOStoredRegister = 0x103c, // D16 R
kEventFIFOStatusRegister = 0x103e, // D16 R
kROMOui2 = 0x4024,
kROMOui1 = 0x4028,
kROMOui0 = 0x402c,
kROMBoard2 = 0x4034,
kROMBoard1 = 0x4038,
kROMBoard0 = 0x403c,
kROMRevis3 = 0x4040,
kROMRevis2 = 0x4044,
kROMRevis1 = 0x4048,
kROMRevis0 = 0x404c,
kROMSerNum1 = 0x4080,
kROMSerNum0 = 0x4084,
};
/**
*
* \author <NAME> <<EMAIL>>
* \author <NAME> <<EMAIL>>
* \date Jun 2010 (NA62-Gigatracker)
* \date May 2015 (CMS-TOTEM PPS)
*/
class TDCV1x90 : public GenericBoard<TDCV1x90Register,cvA32_U_DATA>
{
public:
enum DLLMode {
DLL_Direct_LowRes = 0x0,
DLL_PLL_LowRes = 0x1,
DLL_PLL_MedRes = 0x2,
DLL_PLL_HighRes = 0x3
};
TDCV1x90(int32_t bhandle, uint32_t baseaddr);
~TDCV1x90();
void SetVerboseLevel(unsigned short verb=1) { fVerb=verb; }
void SetTestMode(bool en=true) const;
bool GetTestMode() const;
uint32_t GetModel() const;
uint32_t GetOUI() const;
uint32_t GetSerialNumber() const;
uint16_t GetFirmwareRevision() const;
void CheckConfiguration() const;
void EnableChannel(short) const;
void DisableChannel(short) const;
void SetPoI(uint16_t word1, uint16_t word2) const;
std::map<unsigned short, bool> GetPoI() const;
void SetLSBTraileadEdge(trailead_edge_lsb) const;
void SetAcquisitionMode(const AcquisitionMode&);
inline AcquisitionMode GetAcquisitionMode() {
ReadAcquisitionMode();
return fAcquisitionMode;
}
void SetTriggerMatching();
void SetContinuousStorage();
void SetDetectionMode(const DetectionMode& detm);
inline DetectionMode GetDetectionMode() {
ReadDetectionMode();
return fDetectionMode;
}
void SetDLLClock(const DLLMode& dll) const;
DLLMode GetDLLClock() const;
void SetGlobalOffset(const GlobalOffset&) const;
GlobalOffset GetGlobalOffset() const;
void SetRCAdjust(int,uint16_t) const;
uint16_t GetRCAdjust(int) const;
/**
* Number of acquired events since the latest module’s reset/clear;
* this counter works in trigger Matching Mode only.
* \brief Number of occured triggers
*/
uint32_t GetEventCounter() const;
/**
* \brief Number of events currently stored in the output buffer
*/
uint16_t GetEventStored() const;
void SetTDCEncapsulation(bool) const;
bool GetTDCEncapsulation() const;
void SetErrorMarks(bool mode=true);
inline bool GetErrorMarks() const { return fErrorMarks; }
void SetPairModeResolution(int,int) const;
uint16_t GetResolution() const;
void SetBLTEventNumberRegister(const uint16_t&) const;
uint16_t GetBLTEventNumberRegister() const;
/**
* Set the width of the match window (in number of clock cycles)
* \param[in] Window width, in units of clock cycles
*/
void SetWindowWidth(const uint16_t&);
inline uint16_t GetWindowWidth() const { return fWindowWidth; }
/**
* Set the offset of the match window with respect to the trigger itself, i.e. the
* time difference (expressed in clock cycles) between the start of the match window
* and the trigger time
* \param[in] Window offset, in units of clock cycles
*/
void SetWindowOffset(const int16_t&) const;
int16_t GetWindowOffset() const;
void SetTriggerTimeSubtraction(bool enabled=true) const;
TDCV1x90TriggerConfig GetTriggerConfiguration() const;
//uint16_t GetTriggerConfiguration(const trig_conf&) const;
bool SoftwareClear() const;
bool SoftwareReset() const;
bool HardwareReset() const;
inline void SetETTT(bool ettt=true) const {
TDCV1x90Control ctl = GetControl();
ctl.SetETTT(ettt);
SetControl(ctl);
}
inline bool GetETTT() const { return GetControl().GetETTT(); }
void SetStatus(const TDCV1x90Status&) const;
TDCV1x90Status GetStatus() const;
void SetControl(const TDCV1x90Control&) const;
TDCV1x90Control GetControl() const;
TDCEventCollection FetchEvents();
void SetChannelDeadTime(unsigned short dt) const;
unsigned short GetChannelDeadTime() const;
//bool IsEventFIFOReady();
void SetFIFOSize(const uint16_t&) const;
uint16_t GetFIFOSize() const;
// Close/Clean everything before exit
void abort();
private:
bool WaitMicro(const micro_handshake& mode) const;
void ReadAcquisitionMode();
void ReadDetectionMode();
unsigned short fVerb;
AcquisitionMode fAcquisitionMode;
DetectionMode fDetectionMode;
bool fErrorMarks;
uint16_t fWindowWidth;
uint32_t* fBuffer;
uint32_t nchannels;
bool gEnd;
std::string pair_lead_res[8];
std::string pair_width_res[16];
};
/// Mapper from physical VME addresses to pointers to TDC objects
typedef std::map<uint32_t,VME::TDCV1x90*> TDCCollection;
}
#endif
<file_sep>/src/VME_CFDV812.cpp
#include "VME_CFDV812.h"
namespace VME
{
CFDV812::CFDV812(int32_t bhandle, uint32_t baseaddr) :
GenericBoard<CFDV812Register,cvA24_U_DATA>(bhandle, baseaddr)
{
try {
CheckConfiguration();
} catch (Exception& e) {
e.Dump();
}
}
void
CFDV812::CheckConfiguration() const
{
try {
bool success = true;
success |= (GetManufacturerId()==0x2);
success |= (GetModuleType()==0x51);
if (!success) {
std::ostringstream os;
os << "Wrong configuration retrieved from CFD with base address 0x" << std::hex << fBaseAddr;
throw Exception(__PRETTY_FUNCTION__, os.str(), Fatal);
}
} catch (Exception& e) {
e.Dump();
std::ostringstream os; os << "Failed to retrieve configuration from CFD with base address 0x" << std::hex << fBaseAddr;
throw Exception(__PRETTY_FUNCTION__, os.str(), Fatal);
}
}
unsigned short
CFDV812::GetFixedCode() const
{
uint16_t word = 0x0;
try { ReadRegister(kV812FixedCode, &word); } catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Failed to retrieve the fixed code", JustWarning);
}
return static_cast<unsigned int>(word);
}
unsigned short
CFDV812::GetManufacturerId() const
{
uint16_t word = 0x0;
try { ReadRegister(kV812Info0, &word); } catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Failed to retrieve the manufacturer identifier", JustWarning);
}
return static_cast<unsigned int>((word>>10)&0x3f);
}
unsigned short
CFDV812::GetModuleType() const
{
uint16_t word = 0x0;
try { ReadRegister(kV812Info0, &word); } catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Failed to retrieve the module type", JustWarning);
}
return static_cast<unsigned int>(word&0x3ff);
}
unsigned short
CFDV812::GetModuleVersion() const
{
uint16_t word = 0x0;
try { ReadRegister(kV812Info1, &word); } catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Failed to retrieve the module version", JustWarning);
}
return static_cast<unsigned int>((word>>12)&0xf);
}
unsigned short
CFDV812::GetSerialNumber() const
{
uint16_t word = 0x0;
try { ReadRegister(kV812Info1, &word); } catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Failed to retrieve the serial number", JustWarning);
}
return static_cast<unsigned int>(word&0xfff);
}
void
CFDV812::SetPOI(unsigned short poi) const
{
try { WriteRegister(kV812PatternOfInhibit, poi); } catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Failed to set the pattern of inhibit", JustWarning);
}
}
void
CFDV812::SetThreshold(unsigned short channel_id, unsigned short value) const
{
if (channel_id<0 or channel_id>num_cfd_channels) return;
try {
CFDV812Register reg = static_cast<CFDV812Register>(kV812ThresholdChannel0+channel_id*0x2);
WriteRegister(reg, value);
} catch (Exception& e) {
e.Dump();
std::ostringstream os;
os << "Failed to set the threshold for channel " << channel_id;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
}
void
CFDV812::SetOutputWidth(unsigned short group_id, unsigned short value) const
{
uint16_t word = static_cast<uint16_t>(value&0xffff);
CFDV812Register reg;
if (group_id==0) reg = kV812OutputWidthGroup0;
else if (group_id==1) reg = kV812OutputWidthGroup1;
else throw Exception(__PRETTY_FUNCTION__, "Requested to change the output width of an unrecognized group identifier", JustWarning);
try {
WriteRegister(reg, word);
} catch (Exception& e) {
e.Dump();
std::ostringstream os;
os << "Failed to set output width for group " << group_id
<< " to value " << value << " (~" << OutputWidthCalculator(value) << " ns)";
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
std::ostringstream os;
os << "Output width from group " << group_id << " changed to ~" << OutputWidthCalculator(value) << " ns";
PrintInfo(os.str());
}
void
CFDV812::SetDeadTime(unsigned short group_id, unsigned short value) const
{
uint16_t word = static_cast<uint16_t>(value&0xffff);
CFDV812Register reg;
if (group_id==0) reg = kV812DeadTimeGroup0;
else if (group_id==1) reg = kV812DeadTimeGroup1;
else throw Exception(__PRETTY_FUNCTION__, "Requested to change the dead time of an unrecognized group identifier", JustWarning);
try {
WriteRegister(reg, word);
} catch (Exception& e) {
e.Dump();
std::ostringstream os;
os << "Failed to set dead time for group " << group_id
<< " to value " << value << " (~" << DeadTimeCalculator(value) << " ns)";
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
std::ostringstream os;
os << "Dead time from group " << group_id << " changed to ~" << DeadTimeCalculator(value) << " ns";
PrintInfo(os.str());
}
float
CFDV812::OutputWidthCalculator(unsigned short value) const
{
if (value>255 or value<0) return -1.;
std::map<unsigned short,float> lookup_table;
lookup_table[ 0] = 11.32; lookup_table[ 15] = 12.34; lookup_table[ 30] = 13.47;
lookup_table[ 45] = 14.75; lookup_table[ 60] = 16.07; lookup_table[ 75] = 17.51;
lookup_table[ 90] = 19.03; lookup_table[105] = 21.29; lookup_table[120] = 23.69;
lookup_table[135] = 26.71; lookup_table[150] = 30.61; lookup_table[165] = 35.20;
lookup_table[180] = 41.83; lookup_table[195] = 51.02; lookup_table[210] = 64.53;
lookup_table[225] = 87.47; lookup_table[240] =130.70; lookup_table[255] =240.70;
std::map<unsigned short,float>::iterator it;
if ((it=lookup_table.find(value))!=lookup_table.end()) return it->second;
else {
unsigned short last_id = 0; float last_value = -1.;
for (it=lookup_table.begin(); it!=lookup_table.end(); it++) {
if (value>it->first) { last_id = it->first; last_value = it->second; }
else return (last_value+(it->second-last_value)/(value-last_id));
}
}
return -1.;
}
float
CFDV812::DeadTimeCalculator(unsigned short value) const
{
if (value>255 or value<0) return -1.;
return (150.+(2000.-150.)/255*value);
}
}
<file_sep>/scripts/RunControl.py
#!/usr/bin/python
from sys import argv
import pygtk
pygtk.require('2.0')
import gtk, glib, gobject
import re
import time, signal
from SocketHandler import SocketHandler
from Plot import LinePlot
class DAQgui:
exc_rgx = re.compile(r'\[(.*)\] === (.*)\ === (.*)')
client_rgx = re.compile(r'(.*)\ \(type (.*)\)')
def __init__(self):
self.socket_handler = None
self.client_id = -1
self.acquisition_started = False
self.daq_loop_launched = False
self.current_run_id = -1
self.previous_burst_time = -1.
self.trigger_rate_data = [[0, 0.]]
self.time_start = time.time()
self.tot_trigger_data = [[self.time_start, 0]]
self.dqm_enabled = True
self.dqm_updated_plots = []
self.dqm_updated_plots_images = []
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
#self.window.maximize()
self.window.set_title("PPS Run control")
self.window.set_border_width(20)
main = gtk.VBox(False, 10)
top = gtk.HBox(False, 10)
bottom = gtk.HBox(False, 10)
buttons = gtk.VBox(False, 5)
run = gtk.VBox(False, 5)
top.pack_start(buttons, False)
buttons.show()
top.pack_start(run, False)
run.show()
main.pack_start(top, False)
self.dqm_frame = gtk.HBox(False)
main.pack_start(bottom, False)
main.pack_start(self.dqm_frame, False)
top.show()
bottom.show()
self.dqm_frame.show()
self.log_frame = gtk.ScrolledWindow()
self.log_view = gtk.TextView()
self.log_view.set_editable(False)
self.log_frame.set_size_request(200, 400)
#self.log = self.log_view.get_buffer()
self.log = gtk.TextBuffer()
self.log_view.set_buffer(self.log)
bottom.pack_start(self.log_frame)
self.log_frame.add(self.log_view)
self.log_frame.show()
self.log_view.show()
#self.stat_frame = gtk.ScrolledWindow()
self.stat_frame = gtk.VBox(False)
self.stat_frame.set_size_request(50, 400)
bottom.pack_start(self.stat_frame)
self.tot_trigger = gtk.Label()
self.stat_frame.pack_start(self.tot_trigger)
self.tot_trigger.set_markup('Triggers number: ###')
self.tot_trigger.set_alignment(0, 0)
self.tot_trigger.show()
self.trigger_rate = gtk.Label()
self.stat_frame.pack_start(self.trigger_rate)
self.trigger_rate.set_markup('Trigger rate: ###')
self.trigger_rate.set_alignment(0, 0)
self.trigger_rate.show()
self.hv_imon0 = gtk.Label()
self.stat_frame.pack_start(self.hv_imon0)
self.hv_imon0.set_markup('I(GasToF):###')
self.hv_imon0.set_alignment(0, 0)
self.hv_imon0.show()
self.hv_vmon0 = gtk.Label()
self.stat_frame.pack_start(self.hv_vmon0)
self.hv_vmon0.set_markup('V(GasToF):###')
self.hv_vmon0.set_alignment(0, 0)
self.hv_vmon0.show()
self.hv_imon1 = gtk.Label()
self.stat_frame.pack_start(self.hv_imon1)
self.hv_imon1.set_markup('I(reference timing):###')
self.hv_imon1.set_alignment(0, 0)
self.hv_imon1.show()
self.hv_vmon1 = gtk.Label()
self.stat_frame.pack_start(self.hv_vmon1)
self.hv_vmon1.set_markup('V(reference timing):###')
self.hv_vmon1.set_alignment(0, 0)
self.hv_vmon1.show()
self.plots_frame = gtk.HBox(False)
self.stat_frame.pack_start(self.plots_frame)
self.trigger_rate_plot = LinePlot()
self.trigger_rate_plot.set_size_request(-1, 300)
self.plots_frame.pack_start(self.trigger_rate_plot)
self.trigger_rate_plot.set_data(self.trigger_rate_data, 'Trigger rate')
self.trigger_rate_plot.show()
self.tot_trigger_plot = LinePlot()
self.plots_frame.pack_start(self.tot_trigger_plot)
self.tot_trigger_plot.set_data(self.trigger_rate_data, 'Triggers number')
self.plots_frame.set_size_request(-1, 300)
self.tot_trigger_plot.show()
#self.plots_frame.show()
self.stat_frame.show()
self.window.connect('destroy', self.Close)
self.bind_button = gtk.Button("Bind")
self.bind_button.connect('clicked', self.Bind)
self.bind_button.set_size_request(100, -1)
self.bind_button.set_tooltip_text("Bind this GUI instance to the main controller")
self.bind_button.set_sensitive(True)
buttons.pack_start(self.bind_button, False, False)
self.bind_button.show()
self.unbind_button = gtk.Button("Unbind")
self.unbind_button.connect('clicked', self.Unbind)
self.unbind_button.set_tooltip_text("Disconnect this instance from the main controller.\nIf any run is started it will be left as it is!")
self.unbind_button.set_sensitive(False)
buttons.pack_start(self.unbind_button, False)
self.unbind_button.show()
self.exit_button = gtk.Button("Quit")
self.exit_button.connect('clicked', self.Close)
self.exit_button.set_tooltip_text("Quit and disconnect this instance from the main controller")
buttons.pack_start(self.exit_button, False)
self.exit_button.show()
self.socket_id = gtk.Label()
self.socket_id.set_tooltip_text("Identifier of this instance to the socket")
buttons.pack_start(self.socket_id, False)
self.socket_id.set_markup('########')
self.socket_id.show()
self.start_button = gtk.Button("Start")
self.start_button.connect('clicked', self.StartAcquisition)
self.start_button.set_tooltip_text("Start a new run with the configuration provided in $PPS_PATH/config/config.xml")
#self.start_button.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0, 1, 0))
self.start_button.set_size_request(120, 60)
self.start_button.set_sensitive(False)
run.pack_start(self.start_button, False, False)
self.start_button.show()
self.stop_button = gtk.Button("Stop")
self.stop_button.connect('clicked', self.StopAcquisition)
self.stop_button.set_size_request(120, 30)
self.stop_button.set_sensitive(False)
run.pack_start(self.stop_button, False, False)
self.stop_button.show()
self.run_id = gtk.Label()
run.pack_start(self.run_id, False)
self.run_id.set_markup('Run id: ###')
self.run_id.show()
#self.list_clients = gtk.ListStore(int, int)
self.list_clients = gtk.Label()
self.list_clients.set_size_request(-1, 120)
top.pack_start(self.list_clients, True)
self.list_clients.show()
self.status_bar = gtk.Statusbar()
main.pack_start(self.status_bar)
self.status_bar.show()
#self.window.maximize()
self.window.set_default_size(1024, 668)
self.window.add(main)
main.show()
self.window.show()
def Bind(self, widget, data=None):
if self.socket_handler:
print "Warning: Socket already bound to master"
return
try:
self.socket_handler = SocketHandler('localhost', 1987)
self.socket_handler.Handshake(5) # 5=DAQ
self.bind_button.set_sensitive(False)
self.unbind_button.set_sensitive(True)
self.start_button.set_sensitive(not self.acquisition_started)
self.stop_button.set_sensitive(self.acquisition_started)
self.client_id = int(self.socket_handler.GetClientId())
self.socket_id.set_markup('Client id: <b>%d</b>' % self.client_id)
self.socket_handler.Send('GET_RUN_NUMBER', self.client_id)
res = self.socket_handler.Receive('RUN_NUMBER')
if res:
self.current_run_id = int(res[1])
self.run_id.set_markup('Run id: <b>%d</b>' % self.current_run_id)
glib.timeout_add(1000, self.Update)
self.Log('Client connected with id: %d' % self.client_id)
self.Update()
if self.acquisition_started and not self.daq_loop_launched:
#print "Launching the acquisition monitor loop."
self.DAQLoop()
except SocketHandler.SocketError:
print "Failed to bind!"
return
def Unbind(self, widget, data=None):
if self.socket_handler:
print "Requested to unbind from master"
if not self.socket_handler.Disconnect():
print 'forcing the stop'
self.socket_handler = None
print 'socket handler deleted'
self.socket_id.set_markup('########')
self.bind_button.set_sensitive(True)
self.unbind_button.set_sensitive(False)
self.start_button.set_sensitive(False)
self.stop_button.set_sensitive(False)
self.socket_handler = None
self.client_id = -1
def Close(self, widget, data=None):
self.Unbind(self)
gtk.main_quit()
def Update(self, source=None, condition=None):
if not self.socket_handler: return False
#print "Getting clients..."
self.socket_handler.Send('GET_CLIENTS', self.client_id)
rcv = self.socket_handler.Receive()
if len(rcv)<2: return True
if rcv[0]=='CLIENTS_LIST':
if ';' not in rcv[1]: return True
clients_list = []
for client in rcv[1].split(';'):
try: client_id, client_type = [int(v) for v in re.split(self.client_rgx, client)[1:3]]
except ValueError:
print "Wrong value for client list:", client
return True
clients_list.append({'id': client_id, 'type': client_type, 'me': (client_id==self.client_id), 'web': (client_type==2)})
if client_type==3: self.acquisition_started = True
self.UpdateClientsList(clients_list)
self.start_button.set_sensitive(not self.acquisition_started)
self.stop_button.set_sensitive(self.acquisition_started)
if self.acquisition_started and not self.daq_loop_launched:
#print "Launching the acquisition monitor loop."
self.DAQLoop()
return True
def DAQLoop(self):
gobject.io_add_watch(self.socket_handler, gobject.IO_IN, self.ReceiveDAQMasterMessages)
def ReceiveDAQMasterMessages(self, source, condition):
if not self.socket_handler: return False
if not self.acquisition_started: return False
if not self.daq_loop_launched: self.daq_loop_launched = True
rcv = source.Receive()
print 'received', rcv
if rcv[0]=='EXCEPTION':
type, func, log = re.split(self.exc_rgx, rcv[1])[1:4]
self.LogException(type, func, log)
elif rcv[0]=='RUN_NUMBER':
self.current_run_id = int(rcv[1])
self.run_id.set_markup('Run id: <b>%d</b>' % self.current_run_id)
self.dqm_updated_plots = []
self.dqm_updated_plots_images = []
elif rcv[0]=='NUM_TRIGGERS':
#return False
burst_id, num_trig = [int(a) for a in rcv[1].split(':')]
self.tot_trigger.set_markup('Triggers number: <b>%d</b>' % num_trig)
now = time.time()
self.tot_trigger_data.append([(now-self.time_start)*1e6, num_trig])
#self.tot_trigger_plot.set_data(self.tot_trigger_data)
if self.previous_burst_time>0:
rate = num_trig/(now-self.previous_burst_time)/1000.
self.trigger_rate.set_markup('Trigger rate: <b>%.2f kHz</b>' % round(rate, 2))
has_data = False
i = 0
#print 'aaa',self.trigger_rate_data
for data in self.trigger_rate_data:
if data[0]==burst_id:
self.trigger_rate_data[i][1] = rate
has_data = True
break
i += 1
if not has_data:
self.trigger_rate_data.append([burst_id, rate])
#print now, "trigger rate: ", rate
#self.trigger_rate_plot.set_data(self.trigger_rate_data, 'Trigger rate (kHz)')
self.previous_burst_time = now
return True
elif rcv[0]=='HV_STATUS':
channel, stat = rcv[1].split(':')
status, imon, vmon = [int(a) for a in stat.split(',')]
if channel=='0':
self.hv_imon0.set_markup('I(GasToF): <b>%d uA</b>' % imon)
self.hv_vmon0.set_markup('V(GasToF): <b>%d V</b>' % vmon)
elif channel=='3':
self.hv_imon1.set_markup('I(reference timing): <b>%d uA</b>' % imon)
self.hv_vmon1.set_markup('V(reference timing): <b>%d V</b>' % vmon)
return True
elif rcv[0]=='UPDATED_DQM_PLOT':
return True
if not self.dqm_enabled: return True
i = 0
for p in self.dqm_updated_plots:
if p==rcv[1] or rcv[1][0:15] in p:
if p!=rcv[1]: self.dqm_updated_plots[i] = rcv[1]
try:
pixbuf = gtk.gdk.pixbuf_new_from_file_at_size('/tmp/%s.png' % (rcv[1]), 200, 200)
self.dqm_updated_plots_images[i].set_from_pixbuf(pixbuf)
except glib.GError:
return True
return True
i += 1
self.dqm_updated_plots.append(rcv[1])
img = gtk.Image()
try:
pixbuf = gtk.gdk.pixbuf_new_from_file_at_size('/tmp/%s.png' % (rcv[1]), 200, 200)
img.set_from_pixbuf(pixbuf)
self.dqm_frame.pack_start(img)
self.dqm_updated_plots_images.append(img)
img.show()
except glib.GError:
return True
return True
def UpdateClientsList(self, clients_list):
#for client in clients_list:
# self.list_clients.append([client['id'], client['type']])
#columns = ["Id", "Type"]
#view = gtk.TreeView(model=self.list_clients)
#idx = 0
#for c in columns:
# col = gtk.TreeViewColumn(c, gtk.CellRendererText(), text=idx)
# view.append_column(col)
# idx += 1
out = ""
for c in clients_list:
#out += "Client %d, type %d (%s)\n" % (c['id'], c['type'], self.GetClientTypeName(c['type']))
out += "<b>%s</b> (%d) " % (self.GetClientTypeName(c['type']), c['id'])
self.list_clients.set_markup(out)
def GetClientTypeName(self, type):
if type==-1: return "INVALID"
elif type==0: return "MASTER"
elif type==1: return "WEB_CLIENT"
elif type==2: return "TERM_CLIENT"
elif type==3: return "DAQ"
elif type==4: return "DQM"
elif type==5: return "GUI"
def StartAcquisition(self, widget, data=None):
print "Requested to start acquisition"
self.socket_handler.Send('START_ACQUISITION', self.client_id)
rcv = self.socket_handler.Receive('ACQUISITION_STARTED')
self.acquisition_started = True
self.start_button.set_sensitive(not self.acquisition_started)
self.stop_button.set_sensitive(self.acquisition_started)
def StopAcquisition(self, widget, data=None):
print "Requested to stop acquisition"
self.socket_handler.Send('STOP_ACQUISITION', self.client_id)
rcv = self.socket_handler.Receive('ACQUISITION_STOPPED')
self.acquisition_started = False
self.start_button.set_sensitive(not self.acquisition_started)
self.stop_button.set_sensitive(self.acquisition_started)
def Log(self, data=None):
self.log.insert_at_cursor(data+'\n')
while gtk.events_pending():
gtk.main_iteration()
def LogException(self, code, func, message):
str = "%s" % (message)
self.Log(str)
def main(self):
gtk.main()
if __name__=='__main__':
signal.signal(signal.SIGINT, signal.SIG_DFL)
gui = DAQgui()
gui.main()
<file_sep>/test/reader.cpp
#include <iostream>
#include "FileReader.h"
#include "TCanvas.h"
#include "TH1.h"
#include "TF1.h"
#include "TLegend.h"
#include "TStyle.h"
using namespace std;
using namespace VME;
int
main(int argc, char* argv[])
{
unsigned int channel_id = 0;
if (argc<2) {
cerr << "Usage:\n\t" << argv[0] << " <input file>" << endl;
return -1;
}
if (argc>=3) {
channel_id = atoi(argv[2]);
}
TDCMeasurement m;
unsigned int num_events, num_triggers;
TH1D* hist_lead = new TH1D("lead", "", 700, -14000., 14000.);
TH1D* hist_trail = new TH1D("trail", "", 700, -14000., 14000.);
TH1D* hist_lead_zoom = new TH1D("lead_zoom", "", 600, 255., 325.);
TH1D* hist_trail_zoom = new TH1D("trail_zoom", "", 600, 255., 325.);
TH1D* hist_tot = new TH1D("tot", "", 100, 27., 29.);
TH1D* hist_numevts = new TH1D("nevts", "", 100, -.5, 99.5);
FileReader f(argv[1]);
cout << "Run/burst id: " << f.GetRunId() << " / " << f.GetBurstId() << endl;
cout << "Acquisition mode: " << f.GetAcquisitionMode() << endl;
cout << "Detection mode: " << f.GetDetectionMode() << endl;
//cout << f.GetNumTDCs() << " TDCs recorded" << endl;
num_triggers = num_events = 0;
while (true) {
try {
if (!f.GetNextMeasurement(channel_id, &m)) break;
m.Dump();
for (unsigned int i=0; i<m.NumEvents(); i++) {
//std::cout << "--> " << (m.GetToT(i)*25./1024.) << std::endl;
hist_lead->Fill(m.GetLeadingTime(i)*25./1024.);
hist_trail->Fill(m.GetTrailingTime(i)*25./1024.);
hist_lead_zoom->Fill(m.GetLeadingTime(i)*25./1024.);
hist_trail_zoom->Fill(m.GetTrailingTime(i)*25./1024.);
hist_tot->Fill(m.GetToT(i)*25./1024.);
//std::cout << "ettt=" << m.GetETTT() << std::endl;
}
num_events += m.NumEvents();
hist_numevts->Fill(m.NumEvents()-.5);
num_triggers += 1;
} catch (Exception& e) { e.Dump(); }
}
cerr << "total number of triggers: " << num_triggers << endl;
cerr << "mean number of events per trigger in channel " << channel_id << ": " << ((float)num_events/num_triggers) << endl;
gStyle->SetPadGridX(true); gStyle->SetPadGridY(true);
gStyle->SetPadTickX(true); gStyle->SetPadTickY(true);
TCanvas* c_time = new TCanvas;
TLegend* leg = new TLegend(0.15, 0.3, 0.35, 0.4);
hist_lead->Draw();
leg->AddEntry(hist_lead, "Leading edge");
hist_trail->Draw("same");
hist_trail->SetLineColor(kRed+1);
leg->AddEntry(hist_trail, "Trailing edge");
hist_lead->GetXaxis()->SetTitle("Hit edge time (ns)");
hist_lead->GetYaxis()->SetTitle(Form("Events in channel %d",channel_id));
leg->Draw();
c_time->SaveAs("dist_edgetime.png");
gStyle->SetOptStat(0);
TCanvas* c_time_zoom = new TCanvas;
TLegend* leg2 = new TLegend(0.45, 0.75, 0.85, 0.85);
hist_lead_zoom->Draw();
hist_trail_zoom->Draw("same");
hist_trail_zoom->SetLineColor(kRed+1);
hist_lead_zoom->GetXaxis()->SetTitle("Hit edge time (ns)");
hist_lead_zoom->GetYaxis()->SetTitle(Form("Events in channel %d",channel_id));
/*hist_lead_zoom->Fit("gaus", "0");
hist_trail_zoom->Fit("gaus", "0");
TF1* f1 = (TF1*)hist_lead_zoom->GetFunction("gaus");
TF1* f2 = (TF1*)hist_trail_zoom->GetFunction("gaus");
leg2->AddEntry(hist_lead_zoom, Form("Leading edge #mu=%.3g, #sigma=%.3g",f1->GetParameter(1),f1->GetParameter(2)), "l");
leg2->AddEntry(hist_trail_zoom, Form("Trailing edge #mu=%.3g, #sigma=%.3g",f2->GetParameter(1),f2->GetParameter(2)), "l");
leg2->Draw();*/
c_time_zoom->SaveAs("dist_edgetime_zoom.png");
c_time_zoom->SaveAs("dist_edgetime_zoom.pdf");
cout << "integral: " << hist_lead_zoom->Integral() << " / " << hist_trail_zoom->Integral() << endl;
gStyle->SetOptStat(1111);
TCanvas* c_tot = new TCanvas;
hist_tot->Draw();
hist_tot->GetXaxis()->SetTitle("Time over threshold (ns)");
hist_tot->GetYaxis()->SetTitle(Form("Events in channel %d",channel_id));
hist_tot->GetYaxis()->SetTitleOffset(1.45);
c_tot->SaveAs("dist_tot.png");
c_tot->SaveAs("dist_tot.pdf");
c_tot->SetLogy();
c_tot->SaveAs("dist_tot_logscale.png");
TCanvas* c_nevts = new TCanvas;
hist_numevts->Draw();
hist_numevts->GetXaxis()->SetTitle(Form("Hits multiplicity in channel %d / trigger",channel_id));
hist_numevts->GetYaxis()->SetTitle("Triggers");
c_nevts->SaveAs("dist_nevts.png");
return 0;
}
<file_sep>/include/MessageKeys.h
#ifndef MessageKeys_h
#define MessageKeys_h
#include "messages.h"
/// This is where we define the list of available socket messages to be
/// sent/received by any actor.
MESSAGES_ENUM(\
// generic messages
INVALID_KEY, WEBSOCKET_KEY, EXCEPTION,\
// client messages
ADD_CLIENT, REMOVE_CLIENT, GET_CLIENTS, CLIENT_TYPE, PING_CLIENT,\
GET_RUN_NUMBER, SET_NEW_FILENAME, NEW_RUN,\
// master messages
MASTER_BROADCAST, MASTER_DISCONNECT,\
SET_CLIENT_ID,\
THIS_CLIENT_DELETED, OTHER_CLIENT_DELETED,\
CLIENTS_LIST, GET_CLIENT_TYPE, PING_ANSWER,\
ACQUISITION_STARTED, ACQUISITION_STOPPED,\
RUN_NUMBER, NEW_FILENAME,\
// web socket messages
WEB_GET_CLIENTS,\
START_ACQUISITION, STOP_ACQUISITION,\
// DQM messages
NEW_DQM_PLOT, UPDATED_DQM_PLOT, NUM_TRIGGERS, HV_STATUS,\
// other
OTHER_MESSAGE,\
);
#endif
<file_sep>/include/FileConstants.h
#ifndef FileConstants_h
#define FileConstants_h
#include <stdint.h>
#include <stdlib.h>
#include <string>
#include <map>
#include <fstream>
#include "VME_TDCEvent.h"
/**
* General header to store in each collected data file for offline readout. It
* enable any reader to retrieve the run/spill number, as well as the HPTDC
* configuration during data collection.
* \brief Header to the output files
* \author <NAME> <<EMAIL>>
* \date 14 Apr 2015
*/
struct file_header_t {
uint32_t magic;
uint32_t run_id;
uint32_t spill_id;
uint8_t num_hptdc;
VME::AcquisitionMode acq_mode;
VME::DetectionMode det_mode;
};
/// Generate a random string of fixed length for file name
inline std::string GenerateString(const size_t len=5)
{
std::string out;
srand(time(NULL));
const char az[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
out = "";
for (size_t i=0; i<len; i++) { out += az[rand()%(sizeof(az)-1)]; }
return out;
}
/**
* \brief Redirect outputs to another output stream
*/
class Logger
{
public:
inline Logger(std::ostream& lhs, std::ostream& rhs=std::cout) : fStream(rhs), fBuffer(fStream.rdbuf()) {
fStream.rdbuf(lhs.rdbuf());
}
inline ~Logger() { fStream.rdbuf(fBuffer); }
private:
std::ostream& fStream;
std::streambuf* const fBuffer;
};
/**
* \brief Redirect output stream to a string
* \author <NAME> <<EMAIL>>
* \date 3 Aug 2015
*/
class LogRedirector
{
public:
inline LogRedirector(std::ostream& stm=std::cout) : fSS(), fRedirect(fSS, stm) {;}
inline std::string contents() const { return fSS.str(); }
private:
std::ostringstream fSS;
const Logger fRedirect;
};
#endif
<file_sep>/README.md
# CT-PPS Run control
Run control for the CT-PPS 2015 beam test
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
project(PPS_TB_RC)
set(CAEN_LOCATION "/usr/lib")
set(GCC_COMPILE_FLAGS "-Wall -fPIC -O2 -g -lsqlite3")
set(GCC_LINK_FLAGS "-lsqlite3")
add_definitions(${GCC_COMPILE_FLAGS})
file(GLOB vme_sources ${PROJECT_SOURCE_DIR}/src/VME*.cpp)
file(GLOB nim_sources ${PROJECT_SOURCE_DIR}/src/NIM*.cpp)
add_library(det_lib OBJECT ${vme_sources} ${nim_sources})
# File reader
file(GLOB reader_sources ${PROJECT_SOURCE_DIR}/src/FileReader.cpp)
add_library(reader_lib OBJECT ${reader_sources})
file(GLOB sources ${PROJECT_SOURCE_DIR}/src/*.cpp)
list(REMOVE_ITEM sources ${vme_sources})
list(REMOVE_ITEM sources ${nim_sources})
list(REMOVE_ITEM sources ${reader_sources})
add_library(src_lib OBJECT ${sources})
set_property(TARGET src_lib PROPERTY LINK_FLAGS "-lsqlite3")
include_directories("${PROJECT_SOURCE_DIR}/include")
add_executable(ppsRun main.cpp $<TARGET_OBJECTS:src_lib>)
set_property(TARGET ppsRun PROPERTY LINK_FLAGS "-lsqlite3")
add_executable(listener listener.cpp $<TARGET_OBJECTS:src_lib>)
set_property(TARGET listener PROPERTY LINK_FLAGS "-lsqlite3")
# Here have tests
add_subdirectory(test EXCLUDE_FROM_ALL)
# Here have DQM clients
add_subdirectory(dqm EXCLUDE_FROM_ALL)
# CAEN stuff
add_library(caen SHARED IMPORTED)
set_property(TARGET caen PROPERTY IMPORTED_LOCATION "${CAEN_LOCATION}/libCAENVME.so")
# Copy the XML configuration files to the config/ folder
file(GLOB config_files RELATIVE ${PROJECT_SOURCE_DIR} config/*.xml)
foreach(_script ${config_files})
configure_file(${_script} ${PROJECT_BINARY_DIR}/${_script} COPYONLY)
endforeach()
set(CMAKE_CXX_FLAGS "-DLINUX")
add_executable(ppsFetch fetch_vme.cpp $<TARGET_OBJECTS:src_lib> $<TARGET_OBJECTS:det_lib>)
target_link_libraries(ppsFetch caen)
set_property(TARGET ppsFetch PROPERTY LINK_FLAGS "-lCAENVME -ltinyxml2 -lsqlite3")
add_executable(HVsettings change_hv_settings.cpp $<TARGET_OBJECTS:src_lib> $<TARGET_OBJECTS:det_lib>)
target_link_libraries(HVsettings caen)
set_property(TARGET HVsettings PROPERTY LINK_FLAGS "-lCAENVME -ltinyxml2 -lsqlite3")
add_executable(NINOsettings change_nino_threshold_voltage.cpp $<TARGET_OBJECTS:src_lib> $<TARGET_OBJECTS:det_lib>)
target_link_libraries(NINOsettings caen)
set_property(TARGET NINOsettings PROPERTY LINK_FLAGS "-lCAENVME -ltinyxml2 -lsqlite3")
<file_sep>/test/multipipeserver.py
#!/usr/bin/env python
import socket
import sys
import thread
import time
HOST = 'localhost' # Symbolic name meaning all available interfaces
PORT = 1982 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(3)
print 'Socket now listening'
connections = []
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(1024)
reply = data #'Simon says...' + data
if not data:
break
# conn.sendall(reply)
for c in connections:
c.sendall(reply)
#came out of loop
conn.close()
# def foo():
# while 1:
# yield 5
# yield "asdkams"
# pass
conn, addr = s.accept()
print 'Head connected with ' + addr[0] + ':' + str(addr[1])
thread.start_new_thread(clientthread ,(conn,))
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
time.sleep(5) # sleep 5 seconds
conn, addr = s.accept()
connections.append(conn)
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
s.close()
<file_sep>/change_nino_threshold_voltage.cpp
#include "VMEReader.h"
#include "VME_FPGAUnitV1495.h"
using namespace std;
VMEReader* vme;
int gEnd = 0;
int main(int argc, char *argv[]) {
uint32_t address = 0x32100000;
bool with_socket = true;
vme = new VMEReader("/dev/a2818_0", VME::CAEN_V2718, with_socket);
try { vme->AddFPGAUnit(address); } catch (Exception& e) { e.Dump(); }
VME::FPGAUnitV1495* fpga = vme->GetFPGAUnit(address);
const bool use_fpga = (fpga!=0);
uint32_t Vth = 10;
while(Vth != 0xFFFF){
std::cout << "How much should the threshold value? ";
std::cin >> Vth;
std::cout << std::endl;
if (use_fpga) {
fpga->SetThresholdVoltage(Vth, 0);
std::cout << "You asked for: "<< Vth << " and the readback value of the Threshold Voltage is: " << fpga->GetThresholdVoltage(0) << std::endl;
}
}
return 0;
}
<file_sep>/scripts/run_over_all_files.py
from glob import glob
from os.path import isfile
from sys import argv
from subprocess import call
def getint(name):
filenum = name.split("_")[3]
return int(filenum)
def main(argv):
if len(argv)<3:
print 'Usage:', argv[0], '<run id> <board id>'
return
files_in = [f for f in glob('/home/ppstb/timing_data/events_%d_*_board%d.dat' % (int(argv[1]), int(argv[2]))) if isfile(f)]
files_in.sort(key=getint)
print "Sorted files:"
print files_in
i = 0
for f in files_in:
print 'Processing (%d/%d) %s...' % (i+1, len(files_in), f)
call(['/home/ppstb/pps-tbrc/build/test/write_tree', f, f.replace('.dat', '.root')])
i += 1
if __name__=='__main__':
main(argv)
<file_sep>/test/testdb.cpp
#include "OnlineDBHandler.h"
using namespace std;
int
main(int argc, char* argv[])
{
try {
//OnlineDBHandler run("test.db");
OnlineDBHandler run("run_infos.db"); //WARNING! change me!!!
/*for (unsigned int i=0; i<2; i++) {
run.NewRun();
run.SetTDCConditions(0, 0x00aa0000, i, 1, "quartic_1");
run.SetTDCConditions(1, 0x00bb0000, 0, i, "quartic_2");
for (unsigned int j=0; j<i; j++) run.NewBurst();
}*/
cout << run.GetLastRun() << endl;
cout << run.GetLastBurst(run.GetLastRun()) << endl;
OnlineDBHandler::RunCollection rc = run.GetRuns();
for (OnlineDBHandler::RunCollection::iterator it=rc.begin(); it!=rc.end(); it++) {
cout << "Run " << it->first << " started at " << it->second << endl;
OnlineDBHandler::BurstInfos bi = run.GetRunInfo(it->first);
for (OnlineDBHandler::BurstInfos::iterator b=bi.begin(); b!=bi.end(); b++) {
cout << " burst id " << b->burst_id << " began at " << b->time_start << endl;
}
try {
OnlineDBHandler::TDCConditionsCollection cond = run.GetTDCConditions(it->first);
for (OnlineDBHandler::TDCConditionsCollection::iterator tdc=cond.begin(); tdc!=cond.end(); tdc++) {
cout << " tdc " << tdc->tdc_id << " has address 0x" << hex << tdc->tdc_address << dec
<< " and a " << tdc->detector << " on its back"
<< endl;
}
} catch (Exception& e) { e.Dump(); }
}
} catch (Exception& e) {
e.Dump();
}
return 0;
}
<file_sep>/include/VME_GenericBoard.h
#ifndef VME_GenericBoard_h
#define VME_GenericBoard_h
#include <stdint.h>
#include <sstream>
#include "CAENVMElib.h"
#include "CAENVMEtypes.h"
#include "CAENVMEoslib.h"
#include "Exception.h"
#define CAEN_ERROR(x) 30000+abs(x)
namespace VME
{
template<class Register, CVAddressModifier am>
class GenericBoard
{
public:
inline GenericBoard(int32_t bhandle, uint32_t baseaddr) : fHandle(bhandle), fBaseAddr(baseaddr) {;}
inline virtual ~GenericBoard() {;}
protected:
/**
* Write a 16-bit word in the register
* \brief Write on register
* \param[in] addr register
* \param[in] data word
*/
inline void WriteRegister(const Register& reg, const uint16_t& data) const {
const uint32_t address = fBaseAddr+reg;
uint16_t* fdata = new uint16_t; *fdata = data;
CVErrorCodes out = CAENVME_WriteCycle(fHandle, address, fdata, am, cvD16);
if (out!=cvSuccess) {
std::ostringstream o;
o << "Impossible to write register at 0x" << std::hex << reg << "\n\t"
<< "Addressing mode: 0x" << std::hex << am << "\n\t"
<< "Base address: 0x" << std::hex << fBaseAddr << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning, CAEN_ERROR(out));
}
delete fdata;
}
/**
* Write a 32-bit word in the register
* \brief Write on register
* \param[in] addr register
* \param[in] data word
*/
inline void WriteRegister(const Register& reg, const uint32_t& data) const {
const uint32_t address = fBaseAddr+reg;
uint32_t* fdata = new uint32_t; *fdata = data;
CVErrorCodes out = CAENVME_WriteCycle(fHandle, address, fdata, am, cvD32);
if (out!=cvSuccess) {
std::ostringstream o;
o << "Impossible to write register at 0x" << std::hex << reg << "\n\t"
<< "Addressing mode: 0x" << std::hex << am << "\n\t"
<< "Base address: 0x" << std::hex << fBaseAddr << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning, CAEN_ERROR(out));
}
//WaitIRQ(IRQ1|IRQ2|IRQ3|IRQ4|IRQ5|IRQ6|, 100);
delete fdata;
}
/**
* Read a 16-bit word in the register
* \brief Read on register
* \param[in] addr register
* \param[out] data word
*/
inline void ReadRegister(const Register& reg, uint16_t* data) const {
const uint32_t address = fBaseAddr+reg;
CVErrorCodes out = CAENVME_ReadCycle(fHandle, address, data, am, cvD16);
if (out!=cvSuccess) {
std::ostringstream o;
o << "Impossible to read register at 0x" << std::hex << reg << "\n\t"
<< "Addressing mode: 0x" << std::hex << am << "\n\t"
<< "Base address: 0x" << std::hex << fBaseAddr << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning, CAEN_ERROR(out));
}
}
/**
* Read a 32-bit word in the register
* \brief Read on register
* \param[in] addr register
* \param[out] data word
*/
inline void ReadRegister(const Register& reg, uint32_t* data) const {
const uint32_t address = fBaseAddr+reg;
CVErrorCodes out = CAENVME_ReadCycle(fHandle, address, data, am, cvD32);
if (out!=cvSuccess) {
std::ostringstream o;
o << "Impossible to read register at 0x" << std::hex << reg << "\n\t"
<< "Addressing mode: 0x" << std::hex << am << "\n\t"
<< "Base address: 0x" << std::hex << fBaseAddr << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning, CAEN_ERROR(out));
}
}
int32_t fHandle;
uint32_t fBaseAddr;
};
}
#endif
<file_sep>/test/dqmer.py
#Socket client example in python
import sys #for exit
sys.path.append("/home/ppstb/pps-tbrc/scripts")
import SocketHandler
import DQMReader
def dummy_computing(filename):
reader = DQMReader.DQMReader(filename)
reader.ProcessBinaryFile()
resultfilename = reader.GetOutputFilename()
return resultfilename
def run_dqm_process( messenger_socket, computation_process = dummy_computing ):
while True: # while socket and connection are alive, but, as people say, it is hard to check
incoming_message = ""
result_filename = ""
# RECEIVE
incoming_message = messenger_socket.Receive()
# COMPUTE
if len(incoming_message)!=2:
print "Got wrong message:\n%s" % incoming_message # OR send error to the messenger?
# MAYBE add 1 more message -- "KILL_DQM" -- and stop DQM process with it?
continue
if incoming_message[0] == "NEW_FILENAME":
try:
(tdc_addr, filename) = incoming_message[1].split(':')
except ValueError:
print "Got invalid 'NEW_FILENAME' message value: %s" % (incoming_message[1])
continue
print incoming_message[1], tdc_addr, filename
result_filename = computation_process( filename )
# SEND
try:
messenger_socket.Send("NEW_DQM_PLOT", result_filename)
except SocketHandler.SendingError:
#Send failed
print 'Send failed'
sys.exit()
if __name__ == '__main__':
host = "localhost"
socket_to_messenger = SocketHandler.SocketHandler( host, 1987 )
socket_to_messenger.Handshake( 4 ) # 4 = DQM
run_dqm_process( socket_to_messenger )
<file_sep>/test/reader_oneedge.cpp
#include <iostream>
#include <vector>
#include "FileReader.h"
#include "TH1.h"
#include "TCanvas.h"
#include "TLegend.h"
#include "TStyle.h"
using namespace std;
using namespace VME;
int
main(int argc, char* argv[])
{
unsigned int channel1_id = 0, channel2_id = 0;
if (argc<4) {
cout << "Usage:\n\t" << argv[0] << " <input file:str> <channel 1:int> <channel 2:int>" << endl;
return -1;
}
else {
channel1_id = atoi(argv[2]);
channel2_id = atoi(argv[3]);
}
TDCMeasurement m;
int num_events1, num_events2;
vector<double> time1, time1_ettt, time2, time2_ettt;
TH1D* h_diff = new TH1D("diff", "", 200, -2., 2.);
TH1D* h_diff_ettt = new TH1D("diff_ettt", "", 200, -2., 2.);
num_events1 = num_events2 = 0;
FileReader f1(argv[1]);
while (true) {
try {
if (!f1.GetNextMeasurement(channel1_id, &m)) break;
time1.push_back(m.GetLeadingTime()*25./1024);
time1_ettt.push_back(m.GetLeadingTime()*25./1024-m.GetETTT());
num_events1 += m.NumEvents();
} catch (Exception& e) {
e.Dump();
}
}
FileReader f2(argv[1]);
while (true) {
try {
if (!f2.GetNextMeasurement(channel2_id, &m)) break;
time2.push_back(m.GetLeadingTime()*25./1024);
time2_ettt.push_back(m.GetLeadingTime()*25./1024-m.GetETTT());
num_events2 += m.NumEvents();
} catch (Exception& e) {
e.Dump();
}
}
if (time1.size()!=time2.size()) {
cerr << "Not the same number of events in both channels! aborting..." << endl;
return -1;
}
for (unsigned int i=0; i<time1.size(); i++) {
h_diff->Fill(time1[i]-time2[i]);
h_diff_ettt->Fill(time1_ettt[i]-time2_ettt[i]);
}
cerr << "number of events:" << endl
<< " channel " << channel1_id << ": " << num_events1 << " / " << time1.size() << endl
<< " channel " << channel2_id << ": " << num_events2 << " / " << time2.size() << endl;
gStyle->SetPadGridX(true); gStyle->SetPadGridY(true);
gStyle->SetPadTickX(true); gStyle->SetPadTickY(true);
TCanvas* c = new TCanvas;
TLegend* leg = new TLegend(.15, .75, .4, .85);
h_diff->Draw();
leg->AddEntry(h_diff, "No correction");
h_diff_ettt->Draw("same");
h_diff_ettt->SetLineColor(kRed+1);
leg->AddEntry(h_diff_ettt, "ETTT correction");
h_diff->GetXaxis()->SetTitle(Form("Leading time ch %d - leading time ch %d (ns)",channel1_id,channel2_id));
h_diff->GetYaxis()->SetTitle("Triggers");
leg->Draw();
c->SaveAs("timediff_leading.png");
return 0;
}
<file_sep>/include/DQMProcess.h
#include "Client.h"
#include "Exception.h"
#include "OnlineDBHandler.h"
#define DQM_OUTPUT_DIR "/tmp/"
namespace DQM
{
/**
* \brief Handler for a common DQM process to run on the socket
* \author <NAME> <<EMAIL>>
* \date 3 Aug 2015
*/
class DQMProcess : public Client
{
public:
inline DQMProcess(int port, unsigned short order=0, const char* det_type="") :
Client(port), fOrder(order), fRunNumber(0), fDetectorType(det_type) {
Client::Connect(Socket::DQM);
SocketMessage run_msg = Client::SendAndReceive(GET_RUN_NUMBER, RUN_NUMBER);
std::cout << "Current run number is: " << run_msg.GetIntValue() << std::endl;
fRunNumber = run_msg.GetIntValue();
IsInRun();
}
inline ~DQMProcess() { Client::Disconnect(); }
enum Action { NewPlot = 0x0, UpdatedPlot = 0x1 };
/// Run a DQM plotter making use of the board/output filename information
inline void Run(bool (*fcn)(unsigned int addr, std::string filename, std::vector<std::string>* outputs), const Action& act=NewPlot) {
bool status = false;
uint32_t board_address; std::string filename;
std::vector<std::string> outputs;
try {
while (true) {
outputs.clear();
int ret = ParseMessage(&board_address, &filename);
if (ret!=1) continue;
// new raw file to process
try { status = fcn(board_address, filename, &outputs); } catch (Exception& e) { Client::Send(e); continue; }
if (!status) continue; // failed to produce plots
std::cout << "Produced " << outputs.size() << " plot(s) for board with address 0x" << std::hex << board_address << std::endl;
MessageKey key = INVALID_KEY;
switch (act) {
case NewPlot: key = NEW_DQM_PLOT; break;
case UpdatedPlot: key = UPDATED_DQM_PLOT; break;
}
//sleep(fOrder);
for (std::vector<std::string>::iterator nm=outputs.begin(); nm!=outputs.end(); nm++) {
Client::Send(SocketMessage(key, *nm)); usleep(500);
}
}
} catch (Exception& e) { /*Client::Send(e);*/ e.Dump(); }
}
/// Run a DQM plotter without any information on the board/output filename
inline void Run(bool (*fcn)(std::vector<std::string>* outputs), const Action& act=NewPlot) {
bool status = false;
uint32_t board_address; std::string filename;
std::vector<std::string> outputs;
try {
while (true) {
outputs.clear();
int ret = ParseMessage(&board_address, &filename);
if (ret!=1) continue;
// new raw file to process
try { status = fcn(&outputs); } catch (Exception& e) { Client::Send(e); continue; }
if (!status) continue; // failed to produce plots
std::cout << "Produced " << outputs.size() << " plot(s)" << std::endl;
MessageKey key = INVALID_KEY;
switch (act) {
case NewPlot: key = NEW_DQM_PLOT; break;
case UpdatedPlot: key = UPDATED_DQM_PLOT; break;
}
//sleep(fOrder);
for (std::vector<std::string>::iterator nm=outputs.begin(); nm!=outputs.end(); nm++) {
Client::Send(SocketMessage(key, *nm)); usleep(500);
}
} // end of infinite loop to fetch messages
} catch (Exception& e) { Client::Send(e); e.Dump(); }
}
private:
int ParseMessage(uint32_t* board_address, std::string* filename) {
SocketMessage msg = Client::Receive(NEW_FILENAME);
if (msg.GetKey()==NEW_FILENAME) {
if (msg.GetValue()=="") {
std::ostringstream os; os << "Invalid output file path received through the NEW_FILENAME message: " << msg.GetValue();
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
std::string value = msg.GetValue();
size_t end = value.find(':');
if (end==std::string::npos) {
std::ostringstream s; s << "Invalid filename message built! (\"" << value << "\")";
throw Exception(__PRETTY_FUNCTION__, s.str().c_str(), JustWarning);
}
*board_address = atoi(value.substr(0, end).c_str());
*filename = value.substr(end+1);
if (fDetectorType=="") return 1;
if (fAddressesCanProcess.find(*board_address)==fAddressesCanProcess.end()) {
std::cout << "board address " << *board_address << " is not in run" << std::endl;
return 0;
}
std::cout << "Board address: " << *board_address << ", filename: " << *filename << std::endl;
return 1;
}
else if (msg.GetKey()==RUN_NUMBER) {
try { fRunNumber = msg.GetIntValue(); } catch (Exception& e) {
std::cout << "Invalid Run number received: " << msg.GetValue() << std::endl;
return -2;
}
if (IsInRun()) return 0;
else return -3;
}
else {
std::cout << "Invalid message received: " << MessageKeyToString(msg.GetKey()) << std::endl;
return -1;
}
return -1;
}
inline bool IsInRun() {
if (fDetectorType=="") return true; // no particular reason to leave it outside run
fAddressesCanProcess.clear();
std::string type = "";
try {
OnlineDBHandler::TDCConditionsCollection cc;
try { cc = OnlineDBHandler().GetTDCConditions(fRunNumber); } catch (Exception& e) {
e.Dump();
std::cout << "Trying to fetch last run's conditions..." << std::endl;
cc = OnlineDBHandler().GetTDCConditions(fRunNumber-1); //FIXME why is this happening????
}
for (OnlineDBHandler::TDCConditionsCollection::const_iterator c=cc.begin(); c!=cc.end(); c++) {
if (c->detector.find(fDetectorType)!=std::string::npos) {
std::cout << "Detectors of type \"" << fDetectorType << "\" are present in the run!"
<< " Let's process them in a (near) future!" << std::endl;
fAddressesCanProcess.insert(std::pair<unsigned long, std::string>(c->tdc_address, c->detector));
}
}
if (fAddressesCanProcess.size()!=0) return true;
std::cout << "Detector not in conditions... leaving this DQM (" << fDetectorType << ") hanging." << std::endl;
return false;
} catch (Exception& e) {
e.Dump();
std::cout << "Failed to retrieve online TDC conditions. Aborting" << std::endl;
return false;
}
}
unsigned short fOrder;
unsigned int fRunNumber;
std::string fDetectorType;
std::map<unsigned long, std::string> fAddressesCanProcess;
};
}
<file_sep>/include/VME_TDCMeasurement.h
#ifndef VME_TDCMeasurement_h
#define VME_TDCMeasurement_h
#include <vector>
#include <map>
#include "VME_TDCEvent.h"
namespace VME
{
/**
* \author <NAME> <<EMAIL>>
* \date Jun 2015
*/
class TDCMeasurement
{
public:
inline TDCMeasurement() {;}
inline TDCMeasurement(const std::vector<TDCEvent>& v) { SetEventsCollection(v); }
inline ~TDCMeasurement() { fMap.clear(); }
inline void Dump() {
std::ostringstream os;
/*for (std::map<Type,TDCEvent>::const_iterator e=fMap.begin(); e!=fMap.end(); e++) {
os << "=> Type=" << e->first << std::endl;
}*/
os << "TDC/Channel Id: " << GetTDCId() << " / " << GetChannelId() << "\n\t"
<< "Event/bunch Id: " << GetEventId() << " / " << GetBunchId() << "\n\t";
for (unsigned int i=0; i<NumEvents(); i++) {
os << "----- Event " << i << " -----" << "\n\t"
<< "Leading time: " << GetLeadingTime() << "\n\t"
<< "Trailing time: " << GetTrailingTime() << "\n\t";
}
os << NumEvents() << " hits recorded" << "\n\t"
<< NumErrors() << " error words";
PrintInfo(os.str());
}
inline void SetEventsCollection(const std::vector<TDCEvent>& v) {
unsigned int num_measurements = 0;
fMap.clear(); fEvents.clear();
TDCEvent leading; bool has_leading = false;
for (std::vector<TDCEvent>::const_iterator e=v.begin(); e!=v.end(); e++) {
switch (e->GetType()) {
case TDCEvent::GlobalHeader: fMap.insert(std::pair<TDCEvent::EventType,TDCEvent>(TDCEvent::GlobalHeader, *e)); break;
case TDCEvent::GlobalTrailer: fMap.insert(std::pair<TDCEvent::EventType,TDCEvent>(TDCEvent::GlobalTrailer, *e)); break;
case TDCEvent::TDCHeader: fMap.insert(std::pair<TDCEvent::EventType,TDCEvent>(TDCEvent::TDCHeader, *e)); break;
case TDCEvent::TDCTrailer: fMap.insert(std::pair<TDCEvent::EventType,TDCEvent>(TDCEvent::TDCTrailer, *e)); break;
case TDCEvent::ETTT: fMap.insert(std::pair<TDCEvent::EventType,TDCEvent>(TDCEvent::ETTT, *e)); break;
case TDCEvent::TDCError: fMap.insert(std::pair<TDCEvent::EventType,TDCEvent>(TDCEvent::TDCError, *e)); break;
case TDCEvent::TDCMeasurement:
if (!e->IsTrailing()) { leading = *e; has_leading = true; }
else {
if (!has_leading) throw Exception(__PRETTY_FUNCTION__, "Failed to retrieve leading/trailing edges", JustWarning);//return;
fEvents.push_back(std::pair<TDCEvent,TDCEvent>(leading, *e));
num_measurements++;
}
break;
case TDCEvent::Filler:
default:
break;
}
}
}
inline uint32_t GetLeadingTime(unsigned short event_id=0) {
if (event_id>=fEvents.size()) { return 0; }
return fEvents[event_id].first.GetTime();
}
inline uint32_t GetTrailingTime(unsigned short event_id=0) {
if (event_id>=fEvents.size()) { return 0; }
return fEvents[event_id].second.GetTime();
}
inline uint16_t GetToT(unsigned short event_id=0) {
if (event_id>=fEvents.size()) { return 0; }
uint32_t tt = GetTrailingTime(event_id), lt = GetLeadingTime(event_id);
if ((tt-lt)>(1<<21)) tt += ((1<<21));
return tt-lt;
}
inline uint16_t GetChannelId(unsigned short event_id=0) {
if (event_id>=fEvents.size()) { return 0; }
return fEvents[event_id].second.GetChannelId();
}
inline uint16_t GetTDCId() {
if (!fMap.count(TDCEvent::TDCHeader)) { return 0; }
return fMap[TDCEvent::TDCHeader].GetTDCId();
}
inline uint16_t GetEventId() {
if (!fMap.count(TDCEvent::TDCHeader)) { return 0; }
return fMap[TDCEvent::TDCHeader].GetEventId();
}
inline uint16_t GetBunchId() {
if (!fMap.count(TDCEvent::TDCHeader)) { return 0; }
return fMap[TDCEvent::TDCHeader].GetBunchId();
}
inline uint32_t GetETTT() {
if (!fMap.count(TDCEvent::ETTT) or !fMap.count(TDCEvent::GlobalTrailer)) { return 0; }
return (fMap[TDCEvent::ETTT].GetETTT()&0x07ffffff)*32+fMap[TDCEvent::GlobalTrailer].GetGeo();
}
inline size_t NumEvents() const { return fEvents.size(); }
inline size_t NumErrors() const { return fMap.count(TDCEvent::TDCError); }
private:
std::map<TDCEvent::EventType,TDCEvent> fMap;
std::vector< std::pair<TDCEvent,TDCEvent> > fEvents;
};
}
#endif
<file_sep>/dqm/daq.cpp
#include "DQMProcess.h"
#include "OnlineDBHandler.h"
#include "PPSCanvas.h"
#include <fstream>
#include "TGraph.h"
#include "TAxis.h"
using namespace std;
bool
DAQDQM(vector<string>* outputs)
{
try {
OnlineDBHandler ri;
unsigned int last_run = ri.GetLastRun();
OnlineDBHandler::BurstInfos si = ri.GetRunInfo(last_run);
TGraph* gr_spills = new TGraph;
unsigned int i = 0;
for (OnlineDBHandler::BurstInfos::iterator s=si.begin(); s!=si.end(); s++, i++) {
gr_spills->SetPoint(i, s->time_start, s->burst_id);
}
DQM::PPSCanvas* c_spills = new DQM::PPSCanvas(Form("daq_triggers_time_%d", last_run), "Burst train arrival time");
c_spills->SetRunInfo(last_run, TDatime().AsString());
c_spills->Grid()->SetGrid(1, 1);
gr_spills->Draw("alp");
gr_spills->GetXaxis()->SetTimeDisplay(1);
gr_spills->GetXaxis()->SetTitle("Burst train arrival time");
gr_spills->GetYaxis()->SetTitle("Burst train ID");
gr_spills->SetMarkerStyle(20);
gr_spills->SetMarkerSize(.6);
c_spills->Save("png", DQM_OUTPUT_DIR);
outputs->push_back(c_spills->GetName());
} catch (Exception& e) { e.Dump(); }
return true;
}
int
main(int argc, char* argv[])
{
DQM::DQMProcess dqm(1987, 0);
dqm.Run(DAQDQM, DQM::DQMProcess::UpdatedPlot);
return 0;
}
<file_sep>/test/errors.cpp
#include <iostream>
#include "FileReader.h"
#include "TCanvas.h"
#include "TH1.h"
#include "TLegend.h"
#include "TStyle.h"
using namespace std;
using namespace VME;
int
main(int argc, char* argv[])
{
unsigned int channel_id = 0;
if (argc<2) {
cerr << "Usage:\n\t" << argv[0] << " <input file>" << endl;
return -1;
}
TDCMeasurement m;
unsigned int num_triggers;
TH1D* hist_numerrors = new TH1D("nerrors", "", 10, -.5, 9.5);
FileReader f(argv[1]);
//cout << f.GetNumTDCs() << " TDCs recorded" << endl;
num_triggers = 0;
while (true) {
try {
if (!f.GetNextMeasurement(channel_id, &m)) break;
hist_numerrors->Fill(m.NumErrors()-.5);
if (m.NumErrors()) cout << m.NumErrors() << endl;
//cerr << "ettt=" << m.GetETTT() << endl;
num_triggers += 1;
} catch (Exception& e) { e.Dump(); }
}
cerr << "total number of triggers: " << num_triggers << endl;
gStyle->SetPadGridX(true); gStyle->SetPadGridY(true);
gStyle->SetPadTickX(true); gStyle->SetPadTickY(true);
TCanvas* c_nerrors = new TCanvas;
hist_numerrors->Draw();
hist_numerrors->GetXaxis()->SetTitle("Number of errors / trigger");
hist_numerrors->GetYaxis()->SetTitle("Triggers");
c_nerrors->SaveAs("dist_nerrors.png");
return 0;
}
<file_sep>/include/VME_FPGAUnitV1495.h
#ifndef VME_FPGAUnitV1495_h
#define VME_FPGAUnitV1495_h
#include "VME_GenericBoard.h"
#include <map>
#include <unistd.h>
namespace VME
{
enum FPGAUnitV1495Register {
// User-defined registers
kV1495ScalerCounter = 0x100c,
kV1495DelaySettings = 0x1010,
kV1495UserFWRevision = 0x1014,
kV1495TDCBoardInterface = 0x1018,
kV1495ClockSettings = 0x101c,
kV1495Control = 0x1020,
kV1495TriggerSettings = 0x1024,
kV1495OutputSettings = 0x1028,
kV1495ThresholdVoltage0 = 0x1028,
kV1495ThresholdVoltage1 = 0x1010,
// CAEN board registers
kV1495GeoAddress = 0x8008,
kV1495UserFPGAFlashMem = 0x8014,
kV1495UserFPGAConfig = 0x8016,
kV1495ModuleReset = 0x800a,
kV1495FWRevision = 0x800c,
kV1495ConfigurationROM = 0x8100,
kV1495OUI2 = 0x8124,
kV1495OUI1 = 0x8128,
kV1495OUI0 = 0x812c,
kV1495Board2 = 0x8134,
kV1495Board1 = 0x8138,
kV1495Board0 = 0x813c,
kV1495HWRevision3 = 0x8140,
kV1495HWRevision2 = 0x8144,
kV1495HWRevision1 = 0x8148,
kV1495HWRevision0 = 0x814c,
kV1495SerNum0 = 0x8180,
kV1495SerNum1 = 0x8184
};
enum FPGAUnitV1495DACCH {
// User-defined registers
cH0 = 0,
cH1 = 4096,
cH2 = 8192,
cH3 = 12288
};
const int OneVolt = 1634;
/**
* User-defined control word to be propagated to the
* CAEN V1495 board firmware.
* \author <NAME> <<EMAIL>>
* \date 27 Jun 2015
*/
class FPGAUnitV1495Control
{
public:
inline FPGAUnitV1495Control(uint32_t word) : fWord(word) {;}
inline virtual ~FPGAUnitV1495Control() {;}
inline void Dump() const {
std::ostringstream os;
os << "Raw control word: ";
for (int i=15; i>=0; i--) {
os << ((fWord>>i)&0x1);
if (i%4==0) os << " ";
}
PrintInfo(os.str());
}
inline uint32_t GetWord() const { return fWord; }
enum ClockSource { InternalClock=0x0, ExternalClock=0x1 };
/**
* \brief Get the clock source
*/
inline ClockSource GetClockSource() const { return static_cast<ClockSource>(GetBit(0)); }
/**
* \brief Switch between internal and external clock source
*/
inline void SetClockSource(const ClockSource& cs) { SetBit(0, cs); }
enum TriggerSource { InternalTrigger=0x0, ExternalTrigger=0x1 };
/**
* \brief Get the trigger source
*/
inline TriggerSource GetTriggerSource() const { return static_cast<TriggerSource>(GetBit(1)); }
/**
* \brief Switch between internal and external trigger source
*/
inline void SetTriggerSource(const TriggerSource& cs) { SetBit(1, cs); }
inline bool GetScalerStatus() const { return GetBit(2); }
inline void SetScalerStatus(bool start=true) { SetBit(2, start); }
inline void SetScalerReset(bool reset=true) { SetBit(3, reset); }
enum SignalSource { InternalSignal=0x0, ExternalSignal=0x1 };
inline SignalSource GetSignalSource(unsigned short map_id) const { return static_cast<SignalSource>(GetBit(4+map_id)); }
inline void SetSignalSource(unsigned short map_id, const SignalSource& s) { SetBit(4+map_id, s); }
enum TriggeringMode { ContinuousStorage=0x0, TriggerMatching=0x1 };
inline TriggeringMode GetTriggeringMode() const { return static_cast<TriggeringMode>(GetBit(6)); }
inline void SetTriggeringMode(const TriggeringMode& tm) { SetBit(6, tm); }
private:
inline bool GetBit(unsigned short id) const { return static_cast<bool>((fWord>>id)&0x1); }
inline void SetBit(unsigned short id, unsigned short value=0x1) {
if (value==GetBit(id)) return;
unsigned short sign = (value==0x0) ? -1 : 1; fWord += sign*(0x1<<id);
}
uint32_t fWord;
};
/**
* Handler for the multi-purposes FPGA unit (CAEN V1495)
* \author <NAME> <<EMAIL>>
* \date 25 Jun 2015
*/
class FPGAUnitV1495 : public GenericBoard<FPGAUnitV1495Register,cvA32_U_DATA>
{
public:
FPGAUnitV1495(int32_t bhandle, uint32_t baseaddr);
~FPGAUnitV1495();
unsigned short GetCAENFirmwareRevision() const;
unsigned short GetUserFirmwareRevision() const;
unsigned int GetHardwareRevision() const;
unsigned short GetSerialNumber() const;
unsigned short GetGeoAddress() const;
void CheckBoardVersion() const;
void ResetFPGA() const;
void DumpFWInformation() const;
enum TDCBits { kReset=0x1, kTrigger=0x2, kClear=0x4 };
/**
* \brief Set a pattern of bits to be sent to all TDCs through the ECL mezzanine
*/
void SetTDCBits(unsigned short bits) const;
/**
* \brief Send a pulse to TDCs' front panel
* \param[in] bits The pattern to send (3 bits)
* \param[in] time_us Pulse width (in us)
*/
void PulseTDCBits(unsigned short bits, unsigned int time_us=10) const;
/**
* \brief Retrieve the current bits sent to TDCs' front panel
* \return A 3-bit word PoI
*/
unsigned short GetTDCBits() const;
/**
* \brief Retrieve the user-defined control word
*/
FPGAUnitV1495Control GetControl() const;
/**
* \brief Set the user-defined control word
*/
void SetControl(const FPGAUnitV1495Control& control) const;
/**
* \brief Set the internal clock period
* \param[in] period Clock period (in units of 25 ns)
*/
void SetInternalClockPeriod(uint32_t period) const;
/**
* \brief Retrieve the internal clock period
* \return Clock period (in units of 25 ns)
*/
uint32_t GetInternalClockPeriod() const;
/**
* \brief Set the internal trigger period
* \param[in] period Trigger period (in units of 50 ns)
*/
void SetInternalTriggerPeriod(uint32_t period) const;
/**
* \brief Retrieve the internal trigger period
* \return Trigger period (in units of 50 ns)
*/
uint32_t GetInternalTriggerPeriod() const;
/**
* \brief Retrieve the threshold voltage
* \return Threshold voltage (in units of 50 ns)
*/
uint32_t GetThresholdVoltage(uint32_t tdc_number) const;
/**
* \brief Set the threshold voltage
* \param[in] Threshold voltage (in units of 50 ns)
*/
void SetThresholdVoltage(uint32_t voltage, uint32_t tdc_number) const;
uint32_t GetOutputPulser() const;
void ClearOutputPulser() const;
void SetOutputPulser(unsigned short id, bool enable=true) const;
void SetOutputPulserPOI(uint32_t poi) const;
uint32_t GetOutputDelay() const;
void SetOutputDelay(uint32_t delay) const;
/// Start the inner triggers counter
void StartScaler();
/// Stop the inner triggers counter
void StopScaler();
//void PauseScaler() const;
/// Return the inner triggers counter value
uint32_t GetScalerValue() const;
/// Is this FPGA board used as a mean to propagate the control signal to HPTDCs?
inline void SetTDCControlFanout(bool sw=true) { fIsTDCControlFanout = sw; }
/// Is this FPGA board used as a mean to propagate the control signal to HPTDCs?
inline bool IsTDCControlFanout() const { return fIsTDCControlFanout; }
private:
bool fScalerStarted;
bool fIsTDCControlFanout;
};
/// Mapper from physical VME addresses to pointers to FPGA objects
typedef std::map<uint32_t,VME::FPGAUnitV1495*> FPGAUnitCollection;
}
#endif
<file_sep>/include/VME_BridgeVx718.h
/* Interface for CAEN Vx718 VME Bridge */
#ifndef VME_BridgeVx718_h
#define VME_BridgeVx718_h
#include "VME_GenericBoard.h"
#include "VME_PCIInterfaceA2818.h"
#include <unistd.h>
namespace VME
{
/// Compatible bridge types
enum BridgeType { CAEN_V1718, CAEN_V2718 };
class BridgeVx718Status
{
public:
inline BridgeVx718Status(uint16_t word) : fWord(word) {;}
inline virtual ~BridgeVx718Status() {;}
inline void Dump() const {
std::ostringstream os;
os << "System reset: " << GetSystemReset() << "\n\t"
<< "System control: " << GetSystemControl() << "\n\t"
<< "DTACK: " << GetDTACK() << "\n\t"
<< "Bus error: " << GetBERR() << "\n\t"
<< "Dip switches:\n\t\t";
for (unsigned int i=0; i<5; i++) {
os << "(" << i << ") -> " << GetDipSwitch(i);
if (i<4) os << "\n\t\t";
}
PrintInfo(os.str());
}
inline bool GetSystemReset() const { return static_cast<bool>(fWord&0x1); }
inline bool GetSystemControl() const { return static_cast<bool>((fWord>>1)&0x1); }
inline bool GetDTACK() const { return static_cast<bool>((fWord>>4)&0x1); }
inline bool GetBERR() const { return static_cast<bool>((fWord>>5)&0x1); }
inline bool GetDipSwitch(unsigned int sw) const {
if (sw>5) {
std::ostringstream os; os << "Trying to get the value of a dip switch outside allowed range [0:4]! (" << sw << ")";
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
return static_cast<bool>((fWord>>(8+sw))&0x1);
}
inline bool GetUSBType() const { return static_cast<bool>((fWord>>15)&0x1); }
private:
uint16_t fWord;
};
class BridgeVx718Control
{
public:
inline BridgeVx718Control(uint16_t word) : fWord(word) {;}
inline virtual ~BridgeVx718Control() {;}
/**
* \brief Arbiter type
* \return true if "Round Robin", else fixed priority
*/
inline bool GetArbiterType() const { return static_cast<bool>((fWord>>1)&0x1); }
/**
* \brief Requester type
* \return true if demand, else fair
*/
inline bool GetRequesterType() const { return static_cast<bool>((fWord>>2)&0x1); }
/**
* \brief Release type
* \return true if release on request, else release when done
*/
inline bool GetReleaseType() const { return static_cast<bool>((fWord>>3)&0x1); }
inline unsigned int GetBusReqLevel() const { return static_cast<unsigned int>((fWord>>4)&0x3); }
inline bool GetInterruptReq() const { return static_cast<bool>((fWord>>6)&0x1); }
inline bool GetSysRes() const { return static_cast<bool>((fWord>>7)&0x1); }
/**
* \brief VME bus timeout
* \return true if 1400 us, else 50 us
*/
inline bool GetBusTimeout() const { return static_cast<bool>((fWord>>8)&0x1); }
/**
* \brief Address Increment
* \return true if enabled, else false (FIFO mode)
*/
inline bool GetAddressIncrement() const { return static_cast<bool>((fWord>>9)&0x1); }
private:
uint16_t fWord;
};
/**
* This class initializes the CAEN V1718 VME bridge in order to control the crate.
* \brief class defining the VME bridge
* \author <NAME> <<EMAIL>>
* \author <NAME> <<EMAIL>>
* \date Jun 2010
*/
class BridgeVx718 : public GenericBoard<CVRegisters,cvA32_U_DATA>
{
public:
enum IRQId { IRQ1=0x1, IRQ2=0x2, IRQ3=0x4, IRQ4=0x8, IRQ5=0x10, IRQ6=0x20, IRQ7=0x40 };
/**
* Bridge class constructor
* \brief Constructor
* \param[in] device Device identifier on the VME crate
* \param[in] type Device type (1718/2718)
*/
BridgeVx718(const char* device, BridgeType type);
/**
* Bridge class destructor
* \brief Destructor
*/
~BridgeVx718();
/**
* \brief Bridge's handle value
* \return Handle value
*/
inline int32_t GetHandle() const { return fHandle; }
void CheckPCIInterface(const char* device) const;
void CheckConfiguration() const;
void TestOutputs() const;
/// Perform a system reset of the module
void Reset() const;
BridgeVx718Status GetStatus() const;
void SetIRQ(unsigned int irq, bool enable=true);
void WaitIRQ(unsigned int irq, unsigned long timeout=1000) const;
unsigned int GetIRQStatus() const;
/**
* \brief Set and control the output lines
*/
void OutputConf(CVOutputSelect output) const;
void OutputOn(unsigned short output) const;
void OutputOff(unsigned short output) const;
/**
* \brief Set and read the input lines
*/
void InputConf(CVInputSelect input) const;
void InputRead(CVInputSelect input) const;
void StartPulser(double period, double width, unsigned int num_pulses=0) const;
void StopPulser() const;
void SinglePulse(unsigned short channel) const;
private:
bool fHasIRQ;
};
}
#endif
<file_sep>/fetch_vme.cpp
#include "VMEReader.h"
#include "FileConstants.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <ctime>
#include <signal.h>
#define NUM_TRIG_BEFORE_FILE_CHANGE 1000
#define PATH "/home/ppstb/timing_data/"
using namespace std;
VMEReader* vme;
int gEnd = 0;
void CtrlC(int aSig) {
if (gEnd==0) { cerr << endl << "[C-c] Trying a clean exit!" << endl; vme->Abort(); }
else if (gEnd>=5) { cerr << endl << "[C-c > 5 times] ... Forcing exit!" << endl; exit(0); }
gEnd++;
}
int main(int argc, char *argv[]) {
signal(SIGINT, CtrlC);
// Where to put the logs
ofstream err_log("daq.err", ios::binary);
//const Logger lr(err_log, cerr);
string xml_config;
if (argc<2) {
cout << "No configuration file provided! using default config/config.xml" << endl;
xml_config = string(getenv("PPS_PATH"))+"/config/config.xml";
}
else xml_config = argv[1];
const unsigned int num_tdc = 1;
ofstream out_file[num_tdc];
unsigned int num_events[num_tdc];
VME::TDCEventCollection ec;
VME::AcquisitionMode acq_mode = VME::TRIG_MATCH;
VME::DetectionMode det_mode = VME::TRAILEAD;
file_header_t fh;
fh.magic = 0x30535050; // PPS0 in ASCII
fh.run_id = 0;
fh.spill_id = 0;
fh.acq_mode = acq_mode;
fh.det_mode = det_mode;
time_t t_beg;
for (unsigned int i=0; i<num_tdc; i++) num_events[i] = 0;
unsigned long num_triggers = 0, num_all_triggers = 0, num_files = 0;
try {
bool with_socket = true;
vme = new VMEReader("/dev/a2818_0", VME::CAEN_V2718, with_socket);
// Declare a new run to the online database
vme->NewRun();
NIM::HVModuleN470* hv;
try {
vme->AddHVModule(0x500000, 0xc);
} catch (Exception& e) { if (vme->UseSocket()) vme->Send(e); }
try {
hv = vme->GetHVModule();
cout << "module id=" << hv->GetModuleId() << endl;
hv->ReadMonitoringValues();
try {
vme->LogHVValues(0, hv->ReadChannelValues(0));
vme->LogHVValues(3, hv->ReadChannelValues(3));
} catch (Exception& e) {;}
} catch (Exception& e) { if (vme->UseSocket()) vme->Send(e); e.Dump(); }
/*hv->SetChannelV0(0, 320);
hv->SetChannelI0(0, 0);
hv->ReadChannelValues(0);*/
// Initialize the configuration one single time
try { vme->ReadXML(xml_config); } catch (Exception& e) {
if (vme->UseSocket()) vme->Send(e);
}
fh.run_id = vme->GetRunNumber();
static const unsigned int num_tdc = vme->GetNumTDC();
VME::FPGAUnitCollection fpgas = vme->GetFPGAUnitCollection(); VME::FPGAUnitV1495* fpga = 0;
for (VME::FPGAUnitCollection::iterator afpga=fpgas.begin(); afpga!=fpgas.end(); afpga++) {
if (afpga->second->IsTDCControlFanout()) { fpga = afpga->second; break; }
}
const bool use_fpga = (fpga!=0);
if (!use_fpga) {
std::ostringstream os;
os << "Trying to launch the acquisition with a\n\t"
<< "configuration in which no FPGA board provide\n\t"
<< "control lines fanout to HPTDCs!\n\t\n\t"
<< "Please check your config.xml file... Aborting!";
throw Exception(__PRETTY_FUNCTION__, os.str(), Fatal);
exit(0);
}
fstream out_file[num_tdc];
string acqmode[num_tdc], detmode[num_tdc];
int num_triggers_in_files;
t_beg = time(0);
// Initial dump of the acquisition parameters before writing the files
cerr << endl << "*** Ready for acquisition! ***" << endl;
VME::TDCCollection tdcs = vme->GetTDCCollection(); unsigned int i = 0;
for (VME::TDCCollection::iterator atdc=tdcs.begin(); atdc!=tdcs.end(); atdc++, i++) {
switch (atdc->second->GetAcquisitionMode()) {
case VME::CONT_STORAGE: acqmode[i] = "Continuous storage"; break;
case VME::TRIG_MATCH: acqmode[i] = "Trigger matching"; break;
default:
acqmode[i] = "[Invalid mode]";
throw Exception(__PRETTY_FUNCTION__, "Invalid acquisition mode!", Fatal);
}
switch (atdc->second->GetDetectionMode()) {
case VME::PAIR: detmode[i] = "Pair measurement"; break;
case VME::OLEADING: detmode[i] = "Leading edge only"; break;
case VME::OTRAILING: detmode[i] = "Trailing edge only"; break;
case VME::TRAILEAD: detmode[i] = "Leading and trailing edges"; break;
}
}
cerr << "Acquisition mode: ";
for (unsigned int i=0; i<num_tdc; i++) { if (i>0) cerr << " / "; cerr << acqmode[i]; }
cerr << endl
<< "Detection mode: ";
for (unsigned int i=0; i<num_tdc; i++) { if (i>0) cerr << " / "; cerr << detmode[i]; }
cerr << endl
<< "Local time: " << asctime(localtime(&t_beg));
if (use_fpga) {
fpga->StartScaler();
}
// Change outputs file once a minimal amount of triggers is hit
while (true) {
// First all registers are updated
i = 0; time_t start = time(0);
num_triggers_in_files = 0;
// Declare a new burst to the online DB
vme->NewBurst();
fh.spill_id = vme->GetBurstNumber();
// TDC output files configuration
for (VME::TDCCollection::iterator atdc=tdcs.begin(); atdc!=tdcs.end(); atdc++, i++) {
VME::TDCV1x90* tdc = atdc->second;
fh.acq_mode = tdc->GetAcquisitionMode();
fh.det_mode = tdc->GetDetectionMode();
ostringstream filename;
filename << PATH << "/events"
<< "_" << fh.run_id
<< "_" << fh.spill_id
<< "_" << start
<< "_board" << i
//<< "_" GenerateString(4)
<< ".dat";
vme->SetOutputFile(atdc->first, filename.str());
out_file[i].open(vme->GetOutputFile(atdc->first).c_str(), fstream::out | ios::binary);
if (!out_file[i].is_open()) {
throw Exception(__PRETTY_FUNCTION__, "Error opening file", Fatal);
}
out_file[i].write((char*)&fh, sizeof(file_header_t));
}
// Pulse to set a common starting time for both TDC boards
if (use_fpga) {
fpga->PulseTDCBits(VME::FPGAUnitV1495::kReset|VME::FPGAUnitV1495::kClear); // send a RST+CLR signal from FPGA to TDCs
}
// Data readout from the two TDC boards
unsigned long tm = 0;
unsigned long nt = 0;
uint32_t word;
while (true) {
if (use_fpga and (vme->GetGlobalAcquisitionMode()==VMEReader::TriggerStart)) {
if ((nt=fpga->GetScalerValue())!=num_triggers) {
for (unsigned int i=0; i<tdcs.size(); i++) {
if (out_file[i].is_open()) {
word = VME::TDCEvent(VME::TDCEvent::Trigger).GetWord();
out_file[i].write((char*)&word, sizeof(uint32_t));
}
}
num_triggers = nt;
}
/*else if (cnt_without_new_trigger>1000) { break; cnt_without_new_trigger = 0; }
cnt_without_new_trigger++;*/ //FIXME new feature to be tested before integration
}
unsigned int i = 0; tm += 1;
for (VME::TDCCollection::iterator atdc=tdcs.begin(); atdc!=tdcs.end(); atdc++, i++) {
ec = atdc->second->FetchEvents();
if (ec.size()==0) continue; // no events were fetched
for (VME::TDCEventCollection::const_iterator e=ec.begin(); e!=ec.end(); e++) {
word = e->GetWord();
out_file[i].write((char*)&word, sizeof(uint32_t));
/*cout << dec << "board" << i << ": " << hex << e->GetType() << "\t";
if (e->GetType()==VME::TDCEvent::TDCMeasurement) cout << e->GetChannelId();
cout << endl;*/
//e->Dump();
//if (e->GetType()==VME::TDCEvent::TDCMeasurement) cout << "----> (board " << dec << i << " with address " << hex << atdc->first << dec << ") new event on channel " << e->GetChannelId() << endl;
}
num_events[i] += ec.size();
}
if (use_fpga and tm>5000) { // probe the scaler value every N data readouts
if (vme->GetGlobalAcquisitionMode()!=VMEReader::TriggerStart) num_triggers = fpga->GetScalerValue();
try {
vme->BroadcastHVStatus(0, hv->ReadChannelValues(0));
vme->BroadcastHVStatus(3, hv->ReadChannelValues(3));
} catch (Exception& e) {;}
num_triggers_in_files = num_triggers-num_all_triggers;
cerr << "--> " << num_triggers << " triggers acquired in this run so far" << endl;
if (num_triggers_in_files>0 and num_triggers_in_files>=NUM_TRIG_BEFORE_FILE_CHANGE) {
num_all_triggers = num_triggers;
break; // break the infinite loop to write and close the current file
}
tm = 0;
}
}
num_files += 1;
cerr << "---> " << num_triggers_in_files << " triggers written in current TDC output files" << endl;
unsigned int i = 0;
for (VME::TDCCollection::const_iterator atdc=tdcs.begin(); atdc!=tdcs.end(); atdc++, i++) {
if (out_file[i].is_open()) out_file[i].close();
cout << "Sent output from TDC 0x" << hex << atdc->first << dec << " in spill id " << fh.spill_id << endl;
vme->SendOutputFile(atdc->first); usleep(1000);
}
vme->BroadcastNewBurst(fh.spill_id); usleep(1000);
vme->BroadcastTriggerRate(fh.spill_id, num_triggers);
}
} catch (Exception& e) {
// If any TDC::FetchEvent method throws an "acquisition stop" message
if (e.ErrorNumber()==TDC_ACQ_STOP) {
unsigned int i = 0;
try {
VME::TDCCollection tdcs = vme->GetTDCCollection();
for (VME::TDCCollection::const_iterator atdc=tdcs.begin(); atdc!=tdcs.end(); atdc++, i++) {
if (out_file[i].is_open()) out_file[i].close();
vme->SendOutputFile(atdc->first); usleep(1000);
}
time_t t_end = time(0);
double nsec_tot = difftime(t_end, t_beg), nsec = fmod(nsec_tot,60), nmin = (nsec_tot-nsec)/60.;
cerr << endl << "*** Acquisition stopped! ***" << endl
<< "Local time: " << asctime(localtime(&t_end))
<< "Total acquisition time: " << difftime(t_end, t_beg) << " seconds"
<< " (" << nmin << " min " << nsec << " sec)"
<< endl;
cerr << endl << "Acquired ";
for (unsigned int i=0; i<num_tdc; i++) { if (i>0) cerr << " / "; cerr << num_events[i]; }
cerr << " words in " << num_files << " files for " << num_triggers << " triggers in this run" << endl;
ostringstream os;
os << "Acquired ";
for (unsigned int i=0; i<num_tdc; i++) { if (i>0) os << " / "; os << num_events[i]; }
os << " words in " << num_files << " files for " << num_triggers << " triggers in this run" << endl
<< "Total acquisition time: " << difftime(t_end, t_beg) << " seconds"
<< " (" << nmin << " min " << nsec << " sec)";
if (vme->UseSocket()) vme->Send(Exception(__PRETTY_FUNCTION__, os.str(), Info));
delete vme;
} catch (Exception& e) { e.Dump(); }
return 0;
}
e.Dump();
if (vme->UseSocket()) vme->Send(e);
return -1;
}
return 0;
}
<file_sep>/listener.cpp
#include "Client.h"
#include <iostream>
using namespace std;
Client* l = 0;
int gEnd = 0;
void CtrlC(int aSig) {
if (gEnd==0) {
cout << endl << "[C-c] Trying a clean exit!" << endl;
if (l) delete l;
exit(0);
}
else if (gEnd>=5) {
cout << endl << "[C-c > 5 times] ... Forcing exit!" << endl;
exit(0);
}
gEnd++;
}
int main(int argc, char* argv[])
{
if (argc<2) return -1;
signal(SIGINT, CtrlC);
const int port = atoi(argv[1]);
cout << "Starting to listen on port " << port << endl;
l = new Client(port);
if (!l->Connect()) {
cout << "Failed to connect the listener" << endl;
return -1;
}
while (true) {
try {
l->Send(SocketMessage(GET_CLIENTS));
l->Receive();
sleep(2);
} catch (Exception& e) {
e.Dump();
//exit(0);
}
}
delete l;
return 0;
}
<file_sep>/src/VMEReader.cpp
#include "VMEReader.h"
VMEReader::VMEReader(const char *device, VME::BridgeType type, bool on_socket) :
Client(1987), fBridge(0), fSG(0), fCAENET(0), fHV(0),
fOnSocket(on_socket), fIsPulserStarted(false)
{
try {
if (fOnSocket) Client::Connect(DETECTOR);
fBridge = new VME::BridgeVx718(device, type);
} catch (Exception& e) {
e.Dump();
if (fOnSocket) Client::Send(e);
}
}
VMEReader::~VMEReader()
{
if (fOnSocket) {
Client::Send(Exception(__PRETTY_FUNCTION__, "Stopping the acquisition process", Info, 30001));
Client::Disconnect();
}
if (fSG) delete fSG;
if (fIsPulserStarted) fBridge->StopPulser();
if (fBridge) delete fBridge;
if (fHV) delete fHV;
if (fCAENET) delete fCAENET;
}
void
VMEReader::ReadXML(const char* filename)
{
tinyxml2::XMLDocument doc;
doc.LoadFile(filename);
if (doc.Error()) {
std::ostringstream os;
os << "Error while trying to parse the configuration file \"" << filename << "\"" << "\n\t"
<< "Code: " << doc.ErrorID() << "\n\t"
<< "Dump of error:" << "\n"
<< doc.GetErrorStr1();
throw Exception(__PRETTY_FUNCTION__, os.str(), Fatal);
}
if (tinyxml2::XMLElement* atrig=doc.FirstChildElement("triggering")) {
if (const char* mode=atrig->Attribute("mode")) {
std::ostringstream os; os << "Triggering mode: ";
if (!strcmp(mode,"continuous_storage")) { fGlobalAcqMode = ContinuousStorage; os << "Continuous storage (manual)"; }
if (!strcmp(mode,"trigger_start")) { fGlobalAcqMode = TriggerStart; os << "Continuous storage (trigger on start)"; }
if (!strcmp(mode,"trigger_matching")) { fGlobalAcqMode = TriggerMatching; os << "Trigger matching"; }
if (fOnSocket) Client::Send(Exception(__PRETTY_FUNCTION__, os.str(), Info));
}
}
for (tinyxml2::XMLElement* afpga=doc.FirstChildElement("fpga"); afpga!=NULL; afpga=afpga->NextSiblingElement("fpga")) {
if (const char* address=afpga->Attribute("address")) {
unsigned long addr = static_cast<unsigned long>(strtol(address, NULL, 0));
if (!addr) throw Exception(__PRETTY_FUNCTION__, "Failed to parse FPGA's base address", Fatal);
try {
try { AddFPGAUnit(addr); } catch (Exception& e) { if (fOnSocket) Client::Send(e); }
VME::FPGAUnitV1495* fpga = GetFPGAUnit(addr);
if (const char* type=afpga->Attribute("type")) {
if (strcmp(type, "tdc_fanout")==0) fpga->SetTDCControlFanout(true);
}
VME::FPGAUnitV1495Control control = fpga->GetControl();
if (tinyxml2::XMLElement* clock=afpga->FirstChildElement("clock")) {
if (tinyxml2::XMLElement* source=clock->FirstChildElement("source")) {
if (!strcmp(source->GetText(),"internal")) control.SetClockSource(VME::FPGAUnitV1495Control::InternalClock);
if (!strcmp(source->GetText(),"external")) control.SetClockSource(VME::FPGAUnitV1495Control::ExternalClock);
}
if (tinyxml2::XMLElement* period=clock->FirstChildElement("period")) {
fpga->SetInternalClockPeriod(atoi(period->GetText()));
}
}
if (tinyxml2::XMLElement* trig=afpga->FirstChildElement("trigger")) {
if (tinyxml2::XMLElement* source=trig->FirstChildElement("source")) {
if (!strcmp(source->GetText(),"internal")) control.SetTriggerSource(VME::FPGAUnitV1495Control::InternalTrigger);
if (!strcmp(source->GetText(),"external")) control.SetTriggerSource(VME::FPGAUnitV1495Control::ExternalTrigger);
}
if (tinyxml2::XMLElement* period=trig->FirstChildElement("period")) {
fpga->SetInternalTriggerPeriod(atoi(period->GetText()));
}
}
if (tinyxml2::XMLElement* sig=afpga->FirstChildElement("signal")) {
if (tinyxml2::XMLElement* source=sig->FirstChildElement("source")) {
if (!strcmp(source->GetText(),"internal")) for (unsigned int i=0; i<2; i++) control.SetSignalSource(i, VME::FPGAUnitV1495Control::InternalSignal);
if (!strcmp(source->GetText(),"external")) for (unsigned int i=0; i<2; i++) control.SetSignalSource(i, VME::FPGAUnitV1495Control::ExternalSignal);
}
if (tinyxml2::XMLElement* poi=sig->FirstChildElement("poi")) {
fpga->SetOutputPulserPOI(atoi(poi->GetText()));
}
}
if (tinyxml2::XMLElement* vth=afpga->FirstChildElement("threshold")) {
if (tinyxml2::XMLElement* tdc0=vth->FirstChildElement("tdc0")) {
fpga->SetThresholdVoltage(atoi(tdc0->GetText()), 0);
}
if (tinyxml2::XMLElement* tdc1=vth->FirstChildElement("tdc1")) {
fpga->SetThresholdVoltage(atoi(tdc1->GetText()), 1);
}
if (tinyxml2::XMLElement* tdc2=vth->FirstChildElement("tdc2")) {
fpga->SetThresholdVoltage(atoi(tdc2->GetText()), 2);
}
if (tinyxml2::XMLElement* tdc3=vth->FirstChildElement("tdc3")) {
fpga->SetThresholdVoltage(atoi(tdc3->GetText()), 3);
}
}
switch (fGlobalAcqMode) {
case ContinuousStorage:
case TriggerStart:
control.SetTriggeringMode(VME::FPGAUnitV1495Control::ContinuousStorage); break;
case TriggerMatching:
control.SetTriggeringMode(VME::FPGAUnitV1495Control::TriggerMatching); break;
}
fpga->SetControl(control);
fpga->GetControl().Dump();
fpga->DumpFWInformation();
} catch (Exception& e) { e.Dump(); if (fOnSocket) Client::Send(e); throw e; }
}
else throw Exception(__PRETTY_FUNCTION__, "Failed to extract FPGA's base address", Fatal);
}
unsigned int tdc_id = 0;
for (tinyxml2::XMLElement* atdc=doc.FirstChildElement("tdc"); atdc!=NULL; atdc=atdc->NextSiblingElement("tdc"), tdc_id++) {
if (const char* address=atdc->Attribute("address")) {
unsigned long addr = static_cast<unsigned long>(strtol(address, NULL, 0));
if (!addr) throw Exception(__PRETTY_FUNCTION__, "Failed to parse TDC's base address", Fatal);
try {
try { AddTDC(addr); } catch (Exception& e) { if (fOnSocket) Client::Send(e); }
VME::TDCV1x90* tdc = GetTDC(addr);
uint16_t poi_group1 = 0xffff, poi_group2 = 0xffff;
std::string detector_name = "unknown";
switch (fGlobalAcqMode) {
case ContinuousStorage:
case TriggerStart:
tdc->SetAcquisitionMode(VME::CONT_STORAGE); break;
case TriggerMatching:
tdc->SetAcquisitionMode(VME::TRIG_MATCH); break;
}
//std::cout << triggering_mode << " --> " << tdc->GetAcquisitionMode() << std::endl;
if (tinyxml2::XMLElement* verb=atdc->FirstChildElement("verbosity")) {
tdc->SetVerboseLevel(atoi(verb->GetText()));
}
if (tinyxml2::XMLElement* det=atdc->FirstChildElement("detector")) {
detector_name = det->GetText();
}
if (tinyxml2::XMLElement* det=atdc->FirstChildElement("det_mode")) {
if (!strcmp(det->GetText(),"trailead")) tdc->SetDetectionMode(VME::TRAILEAD);
if (!strcmp(det->GetText(),"leading")) tdc->SetDetectionMode(VME::OLEADING);
if (!strcmp(det->GetText(),"trailing")) tdc->SetDetectionMode(VME::OTRAILING);
if (!strcmp(det->GetText(),"pair")) tdc->SetDetectionMode(VME::PAIR);
}
if (tinyxml2::XMLElement* dll=atdc->FirstChildElement("dll")) {
if (!strcmp(dll->GetText(),"Direct_Low_Resolution")) tdc->SetDLLClock(VME::TDCV1x90::DLL_Direct_LowRes);
if (!strcmp(dll->GetText(),"PLL_Low_Resolution")) tdc->SetDLLClock(VME::TDCV1x90::DLL_PLL_LowRes);
if (!strcmp(dll->GetText(),"PLL_Medium_Resolution")) tdc->SetDLLClock(VME::TDCV1x90::DLL_PLL_MedRes);
if (!strcmp(dll->GetText(),"PLL_High_Resolution")) tdc->SetDLLClock(VME::TDCV1x90::DLL_PLL_HighRes);
}
if (tinyxml2::XMLElement* poi=atdc->FirstChildElement("poi")) {
if (tinyxml2::XMLElement* g0=poi->FirstChildElement("group0")) { poi_group1 = atoi(g0->GetText()); }
if (tinyxml2::XMLElement* g1=poi->FirstChildElement("group1")) { poi_group2 = atoi(g1->GetText()); }
}
tdc->SetPoI(poi_group1, poi_group2);
if (atdc->FirstChildElement("ettt")) { tdc->SetETTT(); }
if (tinyxml2::XMLElement* wind=atdc->FirstChildElement("trigger_window")) {
if (tinyxml2::XMLElement* width=wind->FirstChildElement("width")) { tdc->SetWindowWidth(atoi(width->GetText())); }
if (tinyxml2::XMLElement* offset=wind->FirstChildElement("offset")) { tdc->SetWindowOffset(atoi(offset->GetText())); }
}
OnlineDBHandler().SetTDCConditions(tdc_id, addr, tdc->GetAcquisitionMode(), tdc->GetDetectionMode(), detector_name);
} catch (Exception& e) { throw e; }
}
}
for (tinyxml2::XMLElement* acfd=doc.FirstChildElement("cfd"); acfd!=NULL; acfd=acfd->NextSiblingElement("cfd")) {
if (const char* address=acfd->Attribute("address")) {
unsigned long addr = static_cast<unsigned long>(strtol(address, NULL, 0));
if (!addr) throw Exception(__PRETTY_FUNCTION__, "Failed to parse CFD's base address", Fatal);
try {
try { AddCFD(addr); } catch (Exception& e) { if (fOnSocket) Client::Send(e); }
VME::CFDV812* cfd = GetCFD(addr);
if (tinyxml2::XMLElement* poi=acfd->FirstChildElement("poi")) { cfd->SetPOI(atoi(poi->GetText())); }
if (tinyxml2::XMLElement* ow=acfd->FirstChildElement("output_width")) {
if (tinyxml2::XMLElement* g0=ow->FirstChildElement("group0")) { cfd->SetOutputWidth(0, atoi(g0->GetText())); }
if (tinyxml2::XMLElement* g1=ow->FirstChildElement("group1")) { cfd->SetOutputWidth(1, atoi(g1->GetText())); }
}
if (tinyxml2::XMLElement* dt=acfd->FirstChildElement("dead_time")) {
if (tinyxml2::XMLElement* g0=dt->FirstChildElement("group0")) { cfd->SetDeadTime(0, atoi(g0->GetText())); }
if (tinyxml2::XMLElement* g1=dt->FirstChildElement("group1")) { cfd->SetDeadTime(1, atoi(g1->GetText())); }
}
if (tinyxml2::XMLElement* thr=acfd->FirstChildElement("threshold")) {
for (tinyxml2::XMLElement* ch=thr->FirstChildElement("channel"); ch!=NULL; ch=ch->NextSiblingElement("channel")) {
cfd->SetThreshold(atoi(ch->Attribute("id")), atoi(ch->GetText()));
std::cout << "Threshold for channel " << atoi(ch->Attribute("id")) << " set to " << ch->GetText() << std::endl;
}
}
} catch (Exception& e) { throw e; }
}
}
std::cout << "Global acquisition mode: " << fGlobalAcqMode << std::endl;
unsigned int run = GetRunNumber();
std::ifstream source(filename, std::ios::binary);
std::stringstream out_name; out_name << std::getenv("PPS_PATH") << "/config/config_run" << run << ".xml";
std::ofstream dest(out_name.str().c_str(), std::ios::binary);
dest << source.rdbuf();
if (fOnSocket) Client::Send(Exception(__PRETTY_FUNCTION__, "Ready to release veto!", Info));
//doc.Print();
}
unsigned int
VMEReader::GetRunNumber() const
{
if (!fOnSocket) return 0;
SocketMessage msg;
try {
msg = Client::SendAndReceive(SocketMessage(GET_RUN_NUMBER), RUN_NUMBER);
return static_cast<unsigned int>(msg.GetIntValue());
} catch (Exception& e) {
e.Dump();
if (fOnSocket) Client::Send(e);
}
return 0;
}
void
VMEReader::AddTDC(uint32_t address)
{
if (!fBridge) throw Exception(__PRETTY_FUNCTION__, "No bridge detected! Aborting...", Fatal);
try {
fTDCCollection.insert(std::pair<uint32_t,VME::TDCV1x90*>(
address,
new VME::TDCV1x90(fBridge->GetHandle(), address)
));
} catch (Exception& e) {
e.Dump();
if (fOnSocket) Client::Send(e);
}
std::ostringstream os;
os << "TDC with base address 0x" << std::hex << address << " successfully built";
throw Exception(__PRETTY_FUNCTION__, os.str(), Info, TDC_ACQ_START);
}
void
VMEReader::AddCFD(uint32_t address)
{
if (!fBridge) throw Exception(__PRETTY_FUNCTION__, "No bridge detected! Aborting...", Fatal);
try {
fCFDCollection.insert(std::pair<uint32_t,VME::CFDV812*>(
address,
new VME::CFDV812(fBridge->GetHandle(), address)
));
} catch (Exception& e) {
e.Dump();
if (fOnSocket) Client::Send(e);
}
std::ostringstream os; os << "CFD with base address 0x" << std::hex << address << " successfully built";
throw Exception(__PRETTY_FUNCTION__, os.str(), Info, TDC_ACQ_START);
}
void
VMEReader::AddIOModule(uint32_t address)
{
if (!fBridge) throw Exception(__PRETTY_FUNCTION__, "No bridge detected! Aborting...", Fatal);
try {
fSG = new VME::IOModuleV262(fBridge->GetHandle(), address);
} catch (Exception& e) {
e.Dump();
if (fOnSocket) Client::Send(e);
}
std::ostringstream os; os << "I/O module with base address 0x" << std::hex << address << " successfully built";
throw Exception(__PRETTY_FUNCTION__, os.str(), Info, TDC_ACQ_START);
}
void
VMEReader::AddFPGAUnit(uint32_t address)
{
if (!fBridge) throw Exception(__PRETTY_FUNCTION__, "No bridge detected! Aborting...", Fatal);
try {
fFPGACollection.insert(std::pair<uint32_t,VME::FPGAUnitV1495*>(
address,
new VME::FPGAUnitV1495(fBridge->GetHandle(), address)
));
} catch (Exception& e) {
e.Dump();
if (fOnSocket) Client::Send(e);
}
sleep(4); // wait for FW to be ready...
std::ostringstream os; os << "FPGA module with base address 0x" << std::hex << address << " successfully built";
throw Exception(__PRETTY_FUNCTION__, os.str(), Info, TDC_ACQ_START);
}
void
VMEReader::AddHVModule(uint32_t vme_address, uint16_t nim_address)
{
if (!fBridge) throw Exception(__PRETTY_FUNCTION__, "No bridge detected! Aborting...", Fatal);
if (!fCAENET) fCAENET = new VME::CAENETControllerV288(fBridge->GetHandle(), vme_address);
try {
fHV = new NIM::HVModuleN470(nim_address, *fCAENET);
} catch (Exception& e) {
e.Dump();
if (fOnSocket) Client::Send(e);
std::ostringstream os;
os << "Failed to add NIM HV module at address 0x" << std::hex << nim_address << "\n\t"
<< "through VME CAENET controller at address 0x" << std::hex << vme_address;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
std::ostringstream os;
os << "NIM HV module with address 0x" << std::hex << nim_address << "\n\t"
<< " (through VME CAENET controller at base address 0x" << std::hex << vme_address << ") successfully built";
throw Exception(__PRETTY_FUNCTION__, os.str(), Info, TDC_ACQ_START);
}
void
VMEReader::Abort()
{
if (!fBridge) throw Exception(__PRETTY_FUNCTION__, "No bridge detected! Aborting...", Fatal);
try {
for (VME::TDCCollection::iterator t=fTDCCollection.begin(); t!=fTDCCollection.end(); t++) {
t->second->abort();
}
} catch (Exception& e) {
e.Dump();
if (fOnSocket) Client::Send(e);
}
}
void
VMEReader::NewRun() const
{
if (!fOnSocket) return;
Client::Send(SocketMessage(NEW_RUN));
std::ostringstream os; os << "New run detected: " << GetRunNumber();
Client::Send(Exception(__PRETTY_FUNCTION__, os.str(), JustWarning));
}
void
VMEReader::SetOutputFile(uint32_t tdc_address, std::string filename)
{
OutputFiles::iterator it = fOutputFiles.find(tdc_address);
if (it!=fOutputFiles.end()) { it->second = filename; }
else fOutputFiles.insert(std::pair<uint32_t, std::string>(tdc_address, filename));
}
void
VMEReader::SendOutputFile(uint32_t tdc_address) const
{
if (!fOnSocket) return;
OutputFiles::const_iterator it = fOutputFiles.find(tdc_address);
if (it!=fOutputFiles.end()) {
std::ostringstream os;
os << tdc_address << ":" << it->second;
Client::Send(SocketMessage(SET_NEW_FILENAME, os.str()));
}
}
void
VMEReader::BroadcastNewBurst(unsigned int burst_id) const
{
if (!fOnSocket) return;
std::ostringstream os; os << "New output file detected: burst id " << burst_id;
Client::Send(Exception(__PRETTY_FUNCTION__, os.str(), JustWarning));
}
void
VMEReader::BroadcastTriggerRate(unsigned int burst_id, unsigned long num_triggers) const
{
std::ostringstream os; os << burst_id << ":" << num_triggers;
Client::Send(SocketMessage(NUM_TRIGGERS, os.str()));
}
void
VMEReader::BroadcastHVStatus(unsigned short channel_id, const NIM::HVModuleN470ChannelValues& val) const
{
std::ostringstream os; os << channel_id << ":" << val.ChannelStatus() << "," << val.Imon() << "," << val.Vmon();
Client::Send(SocketMessage(HV_STATUS, os.str()));
}
void
VMEReader::LogHVValues(unsigned short channel_id, const NIM::HVModuleN470ChannelValues& val) const
{
try {
OnlineDBHandler().SetHVConditions(channel_id, val.V0(), val.I0());
} catch (Exception& e) {
e.Dump();
}
}
<file_sep>/include/Exception.h
#ifndef Exception_h
#define Exception_h
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib> // exit()
#define PrintInfo(m) Exception(__PRETTY_FUNCTION__, m, Info).Dump();
/**
* \brief Enumeration of exception severities
* \author <NAME> <<EMAIL>>
* \date 27 Mar 2015
*/
typedef enum
{
Undefined=-1,
Info,
JustWarning,
Fatal
} ExceptionType;
/**
* \brief A simple exception handler
* \author <NAME> <<EMAIL>>
* \date 24 Mar 2015
*/
class Exception
{
public:
inline Exception(const char* from, std::string desc, ExceptionType type=Undefined, const int id=0) {
fFrom = from;
fDescription = desc;
fType = type;
fErrorNumber = id;
}
inline Exception(const char* from, const char* desc, ExceptionType type=Undefined, const int id=0) {
fFrom = from;
fDescription = desc;
fType = type;
fErrorNumber = id;
}
inline ~Exception() {
if (Type()==Fatal) exit(0);
// we stop this process' execution on fatal exception
}
inline std::string From() const { return fFrom; }
inline int ErrorNumber() const { return fErrorNumber; }
inline std::string Description() const { return fDescription; }
inline ExceptionType Type() const { return fType; }
inline std::string TypeString() const {
switch (Type()) {
case JustWarning: return "\033[34;1mJustWarning\033[0m";
case Info: return "\033[33;1mInfo\033[0m";
case Fatal: return "\033[31;1mFatal\033[0m";
case Undefined: default: return "\33[7;1mUndefined\033[0m";
}
}
inline void Dump(std::ostream& os=std::cerr) const {
if (Type()==Info) {
os << "======================= \033[33;1mInformation\033[0m =======================" << std::endl
<< " From: " << From() << std::endl;
}
else {
os << "=================== Exception detected! ===================" << std::endl
<< " Class: " << TypeString() << std::endl
<< " Raised by: " << From() << std::endl;
}
os << " Description: " << std::endl
<< "\t" << Description() << std::endl;
if (ErrorNumber()!=0)
os << "-----------------------------------------------------------" << std::endl
<< " Error #" << ErrorNumber() << std::endl;
os << "===========================================================" << std::endl;
}
inline std::string OneLine() const {
std::ostringstream os;
os << "[" << Type() << "] === " << From() << " === "
<< Description();
return os.str();
}
private:
std::string fFrom;
std::string fDescription;
ExceptionType fType;
int fErrorNumber;
};
#endif
<file_sep>/scripts/SocketHandler.py
#!/usr/bin/env python
import asyncore
import socket
import sys
import os, re
from cStringIO import StringIO
class AsyncClient(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
address = (host, port)
self.connect(address)
self.write_buffer = ''
self.read_buffer = StringIO()
def handle_connect(self):
print 'handle_connect()'
def handle_close(self):
self.close()
def readable(self):
return True
def writable(self):
return (len(self.write_buffer)>0)
def handle_write(self):
print 'handle_write()'
sent = self.send(self.write_buffer)
self.write_buffer = self.write_buffer[sent:]
def handle_read(self):
#print 'handle_read()'
data = self.recv(8192)
if data:
self.read_buffer.write(data)
raise asyncore.ExitNow('Message fetched!')
def fileno(self):
return self.socket.fileno()
def serve_until_message(self):
try:
asyncore.loop(1, 5)
except asyncore.ExitNow, e:
#_split = re.compile(r'[\0%s]' % re.escape(''.join([os.path.sep, os.path.altsep or ''])))
msgs = []
for msg in self.read_buffer.getvalue().split('\0'):
out = msg.split(':')
msgs.append((out[0], ':'.join(out[1:]).replace('\0', '')))
self.read_buffer = StringIO()
#return (out[0], _split.sub('', ':'.join(out[1:])))
return msgs
class SocketHandler:
class SocketError(Exception):
pass
class SendingError(Exception):
pass
class InvalidMessage(Exception):
pass
def __init__(self, host, port):
self.client_id = -1
try:
self.socket = AsyncClient(host, port)
except socket.error:
print "Failed to create socket!"
sys.exit()
print "Socket created"
try:
remote_ip = socket.gethostbyname(host)
except socket.gaierror:
print "Hostname could not be resolved! Exiting"
sys.exit()
# connect to remote server
infos = (remote_ip, port)
try:
self.socket.connect(infos)
except socket.error:
raise self.SocketError
def fileno(self):
return self.socket.fileno()
def Handshake(self, client_type):
try:
self.Send('ADD_CLIENT', client_type)
except SendingError:
print "Impossible to send client type. Exiting"
raise self.SocketError
sys.exit()
msg = self.Receive()
print msg
if msg and msg[0]=='SET_CLIENT_ID':
self.client_id = msg[1]
print 'Client id='+ self.client_id
def GetClientId(self): return self.client_id
def Disconnect(self):
try:
self.Send('REMOVE_CLIENT', self.client_id)
print 'REMOVE_CLIENT', self.client_id, 'sent'
return True
except SendingError:
print "Failed to disconnect the GUI from master. Exiting roughly..."
return False
def ReceiveAll(self):
return self.socket.serve_until_message()
def Receive(self, key=None, max_num_trials=2):
num_trials = 0
while True:
num_trials += 1
out = self.socket.serve_until_message()
if not out: continue
if not key: return out[0] #FIXME what about the others?
print out
for msg in out:
if len(msg)>1 and msg[0]==key: return msg
if num_trials>max_num_trials: return None
def Send(self, key, value):
try:
self.socket.sendall(key+':'+str(value))
except socket.error:
raise self.SendingError
return True
<file_sep>/test/multireader.cpp
#include "FileReader.h"
#include "PPSCanvas.h"
#include "QuarticCanvas.h"
#include <iostream>
#include <fstream>
#include <vector>
#include "TH1.h"
using namespace std;
int main(int argc, char* argv[]) {
if (argc<2) {
cerr << "Usage: " << argv[0] << " <files list>" << endl;
return -1;
}
enum general_plots {
kNumWords,
numGenPlots
};
enum quartic_plots {
kLeadingTime,
kNumEvents,
numQuPlots
};
const unsigned int num_gen_plots = numGenPlots;
DQM::PPSCanvas* cgen[num_gen_plots];
const unsigned int num_qu_plots = numQuPlots;
DQM::QuarticCanvas* cqu[num_qu_plots];
vector<string> files;
string buff;
fstream list(argv[1]);
while (list>>buff) { files.push_back(buff); }
TH1D* h_num_words = new TH1D("num_words", "", 300, 0., 300000.);
cqu[kLeadingTime] = new DQM::QuarticCanvas("multiread_quartic_mean_leading_time", "Mean leading time (ns)");
//cqu[kNumEvents] = new DQM::QuarticCanvas("multiread_quartic_num_events_per_channel", "Number of events per channel");
VME::TDCMeasurement m;
for (vector<string>::iterator f=files.begin(); f!=files.end(); f++) {
try {
FileReader fr(*f);
cout << "Opening file with burst train " << fr.GetBurstId() << endl;
h_num_words->Fill(fr.GetNumEvents());
for (unsigned int ch=0; ch<32; ch++) {
while (true) {
if (!fr.GetNextMeasurement(ch, &m)) break;
//cqu[kNumEvents]->FillChannel(ch, m.NumEvents());
unsigned int leadingtime = 0;
for (unsigned int i=0; i<m.NumEvents(); i++) { leadingtime += m.GetLeadingTime(i); }
cqu[kLeadingTime]->FillChannel(ch, leadingtime*25./1000./m.NumEvents());
}
fr.Clear();
}
} catch (Exception& e) {
e.Dump();
}
}
cgen[kNumWords] = new DQM::PPSCanvas("multiread_num_words_per_file", "Number of data words per file");
//cgen[kNumWords]->cd();
h_num_words->Draw();
//cgen[kNumWords]->Grid()->SetLogx();
cgen[kNumWords]->Save("png");
//cqu[kNumEvents]->Save("png");
cqu[kLeadingTime]->Save("png");
return 0;
}
<file_sep>/include/VME_CAENETControllerV288.h
#ifndef VME_CAENETControllerV288_h
#define VME_CAENETControllerV288_h
#include "VME_GenericBoard.h"
#include <vector>
#include <unistd.h>
#define MSTIDENT 1
namespace VME
{
enum CAENETControllerV288Register {
kV288DataBuffer = 0x00, // R/W
kV288Status = 0x02, // R
kV288Transmission = 0x04, // W
kV288ModuleReset = 0x06, // W
kV288IRQVector = 0x08 // W
};
enum CAENETControllerV288Answer {
cnSuccess = 0x0000,
cnBusy = 0xff00,
cnUnrecognizedCode = 0xff01,
cnIncorrectValue = 0xff02,
cnNoData = 0xfffd,
cnIncorrectHCC = 0xfffe,
cnWrongModuleAddress = 0xffff
};
class CAENETControllerV288Status
{
public:
inline CAENETControllerV288Status(uint16_t word) : fWord(word) {;}
inline ~CAENETControllerV288Status() {;}
enum OperationStatus { Valid=0x0, Invalid=0x1 };
inline OperationStatus GetOperationStatus() const { return static_cast<OperationStatus>(fWord&0x1); }
private:
uint16_t fWord;
};
/**
* \brief Handler for a CAEN V288 CAENET controller
* \author <NAME> <<EMAIL>>
* \date 23 Jul 2015
*/
class CAENETControllerV288 : public GenericBoard<CAENETControllerV288Register,cvA24_U_DATA>
{
public:
CAENETControllerV288(int32_t handle, uint32_t baseaddr);
~CAENETControllerV288();
void Reset() const;
CAENETControllerV288Status GetStatus() const;
/// Fill the buffer with an additional 16-bit word
friend void operator<<(const CAENETControllerV288& cnt, uint16_t word) {
try {
cnt.WriteRegister(kV288DataBuffer, word);
if (cnt.GetStatus().GetOperationStatus()!=CAENETControllerV288Status::Valid)
throw Exception(__PRETTY_FUNCTION__, "Wrong status retrieved", JustWarning);
} catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Failed to fill the buffer with an additional word", JustWarning);
}
}
/// Read back a 16-bit word from the buffer
friend uint16_t& operator>>(const CAENETControllerV288& cnt, uint16_t& word) {
try {
cnt.ReadRegister(kV288DataBuffer, &word);
if (cnt.GetStatus().GetOperationStatus()!=CAENETControllerV288Status::Valid)
throw Exception(__PRETTY_FUNCTION__, "Wrong status retrieved", JustWarning);
} catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Failed to retrieve an additional word from the buffer", JustWarning);
}
return word;
}
/// Send the whole buffer through the network
void SendBuffer() const;
/// Retrieve the network buffer
std::vector<uint16_t> FetchBuffer(unsigned int num_words) const;
bool WaitForResponse(CAENETControllerV288Answer* response, unsigned int max_trials=-1) const;
private:
};
}
#endif
<file_sep>/include/GastofCanvas.h
#include "TCanvas.h"
#include "TPaveText.h"
#include "TLegend.h"
#include "TH2.h"
#include "TStyle.h"
#include "TDatime.h"
namespace DQM
{
/**
* \author <NAME> <<EMAIL>>
* \date 25 Jul 2015
*/
class GastofCanvas : public TCanvas
{
public:
inline GastofCanvas() :
TCanvas("null"), fLegend(0), fLegendX(.52), fLegendY(.76), fLegendNumEntries(0),
fUpperLabel(0), fLabelsDrawn(false), fRunId(0), fRunDate(TDatime().AsString()) {;}
inline GastofCanvas(TString name, unsigned int width=500, unsigned int height=500, TString upper_label="") :
TCanvas(name, "", width, height), fWidth(width), fHeight(height), fLegend(0), fLegendX(.52), fLegendY(.76), fLegendNumEntries(0),
fUpperLabelText(upper_label), fUpperLabel(0), fLabelsDrawn(false),
fRunId(0), fRunDate(TDatime().AsString()) { Build(); }
inline GastofCanvas(TString name, TString upper_label) :
TCanvas(name, "", 500, 500), fWidth(500), fHeight(500), fLegend(0), fLegendX(.52), fLegendY(.76), fLegendNumEntries(0),
fUpperLabelText(upper_label), fUpperLabel(0), fLabelsDrawn(false),
fRunId(0), fRunDate(TDatime().AsString()) { Build(); }
inline virtual ~GastofCanvas() {
if (fLegend) delete fLegend;
if (fUpperLabel) delete fUpperLabel;
if (fHist) delete fHist;
}
inline void SetRunInfo(unsigned int board_id, unsigned int run_id, unsigned int spill_id, TString date) {
fBoardId = board_id;
fRunId = run_id;
fSpillId = spill_id;
fRunDate = date;
}
inline void SetUpperLabel(TString text) {
fUpperLabelText = text;
fUpperLabel = new TPaveText(.45, .922, .885, .952, "NDC");
fUpperLabel->SetMargin(0.);
fUpperLabel->SetFillColor(kWhite);
fUpperLabel->SetLineColor(kWhite);
fUpperLabel->SetLineWidth(0);
fUpperLabel->SetShadowColor(kWhite);
fUpperLabel->SetTextFont(43);
fUpperLabel->SetTextAlign(33);
fUpperLabel->SetTextSize(18);
fUpperLabel->AddText(fUpperLabelText);
fUpperLabel->Draw();
}
inline void FillChannel(unsigned short nino_id, unsigned short channel_id, double content) {
const Coord c = GetCoordinates(nino_id, channel_id);
fHist->Fill(c.x-0.5, c.y-0.5, content);
}
inline TH2D* Grid() { return fHist; }
inline void Save(TString ext="png", TString path=".") {
bool valid_ext = true;
valid_ext |= (strcmp(ext, "png")!=0);
valid_ext |= (strcmp(ext, "pdf")!=0);
if (!valid_ext) return;
DrawGrid();
if (!fLabelsDrawn) {
fLabel1 = new TPaveText(.112, .925, .2, .955, "NDC");
fLabel1->AddText("GasToF");
fLabel1->SetMargin(0.);
fLabel1->SetFillColor(kWhite);
fLabel1->SetLineColor(kWhite);
fLabel1->SetLineWidth(0);
fLabel1->SetShadowColor(kWhite);
fLabel1->SetTextFont(63);
fLabel1->SetTextAlign(13);
fLabel1->SetTextSize(22);
fLabel1->Draw();
fLabel2 = new TPaveText(.29, .925, .36, .955, "NDC");
fLabel2->AddText("TB2015");
fLabel2->SetMargin(0.);
fLabel2->SetFillColor(kWhite);
fLabel2->SetLineColor(kWhite);
fLabel2->SetLineWidth(0);
fLabel2->SetShadowColor(kWhite);
fLabel2->SetTextFont(43);
fLabel2->SetTextAlign(13);
fLabel2->SetTextSize(22);
fLabel2->Draw();
fLabel3 = new TPaveText(.5, .0, .98, .05, "NDC");
fLabel3->AddText(Form("Board %x, Run %d - Spill %d - %s", fBoardId>>16, fRunId, fSpillId, fRunDate.Data()));
fLabel3->SetMargin(0.);
fLabel3->SetFillColor(kWhite);
fLabel3->SetLineColor(kWhite);
fLabel3->SetLineWidth(0);
fLabel3->SetShadowColor(kWhite);
fLabel3->SetTextFont(43);
fLabel3->SetTextAlign(32);
fLabel3->SetTextSize(16);
fLabel3->Draw();
fLabel4 = new TPaveText(.01, .0, .21, .05, "NDC");
fLabel4->AddText("#downarrow beam #downarrow");
fLabel4->SetMargin(0.);
fLabel4->SetFillColor(kWhite);
fLabel4->SetLineColor(kWhite);
fLabel4->SetLineWidth(0);
fLabel4->SetShadowColor(kWhite);
fLabel4->SetTextFont(43);
fLabel4->SetTextAlign(22);
fLabel4->SetTextSize(18);
fLabel4->Draw();
if (fLegend->GetNRows()!=0) fLegend->Draw();
SetUpperLabel(fUpperLabelText);
fLabelsDrawn = true;
}
TCanvas::SaveAs(Form("%s/%s.%s", path.Data(), TCanvas::GetName(), ext.Data()));
c1->SetLogz();
TCanvas::SaveAs(Form("%s/%s_logscale.%s", path.Data(), TCanvas::GetName(), ext.Data()));
}
private:
inline void Build() {
fLegend = new TLegend(fLegendX, fLegendY, fLegendX+.35, fLegendY+.12);
fLegend->SetFillColor(kWhite);
fLegend->SetLineColor(kWhite);
fLegend->SetLineWidth(0);
fLegend->SetTextFont(43);
fLegend->SetTextSize(14);
fHist = new TH2D(Form("hist_%s", TCanvas::GetName()), "", 8, 0.5, 8.5, 8, 0.5, 8.5);
}
inline void DrawGrid() {
TCanvas::cd();
gStyle->SetOptStat(0);
TCanvas::Divide(1,2);
c1 = (TPad*)TCanvas::GetPad(1);
c2 = (TPad*)TCanvas::GetPad(2);
c1->SetPad(0.,0.,1.,1.);
c2->SetPad(0.,0.,1.,0.);
c1->SetBottomMargin(0.1);
c1->SetLeftMargin(0.1);
c1->SetRightMargin(0.115);
c1->SetTopMargin(0.1);
TCanvas::cd(1);
fHist->Draw("colz");
fHist->SetMarkerStyle(20);
fHist->SetMarkerSize(.87);
fHist->SetTitleFont(43, "XYZ");
fHist->SetTitleSize(22, "XYZ");
//fHist->SetTitleOffset(2., "Y");
fHist->SetLabelFont(43, "XYZ");
fHist->SetLabelSize(24, "XY");
fHist->SetLabelSize(15, "Z");
fHist->SetTitleOffset(1.3, "Y");
c1->SetTicks(1, 1);
//c1->SetGrid(1, 1);
}
struct Coord { unsigned int x; unsigned int y; };
inline Coord GetCoordinates(unsigned short nino_id, unsigned short channel_id) const {
Coord out;
out.x = out.y = 0;
switch (nino_id) {
case 0:
switch (channel_id) {
case 0: out.x = 1, out.y = 1; break;
case 1: out.x = 2, out.y = 1; break;
case 2: out.x = 3, out.y = 1; break;
case 3: out.x = 4, out.y = 1; break;
case 4: out.x = 5, out.y = 1; break;
case 5: out.x = 6, out.y = 1; break;
case 6: out.x = 7, out.y = 1; break;
case 7: out.x = 8, out.y = 1; break;
case 8: out.x = 1, out.y = 2; break;
case 9: out.x = 2, out.y = 2; break;
case 10: out.x = 7, out.y = 2; break;
case 11: out.x = 8, out.y = 2; break;
case 12: out.x = 1, out.y = 3; break;
case 13: out.x = 8, out.y = 3; break;
case 14: out.x = 1, out.y = 4; break;
case 15: out.x = 8, out.y = 4; break;
case 16: out.x = 1, out.y = 5; break;
case 17: out.x = 8, out.y = 5; break;
case 18: out.x = 1, out.y = 6; break;
case 19: out.x = 8, out.y = 6; break;
case 20: out.x = 1, out.y = 7; break;
case 21: out.x = 2, out.y = 7; break;
case 22: out.x = 7, out.y = 7; break;
case 23: out.x = 8, out.y = 7; break;
case 24: out.x = 1, out.y = 8; break;
case 25: out.x = 2, out.y = 8; break;
case 26: out.x = 3, out.y = 8; break;
case 27: out.x = 4, out.y = 8; break;
case 28: out.x = 5, out.y = 8; break;
case 29: out.x = 6, out.y = 8; break;
case 30: out.x = 7, out.y = 8; break;
case 31: out.x = 8, out.y = 8; break;
}
break;
case 1:
switch (channel_id) {
case 0: out.x = 3, out.y = 2; break;
case 1: out.x = 4, out.y = 2; break;
case 2: out.x = 5, out.y = 2; break;
case 3: out.x = 6, out.y = 2; break;
case 4: out.x = 2, out.y = 3; break;
case 5: out.x = 3, out.y = 3; break;
case 6: out.x = 4, out.y = 3; break;
case 7: out.x = 5, out.y = 3; break;
case 8: out.x = 6, out.y = 3; break;
case 9: out.x = 7, out.y = 3; break;
case 10: out.x = 2, out.y = 4; break;
case 11: out.x = 3, out.y = 4; break;
case 12: out.x = 4, out.y = 4; break;
case 13: out.x = 5, out.y = 4; break;
case 14: out.x = 6, out.y = 4; break;
case 15: out.x = 7, out.y = 4; break;
case 16: out.x = 2, out.y = 5; break;
case 17: out.x = 3, out.y = 5; break;
case 18: out.x = 4, out.y = 5; break;
case 19: out.x = 5, out.y = 5; break;
case 20: out.x = 6, out.y = 5; break;
case 21: out.x = 7, out.y = 5; break;
case 22: out.x = 2, out.y = 6; break;
case 23: out.x = 3, out.y = 6; break;
case 24: out.x = 4, out.y = 6; break;
case 25: out.x = 5, out.y = 6; break;
case 26: out.x = 6, out.y = 6; break;
case 27: out.x = 7, out.y = 6; break;
case 28: out.x = 3, out.y = 7; break;
case 29: out.x = 4, out.y = 7; break;
case 30: out.x = 5, out.y = 7; break;
case 31: out.x = 6, out.y = 7; break;
}
break;
default:
throw Exception(__PRETTY_FUNCTION__, Form("Invalid NINO identifier fetched! NINO: %d", nino_id), JustWarning);
}
return out;
}
TPad *c1, *c2;
TH2D* fHist;
double fWidth, fHeight;
TLegend *fLegend;
double fLegendX, fLegendY;
unsigned int fLegendNumEntries;
TPaveText *fLabel1, *fLabel2, *fLabel3, *fLabel4;
TString fUpperLabelText;
TPaveText *fUpperLabel;
bool fLabelsDrawn;
unsigned int fBoardId, fRunId, fSpillId;
TString fRunDate;
};
}
<file_sep>/dqm/quartic.cpp
#include "FileReader.h"
#include "DQMProcess.h"
#include "QuarticCanvas.h"
using namespace std;
bool
QuarticDQM(unsigned int address, string filename, vector<string>* outputs)
{
FileReader reader;
try { reader.Open(filename); } catch (Exception& e) { throw e; }
if (!reader.IsOpen()) throw Exception(__PRETTY_FUNCTION__, "Failed to build FileReader", JustWarning);
cout << "Run/Burst Id = " << reader.GetRunId() << " / " << reader.GetBurstId() << endl;
const unsigned int num_channels = 32;
double mean_num_events[num_channels], mean_tot[num_channels];
int trigger_td;
unsigned int num_events[num_channels];
enum plots {
kDensity,
//kMeanToT,
//kTriggerTimeDiff,
kNumPlots
};
const unsigned short num_plots = kNumPlots;
DQM::QuarticCanvas* canv[num_plots];
canv[kDensity] = new DQM::QuarticCanvas(Form("quartic_%d_%d_%d_channels_density", reader.GetRunId(), reader.GetBurstId(), address>>16), "Channels density");
//canv[kMeanToT] = new DQM::QuarticCanvas(Form("quartic_%d_%d_%d_mean_tot", reader.GetRunId(), reader.GetBurstId(), address), "Mean ToT (ns)");
//canv[kTriggerTimeDiff] = new DQM::QuarticCanvas(Form("quartic_%d_%d_%d_trigger_time_difference", reader.GetRunId(), reader.GetBurstId(), address), "Time btw. each trigger (ns)");
VME::TDCMeasurement m;
for (unsigned int i=0; i<num_channels; i++) {
mean_num_events[i] = mean_tot[i] = 0.;
num_events[i] = 0;
trigger_td = 0;
try {
while (true) {
if (!reader.GetNextMeasurement(i, &m)) break;
//if (trigger_td!=0) { canv[kTriggerTimeDiff]->FillChannel(i, (m.GetLeadingTime(0)-trigger_td)*25./1.e3); }
trigger_td = m.GetLeadingTime(0);
for (unsigned int j=0; j<m.NumEvents(); j++) {
mean_tot[i] += m.GetToT(j)*25./1.e3/m.NumEvents();
}
mean_num_events[i] += m.NumEvents();
if (m.NumEvents()!=0) num_events[i] += 1;
}
if (num_events[i]>0) {
mean_num_events[i] /= num_events[i];
mean_tot[i] /= num_events[i];
}
canv[kDensity]->FillChannel(i, num_events[i]);
//canv[kMeanToT]->FillChannel(i, mean_tot[i]);
cout << dec;
cout << "Finished extracting channel " << i << ": " << num_events[i] << " measurements, "
<< "mean number of hits: " << mean_num_events[i] << ", "
<< "mean tot: " << mean_tot[i] << endl;
reader.Clear();
} catch (Exception& e) {
e.Dump();
if (e.ErrorNumber()<41000) throw e;
}
}
for (unsigned int i=0; i<num_plots; i++) {
canv[i]->SetRunInfo(address, reader.GetRunId(), reader.GetBurstId(), TDatime().AsString());
canv[i]->Save("png", DQM_OUTPUT_DIR);
outputs->push_back(canv[i]->GetName());
}
return true;
}
int
main(int argc, char* argv[])
{
if (argc==1) {
DQM::DQMProcess dqm(1987, 2, "quartic");
dqm.Run(QuarticDQM);
}
else {
vector<string> out;
QuarticDQM(0, argv[1], &out);
}
return 0;
}
<file_sep>/include/Client.h
#ifndef Client_h
#define Client_h
#include <string>
#include <sstream>
#include "Socket.h"
/**
* Client object used by the server to send/receive commands from
* the messenger/broadcaster.
* \brief Base client object for the socket
*
* \author <NAME> <<EMAIL>>
* \date 24 Mar 2015
* \ingroup Socket
*/
class Client : public Socket
{
public:
/// General void client constructor
inline Client() {;}
/// Bind a socket client to a given port
Client(int port);
virtual ~Client();
/// Bind this client to the socket
bool Connect(const SocketType& type=CLIENT);
/// Unbind this client from the socket
void Disconnect();
/// Send a message to the master through the socket
inline void Send(const Message& m) const { SendMessage(m); }
inline void Send(const Exception& e) const { SendMessage(SocketMessage(EXCEPTION, e.OneLine())); }
inline SocketMessage SendAndReceive(const SocketMessage& m, const MessageKey& a) const {
SocketMessage msg; int i = 0;
try {
SendMessage(m);
do { msg = FetchMessage(); i++; } while (msg.GetKey()!=a and i<MAX_SOCKET_ATTEMPTS);
} catch (Exception& e) { e.Dump(); throw e; }
return msg;
}
/// Receive a socket message from the master
void Receive();
SocketMessage Receive(const MessageKey& key);
/// Parse a SocketMessage received from the master
virtual void ParseMessage(const SocketMessage& m) {;}
/// Socket actor type retrieval method
virtual SocketType GetType() const { return fType; }
private:
/// Announce our entry on the socket to its master
void Announce();
int fClientId;
bool fIsConnected;
SocketType fType;
};
#endif
<file_sep>/scripts/PPSenv.sh
#!/bin/sh
function ppsRun() {
cd $PPS_PATH;
$PPS_PATH"/ppsRun";
}
function ppsGUI() {
cd $PPS_PATH;
/usr/bin/python $PPS_PATH/../scripts/RunControl.py
}
function ppsLastRun() {
/usr/bin/python $PPS_PATH/../scripts/run_number.py $1
}
function ppsHVstatus() {
/usr/bin/python $PPS_PATH/../scripts/hv_status.py $1
}
function ppsDQM() {
declare -a proc=(
"gastof"
"quartic"
"daq"
"db")
function start_proc() {
cd $PPS_PATH;
$PPS_PATH/dqm/"$1" > /dev/null 2>&1 &
}
function stop_proc() {
killall -9 "$1";
}
function status_proc() {
state=`ps -C "$1" -o stat | tail -1`
time_started=`ps -C "$1" -o lstart | tail -1`
if [[ $state =~ .*STA.* ]] ; then
state=""
time_started="Stopped";
fi
printf "%15s: %2s\t%-10s\n" "$1" "$state" "$time_started";
}
if [ -z "$1" ] ; then
echo "Usage: ppsDQM [start|stop|status]"
return
fi
cd $PPS_PATH;
if [ "$1" == "start" ] ; then
echo "Starting DQM processes..."
for i in "${proc[@]}" ; do
stop_proc $i > /dev/null 2>&1
start_proc $i;
done
elif [ "$1" == "stop" ] ; then
echo "Stopping DQM processes..."
for i in "${proc[@]}" ; do
stop_proc $i > /dev/null 2>&1
done
elif [ "$1" == "status" ] ; then
echo "List of DQM threads:";
for i in "${proc[@]}" ; do
status_proc $i;
done
fi
}
<file_sep>/include/messages.h
#ifndef messages_h
#define messages_h
#include <algorithm>
#include <string>
#include <vector>
/**
* Convert a char/"char,char,..." pair into a <string,string,string,...>
* vector
* \param[in] a A word representing the first message type provided
* \param[in] b A word representing a comma-separated list of message keys
* (starting from the second in the user-defined list)
* \return A well-defined, homogenized vector of strings to be propagated
* through the message keys builder
* \author <NAME> <<EMAIL>>
* \date 26 Mar 2015
*/
inline std::vector<std::string> sar(const char* a, const char* b)
{
std::string o = b;
std::vector<std::string> out;
out.push_back(a);
size_t pos; std::string token;
o.erase(std::remove(o.begin(), o.end(), ' '), o.end());
while ((pos=o.find(","))!=std::string::npos) {
token = o.substr(0, pos);
out.push_back(token.c_str());
o.erase(0, pos+1);
}
return out;
}
/**
* Generate a list of message types (with a struct / string matching), given a
* set of computer-readable names provided as an argument.
* \brief Message keys builder
* \note FIXME: is it sufficiently obfuscated ? I don't think so...
* \author <NAME> <<EMAIL>>
* \date 26 Mar 2015
*/
#define MESSAGES_ENUM(m1, ...)\
enum MessageKey { m1=0, __VA_ARGS__ };\
inline std::string MessageKeyToString(MessageKey value) {\
std::vector<std::string> s=sar(#m1, #__VA_ARGS__);\
return (((unsigned int)value<s.size())&&(value>=0)) ? s[value] : s[0]; } \
inline const MessageKey MessageKeyToObject(const char* value) {\
std::vector<std::string> s=sar(#m1, #__VA_ARGS__);\
for (size_t i=0; i<s.size(); i++) { if (s[i]==std::string(value)) return (MessageKey)i; }\
return (MessageKey)(-1); }
#endif
<file_sep>/scripts/make_ntuples.sh
#!/bin/sh
if [ -z "$1" ] ; then
echo "Usage: "$0" <run_id> <board_id>"
exit
fi
if [ -z "$2" ] ; then
echo "Usage: "$0" <run_id> <board_id>"
exit
fi
python $PPS_BASE_PATH/scripts/run_over_all_files.py $1 $2 && hadd -f "run"$1"_board"$2".root" $PPS_DATA_PATH/events_$1_*_board$2.root
<file_sep>/src/NIM_HVModuleN470.cpp
#include "NIM_HVModuleN470.h"
namespace NIM
{
HVModuleN470::HVModuleN470(uint16_t addr, VME::CAENETControllerV288& cont) :
fController(cont), fAddress(addr)
{;}
std::string
HVModuleN470::GetModuleId() const
{
std::string word = "";
std::vector<unsigned short> out;
try {
ReadRegister(kN470GeneralInfo, &out, 16);
for (std::vector<unsigned short>::iterator it=out.begin(); it!=out.end(); it++) {
word += static_cast<char>((*it)&0xff);
}
} catch (Exception& e) {
e.Dump();
}
return word;
}
HVModuleN470Values
HVModuleN470::ReadMonitoringValues() const
{
std::vector<unsigned short> out;
try { ReadRegister(kN470MonStatus, &out, 16); } catch (Exception& e) {
e.Dump();
}
HVModuleN470Values vals(out);
//vals.Dump();
return vals;
}
HVModuleN470ChannelValues
HVModuleN470::ReadChannelValues(unsigned short ch_id) const
{
if (ch_id<0 or ch_id>=NUM_CHANNELS) throw Exception(__PRETTY_FUNCTION__, "Invalid channel id", JustWarning);
std::vector<unsigned short> out;
const HVModuleN470Opcodes opc = static_cast<HVModuleN470Opcodes>((unsigned short)(kN470OperationalParams&0xff)+(ch_id<<8));
try { ReadRegister(opc, &out, 11); } catch (Exception& e) {
e.Dump();
}
HVModuleN470ChannelValues vals(ch_id, out);
//vals.Dump();
return vals;
}
void
HVModuleN470::SetChannelV0(unsigned short ch_id, unsigned short v0) const
{
if (ch_id<0 or ch_id>=NUM_CHANNELS) throw Exception(__PRETTY_FUNCTION__, "Invalid channel id", JustWarning);
const HVModuleN470Opcodes opc = static_cast<HVModuleN470Opcodes>((unsigned short)(kN470V0Value&0xff)+(ch_id<<8));
try { WriteRegister(opc, v0); } catch (Exception& e) {
e.Dump();
std::ostringstream os; os << "Failed to set V0 to " << v0 << " V on channel " << ch_id;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
}
void
HVModuleN470::SetChannelI0(unsigned short ch_id, unsigned short i0) const
{
if (ch_id<0 or ch_id>=NUM_CHANNELS) throw Exception(__PRETTY_FUNCTION__, "Invalid channel id", JustWarning);
const HVModuleN470Opcodes opc = static_cast<HVModuleN470Opcodes>((unsigned short)(kN470I0Value&0xff)+(ch_id<<8));
try { WriteRegister(opc, i0); } catch (Exception& e) {
e.Dump();
std::ostringstream os; os << "Failed to set I0 to " << i0 << " uA on channel " << ch_id;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
}
void
HVModuleN470::SetChannelV1(unsigned short ch_id, unsigned short v1) const
{
if (ch_id<0 or ch_id>=NUM_CHANNELS) throw Exception(__PRETTY_FUNCTION__, "Invalid channel id", JustWarning);
const HVModuleN470Opcodes opc = static_cast<HVModuleN470Opcodes>((unsigned short)(kN470V1Value&0xff)+(ch_id<<8));
try { WriteRegister(opc, v1); } catch (Exception& e) {
e.Dump();
std::ostringstream os; os << "Failed to set V1 to " << v1 << " V on channel " << ch_id;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
}
void
HVModuleN470::SetChannelI1(unsigned short ch_id, unsigned short i1) const
{
if (ch_id<0 or ch_id>=NUM_CHANNELS) throw Exception(__PRETTY_FUNCTION__, "Invalid channel id", JustWarning);
const HVModuleN470Opcodes opc = static_cast<HVModuleN470Opcodes>((unsigned short)(kN470I1Value&0xff)+(ch_id<<8));
try { WriteRegister(opc, i1); } catch (Exception& e) {
e.Dump();
std::ostringstream os; os << "Failed to set I1 to " << i1 << " uA on channel " << ch_id;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
}
void
HVModuleN470::EnableChannel(unsigned short ch_id) const
{
if (ch_id<0 or ch_id>=NUM_CHANNELS) throw Exception(__PRETTY_FUNCTION__, "Invalid channel id", JustWarning);
const HVModuleN470Opcodes opc = static_cast<HVModuleN470Opcodes>((unsigned short)(kN470ChannelOn&0xff)+(ch_id<<8));
try { WriteRegister(opc, 0x1); } catch (Exception& e) {
e.Dump();
std::ostringstream os; os << "Failed to enable channel " << ch_id;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
}
void
HVModuleN470::DisableChannel(unsigned short ch_id) const
{
if (ch_id<0 or ch_id>=NUM_CHANNELS) throw Exception(__PRETTY_FUNCTION__, "Invalid channel id", JustWarning);
const HVModuleN470Opcodes opc = static_cast<HVModuleN470Opcodes>((unsigned short)(kN470ChannelOff&0xff)+(ch_id<<8));
try { WriteRegister(opc, 0x1); } catch (Exception& e) {
e.Dump();
std::ostringstream os; os << "Failed to disable channel " << ch_id;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
}
void
HVModuleN470::ReadRegister(const HVModuleN470Opcodes& reg, std::vector<uint16_t>* data, unsigned int num_words) const
{
try {
fController << (uint16_t)MSTIDENT;
fController << (uint16_t)fAddress;
fController << (uint16_t)reg;
fController.SendBuffer();
*data = fController.FetchBuffer(num_words);
if (data->size()!=num_words)
throw Exception(__PRETTY_FUNCTION__, "Wrong word size retrieved", JustWarning);
} catch (Exception& e) {
e.Dump();
std::ostringstream o;
o << "Impossible to read register at 0x" << std::hex << reg << "\n\t"
<< "Base address: 0x" << std::hex << fAddress;
throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning);
}
}
void
HVModuleN470::WriteRegister(const HVModuleN470Opcodes& reg, const std::vector<uint16_t>& data) const
{
try {
fController << (uint16_t)MSTIDENT;
fController << (uint16_t)fAddress;
fController << (uint16_t)reg;
for (std::vector<uint16_t>::const_iterator it=data.begin(); it!=data.end(); it++) {
fController << (uint16_t)(*it);
}
fController.SendBuffer();
usleep(5000);
} catch (Exception& e) {
e.Dump();
std::ostringstream o;
o << "Impossible to read register at 0x" << std::hex << reg << "\n\t"
<< "Base address: 0x" << std::hex << fAddress;
throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning);
}
}
void
HVModuleN470::WriteRegister(const HVModuleN470Opcodes& reg, const uint16_t& data) const
{
try {
std::vector<uint16_t> v_data; v_data.push_back(data);
WriteRegister(reg, v_data);
} catch (Exception& e) { throw e; }
}
}
<file_sep>/test/reader_channelid.cpp
#include <iostream>
#include "FileReader.h"
#include "TCanvas.h"
#include "TH1.h"
#include "TF1.h"
#include "TStyle.h"
#include "TLegend.h"
using namespace std;
using namespace VME;
int
main(int argc, char* argv[])
{
if (argc<2) {
cout << "Usage:\n\t" << argv[0] << " <input file>" << endl;
return -1;
}
TDCMeasurement m;
int num_events;
const unsigned int num_channels = 32;
TH1D* h[num_channels];
for (unsigned int i=0; i<num_channels; i++) {
h[i] = new TH1D(Form("tot_%i",i), "", 100, 0., 200.);
FileReader f(argv[1]);
num_events = 0;
while (true) {
try {
if (!f.GetNextMeasurement(i, &m)) break;
//cout << m.GetLeadingTime()-m.GetTrailingTime() << endl;
for (unsigned int j=0; j<m.NumEvents(); j++) {
h[i]->Fill(m.GetToT(j)*25./1024.);
}
num_events += m.NumEvents();
} catch (Exception& e) { /*e.Dump();*/ }
}
cout << "number of events in channel " << i << ": " << num_events << endl;
}
gStyle->SetPadGridX(true); gStyle->SetPadGridY(true);
gStyle->SetPadTickX(true); gStyle->SetPadTickY(true);
gStyle->SetOptStat(0);
TCanvas* c = new TCanvas("canv_multichannels", "", 1200, 800);
c->Divide(2);
TLegend *leg1, *leg2;
leg1 = new TLegend(0.12, 0.65, 0.6, 0.88);
leg2 = new TLegend(0.12, 0.65, 0.6, 0.88);
double mx1 = -1., mx2 = -1;
c->cd(1);
for (unsigned int i=0; i<num_channels; i++) {
if (i==num_channels/2) {
leg1->Draw();
c->cd(2);
}
if (i==0 or i==num_channels/2) h[i]->Draw();
else h[i]->Draw("same");
if (i<num_channels/2) {
h[i]->SetLineColor(i+2);// h[i]->SetLineStyle(1);
mx1 = max(mx1, h[i]->GetMaximum());
}
else {
h[i]->SetLineColor(i+2-num_channels/2);// h[i]->SetLineStyle(2);
mx2 = max(mx2, h[i]->GetMaximum());
}
if (h[i]->Integral()!=0) {
h[i]->Fit("gaus", "0");
TF1* f = (TF1*)h[i]->GetFunction("gaus");
if (i<num_channels/2) leg1->AddEntry(h[i], Form("Channel %i N=%.1f, #mu=%.4g, #sigma=%.3g",i,h[i]->Integral(),f->GetParameter(1),f->GetParameter(2)), "l");
else leg2->AddEntry(h[i], Form("Channel %i N=%.1f, #mu=%.4g, #sigma=%.3g",i,h[i]->Integral(),f->GetParameter(1),f->GetParameter(2)), "l");
}
else {
if (i<num_channels/2) leg1->AddEntry(h[i], Form("Channel %i",i), "l");
else leg2->AddEntry(h[i], Form("Channel %i",i), "l");
}
}
leg2->Draw();
h[0]->GetXaxis()->SetTitle("Time over threshold (ns)");
h[0]->GetYaxis()->SetTitle("Events");
h[0]->GetYaxis()->SetRangeUser(.1, mx1*1.3);
h[num_channels/2]->GetXaxis()->SetTitle("Time over threshold (ns)");
h[num_channels/2]->GetYaxis()->SetTitle("Events");
h[num_channels/2]->GetYaxis()->SetRangeUser(.1, mx2*1.3);
leg1->SetTextFont(43); leg1->SetTextSize(14);
leg2->SetTextFont(43); leg2->SetTextSize(14);
c->SaveAs("dist_tot_multichannels.png");
c->SaveAs("dist_tot_multichannels.pdf");
return 0;
}
<file_sep>/include/VME_PCIInterfaceA2818.h
#ifndef VME_PCIInterfaceA2828_h
#define VME_PCIInterfaceA2818_h
#include "CAENVMEtypes.h"
#include <string>
namespace VME
{
class PCIInterfaceA2818
{
public:
inline PCIInterfaceA2818(const char* device) {
int dev = atoi(device);
CVErrorCodes ret = CAENVME_Init(cvA2818, 0x0, dev, &fHandle);
if (ret!=cvSuccess) {
std::ostringstream os;
os << "Failed to initiate communication with" << "\n\t"
<< "the PCI/VME interface board" << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(ret);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(ret));
}
}
inline virtual ~PCIInterfaceA2818() {
CAENVME_End(fHandle);
}
inline std::string GetFWRevision() const {
char out[30];
CVErrorCodes ret = CAENVME_BoardFWRelease(fHandle, out);
if (ret!=cvSuccess) {
std::ostringstream os;
os << "Failed to retrieve the FW version" << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(ret);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(ret));
}
return std::string(out);
}
private:
int fHandle;
};
}
#endif
<file_sep>/scripts/Plot.py
#!/usr/bin/python
import gtk
from gtk import gdk
import cairo
from pycha.line import LineChart
from pycha.bar import VerticalBarChart
class Plot (gtk.DrawingArea):
def __init__(self):
gtk.DrawingArea.__init__(self)
self.connect("expose_event", self.expose)
self.connect("size-allocate", self.size_allocate)
self._surface = None
self._options = None
def set_options(self, options):
"""Set plot's options"""
self._options = options
def set_data(self, data):
pass
def get_data(self):
pass
def plot(self):
pass
def expose(self, widget, event):
context = widget.window.cairo_create()
context.rectangle(event.area.x, event.area.y, event.area.width, event.area.height)
context.clip()
self.draw(context)
return False
def draw(self, context):
rect = self.get_allocation()
self._surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, rect.width, rect.height)
self.plot()
context.set_source_surface(self._surface, 0, 0)
context.paint()
def size_allocate(self, widget, requisition):
self.queue_draw()
class LinePlot(Plot):
def __init__(self):
Plot.__init__(self)
def set_data(self, data, title='Data'):
"""
Update plot's data and refreshes DrawingArea contents. Data must be a
list containing a set of x and y values.
"""
self._data = ((title, data),)
self.queue_draw()
def plot(self):
"""Initializes chart (if needed), set data and plots."""
chart = LineChart(self._surface, self._options)
chart.addDataset(self._data)
chart.render()
<file_sep>/include/FileReader.h
#ifndef FileReader_h
#define FileReader_h
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <sys/stat.h>
#include <iomanip>
#include "FileConstants.h"
#include "Exception.h"
#include "VME_TDCMeasurement.h"
/**
* \brief Handler for a TDC output file readout
* \author <NAME> <<EMAIL>>
* \date Jun 2015
*/
class FileReader
{
public:
inline FileReader() {;}
/**
* \brief Class constructor
* \param[in] name Path to the file to read
* \param[in] ro Data readout mode (continuous storage or trigger matching)
*/
FileReader(std::string name);
~FileReader();
void Open(std::string name);
inline bool IsOpen() const { return fFile.is_open(); }
inline void Clear() { fFile.clear(); fFile.seekg(sizeof(file_header_t), std::ios::beg); }
void Dump() const;
inline unsigned int GetNumTDCs() const { return fHeader.num_hptdc; }
inline unsigned int GetRunId() const { return fHeader.run_id; }
inline unsigned int GetBurstId() const { return fHeader.spill_id; }
inline unsigned int GetAcquisitionMode() const { return fHeader.acq_mode; }
inline unsigned int GetDetectionMode() const { return fHeader.det_mode; }
unsigned long GetNumEvents() const { return fNumEvents; }
bool GetNextEvent(VME::TDCEvent*);
/**
* \brief Fetch the next full measurement on a given channel
* \param[in] channel_id Unique identifier of the channel number to retrieve
* \param[out] m A full measurement with leading, trailing times, ...
* \return A boolean stating the success of retrieval operation
*/
bool GetNextMeasurement(unsigned int channel_id, VME::TDCMeasurement* mc);
private:
std::ifstream fFile;
file_header_t fHeader;
VME::AcquisitionMode fReadoutMode;
time_t fWriteTime;
unsigned long fNumEvents;
};
#endif
<file_sep>/dqm/db.cpp
#include "DQMProcess.h"
#include "OnlineDBHandler.h"
#include "PPSCanvas.h"
#include <fstream>
#include "TGraph.h"
#include "TH1.h"
using namespace std;
bool
DBDQM(vector<string>* outputs)
{
try {
OnlineDBHandler ri;
unsigned int last_run = ri.GetLastRun();
OnlineDBHandler::BurstInfos si = ri.GetRunInfo(last_run);
TGraph* gr_spills = new TGraph;
TH1D* h_dist_time = new TH1D("dist_timew", "", 100, 0., 100.);
unsigned int i = 0;
int last_time_start = -1;
for (OnlineDBHandler::BurstInfos::iterator s=si.begin(); s!=si.end(); s++, i++) {
if (last_time_start>0) {
gr_spills->SetPoint(i, s->burst_id, s->time_start-last_time_start);
h_dist_time->Fill(s->time_start-last_time_start);
}
last_time_start = s->time_start;
}
DQM::PPSCanvas* c_spills = new DQM::PPSCanvas(Form("db_time_btw_write_%d", last_run), "Time between file writings");
c_spills->SetRunInfo(last_run, TDatime().AsString());
c_spills->Grid()->SetGrid(1, 1);
gr_spills->Draw("ap");
gr_spills->GetXaxis()->SetTitle("Burst train");
gr_spills->GetYaxis()->SetTitle("Time to write file (s)");
gr_spills->SetMarkerStyle(20);
gr_spills->SetMarkerSize(.6);
c_spills->Save("png", DQM_OUTPUT_DIR);
outputs->push_back(c_spills->GetName());
DQM::PPSCanvas* c_dst = new DQM::PPSCanvas(Form("db_time_btw_write_dist_%d", last_run), "Time between file writings");
c_dst->SetRunInfo(last_run, TDatime().AsString());
c_dst->Grid()->SetGrid(1, 1);
h_dist_time->Draw();
h_dist_time->GetXaxis()->SetTitle("Time to write file (s)");
h_dist_time->GetYaxis()->SetTitle("Burst trains");
c_dst->Save("png", DQM_OUTPUT_DIR);
outputs->push_back(c_dst->GetName());
/*delete gr_spills; delete c_spills;
delete h_dist_time; delete c_dst;*/
} catch (Exception& e) { e.Dump(); }
return true;
}
int
main(int argc, char* argv[])
{
DQM::DQMProcess dqm(1987, 4);
dqm.Run(DBDQM, DQM::DQMProcess::UpdatedPlot);
return 0;
}
<file_sep>/change_hv_settings.cpp
#include "VMEReader.h"
#include "FileConstants.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <ctime>
#include <signal.h>
using namespace std;
VMEReader* vme;
int gEnd = 0;
void CtrlC(int aSig) {
if (gEnd==0) { cerr << endl << "[C-c] Trying a clean exit!" << endl; vme->Abort(); }
else if (gEnd>=5) { cerr << endl << "[C-c > 5 times] ... Forcing exit!" << endl; exit(0); }
gEnd++;
}
int main(int argc, char *argv[]) {
signal(SIGINT, CtrlC);
try {
bool with_socket = false;
vme = new VMEReader("/dev/usb/v2718_0", VME::CAEN_V2718, with_socket);
try { vme->AddHVModule(0x500000, 0xc); } catch (Exception& e) { e.Dump(); }
NIM::HVModuleN470* hv = vme->GetHVModule();
cout << "module id=" << hv->GetModuleId() << endl;
//hv->ReadMonitoringValues().Dump();
hv->EnableChannel(3);
//hv->SetChannelV0(0, 2400);
//hv->SetChannelI0(0, 500);
//hv->ReadChannelValues(0).Dump();
//hv->ReadChannelValues(3).Dump();
} catch (Exception& e) {
e.Dump();
return -1;
}
return 0;
}
<file_sep>/src/VME_IOModuleV262.cpp
#include "VME_IOModuleV262.h"
namespace VME
{
IOModuleV262::IOModuleV262(int32_t bhandle, uint32_t baseaddr) :
GenericBoard<IOModuleV262Register,cvA24_U_DATA>(bhandle, baseaddr)
{
std::ostringstream os;
os << "New I/O module added:" << "\n\t"
<< " Identifier: 0x" << std::hex << GetIdentifier() << "\n\t"
<< " Serial number: " << std::dec << GetSerialNumber() << "\n\t"
<< " Version: " << std::dec << GetModuleVersion() << "\n\t"
<< " Type: " << std::dec << GetModuleType() << "\n\t"
<< " Manufacturer: 0x" << std::hex << GetManufacturerId();
PrintInfo(os.str());
uint16_t word = 0xff;
try {
WriteRegister(kNIMLevelWrite, word);
} catch (Exception& e) { e.Dump(); }
}
unsigned short
IOModuleV262::GetSerialNumber() const
{
uint16_t word;
try {
ReadRegister(kBoardInfo1, &word);
return static_cast<unsigned short>(word&0xfff);
} catch (Exception& e) { e.Dump(); }
return 0;
}
unsigned short
IOModuleV262::GetModuleVersion() const
{
uint16_t word;
try {
ReadRegister(kBoardInfo1, &word);
return static_cast<unsigned short>((word>>12)&0xf);
} catch (Exception& e) { e.Dump(); }
return 0;
}
unsigned short
IOModuleV262::GetModuleType() const
{
uint16_t word;
try {
ReadRegister(kBoardInfo0, &word);
return static_cast<unsigned short>(word&0x3ff);
} catch (Exception& e) { e.Dump(); }
return 0;
}
unsigned short
IOModuleV262::GetManufacturerId() const
{
uint16_t word;
try {
ReadRegister(kBoardInfo0, &word);
return static_cast<unsigned short>((word>>10)&0x3f);
} catch (Exception& e) { e.Dump(); }
return 0;
}
unsigned short
IOModuleV262::GetIdentifier() const
{
uint16_t word;
try {
ReadRegister(kIdentifier, &word);
return word;
} catch (Exception& e) { e.Dump(); }
return 0;
}
}
<file_sep>/include/VME_IOModuleV262.h
#ifndef VME_IOModuleV262_h
#define VME_IOModuleV262_h
#include "VME_GenericBoard.h"
namespace VME
{
enum IOModuleV262Register {
kECLLevelWrite = 0x04,
kNIMLevelWrite = 0x06,
kNIMPulseWrite = 0x08,
kNIMPulseRead = 0x0a,
kIdentifier = 0xfa,
kBoardInfo0 = 0xfc,
kBoardInfo1 = 0xfe
};
class IOModuleV262 : public GenericBoard<IOModuleV262Register,cvA24_U_DATA>
{
public:
IOModuleV262(int32_t bhandle, uint32_t baseaddr);
inline ~IOModuleV262() {;}
unsigned short GetSerialNumber() const;
unsigned short GetModuleVersion() const;
unsigned short GetModuleType() const;
unsigned short GetManufacturerId() const;
unsigned short GetIdentifier() const;
private:
};
}
#endif
<file_sep>/include/NIM_HVModuleN470.h
#ifndef NIM_HVModuleN470_h
#define NIM_HVModuleN470_h
#include "VME_CAENETControllerV288.h"
#define NUM_CHANNELS 4
namespace NIM
{
enum HVModuleN470Opcodes {
kN470GeneralInfo = 0x00, // R
kN470MonStatus = 0x01, // R
kN470OperationalParams = 0x02, // R
kN470V0Value = 0x03, // W
kN470I0Value = 0x04, // W
kN470V1Value = 0x05, // W
kN470I1Value = 0x06, // W
kN470TripValue = 0x07, // W
kN470RampUpValue = 0x08, // W
kN470RampDownValue = 0x09, // W
kN470ChannelOn = 0x0a, // W
kN470ChannelOff = 0x0b, // W
kN470KillAllChannels = 0x0c, // W
kN470ClearAlarm = 0x0d, // W
kN470EnableFrontPanel = 0x0e, // W
kN470DisableFrontPanel = 0x0f, // W
kN470TTLLevel = 0x10, // W
kN470NIMLevel = 0x11 // W
};
/**
* \brief General monitoring values for the HV power supply
* \author <NAME> <<EMAIL>>
* \date 24 Jul 2015
*/
class HVModuleN470Values
{
public:
inline HVModuleN470Values(std::vector<unsigned short> vals) : fValues(vals) {;}
inline ~HVModuleN470Values() {;}
inline void Dump() const {
std::ostringstream os;
os << "Monitoring values:" << "\n\t"
<< " Vmon = " << Vmon() << " V" << "\n\t"
<< " Imon = " << Imon() << " uA" << "\n\t"
<< " Vmax = " << Vmax() << " V" << "\n\t"
<< " Individual channels status:" << "\n\t";
for (unsigned int i=0; i<NUM_CHANNELS; i++) {
os << "===== Channel " << i << " =====" << "\n\t"
<< GetChannelStatus(i);
if (i<3) os << "\n\t";
}
PrintInfo(os.str());
}
inline unsigned short Vmon() const { return fValues.at(0); }
inline unsigned short Imon() const { return fValues.at(1); }
inline unsigned short Vmax() const { return fValues.at(2); }
class ChannelStatus {
public:
inline ChannelStatus(unsigned short word) : fWord(word) {;}
inline ~ChannelStatus() {;}
inline bool Enabled() const { return (fWord&0x1); }
inline bool OVC() const { return ((fWord>>1)&0x1); }
inline bool OVV() const { return ((fWord>>2)&0x1); }
inline bool UNV() const { return ((fWord>>3)&0x1); }
inline bool Trip() const { return ((fWord>>4)&0x1); }
inline bool RampUp() const { return ((fWord>>5)&0x1); }
inline bool RampDown() const { return ((fWord>>6)&0x1); }
inline bool MaxV() const { return ((fWord>>7)&0x1); }
inline bool Polarity() const { return ((fWord>>8)&0x1); }
inline bool Vsel() const { return ((fWord>>9)&0x1); }
inline bool Isel() const { return ((fWord>>10)&0x1); }
inline bool Kill() const { return ((fWord>>11)&0x1); }
inline bool HVEnabled() const { return ((fWord>>12)&0x1); }
enum SignalStandard { NIM=0x0, TTL=0x1 };
inline SignalStandard Standard() const { return static_cast<SignalStandard>((fWord>>13)&0x1); }
inline bool NonCalibrated() const { return ((fWord>>14)&0x1); }
inline bool Alarm() const { return ((fWord>>15)&0x1); }
inline friend std::ostream& operator<<(std::ostream& os, const ChannelStatus& cs) {
os << "Channel enabled? " << cs.Enabled() << " with polarity " << cs.Polarity() << "\n\t"
<< "OVC=" << cs.OVC() << ", OVV=" << cs.OVV() << ", UNV=" << cs.UNV() << "\n\t"
<< "Trip? " << cs.Trip() << ", Kill? " << cs.Kill() << ", Alarm? " << cs.Alarm() << "\n\t"
<< "Ramp up? " << cs.RampUp() << " / down? " << cs.RampDown() << "\n\t"
<< "MaxV=" << cs.MaxV() << ", Vsel=" << cs.Vsel() << ", Isel=" << cs.Isel() << "\n\t"
<< "HV enabled? " << cs.HVEnabled();
return os;
}
inline void Dump() const {
std::ostringstream os; os << this;
PrintInfo(os.str());
}
private:
unsigned short fWord;
};
inline ChannelStatus GetChannelStatus(unsigned short ch_id) const {
if (ch_id<0 or ch_id>=NUM_CHANNELS) return 0;
return ChannelStatus(fValues.at(3+ch_id));
}
private:
std::vector<unsigned short> fValues;
};
/**
* \brief Single channel monitoring values for the HV power supply
* \author <NAME> <<EMAIL>>
* \date 24 Jul 2015
*/
class HVModuleN470ChannelValues
{
public:
inline HVModuleN470ChannelValues(unsigned short ch_id, std::vector<unsigned short> vals) :
fChannelId(ch_id), fValues(vals) {;}
inline ~HVModuleN470ChannelValues() {;}
inline void Dump() const {
std::ostringstream os;
os << "Individual channel values: channel " << fChannelId << "\n\t"
<< "Vmon/Imon = " << std::setw(4) << Vmon() << " V / " << std::setw(4) << Imon() << " uA\n\t"
<< "V0/I0 = " << std::setw(4) << V0() << " V / " << std::setw(4) << I0() << " uA\n\t"
<< "V1/I1 = " << std::setw(4) << V1() << " V / " << std::setw(4) << I1() << " uA\n\t"
<< "Trip = " << Trip() << "\n\t"
<< "Ramp up/down = " << RampUp() << " / " << RampDown() << "\n\t"
<< "Maximal V = " << MaxV() << " V";
PrintInfo(os.str());
}
inline unsigned short ChannelStatus() const { return fValues.at(0); }
inline unsigned short Vmon() const { return fValues.at(1); }
inline unsigned short Imon() const { return fValues.at(2); }
inline unsigned short V0() const { return fValues.at(3); }
inline unsigned short I0() const { return fValues.at(4); }
inline unsigned short V1() const { return fValues.at(5); }
inline unsigned short I1() const { return fValues.at(6); }
inline unsigned short Trip() const { return fValues.at(7); }
inline unsigned short RampUp() const { return fValues.at(8); }
inline unsigned short RampDown() const { return fValues.at(9); }
inline unsigned short MaxV() const { return fValues.at(10); }
private:
unsigned short fChannelId;
std::vector<unsigned short> fValues;
};
class HVModuleN470
{
public:
HVModuleN470(uint16_t addr, VME::CAENETControllerV288& cont);
inline ~HVModuleN470() {;}
std::string GetModuleId() const;
unsigned short GetFWRevision() const;
HVModuleN470Values ReadMonitoringValues() const;
HVModuleN470ChannelValues ReadChannelValues(unsigned short ch_id) const;
void SetChannelV0(unsigned short ch_id, unsigned short v0) const;
void SetChannelI0(unsigned short ch_id, unsigned short i0) const;
void SetChannelV1(unsigned short ch_id, unsigned short v1) const;
void SetChannelI1(unsigned short ch_id, unsigned short i1) const;
void EnableChannel(unsigned short ch_id) const;
void DisableChannel(unsigned short ch_id) const;
private:
/**
* Read a vector of 16-bit words in the register
* \brief Read in register
* \param[in] addr register
* \param[out] vector of data words
*/
void ReadRegister(const HVModuleN470Opcodes& reg, std::vector<uint16_t>* data, unsigned int num_words=1) const;
/**
* Write a vector of 16-bit words in the register
* \brief Write on register
* \param[in] addr register
* \param[out] data word
*/
void WriteRegister(const HVModuleN470Opcodes& reg, const std::vector<uint16_t>& data) const;
/**
* Write a 16-bit word in the register
* \brief Write on register
* \param[in] addr register
* \param[out] data word
*/
void WriteRegister(const HVModuleN470Opcodes& reg, const uint16_t& data) const;
VME::CAENETControllerV288 fController;
uint16_t fAddress;
};
}
#endif
<file_sep>/include/Socket.h
#ifndef Socket_h
#define Socket_h
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> // internet address family (for sockaddr_in)
#include <arpa/inet.h> // definitions for internet operations
#include <netdb.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <set>
#include <sstream>
#include <iostream>
#include "Exception.h"
#include "SocketMessage.h"
#define SOCKET_ERROR(x) 10000+x
#define MAX_WORD_LENGTH 5000
#define MAX_SOCKET_ATTEMPTS 2
/**
* \defgroup Socket Socket communication objects
*/
/**
* General object providing all useful method to
* connect/bind/send/receive information through system sockets.
* \brief Base socket object from which clients/master from a socket inherit
*
* \author <NAME> <<EMAIL>>
* \date 23 Mar 2015
* \ingroup Socket
*/
class Socket
{
public:
/**
* \brief Type of actor playing a role on the socket
*/
typedef enum { INVALID=-1, MASTER=0, WEBSOCKET_CLIENT, CLIENT, DETECTOR, DQM, DAQ } SocketType;
typedef std::set< std::pair<int,SocketType> > SocketCollection;
public:
inline Socket() {;}
Socket(int port);
virtual ~Socket();
/// Terminates the socket and all attached communications
void Stop();
inline void SetPort(int port) { fPort=port; }
/// Retrieve the port used for this socket
inline int GetPort() const { return fPort; }
/**
* Set the socket to accept connections any client transmitting through the
* socket
* \brief Accept connection from a client
* \param[inout] socket Master/client object to enable on the socket
*/
void AcceptConnections(Socket& socket);
/**
* Register all open file descriptors to read their communication through the
* socket
*/
void SelectConnections();
inline void SetSocketId(int sid) { fSocketId=sid; }
inline int GetSocketId() const { return fSocketId; }
inline SocketType GetSocketType(int sid) const {
// FIXME need to find a more C++-like method...
for (SocketCollection::const_iterator it=fSocketsConnected.begin(); it!=fSocketsConnected.end(); it++) {
if (it->first==sid) return it->second;
}
std::ostringstream o; o << "Client # " << sid << " not found in listeners list";
throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning);
return INVALID;
}
inline bool IsWebSocket(int sid) const { return GetSocketType(sid)==WEBSOCKET_CLIENT; }
void DumpConnected() const;
protected:
/**
* Launch all mandatory operations to set the socket to be used
* \brief Start the socket
* \return Success of the operation
*/
bool Start();
/**
* \brief Bind a name to a socket
* \return Success of the operation
*/
void Bind();
void PrepareConnection();
/**
* Set the socket to listen to any message coming from outside
* \brief Listen to incoming messages
*/
void Listen(int maxconn);
/**
* \brief Send a message on a socket
*/
void SendMessage(Message message, int id=-1) const;
/**
* \brief Receive a message from a socket
* \return Received message as a std::string
*/
Message FetchMessage(int id=-1) const;
private:
/**
* A file descriptor for this socket, if \a Create was performed beforehand.
*/
int fSocketId;
protected:
int fPort;
char fBuffer[MAX_WORD_LENGTH];
SocketCollection fSocketsConnected;
/// Master file descriptor list
fd_set fMaster;
/// Temp file descriptor list for select()
fd_set fReadFds;
private:
/**
* \brief Create an endpoint for communication
*/
void Create();
/**
* \brief Configure the socket object for communication
*/
void Configure();
struct sockaddr_in fAddress;
};
#endif
<file_sep>/src/Socket.cpp
#include "Socket.h"
Socket::Socket(int port) :
fSocketId(-1), fPort(port)
{
memset(fBuffer, 0, MAX_WORD_LENGTH);
memset(&fAddress, 0, sizeof(fAddress));
// Clear the master and temp file descriptor sets
FD_ZERO(&fMaster);
FD_ZERO(&fReadFds);
}
Socket::~Socket()
{}
bool
Socket::Start()
{
try {
Create();
Configure();
} catch (Exception& e) {
e.Dump();
return false;
}
return true;
}
void
Socket::Stop()
{
if (fSocketId==-1) return;
close(fSocketId);
fSocketId = -1;
}
void
Socket::Create()
{
fSocketId = socket(AF_INET, SOCK_STREAM, 0);
if (fSocketId==-1) {
throw Exception(__PRETTY_FUNCTION__, "Cannot create socket!", Fatal, SOCKET_ERROR(errno));
}
}
void
Socket::Configure()
{
const int on = 1/*, off = 0*/;
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
if (setsockopt(fSocketId, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout))!=0
or setsockopt(fSocketId, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout))!=0
or setsockopt(fSocketId, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on))!=0) {
throw Exception(__PRETTY_FUNCTION__, "Cannot modify socket options", Fatal, SOCKET_ERROR(errno));
}
}
void
Socket::Bind()
{
// binding the socket
fAddress.sin_family = AF_INET;
fAddress.sin_addr.s_addr = INADDR_ANY;
fAddress.sin_port = htons(fPort);
int bind_result = bind(fSocketId, (struct sockaddr*)&fAddress, sizeof(fAddress));
if (bind_result==-1) {
Stop();
throw Exception(__PRETTY_FUNCTION__, "Cannot bind socket!", Fatal, SOCKET_ERROR(errno));
}
}
void
Socket::PrepareConnection()
{
fAddress.sin_family = AF_INET;
fAddress.sin_port = htons(fPort);
if (connect(fSocketId, (struct sockaddr*)&fAddress, sizeof(fAddress))!=0) {
Stop();
if (errno==111) { // Connection refused (likely that the server is non-existent)
std::ostringstream os;
os << "Messenger is not reachable through sockets!" << std::endl
<< "\tCheck that it is properly launched on the central" << std::endl
<< "\tmachine!";
throw Exception(__PRETTY_FUNCTION__, os.str(), Fatal, SOCKET_ERROR(errno));
}
throw Exception(__PRETTY_FUNCTION__, "Cannot connect to socket!", Fatal, SOCKET_ERROR(errno));
}
}
void
Socket::AcceptConnections(Socket& socket)
{
// Now we can start accepting connections from clients
socklen_t len = sizeof(fAddress);
socket.SetSocketId(accept(fSocketId, (struct sockaddr*)&fAddress, &len));
std::ostringstream o; o << "New client with # " << socket.GetSocketId();
PrintInfo(o.str());
if (socket.GetSocketId()<0) {
throw Exception(__PRETTY_FUNCTION__, "Cannot accept client!", JustWarning, SOCKET_ERROR(errno));
}
// Add to master set
FD_SET(socket.GetSocketId(), &fMaster);
fSocketsConnected.insert(std::pair<int,SocketType>(socket.GetSocketId(), CLIENT));
}
void
Socket::SelectConnections()
{
if (fSocketsConnected.size()==0) {
throw Exception(__PRETTY_FUNCTION__, "The messenger socket is not registered to the sockets list!", Fatal);
}
int highest = fSocketsConnected.rbegin()->first; // last one in the set
if (select(highest+1, &fReadFds, NULL, NULL, NULL)==-1) {
throw Exception(__PRETTY_FUNCTION__, "Unable to select the connection!", Fatal, SOCKET_ERROR(errno));
}
}
void
Socket::Listen(int maxconn)
{
if (listen(fSocketId, maxconn)!=0) {
Stop();
throw Exception(__PRETTY_FUNCTION__, "Cannot listen on socket!", JustWarning, SOCKET_ERROR(errno));
}
// Add the messenger to the master set
FD_SET(fSocketId, &fMaster);
fSocketsConnected.insert(std::pair<int,SocketType>(fSocketId, MASTER));
}
void
Socket::SendMessage(Message message, int id) const
{
if (id<0) id = fSocketId;
std::string message_s = message.GetString();
usleep(1000);
if (send(id, message_s.c_str(), message_s.size(), MSG_NOSIGNAL)<=0) {
throw Exception(__PRETTY_FUNCTION__, "Cannot send message!", JustWarning, SOCKET_ERROR(errno));
}
}
Message
Socket::FetchMessage(int id) const
{
// At first we prepare the buffer to be filled
char buf[MAX_WORD_LENGTH];
memset(buf, 0, MAX_WORD_LENGTH);
if (id<0) id = fSocketId;
size_t num_bytes = recv(id, buf, MAX_WORD_LENGTH, 0);
if (num_bytes<0) {
throw Exception(__PRETTY_FUNCTION__, "Cannot read answer from receiver!", JustWarning, SOCKET_ERROR(errno));
//...
}
else if (num_bytes==0) {
std::ostringstream o; o << "Socket " << id << " just got disconnected";
throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning, 11000);
}
std::string out(buf);
return Message(out.substr(0, num_bytes));
}
void
Socket::DumpConnected() const
{
std::ostringstream os;
os << " List of sockets connected: ";
for (SocketCollection::const_iterator it=fSocketsConnected.begin(); it!=fSocketsConnected.end(); it++) {
os << " " << it->first;
if (it->second) os << " (web)";
}
PrintInfo(os.str());
}
<file_sep>/include/Messenger.h
#ifndef Messenger_h
#define Messenger_h
#include "Socket.h"
#include "OnlineDBHandler.h"
#include <unistd.h>
#include <sys/wait.h>
/**
* Messenger/broadcaster object used by the server to send/receive commands from
* the clients/listeners.
* \brief Base master object for the socket
*
* \author <NAME> <<EMAIL>>
* \date 23 Mar 2015
* \ingroup Socket
*/
class Messenger : public Socket
{
public:
/// Build a void master object or socket actor
Messenger();
/// Build a master object to control the socket
Messenger(int port);
~Messenger();
/**
* Connect this master to the socket for clients to be able to bind.
* \brief Connect the master to the socket
*/
bool Connect();
/**
* Remove this master from the socket, thus disconnecting automatically the
* clients connected.
* \brief Remove the master and destroy the socket
*/
void Disconnect();
/**
* \brief Send any type of message to any client
* \param[in] m Message to transmit
* \param[in] sid Unique identifier of the client on this socket
*/
void Send(const Message& m, int sid) const;
/**
* \brief Send any type of message to all clients of one type
* \param[in] type Client type
* \param[in] m Message to transmit
*/
inline void SendAll(const Socket::SocketType& type, const Message& m) const {
for (SocketCollection::const_iterator it=fSocketsConnected.begin(); it!=fSocketsConnected.end(); it++) {
if (it->second==type) Send(m, it->first);
}
}
inline void SendAll(const Socket::SocketType& type, const Exception& e) const {
for (SocketCollection::const_iterator it=fSocketsConnected.begin(); it!=fSocketsConnected.end(); it++) {
if (it->second==type) Send(SocketMessage(EXCEPTION, e.OneLine()), it->first);
}
}
/// Handle a message reception from a client
void Receive();
/**
* \brief Emit a message to all clients connected through the socket
* \param[in] m Message to transmit
*/
void Broadcast(const Message& m) const;
/// Start the data acquisition
void StartAcquisition();
void StopAcquisition();
/// Socket actor type retrieval method
inline SocketType GetType() const { return MASTER; }
private:
/**
* Add one client to the list of socket actors to monitor for message
* retrieval/submission.
* \brief Add a client to listen to
*/
void AddClient();
/**
* Ask to a client to disconnect from this socket.
* \brief Disconnect a client
* \param[in] sid Unique identifier of the client to disconnect
* \param[in] key Key to the message to transmit for disconnection
* \param[in] force Do we need to force the client out of this socket ?
*/
void DisconnectClient(int sid, MessageKey key, bool force=false);
void SwitchClientType(int sid, Socket::SocketType type);
/**
* \brief Process a message received from the socket
* \param[in] Unique identifier of the client sending the message
*/
void ProcessMessage(SocketMessage m, int sid);
int fNumAttempts;
pid_t fPID;
int fStdoutPipe[2], fStderrPipe[2];
};
#endif
<file_sep>/dqm/CMakeLists.txt
project(DQM CXX)
# DQM modules needing a ROOT instance
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} /usr/share/root/cmake)
find_package(ROOT)
if (ROOT_FOUND)
include_directories(${ROOT_INCLUDE_DIR})
link_directories(${ROOT_LIBRARY_DIR})
if(${ROOT_VERSION} LESS 6.0)
set(GCC_COMPILE_FLAGS "-Wno-shadow -fPIC")
else()
set(GCC_COMPILE_FLAGS "-Wno-shadow -fPIC -std=c++11")
endif()
add_definitions(${GCC_COMPILE_FLAGS})
endif()
function(ADD_DQM exec)
add_executable(${exec} ${PROJECT_SOURCE_DIR}/${exec}.cpp $<TARGET_OBJECTS:reader_lib> $<TARGET_OBJECTS:src_lib>)
target_link_libraries(${exec} ${ROOT_LIBRARIES} ${ROOT_COMPONENT_LIBRARIES})
#set_property(TARGET ${exec} PROPERTY EXCLUDE_FROM_ALL true)
set_property(TARGET ${exec} PROPERTY LINK_FLAGS "-lsqlite3")
endfunction()
if (ROOT_FOUND)
add_dqm(gastof)
add_dqm(quartic)
add_dqm(daq)
add_dqm(db)
endif()
<file_sep>/src/Messenger.cpp
#include "Messenger.h"
Messenger::Messenger() :
Socket(-1), fNumAttempts(0), fPID(-1)
{}
Messenger::Messenger(int port) :
Socket(port), fNumAttempts(0), fPID(-1)
{
std::cout << __PRETTY_FUNCTION__ << " new Messenger at port " << GetPort() << std::endl;
}
Messenger::~Messenger()
{
Disconnect();
}
bool
Messenger::Connect()
{
try {
Start();
Bind();
Listen(50);
} catch (Exception& e) {
e.Dump();
return false;
}
return true;
}
void
Messenger::Disconnect()
{
if (fPort<0) return; // do not broadcast the death of a secondary messenger!
try {
Broadcast(SocketMessage(MASTER_DISCONNECT, ""));
} catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Failed to broadcast the server disconnection status!", JustWarning, SOCKET_ERROR(errno));
}
Stop();
}
void
Messenger::AddClient()
{
Socket s;
try {
AcceptConnections(s);
Message message = FetchMessage(s.GetSocketId());
SocketMessage m(message);
if (m.GetKey()==ADD_CLIENT) {
SocketType type = static_cast<SocketType>(m.GetIntValue());
if (type!=CLIENT) SwitchClientType(s.GetSocketId(), type);
}
// Send the client's unique identifier
Send(SocketMessage(SET_CLIENT_ID, s.GetSocketId()), s.GetSocketId());
} catch (Exception& e) {
e.Dump();
}
}
void
Messenger::DisconnectClient(int sid, MessageKey key, bool force)
{
SocketType type;
try { type = GetSocketType(sid); } catch (Exception& e) {
e.Dump();
return;
}
std::ostringstream o; o << "Disconnecting client # " << sid;
PrintInfo(o.str());
Socket s;
s.SetSocketId(sid);
s.Stop();
fSocketsConnected.erase(std::pair<int,SocketType>(sid, type));
FD_CLR(sid, &fMaster);
}
void
Messenger::SwitchClientType(int sid, SocketType type)
{
try {
fSocketsConnected.erase (std::pair<int,SocketType>(sid, GetSocketType(sid)));
fSocketsConnected.insert(std::pair<int,SocketType>(sid, type));
} catch (Exception& e) { e.Dump(); }
}
void
Messenger::Send(const Message& m, int sid) const
{
try {
SendMessage(m, sid);
} catch (Exception& e) { e.Dump(); }
}
void
Messenger::Receive()
{
Message msg;
SocketMessage m;
// We start by copying the master file descriptors list to the
// temporary list for readout
fReadFds = fMaster;
try { SelectConnections(); } catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Impossible to select the connections!", Fatal);
}
// Looking for something to read!
for (SocketCollection::const_iterator s=fSocketsConnected.begin(); s!=fSocketsConnected.end(); s++) {
if (!FD_ISSET(s->first, &fReadFds)) continue;
// First check if we need to handle new connections
if (s->first==GetSocketId()) { AddClient(); return; }
// Handle data from a client
try { msg = FetchMessage(s->first); } catch (Exception& e) {
//std::cout << "exception found..." << e.OneLine() << ", "<< e.ErrorNumber() << std::endl;
e.Dump();
if (e.ErrorNumber()==11000) { DisconnectClient(s->first, THIS_CLIENT_DELETED); return; }
}
m = SocketMessage(msg.GetString());
// Message was successfully decoded
fNumAttempts = 0;
try { ProcessMessage(m, s->first); } catch (Exception& e) {
if (e.ErrorNumber()==11001) break;
}
}
}
void
Messenger::ProcessMessage(SocketMessage m, int sid)
{
if (m.GetKey()==REMOVE_CLIENT) {
if (m.GetIntValue()==GetSocketId()) {
std::ostringstream o;
o << "Some client (id=" << sid << ") asked for this master's disconnection!"
<< "\n\tIgnoring this request...";
throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning);
return;
}
const MessageKey key = (sid==m.GetIntValue()) ? THIS_CLIENT_DELETED : OTHER_CLIENT_DELETED;
DisconnectClient(m.GetIntValue(), key);
throw Exception(__PRETTY_FUNCTION__, "Removing socket client", Info, 11001);
}
else if (m.GetKey()==PING_CLIENT) {
const int toping = m.GetIntValue();
Send(SocketMessage(PING_CLIENT), toping);
SocketMessage msg; int i=0;
do { msg = FetchMessage(toping); i++; } while (msg.GetKey()!=PING_ANSWER && i<MAX_SOCKET_ATTEMPTS);
try { Send(SocketMessage(PING_ANSWER, msg.GetValue()), sid); } catch (Exception& e) { e.Dump(); }
}
else if (m.GetKey()==GET_CLIENTS) {
int i = 0; std::ostringstream os;
for (SocketCollection::const_iterator it=fSocketsConnected.begin(); it!=fSocketsConnected.end(); it++, i++) {
if (i!=0) os << ";";
os << it->first << " (type " << static_cast<int>(it->second) << ")";
}
try { Send(SocketMessage(CLIENTS_LIST, os.str()), sid); } catch (Exception& e) { e.Dump(); }
}
else if (m.GetKey()==WEB_GET_CLIENTS) {
int i = 0; SocketType type; std::ostringstream os;
for (SocketCollection::const_iterator it=fSocketsConnected.begin(); it!=fSocketsConnected.end(); it++, i++) {
type = (it->first==GetSocketId()) ? MASTER : it->second;
if (i!=0) os << ";";
os << it->first << ",";
if (it->first==GetSocketId()) os << "Master,";
else os << "Client" << it->first << ",";
os << static_cast<int>(type) << "\0";
}
try { Send(SocketMessage(CLIENTS_LIST, os.str()), sid); } catch (Exception& e) { e.Dump(); }
}
else if (m.GetKey()==START_ACQUISITION) {
try { StartAcquisition(); } catch (Exception& e) {
e.Dump();
SendAll(DAQ, e);
}
}
else if (m.GetKey()==STOP_ACQUISITION) {
try { StopAcquisition(); } catch (Exception& e) {
e.Dump();
SendAll(DAQ, e);
}
}
else if (m.GetKey()==NEW_RUN) {
try {
OnlineDBHandler().NewRun();
int last_run = OnlineDBHandler().GetLastRun();
SendAll(DQM, SocketMessage(RUN_NUMBER, last_run)); SendAll(DAQ, SocketMessage(RUN_NUMBER, last_run));
} catch (Exception& e) {
e.Dump();
}
}
else if (m.GetKey()==GET_RUN_NUMBER) {
int last_run = 0;
try { last_run = OnlineDBHandler().GetLastRun(); } catch (Exception& e) { last_run = -1; }
try { Send(SocketMessage(RUN_NUMBER, last_run), sid); } catch (Exception& e) { e.Dump(); }
}
else if (m.GetKey()==SET_NEW_FILENAME) {
try {
std::cout << "---> " << m.GetValue() << std::endl;
SendAll(DQM, SocketMessage(NEW_FILENAME, m.GetValue().c_str()));
} catch (Exception& e) { e.Dump(); }
}
else if (m.GetKey()==NUM_TRIGGERS or m.GetKey()==HV_STATUS) {
try {
SendAll(DAQ, m);
} catch (Exception& e) { e.Dump(); }
}
else if (m.GetKey()==NEW_DQM_PLOT or m.GetKey()==UPDATED_DQM_PLOT) {
try {
SendAll(DAQ, m);
} catch (Exception& e) { e.Dump(); }
}
else if (m.GetKey()==EXCEPTION) {
try {
SendAll(DAQ, m);
std::cout << "--> " << m.GetValue() << std::endl;
} catch (Exception& e) { e.Dump(); }
}
/*else {
try { Send(SocketMessage(INVALID_KEY), sid); } catch (Exception& e) { e.Dump(); }
std::ostringstream o;
o << "Received an invalid message: " << m.GetString();
throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning);
}*/
}
void
Messenger::Broadcast(const Message& m) const
{
try {
for (SocketCollection::const_iterator sid=fSocketsConnected.begin(); sid!=fSocketsConnected.end(); sid++) {
if (sid->first==GetSocketId()) continue;
Send(m, sid->first);
}
} catch (Exception& e) {
e.Dump();
}
}
void
Messenger::StartAcquisition()
{
fPID = fork();
std::ostringstream os; int ret;
try {
switch (fPID) {
case -1:
throw Exception(__PRETTY_FUNCTION__, "Failed to fork the current process!", JustWarning);
case 0:
PrintInfo("Launching the daughter acquisition process");
ret = execl("ppsFetch", "", (char*)NULL);
os.str("");
os << "Failed to launch the daughter process!" << "\n\t"
<< "Return value: " << ret << "\n\t"
<< "Errno: " << errno;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
default:
break;
}
SendAll(DAQ, SocketMessage(ACQUISITION_STARTED));
// Send the run number to DQMonitors
int last_run = -1;
try { last_run = OnlineDBHandler().GetLastRun(); } catch (Exception& e) { last_run = -1; }
try { SendAll(DQM, SocketMessage(RUN_NUMBER, last_run)); } catch (Exception& e) { e.Dump(); }
throw Exception(__PRETTY_FUNCTION__, "Acquisition started!", Info, 30000);
} catch (Exception& e) { e.Dump(); }
}
void
Messenger::StopAcquisition()
{
signal(SIGCHLD, SIG_IGN);
int ret = kill(fPID, SIGINT);
if (ret<0) {
std::ostringstream os;
os << "Failed to kill the acquisition process with pid=" << fPID << "\n\t"
<< "Return value: " << ret << " (errno=" << errno << ")";
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}
SendAll(DAQ, SocketMessage(ACQUISITION_STOPPED));
throw Exception(__PRETTY_FUNCTION__, "Acquisition stop signal sent!", Info, 30001);
}
<file_sep>/src/Client.cpp
#include "Client.h"
Client::Client(int port) :
Socket(port), fClientId(-1), fIsConnected(false)
{}
Client::~Client()
{
if (fIsConnected) Disconnect();
}
bool
Client::Connect(const SocketType& type)
{
fType = type;
try {
Start();
PrepareConnection();
Announce();
} catch (Exception& e) {
e.Dump();
return false;
}
fIsConnected = true;
return true;
}
void
Client::Announce()
{
try {
// Once connected we send our request for connection
SendMessage(SocketMessage(ADD_CLIENT, static_cast<int>(GetType())));
// Then we wait for to the server to send us a connection acknowledgement
// + an id
SocketMessage ack(FetchMessage());
switch (ack.GetKey()) {
case SET_CLIENT_ID:
fClientId = ack.GetIntValue();
break;
case INVALID_KEY:
default:
throw Exception(__PRETTY_FUNCTION__, "Received an invalid answer from server", JustWarning);
}
} catch (Exception& e) {
e.Dump();
}
std::cout << __PRETTY_FUNCTION__ << " connected to socket at port " << GetPort() << ", received id \"" << fClientId << "\""<< std::endl;
}
void
Client::Disconnect()
{
std::cout << "===> Disconnecting the client from socket" << std::endl;
if (!fIsConnected) return;
try {
SendMessage(SocketMessage(REMOVE_CLIENT, fClientId), -1);
} catch (Exception& e) {
e.Dump();
}
try {
SocketMessage ack(FetchMessage());
if (ack.GetKey()==THIS_CLIENT_DELETED or ack.GetKey()==OTHER_CLIENT_DELETED) {
fIsConnected = false;
}
} catch (Exception& e) {
if (e.ErrorNumber()!=11000) // client has been disconnected
e.Dump();
else return;
}
}
void
Client::Receive()
{
SocketMessage msg;
try {
msg = FetchMessage();
} catch (Exception& e) {
if (e.ErrorNumber()==11000) // client has been disconnected
throw Exception(__PRETTY_FUNCTION__, "Some other socket asked for this client's disconnection. Obtemperating...", Fatal);
}
if (msg.GetKey()==MASTER_DISCONNECT) {
throw Exception(__PRETTY_FUNCTION__, "Master disconnected!", Fatal);
}
else if (msg.GetKey()==OTHER_CLIENT_DELETED) {
throw Exception(__PRETTY_FUNCTION__, "Some other socket asked for this client's disconnection. Obtemperating...", Fatal);
}
else if (msg.GetKey()==GET_CLIENT_TYPE) {
Send(SocketMessage(CLIENT_TYPE, static_cast<int>(GetType())));
}
else if (msg.GetKey()==PING_CLIENT) {
std::ostringstream os; os << "Pong. My name is " << GetSocketId() << " and I feel fine, thank you!";
Send(SocketMessage(PING_ANSWER, os.str()));
PrintInfo("Got a ping, answering...");
}
else if (msg.GetKey()==CLIENTS_LIST) {
VectorValue vals = msg.GetVectorValue();
int i = 0; std::ostringstream o; o << "List of members on the socket:\n\t";
for (VectorValue::const_iterator v=vals.begin(); v!=vals.end(); v++, i++) {
if (i!=0) o << ", ";
o << *v;
}
PrintInfo(o.str());
}
else {
ParseMessage(msg);
}
}
SocketMessage
Client::Receive(const MessageKey& key)
{
SocketMessage msg;
try {
msg = FetchMessage();
if (msg.GetKey()==key) { return msg; }
} catch (Exception& e) {
if (e.ErrorNumber()==11000) // client has been disconnected
throw Exception(__PRETTY_FUNCTION__, "Some other socket asked for this client's disconnection. Obtemperating...", Fatal);
e.Dump();
}
return msg;
}
<file_sep>/test/write_tree.cpp
#include "FileReader.h"
#include <iostream>
#include <fstream>
#include <vector>
#include "TFile.h"
#include "TTree.h"
#define MAX_MEAS 10000
using namespace std;
int main(int argc, char* argv[]) {
if (argc<2) {
cerr << "Usage: " << argv[0] << " <input raw file> [output root file]" << endl;
return -1;
}
string output = "output.root";
if (argc>2) output = argv[2];
unsigned int fNumMeasurements, fNumErrors;
unsigned int fRunId, fBurstId;
unsigned long fETTT;
// JH - testing
unsigned int fEventID;
unsigned int fChannelId[MAX_MEAS];
double fLeadingEdge[MAX_MEAS], fTrailingEdge[MAX_MEAS], fToT[MAX_MEAS];
TFile* f = new TFile(output.c_str(), "recreate");
TTree* t = new TTree("tdc", "List of TDC measurements");
t->Branch("num_measurements", &fNumMeasurements, "num_measurements/i");
t->Branch("num_errors", &fNumErrors, "num_errors/i");
t->Branch("run_id", &fRunId, "run_id/i");
t->Branch("channel_id", fChannelId, "channel_id[num_measurements]/I");
//t->Branch("burst_id", &fBurstId, "burst_id/i"); // need to be clever for this...
t->Branch("ettt", &fETTT, "ettt/l");
t->Branch("leading_edge", fLeadingEdge, "leading_edge[num_measurements]/D");
t->Branch("trailing_edge", fTrailingEdge, "trailing_edge[num_measurements]/D");
t->Branch("tot", fToT, "tot[num_measurements]/D");
// JH - testing
t->Branch("event_id",&fEventID, "event_id/I");
fNumMeasurements = fNumErrors = fRunId = fBurstId = 0;
for (unsigned int i=0; i<MAX_MEAS; i++) {
fLeadingEdge[i] = fTrailingEdge[i] = fToT[i] = 0.;
fChannelId[i] = -1;
}
VME::TDCMeasurement m;
try {
FileReader fr(argv[1]);
fRunId = fr.GetRunId();
cout << "Opening file with burst train " << fr.GetBurstId() << endl;
for (unsigned int ch=0; ch<32; ch++) {
while (true) {
if (!fr.GetNextMeasurement(ch, &m))
break;
fNumMeasurements = m.NumEvents();
fNumErrors = m.NumErrors();
// JH - testing
fEventID = m.GetEventId();
fETTT = m.GetETTT();
for (unsigned int i=0; i<m.NumEvents(); i++) {
fLeadingEdge[i] = m.GetLeadingTime(i)*25./1024.;
fChannelId[i] = ch;
fTrailingEdge[i] = m.GetTrailingTime(i)*25./1024.;
fToT[i] = m.GetToT(i)*25./1024.;
}
t->Fill();
}
fr.Clear();
}
} catch (Exception& e) {
e.Dump();
}
f->Write();
return 0;
}
<file_sep>/src/VME_BridgeVx718.cpp
#include "VME_BridgeVx718.h"
namespace VME
{
BridgeVx718::BridgeVx718(const char* device, BridgeType type) :
GenericBoard<CVRegisters,cvA32_U_DATA>(0, 0x0)
{
int dev = atoi(device);
CVBoardTypes tp;
CVErrorCodes ret;
std::ostringstream o;
/*char rel[20];
CAENVME_SWRelease(rel);
o.str("");
o << "Initializing the VME bridge\n\t"
<< "CAEN library release: " << rel;
PrintInfo(o.str());*/
switch (type) {
case CAEN_V1718: tp = cvV1718; break;
case CAEN_V2718:
tp = cvV2718;
try { CheckPCIInterface(device); } catch (Exception& e) {
e.Dump();
throw Exception(__PRETTY_FUNCTION__, "Failed to initialize the PCI/VME interface card!", Fatal);
}
break;
default:
o.str("");
o << "Invalid VME bridge type: " << type;
throw Exception(__PRETTY_FUNCTION__, o.str(), Fatal);
}
ret = CAENVME_Init(tp, 0x0, dev, &fHandle);
if (ret!=cvSuccess) {
o.str("");
o << "Error opening the VME bridge!\n\t"
<< "CAEN error: " << CAENVME_DecodeError(ret);
throw Exception(__PRETTY_FUNCTION__, o.str(), Fatal, CAEN_ERROR(ret));
}
char board_rel[100];
ret = CAENVME_BoardFWRelease(fHandle, board_rel);
if (ret!=cvSuccess) {
o.str("");
o << "Failed to retrieve the board FW release!\n\t"
<< "CAEN error: " << CAENVME_DecodeError(ret);
throw Exception(__PRETTY_FUNCTION__, o.str(), Fatal, CAEN_ERROR(ret));
}
o.str("");
o << "Bridge firmware version: " << board_rel;
PrintInfo(o.str());
CheckConfiguration();
//SetIRQ(IRQ1|IRQ2|IRQ3|IRQ4|IRQ5|IRQ6|IRQ7, false);
}
BridgeVx718::~BridgeVx718()
{
CAENVME_End(fHandle);
}
void
BridgeVx718::CheckPCIInterface(const char* device) const
{
try {
PCIInterfaceA2818 pci(device);
std::ostringstream os;
os << "PCI/VME interface card information:" << "\n\t"
<< " FW version: " << pci.GetFWRevision();
PrintInfo(os.str());
} catch (Exception& e) {
throw e;
}
}
void
BridgeVx718::CheckConfiguration() const
{
CVErrorCodes ret;
CVDisplay config;
std::ostringstream o;
ret = CAENVME_ReadDisplay(fHandle, &config);
if (ret!=cvSuccess) {
std::ostringstream os;
os << "Failed to retrieve configuration displayed on\n\t"
<< "module's front panel\n\t"
<< "CAEN error: " << CAENVME_DecodeError(ret);
throw Exception(__PRETTY_FUNCTION__, os.str(), Fatal, CAEN_ERROR(ret));
}
}
void
BridgeVx718::Reset() const
{
CVErrorCodes out = CAENVME_SystemReset(fHandle);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to request status register" << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(out));
}
PrintInfo("Resetting the bridge module!");
}
BridgeVx718Status
BridgeVx718::GetStatus() const
{
uint32_t data;
CVErrorCodes out = CAENVME_ReadRegister(fHandle, cvStatusReg, &data);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to request status register" << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(out));
}
return BridgeVx718Status(data);
}
void
BridgeVx718::SetIRQ(unsigned int irq, bool enable)
{
CVErrorCodes out;
unsigned long word = static_cast<unsigned long>(irq);
if (enable) out = CAENVME_IRQEnable (fHandle, word);
else out = CAENVME_IRQDisable(fHandle, word);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to set IRQ enable status to " << enable << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(out));
}
fHasIRQ = enable;
}
void
BridgeVx718::WaitIRQ(unsigned int irq, unsigned long timeout) const
{
uint8_t word = static_cast<uint8_t>(irq);
CVErrorCodes out = CAENVME_IRQWait(fHandle, word, timeout);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to request IRQ" << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(out));
}
}
unsigned int
BridgeVx718::GetIRQStatus() const
{
uint8_t mask;
CVErrorCodes out = CAENVME_IRQCheck(fHandle, &mask);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to retrieve IRQ status" << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(out));
}
return static_cast<unsigned int>(mask);
}
// output := cvOutput[0,4]
void
BridgeVx718::OutputConf(CVOutputSelect output) const
{
CVErrorCodes out = CAENVME_SetOutputConf(fHandle, output, cvDirect, cvActiveHigh, cvManualSW);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to configure output register #" << static_cast<int>(output) << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(out));
}
}
// output := cvOutput[0,4]
void
BridgeVx718::OutputOn(unsigned short output) const
{
CVErrorCodes out = CAENVME_SetOutputRegister(fHandle, output);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to enable output register #" << static_cast<int>(output) << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(out));
}
}
void
BridgeVx718::OutputOff(unsigned short output) const
{
CVErrorCodes out = CAENVME_ClearOutputRegister(fHandle, output);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to disable output register #" << static_cast<int>(output) << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(out));
}
}
// input := cvInput[0,1]
void
BridgeVx718::InputConf(CVInputSelect input) const
{
CVErrorCodes out = CAENVME_SetInputConf(fHandle, input, cvDirect, cvActiveHigh);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to configure input register #" << static_cast<int>(input) << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(out));
}
}
void
BridgeVx718::InputRead(CVInputSelect input) const
{
unsigned int data;
CVErrorCodes out = CAENVME_ReadRegister(fHandle, cvInputReg, &data);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to read data input register #" << static_cast<int>(input) << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(out));
}
// decoding with CVInputRegisterBits
std::cout << "Input line 0 status: " << ((data&cvIn0Bit) >> 0) << std::endl;
std::cout << "Input line 1 status: " << ((data&cvIn1Bit) >> 1) << std::endl;
}
void
BridgeVx718::StartPulser(double period, double width, unsigned int num_pulses) const
{
unsigned char per, wid, np;
CVTimeUnits unit;
CVErrorCodes out;
CVPulserSelect pulser = cvPulserA;
CVIOSources start = cvManualSW, stop = cvManualSW;
try {
//OutputConf(cvOutput0);
/*OutputConf(cvOutput1);
OutputConf(cvOutput2);
OutputConf(cvOutput3);*/
} catch (Exception& e) {
e.Dump();
}
// in us!
if (width<0xFF*25.e-3) { // 6.375 us
unit = cvUnit25ns;
wid = static_cast<unsigned char>(width*1000/25);
per = static_cast<unsigned char>(period*1000/25);
}
else if (width<0xFF*1.6) { // 408 us
unit = cvUnit1600ns;
wid = static_cast<unsigned char>(width*1000/1600);
per = static_cast<unsigned char>(period*1000/1600);
}
else if (width<0xFF*410.) { // 104.55 ms
unit = cvUnit410us;
wid = static_cast<unsigned char>(width/410);
per = static_cast<unsigned char>(period/410);
}
else if (width<0xFF*104.e3) { // 26.52 s
unit = cvUnit104ms;
wid = static_cast<unsigned char>(width/104e3);
per = static_cast<unsigned char>(period/104e3);
}
else throw Exception(__PRETTY_FUNCTION__, "Unsupported pulser width!", JustWarning);
np = static_cast<unsigned char>(num_pulses&0xFF);
std::cout << width << " / " << period << " --> " << static_cast<unsigned short>(wid&0xFF) << " / " << static_cast<unsigned short>(per&0xFF) << std::endl;
out = CAENVME_SetPulserConf(fHandle, pulser, per, wid, unit, np, start, stop);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to configure the pulser" << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(out));
}
out = CAENVME_GetPulserConf(fHandle, pulser, &per, &wid, &unit, &np, &start, &stop);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to retrieve the pulser configuration" << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(out));
}
std::ostringstream os;
os << "Starting a pulser with:" << "\n\t"
<< " Pulse width: " << width << " us" << "\n\t"
<< " Period: " << period << " us" << "\n\t"
<< " Number of pulses: " << num_pulses << " (0 means infty)" << "\n\t"
<< " Debug: " << static_cast<unsigned short>(per) << " / "
<< static_cast<unsigned short>(wid) << " / "
<< static_cast<unsigned short>(np) << " / ("
<< static_cast<unsigned short>(unit) << " / "
<< static_cast<unsigned short>(start) << " / "
<< static_cast<unsigned short>(stop) << ")";
PrintInfo(os.str());
/*out = CAENVME_StartPulser(fHandle, pulser);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to start the pulser" << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
}*/
}
void
BridgeVx718::StopPulser() const
{
CVPulserSelect pulser = cvPulserA;
CVErrorCodes out =CAENVME_StopPulser(fHandle, pulser);
if (out!=cvSuccess) {
std::ostringstream os;
os << "Failed to stop the pulser" << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, CAEN_ERROR(out));
}
}
void
BridgeVx718::SinglePulse(unsigned short channel) const
{
unsigned short mask = 0x0;
CVErrorCodes out;
switch (channel) {
case 0: mask |= cvOut0Bit; break;
case 1: mask |= cvOut1Bit; break;
case 2: mask |= cvOut2Bit; break;
case 3: mask |= cvOut3Bit; break;
case 4: mask |= cvOut4Bit; break;
default: throw Exception(__PRETTY_FUNCTION__, "Trying to pulse on an undefined channel", JustWarning);
}
OutputConf(static_cast<CVOutputSelect>(channel));
out = CAENVME_PulseOutputRegister(fHandle, mask);
if (out!=cvSuccess) {
std::ostringstream o;
o << "Impossible to single-pulse output channel " << channel << "\n\t"
<< "CAEN error: " << CAENVME_DecodeError(out);
throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning, CAEN_ERROR(out));
}
}
void
BridgeVx718::TestOutputs() const
{
/*bool on = false;
OutputConf(cvOutput0); OutputConf(cvOutput1); OutputConf(cvOutput2); OutputConf(cvOutput3);
while (true) {
if (!on) {
OutputOn(cvOut0Bit|cvOut1Bit|cvOut2Bit|cvOut3Bit);
on = true;
sleep(1);
}
else {
OutputOff(cvOut0Bit|cvOut1Bit|cvOut2Bit|cvOut3Bit);
on = false;
sleep(1);
}
}*/
while (true) {
SinglePulse(0); sleep(1);
}
}
}
<file_sep>/src/FileReader.cpp
#include "FileReader.h"
FileReader::FileReader(std::string file)
{
Open(file);
}
FileReader::~FileReader()
{
if (fFile.is_open()) fFile.close();
}
void
FileReader::Open(std::string file)
{
fFile.open(file.c_str(), std::ios::in|std::ios::binary);
if (!fFile.is_open()) {
std::stringstream s;
s << "Error while trying to open the file \""
<< file << "\" for reading!";
throw Exception(__PRETTY_FUNCTION__, s.str(), JustWarning, 40000);
}
struct stat st;
// Retrieve the file size
if (stat(file.c_str(), &st) == -1) {
std::stringstream s;
s << "Error retrieving size of \"" << file << "\"!";
fFile.close();
throw Exception(__PRETTY_FUNCTION__, s.str(), JustWarning, 40001);
}
if (!fFile.good()) {
fFile.close();
throw Exception(__PRETTY_FUNCTION__, "Can not read file header!", JustWarning, 40002);
}
fFile.read((char*)&fHeader, sizeof(file_header_t));
fNumEvents = (st.st_size-sizeof(file_header_t))/sizeof(uint32_t);
if (fHeader.magic!=0x30535050) {
fFile.close();
throw Exception(__PRETTY_FUNCTION__, "Wrong magic number!", JustWarning, 40003);
}
fWriteTime = st.st_mtime;
fReadoutMode = fHeader.acq_mode;
}
void
FileReader::Dump() const
{
std::stringstream s;
char buff[80];
strftime(buff, 80, "%c", localtime(&fWriteTime));
s << "File written on: " << buff << "\n\t"
<< "Run number: " << fHeader.run_id << "\n\t"
<< "Readout mode: " << fHeader.acq_mode << "\n\t"
<< "Number of events: " << fNumEvents;
PrintInfo(s.str());
}
bool
FileReader::GetNextEvent(VME::TDCEvent* ev)
{
uint32_t buffer;
fFile.read((char*)&buffer, sizeof(uint32_t));
ev->SetWord(buffer);
#ifdef DEBUG
std::cerr << "Event type: " << ev->GetType();
if (ev->GetType()==VME::TDCEvent::TDCMeasurement)
std::cerr << " channel " << std::setw(2) << ev->GetChannelId() << " trail? " << ev->IsTrailing();
std::cerr << std::endl;
#endif
if (fFile.eof()) return false;
return true;
}
bool
FileReader::GetNextMeasurement(unsigned int channel_id, VME::TDCMeasurement* mc)
{
VME::TDCEvent ev;
std::vector<VME::TDCEvent> ec;
/*do { GetNextEvent(&ev);
std::cout << ev.GetChannelId() << " type: " << ev.GetType() << std::endl;
} while (ev.GetType()!=VME::TDCEvent::TDCHeader);*/
/*do {
GetNextEvent(&ev);
if (ev.GetChannelId()!=channel_id) continue;
ec.push_back(ev);
std::cout << ev.GetType() << std::endl;
} while (ev.GetType()!=VME::TDCEvent::TDCHeader);*/
if (fReadoutMode==VME::CONT_STORAGE) {
bool has_lead = false, has_trail = false, has_error = false;
while (true) {
if (!GetNextEvent(&ev)) return false;
if (ev.GetChannelId()!=channel_id) { continue; }
ec.push_back(ev);
switch (ev.GetType()) {
case VME::TDCEvent::TDCHeader:
case VME::TDCEvent::TDCTrailer:
//std::cerr << "Event Id=" << ev.GetEventId() << std::endl;
break;
case VME::TDCEvent::TDCMeasurement:
//std::cerr << "Leading measurement? " << (!ev.IsTrailing()) << std::endl;
if (ev.IsTrailing()) has_trail = true;
else has_lead = true;
break;
case VME::TDCEvent::GlobalHeader:
case VME::TDCEvent::GlobalTrailer:
case VME::TDCEvent::ETTT:
break;
case VME::TDCEvent::TDCError:
has_error = true;
//std::cerr << " ---> Error flags: " << ev.GetErrorFlags() << std::endl;
break;
case VME::TDCEvent::Filler:
case VME::TDCEvent::Trigger:
break;
}
if (has_lead and has_trail) break;
if (ev.GetType()==VME::TDCEvent::Trigger) break;
}
if (has_error) throw Exception(__PRETTY_FUNCTION__, "Measurement has at least one error word.", JustWarning, 41000);
}
else if (fReadoutMode==VME::TRIG_MATCH) {
bool has_error = false;
while (true) {
if (!GetNextEvent(&ev)) return false;
//ev.Dump();
/*std::cout << "0x" << std::hex << ev.GetType();
if (ev.GetType()==VME::TDCEvent::TDCMeasurement) {
std::cout << "\t" << ev.IsTrailing() << "\t" << ev.GetChannelId();
}
std::cout << std::endl;*/
if (ev.GetType()==VME::TDCEvent::TDCMeasurement) {
if (ev.GetChannelId()!=channel_id) continue;
}
else if (ev.GetType()==VME::TDCEvent::TDCError) {
has_error = true;
}
ec.push_back(ev);
if (ev.GetType()==VME::TDCEvent::GlobalTrailer) break;
}
//if (has_error) throw Exception(__PRETTY_FUNCTION__, "Measurement has at least one error word.", JustWarning, 41000);
}
else {
std::ostringstream os;
os << "Unrecognized readout/acquisition mode: " << fReadoutMode;
throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning, 40004);
}
try { mc->SetEventsCollection(ec); } catch (Exception& e) { e.Dump(); }
return true;
}
<file_sep>/include/SocketMessage.h
#ifndef SocketMessage_h
#define SocketMessage_h
#include <utility>
#include <map>
#include <string>
#include "Message.h"
#include <iostream>
typedef std::pair<MessageKey, std::string> MessageMap;
typedef std::vector<std::string> VectorValue;
/**
* \brief Socket-passed message type
* \author <NAME> <<EMAIL>>
* \date 26 Mar 2015
* \ingroup Socket
*/
class SocketMessage : public Message
{
public:
inline SocketMessage() : Message("") {;}
inline SocketMessage(const Message& msg) : Message(msg) {
try { fMessage = Object(); } catch (Exception& e) { return; }
}
inline SocketMessage(const char* msg_s) : Message(msg_s) {
try { fMessage = Object(); } catch (Exception& e) { return; }
}
inline SocketMessage(std::string msg_s) : Message(msg_s) {
try { fMessage = Object(); } catch (Exception& e) { return; }
}
/// Construct a socket message out of a key
inline SocketMessage(const MessageKey& key) : Message() { SetKeyValue(key, ""); }
/// Construct a socket message out of a key and a string-type value
inline SocketMessage(const MessageKey& key, const char* value) : Message() { SetKeyValue(key, value); }
/// Construct a socket message out of a key and a string-type value
inline SocketMessage(const MessageKey& key, std::string value) : Message() { SetKeyValue(key, value.c_str()); }
/// Construct a socket message out of a key and a short integer-type value
inline SocketMessage(const MessageKey& key, const short value) : Message() { SetKeyValue(key, value); }
/// Construct a socket message out of a key and an integer-type value
inline SocketMessage(const MessageKey& key, const int value) : Message() { SetKeyValue(key, value); }
/// Construct a socket message out of a key and a long integer-type value
inline SocketMessage(const MessageKey& key, const long value) : Message() { SetKeyValue(key, value); }
/// Construct a socket message out of a key and a float-type value
inline SocketMessage(const MessageKey& key, const float value) : Message() { SetKeyValue(key, value); }
/// Construct a socket message out of a key and a double precision-type value
inline SocketMessage(const MessageKey& key, const double value) : Message() { SetKeyValue(key, value); }
/// Construct a socket message out of a map of key/string-type value
inline SocketMessage(MessageMap msg_m) : Message() { fMessage = msg_m; }
inline ~SocketMessage() {;}
/// String-valued message
inline void SetKeyValue(const MessageKey& key, const char* value) {
fMessage = make_pair(key, std::string(value));
fString = String();
}
/// Send a short integer-valued message
inline void SetKeyValue(const MessageKey& key, short int_value) {
std::ostringstream ss; ss << int_value;
SetKeyValue(key, ss.str().c_str());
}
/// Send an integer-valued message
inline void SetKeyValue(const MessageKey& key, int int_value) {
std::ostringstream ss; ss << int_value;
SetKeyValue(key, ss.str().c_str());
}
/// Send a long integer-valued message
inline void SetKeyValue(const MessageKey& key, long int_value) {
std::ostringstream ss; ss << int_value;
SetKeyValue(key, ss.str().c_str());
}
/// Float-valued message
inline void SetKeyValue(const MessageKey& key, float float_value) {
std::ostringstream ss; ss << float_value;
SetKeyValue(key, ss.str().c_str());
}
/// Double-valued message
inline void SetKeyValue(const MessageKey& key, double double_value) {
std::ostringstream ss; ss << double_value;
SetKeyValue(key, ss.str().c_str());
}
/// Extract the whole key:value message
inline std::string GetString() const { return fString; }
/// Extract the message's key
inline MessageKey GetKey() const { return fMessage.first; }
/// Extract the message's string value
inline std::string GetValue() const { return fMessage.second; }
/// Extract the message's string value (without the trailing endlines)
inline std::string GetCleanedValue() const {
std::string s = fMessage.second;
s.erase(std::remove(s.begin(), s.end(), '\n'), s.end());
s.erase(std::remove(s.begin(), s.end(), '\r'), s.end());
return s;
}
/// Extract the message's integer value
inline int GetIntValue() const { return atoi(fMessage.second.c_str()); }
/// Extract the message's vector of string value
inline VectorValue GetVectorValue() const {
size_t start = 0, end = 0;
VectorValue out;
std::string value = GetValue();
while ((end=value.find(';', start))!=std::string::npos) {
out.push_back(value.substr(start, end-start));
start = end + 1;
}
out.push_back(value.substr(start));
return out;
}
inline void Dump(std::ostream& os=std::cout) const {
os << "=============== Socket Message dump ===============" << std::endl
<< " Key: " << MessageKeyToString(GetKey()) << " (" << GetKey() << ")" << std::endl
<< " Value: " << GetValue() << std::endl
<< "===================================================" << std::endl;
}
private:
inline MessageMap Object() const {
MessageMap out;
MessageKey key;
std::string value;
size_t end;
if ((end=fString.find(':'))==std::string::npos) {
std::ostringstream s; s << "Invalid message built! (\"" << fString << "\")";
throw Exception(__PRETTY_FUNCTION__, s.str().c_str(), JustWarning);
}
key = MessageKeyToObject(fString.substr(0, end).c_str());
value = fString.substr(end+1);
std::cout << MessageKeyToString(key) << " -> " << value << std::endl;
return make_pair(key, value);
}
inline std::string String() const {
std::string out = MessageKeyToString(fMessage.first);
out += ':';
out += fMessage.second;
out += '\0';
return out;
}
MessageMap fMessage;
};
#endif
| 33f48429e074b4f52f42249e088b6f73e31b0a9b | [
"CMake",
"Markdown",
"Python",
"C",
"C++",
"Shell"
]
| 74 | C++ | forthommel/pps-tbrc | fcfac644c948790db6c646db73b2f66270b38feb | 1e67cd04f47a35131fa019abfdabda23845e2a78 |
refs/heads/master | <repo_name>LannaLMB/AbstractClasses<file_sep>/AbstractClasses/Program.cs
using System;
using System.Threading;
namespace AbstractClasses
{
class Program
{
static void Main(string[] args)
{
// Instantiate Dog class to create dog object
Dog dog = new Dog();
// Instantiate Cat class to create cat object
Cat cat = new Cat();
dog.animalSound();
cat.animalSound();
// This allows the console window to stay open for 3 seconds.
// That way we can view our results for 3 seconds before the window closes.
// This is using milliseconds.
Thread.Sleep(3000);
}
}
}<file_sep>/AbstractClasses/Cat.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace AbstractClasses
{
class Cat : Animal // The Cat Class inherits our Animal(Base) Class
{
public override void animalSound()
{
Console.WriteLine("Meow!");
// return ("Meow!");
}
}
}<file_sep>/AbstractClasses/Dog.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace AbstractClasses
{
class Dog : Animal // The Dog Class inherits our Animal(Base) Class
{
public override void animalSound()
{
//return ("Woof!");
Console.WriteLine("Woof!");
}
}
}<file_sep>/README.md
# AbstractClasses
This program will showcase what Abstract Classes are and how to use them in a C# Console Application.
<file_sep>/AbstractClasses/Animal.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace AbstractClasses
{
abstract class Animal // This is our Base/Parent Class
{
public abstract void animalSound();
}
} | ed1cc796f738a39afc053893bd980e66160ae824 | [
"Markdown",
"C#"
]
| 5 | C# | LannaLMB/AbstractClasses | b6ca10c0febde983ae98a1806b99c5bb1aac75e2 | 3c7373548c391ff5e52bdc0e5193d3b1007e95ac |
refs/heads/master | <repo_name>olkruglova/Angular-todolist<file_sep>/src/app/todo-item/todo-item.component.ts
import { Component, OnInit, EventEmitter, Input, Output } from '@angular/core';
import { TodoItem } from '../interfaces/todo-item';
@Component({
selector: 'app-todo-item',
templateUrl: './todo-item.component.html',
styleUrls: ['./todo-item.component.css']
})
export class TodoItemComponent implements OnInit {
@Input() item:TodoItem;
@Output() upTask: EventEmitter<any> = new EventEmitter();
@Output() remove: EventEmitter<TodoItem> = new EventEmitter();
@Output() update: EventEmitter<any> = new EventEmitter();
isInEditMode: boolean = false;
constructor() { }
ngOnInit() {
}
removeItem() {
this.remove.emit(this.item);
}
completeItem() {
this.update.emit({
item: this.item,
changes: {completed: !this.item.completed}
});
}
editItem(){
this.isInEditMode = true;
}
updateTask(newTask:any) {
console.log(this.item);
this.upTask.emit(this.item, newTask);
}
}
<file_sep>/src/app/input/input.component.ts
import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
@Component({
selector: 'app-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit {
title:string = "Angular"
generatePlaceholder():string {
return 'New todo item ...';
}
@Output() submit: EventEmitter<string> = new EventEmitter();
submitValue(newTitle: string) {
console.log(newTitle);
this.submit.emit(newTitle);
}
constructor() { }
ngOnInit() {
}
}
<file_sep>/src/app/todo/todo.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-todo',
templateUrl: './todo.component.html',
styleUrls: ['./todo.component.css']
})
export class TodoComponent implements OnInit {
name:string = "Olga";
title:string = "My todo";
userLoggedIn:boolean = false;
constructor() { }
ngOnInit() {
}
}
| ce5729e9fa365b894d7ddc50a6509a5c9567b596 | [
"TypeScript"
]
| 3 | TypeScript | olkruglova/Angular-todolist | d7608146714a9d727125e719c30e2942ec710432 | 4d8ecf1925b35459bef4dc0d4564ba380319bd64 |
refs/heads/main | <file_sep>// // Insiration from https://www.youtube.com/watch?v=wPElVpR1rwA&t=1640s
function performAction() {
let long;
let lat;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
long = position.coords.longitude;
lat = position.coords.latitude;
console.log(lat, long)
const wbApi = `https://api.weatherbit.io/v2.0/forecast/daily?lat=${lat}&lon=${long}&key=5f6318133b1e4773bb68e669f73545bd`
fetch(wbApi, {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}})
.then (res => res.json())
.then (data => {
document.getElementById('current').style.display = "flex";
document.getElementById('locationResultCurrent').innerHTML = `<span>${data.city_name}</span>, ${data.country_code}`;
document.getElementById('today').innerHTML =
`<td class="temp"><span>${data.data[0].temp}</span> °C</td>
<td class="description"><span>${data.data[0].weather.description}</span></td>
<td>
<img class="icon" src="https://www.weatherbit.io/static/img/icons/${data.data[0].weather.icon}.png"/>
</td>`;
})
});
} else {
let currentDiv = document.getElementById('current')
currentDiv.style.display = "none";
}
};
export { performAction }
<file_sep>// from https://knowledge.udacity.com/questions/336147
import app from './server' // Link to your server file
import supertest from 'supertest'
const request = supertest(app)
it('Testing /all endpoint', async done => {
const response = await request.get('/all')
expect(response.status).toBe(200) // check if request was successfull
expect(response.body).toBeDefined(); // check if response returned value of projecteData
done()
})
<file_sep>// Mostly from project 3&4
let projectData = {};
// API'S
const dotenv = require('dotenv');
dotenv.config();
const wbUrl = 'https://api.weatherbit.io/v2.0/forecast/daily?lat='
const wbk = process.env.weatherBitKey
const pbk = process.env.pixabayKey
const pbUrl = `https://pixabay.com/api/?key=${pbk}`
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Middleware*/
const bodyParser = require('body-parser');
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');
const { response } = require('express');
app.use(cors());
// to allow making fetch requests in server
const fetch = require('node-fetch');
// Initialize the main project folder
app.use(express.static('dist'))
app.get('/', function (req, res) {
res.sendFile('dist/index.html')
})
// Export module for testing
module.exports = app
// WeatherBit API request with geonamesCoords
app.post('/add', getWeather);
async function getWeather (req, res) {
let weatherUrl = `${wbUrl}${req.body.lat}&lon=${req.body.long}&key=${wbk}`
const response = await fetch(weatherUrl)
try {
const data = await response.json()
// location
projectData.placeName = data.city_name;
projectData.country = data.country_code;
projectData.duration = req.body.duration;
// forecast data points
let arrivalDayIndex = req.body.daysTillDep;
let returnDayIndex = arrivalDayIndex + 5;
// an array to store this data:
const WeatherDataArray = data.data
const tripWeatherArray = []
if (arrivalDayIndex<7) {
for(let i = arrivalDayIndex; i <= returnDayIndex; i++ ){
tripWeatherArray.push(WeatherDataArray[i])
projectData.temps = tripWeatherArray.map(dayData => dayData.temp)
projectData.descriptions = tripWeatherArray.map(dayData => dayData.weather.description)
projectData.icons = tripWeatherArray.map(dayData => dayData.weather.icon)
projectData.dates = tripWeatherArray.map(dayData => dayData.valid_date.split("-").reverse().join("-"))
}
} else {
projectData.todayTemp = data.data[0].temp
projectData.todayDescription = data.data[0].weather.description
projectData.todayIcon = data.data[0].weather.icon
projectData.todayDate = data.data[0].valid_date.split("-").reverse().join("-")
};
res.send(projectData);
console.log(projectData);
} catch (error) {
console.log('error', error)
}
}
// Add a GET route that returns the projectData object
app.get('/all', function (req, res) {
res.send(projectData);
})
<file_sep># Capstone - Travel App
## Overview
This project aims to combine all skills learned in the previous projects to build our own custom travel app. This app allows the user to fill in a travel destination and traveling dates. Upon page load the app will display the current weahter from the users location. Upon submit the app will display a background image of the travel destination and a weather forecast of the destination depending of how far in advance the travel plans are. If the user is traveling within a week the forecast will be of this week starting with their arrival day. If the trip is later the current weather will be displayed.
I choose the following options from the Extend your Project/Ways to Stand Out sections:
* Add end date and display length of trip.
* Incorporate icons into forecast.
* Instead of just pulling a single day forecast, pull the forecast for multiple days.
* And I've added the current weather at the users location upon page load.
## Instructions
This will require a understanding of JavaScript, create clean and appealing HTML/CSS, targeting the DOM, working with objects and retrieving data from 3 APIs in which one of those is reliant on another to work. Finally this is all going to be done in a Webpack environment, using an express server and wrapped up with service workers.
### Tools used
* HTML
* SCSS
* Javascript
* Node
* Express
* GeoNames API
* WeatherBit API
* PixaBay API
* Jest
* Workbox
## Installation
### 1 Getting Started
Make sure Node and npm are installed from the terminal.
node -v
npm -v
Fork this repo and clone to begin your project setup and install everything:
`cd` <project directory>
`npm install`
Install the following loaders and plugins
- npm i -D @babel/core @babel/preset-env babel-loader
- npm i -D style-loader node-sass css-loader sass-loader
- npm i -D clean-webpack-plugin
- npm i -D html-webpack-plugin
- npm i -D mini-css-extract-plugin
- npm i -D optimize-css-assets-webpack-plugin terser-webpack-plugin
### 2 Setting up the API
Sign up for the API-key's at geonames.org weatherbit.io pixabay.com
You'll need to configure environment variables using the dotenv package:
Use npm to install the dotenv package
npm install dotenv
Create a new .env file in the root of your project.
Fill the .env file with your weatherbit API key like this:
API_KEY=**************************
### 3 Setup service workers for offline functionality
Require the plugin, by appending the new plugin statement in your webpack.prod.js file.
const WorkboxPlugin = require('workbox-webpack-plugin')
Instantiate the new plugin in the plugin list.
plugins: [
new WorkboxPlugin.GenerateSW(),
]
use npm to install the plugin:
npm install workbox-webpack-plugin --save-dev
### 4 Run the app
npm run build : builds project
npm start : Run project
The app opens on localhost 3000.
The server listens on port 3030.
To run Jest Test on the server 'comment out' the Setup Server part of server.js
and run: npm run test
## Known issues
There is a compatibility issue with the terser plugin. The plugin needs to be downgrade in the package.json file to
> "terser-webpack-plugin": "^4.2.3"
Then run
- npm i
- npm run build-prod
<file_sep>
async function handleSubmit(event) {
event.preventDefault()
// check what text was put into the form field
let userDestination = document.getElementById('uiLocation').value
console.log(`user entered: ${userDestination}`)
let userDeparture = document.getElementById('uiDeparture').value
console.log(`user entered: ${userDeparture}`)
let userReturn = document.getElementById('uiReturn').value
console.log(`user entered: ${userReturn}`)
let currentDiv = document.getElementById('current')
let forecastDiv = document.getElementById('forecast')
// Inspiration from https://www.geeksforgeeks.org/how-to-calculate-the-number-of-days-between-two-dates-in-javascript/
// Countdown
const today = new Date()
const date1 = new Date(userDeparture);
const date2 = new Date(userReturn);
const timeTillDep = Math.abs(date1 - today);
const daysTillDep = Math.ceil(timeTillDep / (1000 * 60 * 60 * 24));
const timeTillRet = Math.abs(date2 - today);
const daysTillRet = Math.ceil(timeTillRet / (1000 * 60 * 60 * 24));
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
console.log("days till departure: " + daysTillDep + " days");
console.log("duration: " + diffDays + " days");
// Set display
toggleDisplay(daysTillDep,currentDiv,forecastDiv)
// PixaBay API request
await getImage(userDestination)
// FourSquare API request
await getVenues(userDestination)
// GeoNames API request
await getCoords(userDestination)
// post userInput to serverside, inspiration from project3
.then (function(data) {
postCoords('http://localhost:3030/add', {
placeName: data.geonames[0].name,
lat: data.geonames[0].lat,
long: data.geonames[0].lng,
country: data.geonames[0].countryName,
daysTillDep: daysTillDep,
daysTillRet: daysTillRet,
duration: diffDays})
.then(function(newData) {
updateUI()
})
})
};
// Toggle results display
function toggleDisplay(daysTillDep,currentDiv, forecastDiv) {
if (daysTillDep > 6) {
currentDiv.style.display = "flex";
forecastDiv.style.display = "none";
} else {
currentDiv.style.display = "none";
forecastDiv.style.display = "flex";
}
};
// PixaBay API Request
async function getImage (userDestination) {
let imageUrl = `https://pixabay.com/api/?key=20000501-dad6322171b2d4f4f813207da&q=${userDestination}&image_type=photo`
const response = await fetch(imageUrl)
try {
const data = await response.json()
// from https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript
let randomNumber = Math.floor(Math.random() * 20) + 1;
let dataSelector = data.hits[randomNumber];
document.getElementById('photo').style.backgroundImage = `url(${dataSelector.largeImageURL})`;
} catch (error) {
console.log('error', error)
}
}
// fourSquare API request
async function getVenues(userDestination) {
const clientId = 'H<KEY>';
const clientSecret = '<KEY>';
const url = 'https://api.foursquare.com/v2/venues/explore?near=';
let venueUrl = `${url}${userDestination}&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20210222`;
const response = await fetch(venueUrl);
try {
const venueData = await response.json();
const venues = venueData.response.groups[0].items.map(item => item.venue);
for (let i = 0; i < 3; i++) {
document.getElementById('fourSquare').style.display = "flex";
const venueId = `venue${i}`;
document.getElementById(venueId).innerHTML =
`<h3>${venues[i].name}</h3>
<img class="venueimage" src="${venues[i].categories[0].icon.prefix}bg_64${venues[i].categories[0].icon.suffix}"/>
<h3>Address:</h3>
<p>${venues[i].location.address}</p>
<p>${venues[i].location.city}</p>
<p>${venues[i].location.country}</p>`;
}
}
catch(error) {
console.log(error)
}
};
// geoNames API Request
async function getCoords(userDestination) {
let geoUrl = `http://api.geonames.org/searchJSON?q=${userDestination}&maxRows=1&username=dycoster`;
const response = await fetch (geoUrl);
try {
const data = await response.json();
console.log(data);
return data;
} catch (error) {
console.log('error', error)
}
};
const postCoords = async (url = '', data = {})=> {
const response = await fetch (url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
try {
const newData = await response.json();
return newData;
}catch (error) {
console.log("error", error);
}
};
const updateUI = async () => {
const request = await fetch('http://localhost:3030/all');
try{
const allData = await request.json();
// Todays weather
document.getElementById('locationResultCurrent').innerHTML = `<span>${allData.placeName}</span>, ${allData.country};`
document.getElementById('today').innerHTML =
`<td class="date"><span>${allData.todayDate}</span></td>
<td class="temp"><span>${allData.todayTemp}</span> °C</td>
<td class="description"><span>${allData.todayDescription}</span></td>
<td>
<img class="icon" src="https://www.weatherbit.io/static/img/icons/${allData.todayIcon}.png"/>
</td>`;
// Forecasted weather
document.getElementById('locationResultForecast').innerHTML = `<span>${allData.placeName}</span>, ${allData.country};`
for (let i = 0; i < 5; i++) {
const divId = `day${i}`;
document.getElementById(divId).innerHTML =
`<td class="date"><span>${allData.dates[i]}</span></td>
<td class="temp"><span>${allData.temps[i]}</span> °C</td>
<td class="description"><span>${allData.descriptions[i]}</span></td>
<td>
<img class="icon" src="https://www.weatherbit.io/static/img/icons/${allData.icons[i]}.png"/>
</td>`;
}
}
catch (error) {
console.log("error", error);
}
};
export {
toggleDisplay,
handleSubmit,
getImage,
getCoords,
postCoords,
updateUI
}
<file_sep>import { performAction } from './js/app'
import { handleSubmit, toggleDisplay, getImage, getCoords, postCoords, updateUI } from './js/formHandler'
import './styles/body.scss'
import './styles/resets.scss'
// add eventlistener with callback action
window.addEventListener("load", performAction);
document.getElementById('submit').addEventListener('click', handleSubmit);
// moved to index.js as suggested in https://knowledge.udacity.com/questions/435694
// Check that service workers are supported
// if ('serviceWorker' in navigator) {
// // Use the window load event to keep the page load performant
// window.addEventListener('load', () => {
// console.log('Installing service workers')
// navigator.serviceWorker.register('/service-worker.js');
// });
// }
export {
performAction,
handleSubmit,
toggleDisplay,
getImage,
getCoords,
postCoords,
updateUI
}<file_sep>// from https://knowledge.udacity.com/questions/336147
// Setup Server
const app = require('./server.js')
app.listen(3030, ()=>{
console.log(`running on localhost: 3030`);
}); | 059e87b2ec81c5e39c26eb9e21eec66f9c926143 | [
"JavaScript",
"Markdown"
]
| 7 | JavaScript | dycoster/TravelApp | c789baaad6b88a4d479ac1a00b2c1613148ad57e | 8ff576130c9e601fe839aea09d89b5a228363ec3 |
refs/heads/master | <repo_name>ReqHU/testtask<file_sep>/src/main/java/com/reqhu/testtask/domain/Room.java
package com.reqhu.testtask.domain;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.FieldDefaults;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.List;
@Entity
@Table(name = "rooms")
@FieldDefaults(level = AccessLevel.PRIVATE)
@NoArgsConstructor
@Getter
@Setter
public class Room extends AbstractEntity {
String type;
@OneToMany(mappedBy = "room")
List<Booking> bookings;
}
<file_sep>/src/main/java/com/reqhu/testtask/service/BookingService.java
package com.reqhu.testtask.service;
import com.reqhu.testtask.domain.Booking;
import com.reqhu.testtask.domain.Room;
import com.reqhu.testtask.domain.User;
import com.reqhu.testtask.repository.BookingRepository;
import com.reqhu.testtask.repository.RoomRepository;
import com.reqhu.testtask.repository.UserRepository;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import static com.reqhu.testtask.util.BookingsUtil.checkForAvailability;
@Service
public class BookingService {
private final BookingRepository bookingRepository;
private final UserRepository userRepository;
private final RoomRepository roomRepository;
public BookingService(BookingRepository bookingRepository, UserRepository userRepository, RoomRepository roomRepository) {
this.bookingRepository = bookingRepository;
this.userRepository = userRepository;
this.roomRepository = roomRepository;
}
public List<Booking> findAll() {
return bookingRepository.findAll();
}
@Transactional
public void deleteById(int id) {
bookingRepository.deleteById(id);
}
@Transactional
public void save(
String name, String description, LocalDateTime startDateTime,
LocalDateTime endDateTime, Integer userId, Integer roomId
) {
if (name.isBlank()) {
throw new IllegalArgumentException("Название манипуляции не должно быть пустым.");
}
if (startDateTime.isAfter(endDateTime)) {
throw new IllegalArgumentException("Дата/время начала манипуляции должно быть перед датой/временем конца манипуляции.");
}
User user = userRepository.findById(userId).orElseThrow();
Room room = roomRepository.findById(roomId).orElseThrow();
if (checkForAvailability(startDateTime, endDateTime, user.getBookings())) {
if (checkForAvailability(startDateTime, endDateTime, room.getBookings())) {
bookingRepository.nativeSqlSave(name, description, startDateTime, endDateTime, userId, roomId);
} else {
throw new RuntimeException("Помещение занято в это время.");
}
} else {
throw new RuntimeException("Участник занят в это время.");
}
}
@Scheduled(cron = "0 * * * * *")
@Transactional
public void deleteBookingsAutomatically() {
List<Booking> bookings = bookingRepository.findAll();
for (Booking booking : bookings) {
if (booking.getEndDateTime().isBefore(LocalDateTime.now())) {
bookingRepository.deleteById(booking.getId());
}
}
}
}
<file_sep>/src/main/resources/db/initDB.sql
CREATE SEQUENCE global_seq AS INTEGER START WITH 1;
CREATE TABLE users
(
id INTEGER GENERATED BY DEFAULT AS SEQUENCE global_seq,
name VARCHAR(255) NOT NULL, -- Врач/медсестра/и т.д.
PRIMARY KEY (id),
UNIQUE (name)
);
CREATE TABLE rooms
(
id INTEGER GENERATED BY DEFAULT AS SEQUENCE global_seq,
type VARCHAR(255) NOT NULL,
PRIMARY KEY (id),
UNIQUE (type)
);
CREATE TABLE bookings
(
id INTEGER GENERATED BY DEFAULT AS SEQUENCE global_seq,
name VARCHAR(255) NOT NULL,
description VARCHAR(255) ,
start_date_time TIMESTAMP NOT NULL,
end_date_time TIMESTAMP NOT NULL,
user_id INTEGER NOT NULL,
room_id INTEGER NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
FOREIGN KEY (room_id) REFERENCES rooms (id) ON DELETE CASCADE
);
INSERT INTO users (name) VALUES
('Врач'), -- 1
('Медсестра'); -- 2
INSERT INTO rooms (type) VALUES
('Тип помещения 1'), -- 3
('Тип помещения 2'); -- 4<file_sep>/src/main/java/com/reqhu/testtask/repository/BookingRepository.java
package com.reqhu.testtask.repository;
import com.reqhu.testtask.domain.Booking;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
@Repository
@Transactional
public interface BookingRepository extends JpaRepository<Booking, Integer> {
@Modifying
@Query(value =
"INSERT INTO bookings (name, description, start_date_time, end_date_time, user_id, room_id) " +
"VALUES (:name, :description, :start_date_time, :end_date_time, :user_id, :room_id)",
nativeQuery = true)
void nativeSqlSave(
@Param("name") String name, @Param("description") String description,
@Param("start_date_time") LocalDateTime startDateTime, @Param("end_date_time") LocalDateTime endDateTime,
@Param("user_id") Integer userId, @Param("room_id") Integer roomId);
}
<file_sep>/src/main/resources/application.properties
spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
spring.datasource.url=jdbc:hsqldb:mem:testtaskDB
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.schema=classpath:db/initDB.sql
spring.datasource.initialization-mode=always
spring.jpa.open-in-view=false
spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
| 547f8d944c0c61829ee50ed3e495a01f643d71e7 | [
"Java",
"SQL",
"INI"
]
| 5 | Java | ReqHU/testtask | cd0685512c75d0d3bfdf9737072d71329c5afe70 | f05ea33866b7f5f4048a4f4cab13d6a469607c0e |
refs/heads/master | <repo_name>mamduhmahfudzi/data-science-bootstrap<file_sep>/statistics.py
from typing import List
import numpy as np
Vector = np.ndarray
def mean(xs: List[float]) -> float:
return sum(xs) / len(xs)
def deviation(xs: List[float]) -> List[float]:
x_bar = mean(xs)
return [x - x_bar for x in xs]
def variance(xs: List[float]) -> float:
assert len(xs) >= 2, "Variance requires at least two elements"
n = len(xs)
deviations = deviation(xs)
return np.dot(deviations, deviations) / (n)
def standard_deviation(xs: np.ndarray) -> np.ndarray:
return np.sqrt(variance(xs))
def covariance(xs: Vector, ys: Vector) -> Vector:
assert len(xs) == len(ys), "Vector 1 and Vector 2 must have same number of elements"
return np.dot(deviation(xs), deviation(ys)) / (len(xs))
def correlation(xs: Vector, ys:Vector) -> float:
std_x = standard_deviation(xs)
std_y = standard_deviation(ys)
if std_x > 0 and std_y > 0:
return covariance(xs,ys) / (std_x * std_y)
else:
return 0
x = [i for i in range(-100, 100, 1)]
y = [i for i in range(-100, 100, 1)]
# print(variance(x))
# print(variance(y))
# print(covariance(x, y))
print(correlation(x, y))
# assert correlation(x, y) == 1
<file_sep>/gradient_descend.py
from typing import Callable
import numpy as np
import math
Vector = np.ndarray
def difference_quotient(f: Callable[[float], float],
x: float,
h:float):
return (f(x+h) - f(x)) / h
def partial_difference_quotient(f: Callable[[Vector], float],
v: Vector,
i: int,
h: float) -> float:
w = [v_j + (h if j == i else 0) for j, v_j in enumerate(v)]
return (f(w) - f(v)) / h
def estimate_gradient(f: Callable[[Vector], float],
v: Vector,
h: float = 0.0001) -> Vector:
return [partial_difference_quotient(f, v, i, h)
for i in range(len(v))]
def gradient_step(v: Vector, gradient: Vector, step_size: float) -> Vector:
assert len(v) == len(gradient), "Vector 1 and Vector 2 must have same number of elements"
step = np.asarray(gradient) * step_size
return v + step
def sum_of_square_gradient(v: Vector) -> Vector:
return [2 * v_i for v_i in v]
import random
from linear_algebra import distance
v = [random.uniform(-10, 10) for i in range(3)]
for epoch in range(1000):
grad = sum_of_square_gradient(v) # compute the gradient at v
v = gradient_step(v, grad, -0.01) # take a negative gradient step
print(epoch, v)
assert distance(v, [0, 0, 0]) < 0.001 # v should be close to 0<file_sep>/linear_algebra.py
from typing import List
import math
import numpy as np
Vector = np.ndarray
def add(v: Vector, w: Vector) -> Vector:
"""Add Corresoponding Elements"""
assert len(v) == len(w), "vector must be the same length"
return [v_i + w_i for v_i, w_i in zip(v, w)]
assert add([1, 2, 3], [4, 5, 6]) == [5, 7, 9]
def subtract(v: Vector, w: Vector) -> Vector:
assert len(v) == len(w)
return np.array([v_i - w_i for v_i, w_i in zip(v, w)])
# def distance(v: Vector, w: Vector) -> Vector:
# delta = subtract(v, w)
# delta_square = np.power(delta, 2)
# return delta_square
def distance(v: Vector, w: Vector) -> Vector:
delta = subtract(v, w)
delta_square = np.power(delta, 2)
square_sum = np.sum(delta_square)
return np.sqrt(square_sum)
assert distance([0,0], [3,4]) == 5 | 3856f440eb976bbe6ed746ec08ffc90275739b30 | [
"Python"
]
| 3 | Python | mamduhmahfudzi/data-science-bootstrap | 2feb57e79d8ba544ef378e7ddc3f6e6f50fd53e3 | 6081e5487091e71910a353bff22cb7d1e45ce802 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour {
private Rigidbody2D rb;
private bool isGrounded;
[SerializeField]
private float jumpForce;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D> ();
isGrounded = true;
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "ground")
isGrounded = true;
}
// Update is called once per frame
void FixedUpdate () {
/*if (Input.GetKeyDown (KeyCode.Space) && isGrounded)
{
}*/
}
public void Jump(){
if(isGrounded)
{
isGrounded = false;
rb.AddForce (Vector2.up * jumpForce, ForceMode2D.Impulse);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Block : MonoBehaviour {
private float timeDistance = 3.5f; //tiempo que se a demorar recorriendo la distancia x
private float Distance = 19f; // distancia x, es la distancia que hay desde el personaje hasta el spawn de enemigos
[SerializeField]
private Text textWord;
// Use this for initialization
void Start () {
}
public void SetText(string myText)
{
textWord.text = myText;
}
// Update is called once per frame
void Update () {
float currentMove = (Time.deltaTime * Distance) / timeDistance;
transform.Translate (Vector3.right*-currentMove);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BlockCreator : MonoBehaviour {
public RhythmTool rhythmTool;
public AudioClip audioClip;
[SerializeField]
private Transform spawnTransform;
[SerializeField]
private GameObject blockPrefab;
[SerializeField]
private int beatsToSpawn;
[SerializeField]
private AudioSource mainSample;
[SerializeField]
private int[] songCode; //codigo que define el orden de salida de las silabas
[SerializeField]
private string[] words; //aca se definen cuales silabas van a salir
private int currentWord;
private GameObject[] poolBlocks = new GameObject[10];
private int countBeat;
private int currentBlock;
private AnalysisData lowFrec;
private int currentFrame;
private float lastFrec; // la ultima frecuencia que activo la creacion de bloques
// Use this for initialization
void Start ()
{
lowFrec = rhythmTool.low;
SetUpRhythmTool ();
CreatPoolBlocks ();
}
//OnReadyToPlay is called by RhythmTool after NewSong(), when RhythmTool is ready to start playing the song.
//When RhythmTool is ready depends on lead and on whether preCalculate is enabled.
private void OnSongLoaded()
{
//Start playing the song
rhythmTool.Play();
mainSample.PlayDelayed(3.5f);
}
// Update is called once per frame
void Update ()
{
if (CheckInSongRange()) return;
if (CheckIsOnSet())
SpawnBlock ();
lastFrec = lowFrec.magnitude [currentFrame];
}
public void CheckBeat ()
{
countBeat++;
if (countBeat >= beatsToSpawn) {
countBeat = 0;
SpawnBlock ();
}
}
private void CreatPoolBlocks()
{
for(int i = 0; i <poolBlocks.Length; i++)
{
poolBlocks[i] = Instantiate(blockPrefab);
poolBlocks[i].SetActive(false);
}
}
private bool CheckIsOnSet()
{
currentFrame = rhythmTool.currentFrame;
float onSet = lowFrec.GetOnset (currentFrame);
Debug.Log("Estoy aqui");
return (onSet > 0 && lastFrec != lowFrec.magnitude [currentFrame]);
}
private bool CheckInSongRange ()
{
return currentBlock >= rhythmTool.totalFrames;
}
void SetUpRhythmTool ()
{
rhythmTool = GetComponent<RhythmTool>();
//Give it a song.
rhythmTool.NewSong(audioClip);
//Subscribe to SongLoaded event.
rhythmTool.SongLoaded += OnSongLoaded;
}
void SpawnBlock ()
{
if (currentBlock>= poolBlocks.Length) {
currentBlock = 0;
}
poolBlocks [currentBlock].transform.position = spawnTransform.position;
poolBlocks [currentBlock].SetActive (true);
poolBlocks [currentBlock].GetComponent<Block> ().SetText (words [songCode [currentWord]]);
currentBlock++;
currentWord++;
}
}
| 8d688861e600632150faf8c700b73fbeb4b72bf9 | [
"C#"
]
| 3 | C# | Wizard3d/bandaLetras | 645f8bf765ee2e240a453dd9f9d57abf3af749bc | 5d4eafe3b64462febebeff7994c2947693a05161 |
refs/heads/master | <repo_name>krtb/react-evernote-guided-project-nyc-mhtn-web-060418-1534369924<file_sep>/frontend/src/components/NoteList.js
import React from 'react';
import NoteItem from './NoteItem';
const NoteList = (props) => {
const notesArray = props.secondLevelNotesDAta.map((oneNoteObj) => {
return <NoteItem handleDelete={props.handleDelete} handleEdit={props.handleEdit} handleClick={props.handleClick} oneNote={oneNoteObj} key={oneNoteObj.id} title={oneNoteObj.title} body={oneNoteObj.body} />
})
return (
<ul>
{notesArray}
</ul>
);
}
export default NoteList;
<file_sep>/frontend/src/components/NoteEditor.js
import React, { Component } from 'react';
class NoteEditor extends Component {
state = {
currentTitle: this.props.noteEdit.title,
currentBody: this.props.noteEdit.body,
}
handleTitleChange = (event) => {
this.setState({
currentTitle: event.target.value
})
}
handleBodyChange = (event) => {
this.setState({
currentBody: event.target.value
})
}
updatePatch = (editID, editTitle, editBody) => {
let editURL = `${'http://localhost:3000/api/v1/notes'}/${editID}`
let editPatch = {
method: 'PATCH',
body: JSON.stringify({
title: editTitle,
body: editBody
}),
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
}
}
return fetch(editURL, editPatch).then(resp=>resp.json())
}
handleSubmit = (event, props, state) => {
event.preventDefault()
// would set state here
console.log(state)
// this.setState({
// noteClicked: false
// })
let editID = props.noteEdit.oneNote.id
let editTitle = state.currentTitle
let editBody = state.currentBody
// console.log(event, props.noteEdit.oneNote.id, state.currentTitle, state.currentBody);
this.updatePatch(editID, editTitle, editBody).then(()=> this.props.fetchNotes())
this.props.handleCancel()
}
render() {
return (
<form className="note-editor" onSubmit={(event) => this.handleSubmit(event, this.props, this.state)} >
<input type="text" name="title" value={this.state.currentTitle} onChange={this.handleTitleChange} />
<textarea name="body" value={this.state.currentBody} onChange={this.handleBodyChange} />
<div className="button-row">
<input className="button" type="submit" value="Save" />
<button type="button" onClick={this.props.handleCancel}>Cancel</button>
</div>
</form>
);
}
}
export default NoteEditor; | 481d4e8f854c889f343ae845f07ea4e5fd214a09 | [
"JavaScript"
]
| 2 | JavaScript | krtb/react-evernote-guided-project-nyc-mhtn-web-060418-1534369924 | d9d6b0cf8b7498d3604967e55e53de57231e79fd | 3691a284d2141cd63b74d880a944e62edfba35b2 |
refs/heads/master | <repo_name>javonesm89/react-simple-state-lab-dumbo-web-100719<file_sep>/src/Cell.js
// import React, { Componenet } from 'react'
// class Cell extends React.Component{
// state = {
// color: this.props.value
// }
// onClick = () => {
// this.setState ({
// color: '#333'
// })
// }
// render (){
// return <div onClick={this.onClick} className='cell' style={{backgroundColor: this.state.color}} ></div>
// }
// }
// export default Cell
import React, { Componenet } from 'react'
class Cell extends React.Component{
state = {
color: this.props.value
}
onClick = () => {
this.setState ({
color: '#333'
})
}
render (){
return <div onClick={this.onClick} className='cell' style={{backgroundColor: this.state.color}} ></div>
}
}
export default Cell | e9b7b58014fbe260f2ae2d1e8f856fbefcb30b13 | [
"JavaScript"
]
| 1 | JavaScript | javonesm89/react-simple-state-lab-dumbo-web-100719 | 90188e205c511c49f99ab1c0f460b37120234f75 | fdb0ab8c5e87a4ea54c9d14db9fb84634b10fab0 |
refs/heads/master | <repo_name>JulianGindi/Data-Structures<file_sep>/linkedList.c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char data;
struct node *next;
} list_node;
void add_node(char value, list_node **head_ptr);
void print_list(list_node *);
void free_list(list_node **);
void delete_node(char, list_node **);
int main()
{
int choice; char value;
list_node *head=NULL;
printf("Please select one of the following options:\n Press 1, to insert an element into the list. \n Press 2, to delete an element from the list. \n Press 3, to end.\n");
scanf("%d", &choice);
while(choice!=3){
switch(choice){
case 1:
printf("Enter a character:\n");
scanf("\n%c", &value);
add_node(value,&head);
print_list(head);
break;
case 2:
if(head==NULL){
printf("Empty list, impossible to delete");
}
else{
printf("Enter a character to be deleted:\n");
scanf("\n%c", &value);
delete_node(value, &head);
}
printf("Deleting Node\n");
print_list(head);
break;
default:
printf("Input Error!\n");
break;
}
printf("?\n");
scanf("%d", &choice);
}
printf("Exited Program\n");
free_list(&head);
}
void add_node(char value, list_node **head_ptr){
list_node *new_node, *current_node, *previous_node=NULL;
new_node = (list_node*)malloc(sizeof(list_node));
current_node=(*head_ptr);
new_node->data=value;
new_node->next=NULL;
while((current_node!=NULL) && ((current_node->data)<value)){
previous_node=current_node;
current_node=current_node->next;
}
if(previous_node==NULL){
new_node->next=current_node;
(*head_ptr)=new_node;
}
else{
previous_node->next=new_node;
new_node->next=current_node;
}
}
void print_list(list_node *head){
list_node *iterator;
if(head==NULL){
printf("List is empty.\n\n");
}
else{
printf("Elements of the list:");
iterator = head;
while ( iterator != NULL) {
printf( "%c ==> ", iterator->data );
iterator = iterator->next;
}
printf("NULL\n");
}
}
void free_list(list_node **head_ptr){
list_node *iterator;
while((*head_ptr)!=NULL){
iterator = (*head_ptr);
(*head_ptr) = (*head_ptr)->next;
free(iterator);
}
}
void delete_node(char value, list_node **head_ptr){
list_node *previous=NULL, *current;
current=(*head_ptr);
if(current->data == value){
(*head_ptr)=(*head_ptr)->next;
free(current);
}
else{
while((current!=NULL)&&(current->data!=value)){
previous=current;
current=current->next;
}
if(current!=NULL){
previous->next=current->next;
free(current);
printf("element %c deleted", value);
}
else{
printf("element not found");
}
}
}
| 736c93e3cb461389e2ba534d0162b43dae8490f7 | [
"C"
]
| 1 | C | JulianGindi/Data-Structures | d73e762692a4897e0e98f6aaae0a02ee6cd8554f | e6a043b566ac1d1c6286c254701b2d443f7fb42c |
refs/heads/master | <repo_name>joernott/docker-oc-elasticsearch<file_sep>/src/entrypoint
#!/bin/bash
IP=$(ip a show eth0 |grep "inet "|sed -e 's|.*inet ||' -e 's|/.*||')
sed -e "s|#network.host: .*|network.host: [ \"127.0.0.1\", \"${IP}\" ]|" -i /etc/elasticsearch/elasticsearch.yml
cat /etc/elasticsearch/elasticsearch.yml
chown -R ${APP_USER}:${APP_GROUP} ${APP_HOME} /etc/elasticsearch /etc/sysconfig/elasticsearch /var/log/elasticsearch /var/lib/elasticsearch
cd ${APP_HOME}
gosu ${APP_USER}:${APP_GROUP} /usr/share/elasticsearch/bin/elasticsearch \
-p ${PID_DIR}/elasticsearch.pid \
$@
<file_sep>/src/tmp/install/oc-elasticsearch.sh
#!/bin/bash
set -e
set -x
source /tmp/install/functions.sh
add_repos elasticsearch${ELASTICSEARCH_VERSION:0:1}
create_user_and_group
install_software iproute elasticsearch-${ELASTICSEARCH_VERSION}
cleanup
<file_sep>/build.sh
#!/bin/bash
set -e
set -x
curl -sSo src/tmp/install/functions.sh https://raw.githubusercontent.com/joernott/docker-oc-install-library/master/install_functions.sh
source src/tmp/install/functions.sh
patch_dockerfile Dockerfile5
docker build -f Dockerfile5 -t registry.ott-consult.de/oc/elasticsearch:5 .
docker push registry.ott-consult.de/oc/elasticsearch:5
patch_dockerfile Dockerfile6
docker build -f Dockerfile6 -t registry.ott-consult.de/oc/elasticsearch:6 .
docker push registry.ott-consult.de/oc/elasticsearch:6
docker tag registry.ott-consult.de/oc/elasticsearch:6 registry.ott-consult.de/oc/elasticsearch:latest
docker push registry.ott-consult.de/oc/elasticsearch:6
docker push registry.ott-consult.de/oc/elasticsearch:latest
patch_dockerfile Dockerfile7
docker build -f Dockerfile7 -t registry.ott-consult.de/oc/elasticsearch:7 .
docker push registry.ott-consult.de/oc/elasticsearch:7
<file_sep>/README.md
# Docker image: Elasticsearch 5/6 on CentOS 7
Running Elasticsearch 5 or 6 on CentOS 7
The version tagged 5 runs Elasticsearch 5.x, version 6 or latest refers to Elasticsearch 6.x.
The application runs as non-privileged user/group elasticsearch/elk.
## Usage:
### Simple usage
```
docker run -d -p 9100:9100 -p 9200:9200 \
-v /data/elasticsearch/var/elasticsearch:/var/elasticsearch \
-v /data/elasticsearch/etc/elasticsearch:/etc/elasticsearch \
registry.ott-consult.de/oc/elasticsearch:latest
```
| 79c36aab6e65dd74ddf8fb4d3f7e488d17b2907f | [
"Markdown",
"Shell"
]
| 4 | Shell | joernott/docker-oc-elasticsearch | 6d278a73a5a510d25634b7ee980232ad27a8aad0 | 6a861fc211686fdde397c40fef51c7f855ee1019 |
refs/heads/master | <file_sep>from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.user == request.user
class IsStaffOrReadOnly(permissions.BasePermission):
def has_permission(self, request, view):
return (
request.method in permissions.SAFE_METHODS or
request.user and
request.user.is_staff
)
class IsAdminOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return (
request.method in permissions.SAFE_METHODS or
request.user and
request.user.is_superuser
)
<file_sep>from .models import Category, Post
from . import serializers
from django.contrib.auth.models import User
from django.views.generic import ListView
from rest_framework import viewsets, permissions
from . import permissions as custom_perms
class CategoryListView(viewsets.ModelViewSet):
queryset = Category.objects.all()
serializer_class = serializers.CategorySerializer
permission_classes = (
custom_perms.IsStaffOrReadOnly,
)
class PostListView(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = serializers.PostsSerializer
permission_classes = (
permissions.IsAuthenticatedOrReadOnly,
custom_perms.IsOwnerOrReadOnly,
)
class UserListView(viewsets.ModelViewSet):
queryset = User.objects.filter(is_superuser=False)
serializer_class = serializers.UserSerializer
permission_classes = (
custom_perms.IsAdminOrReadOnly,
)
def get_serializer_class(self):
if self.action == 'create':
return serializers.CreateUserSerializer
return self.serializer_class
class ArticleListView(ListView):
model = Post
template_name = 'notification/index.html'
queryset = Post.objects.all().order_by('-pk')
<file_sep>from django.conf.urls import url, include
from . import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'categories', views.CategoryListView)
router.register(r'post', views.PostListView)
router.register(r'users', views.UserListView)
urlpatterns = [
url(r'api/', include(router.urls)),
url(r'index/', views.ArticleListView.as_view(), name='index')
]
<file_sep>from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
import json
class NotificationConsumer(WebsocketConsumer):
def connect(self):
self.group_name = 'homepage_users'
async_to_sync(self.channel_layer.group_add)(
self.group_name,
self.channel_name
)
self.accept()
def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)(
self.group_name,
self.channel_name
)
def add_post(self, event):
self.send(text_data=json.dumps({
'message': event['message']
}))
| 67e5957d686136e6cf573be11a218e493f282051 | [
"Python"
]
| 4 | Python | NedelkoA/articles_page | 300482ce35c0a4325739418e9814f8869d0a0cba | 522587598ffee53bc9828bca7f87f45cef0d4a7c |
refs/heads/master | <repo_name>dscache/Responsi5180411406<file_sep>/settings.gradle
include ':app'
rootProject.name='Responsi5180411406'
<file_sep>/app/src/main/java/com/dwisatria/responsi5180411406/dashboard.kt
package com.dwisatria.responsi5180411406
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class dashboard : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dashboard)
//get data from intent
val intent = intent
val email = intent.getStringExtra("email")
val password = intent.getStringExtra("<PASSWORD>")
//textview
val result = findViewById<TextView>(R.id.result)
//setText
result.text = "email : "+email+"\npassword : "+password
}
}<file_sep>/app/src/main/java/com/dwisatria/responsi5180411406/MainActivity.kt
package com.dwisatria.responsi5180411406
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONException
import java.io.IOException
class MainActivity : AppCompatActivity() {
val id:Int=1
val language:String = "toRegister"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val email = findViewById<EditText>(R.id.email)
val password = findViewById<EditText>(R.id.password)
val btnprologin = findViewById<Button>(R.id.btn_prologin)
btnprologin.setOnClickListener(){
val email = email.text.toString()
val password = <PASSWORD>.text.<PASSWORD>()
intent = Intent(this,dashboard::class.java)
intent.putExtra("email", email)
intent.putExtra("password", <PASSWORD>)
startActivity(intent)
}
btn_torgstr.setOnClickListener(){
intent = Intent(this,register::class.java)
intent.putExtra("id_value", id)
intent.putExtra("language_value", language)
startActivity(intent)
}
}
}
<file_sep>/app/src/main/java/com/dwisatria/responsi5180411406/previewRegister.kt
package com.dwisatria.responsi5180411406
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class previewRegister : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_preview)
//get data from intent
val intent = intent
val nama = intent.getStringExtra("nama")
val uname = intent.getStringExtra("uname")
val email = intent.getStringExtra("email")
val phone = intent.getStringExtra("phone")
val password = intent.getStringExtra("password")
//textview
val result = findViewById<TextView>(R.id.result)
//setText
result.text = "Nama : "+nama+"\nUsername : "+uname+"\nemail : "+email+"\nphone : "+phone+"\npassword : "+password
}
}<file_sep>/app/src/main/java/com/dwisatria/responsi5180411406/register.kt
package com.dwisatria.responsi5180411406
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_register.*
class register : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
val bundle:Bundle = intent.extras
val id = bundle.get("id_value")
val language = bundle.get("language_value")
Toast.makeText(applicationContext,id.toString()+""+language, Toast.LENGTH_LONG).show()
val nama = findViewById<EditText>(R.id.nama)
val uname = findViewById<EditText>(R.id.username)
val email = findViewById<EditText>(R.id.email)
val phone = findViewById<EditText>(R.id.phone)
val password = findViewById<EditText>(R.id.password)
val btnproses = findViewById<Button>(R.id.btn_proses)
//handle button click
btnproses.setOnClickListener {
//get text from edittexts
val nama = nama.text.toString()
val uname = uname.text.toString()
val email = email.text.toString()
val phone= phone.text.toString()
val password = password.text.toString()
//intent to start activity
val intent = Intent(this , previewRegister::class.java)
intent.putExtra("nama", nama)
intent.putExtra("uname", uname)
intent.putExtra("email", email)
intent.putExtra("phone", phone)
intent.putExtra("password", password)
startActivity(intent)
}
btn_back.setOnClickListener(){
intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
}
} | 2c14161a35127c7a14a18497ab39db0f28fe87b1 | [
"Kotlin",
"Gradle"
]
| 5 | Gradle | dscache/Responsi5180411406 | 9187b2de17338931bd4f9f154b66a13ce3179046 | af83d4a3975c9b118b0d5e59f8acf98bee931299 |
refs/heads/master | <repo_name>default-INT/StudentPerformanceService-WPF<file_sep>/StudentPerformanceServiceCL/Services/StudentFilterService.cs
using StudentPerformanceServiceCL.Models.Entities;
using StudentPerformanceServiceCL.Services.StudentFilters;
using StudentPerformanceServiceCL.Services.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Services
{
public class StudentFilterService
{
public IEnumerable<StudentViewModel> StudentViews { get; set; }
public IEnumerable<StudentViewModel> GetStudents(string facultyName = null, string specialtyName = null,
int? course = null, Session session = null)
{
var studentFilter = new StudentFilter();
studentFilter.SetDefaultData();
if (facultyName != null)
studentFilter = new FacultyStudentFilter(studentFilter, facultyName);
if (specialtyName != null)
studentFilter = new SpecialtyStudentFilter(studentFilter, specialtyName);
if (course != null)
studentFilter = new CourseStudentFilter(studentFilter, course.Value);
if (session != null)
studentFilter = new SessionStudentFilter(studentFilter, session);
StudentViews = studentFilter.Students;
return StudentViews;
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/IFacultyDAO.cs
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data
{
public interface IFacultyDAO
{
IEnumerable<Faculty> Faculties { get; }
void Add(Faculty faculty);
}
}
<file_sep>/StudentPerformanceServiceCL/Services/StudentFilters/CourseStudentFilter.cs
using StudentPerformanceServiceCL.Services.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Services.StudentFilters
{
internal class CourseStudentFilter : StudentFilterDecorator
{
private int course;
public CourseStudentFilter(StudentFilter studentFilter, int course) : base(studentFilter)
{
this.course = course;
}
public override IEnumerable<StudentViewModel> Students
{
get => studentFilter.Students
.Where(s => s.Course == course);
set => base.Students = value;
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/SubjectSpecialty.cs
using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities
{
[Table(Name = "subjects_specialties")]
internal class SubjectSpecialty : Entity
{
[Column(Name = "subject_id")]
public int SubjectId { get; set; }
[Column(Name = "specialty_id")]
public int SpecialtyId { get; set; }
public Subject subject;
public Specialty specialty;
public Subject Subject
{
get
{
if (subject != null) return subject;
subject = db.SubjectDAO.Subjects
.FirstOrDefault(s => s.Id == SubjectId);
return subject;
}
}
public Specialty Specialty
{
get
{
if (specialty != null) return specialty;
specialty = db.SpecialtyDAO.Specialties
.FirstOrDefault(s => s.Id == SpecialtyId);
return specialty;
}
}
}
}
<file_sep>/StudentPerformanceServiceWPF/Pages/AdminPages/AddGroupUserControl.xaml.cs
using StudentPerformanceServiceCL.Models.Data;
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace StudentPerformanceServiceWPF.Pages.AdminPages
{
/// <summary>
/// Логика взаимодействия для AddGroupUserControl.xaml
/// </summary>
public partial class AddGroupUserControl : UserControl
{
public AddGroupUserControl()
{
InitializeComponent();
ElementManager.Instance.ChangeTitleText("Добавление новой группы");
LoadSpecialties();
}
private async void LoadSpecialties()
{
IEnumerable<Specialty> specialties = null;
await Task.Run(() =>
{
var db = DAOFactory.GetDAOFactory();
specialties = db.SpecialtyDAO.Specialties;
});
specialtiesComboBox.Items.Clear();
foreach (var specialty in specialties)
{
specialtiesComboBox.Items.Add(specialty);
}
specialtiesComboBox.SelectedIndex = 0;
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
try
{
var name = nameTextBox.Text;
var semester = int.Parse(semesterTextBox.Text);
var specialty = (Specialty)specialtiesComboBox.SelectedItem;
var db = DAOFactory.GetDAOFactory();
db.GroupDAO.Add(new Group()
{
Name = name,
Semester = semester,
SpecialtyId = specialty.Id
});
nameTextBox.Text = string.Empty;
semesterTextBox.Text = string.Empty;
msgLabel.Content = "Группа успешно добавлена";
}
catch (Exception ex)
{
msgLabel.Content = ex.Message;
}
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Tests/Test.cs
using StudentPerformanceServiceCL.Models.Data;
using StudentPerformanceServiceCL.Models.Entities.Accounts;
using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities.Tests
{
/// <summary>
/// Общий класс для всех испытаний (курсовая, зачёт и экзамен).
/// </summary>
[Table(Name = "tests")]
[InheritanceMapping(Code = 0, IsDefault = true, Type = typeof(OffsetTest))]
[InheritanceMapping(Code = 1, Type = typeof(ExamTest))]
[InheritanceMapping(Code = 2, Type = typeof(CourseworkTest))]
public class Test : Entity, ICaster<Test>
{
[Column(Name = "date")]
public DateTime Date { get; set; }
[Column(Name = "subject_id")]
public int SubjectId { get; set; }
[Column(Name = "group_id")]
public int GroupId { get; set; }
[Column(Name = "type", IsDiscriminator = true)]
public int Type { get; set; }
[Column(Name = "semester")]
public int Semester { get; set; }
[Column(Name = "session_id")]
public int SessionId { get; set; }
private Subject subject;
private Group group;
private Session session;
public Test()
{
}
public Test(Test test)
{
Id = test.Id;
Date = test.Date;
SubjectId = test.SubjectId;
GroupId = test.GroupId;
Type = test.Type;
Semester = test.Semester;
SessionId = test.SessionId;
}
public Subject Subject
{
get
{
if (subject != null) return subject;
subject = db.SubjectDAO.Subjects
.FirstOrDefault(s => s.Id == SubjectId);
return subject;
}
}
public Group Group
{
get
{
if (group != null) return group;
group = db.GroupDAO.Groups
.FirstOrDefault(g => g.Id == GroupId);
return group;
}
}
public Session Session
{
get
{
if (session != null) return session;
session = db.SessionDAO.Sessions
.FirstOrDefault(s => s.Id == SessionId);
return session;
}
}
public IEnumerable<Student> Students
{
get
{
var groups = db.GroupDAO.Groups.Where(g => g.Semester == Semester);
IEnumerable<Student> students = new List<Student>(); ;
foreach (var group in groups)
{
students = students.Concat(group.Students);
}
return students;
}
}
public IEnumerable<TestResult> TestResults => db.TestDAO.TestResults
.Where(t => t.TestId == Id);
public virtual string TypeStr => throw new Exception("Test undefine");
public override string ToString() => TypeStr + " по " + Subject.Name + " " + Group.Name;
public Test Cast()
{
switch (Type)
{
case 0:
return new OffsetTest(this);
case 1:
return new ExamTest(this);
case 2:
return new CourseworkTest(this);
default:
throw new InvalidCastException();
}
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Tests/ExamTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities.Tests
{
/// <summary>
/// Класс описывающий испытание в виде экзамена.
/// </summary>
public class ExamTest : Test
{
public ExamTest()
{
Type = 1;
}
public ExamTest(Test test) : base(test)
{
Type = 1;
}
public override string TypeStr => "Экзамен";
}
}
<file_sep>/DbGenerator.sql
CREATE DATABASE student_performance_service;
CREATE TABLE faculties (
id serial primary key not null ,
name text not null unique
);
CREATE TABLE specialties (
id serial primary key not null ,
name text not null ,
faculty_id int not null,
foreign key (faculty_id) references faculties (id)
);
CREATE TABLE groups (
id serial primary key not null ,
name text not null ,
semester int not null ,
specialty_id int not null,
foreign key (specialty_id) references specialties (id)
);
CREATE TABLE accounts (
id serial primary key not null ,
login text not null unique ,
password text not null ,
full_name text not null ,
role int not null ,
group_id int,
foreign key (group_id) references groups (id)
);
CREATE TABLE subjects (
id serial primary key not null ,
name text not null ,
teacher text not null
);
CREATE TABLE subjects_specialties (
id serial primary key not null ,
subject_id int not null ,
specialty_id int not null ,
foreign key (subject_id) references subjects (id),
foreign key (specialty_id) references specialties (id)
);
CREATE TABLE sessions (
id serial primary key not null ,
year int not null ,
season boolean
);
CREATE TABLE tests (
id serial primary key not null ,
date date not null ,
subject_id int not null ,
group_id int not null ,
type int not null ,
semester int not null,
session_id int not null ,
foreign key (subject_id) references subjects (id),
foreign key (group_id) references groups (id),
foreign key (session_id) references sessions (id)
);
CREATE TABLE test_results (
id serial primary key not null ,
test_id int not null ,
student_id int not null ,
completion_date date not null ,
mark int not null ,
attempts_number int not null ,
foreign key (test_id) references tests (id),
foreign key (student_id) references accounts (id)
);
INSERT INTO accounts(login, password, full_name, role) VALUES ('admin', 'a1806', 'Семуткин А.А.', 0);
INSERT INTO accounts(login, password, full_name, role) VALUES ('methodist', 'm1806', 'Липский Д.Ю.', 1);
INSERT INTO faculties(name) VALUES ('ФАИС');
INSERT INTO faculties(name) VALUES ('ЭФ');
INSERT INTO faculties(name) VALUES ('ГЭФ');
INSERT INTO specialties(name, faculty_id) VALUES ('Информационные системы и технологии (в производстве)', 1);
INSERT INTO specialties(name, faculty_id) VALUES ('Информационные системы и технологии (в игровой индустрии)', 1);
INSERT INTO specialties(name, faculty_id) VALUES ('Энергетические системы и сети', 2);
INSERT INTO specialties(name, faculty_id) VALUES ('Элекстроснабжение', 2);
INSERT INTO specialties(name, faculty_id) VALUES ('Экономика и управление на предприятии', 3);
INSERT INTO specialties(name, faculty_id) VALUES ('Менеджмент', 3);
INSERT INTO groups (name, semester, specialty_id) VALUES ('ИТП-21', 4, 1);
INSERT INTO groups (name, semester, specialty_id) VALUES ('ИТИ-21', 4, 2);
INSERT INTO groups (name, semester, specialty_id) VALUES ('ЭС-31', 6, 3);
INSERT INTO groups (name, semester, specialty_id) VALUES ('ЭН-31', 6, 4);
INSERT INTO groups (name, semester, specialty_id) VALUES ('ЭП-11', 2, 5);
INSERT INTO groups (name, semester, specialty_id) VALUES ('М-11', 2, 6);
INSERT INTO accounts(login, password, full_name, role, group_id) VALUES ('ropot', 's1806', 'Ропот И.В.', 2, 1);
INSERT INTO accounts(login, password, full_name, role, group_id) VALUES ('solod', 's1806', 'Солодков М.А.', 2, 2);
INSERT INTO accounts(login, password, full_name, role, group_id) VALUES ('dekker', 's1806', '<NAME>.В.', 2, 1);
INSERT INTO accounts(login, password, full_name, role, group_id) VALUES ('stolny', 's1806', 'Стольный Д.С.', 2, 2);
INSERT INTO accounts(login, password, full_name, role, group_id) VALUES ('sema', 's1806', 'Семёнов Д.С.', 2, 1);
INSERT INTO subjects(name, teacher) VALUES ('Высшая математика', 'Авакян Е.З.');
INSERT INTO subjects(name, teacher) VALUES ('ООП', 'Курочка К.С.');
INSERT INTO subjects(name, teacher) VALUES ('Компьютерные сети', 'Курочка К.С.');
INSERT INTO subjects_specialties (subject_id, specialty_id) VALUES (2, 1);
INSERT INTO subjects_specialties (subject_id, specialty_id) VALUES (2, 2);
INSERT INTO sessions(year, season) VALUES (2020, true);
INSERT INTO tests(date, subject_id, group_id, type, semester, session_id) VALUES ('2020-06-18', 2, 1, 2, 4, 1);
INSERT INTO tests(date, subject_id, group_id, type, semester, session_id) VALUES ('2020-06-20', 2, 2, 2, 4, 1);
INSERT INTO tests(date, subject_id, group_id, type, semester, session_id) VALUES ('2020-06-24', 2, 1, 1, 4, 1);
INSERT INTO tests(date, subject_id, group_id, type, semester, session_id) VALUES ('2020-06-26', 2, 2, 1, 4, 1);
INSERT INTO tests(date, subject_id, group_id, type, semester, session_id) VALUES ('2020-06-15', 1, 1, 0, 4, 1);
INSERT INTO tests(date, subject_id, group_id, type, semester, session_id) VALUES ('2020-06-17', 1, 2, 0, 4, 1);
INSERT INTO tests(date, subject_id, group_id, type, semester, session_id) VALUES ('2020-06-26', 3, 1, 1, 4, 1);
INSERT INTO tests(date, subject_id, group_id, type, semester, session_id) VALUES ('2020-06-24', 3, 2, 1, 4, 1);
<file_sep>/StudentPerformanceServiceCL/Services/UserService.cs
using StudentPerformanceServiceCL.Models.Entities.Accounts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Services
{
public class UserService
{
private static UserService instance;
private UserService() { }
public static UserService Instance
{
get
{
if (instance != null) return instance;
instance = new UserService();
return instance;
}
}
public Account Account { get; set; }
public void LogOut()
{
Account = null;
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/PostgreDAO/PgDAOFactory.cs
using DbLinq.Data.Linq;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data.PostgreDAO
{
internal class PgDAOFactory : DAOFactory
{
private const string ConnectionString = @"Server=localhost;Port=5432;Database=student_performance_service;User Id=postgres;" +
"Password=<PASSWORD>;Integrated Security=true;";
private readonly StudentPerformanceServiceContext _context;
internal PgDAOFactory()
{
var connection = new NpgsqlConnection(ConnectionString);
_context = new StudentPerformanceServiceContext(connection);
}
public override IAccountDAO AccountDAO => new PgAccountDAO(_context);
public override IFacultyDAO FacultyDAO => new PgFacultyDAO(_context);
public override IGroupDAO GroupDAO => new PgGroupDAO(_context);
public override ISpecialtyDAO SpecialtyDAO => new PgSpecialtyDAO(_context);
public override ISubjectDAO SubjectDAO => new PgSubjectDAO(_context);
public override ITestDAO TestDAO => new PgTestDAO(_context);
public override ISessionDAO SessionDAO => new PgSessionDAO(_context);
internal override ISubjectSpecialtyDAO SubjectSpecialtyDAO => new PgSubjectSpecialtyDAO(_context);
}
}
<file_sep>/StudentPerformanceServiceWPF/Pages/AdminPages/ReportOnSpecialtiesUserControl.xaml.cs
using Microsoft.Win32;
using StudentPerformanceServiceCL.Models.Data;
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
namespace StudentPerformanceServiceWPF.Pages.AdminPages
{
/// <summary>
/// Логика взаимодействия для ReportOnSpecialtiesUserControl.xaml
/// </summary>
public partial class ReportOnSpecialtiesUserControl : UserControl
{
private IEnumerable<SpecialtyView> specialtyViews;
public ReportOnSpecialtiesUserControl()
{
InitializeComponent();
ElementManager.Instance.ChangeTitleText("Отчёт по специальностям");
LoadData();
}
private async void LoadData()
{
await Task.Run(() =>
{
var db = DAOFactory.GetDAOFactory();
specialtyViews = db.SpecialtyDAO.Specialties
.Select(s => new SpecialtyView()
{
Id = s.Id,
SpecialtyName = s.Name,
EasySubject = s.EasySubject != null ? s.EasySubject.Name : "Не определён",
HardSubject = s.HardSubject != null ? s.HardSubject.Name : "Не определён",
Specialty = s
});
});
dataGrid.Items.Clear();
foreach (var specialty in specialtyViews)
{
dataGrid.Items.Add(specialty);
}
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "XML файл(*.xml)|*.xml|Все файлы(*.*)|*.*";
try
{
saveFileDialog.ShowDialog();
string filename = saveFileDialog.FileName;
SaveToXML(filename);
MessageBox.Show("Файл успешно сохранён.");
}
catch (Exception ex)
{
MessageBox.Show("Не удалось сохранить файл. " + ex.Message);
}
}
private void SaveToXML(string path)
{
XDocument xDoc = new XDocument();
XElement root = new XElement("reports");
foreach (var specialty in specialtyViews)
{
root.Add(new XElement("specialty",
new XElement("id", specialty.Id),
new XElement("name", specialty.SpecialtyName),
new XElement("easySubject", specialty.EasySubject),
new XElement("hardSubject", specialty.HardSubject)
));
}
xDoc.Add(root);
xDoc.Save(path);
}
private class SpecialtyView
{
public int Id { get; set; }
public string SpecialtyName { get; set; }
public string EasySubject { get; set; }
public string HardSubject { get; set; }
public Specialty Specialty { get; set; }
}
}
}
<file_sep>/StudentPerformanceServiceWPF/Pages/MethodistDeaneryPages/MethodistDeaneryUserControl.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace StudentPerformanceServiceWPF.Pages.MethodistDeaneryPages
{
/// <summary>
/// Логика взаимодействия для MethodistDeaneryUserControl.xaml
/// </summary>
public partial class MethodistDeaneryUserControl : UserControl
{
private readonly ElementManager elementManager;
public MethodistDeaneryUserControl()
{
InitializeComponent();
elementManager = ElementManager.Instance;
addTestButton.Click += (s, e) => elementManager.SetContent(new AddTestUserControl());
certifyStudentButton.Click += (s, e) => elementManager.SetContent(new CertifyUserControl());
}
}
}
<file_sep>/StudentPerformanceServiceWPF/LogInWindow.xaml.cs
using StudentPerformanceServiceCL.Models.Data;
using StudentPerformanceServiceCL.Models.Entities.Accounts;
using StudentPerformanceServiceCL.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace StudentPerformanceServiceWPF
{
/// <summary>
/// Логика взаимодействия для LogInWindow.xaml
/// </summary>
public partial class LogInWindow : Window
{
public LogInWindow()
{
InitializeComponent();
}
private async void LogInButton_Click(object sender, RoutedEventArgs e)
{
try
{
msgLable.Content = "Идёт получение данных...";
var login = loginTextBox.Text;
var password = <PASSWORD>;
Account user = null;
await Task.Run(() =>
{
var db = DAOFactory.GetDAOFactory();
user = db.AccountDAO.LogIn(login, password);
});
if (user == null) throw new Exception("Неверный логин или пароль");
var userService = UserService.Instance;
userService.Account = user;
loginTextBox.Text = string.Empty;
passwordTextBox.Password = string.Empty;
msgLable.Content = "Добро пожаловать, " + user.FullName;
Close();
}
catch (Exception ex)
{
msgLable.Content = ex.Message;
}
}
}
}
<file_sep>/StudentPerformanceServiceUT/SubjectUnitTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StudentPerformanceServiceCL.Models.Data;
namespace StudentPerformanceServiceUT
{
[TestClass]
public class SubjectUnitTest
{
private readonly DAOFactory db;
public SubjectUnitTest()
{
db = DAOFactory.GetDAOFactory();
}
[TestMethod]
public void Subjects_GetFormDB()
{
var subjects = db.SubjectDAO.Subjects;
foreach (var subject in subjects)
{
Console.WriteLine(subject);
}
Assert.IsNotNull(subjects);
}
[TestMethod]
public void Subjects_GetNavigatePropertiesFormDB()
{
var subjects = db.SubjectDAO.Subjects;
foreach (var subject in subjects)
{
Console.WriteLine(subject.Specialties);
}
Assert.IsNotNull(subjects);
}
}
}
<file_sep>/StudentPerformanceServiceWPF/Pages/AdminPages/AddSubjectUserControl.xaml.cs
using StudentPerformanceServiceCL.Models.Data;
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace StudentPerformanceServiceWPF.Pages.AdminPages
{
/// <summary>
/// Логика взаимодействия для AddSubjectUserControl.xaml
/// </summary>
public partial class AddSubjectUserControl : UserControl
{
public AddSubjectUserControl()
{
InitializeComponent();
ElementManager.Instance.ChangeTitleText("Добавление новой дисциплины");
LoadSpecialties();
}
private async void LoadSpecialties()
{
IEnumerable<Specialty> specialties = null;
await Task.Run(() =>
{
var db = DAOFactory.GetDAOFactory();
specialties = db.SpecialtyDAO.Specialties;
});
specialtiesComboBox.Items.Clear();
foreach (var specialty in specialties)
{
specialtiesComboBox.Items.Add(specialty);
}
specialtiesComboBox.SelectedIndex = 0;
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
try
{
var name = nameTextBox.Text;
var teacher = teacherFullNameTextBox.Text;
var specialty = (Specialty)specialtiesComboBox.SelectedValue;
var db = DAOFactory.GetDAOFactory();
db.SubjectDAO.Add(new Subject()
{
Name = name,
Teacher = teacher
}, specialty);
nameTextBox.Text = string.Empty;
teacherFullNameTextBox.Text = string.Empty;
msgLabel.Content = "Дисциплина успешно добавлена";
}
catch (Exception ex)
{
msgLabel.Content = ex.Message;
}
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/PostgreDAO/PgFacultyDAO.cs
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data.PostgreDAO
{
internal class PgFacultyDAO : IFacultyDAO
{
private readonly StudentPerformanceServiceContext _context;
public PgFacultyDAO(StudentPerformanceServiceContext context)
{
_context = context;
}
public IEnumerable<Faculty> Faculties => _context.Faculties;
public void Add(Faculty faculty)
{
_context.Faculties.InsertOnSubmit(faculty);
_context.SubmitChanges();
}
}
}
<file_sep>/StudentPerformanceServiceCL/Services/StudentFilters/SpecialtyStudentFilter.cs
using StudentPerformanceServiceCL.Services.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Services.StudentFilters
{
internal class SpecialtyStudentFilter : StudentFilterDecorator
{
private string specialtyName;
public SpecialtyStudentFilter(StudentFilter studentFilter, string specialty) : base(studentFilter)
{
this.specialtyName = specialty;
}
public override IEnumerable<StudentViewModel> Students
{
get => studentFilter.Students
.Where(s => s.Group.Specialty.Name == specialtyName);
set => base.Students = value;
}
}
}
<file_sep>/StudentPerformanceServiceUT/GroupUnitTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StudentPerformanceServiceCL.Models.Data;
namespace StudentPerformanceServiceUT
{
[TestClass]
public class GroupUnitTest
{
private readonly DAOFactory db;
public GroupUnitTest()
{
db = DAOFactory.GetDAOFactory();
}
[TestMethod]
public void Groups_GetFromDB()
{
var groups = db.GroupDAO.Groups;
foreach (var group in groups)
{
Console.WriteLine(group);
}
Assert.IsNotNull(groups);
}
[TestMethod]
public void Groups_GetNavigatePropertysFromDB()
{
var groups = db.GroupDAO.Groups;
foreach (var group in groups)
{
Console.WriteLine(group.Specialty);
Console.WriteLine(group.Students);
}
Assert.IsNotNull(groups);
}
}
}
<file_sep>/StudentPerformanceServiceWPF/MainWindow.xaml.cs
using StudentPerformanceServiceCL.Models.Entities.Accounts;
using StudentPerformanceServiceCL.Services;
using StudentPerformanceServiceWPF.Pages.AdminPages;
using StudentPerformanceServiceWPF.Pages.MethodistDeaneryPages;
using StudentPerformanceServiceWPF.Pages.StudentPages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace StudentPerformanceServiceWPF
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly ElementManager elementManager;
private readonly UserService userService;
public MainWindow()
{
InitializeComponent();
userService = UserService.Instance;
elementManager = ElementManager.Instance;
(new LogInWindow()).ShowDialog();
elementManager = ElementManager.SetInstance(mainContent, menuButtonContent, titleLabel);
SetButtonMenu();
}
private void SetButtonMenu()
{
try
{
var authUser = userService.Account;
statusMenuItem.Header = authUser.Status;
fullNameMenuItem.Header = authUser.FullName;
elementManager.SetContent(new UserControl());
if (authUser is Admin)
{
elementManager.SetButtonMenu(new AdminButtonsUserControl());
}
else if (authUser is MethodistDeanery)
{
elementManager.SetButtonMenu(new MethodistDeaneryUserControl());
}
else if (authUser is Student)
{
elementManager.SetButtonMenu(new StudentUserControl());
}
else throw new Exception("User undefined");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Close();
}
}
private void ExitMenuItem_Click(object sender, RoutedEventArgs e)
{
userService.LogOut();
Hide();
(new LogInWindow()).ShowDialog();
Show();
SetButtonMenu();
}
}
}
<file_sep>/StudentPerformanceServiceWPF/Pages/AdminPages/AdminButtonsUserControl.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace StudentPerformanceServiceWPF.Pages.AdminPages
{
/// <summary>
/// Логика взаимодействия для AdminButtonsUserControl.xaml
/// </summary>
public partial class AdminButtonsUserControl : UserControl
{
private readonly ElementManager elementManager;
public AdminButtonsUserControl()
{
InitializeComponent();
elementManager = ElementManager.Instance;
}
private void AddUserButton_Click(object sender, RoutedEventArgs e)
{
elementManager.SetContent(new AddUserUserControl());
}
private void SessionAddButton_Click(object sender, RoutedEventArgs e)
{
elementManager.SetContent(new AddSessionUserControl());
}
private void SubjectAddButton_Click(object sender, RoutedEventArgs e)
{
elementManager.SetContent(new AddSubjectUserControl());
}
private void GroupAddButton_Click(object sender, RoutedEventArgs e)
{
elementManager.SetContent(new AddGroupUserControl());
}
private void StudentReportButton_Click(object sender, RoutedEventArgs e)
{
elementManager.SetContent(new ReportOnStudentUserControl());
}
private void ReportOnSpecialtyButton_Click(object sender, RoutedEventArgs e)
{
elementManager.SetContent(new ReportOnSpecialtiesUserControl());
}
private void ReportStudentPerformanceButton_Click(object sender, RoutedEventArgs e)
{
elementManager.SetContent(new ReportStudentPerformanceUserControl());
}
}
}
<file_sep>/StudentPerformanceServiceUT/FacultyUnitTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StudentPerformanceServiceCL.Models.Data;
namespace StudentPerformanceServiceUT
{
[TestClass]
public class FacultyUnitTest
{
private readonly DAOFactory db;
public FacultyUnitTest()
{
db = DAOFactory.GetDAOFactory();
}
[TestMethod]
public void Faculties_GetFromDB()
{
var faculties = db.FacultyDAO.Faculties;
foreach (var faculty in faculties)
{
Console.WriteLine(faculty);
}
Assert.IsNotNull(faculties);
}
[TestMethod]
public void Faculties_GetNavigatePropertiesFromDB()
{
var faculties = db.FacultyDAO.Faculties;
foreach (var faculty in faculties)
{
Console.WriteLine(faculty.Specialties);
}
Assert.IsNotNull(faculties);
}
}
}
<file_sep>/StudentPerformanceServiceWPF/Pages/AdminPages/AddSessionUserControl.xaml.cs
using StudentPerformanceServiceCL.Models.Data;
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace StudentPerformanceServiceWPF.Pages.AdminPages
{
/// <summary>
/// Логика взаимодействия для AddSessionUserControl.xaml
/// </summary>
public partial class AddSessionUserControl : UserControl
{
public AddSessionUserControl()
{
InitializeComponent();
ElementManager.Instance.ChangeTitleText("Назначение сессии");
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
try
{
var year = int.Parse(yearTextBox.Text);
var season = summerRadioButton.IsChecked.Value;
var db = DAOFactory.GetDAOFactory();
db.SessionDAO.Add(new Session()
{
Year = year,
Season = season
});
yearTextBox.Text = string.Empty;
msgLabel.Content = "Сессия успешно добавлена";
}
catch (Exception ex)
{
msgLabel.Content = ex.Message;
}
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/PostgreDAO/PgGroupDAO.cs
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data.PostgreDAO
{
internal class PgGroupDAO : IGroupDAO
{
private readonly StudentPerformanceServiceContext _context;
public PgGroupDAO(StudentPerformanceServiceContext context)
{
_context = context;
}
public IEnumerable<Group> Groups => _context.Groups;
public void Add(Group group)
{
_context.Groups.InsertOnSubmit(group);
_context.SubmitChanges();
}
public void Update(Group group)
{
var updateGroup = _context.Groups.FirstOrDefault(g => g.Id == group.Id);
updateGroup.Name = group.Name;
updateGroup.Semester = group.Semester;
updateGroup.SpecialtyId = group.SpecialtyId;
_context.SubmitChanges();
}
}
}
<file_sep>/StudentPerformanceServiceUT/SpecialtyUnitTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StudentPerformanceServiceCL.Models.Data;
namespace StudentPerformanceServiceUT
{
[TestClass]
public class SpecialtyUnitTest
{
private readonly DAOFactory db;
public SpecialtyUnitTest()
{
db = DAOFactory.GetDAOFactory();
}
[TestMethod]
public void Specialties_GetFormDB()
{
var specialties = db.SpecialtyDAO.Specialties;
foreach (var spec in specialties)
{
Console.WriteLine(spec);
}
Assert.IsNotNull(specialties);
}
[TestMethod]
public void Specialties_GetNavigatePropertiesFormDB()
{
var specialties = db.SpecialtyDAO.Specialties;
foreach (var spec in specialties)
{
Console.WriteLine(spec.Faculty);
Console.WriteLine(spec.Students);
Console.WriteLine(spec.Subjects);
}
Assert.IsNotNull(specialties);
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Accounts/Student.cs
using StudentPerformanceServiceCL.Models.Data;
using StudentPerformanceServiceCL.Models.Entities.Tests;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities.Accounts
{
/// <summary>
/// Класс описывающий студента определённого курса по определённой специальности.
/// </summary>
public class Student : Account
{
public int GroupId
{
get => __groupId.Value;
set => __groupId = value;
}
private Group group;
public override string Status => "Студент";
public Student()
{
Role = 2;
}
public Student(Account account) : base(account)
{
Role = 2;
}
public Group Group
{
get
{
if (group != null) return group;
group = db.GroupDAO.Groups
.FirstOrDefault(g => g.Id == GroupId);
return group;
}
}
public int? Course => Convert.ToInt32(Math.Round((double) Group.Semester / 2));
public IEnumerable<TestResult> TestResults
{
get => db.TestDAO.TestResults
.Where(t => t.StudentId == Id);
}
public override string ToString() => FullName + " " + Group.Name;
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Accounts/MethodistDeanery.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities.Accounts
{
public class MethodistDeanery : Account
{
public int FacultyId
{
get => __facultyId.Value;
set => __facultyId = value;
}
public MethodistDeanery()
{
Role = 1;
}
public MethodistDeanery(Account account) : base(account)
{
Role = 1;
}
public override string Status => "Методист деканата";
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Accounts/Account.cs
using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities.Accounts
{
[Table(Name = "accounts")]
[InheritanceMapping(Code = 0, Type = typeof(Admin))]
[InheritanceMapping(Code = 1, Type = typeof(MethodistDeanery))]
[InheritanceMapping(Code = 2, Type = typeof(Student), IsDefault = true)]
public class Account : Entity, ICaster<Account>
{
public Account()
{
}
public Account(Account account)
{
Id = account.Id;
Login = account.Login;
Password = <PASSWORD>.Password;
FullName = account.FullName;
Role = account.Role;
__groupId = account.__groupId;
__facultyId = account.__facultyId;
}
[Column(Name = "login")]
public string Login { get; set; }
[Column(Name = "password")]
public string Password { get; set; }
[Column(Name = "full_name")]
public string FullName { get; set; }
[Column(Name = "role", IsDiscriminator = true)]
public int Role { get; set; }
[Column(Name = "group_id")]
public int? __groupId { get; set; }
[Column(Name = "faculty_id")]
public int? __facultyId { get; set; }
public virtual string Status => throw new Exception("Account undefined!");
public Account Cast()
{
switch (Role)
{
case 0:
return new Admin(this);
case 1:
return new MethodistDeanery(this);
case 2:
return new Student(this);
default:
throw new InvalidCastException();
}
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Subject.cs
using StudentPerformanceServiceCL.Models.Entities.Tests;
using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities
{
/// <summary>
/// Класс описывает дисциплину / предмет.
/// </summary>
[Table(Name = "subjects")]
public class Subject : Entity
{
[Column(Name = "name")]
public string Name { get; set; }
[Column(Name = "teacher")]
public string Teacher { get; set; }
public IEnumerable<Test> Tests => db.TestDAO.Tests
.Where(t => t.SubjectId == Id);
public IEnumerable<TestResult> TestResults
{
get
{
IEnumerable<TestResult> outTestResults = new List<TestResult>();
foreach (var testResults in Tests.Select(t => t.TestResults))
{
outTestResults = outTestResults.Concat(testResults.ToList());
}
return outTestResults;
}
}
public IEnumerable<Specialty> Specialties => db.SubjectSpecialtyDAO.SubjectSpecialties
.Where(s => s.SubjectId == Id)
.Select(s => s.Specialty);
public IEnumerable<Group> Groups
{
get
{
IEnumerable<Group> outGroups = new List<Group>();
foreach (var groups in Specialties.Select(s => s.Groups))
{
outGroups = outGroups.Concat(groups);
}
return outGroups;
}
}
public override string ToString() => Name;
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/DAOFactory.cs
using StudentPerformanceServiceCL.Models.Data.PostgreDAO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data
{
public abstract class DAOFactory
{
public abstract IAccountDAO AccountDAO { get; }
public abstract IFacultyDAO FacultyDAO { get; }
public abstract IGroupDAO GroupDAO { get; }
public abstract ISpecialtyDAO SpecialtyDAO { get; }
public abstract ISubjectDAO SubjectDAO { get; }
public abstract ITestDAO TestDAO { get; }
public abstract ISessionDAO SessionDAO { get; }
internal abstract ISubjectSpecialtyDAO SubjectSpecialtyDAO { get; }
public static DAOFactory GetDAOFactory(Database database = Database.PostgreSQL)
{
switch (database)
{
case Database.PostgreSQL:
return new PgDAOFactory();
default: return null;
}
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Specialty.cs
using StudentPerformanceServiceCL.Models.Data;
using StudentPerformanceServiceCL.Models.Entities.Accounts;
using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities
{
/// <summary>
/// Класс описывающий специальность факультета.
/// </summary>
[Table(Name = "specialties")]
public class Specialty : Entity
{
[Column(Name = "name")]
public string Name { get; set; }
[Column(Name = "faculty_id")]
public int FacultyId { get; set; }
public Subject HardSubject => Subjects
.ToList()
.Where(s => s.TestResults.Count() != 0)
.OrderBy(s => s.TestResults.Average(t => t.Mark))
.FirstOrDefault();
public Subject EasySubject => Subjects
.ToList()
.Where(s => s.TestResults.Count() != 0)
.OrderByDescending(s => s.TestResults.Average(t => t.Mark))
.FirstOrDefault();
public Faculty Faculty => db.FacultyDAO.Faculties
.FirstOrDefault(f => f.Id == FacultyId);
public IEnumerable<Subject> Subjects => db.SubjectSpecialtyDAO.SubjectSpecialties
.Where(s => s.SpecialtyId == Id)
.Select(s => s.Subject);
public IEnumerable<Student> Students => db.AccountDAO.Students
.Where(s => s.Group.SpecialtyId == Id);
public IEnumerable<Group> Groups => db.GroupDAO.Groups
.Where(g => g.SpecialtyId == Id);
public override string ToString() => Name;
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/Database.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data
{
public enum Database
{
PostgreSQL
}
}
<file_sep>/README.md
# Курсовой проект StudentPerformanceService-WPF по дисциплине "ООП"
Проект выполнен на языке программирования C# и представляет собой десктопное приложение с обращением к безе данных.
***
Используемые технологии:
* WPF
* PostgreSQL
* LINQ, LINQ to DB
* Material Design для WPF
***
Приложение реализовано по архитектурному паттерну MVC, где модель данных и контроллеры хранятся в библиотеке классов, что позволяет избежать
связывания с графическим интерфейсом.
***
Было проведено интегрированое и модульное тестирования приложения.
***
Для генерации базы данных требуется выполнить скрипт _DbGenerator.sql_ в СУБД PostgerSQL.
<file_sep>/StudentPerformanceServiceWPF/Pages/AdminPages/AddUserUserControl.xaml.cs
using StudentPerformanceServiceCL.Models.Data;
using StudentPerformanceServiceCL.Models.Entities;
using StudentPerformanceServiceCL.Models.Entities.Accounts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Group = StudentPerformanceServiceCL.Models.Entities.Group;
namespace StudentPerformanceServiceWPF.Pages.AdminPages
{
/// <summary>
/// Логика взаимодействия для AddUserUserControl.xaml
/// </summary>
public partial class AddUserUserControl : UserControl
{
private const string PatternLogin = "[A-z0-9]{4,12}";
private const string PatternPassword = "[<PASSWORD>}";
private const string PatternFullName = "[А-я\\s]{4,20}";
public AddUserUserControl()
{
InitializeComponent();
ElementManager.Instance.ChangeTitleText("Добавление пользователя");
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
try
{
if (!ValidationData()) throw new Exception("Введённые данные имеют неверный формат!");
var login = loginTextBox.Text;
var password = passwordTextBox.Password == <PASSWORD>RetryTextBox.Password ? passwordTextBox.Password
: throw new Exception("Пароли не совпадают!");
var fullName = fullNameTextBox.Text;
var db = DAOFactory.GetDAOFactory();
switch (roleComboBox.SelectedIndex)
{
case 0:
var faculty = (Faculty)facultyGroupComboBox.SelectedItem;
db.AccountDAO.Add(new MethodistDeanery()
{
Login = login,
Password = <PASSWORD>,
FullName = fullName,
FacultyId = faculty.Id
});
break;
case 1:
var group = (Group)facultyGroupComboBox.SelectedItem;
db.AccountDAO.Add(new Student()
{
Login = login,
Password = <PASSWORD>,
FullName = fullName,
GroupId = group.Id
});
break;
default:
throw new Exception("Выбран несуществующий тип аккаунта!");
}
loginTextBox.Text = string.Empty;
passwordTextBox.Password = string.Empty;
passwordRetryTextBox.Password = string.Empty;
fullNameTextBox.Text = string.Empty;
msgLabel.Content = "Пользователь успешно добавлен в систему";
}
catch (Exception ex)
{
msgLabel.Content = ex.Message;
}
}
private bool ValidationData() => Regex.IsMatch(loginTextBox.Text, PatternLogin)
&& Regex.IsMatch(passwordTextBox.Password, PatternPassword)
&& Regex.IsMatch(fullNameTextBox.Text, PatternFullName);
private async void RoleComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
ComboBox comboBox = (ComboBox)sender;
IEnumerable<Entity> entities = null;
switch (comboBox.SelectedIndex)
{
case 0:
if (facultyGroupLabel != null) facultyGroupLabel.Content = "Выберите факультет:";
await Task.Run(() =>
{
var db = DAOFactory.GetDAOFactory();
entities = db.FacultyDAO.Faculties;
});
break;
case 1:
if (facultyGroupLabel != null) facultyGroupLabel.Content = "Выберите группу:";
await Task.Run(() =>
{
var db = DAOFactory.GetDAOFactory();
entities = db.GroupDAO.Groups;
});
break;
default:
throw new Exception("Не удалось загрузить данные....");
}
facultyGroupComboBox.Items.Clear();
foreach (var entity in entities)
{
facultyGroupComboBox.Items.Add(entity);
}
}
catch (Exception ex)
{
msgLabel.Content = ex.Message;
}
}
}
}
<file_sep>/StudentPerformanceServiceWPF/Pages/MethodistDeaneryPages/CertifyUserControl.xaml.cs
using StudentPerformanceServiceCL.Models.Data;
using StudentPerformanceServiceCL.Models.Entities.Accounts;
using StudentPerformanceServiceCL.Models.Entities.Tests;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace StudentPerformanceServiceWPF.Pages.MethodistDeaneryPages
{
/// <summary>
/// Логика взаимодействия для CertifyUserControl.xaml
/// </summary>
public partial class CertifyUserControl : UserControl
{
private Test selectedTest;
public CertifyUserControl()
{
InitializeComponent();
ElementManager.Instance.ChangeTitleText("Добавление аттестации студенту");
LoadTest();
testComboBox.SelectionChanged += (s, e) =>
{
var comboBox = (ComboBox)s;
selectedTest = (Test)comboBox.SelectedItem;
LoadStudents();
};
}
private async void LoadTest()
{
IEnumerable<Test> tests = null;
await Task.Run(() =>
{
var db = DAOFactory.GetDAOFactory();
tests = db.TestDAO.Tests;
});
testComboBox.Items.Clear();
foreach (var test in tests)
{
testComboBox.Items.Add(test);
}
}
private async void LoadStudents()
{
IEnumerable<Student> students = null;
await Task.Run(() => students = selectedTest.Group.Students
.Where(s => s.TestResults.FirstOrDefault(t => t.TestId == selectedTest.Id) == null));
await Task.Run(() =>
{
var db = DAOFactory.GetDAOFactory();
var retakeStudents = db.TestDAO.TestResults
.Where(t => t.Retake)
.Select(t => t.Student);
students = students.Concat(retakeStudents);
});
studentComboBox.Items.Clear();
foreach (var student in students)
{
studentComboBox.Items.Add(student);
}
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
try
{
var student = (Student)studentComboBox.SelectedItem;
var selectedDate = datePicker.SelectedDate.Value;
var mark = int.Parse((string)((ComboBoxItem)markComboBox.SelectedItem).Content);
var db = DAOFactory.GetDAOFactory();
db.TestDAO.Add(new TestResult()
{
TestId = selectedTest.Id,
StudentId = student.Id,
CompletionDate = selectedDate,
Mark = mark
});
msgLabel.Content = "Студент " + student.FullName + " успешно аттестован";
}
catch (Exception ex)
{
msgLabel.Content = ex.Message;
}
}
}
}
<file_sep>/StudentPerformanceServiceUT/QuestTestUnitTest.cs
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StudentPerformanceServiceCL.Models.Data;
namespace StudentPerformanceServiceUT
{
[TestClass]
public class QuestTestUnitTest
{
private readonly DAOFactory db;
public QuestTestUnitTest()
{
db = DAOFactory.GetDAOFactory();
}
[TestMethod]
public void Tests_GetFromDB()
{
var tests = db.TestDAO.Tests;
foreach (var test in tests)
{
Console.WriteLine(test);
}
Assert.IsNotNull(tests);
}
[TestMethod]
public void ExamTests_GetFromDB()
{
var tests = db.TestDAO.ExamTests;
foreach (var test in tests)
{
Console.WriteLine(test);
}
Assert.IsNotNull(tests);
}
[TestMethod]
public void OffsetTests_GetFromDB()
{
var tests = db.TestDAO.OffsetTests;
foreach (var test in tests)
{
Console.WriteLine(test);
}
Assert.IsNotNull(tests);
}
[TestMethod]
public void CourseworkTests_GetFromDB()
{
var tests = db.TestDAO.CourseworkTests;
foreach (var test in tests)
{
Console.WriteLine(test);
}
Assert.IsNotNull(tests);
}
[TestMethod]
public void Test_GroupGetFromDB()
{
var test = db.TestDAO.Tests.First();
Console.WriteLine(test.Group);
Assert.IsNotNull(test.Group);
}
[TestMethod]
public void Test_SubjectGetFromDB()
{
var test = db.TestDAO.Tests.First();
Console.WriteLine(test.Subject);
Assert.IsNotNull(test.Subject);
}
[TestMethod]
public void Test_StudentsGetFromDB()
{
var test = db.TestDAO.Tests.First();
Console.WriteLine(test.Students);
Assert.IsNotNull(test.Students);
}
[TestMethod]
public void Test_SessionGetFromDB()
{
var test = db.TestDAO.Tests.First();
Console.WriteLine(test.Session);
Assert.IsNotNull(test.Session);
}
}
}
<file_sep>/StudentPerformanceServiceWPF/Pages/MethodistDeaneryPages/AddTestUserControl.xaml.cs
using StudentPerformanceServiceCL.Models.Data;
using StudentPerformanceServiceCL.Models.Entities;
using StudentPerformanceServiceCL.Models.Entities.Tests;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace StudentPerformanceServiceWPF.Pages.MethodistDeaneryPages
{
/// <summary>
/// Логика взаимодействия для AddTestUserControl.xaml
/// </summary>
public partial class AddTestUserControl : UserControl
{
private Subject selectetSubject;
public AddTestUserControl()
{
InitializeComponent();
ElementManager.Instance.ChangeTitleText("Добавление испытания");
LoadSubject();
LoadSession();
subjectComboBox.SelectionChanged += (s, e) =>
{
var comboBox = (ComboBox)s;
selectetSubject = (Subject)comboBox.SelectedItem;
LoadGroups();
};
}
private async void LoadSubject()
{
IEnumerable<Subject> subjects = null;
await Task.Run(() =>
{
var db = DAOFactory.GetDAOFactory();
subjects = db.SubjectDAO.Subjects;
});
subjectComboBox.Items.Clear();
foreach (var subject in subjects)
{
subjectComboBox.Items.Add(subject);
}
}
private async void LoadGroups()
{
IEnumerable<Group> groups = null;
await Task.Run(() => groups = selectetSubject.Groups);
groupComboBox.Items.Clear();
foreach (var group in groups)
{
groupComboBox.Items.Add(group);
}
}
private async void LoadSession()
{
IEnumerable<Session> sessions = null;
await Task.Run(() =>
{
var db = DAOFactory.GetDAOFactory();
sessions = db.SessionDAO.Sessions;
});
sessionComboBox.Items.Clear();
foreach (var session in sessions)
{
sessionComboBox.Items.Add(session);
}
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
try
{
var selectedDate = datePicker.SelectedDate.Value;
var group = (Group)groupComboBox.SelectedItem;
var session = (Session)sessionComboBox.SelectedItem;
var semester = group.Semester;
var db = DAOFactory.GetDAOFactory();
switch (testTypeComboBox.SelectedIndex)
{
case 0:
db.TestDAO.Add(new OffsetTest()
{
Date = selectedDate,
SubjectId = selectetSubject.Id,
GroupId = group.Id,
Semester = semester,
SessionId = session.Id
});
break;
case 1:
db.TestDAO.Add(new ExamTest()
{
Date = selectedDate,
SubjectId = selectetSubject.Id,
GroupId = group.Id,
Semester = semester,
SessionId = session.Id
});
break;
case 2:
db.TestDAO.Add(new CourseworkTest()
{
Date = selectedDate,
SubjectId = selectetSubject.Id,
GroupId = group.Id,
Semester = semester,
SessionId = session.Id
});
break;
default:
throw new Exception("Тип испытания не определён");
}
msgLabel.Content = "Испытание успешно добавлено";
}
catch (Exception ex)
{
msgLabel.Content = ex.Message;
}
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/ITestDAO.cs
using StudentPerformanceServiceCL.Models.Entities.Tests;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data
{
public interface ITestDAO
{
IEnumerable<Test> Tests { get; }
IEnumerable<ExamTest> ExamTests { get; }
IEnumerable<OffsetTest> OffsetTests { get; }
IEnumerable<CourseworkTest> CourseworkTests { get; }
IEnumerable<TestResult> TestResults { get; }
void Add(Test test);
void Add(TestResult testResult);
void Update(TestResult testResult);
}
}
<file_sep>/StudentPerformanceServiceCL/Services/StudentFilters/StudentFilterDecorator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Services.StudentFilters
{
internal abstract class StudentFilterDecorator : StudentFilter
{
protected StudentFilter studentFilter;
protected StudentFilterDecorator(StudentFilter studentFilter)
{
this.studentFilter = studentFilter;
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Tests/CourseworkTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities.Tests
{
/// <summary>
/// Класс описыващий испытание в виде курсовой работы.
/// </summary>
public class CourseworkTest : Test
{
public CourseworkTest()
{
Type = 2;
}
public CourseworkTest(Test test) : base(test)
{
Type = 2;
}
public override string TypeStr => "Курсовая";
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/ICaster.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities
{
internal interface ICaster<T>
{
T Cast();
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/ISpecialtyDAO.cs
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data
{
public interface ISpecialtyDAO
{
IEnumerable<Specialty> Specialties { get; }
void Add(Specialty specialty);
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/PostgreDAO/PgSessionDAO.cs
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data.PostgreDAO
{
internal class PgSessionDAO : ISessionDAO
{
private readonly StudentPerformanceServiceContext _context;
public PgSessionDAO(StudentPerformanceServiceContext context)
{
_context = context;
}
public IEnumerable<Session> Sessions => _context.Sessions;
public void Add(Session session)
{
if (_context.Sessions
.FirstOrDefault(s => s.Year == session.Year && s.Season == session.Season) != null)
throw new Exception("Данная сессия уже назначена");
_context.Sessions.InsertOnSubmit(session);
_context.SubmitChanges();
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Accounts/Admin.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities.Accounts
{
public class Admin : Account
{
public Admin()
{
Role = 0;
}
public Admin(Account account) : base(account)
{
Role = 0;
}
public override string Status => "Администратор";
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Entity.cs
using StudentPerformanceServiceCL.Models.Data;
using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities
{
public abstract class Entity
{
[Column(IsPrimaryKey = true, Name = "id", IsDbGenerated = true)]
public int Id { get; set; }
protected DAOFactory db => DAOFactory.GetDAOFactory();
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/IGroupDAO.cs
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data
{
public interface IGroupDAO
{
IEnumerable<Group> Groups { get; }
void Add(Group group);
void Update(Group group);
}
}
<file_sep>/StudentPerformanceServiceWPF/Pages/AdminPages/ReportOnStudentUserControl.xaml.cs
using Microsoft.Win32;
using StudentPerformanceServiceCL.Models.Data;
using StudentPerformanceServiceCL.Models.Entities;
using StudentPerformanceServiceCL.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
namespace StudentPerformanceServiceWPF.Pages.AdminPages
{
/// <summary>
/// Логика взаимодействия для ReportOnStudentUserControl.xaml
/// </summary>
public partial class ReportOnStudentUserControl : UserControl
{
private readonly StudentFilterService studentFilter;
private string selectFaculty;
private string selectSepcialty;
private int? selectCourse;
public ReportOnStudentUserControl()
{
InitializeComponent();
studentFilter = new StudentFilterService();
StartupLoad();
ElementManager.Instance.ChangeTitleText("Отчёт по студентам");
facultyComboBox.SelectionChanged += (s, e) =>
{
var comboBox = (ComboBox)s;
selectFaculty = comboBox.SelectedIndex == 0 ? null : ((Faculty)comboBox.SelectedItem).Name;
LoadStudents();
};
courseComboBox.SelectionChanged += (s, e) =>
{
var comboBox = (ComboBox)s;
selectCourse = comboBox.SelectedIndex == 0 ? new int?() :
int.Parse((string)((ComboBoxItem)comboBox.SelectedItem).Content);
LoadStudents();
};
specialtyComboBox.SelectionChanged += (s, e) =>
{
var comboBox = (ComboBox)s;
selectSepcialty = comboBox.SelectedIndex == 0 ? null : ((Specialty)comboBox.SelectedItem).Name;
LoadStudents();
};
}
private void StartupLoad()
{
LoadSpecialties();
LoadFaculies();
LoadStudents();
}
private void LoadSpecialties()
{
var db = DAOFactory.GetDAOFactory();
IEnumerable<Specialty> specialties = db.SpecialtyDAO.Specialties;
specialtyComboBox.Items.Clear();
specialtyComboBox.Items.Add("(Все специальности)");
foreach (var specialty in specialties)
{
specialtyComboBox.Items.Add(specialty);
}
}
private void LoadFaculies()
{
var db = DAOFactory.GetDAOFactory();
IEnumerable<Faculty> faculties = db.FacultyDAO.Faculties;
facultyComboBox.Items.Clear();
facultyComboBox.Items.Add("(Все факультеты)");
foreach (var faculty in faculties)
{
facultyComboBox.Items.Add(faculty);
}
}
private async void LoadStudents()
{
await Task.Run(() => studentFilter.GetStudents(selectFaculty, selectSepcialty, selectCourse));
dataGrid.Items.Clear();
foreach (var student in studentFilter.StudentViews)
{
dataGrid.Items.Add(student);
}
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "XML файл(*.xml)|*.xml|Все файлы(*.*)|*.*";
try
{
saveFileDialog.ShowDialog();
string filename = saveFileDialog.FileName;
SaveToXML(filename);
MessageBox.Show("Файл успешно сохранён.");
}
catch (Exception ex)
{
MessageBox.Show("Не удалось сохранить файл. " + ex.Message);
}
}
private void SaveToXML(string path)
{
XDocument xDoc = new XDocument();
XElement root = new XElement("reports");
foreach (var student in studentFilter.StudentViews)
{
root.Add(new XElement("student",
new XElement("id", student.Id),
new XElement("fullName", student.StudentFullName),
new XElement("faculty", student.FacultyName),
new XElement("group", student.GroupName),
new XElement("course", student.Course),
new XElement("avgMark", student.AvgMark)
));
}
xDoc.Add(root);
xDoc.Save(path);
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Tests/TestResult.cs
using StudentPerformanceServiceCL.Models.Entities.Accounts;
using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities.Tests
{
/// <summary>
/// Результаты сдачи испытания для конкретного студента.
/// </summary>
[Table(Name = "test_results")]
public class TestResult : Entity
{
[Column(Name = "test_id")]
public int TestId { get; set; }
[Column(Name = "student_id")]
public int StudentId { get; set; }
[Column(Name = "completion_date")]
public DateTime CompletionDate { get; set; }
[Column(Name = "mark")]
public int Mark { get; set; }
[Column(Name = "retake")]
public bool Retake { get; set; }
[Column(Name = "attempts_number")]
public int AttemptsNumber { get; set; }
public Test Test => db.TestDAO.Tests
.FirstOrDefault(t => t.Id == TestId);
public Student Student => db.AccountDAO.Students
.FirstOrDefault(s => s.Id == StudentId);
}
}
<file_sep>/StudentPerformanceServiceUT/AccountUnitTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StudentPerformanceServiceCL.Models.Data;
namespace StudentPerformanceServiceUT
{
[TestClass]
public class AccountUnitTest
{
private readonly DAOFactory db;
public AccountUnitTest()
{
db = DAOFactory.GetDAOFactory();
}
[TestMethod]
public void MethodistDeanerys_GetFromDB()
{
var accounts = db.AccountDAO.MethodistDeaneries;
foreach (var account in accounts)
{
Console.WriteLine(account);
}
Assert.IsNotNull(accounts);
}
[TestMethod]
public void Students_GetFromDB()
{
var accounts = db.AccountDAO.Students;
foreach (var account in accounts)
{
Console.WriteLine(account);
}
Assert.IsNotNull(accounts);
}
[TestMethod]
public void LogInAdmin_GetFromDB()
{
var account = db.AccountDAO.LogIn("admin", "a1806"); ;
Console.WriteLine(account);
Assert.IsNotNull(account);
}
[TestMethod]
public void LogInMethodistDeanery_GetFromDB()
{
var account = db.AccountDAO.LogIn("methodist", "m1806"); ;
Console.WriteLine(account);
Assert.IsNotNull(account);
}
[TestMethod]
public void LogInStudent_GetFromDB()
{
var account = db.AccountDAO.LogIn("ropot", "s1806"); ;
Console.WriteLine(account);
Assert.IsNotNull(account);
}
[TestMethod]
public void Students_GetNavigatePropertysFromDB()
{
var accounts = db.AccountDAO.Students;
foreach (var account in accounts)
{
Console.WriteLine(account.Group);
Console.WriteLine(account.TestResults);
}
Assert.IsNotNull(accounts);
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Faculty.cs
using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities
{
/// <summary>
/// Класс описывающий сущность "Факультет"
/// </summary>
[Table(Name = "faculties")]
public class Faculty : Entity
{
[Column(Name = "name")]
public string Name { get; set; }
public IEnumerable<Specialty> Specialties => db.SpecialtyDAO.Specialties
.Where(s => s.FacultyId == Id);
public override string ToString() => Name;
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Session.cs
using StudentPerformanceServiceCL.Models.Entities.Tests;
using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities
{
[Table(Name = "sessions")]
public class Session : Entity
{
[Column(Name = "year")]
public int Year { get; set; }
[Column(Name = "season")]
public bool Season { get; set; }
public IEnumerable<Test> Tests => db.TestDAO.Tests
.Where(t => t.SessionId == Id);
public override string ToString() =>
(Season ? "Зимняя " : "Летняя ") + "сессия " + Year + " года";
}
}<file_sep>/StudentPerformanceServiceCL/Models/Entities/Group.cs
using StudentPerformanceServiceCL.Models.Entities.Accounts;
using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities
{
/// <summary>
/// Класс описывающий группу студента.
/// </summary>
[Table(Name = "groups")]
public class Group : Entity
{
[Column(Name = "name")]
public string Name { get; set; }
[Column(Name = "semester")]
public int Semester { get; set; }
[Column(Name = "specialty_id")]
public int SpecialtyId { get; set; }
public Specialty Specialty => db.SpecialtyDAO.Specialties
.FirstOrDefault(s => s.Id == SpecialtyId);
public IEnumerable<Student> Students => db.AccountDAO.Students
.Where(s => s.GroupId == Id);
public override string ToString() => Name;
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/ISessionDAO.cs
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data
{
public interface ISessionDAO
{
IEnumerable<Session> Sessions { get; }
void Add(Session session);
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/PostgreDAO/StudentPerformanceServiceContext.cs
using DbLinq.Data.Linq;
using DbLinq.PostgreSql;
using StudentPerformanceServiceCL.Models.Entities;
using StudentPerformanceServiceCL.Models.Entities.Accounts;
using StudentPerformanceServiceCL.Models.Entities.Tests;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data.PostgreDAO
{
internal class StudentPerformanceServiceContext : PgsqlDataContext
{
internal Table<Account> Accounts => GetTable<Account>();
internal Table<Faculty> Faculties => GetTable<Faculty>();
internal Table<Group> Groups => GetTable<Group>();
internal Table<Specialty> Specialties => GetTable<Specialty>();
internal Table<Subject> Subjects => GetTable<Subject>();
internal Table<Test> Tests => GetTable<Test>();
internal Table<TestResult> TestResults => GetTable<TestResult>();
internal Table<SubjectSpecialty> SubjectSpecialties => GetTable<SubjectSpecialty>();
internal Table<Session> Sessions => GetTable<Session>();
public StudentPerformanceServiceContext(DbConnection conn) : base(conn)
{
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/PostgreDAO/PgTestDAO.cs
using StudentPerformanceServiceCL.Models.Entities.Tests;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data.PostgreDAO
{
internal class PgTestDAO : ITestDAO
{
private readonly StudentPerformanceServiceContext _context;
public PgTestDAO(StudentPerformanceServiceContext context)
{
_context = context;
}
public IEnumerable<Test> Tests => _context.Tests
.AsEnumerable()
.Select(t => t.Cast());
public IEnumerable<ExamTest> ExamTests => _context.Tests
.Where(t => t.Type == 1)
.AsEnumerable()
.Select(t => new ExamTest(t));
public IEnumerable<OffsetTest> OffsetTests => _context.Tests
.Where(t => t.Type == 0)
.AsEnumerable()
.Select(t => new OffsetTest(t));
public IEnumerable<CourseworkTest> CourseworkTests => _context.Tests
.Where(t => t.Type == 2)
.AsEnumerable()
.Select(t => new CourseworkTest(t));
public IEnumerable<TestResult> TestResults => _context.TestResults;
public void Add(Test test)
{
_context.Tests.InsertOnSubmit(new Test(test));
_context.SubmitChanges();
}
public void Add(TestResult testResult)
{
var existTest = _context.TestResults
.FirstOrDefault(tr => tr.TestId == testResult.TestId && tr.StudentId == testResult.StudentId);
if (existTest != null)
{
existTest.Mark = testResult.Mark;
existTest.CompletionDate = testResult.CompletionDate;
existTest.Retake = false;
existTest.AttemptsNumber += 1;
}
else
{
testResult.AttemptsNumber += 1;
_context.TestResults.InsertOnSubmit(testResult);
}
_context.SubmitChanges();
}
public void Update(TestResult testResult)
{
var updateTestResult = _context.TestResults
.FirstOrDefault(t => t.Id == testResult.Id);
updateTestResult.Mark = testResult.Mark;
updateTestResult.StudentId = testResult.StudentId;
updateTestResult.TestId = testResult.TestId;
updateTestResult.AttemptsNumber = testResult.AttemptsNumber;
updateTestResult.CompletionDate = testResult.CompletionDate;
_context.SubmitChanges();
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/PostgreDAO/PgAccountDAO.cs
using StudentPerformanceServiceCL.Models.Entities.Accounts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data.PostgreDAO
{
internal class PgAccountDAO : IAccountDAO
{
private readonly StudentPerformanceServiceContext _context;
public PgAccountDAO(StudentPerformanceServiceContext context)
{
_context = context;
}
public IEnumerable<MethodistDeanery> MethodistDeaneries => _context.Accounts
.Where(a => a.Role == 1)
.AsEnumerable()
.Select(a => new MethodistDeanery(a));
public IEnumerable<Student> Students => _context.Accounts
.Where(a => a.Role == 2)
.AsEnumerable()
.Select(a => new Student(a));
public void Add(Account account)
{
_context.Accounts.InsertOnSubmit(new Account(account));
_context.SubmitChanges();
}
public Account LogIn(string login, string password)
{
var account = _context.Accounts
.FirstOrDefault(a => a.Login == login && a.Password == <PASSWORD>);
if (account == null) throw new Exception("Неверный логин или пароль");
return account.Cast();
}
public void Remove(Student student)
{
var account = _context.Accounts.FirstOrDefault(a => a.Id == student.Id);
_context.Accounts.DeleteOnSubmit(account);
_context.SubmitChanges();
}
}
}
<file_sep>/StudentPerformanceServiceCL/Services/StudentFilters/StudentFilter.cs
using StudentPerformanceServiceCL.Models.Data;
using StudentPerformanceServiceCL.Services.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Services.StudentFilters
{
internal class StudentFilter
{
public virtual IEnumerable<StudentViewModel> Students { get; set; }
public void SetDefaultData()
{
var db = DAOFactory.GetDAOFactory();
Students = db.AccountDAO.Students
.Select(s => new StudentViewModel()
{
Id = s.Id,
Student = s,
StudentFullName = s.FullName,
Group = s.Group,
GroupName = s.Group.Name,
Course = s.Course.Value,
AvgMark = s.TestResults.Count() != 0 ? s.TestResults.Sum(t => t.Mark) / s.TestResults.Count() : 0,
Faculty = s.Group.Specialty.Faculty,
FacultyName = s.Group.Specialty.Faculty.Name,
TestResults = s.TestResults
});
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Entities/Tests/OffsetTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Entities.Tests
{
/// <summary>
/// Класс описывающий испытание в виде зачёта.
/// </summary>
public class OffsetTest : Test
{
public OffsetTest()
{
Type = 0;
}
public OffsetTest(Test test) : base(test)
{
Type = 0;
}
public override string TypeStr => "Зачёт";
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/PostgreDAO/PgSubjectDAO.cs
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data.PostgreDAO
{
internal class PgSubjectDAO : ISubjectDAO
{
private readonly StudentPerformanceServiceContext _context;
public PgSubjectDAO(StudentPerformanceServiceContext context)
{
_context = context;
}
public IEnumerable<Subject> Subjects => _context.Subjects;
public void Add(Subject subject, Specialty specialty)
{
var exitSubject = _context.Subjects
.FirstOrDefault(s => s.Name == subject.Name && s.Teacher == subject.Teacher);
if (exitSubject != null)
{
subject = exitSubject;
}
else
{
_context.Subjects.InsertOnSubmit(subject);
_context.SubmitChanges();
}
_context.SubjectSpecialties
.InsertOnSubmit(new SubjectSpecialty()
{
SpecialtyId = specialty.Id,
SubjectId = subject.Id
});
_context.SubmitChanges();
}
}
}
<file_sep>/StudentPerformanceServiceCL/Services/ViewModels/StudentViewModel.cs
using StudentPerformanceServiceCL.Models.Entities;
using StudentPerformanceServiceCL.Models.Entities.Accounts;
using StudentPerformanceServiceCL.Models.Entities.Tests;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Services.ViewModels
{
public class StudentViewModel
{
public int Id { get; set; }
public string StudentFullName { get; set; }
public string FacultyName { get; set; }
public string GroupName { get; set; }
public int Course { get; set; }
public double AvgMark { get; set; }
public Faculty Faculty { get; set; }
public Group Group { get; set; }
public Student Student { get; set; }
public IEnumerable<TestResult> TestResults { get; set; }
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/PostgreDAO/PgSpecialtyDAO.cs
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data.PostgreDAO
{
internal class PgSpecialtyDAO : ISpecialtyDAO
{
private readonly StudentPerformanceServiceContext _context;
public PgSpecialtyDAO(StudentPerformanceServiceContext context)
{
_context = context;
}
public IEnumerable<Specialty> Specialties => _context.Specialties;
public void Add(Specialty specialty)
{
_context.Specialties.InsertOnSubmit(specialty);
_context.SubmitChanges();
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/ISubjectDAO.cs
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data
{
public interface ISubjectDAO
{
IEnumerable<Subject> Subjects { get; }
void Add(Subject subject, Specialty specialty);
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/ISubjectSpecialtyDAO.cs
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data
{
internal interface ISubjectSpecialtyDAO
{
IEnumerable<SubjectSpecialty> SubjectSpecialties { get; }
void Add(SubjectSpecialty subjectSpecialty);
}
}
<file_sep>/StudentPerformanceServiceWPF/ElementManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace StudentPerformanceServiceWPF
{
internal class ElementManager
{
private Grid _mainGrid;
private Grid _buttonMenu;
private Label _titleLable;
private ElementManager(Grid mainGrid, Grid buttonMenu, Label titleLable)
{
_mainGrid = mainGrid;
_buttonMenu = buttonMenu;
_titleLable = titleLable;
}
public static ElementManager SetInstance(Grid mainGrid, Grid buttonMenu, Label titleLable)
{
Instance = new ElementManager(mainGrid, buttonMenu, titleLable);
return Instance;
}
public static ElementManager Instance { get; private set; }
public void SetContent(UserControl userControl)
{
_mainGrid.Children.Clear();
_mainGrid.Children.Add(userControl);
}
public void SetButtonMenu(UserControl userControl)
{
_buttonMenu.Children.Clear();
_buttonMenu.Children.Add(userControl);
}
public void ChangeTitleText(string titleText)
{
_titleLable.Content = titleText;
}
}
}
<file_sep>/StudentPerformanceServiceCL/Services/StudentFilters/SessionStudentFilter.cs
using StudentPerformanceServiceCL.Models.Entities;
using StudentPerformanceServiceCL.Services.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Services.StudentFilters
{
internal class SessionStudentFilter : StudentFilterDecorator
{
private Session _session;
public SessionStudentFilter(StudentFilter studentFilter, Session session) : base(studentFilter)
{
_session = session;
}
public override IEnumerable<StudentViewModel> Students
{
get => studentFilter.Students
.Select(s =>
{
var testResult = s.Student.TestResults
.Where(t => t.Test.SessionId == _session.Id);
return new StudentViewModel()
{
Id = s.Id,
StudentFullName = s.StudentFullName,
Student = s.Student,
Course = s.Course,
Group = s.Group,
GroupName = s.GroupName,
Faculty = s.Faculty,
FacultyName = s.FacultyName,
AvgMark = testResult.Count() != 0 ? testResult.Sum(t => t.Mark) / testResult.Count() : 0,
TestResults = testResult
};
});
set => base.Students = value;
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/PostgreDAO/PgSubjectSpecialtyDAO.cs
using StudentPerformanceServiceCL.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data.PostgreDAO
{
internal class PgSubjectSpecialtyDAO : ISubjectSpecialtyDAO
{
private readonly StudentPerformanceServiceContext _context;
public PgSubjectSpecialtyDAO(StudentPerformanceServiceContext context)
{
_context = context;
}
public IEnumerable<SubjectSpecialty> SubjectSpecialties => _context.SubjectSpecialties;
public void Add(SubjectSpecialty subjectSpecialty)
{
_context.SubjectSpecialties.InsertOnSubmit(subjectSpecialty);
_context.SubmitChanges();
}
}
}
<file_sep>/StudentPerformanceServiceCL/Models/Data/IAccountDAO.cs
using StudentPerformanceServiceCL.Models.Entities.Accounts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentPerformanceServiceCL.Models.Data
{
public interface IAccountDAO
{
IEnumerable<MethodistDeanery> MethodistDeaneries { get; }
IEnumerable<Student> Students { get; }
Account LogIn(string login, string password);
void Add(Account account);
void Remove(Student student);
}
}
| c2c0d0ab7929cc1d22f77a73da036a2d88b75624 | [
"Markdown",
"C#",
"SQL"
]
| 66 | C# | default-INT/StudentPerformanceService-WPF | 826b4482d11cbcbda4ef84830e1245e0c400e103 | 820c388fbf7f176e22ef5e41ad3521ce03897af1 |
refs/heads/master | <file_sep>public class TestArrays {
public static void main(String[] args) {
//Initializing array in one statement
int score [] = {2,4,5,7,9};
System.out.println(score[1]);
System.out.println("index\tvalue");
int math []= {18,99,17,28};
for(int study=0; study<math.length; study++) {
System.out.println(study + "\t" + math[study]);
}
}
}
<file_sep>public class Arrays {
public void LearningArrays () {
System.out.println("Arrrrray is fun to work with");
}
}
| 53c202049e83fc9bfc12fffb56c3365e54956c4a | [
"Java"
]
| 2 | Java | jeniferahmed/TEAMOF2 | fea693bcae100997692a6ea2bc37523c3c29a366 | bd1d3a23bc2ab7a323d60cb6a4d4a2b86c722401 |
refs/heads/master | <repo_name>RhysWJones/Projects<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ApplicationUI/GetUsersByCityCommand.cs
using AnimalCareSystem.Data;
using AnimalCareSystem.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ApplicationUI
{
public class GetUsersByCityCommand : ICommand
{
private AccountHandler _accountHandler;
private string _city;
public GetUsersByCityCommand(string city, ApplicationDbContext dbContext)
{
_city = city;
_accountHandler = new AccountHandler(dbContext);
}
public async Task<object> Execute()
{
return await _accountHandler.GetUsersByCity(_city);
}
}
}
<file_sep>/OOAE/T2/T2-05/wk2-05_lec1_CommandProj/wk2-05_lec1_CommandProj/src/command/GetAllEmployeesCommand.java
package command;
import model.EmployeeHandler;
import view.AllEmployeesView;
/**
*
* @author <NAME>
*/
public class GetAllEmployeesCommand implements Command
{
EmployeeHandler receiver;
public GetAllEmployeesCommand(EmployeeHandler receiver)
{
this.receiver = receiver;
}
@Override
public void execute()
{
new AllEmployeesView(receiver.findAllEmployees()).print();
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-war/src/java/managed_bean/RescheduleDeliveryBean.java
package managed_bean;
import dto.DeliveryDTO;
import ejb.User_UIRemote;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.Date;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
/**
*
* @author Rhys
*/
@Named(value = "rescheduleDeliveryBean")
@SessionScoped
public class RescheduleDeliveryBean implements Serializable
{
private Date newDeliveryDate;
private DeliveryDTO delivery;
@EJB
private User_UIRemote userUI;
public RescheduleDeliveryBean()
{
}
public String rescheduleDelivery()
{
boolean deliveryRescheduled = userUI.rescheduleDelivery(delivery.getDeliveryId(), newDeliveryDate);
if(deliveryRescheduled)
{
delivery = null;
newDeliveryDate = null;
return "Success";
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Delivery could not be re-scheduled."));
return "";
}
}
public Date getNewDeliveryDate()
{
return newDeliveryDate;
}
public void setNewDeliveryDate(Date newDeliveryDate)
{
this.newDeliveryDate = newDeliveryDate;
}
public DeliveryDTO getDelivery()
{
return delivery;
}
public void setDelivery(DeliveryDTO delivery)
{
this.delivery = delivery;
}
public String setDeliveryForRescheduling(DeliveryDTO delivery)
{
setDelivery(delivery);
return "Reschedule Delivery";
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_Library/test/dto/DeliveryDTOIT.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import java.util.ArrayList;
import java.util.Date;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
*
* @author Rhys
*/
public class DeliveryDTOIT
{
private DeliveryDTO deliveryDTOInstance = new DeliveryDTO();
public DeliveryDTOIT()
{
//Initialise DTO's
DeliveryStatusDTO deliveryStatusDTOInstance = new DeliveryStatusDTO();
DepotDTO depotDTOInstance = new DepotDTO();
RouteDTO routeDTOInstance = new RouteDTO();
UserDTO userDTOInstance = new UserDTO();
ParcelDTO parcelDTOInstance = new ParcelDTO();
//Initialise Lists
ArrayList<DeliveryDTO> deliveryList = new ArrayList<DeliveryDTO>();
deliveryList.add(deliveryDTOInstance);
ArrayList<RouteDTO> routeList = new ArrayList<RouteDTO>();
routeList.add(routeDTOInstance);
ArrayList<UserDTO> userList = new ArrayList<UserDTO>();
userList.add(userDTOInstance);
//Create ParcelDTO
parcelDTOInstance.setParcelId(1);
parcelDTOInstance.setRecipientName("Test Recipient");
parcelDTOInstance.setAddressLine1("Test Address 1");
parcelDTOInstance.setAddressLine2("Test Address 2");
parcelDTOInstance.setCity("Test City");
parcelDTOInstance.setPostcode("Test Postcode");
parcelDTOInstance.setDelivered(false);
parcelDTOInstance.setDelivery(deliveryDTOInstance);
//Create UserDTO
userDTOInstance.setId(1);
userDTOInstance.setForename("Test");
userDTOInstance.setSurname("User");
userDTOInstance.setEmail("Test Email");
userDTOInstance.setPassword("<PASSWORD>");
userDTOInstance.setAddressLine1("Test Address 1");
userDTOInstance.setAddressLine2("Test Address 2");
userDTOInstance.setCity("Test City");
userDTOInstance.setPostcode("Test Postcode");
userDTOInstance.setTelephone("Test Telephone");
userDTOInstance.setDateOfBirth(new Date());
userDTOInstance.setIsDriver(true);
userDTOInstance.setDriverId(1);
userDTOInstance.setRouteId(routeDTOInstance);
//Create DeliveryStatusDTO
deliveryStatusDTOInstance.setDeliveryStatusId(1);
deliveryStatusDTOInstance.setName("Test Status");
//Create DepotDTO
depotDTOInstance.setDepotId(1);
depotDTOInstance.setName("Test Depot");
depotDTOInstance.setDepotDeliveries(deliveryList);
depotDTOInstance.setDepotRoutes(routeList);
//Create RouteDTO
routeDTOInstance.setRouteId(1);
routeDTOInstance.setName("Test Route");
routeDTOInstance.setDeliveries(deliveryList);
routeDTOInstance.setDepot(depotDTOInstance);
routeDTOInstance.setUsers(userList);
//Create DeliveryDTO
deliveryDTOInstance.setDeliveryId(1);
deliveryDTOInstance.setDeliveryDate(new Date());
deliveryDTOInstance.setDeliveryStatus(deliveryStatusDTOInstance);
deliveryDTOInstance.setDepot(depotDTOInstance);
deliveryDTOInstance.setParcel(parcelDTOInstance);
deliveryDTOInstance.setRoute(routeDTOInstance);
}
@BeforeAll
public static void setUpClass()
{
}
@AfterAll
public static void tearDownClass()
{
}
@BeforeEach
public void setUp()
{
}
@AfterEach
public void tearDown()
{
}
/**
* Test of getDeliveryId method, of class DeliveryDTO.
*/
@Test
public void testGetDeliveryId()
{
System.out.println("Test getDeliveryId");
int expResult = 1;
int result = deliveryDTOInstance.getDeliveryId();
assertEquals(expResult, result);
}
/**
* Test of setDeliveryId method, of class DeliveryDTO.
*/
@Test
public void testSetDeliveryId()
{
System.out.println("setDeliveryId");
int deliveryId = 2;
deliveryDTOInstance.setDeliveryId(deliveryId);
}
/**
* Test of getDeliveryDate method, of class DeliveryDTO.
*/
@Test
public void testGetDeliveryDate()
{
System.out.println("getDeliveryDate");
Date expResult = new Date();
Date result = deliveryDTOInstance.getDeliveryDate();
assertTrue(expResult.getDate() == result.getDate());
assertTrue(expResult.getMonth()== result.getMonth());
assertTrue(expResult.getYear() == result.getYear());
}
/**
* Test of setDeliveryDate method, of class DeliveryDTO.
*/
@Test
public void testSetDeliveryDate()
{
System.out.println("setDeliveryDate");
Date deliveryDate = new Date();
deliveryDTOInstance.setDeliveryDate(deliveryDate);
assertSame(deliveryDate, deliveryDTOInstance.getDeliveryDate());
}
/**
* Test of getDeliveryStatus method, of class DeliveryDTO.
*/
@Test
public void testGetDeliveryStatus()
{
System.out.println("getDeliveryStatus");
int expResultId = 1;
int resultId = deliveryDTOInstance.getDeliveryStatus().getDeliveryStatusId();
assertEquals(expResultId, resultId);
String expResultName = "Test Status";
String resultName = deliveryDTOInstance.getDeliveryStatus().getName();
assertTrue(expResultName.equals(resultName));
}
/**
* Test of setDeliveryStatus method, of class DeliveryDTO.
*/
@Test
public void testSetDeliveryStatus()
{
System.out.println("setDeliveryStatus");
DeliveryStatusDTO deliveryStatus = new DeliveryStatusDTO();
deliveryDTOInstance.setDeliveryStatus(deliveryStatus);
assertSame(deliveryDTOInstance.getDeliveryStatus(), deliveryStatus);
}
/**
* Test of getDepot method, of class DeliveryDTO.
*/
@Test
public void testGetDepot()
{
System.out.println("getDepot");
int expResultId = 1;
int resultId = deliveryDTOInstance.getDepot().getDepotId();
assertEquals(expResultId, resultId);
String expResultName = "Test Depot";
String resultName = deliveryDTOInstance.getDepot().getName();
assertTrue(resultName.equals(expResultName));
assertTrue(deliveryDTOInstance.getDepot().getDepotDeliveries() != null);
assertTrue(deliveryDTOInstance.getDepot().getDepotRoutes() != null);
}
/**
* Test of setDepot method, of class DeliveryDTO.
*/
@Test
public void testSetDepot()
{
System.out.println("setDepot");
DepotDTO depot = new DepotDTO();
deliveryDTOInstance.setDepot(depot);
assertTrue(deliveryDTOInstance.getDepot() != null);
}
/**
* Test of getParcel method, of class DeliveryDTO.
*/
@Test
public void testGetParcel()
{
System.out.println("getParcel");
int expResultId = 1;
int resultId = deliveryDTOInstance.getParcel().getParcelId();
assertEquals(expResultId, resultId);
String expResultName = "Test Recipient";
String resultName = deliveryDTOInstance.getParcel().getRecipientName();
assertTrue(resultName.equals(expResultName));
String expResultAddress1 = "Test Address 1";
String resultAddress1 = deliveryDTOInstance.getParcel().getAddressLine1();
assertTrue(resultAddress1.equals(expResultAddress1));
String expResultAddress2 = "Test Address 2";
String resultAddress2 = deliveryDTOInstance.getParcel().getAddressLine2();
assertTrue(resultAddress2.equals(expResultAddress2));
String expResultCity = "Test City";
String resultCity = deliveryDTOInstance.getParcel().getCity();
assertTrue(resultCity.equals(expResultCity));
String expResultPostcode = "Test Postcode";
String resultPostcode = deliveryDTOInstance.getParcel().getPostcode();
assertTrue(resultPostcode.equals(expResultPostcode));
assertTrue(deliveryDTOInstance.getParcel().getDelivery() != null);
}
/**
* Test of setParcel method, of class DeliveryDTO.
*/
@Test
public void testSetParcel()
{
System.out.println("setParcel");
ParcelDTO parcel = new ParcelDTO();
deliveryDTOInstance.setParcel(parcel);
assertTrue(deliveryDTOInstance.getParcel() != null);
}
/**
* Test of getRoute method, of class DeliveryDTO.
*/
@Test
public void testGetRoute()
{
System.out.println("getRoute");
int expResultId = 1;
int resultId = deliveryDTOInstance.getRoute().getRouteId();
assertEquals(resultId, expResultId);
String expResultName = "Test Route";
String resultName = deliveryDTOInstance.getRoute().getName();
assertTrue(resultName.equals(expResultName));
assertTrue(deliveryDTOInstance.getRoute().getDeliveries() != null);
assertTrue(deliveryDTOInstance.getRoute().getDepot()!= null);
assertTrue(deliveryDTOInstance.getRoute().getUsers()!= null);
}
/**
* Test of setRoute method, of class DeliveryDTO.
*/
@Test
public void testSetRoute()
{
System.out.println("setRoute");
RouteDTO route = new RouteDTO();
deliveryDTOInstance.setRoute(route);
assertTrue(deliveryDTOInstance.getRoute() != null);
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/UpdateUserCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class UpdateUserCommand : ICommand
{
private UserHandler UserHandler;
private ApplicationUser UpdatedUser;
public UpdateUserCommand(ApplicationUser updatedUser, UserManager<ApplicationUser> userManager, ApplicationDbContext dbContext)
{
UserHandler = new UserHandler(userManager, dbContext);
UpdatedUser = updatedUser;
}
public async Task<object> Execute()
{
return await UserHandler.UpdateUser(UpdatedUser);
}
}
}
<file_sep>/OOAE/T1/T1-03 check portfolio/VehicleShowroomProj/src/vehicleshowroomproj/Customer.java
package vehicleshowroomproj;
public class Customer
{
private String name;
private String contactDetails;
public Customer(String name)
{
this.name = name;
this.contactDetails = name + "@<EMAIL>";
}
public Customer(String name, String contactDetails)
{
this.name = name;
this.contactDetails = contactDetails;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getContactDetails()
{
return contactDetails;
}
public void setContactDetails(String contactDetails)
{
this.contactDetails = contactDetails;
}
@Override
public String toString()
{
return "\n Customer Name: " + name + "\n Customer Contact Details: " + contactDetails;
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/DataParallelismProj/CommandsFactory/NullObjectCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataParallelismProj.CommandsFactory
{
class NullObjectCommand : ICommand
{
public object Execute()
{
return this;
}
}
}
<file_sep>/WMAD/CinemaBookingSystem/src/java/adminUI/CancelBookingCommand.java
package adminUI;
import dto.BookingDTO;
import handler.BookingHandler;
/**
*
* @author <NAME>
*/
public class CancelBookingCommand implements AdminCommand
{
private BookingDTO booking;
private BookingHandler bookHndlr = null;
public CancelBookingCommand(BookingDTO booking)
{
this.booking = booking;
bookHndlr = BookingHandler.getInstance();
}
@Override
public Object execute()
{
return bookHndlr.cancelBooking(booking);
}
}
<file_sep>/ESA/Flights Management/src/view/AllFlightsView.java
package view;
import database.Flight;
import database.Seat;
import java.awt.Font;
import java.util.ArrayList;
import javax.swing.JLabel;
public class AllFlightsView
{
ArrayList<Flight> flights;
ArrayList<JLabel> flightCards = new ArrayList();
public AllFlightsView(ArrayList<Flight> flights)
{
this.flights = flights;
}
public ArrayList<Integer> getFlightNames()
{
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < flights.size(); i++)
{
list.add(flights.get(i).getFlightID());
}
return list;
}
public ArrayList<JLabel> makeCards()
{
for (Flight f : flights)
{
JLabel label = new JLabel();
StringBuilder buff = new StringBuilder();
buff.append("<html><table>");
buff.append(String.format("<tr><td align='left'>%s</td><td>:</td><td>%s</td></tr>", "Flight number: " + f.getFlightID(), "\tPlane id: " + f.getPlaneID()));
buff.append(String.format("<tr><td align='left'>%s</td><td>:</td><td>%s</td></tr>", "\tFrom: " + f.getfOrigin(), "\tTo: " + f.getfDestination()));
buff.append(String.format("<tr><td align='left'>%s</td><td>:</td><td>%s</td></tr>", "\tDeparture date: " + f.getDepartureDate(), "\tArrival date: " + f.getArrivalDate()));
buff.append(String.format("<tr><td align='left'>%s</td><td>:</td><td>%s</td></tr>", "\tPlane designation: " + f.getPlane().getDesignation(), "\tPlane capacity: " + f.getPlane().getCapacity()));
buff.append(String.format("<tr><td align='left'>%s</td><td>:</td><td>%s</td></tr>", "\tPlane airline: " + f.getPlane().getAirline(), "\tEquipment: " + f.getPlane().getEquipment()));
buff.append(String.format("<tr><td align='left'>%s</td><td>:</td><td>%s</td></tr>", "\tDeparture time: " + f.getDepartureTime(), "\tArrival time: " + f.getArrivalTime()));
buff.append("</table></html>");
label.setText(buff.toString());
label.setFont(new Font("Serif", Font.PLAIN, 40));
flightCards.add(label);
}
return flightCards;
}
public ArrayList<String> getString()
{
ArrayList<String> allFlights = new ArrayList<String>();
for (Flight f : flights)
{
allFlights.add("FLIGHT" + "\n\tFlight number: " + f.getFlightID() + "\tPlane id: " + f.getPlaneID() + "\n\tFrom: " + f.getfOrigin()
+ "\tTo: " + f.getfDestination() + "\n\tDeparture date: " + f.getDepartureDate()
+ "\tArrival date: " + f.getArrivalDate() + "\n\tPlane designation: "
+ f.getPlane().getDesignation()
+ "\tPlane capacity: " + f.getPlane().getCapacity()
+ "\n\tPlane airline: " + f.getPlane().getAirline()
+ "\tEquipment: " + f.getPlane().getEquipment()
+ "\n");
for (Seat s : f.getSeat())
{
allFlights.add("\tSeat id: " + s.getSeatID() + "\tSeat number: " + s.getSeatNumber() + "\t\tSeat taken: " + s.getSeatTaken());
}
allFlights.add("\n");
}
return allFlights;
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/SendEmailCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class SendEmailCommand : ICommand
{
private EmailHandler EmailHandler;
private ApplicationUser User;
private IFormFileCollection FileCollection;
public SendEmailCommand(IFormFileCollection fileCollection, ApplicationUser user)
{
EmailHandler = new EmailHandler();
User = user;
FileCollection = fileCollection;
}
public async Task<object> Execute()
{
return EmailHandler.SendEmailToDVLA(FileCollection, User);
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ViewModels/ServiceRateViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ViewModels
{
public class ServiceRateViewModel
{
public ServiceTypeViewModel ServiceType { get; set; }
public string ServiceName { get; set; }
[Range(0, 100)]
public int Rate { get; set; }
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Controllers/AccountController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Controllers
{
[Route("account")]
public class AccountController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private String Email;
private String Password;
private bool RememberMe;
private ApplicationDbContext DbContext;
public AccountController(ILogger<HomeController> logger, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ApplicationDbContext dbContext)
{
_logger = logger;
_userManager = userManager;
_signInManager = signInManager;
DbContext = dbContext;
}
[HttpGet, Route("login")]
public async Task<IActionResult> Login()
{
return View(new LoginViewModel());
}
[HttpPost, Route("login")]
public async Task<IActionResult> Login(LoginViewModel loginViewModel)
{
ViewResult viewResult = View();
if (ModelState.IsValid)
{
Email = loginViewModel.Email;
Password = loginViewModel.Password;
RememberMe = loginViewModel.RememberMe;
Microsoft.AspNetCore.Identity.SignInResult loginResult = (Microsoft.AspNetCore.Identity.SignInResult)await CommandFactory.CreateCommand(CommandFactory.LOGIN, Email, Password, RememberMe, _signInManager).Execute();
if (loginResult.Succeeded)
{
TempData["successmessage"] = "Logged in Successfully!";
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Login Failure. Please check your login details.");
return View();
}
}
return viewResult;
}
[HttpGet, Route("register")]
public async Task<IActionResult> Register()
{
return View(new RegisterViewModel());
}
[HttpPost, Route("register")]
public async Task<IActionResult> Register(RegisterViewModel registerViewModel)
{
if (ModelState.IsValid)
{
ApplicationUser newUser = ConvertToApplicationUser(registerViewModel);
IdentityResult registrationResult = (IdentityResult)await CommandFactory.CreateCommand(CommandFactory.REGISTER, newUser, _userManager, _signInManager).Execute();
if (registrationResult.Succeeded)
{
TempData["successmessage"] = "Registered Successfully!";
return RedirectToAction("Index", "Home");
}
else
{
TempData["errormessage"] = "Registration Failure";
return View();
}
}
return View();
}
public async Task<IActionResult> BlacklistUser(string? id)
{
IActionResult authenticationResult = await AuthenticateUserLogin(true);
if (authenticationResult != null)
{
return authenticationResult;
}
string userId = (string)id;
int userBlacklisted = (int)await CommandFactory.CreateCommand(CommandFactory.BLACKLIST_USER, userId, DbContext, _userManager).Execute();
if(userBlacklisted < 1 || userBlacklisted > 1)
{
TempData["errormessage"] = "Failed To Blacklist User!";
return RedirectToAction("Index", "Home");
}
else
{
TempData["successmessage"] = "User Blacklisted!";
return RedirectToAction("Index", "Home");
}
}
public async Task<IActionResult> AuthenticateUserLogin(bool adminRequired)
{
ApplicationUser CurrentUser = await _userManager.GetUserAsync(HttpContext.User);
bool IsAdmin = false;
if (CurrentUser == null)
{
TempData["errormessage"] = "You need to be logged in to book a vehicle." + Environment.NewLine + " If you do not have an account, please navigate to the registration page by clicking on 'Register' at the top of the screen.";
return RedirectToAction("Login", "Account");
}
else
{
IsAdmin = await _userManager.IsInRoleAsync(CurrentUser, "Admin");
}
if (adminRequired && IsAdmin == false)
{
TempData["errormessage"] = "You require admin privileges to view that page.";
return RedirectToAction("Index", "Home");
}
else return null;
}
public ApplicationUser ConvertToApplicationUser(RegisterViewModel registerViewModel)
{
ApplicationUser newUser = new ApplicationUser();
newUser.UserName = registerViewModel.Email;
newUser.Email = registerViewModel.Email;
newUser.PasswordHash = <PASSWORD>;
newUser.PhoneNumber = registerViewModel.PhoneNumber;
newUser.Forename = registerViewModel.Forename;
newUser.Surname = registerViewModel.Surname;
newUser.AddressLine1 = registerViewModel.AddressLine1;
newUser.AddressLine2 = registerViewModel.AddressLine2;
newUser.Postcode = registerViewModel.Postcode;
newUser.DateOfBirth = registerViewModel.DateOfBirth;
newUser.Blacklisted = false;
newUser.LicenseNumber = registerViewModel.LicenseNumber;
return newUser;
}
[Route("error")]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Data/ApplicationDbContext.cs
using System;
using System.Collections.Generic;
using System.Text;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public DbSet<ApplicationUser> User { get; set; }
public DbSet<Vehicle> Vehicle { get; set; }
public DbSet<VehicleType> VehicleType { get; set; }
public DbSet<Transmission> Transmission { get; set; }
public DbSet<Fuel> Fuel { get; set; }
public DbSet<Equipment> Equipment { get; set; }
public DbSet<Booking> Booking { get; set; }
public DbSet<EquipmentBooking> EquipmentBooking { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
Database.EnsureCreated();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
//modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");
modelBuilder.Entity<Vehicle>().ToTable("Vehicles");
modelBuilder.Entity<VehicleType>().ToTable("VehicleType");
modelBuilder.Entity<Transmission>().ToTable("Transmission");
modelBuilder.Entity<Fuel>().ToTable("Fuel");
modelBuilder.Entity<Equipment>().ToTable("Equipment");
modelBuilder.Entity<Booking>().ToTable("Bookings");
modelBuilder.Entity<EquipmentBooking>().ToTable("EquipmentBookings");
modelBuilder.Entity<Booking>().Property(b => b.Price).HasColumnType("money");
modelBuilder.Entity<Equipment>().Property(e => e.Price).HasColumnType("money");
modelBuilder.Entity<Vehicle>().Property(v => v.CostPerDay).HasColumnType("money");
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/database/DTOConversionGateway.java
package database;
import dto.DeliveryDTO;
import dto.DeliveryStatusDTO;
import dto.DepotDTO;
import dto.ParcelDTO;
import dto.RouteDTO;
import dto.UserDTO;
import entity.Delivery;
import entity.DeliveryStatus;
import entity.Depot;
import entity.Parcel;
import entity.Route;
import entity.Users;
import javax.ejb.Stateless;
/**
*
* @author Rhys
*/
@Stateless
public class DTOConversionGateway implements DTOConversionGatewayLocal
{
@Override
public RouteDTO createRouteDTO(Route route)
{
RouteDTO routeDTO = new RouteDTO();
routeDTO.setRouteId(route.getRouteId());
routeDTO.setName(route.getName());
routeDTO.setDepot(createDepotDTO(route.getDepotId()));
return routeDTO;
}
@Override
public DepotDTO createDepotDTO(Depot depot)
{
DepotDTO depotDTO = new DepotDTO();
depotDTO.setDepotId(depot.getDepotId());
depotDTO.setName(depot.getName());
return depotDTO;
}
@Override
public ParcelDTO createParcelDTO(Parcel parcel)
{
ParcelDTO parcelDTO = new ParcelDTO();
parcelDTO.setParcelId(parcel.getParcelId());
parcelDTO.setRecipientName(parcel.getRecipientName());
parcelDTO.setAddressLine1(parcel.getAddressLine1());
if (parcel.getAddressLine2() != null)
{
parcelDTO.setAddressLine2(parcel.getAddressLine2());
}
parcelDTO.setPostcode(parcel.getPostcode());
parcelDTO.setCity(parcel.getCity());
return parcelDTO;
}
@Override
public DeliveryStatusDTO createDeliveryStatusDTO(DeliveryStatus deliveryStatus)
{
DeliveryStatusDTO deliveryStatusDTO = new DeliveryStatusDTO();
deliveryStatusDTO.setDeliveryStatusId(deliveryStatus.getDeliveryStatusId());
deliveryStatusDTO.setName(deliveryStatus.getName());
return deliveryStatusDTO;
}
@Override
public DeliveryDTO createDeliveryDTO(Delivery delivery)
{
DeliveryDTO deliveryDTO = new DeliveryDTO();
deliveryDTO.setDeliveryId(delivery.getDeliveryId());
deliveryDTO.setDeliveryDate(delivery.getDeliveryDate());
deliveryDTO.setDeliveryStatus(createDeliveryStatusDTO(delivery.getDeliveryStatusId()));
deliveryDTO.setParcel(createParcelDTO(delivery.getParcelId()));
if (delivery.getDepotId() != null)
{
deliveryDTO.setDepot(createDepotDTO(delivery.getDepotId()));
}
if (delivery.getRouteId() != null)
{
deliveryDTO.setRoute(createRouteDTO(delivery.getRouteId()));
}
return deliveryDTO;
}
@Override
public UserDTO createUserDTO(Users user)
{
UserDTO userDTO = new UserDTO();
userDTO.setId(user.getUserId());
userDTO.setForename(user.getForename());
userDTO.setSurname(user.getSurname());
userDTO.setDateOfBirth(user.getDob());
userDTO.setAddressLine1(user.getAddressLine1());
userDTO.setAddressLine2(user.getAddressLine2());
userDTO.setPostcode(user.getPostcode());
userDTO.setCity(user.getCity());
userDTO.setTelephone(user.getTelephone());
userDTO.setEmail(user.getEmail());
userDTO.setPassword(<PASSWORD>());
userDTO.setIsDriver(user.getIsDriver());
if (userDTO.isIsDriver())
{
userDTO.setDriverId(user.getDriverId());
if(user.getRouteId() != null)
{
userDTO.setRouteId(createRouteDTO(user.getRouteId()));
}
}
return userDTO;
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ViewModels/EditBookingViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels
{
public class EditBookingViewModel
{
[Required]
public long BookingId { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime EndDate { get; set; }
public Boolean StartHalfDay { get; set; }
public Boolean EndHalfDay { get; set; }
public Boolean LateReturn { get; set; }
public Boolean Collected { get; set; }
public decimal Price { get; set; }
public List<EquipmentCheckboxSelectViewModel> ChosenEquipmentList { get; set; }
public long VehicleId { get; set; }
public string VehicleName { get; set; }
public decimal VehicleCostPerDay { get; set; }
public string UserForename { get; set; }
public string UserSurname { get; set; }
}
}
<file_sep>/OOAE/T2/T2-05/wk2-05_lec1_VisitorProj/wk2-05_lec1_VisitorProj/src/Department/DepartmentVisitor.java
package Department;
/**
*
* @author <NAME>
*/
public abstract class DepartmentVisitor
{
void visitDepartment(Department d)
{
visitDepartment(d);
}
}<file_sep>/WMAD/CinemaBookingSystem/test/dto/FilmDTOTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author <NAME>
*/
public class FilmDTOTest
{
private FilmDTO film1;
public FilmDTOTest()
{
film1 = new FilmDTO(0, "title", 18, 120, "description");
}
@BeforeClass
public static void setUpClass()
{
}
@AfterClass
public static void tearDownClass()
{
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
/**
* Test of getFilmID method, of class FilmDTO.
*/
@Test
public void testGetFilmID()
{
System.out.println("getFilmID");
FilmDTO instance = film1;
int expResult = 0;
int result = instance.getFilmID();
assertEquals(expResult, result);
}
/**
* Test of getTitle method, of class FilmDTO.
*/
@Test
public void testGetTitle()
{
System.out.println("getTitle");
FilmDTO instance = film1;
String expResult = "title";
String result = instance.getTitle();
assertEquals(expResult, result);
}
/**
* Test of getAgeRating method, of class FilmDTO.
*/
@Test
public void testGetAgeRating()
{
System.out.println("getAgeRating");
FilmDTO instance = film1;
int expResult = 18;
int result = instance.getAgeRating();
assertEquals(expResult, result);
}
/**
* Test of getRuntime method, of class FilmDTO.
*/
@Test
public void testGetRuntime()
{
System.out.println("getRuntime");
FilmDTO instance = film1;
int expResult = 120;
int result = instance.getRuntime();
assertEquals(expResult, result);
}
/**
* Test of getDescription method, of class FilmDTO.
*/
@Test
public void testGetDescription()
{
System.out.println("getDescription");
FilmDTO instance = film1;
String expResult = "description";
String result = instance.getDescription();
assertEquals(expResult, result);
}
}
<file_sep>/OOAE/T2/T2-03/GuiObserverPatternProj/src/Subject/JButtonSubject.java
package Subject;
import Observer.Observer;
import java.util.ArrayList;
import javax.swing.JButton;
/**
*
* @author <NAME>
*/
public class JButtonSubject extends JButton implements Subject
{
private ArrayList<Observer> observers;
//Subject state
private int numberOfClicks;
public JButtonSubject(String buttonName)
{
super(buttonName);
observers = new ArrayList<>();
}
@Override
public void attach(Observer observer)
{
observers.add(observer);
}
@Override
public void detach(Observer observer)
{
observers.remove(observer);
}
@Override
public void notifyObservers()
{
for (Observer o : observers)
{
o.update(this);
}
}
public int getNumberOfClicks()
{
return numberOfClicks;
}
//Set state equivalent
public void incrementNumberOfclicks()
{
this.numberOfClicks++;
notifyObservers();
}
}
<file_sep>/OOAE/T2/T2-02/wk2-01_TutProj/src/Manager/DatabaseManager.java
package Manager;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Deals with database interactions.
* @author <NAME>
*/
public class DatabaseManager
{
private String username;
private String password;
private final String url;
private static DatabaseManager instance = new DatabaseManager();
protected DatabaseManager()
{
url = "jdbc:oracle:thin:@<EMAIL>:1521:stora";
}
public static DatabaseManager getInstance()
{
return instance;
}
public Connection getConnection() throws SQLException
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
return DriverManager.getConnection(url, username, password);
}
public void setUsername(String username)
{
this.username = username;
}
public void setPassword(String password)
{
this.password = <PASSWORD>;
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-war/src/java/managed_bean/RegisterBean.java
package managed_bean;
import dto.UserDTO;
import ejb.User_UIRemote;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
/**
*
* @author Rhys
*/
@Named(value = "registerBean")
@RequestScoped
public class RegisterBean
{
@EJB
private User_UIRemote userUI;
private String forename;
private String surname;
private Date dateOfBirth;
private String email;
private String password;
private String confirmPassword;
private String addressLine1;
private String addressLine2;
private String city;
private String postcode;
private String telephone;
private boolean registeredSuccessfully;
private UserDTO registeringUser;
public RegisterBean()
{
}
public String register()
{
if(!this.password.equals(this.confirmPassword))
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Passwords don't match"));
return null;
}
registeringUser = createNewUserDTO();
registeredSuccessfully = userUI.register(registeringUser);
if (registeredSuccessfully)
{
return "registered";
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Login credentials are not correct"));
return null;
}
}
public String getForename()
{
return forename;
}
public void setForename(String forename)
{
this.forename = forename;
}
public String getSurname()
{
return surname;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public Date getDateOfBirth()
{
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth)
{
this.dateOfBirth = dateOfBirth;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
try
{
byte[] hash
= MessageDigest.getInstance("SHA-256")
.digest(password.getBytes(StandardCharsets.UTF_8));
this.password
= Base64.getEncoder().encodeToString(hash);
}
catch (NoSuchAlgorithmException ex)
{
this.password = "";
Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String getConfirmPassword()
{
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword)
{
try
{
byte[] hash
= MessageDigest.getInstance("SHA-256")
.digest(confirmPassword.getBytes(StandardCharsets.UTF_8));
this.confirmPassword
= Base64.getEncoder().encodeToString(hash);
}
catch (NoSuchAlgorithmException ex)
{
this.confirmPassword = "";
Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String getAddressLine1()
{
return addressLine1;
}
public void setAddressLine1(String addressLine1)
{
this.addressLine1 = addressLine1;
}
public String getAddressLine2()
{
return addressLine2;
}
public void setAddressLine2(String addressLine2)
{
this.addressLine2 = addressLine2;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getPostcode()
{
return postcode;
}
public void setPostcode(String postcode)
{
this.postcode = postcode;
}
public String getTelephone()
{
return telephone;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public UserDTO createNewUserDTO()
{
UserDTO newUser = new UserDTO();
newUser.setForename(this.forename);
newUser.setSurname(this.surname);
newUser.setDateOfBirth(this.dateOfBirth);
newUser.setEmail(this.email);
newUser.setPassword(<PASSWORD>);
newUser.setAddressLine1(this.addressLine1);
newUser.setAddressLine2(this.addressLine2);
newUser.setCity(this.city);
newUser.setPostcode(this.postcode);
newUser.setTelephone(this.telephone);
return newUser;
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/GetTotalCostForSupplierTypeForStoreCommand.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using WPFDataParallelismProj.DTO;
using WPFDataParallelismProj.Handler;
namespace WPFDataParallelismProj.CommandsFactory
{
class GetTotalCostForSupplierTypeForStoreCommand : ICommand
{
private HashSet<Order> orders;
private Store store;
private string supplierType;
private OrderHandler orderHandler;
public GetTotalCostForSupplierTypeForStoreCommand(HashSet<Order> orders, Store store, string supplierType)
{
this.orders = orders;
this.store = store;
this.supplierType = supplierType;
orderHandler = new OrderHandler();
}
public async Task<object> Execute()
{
return await orderHandler.GetTotalCostForSupplierTypeForStore(orders, store, supplierType);
}
}
}<file_sep>/WMAD/CinemaBookingSystem/src/java/handler/ShowingHandler.java
package handler;
import dto.FilmDTO;
import dto.ScreenDTO;
import dto.ShowingDTO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
/**
*
* @author <NAME>
*/
public class ShowingHandler
{
private static ShowingHandler instance = null;
protected ShowingHandler()
{
}
public static ShowingHandler getInstance()
{
if (instance == null)
{
instance = new ShowingHandler();
}
return instance;
}
public ArrayList<ShowingDTO> getScreenShowings(ScreenDTO screen)
{
FilmHandler filmHndlr = new FilmHandler();
ArrayList<ShowingDTO> showings = new ArrayList();
ArrayList<FilmDTO> films = new ArrayList();
films = filmHndlr.getAllFilms();
Date time;
DatabaseHandler db = DatabaseHandler.getInstance();
try
{
Connection conn = db.getConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM showing WHERE (SCREEN_ID) = ?");
stmt.setInt(1, screen.getScreenID());
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
for (int i = 0; i < films.size(); i++)
{
if (rs.getInt("film_id") == films.get(i).getFilmID())
{
time = new Date(rs.getTime("time").getTime());
ShowingDTO showing = new ShowingDTO(rs.getInt("Showing_ID"), films.get(i), screen, time, rs.getInt("Available_Seats"));
showings.add(showing);
}
}
}
rs.close();
stmt.close();
conn.close();
}
catch (SQLException sqle)
{
System.out.println("ERROR\nCould not get Showings or Films.\n" + sqle);
}
return showings;
}
public ArrayList<ShowingDTO> getAllShowings()
{
FilmHandler filmHndlr = new FilmHandler();
ScreenHandler screenHndlr = new ScreenHandler();
ArrayList<ShowingDTO> showings = new ArrayList();
ArrayList<FilmDTO> films = filmHndlr.getAllFilms();
ArrayList<ScreenDTO> screens = screenHndlr.getAllScreens();
Date time;
DatabaseHandler db = DatabaseHandler.getInstance();
try
{
Connection conn = db.getConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM showing");
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
for (int i = 0; i < films.size(); i++)
{
if (rs.getInt("film_id") == films.get(i).getFilmID())
{
time = new Date(rs.getTime("time").getTime());
ShowingDTO showing = new ShowingDTO(rs.getInt("Showing_ID"), films.get(i), screens.get(i), time, rs.getInt("Available_Seats"));
showings.add(showing);
}
}
}
rs.close();
stmt.close();
conn.close();
}
catch (SQLException sqle)
{
System.out.println("ERROR\nCould not get Showings.\n" + sqle);
}
return showings;
}
public boolean addShowing(FilmDTO film, ScreenDTO screen, String time)
{
boolean insertOK = false;
DatabaseHandler db = DatabaseHandler.getInstance();
try
{
Connection conn = db.getConnection();
PreparedStatement stmt = conn.prepareStatement("INSERT INTO SHOWING (FILM_ID, SCREEN_ID, TIME, AVAILABLE_SEATS) values (?, ?, ?, ?)");
stmt.setInt(1, film.getFilmID());
stmt.setInt(2, screen.getScreenID());
stmt.setTime(3, java.sql.Time.valueOf(time));
stmt.setInt(4, 20);
int rows = stmt.executeUpdate();
insertOK = rows == 1;
stmt.close();
conn.close();
}
catch (SQLException sqle)
{
System.out.println("ERROR\nCOULD NOT INSERT SHOWING\n" + sqle);
}
return insertOK;
}
}
<file_sep>/OOAE/T1/T1-09/VehicleShowroomProj/test/vehicleshowroomproj/VehicleTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vehicleshowroomproj;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Rhysj
*/
public class VehicleTest
{
public VehicleTest()
{
}
@BeforeClass
public static void setUpClass()
{
}
@AfterClass
public static void tearDownClass()
{
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
/**
* Test of setManufacturer method, of class Vehicle.
*/
@Test
public void testSetManufacturer()
{
System.out.println("setManufacturer");
String manufacturer = "";
Vehicle instance = null;
instance.setManufacturer(manufacturer);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getManufacturer method, of class Vehicle.
*/
@Test
public void testGetManufacturer()
{
System.out.println("getManufacturer");
Vehicle instance = null;
String expResult = "";
String result = instance.getManufacturer();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setModel method, of class Vehicle.
*/
@Test
public void testSetModel()
{
System.out.println("setModel");
String model = "";
Vehicle instance = null;
instance.setModel(model);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getModel method, of class Vehicle.
*/
@Test
public void testGetModel()
{
System.out.println("getModel");
Vehicle instance = null;
String expResult = "";
String result = instance.getModel();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setCustName method, of class Vehicle.
*/
@Test
public void testSetCustName()
{
System.out.println("setCustName");
String name = "";
Vehicle instance = null;
instance.setCustName(name);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getCustName method, of class Vehicle.
*/
@Test
public void testGetCustName()
{
System.out.println("getCustName");
Vehicle instance = null;
String expResult = "";
String result = instance.getCustName();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setVehicleIdentificationNumber method, of class Vehicle.
*/
@Test
public void testSetVehicleIdentificationNumber()
{
System.out.println("setVehicleIdentificationNumber");
String vehicleIdentificationNumber = "";
Vehicle instance = null;
instance.setVehicleIdentificationNumber(vehicleIdentificationNumber);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getVehicleIdentificationNumber method, of class Vehicle.
*/
@Test
public void testGetVehicleIdentificationNumber()
{
System.out.println("getVehicleIdentificationNumber");
Vehicle instance = null;
String expResult = "";
String result = instance.getVehicleIdentificationNumber();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setManufactureDate method, of class Vehicle.
*/
@Test
public void testSetManufactureDate()
{
System.out.println("setManufactureDate");
String manufactureDate = "";
Vehicle instance = null;
instance.setManufactureDate(manufactureDate);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getManufactureDate method, of class Vehicle.
*/
@Test
public void testGetManufactureDate()
{
System.out.println("getManufactureDate");
Vehicle instance = null;
String expResult = "";
String result = instance.getManufactureDate();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setDateSold method, of class Vehicle.
*/
@Test
public void testSetDateSold()
{
System.out.println("setDateSold");
String dateSold = "";
Vehicle instance = null;
instance.setDateSold(dateSold);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getDateSold method, of class Vehicle.
*/
@Test
public void testGetDateSold()
{
System.out.println("getDateSold");
Vehicle instance = null;
String expResult = "";
String result = instance.getDateSold();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of isSold method, of class Vehicle.
*/
@Test
public void testIsSold()
{
System.out.println("isSold");
Vehicle instance = null;
boolean expResult = false;
boolean result = instance.isSold();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setIsSold method, of class Vehicle.
*/
@Test
public void testSetIsSold()
{
System.out.println("setIsSold");
boolean isSold = false;
Vehicle instance = null;
instance.setIsSold(isSold);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getTaxBand method, of class Vehicle.
*/
@Test
public void testGetTaxBand()
{
System.out.println("getTaxBand");
Vehicle instance = null;
char expResult = ' ';
char result = instance.getTaxBand();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setTaxBand method, of class Vehicle.
*/
@Test
public void testSetTaxBand()
{
System.out.println("setTaxBand");
char taxBand = ' ';
Vehicle instance = null;
instance.setTaxBand(taxBand);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getCost method, of class Vehicle.
*/
@Test
public void testGetCost()
{
System.out.println("getCost");
Vehicle instance = null;
int expResult = 0;
int result = instance.getCost();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setCost method, of class Vehicle.
*/
@Test
public void testSetCost()
{
System.out.println("setCost");
int cost = 0;
Vehicle instance = null;
instance.setCost(cost);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of buy method, of class Vehicle.
*/
@Test
public void testBuy()
{
System.out.println("buy");
String dateSold = "";
String custName = "";
Vehicle instance = null;
instance.buy(dateSold, custName);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of toString method, of class Vehicle.
*/
@Test
public void testToString()
{
System.out.println("toString");
Vehicle instance = null;
String expResult = "";
String result = instance.toString();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of co2Emissions method, of class Vehicle.
*/
@Test
public void testCo2Emissions()
{
System.out.println("co2Emissions");
char taxBand = ' ';
Vehicle instance = null;
String expResult = "";
String result = instance.co2Emissions(taxBand);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/GetVehicleTypesCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class GetVehicleTypesCommand : ICommand
{
private VehicleHandler VehicleHandler;
public GetVehicleTypesCommand(ApplicationDbContext dbContext)
{
VehicleHandler = new VehicleHandler(dbContext);
}
public async Task<object> Execute()
{
return await VehicleHandler.GetVehicleTypes();
}
}
}
<file_sep>/WMAD/CinemaBookingSystem/src/java/customerUI/GetScreenShowingsCommand.java
package customerUI;
import dto.ScreenDTO;
import handler.ShowingHandler;
/**
*
* @author <NAME>
*/
public class GetScreenShowingsCommand implements CustomerCommand
{
private final ScreenDTO screen;
private ShowingHandler showingHndlr = null;
public GetScreenShowingsCommand(ScreenDTO screen)
{
this.screen = screen;
showingHndlr = ShowingHandler.getInstance();
}
@Override
public Object execute()
{
return showingHndlr.getScreenShowings(screen);
}
}
<file_sep>/CNA/SimpleClientServer/Packet/PacketType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Packets
{
public enum PacketType
{
EMPTY,
NICKNAME,
CHATMESSAGE,
BUYPRODUCT,
SELLPRODUCT
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/DTO/Supplier.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFDataParallelismProj.DTO
{
class Supplier
{
public String SupplierName { get; set; }
public String SupplierType { get; set; }
public Supplier()
: this("", "")
{
}
public Supplier(String supplierName, String supplierType)
{
this.SupplierName = supplierName;
this.SupplierType = supplierType;
}
override
public String ToString()
{
return SupplierName + ", " + SupplierType;
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/GetCoincidingBookingsCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class GetCoincidingBookingsCommand : ICommand
{
private DateTime RequestedStartDate;
private DateTime RequestedEndDate;
private BookingHandler BookingHandler;
public GetCoincidingBookingsCommand(DateTime requestedStartDate, DateTime requestedEndDate, ApplicationDbContext dbContext)
{
BookingHandler = new BookingHandler(dbContext);
RequestedStartDate = requestedStartDate;
RequestedEndDate = requestedEndDate;
}
public async Task<object> Execute()
{
return await BookingHandler.GetCoincidingBookings(RequestedStartDate, RequestedEndDate);
}
}
}
<file_sep>/OOAE/T1/T1-09/cardDeckProj/src/carddeckproj/DisplayableCard.java
package carddeckproj;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
public class DisplayableCard extends Card implements Displayable
{
private Image image;
private String imageFilename = "";
public DisplayableCard(Rank rank, Suit suit)
{
super(rank, suit);
}
@Override
public void display(Graphics g, int x, int y)
{
image = new ImageIcon(getClass().getResource("/images/" + getCardNumber() + ".png")).getImage();
g.drawImage(image, x, y, null);
}
private int getCardNumber()
{
return (super.getSuit().ordinal() * 13) + super.getRank().ordinal();
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/DataParallelismProj/CommandsFactory/GetAllStoresCommand.cs
using DataParallelismProj.Handler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataParallelismProj.CommandsFactory
{
class GetAllStoresCommand : ICommand
{
StoreHandler storeHandler = null;
public GetAllStoresCommand()
{
storeHandler = new StoreHandler();
}
public object Execute()
{
return storeHandler.GetAllStores();
}
}
}
<file_sep>/ESA/Flights Management/src/GUI/SearchPassenger.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import command.CommandFactory;
import database.FlightAndPassengers;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
import java.text.NumberFormat;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JPanel;
import javax.swing.text.NumberFormatter;
/**
*
* @author danpa
*/
public class SearchPassenger extends javax.swing.JFrame
{
NumberFormatter formatter;
JPanel panel;
public SearchPassenger()
{
NumberFormat format = NumberFormat.getInstance();
format.setGroupingUsed(false);
formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setMaximum(Integer.MAX_VALUE);
formatter.setAllowsInvalid(true);
initComponents();
this.panel = jPanel1;
ArrayList<String> Risklabels = (ArrayList<String>) CommandFactory.create(CommandFactory.GET_ALL_RISKS).execute();
ArrayList<Integer> Flightlabels = (ArrayList<Integer>) CommandFactory.create(CommandFactory.GET_ALL_FLIGHT_NUMBERS).execute();
jComboBox1.setModel(new DefaultComboBoxModel(Risklabels.toArray()));
jComboBox2.setModel(new DefaultComboBoxModel(Flightlabels.toArray()));
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public JPanel getPanel()
{
return panel;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jCheckBox1 = new javax.swing.JCheckBox();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jTextField2 = new javax.swing.JTextField();
jFormattedTextField4 = new javax.swing.JFormattedTextField(formatter);
jButton1 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jFormattedTextField3 = new javax.swing.JFormattedTextField(formatter);
jComboBox1 = new javax.swing.JComboBox<>();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox<>();
jLabel10 = new javax.swing.JLabel();
jButton7 = new javax.swing.JButton();
jFormattedTextField2 = new javax.swing.JFormattedTextField(formatter);
jButton8 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jCheckBox1.setText("jCheckBox1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel2.setText("Select a criteria to search by: ");
jLabel6.setText("Passport Number");
jLabel1.setText("Search for a passenger:");
jLabel3.setText("Surname: ");
jLabel7.setText("Results:");
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton1.setText("Search by Surname");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton3.setText("Search by passport num");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jLabel5.setText("Risk score - enter minimum: ");
jLabel8.setText("Risk factor: ");
jFormattedTextField3.setToolTipText("");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jButton4.setText("Search by risk score");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton5.setText("Search by risk factor");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jLabel4.setText("Search for a flight: ");
jLabel9.setText("Flight number: ");
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel10.setText("Risk score - enter minimum:");
jButton7.setText("Search by flight number");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jButton8.setText("Search by risk score");
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
jButton6.setText("Clear");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(143, 143, 143)
.addComponent(jLabel6))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jFormattedTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jFormattedTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton8, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(0, 610, Short.MAX_VALUE))
.addComponent(jScrollPane1))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(jLabel7)
.addGap(27, 27, 27)
.addComponent(jScrollPane1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addGap(27, 27, 27)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel6))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jFormattedTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton3))
.addGap(41, 41, 41)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jFormattedTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton4)
.addComponent(jButton5))
.addGap(37, 37, 37)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(jLabel10))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton7)
.addComponent(jButton8))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 164, Short.MAX_VALUE)
.addComponent(jButton6)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
ArrayList<String> labels = (ArrayList<String>) CommandFactory.create(CommandFactory.SEARCH_PASSENGERS_BY_SURNAME, jTextField2.getText()).execute();
populatePanel(labels);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
ArrayList<String> labels = (ArrayList<String>) CommandFactory.create(CommandFactory.SEARCH_PASSENGERS_BY_PASSPORT_NUM, Integer.parseInt(jFormattedTextField4.getText())).execute();
populatePanel(labels);
System.out.println(jFormattedTextField2.getText());
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
ArrayList<String> labels = (ArrayList<String>) CommandFactory.create(CommandFactory.VIEW_ALL_PASSENGERS_RISKS_WITH_MIN, Integer.parseInt(jFormattedTextField3.getText())).execute();
populatePanel(labels);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
ArrayList<String> labels = (ArrayList<String>) CommandFactory.create(CommandFactory.VIEW_ALL_PASSENGERS_RISKS_WITH_TYPE, (jComboBox1.getSelectedIndex())).execute();
populatePanel(labels);
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
jTextField2.setText("");
jFormattedTextField2.setText("");
jFormattedTextField3.setText("");
jFormattedTextField4.setText("");
jTextArea1.setText(null);
}//GEN-LAST:event_jButton6ActionPerformed
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
ArrayList<String> FlightLabels = (ArrayList<String>) CommandFactory.create(CommandFactory.VIEW_FLIGHT, (jComboBox2.getSelectedIndex())).execute();
populatePanel(FlightLabels);
jTextArea1.append((String) CommandFactory.create(CommandFactory.CHECK_PASSENGERS_ON_FLIGHT, (jComboBox2.getSelectedIndex())).execute());
}//GEN-LAST:event_jButton7ActionPerformed
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
try {
ArrayList<FlightAndPassengers> flights = (ArrayList<FlightAndPassengers>) CommandFactory.create(CommandFactory.GET_FLIGHTS_BY_MIN_RISK, Integer.parseInt(jFormattedTextField2.getText())).execute();
for (FlightAndPassengers flight : flights) {
jTextArea1.append(flight.toStringRiskyPassengers()+ "\n-----------------------------------------------------------------------------------------------\n");
}
} catch (Exception ex) {
jTextArea1.append("Not a number" + "\n");
}
}//GEN-LAST:event_jButton8ActionPerformed
private void populatePanel(ArrayList<String> labels) {
if (labels.size() != 0) {
for (String label : labels)
{
jTextArea1.append("\n" + label);
}
}
else
{
jTextArea1.append("\nNone found!");
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[])
{
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
{
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName()))
{
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (ClassNotFoundException ex)
{
java.util.logging.Logger.getLogger(SearchPassenger.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(SearchPassenger.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(SearchPassenger.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(SearchPassenger.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new SearchPassenger().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JComboBox<String> jComboBox2;
private javax.swing.JFormattedTextField jFormattedTextField2;
private javax.swing.JFormattedTextField jFormattedTextField3;
private javax.swing.JFormattedTextField jFormattedTextField4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField2;
// End of variables declaration//GEN-END:variables
}
<file_sep>/WMAD/WMAD_assignment_2/app/src/main/java/com/example/rhysj/wmad_assignment_2/MainActivity.java
package com.example.rhysj.wmad_assignment_2;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.*;
import com.android.volley.toolbox.*;
import com.example.rhysj.wmad_assignment_2.DTO.ScreenDTO;
import com.example.rhysj.wmad_assignment_2.ListAdapter.ScreenListAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements Response.Listener<String>, AdapterView.OnItemClickListener
{
private NavigationSlider navView;
private ArrayList<ScreenDTO> cinemaScreens;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Sets which xml file to load
setContentView(R.layout.activity_main);
navView = new NavigationSlider(this);
getSupportActionBar().setTitle("View Cinemas");
viewCinemas();
}
@Override
public void onBackPressed()
{
if(!navView.backPressed())
{
super.onBackPressed();
}
}
public void viewCinemas()
{
BaseConnectionHandler BCH = new BaseConnectionHandler();
String urlPath = BCH.baseConnection + "/CustomerUI/screen";
StringRequest stringRequest = new StringRequest(Request.Method.GET, urlPath, this,
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
}
@Override
public void onResponse(String response)
{
Gson gson = new Gson();
cinemaScreens = gson.fromJson(response, new TypeToken<ArrayList<ScreenDTO>>(){}.getType());
ListView list = findViewById(R.id.screens_listview);
ScreenListAdapter adapter = new ScreenListAdapter(cinemaScreens, this);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
ScreenDTO selectedScreen = cinemaScreens.get(position);
Intent intent = new Intent(this, ViewShowingsActivity.class);
intent.putExtra("selectedScreen", selectedScreen);
startActivity(intent);
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Migrations/20200830115318_ModelFixedDuplicateIds.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace AnimalCareSystem.Migrations
{
public partial class ModelFixedDuplicateIds : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Message_AspNetUsers_ReceivingUserId1",
table: "Message");
migrationBuilder.DropForeignKey(
name: "FK_Message_AspNetUsers_SendingUserId1",
table: "Message");
migrationBuilder.DropForeignKey(
name: "FK_UserReview_AspNetUsers_ReceivingUserId1",
table: "UserReview");
migrationBuilder.DropForeignKey(
name: "FK_UserReview_AspNetUsers_ReviewingUserId1",
table: "UserReview");
migrationBuilder.DropIndex(
name: "IX_UserReview_ReceivingUserId1",
table: "UserReview");
migrationBuilder.DropIndex(
name: "IX_UserReview_ReviewingUserId1",
table: "UserReview");
migrationBuilder.DropIndex(
name: "IX_Message_ReceivingUserId1",
table: "Message");
migrationBuilder.DropIndex(
name: "IX_Message_SendingUserId1",
table: "Message");
migrationBuilder.DropColumn(
name: "ReceivingUserId1",
table: "UserReview");
migrationBuilder.DropColumn(
name: "ReviewingUserId1",
table: "UserReview");
migrationBuilder.DropColumn(
name: "ReceivingUserId1",
table: "Message");
migrationBuilder.DropColumn(
name: "SendingUserId1",
table: "Message");
migrationBuilder.AlterColumn<string>(
name: "ReviewingUserId",
table: "UserReview",
nullable: false,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.AlterColumn<string>(
name: "ReceivingUserId",
table: "UserReview",
nullable: false,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.AddColumn<string>(
name: "Title",
table: "UserReview",
nullable: true);
migrationBuilder.AlterColumn<string>(
name: "SendingUserId",
table: "Message",
nullable: false,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.AlterColumn<string>(
name: "ReceivingUserId",
table: "Message",
nullable: false,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.CreateIndex(
name: "IX_UserReview_ReceivingUserId",
table: "UserReview",
column: "ReceivingUserId");
migrationBuilder.CreateIndex(
name: "IX_UserReview_ReviewingUserId",
table: "UserReview",
column: "ReviewingUserId");
migrationBuilder.CreateIndex(
name: "IX_Message_ReceivingUserId",
table: "Message",
column: "ReceivingUserId");
migrationBuilder.CreateIndex(
name: "IX_Message_SendingUserId",
table: "Message",
column: "SendingUserId");
migrationBuilder.AddForeignKey(
name: "FK_Message_AspNetUsers_ReceivingUserId",
table: "Message",
column: "ReceivingUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Message_AspNetUsers_SendingUserId",
table: "Message",
column: "SendingUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
migrationBuilder.AddForeignKey(
name: "FK_UserReview_AspNetUsers_ReceivingUserId",
table: "UserReview",
column: "ReceivingUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_UserReview_AspNetUsers_ReviewingUserId",
table: "UserReview",
column: "ReviewingUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Message_AspNetUsers_ReceivingUserId",
table: "Message");
migrationBuilder.DropForeignKey(
name: "FK_Message_AspNetUsers_SendingUserId",
table: "Message");
migrationBuilder.DropForeignKey(
name: "FK_UserReview_AspNetUsers_ReceivingUserId",
table: "UserReview");
migrationBuilder.DropForeignKey(
name: "FK_UserReview_AspNetUsers_ReviewingUserId",
table: "UserReview");
migrationBuilder.DropIndex(
name: "IX_UserReview_ReceivingUserId",
table: "UserReview");
migrationBuilder.DropIndex(
name: "IX_UserReview_ReviewingUserId",
table: "UserReview");
migrationBuilder.DropIndex(
name: "IX_Message_ReceivingUserId",
table: "Message");
migrationBuilder.DropIndex(
name: "IX_Message_SendingUserId",
table: "Message");
migrationBuilder.DropColumn(
name: "Title",
table: "UserReview");
migrationBuilder.AlterColumn<int>(
name: "ReviewingUserId",
table: "UserReview",
type: "int",
nullable: false,
oldClrType: typeof(string));
migrationBuilder.AlterColumn<int>(
name: "ReceivingUserId",
table: "UserReview",
type: "int",
nullable: false,
oldClrType: typeof(string));
migrationBuilder.AddColumn<string>(
name: "ReceivingUserId1",
table: "UserReview",
type: "nvarchar(450)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ReviewingUserId1",
table: "UserReview",
type: "nvarchar(450)",
nullable: true);
migrationBuilder.AlterColumn<int>(
name: "SendingUserId",
table: "Message",
type: "int",
nullable: false,
oldClrType: typeof(string));
migrationBuilder.AlterColumn<int>(
name: "ReceivingUserId",
table: "Message",
type: "int",
nullable: false,
oldClrType: typeof(string));
migrationBuilder.AddColumn<string>(
name: "ReceivingUserId1",
table: "Message",
type: "nvarchar(450)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "SendingUserId1",
table: "Message",
type: "nvarchar(450)",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_UserReview_ReceivingUserId1",
table: "UserReview",
column: "ReceivingUserId1");
migrationBuilder.CreateIndex(
name: "IX_UserReview_ReviewingUserId1",
table: "UserReview",
column: "ReviewingUserId1");
migrationBuilder.CreateIndex(
name: "IX_Message_ReceivingUserId1",
table: "Message",
column: "ReceivingUserId1");
migrationBuilder.CreateIndex(
name: "IX_Message_SendingUserId1",
table: "Message",
column: "SendingUserId1");
migrationBuilder.AddForeignKey(
name: "FK_Message_AspNetUsers_ReceivingUserId1",
table: "Message",
column: "ReceivingUserId1",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Message_AspNetUsers_SendingUserId1",
table: "Message",
column: "SendingUserId1",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserReview_AspNetUsers_ReceivingUserId1",
table: "UserReview",
column: "ReceivingUserId1",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserReview_AspNetUsers_ReviewingUserId1",
table: "UserReview",
column: "ReviewingUserId1",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ApplicationUI/RegisterCommand.cs
using AnimalCareSystem.Handlers;
using AnimalCareSystem.Models;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ApplicationUI
{
public class RegisterCommand : ICommand
{
private AccountHandler AccountHandler;
private ApplicationUser NewUser;
public RegisterCommand(ApplicationUser newUser, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
NewUser = newUser;
AccountHandler = new AccountHandler(userManager, signInManager);
}
public async Task<object> Execute()
{
return await AccountHandler.RegisterUser(NewUser);
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/application_ui/DeleteAccountCommandLocal.java
package application_ui;
import dto.UserDTO;
import javax.ejb.Local;
/**
*
* @author Rhys
*/
@Local
public interface DeleteAccountCommandLocal extends Command
{
@Override
public Object execute();
void setUser(UserDTO user);
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Controllers/BookingController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Http;
using System.IO;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Controllers
{
public class BookingController : Controller
{
private ViewVehicleBookingsViewModel ViewVehicleBookingsViewModel;
private List<VehicleBookingsViewModel> VehicleBookingModels;
private List<UserBookingsViewModel> UserBookingModels;
private List<EquipmentCheckboxSelectViewModel> EquipmentCheckboxSelect;
private BookVehicleViewModel BookVehicleViewModel;
private ApplicationDbContext DbContext;
private readonly UserManager<ApplicationUser> _userManager;
private long VehicleId;
private string errorString = "";
public BookingController(ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager)
{
DbContext = dbContext;
_userManager = userManager;
}
[HttpGet]
public async Task<IActionResult> BookVehicle(int? id)
{
IActionResult authenticationResult = await AuthenticateUserLogin(false);
if(authenticationResult != null)
{
return authenticationResult;
}
ApplicationUser CurrentUser = await _userManager.GetUserAsync(HttpContext.User);
if (CurrentUser.Blacklisted == true)
{
TempData["errormessage"] = "You are unable to book a vehicle due to a prior failure to collect a booked vehicle. Please contact us directly if you wish you rectify this issue.";
return RedirectToAction("Index", "Home");
}
BookVehicleViewModel = new BookVehicleViewModel();
EquipmentCheckboxSelect = new List<EquipmentCheckboxSelectViewModel>();
BookVehicleViewModel.UserId = CurrentUser.Id;
if (id > 0)
{
VehicleId = (int)id;
ViewData["ChosenVehicle"] = await GetChosenVehicle(VehicleId);
List<Equipment> equipmentList = (List<Equipment>)await CommandFactory.CreateCommand(CommandFactory.GET_ALL_EQUIPMENT, DbContext).Execute();
BookVehicleViewModel.ChosenEquipmentList = CreateEquipmentCheckboxSelectList(equipmentList);
return View(BookVehicleViewModel);
}
else
{
TempData["errormessage"] = "Something went wrong! If this error persists, please contact us directly.";
return View(BookVehicleViewModel);
}
}
[HttpPost]
public async Task<IActionResult> BookVehicle(BookVehicleViewModel bookVehicleViewModel)
{
IActionResult authenticationResult = await AuthenticateUserLogin(false);
if (authenticationResult != null)
{
return authenticationResult;
}
bool bookingValid = ValidateBooking(bookVehicleViewModel);
if(bookingValid)
{
List<Equipment> chosenEquipmentList = new List<Equipment>();
List<Booking> coincidingBookings = (List<Booking>)await CommandFactory.CreateCommand(CommandFactory.CHECK_FOR_COINCIDING_BOOKINGS, bookVehicleViewModel.StartDate, bookVehicleViewModel.EndDate, DbContext).Execute();
if (coincidingBookings.Count > 0)
{
foreach (Booking coincidingBooking in coincidingBookings)
{
if (bookVehicleViewModel.ChosenVehicleId == coincidingBooking.Vehicle.Id)
{
ViewData["ChosenVehicle"] = await GetChosenVehicle(bookVehicleViewModel.ChosenVehicleId);
ModelState.AddModelError("", "The vehicle is not available for the period of your booking. It is booked between " + coincidingBooking.StartDate.AddDays(-1).ToString("dd/MM/yyyy") + " and " + coincidingBooking.EndDate.AddDays(-1).ToString("dd/MM/yyyy"));
return View(bookVehicleViewModel);
}
}
foreach (EquipmentCheckboxSelectViewModel equipmentCheckbox in bookVehicleViewModel.ChosenEquipmentList)
{
if (equipmentCheckbox.CheckboxAnswer == true)
{
Equipment tempEquipment = new Equipment();
tempEquipment.Id = equipmentCheckbox.Id;
tempEquipment.Name = equipmentCheckbox.Name;
bool equipmentAvailable = (bool)await CommandFactory.CreateCommand(CommandFactory.CHECK_EQUIPMENT_AVAILABILITY, coincidingBookings, tempEquipment, DbContext).Execute();
if (equipmentAvailable == true)
{
chosenEquipmentList.Add(tempEquipment);
}
else
{
ViewData["ChosenVehicle"] = await GetChosenVehicle(bookVehicleViewModel.ChosenVehicleId);
errorString = equipmentCheckbox.Name + " is not available for the period of your booking. Please select a different booking period, or continue without this equipment item.";
ModelState.AddModelError("", errorString);
return View(bookVehicleViewModel);
}
}
}
}
Booking newBooking = ConvertViewModelToBooking(bookVehicleViewModel);
int bookingAdded = (int)await CommandFactory.CreateCommand(CommandFactory.ADD_BOOKING, newBooking, chosenEquipmentList, DbContext).Execute();
if (bookingAdded >= 1)
{
TempData["successmessage"] = "Booking successfully created!";
return RedirectToAction("Index", "Home");
}
else
{
ViewData["ChosenVehicle"] = await GetChosenVehicle(VehicleId);
errorString = "Something went wrong, please try again.";
ModelState.AddModelError("", errorString);
return View(bookVehicleViewModel);
}
}
ViewData["ChosenVehicle"] = await GetChosenVehicle(VehicleId);
return View(bookVehicleViewModel);
}
[HttpGet]
public async Task<IActionResult> ViewVehicleBookings(long? id)
{
IActionResult authenticationResult = await AuthenticateUserLogin(true);
if (authenticationResult != null)
{
return authenticationResult;
}
if (id > 0)
{
VehicleId = (long)id;
VehicleBookingModels = new List<VehicleBookingsViewModel>();
ViewVehicleBookingsViewModel = new ViewVehicleBookingsViewModel();
ViewData["ChosenVehicle"] = await GetChosenVehicle(VehicleId);
List<Booking> vehicleBookings = new List<Booking>();
vehicleBookings = (List<Booking>) await CommandFactory.CreateCommand(CommandFactory.GET_ALL_BOOKINGS_FOR_VEHICLE, VehicleId, DbContext).Execute();
ViewVehicleBookingsViewModel.VehicleBookingModels = CreateVehicleBookingModels(vehicleBookings);
return View(ViewVehicleBookingsViewModel);
}
else
{
TempData["errormessage"] = "Something went wrong! If this error persists, please contact an administrator.";
return RedirectToAction("Index", "Home");
}
}
[HttpGet]
public async Task<IActionResult> EditBooking(long? id)
{
IActionResult authenticationResult = await AuthenticateUserLogin(false);
if (authenticationResult != null)
{
return authenticationResult;
}
EquipmentCheckboxSelect = new List<EquipmentCheckboxSelectViewModel>();
long bookingId = (long)id;
List<Equipment> equipmentList = (List<Equipment>)await CommandFactory.CreateCommand(CommandFactory.GET_ALL_EQUIPMENT, DbContext).Execute();
Booking bookingToEdit = (Booking)await CommandFactory.CreateCommand(CommandFactory.GET_BOOKING, bookingId, DbContext).Execute();
EditBookingViewModel editBookingViewModel = CreateEditBookingViewModel(bookingToEdit);
editBookingViewModel.ChosenEquipmentList = CreateEquipmentCheckboxSelectList(equipmentList);
foreach(EquipmentCheckboxSelectViewModel item in editBookingViewModel.ChosenEquipmentList)
{
foreach(EquipmentBooking equipmentBooking in bookingToEdit.EquipmentBookings)
{
if(item.Id == equipmentBooking.Equipment.Id)
{
item.CheckboxAnswer = true;
}
}
}
return View(editBookingViewModel);
}
[HttpPost]
public async Task<IActionResult> EditBooking(EditBookingViewModel editBookingViewModel)
{
IActionResult authenticationResult = await AuthenticateUserLogin(false);
if (authenticationResult != null)
{
return authenticationResult;
}
bool bookingValid = ValidateBooking(editBookingViewModel);
if (bookingValid)
{
List<Equipment> chosenEquipmentList = new List<Equipment>();
List<Booking> coincidingBookings = (List<Booking>)await CommandFactory.CreateCommand(CommandFactory.CHECK_FOR_COINCIDING_BOOKINGS, editBookingViewModel.StartDate, editBookingViewModel.EndDate, DbContext).Execute();
for(int i = 0; i < coincidingBookings.Count; i++)
{
if(coincidingBookings[i].Id == editBookingViewModel.BookingId)
{
coincidingBookings.RemoveAt(i);
break;
}
}
if (coincidingBookings.Count > 0)
{
foreach (Booking coincidingBooking in coincidingBookings)
{
if (editBookingViewModel.VehicleId == coincidingBooking.Vehicle.Id)
{
ViewData["ChosenVehicle"] = await GetChosenVehicle(editBookingViewModel.VehicleId);
ModelState.AddModelError("", "The vehicle is not available for the period of your booking. The latest you can book this vehicle until is " + coincidingBooking.StartDate.AddDays(-1).ToString("dd/MM/yyyy"));
return View(editBookingViewModel);
}
}
foreach (EquipmentCheckboxSelectViewModel equipmentCheckbox in editBookingViewModel.ChosenEquipmentList)
{
if (equipmentCheckbox.CheckboxAnswer == true)
{
Equipment tempEquipment = new Equipment();
tempEquipment.Id = equipmentCheckbox.Id;
tempEquipment.Name = equipmentCheckbox.Name;
bool equipmentAvailable = (bool)await CommandFactory.CreateCommand(CommandFactory.CHECK_EQUIPMENT_AVAILABILITY, coincidingBookings, tempEquipment, DbContext).Execute();
if (equipmentAvailable == true)
{
chosenEquipmentList.Add(tempEquipment);
}
else
{
errorString = "A " + equipmentCheckbox.Name + " is not available for the period of your booking. Please select a different booking period, or continue without this equipment item.";
ModelState.AddModelError("", errorString);
return View(editBookingViewModel);
}
}
}
}
Booking booking = ConvertViewModelToBooking(editBookingViewModel);
if(booking == null)
{
errorString = "Something went wrong, please try again.";
ModelState.AddModelError("", errorString);
return View(editBookingViewModel);
}
int bookingUpdated = (int)await CommandFactory.CreateCommand(CommandFactory.UPDATE_BOOKING, booking, chosenEquipmentList, DbContext).Execute();
if (bookingUpdated >= 1)
{
TempData["successmessage"] = "Booking Updated Successfully.";
return RedirectToAction("Index", "Home");
}
else
{
errorString = "Something went wrong, please try again.";
ModelState.AddModelError("", errorString);
return View(editBookingViewModel);
}
}
return View(editBookingViewModel);
}
public async Task<IActionResult> DeleteBooking(long? id)
{
IActionResult authenticationResult = await AuthenticateUserLogin(false);
if (authenticationResult != null)
{
return authenticationResult;
}
long bookingId = (long)id;
int bookingDeleted = (int)await CommandFactory.CreateCommand(CommandFactory.DELETE_BOOKING, bookingId, DbContext).Execute();
if(bookingDeleted < 1)
{
errorString = "Something went wrong, please try again.";
ModelState.AddModelError("", errorString);
return View();
}
TempData["successmessage"] = "Booking Deleted Successfully!";
return RedirectToAction("Index", "Home");
}
[HttpGet]
public async Task<IActionResult> CollectBooking(long? id)
{
IActionResult authenticationResult = await AuthenticateUserLogin(true);
if (authenticationResult != null)
{
return authenticationResult;
}
long bookingId = (long)id;
Booking userBooking = (Booking)await CommandFactory.CreateCommand(CommandFactory.GET_BOOKING, bookingId, DbContext).Execute();
CollectBookingViewModel collectBookingViewModel = new CollectBookingViewModel();
collectBookingViewModel.BookingId = (int)bookingId;
collectBookingViewModel.DrivingLicenseNumber = userBooking.User.LicenseNumber;
return View(collectBookingViewModel);
}
[HttpPost]
public async Task<IActionResult> CollectBooking(CollectBookingViewModel collectBookingViewModel)
{
//Check the user is an admin.
IActionResult authenticationResult = await AuthenticateUserLogin(true);
if (authenticationResult != null)
{
return authenticationResult;
}
//get the full booking record
int bookingId = collectBookingViewModel.BookingId;
Booking userBooking = (Booking)await CommandFactory.CreateCommand(CommandFactory.GET_BOOKING, bookingId, DbContext).Execute();
//Create a unique folder path based on the booking users name and license number, then upload the file to that folder.
string folderPath = GenerateUserBasedFolderPath(userBooking.User);
string uploadedFilePath = await UploadIdentificationFile(collectBookingViewModel.AdditionalIdentificationImage, folderPath);
if(uploadedFilePath.Equals("uploadFailed"))
{
errorString = "Something went wrong, please try again.";
ModelState.AddModelError("", errorString);
return View();
}
else
{
//Update the bookee's user data with the file path for the identification image.
userBooking.User.IdentificationFolderSource = uploadedFilePath;
int userUpdated = (int) await CommandFactory.CreateCommand(CommandFactory.UPDATE_USER, userBooking.User, DbContext, _userManager).Execute();
if(userUpdated < 1)
{
errorString = "Something went wrong, please try again.";
ModelState.AddModelError("", errorString);
return View();
}
}
//Check if the user's license is still valid, or whether it has been reported as lost, stolen or suspended
bool userLicenseInvalid;
try
{
userLicenseInvalid = await CheckIfUserLicenseValid(userBooking.User);
}
catch (Exception e)
{
TempData["errormessage"] = e.Message;
return View();
}
//If the user's license is valid, then we check whether they have previously committed insurance fraud.
if (!userLicenseInvalid)
{
bool userCommittedInsuranceFraud;
try
{
userCommittedInsuranceFraud = await CheckIfUserCommittedInsuranceFraud(userBooking.User);
}
catch (Exception e)
{
TempData["errormessage"] = e.Message;
return View();
}
//If the user committed insurance fraud, then alert the admin and delete the booking.
if(userCommittedInsuranceFraud)
{
int bookingDeleted = (int)await CommandFactory.CreateCommand(CommandFactory.DELETE_BOOKING, bookingId, DbContext).Execute();
errorString = "This booking can not be collected: The person who made this booking has previously made a fraudulent insurance claim. This booking has been deleted.";
TempData["errormessage"] = errorString;
return RedirectToAction("Index", "Home");
}
else
{
int bookingCollected = (int)await CommandFactory.CreateCommand(CommandFactory.COLLECT_BOOKING, bookingId, DbContext).Execute();
if (bookingCollected < 1)
{
errorString = "Something went wrong, please try again.";
ModelState.AddModelError("", errorString);
return View();
}
TempData["successmessage"] = "Booking Marked As Collected!";
return RedirectToAction("Index", "Home");
}
}
else
{
//Put the files into collection ready to email to the DVLA
FormFileCollection fileCollection = new FormFileCollection();
fileCollection.Add(collectBookingViewModel.DrivingLicenseImageBack);
fileCollection.Add(collectBookingViewModel.DrivingLicenseImageFront);
fileCollection.Add(collectBookingViewModel.PersonCollectingImage);
fileCollection.Add(collectBookingViewModel.AdditionalIdentificationImage);
//Send the email to the DVLA and then delete the booking and inform the admin.
await CommandFactory.CreateCommand(CommandFactory.SEND_EMAIL, fileCollection, userBooking.User).Execute();
int bookingDeleted = (int)await CommandFactory.CreateCommand(CommandFactory.DELETE_BOOKING, bookingId, DbContext).Execute();
errorString = "This booking can not be collected: The license associated with this booking is currently invalidated by the DVLA. The DVLA have been informed and this booking has been deleted.";
TempData["errormessage"] = errorString;
return RedirectToAction("Index", "Home");
}
}
public async Task<IActionResult> ViewUserBookings()
{
IActionResult authenticationResult = await AuthenticateUserLogin(false);
if (authenticationResult != null)
{
return authenticationResult;
}
ApplicationUser CurrentUser = await _userManager.GetUserAsync(HttpContext.User);
string UserId = CurrentUser.Id;
UserBookingModels = new List<UserBookingsViewModel>();
ViewUserBookingsViewModel ViewUserBookingsViewModel = new ViewUserBookingsViewModel();
List<Booking> userBookings = new List<Booking>();
userBookings = (List<Booking>)await CommandFactory.CreateCommand(CommandFactory.GET_ALL_BOOKINGS_FOR_USER, UserId, DbContext).Execute();
ViewUserBookingsViewModel.UserBookingModels = CreateUserBookingModels(userBookings);
return View(ViewUserBookingsViewModel);
}
public async Task<IActionResult> AuthenticateUserLogin(bool adminRequired)
{
ApplicationUser CurrentUser = await _userManager.GetUserAsync(HttpContext.User);
bool IsAdmin = false;
if (CurrentUser == null)
{
TempData["errormessage"] = "You need to be logged in to book a vehicle." + Environment.NewLine + " If you do not have an account, please navigate to the registration page by clicking on 'Register' at the top of the screen.";
return RedirectToAction("Login", "Account");
}
else
{
IsAdmin = await _userManager.IsInRoleAsync(CurrentUser, "Admin");
}
if (adminRequired && IsAdmin == false)
{
TempData["errormessage"] = "You require admin privileges to view that page.";
return RedirectToAction("Index", "Home");
}
else return null;
}
public bool ValidateBooking(Object bookingViewModel)
{
bool valid = true;
if (bookingViewModel is BookVehicleViewModel)
{
BookVehicleViewModel bookVehicleViewModel = (BookVehicleViewModel)bookingViewModel;
double dateRangeInDays = (bookVehicleViewModel.StartDate.Date - bookVehicleViewModel.EndDate.Date).TotalDays;
if (bookVehicleViewModel.StartDate.Date < DateTime.Today.Date)
{
ModelState.AddModelError("", "Booking cannot begin in the past.");
valid = false;
}
if (dateRangeInDays > 14)
{
ModelState.AddModelError("", "Booking cannot be for longer than 2 weeks.");
valid = false;
}
if (dateRangeInDays == 0 && bookVehicleViewModel.EndHalfDay != true)
{
ModelState.AddModelError("", "Minimum booking length is half a day.");
valid = false;
}
}
else if(bookingViewModel is EditBookingViewModel)
{
EditBookingViewModel editBookingViewModel = (EditBookingViewModel)bookingViewModel;
double dateRangeInDays = (editBookingViewModel.StartDate.Date - editBookingViewModel.EndDate.Date).TotalDays;
if (dateRangeInDays > 14)
{
ModelState.AddModelError("", "Booking cannot be for longer than 2 weeks.");
valid = false;
}
if (dateRangeInDays == 0 && editBookingViewModel.EndHalfDay != true)
{
ModelState.AddModelError("", "Minimum booking length is half a day.");
valid = false;
}
return valid;
}
return valid;
}
public async Task<Vehicle> GetChosenVehicle(long vehicleId)
{
return (Vehicle)await CommandFactory.CreateCommand(CommandFactory.GET_VEHICLE, vehicleId, DbContext).Execute();
}
public List<VehicleBookingsViewModel> CreateVehicleBookingModels(List<Booking> vehicleBookings)
{
for (int i = 0; i < vehicleBookings.Count; i++)
{
VehicleBookingModels.Add(new VehicleBookingsViewModel());
VehicleBookingModels[i].BookingId = vehicleBookings[i].Id;
VehicleBookingModels[i].StartDate = vehicleBookings[i].StartDate;
VehicleBookingModels[i].EndDate = vehicleBookings[i].EndDate;
VehicleBookingModels[i].BookedBy = vehicleBookings[i].User.Forename + " " + vehicleBookings[i].User.Surname;
if (vehicleBookings[i].StartDate < DateTime.Today && vehicleBookings[i].EndDate > DateTime.Today && vehicleBookings[i].Collected == true)
{
VehicleBookingModels[i].IsCurrentlyOnRental = true;
}
if (vehicleBookings[i].StartDate < DateTime.Today && vehicleBookings[i].Collected == false)
{
VehicleBookingModels[i].NotCollected = true;
}
}
return VehicleBookingModels;
}
public List<UserBookingsViewModel> CreateUserBookingModels(List<Booking> userBookings)
{
for (int i = 0; i < userBookings.Count; i++)
{
UserBookingModels.Add(new UserBookingsViewModel());
UserBookingModels[i].BookingId = userBookings[i].Id;
UserBookingModels[i].StartDate = userBookings[i].StartDate;
UserBookingModels[i].EndDate = userBookings[i].EndDate;
UserBookingModels[i].VehicleBooked = userBookings[i].Vehicle.Manufacturer + " " + userBookings[i].Vehicle.Model;
UserBookingModels[i].Price = userBookings[i].Price;
if (userBookings[i].StartDate < DateTime.Today && userBookings[i].EndDate > DateTime.Today && userBookings[i].Collected == true)
{
UserBookingModels[i].IsCurrentlyOnRental = true;
}
if (userBookings[i].StartDate < DateTime.Today && userBookings[i].Collected == false)
{
UserBookingModels[i].NotCollected = true;
}
}
return UserBookingModels;
}
public List<EquipmentCheckboxSelectViewModel> CreateEquipmentCheckboxSelectList(List<Equipment> equipmentList)
{
for (int i = 0; i < equipmentList.Count; i++)
{
EquipmentCheckboxSelect.Add(new EquipmentCheckboxSelectViewModel());
EquipmentCheckboxSelect[i].Id = equipmentList[i].Id;
EquipmentCheckboxSelect[i].Name = equipmentList[i].Name;
}
return EquipmentCheckboxSelect;
}
public Booking ConvertViewModelToBooking(Object bookingViewModel)
{
if(bookingViewModel is BookVehicleViewModel)
{
BookVehicleViewModel bookVehicleViewModel = (BookVehicleViewModel)bookingViewModel;
Booking booking = new Booking();
ApplicationUser userBooking = new ApplicationUser();
Vehicle chosenVehicle = new Vehicle();
userBooking.Id = bookVehicleViewModel.UserId;
chosenVehicle.Id = bookVehicleViewModel.ChosenVehicleId;
booking.StartDate = bookVehicleViewModel.StartDate;
booking.EndDate = bookVehicleViewModel.EndDate;
booking.StartHalfDay = bookVehicleViewModel.StartHalfDay;
booking.EndHalfDay = bookVehicleViewModel.EndHalfDay;
booking.Price = bookVehicleViewModel.TotalCost;
booking.Vehicle = chosenVehicle;
booking.User = userBooking;
return booking;
}
else if(bookingViewModel is EditBookingViewModel)
{
EditBookingViewModel editBookingViewModel = (EditBookingViewModel)bookingViewModel;
Booking booking = new Booking();
booking.Id = editBookingViewModel.BookingId;
booking.StartDate = editBookingViewModel.StartDate;
booking.EndDate = editBookingViewModel.EndDate;
booking.StartHalfDay = editBookingViewModel.StartHalfDay;
booking.EndHalfDay = editBookingViewModel.EndHalfDay;
booking.Price = editBookingViewModel.Price;
booking.Collected = editBookingViewModel.Collected;
return booking;
}
return null;
}
public EditBookingViewModel CreateEditBookingViewModel(Booking bookingToEdit)
{
EditBookingViewModel editBookingViewModel = new EditBookingViewModel();
editBookingViewModel.BookingId = bookingToEdit.Id;
editBookingViewModel.StartDate = bookingToEdit.StartDate;
editBookingViewModel.EndDate = bookingToEdit.EndDate;
editBookingViewModel.LateReturn = bookingToEdit.LateReturn;
editBookingViewModel.StartHalfDay = bookingToEdit.EndHalfDay;
editBookingViewModel.Collected = bookingToEdit.Collected;
editBookingViewModel.Price = bookingToEdit.Price;
editBookingViewModel.VehicleId = bookingToEdit.Vehicle.Id;
editBookingViewModel.VehicleName = bookingToEdit.Vehicle.Manufacturer + " " + bookingToEdit.Vehicle.Model;
editBookingViewModel.VehicleCostPerDay = bookingToEdit.Vehicle.CostPerDay;
editBookingViewModel.UserForename = bookingToEdit.User.Forename;
editBookingViewModel.UserSurname = bookingToEdit.User.Surname;
return editBookingViewModel;
}
public async Task<bool> CheckIfUserLicenseValid(ApplicationUser user)
{
bool userLicenseInvalid = false;
List<String> listOfInvalidLicenses = (List<String>) await CommandFactory.CreateCommand(CommandFactory.GET_INVALID_LICENSES).Execute();
if(listOfInvalidLicenses != null)
{
foreach (String invalidLicense in listOfInvalidLicenses)
{
String[] licenseDataSplit = invalidLicense.Split(',');
if (user.LicenseNumber.Equals(licenseDataSplit[0]))
{
userLicenseInvalid = true;
}
}
}
else
{
Exception DVLAFileUnavailableException = new Exception();
DVLAFileUnavailableException.Message.Insert(0, "Unable To Check User Against DVLA File. Please Ensure a DVLA File Is Uploaded.");
throw new Exception();
}
return userLicenseInvalid;
}
public async Task<bool> CheckIfUserCommittedInsuranceFraud(ApplicationUser user)
{
List<FraudulentClaim> fraudulentClaims = (List<FraudulentClaim>)await CommandFactory.CreateCommand(CommandFactory.GET_INSURANCE_FRAUD_DATA).Execute();
foreach(FraudulentClaim claim in fraudulentClaims)
{
if(claim.Forenames.Equals(user.Forename, StringComparison.OrdinalIgnoreCase) && claim.FamilyName.Equals(user.Surname, StringComparison.OrdinalIgnoreCase) && claim.DateOfBirth.Date == user.DateOfBirth.Date)
{
return true;
}
}
return false;
}
public async Task<string> UploadIdentificationFile(IFormFile file, string folderPath)
{
string fileName = "";
string filePath = "";
fileName = Path.GetFileName(file.FileName);
Directory.CreateDirectory(folderPath);
filePath = Path.Combine(folderPath, fileName);
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
return filePath;
}
catch (Exception e)
{
TempData["errormessage"] = "Image failed to upload. Please try again!";
return "uploadFailed";
}
}
public string GenerateUserBasedFolderPath(ApplicationUser user)
{
string userPath = @"Files\" + user.Forename + "_" + user.Surname + "_" + user.LicenseNumber;
string folderPath = Path.Combine(Directory.GetCurrentDirectory(), userPath);
return folderPath;
}
}
}<file_sep>/OOAE/T2/T2-04/FactoryMethodPatternGUIProj/src/factorymethodpatternguiproj/UIProduct.java
package factorymethodpatternguiproj;
import javax.swing.JPanel;
/**
*
* @author <NAME>
*/
public abstract class UIProduct extends JPanel
{
protected String[] options;
public UIProduct(String[] options)
{
this.options = options;
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/build/generated-sources/ap-source-output/entity/Users_.java
package entity;
import entity.Route;
import java.util.Date;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2020-01-04T18:59:51")
@StaticMetamodel(Users.class)
public class Users_ {
public static volatile SingularAttribute<Users, String> city;
public static volatile SingularAttribute<Users, String> postcode;
public static volatile SingularAttribute<Users, String> telephone;
public static volatile SingularAttribute<Users, Integer> userId;
public static volatile SingularAttribute<Users, String> forename;
public static volatile SingularAttribute<Users, String> password;
public static volatile SingularAttribute<Users, Route> routeId;
public static volatile SingularAttribute<Users, Integer> driverId;
public static volatile SingularAttribute<Users, String> surname;
public static volatile SingularAttribute<Users, Date> dob;
public static volatile SingularAttribute<Users, String> addressLine1;
public static volatile SingularAttribute<Users, String> addressLine2;
public static volatile SingularAttribute<Users, Boolean> isDriver;
public static volatile SingularAttribute<Users, String> email;
}<file_sep>/CNA/SimpleClientServer/README.md
# README #
### What is this repository for? ###
* A Simple Networked Client Application. Used to demonstrate basic techniques such as opening a TCP Connection and reading/writing data.
* v1.0
### How do I get set up? ###
* Built in C# and Visual Studio 2013
* Targets .NET Framework 4
### Who do I talk to? ###
* <NAME> - Staffordshire University
* <EMAIL><file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Handlers/VehicleHandler.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers
{
public class VehicleHandler
{
private ApplicationDbContext DbContext;
public VehicleHandler(ApplicationDbContext dbContext)
{
DbContext = dbContext;
}
public async Task<List<VehicleType>> GetVehicleTypes()
{
List<VehicleType> vehicleTypes = await DbContext.VehicleType.ToListAsync();
return vehicleTypes;
}
public async Task<List<Transmission>> GetTransmissionTypes()
{
List<Transmission> transmissionTypes = await DbContext.Transmission.ToListAsync();
return transmissionTypes;
}
public async Task<List<Fuel>> GetFuelTypes()
{
List<Fuel> fuelTypes = await DbContext.Fuel.ToListAsync();
return fuelTypes;
}
public async Task<int> AddVehicle(Vehicle newVehicle)
{
int result;
newVehicle.VehicleType = await DbContext.VehicleType.FindAsync(newVehicle.VehicleType.Id);
newVehicle.Transmission = await DbContext.Transmission.FindAsync(newVehicle.Transmission.Id);
newVehicle.Fuel = await DbContext.Fuel.FindAsync(newVehicle.Fuel.Id);
await DbContext.Vehicle.AddAsync(newVehicle);
result = await DbContext.SaveChangesAsync();
return result;
}
public async Task<List<Vehicle>> GetVehicles()
{
List<Vehicle> vehicles = await DbContext.Vehicle.Include(vehicle => vehicle.VehicleType)
.Include(vehicle => vehicle.Fuel)
.Include(vehicle => vehicle.Transmission)
.ToListAsync();
return vehicles;
}
public async Task<Vehicle> GetVehicle(long vehicleId)
{
Vehicle vehicle = await DbContext.Vehicle.Where(vehicle => vehicle.Id == vehicleId)
.Include(vehicle => vehicle.VehicleType)
.Include(vehicle => vehicle.Fuel)
.Include(vehicle => vehicle.Transmission)
.FirstOrDefaultAsync();
return vehicle;
}
public async Task<int> UpdateVehicleComparisonSource(int vehicleId, string comparisonSourceURL)
{
Vehicle vehicleToEdit = await GetVehicle(vehicleId);
vehicleToEdit.VehicleComparisonSourceURL = comparisonSourceURL;
DbContext.Vehicle.Update(vehicleToEdit);
return await DbContext.SaveChangesAsync();
}
public async Task<int> UpdateVehicleCostPerDay(long vehicleId, int newCostPerDay)
{
Vehicle vehicleToEdit = await GetVehicle(vehicleId);
vehicleToEdit.CostPerDay = newCostPerDay;
DbContext.Vehicle.Update(vehicleToEdit);
return await DbContext.SaveChangesAsync();
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ViewModels/HomeViewModel.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels
{
public class HomeViewModel
{
public List<Vehicle> Vehicles { get; set; }
public int Age { get; set; }
}
}
<file_sep>/ESA/Flights Management/src/view/GetRisksView.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import database.Risk;
import java.util.ArrayList;
import javax.swing.JLabel;
/**
*
* @author danpa
*/
public class GetRisksView
{
ArrayList<Risk> risks;
public GetRisksView(ArrayList<Risk> risks)
{
this.risks = risks;
}
public ArrayList<String> getRiskNames()
{
ArrayList<String> names = new ArrayList<>();
for (int i = 0; i < risks.size(); i++)
{
names.add(risks.get(i).getRiskFactor());
}
return names;
}
public ArrayList<JLabel> GetLabels()
{
ArrayList<JLabel> labels = new ArrayList<>();
risks.forEach((Risk) ->
{
labels.add(new JLabel(Risk.getLabel()));
});
return labels;
}
}
<file_sep>/CNA/SimpleClientServer/SimpleServerCS/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleServerCS
{
class Program
{
static void Main(string[] args)
{
SimpleServer _simpleServer = new SimpleServer("127.0.0.1", 4444);
_simpleServer.Start();
_simpleServer.Stop();
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/UpdateVehicleComparisonSourceCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class UpdateVehicleComparisonSourceCommand : ICommand
{
private VehicleHandler VehicleHandler;
private int VehicleId;
private string ComparisonSourceURL;
public UpdateVehicleComparisonSourceCommand(ApplicationDbContext dbContext, int vehicleId, string comparisonSourceURL)
{
VehicleHandler = new VehicleHandler(dbContext);
VehicleId = vehicleId;
ComparisonSourceURL = comparisonSourceURL;
}
public async Task<object> Execute()
{
return await VehicleHandler.UpdateVehicleComparisonSource(VehicleId, ComparisonSourceURL);
}
}
}
<file_sep>/OOAE/T1/T1-06/JUnitProj_LB06/test/junitproj/DVDTest.java
package junitproj;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class DVDTest
{
DVD d1, d2, d3;
Person p1, p2;
public DVDTest()
{
p1 = new Person("Leonardo", "DiCaprio");
d1 = new DVD("Inception", p1, 5);
p2 = new Person("Leonardo", "DiCaprio");
d2 = new DVD("Inception", p2, 5);
d3 = new DVD("Gone with the Wind", p2, 4);
}
@BeforeClass
public static void setUpClass() throws Exception
{
}
@AfterClass
public static void tearDownClass() throws Exception
{
}
@Before
public void setUp() throws Exception
{
}
@After
public void tearDown() throws Exception
{
}
/**
* Test of getTitle method, of class DVD.
*/
@Test
public void testGetTitle()
{
System.out.println("getTitle");
DVD instance = d1;
String expResult = "Inception";
String result = instance.getTitle();
assertEquals(expResult, result);
}
/**
* Test of setTitle method, of class DVD.
*/
@Test
public void testSetTitle()
{
System.out.println("setTitle");
String title = "Inception";
DVD instance = d1;
instance.setTitle(title);
}
/**
* Test of getLeadActor method, of class DVD.
*/
@Test
public void testGetLeadActor()
{
System.out.println("getLeadActor");
DVD instance = d1;
Person expResult = p1;
Person result = instance.getLeadActor();
assertEquals(expResult, result);
}
/**
* Test of setLeadActor method, of class DVD.
*/
@Test
public void testSetLeadActor()
{
System.out.println("setLeadActor");
Person leadActor = p1;
DVD instance = d1;
instance.setLeadActor(leadActor);
}
/**
* Test of getNoOfStars method, of class DVD.
*/
@Test
public void testGetNoOfStars()
{
System.out.println("getNoOfStars");
DVD instance = d1;
int expResult = 5;
int result = instance.getNoOfStars();
assertEquals(expResult, result);
}
/**
* Test of setNoOfStars method, of class DVD.
*/
@Test
public void testSetNoOfStars()
{
System.out.println("setNoOfStars");
int noOfStars = 5;
DVD instance = d1;
instance.setNoOfStars(noOfStars);
}
/**
* Test of toString method, of class DVD.
*/
@Test
public void testToString()
{
System.out.println("toString");
DVD instance = d1;
String expResult = "Title: Inception"
+ "\nLead Actor: <NAME>"
+ "\nNumber of stars: 5";
String result = instance.toString();
assertEquals(expResult, result);
}
@Test
public void testEquals()
{
assertEquals(d2, d1);
assertNotSame(d2, d1);
assertEquals(d1, d1);
assertSame(d1, d1);
assertFalse(d3.equals(d1));
}
@Test
public void testHashCode()
{
assertEquals(d2.hashCode(), d1.hashCode());
assertEquals(p2.hashCode(), d1.getLeadActor().hashCode());
}
@Test
public void testClone() throws CloneNotSupportedException
{
DVD d2 = (DVD)d1.deepClone();
assertEquals(d2, d1);
assertNotSame(d2, d1);
// change the lead actor of the original DVD object
Person p1 = d1.getLeadActor();
p1.setFirstName("Clark");
p1.setLastName("Gable");
assertFalse(d2.equals(d1));
assertEquals("<NAME>", d1.getLeadActor().toString());
assertEquals("<NAME>", d2.getLeadActor().toString());
}
@Test
public void testCompareTo()
{
assertEquals(1, d1.compareTo(d3));
assertEquals(-1, d3.compareTo(d1));
assertEquals(0, d1.compareTo(d1));
}
}
<file_sep>/WMAD/CinemaBookingSystem/src/java/dto/ShowingDTO.java
package dto;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author <NAME>
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ShowingDTO implements Serializable
{
private int showingID;
private FilmDTO film;
private ScreenDTO screen;
private String time;
private int availableSeats;
public ShowingDTO()
{
this.showingID = 0;
this.film = new FilmDTO();
this.screen = new ScreenDTO();
this.time = "";
this.availableSeats = 0;
}
public ShowingDTO(int showingID, FilmDTO film, ScreenDTO screen, String time, int availableSeats)
{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
this.showingID = showingID;
this.film = film;
this.screen = screen;
this.time = sdf.format(time);
this.availableSeats = availableSeats;
}
public ShowingDTO(int showingID, FilmDTO film, ScreenDTO screen, Date time, int availableSeats)
{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
this.showingID = showingID;
this.film = film;
this.screen = screen;
this.time = sdf.format(time);
this.availableSeats = availableSeats;
}
public int getShowingID()
{
return showingID;
}
public FilmDTO getFilm()
{
return film;
}
public ScreenDTO getScreen()
{
return screen;
}
public String getTime()
{
return time;
}
public int getAvailableSeats()
{
return availableSeats;
}
}
<file_sep>/OOAE/T2/T2-05/wk2-05_lec1_BuilderProj/wk2-05_lec1_VisitorProj/src/department/DepartmentPrinter.java
package department;
/**
*
* @author <NAME>
*/
public class DepartmentPrinter extends DepartmentVisitor
{
@Override
public void visitDepartment(Department d)
{
System.out.printf("%-5d %-10s %-10s\n",
d.getID(),
d.getName(),
d.getLocation());
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Handlers/AccountHandler.cs
using AnimalCareSystem.Data;
using AnimalCareSystem.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace AnimalCareSystem.Handlers
{
public class AccountHandler
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private ApplicationDbContext _dbContext;
public AccountHandler()
{
}
public AccountHandler(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
public AccountHandler(SignInManager<ApplicationUser> signInManager)
{
_signInManager = signInManager;
}
public AccountHandler(UserManager<ApplicationUser> userManager, ApplicationDbContext dbContext)
{
_userManager = userManager;
_dbContext = dbContext;
}
public AccountHandler(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public AccountHandler(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<List<ApplicationUser>> GetUsersByCity(string city)
{
List<ApplicationUser> usersInCity = await _dbContext.User.Where(user => user.City == city).ToListAsync();
return usersInCity;
}
public async Task<int> UpdateUser(ApplicationUser editedUser)
{
_dbContext.User.Update(editedUser);
return await _dbContext.SaveChangesAsync();
}
public async Task<IdentityResult> ConfirmEmail(ApplicationUser user, string confirmationCode)
{
IdentityResult result = await _userManager.ConfirmEmailAsync(user, confirmationCode);
return result;
}
public async Task<ApplicationUser> GetUserById(string userId)
{
ApplicationUser user = await _dbContext.User.Where(user => user.Id == userId)
.Include(user => user.ReceivedReviews).ThenInclude(userReview => userReview.ReviewingUser)
.Include(user => user.ServiceRates).ThenInclude(serviceRates => serviceRates.ServiceType)
.FirstOrDefaultAsync();
//ApplicationUser user = await _userManager.FindByIdAsync(userId);
return user;
}
public async Task<string> GetEmailConfirmationToken(ApplicationUser user)
{
string emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);
return emailConfirmationToken;
}
public async Task<IdentityResult> RegisterUser(ApplicationUser newUser)
{
IdentityResult result = await _userManager.CreateAsync(newUser, newUser.PasswordHash);
await _userManager.AddClaimAsync(newUser, new Claim("Forename", newUser.Forename));
await _userManager.AddToRoleAsync(newUser, "User");
return result;
}
public async Task<SignInResult> Login(string email, string password, bool rememberMe)
{
SignInResult result = await _signInManager.PasswordSignInAsync(email, password, rememberMe, lockoutOnFailure: false);
return result;
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Models/Message.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.Models
{
public class Message
{
[Required]
public int Id { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Content { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime DateTimeSent { get; set; }
[Required]
public ApplicationUser ReceivingUser { get; set; }
[Required]
public ApplicationUser SendingUser { get; set; }
public Message()
{
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/GetAllEquipmentCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class GetAllEquipmentCommand : ICommand
{
private EquipmentHandler EquipmentHandler;
public GetAllEquipmentCommand(ApplicationDbContext dbContext)
{
EquipmentHandler = new EquipmentHandler(dbContext);
}
public async Task<object> Execute()
{
return await EquipmentHandler.GetAllEquipment();
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/GetInvalidLicensesCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class GetInvalidLicensesCommand : ICommand
{
private FileHandler FileHandler;
public GetInvalidLicensesCommand()
{
FileHandler = new FileHandler();
}
public async Task<object> Execute()
{
return FileHandler.GetAllInvalidLicenses();
}
}
}
<file_sep>/OOAE/T2/T2-04/FactoryMethodPatternGUIProj/src/factorymethodpatternguiproj/Factory.java
package factorymethodpatternguiproj;
/**
*
* @author <NAME>
*/
public abstract class Factory
{
public abstract UIProduct createUIProduct(String[] options);
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/UpdateBookingCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class UpdateBookingCommand : ICommand
{
private Booking Booking;
private List<Equipment> ChosenEquipmentList;
private BookingHandler BookingHandler;
public UpdateBookingCommand(Booking booking, List<Equipment> chosenEquipmentList, ApplicationDbContext dbContext)
{
Booking = booking;
ChosenEquipmentList = chosenEquipmentList;
BookingHandler = new BookingHandler(dbContext);
}
public async Task<object> Execute()
{
return await BookingHandler.UpdateBooking(Booking, ChosenEquipmentList);
}
}
}
<file_sep>/OOAE/T1/T1-09/cardDeckProj/src/carddeckproj/CardDeckProj.java
package carddeckproj;
public class CardDeckProj
{
public static void main(String[] args)
{
//Creating card objects and constructing them.
Deck theDeck = new Deck();
Hand handOfCards = new Hand();
//outputs
// getSuits(theCards);
// getRanks(theCards);
printCards(theDeck);
//Create hand of five cards
createHand(theDeck, handOfCards);
printHand(handOfCards);
printHandValues(handOfCards);
}
public static void createHand(Deck theDeck, Hand handOfCards)
{
handOfCards.addCard(theDeck.theCards[23]);
handOfCards.addCard(theDeck.theCards[27]);
handOfCards.addCard(theDeck.theCards[6]);
handOfCards.addCard(theDeck.theCards[48]);
handOfCards.addCard(theDeck.theCards[32]);
}
public static void printHand(Hand handOfCards)
{
System.out.println("Hand: " + handOfCards.toString());
System.out.println("");
}
public static void printHandValues (Hand handOfCards)
{
System.out.println("Hand total: " + handOfCards.getHandValue());
System.out.println("");
}
public static void getSuits(Deck theDeck)
{
System.out.println("getSuit:");
for (int i = 0; i < theDeck.theCards.length; i++)
{
System.out.println(theDeck.theCards[i].getSuit());
}
System.out.print("\n");
}
public static void getRanks(Deck theDeck)
{
System.out.println("getRank:");
for (Card cards : theDeck.theCards)
{
System.out.println(cards.getRank());
}
System.out.print("\n");
}
public static void printCards(Deck theDeck)
{
theDeck.toString(theDeck.theCards);
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/DataParallelismProj/Handler/FileHandler.cs
using DataParallelismProj.DTO;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataParallelismProj.Handler
{
class FileHandler
{
string folderPath = "StoreData";
string storeCodesFile = "StoreCodes.csv";
string storeDataFolder = "StoreData";
public Boolean LoadOrders(string selectedFolderPath)
{
ConcurrentDictionary<string, Store> stores = LoadStores();
ConcurrentDictionary<string, Date> dates = new ConcurrentDictionary<string, Date>();
List<Order> orders = new List<Order>();
string[] fileNames = Directory.GetFiles(folderPath + @"\" + storeDataFolder);
Parallel.ForEach(fileNames, filePath =>
{
//Full file name with the extension (#####.csv)
string fileNameExt = Path.GetFileName(filePath);
//File name without extension
string fileName = Path.GetFileNameWithoutExtension(filePath);
//Split the filename up into store code, week and year
string[] fileNameSplit = fileName.Split('_');
//Gets the store object with the matching store code.
Store store = stores[fileNameSplit[0]];
//Create Date object from week and year.
Date date = new Date { Week = Convert.ToInt32(fileNameSplit[1]), Year = Convert.ToInt32(fileNameSplit[2]) };
if (!dates.ContainsKey(date.ToString()))
{
dates.TryAdd(date.ToString(), date);
}
//fileNameSplit[0] = store code
//fileNameSplit[1] = week number
//fileNameSplit[2] = year
string[] orderData = File.ReadAllLines(folderPath + @"\" + storeDataFolder + @"\" + fileNameExt);
foreach (string entry in orderData)
{
string[] orderSplit = entry.Split(',');
Order order = new Order(store, date, new Supplier(orderSplit[0], orderSplit[1]), Convert.ToDouble(orderSplit[2]));
order.Date = date;
lock(orders)
{
orders.Add(order);
}
//orderSplit[0] = supplier name
//orderSplit[1] = supplier type
//orderSplit[2] = cost
}
});
return true;
}
public ConcurrentDictionary<string, Store> LoadStores()
{
ConcurrentDictionary<string, Store> stores = new ConcurrentDictionary<string, Store>();
string storeCodesFilePath = Directory.GetCurrentDirectory() + @"\" + folderPath + @"\" + storeCodesFile;
string[] storeCodesData = File.ReadAllLines(storeCodesFilePath);
Parallel.ForEach(storeCodesData, storeData =>
{
string[] storeDataSplit = storeData.Split(',');
Store store = new Store { StoreCode = storeDataSplit[0], StoreName = storeDataSplit[1] };
if (!stores.ContainsKey(store.StoreCode))
stores.TryAdd(store.StoreCode, store);
//storeDataSplit[0] = store code
//storeDataSplit[1] = store location
});
return stores;
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ApplicationUI/GetUserByIdCommand.cs
using AnimalCareSystem.Data;
using AnimalCareSystem.Handlers;
using AnimalCareSystem.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ApplicationUI
{
public class GetUserByIdCommand : ICommand
{
private string UserId;
private AccountHandler AccountHandler;
public GetUserByIdCommand(string userId, UserManager<ApplicationUser> userManager, ApplicationDbContext dbContext)
{
UserId = userId;
AccountHandler = new AccountHandler(userManager, dbContext);
}
public async Task<object> Execute()
{
return await AccountHandler.GetUserById(UserId);
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/database/UserGateway.java
package database;
import dto.UserDTO;
import entity.Route;
import entity.Users;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
/**
*
* @author Rhys
*/
@Stateless
public class UserGateway implements UserGatewayLocal
{
@PersistenceContext
EntityManager em;
@EJB
DTOConversionGatewayLocal DTOConversionGateway;
@Override
public UserDTO login(String email, String password)
{
boolean credentialsCorrect = false;
try
{
Users user = (Users) em.createNamedQuery("Users.getUserByCredentials").setParameter("email", email).setParameter("password", password).getSingleResult();
if (user.getPassword().equals(password))
{
credentialsCorrect = true;
}
if (credentialsCorrect == true)
{
UserDTO userDTO = DTOConversionGateway.createUserDTO(user);
return userDTO;
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Login credentials are not correct"));
return null;
}
}
catch (NoResultException e)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Login credentials are not correct"));
return null;
}
}
@Override
public boolean registerNewUser(UserDTO registeringUserDTO)
{
try
{
Users newUser = new Users();
newUser.setForename(registeringUserDTO.getForename());
newUser.setSurname(registeringUserDTO.getSurname());
newUser.setDob(registeringUserDTO.getDateOfBirth());
newUser.setAddressLine1(registeringUserDTO.getAddressLine1());
newUser.setAddressLine2(registeringUserDTO.getAddressLine2());
newUser.setPostcode(registeringUserDTO.getPostcode());
newUser.setCity(registeringUserDTO.getCity());
newUser.setTelephone(registeringUserDTO.getTelephone());
newUser.setEmail(registeringUserDTO.getEmail());
newUser.setPassword(<PASSWORD>());
newUser.setIsDriver(false);
em.persist(newUser);
}
catch (Exception e)
{
return false;
}
return true;
}
@Override
public UserDTO updateAccountDetails(UserDTO user, String oldPassword, String oldEmail)
{
try
{
Users originalUser = (Users) em.createNamedQuery("Users.getUserByCredentials").setParameter("email", oldEmail).setParameter("password", oldPassword).getSingleResult();
if (!originalUser.getEmail().equals(user.getEmail()))
{
originalUser.setEmail(user.getEmail());
}
if (!originalUser.getPassword().equals(user.getPassword()))
{
originalUser.setPassword(user.<PASSWORD>());
}
if (!originalUser.getAddressLine1().equals(user.getAddressLine1()))
{
originalUser.setAddressLine1(user.getAddressLine1());
}
if (!originalUser.getAddressLine2().equals(user.getAddressLine2()))
{
originalUser.setAddressLine2(user.getAddressLine1());
}
if (!originalUser.getPostcode().equals(user.getPostcode()))
{
originalUser.setPostcode(user.getPostcode());
}
if (!originalUser.getCity().equals(user.getCity()))
{
originalUser.setCity(user.getCity());
}
if (!originalUser.getTelephone().equals(user.getTelephone()))
{
originalUser.setTelephone(user.getTelephone());
}
em.persist(originalUser);
UserDTO updatedUser = DTOConversionGateway.createUserDTO(originalUser);
return updatedUser;
}
catch (Exception e)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Failed to verify credentials"));
return null;
}
}
@Override
public boolean deleteAccount(UserDTO user)
{
try
{
Users userAccount = (Users) em.createNamedQuery("Users.getUserByCredentials").setParameter("email", user.getEmail()).setParameter("password", user.getPassword()).getSingleResult();
em.remove(userAccount);
return true;
}
catch(Exception e)
{
return false;
}
}
@Override
public UserDTO assignRouteToDriver(UserDTO user, int routeId)
{
try
{
Users driver = (Users) em.createNamedQuery("Users.getUserByCredentials")
.setParameter("email", user.getEmail())
.setParameter("password", user.getPassword())
.getSingleResult();
Route chosenRoute = (Route) em.createNamedQuery("Route.findByRouteId")
.setParameter("routeId", routeId)
.getSingleResult();
driver.setRouteId(chosenRoute);
em.persist(driver);
UserDTO updatedDriverDTO = DTOConversionGateway.createUserDTO(driver);
return updatedDriverDTO;
}
catch(Exception e)
{
return null;
}
}
}
<file_sep>/CNA/SimpleClientServer/SimpleServerCS/SimpleServer.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Packets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Diagnostics;
namespace SimpleServerCS
{
class SimpleServer
{
static Semaphore semaphoreObject;
TcpListener _tcpListener;
static List<Client> _clients = new List<Client>();
public SimpleServer(string ipAddress, int port)
{
IPAddress ip = IPAddress.Parse(ipAddress);
_tcpListener = new TcpListener(ip, port);
semaphoreObject = new Semaphore(initialCount: 0, maximumCount: 1);
semaphoreObject.Release();
}
public void Start()
{
_tcpListener.Start();
Console.WriteLine("Listening...");
while (true)
{
Socket socket = _tcpListener.AcceptSocket();
Client client = new Client(socket);
_clients.Add(client);
client.Start();
}
}
public void Stop()
{
foreach (Client client in _clients)
{
client.Stop();
}
_tcpListener.Stop();
}
public static void SocketMethod(Client client)
{
try
{
Socket socket = client.socket;
NetworkStream stream = client.stream;
BinaryReader reader = client.reader;
BinaryFormatter formatter = new BinaryFormatter();
int noOfIncomingBytes;
while ((noOfIncomingBytes = reader.ReadInt32()) != 0)
{
byte[] bytes = reader.ReadBytes(noOfIncomingBytes);
MemoryStream memoryStream = new MemoryStream(bytes);
Packet packet = formatter.Deserialize(memoryStream) as Packet;
switch (packet.type)
{
case PacketType.NICKNAME:
string nickName = ((NicknamePacket)packet).nickname;
client.nickname = nickName;
break;
case PacketType.CHATMESSAGE:
string message = ((ChatMessagePacket)packet).message;
foreach (Client c in _clients)
{
c.SendText(client, message);
}
break;
case PacketType.BUYPRODUCT:
String waitMessage = "Is buying... " + ((BuyProductPacket)packet).productType + "'s";
message = "Bought " + ((BuyProductPacket)packet).productType + "'s";
semaphoreObject.WaitOne();
foreach (Client c in _clients)
{
c.SendText(client, waitMessage);
}
Thread.Sleep(5000);
foreach (Client c in _clients)
{
c.SendText(client, message);
}
semaphoreObject.Release();
break;
case PacketType.SELLPRODUCT:
waitMessage = "Is selling... " + ((SellProductPacket)packet).productType + "'s";
message = "Sold " + ((SellProductPacket)packet).productType + "'s";
semaphoreObject.WaitOne();
foreach (Client c in _clients)
{
c.SendText(client, waitMessage);
}
Thread.Sleep(5000);
foreach (Client c in _clients)
{
c.SendText(client, message);
}
semaphoreObject.Release();
break;
}
}
}
catch (Exception e)
{
Console.WriteLine("Error occured: " + e.Message);
}
finally
{
client.Stop();
}
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-war/src/java/managed_bean/AccountDetailsViewBean.java
package managed_bean;
import dto.UserDTO;
import ejb.User_UIRemote;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
/**
*
* @author Rhys
*/
@Named(value = "accountDetailsViewBean")
@SessionScoped
public class AccountDetailsViewBean implements Serializable
{
@EJB
private User_UIRemote userUI;
private UserDTO user;
private String oldPassword;
private String confirmPassword;
private String newPassword;
private String oldEmail;
public AccountDetailsViewBean()
{
}
public String updateAccountDetails()
{
String hashedEmptyString = "";
try
{
byte[] hash
= MessageDigest.getInstance("SHA-256")
.digest(hashedEmptyString.getBytes(StandardCharsets.UTF_8));
hashedEmptyString = Base64.getEncoder().encodeToString(hash);
}
catch (NoSuchAlgorithmException ex)
{
hashedEmptyString = "";
Logger.getLogger(AccountDetailsViewBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (!user.getPassword().equals(oldPassword) && !oldPassword.equals(hashedEmptyString))
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Old password is incorrect"));
return "";
}
if (!newPassword.equals(confirmPassword))
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("New password does not match password confirmation"));
return "";
}
if(!newPassword.equals(hashedEmptyString))
{
user.setPassword(newPassword);
}
UserDTO updatedUser;
if(oldPassword.equals(hashedEmptyString))
{
updatedUser = userUI.updateAccountDetails(user, user.getPassword(), oldEmail);
}
else
{
updatedUser = userUI.updateAccountDetails(user, oldPassword, oldEmail);
}
if (user != null)
{
HttpSession sessionScope = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
sessionScope.setAttribute("loggedUser", updatedUser);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Account Updated"));
return "Account Updated";
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Account could not be updated"));
return "";
}
}
public String displayAccountDetails()
{
HttpSession sessionScope = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
UserDTO loggedInUser = (UserDTO) sessionScope.getAttribute("loggedUser");
UserDTO loggedInUserCopy = new UserDTO();
loggedInUserCopy.setForename(loggedInUser.getForename());
loggedInUserCopy.setSurname(loggedInUser.getSurname());
loggedInUserCopy.setDateOfBirth(loggedInUser.getDateOfBirth());
loggedInUserCopy.setEmail(loggedInUser.getEmail());
loggedInUserCopy.setPassword(<PASSWORD>());
loggedInUserCopy.setAddressLine1(loggedInUser.getAddressLine1());
loggedInUserCopy.setAddressLine2(loggedInUser.getAddressLine2());
loggedInUserCopy.setPostcode(loggedInUser.getPostcode());
loggedInUserCopy.setCity(loggedInUser.getCity());
loggedInUserCopy.setTelephone(loggedInUser.getTelephone());
setUser(loggedInUserCopy);
setOldEmail(loggedInUser.getEmail());
return "Display Account Details";
}
public String deleteAccount()
{
boolean accountDeleted = userUI.deleteAccount(user);
if(accountDeleted)
{
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Account Deleted"));
return "Account Deleted";
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Account could not be deleted, please try again later"));
return "";
}
}
public String getOldEmail()
{
return oldEmail;
}
public void setOldEmail(String oldEmail)
{
this.oldEmail = oldEmail;
}
public String getNewPassword()
{
return newPassword;
}
public void setNewPassword(String newPassword)
{
try
{
byte[] hash
= MessageDigest.getInstance("SHA-256")
.digest(newPassword.getBytes(StandardCharsets.UTF_8));
this.newPassword
= Base64.getEncoder().encodeToString(hash);
}
catch (NoSuchAlgorithmException ex)
{
this.newPassword = "";
Logger.getLogger(AccountDetailsViewBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String getConfirmPassword()
{
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword)
{
try
{
byte[] hash
= MessageDigest.getInstance("SHA-256")
.digest(confirmPassword.getBytes(StandardCharsets.UTF_8));
this.confirmPassword
= Base64.getEncoder().encodeToString(hash);
}
catch (NoSuchAlgorithmException ex)
{
this.confirmPassword = "";
Logger.getLogger(AccountDetailsViewBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public UserDTO getUser()
{
return user;
}
public void setUser(UserDTO user)
{
this.user = user;
}
public String getOldPassword()
{
return oldPassword;
}
public void setOldPassword(String oldPassword)
{
try
{
byte[] hash
= MessageDigest.getInstance("SHA-256")
.digest(oldPassword.getBytes(StandardCharsets.UTF_8));
this.oldPassword
= Base64.getEncoder().encodeToString(hash);
}
catch (NoSuchAlgorithmException ex)
{
this.oldPassword = "";
Logger.getLogger(AccountDetailsViewBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
<file_sep>/README.md
# Projects
A collection of projects created during my time at university.
It's important to note that many of these applications are prototypes or a proof of concept. They were also created to meet a specified mark scheme and specific learning outcomes
which often didn't make a lot of sense in a genuine business application and often forced the use of functionality that wasn't necessary. Therefore many of these projects
may seem incomplete.
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ApplicationUI/UpdateUserCommand.cs
using AnimalCareSystem.Data;
using AnimalCareSystem.Handlers;
using AnimalCareSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ApplicationUI
{
public class UpdateUserCommand : ICommand
{
private AccountHandler AccountHandler;
private ApplicationUser EditedUser;
public UpdateUserCommand(ApplicationUser editedUser, ApplicationDbContext dbContext)
{
EditedUser = editedUser;
AccountHandler = new AccountHandler(dbContext);
}
public async Task<object> Execute()
{
return await AccountHandler.UpdateUser(EditedUser);
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Handlers/AccessDbHandler.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers
{
public class AccessDbHandler
{
public static List<FraudulentClaim> GetInsuranceFraudData()
{
string filePath = Path.Combine(Directory.GetCurrentDirectory(), "Files", "ABI_DRIVER_FRAUD1.accdb");
string connectionString = @"Driver={Microsoft Access Driver (*.mdb, *.accdb)}; Dbq=" + filePath + ";";
string queryString = "SELECT * FROM fraudulent_claim_data;";
object[] columns = new object[7];
FraudulentClaim fraudulentClaim;
List<FraudulentClaim> listOfFraudulentClaims = new List<FraudulentClaim>();
try
{
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
OdbcCommand command = new OdbcCommand(queryString, connection);
connection.Open();
OdbcDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int numberOfColumns = reader.GetValues(columns);
fraudulentClaim = new FraudulentClaim();
fraudulentClaim.ID = (int)columns[0];
fraudulentClaim.FamilyName = (string)columns[1];
fraudulentClaim.Forenames = (string)columns[2];
fraudulentClaim.DateOfBirth = (DateTime)columns[3];
fraudulentClaim.AddressOfClaim = (string)columns[4];
fraudulentClaim.DateOfClaim = (DateTime)columns[5];
fraudulentClaim.InsurerCode = (int)columns[6];
listOfFraudulentClaims.Add(fraudulentClaim);
}
reader.Close();
}
return listOfFraudulentClaims;
}
catch(Exception e)
{
return null;
}
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-war/src/java/managed_bean/DriverDeliveriesViewBean.java
package managed_bean;
import dto.DeliveryDTO;
import dto.UserDTO;
import ejb.DriverUIRemote;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.ArrayList;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
/**
*
* @author Rhys
*/
@Named(value = "driverDeliveriesViewBean")
@SessionScoped
public class DriverDeliveriesViewBean implements Serializable
{
@EJB
private DriverUIRemote driverUI;
private ArrayList<DeliveryDTO> driverDeliveries;
public DriverDeliveriesViewBean()
{
}
public String getDeliveriesForView()
{
HttpSession sessionScope = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
UserDTO driver = (UserDTO)sessionScope.getAttribute("loggedDriver");
driverDeliveries = driverUI.getDriverDeliveries(driver.getRouteId().getRouteId());
if(driverDeliveries != null)
{
return "Display Driver Deliveries";
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("You have no deliveries to deliver currently"));
return "";
}
}
public String deliverDelivery(int deliveredDelivery)
{
boolean deliveryDelivered = driverUI.deliverDelivery(deliveredDelivery);
if(deliveryDelivered)
{
return getDeliveriesForView();
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Could not confirm delivery"));
return "";
}
}
public String failDelivery(int failedDelivery)
{
boolean deliveryFailed = driverUI.failDelivery(failedDelivery);
if(deliveryFailed)
{
return getDeliveriesForView();
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Could not confirm delivery failure"));
return "";
}
}
public ArrayList<DeliveryDTO> getDriverDeliveries()
{
return driverDeliveries;
}
public void setDriverDeliveries(ArrayList<DeliveryDTO> driverDeliveries)
{
this.driverDeliveries = driverDeliveries;
}
}
<file_sep>/OOAE/T1/T1-08/WrapperClassProj/nbproject/private/private.properties
compile.on.save=true
user.properties.file=C:\\Users\\Rhys\\AppData\\Roaming\\NetBeans\\8.2\\build.properties
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-war/src/java/managed_bean/DateValidator.java
package managed_bean;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
/**
*
* @author Rhys
*/
@FacesValidator(value = "dateValidator")
public class DateValidator implements Validator
{
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException
{
String msg;
Date today = new Date();
if (component.getId().equals("collectionDate"))
{
Date dateToCheck = (Date) value;
if (dateToCheck.before(today))
{
msg = "You cannot book a collection for the past or for the same day";
throw new ValidatorException(new FacesMessage(msg));
}
}
if(component.getId().equals("newDeliveryDate"))
{
Date dateToCheck = (Date) value;
if (dateToCheck.before(today))
{
msg = "You cannot book a collection for the past or for the same day";
throw new ValidatorException(new FacesMessage(msg));
}
}
}
}
<file_sep>/OOAE/T2/T2-05/wk2-05_lec1_VisitorProj/wk2-05_lec1_VisitorProj/nbproject/private/private.properties
compile.on.save=true
file.reference.ojdbc6.jar=E:\\UNI-LEVEL 5\\ojdbc6.jar
user.properties.file=C:\\Users\\J016984c\\AppData\\Roaming\\NetBeans\\8.2\\build.properties
<file_sep>/CNA/SimpleClientServer/Packet/Packet.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Packets
{
[Serializable]
public class Packet
{
public PacketType type = PacketType.EMPTY;
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/GetBookingCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class GetBookingCommand : ICommand
{
BookingHandler BookingHandler;
long BookingId;
public GetBookingCommand(long bookingId, ApplicationDbContext dbContext)
{
BookingId = bookingId;
BookingHandler = new BookingHandler(dbContext);
}
public async Task<object> Execute()
{
return await BookingHandler.GetBooking(BookingId);
}
}
}
<file_sep>/ESA/Flights Management/src/model/RiskHandler.java
package model;
import database.DatabaseConnectionPool;
import database.Risk;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author ESA
*/
public class RiskHandler
{
// public ArrayList<Passenger> checkAllRisksOnFlight(int FlightID)
// {
// ArrayList<Passenger> passengersOnFlight = new FlightHandler().viewPassengersOnFlight(FlightID);
//
// for(Passenger passenger : passengersOnFlight)
// {
// try
// {
// getRisksForPassenger(passenger);
// }
// catch (SQLException ex)
// {
// Logger.getLogger(RiskHandler.class.getName()).log(Level.SEVERE, null, ex);
// }
// }
//
// return passengersOnFlight;
// }
public boolean insertNewRiskValue(Risk newRisk)
{
boolean insertOK = false;
DatabaseConnectionPool pool = DatabaseConnectionPool.getInstance();
Connection con = pool.getAvailableConnection();
try
{
PreparedStatement stmt = con.prepareStatement("INSERT INTO RISK(RISK_DESC, RISK_SCORE) VALUES(?, ?)");
stmt.setString(1, newRisk.getRiskFactor());
stmt.setInt(2, newRisk.getRiskScore());
int rows = stmt.executeUpdate();
insertOK = rows == 1;
stmt.close();
pool.returnConnection(con);
}
catch (SQLException ex)
{
Logger.getLogger(RiskHandler.class.getName()).log(Level.SEVERE, null, ex);
}
return insertOK;
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Migrations/20191215025321_EquipmentBookingEdit.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Migrations
{
public partial class EquipmentBookingEdit : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_EquipmentBookings_Bookings_BookingId1",
table: "EquipmentBookings");
migrationBuilder.DropForeignKey(
name: "FK_EquipmentBookings_Equipment_EquipmentId1",
table: "EquipmentBookings");
migrationBuilder.DropIndex(
name: "IX_EquipmentBookings_BookingId1",
table: "EquipmentBookings");
migrationBuilder.DropIndex(
name: "IX_EquipmentBookings_EquipmentId1",
table: "EquipmentBookings");
migrationBuilder.DropColumn(
name: "BookingId1",
table: "EquipmentBookings");
migrationBuilder.DropColumn(
name: "EquipmentId1",
table: "EquipmentBookings");
migrationBuilder.AlterColumn<long>(
name: "EquipmentId",
table: "EquipmentBookings",
nullable: true,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.AlterColumn<long>(
name: "BookingId",
table: "EquipmentBookings",
nullable: true,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.AddColumn<int>(
name: "Count",
table: "EquipmentBookings",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateIndex(
name: "IX_EquipmentBookings_BookingId",
table: "EquipmentBookings",
column: "BookingId");
migrationBuilder.CreateIndex(
name: "IX_EquipmentBookings_EquipmentId",
table: "EquipmentBookings",
column: "EquipmentId");
migrationBuilder.AddForeignKey(
name: "FK_EquipmentBookings_Bookings_BookingId",
table: "EquipmentBookings",
column: "BookingId",
principalTable: "Bookings",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_EquipmentBookings_Equipment_EquipmentId",
table: "EquipmentBookings",
column: "EquipmentId",
principalTable: "Equipment",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_EquipmentBookings_Bookings_BookingId",
table: "EquipmentBookings");
migrationBuilder.DropForeignKey(
name: "FK_EquipmentBookings_Equipment_EquipmentId",
table: "EquipmentBookings");
migrationBuilder.DropIndex(
name: "IX_EquipmentBookings_BookingId",
table: "EquipmentBookings");
migrationBuilder.DropIndex(
name: "IX_EquipmentBookings_EquipmentId",
table: "EquipmentBookings");
migrationBuilder.DropColumn(
name: "Count",
table: "EquipmentBookings");
migrationBuilder.AlterColumn<int>(
name: "EquipmentId",
table: "EquipmentBookings",
type: "int",
nullable: false,
oldClrType: typeof(long),
oldNullable: true);
migrationBuilder.AlterColumn<int>(
name: "BookingId",
table: "EquipmentBookings",
type: "int",
nullable: false,
oldClrType: typeof(long),
oldNullable: true);
migrationBuilder.AddColumn<long>(
name: "BookingId1",
table: "EquipmentBookings",
type: "bigint",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "EquipmentId1",
table: "EquipmentBookings",
type: "bigint",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_EquipmentBookings_BookingId1",
table: "EquipmentBookings",
column: "BookingId1");
migrationBuilder.CreateIndex(
name: "IX_EquipmentBookings_EquipmentId1",
table: "EquipmentBookings",
column: "EquipmentId1");
migrationBuilder.AddForeignKey(
name: "FK_EquipmentBookings_Bookings_BookingId1",
table: "EquipmentBookings",
column: "BookingId1",
principalTable: "Bookings",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_EquipmentBookings_Equipment_EquipmentId1",
table: "EquipmentBookings",
column: "EquipmentId1",
principalTable: "Equipment",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
<file_sep>/CNA/SimpleClientServer/SimpleServerCS/Client.cs
using Packets;
using System;
using System.IO;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
namespace SimpleServerCS
{
class Client
{
public Socket socket { get; set; }
public String nickname { get; set; }
private Thread thread { get; set; }
public NetworkStream stream;
public BinaryReader reader;
public BinaryWriter writer;
public Client(Socket socket)
{
this.socket = socket;
stream = new NetworkStream(socket, true);
reader = new BinaryReader(stream, Encoding.UTF8);
writer = new BinaryWriter(stream, Encoding.UTF8);
}
public void Start()
{
thread = new Thread(new ThreadStart(SocketMethod));
thread.Start();
}
public void Stop()
{
socket.Close();
if (thread.IsAlive == true)
{
thread.Abort();
}
}
private void SocketMethod()
{
SimpleServer.SocketMethod(this);
}
public void SendText(Client client, String receivedMessage)
{
if (!socket.Connected)
return;
string message = client.nickname + "==> " + receivedMessage;
ChatMessagePacket chatMessagePacket = new ChatMessagePacket(message);
Send(chatMessagePacket);
}
public void Send(Packet data)
{
MemoryStream mem = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(mem, data);
byte[] buffer = mem.GetBuffer();
writer.Write(buffer.Length);
writer.Write(buffer);
writer.Flush();
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ApplicationUI/LoginCommand.cs
using AnimalCareSystem.Handlers;
using AnimalCareSystem.Models;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ApplicationUI
{
public class LoginCommand : ICommand
{
private string Email;
private string Password;
private bool RememberMe;
private AccountHandler AccountHandler;
public LoginCommand(string email, string password, bool rememberMe, SignInManager<ApplicationUser> signInManager)
{
Email = email;
Password = <PASSWORD>;
RememberMe = rememberMe;
AccountHandler = new AccountHandler(signInManager);
}
public async Task<object> Execute()
{
return await AccountHandler.Login(Email, Password, RememberMe);
}
}
}
<file_sep>/ESA/ESA/src/esa/CodeExample.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package esa;
/**
*
* @author danpa
*/
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CodeExample extends JPanel{
static JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TabbedPaneDemo codeExample = new TabbedPaneDemo();
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container panel = frame.getContentPane();
panel.setLayout(new BorderLayout());
panel.add(new TabbedPaneDemo(), BorderLayout.CENTER);
frame.pack();
frame.setSize(1000, 1000);
frame.setVisible(true);
}
});
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ViewModels/PriceMatchVehiclesViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels
{
public class PriceMatchVehiclesViewModel
{
[Required]
public int VehicleId { get; set; }
public string VehicleDescription { get; set; }
public string VehicleTypeCostPerDay { get; set; }
public string PriceToMatch { get; set; }
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/GetFuelTypesCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class GetFuelTypesCommand : ICommand
{
private VehicleHandler VehicleHandler;
public GetFuelTypesCommand(ApplicationDbContext dbContext)
{
VehicleHandler = new VehicleHandler(dbContext);
}
public async Task<object> Execute()
{
return await VehicleHandler.GetFuelTypes();
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/Handler/DateHandler.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFDataParallelismProj.DTO;
namespace WPFDataParallelismProj.Handler
{
class DateHandler
{
public async Task<Date[]> GetDates(HashSet<Order> orders)
{
Date[] dates = new Date[0];
await Task.Run(() =>
{
dates = orders.GroupBy(order => order.Date)
.Select(order => order.Key).ToArray();
});
return dates;
}
}
}
<file_sep>/ESA/Flights Management/test/database/FlightTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package database;
import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Krzychu
*/
public class FlightTest {
public FlightTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getSeat method, of class Flight.
*/
@Test
public void testGetSeat() {
System.out.println("getSeat");
Flight instance = new Flight();
Seat expResult = new Seat(1,1,1,true);
instance.addSeat(expResult);
ArrayList<Seat> seats = instance.getSeat();
Seat result = seats.get(0);
assertEquals(expResult, result);
}
/**
* Test of addSeat method, of class Flight.
*/
@Test
public void testAddSeat() {
System.out.println("addSeat");
Seat expResult = new Seat(1,1,1,true);
Flight instance = new Flight();
instance.addSeat(expResult);
ArrayList<Seat> seats = instance.getSeat();
Seat result = seats.get(0);
assertEquals(expResult, result);
}
/**
* Test of getPlane method, of class Flight.
*/
@Test
public void testGetPlane() {
System.out.println("getPlane");
Flight instance = new Flight();
Plane expResult = new Plane(1,"test1",1,"test2","test3");
instance.setPlane(expResult);
Plane result = instance.getPlane();
assertEquals(expResult, result);
}
/**
* Test of setPlane method, of class Flight.
*/
@Test
public void testSetPlane() {
System.out.println("setPlane");
Flight instance = new Flight();
Plane expResult = new Plane(1,"test1",1,"test2","test3");
instance.setPlane(expResult);
Plane result = instance.getPlane();
assertEquals(expResult, result);
}
/**
* Test of getFlightID method, of class Flight.
*/
@Test
public void testGetFlightID() {
System.out.println("getFlightID");
Flight instance = new Flight();
int expResult = 1;
instance.setFlightID(expResult);
int result = instance.getFlightID();
assertEquals(expResult, result);
}
/**
* Test of setFlightID method, of class Flight.
*/
@Test
public void testSetFlightID() {
System.out.println("setFlightID");
Flight instance = new Flight();
int expResult = 1;
instance.setFlightID(expResult);
int result = instance.getFlightID();
assertEquals(expResult, result);
}
/**
* Test of getPlaneID method, of class Flight.
*/
@Test
public void testGetPlaneID() {
System.out.println("getPlaneID");
Flight instance = new Flight();
int expResult = 1;
instance.setPlaneID(expResult);
int result = instance.getPlaneID();
assertEquals(expResult, result);
}
/**
* Test of setPlaneID method, of class Flight.
*/
@Test
public void testSetPlaneID() {
System.out.println("setPlaneID");
Flight instance = new Flight();
int expResult = 1;
instance.setPlaneID(expResult);
int result = instance.getPlaneID();
assertEquals(expResult, result);
}
/**
* Test of getfOrigin method, of class Flight.
*/
@Test
public void testGetfOrigin() {
System.out.println("getfOrigin");
Flight instance = new Flight();
String expResult = "test origin";
instance.setfOrigin(expResult);
String result = instance.getfOrigin();
assertEquals(expResult, result);
}
/**
* Test of setfOrigin method, of class Flight.
*/
@Test
public void testSetfOrigin() {
System.out.println("setfOrigin");
Flight instance = new Flight();
String expResult = "test origin";
instance.setfOrigin(expResult);
String result = instance.getfOrigin();
assertEquals(expResult, result);
}
/**
* Test of getfDestination method, of class Flight.
*/
@Test
public void testGetfDestination() {
System.out.println("getfDestination");
Flight instance = new Flight();
String expResult = "test destination";
instance.setfDestination(expResult);
String result = instance.getfDestination();
assertEquals(expResult, result);
}
/**
* Test of setfDestination method, of class Flight.
*/
@Test
public void testSetfDestination() {
System.out.println("setfDestination");
Flight instance = new Flight();
String expResult = "test destination";
instance.setfDestination(expResult);
String result = instance.getfDestination();
assertEquals(expResult, result);
}
/**
* Test of getDepartureDate method, of class Flight.
*/
@Test
public void testGetDepartureDate() {
System.out.println("getDepartureDate");
Flight instance = new Flight();
Date expResult = Date.valueOf("2018-03-03");
instance.setDepartureDate(expResult);
Date result = instance.getDepartureDate();
assertEquals(expResult, result);
}
/**
* Test of setDepartureDate method, of class Flight.
*/
@Test
public void testSetDepartureDate() {
System.out.println("setDepartureDate");
Flight instance = new Flight();
Date expResult = Date.valueOf("2018-03-03");
instance.setDepartureDate(expResult);
Date result = instance.getDepartureDate();
assertEquals(expResult, result);
}
/**
* Test of getDepartureTime method, of class Flight.
*/
@Test
public void testGetDepartureTime() {
System.out.println("getDepartureTime");
Flight instance = new Flight();
Time expResult = Time.valueOf("20:20:00");
instance.setDepartureTime(expResult);
Time result = instance.getDepartureTime();
assertEquals(expResult, result);
}
/**
* Test of setDepartureTime method, of class Flight.
*/
@Test
public void testSetDepartureTime() {
System.out.println("setDepartureTime");
Flight instance = new Flight();
Time expResult = Time.valueOf("20:20:00");
instance.setDepartureTime(expResult);
Time result = instance.getDepartureTime();
assertEquals(expResult, result);
}
/**
* Test of getArrivalTime method, of class Flight.
*/
@Test
public void testGetArrivalTime() {
System.out.println("getArrivalTime");
Flight instance = new Flight();
Time expResult = Time.valueOf("20:20:00");
instance.setArrivalTime(expResult);
Time result = instance.getArrivalTime();
assertEquals(expResult, result);
}
/**
* Test of setArrivalTime method, of class Flight.
*/
@Test
public void testSetArrivalTime() {
System.out.println("setArrivalTime");
Flight instance = new Flight();
Time expResult = Time.valueOf("20:20:00");
instance.setArrivalTime(expResult);
Time result = instance.getArrivalTime();
assertEquals(expResult, result);
}
/**
* Test of getArrivalDate method, of class Flight.
*/
@Test
public void testGetArrivalDate() {
System.out.println("getArrivalDate");
Flight instance = new Flight();
Date expResult = Date.valueOf("2018-03-03");
instance.setArrivalDate(expResult);
Date result = instance.getArrivalDate();
assertEquals(expResult, result);
}
/**
* Test of setArrivalDate method, of class Flight.
*/
@Test
public void testSetArrivalDate() {
System.out.println("setArrivalDate");
Flight instance = new Flight();
Date expResult = Date.valueOf("2018-03-03");
instance.setArrivalDate(expResult);
Date result = instance.getArrivalDate();
assertEquals(expResult, result);
}
}<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/GetTotalCostInWeekForSupplierTypeForStoreCommand.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using WPFDataParallelismProj.DTO;
using WPFDataParallelismProj.Handler;
namespace WPFDataParallelismProj.CommandsFactory
{
class GetTotalCostInWeekForSupplierTypeForStoreCommand : ICommand
{
private HashSet<Order> orders;
private Date date;
private Store store;
private string supplierType;
private OrderHandler orderHandler;
public GetTotalCostInWeekForSupplierTypeForStoreCommand(HashSet<Order> orders, Date date, Store store, string supplierType)
{
this.orders = orders;
this.date = date;
this.store = store;
this.supplierType = supplierType;
orderHandler = new OrderHandler();
}
public async Task<object> Execute()
{
return await orderHandler.GetTotalCostInWeekForSupplierTypeForStore(orders, date, store, supplierType);
}
}
}<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/LoginCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class LoginCommand : ICommand
{
private String Email;
private String PasswordHash;
private UserHandler UserHandler;
private bool RememberMe;
public LoginCommand(string email, string passwordHash, bool rememberMe, SignInManager<ApplicationUser> signInManager)
{
Email = email;
PasswordHash = passwordHash;
RememberMe = rememberMe;
UserHandler = new UserHandler(signInManager);
}
public async Task<object> Execute()
{
return await UserHandler.Login(Email, PasswordHash, RememberMe);
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Models/Vehicle.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Models
{
public class Vehicle
{
public long Id { get; set; }
public String Manufacturer { get; set; }
public String Model { get; set; }
public int Doors { get; set; }
public int Seats { get; set; }
public String Colour { get; set; }
[DataType(DataType.Currency)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
[Display(Name = "GB£")]
public decimal CostPerDay { get; set; }
public VehicleType VehicleType { get; set; }
public Fuel Fuel { get; set; }
public Transmission Transmission { get; set; }
public String VehicleImageSource { get; set; }
public String VehicleComparisonSourceURL { get; set; }
public Vehicle()
{
}
public Vehicle(long id, string manufacturer, string model, int doors, int seats, string colour, VehicleType vehicleType, Fuel fuel, Transmission transmission, decimal costPerDay, String vehicleImageSource)
{
Id = id;
Manufacturer = manufacturer;
Model = model;
Doors = doors;
Seats = seats;
Colour = colour;
VehicleType = vehicleType;
Fuel = fuel;
Transmission = transmission;
CostPerDay = costPerDay;
VehicleImageSource = vehicleImageSource;
}
public Vehicle(long id, string manufacturer, string model, int doors, int seats, string colour, VehicleType vehicleType, Fuel fuel, Transmission transmission, decimal costPerDay)
{
Id = id;
Manufacturer = manufacturer;
Model = model;
Doors = doors;
Seats = seats;
Colour = colour;
VehicleType = vehicleType;
Fuel = fuel;
Transmission = transmission;
CostPerDay = costPerDay;
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Data/ApplicationDbContext.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using AnimalCareSystem.Models;
namespace AnimalCareSystem.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public DbSet<ApplicationUser> User { get; set; }
public DbSet<Job> Job { get; set; }
public DbSet<JobStatus> JobStatus { get; set; }
public DbSet<Message> Message { get; set; }
public DbSet<ServiceRate> ServiceRate { get; set; }
public DbSet<ServiceType> ServiceType { get; set; }
public DbSet<UserReport> UserReport { get; set; }
public DbSet<UserReview> UserReview { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
Database.EnsureCreated();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
modelBuilder.Entity<Job>().ToTable("Job");
modelBuilder.Entity<JobStatus>().ToTable("JobStatus");
modelBuilder.Entity<Message>().ToTable("Message");
modelBuilder.Entity<ServiceRate>().ToTable("ServiceRate");
modelBuilder.Entity<ServiceType>().ToTable("ServiceType");
modelBuilder.Entity<UserReport>().ToTable("UserReport");
modelBuilder.Entity<UserReview>().ToTable("UserReview");
modelBuilder.Entity<IdentityUser>()
.HasIndex(iu => iu.Id)
.IsUnique(true);
modelBuilder.Entity<Job>()
.HasIndex(iu => iu.Id)
.IsUnique(true);
modelBuilder.Entity<JobStatus>()
.HasIndex(iu => iu.Id)
.IsUnique(true);
modelBuilder.Entity<Message>()
.HasIndex(iu => iu.Id)
.IsUnique(true);
modelBuilder.Entity<ServiceRate>()
.HasIndex(iu => iu.Id)
.IsUnique(true);
modelBuilder.Entity<ServiceType>()
.HasIndex(iu => iu.Id)
.IsUnique(true);
modelBuilder.Entity<UserReport>()
.HasIndex(iu => iu.Id)
.IsUnique(true);
modelBuilder.Entity<UserReview>()
.HasIndex(iu => iu.Id)
.IsUnique(true);
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ViewModels/CollectBookingViewModel.cs
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels
{
public class CollectBookingViewModel
{
[Required(ErrorMessage = "Booking ID is required.")]
public int BookingId { get; set; }
[Required(ErrorMessage = "Driving license number is required.")]
public String DrivingLicenseNumber { get; set; }
[Required(ErrorMessage = "An image of the front of the driving license is required.")]
public IFormFile DrivingLicenseImageFront { get; set; }
[Required(ErrorMessage = "An image of the back of the driving license is required.")]
public IFormFile DrivingLicenseImageBack { get; set; }
[Required(ErrorMessage = "An image of the person collecting the booking is required")]
public IFormFile PersonCollectingImage { get; set; }
[Required(ErrorMessage = "An image of the additional identification is required")]
public IFormFile AdditionalIdentificationImage { get; set; }
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/CommandFactory.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class CommandFactory
{
public const int REGISTER = 1;
public const int LOGIN = 2;
public const int GET_VEHICLE_TYPES = 3;
public const int GET_TRANSMISSION_TYPES = 4;
public const int GET_FUEL_TYPES = 5;
public const int ADD_VEHICLE = 6;
public const int GET_VEHICLES = 7;
public const int GET_ALL_BOOKINGS_FOR_VEHICLE = 8;
public const int GET_VEHICLE = 9;
public const int GET_ALL_EQUIPMENT = 10;
public const int CHECK_FOR_COINCIDING_BOOKINGS = 11;
public const int CHECK_EQUIPMENT_AVAILABILITY = 12;
public const int ADD_BOOKING = 13;
public const int CREATE_EQUIPMENT_BOOKING = 14;
public const int GET_BOOKING = 15;
public const int UPDATE_BOOKING = 16;
public const int DELETE_BOOKING = 17;
public const int BLACKLIST_USER = 18;
public const int COLLECT_BOOKING = 19;
public const int GET_ALL_BOOKINGS_FOR_USER = 20;
public const int GET_INVALID_LICENSES = 21;
public const int SEND_EMAIL = 22;
public const int UPDATE_USER = 23;
public const int GET_INSURANCE_FRAUD_DATA = 24;
public const int UPDATE_VEHICLE_COMPARISON_SOURCE = 25;
public const int UPDATE_VEHICLE_COST_PER_DAY = 26;
public static ICommand CreateCommand(int commandType)
{
switch(commandType)
{
case GET_INVALID_LICENSES:
return new GetInvalidLicensesCommand();
case GET_INSURANCE_FRAUD_DATA:
return new GetInsuranceFraudDataCommand();
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, ApplicationDbContext dbContext, int entityId, string text)
{
switch(commandType)
{
case UPDATE_VEHICLE_COMPARISON_SOURCE:
return new UpdateVehicleComparisonSourceCommand(dbContext, entityId, text);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, ApplicationDbContext dbContext, long entityId, int number)
{
switch(commandType)
{
case UPDATE_VEHICLE_COST_PER_DAY:
return new UpdateVehicleCostPerDayCommand(dbContext, entityId, number);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, IFormFileCollection formFileCollection, ApplicationUser user)
{
switch(commandType)
{
case SEND_EMAIL:
return new SendEmailCommand(formFileCollection, user);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, ApplicationDbContext dbContext)
{
switch (commandType)
{
case GET_VEHICLE_TYPES:
return new GetVehicleTypesCommand(dbContext);
case GET_TRANSMISSION_TYPES:
return new GetTransmissionTypesCommand(dbContext);
case GET_FUEL_TYPES:
return new GetFuelTypesCommand(dbContext);
case GET_VEHICLES:
return new GetVehiclesCommand(dbContext);
case GET_ALL_EQUIPMENT:
return new GetAllEquipmentCommand(dbContext);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, ApplicationUser newUser, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
switch (commandType)
{
case REGISTER:
return new RegisterCommand(newUser, userManager, signInManager);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, string email, string password, bool rememberMe, SignInManager<ApplicationUser> signInManager)
{
switch (commandType)
{
case LOGIN:
return new LoginCommand(email, password, rememberMe, signInManager);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, long entityId, ApplicationDbContext dbContext)
{
switch (commandType)
{
case GET_ALL_BOOKINGS_FOR_VEHICLE:
return new GetAllBookingsForVehicleCommand(entityId, dbContext);
case GET_VEHICLE:
return new GetVehicleCommand(entityId, dbContext);
case GET_BOOKING:
return new GetBookingCommand(entityId, dbContext);
case DELETE_BOOKING:
return new DeleteBookingCommand(entityId, dbContext);
case COLLECT_BOOKING:
return new CollectBookingCommand(entityId, dbContext);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, string userId, ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager)
{
switch (commandType)
{
case BLACKLIST_USER:
return new BlacklistUserCommand(userId, dbContext, userManager);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, ApplicationUser user, ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager)
{
switch (commandType)
{
case UPDATE_USER:
return new UpdateUserCommand(user, userManager, dbContext);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, string userId, ApplicationDbContext dbContext)
{
switch (commandType)
{
case GET_ALL_BOOKINGS_FOR_USER:
return new GetAllBookingsForUserCommand(userId, dbContext);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, Vehicle newVehicle, ApplicationDbContext dbContext)
{
switch (commandType)
{
case ADD_VEHICLE:
return new AddVehicleCommand(newVehicle, dbContext);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, DateTime requestedStartDate, DateTime requestedEndDate, ApplicationDbContext dbContext)
{
switch (commandType)
{
case CHECK_FOR_COINCIDING_BOOKINGS:
return new GetCoincidingBookingsCommand(requestedStartDate, requestedEndDate, dbContext);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, List<Booking> bookings, Equipment equipment, ApplicationDbContext dbContext)
{
switch (commandType)
{
case CHECK_EQUIPMENT_AVAILABILITY:
return new CheckEquipmentAvailabilityCommand(equipment, bookings, dbContext);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, Booking booking, List<Equipment> chosenEquipmentList, ApplicationDbContext dbContext)
{
switch (commandType)
{
case ADD_BOOKING:
return new AddBookingCommand(booking, chosenEquipmentList, dbContext);
case UPDATE_BOOKING:
return new UpdateBookingCommand(booking, chosenEquipmentList, dbContext);
default:
return new NullObjectCommand();
}
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ApplicationUI/GetConfirmationEmailTokenCommand.cs
using AnimalCareSystem.Handlers;
using AnimalCareSystem.Models;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ApplicationUI
{
public class GetConfirmationEmailTokenCommand : ICommand
{
private ApplicationUser User;
private AccountHandler AccountHandler;
public GetConfirmationEmailTokenCommand(ApplicationUser user, UserManager<ApplicationUser> userManager)
{
User = user;
AccountHandler = new AccountHandler(userManager);
}
public async Task<object> Execute()
{
return await AccountHandler.GetEmailConfirmationToken(User);
}
}
}
<file_sep>/ESA/Flights Management/src/model/PassengerHandler.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import database.*;
import java.sql.*;
import builder.*;
import java.util.ArrayList;
/**
*
* @author Greg
*/
public class PassengerHandler
{
private String PassengerInfo;
private final String add = "INSERT INTO PASSENGER (FORENAME, SURNAME, DOB, NATIONALITY, PASSPORT_NUMBER)VALUES (";
private static final String FIND_ALL = "SELECT * FROM PASSENGER ORDER BY PASSENGER.PASSENGER_ID";
private static final String FIND_BY_SURNAME = "SELECT * FROM PASSENGER WHERE SURNAME = ?";
private static final String FIND_BY_PASSPORT_NUMBER = "SELECT * FROM PASSENGER WHERE PASSPORT_NUMBER = ?";
private static final String ORDER_BY = " ORDER BY PASSENGER.PASSENGER_ID";
private static final String FIND_SPECIFIC = "SELECT * FROM PASSENGER WHERE (";
public Boolean addPassenger(Passenger p)
{
DatabaseConnectionPool pool = DatabaseConnectionPool.getInstance();
Connection con = pool.getAvailableConnection();
try
{
PassengerInfo = (p.toString());
PreparedStatement stmt = con.prepareStatement(add + PassengerInfo + ")");
stmt.execute();
stmt.close();
pool.returnConnection(con);
return true;
}
catch (SQLException sqle)
{
sqle.printStackTrace(System.err);
return false;
}
}
public ArrayList<Passenger> findAllPassengers()
{
ArrayList<Passenger> list = new ArrayList<>();
int oldPNum = -1;
PassengerBuilder pb = null;
DatabaseConnectionPool pool = DatabaseConnectionPool.getInstance();
Connection con = pool.getAvailableConnection();
try
{
PreparedStatement stmt = con.prepareStatement(FIND_ALL);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
int PassengerID = rs.getInt("PASSENGER_ID");
if (PassengerID != oldPNum)
{
if (pb != null)
{
list.add(pb.build());
}
pb = new PassengerBuilder();
pb.setPID(PassengerID);
pb.setPForename(rs.getString("FORENAME"));
pb.setPSurname(rs.getString("SURNAME"));
pb.setPDOB(rs.getDate("DOB"));
pb.setPNationality(rs.getString("NATIONALITY"));
pb.setPPassportNumber(rs.getInt("PASSPORT_NUMBER"));
oldPNum = PassengerID;
}
}
if (pb != null)
{
Passenger p = pb.build();
addtRisksToPassenger(p);
list.add(p);
}
rs.close();
stmt.close();
pool.returnConnection(con);
return list;
}
catch (SQLException sqle)
{
sqle.printStackTrace(System.err);
return list;
}
}
public void addtRisksToPassenger(Passenger passenger) throws SQLException
{
ArrayList<Risk> risks = new ArrayList();
ArrayList<Integer> riskIDs = new ArrayList();
DatabaseConnectionPool pool = DatabaseConnectionPool.getInstance();
Connection con = pool.getAvailableConnection();
try
{
PreparedStatement stmt = con.prepareStatement("SELECT * FROM passenger_risk WHERE passenger_id = ?");
stmt.setInt(1, passenger.getPassengerID());
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
riskIDs.add(rs.getInt("risk_id"));
}
for (int riskID : riskIDs)
{
stmt = con.prepareStatement("SELECT * FROM risk WHERE risk_id = ?");
stmt.setInt(1, riskID);
rs = stmt.executeQuery();
while (rs.next())
{
Risk risk = new Risk(rs.getInt("risk_id"), rs.getString("risk_desc"), rs.getInt("risk_score"));
risks.add(risk);
passenger.addRisk(risk);
}
}
rs.close();
stmt.close();
pool.returnConnection(con);
}
catch (SQLException sqle)
{
System.out.println("ERROR\n" + sqle);
}
}
public ArrayList<Passenger> GetAllPassengersBySurname(String surname)
{
ArrayList<Passenger> list = new ArrayList<>();
int oldPNum = -1;
PassengerBuilder pb = null;
DatabaseConnectionPool pool = DatabaseConnectionPool.getInstance();
Connection con = pool.getAvailableConnection();
try
{
PreparedStatement preparedStatement = con.prepareStatement(FIND_BY_SURNAME);
preparedStatement.setString(1, surname);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next())
{
int PassengerID = rs.getInt("PASSENGER_ID");
if (PassengerID != oldPNum)
{
if (pb != null)
{
list.add(pb.build());
}
pb = new PassengerBuilder();
pb.setPID(PassengerID);
pb.setPForename(rs.getString("FORENAME"));
pb.setPSurname(rs.getString("SURNAME"));
pb.setPDOB(rs.getDate("DOB"));
pb.setPNationality(rs.getString("NATIONALITY"));
pb.setPPassportNumber(rs.getInt("PASSPORT_NUMBER"));
oldPNum = PassengerID;
}
}
if (pb != null)
{
list.add(pb.build());
}
rs.close();
preparedStatement.close();
pool.returnConnection(con);
return list;
}
catch (SQLException sqle)
{
sqle.printStackTrace(System.err);
return list;
}
}
public ArrayList<Passenger> GetAllPassengersByPassport(int integer)
{
ArrayList<Passenger> list = new ArrayList<>();
int oldPNum = -1;
PassengerBuilder pb = null;
DatabaseConnectionPool pool = DatabaseConnectionPool.getInstance();
Connection con = pool.getAvailableConnection();
try
{
PreparedStatement preparedStatement = con.prepareStatement(FIND_BY_PASSPORT_NUMBER);
preparedStatement.setInt(1, integer);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next())
{
int PassengerID = rs.getInt("PASSENGER_ID");
if (PassengerID != oldPNum)
{
if (pb != null)
{
list.add(pb.build());
}
pb = new PassengerBuilder();
pb.setPID(PassengerID);
pb.setPForename(rs.getString("FORENAME"));
pb.setPSurname(rs.getString("SURNAME"));
pb.setPDOB(rs.getDate("DOB"));
pb.setPNationality(rs.getString("NATIONALITY"));
pb.setPPassportNumber(rs.getInt("PASSPORT_NUMBER"));
oldPNum = PassengerID;
}
}
if (pb != null)
{
list.add(pb.build());
}
rs.close();
preparedStatement.close();
pool.returnConnection(con);
return list;
}
catch (SQLException sqle)
{
sqle.printStackTrace(System.err);
return list;
}
}
public ArrayList<Passenger> findSpecificPassenger(Passenger p)
{
ArrayList<Passenger> list = new ArrayList<>();
int oldPNum = -1;
PassengerBuilder pb = null;
String SearchCriteria = null;
if (p.getPassengerID() == 0)
{
SearchCriteria = "PASSENGER_ID = " + p.getPassengerID() + " AND ";
}
else if (p.getForename() == null)
{
SearchCriteria = "FORENAME = '" + p.getForename() + "' AND ";
}
else if (p.getSurname() == null)
{
SearchCriteria = "SURNAME = '" + p.getSurname() + "' AND ";
}
else if (p.getDOB() == null)
{
SearchCriteria = "DOB = '" + p.getDOB() + "' AND ";
}
else if (p.getNationality() == null)
{
SearchCriteria = "NATIONALITY = " + p.getNationality() + "' AND ";
}
else if (p.getPassportNumber() == 0)
{
SearchCriteria = "PASSPORT_NUMBER = " + p.getPassportNumber();
}
if (SearchCriteria.endsWith(" AND "))
{
SearchCriteria = SearchCriteria.substring(5);
}
DatabaseConnectionPool pool = DatabaseConnectionPool.getInstance();
Connection con = pool.getAvailableConnection();
if (SearchCriteria == null)
{
return null;
}
else
{
SearchCriteria = SearchCriteria + ")" + ORDER_BY;
}
try
{
PreparedStatement stmt = con.prepareStatement(FIND_SPECIFIC + SearchCriteria);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
int PassengerID = rs.getInt("PASSENGER_ID");
if (PassengerID != oldPNum)
{
if (pb != null)
{
list.add(pb.build());
}
pb = new PassengerBuilder();
pb.setPID(PassengerID);
pb.setPForename(rs.getString("FORENAME"));
pb.setPSurname(rs.getString("SURNAME"));
pb.setPDOB(rs.getDate("DOB"));
pb.setPNationality(rs.getString("NATIONALITY"));
pb.setPPassportNumber(rs.getInt("PASSPORT_NUMBER"));
oldPNum = PassengerID;
}
}
if (pb != null)
{
Passenger pas = pb.build();
addtRisksToPassenger(pas);
list.add(pas);
}
rs.close();
stmt.close();
pool.returnConnection(con);
return list;
}
catch (SQLException sqle)
{
sqle.printStackTrace(System.err);
return list;
}
}
public String checkPassengerRiskLevel(Passenger passenger, int maxRiskValue)
{
String riskLevel = "Green";
int totalRiskScore = 0;
System.out.println(passenger.toString());
for (Risk risk : passenger.getRisks())
{
totalRiskScore += risk.getRiskScore();
}
if (totalRiskScore < (maxRiskValue / 2))
{
riskLevel = "Green";
}
else if (totalRiskScore >= (maxRiskValue / 2) && totalRiskScore < maxRiskValue)
{
riskLevel = "Amber";
}
else if (totalRiskScore >= maxRiskValue)
{
riskLevel = "Red";
}
return riskLevel;
}
}
<file_sep>/ESA/Flights Management/test/database/RiskTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package database;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Krzychu
*/
public class RiskTest {
public RiskTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getPassRisk method, of class Risk.
*/
@Test
public void testGetPassRisk() {
System.out.println("getPassRisk");
Risk instance = new Risk();
PassengerRisk_ByFlight expResult = new PassengerRisk_ByFlight(5, 5);
instance.setPassRisk(expResult);
PassengerRisk_ByFlight result = instance.getPassRisk();
assertEquals(expResult, result);
}
/**
* Test of setPassRisk method, of class Risk.
*/
@Test
public void testSetPassRisk() {
System.out.println("setPassRisk");
Risk instance = new Risk();
PassengerRisk_ByFlight expResult = new PassengerRisk_ByFlight(5, 5);
instance.setPassRisk(expResult);
PassengerRisk_ByFlight result = instance.getPassRisk();
assertEquals(expResult, result);
}
/**
* Test of getRiskID method, of class Risk.
*/
@Test
public void testGetRiskID() {
System.out.println("getRiskID");
Risk instance = new Risk(2,"test",0);
int expResult = 2;
int result = instance.getRiskID();
assertEquals(expResult, result);
}
/**
* Test of setRiskID method, of class Risk.
*/
@Test
public void testSetRiskID() {
System.out.println("setRiskID");
int expResult = 2;
Risk instance = new Risk();
instance.setRiskID(expResult);
int result = instance.getRiskID();
assertEquals(expResult, result);
}
/**
* Test of getRiskFactor method, of class Risk.
*/
@Test
public void testGetRiskFactor() {
System.out.println("getRiskFactor");
Risk instance = new Risk(2,"test",0);
String expResult = "test";
String result = instance.getRiskFactor();
assertEquals(expResult, result);
}
/**
* Test of setRiskFactor method, of class Risk.
*/
@Test
public void testSetRiskFactor() {
System.out.println("setRiskFactor");
String expResult = "test";
Risk instance = new Risk();
instance.setRiskFactor(expResult);
String result = instance.getRiskFactor();
assertEquals(expResult, result);
}
/**
* Test of getRiskScore method, of class Risk.
*/
@Test
public void testGetRiskScore() {
System.out.println("getRiskScore");
Risk instance = new Risk(2,"test",10);
int expResult = 10;
int result = instance.getRiskScore();
assertEquals(expResult, result);
}
/**
* Test of setRiskScore method, of class Risk.
*/
@Test
public void testSetRiskScore() {
System.out.println("setRiskScore");
int expResult = 10;
Risk instance = new Risk();
instance.setRiskScore(expResult);
int result = instance.getRiskScore();
assertEquals(expResult, result);
}
}
<file_sep>/OOAE/T2/T2-05/wk2-05_lec1_BuilderProj/wk2-05_lec1_VisitorProj/src/command/CommandFactory.java
package command;
import model.ConsultantHandler;
import model.DepartmentHandler;
import model.EmployeeHandler;
public class CommandFactory
{
public static final int VIEW_ALL_DEPARTMENTS = 1;
public static final int VIEW_ALL_EMPLOYEES = 2;
public static final int VIEW_ALL_CONSULTANTS = 3;
public static Command create(int typeOfCommand)
{
switch (typeOfCommand)
{
case VIEW_ALL_DEPARTMENTS:
return new GetAllDeptsCommand(new DepartmentHandler());
case VIEW_ALL_EMPLOYEES:
return new GetAllEmployeesCommand(new EmployeeHandler());
case VIEW_ALL_CONSULTANTS:
return new GetAllConsultantsCommand(new ConsultantHandler());
default:
return null;
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ApplicationUI/CommandFactory.cs
using AnimalCareSystem.Data;
using AnimalCareSystem.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ApplicationUI
{
public class CommandFactory
{
public const int REGISTER = 1;
public const int LOGIN = 2;
public const int GET_CONFIRMATION_EMAIL_TOKEN = 3;
public const int GET_USER_BY_ID = 4;
public const int CONFIRM_EMAIL = 5;
public const int GET_SERVICE_TYPES = 6;
public const int UPDATE_USER = 7;
public const int GET_USERS_BY_CITY = 8;
public static ICommand CreateCommand(int commandType, ApplicationUser newUser, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
switch (commandType)
{
case REGISTER:
return new RegisterCommand(newUser, userManager, signInManager);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, string email, string password, bool rememberMe, SignInManager<ApplicationUser> signInManager)
{
switch (commandType)
{
case LOGIN:
return new LoginCommand(email, password, rememberMe, signInManager);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, ApplicationUser user, UserManager<ApplicationUser> userManager)
{
switch (commandType)
{
case GET_CONFIRMATION_EMAIL_TOKEN:
return new GetConfirmationEmailTokenCommand(user, userManager);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, string id, UserManager<ApplicationUser> userManager, ApplicationDbContext dbContext)
{
switch(commandType)
{
case GET_USER_BY_ID:
return new GetUserByIdCommand(id, userManager, dbContext);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, ApplicationUser user, string id, UserManager<ApplicationUser> userManager)
{
switch (commandType)
{
case CONFIRM_EMAIL:
return new ConfirmEmailCommand(user, id, userManager);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, ApplicationDbContext dbContext)
{
switch(commandType)
{
case GET_SERVICE_TYPES:
return new GetServiceTypesCommand(dbContext);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, ApplicationUser user, ApplicationDbContext dbContext)
{
switch (commandType)
{
case UPDATE_USER:
return new UpdateUserCommand(user, dbContext);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, string str, ApplicationDbContext dbContext)
{
switch (commandType)
{
case GET_USERS_BY_CITY:
return new GetUsersByCityCommand(str, dbContext);
default:
return new NullObjectCommand();
}
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/CommandFactory.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFDataParallelismProj.DTO;
namespace WPFDataParallelismProj.CommandsFactory
{
class CommandFactory
{
public const int SET_FOLDER_PATH = 1;
public const int LOAD_DATA = 2;
public const int GET_SUPPLIERS = 3;
public const int GET_STORES = 4;
public const int GET_SUPPLIER_TYPES = 5;
public const int GET_DATES = 6;
public const int GET_TOTAL_COST_ALL_ORDERS = 7;
public const int GET_TOTAL_COST_FOR_STORE = 8;
public const int GET_TOTAL_COST_IN_WEEK = 9;
public const int GET_TOTAL_COST_IN_WEEK_FOR_STORE = 10;
public const int GET_TOTAL_COST_FOR_SUPPLIER = 11;
public const int GET_TOTAL_COST_FOR_SUPPLIER_TYPE = 12;
public const int GET_TOTAL_COST_IN_WEEK_FOR_SUPPLIER_TYPE = 13;
public const int GET_TOTAL_COST_FOR_SUPPLIER_TYPE_FOR_STORE = 14;
public const int GET_TOTAL_COST_IN_WEEK_FOR_SUPPLIER_TYPE_FOR_STORE = 15;
public static ICommand CreateCommand(int commandType, Action<int, int> callback)
{
switch (commandType)
{
case LOAD_DATA:
return new LoadDataCommand(callback);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, HashSet<Order> orders)
{
switch (commandType)
{
case GET_STORES:
return new GetStoresCommand(orders);
case GET_SUPPLIERS:
return new GetSuppliersCommand(orders);
case GET_SUPPLIER_TYPES:
return new GetSupplierTypesCommand(orders);
case GET_DATES:
return new GetDatesCommand(orders);
case GET_TOTAL_COST_ALL_ORDERS:
return new GetTotalCostAllOrdersCommand(orders);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, HashSet<Order> orders, Store store)
{
switch (commandType)
{
case GET_TOTAL_COST_FOR_STORE:
return new GetTotalCostForStoreCommand(orders, store);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, HashSet<Order> orders, Date date)
{
switch (commandType)
{
case GET_TOTAL_COST_IN_WEEK:
return new GetTotalCostInWeekCommand(orders, date);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, HashSet<Order> orders, Date date, string supplierType)
{
switch (commandType)
{
case GET_TOTAL_COST_IN_WEEK_FOR_SUPPLIER_TYPE:
return new GetTotalCostInWeekForSupplierTypeCommand(orders, date, supplierType);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, HashSet<Order> orders, Store store, string supplierType)
{
switch (commandType)
{
case GET_TOTAL_COST_FOR_SUPPLIER_TYPE_FOR_STORE:
return new GetTotalCostForSupplierTypeForStoreCommand(orders, store, supplierType);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, HashSet<Order> orders, Date date, Store store, string supplierType)
{
switch (commandType)
{
case GET_TOTAL_COST_IN_WEEK_FOR_SUPPLIER_TYPE_FOR_STORE:
return new GetTotalCostInWeekForSupplierTypeForStoreCommand(orders, date, store, supplierType);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, HashSet<Order> orders, string sup)
{
switch (commandType)
{
case GET_TOTAL_COST_FOR_SUPPLIER:
return new GetTotalCostForSupplierCommand(orders, sup);
case GET_TOTAL_COST_FOR_SUPPLIER_TYPE:
return new GetTotalCostForSupplierTypeCommand(orders, sup);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, HashSet<Order> orders, Date date, Store store)
{
switch (commandType)
{
case GET_TOTAL_COST_IN_WEEK_FOR_STORE:
return new GetTotalCostInWeekForStoreCommand(orders, date, store);
default:
return new NullObjectCommand();
}
}
public static ICommand CreateCommand(int commandType, string selectedFolderPath)
{
switch (commandType)
{
case SET_FOLDER_PATH:
return new SetFolderPathCommand(selectedFolderPath);
default:
return new NullObjectCommand();
}
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/GetTotalCostForSupplierTypeCommand.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using WPFDataParallelismProj.DTO;
using WPFDataParallelismProj.Handler;
namespace WPFDataParallelismProj.CommandsFactory
{
class GetTotalCostForSupplierTypeCommand : ICommand
{
private HashSet<Order> orders;
private string supplierType;
private OrderHandler orderHandler;
public GetTotalCostForSupplierTypeCommand(HashSet<Order> orders, string supplierType)
{
this.orders = orders;
this.supplierType = supplierType;
orderHandler = new OrderHandler();
}
public async Task<object> Execute()
{
return await orderHandler.GetTotalCostForSupplierType(orders, supplierType);
}
}
}<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-war/src/java/managed_bean/LoginBean.java
package managed_bean;
import dto.UserDTO;
import ejb.User_UIRemote;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
/**
*
* @author Rhys
*/
@Named(value = "loginBean")
@RequestScoped
public class LoginBean implements Serializable
{
@EJB
private User_UIRemote userUI;
private String email = "";
private String password = "";
private UserDTO loggedInUser;
public LoginBean()
{
}
public String login()
{
loggedInUser = userUI.login(email, password);
if (loggedInUser != null)
{
if (loggedInUser.isIsDriver())
{
HttpSession sessionScope = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
sessionScope.setAttribute("loggedDriver", loggedInUser);
}
else
{
HttpSession sessionScope = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
sessionScope.setAttribute("loggedUser", loggedInUser);
}
return "loggedIn";
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Login credentials are not correct"));
return null;
}
}
public void clearCredentials()
{
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
}
public String logout()
{
clearCredentials();
return "loggedOut";
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
try
{
byte[] hash
= MessageDigest.getInstance("SHA-256")
.digest(password.getBytes(StandardCharsets.UTF_8));
this.password
= Base64.getEncoder().encodeToString(hash);
}
catch (NoSuchAlgorithmException ex)
{
this.password = "";
Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/entity/DeliveryStatus.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Rhys
*/
@Entity
@Table(name = "DELIVERY_STATUS")
@XmlRootElement
@NamedQueries(
{
@NamedQuery(name = "DeliveryStatus.findAll", query = "SELECT d FROM DeliveryStatus d"),
@NamedQuery(name = "DeliveryStatus.findByDeliveryStatusId", query = "SELECT d FROM DeliveryStatus d WHERE d.deliveryStatusId = :deliveryStatusId"),
@NamedQuery(name = "DeliveryStatus.findByName", query = "SELECT d FROM DeliveryStatus d WHERE d.name = :name")
})
public class DeliveryStatus implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "DELIVERY_STATUS_ID")
private Integer deliveryStatusId;
@Size(max = 255)
@Column(name = "NAME")
private String name;
@OneToMany(mappedBy = "deliveryStatusId")
private Collection<Delivery> deliveryCollection;
public DeliveryStatus()
{
}
public DeliveryStatus(Integer deliveryStatusId)
{
this.deliveryStatusId = deliveryStatusId;
}
public Integer getDeliveryStatusId()
{
return deliveryStatusId;
}
public void setDeliveryStatusId(Integer deliveryStatusId)
{
this.deliveryStatusId = deliveryStatusId;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@XmlTransient
public Collection<Delivery> getDeliveryCollection()
{
return deliveryCollection;
}
public void setDeliveryCollection(Collection<Delivery> deliveryCollection)
{
this.deliveryCollection = deliveryCollection;
}
@Override
public int hashCode()
{
int hash = 0;
hash += (deliveryStatusId != null ? deliveryStatusId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object)
{
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof DeliveryStatus))
{
return false;
}
DeliveryStatus other = (DeliveryStatus) object;
if ((this.deliveryStatusId == null && other.deliveryStatusId != null) || (this.deliveryStatusId != null && !this.deliveryStatusId.equals(other.deliveryStatusId)))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "entity.DeliveryStatus[ deliveryStatusId=" + deliveryStatusId + " ]";
}
}
<file_sep>/CNA/SimpleClientServer/SimpleClientCS/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleClient
{
class Program
{
private const string hostname = "127.0.0.1";
private const int port = 4444;
public static void Main()
{
SimpleClient _client = new SimpleClient();
if (_client.Connect(hostname, port))
{
Console.WriteLine("Connected...");
try
{
_client.Run();
}
catch (NotConnectedException e)
{
Console.WriteLine("Client not Connected");
}
}
else
{
Console.WriteLine("Failed to connect to: " + hostname + ":" + port);
}
Console.Read();
}
}
}
<file_sep>/OOAE/T2/T2-01/wk2-01_TutProj/src/DTO/DeptDTO.java
package DTO;
/**
*
* @author <NAME>
*/
public class DeptDTO implements Comparable<DeptDTO>
{
private int departmentNumber;
private String departmentName;
private String departmentLocation;
public DeptDTO(int departmentNumber, String departmentName, String departmentLocation)
{
this.departmentNumber = departmentNumber;
this.departmentName = departmentName;
this.departmentLocation = departmentLocation;
}
public int getDepartmentNumber()
{
return departmentNumber;
}
public void setDepartmentNumber(int departmentNumber)
{
this.departmentNumber = departmentNumber;
}
public String getDepartmentName()
{
return departmentName;
}
public void setDepartmentName(String departmentName)
{
this.departmentName = departmentName;
}
public String getDepartmentLocation()
{
return departmentLocation;
}
public void setDepartmentLocation(String departmentLocation)
{
this.departmentLocation = departmentLocation;
}
@Override
public int compareTo(DeptDTO compareDept)
{
return Integer.compare(this.departmentNumber, compareDept.getDepartmentNumber());
}
@Override
public String toString()
{
return this.departmentNumber + ":" + this.departmentName + ":" + this.departmentLocation;
}
}
<file_sep>/OOAE/T1/T1-04 check portfolio/ShapesProj/src/shapesproj/ShapesProj.java
package shapesproj;
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class ShapesProj extends JFrame
{
private static ArrayList<Drawable> shapes = new ArrayList<>();
public static void main(String[] args)
{
myJFrame frame = new myJFrame();
frame.setSize(600, 800);
frame.setLocation(200, 100);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
DrawableCircle circle = new DrawableCircle(100, 100, 100);
circle.setColour(Color.red);
circle.setPosition(150, 175);
DrawableRectangle rectangle = new DrawableRectangle(40, 40);
rectangle.setColour(Color.green);
rectangle.setPosition(50, 100);
shapes.add(circle);
shapes.add(rectangle);
}
public static class myJFrame extends JFrame
{
@Override
public void paint(Graphics g)
{
super.paint(g);
for(Drawable d : shapes)
{
d.draw(g);
}
}
}
}
<file_sep>/OOAE/T1/T1-09/VehicleShowroomProj/test/vehicleshowroomproj/ShowroomTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vehicleshowroomproj;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Rhysj
*/
public class ShowroomTest
{
public ShowroomTest()
{
}
@BeforeClass
public static void setUpClass()
{
}
@AfterClass
public static void tearDownClass()
{
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
/**
* Test of setCurrentVehicle method, of class Showroom.
*/
@Test
public void testSetCurrentVehicle()
{
System.out.println("setCurrentVehicle");
Vehicle vehicle = null;
Showroom instance = new Showroom();
instance.setCurrentVehicle(vehicle);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getCurrentVehicle method, of class Showroom.
*/
@Test
public void testGetCurrentVehicle()
{
System.out.println("getCurrentVehicle");
Showroom instance = new Showroom();
Vehicle expResult = null;
Vehicle result = instance.getCurrentVehicle();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of nextVehicle method, of class Showroom.
*/
@Test
public void testNextVehicle()
{
System.out.println("nextVehicle");
Showroom instance = new Showroom();
Boolean expResult = null;
Boolean result = instance.nextVehicle();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of previousVehicle method, of class Showroom.
*/
@Test
public void testPreviousVehicle()
{
System.out.println("previousVehicle");
Showroom instance = new Showroom();
Boolean expResult = null;
Boolean result = instance.previousVehicle();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of addVehicle method, of class Showroom.
*/
@Test
public void testAddVehicle()
{
System.out.println("addVehicle");
Vehicle vehicle = null;
Showroom instance = new Showroom();
boolean expResult = false;
boolean result = instance.addVehicle(vehicle);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of findVehicleByVin method, of class Showroom.
*/
@Test
public void testFindVehicleByVin()
{
System.out.println("findVehicleByVin");
String vin = "";
Showroom instance = new Showroom();
String expResult = "";
String result = instance.findVehicleByVin(vin);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of printArray method, of class Showroom.
*/
@Test
public void testPrintArray()
{
System.out.println("printArray");
Showroom instance = new Showroom();
instance.printArray();
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/CheckEquipmentAvailabilityCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class CheckEquipmentAvailabilityCommand : ICommand
{
private EquipmentHandler EquipmentHandler;
private Equipment Equipment;
private List<Booking> Bookings;
public CheckEquipmentAvailabilityCommand(Equipment equipment, List<Booking> bookings, ApplicationDbContext dbContext)
{
Equipment = equipment;
Bookings = bookings;
EquipmentHandler = new EquipmentHandler(dbContext);
}
public async Task<object> Execute()
{
return await EquipmentHandler.CheckEquipmentAvailability(Equipment, Bookings);
}
}
}
<file_sep>/OOAE/T1/T1-11/ProducerConsumerProj/src/producerconsumerproj/Buffer.java
package producerconsumerproj;
import java.util.*;
public class Buffer
{
private Queue<Integer> theData;
private final int MAX; // maximum size of the buffer
private int numItems;
public Buffer(int m)
{
MAX = m;
theData = new LinkedList<Integer>();
numItems = 0;
}
public synchronized int getNext(int consumerNo) throws InterruptedException
{
while (theData.size() == 0)
{
System.out.println("Consumer " + consumerNo + " attempting to remove from empty buffer - wait");
wait();
}
int data = theData.remove();
--numItems;
System.out.println("Consumer " + consumerNo + " retrieved " + data + " from buffer: " + theData.toString());
notifyAll();
return data;
}
public synchronized void add(int data, int producerNo) throws InterruptedException
{
while (numItems == MAX)
{
System.out.println("Producer " + producerNo + " attempting to add to full buffer - wait");
wait();
}
theData.add(data);
System.out.println("Producer " + producerNo + " added " + data + " to buffer:" + theData.toString());
++numItems;
notifyAll();
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_Library/src/dto/ParcelDTO.java
package dto;
/**
*
* @author Rhys
*/
public class ParcelDTO
{
private int parcelId;
private String recipientName;
private String addressLine1;
private String addressLine2;
private String postcode;
private String city;
private boolean delivered;
private DeliveryDTO delivery;
public ParcelDTO()
{
}
public ParcelDTO(int parcelId, String recipientName, String addressLine1, String addressLine2, String postcode, String city, boolean delivered, DeliveryDTO delivery)
{
this.parcelId = parcelId;
this.recipientName = recipientName;
this.addressLine1 = addressLine1;
this.addressLine2 = addressLine2;
this.postcode = postcode;
this.city = city;
this.delivered = delivered;
this.delivery = delivery;
}
public int getParcelId()
{
return parcelId;
}
public void setParcelId(int parcelId)
{
this.parcelId = parcelId;
}
public String getRecipientName()
{
return recipientName;
}
public void setRecipientName(String recipientName)
{
this.recipientName = recipientName;
}
public String getAddressLine1()
{
return addressLine1;
}
public void setAddressLine1(String addressLine1)
{
this.addressLine1 = addressLine1;
}
public String getAddressLine2()
{
return addressLine2;
}
public void setAddressLine2(String addressLine2)
{
this.addressLine2 = addressLine2;
}
public String getPostcode()
{
return postcode;
}
public void setPostcode(String postcode)
{
this.postcode = postcode;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public boolean isDelivered()
{
return delivered;
}
public void setDelivered(boolean delivered)
{
this.delivered = delivered;
}
public DeliveryDTO getDelivery()
{
return delivery;
}
public void setDelivery(DeliveryDTO delivery)
{
this.delivery = delivery;
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_Library/src/ejb/User_UIRemote.java
package ejb;
import dto.DeliveryDTO;
import dto.UserDTO;
import java.util.ArrayList;
import java.util.Date;
import javax.ejb.Remote;
/**
*
* @author Rhys
*/
@Remote
public interface User_UIRemote
{
UserDTO login(String email, String password);
boolean register(UserDTO userDTO);
DeliveryDTO search(int deliveryId);
boolean cancelDelivery(int deliveryId);
boolean bookCollection(int deliveryId, Date collectionDate);
boolean rescheduleDelivery(int deliveryId, Date newDeliveryDate);
ArrayList<DeliveryDTO> getRecipientDeliveries(int userId);
public UserDTO updateAccountDetails(UserDTO user, String oldPassword, String oldEmail);
boolean deleteAccount(UserDTO user);
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ApplicationUI/GetServiceTypesCommand.cs
using AnimalCareSystem.Data;
using AnimalCareSystem.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ApplicationUI
{
public class GetServiceTypesCommand : ICommand
{
private ServiceHandler ServiceHandler;
public GetServiceTypesCommand(ApplicationDbContext dbContext)
{
ServiceHandler = new ServiceHandler(dbContext);
}
public async Task<object> Execute()
{
return await ServiceHandler.GetServiceTypes();
}
}
}
<file_sep>/OOAE/T1/T1-03 check portfolio/VehicleShowroomProj/src/vehicleshowroomproj/TestCustomer.java
package vehicleshowroomproj;
public class TestCustomer
{
public static void main(String[] args)
{
Customer customer1 = new Customer("<NAME>", "<EMAIL>");
System.out.println(" " + customer1.getName());
System.out.println(" " + customer1.getContactDetails());
customer1.setName("<NAME>");
customer1.setContactDetails("07721145832");
System.out.println("\n setName and setContactDetails called to change the original attributes \n");
System.out.println(" " + customer1.getName());
System.out.println(" " + customer1.getContactDetails());
System.out.println("\n Now we will call toString");
System.out.println(" " + customer1.toString());
}
}
<file_sep>/OOAE/T1/T1-02/VehicleShowroomProj/src/vehicleshowroomproj/VehicleShowroomProj.java
package vehicleshowroomproj;
public class VehicleShowroomProj
{
public static void main(String[] args)
{
// create objects
Showroom showroom = new Showroom();
Customer customer1 = new Customer("<NAME>", "07585123456");
Customer customer2 = new Customer("<NAME>", "<EMAIL>");
Vehicle vehicle1 = new Vehicle("Mercedes", "SLK", "12h123b", "12/9/2017", 'C', 43000);
Vehicle vehicle2 = new Vehicle("peugeot", "208", "96a858h", "17/9/2014", 'B', 19595);
Vehicle vehicle3 = new Vehicle("Fiat", "500", "57f158p", "27/9/2017", 'G', 18700);
Vehicle vehicle4 = new Vehicle("Ford", "Kuga", "46n947l", "27/8/2013", 'D', 21000);
//print all vehicle details
System.out.println(" !!CALLING VEHICLE.TOSTRING!! \n");
System.out.println(" vehicle 1: \n" + vehicle1.toString() + "\n\n vehicle 2: \n"
+ vehicle2.toString() + "\n\n vehicle 3: \n" + vehicle3.toString() + "\n\n vehicle 4: \n"
+ vehicle4.toString() + "\n\n");
//buy vehicles
vehicle1.buy("27/9/2017", customer1);
vehicle3.buy("5/10/2017", customer2);
//re-print all vehicle details
System.out.println(" !!CALLING VEHICLE.TOSTRING AFTER BUYING VEHICLE 1 AND 3!! \n");
System.out.println(" vehicle 1: \n" + vehicle1.toString() + "\n\n vehicle 2: \n"
+ vehicle2.toString() + "\n\n vehicle 3: \n" + vehicle3.toString() + "\n\n vehicle 4: \n"
+ vehicle4.toString() + "\n\n");
//add vehicles to showroom
showroom.addVehicle(vehicle1);
showroom.addVehicle(vehicle2);
showroom.addVehicle(vehicle3);
//find vehicle by a vin number
System.out.println(" !!CALLING SHOWROOM.FINDVEHICLEBYVIN!! \n");
System.out.println(" Vehicle found by VIN 57F158P: \n" + showroom.findVehicleByVin("57f158p")
+ "\n\n");
//set showroom current vehicle and cycle next and previous checked boundaries
System.out.println(" !!CALLING CURRENTVEHICLE/NEXTVEHICLE/PREVIOUSVEHICLE!! \n");
showroom.setCurrentVehicle(vehicle1);
System.out.println(" Current Vehicle: \n" + showroom.getCurrentVehicle());
showroom.nextVehicle();
System.out.println("\n Current Vehicle after next vehicle \n" + showroom.getCurrentVehicle());
showroom.previousVehicle();
System.out.println("\n Current Vehicle after previous vehicle \n" + showroom.getCurrentVehicle());
showroom.previousVehicle();
System.out.println("\n Current Vehicle after previous vehicle (Should be unchanged) \n" + showroom.getCurrentVehicle());
showroom.setCurrentVehicle(vehicle3);
System.out.println("\n Current Vehicle after setting current vehicle to the "
+ "end of the list \n" + showroom.getCurrentVehicle());
System.out.println("\n Now to try and get the details of the next vehicle: ");
showroom.nextVehicle();
System.out.println("\n Current Vehicle after next vehicle (Should be unchanged) \n" + showroom.getCurrentVehicle());
System.out.println("\n And finally we will print all of the vehicles in the showroom: \n");
//print all of the vehicles in the showroom
showroom.printArray();
System.out.println(" !!CALLING GETAGEOFVEHICLE FOR VEHICLE1!! \n");
System.out.println(" Vehicle 1 is: " + vehicle1.getAgeOfVehicle() + " weeks old.");
System.out.println("\n\n\n");
System.out.println("Vehicles sold recently (in the last 2 weeks) are: \n" + showroom.getVehiclesSoldRecently());
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ViewModels/UserSearchResultsListViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ViewModels
{
public class UserSearchResultsListViewModel
{
public List<UserSearchResultsViewModel> Users { get; set; }
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Repositories/AccountRepository.cs
using AnimalCareSystem.ApplicationUI;
using AnimalCareSystem.Data;
using AnimalCareSystem.Models;
using AnimalCareSystem.ViewModels;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.Repositories
{
public class AccountRepository : IRepository
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private ApplicationDbContext _dbContext;
public AccountRepository(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ApplicationDbContext dbContext)
{
_userManager = userManager;
_signInManager = signInManager;
_dbContext = dbContext;
}
public async Task<object> Create(object obj)
{
KeyValuePair<string, object> requestData = (KeyValuePair<string, object>)obj;
switch (requestData.Key)
{
case "register":
RegisterViewModel registerViewModel = (RegisterViewModel)requestData.Value;
ApplicationUser newUser = await RegisterNewUser(registerViewModel);
return newUser;
default:
return null;
}
}
public Task<object> Delete(object obj)
{
throw new NotImplementedException();
}
public async Task<object> Get(object obj)
{
KeyValuePair<string, object> requestData = (KeyValuePair<string, object>)obj;
switch (requestData.Key)
{
case "login":
LoginViewModel loginViewModel = (LoginViewModel)requestData.Value;
SignInResult result = await Login(loginViewModel);
return result;
case "getEmailConfirmationToken":
ApplicationUser user = (ApplicationUser)requestData.Value;
string emailConfirmationToken = await GetEmailConfirmationToken(user);
return emailConfirmationToken;
case "getUserById":
string userId = (string)requestData.Value;
user = await GetUserById(userId);
return user;
default:
return null;
}
}
public async Task<object> Update(object obj)
{
KeyValuePair<string, object> requestData = (KeyValuePair<string, object>)obj;
switch (requestData.Key)
{
case "confirmEmail":
Dictionary<string, object> confirmEmailDictionary = (Dictionary<string, object>)requestData.Value;
ApplicationUser user = (ApplicationUser)confirmEmailDictionary["user"];
string confirmationCode = (string)confirmEmailDictionary["code"];
IdentityResult result = await ConfirmEmail(user, confirmationCode);
return result;
default:
return null;
}
}
public async Task<ApplicationUser> RegisterNewUser(RegisterViewModel registerViewModel)
{
ApplicationUser newUser = ConvertToUser(registerViewModel);
if (newUser != null)
{
IdentityResult registrationResult = (IdentityResult)await CommandFactory.CreateCommand(CommandFactory.REGISTER, newUser, _userManager, _signInManager).Execute();
if (registrationResult.Succeeded)
{
return newUser;
}
}
return null;
}
public async Task<SignInResult> Login(LoginViewModel loginViewModel)
{
SignInResult loginResult = (SignInResult)await CommandFactory.CreateCommand(CommandFactory.LOGIN, loginViewModel.Email, loginViewModel.Password, loginViewModel.RememberMe, _signInManager).Execute();
return loginResult;
}
public async Task<string> GetEmailConfirmationToken(ApplicationUser user)
{
string emailConfirmationToken = (string)await CommandFactory.CreateCommand(CommandFactory.GET_CONFIRMATION_EMAIL_TOKEN, user, _userManager).Execute();
return emailConfirmationToken;
}
public async Task<ApplicationUser> GetUserById(string userId)
{
ApplicationUser user = (ApplicationUser)await CommandFactory.CreateCommand(CommandFactory.GET_USER_BY_ID, userId, _userManager, _dbContext).Execute();
return user;
}
public async Task<IdentityResult> ConfirmEmail(ApplicationUser user, string confirmationCode)
{
IdentityResult result = (IdentityResult)await CommandFactory.CreateCommand(CommandFactory.CONFIRM_EMAIL, user, confirmationCode, _userManager).Execute();
return result;
}
public ApplicationUser ConvertToUser(RegisterViewModel registerViewModel)
{
ApplicationUser newUser = new ApplicationUser();
newUser.PhoneNumber = registerViewModel.PhoneNumber;
newUser.Forename = registerViewModel.Forename;
newUser.Surname = registerViewModel.Surname;
newUser.AddressLine1 = registerViewModel.AddressLine1;
newUser.AddressLine2 = registerViewModel.AddressLine2;
newUser.City = registerViewModel.City;
newUser.County = registerViewModel.County;
newUser.Postcode = registerViewModel.Postcode;
newUser.DateOfBirth = registerViewModel.DateOfBirth;
newUser.Email = registerViewModel.Email;
newUser.UserName = registerViewModel.Email;
newUser.PasswordHash = registerViewModel.Password;
return newUser;
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/DataParallelismProj/DTO/Supplier.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataParallelismProj.DTO
{
class Supplier
{
public String SupplierName { get; set; }
public String SupplierType { get; set; }
public Supplier()
: this("", "")
{
}
public Supplier(String supplierName, String supplierType)
{
this.SupplierName = supplierName;
this.SupplierType = supplierType;
}
}
}
<file_sep>/CNA/SimpleClientServer/SimpleClientCS/SimpleClient.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace SimpleClient
{
class NotConnectedException : Exception
{
public NotConnectedException() : base("TcpClient not connected.")
{}
public NotConnectedException(string message) : base(message)
{}
}
class SimpleClient
{
private Thread thread { get; set; }
private TcpClient _tcpClient;
private NetworkStream _stream;
private StreamWriter _writer;
private StreamReader _reader;
public SimpleClient()
{
_tcpClient = new TcpClient();
}
public bool Connect(string hostname, int port)
{
try
{
_tcpClient.Connect(hostname, port);
_stream = _tcpClient.GetStream();
_writer = new StreamWriter(_stream, Encoding.UTF8);
_reader = new StreamReader(_stream, Encoding.UTF8);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
return false;
}
return true;
}
public void Run()
{
if (!_tcpClient.Connected) throw new NotConnectedException();
thread = new Thread(new ThreadStart(ProcessServerResponse));
thread.Start();
try
{
string userInput;
Console.Write("Enter the data to be sent: ");
while ((userInput = Console.ReadLine()) != null)
{
_writer.WriteLine(userInput);
_writer.Flush();
if (userInput.Equals("9"))
break;
Console.Write("Enter the data to be sent: ");
}
}
catch (Exception e)
{
Console.WriteLine("Unexpected Error: " + e.Message);
}
finally
{
_tcpClient.Close();
}
Console.Read();
}
private void ProcessServerResponse()
{
while (true)
{
Console.Write("Server says: ");
Console.WriteLine(_reader.ReadLine());
Console.WriteLine();
}
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ViewModels/UserProfileEditViewModel.cs
using AnimalCareSystem.Models;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ViewModels
{
public class UserProfileEditViewModel
{
public string UserId { get; set; }
public string Description { get; set; }
public List<ServiceRateViewModel> ServiceRates { get; set; }
public IFormFile ProfilePhoto { get; set; }
public bool Carer { get; set; }
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ViewModels/FileUploadViewModel.cs
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels
{
public class FileUploadViewModel
{
[Required(ErrorMessage = "A DVLA file is required")]
public IFormFile DVLADataFile { get; set; }
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Models/VehicleType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Models
{
public class VehicleType
{
public long Id { get; set; }
public String Size { get; set; }
public VehicleType()
{
}
public VehicleType(long id, string size)
{
this.Id = id;
Size = size;
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Models/Job.cs
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.Models
{
public class Job
{
[Required]
public int Id { get; set; }
[Required]
[DataType(DataType.Text)]
public string Title { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime EndDate { get; set; }
[Required]
public JobStatus JobStatus { get; set; }
[Required]
public ServiceType ServiceType { get; set; }
[Required]
public ApplicationUser JobOwner { get; set; }
public ApplicationUser Carer { get; set; }
public Job()
{
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/GetTotalCostInWeekForStoreCommand.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using WPFDataParallelismProj.DTO;
using WPFDataParallelismProj.Handler;
namespace WPFDataParallelismProj.CommandsFactory
{
class GetTotalCostInWeekForStoreCommand : ICommand
{
private HashSet<Order> orders;
private Date date;
private Store store;
private OrderHandler orderHandler;
public GetTotalCostInWeekForStoreCommand(HashSet<Order> orders, Date date, Store store)
{
this.orders = orders;
this.date = date;
this.store = store;
orderHandler = new OrderHandler();
}
public Task<object> Execute()
{
return orderHandler.GetTotalCostInWeekForStore(orders, date, store);
}
}
}<file_sep>/OOAE/T2/T2-03/GuiObserverPatternProj/src/Observer/Observer.java
package Observer;
import Subject.Subject;
/**
*
* @author <NAME>
*/
public interface Observer
{
public void update(Subject subject);
}
<file_sep>/ESA/Flights Management/src/command/GetAllPassengersRisks_ByFlight.java
package command;
import model.PassengerRisk;
import view.AllPassengersRiskView;
/**
*
* @author Krzychu-x
*/
public class GetAllPassengersRisks_ByFlight implements Command
{
PassengerRisk receiver;
public GetAllPassengersRisks_ByFlight(PassengerRisk receiver)
{
this.receiver = receiver;
}
@Override
public Object execute()
{
return new AllPassengersRiskView(receiver.findAllPassengersRisks(-1)).print();
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/NullObjectCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFDataParallelismProj.CommandsFactory
{
class NullObjectCommand : ICommand
{
public async Task<object> Execute()
{
return this;
}
}
}
<file_sep>/ESA/Flights Management/test/model/PassengerHandlerTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import database.Passenger;
import java.sql.Date;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Greg
*/
public class PassengerHandlerTest {
public PassengerHandlerTest() {
}
@Before
public void setUp() {
}
/**
* Test of addPassenger method, of class PassengerHandler.
*/
@Test
public void testAddPassenger() {
System.out.println("addPassenger");
Passenger p = new Passenger();
p.setForename("DAVID");
p.setSurname("DAVIDSON");
p.setDOB(new Date(2012-02-02));
p.setNationality("ENGLISH");
PassengerHandler instance = new PassengerHandler();
assertTrue(instance.addPassenger(p));
}
/**
* Test of findAllPassengers method, of class PassengerHandler.
*/
@Test
public void testFindAllPassengers() {
System.out.println("findAllPassengers");
PassengerHandler instance = new PassengerHandler();
ArrayList<Passenger> expResult = new ArrayList();
for(int i = 1; i < 24; i++){
Passenger p = new Passenger();
p.setPassengerID(i);
p.setForename("Rob");
p.setSurname("Smith");
p.setDOB(new Date(2018-02-20));
p.setNationality("USA");
p.setPassportNumber(i);
expResult.add(p);
}
ArrayList<Passenger> result = instance.findAllPassengers();
assertEquals(expResult, result);
}
/**
* Test of findSpecificPassenger method, of class PassengerHandler.
*/
@Test
public void testFindSpecificPassenger() {
System.out.println("findSpecificPassenger");
Passenger p = new Passenger();
PassengerHandler instance = new PassengerHandler();
ArrayList<Passenger> expResult = new ArrayList();
p.setPassengerID(3);
expResult.add(p);
ArrayList<Passenger> result = instance.findSpecificPassenger(p);
assertEquals(expResult, result);
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/DataParallelismProj/DTO/Date.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataParallelismProj.DTO
{
class Date
{
private int _week;
public int Week
{
get
{
return _week;
}
set
{
if (!(value < 0 || value > 52))
{
_week = value;
}
}
}
private int _year;
public int Year
{
get
{
return _year;
}
set
{
if(!(value < 1970))
{
_year = value;
}
}
}
override
public String ToString()
{
return "Week: " + Week + " Year: " + Year;
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Models/ApplicationUser.cs
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.Models
{
public class ApplicationUser : IdentityUser
{
/*IdentityUser has properties that will be used, this is why this class doesn't define them.
* Id
* Email
* NormalizedEmail
* EmailConfirmed
* PasswordHash
* PhoneNumber
*/
[PersonalData]
[Required]
[DataType(DataType.Text)]
public string Forename { get; set; }
[PersonalData]
[Required]
[DataType(DataType.Text)]
public string Surname { get; set; }
[PersonalData]
[Required]
public DateTime DateOfBirth { get; set; }
[PersonalData]
[Required]
[DataType(DataType.Text)]
public string AddressLine1 { get; set; }
[PersonalData]
[DataType(DataType.Text)]
public string AddressLine2 { get; set; }
[PersonalData]
[Required]
[DataType(DataType.Text)]
public string City { get; set; }
[PersonalData]
[Required]
[DataType(DataType.Text)]
public string County { get; set; }
[PersonalData]
[Required]
[DataType(DataType.PostalCode)]
public string Postcode { get; set; }
[DataType(DataType.Text)]
public string PhotoFolderSource { get; set; }
[DataType(DataType.Text)]
public string IdentificationProofFileSource { get; set; }
public bool IdentificationVerified { get; set; }
[DataType(DataType.Text)]
public string AddressProofFileSource { get; set; }
public bool AddressVerified { get; set; }
public string DBSCheckFileSource { get; set; }
public bool DBSChecked { get; set; }
public bool Carer { get; set; }
[DataType(DataType.Text)]
public string BoardingLicenseProofFileSource { get; set; }
public bool BoardingLicenseVerified { get; set; }
public bool Banned { get; set; }
public bool Admin { get; set; }
public string Description { get; set; }
public List<ServiceRate> ServiceRates { get; set; }
[InverseProperty("JobOwner")]
public List<Job> JobsOwned { get; set; }
[InverseProperty("Carer")]
public List<Job> JobsAsCarer { get; set; }
[InverseProperty("ReceivingUser")]
public List<Message> ReceivedMessages { get; set; }
[InverseProperty("SendingUser")]
public List<Message> SentMessages { get; set; }
[InverseProperty("ReviewingUser")]
public List<UserReview> WrittenReviews { get; set; }
[InverseProperty("ReceivingUser")]
public List<UserReview> ReceivedReviews { get; set; }
public List<UserReport> ReportsAgainstUser { get; set; }
public ApplicationUser()
{
this.Carer = false;
this.AddressVerified = false;
this.IdentificationVerified = false;
this.BoardingLicenseVerified = false;
this.Banned = false;
this.Admin = false;
this.Description = "";
}
public ApplicationUser(string Id, string UserName, string NormalizedUserName, string Email, string NormalizedEmail, bool EmailConfirmed, string PasswordHash, string PhoneNumber, string forename, string surname, string addressLine1, string addressLine2, string postcode, DateTime dateOfBirth)
{
this.Id = Id;
this.UserName = UserName;
this.NormalizedUserName = NormalizedUserName;
this.Email = Email;
this.NormalizedEmail = NormalizedEmail;
this.EmailConfirmed = EmailConfirmed;
this.PasswordHash = <PASSWORD>;
this.PhoneNumber = PhoneNumber;
Forename = forename;
Surname = surname;
AddressLine1 = addressLine1;
AddressLine2 = addressLine2;
Postcode = postcode;
DateOfBirth = dateOfBirth;
}
}
}
<file_sep>/WMAD/WMAD_assignment_2/app/src/main/java/com/example/rhysj/wmad_assignment_2/ListAdapter/ShowingListAdapter.java
package com.example.rhysj.wmad_assignment_2.ListAdapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.rhysj.wmad_assignment_2.R;
import com.example.rhysj.wmad_assignment_2.DTO.ShowingDTO;
import java.util.ArrayList;
/**
* Created by <NAME> on 04/04/2018.
*/
public class ShowingListAdapter extends BaseAdapter
{
private ArrayList<ShowingDTO> showings;
private Context context;
public ShowingListAdapter(ArrayList<ShowingDTO> showings, Context context)
{
this.showings = showings;
this.context = context;
}
@Override
public int getCount()
{
return showings.size();
}
@Override
public Object getItem(int position)
{
return showings.get(position);
}
@Override
public long getItemId(int position)
{
return showings.indexOf(getItem(position));
}
private class ViewHolder
{
TextView film_info;
TextView film_description;
TextView showing_time;
}
@Override
public View getView(int position, View view, ViewGroup parent)
{
ViewHolder holder = null;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//REMOVED BECAUSE OF ISSUES WITH THE FINAL LIST ITEM BEING WRONG AND PERFORMANCE FOR MY APP WILL NOT BE IMPACTED GREATLY.
//if (view == null)
//{
ShowingDTO showing = showings.get(position);
view = inflater.inflate(R.layout.showing_list_item, null);
holder = new ViewHolder();
holder.film_info = view.findViewById(R.id.showing_list_item_film_info);
holder.film_description = view.findViewById(R.id.showing_list_item_film_description);
holder.showing_time = view.findViewById(R.id.showing_list_item_showing_time);
holder.film_info.setText(showing.getFilm().getTitle() + " Age Rating: " + showing.getFilm().getAgeRating());
holder.film_description.setText(showing.getFilm().getDescription());
holder.showing_time.setText(showing.getTime());
//}
//else
//{
//holder = (ViewHolder) view.getTag();
//}
return view;
}
}
<file_sep>/OOAE/T2/T2-03/AuctionTemplatePatternProj/src/AuctionItem/Painting.java
package AuctionItem;
/**
* Determines VAT and Commission rates for Painting and calculates the cost a
buyer will pay, and the amount a seller will receive.
*
* @author <NAME>
*/
public class Painting extends AuctionItem
{
private final double VAT = 0.0;
private final double commission = 0.4;
/**
* Constructs Painting Object and sets the item description.
*
* @param description
*/
public Painting(String description)
{
super.description = description;
}
/**
* Calculates the cost a buyer will pay for a painting after VAT.
*
* @param hammerPrice
* @return
*/
@Override
public double calculateCostBuyerPaid(double hammerPrice)
{
return (hammerPrice * VAT);
}
/**
* Calculates the amount a seller will receive for a Painting after
* commission.
*
* @param hammerPrice
* @return
*/
@Override
public double calculateAmountSellerReceived(double hammerPrice)
{
return (hammerPrice * commission);
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/CollectBookingCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class CollectBookingCommand : ICommand
{
private BookingHandler BookingHandler;
private long BookingId;
public CollectBookingCommand(long bookingId, ApplicationDbContext dbContext)
{
BookingHandler = new BookingHandler(dbContext);
BookingId = bookingId;
}
public async Task<object> Execute()
{
return await BookingHandler.CollectBooking(BookingId);
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Migrations/20200824192000_AddDescriptionToUsers.cs
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace AnimalCareSystem.Migrations
{
public partial class AddDescriptionToUsers : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "Job");
migrationBuilder.DropTable(
name: "Message");
migrationBuilder.DropTable(
name: "ServiceRate");
migrationBuilder.DropTable(
name: "UserReport");
migrationBuilder.DropTable(
name: "UserReview");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "JobStatus");
migrationBuilder.DropTable(
name: "ServiceType");
migrationBuilder.DropTable(
name: "AspNetUsers");
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
Discriminator = table.Column<string>(nullable: false),
Forename = table.Column<string>(nullable: true),
Surname = table.Column<string>(nullable: true),
DateOfBirth = table.Column<DateTime>(nullable: true),
AddressLine1 = table.Column<string>(nullable: true),
AddressLine2 = table.Column<string>(nullable: true),
City = table.Column<string>(nullable: true),
County = table.Column<string>(nullable: true),
Postcode = table.Column<string>(nullable: true),
PhotoFolderSource = table.Column<string>(nullable: true),
IdentificationProofFileSource = table.Column<string>(nullable: true),
IdentificationVerified = table.Column<bool>(nullable: true),
AddressProofFileSource = table.Column<string>(nullable: true),
AddressVerified = table.Column<bool>(nullable: true),
Carer = table.Column<bool>(nullable: true),
BoardingLicenseProofFileSource = table.Column<string>(nullable: true),
BoardingLicenseVerified = table.Column<bool>(nullable: true),
Banned = table.Column<bool>(nullable: true),
Admin = table.Column<bool>(nullable: true),
Description = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "JobStatus",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_JobStatus", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ServiceType",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ServiceType", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
RoleId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
ProviderKey = table.Column<string>(maxLength: 128, nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
Name = table.Column<string>(maxLength: 128, nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Message",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Content = table.Column<string>(nullable: false),
DateTimeSent = table.Column<DateTime>(nullable: false),
ReceivingUserId = table.Column<int>(nullable: false),
ReceivingUserId1 = table.Column<string>(nullable: true),
SendingUserId = table.Column<int>(nullable: false),
SendingUserId1 = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Message", x => x.Id);
table.ForeignKey(
name: "FK_Message_AspNetUsers_ReceivingUserId1",
column: x => x.ReceivingUserId1,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Message_AspNetUsers_SendingUserId1",
column: x => x.SendingUserId1,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "UserReport",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<string>(nullable: false),
Description = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserReport", x => x.Id);
table.ForeignKey(
name: "FK_UserReport_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "UserReview",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ReviewingUserId = table.Column<int>(nullable: false),
ReviewingUserId1 = table.Column<string>(nullable: true),
ReceivingUserId = table.Column<int>(nullable: false),
ReceivingUserId1 = table.Column<string>(nullable: true),
Description = table.Column<string>(nullable: true),
Date = table.Column<DateTime>(nullable: false),
Recommended = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserReview", x => x.Id);
table.ForeignKey(
name: "FK_UserReview_AspNetUsers_ReceivingUserId1",
column: x => x.ReceivingUserId1,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_UserReview_AspNetUsers_ReviewingUserId1",
column: x => x.ReviewingUserId1,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Job",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Title = table.Column<string>(nullable: false),
Description = table.Column<string>(nullable: false),
StartDate = table.Column<DateTime>(nullable: false),
EndDate = table.Column<DateTime>(nullable: false),
JobStatusId = table.Column<int>(nullable: false),
ServiceTypeId = table.Column<int>(nullable: false),
JobOwnerId = table.Column<string>(nullable: false),
CarerId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Job", x => x.Id);
table.ForeignKey(
name: "FK_Job_AspNetUsers_CarerId",
column: x => x.CarerId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Job_AspNetUsers_JobOwnerId",
column: x => x.JobOwnerId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Job_JobStatus_JobStatusId",
column: x => x.JobStatusId,
principalTable: "JobStatus",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Job_ServiceType_ServiceTypeId",
column: x => x.ServiceTypeId,
principalTable: "ServiceType",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ServiceRate",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ServiceTypeId = table.Column<int>(nullable: false),
UserId = table.Column<string>(nullable: false),
Rate = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ServiceRate", x => x.Id);
table.ForeignKey(
name: "FK_ServiceRate_ServiceType_ServiceTypeId",
column: x => x.ServiceTypeId,
principalTable: "ServiceType",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ServiceRate_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUsers_Id",
table: "AspNetUsers",
column: "Id",
unique: true);
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_Job_CarerId",
table: "Job",
column: "CarerId");
migrationBuilder.CreateIndex(
name: "IX_Job_Id",
table: "Job",
column: "Id",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Job_JobOwnerId",
table: "Job",
column: "JobOwnerId");
migrationBuilder.CreateIndex(
name: "IX_Job_JobStatusId",
table: "Job",
column: "JobStatusId");
migrationBuilder.CreateIndex(
name: "IX_Job_ServiceTypeId",
table: "Job",
column: "ServiceTypeId");
migrationBuilder.CreateIndex(
name: "IX_JobStatus_Id",
table: "JobStatus",
column: "Id",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Message_Id",
table: "Message",
column: "Id",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Message_ReceivingUserId1",
table: "Message",
column: "ReceivingUserId1");
migrationBuilder.CreateIndex(
name: "IX_Message_SendingUserId1",
table: "Message",
column: "SendingUserId1");
migrationBuilder.CreateIndex(
name: "IX_ServiceRate_Id",
table: "ServiceRate",
column: "Id",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_ServiceRate_ServiceTypeId",
table: "ServiceRate",
column: "ServiceTypeId");
migrationBuilder.CreateIndex(
name: "IX_ServiceRate_UserId",
table: "ServiceRate",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_ServiceType_Id",
table: "ServiceType",
column: "Id",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_UserReport_Id",
table: "UserReport",
column: "Id",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_UserReport_UserId",
table: "UserReport",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_UserReview_Id",
table: "UserReview",
column: "Id",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_UserReview_ReceivingUserId1",
table: "UserReview",
column: "ReceivingUserId1");
migrationBuilder.CreateIndex(
name: "IX_UserReview_ReviewingUserId1",
table: "UserReview",
column: "ReviewingUserId1");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "Job");
migrationBuilder.DropTable(
name: "Message");
migrationBuilder.DropTable(
name: "ServiceRate");
migrationBuilder.DropTable(
name: "UserReport");
migrationBuilder.DropTable(
name: "UserReview");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "JobStatus");
migrationBuilder.DropTable(
name: "ServiceType");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/entity/Parcel.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Rhys
*/
@Entity
@Table(name = "PARCEL")
@XmlRootElement
@NamedQueries(
{
@NamedQuery(name = "Parcel.findAll", query = "SELECT p FROM Parcel p"),
@NamedQuery(name = "Parcel.findByParcelId", query = "SELECT p FROM Parcel p WHERE p.parcelId = :parcelId"),
@NamedQuery(name = "Parcel.findByRecipientName", query = "SELECT p FROM Parcel p WHERE p.recipientName = :recipientName"),
@NamedQuery(name = "Parcel.findByAddressLine1", query = "SELECT p FROM Parcel p WHERE p.addressLine1 = :addressLine1"),
@NamedQuery(name = "Parcel.findByAddressLine2", query = "SELECT p FROM Parcel p WHERE p.addressLine2 = :addressLine2"),
@NamedQuery(name = "Parcel.findByPostcode", query = "SELECT p FROM Parcel p WHERE p.postcode = :postcode"),
@NamedQuery(name = "Parcel.findByCity", query = "SELECT p FROM Parcel p WHERE p.city = :city"),
@NamedQuery(name = "Parcel.findByDelivered", query = "SELECT p FROM Parcel p WHERE p.delivered = :delivered"),
@NamedQuery(name = "Parcel.getDeliveriesForUser", query = "SELECT p FROM Parcel p WHERE p.recipientName = :recipientName AND p.addressLine1 = :addressLine1 AND p.postcode = :postcode AND p.city = :city")
})
public class Parcel implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "PARCEL_ID")
private Integer parcelId;
@Size(max = 255)
@Column(name = "RECIPIENT_NAME")
private String recipientName;
@Size(max = 255)
@Column(name = "ADDRESS_LINE_1")
private String addressLine1;
@Size(max = 255)
@Column(name = "ADDRESS_LINE_2")
private String addressLine2;
@Size(max = 255)
@Column(name = "POSTCODE")
private String postcode;
@Size(max = 255)
@Column(name = "CITY")
private String city;
@Column(name = "DELIVERED")
private Boolean delivered;
@OneToOne(mappedBy = "parcelId")
private Delivery delivery;
public Parcel()
{
}
public Parcel(Integer parcelId)
{
this.parcelId = parcelId;
}
public Integer getParcelId()
{
return parcelId;
}
public void setParcelId(Integer parcelId)
{
this.parcelId = parcelId;
}
public String getRecipientName()
{
return recipientName;
}
public void setRecipientName(String recipientName)
{
this.recipientName = recipientName;
}
public String getAddressLine1()
{
return addressLine1;
}
public void setAddressLine1(String addressLine1)
{
this.addressLine1 = addressLine1;
}
public String getAddressLine2()
{
return addressLine2;
}
public void setAddressLine2(String addressLine2)
{
this.addressLine2 = addressLine2;
}
public String getPostcode()
{
return postcode;
}
public void setPostcode(String postcode)
{
this.postcode = postcode;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public Boolean getDelivered()
{
return delivered;
}
public void setDelivered(Boolean delivered)
{
this.delivered = delivered;
}
@XmlTransient
public Delivery getDelivery()
{
return delivery;
}
public void setDelivery(Delivery delivery)
{
this.delivery = delivery;
}
@Override
public int hashCode()
{
int hash = 0;
hash += (parcelId != null ? parcelId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object)
{
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Parcel))
{
return false;
}
Parcel other = (Parcel) object;
if ((this.parcelId == null && other.parcelId != null) || (this.parcelId != null && !this.parcelId.equals(other.parcelId)))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "entity.Parcel[ parcelId=" + parcelId + " ]";
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ViewModels/LoginViewModel.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels
{
public class LoginViewModel
{
[Required, EmailAddress]
public String Email { get; set; }
[Required]
[DataType(DataType.Password)]
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$",
ErrorMessage = "Incorrect Password.")] //Regex taken from here: https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a.
public String Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
}
<file_sep>/WMAD/CinemaBookingSystem/test/dto/BookingDTOTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import java.util.Date;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author <NAME>
*/
public class BookingDTOTest
{
private UserDTO customer;
private ShowingDTO showing;
private BookingDTO booking;
private FilmDTO film;
private ScreenDTO screen;
private CinemaDTO cinema;
private Date time;
public BookingDTOTest()
{
Date DOB = new Date(1994 - 1900, 6, 24);
time = new Date(2017 - 1900, 6, 24, 15, 30);
customer = new UserDTO(0, "John", "Smith", DOB, "20 D<NAME>", "Staffordshire", "ST17 2ES", "Johnno101", "Pass", true);
cinema = new CinemaDTO(0, "cineworld");
film = new FilmDTO(0, "title", 18, 120, "description");
screen = new ScreenDTO(0, cinema, "screenName");
showing = new ShowingDTO(0, film, screen, time, 20);
booking = new BookingDTO(0, customer, showing, 3);
}
@BeforeClass
public static void setUpClass()
{
}
@AfterClass
public static void tearDownClass()
{
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
/**
* Test of getBookingID method, of class BookingDTO.
*/
@Test
public void testGetBookingID()
{
System.out.println("getBookingID");
BookingDTO instance = booking;
int expResult = 0;
int result = instance.getBookingID();
assertEquals(expResult, result);
}
/**
* Test of getCustomer method, of class BookingDTO.
*/
@Test
public void testGetCustomer()
{
System.out.println("getCustomer");
BookingDTO instance = booking;
UserDTO expResult = customer;
UserDTO result = instance.getCustomer();
assertEquals(expResult, result);
}
/**
* Test of getShowing method, of class BookingDTO.
*/
@Test
public void testGetShowing()
{
System.out.println("getShowing");
BookingDTO instance = booking;
ShowingDTO expResult = showing;
ShowingDTO result = instance.getShowing();
assertEquals(expResult, result);
}
/**
* Test of getQuantity method, of class BookingDTO.
*/
@Test
public void testGetQuantity()
{
System.out.println("getQuantity");
BookingDTO instance = booking;
int expResult = 3;
int result = instance.getQuantity();
assertEquals(expResult, result);
}
}
<file_sep>/OOAE/T1/T1-05/JUnitProj/test/junitproj/DVDTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package junitproj;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Rhysj
*/
public class DVDTest
{
DVD film;
Person p1;
public DVDTest()
{
p1 = new Person("Christian", "Bale");
film = new DVD("The Dark Knight", p1, 228);
}
@BeforeClass
public static void setUpClass() throws Exception
{
}
@AfterClass
public static void tearDownClass() throws Exception
{
}
@Before
public void setUp() throws Exception
{
}
@After
public void tearDown() throws Exception
{
}
/**
* Test of getTitle method, of class DVD.
*/
@Test
public void testGetTitle()
{
System.out.println("getTitle");
DVD instance = film;
String expResult = "The Dark Knight";
String result = instance.getTitle();
assertEquals(expResult, result);
}
/**
* Test of setTitle method, of class DVD.
*/
@Test
public void testSetTitle()
{
System.out.println("setTitle");
String title = "The Dark Knight";
DVD instance = film;
instance.setTitle(title);
}
/**
* Test of getLeadActor method, of class DVD.
*/
@Test
public void testGetLeadActor()
{
System.out.println("getLeadActor");
DVD instance = film;
Person expResult = p1;
Person result = instance.getLeadActor();
assertEquals(expResult, result);
}
/**
* Test of setLeadActor method, of class DVD.
*/
@Test
public void testSetLeadActor()
{
System.out.println("setLeadActor");
Person leadActor = p1;
DVD instance = film;
instance.setLeadActor(leadActor);
}
/**
* Test of getNoOfStars method, of class DVD.
*/
@Test
public void testGetNoOfStars()
{
System.out.println("getNoOfStars");
DVD instance = film;
int expResult = 228;
int result = instance.getNoOfStars();
assertEquals(expResult, result);
}
/**
* Test of setNoOfStars method, of class DVD.
*/
@Test
public void testSetNoOfStars()
{
System.out.println("setNoOfStars");
int noOfStars = 228;
DVD instance = film;
instance.setNoOfStars(noOfStars);
}
/**
* Test of toString method, of class DVD.
*/
@Test
public void testToString()
{
System.out.println("toString");
DVD instance = film;
String expResult = "Title: The Dark Knight"
+ "\nLead Actor: <NAME>"
+ "\nNumber of stars: 228";
String result = instance.toString();
assertEquals(expResult, result);
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/database/DeliveryGateway.java
package database;
import dto.DeliveryDTO;
import entity.Delivery;
import entity.DeliveryStatus;
import entity.Parcel;
import entity.Users;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
/**
*
* @author Rhys
*/
@Stateless
public class DeliveryGateway implements DeliveryGatewayLocal
{
@PersistenceContext
EntityManager em;
@EJB
DTOConversionGatewayLocal DTOConversionGateway;
@Override
public DeliveryDTO searchForDelivery(int deliveryId)
{
try
{
Delivery delivery = (Delivery) em.createNamedQuery("Delivery.findByDeliveryId").setParameter("deliveryId", deliveryId).getSingleResult();
DeliveryDTO deliveryDTO = DTOConversionGateway.createDeliveryDTO(delivery);
return deliveryDTO;
}
catch (NoResultException e)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Delivery not found"));
return null;
}
}
@Override
public boolean cancelDelivery(int deliveryId)
{
try
{
Delivery delivery = (Delivery) em.createNamedQuery("Delivery.findByDeliveryId").setParameter("deliveryId", deliveryId).getSingleResult();
DeliveryStatus cancellationRequestedStatus = (DeliveryStatus) em.createNamedQuery("DeliveryStatus.findByName").setParameter("name", "Scheduled For Cancellation").getSingleResult();
delivery.setDeliveryStatusId(cancellationRequestedStatus);
em.persist(delivery);
return true;
}
catch (Exception e)
{
return false;
}
}
@Override
public boolean bookCollection(int deliveryId, Date collectionDate)
{
try
{
Delivery delivery = (Delivery) em.createNamedQuery("Delivery.findByDeliveryId").setParameter("deliveryId", deliveryId).getSingleResult();
DeliveryStatus awaitingCollectionStatus = (DeliveryStatus) em.createNamedQuery("DeliveryStatus.findByName").setParameter("name", "Awaiting Collection").getSingleResult();
delivery.setDeliveryStatusId(awaitingCollectionStatus);
delivery.setDeliveryDate(collectionDate);
em.persist(delivery);
return true;
}
catch (Exception e)
{
return false;
}
}
@Override
public boolean rescheduleDelivery(int deliveryId, Date newDeliveryDate)
{
try
{
Delivery delivery = (Delivery) em.createNamedQuery("Delivery.findByDeliveryId").setParameter("deliveryId", deliveryId).getSingleResult();
DeliveryStatus rescheduledForDelivery = (DeliveryStatus) em.createNamedQuery("DeliveryStatus.findByName").setParameter("name", "Re-Scheduled For Delivery").getSingleResult();
delivery.setDeliveryDate(newDeliveryDate);
delivery.setDeliveryStatusId(rescheduledForDelivery);
em.persist(delivery);
return true;
}
catch (Exception e)
{
return false;
}
}
@Override
public ArrayList<DeliveryDTO> getRecipientDeliveries(int userId)
{
try
{
Users recipient = (Users) em.createNamedQuery("Users.findByUserId").setParameter("userId", userId).getSingleResult();
String recipientName = recipient.getForename() + " " + recipient.getSurname();
List<Parcel> parcels = (List<Parcel>) em.createNamedQuery("Parcel.getDeliveriesForUser")
.setParameter("recipientName", recipientName)
.setParameter("addressLine1", recipient.getAddressLine1())
.setParameter("postcode", recipient.getPostcode())
.setParameter("city", recipient.getCity())
.getResultList();
ArrayList<DeliveryDTO> deliveryDTOCollection = new ArrayList<DeliveryDTO>();
for (int i = 0; i < parcels.size(); i++)
{
Delivery delivery = (Delivery) em.createNamedQuery("Delivery.findByDeliveryId").setParameter("deliveryId", parcels.get(i).getDelivery().getDeliveryId()).getSingleResult();
deliveryDTOCollection.add(DTOConversionGateway.createDeliveryDTO(delivery));
}
return deliveryDTOCollection;
}
catch (Exception e)
{
return null;
}
}
@Override
public ArrayList<DeliveryDTO> getDeliveriesForRoute(int routeId)
{
try
{
List<Delivery> deliveryList = (List<Delivery>) em.createNamedQuery("Delivery.getDeliveriesForRoute")
.setParameter("routeId", routeId)
.setParameter("deliveryStatus", "At Depot")
.getResultList();
ArrayList<DeliveryDTO> deliveries = new ArrayList<DeliveryDTO>();
for (Delivery delivery : deliveryList)
{
deliveries.add(DTOConversionGateway.createDeliveryDTO(delivery));
}
return deliveries;
}
catch (Exception e)
{
return null;
}
}
@Override
public boolean setRouteDeliveriesToOutForDelivery(int routeId)
{
try
{
List<Delivery> routeDeliveries = (List<Delivery>) em.createNamedQuery("Delivery.getDeliveriesForRoute")
.setParameter("routeId", routeId)
.setParameter("deliveryStatus", "At Depot")
.getResultList();
DeliveryStatus outForDeliveryStatus = (DeliveryStatus) em.createNamedQuery("DeliveryStatus.findByName")
.setParameter("name", "Out For Delivery")
.getSingleResult();
for (Delivery routeDelivery : routeDeliveries)
{
routeDelivery.setDeliveryStatusId(outForDeliveryStatus);
em.persist(routeDelivery);
}
return true;
}
catch (Exception e)
{
return false;
}
}
@Override
public ArrayList<DeliveryDTO> getDriverDeliveries(int routeId)
{
try
{
List<Delivery> deliveryList = (List<Delivery>) em.createNamedQuery("Delivery.getDriverDeliveries")
.setParameter("routeId", routeId)
.getResultList();
ArrayList<DeliveryDTO> deliveries = new ArrayList<DeliveryDTO>();
deliveryList.forEach((delivery) ->
{
if(!delivery.getDeliveryStatusId().getName().equals("Dispatched")
|| !delivery.getDeliveryStatusId().getName().equals("At Depot")
|| !delivery.getDeliveryStatusId().getName().equals("Awaiting Collection"))
{
deliveries.add(DTOConversionGateway.createDeliveryDTO(delivery));
}
});
return deliveries;
}
catch (Exception e)
{
return null;
}
}
@Override
public boolean deliverDelivery(int deliveryId)
{
try
{
Delivery delivery = (Delivery) em.createNamedQuery("Delivery.findByDeliveryId").setParameter("deliveryId", deliveryId).getSingleResult();
DeliveryStatus deliveredStatus = (DeliveryStatus) em.createNamedQuery("DeliveryStatus.findByName").setParameter("name", "Delivered").getSingleResult();
delivery.setDeliveryStatusId(deliveredStatus);
em.persist(delivery);
return true;
}
catch(Exception e)
{
return false;
}
}
@Override
public boolean failDelivery(int deliveryId)
{
try
{
Delivery delivery = (Delivery) em.createNamedQuery("Delivery.findByDeliveryId").setParameter("deliveryId", deliveryId).getSingleResult();
DeliveryStatus deliveryFailedStatus = (DeliveryStatus) em.createNamedQuery("DeliveryStatus.findByName").setParameter("name", "Delivery Failed").getSingleResult();
delivery.setDeliveryStatusId(deliveryFailedStatus);
em.persist(delivery);
return true;
}
catch(Exception e)
{
return false;
}
}
@Override
public boolean changeDeliveryStatus(int deliveryId, int deliveryStatusId)
{
try
{
Delivery delivery = (Delivery) em.createNamedQuery("Delivery.findByDeliveryId").setParameter("deliveryId", deliveryId).getSingleResult();
DeliveryStatus newStatus = (DeliveryStatus) em.createNamedQuery("DeliveryStatus.findByDeliveryStatusId").setParameter("deliveryStatusId", deliveryStatusId).getSingleResult();
delivery.setDeliveryStatusId(newStatus);
em.persist(delivery);
return true;
}
catch(Exception e)
{
return false;
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/Handler/FileHandler.cs
using WPFDataParallelismProj.DTO;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFDataParallelismProj.Handler
{
class FileHandler
{
private string folderPath = "StoreData";
private string storeCodesFile = "StoreCodes.csv";
private string storeDataFolder = "StoreData";
private static FileHandler instance;
private FileHandler()
{
}
public static FileHandler GetInstance()
{
if (instance == null)
{
instance = new FileHandler();
}
return instance;
}
public async Task<bool> SetFolderPath(string selectedFolderPath)
{
await Task.Run(() =>
{
folderPath = selectedFolderPath;
});
return true;
}
public async Task<HashSet<Order>> LoadOrders(Action<int, int> callback)
{
ConcurrentDictionary<string, Store> stores = await LoadStores(callback);
ConcurrentDictionary<string, Date> dates = new ConcurrentDictionary<string, Date>();
HashSet<Order> orders = new HashSet<Order>();
string[] fileNames = Directory.GetFiles(folderPath + @"\" + storeDataFolder);
int orderFilesRead = 0;
await Task.Run(() =>
{
//foreach(string filePath in fileNames)
Parallel.ForEach(fileNames, filePath =>
{
//Full file name with the extension (#####.csv)
string fileNameExt = Path.GetFileName(filePath);
//File name without extension
string fileName = Path.GetFileNameWithoutExtension(filePath);
//Split the filename up into store code, week and year
string[] fileNameSplit = fileName.Split('_');
//Gets the store object with the matching store code.
Store store = stores[fileNameSplit[0]];
//Create Date object from week and year.
Date date = new Date { Week = Convert.ToInt32(fileNameSplit[1]), Year = Convert.ToInt32(fileNameSplit[2]) };
if (!dates.ContainsKey(date.ToString()))
{
dates.TryAdd(date.ToString(), date);
}
string[] orderData = File.ReadAllLines(folderPath + @"\" + storeDataFolder + @"\" + fileNameExt);
foreach (string entry in orderData)
{
string[] orderSplit = entry.Split(',');
Order order = new Order(store, dates[date.ToString()], new Supplier(orderSplit[0], orderSplit[1]), Convert.ToDouble(orderSplit[2]));
lock (orders)
{
orders.Add(order);
}
}
orderFilesRead++;
callback(orderFilesRead, fileNames.Length);
});
});
return orders;
}
public async Task<ConcurrentDictionary<string, Store>> LoadStores(Action<int, int> callback)
{
ConcurrentDictionary<string, Store> stores = new ConcurrentDictionary<string, Store>();
string storeCodesFilePath = folderPath + @"\" + storeCodesFile;
string[] storeCodesData = File.ReadAllLines(storeCodesFilePath);
int storeFilesRead = 0;
await Task.Run(() =>
{
Parallel.ForEach(storeCodesData, storeData =>
{
string[] storeDataSplit = storeData.Split(',');
Store store = new Store { StoreCode = storeDataSplit[0], StoreName = storeDataSplit[1] };
if (!stores.ContainsKey(store.StoreCode))
{
stores.TryAdd(store.StoreCode, store);
storeFilesRead++;
callback(storeFilesRead, storeCodesData.Length);
}
});
});
return stores;
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/GetTotalCostInWeekCommand.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using WPFDataParallelismProj.DTO;
using WPFDataParallelismProj.Handler;
namespace WPFDataParallelismProj.CommandsFactory
{
class GetTotalCostInWeekCommand : ICommand
{
private HashSet<Order> orders;
private Date date;
private OrderHandler orderHandler;
public GetTotalCostInWeekCommand(HashSet<Order> orders, Date date)
{
this.orders = orders;
this.date = date;
orderHandler = new OrderHandler();
}
public async Task<object> Execute()
{
return await orderHandler.GetTotalCostInWeek(orders, date);
}
}
}<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Repositories/ProfileRepository.cs
using AnimalCareSystem.ApplicationUI;
using AnimalCareSystem.Data;
using AnimalCareSystem.Models;
using AnimalCareSystem.ViewModels;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.Repositories
{
public class ProfileRepository : IRepository
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private ApplicationDbContext _dbContext;
public ProfileRepository(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ApplicationDbContext dbContext)
{
_userManager = userManager;
_signInManager = signInManager;
_dbContext = dbContext;
}
public async Task<object> Create(object obj)
{
throw new NotImplementedException();
}
public async Task<object> Delete(object obj)
{
throw new NotImplementedException();
}
public async Task<object> Get(object obj)
{
KeyValuePair<string, object> requestData = (KeyValuePair<string, object>)obj;
switch (requestData.Key)
{
case "getUserProfile":
string userId = (string)requestData.Value;
ApplicationUser user = await GetUserById(userId);
UserProfileViewModel userProfileViewModel = BuildUserProfileViewModel(user);
return userProfileViewModel;
case "editProfile":
userId = (string)requestData.Value;
user = await GetUserById(userId);
UserProfileEditViewModel userProfileEditViewModel = await BuildProfileEditViewModel(user);
return userProfileEditViewModel;
default:
return null;
}
}
public async Task<object> Update(object obj)
{
KeyValuePair<string, object> requestData = (KeyValuePair<string, object>)obj;
switch (requestData.Key)
{
case "editProfile":
UserProfileEditViewModel userProfileEditViewModel = (UserProfileEditViewModel)requestData.Value;
ApplicationUser uneditedUser = await GetUserById(userProfileEditViewModel.UserId);
int updateResult = await UpdateUserProfile(userProfileEditViewModel, uneditedUser);
return updateResult;
default:
return null;
}
}
public async Task<int> UpdateUserProfile(UserProfileEditViewModel userProfileEditViewModel, ApplicationUser uneditedUser)
{
if(userProfileEditViewModel.ProfilePhoto != null)
{
string fileName = "";
string filePath = "";
fileName = Path.GetFileName(userProfileEditViewModel.ProfilePhoto.FileName);
filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\Images\\User_Images\\", fileName);
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
await userProfileEditViewModel.ProfilePhoto.CopyToAsync(fileStream);
}
uneditedUser.PhotoFolderSource = Path.Combine("~/Images/User_Images/", fileName);
}
catch (Exception e)
{
return 0;
}
}
if (uneditedUser.Description != userProfileEditViewModel.Description)
{
uneditedUser.Description = userProfileEditViewModel.Description;
}
if(userProfileEditViewModel.Carer == true)
{
foreach (ServiceRateViewModel serviceRateViewModel in userProfileEditViewModel.ServiceRates)
{
ServiceRate serviceRateTest = uneditedUser.ServiceRates.FirstOrDefault(rate => rate.ServiceType.Id == serviceRateViewModel.ServiceType.Id);
if (serviceRateTest == null)
{
ServiceRate newServiceRate = new ServiceRate();
ServiceType serviceType = new ServiceType();
newServiceRate.Rate = serviceRateViewModel.Rate;
newServiceRate.User = uneditedUser;
newServiceRate.ServiceType = serviceType;
newServiceRate.ServiceType.Id = serviceRateViewModel.ServiceType.Id;
newServiceRate.ServiceType.Name = serviceRateViewModel.ServiceType.Name;
uneditedUser.ServiceRates.Add(newServiceRate);
}
else
{
serviceRateTest.Rate = serviceRateViewModel.Rate;
}
foreach (ServiceRate serviceRate in uneditedUser.ServiceRates)
{
if (serviceRate.ServiceType.Id == serviceRateViewModel.ServiceType.Id)
{
serviceRate.Rate = serviceRateViewModel.Rate;
}
}
}
}
int updateResult = (int)await CommandFactory.CreateCommand(CommandFactory.UPDATE_USER, uneditedUser, _dbContext).Execute();
return updateResult;
}
public async Task<UserProfileEditViewModel> BuildProfileEditViewModel(ApplicationUser user)
{
UserProfileEditViewModel userProfileEditViewModel = new UserProfileEditViewModel();
userProfileEditViewModel.UserId = user.Id;
userProfileEditViewModel.Description = user.Description;
userProfileEditViewModel.Carer = user.Carer;
if (user.Carer)
{
List<ServiceRateViewModel> serviceRateViewModelList = new List<ServiceRateViewModel>();
List<ServiceType> serviceTypes = (List<ServiceType>)await CommandFactory.CreateCommand(CommandFactory.GET_SERVICE_TYPES, _dbContext).Execute();
foreach (ServiceType service in serviceTypes)
{
ServiceTypeViewModel serviceTypeViewModel = new ServiceTypeViewModel();
ServiceRateViewModel serviceRateViewModel = new ServiceRateViewModel();
ServiceRate serviceRate = user.ServiceRates.FirstOrDefault(rate => rate.ServiceType.Id == service.Id);
//if (!user.ServiceRates.Any(rate => rate.ServiceType == service))
if (serviceRate == null)
{
serviceTypeViewModel.Id = service.Id;
serviceTypeViewModel.Name = service.Name;
serviceRateViewModel.ServiceType = serviceTypeViewModel;
serviceRateViewModel.Rate = 0;
}
else
{
serviceTypeViewModel.Id = service.Id;
serviceTypeViewModel.Name = service.Name;
serviceRateViewModel.ServiceType = serviceTypeViewModel;
serviceRateViewModel.Rate = serviceRate.Rate;
}
serviceRateViewModelList.Add(serviceRateViewModel);
}
userProfileEditViewModel.ServiceRates = serviceRateViewModelList;
}
return userProfileEditViewModel;
}
public async Task<ApplicationUser> GetUserById(string userId)
{
ApplicationUser user = (ApplicationUser)await CommandFactory.CreateCommand(CommandFactory.GET_USER_BY_ID, userId, _userManager, _dbContext).Execute();
return user;
}
public UserProfileViewModel BuildUserProfileViewModel(ApplicationUser user)
{
UserProfileViewModel userProfileViewModel = new UserProfileViewModel();
List<ReviewViewModel> reviewViewModelList = new List<ReviewViewModel>();
List<ServiceRateViewModel> serviceRateViewModelList = new List<ServiceRateViewModel>();
userProfileViewModel.UserId = user.Id;
userProfileViewModel.Forename = user.Forename;
userProfileViewModel.Surname = user.Surname;
userProfileViewModel.IdentificationVerified = user.IdentificationVerified;
userProfileViewModel.AddressVerified = user.AddressVerified;
userProfileViewModel.DBSChecked = user.DBSChecked;
userProfileViewModel.BoardingLicenseVerified = user.BoardingLicenseVerified;
userProfileViewModel.Description = user.Description;
userProfileViewModel.PhotoFolderSource = user.PhotoFolderSource;
userProfileViewModel.City = user.City;
int recommendationsCount = 0;
foreach (UserReview review in user.ReceivedReviews)
{
ReviewViewModel reviewViewModel = new ReviewViewModel();
reviewViewModel.Title = review.Title;
reviewViewModel.Description = review.Description;
reviewViewModel.DateOfReview = review.Date;
reviewViewModel.ReviewingUserForename = review.ReviewingUser.Forename;
reviewViewModel.Recommended = review.Recommended;
if (review.Recommended)
{
recommendationsCount = recommendationsCount + 1;
}
reviewViewModelList.Add(reviewViewModel);
}
foreach (ServiceRate serviceRate in user.ServiceRates)
{
ServiceRateViewModel serviceRateViewModel = new ServiceRateViewModel();
serviceRateViewModel.ServiceName = serviceRate.ServiceType.Name;
serviceRateViewModel.Rate = serviceRate.Rate;
serviceRateViewModelList.Add(serviceRateViewModel);
}
userProfileViewModel.NumberOfRecommendations = recommendationsCount;
userProfileViewModel.Carer = user.Carer;
userProfileViewModel.Reviews = reviewViewModelList.OrderByDescending(review => review.DateOfReview).ToList();
userProfileViewModel.ServiceRates = serviceRateViewModelList;
return userProfileViewModel;
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Handlers/EquipmentHandler.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers
{
public class EquipmentHandler
{
ApplicationDbContext DbContext;
public EquipmentHandler(ApplicationDbContext dbContext)
{
DbContext = dbContext;
}
public async Task<List<Equipment>> GetAllEquipment()
{
List<Equipment> Equipment = await DbContext.Equipment.ToListAsync();
return Equipment;
}
public async Task<Equipment> GetEquipmentById(long equipmentId)
{
Equipment equipment = await DbContext.Equipment.Where(e => e.Id == equipmentId).FirstOrDefaultAsync();
return equipment;
}
public async Task<bool> CheckEquipmentAvailability(Equipment equipment, List<Booking> bookings)
{
bool available = false;
List<EquipmentBooking> conflictingEquipmentBookings = new List<EquipmentBooking>();
equipment = await GetEquipmentById(equipment.Id);
foreach (Booking booking in bookings)
{
EquipmentBooking ConflictingEquipmentBooking = await DbContext.EquipmentBooking.Where(eb => eb.Booking.Id == booking.Id).FirstOrDefaultAsync();
if(ConflictingEquipmentBooking != null)
{
conflictingEquipmentBookings.Add(ConflictingEquipmentBooking);
}
}
if(conflictingEquipmentBookings.Count < equipment.Count)
{
available = true;
}
return available;
}
}
}
<file_sep>/CNA/SimpleClientServer/Packet/ChatMessagePacket.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Packets
{
[Serializable]
public class ChatMessagePacket : Packet
{
public String message { get; protected set; }
public ChatMessagePacket(String message)
{
this.type = PacketType.CHATMESSAGE;
this.message = message;
}
}
}
<file_sep>/WMAD/CinemaBookingSystem/src/java/adminUI/AddShowingCommand.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package adminUI;
import dto.FilmDTO;
import dto.ScreenDTO;
import handler.ShowingHandler;
/**
*
* @author <NAME>
*/
public class AddShowingCommand implements AdminCommand
{
private FilmDTO film;
private ScreenDTO screen;
private ShowingHandler showHndlr = null;
private String time;
public AddShowingCommand(FilmDTO film, ScreenDTO screen, String time)
{
this.film = film;
this.screen = screen;
this.time = time;
showHndlr = ShowingHandler.getInstance();
}
@Override
public Object execute()
{
return showHndlr.addShowing(film, screen, time);
}
}
<file_sep>/OOAE/T1/T1-03 check portfolio/VehicleShowroomProj/src/vehicleshowroomproj/VehicleShowroomProj.java
package vehicleshowroomproj;
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class VehicleShowroomProj
{
public static void main(String[] args)
{
new ShowroomGui();
// // create objects
// Showroom showroom = new Showroom();
//
// ArrayList<Customer> customers = new ArrayList<>();
//
// customers.add(new Customer("<NAME>", "07585123456"));
// customers.add(new Customer("<NAME>", "<EMAIL>"));
//
// ArrayList<Vehicle> vehicles = new ArrayList<>();
//
// populateArray(vehicles);
//
// //print all vehicle details
// printVehicleDetails(vehicles);
//
// //buy vehicles
// buyVehicle(vehicles, customers);
//
// //re-print all vehicle details
// printVehicleDetails(vehicles);
//
// //add vehicles to showroom
// addVehicleToShowroom(vehicles, showroom);
}
public static void printVehicleDetails(ArrayList<Vehicle> vehicles)
{
System.out.println(" !!CALLING VEHICLE.TOSTRING!! \n");
int index = 1;
for(Vehicle vehicle : vehicles)
{
System.out.println(" vehicle " + index + ": \n" + vehicle);
System.out.println("");
index++;
}
}
public static void populateArray(ArrayList<Vehicle> vehicles)
{
vehicles.add(new Vehicle("Mercedes", "SLK", "12h123b", "12/9/2017", 'C', 43000));
vehicles.add(new Vehicle("peugeot", "208", "96a858h", "17/9/2014", 'B', 19595));
vehicles.add(new Vehicle("Fiat", "500", "57f158p", "10/10/2017", 'G', 18700));
vehicles.add(new Vehicle("Ford", "Kuga", "46n947l", "27/8/2013", 'D', 21000));
}
public static void createCustomers(ArrayList<Customer> customers)
{
customers.add(new Customer("<NAME>", "07585123456"));
customers.add(new Customer("<NAME>", "<EMAIL>"));
}
public static void buyVehicle(ArrayList<Vehicle> vehicles, ArrayList<Customer> customers)
{
vehicles.get(0).buy("27/9/2017", customers.get(0));
vehicles.get(2).buy("5/10/2017", customers.get(1));
}
public static void addVehicleToShowroom(ArrayList<Vehicle> vehicles, Showroom showroom)
{
showroom.addVehicle(vehicles.get(0));
showroom.addVehicle(vehicles.get(1));
showroom.addVehicle(vehicles.get(2));
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Handlers/UserHandler.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers
{
public class UserHandler
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private ApplicationDbContext DbContext;
public UserHandler(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
public UserHandler(UserManager<ApplicationUser> userManager, ApplicationDbContext dbContext)
{
DbContext = dbContext;
_userManager = userManager;
}
public UserHandler(SignInManager<ApplicationUser> signInManager)
{
_signInManager = signInManager;
}
public async Task<IdentityResult> RegisterUser(ApplicationUser newUser)
{
IdentityResult result = await _userManager.CreateAsync(newUser, newUser.PasswordHash);
var claim = await _userManager.AddClaimAsync(newUser, new Claim("Forename", newUser.Forename));
var role = await _userManager.AddToRoleAsync(newUser, "User");
if (result.Succeeded)
{
await _signInManager.SignInAsync(newUser, isPersistent: false);
}
return result;
}
public async Task<SignInResult> Login(string email, string passwordHash, bool rememberMe)
{
SignInResult result = await _signInManager.PasswordSignInAsync(email, passwordHash, rememberMe, lockoutOnFailure: false);
return result;
}
public async Task<int> BlacklistUser(string userId)
{
ApplicationUser user = await GetUser(userId);
user.Blacklisted = true;
DbContext.User.Update(user);
return await DbContext.SaveChangesAsync();
}
public async Task<ApplicationUser> GetUser(string userId)
{
return await _userManager.FindByIdAsync(userId);
}
public async Task<int> UpdateUser(ApplicationUser updatedUser)
{
ApplicationUser uneditedUser = await GetUser(updatedUser.Id);
if(uneditedUser != null)
{
if(uneditedUser.IdentificationFolderSource != updatedUser.IdentificationFolderSource)
{
uneditedUser.IdentificationFolderSource = updatedUser.IdentificationFolderSource;
}
DbContext.User.Update(updatedUser);
return await DbContext.SaveChangesAsync();
}
return 0;
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/entity/Route.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Rhys
*/
@Entity
@Table(name = "ROUTE")
@XmlRootElement
@NamedQueries(
{
@NamedQuery(name = "Route.findAll", query = "SELECT r FROM Route r"),
@NamedQuery(name = "Route.findByRouteId", query = "SELECT r FROM Route r WHERE r.routeId = :routeId"),
@NamedQuery(name = "Route.findByName", query = "SELECT r FROM Route r WHERE r.name = :name")
})
public class Route implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ROUTE_ID")
private Integer routeId;
@Size(max = 255)
@Column(name = "NAME")
private String name;
@JoinColumn(name = "DEPOT_ID", referencedColumnName = "DEPOT_ID")
@ManyToOne
private Depot depotId;
@OneToMany(mappedBy = "routeId")
private Collection<Users> usersCollection;
@OneToMany(mappedBy = "routeId")
private Collection<Delivery> deliveryCollection;
public Route()
{
}
public Route(Integer routeId)
{
this.routeId = routeId;
}
public Integer getRouteId()
{
return routeId;
}
public void setRouteId(Integer routeId)
{
this.routeId = routeId;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Depot getDepotId()
{
return depotId;
}
public void setDepotId(Depot depotId)
{
this.depotId = depotId;
}
@XmlTransient
public Collection<Users> getUsersCollection()
{
return usersCollection;
}
public void setUsersCollection(Collection<Users> usersCollection)
{
this.usersCollection = usersCollection;
}
@XmlTransient
public Collection<Delivery> getDeliveryCollection()
{
return deliveryCollection;
}
public void setDeliveryCollection(Collection<Delivery> deliveryCollection)
{
this.deliveryCollection = deliveryCollection;
}
@Override
public int hashCode()
{
int hash = 0;
hash += (routeId != null ? routeId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object)
{
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Route))
{
return false;
}
Route other = (Route) object;
if ((this.routeId == null && other.routeId != null) || (this.routeId != null && !this.routeId.equals(other.routeId)))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "entity.Route[ routeId=" + routeId + " ]";
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/GetVehicleCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class GetVehicleCommand : ICommand
{
private VehicleHandler VehicleHandler;
private long VehicleId;
public GetVehicleCommand(long vehicleId, ApplicationDbContext dbContext)
{
VehicleHandler = new VehicleHandler(dbContext);
VehicleId = vehicleId;
}
public async Task<object> Execute()
{
return await VehicleHandler.GetVehicle(VehicleId);
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/nbproject/private/private.properties
deploy.ant.properties.file=C:\\Users\\Rhys\\AppData\\Roaming\\NetBeans\\11.1\\config\\GlassFishEE6\\Properties\\gfv31282814137.properties
j2ee.platform.is.jsr109=true
j2ee.server.domain=C:/Users/Rhys/Glassfish/glassfish/domains/domain1
j2ee.server.home=C:/Users/Rhys/Glassfish/glassfish
j2ee.server.instance=[C:\\Users\\Rhys\\Glassfish\\glassfish;C:\\Users\\Rhys\\Glassfish\\glassfish\\domains\\domain1]deployer:gfv5ee8:localhost:4848
j2ee.server.middleware=C:/Users/Rhys/Glassfish
netbeans.user=C:\\Users\\Rhys\\AppData\\Roaming\\NetBeans\\11.1
user.properties.file=C:\\Users\\Rhys\\AppData\\Roaming\\NetBeans\\11.1\\build.properties
<file_sep>/WMAD/CinemaBookingSystem/src/java/adminUI/AdminCommandFactory.java
package adminUI;
import dto.BookingDTO;
import dto.FilmDTO;
import dto.ScreenDTO;
/**
*
* @author <NAME>
*/
public class AdminCommandFactory
{
public static final int LOGIN_ADMIN = 1;
public static final int GET_ALL_FILMS = 2;
public static final int DELETE_FILM = 3;
public static final int ADD_FILM = 4;
public static final int GET_ALL_BOOKINGS = 5;
public static final int CANCEL_BOOKING = 6;
public static final int ADD_SHOWING = 7;
public static AdminCommand createCommand(int commandType, String username, String password)
{
switch (commandType)
{
case LOGIN_ADMIN:
return new LoginAdminCommand(username, password);
default:
return null;
}
}
public static AdminCommand createCommand(int commandType)
{
switch (commandType)
{
case GET_ALL_FILMS:
return new GetAllFilmsCommand();
case GET_ALL_BOOKINGS:
return new GetAllBookingsCommand();
default:
return null;
}
}
public static AdminCommand createCommand(int commandType, int filmID)
{
switch (commandType)
{
case DELETE_FILM:
return new DeleteFilmCommand(filmID);
default:
return null;
}
}
public static AdminCommand createCommand(int commandType, FilmDTO film)
{
switch (commandType)
{
case ADD_FILM:
return new AddFilmCommand(film);
default:
return null;
}
}
public static AdminCommand createCommand(int commandType, BookingDTO booking)
{
switch (commandType)
{
case CANCEL_BOOKING:
return new CancelBookingCommand(booking);
default:
return null;
}
}
public static AdminCommand createCommand(int commandType, FilmDTO film, ScreenDTO screen, String time)
{
switch (commandType)
{
case ADD_SHOWING:
return new AddShowingCommand(film, screen, time);
default:
return null;
}
}
}
<file_sep>/WMAD/CinemaBookingSystem/src/java/managedbean/AddFilmBean.java
package managedbean;
import adminUI.AdminCommandFactory;
import dto.FilmDTO;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
/**
*
* @author <NAME>
*/
@Named(value = "AddFilmBean")
@RequestScoped
public class AddFilmBean
{
private String title;
private int ageRating;
private int runtime;
private String description;
public String addFilm()
{
boolean filmAdded = false;
FilmDTO film = new FilmDTO(0, title, ageRating, runtime, description);
filmAdded = (boolean) AdminCommandFactory
.createCommand(
AdminCommandFactory.ADD_FILM, film)
.execute();
if(filmAdded)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Film Added."));
return "Film Added";
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Error: Film could not be Added."));
return null;
}
}
public String getTitle()
{
return title;
}
public int getAgeRating()
{
return ageRating;
}
public int getRuntime()
{
return runtime;
}
public String getDescription()
{
return description;
}
public void setTitle(String title)
{
this.title = title;
}
public void setAgeRating(int ageRating)
{
this.ageRating = ageRating;
}
public void setRuntime(int runtime)
{
this.runtime = runtime;
}
public void setDescription(String description)
{
this.description = description;
}
}
<file_sep>/OOAE/T2/T2-05/wk2-05_lec1_VisitorProj/wk2-05_lec1_VisitorProj/src/model/EmployeeHandler.java
package model;
import database.DatabaseConnectionPool;
import Employee.Employee;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
/**
*
* @author <NAME>
*/
public class EmployeeHandler
{
private static final String FIND_ALL = "Select * from Emp";
public ArrayList<Employee> findAllEmployees()
{
ArrayList<Employee> list = new ArrayList<>();
DatabaseConnectionPool pool = DatabaseConnectionPool.getInstance();
Connection con = pool.getAvailableConnection();
try
{
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(FIND_ALL);
while (rs.next())
{
Employee emp = new Employee(
rs.getInt("empNo"),
rs.getString("eName"),
rs.getString("job"),
rs.getInt("mgr"),
rs.getDate("hireDate"),
rs.getInt("sal"),
rs.getInt("comm"),
rs.getInt("deptNo"));
list.add(emp);
}
rs.close();
stmt.close();
pool.returnConnection(con);
return list;
}
catch (SQLException sqle)
{
sqle.printStackTrace(System.err);
return list;
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/DataParallelismProj/DTO/Order.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataParallelismProj.DTO
{
class Order
{
public Store Store { get; set; }
public Supplier Supplier { get; set; }
public double Price { get; set; }
public Date Date { get; set; }
public Order()
: this(new Store(), new Date(), new Supplier(), 0.0)
{
}
public Order(Store store, Date date, Supplier supplier, double price)
{
this.Store = store;
this.Supplier = supplier;
this.Price = price;
}
}
}
<file_sep>/OOAE/T1/T1-11/ProducerConsumerProj/src/producerconsumerproj/Producer.java
package producerconsumerproj;
public class Producer extends Thread
{
private Buffer buffer;
private int producerNum;
public Producer(Buffer buffer, int producerNum)
{
this.buffer = buffer;
this.producerNum = producerNum;
}
public void run()
{
for (int i = 0; i < 5; i++)
{
try
{
buffer.add((i + 1), producerNum);
Thread.sleep(2000);
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted.\n" + e);
}
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/DataParallelismProj/Handler/OrderHandler.cs
using DataParallelismProj.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataParallelismProj.Handler
{
class OrderHandler
{
public List<Supplier> GetAllSuppliers()
{
return null;
}
}
}
<file_sep>/OOAE/T1/T1-09/cardDeckProj/src/carddeckproj/DisplayableDeck.java
package carddeckproj;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
public class DisplayableDeck extends Deck implements Displayable
{
private Image image;
@Override
public void display(Graphics g, int x, int y)
{
image = new ImageIcon(getClass().getResource("/images/b1fv.png")).getImage();
g.drawImage(image, x, y, null);
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/ejb/UserHandler.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ejb;
import database.UserGatewayLocal;
import dto.UserDTO;
import javax.ejb.EJB;
import javax.ejb.Stateless;
/**
*
* @author Rhys
*/
@Stateless
public class UserHandler implements UserHandlerLocal
{
@EJB
UserGatewayLocal userTable;
@Override
public UserDTO login(String email, String password)
{
return userTable.login(email, password);
}
@Override
public boolean register(UserDTO registeringUserDTO)
{
return userTable.registerNewUser(registeringUserDTO);
}
@Override
public UserDTO updateAccountDetails(UserDTO user, String oldPassword, String oldEmail)
{
return userTable.updateAccountDetails(user, oldPassword, oldEmail);
}
@Override
public boolean deleteAccount(UserDTO user)
{
return userTable.deleteAccount(user);
}
@Override
public UserDTO assignRouteToDriver(UserDTO user, int routeId)
{
return userTable.assignRouteToDriver(user, routeId);
}
}
<file_sep>/WMAD/WMAD_assignment_2/app/src/main/java/com/example/rhysj/wmad_assignment_2/JsonConverter/StringToDateConverter.java
package com.example.rhysj.wmad_assignment_2.JsonConverter;
import android.util.Log;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created by J016984c on 11/04/2018.
*/
public class StringToDateConverter implements JsonDeserializer<Date>
{
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
String json_date = json.getAsString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH);
try
{
Date date = sdf.parse(json_date);
return date;
}
catch(ParseException pe)
{
Log.e("JSON_TO_DATE_ERROR: ", "Parse failed" + pe);
return new Date();
}
}
}
<file_sep>/ESA/ESA/src/esa/MainPanel.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package esa;
import com.javaswingcomponents.accordion.JSCAccordion;
import com.javaswingcomponents.accordion.TabOrientation;
import com.javaswingcomponents.accordion.listener.AccordionEvent;
import com.javaswingcomponents.accordion.listener.AccordionListener;
import com.javaswingcomponents.accordion.plaf.AccordionUI;
import com.javaswingcomponents.accordion.plaf.basic.BasicHorizontalTabRenderer;
import com.javaswingcomponents.accordion.plaf.darksteel.DarkSteelAccordionUI;
import com.javaswingcomponents.framework.painters.configurationbound.GradientColorPainter;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* @author danpa
*/
public class MainPanel extends JPanel{
static JPanel frame;
private JSCAccordion accordion = new JSCAccordion();
private ArrayList<JPanel> tabs = new ArrayList();
private String type;
public MainPanel(String type) {
this.type = type;
for(int i=0;i<5;i++){
addTab(type +" "+ (i+1),i);
}
howToListenForChanges(accordion);
howToChangeTabOrientation(accordion);
howToChangeTheLookAndFeel(accordion);
howToCustomizeALookAndFeel(accordion);
setLayout(new GridLayout(1,1,30,30));
add(accordion);
}
/**
* When adding a tab to the accordion, you must supply text for the tab
* as well as a component that will be used as the content contained for tab.
* The example below will add five tabs
* The first tab will contain the text "Tab 1" and a JButton
* The second tab will contain the text "Tab 2" and a JLabel
* The third tab will contain the text "Tab 3" and a JTree wrapped in a JScrollpane
* The fourth tab will contain the text "Tab 4" and an empty JPanel, with opaque = true
* The fifth tab will contain the text "Tab 5" and an empty JPanel with opaque = false
*
* The key thing to note is the effect of adding an opaque or non opaque component to
* the accordion.
* @param accordion
*/
private void addTab(String name, int tabNum) {
JPanel opaquePanel = new JPanel();
opaquePanel.setOpaque(true);
opaquePanel.setBackground(Color.GRAY);
accordion.addTab(name, opaquePanel);
tabs.add(opaquePanel);
// accordion.addTab("Tab 1", detailsPanel());
// accordion.addTab("Tab 2", new JLabel("Label"));
// accordion.addTab("Tab 3", new JScrollPane(new JTree()));
// accordion.addTab("Tab 4", opaquePanel);
// accordion.addTab("Tab 5", transparentPanel);
}
/**
* It can be useful to be notified when changes occur on the accordion.
* The accordion can notify a listener when a tab is added, selected or removed.
* @param accordion
*/
private void howToListenForChanges(JSCAccordion accordion) {
accordion.addAccordionListener(new AccordionListener() {
@Override
public void accordionChanged(AccordionEvent accordionEvent) {
//available fields on accordionEvent.
switch (accordionEvent.getEventType()) {
case TAB_ADDED: {
//add your logic here to react to a tab being added.
break;
}
case TAB_REMOVED: {
//add your logic here to react to a tab being removed.
break;
}
case TAB_SELECTED: {
int selected = accordionEvent.getSource().getSelectedIndex();
tabs.get(selected).add(detailsPanel(type,selected));
break;
}
}
}
});
}
/**
* You can change the tab orientation to slide either vertically or horizontally.
* @param accordion
*/
private void howToChangeTabOrientation(JSCAccordion accordion) {
//will make the accordion slide from top to bottom
accordion.setTabOrientation(TabOrientation.VERTICAL);
//will make the accordion slide from left ro right
//accordion.setTabOrientation(TabOrientation.HORITZONTAL);
}
/**
* You can change the look and feel of the component by changing its ui.
* In this example we will change the UI to the DarkSteelUI
* @param accordion
*/
private void howToChangeTheLookAndFeel(JSCAccordion accordion) {
//We create a new instance of the UI
AccordionUI newUI = DarkSteelAccordionUI.createUI(accordion);
//We set the UI
accordion.setUI(newUI);
}
/**
* The easiest way to customize a AccordionUI is to change the
* default Background Painter, AccordionTabRenderers or tweak values
* on the currently installed Background Painter, AccordionTabRenderers and UI.
* @param accordion
*/
private void howToCustomizeALookAndFeel(JSCAccordion accordion) {
//example of changing a value on the ui.
DarkSteelAccordionUI ui = (DarkSteelAccordionUI) accordion.getUI();
ui.setHorizontalBackgroundPadding(10);
//example of changing the AccordionTabRenderer
BasicHorizontalTabRenderer tabRenderer = new BasicHorizontalTabRenderer(accordion);
tabRenderer.setFontColor(Color.RED);
accordion.setHorizontalAccordionTabRenderer(tabRenderer);
//example of changing the background painter.
GradientColorPainter backgroundPainter = (GradientColorPainter) accordion.getBackgroundPainter();
backgroundPainter = (GradientColorPainter) accordion.getBackgroundPainter();
backgroundPainter.setStartColor(Color.BLACK);
backgroundPainter.setEndColor(Color.WHITE);
//the outcome of this customization is not the most visually appealing result
//but it just serves to illustrate how to customize the accordion's look and feel.
//The UI is darkSteel.
//The backgroundPainter is a gradient running from Black to White
//The accordionTabRenderer belongs to the BasicAccordionUI
//And finally the text of the tab is red!
}
private JLabel detailsPanel(String type, int selected){
JLabel label = new JLabel("<html>Hello World!<br/>The scorecard for "+ type +": " + selected +" Will go here</html>");
label.setFont(new Font("Serif", Font.PLAIN, 30));
return label;
}
}
<file_sep>/ESA/Flights Management/test/database/PassengerRisk_ByFlightTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package database;
import java.util.ArrayList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Krzychu
*/
public class PassengerRisk_ByFlightTest {
public PassengerRisk_ByFlightTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getRisk method, of class PassengerRisk_ByFlight.
*/
@Test
public void testGetRisk() {
System.out.println("getRisk");
PassengerRisk_ByFlight instance = new PassengerRisk_ByFlight();
Risk expResult = new Risk(2,"test",2);
instance.addRisk(expResult);
ArrayList<Risk> risks = instance.getRisk();
Risk result = risks.get(0);
assertEquals(expResult, result);
}
/**
* Test of addRisk method, of class PassengerRisk_ByFlight.
*/
@Test
public void testAddRisk() {
System.out.println("addRisk");
PassengerRisk_ByFlight instance = new PassengerRisk_ByFlight();
Risk expResult = new Risk(2,"test",2);
instance.addRisk(expResult);
ArrayList<Risk> risks = instance.getRisk();
Risk result = risks.get(0);
assertEquals(expResult, result);
}
/**
* Test of getPassengerID method, of class PassengerRisk_ByFlight.
*/
@Test
public void testGetPassengerID() {
System.out.println("getPassengerID");
PassengerRisk_ByFlight instance = new PassengerRisk_ByFlight(5, 5);
int expResult = 5;
int result = instance.getPassengerID();
assertEquals(expResult, result);
}
/**
* Test of setPassengerID method, of class PassengerRisk_ByFlight.
*/
@Test
public void testSetPassengerID() {
System.out.println("setPassengerID");
PassengerRisk_ByFlight instance = new PassengerRisk_ByFlight();
int expResult = 5;
instance.setPassengerID(expResult);
int result = instance.getPassengerID();
assertEquals(expResult, result);
}
/**
* Test of getFlightID method, of class PassengerRisk_ByFlight.
*/
@Test
public void testGetFlightID() {
System.out.println("getFlightID");
PassengerRisk_ByFlight instance = new PassengerRisk_ByFlight(5, 5);
int expResult = 5;
int result = instance.getFlightID();
assertEquals(expResult, result);
}
/**
* Test of setFlightID method, of class PassengerRisk_ByFlight.
*/
@Test
public void testSetFlightID() {
System.out.println("setFlightID");
PassengerRisk_ByFlight instance = new PassengerRisk_ByFlight();
int expResult = 5;
instance.setFlightID(expResult);
int result = instance.getFlightID();
assertEquals(expResult, result);
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ViewModels/PriceMatchViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels
{
public class PriceMatchViewModel
{
public List<PriceMatchVehiclesViewModel> PriceMatchVehicles { get; set; }
}
}
<file_sep>/ESA/Flights Management/test/database/SeatTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package database;
import java.sql.Date;
import java.sql.Time;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Krzychu
*/
public class SeatTest {
public SeatTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of setFlight method, of class Seat.
*/
@Test
public void testSetFlight() {
System.out.println("setFlight");
Date date = Date.valueOf("2018-03-03");
Time time = Time.valueOf("20:20:00");
Plane plane = new Plane();
Flight expResult = new Flight(1,1,"test1","test2",date,time,date,time,plane);
Seat instance = new Seat();
instance.setFlight(expResult);
Flight result = instance.getFlight();
assertEquals(expResult, result);
}
/**
* Test of getFlight method, of class Seat.
*/
@Test
public void testGetFlight() {
System.out.println("getFlight");
Date date = Date.valueOf("2018-03-03");
Time time = Time.valueOf("20:20:00");
Plane plane = new Plane();
Flight expResult = new Flight(1,1,"test1","test2",date,time,date,time,plane);
Seat instance = new Seat();
instance.setFlight(expResult);
Flight result = instance.getFlight();
assertEquals(expResult, result);
}
/**
* Test of getSeatID method, of class Seat.
*/
@Test
public void testGetSeatID() {
System.out.println("getSeatID");
Seat instance = new Seat();
int expResult = 1;
instance.setSeatID(expResult);
int result = instance.getSeatID();
assertEquals(expResult, result);
}
/**
* Test of setSeatID method, of class Seat.
*/
@Test
public void testSetSeatID() {
System.out.println("setSeatID");
Seat instance = new Seat();
int expResult = 1;
instance.setSeatID(expResult);
int result = instance.getSeatID();
assertEquals(expResult, result);
}
/**
* Test of getFlightID method, of class Seat.
*/
@Test
public void testGetFlightID() {
System.out.println("getFlightID");
Seat instance = new Seat();
int expResult = 1;
instance.setFlightID(expResult);
int result = instance.getFlightID();
assertEquals(expResult, result);
}
/**
* Test of setFlightID method, of class Seat.
*/
@Test
public void testSetFlightID() {
System.out.println("setFlightID");
Seat instance = new Seat();
int expResult = 1;
instance.setFlightID(expResult);
int result = instance.getFlightID();
assertEquals(expResult, result);
}
/**
* Test of getSeatNumber method, of class Seat.
*/
@Test
public void testGetSeatNumber() {
System.out.println("getSeatNumber");
Seat instance = new Seat();
int expResult = 1;
instance.setSeatNumber(expResult);
int result = instance.getSeatNumber();
assertEquals(expResult, result);
}
/**
* Test of setSeatNumber method, of class Seat.
*/
@Test
public void testSetSeatNumber() {
System.out.println("setSeatNumber");
Seat instance = new Seat();
int expResult = 1;
instance.setSeatNumber(expResult);
int result = instance.getSeatNumber();
assertEquals(expResult, result);
}
/**
* Test of getSeatTaken method, of class Seat.
*/
@Test
public void testGetSeatTaken() {
System.out.println("getSeatTaken");
Seat instance = new Seat();
boolean expResult = false;
boolean result = instance.getSeatTaken();
instance.setSeatTaken(result);
assertEquals(expResult, result);
}
/**
* Test of setSeatTaken method, of class Seat.
*/
@Test
public void testSetSeatTaken() {
System.out.println("setSeatTaken");
Seat instance = new Seat();
boolean expResult = false;
boolean result = instance.getSeatTaken();
instance.setSeatTaken(result);
assertEquals(expResult, result);
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/Handler/StoreHandler.cs
using WPFDataParallelismProj.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace WPFDataParallelismProj.Handler
{
class StoreHandler
{
public async Task<Store[]> GetStores(HashSet<Order> orders)
{
Store[] stores = new Store[0];
await Task.Run(() =>
{
stores = orders.GroupBy(order => order.Store)
.Select(order => order.Key).ToArray();
});
return stores;
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ViewModels/UserSearchViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ViewModels
{
public class UserSearchViewModel
{
[Required]
[RegularExpression(@"^[a-zA-Z\s]*$", ErrorMessage = "A city should only contain letters.")]
public string City { get; set; }
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Models/ServiceRate.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.Models
{
public class ServiceRate
{
[Required]
public int Id { get; set; }
[Required]
public ServiceType ServiceType { get; set; }
[Required]
public ApplicationUser User { get; set; }
[DataType(DataType.Currency)]
public int Rate { get; set; }
public ServiceRate()
{
}
}
}
<file_sep>/OOAE/T1/T1-03 check portfolio/innerClassesProj/src/innerclassesproj/Student.java
package innerclassesproj;
public class Student
{
private static String name;
private static Address homeAddress, uniAddress;
public Student(String name, int houseNum, String homeStreet)
{
this.name = name;
homeAddress = new Address(houseNum, homeStreet);
}
public void setUniAddress(Address uniAddress)
{
this.uniAddress = uniAddress;
}
public void setUniAddress(int hNum, String StrName)
{
uniAddress = new Address(hNum, StrName);
}
@Override
public String toString()
{
if (homeAddress != null && uniAddress != null)
{
return "Home Address:\n" + homeAddress + "\n\nUni Address:\n" + uniAddress;
}
else if (homeAddress != null && uniAddress == null)
{
return "" + homeAddress;
}
else if (homeAddress == null && uniAddress != null)
{
return "" + uniAddress;
}
else
{
return "Student has no Address";
}
}
public static class Address
{
private int number;
private String street;
public Address(int number, String street)
{
this.number = number;
this.street = street;
}
@Override
public String toString()
{
return name + "\n" + number + " " + street;
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_Library/test/dto/ParcelDTOIT.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import java.util.Date;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Rhys
*/
public class ParcelDTOIT
{
private ParcelDTO parcelDTOInstance = new ParcelDTO();
public ParcelDTOIT()
{
DeliveryDTO deliveryDTOInstance = new DeliveryDTO();
DeliveryStatusDTO deliveryStatusDTOInstance = new DeliveryStatusDTO();
DepotDTO depotDTOInstance = new DepotDTO();
RouteDTO routeDTOInstance = new RouteDTO();
//Create DeliveryDTO
deliveryDTOInstance.setDeliveryId(1);
deliveryDTOInstance.setDeliveryDate(new Date());
deliveryDTOInstance.setDeliveryStatus(deliveryStatusDTOInstance);
deliveryDTOInstance.setDepot(depotDTOInstance);
deliveryDTOInstance.setParcel(parcelDTOInstance);
deliveryDTOInstance.setRoute(routeDTOInstance);
//Create ParcelDTO
parcelDTOInstance.setParcelId(1);
parcelDTOInstance.setRecipientName("Test Recipient");
parcelDTOInstance.setAddressLine1("Test Address 1");
parcelDTOInstance.setAddressLine2("Test Address 2");
parcelDTOInstance.setCity("Test City");
parcelDTOInstance.setPostcode("Test Postcode");
parcelDTOInstance.setDelivered(false);
parcelDTOInstance.setDelivery(deliveryDTOInstance);
}
@BeforeClass
public static void setUpClass()
{
}
@AfterClass
public static void tearDownClass()
{
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
/**
* Test of getParcelId method, of class ParcelDTO.
*/
@Test
public void testGetParcelId()
{
System.out.println("getParcelId");
int expResult = 1;
int result = parcelDTOInstance.getParcelId();
assertEquals(expResult, result);
}
/**
* Test of setParcelId method, of class ParcelDTO.
*/
@Test
public void testSetParcelId()
{
System.out.println("setParcelId");
int parcelId = 0;
ParcelDTO instance = new ParcelDTO();
instance.setParcelId(parcelId);
assertEquals(instance.getParcelId(), parcelId);
}
/**
* Test of getRecipientName method, of class ParcelDTO.
*/
@Test
public void testGetRecipientName()
{
System.out.println("getRecipientName");
String expResult = "Test Recipient";
String result = parcelDTOInstance.getRecipientName();
assertTrue(expResult.equals(result));
}
/**
* Test of setRecipientName method, of class ParcelDTO.
*/
@Test
public void testSetRecipientName()
{
System.out.println("setRecipientName");
String recipientName = "<NAME>";
ParcelDTO instance = new ParcelDTO();
instance.setRecipientName(recipientName);
assertTrue(instance.getRecipientName().equals(recipientName));
}
/**
* Test of getAddressLine1 method, of class ParcelDTO.
*/
@Test
public void testGetAddressLine1()
{
System.out.println("getAddressLine1");
String expResult = "Test Address 1";
String result = parcelDTOInstance.getAddressLine1();
assertTrue(expResult.equals(result));
}
/**
* Test of setAddressLine1 method, of class ParcelDTO.
*/
@Test
public void testSetAddressLine1()
{
System.out.println("setAddressLine1");
String addressLine1 = "Set Test";
ParcelDTO instance = new ParcelDTO();
instance.setAddressLine1(addressLine1);
assertTrue(instance.getAddressLine1().equals(addressLine1));
}
/**
* Test of getAddressLine2 method, of class ParcelDTO.
*/
@Test
public void testGetAddressLine2()
{
System.out.println("getAddressLine2");
String expResult = "Test Address 2";
String result = parcelDTOInstance.getAddressLine2();
assertTrue(expResult.equals(result));
}
/**
* Test of setAddressLine2 method, of class ParcelDTO.
*/
@Test
public void testSetAddressLine2()
{
System.out.println("setAddressLine2");
String addressLine2 = "Set Test";
ParcelDTO instance = new ParcelDTO();
instance.setAddressLine2(addressLine2);
assertTrue(instance.getAddressLine2().equals(addressLine2));
}
/**
* Test of getPostcode method, of class ParcelDTO.
*/
@Test
public void testGetPostcode()
{
System.out.println("getPostcode");
String expResult = "Test Postcode";
String result = parcelDTOInstance.getPostcode();
assertTrue(expResult.equals(result));
}
/**
* Test of setPostcode method, of class ParcelDTO.
*/
@Test
public void testSetPostcode()
{
System.out.println("setPostcode");
String postcode = "Test Set";
ParcelDTO instance = new ParcelDTO();
instance.setPostcode(postcode);
assertTrue(instance.getPostcode().equals(postcode));
}
/**
* Test of getCity method, of class ParcelDTO.
*/
@Test
public void testGetCity()
{
System.out.println("getCity");
String expResult = "Test City";
String result = parcelDTOInstance.getCity();
assertTrue(expResult.equals(result));
}
/**
* Test of setCity method, of class ParcelDTO.
*/
@Test
public void testSetCity()
{
System.out.println("setCity");
String city = "Test Set";
ParcelDTO instance = new ParcelDTO();
instance.setCity(city);
assertTrue(instance.getCity().equals(city));
}
/**
* Test of isDelivered method, of class ParcelDTO.
*/
@Test
public void testIsDelivered()
{
System.out.println("isDelivered");
boolean expResult = false;
boolean result = parcelDTOInstance.isDelivered();
assertEquals(expResult, result);
}
/**
* Test of setDelivered method, of class ParcelDTO.
*/
@Test
public void testSetDelivered()
{
System.out.println("setDelivered");
boolean delivered = true;
ParcelDTO instance = new ParcelDTO();
instance.setDelivered(delivered);
assertEquals(instance.isDelivered(), delivered);
}
/**
* Test of getDelivery method, of class ParcelDTO.
*/
@Test
public void testGetDelivery()
{
System.out.println("getDelivery");
DeliveryDTO result = parcelDTOInstance.getDelivery();
assertTrue(result != null);
}
/**
* Test of setDelivery method, of class ParcelDTO.
*/
@Test
public void testSetDelivery()
{
System.out.println("setDelivery");
DeliveryDTO delivery = new DeliveryDTO();
delivery.setDeliveryId(1);
ParcelDTO instance = new ParcelDTO();
instance.setDelivery(delivery);
assertTrue(instance.getDelivery() != null);
assertEquals(instance.getDelivery().getDeliveryId(), 1);
}
}
<file_sep>/OOAE/T1/T1-03 check portfolio/innerClassesProj/src/innerclassesproj/TestStudent.java
package innerclassesproj;
public class TestStudent
{
public static void main(String[] args)
{
Student s1 = new Student ("Daffy", 21, "Smithfield Drive");
Student.Address anotherAddress = new Student.Address(8, "Deerfield Way");
Student.Address uniAddress = new Student.Address(72, "Nottingham Drive");
s1.setUniAddress(uniAddress);
System.out.println(anotherAddress.toString());
System.out.println("");
System.out.println(s1.toString());
}
}<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Repositories/IRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.Repositories
{
interface IRepository
{
Task<Object> Create(Object obj);
Task<Object> Get(Object obj);
Task<Object> Update(Object obj);
Task<Object> Delete(Object obj);
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/GetSupplierTypesCommand.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WPFDataParallelismProj.DTO;
using WPFDataParallelismProj.Handler;
namespace WPFDataParallelismProj.CommandsFactory
{
class GetSupplierTypesCommand : ICommand
{
private HashSet<Order> orders;
private SupplierHandler supplierHandler;
public GetSupplierTypesCommand(HashSet<Order> orders)
{
this.orders = orders;
supplierHandler = new SupplierHandler();
}
public async Task<object> Execute()
{
return await supplierHandler.GetSupplierTypes(orders);
}
}
}<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/GetTransmissionTypesCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class GetTransmissionTypesCommand : ICommand
{
private VehicleHandler VehicleHandler;
public GetTransmissionTypesCommand(ApplicationDbContext dbContext)
{
VehicleHandler = new VehicleHandler(dbContext);
}
public async Task<object> Execute()
{
return await VehicleHandler.GetTransmissionTypes();
}
}
}
<file_sep>/OOAE/T2/T2-05/wk2-05_lec1_BuilderProj/wk2-05_lec1_VisitorProj/src/view/AllDepartmentsView.java
package view;
import department.Department;
import department.DepartmentPrinter;
import java.util.ArrayList;
public class AllDepartmentsView
{
ArrayList<Department> departments;
public AllDepartmentsView(ArrayList<Department> departments)
{
this.departments = departments;
}
public void print()
{
DepartmentPrinter deptPrinter = new DepartmentPrinter();
System.out.println("All departments");
System.out.println("===============");
for (Department dept : departments)
{
dept.accept(deptPrinter);
}
}
}
<file_sep>/CNA/SimpleClientServer/Packet/NicknamePacket.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Packets
{
[Serializable]
public class NicknamePacket : Packet
{
public String nickname { get; protected set; }
public NicknamePacket(String nickname)
{
this.type = PacketType.NICKNAME;
this.nickname = nickname;
}
}
}
<file_sep>/ESA/Flights Management/src/view/AllPassengersView.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import database.Passenger;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JLabel;
/**
*
* @author Greg
*/
public class AllPassengersView
{
private ArrayList<Passenger> AllPassengers;
public AllPassengersView(ArrayList<Passenger> AllPassengers)
{
this.AllPassengers = AllPassengers;
}
public String print()
{
System.out.println("All Flights\n");
for (Passenger p : AllPassengers)
{
System.out.println("Passenger ID: " + p.getPassengerID()
+ "\tForename: " + p.getForename()
+ "\tSurname: " + p.getSurname()
+ "\tDate of Birth: " + p.getDOB()
+ "\tNationality: " + p.getNationality()
+ "\tPassport Number: " + p.getPassportNumber() + "\n");
}
return "Test";
}
public ArrayList<JLabel> alphabetise()
{
ArrayList<JLabel> labels = new ArrayList<>();
Collections.sort(AllPassengers);
char alphabet = 'A';
String buff = "";
for (int i = 0; i < AllPassengers.size(); i++)
{
if (alphabet == Character.toUpperCase(AllPassengers.get(i).getSurname().charAt(0)))
{
buff += (AllPassengers.get(i).getLabel());
System.out.println(buff.toString());
}
else
{
labels.add(new JLabel("<html><table>" + buff.toString() + "</table></html>"));
buff = "";
//buff +=( AllPassengers.get(i).getLabel());
// System.out.println(buff.toString());
alphabet++;
}
}
return labels;
}
}
<file_sep>/WMAD/WMAD_assignment_2/app/src/main/java/com/example/rhysj/wmad_assignment_2/DTO/ShowingDTO.java
package com.example.rhysj.wmad_assignment_2.DTO;
/**
* Created by <NAME> on 04/04/2018.
*/
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ShowingDTO implements Serializable
{
private int showingID;
private FilmDTO film;
private ScreenDTO screen;
private String time;
private int availableSeats;
public ShowingDTO()
{
this.showingID = 0;
this.film = new FilmDTO();
this.screen = new ScreenDTO();
this.time = "";
this.availableSeats = 0;
}
public ShowingDTO(int showingID, FilmDTO film, ScreenDTO screen, String time, int availableSeats)
{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
this.showingID = showingID;
this.film = film;
this.screen = screen;
this.time = sdf.format(time);
this.availableSeats = availableSeats;
}
public ShowingDTO(int showingID, FilmDTO film, ScreenDTO screen, Date time, int availableSeats)
{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
this.showingID = showingID;
this.film = film;
this.screen = screen;
this.time = sdf.format(time);
this.availableSeats = availableSeats;
}
public int getShowingID()
{
return showingID;
}
public FilmDTO getFilm()
{
return film;
}
public ScreenDTO getScreen()
{
return screen;
}
public String getTime()
{
return time;
}
public int getAvailableSeats()
{
return availableSeats;
}
}<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/application_ui/CommandFactoryLocal.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package application_ui;
import dto.UserDTO;
import java.util.Date;
import javax.ejb.Local;
/**
*
* @author Rhys
*/
@Local
public interface CommandFactoryLocal
{
Command createCommand(int commandType, String email, String password);
Command createCommand(int commandType, UserDTO userDTO);
Command createCommand(int commandType, int entityId);
Command createCommand(int commandType, int deliveryId, Date date);
Command createCommand(int commandType, UserDTO user, String oldPassword, String oldEmail);
Command createCommand(int commandType);
Command createCommand(int commandType, UserDTO user, int entityId);
Command createCommand(int commandType, int entityId, int secondEntityId);
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Handlers/EmailHandler.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using MailKit.Net.Smtp;
using MimeKit;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers
{
public class EmailHandler
{
private const String SmtpAddress = "smtp.gmail.com";
private const int Port = 465;
private const String Username = "<EMAIL>";
private const String Password = "<PASSWORD>";
private byte[] FileByteArray;
public EmailHandler()
{
}
public bool SendEmailToDVLA(IFormFileCollection fileCollection, ApplicationUser user)
{
MimeMessage message = new MimeMessage();
MailboxAddress fromEmailAddress = new MailboxAddress("BangerCo Car Rentals", "<EMAIL>");
MailboxAddress toEmailAddress = new MailboxAddress("DVLA", "<EMAIL>");
message.From.Add(fromEmailAddress);
message.To.Add(toEmailAddress);
message.Subject = "Invalid Driver: Attempted To Book Car Rental";
BodyBuilder emailBodyBuilder = new BodyBuilder();
emailBodyBuilder.TextBody = "An attempt was made to rent a vehicle by " + user.Forename + " " + user.Surname + " with driving license number " + user.LicenseNumber + " on " + DateTime.Now + "GMT" + ". Our registration number is 03716371. Please find all relevant documents attached.";
try
{
foreach (IFormFile attachment in fileCollection)
{
using (MemoryStream memoryStream = new MemoryStream())
{
attachment.CopyTo(memoryStream);
FileByteArray = memoryStream.ToArray();
}
emailBodyBuilder.Attachments.Add(attachment.FileName, FileByteArray, ContentType.Parse(attachment.ContentType));
}
message.Body = emailBodyBuilder.ToMessageBody();
SmtpClient client = new SmtpClient();
client.Connect(SmtpAddress, Port, true);
client.Authenticate(Username, Password);
client.Send(message);
client.Disconnect(true);
client.Dispose();
return true;
}
catch(Exception e)
{
return false;
}
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/LoadDataCommand.cs
using WPFDataParallelismProj.Handler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFDataParallelismProj.CommandsFactory
{
class LoadDataCommand : ICommand
{
private FileHandler fileHandler;
private Action<int, int> callback;
public LoadDataCommand(Action<int, int> callback)
{
fileHandler = FileHandler.GetInstance();
this.callback = callback;
}
public async Task<object> Execute()
{
return await fileHandler.LoadOrders(callback);
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Models/EquipmentBooking.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Models
{
public class EquipmentBooking
{
public int Id { get; set; }
public Booking Booking { get; set; }
public Equipment Equipment { get; set; }
public int Count { get; set; }
public EquipmentBooking()
{
}
public EquipmentBooking(Booking booking, Equipment equipment)
{
Booking = booking;
Equipment = equipment;
}
public EquipmentBooking(int id, Booking booking, Equipment equipment)
{
Id = id;
Booking = booking;
Equipment = equipment;
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_Library/test/dto/DeliveryStatusDTOIT.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Rhys
*/
public class DeliveryStatusDTOIT
{
private DeliveryStatusDTO deliveryStatusDTOInstance = new DeliveryStatusDTO();
public DeliveryStatusDTOIT()
{
deliveryStatusDTOInstance.setDeliveryStatusId(1);
deliveryStatusDTOInstance.setName("Test Status");
}
@BeforeClass
public static void setUpClass()
{
}
@AfterClass
public static void tearDownClass()
{
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
/**
* Test of getDeliveryStatusId method, of class DeliveryStatusDTO.
*/
@Test
public void testGetDeliveryStatusId()
{
System.out.println("getDeliveryStatusId");
int expResult = 1;
int result = deliveryStatusDTOInstance.getDeliveryStatusId();
assertEquals(expResult, result);
}
/**
* Test of setDeliveryStatusId method, of class DeliveryStatusDTO.
*/
@Test
public void testSetDeliveryStatusId()
{
System.out.println("setDeliveryStatusId");
int deliveryStatusId = 2;
DeliveryStatusDTO instance = new DeliveryStatusDTO();
instance.setDeliveryStatusId(deliveryStatusId);
assertEquals(instance.getDeliveryStatusId(), 2);
}
/**
* Test of getName method, of class DeliveryStatusDTO.
*/
@Test
public void testGetName()
{
System.out.println("getName");
String expResult = "Test Status";
String result = deliveryStatusDTOInstance.getName();
assertEquals(expResult, result);
}
/**
* Test of setName method, of class DeliveryStatusDTO.
*/
@Test
public void testSetName()
{
System.out.println("setName");
String name = "Test Set Status";
deliveryStatusDTOInstance.setName(name);
assertTrue(deliveryStatusDTOInstance.getName().equals(name));
}
}
<file_sep>/OOAE/T1/T1-09/RegularExpressionsProj/src/regularexpressionsproj/RegularExpressionsProj.java
package regularexpressionsproj;
import java.util.Scanner;
public class RegularExpressionsProj
{
public static void main(String[] args)
{
String input = "";
Scanner kybd = new Scanner(System.in);
while (!input.equals("0"))
{
System.out.print("Please enter a name, or 0 to exit:>");
input = kybd.nextLine();
if (input.matches("(Will|William)"))
{
System.out.println("Name matches either Will or William");
}
else if(input.matches("0"))
{
return;
}
else
{
System.out.println("Name does not match");
}
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Models/UserReview.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.Models
{
public class UserReview
{
[Required]
public int Id { get; set; }
[Required]
public ApplicationUser ReviewingUser { get; set; }
[Required]
public ApplicationUser ReceivingUser { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
public string Title { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime Date { get; set; }
[Required]
public bool Recommended { get; set; }
public UserReview()
{
}
}
}
<file_sep>/ESA/Flights Management/nbproject/private/private.properties
compile.on.save=true
<<<<<<< HEAD
do.depend=false
do.jar=true
file.reference.accordion-1.2.0-jar-with-dependencies.jar=F:\\UNI-LEVEL 5\\ESA\\T2\\ESA-Project\\JARS\\accordion-1.2.0-jar-with-dependencies.jar
file.reference.LGoodDatePicker-10.3.1-javadoc.jar=F:\\UNI-LEVEL 5\\ESA\\T2\\ESA-Project\\JARS\\LGoodDatePicker-10.3.1-javadoc.jar
file.reference.swingx-0.9.5-2.jar=F:\\UNI-LEVEL 5\\ESA\\T2\\ESA-Project\\JARS\\swingx-0.9.5-2.jar
javac.debug=true
javadoc.preview=true
user.properties.file=C:\\Users\\Greg\\AppData\\Roaming\\NetBeans\\8.2\\build.properties
=======
file.reference.derby.jar=F:\\UNI-LEVEL 5\\ESA\\T2\\ESA-Project\\JARS\\derby.jar
file.reference.derbyclient.jar=F:\\UNI-LEVEL 5\\ESA\\T2\\ESA-Project\\JARS\\derbyclient.jar
user.properties.file=C:\\Users\\Rhysj\\AppData\\Roaming\\NetBeans\\8.2\\build.properties
>>>>>>> 52eaaa0728336852d64480bf74f1cbd5ecea72ee
<file_sep>/OOAE/T2/T2-05/wk2-05_lec1_VisitorProj/wk2-05_lec1_VisitorProj/src/Client.java
import command.CommandFactory;
import java.util.Scanner;
public class Client
{
public static void main(String[] args)
{
int choice = displayMenu();
CommandFactory.create(choice).execute();
}
public static int displayMenu()
{
Scanner kybd = new Scanner(System.in);
System.out.println("1. Display all departments");
System.out.println("2. Display all employees\n");
System.out.print("Option: >");
int choice = kybd.nextInt();
kybd.nextLine(); // Flush Buffer
return choice;
}
}
<file_sep>/CNA/SimpleClientServer/Packet/SellProductPacket.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Packets
{
[Serializable]
public class SellProductPacket : Packet
{
public String productType { get; protected set; }
public SellProductPacket(String productType)
{
this.type = PacketType.SELLPRODUCT;
this.productType = productType;
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/AddBookingCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class AddBookingCommand : ICommand
{
BookingHandler BookingHandler;
Booking NewBooking;
List<Equipment> ChosenEquipmentList;
public AddBookingCommand(Booking newBooking, List<Equipment> chosenEquipmentList, ApplicationDbContext dbContext)
{
BookingHandler = new BookingHandler(dbContext);
NewBooking = newBooking;
ChosenEquipmentList = chosenEquipmentList;
}
public async Task<object> Execute()
{
return await BookingHandler.AddBooking(NewBooking, ChosenEquipmentList);
}
}
}
<file_sep>/OOAE/T1/T1-05/JUnitProj/src/junitproj/JUnitProj.java
package junitproj;
public class JUnitProj
{
public static void main(String[] args)
{
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Controllers/FileUploadController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace EIRLSS_Assignment2_J016984C_Rhys_Jones.Controllers
{
public class FileUploadController : Controller
{
private readonly ApplicationDbContext DbContext;
private UserManager<ApplicationUser> UserManager;
public FileUploadController(ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager)
{
DbContext = dbContext;
UserManager = userManager;
}
[HttpGet]
public async Task<IActionResult> FileUpload()
{
await AuthenticateUserLogin(true);
FileUploadViewModel fileUploadViewModel = new FileUploadViewModel();
return View(fileUploadViewModel);
}
[HttpPost]
public async Task<IActionResult> FileUpload(FileUploadViewModel fileUploadViewModel)
{
await AuthenticateUserLogin(true);
bool fileUploadedSuccessfully = false;
if (ModelState.IsValid)
{
if(!Path.GetExtension(fileUploadViewModel.DVLADataFile.FileName).Equals(".csv", StringComparison.InvariantCultureIgnoreCase))
{
TempData["errormessage"] = "Incorrect File Type. Please try again!";
return View(fileUploadViewModel);
}
fileUploadedSuccessfully = UploadFile(fileUploadViewModel.DVLADataFile).Result;
if (fileUploadedSuccessfully)
{
TempData["successmessage"] = "File(s) Added Successfully!";
return RedirectToAction("Index", "Home");
}
else
{
TempData["errormessage"] = "Failed to upload file. Please try again!";
return View(fileUploadViewModel);
}
return View();
}
else
{
TempData["errormessage"] = "Failed to upload file. Please try again!";
return View(fileUploadViewModel);
}
}
public async Task<bool> UploadFile(IFormFile file)
{
string fileName = "";
string filePath = "";
fileName = Path.GetFileName(file.FileName);
filePath = Path.Combine(Directory.GetCurrentDirectory(), "Files", fileName);
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
return true;
}
catch (Exception e)
{
TempData["errormessage"] = "File failed to upload. Please try again!";
return false;
}
}
public async Task<IActionResult> AuthenticateUserLogin(bool adminRequired)
{
ApplicationUser CurrentUser = await UserManager.GetUserAsync(HttpContext.User);
bool IsAdmin = await UserManager.IsInRoleAsync(CurrentUser, "Admin");
if (CurrentUser == null)
{
TempData["errormessage"] = "You need to be logged in to upload files." + Environment.NewLine + " If you do not have an account, please navigate to the registration page by clicking on 'Register' at the top of the screen.";
return RedirectToAction("Login", "Account");
}
if (adminRequired && IsAdmin == false)
{
TempData["errormessage"] = "You require admin privileges to view that page.";
return RedirectToAction("Index", "Home");
}
else return null;
}
}
}<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/application_ui/GetDeliveriesForRouteCommand.java
package application_ui;
import ejb.DeliveryHandlerLocal;
import javax.ejb.EJB;
import javax.ejb.Stateless;
/**
*
* @author Rhys
*/
@Stateless
public class GetDeliveriesForRouteCommand implements GetDeliveriesForRouteCommandLocal
{
@EJB
private DeliveryHandlerLocal deliveryHandler;
private int routeId;
@Override
public Object execute()
{
return deliveryHandler.getDeliveriesForRoute(routeId);
}
@Override
public void setRouteId(int routeId)
{
this.routeId = routeId;
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Handlers/ServiceHandler.cs
using AnimalCareSystem.Data;
using AnimalCareSystem.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.Handlers
{
public class ServiceHandler
{
private ApplicationDbContext _dbContext;
public ServiceHandler(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<List<ServiceType>> GetServiceTypes()
{
List<ServiceType> serviceTypes = await _dbContext.ServiceType.ToListAsync();
return serviceTypes;
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Handlers/FileHandler.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers
{
public class FileHandler
{
private String DVLAFilePath = Path.Combine(Directory.GetCurrentDirectory(), "Files", "dvla.csv");
public FileHandler()
{
}
public List<String> GetAllInvalidLicenses()
{
try
{
String[] invalidLicenses = File.ReadAllLines(DVLAFilePath);
List<String> listOfInvalidLicenses = new List<String>(invalidLicenses);
listOfInvalidLicenses.RemoveAt(0);
return listOfInvalidLicenses;
}
catch(Exception e)
{
return null;
}
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ViewModels/RegisterViewModel.cs
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ViewModels
{
public class RegisterViewModel
{
[PersonalData]
[Required]
[RegularExpression(@"^\+?(?:\d\s?){10,12}$",
ErrorMessage = "Invalid phone number.")] //Source: https://stackoverflow.com/questions/44327236/regex-for-uk-phone-number.
public string PhoneNumber { get; set; }
[PersonalData]
[Required]
public string Forename { get; set; }
[PersonalData]
[Required]
public string Surname { get; set; }
[PersonalData]
[Required]
public string AddressLine1 { get; set; }
[PersonalData]
public string AddressLine2 { get; set; }
[PersonalData]
[Required]
public string City { get; set; }
[PersonalData]
[Required]
public string County { get; set; }
[PersonalData]
[Required]
[RegularExpression(@"([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2})",
ErrorMessage = "Invalid postcode.")] //Regex to match a valid UK postcode format found here: https://stackoverflow.com/questions/164979/regex-for-matching-uk-postcodes
public string Postcode { get; set; }
[PersonalData]
[Required]
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[PersonalData]
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 8)]
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$",
ErrorMessage = "Passwords are required to have at least one uppercase character, one numerical character and alphanumeric character from the following: @$!%*?&")] //Source: https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a.
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The passwords do not match.")]
public string ConfirmPassword { get; set; }
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/DTO/Store.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFDataParallelismProj.DTO
{
class Store
{
public String StoreCode { get; set; }
public String StoreName { get; set; }
public Store()
: this("", "")
{
}
public Store(String storeCode, String storeName)
{
this.StoreCode = storeCode;
this.StoreName = storeName;
}
override
public String ToString()
{
return StoreCode + ", " + StoreName;
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/application_ui/GetDeliveriesForRouteCommandLocal.java
package application_ui;
import javax.ejb.Local;
/**
*
* @author Rhys
*/
@Local
public interface GetDeliveriesForRouteCommandLocal extends Command
{
@Override
Object execute();
void setRouteId(int routeId);
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ViewModels/EquipmentCheckboxSelectViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels
{
public class EquipmentCheckboxSelectViewModel
{
public long Id { get; set; }
public string Name { get; set; }
public bool CheckboxAnswer { get; set; }
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ViewModels/ReviewViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ViewModels
{
public class ReviewViewModel
{
public string ReviewingUserForename { get; set; }
public DateTime DateOfReview { get; set; }
public bool Recommended { get; set; }
public string Description { get; set; }
public string Title { get; set; }
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Controllers/AccountController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using AnimalCareSystem.Data;
using AnimalCareSystem.Models;
using AnimalCareSystem.Repositories;
using AnimalCareSystem.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
namespace AnimalCareSystem.Controllers
{
[Route("account")]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ApplicationDbContext _dbContext;
private readonly AccountRepository _accountRepository;
private readonly IEmailSender _emailSender;
public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ApplicationDbContext dbContext, IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_dbContext = dbContext;
_accountRepository = new AccountRepository(userManager, signInManager, dbContext);
_emailSender = emailSender;
}
[HttpGet, Route("login")]
public IActionResult Login()
{
return View(new LoginViewModel());
}
[HttpPost, Route("login")]
public async Task<IActionResult> Login(LoginViewModel loginViewModel)
{
if (ModelState.IsValid)
{
KeyValuePair<string, object> loginKeyValuePair = new KeyValuePair<string, object>("login", loginViewModel);
Microsoft.AspNetCore.Identity.SignInResult success = (Microsoft.AspNetCore.Identity.SignInResult)await _accountRepository.Get(loginKeyValuePair);
if (success.Succeeded)
{
TempData["successmessage"] = "Logged in Successfully!";
return RedirectToAction("Index", "Home");
}
else if (success.IsNotAllowed)
{
ModelState.AddModelError("", "Please verify your email.");
return View();
}
}
return View();
}
[HttpGet, Route("register")]
public IActionResult Register()
{
return View(new RegisterViewModel());
}
[HttpPost, Route("register")]
public async Task<IActionResult> Register(RegisterViewModel registerViewModel)
{
if (ModelState.IsValid)
{
KeyValuePair<string, object> registerKeyValuePair = new KeyValuePair<string, object>("register", registerViewModel);
ApplicationUser user = (ApplicationUser)await _accountRepository.Create(registerKeyValuePair);
if (user != null)
{
KeyValuePair<string, object> emailConfirmTokenKeyValuePair = new KeyValuePair<string, object>("getEmailConfirmationToken", user);
string code = (string)await _accountRepository.Get(emailConfirmTokenKeyValuePair);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
string callbackUrl = Url.Action(
"ConfirmEmail",
"Account",
values: new { userId = user.Id, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync("<EMAIL>", "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
TempData["successmessage"] = "Registered Successfully!";
return View("RegisterConfirmation", new { email = user.Email });
}
TempData["successmessage"] = "Registered Successfully!";
return RedirectToAction("Index", "Home");
}
else
{
TempData["errormessage"] = "Registration Failure";
return View();
}
}
return View();
}
[HttpGet, Route("registerConfirmation")]
public IActionResult RegisterConfirmation(string email)
{
if (email == null)
{
return RedirectToAction("Index", "Home");
}
return View();
}
[HttpGet, Route("confirmEmail")]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
TempData["errormessage"] = "Email Confirmation Failed.";
return RedirectToAction("Index", "Home");
}
KeyValuePair<string, object> getUserByIdKeyValuePair = new KeyValuePair<string, object>("getUserById", userId);
ApplicationUser user = (ApplicationUser)await _accountRepository.Get(getUserByIdKeyValuePair);
if (user == null)
{
return NotFound($"Unable to load user with ID '{userId}'.");
}
code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
Dictionary<string, object> confirmEmailDictionary = new Dictionary<string, object>();
confirmEmailDictionary.Add("user", user);
confirmEmailDictionary.Add("code", code);
KeyValuePair<string, object> confirmEmailValuePair = new KeyValuePair<string, object>("confirmEmail", confirmEmailDictionary);
IdentityResult result = (IdentityResult)await _accountRepository.Update(confirmEmailValuePair);
if (result.Succeeded)
{
TempData["emailconfirmed"] = "Thank you for confirming your email.";
RedirectToAction("Index", "Home");
}
else
{
TempData["emailconfirmerror"] = "Error confirming your email.";
RedirectToAction("Index", "Home");
}
return View();
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Models/ApplicationUser.cs
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Models
{
public class ApplicationUser : IdentityUser
{
/*IdentityUser has a number of properties some relevant ones are listed below
* Id
* UserName
* NormalizedUserName
* Email
* NormalizedEmail
* EmailConfirmed
* PasswordHash
* PhoneNumber
*/
[PersonalData]
[Required]
public String Forename { get; set; }
[PersonalData]
[Required]
public String Surname { get; set; }
[PersonalData]
[Required]
public String AddressLine1 { get; set; }
[PersonalData]
public String AddressLine2 { get; set; }
[PersonalData]
[Required]
[RegularExpression(@"([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2})",
ErrorMessage = "Postcode must match the standard UK postcode format.")] //Regex to match a valid UK postcode format found here: https://stackoverflow.com/questions/164979/regex-for-matching-uk-postcodes
public String Postcode { get; set; }
[PersonalData]
[Required]
public DateTime DateOfBirth { get; set; }
[Required]
[StringLength(16)]
public String LicenseNumber { get; set; }
[Required]
public bool Blacklisted { get; set; }
public String IdentificationFolderSource { get; set; }
public ApplicationUser()
{
}
public ApplicationUser(string Id, string UserName, string NormalizedUserName, string Email, string NormalizedEmail, bool EmailConfirmed, string PasswordHash, string PhoneNumber, string forename, string surname, string addressLine1, string addressLine2, string postcode, DateTime dateOfBirth)
{
this.Id = Id;
this.UserName = UserName;
this.NormalizedUserName = NormalizedUserName;
this.Email = Email;
this.NormalizedEmail = NormalizedEmail;
this.EmailConfirmed = EmailConfirmed;
this.PasswordHash = <PASSWORD>Hash;
this.PhoneNumber = PhoneNumber;
Forename = forename;
Surname = surname;
AddressLine1 = addressLine1;
AddressLine2 = addressLine2;
Postcode = postcode;
DateOfBirth = dateOfBirth;
}
}
}
<file_sep>/OOAE/T2/T2-01/wk2-01_TutProj/src/Source/DbSource.java
package Source;
import DTO.DeptDTO;
import Manager.DatabaseManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class DbSource implements Source
{
public DbSource(String username, String password)
{
DatabaseManager.getInstance().setUsername(username);
DatabaseManager.getInstance().setPassword(password);
}
@Override
public ArrayList<DeptDTO> getAllDepartments() throws SQLException
{
Connection connection = DatabaseManager.getInstance().getConnection();
ArrayList<DeptDTO> departments = new ArrayList<>();
PreparedStatement stmt = connection.prepareStatement("SELECT * from Dept");
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
DeptDTO department = new DeptDTO(rs.getInt("DEPTNO"), rs.getString("DNAME"), rs.getString("LOC"));
departments.add(department);
}
rs.close();
stmt.close();
connection.close();
return departments;
}
@Override
public boolean insertDepartment(DeptDTO dept) throws SQLException
{
boolean insertOK = false;
Connection connection = DatabaseManager.getInstance().getConnection();
PreparedStatement stmt = connection.prepareStatement("INSERT INTO Dept VALUES (?, ?, ?)");
stmt.setInt(1, dept.getDepartmentNumber());
stmt.setString(2, dept.getDepartmentName());
stmt.setString(3, dept.getDepartmentLocation());
int rows = stmt.executeUpdate();
insertOK = rows == 1;
stmt.close();
connection.close();
return insertOK;
}
@Override
public boolean deleteDepartment(DeptDTO dept) throws SQLException
{
try
{
Connection connection = DatabaseManager.getInstance().getConnection();
try
{
PreparedStatement stmt = connection.prepareStatement("DELETE FROM Dept WHERE deptno = ?");
stmt.setInt(1, dept.getDepartmentNumber());
stmt.executeUpdate();
stmt.close();
connection.close();
}
catch (SQLException sqle)
{
throw (sqle);
}
}
catch (SQLException sqle)
{
throw (sqle);
}
return true;
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ViewModels/UserProfileViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ViewModels
{
public class UserProfileViewModel
{
public bool IsPersonalProfile { get; set; }
public string UserId { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public string City { get; set; }
public bool IdentificationVerified { get; set; }
public bool AddressVerified { get; set; }
public bool DBSChecked { get; set; }
public bool BoardingLicenseVerified { get; set; }
public string Description { get; set; }
public int NumberOfRecommendations { get; set; }
public bool Carer { get; set; }
public string PhotoFolderSource { get; set; }
[Required]
public string EmailSubject { get; set; }
[Required]
public string EmailBody { get; set; }
public List<ReviewViewModel> Reviews { get; set; }
public List<ServiceRateViewModel> ServiceRates { get; set; }
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-war/src/java/managed_bean/ExpandedDeliveryViewBean.java
package managed_bean;
import dto.DeliveryDTO;
import ejb.User_UIRemote;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
/**
*
* @author Rhys
*/
@Named(value = "expandedDeliveryViewBean")
@SessionScoped
public class ExpandedDeliveryViewBean implements Serializable
{
private DeliveryDTO delivery;
@EJB
private User_UIRemote userUI;
public ExpandedDeliveryViewBean()
{
}
public String cancelDelivery()
{
boolean cancellationRequested = userUI.cancelDelivery(delivery.getDeliveryId());
if(cancellationRequested)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Cancellation requested for Delivery " + delivery.getDeliveryId()));
delivery = null;
return "Cancellation Requested";
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Cancellation request could not be processed"));
return "Cancellation Failed";
}
}
public DeliveryDTO getDelivery()
{
return delivery;
}
public void setDelivery(DeliveryDTO delivery)
{
this.delivery = delivery;
}
public String setDeliveryForExpansion(DeliveryDTO delivery)
{
setDelivery(delivery);
return "Expand Delivery";
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ViewModels/ViewUserBookingsViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels
{
public class ViewUserBookingsViewModel
{
public List<UserBookingsViewModel> UserBookingModels { get; set; }
}
}
<file_sep>/WMAD/CinemaBookingSystem/test/dto/ShowingDTOTest.java
package dto;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author <NAME>
*/
public class ShowingDTOTest
{
private ShowingDTO showing;
private FilmDTO film;
private ScreenDTO screen;
private CinemaDTO cinema;
private Date time;
public ShowingDTOTest()
{
time = new Date(2017 - 1900, 6, 24, 15, 30);
cinema = new CinemaDTO(0, "cineworld");
film = new FilmDTO(0, "title", 18, 120, "description");
screen = new ScreenDTO(0, cinema, "screenName");
showing = new ShowingDTO(0, film, screen, time, 20);
}
@BeforeClass
public static void setUpClass()
{
}
@AfterClass
public static void tearDownClass()
{
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
/**
* Test of getShowingID method, of class ShowingDTO.
*/
@Test
public void testGetShowingID()
{
System.out.println("getShowingID");
ShowingDTO instance = showing;
int expResult = 0;
int result = instance.getShowingID();
assertEquals(expResult, result);
}
/**
* Test of getFilm method, of class ShowingDTO.
*/
@Test
public void testGetFilm()
{
System.out.println("getFilm");
ShowingDTO instance = showing;
FilmDTO expResult = film;
FilmDTO result = instance.getFilm();
assertEquals(expResult, result);
}
/**
* Test of getScreen method, of class ShowingDTO.
*/
@Test
public void testGetScreen()
{
System.out.println("getScreen");
ShowingDTO instance = showing;
ScreenDTO expResult = screen;
ScreenDTO result = instance.getScreen();
assertEquals(expResult, result);
}
/**
* Test of getTime method, of class ShowingDTO.
*/
@Test
public void testGetTimeString()
{
System.out.println("getTime");
ShowingDTO instance = showing;
String expResult = "15:30";
String result = instance.getTime();
assertEquals(expResult, result);
}
/**
* Test of getAvailableSeats method, of class ShowingDTO.
*/
@Test
public void testGetAvailableSeats()
{
System.out.println("getAvailableSeats");
ShowingDTO instance = showing;
int expResult = 20;
int result = instance.getAvailableSeats();
assertEquals(expResult, result);
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ViewModels/UpdateVehicleComparisonSourceViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels
{
public class UpdateVehicleComparisonSourceViewModel
{
[Required]
public string VehicleComparisonSource { get; set; }
[Required]
public int VehicleId { get; set; }
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_Library/test/dto/DepotDTOIT.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import java.util.ArrayList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Rhys
*/
public class DepotDTOIT
{
private DepotDTO depotDTOInstance = new DepotDTO();
public DepotDTOIT()
{
ArrayList<DeliveryDTO> deliveryList = new ArrayList<DeliveryDTO>();
deliveryList.add(new DeliveryDTO());
ArrayList<RouteDTO> routeList = new ArrayList<RouteDTO>();
routeList.add(new RouteDTO());
depotDTOInstance.setDepotId(1);
depotDTOInstance.setName("Test Depot");
depotDTOInstance.setDepotDeliveries(deliveryList);
depotDTOInstance.setDepotRoutes(routeList);
}
@BeforeClass
public static void setUpClass()
{
}
@AfterClass
public static void tearDownClass()
{
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
/**
* Test of getDepotId method, of class DepotDTO.
*/
@Test
public void testGetDepotId()
{
System.out.println("getDepotId");
int expResult = 1;
int result = depotDTOInstance.getDepotId();
assertEquals(expResult, result);
}
/**
* Test of setDepotId method, of class DepotDTO.
*/
@Test
public void testSetDepotId()
{
System.out.println("setDepotId");
int depotId = 2;
depotDTOInstance.setDepotId(depotId);
assertEquals(depotDTOInstance.getDepotId(), 2);
}
/**
* Test of getName method, of class DepotDTO.
*/
@Test
public void testGetName()
{
System.out.println("getName");
String expResult = "Test Depot";
String result = depotDTOInstance.getName();
assertTrue(result.equals(expResult));
}
/**
* Test of setName method, of class DepotDTO.
*/
@Test
public void testSetName()
{
System.out.println("setName");
String name = "";
DepotDTO instance = new DepotDTO();
instance.setName(name);
assertTrue(instance.getName() != null);
}
/**
* Test of getDepotRoutes method, of class DepotDTO.
*/
@Test
public void testGetDepotRoutes()
{
System.out.println("getDepotRoutes");
int expResultCount = 1;
int resultCount = depotDTOInstance.getDepotRoutes().size();
assertTrue(depotDTOInstance.getDepotRoutes() != null);
assertEquals(resultCount, expResultCount);
}
/**
* Test of setDepotRoutes method, of class DepotDTO.
*/
@Test
public void testSetDepotRoutes()
{
System.out.println("setDepotRoutes");
ArrayList<RouteDTO> depotRoutes = new ArrayList<RouteDTO>();
depotDTOInstance.setDepotRoutes(depotRoutes);
assertTrue(depotDTOInstance.getDepotRoutes() != null);
}
/**
* Test of getDepotDeliveries method, of class DepotDTO.
*/
@Test
public void testGetDepotDeliveries()
{
System.out.println("getDepotDeliveries");
ArrayList<DeliveryDTO> result = depotDTOInstance.getDepotDeliveries();
assertTrue(depotDTOInstance.getDepotDeliveries().size() > 0);
assertTrue(depotDTOInstance.getDepotDeliveries() != null);
}
/**
* Test of setDepotDeliveries method, of class DepotDTO.
*/
@Test
public void testSetDepotDeliveries()
{
System.out.println("setDepotDeliveries");
ArrayList<DeliveryDTO> depotDeliveries = new ArrayList<DeliveryDTO>();
depotDTOInstance.setDepotDeliveries(depotDeliveries);
assertTrue(depotDTOInstance.getDepotDeliveries() != null);
}
}
<file_sep>/ESA/Flights Management/src/command/GetAllFlights.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package command;
import model.FlightHandler;
import view.AllFlightsView;
/**
*
* @author danpa
*/
public class GetAllFlights implements Command {
FlightHandler receiver;
public GetAllFlights(FlightHandler flightHandler) {
this.receiver = receiver;
}
public Object execute()
{
return receiver.findAllFlights();
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Controllers/VehicleController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Controllers
{
public class VehicleController : Controller
{
private readonly ApplicationDbContext DbContext;
private AddVehicleViewModel AddVehicleViewModel;
private UserManager<ApplicationUser> UserManager;
public VehicleController(ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager)
{
DbContext = dbContext;
UserManager = userManager;
}
[HttpGet]
public async Task<IActionResult> AddVehicle()
{
await AuthenticateUserLogin(true);
AddVehicleViewModel = new AddVehicleViewModel();
List<VehicleType> VehicleTypeList = await GetVehicleTypes();
List<Transmission> TransmissionList = await GetTransmissionTypes();
List<Fuel> FuelList = await GetFuelTypes();
ViewData["VehicleTypeList"] = new SelectList(VehicleTypeList, "Id", "Size");
ViewData["TransmissionList"] = new SelectList(TransmissionList, "Id", "Type");
ViewData["FuelList"] = new SelectList(FuelList, "Id", "Type");
return View(AddVehicleViewModel);
}
[HttpPost]
public async Task<IActionResult> AddVehicle(AddVehicleViewModel addVehicleViewModel)
{
await AuthenticateUserLogin(true);
bool imageUploadedSuccessfully = false;
string vehicleImageSource = "";
if(ModelState.IsValid)
{
imageUploadedSuccessfully = UploadVehicleImage(addVehicleViewModel.vehicleImageFile).Result;
if(imageUploadedSuccessfully)
{
vehicleImageSource = Path.GetFileName(addVehicleViewModel.vehicleImageFile.FileName);
Vehicle newVehicle = CreateNewVehicle(addVehicleViewModel, vehicleImageSource);
int vehicleAdded = (int)await CommandFactory.CreateCommand(CommandFactory.ADD_VEHICLE, newVehicle, DbContext).Execute();
if(vehicleAdded == 1)
{
TempData["successmessage"] = "Vehicle Added Successfully!";
return RedirectToAction("Index", "Home");
}
}
else
{
List<VehicleType> VehicleTypeList = await GetVehicleTypes();
List<Transmission> TransmissionList = await GetTransmissionTypes();
List<Fuel> FuelList = await GetFuelTypes();
ViewData["VehicleTypeList"] = new SelectList(VehicleTypeList, "Id", "Size");
ViewData["TransmissionList"] = new SelectList(TransmissionList, "Id", "Type");
ViewData["FuelList"] = new SelectList(FuelList, "Id", "Type");
TempData["errormessage"] = "Failed to add vehicle. Please try again!";
return View(addVehicleViewModel);
}
return View();
}
else
{
List<VehicleType> VehicleTypeList = await GetVehicleTypes();
List<Transmission> TransmissionList = await GetTransmissionTypes();
List<Fuel> FuelList = await GetFuelTypes();
ViewData["VehicleTypeList"] = new SelectList(VehicleTypeList, "Id", "Size");
ViewData["TransmissionList"] = new SelectList(TransmissionList, "Id", "Type");
ViewData["FuelList"] = new SelectList(FuelList, "Id", "Type");
TempData["errormessage"] = "Vehicle data is invalid. Please try again!";
return View(addVehicleViewModel);
}
}
public async Task<IActionResult> AuthenticateUserLogin(bool adminRequired)
{
ApplicationUser CurrentUser = await UserManager.GetUserAsync(HttpContext.User);
bool IsAdmin = await UserManager.IsInRoleAsync(CurrentUser, "Admin");
if (CurrentUser == null)
{
TempData["errormessage"] = "You need to be logged in to book a vehicle." + Environment.NewLine + " If you do not have an account, please navigate to the registration page by clicking on 'Register' at the top of the screen.";
return RedirectToAction("Login", "Account");
}
if (adminRequired && IsAdmin == false)
{
TempData["errormessage"] = "You require admin privileges to view that page.";
return RedirectToAction("Index", "Home");
}
else return null;
}
public async Task<bool> UploadVehicleImage(IFormFile vehicleImageFile)
{
string fileName = "";
string filePath = "";
fileName = Path.GetFileName(vehicleImageFile.FileName);
filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Images\Vehicles", fileName);
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
await vehicleImageFile.CopyToAsync(fileStream);
}
return true;
}
catch(Exception e)
{
TempData["errormessage"] = "Image failed to upload. Please try again!";
return false;
}
}
public Vehicle CreateNewVehicle(AddVehicleViewModel addVehicleViewModel, string VehicleImageSource)
{
Vehicle newVehicle = new Vehicle();
newVehicle.Manufacturer = addVehicleViewModel.Manufacturer;
newVehicle.Model = addVehicleViewModel.Model;
newVehicle.Doors = addVehicleViewModel.Doors;
newVehicle.Seats = addVehicleViewModel.Seats;
newVehicle.Colour = addVehicleViewModel.Colour;
newVehicle.CostPerDay = addVehicleViewModel.CostPerDay;
newVehicle.VehicleType = new VehicleType() { Id = addVehicleViewModel.VehicleTypeId };
newVehicle.Fuel = new Fuel() { Id = addVehicleViewModel.FuelId };
newVehicle.Transmission = new Transmission() { Id = addVehicleViewModel.TransmissionId };
newVehicle.VehicleImageSource = VehicleImageSource;
return newVehicle;
}
public async Task<List<VehicleType>> GetVehicleTypes()
{
return (List<VehicleType>)await CommandFactory.CreateCommand(CommandFactory.GET_VEHICLE_TYPES, DbContext).Execute();
}
public async Task<List<Fuel>> GetFuelTypes()
{
return (List<Fuel>)await CommandFactory.CreateCommand(CommandFactory.GET_FUEL_TYPES, DbContext).Execute();
}
public async Task<List<Transmission>> GetTransmissionTypes()
{
return (List<Transmission>)await CommandFactory.CreateCommand(CommandFactory.GET_TRANSMISSION_TYPES, DbContext).Execute();
}
}
}<file_sep>/WMAD/CinemaBookingSystem/src/java/adminUI/LoginAdminCommand.java
package adminUI;
import handler.AdminHandler;
/**
*
* @author Rhysj
*/
public class LoginAdminCommand implements AdminCommand
{
private final String username;
private final String password;
private AdminHandler adminHndlr = null;
public LoginAdminCommand(String username, String password)
{
this.username = username;
this.password = <PASSWORD>;
adminHndlr = AdminHandler.getInstance();
}
@Override
public Object execute()
{
return adminHndlr.checkAdminCredentials(username, password);
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/GetInsuranceFraudDataCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class GetInsuranceFraudDataCommand : ICommand
{
private AccessDbHandler AccessDbHandler;
public GetInsuranceFraudDataCommand()
{
AccessDbHandler = new AccessDbHandler();
}
public async Task<object> Execute()
{
return AccessDbHandler.GetInsuranceFraudData();
}
}
}
<file_sep>/WMAD/CinemaBookingSystem/src/java/dto/ScreenDTO.java
package dto;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author <NAME>
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ScreenDTO implements Serializable
{
private int screenID;
private CinemaDTO cinema;
private String screenName;
ScreenDTO()
{
this.screenID = 0;
this.cinema = new CinemaDTO();
this.screenName = "";
}
/**
*
* @param screenID
* @param cinema
* @param screenName
*/
public ScreenDTO(int screenID, CinemaDTO cinema, String screenName)
{
this.screenID = screenID;
this.cinema = cinema;
this.screenName = screenName;
}
public int getScreenID()
{
return screenID;
}
public CinemaDTO getCinema()
{
return cinema;
}
public String getScreenName()
{
return screenName;
}
}
<file_sep>/OOAE/T2/T2-01/wk2-01_TutProj/src/Source/Source.java
package Source;
import DTO.DeptDTO;
import java.util.ArrayList;
public interface Source
{
public ArrayList<DeptDTO> getAllDepartments() throws Exception;
public boolean insertDepartment(DeptDTO dept) throws Exception;
public boolean deleteDepartment(DeptDTO dept) throws Exception;
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/BlacklistUserCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class BlacklistUserCommand : ICommand
{
private UserHandler UserHandler;
private string UserId;
public BlacklistUserCommand(string userId, ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager)
{
UserId = userId;
UserHandler = new UserHandler(userManager, dbContext);
}
public async Task<object> Execute()
{
return await UserHandler.BlacklistUser(UserId);
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/GetDatesCommand.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WPFDataParallelismProj.DTO;
using WPFDataParallelismProj.Handler;
namespace WPFDataParallelismProj.CommandsFactory
{
internal class GetDatesCommand : ICommand
{
private HashSet<Order> orders;
private DateHandler dateHandler;
public GetDatesCommand(HashSet<Order> orders)
{
this.orders = orders;
dateHandler = new DateHandler();
}
public async Task<object> Execute()
{
return await dateHandler.GetDates(orders);
}
}
}<file_sep>/ESA/Flights Management/src/model/PassengerRisk.java
package model;
import builder.FlightBuilder;
import builder.PassengerBuilder;
import builder.PassengerRisk_ByFlightBuilder;
import builder.RiskBuilder;
import database.DatabaseConnectionPool;
import database.PassengerRisk_ByFlight;
import database.Risk;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author Krzychu-x
*/
public class PassengerRisk
{
private static final String FIND_ALL = "SELECT * FROM Passenger_Risk LEFT JOIN Risk ON Passenger_Risk.Risk_ID = Risk.Risk_ID JOIN Passenger ON Passenger.Passenger_ID = Passenger_Risk.Passenger_ID JOIN Booking ON Booking.Passenger_ID = Passenger.Passenger_ID JOIN Seat ON Seat.Seat_ID = Booking.Seat_ID ORDER BY Passenger.Passenger_ID, Risk.Risk_ID";
//private static final String FIND_ALL_WITH_MIN = "SELECT * FROM Passenger_Risk LEFT JOIN Risk ON Passenger_Risk.Risk_ID = Risk.Risk_ID JOIN Passenger ON Passenger.Passenger_ID = Passenger_Risk.Passenger_ID JOIN Booking ON Booking.Passenger_ID = Passenger.Passenger_ID JOIN Seat ON Seat.Seat_ID = Booking.Seat_ID where RISK_SCORE > ? ORDER BY Passenger.Passenger_ID, Risk.Risk_ID";
private static final String FIND_ALL_RISKS = "SELECT * FROM RISK";
private static final String FIND_RISKS_WITH_TYPE = "SELECT * FROM Passenger_Risk LEFT JOIN Risk ON Passenger_Risk.Risk_ID = Risk.Risk_ID JOIN Passenger ON Passenger.Passenger_ID = Passenger_Risk.Passenger_ID JOIN Booking ON Booking.Passenger_ID = Passenger.Passenger_ID JOIN Seat ON Seat.Seat_ID = Booking.Seat_ID WHERE passenger_Risk.RISK_ID =? ORDER BY Passenger.Passenger_ID, Risk.Risk_ID";
public ArrayList<Risk> getRisks()
{
ArrayList<Risk> list = new ArrayList();
RiskBuilder riskBuilder = null;
DatabaseConnectionPool pool = DatabaseConnectionPool.getInstance();
Connection con = pool.getAvailableConnection();
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try
{
preparedStatement = con.prepareStatement(FIND_ALL_RISKS);
rs = preparedStatement.executeQuery();
while (rs.next())
{
riskBuilder = new RiskBuilder()
.withRiskID(rs.getInt("RISK_ID"))
.withRiskFactor(rs.getString("RISK_DESC"))
.withRiskScore(rs.getInt("RISK_SCORE"));
list.add(riskBuilder.build());
}
rs.close();
preparedStatement.close();
pool.returnConnection(con);
return list;
}
catch (SQLException sqle)
{
sqle.printStackTrace(System.err);
return list;
}
}
public ArrayList<PassengerRisk_ByFlight> findAllPassengersWithRiskType(int type)
{
ArrayList<PassengerRisk_ByFlight> list = new ArrayList<>();
int oldPassengerID_No = -1;
PassengerRisk_ByFlightBuilder riskBuilder = null;
PassengerBuilder passengerBuilder = null;
FlightBuilder flightBuilder = null;
DatabaseConnectionPool pool = DatabaseConnectionPool.getInstance();
Connection con = pool.getAvailableConnection();
try
{
PreparedStatement preparedStatement = null;
ResultSet rs = null;
preparedStatement = con.prepareStatement(FIND_RISKS_WITH_TYPE);
preparedStatement.setInt(1, type + 1);
rs = preparedStatement.executeQuery();
while (rs.next())
{
int passengerID = rs.getInt("Passenger_ID");
String passengerForname = rs.getString("FORENAME");
String passengerSurname = rs.getString("Surname");
int flightID = rs.getInt("Flight_ID");
if (passengerID != oldPassengerID_No)
{
if (riskBuilder != null)
{
list.add(riskBuilder.build());
}
passengerBuilder = new PassengerBuilder();
passengerBuilder.setPID(passengerID);
passengerBuilder.setPForename(passengerForname);
passengerBuilder.setPSurname(passengerSurname);
flightBuilder = new FlightBuilder();
flightBuilder.withID(flightID);
riskBuilder = new PassengerRisk_ByFlightBuilder()
.withPassID(passengerBuilder.build())
.withFlightID(flightBuilder.build());
oldPassengerID_No = passengerID;
}
int riskID = rs.getInt("risk_ID");
if (riskID > 0)
{
riskBuilder.withRisks(new RiskBuilder()
.withRiskID(riskID)
.withRiskFactor(rs.getString("RISK_DESC"))
.withRiskScore(rs.getInt("Risk_Score"))
.build());
}
}
if (riskBuilder != null)
{
list.add(riskBuilder.build());
}
rs.close();
preparedStatement.close();
pool.returnConnection(con);
return list;
}
catch (SQLException sqle)
{
sqle.printStackTrace(System.err);
return list;
}
}
public ArrayList<PassengerRisk_ByFlight> findAllPassengersRisks(int min)
{
ArrayList<PassengerRisk_ByFlight> list = new ArrayList<>();
int oldPassengerID_No = -1;
PassengerRisk_ByFlightBuilder riskBuilder = null;
PassengerBuilder passengerBuilder = null;
FlightBuilder flightBuilder = null;
DatabaseConnectionPool pool = DatabaseConnectionPool.getInstance();
Connection con = pool.getAvailableConnection();
try
{
PreparedStatement preparedStatement = null;
ResultSet rs = null;
preparedStatement = con.prepareStatement(FIND_ALL);
rs = preparedStatement.executeQuery();
while (rs.next())
{
int passengerID = rs.getInt("Passenger_ID");
String passengerForname = rs.getString("FORENAME");
String passengerSurname = rs.getString("Surname");
int flightID = rs.getInt("Flight_ID");
if (passengerID != oldPassengerID_No)
{
if (riskBuilder != null)
{
if (riskBuilder.build().getTotalRiskScore() >= min)
{
list.add(riskBuilder.build());
}
}
passengerBuilder = new PassengerBuilder();
passengerBuilder.setPID(passengerID);
passengerBuilder.setPForename(passengerForname);
passengerBuilder.setPSurname(passengerSurname);
flightBuilder = new FlightBuilder();
flightBuilder.withID(flightID);
riskBuilder = new PassengerRisk_ByFlightBuilder()
.withPassID(passengerBuilder.build())
.withFlightID(flightBuilder.build());
oldPassengerID_No = passengerID;
}
int riskID = rs.getInt("risk_ID");
if (riskID > 0)
{
riskBuilder.withRisks(new RiskBuilder()
.withRiskID(riskID)
.withRiskFactor(rs.getString("RISK_DESC"))
.withRiskScore(rs.getInt("Risk_Score"))
.build());
}
}
if (riskBuilder != null)
{
if (riskBuilder.build().getTotalRiskScore() >= min)
{
list.add(riskBuilder.build());
}
}
rs.close();
preparedStatement.close();
pool.returnConnection(con);
return list;
}
catch (SQLException sqle)
{
sqle.printStackTrace(System.err);
return list;
}
}
}
<file_sep>/OOAE/T1/T1-09/cardDeckProj/src/carddeckproj/DisplayableHand.java
package carddeckproj;
import java.awt.*;
import javax.swing.*;
public class DisplayableHand extends Hand implements Displayable
{
private Image image;
@Override
public void display(Graphics g, int x, int y)
{
for (int i = 0; i<theCards.length; i++)
{
image = new ImageIcon(getClass().getResource("/images/" + getCardNumber(theCards[i]) + ".png")).getImage();
g.drawImage(image, (i*75 + x), y, null);
}
}
private int getCardNumber(Card card)
{
return (card.getSuit().ordinal() * 13) + card.getRank().ordinal();
}
}
<file_sep>/WMAD/WMAD_assignment_2/app/src/main/java/com/example/rhysj/wmad_assignment_2/NavigationSlider.java
package com.example.rhysj.wmad_assignment_2;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import com.example.rhysj.wmad_assignment_2.DTO.UserDTO;
/**
* Created by <NAME> on 27/02/2018.
*/
public class NavigationSlider implements NavigationView.OnNavigationItemSelectedListener, DrawerLayout.DrawerListener
{
private AppCompatActivity mActivity;
public NavigationSlider(AppCompatActivity activity)
{
mActivity = activity;
//Top bar object
Toolbar toolbar = (Toolbar) mActivity.findViewById(R.id.toolbar);
//AppCompat method
mActivity.setSupportActionBar(toolbar);
//Navigation View screen object
DrawerLayout drawer = (DrawerLayout) mActivity.findViewById(R.id.drawer_layout);
//Sets toggle for navigation drawer
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(mActivity, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
onDrawerOpened(drawer); //Call drawerOpened to make it appear smoother.
//Adds toggle to the drawer listener
drawer.addDrawerListener(toggle);
drawer.addDrawerListener(this);
//Checks the state of the drawer (open or closed) and sets "VerticalMirror" to true or false.
toggle.syncState();
//Creates navigation view
NavigationView navigationView = (NavigationView) mActivity.findViewById(R.id.nav_view);
//Listens for when a navigation button is pressed.
navigationView.setNavigationItemSelectedListener(this);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item)
{
// Handle navigation view item clicks here.
int id = item.getItemId();
String currentActivity = mActivity.getClass().getSimpleName();
if (id == R.id.nav_login)
{
if(!currentActivity.equals("LoginActivity"))
{
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent);
}
}
else if (id == R.id.nav_register)
{
if (!currentActivity.equals("RegisterActivity"))
{
Intent intent = new Intent(mActivity, RegisterActivity.class);
mActivity.startActivity(intent);
}
}
else if (id == R.id.nav_logout)
{
SharedPreferencesHandler.getInstance(mActivity).logout();
if (!currentActivity.equals("MainActivity"))
{
Intent intent = new Intent(mActivity, MainActivity.class);
mActivity.startActivity(intent);
}
}
else if (id == R.id.nav_view_cinemas)
{
if (!currentActivity.equals("MainActivity"))
{
Intent intent = new Intent(mActivity, MainActivity.class);
mActivity.startActivity(intent);
}
}
else if (id == R.id.nav_update_account)
{
if (!currentActivity.equals("UpdateAccountActivity"))
{
Intent intent = new Intent(mActivity, UpdateAccountActivity.class);
mActivity.startActivity(intent);
}
}
else if (id == R.id.nav_view_bookings)
{
if(!currentActivity.equals("ViewBookingsActivity"))
{
Intent intent = new Intent(mActivity, ViewBookingsActivity.class);
mActivity.startActivity(intent);
}
}
else if (id == R.id.nav_add_film)
{
}
else if (id == R.id.nav_view_films)
{
}
DrawerLayout drawer = (DrawerLayout) mActivity.findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public boolean backPressed()
{
DrawerLayout drawer = (DrawerLayout) mActivity.findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
return true;
}
else
{
return false;
}
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
//Not used
}
@Override
public void onDrawerOpened(View drawerView)
{
NavigationView navView = mActivity.findViewById(R.id.nav_view);
if(SharedPreferencesHandler.getInstance(drawerView.getContext()).isUserLoggedIn())
{
UserDTO loggedUser = SharedPreferencesHandler.getInstance(drawerView.getContext()).getLoggedInUser();
//Check credentials to set visible for relevant nav menu items.
if (!loggedUser.isIsAdmin())
{
navView.getMenu().findItem(R.id.nav_login).setVisible(false);
navView.getMenu().findItem(R.id.nav_register).setVisible(false);
navView.getMenu().findItem(R.id.nav_update_account).setVisible(true);
navView.getMenu().findItem(R.id.nav_logout).setVisible(true);
navView.getMenu().findItem(R.id.nav_add_film).setVisible(false);
navView.getMenu().findItem(R.id.nav_view_films).setVisible(false);
navView.getMenu().findItem(R.id.nav_view_bookings).setVisible(false);
navView.getMenu().findItem(R.id.nav_view_cinemas).setVisible(true);
}
else if(loggedUser.isIsAdmin())
{
navView.getMenu().findItem(R.id.nav_login).setVisible(false);
navView.getMenu().findItem(R.id.nav_register).setVisible(false);
navView.getMenu().findItem(R.id.nav_update_account).setVisible(false);
navView.getMenu().findItem(R.id.nav_logout).setVisible(true);
navView.getMenu().findItem(R.id.nav_add_film).setVisible(true);
navView.getMenu().findItem(R.id.nav_view_films).setVisible(true);
navView.getMenu().findItem(R.id.nav_view_bookings).setVisible(true);
navView.getMenu().findItem(R.id.nav_view_cinemas).setVisible(true);
}
}
else
{
navView.getMenu().findItem(R.id.nav_login).setVisible(true);
navView.getMenu().findItem(R.id.nav_register).setVisible(true);
navView.getMenu().findItem(R.id.nav_update_account).setVisible(false);
navView.getMenu().findItem(R.id.nav_logout).setVisible(false);
navView.getMenu().findItem(R.id.nav_add_film).setVisible(false);
navView.getMenu().findItem(R.id.nav_view_films).setVisible(false);
navView.getMenu().findItem(R.id.nav_view_bookings).setVisible(false);
navView.getMenu().findItem(R.id.nav_view_cinemas).setVisible(true);
}
}
@Override
public void onDrawerClosed(View drawerView)
{
//Not used
}
@Override
public void onDrawerStateChanged(int newState)
{
//Not used
}
}
<file_sep>/OOAE/T1/T1-10 Portfolio needed/UsingThreadsProj/src/usingthreadsproj/UsingThreadsProj.java
package usingthreadsproj;
import java.util.ArrayList;
public class UsingThreadsProj
{
public static void main(String[] args)
{
ArrayList<Message> msgs = new ArrayList<Message>();
msgs.add(new Message("Hello world", 2));
msgs.add(new Message("Goodbye world", 3));
msgs.add(new Message("Help!", 5));
printMessages(msgs);
}
public static void printMessages(ArrayList<Message> msgs)
{
for (Message m : msgs)
{
m.start();
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ViewModels/BookVehicleViewModel.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels
{
public class BookVehicleViewModel
{
[Required]
public int ChosenVehicleId { get; set; }
[Required]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[Required]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[DataType(DataType.Date)]
public DateTime EndDate { get; set; }
[Required]
public Boolean StartHalfDay { get; set; }
[Required]
public Boolean EndHalfDay { get; set; }
[Required]
public string UserId { get; set; }
[Required]
public decimal TotalCost { get; set; }
public List<EquipmentCheckboxSelectViewModel> ChosenEquipmentList { get; set; }
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/database/UserGatewayLocal.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package database;
import dto.UserDTO;
import entity.Users;
import javax.ejb.Local;
/**
*
* @author Rhys
*/
@Local
public interface UserGatewayLocal
{
UserDTO login(String email, String password);
boolean registerNewUser(UserDTO registeringUserDTO);
UserDTO updateAccountDetails(UserDTO user, String oldPassword, String oldEmail);
boolean deleteAccount(UserDTO user);
UserDTO assignRouteToDriver(UserDTO user, int routeId);
}
<file_sep>/OOAE/T2/T2-03/AuctionTemplatePatternProj/src/AuctionItem/Jewellery.java
package AuctionItem;
/**
* Determines VAT and Commission rates for Jewellery and calculates the cost a
* buyer will pay, and the amount a seller will receive.
* @author <NAME>
*/
public class Jewellery extends AuctionItem
{
private final double VAT = 0.2;
private final double commission = 0.25;
/**
* Constructs Jewellery Object and sets the item description.
*
* @param description
*/
public Jewellery(String description)
{
super.description = description;
}
/**
* Calculates the cost a buyer will pay for an item of Jewellery after VAT.
*
* @param hammerPrice
* @return
*/
@Override
public double calculateCostBuyerPaid(double hammerPrice)
{
return (hammerPrice * VAT);
}
/**
* Calculates the amount a seller will receive for an item of Jewellery after
* commission.
*
* @param hammerPrice
* @return
*/
@Override
public double calculateAmountSellerReceived(double hammerPrice)
{
return (hammerPrice * commission);
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ViewModels/LoginViewModel.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace AnimalCareSystem.ViewModels
{
public class LoginViewModel
{
[Required, EmailAddress]
public String Email { get; set; }
[Required]
[DataType(DataType.Password)]
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$",
ErrorMessage = "Incorrect Password.")] //Regex Source: https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a.
public String Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
}
<file_sep>/CNA/SimpleClientServer/Packet/BuyProductPacket.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Packets
{
[Serializable]
public class BuyProductPacket : Packet
{
public String productType { get; protected set; }
public BuyProductPacket(String productType)
{
this.type = PacketType.BUYPRODUCT;
this.productType = productType;
}
}
}
<file_sep>/ESA/Flights Management/src/command/GetAllPassengersRisksWIthMin.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package command;
import model.PassengerRisk;
import view.AllPassengersRiskView;
/**
*
* @author danpa
*/
public class GetAllPassengersRisksWIthMin implements Command
{
PassengerRisk receiver;
int riskScore;
public GetAllPassengersRisksWIthMin(PassengerRisk receiver, int riskScore)
{
this.receiver = receiver;
this.riskScore = riskScore;
}
@Override
public Object execute()
{
return new AllPassengersRiskView(receiver.findAllPassengersRisks(riskScore)).print();
}
}
<file_sep>/WMAD/CinemaBookingSystem/nbproject/private/private.properties
deploy.ant.properties.file=C:\\Users\\J016984c\\AppData\\Roaming\\NetBeans\\8.2\\config\\GlassFishEE6\\Properties\\gfv3-554285369.properties
file.reference.derbyclient.jar=C:\\Program Files (x86)\\java\\jdk8\\db\\lib\\derbyclient.jar
j2ee.platform.is.jsr109=true
j2ee.server.domain=E:/UNI-LEVEL 5/WMAD/T2/WMAD Assignment 2 - J016984C/java/glassfish_4dot1/glassfish/domains/domain1
j2ee.server.home=E:/UNI-LEVEL 5/WMAD/T2/WMAD Assignment 2 - J016984C/java/glassfish_4dot1/glassfish
j2ee.server.instance=[E:\\UNI-LEVEL 5\\WMAD\\T2\\WMAD Assignment 2 - J016984C\\java\\glassfish_4dot1\\glassfish;E:\\UNI-LEVEL 5\\WMAD\\T2\\WMAD Assignment 2 - J016984C\\java\\glassfish_4dot1\\glassfish\\domains\\domain1]deployer:gfv3ee6wc:localhost:4848
j2ee.server.middleware=E:/UNI-LEVEL 5/WMAD/T2/WMAD Assignment 2 - J016984C/java/glassfish_4dot1
javac.debug=true
javadoc.preview=true
selected.browser=Chrome
user.properties.file=C:\\Users\\J016984c\\AppData\\Roaming\\NetBeans\\8.2\\build.properties
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/DataParallelismProj/CommandsFactory/LoadDataCommand.cs
using DataParallelismProj.Handler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataParallelismProj.CommandsFactory
{
class LoadDataCommand : ICommand
{
FileHandler fileHandler;
string selectedFolderPath;
public LoadDataCommand(string selectedFolderPath)
{
this.fileHandler = new FileHandler();
this.selectedFolderPath = selectedFolderPath;
}
public object Execute()
{
return fileHandler.LoadOrders(selectedFolderPath);
}
}
}
<file_sep>/WMAD/CinemaBookingSystem/src/java/adminUI/GetAllBookingsCommand.java
package adminUI;
import handler.BookingHandler;
/**
*
* @author <NAME>
*/
public class GetAllBookingsCommand implements AdminCommand
{
BookingHandler bookHndlr = null;
public GetAllBookingsCommand()
{
bookHndlr = BookingHandler.getInstance();
}
@Override
public Object execute()
{
return bookHndlr.getAllBookings();
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ScreenScraper/PriceMatchScraper.cs
using IronWebScraper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ScreenScraper
{
public class PriceMatchScraper : WebScraper
{
private string PriceMatchUrl;
public string PriceString;
public PriceMatchScraper(string priceMatchUrl)
{
PriceMatchUrl = priceMatchUrl;
}
public override void Init()
{
License.LicenseKey = "LicenseKey";
this.LoggingLevel = WebScraper.LogLevel.All;
string workingDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Files\\ScrapedPriceData");
this.WorkingDirectory = workingDirectory;
this.Request(PriceMatchUrl, Parse);
}
public override void Parse(Response response)
{
foreach (var itemPrice in response.Css("[title~=GBP]"))
{
PriceString = itemPrice.TextContentClean;
}
}
}
}
<file_sep>/OOAE/T1/T1-05/LB05_02/src/lb05_02/LB05_02.java
package lb05_02;
public class LB05_02
{
public static void main(String[] args)
{
//countToTen();
System.out.println("");
countToTenFail();
}
public static void countToTen()
{
for (int i = 0; i < 10; i++)
{
if (i < 10)
{
System.out.println(i + 1);
}
else
{
assert (i < 10) : "Number is: " + i;
}
}
}
public static void countToTenFail()
{
for (int i = 0; i <= 11; i++)
{
if (i < 10)
{
System.out.println(i + 1);
}
else
{
assert ((i+1) < 10) : "Number is: " + (i+1);
}
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/GetVehiclesCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class GetVehiclesCommand : ICommand
{
private VehicleHandler VehicleHandler;
public GetVehiclesCommand(ApplicationDbContext dbContext)
{
VehicleHandler = new VehicleHandler(dbContext);
}
public async Task<object> Execute()
{
return await VehicleHandler.GetVehicles();
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/GetAllBookingsForVehicleCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class GetAllBookingsForVehicleCommand : ICommand
{
long VehiclId;
private BookingHandler BookingHandler;
public GetAllBookingsForVehicleCommand(long vehicleId, ApplicationDbContext dbContext)
{
VehiclId = vehicleId;
BookingHandler = new BookingHandler(dbContext);
}
public async Task<object> Execute()
{
return await BookingHandler.GetAllBookingsForVehicle(VehiclId);
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ApplicationUI/ConfirmEmailCommand.cs
using AnimalCareSystem.Handlers;
using AnimalCareSystem.Models;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ApplicationUI
{
public class ConfirmEmailCommand : ICommand
{
private ApplicationUser User;
private string ConfirmationCode;
private AccountHandler AccountHandler;
public ConfirmEmailCommand(ApplicationUser user, string confirmationCode, UserManager<ApplicationUser> userManager)
{
User = user;
ConfirmationCode = confirmationCode;
AccountHandler = new AccountHandler(userManager);
}
public async Task<object> Execute()
{
return await AccountHandler.ConfirmEmail(User, ConfirmationCode);
}
}
}
<file_sep>/ESA/Flights Management/test/model/FlightHandlerTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import database.Flight;
import database.Plane;
import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Krzychu
*/
public class FlightHandlerTest {
public FlightHandlerTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of findAllFlights method, of class FlightHandler.
*/
// @Test
// public void testFindAllFlights() {
// System.out.println("findAllFlights");
// FlightHandler instance1 = new FlightHandler();
// FlightHandler instance2 = new FlightHandler();
// ArrayList<Flight> expResult = instance2.findAllFlights();
// ArrayList<Flight> result = instance1.findAllFlights();
// assertEquals(expResult, result);
//
// }
/**
* Test of addNewFlight method, of class FlightHandler.
*/
@Test
public void testAddNewFlight() {
System.out.println("addNewFlight");
int planeID = 11;
String Destination = "test1";
String Origin = "test2";
Date departureDate = null;
Time departureTime = null;
Date arrivalDate = null;
Time arrivalTime = null;
Plane plane = new Plane();
Flight flight = new Flight(1, 2, Destination, Origin, departureDate, departureTime, arrivalDate, arrivalTime, plane);
FlightHandler instance = new FlightHandler();
boolean result = instance.addNewFlight(flight);
assertTrue(result);
}
/**
* Test of addNewPlane method, of class FlightHandler.
*/
@Test
public void testAddNewPlane() {
System.out.println("addNewPlane");
String designation = "test1";
int capacity = 0;
int planeID = 2;
String airline = "test2";
String equipment = "test3";
Plane plane = new Plane(planeID, designation, capacity, airline, equipment);
FlightHandler instance = new FlightHandler();
boolean result = instance.addNewPlane(plane);
assertTrue(result);
}
/**
* Test of addNewSeat method, of class FlightHandler.
*/
@Test
public void testAddNewSeat() {
System.out.println("addNewSeat");
int flightID = 1;
int seatNumber = 4;
boolean seatTaken = true;
FlightHandler instance = new FlightHandler();
boolean result = instance.addNewSeat(flightID, seatNumber, seatTaken);
assertTrue(result);
}
}<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/GetStoresCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFDataParallelismProj.DTO;
using WPFDataParallelismProj.Handler;
namespace WPFDataParallelismProj.CommandsFactory
{
class GetStoresCommand : ICommand
{
private StoreHandler storeHandler;
private HashSet<Order> orders;
public GetStoresCommand(HashSet<Order> orders)
{
this.orders = orders;
storeHandler = new StoreHandler();
}
public async Task<object> Execute()
{
return await storeHandler.GetStores(orders);
}
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Controllers/SearchController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AnimalCareSystem.Data;
using AnimalCareSystem.Models;
using AnimalCareSystem.Repositories;
using AnimalCareSystem.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace AnimalCareSystem.Controllers
{
[Route("search")]
public class SearchController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ApplicationDbContext _dbContext;
private readonly SearchRepository _searchRepository;
public SearchController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ApplicationDbContext dbContext)
{
_userManager = userManager;
_signInManager = signInManager;
_dbContext = dbContext;
_searchRepository = new SearchRepository(userManager, signInManager, dbContext);
}
[HttpGet]
public IActionResult UserSearch()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult UserSearch([Bind("City")] UserSearchViewModel userSearchViewModel)
{
if (ModelState.IsValid)
{
return RedirectToAction("UserSearchResults", "search", userSearchViewModel);
}
return View();
}
[HttpGet, Route("/results")]
public async Task<IActionResult> UserSearchResults([FromQuery(Name = "City")] string city)
{
UserSearchViewModel userSearchViewModel = new UserSearchViewModel();
userSearchViewModel.City = city;
KeyValuePair<string, object> userSearchKeyValuePair = new KeyValuePair<string, object>("userSearchResults", userSearchViewModel);
UserSearchResultsListViewModel userSearchResultsListViewModel = (UserSearchResultsListViewModel)await _searchRepository.Get(userSearchKeyValuePair);
return View(userSearchResultsListViewModel);
}
}
}
<file_sep>/OOAE/T1/T1-08/WrapperClassProj/src/wrapperclassproj/WrapperClassProj.java
package wrapperclassproj;
import java.util.ArrayList;
import java.util.Scanner;
public class WrapperClassProj
{
static Scanner kybd = new Scanner(System.in);
public static void main(String[] args)
{
ArrayList<Double> numbers = new ArrayList(5);
System.out.print("Please enter 5 doubles:> ");
for(int i=0; i < 5; i++)
{
numbers.add(numberInput());
}
printDoublesBackwards(numbers);
}
public static double numberInput()
{
Double input;
input = kybd.nextDouble();
kybd.nextLine();
return input;
}
public static void printDoublesBackwards(ArrayList<Double> numbers)
{
System.out.println("\nPrinting the doubles backwards!" +
"\n===============================");
for (int i = 4; i >= 0; i--)
{
System.out.println(numbers.get(i));
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Controllers/PriceMatchController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.ScreenScraper;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace EIRLSS_Assignment2_J016984C_Rhys_Jones.Controllers
{
public class PriceMatchController : Controller
{
private readonly ApplicationDbContext DbContext;
private UserManager<ApplicationUser> UserManager;
public PriceMatchController(ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager)
{
DbContext = dbContext;
UserManager = userManager;
}
[HttpGet]
public async Task<IActionResult> UpdateVehicleComparisonSource(long? id)
{
await AuthenticateUserLogin(true);
UpdateVehicleComparisonSourceViewModel updateVehicleComparisonSourceViewModel = new UpdateVehicleComparisonSourceViewModel();
updateVehicleComparisonSourceViewModel.VehicleId = (int)id;
return View(updateVehicleComparisonSourceViewModel);
}
[HttpPost]
public async Task<IActionResult> UpdateVehicleComparisonSource(UpdateVehicleComparisonSourceViewModel updateVehicleComparisonSourceViewModel)
{
await AuthenticateUserLogin(true);
int vehicleId = updateVehicleComparisonSourceViewModel.VehicleId;
string vehicleComparisonSourceString = updateVehicleComparisonSourceViewModel.VehicleComparisonSource;
int sourceUpdated = (int)await CommandFactory.CreateCommand(CommandFactory.UPDATE_VEHICLE_COMPARISON_SOURCE, DbContext, vehicleId, vehicleComparisonSourceString).Execute();
if(sourceUpdated < 1)
{
TempData["errormessage"] = "Failed to update. Please try again!";
return View(updateVehicleComparisonSourceViewModel);
}
else
{
TempData["successmessage"] = "Comparison Source Updated Successfully!";
return RedirectToAction("Index", "Home");
}
}
[HttpGet]
public async Task<IActionResult> PriceMatch()
{
await AuthenticateUserLogin(true);
PriceMatchViewModel priceMatchViewModel = new PriceMatchViewModel();
priceMatchViewModel.PriceMatchVehicles = new List<PriceMatchVehiclesViewModel>();
List<Vehicle> vehicles = (List<Vehicle>)await CommandFactory.CreateCommand(CommandFactory.GET_VEHICLES, DbContext).Execute();
foreach (Vehicle vehicle in vehicles)
{
if(!String.IsNullOrEmpty(vehicle.VehicleComparisonSourceURL))
{
PriceMatchScraper priceMatchScraper = new PriceMatchScraper(vehicle.VehicleComparisonSourceURL);
await priceMatchScraper.StartAsync();
if(!String.IsNullOrEmpty(priceMatchScraper.PriceString))
{
PriceMatchVehiclesViewModel priceMatchVehiclesViewModel = new PriceMatchVehiclesViewModel();
priceMatchVehiclesViewModel.VehicleId = (int) vehicle.Id;
priceMatchVehiclesViewModel.VehicleDescription = (vehicle.Manufacturer + " " + vehicle.Model);
priceMatchVehiclesViewModel.VehicleTypeCostPerDay = (Decimal.ToInt32(vehicle.CostPerDay).ToString() + " GBP");
priceMatchVehiclesViewModel.PriceToMatch = priceMatchScraper.PriceString;
priceMatchViewModel.PriceMatchVehicles.Add(priceMatchVehiclesViewModel);
}
}
}
if(priceMatchViewModel.PriceMatchVehicles.Count > 0)
{
return View(priceMatchViewModel);
}
else
{
TempData["errormessage"] = "No Price Match Data Available.";
return RedirectToAction("Index", "Home");
}
}
[HttpPost]
public async Task<IActionResult> PriceMatch(long? id)
{
await AuthenticateUserLogin(true);
long vehicleId = (long)id;
Vehicle vehicle = (Vehicle)await CommandFactory.CreateCommand(CommandFactory.GET_VEHICLE, vehicleId, DbContext).Execute();
int newCostPerDay = -1;
if (!String.IsNullOrEmpty(vehicle.VehicleComparisonSourceURL))
{
PriceMatchScraper priceMatchScraper = new PriceMatchScraper(vehicle.VehicleComparisonSourceURL);
await priceMatchScraper.StartAsync();
if (!String.IsNullOrEmpty(priceMatchScraper.PriceString))
{
string priceStringToConvert = priceMatchScraper.PriceString.Replace("GBP", "");
priceStringToConvert = priceStringToConvert.Trim();
newCostPerDay = Int32.Parse(priceStringToConvert);
}
}
if(newCostPerDay <= 0)
{
TempData["errormessage"] = "Unable to update vehicle cost per day. Please try again.";
return RedirectToAction("Index", "Home");
}
int vehicleCostUpdated = (int)await CommandFactory.CreateCommand(CommandFactory.UPDATE_VEHICLE_COST_PER_DAY, DbContext, vehicleId, newCostPerDay).Execute();
if(vehicleCostUpdated < 1)
{
TempData["errormessage"] = "Unable to update vehicle cost per day. Please try again.";
return RedirectToAction("Index", "Home");
}
else
{
TempData["successmessage"] = "Vehicle Cost Updated!";
return RedirectToAction("Index", "Home");
}
}
public async Task<IActionResult> AuthenticateUserLogin(bool adminRequired)
{
ApplicationUser CurrentUser = await UserManager.GetUserAsync(HttpContext.User);
bool IsAdmin = await UserManager.IsInRoleAsync(CurrentUser, "Admin");
if (CurrentUser == null)
{
TempData["errormessage"] = "You need to be logged in to upload files." + Environment.NewLine + " If you do not have an account, please navigate to the registration page by clicking on 'Register' at the top of the screen.";
return RedirectToAction("Login", "Account");
}
if (adminRequired && IsAdmin == false)
{
TempData["errormessage"] = "You require admin privileges to view that page.";
return RedirectToAction("Index", "Home");
}
else return null;
}
}
}<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/DataParallelismProj/CommandsFactory/CommandFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataParallelismProj.CommandsFactory
{
class CommandFactory
{
const int GET_ALL_STORES = 1;
const int GET_ALL_SUPPLIERS = 2;
const int LOAD_DATA = 3;
public ICommand CreateCommand(int commandType)
{
switch(commandType)
{
case GET_ALL_STORES:
return new GetAllStoresCommand();
case GET_ALL_SUPPLIERS:
return new GetAllSuppliersCommand();
default:
return new NullObjectCommand();
}
}
public ICommand CreateCommand(int commandType, string selectedFolderPath)
{
switch (commandType)
{
case LOAD_DATA:
return new LoadDataCommand(selectedFolderPath);
default:
return new NullObjectCommand();
}
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_Library/nbproject/private/private.properties
compile.on.save=true
user.properties.file=C:\\Users\\Rhys\\AppData\\Roaming\\NetBeans\\11.1\\build.properties
<file_sep>/OOAE/T1/T1-09/cardDeckProj/src/carddeckproj/GuiDriver.java
package carddeckproj;
import javax.swing.*;
import java.awt.*;
public class GuiDriver extends JFrame
{
private CardGamePanel[] cgp = new CardGamePanel[3];
private DisplayableDeck dd = new DisplayableDeck();
private DisplayableHand dh = new DisplayableHand();
private DisplayableCard dc = new DisplayableCard(Rank.ACE, Suit.SPADES);
public GuiDriver()
{
super("Cards Gui");
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
createHand();
cgp[0] = new CardGamePanel();
cgp[0].setItem(dd, 10, 10);
p.add(cgp[0]);
cgp[1] = new CardGamePanel();
cgp[1].setItem(dh, 10, 10);
p.add(cgp[1]);
cgp[2] = new CardGamePanel();
cgp[2].setItem(dc, 10, 10);
p.add(cgp[2]);
add(p);
this.setSize(400, 375);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);
}
public static void main(String args[])
{
GuiDriver d = new GuiDriver();
}
public void createHand()
{
dd.shuffle();
for (int i = 0; i < dh.theCards.length; i++)
{
dh.addCard(dd.theCards[i]);
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/Handler/SupplierHandler.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFDataParallelismProj.DTO;
namespace WPFDataParallelismProj.Handler
{
class SupplierHandler
{
public async Task<String[]> GetSuppliers(HashSet<Order> orders)
{
String[] suppliers = new String[0];
await Task.Run(() =>
{
suppliers = orders.GroupBy(order => order.Supplier.SupplierName)
.Select(order => order.Key).ToArray();
});
return suppliers;
}
public async Task<String[]> GetSupplierTypes(HashSet<Order> orders)
{
String[] supplierTypes = new String[0];
await Task.Run(() =>
{
supplierTypes = orders.GroupBy(order => order.Supplier.SupplierType)
.Select(order => order.Key).ToArray();
});
return supplierTypes;
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/GetTotalCostInWeekForSupplierTypeCommand.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using WPFDataParallelismProj.DTO;
using WPFDataParallelismProj.Handler;
namespace WPFDataParallelismProj.CommandsFactory
{
class GetTotalCostInWeekForSupplierTypeCommand : ICommand
{
private HashSet<Order> orders;
private Date date;
private string supplierType;
private OrderHandler orderHandler;
public GetTotalCostInWeekForSupplierTypeCommand(HashSet<Order> orders, Date date, string supplierType)
{
this.orders = orders;
this.date = date;
this.supplierType = supplierType;
orderHandler = new OrderHandler();
}
public async Task<object> Execute()
{
return await orderHandler.GetTotalCostInWeekForSupplierType(orders, date, supplierType);
}
}
}<file_sep>/OOAE/T2/T2-05/wk2-05_lec1_VisitorProj/wk2-05_lec1_VisitorProj/src/Employee/EmployeePrinter.java
package Employee;
import java.text.SimpleDateFormat;
/**
*
* @author <NAME>
*/
public class EmployeePrinter extends EmployeeVisitor
{
@Override
public void visitEmployee(Employee e)
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.printf("%-5d %-10s %-10s %-5d %-10s %-5d %-5d %-5d\n",
e.getEmployeeNumber(),
e.getEmployeeName(),
e.getJob(),
e.getManager(),
sdf.format(e.getHireDate()),
e.getSalary(),
e.getComm(),
e.getDeptNo());
}
}
<file_sep>/WMAD/CinemaBookingSystem/src/java/handler/CustomerHandler.java
package handler;
import dto.UserDTO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
/**
*
* @author Rhysj
*/
public class CustomerHandler
{
private static CustomerHandler instance = null;
protected CustomerHandler()
{
}
public static CustomerHandler getInstance()
{
if (instance == null)
{
instance = new CustomerHandler();
}
return instance;
}
public boolean insertCustomer(UserDTO newCustomer)
{
boolean insertOK = false;
DatabaseHandler db = DatabaseHandler.getInstance();
try
{
Connection conn = db.getConnection();
PreparedStatement stmt = conn.prepareStatement("INSERT INTO Users (forename, surname, DOB, address_line_1, address_line_2, username, password, postcode, admin) values (?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, newCustomer.getForename());
stmt.setString(2, newCustomer.getSurname());
java.sql.Date DOB = new java.sql.Date(newCustomer.getDOB().getTime());
stmt.setDate(3, DOB);
stmt.setString(4, newCustomer.getAddressLine1());
stmt.setString(5, newCustomer.getAddressLine2());
stmt.setString(6, newCustomer.getUsername());
stmt.setString(7, newCustomer.getPassword());
stmt.setString(8, newCustomer.getPostcode());
stmt.setBoolean(9, false);
int rows = stmt.executeUpdate();
insertOK = rows == 1;
stmt.close();
conn.close();
}
catch (SQLException sqle)
{
System.out.println("ERROR\nCOULD NOT INSERT CUSTOMER\n" + sqle);
}
return insertOK;
}
public UserDTO checkCustomerCredentials(String username, String password)
{
boolean correctCredentials = false;
int userID = 0;
DatabaseHandler db = DatabaseHandler.getInstance();
try
{
Connection conn = db.getConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM Users WHERE username = ?");
stmt.setString(1, username);
ResultSet rs = stmt.executeQuery();
correctCredentials = rs.next() && rs.getString("password").equals(<PASSWORD>);
userID = rs.getInt("user_id");
rs.close();
stmt.close();
conn.close();
}
catch (Exception e)
{
System.out.println("Customer credentials incorrect.\n" + e);
}
if (correctCredentials)
{
UserDTO customer = getCustomerDetails(userID);
return customer;
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Login credentials are not correct"));
return null;
}
}
public UserDTO getCustomerDetails(int userID)
{
UserDTO customerDetails = null;
DatabaseHandler db = DatabaseHandler.getInstance();
try
{
Connection conn = db.getConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE user_id = ?");
stmt.setInt(1, userID);
ResultSet rs = stmt.executeQuery();
if (rs.next())
{
customerDetails = new UserDTO(rs.getInt("user_ID"), rs.getString("forename"), rs.getString("surname"), rs.getDate("DOB"), rs.getString("address_line_1"),
rs.getString("address_line_2"), rs.getString("postcode"), rs.getString("username"), rs.getString("password"), rs.getBoolean("admin"));
}
rs.close();
stmt.close();
conn.close();
}
catch (SQLException sqle)
{
System.out.println("Error" + sqle);
}
return customerDetails;
}
public boolean updateAccountDetails(UserDTO customer)
{
boolean updateOK = false;
DatabaseHandler db = DatabaseHandler.getInstance();
try
{
Connection conn = db.getConnection();
PreparedStatement stmt = conn.prepareStatement("UPDATE Users SET FORENAME = '" + customer.getForename() + "', SURNAME = '" + customer.getSurname()
+ "', ADDRESS_LINE_1 = '" + customer.getAddressLine1() + "', ADDRESS_LINE_2 = '" + customer.getAddressLine2() + "', POSTCODE = '" + customer.getPostcode()
+ "', PASSWORD = '" + <PASSWORD>.getPassword() + "' WHERE User_ID = ?");
stmt.setInt(1, customer.getUserID());
int rows = stmt.executeUpdate();
updateOK = rows == 1;
stmt.close();
conn.close();
}
catch (SQLException sqle)
{
System.out.println("ERROR\nCOULD NOT INSERT CUSTOMER\n" + sqle);
}
return updateOK;
}
public ArrayList<UserDTO> getAllCustomers()
{
ArrayList<UserDTO> customers = new ArrayList();
DatabaseHandler db = DatabaseHandler.getInstance();
try
{
Connection conn = db.getConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM USERS WHERE ADMIN = FALSE");
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
UserDTO customer = new UserDTO(rs.getInt("USER_ID"), rs.getString("FORENAME"), rs.getString("SURNAME"),
rs.getDate("DOB"), rs.getString("ADDRESS_LINE_1"), rs.getString("ADDRESS_LINE_2"),
rs.getString("POSTCODE"), rs.getString("USERNAME"), rs.getString("PASSWORD"), false);
customers.add(customer);
}
rs.close();
stmt.close();
conn.close();
}
catch (SQLException sqle)
{
System.out.println("ERROR\nCould not get Customers.\n" + sqle);
return null;
}
return customers;
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/DTO/Date.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFDataParallelismProj.DTO
{
class Date : IComparable
{
private int _week;
public int Week
{
get
{
return _week;
}
set
{
if (!(value < 0 || value > 52))
{
_week = value;
}
}
}
private int _year;
public int Year
{
get
{
return _year;
}
set
{
if (!(value < 1970))
{
_year = value;
}
}
}
override
public String ToString()
{
return "Week: " + Week + " Year: " + Year;
}
public int CompareTo(object obj)
{
if (obj.GetType() == GetType())
{
Date d = obj as Date;
if (Year < d.Year)
{
return -1;
}
else if (Year > d.Year)
{
return 1;
}
else if (Week < d.Week)
{
return -1;
}
else if (Week > d.Week)
{
return 1;
}
else
{
return 0;
}
}
else
{
throw new Exception("Wrong object type.");
}
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/StoreDataWindow.xaml.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms.DataVisualization.Charting;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using WPFDataParallelismProj.CommandsFactory;
using WPFDataParallelismProj.DTO;
namespace WPFDataParallelismProj
{
/// <summary>
/// Interaction logic for StoreDataWindow.xaml
/// </summary>
public partial class StoreDataWindow : Window
{
//Folder Path Window instance, for getting the folder path.
private FolderPathWindow FPW;
//Collections of objects.
private HashSet<Order> orders = new HashSet<Order>();
public StoreDataWindow()
{
FPW = new FolderPathWindow();
InitializeComponent();
WindowState = WindowState.Maximized;
FPW.ShowDialog();
Task.Run(async () =>
{
bool setupComplete = (bool)(await (CommandFactory.CreateCommand(CommandFactory.SET_FOLDER_PATH, FPW.SelectedPath).Execute()));
});
}
private void Load_Data_Button_Click(object sender, RoutedEventArgs e)
{
//Empty the collections and garbage collect to avoid cached data reaching 3gb.
orders = null;
GC.Collect();
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Task t1 = new Task(async () =>
{
orders = (HashSet<Order>)(await (CommandFactory.CreateCommand(CommandFactory.LOAD_DATA, LoadProgress).Execute()));
Store[] stores = (Store[])(await (CommandFactory.CreateCommand(CommandFactory.GET_STORES, orders).Execute()));
Date[] dates = (Date[])(await (CommandFactory.CreateCommand(CommandFactory.GET_DATES, orders).Execute()));
Array.Sort(dates);
String[] suppliers = (String[])(await (CommandFactory.CreateCommand(CommandFactory.GET_SUPPLIERS, orders).Execute()));
String[] supplierTypes = (String[])(await (CommandFactory.CreateCommand(CommandFactory.GET_SUPPLIER_TYPES, orders).Execute()));
Dictionary<string, double> supplierOrderChartData = new Dictionary<string, double>();
foreach(string supplier in suppliers)
{
double totalCostForSupplier = (double)(await (CommandFactory.CreateCommand(CommandFactory.GET_TOTAL_COST_FOR_SUPPLIER, orders, supplier).Execute()));
supplierOrderChartData.Add(supplier, totalCostForSupplier);
}
await Dispatcher.BeginInvoke((Action)(() =>
{
stopWatch.Stop();
Chart chart = FindName("Chart") as Chart;
//chart.ChartAreas[0].AxisX.LabelStyle.Angle = -90;
chart.ChartAreas[0].AxisX.LabelStyle.Interval = 1;
chart.ChartAreas[0].AxisY.LabelStyle.Format = "£{000,0}";
chart.ChartAreas[0].AxisY.LabelStyle.Interval = 250000;
chart.DataSource = supplierOrderChartData;
chart.Series["series"].XValueMember = "Key";
chart.Series["series"].YValueMembers = "Value";
if (orders.Count > 0)
{
TimeToLoad.Text = "TimeToLoad: " + stopWatch.Elapsed.TotalSeconds;
DateBox.ItemsSource = dates;
StoreListView.ItemsSource = stores;
SupplierListView.ItemsSource = suppliers;
SupplierTypeListView.ItemsSource = supplierTypes;
}
}));
GC.Collect();
});
t1.Start();
Load_Data_Button.Header = "Reload Data";
}
private void Total_Cost_Of_All_Orders_Button_Click(object sender, RoutedEventArgs e)
{
TimeToLoad.Text = ("Calculating total...");
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Task t1 = new Task(async () =>
{
if (orders.Count > 0)
{
double totalCost = (double)(await (CommandFactory.CreateCommand(CommandFactory.GET_TOTAL_COST_ALL_ORDERS, orders).Execute()));
await Dispatcher.BeginInvoke((Action)(() =>
{
TotalPrice.Text = ("Total cost of all orders: " + totalCost.ToString("C", CultureInfo.CurrentCulture));
stopWatch.Stop();
TimeToLoad.Text = ("Time to load: " + stopWatch.Elapsed.TotalSeconds);
}), DispatcherPriority.Background);
}
else
{
await Dispatcher.BeginInvoke((Action)(() =>
{
TimeToLoad.Text = ("\nData not loaded.");
}), DispatcherPriority.Background);
}
GC.Collect();
});
t1.Start();
}
private void Total_Cost_For_Store_Button_Click(object sender, RoutedEventArgs e)
{
TimeToLoad.Text = ("Calculating total for " + StoreListView.SelectedItem + "...");
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Store selectedStore = (Store)StoreListView.SelectedItem;
Task t1 = new Task(async () =>
{
if (orders.Count > 0)
{
double totalCostForStore = (double)(await (CommandFactory.CreateCommand(CommandFactory.GET_TOTAL_COST_FOR_STORE, orders, selectedStore).Execute()));
await Dispatcher.BeginInvoke((Action)(() =>
{
TotalPrice.Text = ("Total cost for store: " + totalCostForStore.ToString("C", CultureInfo.CurrentCulture));
stopWatch.Stop();
TimeToLoad.Text = ("Time to load: " + stopWatch.Elapsed.TotalSeconds);
}), DispatcherPriority.Background);
}
else
{
await Dispatcher.BeginInvoke((Action)(() =>
{
TimeToLoad.Text = ("\nData not loaded.");
}), DispatcherPriority.Background);
}
GC.Collect();
});
t1.Start();
}
private void Total_Cost_In_Week_Button_Click(object sender, RoutedEventArgs e)
{
TimeToLoad.Text = ("Calculating total for " + DateBox.SelectedItem + "...");
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Date selectedDate = (Date)DateBox.SelectedItem;
Task t1 = new Task(async () =>
{
if (orders.Count > 0)
{
double totalCostForWeek = (double)(await (CommandFactory.CreateCommand(CommandFactory.GET_TOTAL_COST_IN_WEEK, orders, selectedDate).Execute()));
await Dispatcher.BeginInvoke((Action)(() =>
{
TotalPrice.Text = ("Total cost in week: " + totalCostForWeek.ToString("C", CultureInfo.CurrentCulture));
stopWatch.Stop();
TimeToLoad.Text = ("Time to load: " + stopWatch.Elapsed.TotalSeconds);
}), DispatcherPriority.Background);
}
else
{
await Dispatcher.BeginInvoke((Action)(() =>
{
TimeToLoad.Text = ("\nData not loaded.");
}), DispatcherPriority.Background);
}
GC.Collect();
});
t1.Start();
}
private void Total_Cost_In_Week_For_Store_Button_Click(object sender, RoutedEventArgs e)
{
TimeToLoad.Text = ("Calculating total for " + StoreListView.SelectedItem + " on " + DateBox.SelectedItem + "...");
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Date selectedDate = (Date)DateBox.SelectedItem;
Store selectedStore = (Store)StoreListView.SelectedItem;
Task t1 = new Task(async () =>
{
if (orders.Count > 0)
{
double totalCostForStoreForWeek = (double)(await (CommandFactory.CreateCommand(CommandFactory.GET_TOTAL_COST_IN_WEEK_FOR_STORE, orders, selectedDate, selectedStore).Execute()));
await Dispatcher.BeginInvoke((Action)(() =>
{
TotalPrice.Text = ("Total cost in week for store: " + totalCostForStoreForWeek.ToString("C", CultureInfo.CurrentCulture));
stopWatch.Stop();
TimeToLoad.Text = ("Time to load: " + stopWatch.Elapsed.TotalSeconds);
}), DispatcherPriority.Background);
}
else
{
await Dispatcher.BeginInvoke((Action)(() =>
{
TimeToLoad.Text = ("\nData not loaded.");
}), DispatcherPriority.Background);
}
GC.Collect();
});
t1.Start();
}
private void Total_Cost_For_Supplier_Button_Click(object sender, RoutedEventArgs e)
{
TimeToLoad.Text = ("Calculating total for " + SupplierListView.SelectedItem + "...");
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string selectedSupplier = (string)SupplierListView.SelectedItem;
Task t1 = new Task(async () =>
{
if (orders.Count > 0)
{
double totalCostForSupplier = (double)(await (CommandFactory.CreateCommand(CommandFactory.GET_TOTAL_COST_FOR_SUPPLIER, orders, selectedSupplier).Execute()));
await Dispatcher.BeginInvoke((Action)(() =>
{
TotalPrice.Text = ("Total cost for supplier: " + totalCostForSupplier.ToString("C", CultureInfo.CurrentCulture));
stopWatch.Stop();
TimeToLoad.Text = ("Time to load: " + stopWatch.Elapsed.TotalSeconds);
}), DispatcherPriority.Background);
}
else
{
await Dispatcher.BeginInvoke((Action)(() =>
{
TimeToLoad.Text = ("\nData not loaded.");
}), DispatcherPriority.Background);
}
GC.Collect();
});
t1.Start();
}
private void Total_Cost_For_SupplierType_Button_Click(object sender, RoutedEventArgs e)
{
TimeToLoad.Text = ("Calculating total for " + SupplierTypeListView.SelectedItem + "...");
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string selectedSupplierType = (string)SupplierTypeListView.SelectedItem;
Task t1 = new Task(async () =>
{
if (orders.Count > 0)
{
double totalCostForSupplierType = (double)(await (CommandFactory.CreateCommand(CommandFactory.GET_TOTAL_COST_FOR_SUPPLIER_TYPE, orders, selectedSupplierType).Execute()));
await Dispatcher.BeginInvoke((Action)(() =>
{
TotalPrice.Text = ("Total cost for supplier type: " + totalCostForSupplierType.ToString("C", CultureInfo.CurrentCulture));
stopWatch.Stop();
TimeToLoad.Text = ("Time to load: " + stopWatch.Elapsed.TotalSeconds);
}), DispatcherPriority.Background);
}
else
{
await Dispatcher.BeginInvoke((Action)(() =>
{
TimeToLoad.Text = ("\nData not loaded.");
}), DispatcherPriority.Background);
}
GC.Collect();
});
t1.Start();
}
private void Total_Cost_In_Week_For_SupplierType_Button_Click(object sender, RoutedEventArgs e)
{
TimeToLoad.Text = ("Calculating total for " + SupplierTypeListView.SelectedItem + " on " + DateBox.SelectedItem + "...");
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string selectedSupplierType = (string)SupplierTypeListView.SelectedItem;
Date selectedDate = (Date)DateBox.SelectedItem;
Task t1 = new Task(async () =>
{
if (orders.Count > 0)
{
double totalCostInWeekForSupplierType = (double)(await (CommandFactory.CreateCommand(CommandFactory.GET_TOTAL_COST_IN_WEEK_FOR_SUPPLIER_TYPE, orders, selectedDate, selectedSupplierType).Execute()));
await Dispatcher.BeginInvoke((Action)(() =>
{
TotalPrice.Text = ("Total cost in week for supplier type: " + totalCostInWeekForSupplierType.ToString("C", CultureInfo.CurrentCulture));
stopWatch.Stop();
TimeToLoad.Text = ("Time to load: " + stopWatch.Elapsed.TotalSeconds);
}), DispatcherPriority.Background);
}
else
{
await Dispatcher.BeginInvoke((Action)(() =>
{
TimeToLoad.Text = ("\nData not loaded.");
}), DispatcherPriority.Background);
}
GC.Collect();
});
t1.Start();
}
private void Total_Cost_For_SupplierType_For_Store_Button_Click(object sender, RoutedEventArgs e)
{
TimeToLoad.Text = ("Calculating total for " + SupplierTypeListView.SelectedItem + " at " + StoreListView.SelectedItem + "...");
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string selectedSupplierType = (string)SupplierTypeListView.SelectedItem;
Store selectedStore = (Store)StoreListView.SelectedItem;
Task t1 = new Task(async () =>
{
if (orders.Count > 0)
{
double totalCostForSupplierTypeAtStore = (double)(await (CommandFactory.CreateCommand(CommandFactory.GET_TOTAL_COST_FOR_SUPPLIER_TYPE_FOR_STORE, orders, selectedStore, selectedSupplierType).Execute()));
await Dispatcher.BeginInvoke((Action)(() =>
{
TotalPrice.Text = ("Total cost for supplier type for store: " + totalCostForSupplierTypeAtStore.ToString("C", CultureInfo.CurrentCulture));
stopWatch.Stop();
TimeToLoad.Text = ("Time to load: " + stopWatch.Elapsed.TotalSeconds);
}), DispatcherPriority.Background);
}
else
{
await Dispatcher.BeginInvoke((Action)(() =>
{
TimeToLoad.Text = ("\nData not loaded.");
}), DispatcherPriority.Background);
}
GC.Collect();
});
t1.Start();
}
private void Total_Cost_In_Week_For_SupplierType_For_Store_Button_Click(object sender, RoutedEventArgs e)
{
TimeToLoad.Text = ("Calculating total for " + SupplierTypeListView.SelectedItem + " at " + StoreListView.SelectedItem + " on " + DateBox.SelectedItem + "...");
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string selectedSupplierType = (string)SupplierTypeListView.SelectedItem;
Store selectedStore = (Store)StoreListView.SelectedItem;
Date selectedDate = (Date)DateBox.SelectedItem;
Task t1 = new Task(async () =>
{
if (orders.Count > 0)
{
double totalCostInWeekForSupplierTypeAtStore = (double)(await (CommandFactory.CreateCommand(CommandFactory.GET_TOTAL_COST_IN_WEEK_FOR_SUPPLIER_TYPE_FOR_STORE, orders, selectedDate, selectedStore, selectedSupplierType).Execute()));
await Dispatcher.BeginInvoke((Action)(() =>
{
TotalPrice.Text = ("Total cost in week for supplier type for store: " + totalCostInWeekForSupplierTypeAtStore.ToString("C", CultureInfo.CurrentCulture));
stopWatch.Stop();
TimeToLoad.Text = ("Time to load: " + stopWatch.Elapsed.TotalSeconds);
}), DispatcherPriority.Background);
}
else
{
await Dispatcher.BeginInvoke((Action)(() =>
{
TimeToLoad.Text = ("\nData not loaded.");
}), DispatcherPriority.Background);
}
GC.Collect();
});
t1.Start();
}
private async void LoadProgress(int currentlyLoaded, int totalToLoad)
{
await Dispatcher.BeginInvoke(new Action(() =>
{
PBText.Text = "Loaded: " + currentlyLoaded + "/" + totalToLoad;
Loading_Bar.Maximum = totalToLoad;
Loading_Bar.Value = currentlyLoaded;
}));
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/application_ui/ChangeDeliveryStatusCommandLocal.java
package application_ui;
import javax.ejb.Local;
/**
*
* @author Rhys
*/
@Local
public interface ChangeDeliveryStatusCommandLocal extends Command
{
@Override
Object execute();
void setDeliveryId(int deliveryId);
void setDeliveryStatusId(int deliveryStatusId);
}
<file_sep>/OOAE/T1/T1-05/Code Listing LB05_01.txt
package lb05_01;
import java.util.*;
public class LB05_01
{
static Scanner kybd = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Valid integer input was: " + inputInt());
System.out.println("");
System.out.println("Valid double input was: " + inputDouble());
}
public static int inputInt()
{
int num = 0;
boolean valid = false;
while (valid == false)
{
try
{
System.out.print("Enter a number: ");
num = kybd.nextInt();
valid = true;
}
catch (Exception e)
{
System.out.println("Integers only please");
kybd.next();
}
}
return num;
}
public static double inputDouble()
{
double doubleNum = 0;
boolean valid = false;
while (valid == false)
{
try
{
System.out.print("Enter a number: ");
doubleNum = kybd.nextDouble();
valid = true;
}
catch (Exception e)
{
System.out.println("Doubles only please");
kybd.next();
}
}
return doubleNum;
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/nbproject/project.properties
build.classes.excludes=**/*.java,**/*.form,**/.nbattrs
build.dir=build
build.generated.dir=${build.dir}/generated
client.module.uri=EEA_Assignment1_J016984C-war
client.urlPart=
debug.classpath=${javac.classpath}::${jar.content.additional}:${run.classpath}
display.browser=true
dist.dir=dist
dist.jar=${dist.dir}/${jar.name}
endorsed.classpath=\
${libs.javaee-endorsed-api-7.0.classpath}
file.reference.ojdbc6.jar=C:\\Users\\Rhys\\Documents\\Uni Level 6\\ojdbc6.jar
j2ee.appclient.mainclass.args=${j2ee.appclient.tool.args}
j2ee.compile.on.save=true
j2ee.deploy.on.save=true
j2ee.platform=1.7
j2ee.platform.classpath=${j2ee.server.home}/modules/endorsed/grizzly-npn-bootstrap.jar:${j2ee.server.home}/modules/endorsed/jakarta.annotation-api.jar:${j2ee.server.home}/modules/endorsed/jakarta.xml.bind-api.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/bean-validator.jar:${j2ee.server.home}/modules/cdi-api.jar:${j2ee.server.home}/modules/javax.batch-api.jar:${j2ee.server.home}/modules/jaxb-osgi.jar:${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/weld-osgi-bundle.jar:${j2ee.server.middleware}/mq/lib/jaxm-api.jar
j2ee.platform.embeddableejb.classpath=${j2ee.server.home}/lib/embedded/glassfish-embedded-static-shell.jar
j2ee.platform.wscompile.classpath=${j2ee.server.home}/modules/webservices-osgi.jar
j2ee.platform.wsgen.classpath=${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/jaxb-osgi.jar
j2ee.platform.wsimport.classpath=${j2ee.server.home}/modules/webservices-osgi.jar:${j2ee.server.home}/modules/endorsed/webservices-api-osgi.jar:${j2ee.server.home}/modules/jaxb-osgi.jar
j2ee.platform.wsit.classpath=
j2ee.server.type=gfv5ee8
jar.compress=false
jar.content.additional=\
${reference.EEA_Assignment1_J016984C-war.dist-ear}:\
${reference.EEA_Assignment1_J016984C-ejb.dist-ear}
jar.name=EEA_Assignment1_J016984C.ear
javac.debug=true
javac.deprecation=false
javac.source=1.8
javac.target=1.8
meta.inf=src/conf
no.dependencies=false
platform.active=default_platform
project.EEA_Assignment1_J016984C-ejb=EEA_Assignment1_J016984C-ejb
project.EEA_Assignment1_J016984C-war=EEA_Assignment1_J016984C-war
reference.EEA_Assignment1_J016984C-ejb.dist-ear=${project.EEA_Assignment1_J016984C-ejb}/dist/EEA_Assignment1_J016984C-ejb.jar
reference.EEA_Assignment1_J016984C-war.dist-ear=${project.EEA_Assignment1_J016984C-war}/dist/EEA_Assignment1_J016984C-war.war
resource.dir=setup
run.classpath=\
${file.reference.ojdbc6.jar}
source.root=.
<file_sep>/CNA/SimpleClientServer/ChatClient/Nickname.cs
using Packets;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Windows.Forms;
namespace ChatClient
{
public partial class Nickname : Form
{
private BinaryWriter _writer;
public Nickname(BinaryWriter writer)
{
InitializeComponent();
_writer = writer;
}
private void button1_Click(object sender, EventArgs e)
{
String inputNickname;
inputNickname = textBox1.Text;
NicknamePacket nickname = new NicknamePacket(inputNickname);
if (!nickname.Equals(String.Empty))
{
Send(nickname);
this.Close();
}
else
{
label2.Text = "Enter a name!!";
}
}
public void Send(Packet data)
{
MemoryStream mem = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(mem, data);
byte[] buffer = mem.GetBuffer();
try
{
_writer.Write(buffer.Length);
_writer.Write(buffer);
_writer.Flush();
}
catch { }
}
}
}
<file_sep>/OOAE/T2/T2-05/wk2-05_lec1_CommandProj/wk2-05_lec1_CommandProj/src/view/AllEmployeesView.java
package view;
import database.Employee;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
/**
*
* @author <NAME>
*/
public class AllEmployeesView
{
ArrayList<Employee> employees;
public AllEmployeesView(ArrayList<Employee> employees)
{
this.employees = employees;
}
public void print()
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("All employees\n");
for(int i = 0; i < 60; i++);
{
System.out.print("=");
}
for (Employee emp : employees)
{
System.out.printf("\t%5d %10s %10s %5d %10s %5d %5d %5d\n",
emp.getEmployeeNumber(),
emp.getEmployeeName(),
emp.getJob(),
emp.getManager(),
sdf.format(emp.getHireDate()),
emp.getSalary(),
emp.getComm(),
emp.getDeptNo());
}
}
}
<file_sep>/WMAD/WMAD_assignment_2/app/src/main/java/com/example/rhysj/wmad_assignment_2/UpdateAccountActivity.java
package com.example.rhysj.wmad_assignment_2;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.rhysj.wmad_assignment_2.DTO.UserDTO;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
/**
* Created by <NAME> on 12/04/2018.
*/
public class UpdateAccountActivity extends AppCompatActivity implements Response.Listener<String>
{
private NavigationSlider navView;
UserDTO loggedUser;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Sets which xml file to load
setContentView(R.layout.activity_update_account);
navView = new NavigationSlider(this);
getSupportActionBar().setTitle("Update Account Details");
displayLoggedUserDetails();
}
@Override
public void onResponse(String response)
{
if(Boolean.parseBoolean(response))
{
Toast.makeText(getApplicationContext(), "Updated Successfully", Toast.LENGTH_LONG ).show();
Intent intent = new Intent(this, MainActivity.class);
this.startActivity(intent);
}
else
{
Toast.makeText(getApplicationContext(), "Update Failure", Toast.LENGTH_LONG ).show();
}
}
public void update(View view)
{
final String forename = ((EditText) findViewById(R.id.update_forename)).getText().toString();
final String surname = ((EditText) findViewById(R.id.update_surname)).getText().toString();
final String addressLine1 = ((EditText) findViewById(R.id.update_address_line_1)).getText().toString();
final String addressLine2 = ((EditText) findViewById(R.id.update_address_line_2)).getText().toString();
final String postcode = ((EditText) findViewById(R.id.update_postcode)).getText().toString();
final String password;
final String inputPassword = ((EditText) findViewById(R.id.update_password)).getText().toString();
if(inputPassword.isEmpty())
{
BaseConnectionHandler BCH = new BaseConnectionHandler();
String urlPath = BCH.baseConnection + "/CustomerUI/account/";
StringRequest stringRequest = new StringRequest(Request.Method.PUT, urlPath, this,
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String DOB = sdf.format(loggedUser.getDOB().getTime());
String username = loggedUser.getUsername();
String userID = Integer.toString(loggedUser.getUserID());
params.put("userID", userID);
params.put("forename", forename);
params.put("surname", surname);
params.put("DOB", DOB);
params.put("addressLine1", addressLine1);
params.put("addressLine2", addressLine2);
params.put("postcode", postcode);
params.put("username", username);
params.put("password", <PASSWORD>());
return params;
}
};
Volley.newRequestQueue(this).add(stringRequest);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String DOB = sdf.format(loggedUser.getDOB().getTime());
String username = loggedUser.getUsername();
int userID = loggedUser.getUserID();
SharedPreferencesHandler SPH = SharedPreferencesHandler.getInstance(this);
SPH.logout();
SPH.setLoggedInUser(new UserDTO(userID, forename, surname, DOB, addressLine1, addressLine2, postcode, username, loggedUser.getPassword(), loggedUser.isIsAdmin()));
}
else if(!inputPassword.isEmpty())
{
String tempPass = inputPassword;
try
{
byte[] hash = MessageDigest.getInstance("SHA-256")
.digest(tempPass.getBytes(StandardCharsets.UTF_8));
tempPass = Base64.encodeToString(hash, Base64.DEFAULT);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Error serialising password", Toast.LENGTH_LONG ).show();
}
password = <PASSWORD>;
BaseConnectionHandler BCH = new BaseConnectionHandler();
String urlPath = BCH.baseConnection + "/CustomerUI/account/";
StringRequest stringRequest = new StringRequest(Request.Method.PUT, urlPath, this,
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String DOB = sdf.format(loggedUser.getDOB().getTime());
String username = loggedUser.getUsername();
String userID = Integer.toString(loggedUser.getUserID());
params.put("userID", userID);
params.put("forename", forename);
params.put("surname", surname);
params.put("DOB", DOB);
params.put("addressLine1", addressLine1);
params.put("addressLine2", addressLine2);
params.put("postcode", postcode);
params.put("username", username);
params.put("password", password.substring(0, password.length() - 1));
return params;
}
};
Volley.newRequestQueue(this).add(stringRequest);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String DOB = sdf.format(loggedUser.getDOB().getTime());
String username = loggedUser.getUsername();
int userID = loggedUser.getUserID();
SharedPreferencesHandler SPH = SharedPreferencesHandler.getInstance(this);
SPH.logout();
SPH.setLoggedInUser(new UserDTO(userID, forename, surname, DOB, addressLine1, addressLine2, postcode, username, password.substring(0, password.length() - 1), loggedUser.isIsAdmin()));
}
}
public void displayLoggedUserDetails()
{
loggedUser = SharedPreferencesHandler.getInstance(this).getLoggedInUser();
//Set the forename.
EditText forenameInput = findViewById(R.id.update_forename);
forenameInput.setText(loggedUser.getForename());
//Set the surname.
EditText surnameInput = findViewById(R.id.update_surname);
surnameInput.setText(loggedUser.getSurname());
//Set the DOB.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
EditText DOBDisplay = findViewById(R.id.update_DOB);
DOBDisplay.setText(sdf.format(loggedUser.getDOB().getTime()));
//Set the address line 1.
EditText addressLine1Input = findViewById(R.id.update_address_line_1);
addressLine1Input.setText(loggedUser.getAddressLine1());
//Set the address line 2.
EditText addressLine2Input = findViewById(R.id.update_address_line_2);
addressLine2Input.setText(loggedUser.getAddressLine2());
//Set the postcode.
EditText postcodeInput = findViewById(R.id.update_postcode);
postcodeInput.setText(loggedUser.getPostcode());
//Set the username.
EditText usernameDisplay = findViewById(R.id.update_username);
usernameDisplay.setText(loggedUser.getUsername());
}
}
<file_sep>/WMAD/CinemaBookingSystem/src/java/managedbean/ViewBookingsBean.java
package managedbean;
import adminUI.AdminCommandFactory;
import dto.BookingDTO;
import java.io.Serializable;
import java.util.ArrayList;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
/**
*
* @author <NAME>
*/
@Named(value = "ViewBookingsBean")
@SessionScoped
public class ViewBookingsBean implements Serializable
{
private ArrayList<BookingDTO> bookings;
public String viewBookings()
{
bookings = new ArrayList();
bookings = (ArrayList<BookingDTO>) AdminCommandFactory
.createCommand(
AdminCommandFactory.GET_ALL_BOOKINGS)
.execute();
if (!bookings.isEmpty())
{
return "View Bookings";
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Error: No Bookings."));
return null;
}
}
public String cancelBooking(BookingDTO booking)
{
boolean cancelOK = false;
cancelOK = (boolean) AdminCommandFactory
.createCommand(
AdminCommandFactory.CANCEL_BOOKING, booking)
.execute();
if(cancelOK)
{
bookings.remove(booking);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Booking Cancelled."));
return "Cancelled";
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Error: Could not cancel booking."));
return null;
}
}
public ArrayList<BookingDTO> getBookings()
{
return bookings;
}
public void setBookings(ArrayList<BookingDTO> bookings)
{
this.bookings = bookings;
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_Library/src/dto/DepotDTO.java
package dto;
import java.util.ArrayList;
/**
*
* @author Rhys
*/
public class DepotDTO
{
private int depotId;
private String name;
private ArrayList<RouteDTO> depotRoutes;
private ArrayList<DeliveryDTO> depotDeliveries;
public DepotDTO()
{
}
public DepotDTO(int depotId, String name)
{
this.depotId = depotId;
this.name = name;
}
public int getDepotId()
{
return depotId;
}
public void setDepotId(int depotId)
{
this.depotId = depotId;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public ArrayList<RouteDTO> getDepotRoutes()
{
return depotRoutes;
}
public void setDepotRoutes(ArrayList<RouteDTO> depotRoutes)
{
this.depotRoutes = depotRoutes;
}
public ArrayList<DeliveryDTO> getDepotDeliveries()
{
return depotDeliveries;
}
public void setDepotDeliveries(ArrayList<DeliveryDTO> depotDeliveries)
{
this.depotDeliveries = depotDeliveries;
}
}
<file_sep>/WMAD/WMAD_assignment_2/app/src/main/java/com/example/rhysj/wmad_assignment_2/ViewBookingsActivity.java
package com.example.rhysj.wmad_assignment_2;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.rhysj.wmad_assignment_2.DTO.BookingDTO;
import com.example.rhysj.wmad_assignment_2.DTO.FilmDTO;
import com.example.rhysj.wmad_assignment_2.ListAdapter.BookingListAdapter;
import com.example.rhysj.wmad_assignment_2.ListAdapter.FilmListAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
public class ViewBookingsActivity extends AppCompatActivity implements Response.Listener<String>, AdapterView.OnItemClickListener
{
private NavigationSlider navView;
private ArrayList<BookingDTO> bookings;
private BookingDTO selectedBooking;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Sets which xml file to load
setContentView(R.layout.activity_view_bookings);
navView = new NavigationSlider(this);
getSupportActionBar().setTitle("View Bookings");
displayBookings();
}
private void displayBookings()
{
BaseConnectionHandler BCH = new BaseConnectionHandler();
String urlPath = BCH.baseConnection + "/AdminUI/booking";
StringRequest stringRequest = new StringRequest(Request.Method.GET, urlPath, this,
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
selectedBooking = bookings.get(position);
}
@Override
public void onResponse(String response)
{
if(!response.toString().equals("true") && !response.toString().equals("false"))
{
Gson gson = new Gson();
bookings = gson.fromJson(response, new TypeToken<ArrayList<BookingDTO>>() {
}.getType());
ListView list = findViewById(R.id.bookings_listview);
BookingListAdapter adapter = new BookingListAdapter(bookings, this);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
else if(response.toString().equals("true"))
{
Toast.makeText(getApplicationContext(), "Booking deleted successfully.", Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, ViewBookingsActivity.class);
startActivity(intent);
}
else
{
Toast.makeText(getApplicationContext(), "Failed to delete booking.", Toast.LENGTH_LONG).show();
}
}
public void deleteShowing(View view)
{
BaseConnectionHandler BCH = new BaseConnectionHandler();
String urlPath = BCH.baseConnection + "/AdminUI/booking"
+ "/" + selectedBooking.getBookingID()
+ "/" + selectedBooking.getShowing().getShowingID()
+ "/" + selectedBooking.getQuantity();
StringRequest stringRequest = new StringRequest(Request.Method.DELETE, urlPath, this,
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Models/Booking.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Models
{
public class Booking
{
public long Id { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public Boolean LateReturn { get; set; }
public Boolean StartHalfDay { get; set; }
public Boolean EndHalfDay { get; set; }
public Boolean Collected { get; set; }
public decimal Price { get; set; }
public ApplicationUser User { get; set; }
public Vehicle Vehicle { get; set; }
public List<EquipmentBooking> EquipmentBookings { get; set; }
public Booking()
{
}
public Booking(long id, DateTime startDate, DateTime endDate, bool lateReturn, bool startHalfDay, bool endHalfDay, bool collected, ApplicationUser user, Vehicle vehicle, List<EquipmentBooking> equipmentBookings)
{
Id = id;
StartDate = startDate;
EndDate = endDate;
LateReturn = lateReturn;
StartHalfDay = startHalfDay;
EndHalfDay = endHalfDay;
Collected = collected;
User = user;
Vehicle = vehicle;
EquipmentBookings = equipmentBookings;
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Handlers/BookingHandler.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers
{
public class BookingHandler
{
ApplicationDbContext DbContext;
public BookingHandler(ApplicationDbContext dbContext)
{
DbContext = dbContext;
}
public async Task<List<Booking>> GetAllBookingsForVehicle(long vehicleId)
{
List<Booking> bookingsForVehicle = await DbContext.Booking.Where(booking => booking.Vehicle.Id == vehicleId)
.Include(booking => booking.User)
.OrderByDescending(booking => booking.StartDate)
.ToListAsync();
return bookingsForVehicle;
}
public async Task<List<Booking>> GetAllBookingsForUser(string userId)
{
List<Booking> bookingsForUser = await DbContext.Booking.Where(booking => booking.User.Id == userId && (booking.EndDate > DateTime.Today || booking.Collected == false))
.Include(booking => booking.Vehicle)
.OrderByDescending(booking => booking.StartDate)
.ToListAsync();
return bookingsForUser;
}
public async Task<List<Booking>> GetCoincidingBookings(DateTime requestedStartDate, DateTime requestedEndDate)
{
List<Booking> coincidingBookings = await DbContext.Booking
.Where(booking => (booking.StartDate.Date <= requestedStartDate.Date && booking.EndDate.Date >= requestedStartDate.Date) ||
(booking.StartDate.Date < requestedEndDate.Date && requestedEndDate.Date < booking.EndDate.Date) ||
(requestedStartDate.Date < booking.StartDate.Date && booking.StartDate.Date < requestedEndDate.Date))
.Include(booking => booking.User)
.Include(booking => booking.Vehicle)
.ToListAsync();
return coincidingBookings;
}
public async Task<int> AddBooking(Booking newBooking, List<Equipment> chosenEquipmentList)
{
newBooking.User = await DbContext.User.FindAsync(newBooking.User.Id);
newBooking.Vehicle = await DbContext.Vehicle.FindAsync(newBooking.Vehicle.Id);
await DbContext.Booking.AddAsync(newBooking);
bool equipmentBookingsAdded = await CreateEquipmentBookings(newBooking, chosenEquipmentList);
if(equipmentBookingsAdded == false)
{
return 0;
}
var result = await DbContext.SaveChangesAsync();
return result;
}
public async Task<int> UpdateBooking(Booking editedBooking, List<Equipment> chosenEquipmentList)
{
int equipmentBookingsCleared = 0;
Booking uneditedBooking = await GetBooking(editedBooking.Id);
bool equipmentEdited = false;
if(uneditedBooking != null)
{
if (uneditedBooking.StartDate.Date != editedBooking.StartDate.Date)
{
uneditedBooking.StartDate = editedBooking.StartDate;
}
if (uneditedBooking.StartHalfDay != editedBooking.StartHalfDay)
{
uneditedBooking.StartHalfDay = editedBooking.StartHalfDay;
}
if (uneditedBooking.EndDate.Date != editedBooking.EndDate.Date)
{
uneditedBooking.EndDate = editedBooking.EndDate;
}
if(uneditedBooking.EndHalfDay != editedBooking.EndHalfDay)
{
uneditedBooking.EndHalfDay = editedBooking.EndHalfDay;
}
if (uneditedBooking.LateReturn != editedBooking.LateReturn)
{
uneditedBooking.LateReturn = editedBooking.LateReturn;
}
if (uneditedBooking.Collected != editedBooking.Collected)
{
uneditedBooking.Collected = editedBooking.Collected;
}
if (uneditedBooking.Price != editedBooking.Price)
{
uneditedBooking.Price = editedBooking.Price;
}
if (uneditedBooking.Price != editedBooking.Price)
{
uneditedBooking.Price = editedBooking.Price;
}
if(chosenEquipmentList.Count != uneditedBooking.EquipmentBookings.Count)
{
equipmentBookingsCleared = await ClearBookingEquipmentBookings(uneditedBooking.EquipmentBookings);
if (equipmentBookingsCleared < 1)
{
return 0;
}
}
else
{
foreach(EquipmentBooking equipmentBooking in uneditedBooking.EquipmentBookings)
{
if(!chosenEquipmentList.Contains(equipmentBooking.Equipment))
{
equipmentEdited = true;
}
}
if(equipmentEdited)
{
equipmentBookingsCleared = await ClearBookingEquipmentBookings(uneditedBooking.EquipmentBookings);
if (equipmentBookingsCleared < 1)
{
return 0;
}
}
}
DbContext.Booking.Update(uneditedBooking);
await CreateEquipmentBookings(uneditedBooking, chosenEquipmentList);
return await DbContext.SaveChangesAsync();
}
return 0;
}
public async Task<Booking> GetBooking(long bookingId)
{
Booking booking = await DbContext.Booking.Include(b => b.Vehicle)
.Include(b => b.User)
.SingleOrDefaultAsync(b => b.Id == bookingId);
booking.EquipmentBookings = await GetBookingEquipment(booking);
return booking;
}
public async Task<List<EquipmentBooking>> GetBookingEquipment(Booking booking)
{
List<EquipmentBooking> equipmentBookingsForBooking = await DbContext
.EquipmentBooking
.Where(eb => eb.Booking.Id == booking.Id)
.Include(eb => eb.Equipment)
.ToListAsync();
return equipmentBookingsForBooking;
}
public async Task<bool> CreateEquipmentBookings(Booking booking, List<Equipment> equipmentList)
{
try
{
for (int i = 0; i < equipmentList.Count; i++)
{
equipmentList[i] = await DbContext.Equipment.FindAsync(equipmentList[i].Id);
EquipmentBooking equipmentBooking = new EquipmentBooking();
equipmentBooking.Booking = booking;
equipmentBooking.Equipment = equipmentList[i];
await DbContext.EquipmentBooking.AddAsync(equipmentBooking);
}
return true;
}
catch(Exception e)
{
return false;
}
}
public async Task<int> ClearBookingEquipmentBookings(List<EquipmentBooking> equipmentBookings)
{
DbContext.EquipmentBooking.RemoveRange(equipmentBookings);
return await DbContext.SaveChangesAsync();
}
public async Task<int> DeleteBooking(long bookingId)
{
Booking booking = await GetBooking(bookingId);
await ClearBookingEquipmentBookings(booking.EquipmentBookings);
DbContext.Booking.Remove(booking);
return await DbContext.SaveChangesAsync();
}
public async Task<int> CollectBooking(long bookingId)
{
Booking booking = await GetBooking(bookingId);
booking.Collected = true;
DbContext.Booking.Update(booking);
return await DbContext.SaveChangesAsync();
}
}
}
<file_sep>/WMAD/CinemaBookingSystem/src/java/customerUI/CustomerCommandFactory.java
package customerUI;
import dto.CinemaDTO;
import dto.ScreenDTO;
import dto.ShowingDTO;
import dto.UserDTO;
import java.util.ArrayList;
/**
*
* @author <NAME>
*/
public class CustomerCommandFactory
{
public static final int REGISTER_CUSTOMER = 1;
public static final int LOGIN_CUSTOMER = 2;
public static final int GET_ALL_CINEMAS = 3;
public static final int GET_CINEMA_SCREENS = 4;
public static final int GET_SCREEN_SHOWINGS = 5;
public static final int UPDATE_ACCOUNT_DETAILS = 6;
public static final int BOOK_TICKETS = 7;
public static CustomerCommand createCommand(int commandType, UserDTO customer)
{
switch (commandType)
{
case REGISTER_CUSTOMER:
return new RegisterCustomerCommand(customer);
case UPDATE_ACCOUNT_DETAILS:
return new UpdateAccountDetailsCommand(customer);
default:
return null;
}
}
public static CustomerCommand createCommand(int commandType, String username, String password)
{
switch (commandType)
{
case LOGIN_CUSTOMER:
return new LoginCustomerCommand(username, password);
default:
return null;
}
}
public static CustomerCommand createCommand(int commandType)
{
switch (commandType)
{
case GET_ALL_CINEMAS:
return new GetAllCinemasCommand();
default:
return null;
}
}
public static CustomerCommand createCommand(int commandType, ArrayList<CinemaDTO> cinemas)
{
switch (commandType)
{
case GET_CINEMA_SCREENS:
return new GetCinemaScreensCommand(cinemas);
default:
return null;
}
}
public static CustomerCommand createCommand(int commandType, ScreenDTO screen)
{
switch (commandType)
{
case GET_SCREEN_SHOWINGS:
return new GetScreenShowingsCommand(screen);
default:
return null;
}
}
public static CustomerCommand createCommand(int commandType, ShowingDTO showing, UserDTO customer, int noOfSeats)
{
switch (commandType)
{
case BOOK_TICKETS:
return new BookTicketsCommand(showing, customer, noOfSeats);
default:
return null;
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/DataParallelismProj/CommandsFactory/GetAllSuppliersCommand.cs
using DataParallelismProj.Handler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataParallelismProj.CommandsFactory
{
class GetAllSuppliersCommand : ICommand
{
OrderHandler orderHandler;
public GetAllSuppliersCommand()
{
orderHandler = new OrderHandler();
}
public object Execute()
{
return orderHandler.GetAllSuppliers();
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-ejb/src/java/application_ui/DeliverySearchCommand.java
package application_ui;
import ejb.DeliveryHandlerLocal;
import javax.ejb.EJB;
import javax.ejb.Stateless;
/**
*
* @author Rhys
*/
@Stateless
public class DeliverySearchCommand implements DeliverySearchCommandLocal
{
private int deliveryId;
@EJB
private DeliveryHandlerLocal deliveryHandler;
@Override
public void setDeliveryId(int deliveryId)
{
this.deliveryId = deliveryId;
}
@Override
public Object execute()
{
return deliveryHandler.searchForDelivery(deliveryId);
}
}
<file_sep>/OOAE/T2/T2-05/wk2-05_lec1_BuilderProj/wk2-05_lec1_VisitorProj/src/model/ConsultantHandler.java
package model;
import builder.ConsultantBuilder;
import database.Consultant;
import database.DatabaseConnectionPool;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
/**
*
* @author <NAME>
*/
public class ConsultantHandler
{
private static final String FIND_ALL = "Select * from Consultant";
public ArrayList<Consultant> findAllConsultants()
{
ArrayList<Consultant> list = new ArrayList<>();
int oldConNo = -1;
ConsultantBuilder cBuilder = null;
DatabaseConnectionPool pool = DatabaseConnectionPool.getInstance();
Connection con = pool.getAvailableConnection();
try
{
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(FIND_ALL);
while (rs.next())
{
int conNo = rs.getInt("CON_ID");
if (conNo != oldConNo)
{
if (cBuilder != null)
{
list.add(cBuilder.build());
}
cBuilder = new ConsultantBuilder()
.withId(conNo)
.withName(rs.getString("NAME"))
.withPrice(rs.getInt("PRICE"));
oldConNo = conNo;
}
}
if (cBuilder != null)
{
list.add(cBuilder.build());
}
rs.close();
stmt.close();
pool.returnConnection(con);
return list;
}
catch (SQLException sqle)
{
sqle.printStackTrace(System.err);
return list;
}
}
}
<file_sep>/WMAD/WMAD_assignment_2/app/src/main/java/com/example/rhysj/wmad_assignment_2/ViewShowingsActivity.java
package com.example.rhysj.wmad_assignment_2;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.rhysj.wmad_assignment_2.DTO.ScreenDTO;
import com.example.rhysj.wmad_assignment_2.DTO.ShowingDTO;
import com.example.rhysj.wmad_assignment_2.ListAdapter.ShowingListAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
/**
* Created by <NAME> on 05/04/2018.
*/
public class ViewShowingsActivity extends AppCompatActivity implements Response.Listener<String>, AdapterView.OnItemClickListener
{
private NavigationSlider navView;
private ArrayList<ShowingDTO> showings;
private ScreenDTO selectedScreen;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Sets which xml file to load
setContentView(R.layout.activity_view_showings);
navView = new NavigationSlider(this);
getSupportActionBar().setTitle("View Showings");
Intent intent = getIntent();
selectedScreen = (ScreenDTO) intent.getSerializableExtra("selectedScreen");
viewShowings();
SharedPreferencesHandler SPH = SharedPreferencesHandler.getInstance(getApplicationContext());
if(SPH.isUserLoggedIn())
{
if(SPH.getLoggedInUser().isIsAdmin())
{
findViewById(R.id.showing_add_showing).setVisibility(View.VISIBLE);
}
else
{
findViewById(R.id.showing_add_showing).setVisibility(View.INVISIBLE);
}
}
else
{
findViewById(R.id.showing_add_showing).setVisibility(View.INVISIBLE);
}
}
@Override
public void onBackPressed()
{
if(!navView.backPressed())
{
super.onBackPressed();
}
}
public void viewShowings()
{
String encodedScreenName = "";
BaseConnectionHandler BCH = new BaseConnectionHandler();
try
{
encodedScreenName = URLEncoder.encode(selectedScreen.getScreenName(), "UTF-8");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
String urlPath = BCH.baseConnection + "/CustomerUI/showing/" + selectedScreen.getScreenID()
+ "/" + encodedScreenName
+ "/" + selectedScreen.getCinema().getCinemaID()
+ "/" + selectedScreen.getCinema().getName();
StringRequest stringRequest = new StringRequest(Request.Method.GET, urlPath, this,
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
}
@Override
public void onResponse(String response)
{
Gson gson = new Gson();
showings = gson.fromJson(response, new TypeToken<ArrayList<ShowingDTO>>(){}.getType());
ListView list = findViewById(R.id.showings_listview);
ShowingListAdapter adapter = new ShowingListAdapter(showings, this);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
ShowingDTO selectedShowing = showings.get(position);
if(SharedPreferencesHandler.getInstance(this).isUserLoggedIn())
{
if(!SharedPreferencesHandler.getInstance(this).getLoggedInUser().isIsAdmin())
{
Intent intent = new Intent(this, BookTicketsActivity.class);
intent.putExtra("selectedShowing", selectedShowing);
startActivity(intent);
}
else
{
Toast.makeText(getApplicationContext(), "Admin can not book tickets.", Toast.LENGTH_LONG ).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Log in to book seats for: " + selectedShowing.getFilm().getTitle() + " " + selectedShowing.getTime(), Toast.LENGTH_LONG ).show();
}
}
public void addShowing(View view)
{
if(SharedPreferencesHandler.getInstance(this).getLoggedInUser().isIsAdmin())
{
Intent intent = new Intent(this, AddShowingActivity.class);
intent.putExtra("selectedScreen", selectedScreen);
startActivity(intent);
}
}
}
<file_sep>/WMAD/CinemaBookingSystem/src/java/customerUI/LoginCustomerCommand.java
package customerUI;
import handler.CustomerHandler;
/**
*
* @author <NAME>
*/
public class LoginCustomerCommand implements CustomerCommand
{
private final String username;
private final String password;
private CustomerHandler custHndlr = null;
public LoginCustomerCommand(String username, String password)
{
this.username = username;
this.password = <PASSWORD>;
custHndlr = CustomerHandler.getInstance();
}
@Override
public Object execute()
{
return custHndlr.checkCustomerCredentials(username, password);
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/SetFolderPathCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFDataParallelismProj.Handler;
namespace WPFDataParallelismProj.CommandsFactory
{
class SetFolderPathCommand : ICommand
{
private FileHandler fileHandler;
private string selectedFolderPath;
public SetFolderPathCommand(string selectedFolderPath)
{
fileHandler = FileHandler.GetInstance();
this.selectedFolderPath = selectedFolderPath;
}
public async Task<object> Execute()
{
return await fileHandler.SetFolderPath(selectedFolderPath);
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Models/FraudulentClaim.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Models
{
public class FraudulentClaim
{
public int ID { get; set; }
public string FamilyName { get; set; }
public string Forenames { get; set; }
public DateTime DateOfBirth { get; set; }
public string AddressOfClaim { get; set; }
public DateTime DateOfClaim { get; set; }
public int InsurerCode { get; set; }
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/ViewModels/UserSearchResultsViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.ViewModels
{
public class UserSearchResultsViewModel
{
public string UserId { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public bool IdentificationVerified { get; set; }
public bool AddressVerified { get; set; }
public bool DBSChecked { get; set; }
public bool BoardingLicenseVerified { get; set; }
public int NumberOfRecommendations { get; set; }
public string PhotoFolderSource { get; set; }
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Models/UserReport.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.Models
{
public class UserReport
{
[Required]
public int Id { get; set; }
[Required]
public ApplicationUser User { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
public UserReport()
{
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/UpdateVehicleCostPerDayCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class UpdateVehicleCostPerDayCommand : ICommand
{
private VehicleHandler VehicleHandler;
private long VehicleId;
private int NewCostPerDay;
public UpdateVehicleCostPerDayCommand(ApplicationDbContext dbContext, long vehicleId, int newCostPerDay)
{
VehicleHandler = new VehicleHandler(dbContext);
VehicleId = vehicleId;
NewCostPerDay = newCostPerDay;
}
public async Task<object> Execute()
{
return await VehicleHandler.UpdateVehicleCostPerDay(VehicleId, NewCostPerDay);
}
}
}
<file_sep>/OOAE/T2/T2-04/CompositePatternProductProj/src/compositepatternproductproj/CompositePatternProductProj.java
package compositepatternproductproj;
import Product.*;
import java.util.ArrayList;
/**
*
* @author <NAME>
*/
public class CompositePatternProductProj
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
ArrayList<Product> listOfProducts = new ArrayList<>();
createSimpleProducts(listOfProducts);
createComplexProducts(listOfProducts);
for (Product p : listOfProducts)
{
System.out.println(p.toString());
}
}
public static void createSimpleProducts(ArrayList<Product> listOfProducts)
{
//Create hammer product.
Product hammer = new SimpleProduct("Hammer", 19.95);
//Add hammer to the list of products.
listOfProducts.add(hammer);
//Create assorted nails product
Product nails = new SimpleProduct("Assorted nails", 9.95);
//Add assorted nails to the list of products.
listOfProducts.add(nails);
//Create glass front product
Product glass = new SimpleProduct("Glass front", 0.80);
//Add glass front to the list of products.
listOfProducts.add(glass);
//Create frame product
Product frame = new SimpleProduct("Frame", 1.20);
//Add frame to the list of products.
listOfProducts.add(frame);
//Create backing board product
Product board = new SimpleProduct("Backing board", 0.30);
//Add backing board to the list of products.
listOfProducts.add(board);
}
public static void createComplexProducts(ArrayList<Product> listOfProducts)
{
//Create complex (picture) product.
Product picture = new ComplexProduct("Picture");
//Add products to picture
picture.addProduct(new SimpleProduct("Glass front", 0.80));
picture.addProduct(new SimpleProduct("Frame", 1.20));
picture.addProduct(new SimpleProduct("Backing board", 0.30));
//Add complex (picture) product to the list of products.
listOfProducts.add(picture);
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/FolderPathWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WPFDataParallelismProj
{
/// <summary>
/// Interaction logic for FolderPathWindow.xaml
/// </summary>
public partial class FolderPathWindow : Window
{
public String SelectedPath { get; set; }
public FolderPathWindow()
{
InitializeComponent();
}
private void Browse_Button_Click(object sender, RoutedEventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
FBD.ShowDialog();
Folder_Path_TextBox.Text = FBD.SelectedPath;
}
private void Submit_Button_Click(object sender, RoutedEventArgs e)
{
SelectedPath = Folder_Path_TextBox.Text;
this.Close();
}
}
}
<file_sep>/OOAE/T2/T2-04/CompositePatternProductProj/src/Product/SimpleProduct.java
package Product;
import java.util.ArrayList;
/**
*
* @author <NAME>
*/
public class SimpleProduct implements Product
{
private String description;
private double price;
public SimpleProduct(String description, double price)
{
this.description = description;
this.price = price;
}
@Override
public String toString()
{
return description + " £" + price;
}
@Override
public void addProduct(Product product)
{
throw new UnsupportedOperationException("Not supported."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void removeProduct(Product product)
{
throw new UnsupportedOperationException("Not supported."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public ArrayList<Product> getChildren()
{
throw new UnsupportedOperationException("Not supported."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public double getPrice()
{
return price;
}
@Override
public String getDescription()
{
return description;
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_J016984C-war/src/java/managed_bean/DateConverter.java
package managed_bean;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
@FacesConverter(value = "dateConverter")
public class DateConverter implements Converter
{
private final SimpleDateFormat sdf;
public DateConverter()
{
sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(false);
}
@Override
public Object getAsObject(FacesContext context,
UIComponent component,
String dateValue) throws ConverterException
{
try
{
Date d = sdf.parse(dateValue);
return d;
}
catch (ParseException e)
{
throw new ConverterException(e);
}
}
@Override
public String getAsString(FacesContext context,
UIComponent component,
Object value) throws ConverterException
{
if (value == null)
{
return "";
}
if (value instanceof Date)
{
Date d = (Date)value;
return sdf.format(d);
}
String msgInfo = "Unexpected type " + value.getClass().getName();
FacesMessage msg = new FacesMessage("Conversion error",
msgInfo);
FacesContext.getCurrentInstance().addMessage(null, msg);
throw new ConverterException(msg);
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Models/Equipment.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Models
{
public class Equipment
{
public long Id { get; set; }
public String Name { get; set; }
public Decimal Price { get; set; }
public int Count { get; set; }
public List<EquipmentBooking> EquipmentBookings { get; set; }
public Equipment()
{
}
public Equipment(long id, string name, decimal price, List<EquipmentBooking> equipmentBookings)
{
Id = id;
Name = name;
Price = price;
EquipmentBookings = equipmentBookings;
}
}
}
<file_sep>/OOAE/T1/T1-04 check portfolio/ShapesProj/src/shapesproj/Drawable.java
package shapesproj;
import java.awt.Color;
import java.awt.Graphics;
interface Drawable
{
void setColour(Color c);
void setPosition(int x, int y);
void draw(Graphics g);
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Repositories/SearchRepository.cs
using AnimalCareSystem.ApplicationUI;
using AnimalCareSystem.Data;
using AnimalCareSystem.Models;
using AnimalCareSystem.ViewModels;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AnimalCareSystem.Repositories
{
public class SearchRepository : IRepository
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private ApplicationDbContext _dbContext;
public SearchRepository(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ApplicationDbContext dbContext)
{
_userManager = userManager;
_signInManager = signInManager;
_dbContext = dbContext;
}
public Task<object> Create(object obj)
{
throw new NotImplementedException();
}
public Task<object> Delete(object obj)
{
throw new NotImplementedException();
}
public async Task<object> Get(object obj)
{
KeyValuePair<string, object> requestData = (KeyValuePair<string, object>)obj;
switch (requestData.Key)
{
case "userSearchResults":
UserSearchViewModel userSearchViewModel = (UserSearchViewModel)requestData.Value;
UserSearchResultsListViewModel searchResults = (UserSearchResultsListViewModel)await SearchForUsers(userSearchViewModel);
return searchResults;
default:
return null;
}
}
public Task<object> Update(object obj)
{
throw new NotImplementedException();
}
public async Task<UserSearchResultsListViewModel> SearchForUsers(UserSearchViewModel userSearchViewModel)
{
UserSearchResultsListViewModel userSearchResults = new UserSearchResultsListViewModel();
List<UserSearchResultsViewModel> userSearchResultList = new List<UserSearchResultsViewModel>();
userSearchResults.Users = userSearchResultList;
if (userSearchViewModel.City != null)
{
string city = userSearchViewModel.City;
List<ApplicationUser> usersByCity = (List<ApplicationUser>)await CommandFactory.CreateCommand(CommandFactory.GET_USERS_BY_CITY, city, _dbContext).Execute();
foreach(ApplicationUser user in usersByCity)
{
UserSearchResultsViewModel userSearchResultsViewModel = new UserSearchResultsViewModel();
int numberOfRecommendations = 0;
userSearchResultsViewModel.UserId = user.Id;
userSearchResultsViewModel.Forename = user.Forename;
userSearchResultsViewModel.Surname = user.Surname;
userSearchResultsViewModel.IdentificationVerified = user.IdentificationVerified;
userSearchResultsViewModel.AddressVerified = user.AddressVerified;
userSearchResultsViewModel.DBSChecked = user.DBSChecked;
userSearchResultsViewModel.BoardingLicenseVerified = user.BoardingLicenseVerified;
if(user.ReceivedReviews != null)
{
foreach (UserReview userReview in user.ReceivedReviews)
{
if (userReview.Recommended)
{
numberOfRecommendations = numberOfRecommendations + 1;
}
}
}
userSearchResultsViewModel.NumberOfRecommendations = numberOfRecommendations;
userSearchResultsViewModel.PhotoFolderSource = user.PhotoFolderSource;
userSearchResults.Users.Add(userSearchResultsViewModel);
}
}
return userSearchResults;
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/Handler/OrderHandler.cs
using WPFDataParallelismProj.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Threading;
namespace WPFDataParallelismProj.Handler
{
class OrderHandler
{
public async Task<object> GetTotalCostAllOrders(HashSet<Order> orders)
{
double totalCost = 0;
await Task.Run(() =>
{
//var priceArray = from o in orders select o.Price;
totalCost = orders.Sum(o => o.Price);
});
return totalCost;
}
public async Task<object> GetTotalCostForStore(HashSet<Order> orders, Store store)
{
//HashSet<Order> storeOrders = (HashSet<Order>) from o in orders where o.Store.Equals(store) select o;
double totalCostforStore = 0;
await Task.Run(() =>
{
totalCostforStore = orders.Where(o => o.Store.Equals(store)).Sum(o => o.Price);
});
return totalCostforStore;
}
public async Task<object> GetTotalCostInWeekForSupplierTypeForStore(HashSet<Order> orders, Date date, Store store, string supplierType)
{
double totalCostInWeekForSupplierTypeForStore = 0;
await Task.Run(() =>
{
totalCostInWeekForSupplierTypeForStore = orders.Where(o => o.Supplier.SupplierType.Equals(supplierType)
&& o.Store.Equals(store) && o.Date.Equals(date)).Sum(o => o.Price);
});
return totalCostInWeekForSupplierTypeForStore;
}
public async Task<object> GetTotalCostForSupplierTypeForStore(HashSet<Order> orders, Store store, string supplierType)
{
double totalCostForSupplierTypeForStore = 0;
await Task.Run(() =>
{
totalCostForSupplierTypeForStore = orders.Where(o => o.Supplier.SupplierType.Equals(supplierType)
&& o.Store.Equals(store)).Sum(o => o.Price);
});
return totalCostForSupplierTypeForStore;
}
public async Task<object> GetTotalCostInWeekForSupplierType(HashSet<Order> orders, Date date, string supplierType)
{
double totalCostInWeekForSupplierType = 0;
await Task.Run(() =>
{
totalCostInWeekForSupplierType = orders.Where(o => o.Supplier.SupplierType.Equals(supplierType)
&& o.Date.Equals(date)).Sum(o => o.Price);
});
return totalCostInWeekForSupplierType;
}
public async Task<object> GetTotalCostForSupplierType(HashSet<Order> orders, string supplierType)
{
double totalCostForSupplierType = 0;
await Task.Run(() =>
{
totalCostForSupplierType = orders.Where(o => o.Supplier.SupplierType.Equals(supplierType)).Sum(o => o.Price);
});
return totalCostForSupplierType;
}
public async Task<object> GetTotalCostForSupplier(HashSet<Order> orders, string supplier)
{
double totalCostForSupplier = 0;
await Task.Run(() =>
{
totalCostForSupplier = orders.Where(o => o.Supplier.SupplierName.Equals(supplier)).Sum(o => o.Price);
});
return totalCostForSupplier;
}
public async Task<object> GetTotalCostInWeekForStore(HashSet<Order> orders, Date date, Store store)
{
double totalCostInWeekForStore = 0;
await Task.Run(() =>
{
totalCostInWeekForStore = orders.Where(o => o.Date.Equals(date)
&& o.Store.Equals(store)).Sum(o => o.Price);
});
return totalCostInWeekForStore;
}
public async Task<object> GetTotalCostInWeek(HashSet<Order> orders, Date date)
{
double totalCostForWeek = 0;
await Task.Run(() =>
{
totalCostForWeek = orders.Where(o => o.Date.Equals(date)).Sum(o => o.Price);
});
return totalCostForWeek;
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ViewModels/AddVehicleViewModel.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels
{
public class AddVehicleViewModel
{
[Required]
public String Manufacturer { get; set; }
[Required]
public String Model { get; set; }
[Required]
[Range(3,5, ErrorMessage = "The number of doors cannot be below 3 or above 5.")]
public int Doors { get; set; }
[Required]
[Range(2, 7, ErrorMessage = "The number of seats cannot be below 2 or above 7.")]
public int Seats { get; set; }
[Required]
public String Colour { get; set; }
[Required]
[Range(20.00, Double.MaxValue, ErrorMessage = "Cost per day must be a minimum of 20.00.")]
public decimal CostPerDay { get; set; }
[Required(ErrorMessage = "A vehicle type is required")]
public int VehicleTypeId { get; set; }
[Required(ErrorMessage = "A fuel type is required")]
public int FuelId { get; set; }
[Required(ErrorMessage = "A tranmission type is required")]
public int TransmissionId { get; set; }
[Required(ErrorMessage = "A vehicle image file is required")]
public IFormFile vehicleImageFile { get; set; }
}
}
<file_sep>/FYP/Web_Application/AnimalCareSystem/AnimalCareSystem/Controllers/ProfileController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AnimalCareSystem.Data;
using AnimalCareSystem.Models;
using AnimalCareSystem.Repositories;
using AnimalCareSystem.ViewModels;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
namespace AnimalCareSystem.Controllers
{
[Route("profile")]
public class ProfileController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ApplicationDbContext _dbContext;
private readonly ProfileRepository _profileRepository;
private readonly IEmailSender _emailSender;
public ProfileController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ApplicationDbContext dbContext, IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_dbContext = dbContext;
_profileRepository = new ProfileRepository(userManager, signInManager, dbContext);
_emailSender = emailSender;
}
[HttpGet]
public async Task<IActionResult> EditProfile(string userId)
{
KeyValuePair<string, object> editUserProfileKeyValuePair = new KeyValuePair<string, object>("editProfile", userId);
UserProfileEditViewModel userProfileEditViewModel = (UserProfileEditViewModel)await _profileRepository.Get(editUserProfileKeyValuePair);
return View(userProfileEditViewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditProfile(UserProfileEditViewModel userProfileEditViewModel)
{
if (ModelState.IsValid)
{
if (userProfileEditViewModel.ProfilePhoto != null)
{
if (!Path.GetExtension(userProfileEditViewModel.ProfilePhoto.FileName).Equals(".png", StringComparison.InvariantCultureIgnoreCase) && !Path.GetExtension(userProfileEditViewModel.ProfilePhoto.FileName).Equals(".jpg", StringComparison.InvariantCultureIgnoreCase))
{
TempData["errormessage"] = "Incorrect Image File Type. Please try again!";
return View(userProfileEditViewModel);
}
}
KeyValuePair<string, object> editUserProfileKeyValuePair = new KeyValuePair<string, object>("editProfile", userProfileEditViewModel);
int profileUpdateResult = (int)await _profileRepository.Update(editUserProfileKeyValuePair);
if (profileUpdateResult > 0)
{
TempData["successmessage"] = "Updated successfully!";
return RedirectToAction("Index", "Home");
}
else
{
TempData["errormessage"] = "Failed to Update. Please try again.";
return View(userProfileEditViewModel);
}
}
return View(userProfileEditViewModel);
}
[HttpGet, Route("ownProfile")]
public IActionResult OwnProfile()
{
string loggedInUserId = User.FindFirst(ClaimTypes.NameIdentifier).Value;
return RedirectToAction("UserProfile", "Profile", new { userId = loggedInUserId });
}
[HttpGet, Route("userProfile")]
public async Task<IActionResult> UserProfile(string userId)
{
KeyValuePair<string, object> getUserKeyValuePair = new KeyValuePair<string, object>("getUserProfile", userId);
UserProfileViewModel userProfileViewModel = (UserProfileViewModel)await _profileRepository.Get(getUserKeyValuePair);
string loggedInUserId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (loggedInUserId.Equals(userProfileViewModel.UserId))
{
userProfileViewModel.IsPersonalProfile = true;
}
return View(userProfileViewModel);
}
[HttpPost, Route("contactUser")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ContactUser(UserProfileViewModel userProfileViewModel)
{
if(!ModelState.IsValid)
{
TempData["errormessage"] = "Failed to send email. A Subject is required.";
return RedirectToAction("UserProfile", "profile", new { userId = userProfileViewModel.UserId });
}
//If this was the business version of the app i would get the user of the profile and the logged in user using their id's and then use their emails to send this email.
//However since this is a demo, they will be hard coded.
userProfileViewModel.EmailBody = userProfileViewModel.EmailBody.Replace(Environment.NewLine, "<br/>");
await _emailSender.SendEmailAsync("<EMAIL>", userProfileViewModel.EmailSubject, userProfileViewModel.EmailBody);
return RedirectToAction("UserProfile", "profile", new { userId = userProfileViewModel.UserId });
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/DataParallelismProj/Handler/StoreHandler.cs
using DataParallelismProj.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataParallelismProj.Handler
{
class StoreHandler
{
public List<Store> GetAllStores()
{
return null;
}
}
}
<file_sep>/OOAE/T1/T1-11/ProducerConsumerProj/src/producerconsumerproj/Consumer.java
package producerconsumerproj;
public class Consumer extends Thread
{
private Buffer buffer;
private int consumerNum;
public Consumer(Buffer buffer, int consumerNum)
{
this.buffer = buffer;
this.consumerNum = consumerNum;
}
public void run()
{
for (int i = 0; i < 5; i++)
{
try
{
buffer.getNext(consumerNum);
Thread.sleep(2000);
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted.\n" + e);
}
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/DataParallelismProj/FilePathForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DataParallelismProj
{
public partial class FilePathForm : Form
{
public String SelectedPath { get; set; }
public FilePathForm()
{
InitializeComponent();
}
private void SubmitButton_Click(object sender, EventArgs e)
{
SelectedPath = textBox1.Text;
this.Close();
}
private void BrowseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
FBD.ShowDialog();
textBox1.Text = FBD.SelectedPath;
}
}
}
<file_sep>/OOAE/T2/T2-05/wk2-05_lec1_CommandProj/wk2-05_lec1_CommandProj/src/view/AllDepartmentsView.java
package view;
import database.Department;
import java.util.ArrayList;
public class AllDepartmentsView
{
ArrayList<Department> departments;
public AllDepartmentsView(ArrayList<Department> departments)
{
this.departments = departments;
}
public void print()
{
System.out.println("All departments");
System.out.println("===============");
for (Department dept : departments)
{
System.out.printf("\t%5d %10s %10s\n",
dept.getID(),
dept.getName(),
dept.getLocation());
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/CommandsFactory/GetSuppliersCommand.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WPFDataParallelismProj.DTO;
using WPFDataParallelismProj.Handler;
namespace WPFDataParallelismProj.CommandsFactory
{
class GetSuppliersCommand : ICommand
{
private HashSet<Order> orders;
private SupplierHandler supplierHandler;
public GetSuppliersCommand(HashSet<Order> orders)
{
this.orders = orders;
supplierHandler = new SupplierHandler();
}
public async Task<object> Execute()
{
return await supplierHandler.GetSuppliers(orders);
}
}
}<file_sep>/OOAE/T1/T1-09/cardDeckProj/src/carddeckproj/Hand.java
package carddeckproj;
public class Hand
{
protected Card[] theCards;
private int numCards;
private static final int max = 5;
public Hand()
{
theCards = new Card[max];
numCards = 0;
}
public void addCard(Card aCard)
{
if (numCards < max)
{
theCards[numCards++] = aCard;
}
}
public int getCard(Card card)
{
return card.getRank().getNumVal();
}
public int getHandValue()
{
int value = 0;
for (int i = 0; i < theCards.length; i++)
{
value = value + (theCards[i].getRank().getNumVal());
}
return value;
}
@Override
public String toString()
{
String s = "";
for (int i = 0; i < numCards; i++)
{
s += "\n" + theCards[i];
}
return s;
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI;
using Microsoft.AspNetCore.Identity;
using System.Data.Odbc;
using Microsoft.AspNetCore.Http;
using System.IO;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly ApplicationDbContext DbContext;
private HomeViewModel HomeViewModel;
private UserManager<ApplicationUser> UserManager;
public HomeController(ILogger<HomeController> logger, ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager)
{
_logger = logger;
DbContext = dbContext;
UserManager = userManager;
}
[HttpGet]
public async Task<IActionResult> Index()
{
HomeViewModel = new HomeViewModel();
HomeViewModel.Vehicles = (List<Vehicle>)await CommandFactory.CreateCommand(CommandFactory.GET_VEHICLES, DbContext).Execute();
ApplicationUser currentUser = await UserManager.GetUserAsync(HttpContext.User);
if(currentUser != null)
{
var today = DateTime.Today;
HomeViewModel.Age = (today.Year - currentUser.DateOfBirth.Year);
}
return View(HomeViewModel);
}
[HttpGet, Route("privacy")]
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/WPFDataParallelismProj/DTO/Order.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFDataParallelismProj.DTO
{
class Order
{
public Store Store { get; set; }
public Supplier Supplier { get; set; }
public double Price { get; set; }
public Date Date { get; set; }
public Order()
: this(new Store(), new Date(), new Supplier(), 0.0)
{
}
public Order(Store store, Date date, Supplier supplier, double price)
{
Store = store;
Supplier = supplier;
Price = price;
Date = date;
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_Library/src/dto/DeliveryDTO.java
package dto;
import java.util.Date;
/**
*
* @author Rhys
*/
public class DeliveryDTO
{
private int deliveryId;
private Date deliveryDate;
private DeliveryStatusDTO deliveryStatus;
private DepotDTO depot;
private ParcelDTO parcel;
private RouteDTO route;
public DeliveryDTO()
{
}
public DeliveryDTO(int deliveryId, Date deliveryDate, DeliveryStatusDTO deliveryStatus, DepotDTO depot, ParcelDTO parcel, RouteDTO route)
{
this.deliveryId = deliveryId;
this.deliveryDate = deliveryDate;
this.deliveryStatus = deliveryStatus;
this.depot = depot;
this.parcel = parcel;
this.route = route;
}
public int getDeliveryId()
{
return deliveryId;
}
public void setDeliveryId(int deliveryId)
{
this.deliveryId = deliveryId;
}
public Date getDeliveryDate()
{
return deliveryDate;
}
public void setDeliveryDate(Date deliveryDate)
{
this.deliveryDate = deliveryDate;
}
public DeliveryStatusDTO getDeliveryStatus()
{
return deliveryStatus;
}
public void setDeliveryStatus(DeliveryStatusDTO deliveryStatus)
{
this.deliveryStatus = deliveryStatus;
}
public DepotDTO getDepot()
{
return depot;
}
public void setDepot(DepotDTO depot)
{
this.depot = depot;
}
public ParcelDTO getParcel()
{
return parcel;
}
public void setParcel(ParcelDTO parcel)
{
this.parcel = parcel;
}
public RouteDTO getRoute()
{
return route;
}
public void setRoute(RouteDTO route)
{
this.route = route;
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/RegisterCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class RegisterCommand : ICommand
{
private UserHandler UserHandler;
private ApplicationUser NewUser;
public RegisterCommand(ApplicationUser newUser, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
NewUser = newUser;
UserHandler = new UserHandler(userManager, signInManager);
}
public async Task<object> Execute()
{
return await UserHandler.RegisterUser(NewUser);
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/Models/Fuel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.Models
{
public class Fuel
{
public long Id { get; set; }
public String Type { get; set; }
public Fuel()
{
}
public Fuel(long id, string type)
{
this.Id = id;
this.Type = type;
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ApplicationUI/GetAllBookingsForUserCommand.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Data;
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ApplicationUI
{
public class GetAllBookingsForUserCommand : ICommand
{
private BookingHandler BookingHandler;
private string UserId;
public GetAllBookingsForUserCommand(string userId, ApplicationDbContext dbContext)
{
BookingHandler = new BookingHandler(dbContext);
UserId = userId;
}
public async Task<object> Execute()
{
return await BookingHandler.GetAllBookingsForUser(UserId);
}
}
}
<file_sep>/EEA/Assignment 1/Assignment_1_Project/EEA_Assignment1_J016984C/EEA_Assignment1_Library/test/dto/RouteDTOIT.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
import java.util.ArrayList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Rhys
*/
public class RouteDTOIT
{
private RouteDTO routeDTOInstance = new RouteDTO();
public RouteDTOIT()
{
DepotDTO depotDTOInstance = new DepotDTO();
DeliveryDTO deliveryDTOInstance = new DeliveryDTO();
UserDTO userDTOInstance = new UserDTO();
//Initialise Lists
ArrayList<DeliveryDTO> deliveryList = new ArrayList<DeliveryDTO>();
deliveryList.add(deliveryDTOInstance);
ArrayList<RouteDTO> routeList = new ArrayList<RouteDTO>();
routeList.add(routeDTOInstance);
ArrayList<UserDTO> userList = new ArrayList<UserDTO>();
userList.add(userDTOInstance);
//Create DepotDTO
depotDTOInstance.setDepotId(1);
depotDTOInstance.setName("Test Depot");
depotDTOInstance.setDepotDeliveries(deliveryList);
depotDTOInstance.setDepotRoutes(routeList);
//Create RouteDTO
routeDTOInstance.setRouteId(1);
routeDTOInstance.setName("Test Route");
routeDTOInstance.setDeliveries(deliveryList);
routeDTOInstance.setDepot(depotDTOInstance);
routeDTOInstance.setUsers(userList);
}
@BeforeClass
public static void setUpClass()
{
}
@AfterClass
public static void tearDownClass()
{
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
/**
* Test of getRouteId method, of class RouteDTO.
*/
@Test
public void testGetRouteId()
{
System.out.println("getRouteId");
int expResult = 1;
int result = routeDTOInstance.getRouteId();
assertEquals(expResult, result);
}
/**
* Test of setRouteId method, of class RouteDTO.
*/
@Test
public void testSetRouteId()
{
System.out.println("setRouteId");
int routeId = 2;
RouteDTO instance = new RouteDTO();
instance.setRouteId(routeId);
assertEquals(instance.getRouteId(), routeId);
}
/**
* Test of getName method, of class RouteDTO.
*/
@Test
public void testGetName()
{
System.out.println("getName");
String expResult = "Test Route";
String result = routeDTOInstance.getName();
assertTrue(expResult.equals(result));
}
/**
* Test of setName method, of class RouteDTO.
*/
@Test
public void testSetName()
{
System.out.println("setName");
String name = "<NAME>";
RouteDTO instance = new RouteDTO();
instance.setName(name);
assertTrue(instance.getName().equals(name));
}
/**
* Test of getDepot method, of class RouteDTO.
*/
@Test
public void testGetDepot()
{
System.out.println("getDepot");
DepotDTO result = routeDTOInstance.getDepot();
int expResultId = result.getDepotId();
assertEquals(expResultId, 1);
String expResultName = result.getName();
assertTrue(expResultName.equals("Test Depot"));
ArrayList<DeliveryDTO> expResultDeliveries = result.getDepotDeliveries();
assertTrue(expResultDeliveries != null);
ArrayList<RouteDTO> expResultRoutes = result.getDepotRoutes();
assertTrue(expResultRoutes != null);
}
/**
* Test of setDepot method, of class RouteDTO.
*/
@Test
public void testSetDepot()
{
System.out.println("setDepot");
DepotDTO depot = new DepotDTO();
RouteDTO instance = new RouteDTO();
instance.setDepot(depot);
assertTrue(instance.getDepot() != null);
}
/**
* Test of getUsers method, of class RouteDTO.
*/
@Test
public void testGetUsers()
{
System.out.println("getUsers");
ArrayList<UserDTO> result = routeDTOInstance.getUsers();
assertTrue(result != null);
}
/**
* Test of setUsers method, of class RouteDTO.
*/
@Test
public void testSetUsers()
{
System.out.println("setUsers");
ArrayList<UserDTO> users = new ArrayList<UserDTO>();
RouteDTO instance = new RouteDTO();
instance.setUsers(users);
assertTrue(instance.getUsers() != null);
}
/**
* Test of getDeliveries method, of class RouteDTO.
*/
@Test
public void testGetDeliveries()
{
System.out.println("getDeliveries");
ArrayList<DeliveryDTO> result = routeDTOInstance.getDeliveries();
assertTrue(result != null);
}
/**
* Test of setDeliveries method, of class RouteDTO.
*/
@Test
public void testSetDeliveries()
{
System.out.println("setDeliveries");
ArrayList<DeliveryDTO> deliveries = new ArrayList<DeliveryDTO>();
RouteDTO instance = new RouteDTO();
instance.setDeliveries(deliveries);
assertTrue(instance.getDeliveries() != null);
}
}
<file_sep>/CNA/SimpleClientServer/ChatClient/ChatGUI.cs
using System;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Windows.Forms;
using System.IO;
using Packets;
using System.Runtime.Serialization.Formatters.Binary;
namespace ChatClient
{
public partial class ChatGUI : Form
{
private Thread thread { get; set; }
private TcpClient _tcpClient;
private NetworkStream _stream;
private BinaryReader _reader;
private const string hostname = "127.0.0.1";
private const int port = 4444;
private BinaryWriter _writer;
public ChatGUI()
{
InitializeComponent();
_tcpClient = new TcpClient();
if (Connect(hostname, port))
{
richTextBox1.Text += ("Connected... \n");
try
{
Run();
}
catch (NotConnectedException e)
{
richTextBox1.Text += ("Client not Connected \n");
}
}
else
{
richTextBox1.Text += ("Failed to connect to: " + hostname + ":" + port + "\n");
}
Console.Read();
}
public bool Connect(string hostname, int port)
{
try
{
_tcpClient.Connect(hostname, port);
_stream = _tcpClient.GetStream();
_writer = new BinaryWriter(_stream, Encoding.UTF8);
_reader = new BinaryReader(_stream, Encoding.UTF8);
}
catch (Exception e)
{
richTextBox1.Text += ("Exception: " + e.Message);
return false;
}
return true;
}
public void Run()
{
if (!_tcpClient.Connected) throw new NotConnectedException();
nicknameForm();
thread = new Thread(new ThreadStart(ProcessServerResponse));
thread.Start();
}
private void ProcessServerResponse()
{
try
{
BinaryFormatter formatter = new BinaryFormatter();
// Read the number of incoming bytes
int noOfIncomingBytes;
while ((noOfIncomingBytes = _reader.ReadInt32()) != 0)
{
// Read the bytes for noOfIncomingBytes amount
byte[] bytes = _reader.ReadBytes(noOfIncomingBytes);
//Store the bytes in a MemoryStream
MemoryStream memoryStream = new MemoryStream(bytes);
Packet packet = formatter.Deserialize(memoryStream) as Packet;
switch (packet.type)
{
case PacketType.CHATMESSAGE:
string message = ((ChatMessagePacket)packet).message;
addMessage(message);
break;
}
}
}
catch { }
}
public void addMessage(String value)
{
if (InvokeRequired)
{
//This is only called if AddMessage() is called from another thread than the GUI thread.
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.Text += value + "\n"; });
return;
}
//This is only called if you are calling this method from the thread the richTextBox belongs to.
richTextBox1.Text = value;
}
public void Send(Packet data)
{
MemoryStream mem = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(mem, data);
byte[] buffer = mem.GetBuffer();
try
{
_writer.Write(buffer.Length);
_writer.Write(buffer);
_writer.Flush();
}
catch (IOException ioe)
{
thread.Abort();
_tcpClient.Close();
}
}
private void nicknameForm()
{
Nickname nicknameEntry = new Nickname(_writer);
nicknameEntry.ShowDialog();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
thread.Abort();
_tcpClient.Close();
}
private void sendMessageButton_Click(object sender, EventArgs e)
{
string userInput = textBox1.Text;
ChatMessagePacket chatMessage = new ChatMessagePacket(userInput);
textBox1.Text = "";
if (userInput.Trim() != String.Empty)
{
try
{
Send(chatMessage);
}
catch (Exception exc)
{
richTextBox1.Text += ("Unexpected Error: " + exc.Message + "\n");
}
}
}
//Buy Buttons
private void buyApple_Click(object sender, EventArgs e)
{
string productType = "apple";
BuyProductPacket product = new BuyProductPacket(productType);
try
{
Send(product);
}
catch (Exception exc)
{
richTextBox1.Text += ("Unexpected Error: " + exc.Message + "\n");
}
buyApple.Enabled = false;
}
private void buyPear_Click(object sender, EventArgs e)
{
string productType = "pear";
BuyProductPacket product = new BuyProductPacket(productType);
try
{
Send(product);
}
catch (Exception exc)
{
richTextBox1.Text += ("Unexpected Error: " + exc.Message + "\n");
}
}
private void buyBanana_Click(object sender, EventArgs e)
{
string productType = "banana";
BuyProductPacket product = new BuyProductPacket(productType);
try
{
Send(product);
}
catch (Exception exc)
{
richTextBox1.Text += ("Unexpected Error: " + exc.Message + "\n");
}
}
private void buyPlum_Click(object sender, EventArgs e)
{
string productType = "plum";
BuyProductPacket product = new BuyProductPacket(productType);
try
{
Send(product);
}
catch (Exception exc)
{
richTextBox1.Text += ("Unexpected Error: " + exc.Message + "\n");
}
}
private void buyOrange_Click(object sender, EventArgs e)
{
string productType = "orange";
BuyProductPacket product = new BuyProductPacket(productType);
try
{
Send(product);
}
catch (Exception exc)
{
richTextBox1.Text += ("Unexpected Error: " + exc.Message + "\n");
}
}
private void buyPeach_Click(object sender, EventArgs e)
{
string productType = "peach";
BuyProductPacket product = new BuyProductPacket(productType);
try
{
Send(product);
}
catch (Exception exc)
{
richTextBox1.Text += ("Unexpected Error: " + exc.Message + "\n");
}
}
//Sell buttons
private void sellApple_Click(object sender, EventArgs e)
{
string productType = "apple";
SellProductPacket product = new SellProductPacket(productType);
try
{
Send(product);
}
catch (Exception exc)
{
richTextBox1.Text += ("Unexpected Error: " + exc.Message + "\n");
}
}
private void sellPear_Click(object sender, EventArgs e)
{
string productType = "pear";
SellProductPacket product = new SellProductPacket(productType);
try
{
Send(product);
}
catch (Exception exc)
{
richTextBox1.Text += ("Unexpected Error: " + exc.Message + "\n");
}
}
private void sellBanana_Click(object sender, EventArgs e)
{
string productType = "banana";
SellProductPacket product = new SellProductPacket(productType);
try
{
Send(product);
}
catch (Exception exc)
{
richTextBox1.Text += ("Unexpected Error: " + exc.Message + "\n");
}
}
private void sellPlum_Click(object sender, EventArgs e)
{
string productType = "plum";
SellProductPacket product = new SellProductPacket(productType);
try
{
Send(product);
}
catch (Exception exc)
{
richTextBox1.Text += ("Unexpected Error: " + exc.Message + "\n");
}
}
private void sellOrange_Click(object sender, EventArgs e)
{
string productType = "orange";
SellProductPacket product = new SellProductPacket(productType);
try
{
Send(product);
}
catch (Exception exc)
{
richTextBox1.Text += ("Unexpected Error: " + exc.Message + "\n");
}
}
private void sellPeach_Click(object sender, EventArgs e)
{
string productType = "peach";
SellProductPacket product = new SellProductPacket(productType);
try
{
Send(product);
}
catch (Exception exc)
{
richTextBox1.Text += ("Unexpected Error: " + exc.Message + "\n");
}
}
}
}
<file_sep>/T-BSE/Project/DataParallelismProj/DataParallelismProj/DataParallelismProj/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DataParallelismProj.CommandsFactory;
namespace DataParallelismProj
{
public partial class Form1 : Form
{
FilePathForm FPF = new FilePathForm();
public Form1()
{
InitializeComponent();
FPF.ShowDialog();
richTextBox1.Text = FPF.SelectedPath;
}
private void Load_Data_Button_MouseClick(object sender, MouseEventArgs e)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
bool loaded = false;
Task t1 = new Task(() =>
{
CommandFactory commandFactory = new CommandFactory();
loaded = (bool)commandFactory.CreateCommand(3, FPF.SelectedPath).Execute();
stopWatch.Stop();
Invoke(new MethodInvoker(() =>
{
if (loaded)
{
richTextBox1.Text += "\nLoaded successfully";
richTextBox1.Text += "\nTimeToLoad: " + stopWatch.Elapsed.TotalSeconds;
Application.DoEvents();
}
}));
});
t1.Start();
//Task.WaitAny(t1);
//if (loaded)
//{
// richTextBox1.Text += "\nLoaded successfully";
//}
//richTextBox1.Text += "\nTimeToLoad: " + stopWatch.Elapsed.TotalSeconds;
Load_Data_Button.Text = "Reload Data";
}
}
}
<file_sep>/EIRLSS/EIRLSS-Assignment2-J016984C-Rhys-Jones/EIRLSS-Assignment1-J016984C-Rhys-Jones/ViewModels/VehicleBookingsViewModel.cs
using EIRLSS_Assignment1_J016984C_Rhys_Jones.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace EIRLSS_Assignment1_J016984C_Rhys_Jones.ViewModels
{
public class VehicleBookingsViewModel
{
public long BookingId { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{dd/MM/yyyy}")]
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{dd/MM/yyyy}")]
[DataType(DataType.Date)]
public DateTime EndDate { get; set; }
public long UserId { get; set; }
public string BookedBy { get; set; }
public bool IsCurrentlyOnRental { get; set; }
public bool NotCollected { get; set; }
}
}<file_sep>/WMAD/CinemaBookingSystem/src/java/dto/FilmDTO.java
package dto;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author <NAME>
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class FilmDTO implements Serializable
{
private int filmID;
private String title;
private int ageRating;
private int runtime;
private String description;
FilmDTO()
{
this.filmID = 0;
this.title = "";
this.ageRating = 0;
this.runtime = 0;
this.description = "";
}
/**
*
* @param filmID
* @param title
* @param ageRating
* @param runtime
* @param description
*/
public FilmDTO(int filmID, String title, int ageRating, int runtime, String description)
{
this.filmID = filmID;
this.title = title;
this.ageRating = ageRating;
this.runtime = runtime;
this.description = description;
}
public int getFilmID()
{
return filmID;
}
public String getTitle()
{
return title;
}
public int getAgeRating()
{
return ageRating;
}
public int getRuntime()
{
return runtime;
}
public String getDescription()
{
return description;
}
}
<file_sep>/OOAE/T2/T2-03/AuctionTemplatePatternProj/src/AuctionItem/FineChina.java
package AuctionItem;
/**
* Determines VAT and Commission rates for Fine China Calculates the cost a buyer
* will pay, and the amount a seller will receive.
*
* @author <NAME>
*/
public class FineChina extends AuctionItem
{
private final double VAT = 0.15;
private final double commission = 0.2;
/**
* Constructs FineChina Object and sets the item description.
*
* @param description
*/
public FineChina(String description)
{
super.description = description;
}
/**
* Calculates the cost a buyer will pay for an item of Fine China after VAT.
*
* @param hammerPrice
* @return
*/
@Override
public double calculateCostBuyerPaid(double hammerPrice)
{
return (hammerPrice * VAT);
}
/**
* Calculates the amount a seller will receive for an item of Fine China
* after commission.
*
* @param hammerPrice
* @return
*/
@Override
public double calculateAmountSellerReceived(double hammerPrice)
{
return (hammerPrice * commission);
}
}
| 67f40d74fa111c3e5ade44a9363b0cf46b7a30ce | [
"Java",
"C#",
"Markdown",
"INI"
]
| 284 | C# | RhysWJones/Projects | 2d45ec5720b5e03accae124fe3df01b802ce2ea7 | 079ceda286974f1938c648d7d932b7df2f149ea9 |
refs/heads/master | <file_sep>JThread
=======
Library location and contact
----------------------------
Normally, you should be able to download the latest version of the library
from this url:
[http://research.edm.uhasselt.be/jori/jthread](http://research.edm.uhasselt.be/jori/jthread)
The documentation is in the `doc/manual.tex` LaTeX file, and the resulting
PDF can be found on-line at [http://jthread.readthedocs.io](http://jthread.readthedocs.io).
If you have questions about the library, you can mail me at:
[<EMAIL>](mailto:<EMAIL>)
Disclaimer & copyright
----------------------
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
Installation notes
------------------
The library can be compiled using the [CMake](https://cmake.org/) build system.
In case extra include directories or libraries are needed, you can use the
`ADDITIONAL_` CMake variables to specify these. They will be stored in both
the resulting JThread CMake configuration file and the pkg-config file.
<file_sep>// Copyright 2019 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef FRAME_TYPE_BASE_H
#define FRAME_TYPE_BASE_H
#include <string>
#include <stdint.h>
#include "sdp_data.h"
// #include "nalu_types.h"
using std::string;
class FrameTypeBase
{
public:
static FrameTypeBase * CreateNewFrameType(string & EncodeType);
static void DestroyFrameType(FrameTypeBase * frameTypeBase);
public:
FrameTypeBase() {};
virtual ~FrameTypeBase() {};
public:
virtual void Init() {}
virtual uint8_t * PrefixParameterOnce(uint8_t * buf, size_t * size) {return buf;}
virtual bool NeedPrefixParameterOnce() { return false; }
virtual uint8_t * SuffixParameterOnce(uint8_t * buf, size_t * size) {return buf;}
virtual bool NeedSuffixParameterOnce() { return false; }
virtual int PrefixParameterEveryFrame() {return 0;}
virtual int PrefixParameterEveryPacket() {return 0;}
virtual int SuffixParameterOnce() {return 0;}
virtual int SuffixParameterEveryFrame() {return 0;}
virtual int SuffixParameterEveryPacket() {return 0;}
virtual int ParsePacket(const uint8_t * RTPPayload, size_t size, bool * EndFlag) {
if(EndFlag) *EndFlag = true;
return 0;
}
virtual int ParseFrame(const uint8_t * RTPPayload) {return 0;}
virtual int ParseParaFromSDP(SDPMediaInfo & sdpMediaInfo) {return 0;}
/* To play the media sessions
* return:
* 0: not a complete frame, which means there are more packets; other: a complete frame
* */
virtual bool IsFrameComplete(const uint8_t * RTPPayload) {return true;}
// virtual int AssemblePacket(const uint8_t * RTPPayload) {return 0;}
// virtual int GetFlagOffset(const uint8_t * RTPPayload) {return 0;}
virtual size_t CopyData(uint8_t * buf, uint8_t * data, size_t size) {return 0;}
};
#endif
<file_sep>// Copyright 2019 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "frame_type_base.h"
#include "nalu_types_h264.h"
#include "nalu_types_h265.h"
#include "pcmu_types.h"
#include "mpeg_types.h"
#include <string.h>
using std::string;
FrameTypeBase * FrameTypeBase::CreateNewFrameType(string &EncodeType)
{
FrameTypeBase * frame_type_base = NULL;
if(0 == EncodeType.compare(NALUTypeBase_H264::ENCODE_TYPE)) {
frame_type_base = new NALUTypeBase_H264();
} else if(0 == EncodeType.compare(NALUTypeBase_H265::ENCODE_TYPE)) {
frame_type_base = new NALUTypeBase_H265();
} else if(0 == EncodeType.compare(PCMU_Audio::ENCODE_TYPE)) {
frame_type_base = new PCMU_Audio();
} else if(0 == EncodeType.compare(MPEG_Audio::ENCODE_TYPE)) {
frame_type_base = new MPEG_Audio();
}
return frame_type_base;
}
void FrameTypeBase::DestroyFrameType(FrameTypeBase * frameTypeBase)
{
if(!frameTypeBase) {
delete frameTypeBase;
frameTypeBase = NULL;
}
}
<file_sep>// Copyright 2015-2016 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/************************************************************************************************************************************************
* a example to receive rtsp/rtp packets over http
* there are 2 tcp sockets(one sending, one receiving) for http-tunnelling communication.
* the receiving one will receiving both Rtsp response and media data.
* after you DoSETUP, the media session will set up RTP which will take over the receiving socket.
*
* the 'getdata' thead to get media data and the 'sendrtspcmd' thread to send rtsp command, the rtsp response will be handled in RecvRtspCmdClbk.
* if you don't care about the response, it will be dropped if you don't set the callback(refer to http_tunnel_example_simple.cpp")
*
* WARNING: you can receive more one media data within one RtspClient like 'recv_video_and_audio_example'
* That means you should do something like:
* RtspClient client_audio; (for audio receiving)
* RtspClient client_video; (for video receiving)
* NOT:
* RtspClient client; (for audio and video receiving)
************************************************************************************************************************************************/
#include <iostream>
#include "rtspClient.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
using std::cout;
using std::endl;
void * getdata(void * args);
void * sendrtspcmd(void * args);
bool ByeFromServerFlag = false;
void ByeFromServerClbk()
{
cout << "Server send BYE" << endl;
ByeFromServerFlag = true;
}
// callback function to handle rtsp response
void RecvRtspCmdClbk(char * cmd) {
printf("RecvRtspCmdClbk: %s", cmd);
}
int main(int argc, char *argv[])
{
pthread_t getdata_thread;
pthread_t sendrtspcmd_thread;
if(argc != 2) {
cout << "Usage: " << argv[0] << " <URL>" << endl;
cout << "For example: " << endl;
cout << argv[0] << " rtsp://127.0.0.1/ansersion" << endl;
return 1;
}
cout << "Start play " << argv[1] << endl;
cout << "Then put video data into test_packet_recv.h264" << endl;
string RtspUri(argv[1]);
// string RtspUri("rtsp://192.168.81.145/ansersion");
RtspClient Client;
/* Set up rtsp server resource URI */
Client.SetURI(RtspUri);
Client.SetHttpTunnelPort(8000);
Client.SetPort(8000);
if(RTSP_NO_ERROR == Client.DoRtspOverHttpGet()) {
cout << "DoGet OK" << endl;
}
cout << Client.GetResource();
if(RTSP_NO_ERROR == Client.DoRtspOverHttpPost()) {
cout << "DoPost OK" << endl;
}
// /* Set rtsp access username */
Client.SetUsername("Ansersion");
// /* Set rtsp access password */
Client.SetPassword("<PASSWORD>");
// /* Send DESCRIBE command to server */
if(Client.DoOPTIONS() != RTSP_NO_ERROR) {
printf("DoOPTIONS error\n");
return 0;
}
printf("%s\n", Client.GetResponse().c_str());
/* Check whether server return '200'(OK) */
if(!Client.IsResponse_200_OK()) {
printf("DoOPTIONS error\n");
return 0;
}
/* Send DESCRIBE command to server */
if(Client.DoDESCRIBE() != RTSP_NO_ERROR) {
printf("DoDESCRIBE error\n");
return 0;
}
printf("%s\n", Client.GetResponse().c_str());
/* Check whether server return '200'(OK) */
if(!Client.IsResponse_200_OK()) {
printf("DoDESCRIBE error\n");
return 0;
}
/* Parse SDP message after sending DESCRIBE command */
printf("%s\n", Client.GetSDP().c_str());
if(Client.ParseSDP() != RTSP_NO_ERROR) {
printf("ParseSDP error\n");
return 0;
}
/* Send SETUP command to set up all 'audio' and 'video'
* sessions which SDP refers. */
if(Client.DoSETUP() != RTSP_NO_ERROR) {
printf("DoSETUP error\n");
return 0;
}
printf("%s\n", Client.GetResponse().c_str());
Client.SetVideoByeFromServerClbk(ByeFromServerClbk);
if(!Client.IsResponse_200_OK()) {
printf("DoSETUP error\n");
return 0;
}
pthread_create(&sendrtspcmd_thread, NULL, sendrtspcmd, (void*)(&Client));
pthread_create(&getdata_thread, NULL, getdata, (void*)(&Client));
pthread_join(sendrtspcmd_thread, NULL);
pthread_join(getdata_thread, NULL);
return 0;
}
void * getdata(void * args)
{
/* Receive 1000 RTP 'video' packets
* note(FIXME):
* if there are several 'video' session
* refered in SDP, only receive packets of the first
* 'video' session, the same as 'audio'.*/
// int packet_num = 0;
const size_t BufSize = 65534;
uint8_t buf[BufSize];
size_t size = 0;
int try_times = 0;
RtspClient * Client = (RtspClient*)args;
/* Write h264 video data to file "test_packet_recv.h264"
* Then it could be played by ffplay */
int fd = open("test_packet_recv.h264", O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR);
while(true) {
if(!Client->GetMediaData("video", buf, &size, BufSize)) {
if(ByeFromServerFlag) {
printf("ByeFromServerFlag\n");
break;
}
if(try_times > 5) {
printf("try_times > 5\n");
break;
}
try_times++;
continue;
}
if(write(fd, buf, size) < 0) {
perror("write");
}
printf("recv video data: %lu bytes\n", size);
}
return NULL;
}
void * sendrtspcmd(void * args)
{
bool no_response = true;
RtspClient * Client = (RtspClient*)args;
Client->SetRtspCmdClbk("video", RecvRtspCmdClbk);
if(Client->DoPLAY("video", NULL, NULL, NULL, no_response) != RTSP_NO_ERROR) {
printf("DoPLAY error\n");
return 0;
}
// sleep(5);
// printf("start TEARDOWN\n");
// /* Send TEARDOWN command to teardown all of the sessions */
// Client->SetRtspCmdClbk("video", RecvRtspCmdClbk);
// Client->DoTEARDOWN("video", no_response);
return NULL;
}
<file_sep>// Copyright 2015-2019 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*******************************/
/* More info refer to RFC 7655 */
/*******************************/
#ifndef PCMU_TYPES_H
#define PCMU_TYPES_H
#include <string>
#include <stdint.h>
#include <iostream>
#include <frame_type_base.h>
using std::string;
class PCMUTypeBase : public FrameTypeBase
{
public:
virtual ~PCMUTypeBase() {};
public:
virtual size_t CopyData(uint8_t * buf, uint8_t * data, size_t size) { return FrameTypeBase::CopyData(buf, data, size);}
virtual int ParseParaFromSDP(SDPMediaInfo & sdpMediaInfo) { return FrameTypeBase::ParseParaFromSDP(sdpMediaInfo);}
virtual int ParsePacket(const uint8_t * packet, size_t size, bool * EndFlagTmp) {return FrameTypeBase::ParsePacket(packet, size, EndFlagTmp);}
// virtual int GetFlagOffset(const uint8_t * RTPPayload) { return -1; };
};
class PCMU_Audio : public PCMUTypeBase
{
public:
static const string ENCODE_TYPE;
virtual ~PCMU_Audio() {};
virtual size_t CopyData(uint8_t * buf, uint8_t * data, size_t size);
};
#endif
<file_sep>GTest Programs
================================================================================
This package contains files of test suit programs which is based on GTest. To
compile these files, you NEED to prepare gtest sources which are not contained
in this package, and to change the gtest path in Makefile meanwhile.
--------------------------------------------------------------------------------
<file_sep>
set(JTHREAD_FOUND 1)
set(JTHREAD_INCLUDE_DIRS "${CMAKE_INSTALL_PREFIX}/include")
set(JTHREAD_LIBRARIES ${JTHREAD_LIBS_CMAKECONFIG})
<file_sep>// Copyright 2015-2016 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <stdio.h>
#include <sys/types.h>
#include <memory.h>
#include <stdlib.h>
#include <string>
#include <list>
#include <iostream>
#include <gtest/gtest.h>
#include "Base64.hh"
using namespace std;
TEST(Base64, BlankStringInput)
{
string BlankStr("");
unsigned int Size;
unsigned char * out = base64Decode(BlankStr.c_str(), Size, false);
EXPECT_EQ(0, Size);
}
<file_sep>// Copyright 2015 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef MY_REGEX_H
#define MY_REGEX_H
#include <regex.h>
#include <list>
#include <string>
#include <string.h>
#define REGEX_BUF_SIZE 2048
using std::list;
using std::string;
class MyRegex
{
public:
static const int REGEX_FAILURE;
static const int REGEX_SUCCESS;
public:
MyRegex();
~MyRegex();
int Regex(const char * str, const char * pattern, list<string> * groups, bool ignore_case = false);
int Regex(const char * str, const char * pattern, bool ignore_case = false);
/* Imitate the regex use of PERL */
/* Matching line by line */
int RegexLine(string * str, string * pattern, list<string> * groups, bool ignore_case = false);
int RegexLine(string * str, string * pattern, bool ignore_case = false);
protected:
const char * Substr(const char * str, int pos1, int pos2);
regex_t * pReg;
regmatch_t * pMatch;
string::size_type NextPos;
string * LastStr;
char RegexBuf[REGEX_BUF_SIZE];
};
#endif
<file_sep>// Copyright 2015 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <stdio.h>
#include <sys/types.h>
#include <regex.h>
#include <memory.h>
#include <stdlib.h>
#include <string>
#include <list>
#include <iostream>
#include <gtest/gtest.h>
#include <map>
#include "rtspClient.h"
using namespace std;
TEST(rtspClient, RtspClient_ParseSessionID_InvalidInput)
{
RtspClient Client;
string tmp("aslhglj");
EXPECT_EQ(true, Client.ParseSessionID(tmp) == "");
EXPECT_EQ(true, Client.ParseSessionID() == "");
}
TEST(rtspClient, RtspClient_ParseSessionID_RegularInput)
{
string ResponseOfSETUP("\
RTSP/1.0 200 OK\r\n\
Server: VLC/2.1.6\r\n\
Date: Sun, 06 Dec 2015 11:51:38 GMT\r\n\
Transport: RTP/AVP/UDP;unicast;client_port=13362-13363;server_port=40774-40775;ssrc=1883F81B;mode=play\r\n\
Session: 970756dc30b3a638;timeout=60\r\n\
Content-Length: 0\r\n\
Cache-Control: no-cache\r\n\
Cseq: 3");
RtspClient Client;
EXPECT_EQ(true, Client.ParseSessionID(ResponseOfSETUP) == "970756dc30b3a638");
}
<file_sep>// Copyright 2015-2019 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*******************************/
/* More info refer to RFC 6184 */
/*******************************/
#ifndef NALU_TYPES_H264_H
#define NALU_TYPES_H264_H
#include <string>
#include <stdint.h>
#include "nalu_types.h"
// #define NAL_UNIT_TYPE_NUM 32
// #define PACKETIZATION_MODE_NUM 3
#define PACKET_MODE_SINGAL_NAL 0
#define PACKET_MODE_NON_INTERLEAVED 1
#define PACKET_MODE_INTERLEAVED 2
#define IS_PACKET_MODE_VALID(P) \
((P) >= PACKET_MODE_SINGAL_NAL && (P) <= PACKET_MODE_INTERLEAVED)
/* More info refer to H264 'nal_unit_type' */
#define IS_NALU_TYPE_VALID_H264(N) \
( \
((N) >= 1 && (N) <= 12) || \
((N) == H264TypeInterfaceSTAP_A::STAP_A_ID) || \
((N) == H264TypeInterfaceSTAP_B::STAP_B_ID) || \
((N) == H264TypeInterfaceMTAP_16::MTAP_16_ID) || \
((N) == H264TypeInterfaceMTAP_24::MTAP_24_ID) || \
((N) == H264TypeInterfaceFU_A::FU_A_ID) || \
((N) == H264TypeInterfaceFU_B::FU_B_ID) \
)
/* H264TypeInterface */
class H264TypeInterface
{
public:
static H264TypeInterface * NalUnitType_H264[PACKETIZATION_MODE_NUM_H264][NAL_UNIT_TYPE_NUM_H264];
virtual ~H264TypeInterface() {};
virtual uint16_t ParseNALUHeader_F(const uint8_t * rtp_payload) {
if(!rtp_payload) return 0;
uint16_t NALUHeader_F_Mask = 0x0080; // binary: 1000_0000
return (rtp_payload[0] & NALUHeader_F_Mask);
}
virtual uint16_t ParseNALUHeader_NRI(const uint8_t * rtp_payload) {
if(!rtp_payload) return 0;
uint16_t NALUHeader_NRI_Mask = 0x0060; // binary: 0110_0000
return (rtp_payload[0] & NALUHeader_NRI_Mask);
}
virtual uint16_t ParseNALUHeader_Type(const uint8_t * rtp_payload) {
if(!rtp_payload) return 0;
uint16_t NALUHeader_Type_Mask = 0x001F; // binary: 0001_1111
return (rtp_payload[0] & NALUHeader_Type_Mask);
}
virtual bool IsPacketStart(const uint8_t * rtp_payload) {return true;}
virtual bool IsPacketEnd(const uint8_t * rtp_payload) {return true;}
virtual bool IsPacketReserved(const uint8_t * rtp_payload) {return false;}
virtual bool IsPacketThisType(const uint8_t * rtp_payload) {return true;}
virtual int SkipHeaderSize(const uint8_t * rtp_payload) {return 1;}
};
class H264TypeInterfaceSTAP_A : public H264TypeInterface
{
public:
virtual ~H264TypeInterfaceSTAP_A() {};
virtual bool IsPacketStart(const uint8_t * rtp_payload);
virtual bool IsPacketEnd(const uint8_t * rtp_payload);
virtual bool IsPacketThisType(const uint8_t * rtp_payload);
public:
static const uint8_t STAP_A_ID;
};
class H264TypeInterfaceSTAP_B : public H264TypeInterface
{
public:
virtual ~H264TypeInterfaceSTAP_B() {};
public:
static const uint8_t STAP_B_ID;
};
class H264TypeInterfaceMTAP_16 : public H264TypeInterface
{
public:
virtual ~H264TypeInterfaceMTAP_16() {};
public:
static const uint8_t MTAP_16_ID;
};
class H264TypeInterfaceMTAP_24 : public H264TypeInterface
{
public:
virtual ~H264TypeInterfaceMTAP_24() {};
public:
static const uint8_t MTAP_24_ID;
};
#define FU_A_ERR 0xFF
class H264TypeInterfaceFU_A : public H264TypeInterface
{
public:
virtual ~H264TypeInterfaceFU_A() {};
public:
/* Function: "ParseNALUHeader_*":
* Return 'FU_A_ERR'(0xFF) if error occurred */
virtual uint16_t ParseNALUHeader_F(const uint8_t * rtp_payload);
virtual uint16_t ParseNALUHeader_NRI(const uint8_t * rtp_payload);
virtual uint16_t ParseNALUHeader_Type(const uint8_t * rtp_payload);
virtual int SkipHeaderSize(const uint8_t * rtp_payload) {return 2;}
public:
static const uint8_t FU_A_ID;
public:
/* if FU_A payload type */
bool IsPacketThisType(const uint8_t * rtp_payload);
/* Packet Start Flag */
bool IsPacketStart(const uint8_t * rtp_payload);
/* Packet End Flag */
bool IsPacketEnd(const uint8_t * rtp_payload);
/* Reserved */
bool IsPacketReserved(const uint8_t * rtp_payload);
};
class H264TypeInterfaceFU_B : public H264TypeInterface
{
public:
virtual ~H264TypeInterfaceFU_B() {};
public:
static const uint8_t FU_B_ID;
};
class NALUTypeBase_H264 : public NALUTypeBase
{
public:
static const string ENCODE_TYPE;
public:
NALUTypeBase_H264();
virtual ~NALUTypeBase_H264() {};
public:
virtual uint16_t ParseNALUHeader_F(const uint8_t * RTPPayload);
virtual uint16_t ParseNALUHeader_NRI(const uint8_t * RTPPayload);
virtual uint16_t ParseNALUHeader_Type(const uint8_t * RTPPayload);
virtual bool IsPacketStart(const uint8_t * rtp_payload) {return true;}
virtual bool IsPacketEnd(const uint8_t * rtp_payload) {return true;}
virtual bool IsPacketReserved(const uint8_t * rtp_payload) {return false;}
virtual bool IsPacketThisType(const uint8_t * rtp_payload);
virtual H264TypeInterface * GetNaluRtpType(int packetization, int nalu_type_id);
virtual std::string GetName() const { return Name; }
virtual bool GetEndFlag() { return EndFlag; }
virtual bool GetStartFlag() { return StartFlag; }
// H265 interface with no use
virtual uint16_t ParseNALUHeader_Layer_ID(const uint8_t * RTPPayload) {return 0;}
virtual uint16_t ParseNALUHeader_Temp_ID_Plus_1(const uint8_t * RTPPayload) {return 0;}
public:
virtual void Init();
virtual uint8_t * PrefixParameterOnce(uint8_t * buf, size_t * size);
virtual bool NeedPrefixParameterOnce();
virtual int ParseParaFromSDP(SDPMediaInfo & sdpMediaInfo);
virtual int ParsePacket(const uint8_t * RTPPayload, size_t size, bool * EndFlag);
virtual size_t CopyData(uint8_t * buf, uint8_t * data, size_t size);
virtual void SetSPS(const string &s) { SPS.assign(s);}
virtual void SetPPS(const string &s) { PPS.assign(s);}
virtual const string GetSPS() { return SPS;}
virtual const string GetPPS() { return PPS;}
void InsertXPS() { prefixParameterOnce = true; }
void NotInsertXPSAgain() { prefixParameterOnce = false; }
private:
bool prefixParameterOnce;
string SPS;
string PPS;
int Packetization;
public:
H264TypeInterface * NALUType;
};
#endif
<file_sep>/*
This file is a part of JRTPLIB
Copyright (c) 1999-2017 <NAME>
Contact: <EMAIL>
This library was developed at the Expertise Centre for Digital Media
(http://www.edm.uhasselt.be), a research center of the Hasselt University
(http://www.uhasselt.be). The library is based upon work done for
my thesis at the School for Knowledge Technology (Belgium/The Netherlands).
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
/**
* \file rtprawpacket.h
*/
#ifndef RTPRAWPACKET_H
#define RTPRAWPACKET_H
#include "rtpconfig.h"
#include "rtptimeutilities.h"
#include "rtpaddress.h"
#include "rtptypes.h"
#include "rtpmemoryobject.h"
namespace jrtplib
{
/** This class is used by the transmission component to store the incoming RTP and RTCP data in. */
class JRTPLIB_IMPORTEXPORT RTPRawPacket : public RTPMemoryObject
{
public:
/** Creates an instance which stores data from \c data with length \c datalen.
* Creates an instance which stores data from \c data with length \c datalen. Only the pointer
* to the data is stored, no actual copy is made! The address from which this packet originated
* is set to \c address and the time at which the packet was received is set to \c recvtime.
* The flag which indicates whether this data is RTP or RTCP data is set to \c rtp. A memory
* manager can be installed as well.
*/
RTPRawPacket(uint8_t *data,size_t datalen,RTPAddress *address,RTPTime &recvtime,bool rtp,RTPMemoryManager *mgr = 0);
~RTPRawPacket();
/** Returns the pointer to the data which is contained in this packet. */
uint8_t *GetData() { return packetdata; }
/** Returns the length of the packet described by this instance. */
size_t GetDataLength() const { return packetdatalength; }
/** Returns the time at which this packet was received. */
RTPTime GetReceiveTime() const { return receivetime; }
/** Returns the address stored in this packet. */
const RTPAddress *GetSenderAddress() const { return senderaddress; }
/** Returns \c true if this data is RTP data, \c false if it is RTCP data. */
bool IsRTP() const { return isrtp; }
/** Sets the pointer to the data stored in this packet to zero.
* Sets the pointer to the data stored in this packet to zero. This will prevent
* a \c delete call for the actual data when the destructor of RTPRawPacket is called.
* This function is used by the RTPPacket and RTCPCompoundPacket classes to obtain
* the packet data (without having to copy it) and to make sure the data isn't deleted
* when the destructor of RTPRawPacket is called.
*/
void ZeroData() { packetdata = 0; packetdatalength = 0; }
/** Allocates a number of bytes for RTP or RTCP data using the memory manager that
* was used for this raw packet instance, can be useful if the RTPRawPacket::SetData
* function will be used. */
uint8_t *AllocateBytes(bool isrtp, int recvlen) const;
/** Deallocates the previously stored data and replaces it with the data that's
* specified, can be useful when e.g. decrypting data in RTPSession::OnChangeIncomingData */
void SetData(uint8_t *data, size_t datalen);
/** Deallocates the currently stored RTPAddress instance and replaces it
* with the one that's specified (you probably don't need this function). */
void SetSenderAddress(RTPAddress *address);
private:
void DeleteData();
uint8_t *packetdata;
size_t packetdatalength;
RTPTime receivetime;
RTPAddress *senderaddress;
bool isrtp;
};
inline RTPRawPacket::RTPRawPacket(uint8_t *data,size_t datalen,RTPAddress *address,RTPTime &recvtime,bool rtp,RTPMemoryManager *mgr):RTPMemoryObject(mgr),receivetime(recvtime)
{
packetdata = data;
packetdatalength = datalen;
senderaddress = address;
isrtp = rtp;
}
inline RTPRawPacket::~RTPRawPacket()
{
DeleteData();
}
inline void RTPRawPacket::DeleteData()
{
if (packetdata)
RTPDeleteByteArray(packetdata,GetMemoryManager());
if (senderaddress)
RTPDelete(senderaddress,GetMemoryManager());
packetdata = 0;
senderaddress = 0;
}
inline uint8_t *RTPRawPacket::AllocateBytes(bool isrtp, int recvlen) const
{
JRTPLIB_UNUSED(isrtp); // possibly unused
return RTPNew(GetMemoryManager(),(isrtp)?RTPMEM_TYPE_BUFFER_RECEIVEDRTPPACKET:RTPMEM_TYPE_BUFFER_RECEIVEDRTCPPACKET) uint8_t[recvlen];
}
inline void RTPRawPacket::SetData(uint8_t *data, size_t datalen)
{
if (packetdata)
RTPDeleteByteArray(packetdata,GetMemoryManager());
packetdata = data;
packetdatalength = datalen;
}
inline void RTPRawPacket::SetSenderAddress(RTPAddress *address)
{
if (senderaddress)
RTPDelete(senderaddress, GetMemoryManager());
senderaddress = address;
}
} // end namespace
#endif // RTPRAWPACKET_H
<file_sep>// Copyright 2015 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <stdio.h>
#include <sys/types.h>
#include <regex.h>
#include <memory.h>
#include <stdlib.h>
#include <string>
#include <list>
#include <iostream>
#include <gtest/gtest.h>
#include "myRegex.h"
#include "utils.h"
#define MD5_SIZE 32
#define MD5_BUF_SIZE (MD5_SIZE + sizeof('\0'))
using namespace std;
TEST(MD5, MD5_RegularInput)
{
char str[] = "a";
char output[MD5_BUF_SIZE];
char a_md5[] = "0cc175b9c0f1b6a831c399e269772661";
output[MD5_SIZE] = '\0';
EXPECT_EQ(Md5sum32((void *)str, (unsigned char *)output, 1, MD5_BUF_SIZE), 0);
EXPECT_EQ(strncmp(output, a_md5, MD5_SIZE), 0);
}
TEST(MD5, MD5_RegularInput_RTSP_Authentication)
{
string realm("LIVE555 Streaming Media");
string username("Ansersion");
string password("<PASSWORD>");
// string nonce("f3c72dd425d78af5886a2e1f97cd00e0");
string nonce("b8802842a5d9b123cc84f4f9331856ac");
string cmd("SETUP");
string uri("rtsp://192.168.81.157:8554/ansersion/track1");
string tmp("");
char ha1buf[MD5_BUF_SIZE] = {0};
char ha2buf[MD5_BUF_SIZE] = {0};
char habuf[MD5_BUF_SIZE] = {0};
const char c_ha1[] = "ad68dbfd3e130bcabd2e61d19e5695fd";
const char c_ha2[] = "1d47c98b00946762aad35c10a7e61736";
// const char c_ha[] = "02b4d89265cdffcc0414b57fcc6f269c";
const char c_ha[] = "ceee4678adb535175876d1ba9082d0d8";
tmp.assign("");
tmp = username + ":" + realm + ":" + password;
Md5sum32((void *)tmp.c_str(), (unsigned char *)ha1buf, tmp.length(), MD5_BUF_SIZE);
// EXPECT_EQ(strncmp(ha1buf, c_ha1, MD5_SIZE), 0);
tmp.assign("");
tmp = cmd + ":" + uri;
Md5sum32((void *)tmp.c_str(), (unsigned char *)ha2buf, tmp.length(), MD5_BUF_SIZE);
// EXPECT_EQ(strncmp(ha2buf, c_ha2, MD5_SIZE), 0);
tmp.assign(ha1buf);
tmp = tmp + ":" + nonce + ":" + ha2buf;
Md5sum32((void *)tmp.c_str(), (unsigned char *)habuf, tmp.length(), MD5_BUF_SIZE);
EXPECT_EQ(strncmp(habuf, c_ha, MD5_SIZE), 0);
}
<file_sep>// Copyright 2015-2019 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*******************************/
/* More info refer to RFC 6184 */
/*******************************/
#include "nalu_types_h264.h"
#include "nalu_types_h265.h"
#include <string.h>
#include <sstream>
#include <iostream>
#include <stdio.h>
using std::stringstream;
using std::cerr;
using std::endl;
const string NALUTypeBase_H264::ENCODE_TYPE = "H264";
H264TypeInterface H264TypeInterface_H264Obj;
H264TypeInterfaceSTAP_A H264TypeInterfaceSTAP_AObj;
H264TypeInterfaceSTAP_B H264TypeInterfaceSTAP_BObj;
H264TypeInterfaceMTAP_16 H264TypeInterfaceMTAP_16Obj;
H264TypeInterfaceMTAP_24 H264TypeInterfaceMTAP_24Obj;
H264TypeInterfaceFU_A H264TypeInterfaceFU_AObj;
H264TypeInterfaceFU_B H264TypeInterfaceFU_BObj;
H264TypeInterface * H264TypeInterface::NalUnitType_H264[PACKETIZATION_MODE_NUM_H264][NAL_UNIT_TYPE_NUM_H264] =
{
/* Packetization Mode: Single NAL */
{
NULL, &H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj,
&H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj,
&H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj,
&H264TypeInterface_H264Obj, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL
},
/* Packetization Mode: Non-interleaved */
{
NULL, &H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj,
&H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj,
&H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj, &H264TypeInterface_H264Obj,
&H264TypeInterface_H264Obj, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
&H264TypeInterfaceSTAP_AObj, NULL, NULL, NULL,
&H264TypeInterfaceFU_AObj, NULL, NULL, NULL
},
/* Packetization Mode: Interleaved */
{
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, &H264TypeInterfaceSTAP_BObj, &H264TypeInterfaceMTAP_16Obj, &H264TypeInterfaceMTAP_24Obj,
&H264TypeInterfaceFU_AObj, &H264TypeInterfaceFU_BObj, NULL, NULL
}
};
NALUTypeBase_H264::NALUTypeBase_H264():NALUTypeBase()
{
prefixParameterOnce = true;
Packetization = PACKET_MODE_SINGAL_NAL;
NALUType = NULL;
SPS.assign("");
PPS.assign("");
}
void NALUTypeBase_H264::Init()
{
InsertXPS();
}
uint16_t NALUTypeBase_H264::ParseNALUHeader_F(const uint8_t * rtp_payload)
{
if(!rtp_payload) return 0;
uint16_t NALUHeader_F_Mask = 0x0080; // binary: 1000_0000
return (rtp_payload[0] & NALUHeader_F_Mask);
}
uint16_t NALUTypeBase_H264::ParseNALUHeader_NRI(const uint8_t * rtp_payload)
{
if(!rtp_payload) return 0;
uint16_t NALUHeader_NRI_Mask = 0x0060; // binary: 0110_0000
return (rtp_payload[0] & NALUHeader_NRI_Mask);
}
uint16_t NALUTypeBase_H264::ParseNALUHeader_Type(const uint8_t * rtp_payload)
{
if(!rtp_payload) return 0;
uint16_t NALUHeader_Type_Mask = 0x001F; // binary: 0001_1111
return (rtp_payload[0] & NALUHeader_Type_Mask);
}
bool NALUTypeBase_H264::IsPacketThisType(const uint8_t * rtp_payload)
{
// NAL type is valid in the range of [1,12]
uint16_t NalType = ParseNALUHeader_Type(rtp_payload);
return ((1 <= NalType) && (NalType <= 12));
}
size_t NALUTypeBase_H264::CopyData(uint8_t * buf, uint8_t * data, size_t size)
{
size_t CopySize = 0;
if(!buf || !data) return 0;
if(!NALUType) return 0;
uint8_t NALUHeader = 0;
NALUHeader = (uint8_t)(
NALUType->ParseNALUHeader_F(data) |
NALUType->ParseNALUHeader_NRI(data) |
NALUType->ParseNALUHeader_Type(data)
);
if(StartFlag) {
// NALU start code size
buf[0] = 0; buf[1] = 0; buf[2] = 0; buf[3] = 1;
CopySize += 4;
buf[CopySize++] = (NALUHeader & 0xFF);
// memcpy(buf + CopySize, &NALUHeader, sizeof(NALUHeader));
// CopySize += sizeof(NALUHeader);
}
const int SkipHeaderSize = NALUType->SkipHeaderSize(data);
memcpy(buf + CopySize, data + SkipHeaderSize, size - SkipHeaderSize);
CopySize += size - SkipHeaderSize;
return CopySize;
}
H264TypeInterface * NALUTypeBase_H264::GetNaluRtpType(int packetization, int nalu_type_id)
{
if(!IS_NALU_TYPE_VALID_H264(nalu_type_id)) {
return NULL;
}
return H264TypeInterface::NalUnitType_H264[packetization][nalu_type_id];
}
uint8_t * NALUTypeBase_H264::PrefixParameterOnce(uint8_t * buf, size_t * size)
{
if(!buf) return NULL;
if(!size) return NULL;
const size_t NALU_StartCodeSize = 4;
size_t SizeTmp = 0;
if(!NALUTypeBase::PrefixXPS(buf + (*size), &SizeTmp, SPS) || SizeTmp <= NALU_StartCodeSize) {
fprintf(stderr, "\033[31mWARNING: No SPS\033[0m\n");
return NULL;
}
*size += SizeTmp;
if(!NALUTypeBase::PrefixXPS(buf + (*size), &SizeTmp, PPS) || SizeTmp <= NALU_StartCodeSize) {
fprintf(stderr, "\033[31mWARNING: No PPS\033[0m\n");
return NULL;
}
*size += SizeTmp;
NotInsertXPSAgain();
return buf;
}
bool NALUTypeBase_H264::NeedPrefixParameterOnce()
{
return prefixParameterOnce;
}
int NALUTypeBase_H264::ParseParaFromSDP(SDPMediaInfo & sdpMediaInfo)
{
map<int, map<SDP_ATTR_ENUM, string> >::iterator it = sdpMediaInfo.fmtMap.begin();
if(it->second.find(ATTR_SPS) != it->second.end()) {
SetSPS(it->second[ATTR_SPS]);
}
if(it->second.find(ATTR_PPS) != it->second.end()) {
SetPPS(it->second[ATTR_PPS]);
}
if(it->second.find(PACK_MODE) != it->second.end()) {
stringstream ssPackMode;
ssPackMode << it->second[PACK_MODE];
ssPackMode >> Packetization;
// cout << "debug: Packetization=" << NewMediaSession.Packetization << endl;;
}
return 0;
}
int NALUTypeBase_H264::ParsePacket(const uint8_t * packet, size_t size, bool * EndFlagTmp)
{
if(!packet || !EndFlagTmp) {
return -1;
}
if(!IS_PACKET_MODE_VALID(Packetization)) {
cerr << "Error(H264): Invalid Packetization Mode" << endl;
return -2;
}
int PM = Packetization;
int NT = ParseNALUHeader_Type(packet);
NALUType = GetNaluRtpType(PM, NT);
if(NULL == NALUType) {
printf("Error(H264): Unknown NALU Type(PM=%d,NT=%d)\n", PM, NT);
return -3;
}
StartFlag = NALUType->IsPacketStart(packet);
EndFlag = NALUType->IsPacketEnd(packet);
*EndFlagTmp = EndFlag;
return 0;
}
const uint8_t H264TypeInterfaceSTAP_A::STAP_A_ID = 0x18; // decimal: 24
const uint8_t H264TypeInterfaceSTAP_B::STAP_B_ID = 0x19; // decimal: 25
const uint8_t H264TypeInterfaceMTAP_16::MTAP_16_ID = 0x1A; // decimal: 26
const uint8_t H264TypeInterfaceMTAP_24::MTAP_24_ID = 0x1B; // decimal: 27
const uint8_t H264TypeInterfaceFU_A::FU_A_ID = 0x1C; // decimal: 28
const uint8_t H264TypeInterfaceFU_B::FU_B_ID = 0x1D; // decimal: 29
bool H264TypeInterfaceSTAP_A::IsPacketStart(const uint8_t * rtp_payload)
{
return true;
}
bool H264TypeInterfaceSTAP_A::IsPacketEnd(const uint8_t * rtp_payload)
{
return true;
}
bool H264TypeInterfaceSTAP_A::IsPacketThisType(const uint8_t * rtp_payload)
{
if(!rtp_payload) return false;
return (STAP_A_ID == (rtp_payload[0] & STAP_A_ID));
}
bool H264TypeInterfaceFU_A::IsPacketThisType(const uint8_t * rtp_payload)
{
if(!rtp_payload) return false;
return (FU_A_ID == (rtp_payload[0] & FU_A_ID));
}
uint16_t H264TypeInterfaceFU_A::ParseNALUHeader_F(const uint8_t * rtp_payload)
{
if(!rtp_payload) return FU_A_ERR;
if(FU_A_ID != (rtp_payload[0] & FU_A_ID)) return FU_A_ERR;
uint16_t NALUHeader_F_Mask = 0x0080; // binary: 1000_0000
// "F" at the byte of rtp_payload[0]
return (rtp_payload[0] & NALUHeader_F_Mask);
}
uint16_t H264TypeInterfaceFU_A::ParseNALUHeader_NRI(const uint8_t * rtp_payload)
{
if(!rtp_payload) return FU_A_ERR;
if(FU_A_ID != (rtp_payload[0] & FU_A_ID)) return FU_A_ERR;
uint16_t NALUHeader_NRI_Mask = 0x0060; // binary: 0110_0000
// "NRI" at the byte of rtp_payload[0]
return (rtp_payload[0] & NALUHeader_NRI_Mask);
}
uint16_t H264TypeInterfaceFU_A::ParseNALUHeader_Type(const uint8_t * rtp_payload)
{
if(!rtp_payload) return FU_A_ERR;
if(FU_A_ID != (rtp_payload[0] & FU_A_ID)) return FU_A_ERR;
uint16_t NALUHeader_Type_Mask = 0x001F; // binary: 0001_1111
// "Type" at the byte of rtp_payload[0]
return (rtp_payload[1] & NALUHeader_Type_Mask);
}
bool H264TypeInterfaceFU_A::IsPacketStart(const uint8_t * rtp_payload)
{
if(!IsPacketThisType(rtp_payload)) return false;
uint8_t PacketS_Mask = 0x80; // binary:1000_0000
return (rtp_payload[1] & PacketS_Mask);
}
bool H264TypeInterfaceFU_A::IsPacketEnd(const uint8_t * rtp_payload)
{
if(!IsPacketThisType(rtp_payload)) return false;
uint8_t PacketE_Mask = 0x40; // binary:0100_0000
return (rtp_payload[1] & PacketE_Mask);
}
bool H264TypeInterfaceFU_A::IsPacketReserved(const uint8_t * rtp_payload)
{
if(!IsPacketThisType(rtp_payload)) return false;
uint8_t PacketR_Mask = 0x20; // binary:0010_0000
return (rtp_payload[1] & PacketR_Mask);
}
<file_sep>// Copyright 2018 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef SDP_DATA_H
#define SDP_DATA_H
#include <iostream>
#include <map>
#include <string>
#include <stdint.h>
using std::map;
using std::string;
enum SDP_ATTR_ENUM {
MEDIA_TYPE_NAME, // "video", "audio"
CODEC_TYPE, // "H264", "MPA"...
TIME_RATE, // "90000", "8000"...
CHANNEL_NUM, // "1", "2"...
PACK_MODE, // for h264/h265
ATTR_SPS, // for h264/h265
ATTR_PPS, // for h264/h265
ATTR_VPS, // for h265
CONTROL_URI, // "rtsp://127.0.0.1:554/ansersion/trackID=0"...
};
// o=<username> <session id> <version> <network type> <address type> <address>
typedef struct SDPOriginStruct
{
string userName;
long sessionId;
long version;
string networkType;
string addressType;
string address;
// SDPOriginStruct {
// userName = "";
// sessionId = 0;
// version = 0;
// networkType = "";
// addressType = "";
// address = "";
// };
} OriginStruct;
typedef struct SDPConnectionData {
string networkType;
string addressType;
string address;
// SDPConnectionData {
// networkType = "";
// addressType = "";
// address = "";
// };
} SDPConnectionData;
typedef struct SDPSessionTime {
long startTime;
long stopTime;
// SDPSessionTime {
// startTime = 0;
// stopTime = 0;
// };
} SDPSessionTime;
typedef struct SDPMediaInfo {
string mediaType;
string ports;
string transProt;
map<int, map<SDP_ATTR_ENUM, string> > fmtMap;
string controlURI;
// SDPMediaInfo {
// mediaType = "";
// ports = "";
// transProt = "";
// fmtMap.clear();
// controlURI = "";
// };
} SDPMediaInfo;
class SDPData
{
public:
~SDPData();
void parse(string &sdp);
int getSdpVersion() {return sdpVersion;}
string getSessionName() {return sessionName;}
SDPOriginStruct getSdpOriginStruct() {return sdpOriginStruct;}
SDPConnectionData getSdpConnectionData() {return sdpConnectionData;}
SDPSessionTime getSdpSessionTime() {return sdpSessionTime;}
map<string, SDPMediaInfo> getMediaInfoMap() {return mediaInfoMap;}
private:
/* RFC2327.6 */
int sdpVersion;
string sessionName;
SDPOriginStruct sdpOriginStruct;
SDPConnectionData sdpConnectionData;;
SDPSessionTime sdpSessionTime;
map<string, SDPMediaInfo> mediaInfoMap;
};
#endif
<file_sep>cmake_minimum_required(VERSION 2.8)
project(md5)
include_directories(include)
file(GLOB SOURCES "*.cpp")
add_library(md5 STATIC ${SOURCES})
install(TARGETS md5 DESTINATION .)
<file_sep>// Copyright 2015-2019 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*******************************/
/* More info refer to RFC 7655 */
/*******************************/
#include "pcmu_types.h"
#include <string.h>
PCMU_Audio PCMU_AudioObj;
const string PCMU_Audio::ENCODE_TYPE = "PCMU";
size_t PCMU_Audio::CopyData(uint8_t * buf, uint8_t * data, size_t size)
{
size_t CopySize = 0;
if(!buf || !data) return 0;
memcpy(buf + CopySize, data, size);
CopySize += size;
return CopySize;
}
<file_sep>set (HEADERS jmutex.h jthread.h jmutexautolock.h ${PROJECT_BINARY_DIR}/src/jthreadconfig.h)
add_definitions(-DJTHREAD_COMPILING)
if (CMAKE_USE_WIN32_THREADS_INIT)
set(SOURCES win32/jmutex.cpp win32/jthread.cpp)
set(JTHREAD_CONFIG_WIN32THREADS "#define JTHREAD_CONFIG_WIN32THREADS")
set(JTHREAD_WIN32_CRITICALSECTION OFF CACHE BOOL "If set to false, use standard mutex. If set to true, use a critical section object.")
if (JTHREAD_WIN32_CRITICALSECTION)
set(JTHREAD_CONFIG_JMUTEXCRITICALSECTION "#define JTHREAD_CONFIG_JMUTEXCRITICALSECTION")
else (JTHREAD_WIN32_CRITICALSECTION)
set(JTHREAD_CONFIG_JMUTEXCRITICALSECTION "// Using standard Win32 mutex")
endif (JTHREAD_WIN32_CRITICALSECTION)
else (CMAKE_USE_WIN32_THREADS_INIT) # Use pthread
set(SOURCES pthread/jmutex.cpp pthread/jthread.cpp)
set(JTHREAD_CONFIG_WIN32THREADS "// Using pthread based threads")
set(JTHREAD_CONFIG_JMUTEXCRITICALSECTION "")
# Test pthread_cancel (doesn't exits on Android)
set(CMAKE_REQUIRED_LIBRARIES ${CMAKE_THREAD_LIBS_INIT})
check_cxx_source_compiles("#include <pthread.h>\nint main(void) { pthread_cancel((pthread_t)0); return 0; }" JTHREAD_HAVE_PTHREADCANCEL)
if (NOT JTHREAD_HAVE_PTHREADCANCEL)
#message("Enabling JTHREAD_SKIP_PTHREAD_CANCEL")
add_definitions(-DJTHREAD_SKIP_PTHREAD_CANCEL)
else ()
#message("pthread_cancel appears to exist")
endif (NOT JTHREAD_HAVE_PTHREADCANCEL)
endif (CMAKE_USE_WIN32_THREADS_INIT)
if (NOT MSVC)
set(JTHREAD_COMPILE_STATIC_ONLY OFF CACHE BOOL "Flag indicating if only a static library should be built, or both a dynamic and static one")
else ()
set(CMAKE_DEBUG_POSTFIX _d)
set(JTHREAD_COMPILE_STATIC ON CACHE BOOL "Flag indicating if a static library should be built, or a dynamic one")
endif ()
if (NOT MSVC OR JTHREAD_COMPILE_STATIC)
set(JTHREAD_INSTALLTARGETS jthread-static)
add_library(jthread-static STATIC ${SOURCES} ${HEADERS})
set_target_properties(jthread-static PROPERTIES OUTPUT_NAME jthread)
set_target_properties(jthread-static PROPERTIES CLEAN_DIRECT_OUTPUT 1)
target_link_libraries(jthread-static ${CMAKE_THREAD_LIBS_INIT})
endif()
if ((NOT MSVC AND NOT JTHREAD_COMPILE_STATIC_ONLY) OR (MSVC AND NOT JTHREAD_COMPILE_STATIC))
add_library(jthread-shared SHARED ${SOURCES} ${HEADERS})
set_target_properties(jthread-shared PROPERTIES VERSION ${VERSION})
set_target_properties(jthread-shared PROPERTIES OUTPUT_NAME jthread)
set_target_properties(jthread-shared PROPERTIES CLEAN_DIRECT_OUTPUT 1)
set(JTHREAD_INSTALLTARGETS ${JTHREAD_INSTALLTARGETS} jthread-shared)
target_link_libraries(jthread-shared ${CMAKE_THREAD_LIBS_INIT})
endif ()
include_directories(${PROJECT_SOURCE_DIR}/src)
include_directories(${PROJECT_BINARY_DIR}/src)
install(FILES ${HEADERS} DESTINATION include/jthread)
install(TARGETS ${JTHREAD_INSTALLTARGETS} DESTINATION ${LIBRARY_INSTALL_DIR})
if (NOT MSVC)
set(JTHREAD_LIBS "-L${LIBRARY_INSTALL_DIR}" "-ljthread" ${CMAKE_THREAD_LIBS_INIT})
else ()
set(JTHREAD_LIBS optimized "${LIBRARY_INSTALL_DIR}/jthread.lib" debug "${LIBRARY_INSTALL_DIR}/jthread_d.lib" ${CMAKE_THREAD_LIBS_INIT})
endif ()
if (NOT MSVC OR JTHREAD_COMPILE_STATIC)
set(JTHREAD_IMPORT "")
set(JTHREAD_EXPORT "")
else ()
set(JTHREAD_IMPORT "__declspec(dllimport)")
set(JTHREAD_EXPORT "__declspec(dllexport)")
endif ()
configure_file("${PROJECT_SOURCE_DIR}/src/jthreadconfig.h.in"
"${PROJECT_BINARY_DIR}/src/jthreadconfig.h")
foreach(ARG ${JTHREAD_LIBS})
set(JTHREAD_LIBS_CMAKECONFIG "${JTHREAD_LIBS_CMAKECONFIG} \"${ARG}\"")
endforeach()
configure_file("${PROJECT_SOURCE_DIR}/cmake/JThreadConfig.cmake.in"
"${PROJECT_BINARY_DIR}/cmake/JThreadConfig.cmake")
install(FILES
"${PROJECT_BINARY_DIR}/cmake/JThreadConfig.cmake"
DESTINATION ${LIBRARY_INSTALL_DIR}/cmake/JThread)
if (NOT MSVC)
foreach(ARG ${JTHREAD_LIBS})
set(JTHREAD_LIBS_PKGCONFIG "${JTHREAD_LIBS_PKGCONFIG} ${ARG}")
endforeach()
configure_file(${PROJECT_SOURCE_DIR}/pkgconfig/jthread.pc.in ${PROJECT_BINARY_DIR}/pkgconfig/jthread.pc)
install(FILES ${PROJECT_BINARY_DIR}/pkgconfig/jthread.pc DESTINATION ${LIBRARY_INSTALL_DIR}/pkgconfig)
endif ()
<file_sep>// Copyright 2015 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <stdio.h>
#include <sys/types.h>
#include <regex.h>
#include <memory.h>
#include <stdlib.h>
#include <string>
#include <list>
#include <iostream>
#include <gtest/gtest.h>
#include "rtspClient.h"
using namespace std;
TEST(get_parameters, SessionTimeout)
{
// string RtspUri("rtsp://127.0.0.1/ansersion");
string RtspUri("rtsp://192.168.81.157:8554/ansersion");
RtspClient Client(RtspUri);
EXPECT_EQ(Client.DoOPTIONS(), RTSP_NO_ERROR);
EXPECT_TRUE(Client.IsResponse_200_OK());
EXPECT_EQ(Client.DoDESCRIBE(), RTSP_NO_ERROR);
EXPECT_TRUE(Client.IsResponse_200_OK());
EXPECT_EQ(Client.ParseSDP(), RTSP_NO_ERROR);
EXPECT_EQ(Client.DoSETUP(), RTSP_NO_ERROR);
EXPECT_TRUE(Client.IsResponse_200_OK());
EXPECT_EQ(Client.GetSessionTimeout("audio"), 60);
EXPECT_EQ(Client.DoTEARDOWN(), RTSP_NO_ERROR);
EXPECT_TRUE(Client.IsResponse_200_OK());
}
<file_sep>cmake_minimum_required(VERSION 2.8)
project(myRtspClient)
#g++ common_example.cpp -I ../myRtspClient/include ../myRtspClient/libmyRtspClient.a -I ../third_party/JRTPLIB/src ../third_party/JRTPLIB/src/libjrtp.a
add_subdirectory(../third_party/JRTPLIB jrtplib)
include_directories(../third_party/Base64_live555/include)
include_directories(../third_party/md5/include)
include_directories(../third_party/JRTPLIB/src)
include_directories(include)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/jrtplib/src)
file(GLOB SOURCES "*.cpp" "../third_party/Base64_live555/*.cpp" "../third_party/md5/*.cpp")
add_library(myRtspClient SHARED ${SOURCES})
add_dependencies(myRtspClient jrtplib-shared)
target_link_libraries(myRtspClient jrtplib-shared)<file_sep>// Copyright 2015 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <regex.h>
#include <memory.h>
#include <stdlib.h>
#include <string>
#include <list>
#include <iostream>
#include <gtest/gtest.h>
#include "nalu_types_h264.h"
using namespace std;
TEST(NALUPayloadType, STAP_A_RegularInput_1)
{
STAP_A STAPAType;
uint8_t buf1[1024];
size_t size_1;
memset(buf1, 0, 1024);
int fd1 = open("testMedia_nalu_type_STAP_A_1.stap", O_RDONLY);
if((size_1 = read(fd1, buf1, 1024)) <= 0) printf("read testMedia_nalu_type_STAP_A_1.stap error\n");
EXPECT_EQ(STAPAType.ParseNALUHeader_F(buf1), 0x00);
EXPECT_EQ(STAPAType.ParseNALUHeader_NRI(buf1), 0x60);
EXPECT_EQ(STAPAType.ParseNALUHeader_Type(buf1), STAP_A::STAP_A_ID);
EXPECT_EQ(STAPAType.IsPacketThisType(buf1), true);
EXPECT_EQ(STAPAType.IsPacketEnd(buf1), true);
}
TEST(NALUPayloadType, STAP_A_RegularInput_2)
{
STAP_A STAPAType;
uint8_t buf[1024];
uint8_t writeBuf[1024];
int size_1, size_2;
int fdWrite;
int fdTest;
int fdOriginH264;
size_t sizeTmp;
memset(buf, 0, 1024);
memset(writeBuf, 0, 1024);
// copy STAP packet to h264
fdTest = open("testMedia_nalu_type_STAP_A_1.stap", O_RDONLY);
if((size_1 = read(fdTest, buf, 1024)) <= 0) printf("read testMedia_nalu_type_STAP_A_1.stap error\n");
sizeTmp = STAPAType.CopyData(writeBuf, buf, size_1);
fdWrite = open("writeSTAP_Packet1.h264", O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR);
if(write(fdWrite, writeBuf, sizeTmp) < 0) perror("write");
close(fdWrite);
close(fdTest);
// Compare the h264 file from STAP packet and h264 original file
fdOriginH264 = open("testMedia_nalu_type_STAP_A_1.h264", O_RDONLY);
fdWrite = open("writeSTAP_Packet1.h264", O_RDONLY);
if((size_1 = read(fdOriginH264, buf, 1024)) <= 0) printf("read testMedia_nalu_type_STAP_A_1.h264 error\n");
if((size_2 = read(fdWrite, writeBuf, 1024)) <= 0) printf("read writeSTAP_Packet1.h264 error\n");
if(size_1 != size_2) EXPECT_TRUE(false);
for(int i = 0; i < size_1; i++) {
if(writeBuf[i] != buf[i]) EXPECT_TRUE(false);
}
// copy STAP packet to h264
fdTest = open("testMedia_nalu_type_STAP_A_2.stap", O_RDONLY);
if((size_1 = read(fdTest, buf, 1024)) <= 0) printf("read testMedia_nalu_type_STAP_A_2.stap error\n");
sizeTmp = STAPAType.CopyData(writeBuf, buf, size_1);
fdWrite = open("writeSTAP_Packet2.h264", O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR);
if(write(fdWrite, writeBuf, sizeTmp) < 0) perror("write");
close(fdWrite);
close(fdTest);
// Compare the h264 file from STAP packet and h264 original file
fdOriginH264 = open("testMedia_nalu_type_STAP_A_2.h264", O_RDONLY);
fdWrite = open("writeSTAP_Packet2.h264", O_RDONLY);
if((size_1 = read(fdOriginH264, buf, 1024)) <= 0) printf("read testMedia_nalu_type_STAP_A_2.h264 error\n");
if((size_2 = read(fdWrite, writeBuf, 1024)) <= 0) printf("read writeSTAP_Packet2.h264 error\n");
if(size_1 != size_2) EXPECT_TRUE(false);
for(int i = 0; i < size_1; i++) {
if(writeBuf[i] != buf[i]) EXPECT_TRUE(false);
}
}
TEST(NALUPayloadType, FU_A_InvalidInput)
{
FU_A FUAType;
uint8_t InvalidInput1[] = {0x01, 0x9e, 0xea};
uint8_t InvalidInput2[] = {0x41, 0x9a, 0x5d};
EXPECT_EQ(FUAType.ParseNALUHeader_F(InvalidInput1), FU_A_ERR);
EXPECT_EQ(FUAType.ParseNALUHeader_NRI(InvalidInput1), FU_A_ERR);
EXPECT_EQ(FUAType.ParseNALUHeader_Type(InvalidInput1), FU_A_ERR);
EXPECT_EQ(FUAType.IsPacketThisType(InvalidInput1), false);
EXPECT_EQ(FUAType.IsPacketStart(InvalidInput1), false);
EXPECT_EQ(FUAType.IsPacketEnd(InvalidInput1), false);
EXPECT_EQ(FUAType.IsPacketReserved(InvalidInput1), false);
EXPECT_EQ(FUAType.ParseNALUHeader_F(InvalidInput2), FU_A_ERR);
EXPECT_EQ(FUAType.ParseNALUHeader_NRI(InvalidInput2), FU_A_ERR);
EXPECT_EQ(FUAType.ParseNALUHeader_Type(InvalidInput2), FU_A_ERR);
EXPECT_EQ(FUAType.IsPacketThisType(InvalidInput2), false);
EXPECT_EQ(FUAType.IsPacketStart(InvalidInput2), false);
EXPECT_EQ(FUAType.IsPacketEnd(InvalidInput2), false);
EXPECT_EQ(FUAType.IsPacketReserved(InvalidInput2), false);
}
TEST(NALUPayloadType, FU_A_RegularInput)
{
FU_A FUAType;
uint8_t RegularInput_WithStart[] = {0x5c, 0x81, 0x9a};
uint8_t RegularInput_WithEnd[] = {0x5c, 0x41, 0x50};
uint8_t RegularInput[] = {0x5c, 0x01, 0xf6};
EXPECT_EQ(FUAType.ParseNALUHeader_F(RegularInput_WithStart), 0x00);
EXPECT_EQ(FUAType.ParseNALUHeader_NRI(RegularInput_WithStart), 0x40);
EXPECT_EQ(FUAType.ParseNALUHeader_Type(RegularInput_WithStart), 0x01);
EXPECT_EQ(FUAType.IsPacketThisType(RegularInput_WithStart), true);
EXPECT_EQ(FUAType.IsPacketStart(RegularInput_WithStart), true);
EXPECT_EQ(FUAType.IsPacketEnd(RegularInput_WithStart), false);
EXPECT_EQ(FUAType.IsPacketReserved(RegularInput_WithStart), false);
EXPECT_EQ(FUAType.ParseNALUHeader_F(RegularInput_WithEnd), 0x00);
EXPECT_EQ(FUAType.ParseNALUHeader_NRI(RegularInput_WithEnd), 0x40);
EXPECT_EQ(FUAType.ParseNALUHeader_Type(RegularInput_WithEnd), 0x01);
EXPECT_EQ(FUAType.IsPacketThisType(RegularInput_WithEnd), true);
EXPECT_EQ(FUAType.IsPacketStart(RegularInput_WithEnd), false);
EXPECT_EQ(FUAType.IsPacketEnd(RegularInput_WithEnd), true);
EXPECT_EQ(FUAType.IsPacketReserved(RegularInput_WithEnd), false);
EXPECT_EQ(FUAType.ParseNALUHeader_F(RegularInput), 0x00);
EXPECT_EQ(FUAType.ParseNALUHeader_NRI(RegularInput), 0x40);
EXPECT_EQ(FUAType.ParseNALUHeader_Type(RegularInput), 0x01);
EXPECT_EQ(FUAType.IsPacketThisType(RegularInput), true);
EXPECT_EQ(FUAType.IsPacketStart(RegularInput), false);
EXPECT_EQ(FUAType.IsPacketEnd(RegularInput), false);
EXPECT_EQ(FUAType.IsPacketReserved(RegularInput), false);
}
<file_sep>// Copyright 2019 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "nalu_types.h"
#include "Base64.hh"
#include <string.h>
NALUTypeBase::NALUTypeBase(): FrameTypeBase()
{
}
bool NALUTypeBase::NeedPrefixParameterOnce()
{
return false;
}
int NALUTypeBase::ParseParaFromSDP(SDPMediaInfo & sdpMediaInfo)
{
return 0;
}
uint8_t * NALUTypeBase::PrefixXPS(uint8_t * buf, size_t * size, string & xps)
{
if(!buf) return NULL;
if(!size) return NULL;
*size = 0;
buf[0] = 0; buf[1] = 0; buf[2] = 0; buf[3] = 1;
*size += 4;
unsigned int XpsSize = 0;
unsigned char * xpsBuf = base64Decode(xps.c_str(), XpsSize, true);
if(!xpsBuf) return NULL;
memcpy(buf + (*size), xpsBuf, XpsSize);
*size += XpsSize;
delete[] xpsBuf;
xpsBuf = NULL;
return buf;
}
<file_sep>// Copyright 2015-2019 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*******************************/
/* More info refer to RFC 7798 */
/*******************************/
#ifndef NALU_TYPES_H265_H
#define NALU_TYPES_H265_H
#include <string>
#include <stdint.h>
#include "nalu_types.h"
#define NAL_UNIT_TYPE_BIT_NUM 6
#define NUH_LAYER_ID_BIT_NUM 6
#define NUH_TEMPORAL_ID_PLUS1_BIT_NUM 3
#define FUs_H265_ERR 0xFFFF
/* More info refer to H265 'nal_unit_type' */
#define IS_NALU_TYPE_VALID_H265(N) \
( \
((N) >= 0 && (N) <= 40) || \
((N) == H265TypeInterfaceAPs::APs_ID_H265) || \
((N) == H265TypeInterfaceFUs::FUs_ID_H265) \
)
/* H265TypeInterface */
class H265TypeInterface
{
public:
static H265TypeInterface * NalUnitType_H265[PACKETIZATION_MODE_NUM_H265][NAL_UNIT_TYPE_NUM_H265];
virtual ~H265TypeInterface() {};
virtual uint16_t ParseNALUHeader_F(const uint8_t * rtp_payload) {
if(!rtp_payload) return 0;
const uint16_t NALUHeader_F_Mask = 0x8000; // binary: 1000_0000_0000_0000
uint16_t HeaderTmp = 0;
HeaderTmp = ((rtp_payload[0] << 8) | rtp_payload[1]);
HeaderTmp = HeaderTmp & NALUHeader_F_Mask;
return HeaderTmp;
}
virtual uint16_t ParseNALUHeader_NRI(const uint8_t * rtp_payload) {
if(!rtp_payload) return 0;
uint16_t NALUHeader_NRI_Mask = 0x0060; // binary: 0110_0000
return (rtp_payload[0] & NALUHeader_NRI_Mask);
}
virtual uint16_t ParseNALUHeader_Type(const uint8_t * rtp_payload) {
if(!rtp_payload) return 0;
const uint16_t NALUHeader_Type_Mask = 0x7E00; // binary: 0111_1110_0000_0000
uint16_t HeaderTmp = 0;
HeaderTmp = ((rtp_payload[0] << 8) | rtp_payload[1]);
HeaderTmp = HeaderTmp & NALUHeader_Type_Mask;
return HeaderTmp;
}
virtual uint16_t ParseNALUHeader_Layer_ID(const uint8_t * rtp_payload) {
if(!rtp_payload) return 0;
const uint16_t NALUHeader_Layer_ID_Mask = 0x01F8; // binary: 0000_0001_1111_1000
uint16_t HeaderTmp = 0;
HeaderTmp = ((rtp_payload[0] << 8) | rtp_payload[1]);
HeaderTmp = HeaderTmp & NALUHeader_Layer_ID_Mask;
return HeaderTmp;
}
virtual uint16_t ParseNALUHeader_Temp_ID_Plus_1(const uint8_t * rtp_payload) {
if(!rtp_payload) return 0;
const uint16_t NALUHeader_Temp_ID_Mask = 0x0007; // binary: 0000_0000_0000_0111
uint16_t HeaderTmp = 0;
HeaderTmp = ((rtp_payload[0] << 8) | rtp_payload[1]);
HeaderTmp = HeaderTmp & NALUHeader_Temp_ID_Mask;
return HeaderTmp;
}
virtual bool IsPacketStart(const uint8_t * rtp_payload) {return true;}
virtual bool IsPacketEnd(const uint8_t * rtp_payload) {return true;}
virtual bool IsPacketReserved(const uint8_t * rtp_payload) {return false;}
virtual bool IsPacketThisType(const uint8_t * rtp_payload) {return true;}
virtual int SkipHeaderSize(const uint8_t * rtp_payload) {return 2;}
};
class NALUTypeBase_H265 : public NALUTypeBase
{
public:
static const string ENCODE_TYPE;
public:
NALUTypeBase_H265();
virtual ~NALUTypeBase_H265() {};
public:
virtual uint16_t ParseNALUHeader_F(const uint8_t * RTPPayload);
virtual uint16_t ParseNALUHeader_Type(const uint8_t * RTPPayload);
virtual uint16_t ParseNALUHeader_Layer_ID(const uint8_t * RTPPayload);
virtual uint16_t ParseNALUHeader_Temp_ID_Plus_1(const uint8_t * RTPPayload);
virtual bool IsPacketStart(const uint8_t * rtp_payload) { return true; }
virtual bool IsPacketEnd(const uint8_t * rtp_payload) { return true; }
virtual bool IsPacketThisType(const uint8_t * rtp_payload);
H265TypeInterface * GetNaluRtpType(int packetization, int nalu_type_id);
virtual std::string GetName() const { return Name; }
virtual bool GetEndFlag() { return EndFlag; }
virtual bool GetStartFlag() { return StartFlag; }
public:
virtual void SetVPS(const string &s) { VPS.assign(s);}
virtual void SetSPS(const string &s) { SPS.assign(s);}
virtual void SetPPS(const string &s) { PPS.assign(s);}
virtual const string GetVPS() { return VPS;}
virtual const string GetSPS() { return SPS;}
virtual const string GetPPS() { return PPS;}
public:
virtual void Init();
virtual uint8_t * PrefixParameterOnce(uint8_t * buf, size_t * size);
virtual bool NeedPrefixParameterOnce();
virtual int ParseParaFromSDP(SDPMediaInfo & sdpMediaInfo);
virtual int ParsePacket(const uint8_t * RTPPayload, size_t size, bool * EndFlag);
virtual size_t CopyData(uint8_t * buf, uint8_t * data, size_t size);
void InsertXPS() { prefixParameterOnce = true; }
void NotInsertXPSAgain() { prefixParameterOnce = false; }
protected:
bool prefixParameterOnce;
string VPS;
string SPS;
string PPS;
// int Packetization;
// std::string Name;
// bool EndFlag;
// bool StartFlag;
public:
H265TypeInterface * NALUType;
};
class H265TypeInterfaceAPs : public H265TypeInterface
{
public:
virtual ~H265TypeInterfaceAPs() {};
public:
virtual bool IsPacketStart(const uint8_t * rtp_payload);
virtual bool IsPacketEnd(const uint8_t * rtp_payload);
virtual bool IsPacketThisType(const uint8_t * rtp_payload);
virtual int SkipHeaderSize(const uint8_t * rtp_payload) {return 2;}
public:
static const uint16_t APs_ID_H265;
};
class H265TypeInterfaceFUs : public H265TypeInterface
{
public:
virtual ~H265TypeInterfaceFUs() {};
public:
/* Function: "ParseNALUHeader_*":
* Return 'FU_A_ERR'(0xFF) if error occurred */
virtual uint16_t ParseNALUHeader_Type(const uint8_t * RTPPayload);
virtual int SkipHeaderSize(const uint8_t * rtp_payload) {return 3;}
public:
static const uint16_t FUs_ID_H265;
public:
/* if FU_A payload type */
bool IsPacketThisType(const uint8_t * rtp_payload);
/* Packet Start Flag */
bool IsPacketStart(const uint8_t * rtp_payload);
/* Packet End Flag */
bool IsPacketEnd(const uint8_t * rtp_payload);
};
#endif
<file_sep>// Copyright 2018 Ansersion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "myRegex.h"
#include "sdp_data.h"
#include <sstream>
#include <stdlib.h>
using std::stringstream;
using std::cout;
using std::endl;
#include <string.h>
static const char * SDP_ORIGIN_PATTERN = "(.*) +(.*) +(.*) +(.*) +(.*) +(.*)";
static const char * SDP_CONNECTION_DATA_PATTERN = "(.*) +(.*) +(.*)";
static const char * SDP_SESSION_TIME_PATTERN = "(.*) +(.*)";
static const char * SDP_RTPMAP_PATTERN("rtpmap:(.+) +([0-9A-Za-z]+)/([0-9]+)/?([0-9])?");
static const char * SDP_FMTP_H264_PATTERN("fmtp:(.+) +packetization-mode=([0-2]);.*sprop-parameter-sets=([A-Za-z0-9+/=]+),([A-Za-z0-9+/=]+)");
static const char * SDP_FMTP_H265_PATTERN("fmtp:(.+) .*sprop-vps=([A-Za-z0-9+/=]+);.*sprop-sps=([A-Za-z0-9+/=]+);.*sprop-pps=([A-Za-z0-9+/=]+)");
static const char * SDP_CONTROL_PATTERN("control:(.+)");
SDPData::~SDPData()
{
}
void SDPData::parse(string &sdp)
{
MyRegex regex;
string pattern = "([a-zA-Z])=(.*)";
string key("");
string value("");
list<string> group;
/* start parse session info first as default */
bool sessionInfo = true, mediaInfo = false, timeInfo = false;
stringstream ssTmp;
SDPMediaInfo * currentMediaInfo = NULL;
// int debugCount=0;
while(regex.RegexLine(&sdp, &pattern, &group)) {
// cout << "debug: Count " << debugCount++ << endl;
if(group.empty()) {
continue;
}
group.pop_front();
group.pop_front();
key.assign(group.front()); group.pop_front();
value.assign(group.front()); group.pop_front();
/* 's': session info start flag */
/* 'm': media info start flag */
/* 't': time info start flag */
if(key == "s") {
sessionInfo = true;
mediaInfo = false;;
timeInfo = false;
} else if(key == "m") {
sessionInfo = false;
mediaInfo = true;;
timeInfo = false;
} else if(key == "t") {
sessionInfo = false;
mediaInfo = false;
timeInfo = true;
}
if(sessionInfo) {
if("s" == key) {
sessionName.assign(value);
} else if("v" == key) {
ssTmp.clear();
ssTmp.str("");
ssTmp << value;
ssTmp >> sdpVersion;
} else if("o" == key) {
if(regex.Regex(value.c_str(), SDP_ORIGIN_PATTERN, &group)) {
group.pop_front();
ssTmp.clear();
ssTmp.str("");
sdpOriginStruct.userName.assign(group.front());
ssTmp << group.front(); group.pop_front();
ssTmp >> sdpOriginStruct.sessionId;
ssTmp << group.front(); group.pop_front();
ssTmp >> sdpOriginStruct.version;
sdpOriginStruct.networkType.assign(group.front());group.pop_front();
sdpOriginStruct.addressType.assign(group.front());group.pop_front();
sdpOriginStruct.address.assign(group.front());group.pop_front();
}
if(regex.Regex(value.c_str(), SDP_CONNECTION_DATA_PATTERN, &group)) {
group.pop_front();
sdpConnectionData.networkType.assign(group.front());group.pop_front();
sdpConnectionData.addressType.assign(group.front());group.pop_front();
sdpConnectionData.address.assign(group.front());group.pop_front();
}
}
}
if(timeInfo) {
if("t" == key) {
if(regex.Regex(value.c_str(), SDP_SESSION_TIME_PATTERN, &group)) {
group.pop_front();
ssTmp.clear();
ssTmp.str("");
ssTmp << group.front(); group.pop_front();
ssTmp >> sdpSessionTime.startTime;
ssTmp << group.front(); group.pop_front();
ssTmp >> sdpSessionTime.stopTime;
}
}
}
if(mediaInfo) {
if("m" == key) {
ssTmp.clear();
ssTmp.str(value);
string tmp;
ssTmp >> tmp;
currentMediaInfo = &mediaInfoMap[tmp];
currentMediaInfo->mediaType.assign(tmp);
ssTmp >> currentMediaInfo->ports;
ssTmp >> currentMediaInfo->transProt;
ssTmp >> tmp;
while(ssTmp && !tmp.empty()) {
stringstream ss;
int payloadId;
ss << tmp;
ss >> payloadId;
map<SDP_ATTR_ENUM, string> * fmtMapTmp = ¤tMediaInfo->fmtMap[payloadId];
(*fmtMapTmp)[MEDIA_TYPE_NAME] = currentMediaInfo->mediaType;
ssTmp >> tmp;
}
} else if("a" == key) {
group.clear();
cout << "debug: mt=" << currentMediaInfo->mediaType << ",line=" << value << endl;
if(currentMediaInfo != NULL && regex.Regex(value.c_str(), SDP_RTPMAP_PATTERN, &group)) {
group.pop_front();
stringstream ss;
int payloadId;
ss << group.front(); group.pop_front();
ss >> payloadId;
map<int, map<SDP_ATTR_ENUM, string> >::iterator it = currentMediaInfo->fmtMap.find(payloadId);
if(it != currentMediaInfo->fmtMap.end()) {
it->second[CODEC_TYPE] = group.front(); group.pop_front();
it->second[TIME_RATE] = group.front(); group.pop_front();
it->second[CHANNEL_NUM] = "1"; // default 1 channel
if(!group.empty()) {
it->second[CHANNEL_NUM] = group.front(); group.pop_front();
}
}
} else if(currentMediaInfo != NULL && "video" == currentMediaInfo->mediaType && regex.Regex(value.c_str(), SDP_FMTP_H265_PATTERN, &group)) {
cout << "debug: Parse h265" << endl;
group.pop_front();
stringstream ss;
int payloadId;
ss << group.front(); group.pop_front();
ss >> payloadId;
map<int, map<SDP_ATTR_ENUM, string> >::iterator it = currentMediaInfo->fmtMap.find(payloadId);
if(it != currentMediaInfo->fmtMap.end()) {
it->second[ATTR_VPS] = group.front(); group.pop_front();
it->second[ATTR_SPS] = group.front(); group.pop_front();
it->second[ATTR_PPS] = group.front(); group.pop_front();
}
} else if(currentMediaInfo != NULL && "video" == currentMediaInfo->mediaType && regex.Regex(value.c_str(), SDP_FMTP_H264_PATTERN, &group)) {
// cout << "SDP_FMTP_H264_PATTERN" << endl;
group.pop_front();
stringstream ss;
int payloadId;
ss << group.front(); group.pop_front();
ss >> payloadId;
map<int, map<SDP_ATTR_ENUM, string> >::iterator it = currentMediaInfo->fmtMap.find(payloadId);
if(it != currentMediaInfo->fmtMap.end()) {
it->second[PACK_MODE] = group.front(); group.pop_front();
it->second[ATTR_SPS] = group.front(); group.pop_front();
it->second[ATTR_PPS] = group.front(); group.pop_front();
}
} else if(currentMediaInfo != NULL && regex.Regex(value.c_str(), SDP_CONTROL_PATTERN, &group)) {
group.pop_front();
currentMediaInfo->controlURI = group.front(); group.pop_front();
}
}
}
}
}
<file_sep>/*
This file is a part of the JThread package, which contains some object-
oriented thread wrappers for different thread implementations.
Copyright (c) 2000-2017 <NAME> (<EMAIL>)
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "jthread.h"
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
namespace jthread
{
JThread::JThread()
{
retval = NULL;
mutexinit = false;
running = false;
threadid = 0;
}
JThread::~JThread()
{
Kill();
}
int JThread::Start()
{
int status;
if (!mutexinit)
{
if (!runningmutex.IsInitialized())
{
if (runningmutex.Init() < 0)
return ERR_JTHREAD_CANTINITMUTEX;
}
if (!continuemutex.IsInitialized())
{
if (continuemutex.Init() < 0)
return ERR_JTHREAD_CANTINITMUTEX;
}
if (!continuemutex2.IsInitialized())
{
if (continuemutex2.Init() < 0)
return ERR_JTHREAD_CANTINITMUTEX;
}
mutexinit = true;
}
continuemutex.Lock();
runningmutex.Lock();
if (running)
{
runningmutex.Unlock();
continuemutex.Unlock();
return ERR_JTHREAD_ALREADYRUNNING;
}
runningmutex.Unlock();
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
status = pthread_create(&threadid,&attr,TheThread,this);
pthread_attr_destroy(&attr);
if (status != 0)
{
continuemutex.Unlock();
return ERR_JTHREAD_CANTSTARTTHREAD;
}
/* Wait until 'running' is set */
runningmutex.Lock();
while (!running)
{
runningmutex.Unlock();
struct timespec req,rem;
req.tv_sec = 0;
req.tv_nsec = 1000000;
nanosleep(&req,&rem);
runningmutex.Lock();
}
runningmutex.Unlock();
continuemutex.Unlock();
continuemutex2.Lock();
continuemutex2.Unlock();
return 0;
}
int JThread::Kill()
{
continuemutex.Lock();
runningmutex.Lock();
if (!running)
{
runningmutex.Unlock();
continuemutex.Unlock();
return ERR_JTHREAD_NOTRUNNING;
}
#ifndef JTHREAD_SKIP_PTHREAD_CANCEL
pthread_cancel(threadid);
#endif // JTHREAD_SKIP_PTHREAD_CANCEL
running = false;
threadid = 0;
runningmutex.Unlock();
continuemutex.Unlock();
return 0;
}
bool JThread::IsRunning()
{
bool r;
runningmutex.Lock();
r = running;
runningmutex.Unlock();
return r;
}
void *JThread::GetReturnValue()
{
void *val;
runningmutex.Lock();
if (running)
val = NULL;
else
val = retval;
runningmutex.Unlock();
return val;
}
bool JThread::IsSameThread()
{
bool same = false;
continuemutex.Lock();
runningmutex.Lock();
if (running)
{
if (pthread_equal(pthread_self(), threadid))
same = true;
}
runningmutex.Unlock();
continuemutex.Unlock();
return same;
}
void *JThread::TheThread(void *param)
{
JThread *jthread;
void *ret;
jthread = (JThread *)param;
jthread->continuemutex2.Lock();
jthread->runningmutex.Lock();
jthread->running = true;
jthread->runningmutex.Unlock();
jthread->continuemutex.Lock();
jthread->continuemutex.Unlock();
ret = jthread->Thread();
jthread->runningmutex.Lock();
jthread->running = false;
jthread->retval = ret;
jthread->threadid = 0;
jthread->runningmutex.Unlock();
return NULL;
}
void JThread::ThreadStarted()
{
continuemutex2.Unlock();
}
} // end namespace
<file_sep>cmake_minimum_required(VERSION 2.8)
project(Base64_live555)
include_directories(include)
file(GLOB SOURCES "*.cpp")
add_library(base64_live555 STATIC ${SOURCES})
install(TARGETS base64_live555 DESTINATION .)
<file_sep>#!/bin/sh
echo "Use 'sh genMakefiles <os-platform>' to generate Makefile"
echo ""
echo "<os-platform>: refer to files 'config.<os-platform>, such as 'config.armlinux' '"
| 2be2a24533157905751169285002f3f36d410cb9 | [
"Markdown",
"CMake",
"C++",
"Shell"
]
| 27 | Markdown | ppdha82/myRtspClient | d5f7ca6bd665e8770d5c3eb7a430b33dcfb37446 | ac9366c738ae7e77e930776031654e38ada9d820 |
refs/heads/master | <repo_name>quanghuy2604/CNPM<file_sep>/README.md
# CNPM
DiemCong
<file_sep>/UDGD_CK/UDGD_CK/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace UDGD_CK
{
public partial class Form1 : Form
{
public static string strname;
public Form1()
{
InitializeComponent();
}
SqlConnection conect = new SqlConnection(@"Data Source=.;Initial Catalog=QLNhanSu;Integrated Security=True");
private void ketnoi()
{
string sql = "select * from NhanVien as NV,ThanNhan where NV.thanNhan_nv= ThanNhan.maTN";
SqlCommand com = new SqlCommand(sql, conect);
com.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
dgriv.DataSource = dt;
}
private void ketnois()
{
string sql = "select * from ChamCong";
SqlCommand com = new SqlCommand(sql, conect);
com.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
dgv_chamcong.DataSource = dt;
}
private void hienthitext()
{
//group first
txt_manv.DataBindings.Clear();
txt_manv.DataBindings.Add("Text", dgriv.DataSource, "maNV");
txt_hoten.DataBindings.Clear();
txt_hoten.DataBindings.Add("Text", dgriv.DataSource, "tenNV");
cb_pb.DataBindings.Clear();
cb_pb.DataBindings.Add("Text", dgriv.DataSource, "phong");
date_birth.DataBindings.Clear();
date_birth.DataBindings.Add("Text", dgriv.DataSource, "ngaySinh");
txt_thannhan.DataBindings.Clear();
txt_thannhan.DataBindings.Add("Text", dgriv.DataSource, "ten_TN");
cb_cv.DataBindings.Clear();
cb_cv.DataBindings.Add("Text", dgriv.DataSource, "chucVu");
cb_honnhan.DataBindings.Clear();
cb_honnhan.DataBindings.Add("Text", dgriv.DataSource, "honNhan");
//group second
txt_diachi.DataBindings.Clear();
txt_diachi.DataBindings.Add("Text", dgriv.DataSource, "diaChi");
txt_cmnd.DataBindings.Clear();
txt_cmnd.DataBindings.Add("Text", dgriv.DataSource, "CMND");
txt_email.DataBindings.Clear();
txt_email.DataBindings.Add("Text", dgriv.DataSource, "email");
txt_sdt.DataBindings.Clear();
txt_sdt.DataBindings.Add("Text", dgriv.DataSource, "sdt");
txt_thannhan.DataBindings.Clear();
txt_thannhan.DataBindings.Add("Text", dgriv.DataSource, "ten_TN");
txt_sdt_nt.DataBindings.Clear();
txt_sdt_nt.DataBindings.Add("Text", dgriv.DataSource, "sdt_TN");
txt_quanhe.DataBindings.Clear();
txt_quanhe.DataBindings.Add("Text", dgriv.DataSource, "quanHe");
txt_diachiTN.DataBindings.Clear();
txt_diachiTN.DataBindings.Add("Text", dgriv.DataSource, "diaChi_TN");
cb_matn.DataBindings.Clear();
cb_matn.DataBindings.Add("Text", dgriv.DataSource,"thanNhan_nv");
// group 3
txt_luong.DataBindings.Clear();
txt_luong.DataBindings.Add("Text", dgriv.DataSource, "luong");
date_begin.DataBindings.Clear();
date_begin.DataBindings.Add("Text", dgriv.DataSource, "ngayBD");
if (rb_work.Checked == true)
{
date_retire.Enabled = false;
}
else
{
date_retire.Enabled = true;
}
date_retire.DataBindings.Clear();
date_retire.DataBindings.Add("Text", dgriv.DataSource,"ngayNV");
// Tab cham cong
cb_ma.DataBindings.Clear();
cb_ma.DataBindings.Add("Text", dgv_chamcong.DataSource, "maNV_cc");
cb_ten.DataBindings.Clear();
cb_ten.DataBindings.Add("Text", dgv_chamcong.DataSource, "tenNV_cc");
datatime_work.DataBindings.Clear();
datatime_work.DataBindings.Add("Text", dgv_chamcong.DataSource, "ngay_cc");
}
private void label1_Click(object sender, EventArgs e)
{
}
private void lb_name_Click(object sender, EventArgs e)
{
}
private void lb_nt_Click(object sender, EventArgs e)
{
}
private void dgriv_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void tab_thongtin_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
conect.Open();
ketnoi();
ketnois();
hienthitext();
SqlDataAdapter pick = new SqlDataAdapter("select * from NhanVien", conect);
DataTable dts = new DataTable();
pick.Fill(dts);
pick.Dispose();
//
cb_ten.DataSource = dts;
cb_ten.DisplayMember = "tenNV";
cb_ten.ValueMember = "MaNV";
cb_ma.DataSource = dts;
cb_ma.DisplayMember = "MaNV";
cb_ma.ValueMember = "MaNV";
SqlDataAdapter picks = new SqlDataAdapter("select * from PhongBan", conect);
DataTable dtss = new DataTable();
picks.Fill(dtss);
picks.Dispose();
cb_pb.DataSource = dtss;
cb_pb.DisplayMember = "maPB";
cb_pb.ValueMember = "maPB";
SqlDataAdapter pickss = new SqlDataAdapter("select * from ThanNhan", conect);
DataTable dtsss = new DataTable();
pickss.Fill(dtsss);
pickss.Dispose();
cb_matn.DataSource = dtsss;
cb_matn.DisplayMember = "maTN";
cb_matn.ValueMember = "maTN";
btn_them.Enabled = false;
btn_sua.Enabled = false;
btn_xoa.Enabled = false;
}
private void dgriv_CellClick(object sender, DataGridViewCellEventArgs e)
{
int t = dgriv.CurrentCell.RowIndex;
if (dgriv.Rows[t].Cells["gioiTinh"].Value.ToString() == "Nam")
rd_nam.Checked = true;
else if(dgriv.Rows[t].Cells["gioiTinh"].Value.ToString() == "Nu")
rd_nu.Checked = true;
else
{
rd_nam.Checked = false;
rd_nu.Checked = false;
}
//
if (dgriv.Rows[t].Cells["tinhTrang"].Value.ToString() == "Dang Lam")
rb_work.Checked = true;
else if (dgriv.Rows[t].Cells["tinhTrang"].Value.ToString() == "Da Nghi")
rb_endwork.Checked = true;
else
{
rb_work.Checked = true;
rb_endwork.Checked = false;
}
if (dgriv.Rows[t].Cells["ngayNV"].Value.ToString() != "")
{
date_retire.DataBindings.Clear();
date_retire.DataBindings.Add("Text", dgriv.DataSource, "ngayNV");
}
else
date_retire.DataBindings.Clear();
if (rb_work.Checked == true)
{
date_retire.Enabled = false;
}
else
{
date_retire.Enabled = true;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dlr = MessageBox.Show("Bạn muốn thoát chương trình?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dlr == DialogResult.No) e.Cancel = true;
conect.Close();
}
private void btn_refresh_Click(object sender, EventArgs e)
{
ketnois();
}
private void btn_sua_Click(object sender, EventArgs e)
{
try
{
string sqlsua = "UPDATE NhanVien SET tenNV=@tenNV,chucVu=@chucVu , phong = @phong, gioiTinh =@gioiTinh, tinhTrang=@tinhTrang,luong=@luong, diaChi=@diaChi, CMND=@CMND,sdt=@sdt,email=@email,thanNhan_nv=@thanNhan_nv, ngayBD=@ngayBD, ngayNV=@ngayNV where MaNV=@MaNV";
SqlCommand cmd = new SqlCommand(sqlsua, conect);
cmd.Parameters.AddWithValue("chucVu", cb_cv.Text);
cmd.Parameters.AddWithValue("MaNV", txt_manv.Text);
cmd.Parameters.AddWithValue("tenNV", txt_hoten.Text);
cmd.Parameters.AddWithValue("phong", cb_pb.Text);
if (rd_nam.Checked == true)
{
cmd.Parameters.AddWithValue("gioiTinh", "Nam");
}
else
{
cmd.Parameters.AddWithValue("gioiTinh", "Nu");
}
if (rb_work.Checked == true)
{
cmd.Parameters.AddWithValue("tinhTrang", "Dang Lam");
}
else
{
cmd.Parameters.AddWithValue("tinhTrang", "Da Nghi");
}
cmd.Parameters.AddWithValue("luong", txt_luong.Text);
cmd.Parameters.AddWithValue("diaChi", txt_diachi.Text);
cmd.Parameters.AddWithValue("CMND", txt_cmnd.Text);
cmd.Parameters.AddWithValue("sdt", txt_sdt.Text);
cmd.Parameters.AddWithValue("email", txt_email.Text);
cmd.Parameters.AddWithValue("thanNhan_nv", cb_matn.Text);
cmd.Parameters.AddWithValue("ngayBD", date_begin.Value);
cmd.Parameters.AddWithValue("ngayNV", date_retire.Value);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("Nhap sai cai gi roi!!!!");
}
ketnoi();
hienthitext();
}
private void btn_xem_Click(object sender, EventArgs e)
{
ketnoi();
hienthitext();
}
private void btn_xoa_Click(object sender, EventArgs e)
{
try
{
string sqldelete = "DELETE from NhanVien where MaNV='" + txt_manv.Text + "'";
SqlCommand cmd = new SqlCommand(sqldelete, conect);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("Ban khong the nhan vien co Chuc Vi cap cao!");
}
ketnoi();
hienthitext();
}
private void btn_them_Click(object sender, EventArgs e)
{
try
{
string sqlthem = "Insert into NhanVien (MaNV,ngaySinh, tenNV, chucVu,phong, gioiTinh, tinhTrang,luong,diaChi, CMND,sdt,email,thanNhan_nv,ngayBD,ngayNV) values (@MaNV,@ngaySinh, @tenNV, @chucVu,@phong, @gioiTinh, @tinhTrang,@luong,@diaChi, @CMND,@sdt,@email, @thanNhan,@ngayBD,@ngayNV) ";
SqlCommand cmd = new SqlCommand(sqlthem, conect);
cmd.Parameters.AddWithValue("chucVu", cb_cv.Text);
cmd.Parameters.AddWithValue("MaNV", txt_manv.Text);
cmd.Parameters.AddWithValue("tenNV", txt_hoten.Text);
cmd.Parameters.AddWithValue("phong", cb_pb.Text);
if (rd_nam.Checked == true)
{
cmd.Parameters.AddWithValue("gioiTinh", "Nam");
}
else
{
cmd.Parameters.AddWithValue("gioiTinh", "Nu");
}
if (rb_work.Checked == true)
{
cmd.Parameters.AddWithValue("tinhTrang", "Dang Lam");
}
else
{
cmd.Parameters.AddWithValue("tinhTrang", "Da Nghi");
}
cmd.Parameters.AddWithValue("luong", txt_luong.Text);
cmd.Parameters.AddWithValue("diaChi", txt_diachi.Text);
cmd.Parameters.AddWithValue("CMND", txt_cmnd.Text);
cmd.Parameters.AddWithValue("sdt", txt_sdt.Text);
cmd.Parameters.AddWithValue("email", txt_email.Text);
cmd.Parameters.AddWithValue("thanNhan", cb_matn.Text);
cmd.Parameters.AddWithValue("ngayBD", date_begin.Value);
cmd.Parameters.AddWithValue("ngayNV", date_retire.Value);
cmd.Parameters.AddWithValue("ngaySinh", date_birth.Value);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("Ma nhan vien da ton tai");
}
ketnoi();
hienthitext();
}
private void cb_ten_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void btn_timkiem_Click(object sender, EventArgs e)
{
if (cb_timtheo.SelectedIndex==0)
{
string sqltim = "select * from NhanVien as NV,ThanNhan as TN where TN.maTN = NV.thanNhan_nv And NV.MaNV= '" + txt_timkiem.Text + "'";
SqlCommand com = new SqlCommand(sqltim, conect);
com.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
dgriv.DataSource = dt;
}
else if (cb_timtheo.SelectedIndex == 1)
{
string sqltim = "select * from NhanVien as NV,ThanNhan as TN where TN.maTN = NV.thanNhan_nv And NV.tenNV= '" + txt_timkiem.Text + "'";
SqlCommand com = new SqlCommand(sqltim, conect);
com.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
dgriv.DataSource = dt;
}
else if (cb_timtheo.SelectedIndex == 2)
{
string sqltim = "select * from NhanVien as NV,ThanNhan as TN where TN.maTN = NV.thanNhan_nv And NV.chucVu= '" + txt_timkiem.Text + "'";
SqlCommand com = new SqlCommand(sqltim, conect);
com.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
dgriv.DataSource = dt;
}
else if (cb_timtheo.SelectedIndex == 3)
{
string sqltim = "select * from NhanVien as NV,ThanNhan as TN where TN.maTN = NV.thanNhan_nv And NV.phong= '" + txt_timkiem.Text + "'";
SqlCommand com = new SqlCommand(sqltim, conect);
com.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
dgriv.DataSource = dt;
}
else if (cb_timtheo.SelectedIndex == 4)
{
string sqltim = "select * from NhanVien as NV,ThanNhan as TN where TN.maTN = NV.thanNhan_nv And NV.gioiTinh= '" + txt_timkiem.Text + "'";
SqlCommand com = new SqlCommand(sqltim, conect);
com.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
dgriv.DataSource = dt;
}
else
{
ketnoi();
}
}
private void btn_themTN_Click(object sender, EventArgs e)
{
Form frm = new Form2();
frm.Show();
ketnoi();
}
private void btn_lm_Click(object sender, EventArgs e)
{
SqlDataAdapter pickss = new SqlDataAdapter("select * from ThanNhan", conect);
DataTable dtsss = new DataTable();
pickss.Fill(dtsss);
pickss.Dispose();
cb_matn.DataSource = dtsss;
cb_matn.DisplayMember = "maTN";
cb_matn.ValueMember = "maTN";
}
private void btn_dilam_Click(object sender, EventArgs e)
{
try
{
string sqlthem = "Insert into ChamCong(maNV_cc,tenNV_cc,ngay_cc,tinhTrang_cc,ghiChu_cc) values (@maNV_cc,@tenNV_cc,@ngay_cc,@tinhTrang_cc,@ghiChu_cc) ";
SqlCommand cmd = new SqlCommand(sqlthem, conect);
cmd.Parameters.AddWithValue("maNV_cc", cb_ma.Text);
cmd.Parameters.AddWithValue("tenNV_cc", cb_ten.Text);
cmd.Parameters.AddWithValue("tinhTrang_cc", "Di lam");
cmd.Parameters.AddWithValue("ngay_cc", datatime_work.Value);
cmd.Parameters.AddWithValue("ghiChu_cc", txt_ghiChu.Text);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("Du lieu ngay cong cua nhan vien da dc nhap!");
}
ketnois();
}
private void btn_nghi_Click(object sender, EventArgs e)
{
string sqldelete = "DELETE from ChamCong where maNV_cc='" + cb_ma.Text + "'"+ "And ngay_cc='"+datatime_work.Value+"'";
SqlCommand cmd = new SqlCommand(sqldelete, conect);
cmd.ExecuteNonQuery();
ketnois();
}
private void dgv_chamcong_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void btn_suacong_Click(object sender, EventArgs e)
{
try
{
string sqlsua = "UPDATE ChamCong SET maNV_cc=@maNV_cc, tenNV_cc=@tenNV_cc, ngay_cc=@ngay_cc, tinhTrang_cc=@tinhTrang_cc, ghiChu_cc=@ghiChu_cc";
SqlCommand cmd = new SqlCommand(sqlsua, conect);
cmd.Parameters.AddWithValue("maNV_cc", cb_ma.Text);
cmd.Parameters.AddWithValue("tenNV_cc", cb_ten.Text);
cmd.Parameters.AddWithValue("ngay_cc", datatime_work.Value);
cmd.Parameters.AddWithValue("tinhTrang_cc", cb_tt.Text);
cmd.Parameters.AddWithValue("ghiChu_cc", txt_ghiChu.Text);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
MessageBox.Show("Du lieu cham cong da ton tai!");
}
ketnoi();
}
public string lmit = "0";
private void btn_dn_Click(object sender, EventArgs e)
{
dangnhap frm = new dangnhap();
frm.data = new dangnhap.gdl(gvl);
frm.limits = new dangnhap.gdl(glm);
frm.Show();
}
public void gvl(string values)
{
lb_user.Text = "Xin chao:" + values;
}
public void glm(string values)
{
lmit = values;
if (Int32.Parse(lmit) > 5)
{
btn_xoa.Enabled = true;
btn_them.Enabled = true;
btn_sua.Enabled = true;
}
else
{
btn_xoa.Enabled = false;
btn_them.Enabled = false;
btn_sua.Enabled = false;
}
}
}
}
| 941b7191d76e7848ca20fe70db738f105d0f1028 | [
"Markdown",
"C#"
]
| 2 | Markdown | quanghuy2604/CNPM | bc40e60ad6f465e90f87912662d8e02cef84fb71 | 53ea8d0b2848f05308ee84d337fd057b642f2584 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
export class Cart extends Component {
render() {
return (
<div>
<h4>I am a cart</h4>
</div>
);
}
}
export default Cart;
| cea1d28c320c50f70369ffbbf85b1244379457c4 | [
"JavaScript"
]
| 1 | JavaScript | AlfonsoArriola/e-store | 2805eb9522fe280275b47d77ce964e0efc1293d7 | 4609318d7c9c5c89f896e9da199b4c3b7c4c86d1 |
refs/heads/master | <file_sep>package weektest.baway.com.wenzhuang20190326.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import weektest.baway.com.wenzhuang20190326.R;
/**
* @author: 温壮
* @Date: 2019/3/26 9:03
* @description: $描述
*/
public class FragmentDome2 extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.fragment_demo2, container, false);
return inflate;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
| 981978788719f31547c4599b1ab7518ae0eadf2c | [
"Java"
]
| 1 | Java | wenzhuang0401/WenZhuang20190326 | 7aa0115a69449322793e7240c4888080063c53e0 | a8939c0a810946dc2812e9deb3c12c0d9d390130 |
refs/heads/main | <repo_name>andreaskasper/php_lib_cryptocom<file_sep>/src/Instrument.php
<?php
/**
* Instrument is a pair of 2 currencies
*
* Instrument is a pair of 2 currencies
*
* @category cryptocoins
* @package cryptocom
* @author <NAME> <<EMAIL>>
* @copyright 2021
* @license MIT
* @version Release: 0.1
* @link https://github.com/andreaskasper/php_lib_cryptocom/
* @see /examples
* @since 2021-05-12
**/
namespace cryptocom;
class Instrument {
private static $_cache = null;
private static $_cache2 = array();
private $_id = null;
public function __construct($id = null, $id2 = null) {
if (is_null($id2) AND preg_match("@^[A-Z]+_[A-Z]+$@", $id)) {
$this->_id = $id;
return;
}
if (!is_null($id) AND !is_null($id2)) {
$this->_id = $id->id."-".$id2->id;
return;
}
}
public function __get($name) {
switch ($name) {
case "id":
return $this->_id;
case "exists":
self::load0();
return isset(self::$_cache2[$this->_id]);
case "base":
self::load0();
return new Currency(self::$_cache2[$this->_id]["base_currency"] ?? null);
case "quote":
self::load0();
return new Currency(self::$_cache2[$this->_id]["quote_currency"] ?? null);
case "price_decimals":
self::load0();
return self::$_cache2[$this->_id]["price_decimals"] ?? null;
case "quantity_decimals":
self::load0();
return self::$_cache2[$this->_id]["quantity_decimals"] ?? null;
}
}
public static function list() {
self::load0();
$out = array();
foreach (self::$_cache2 as $k => $v) $out = new Instrument($k);
return $out;
}
private static function load0() {
if (is_null(self::$_cache)) {
self::$_cache = core::request("public/get-instruments", array(), false);
foreach (self::$_cache["result"]["instruments"] as $row) self::$_cache2[$row["instrument_name"]] = $row;
}
return self::$_cache;
}
}
<file_sep>/src/SpotTradingOrder.php
<?php
namespace cryptocom;
class SpotTradingOrder {
private $_id = null;
private $cacheurdata = null;
private $cachedata0 = null;
public function __construct($v) {
//echo("Test:".$v.PHP_EOL);
if (is_string($v) OR is_numeric($v)) {
$this->_id = $v."";
} elseif (is_array($v) AND !empty($v)) {
$this->cacheurdata = $v;
$this->_id = $v["order_id"];
}
}
public function __get($name) {
switch ($name) {
case "id": return $this->_id;
case "data": $this->load0(); return $this->cachedata0;
case "urdata": return $this->cacheurdata;
case "exist":
case "exists": $a = $this->load0(); return !empty($a["result"]["order_info"]["status"]);
case "status": return $this->cacheurdata["status"] ?? $this->load0()["result"]["order_info"]["status"] ?? null;
case "side": return $this->cacheurdata["side"] ?? $this->load0()["result"]["order_info"]["side"] ?? null;
case "instrument_string": return $this->cacheurdata["instrument_name"] ?? $this->load0()["result"]["order_info"]["instrument_name"] ?? null;
case "instrument": if (!is_null($this->instrument_string)) return new Instrument($this->instrument_string); else return null;
case "type": return $this->cacheurdata["type"] ?? $this->load0()["result"]["order_info"]["type"] ?? null;
case "price": return new Price($this->cacheurdata["price"] ?? $this->load0()["result"]["order_info"]["price"] ?? null, $this->instrument->quote->id);
case "quantity": return new Quantity($this->cacheurdata["quantity"] ?? $this->load0()["result"]["order_info"]["quantity"] ?? null, $this->instrument->base->id);
case "created": new \DateTime("@".($this->cacheurdata["create_time"] ?? $this->load0()["result"]["order_info"]["create_time"] ?? null));
case "updated": new \DateTime("@".($this->cacheurdata["update_time"] ?? $this->load0()["result"]["order_info"]["update_time"] ?? null));
}
return null;
}
public function refresh() {
$w = array();
$w["order_id"] = $this->_id;
$this->cachedata0 = core::request("private/get-order-detail", $w, true);
return $this->cachedata0;
}
private function load0() {
if (is_null($this->cachedata0)) {
return $this->refresh();
}
return $this->cachedata0;
}
}
<file_sep>/phpunit_test/BookTest.php
<?php
/**
*
*
*
*
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
*/
namespace cryptocom\Test;
use PHPUnit\Framework\TestCase;
/**
* PHPMailer - PHP email transport unit test class.
*/
final class BookTest extends TestCase {
public function testbook() {
$instrument = new \cryptocom\Instrument("BTC_USDT");
$this->assertEquals("BTC_USDT", $instrument->id);
$this->assertEquals(true, $instrument->exists);
}
}
<file_sep>/src/Common.php
<?php
namespace cryptocom;
/**
*
* https://exchange-docs.crypto.com/spot/index.html#common-api-reference
*/
class Common {
public static function book(Instrument $instrument, int $depth = null) : Array {
$out = array();
$w = array();
$w["instrument_name"] = $instrument->id;
if (!empty($depth)) $w["depth"] = $depth;
$data = core::request("public/get-book", $w);
//print_r($data); exit;
foreach ($data["result"]["data"][0]["bids"] as $row) $out["bids"][] = array("price" => new Price($row[0], $instrument->quote->id), "quantity" => new Quantity($row[1], $instrument->base->id), "count" => $row[2]);
foreach ($data["result"]["data"][0]["asks"] as $row) $out["asks"][] = array("price" => new Price($row[0], $instrument->quote->id), "quantity" => new Quantity($row[1], $instrument->base->id), "count" => $row[2]);
$out["instrument"] = $instrument;
$out["timestamp"] = new \DateTime("@".($data["result"]["data"][0]["t"]/1000));
return $out;
}
public static function get_deposit_address(Currency $currency) : Array {
$out = array();
$w = array();
$w["currency"] = $currency->id;
//print_r($w);
$data = core::request("private/get-deposit-address", $w, true);
return $data["result"]["deposit_address_list"] ?? null;
}
public static function ticker(Instrument $instrument) : Array {
$w = array();
$w["instrument_name"] = $instrument->id;
$data = core::request("public/get-ticker", $w);
$out = array();
foreach ($data["result"]["data"] as $row) {
$inst = new Instrument($row["i"]);
return array(
"instrument" => $inst,
"bid" => new Price($row["b"], $inst->base->id),
"ask" => new Price($row["k"], $inst->base->id),
"last" => new Price($row["a"], $inst->base->id),
"volume" => new Quantity($row["v"], $inst->quote->id),
"high" => new Quantity($row["h"], $inst->base->id),
"low" => new Quantity($row["l"], $inst->base->id),
"change" => new Quantity($row["c"], $inst->base->id),
"timestamp" => new \DateTime("@".$row["t"])
);
}
return null;
}
public static function ticker_all() : Array {
$data = core::request("public/get-ticker", array());
$out = array();
foreach ($data["result"]["data"] as $row) {
$inst = new Instrument($row["i"]);
$out[$row["i"]] = array(
"instrument" => $inst,
"bid" => new Price($row["b"], $inst->base->id),
"ask" => new Price($row["k"], $inst->base->id),
"last" => new Price($row["a"], $inst->base->id),
"volume" => new Quantity($row["v"], $inst->quote->id),
"high" => new Quantity($row["h"], $inst->base->id),
"low" => new Quantity($row["l"], $inst->base->id),
"change" => new Quantity($row["c"], $inst->base->id),
"timestamp" => new \DateTime("@".$row["t"])
);
}
if (!is_null($instrument)) return $out[$row["i"]];
return $out;
}
}
<file_sep>/phpunit_test/CurrencyTest.php
<?php
/**
*
*
*
*
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
*/
namespace cryptocom\Test;
use PHPUnit\Framework\TestCase;
/**
* crypto.com - Currency tester
*/
final class CurrencyTest extends TestCase {
public function testcurrencies() {
$curs = array("BTC", "XRP", "CRO");
foreach ($curs as $a) {
$currency = new \cryptocom\Currency($a);
$this->assertEquals(true, is_string($currency->id));
$this->assertEquals(true, is_string($currency->string));
}
}
}
<file_sep>/src/Quantity.php
<?php
namespace cryptocom;
class Quantity extends Coins {}
<file_sep>/src/SpotTrading.php
<?php
namespace cryptocom;
class SpotTrading {
CONST GOOD_TILL_CANCEL = 1;
CONST FILL_OR_KILL = 2;
CONST IMMEDIATE_OR_CANCEL = 3;
CONST BUY = 5;
CONST SELL = 6;
public static function account_summary($currency = null) : Array {
if (empty($currency)) $res = core::request("private/get-account-summary", array(), true);
else $res = core::request("private/get-account-summary", array("currency" => $currency), true);
//print_r($res);
$out = array();
foreach ($res["result"]["accounts"] as $row) {
$out[$row["currency"]] = array(
"balance" => new Quantity($row["balance"], $row["currency"]),
"available" => new Quantity($row["available"], $row["currency"]),
"order" => new Quantity($row["order"], $row["currency"]),
"stake" => new Quantity($row["stake"], $row["currency"]),
"currency" => new Currency($row["currency"])
);
}
return $out;
}
public static function cancel_all_orders(Instrument $instrument) {
$w = array();
$w["instrument_name"] = $instrument->id;
return core::request("private/cancel-all-orders", $w, true);
}
public static function create_limit_order(Instrument $instrument, $side, mixed $quantity, mixed $price, $timeinforce = null) {
if (is_null($timeinforce)) $timeinforce = self::GOOD_TILL_CANCEL;
if (!in_array($side, array(self::BUY, self::SELL))) throw new \Exception("Unknown Side");
if (!in_array($timeinforce, array(self::GOOD_TILL_CANCEL, self::FILL_OR_KILL, self::IMMEDIATE_OR_CANCEL))) throw new \Exception("Unknown TimeInForce");
$w = array();
$w["instrument_name"] = $instrument->id;
$w["side"] = [5 => "BUY", 6 => "SELL"][$side];
$w["type"] = "LIMIT";
if (is_numeric($price)) $w["quantity"] = number_format($quantity, $instrument->quantity_decimals, ".", "");
else $w["quantity"] = number_format($quantity->amount, $instrument->quantity_decimals, ".", "");
if (is_numeric($price)) $w["price"] = number_format($price, $instrument->price_decimals, ".", "");
else $w["price"] = number_format($price->amount, $instrument->price_decimals, ".", "");
$w["time_in_force"] = [1 => "GOOD_TILL_CANCEL",2 => "FILL_OR_KILL",3 => "IMMEDIATE_OR_CANCEL"][$timeinforce];
$resp = core::request("private/create-order", $w, true);
if ($resp["code"] == 30008) throw new \Exception("Minimales Investment für ".$w["instrument_name"]." mit ".$w["quantity"]." unterschritten...");
if ($resp["code"] != 0) throw new \Exception("Problem mit Order: ".json_encode($resp));
//print_r($resp);
return new SpotTradingOrder($resp["result"]["order_id"]."");
}
public static function create_market_order(Instrument $instrument, $side, mixed $quantity) {
if (!in_array($side, array(self::BUY, self::SELL))) throw new \Exception("Unknown Side");
$w = array();
$w["instrument_name"] = $instrument->id;
$w["side"] = [5 => "BUY", 6 => "SELL"][$side];
$w["type"] = "MARKET";
if (is_numeric($quantity)) $q = number_format($quantity, $instrument->quantity_decimals, ".", "");
else $q = number_format($quantity->amount, $instrument->quantity_decimals, ".", "");
if ($w["side"] == "BUY") $w["notional"] = $q;
if ($w["side"] == "SELL") $w["quantity"] = $q;
$resp = core::request("private/create-order", $w, true);
if ($resp["code"] == 30008) throw new \Exception("Minimales Investment für ".$w["instrument_name"]." mit ".$w["quantity"]." unterschritten...");
if ($resp["code"] != 0) throw new \Exception("Problem mit Order: ".json_encode($resp));
//print_r($resp);
return new SpotTradingOrder($resp["result"]["order_id"]."");
}
public static function open_orders(Instrument $instrument, int $page = null, int $pagesize = null) {
$out = array();
$w = array();
$w["instrument_name"] = $instrument->id;
if (!is_null($page)) $w["page"] = $page;
if (!is_null($pagesize)) $w["page_size"] = $pagesize;
$resp = core::request("private/get-open-orders", $w, true);
foreach ($resp["result"]["order_list"] as $row) $out[] = new SpotTradingOrder($row);
return $out;
}
public static function order_history(Instrument $instrument, \DateTime $start_ts = null, \DateTime $end_ts = null, int $page = null, int $pagesize = null) {
$out = array();
$w = array();
$w["instrument_name"] = $instrument->id;
if (!is_null($page)) $w["page"] = $page;
if (!is_null($pagesize)) $w["page_size"] = $pagesize;
$resp = core::request("private/get-order-history", $w, true);
foreach ($resp["result"]["order_list"] as $row) $out[] = new SpotTradingOrder($row);
return $out;
}
}
<file_sep>/README.md
# php_lib_cryptocom
A php class API wrapper for crypto.com

[](https://travis-ci.org/andreaskasper/php_lib_cryptocom)
### Bugs & Issues:
[](https://github.com/andreaskasper/php_lib_cryptocom/issues)

# Features
# Install
## via Composer
composer.json
```json
{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/andreaskasper/php_lib_cryptocom"
}
],
"require": {
"andreaskasper/cryptocom": "*"
},
"minimum-stability": "dev"
}
```
then use composer for example via docker
```console
foo@bar:~$ docker run -it --rm -v ${PWD}:/app/ composer update
```
# Steps
- [x] Build a base test image to test this build process (Travis/Docker)
- [ ] Build tests
- [ ] Gnomes
- [ ] Profit
### support the projects :hammer_and_wrench:
[](https://www.patreon.com/AndreasKasper)
[](https://www.paypal.me/AndreasKasper)
[](bitcoin:35pBJSdu7DJJPyX6Mnz57aQ68uL89yL7ga?label=github-http-honeypot)
<file_sep>/src/core.php
<?php
/**
* Core Functions to request at crypto.com API v2
*
* Core Functions to request at crypto.com API v2
*
* @category cryptocoins
* @package cryptocom
* @author <NAME> <<EMAIL>>
* @copyright 2021
* @license MIT
* @version Release: 0.1
* @link https://github.com/andreaskasper/php_lib_cryptocom/
* @see /examples
* @since 2021-05-12
**/
namespace cryptocom;
class core {
private static $_appkey = null;
private static $_secret = null;
private static $_sandbox = false;
public static function setAPIToken($appkey,$secret) {
self::$_appkey = $appkey;
self::$_secret = $secret;
}
public static function request(string $method, Array $params, bool $signed = null) : Array{
if (self::$_sandbox) $urlroot = "https://uat-api.3ona.co/v2/";
else $urlroot = "https://api.crypto.com/v2/";
if (is_null($signed) OR !$signed) {
$str = file_get_contents($urlroot.$method."?".http_build_query($params));
return json_decode($str, true);
} else {
if (is_null(self::$_appkey)) throw new \Exception("Missing App Key");
if (is_null(self::$_secret)) throw new \Exception("Missing App Secret");
$w = array();
$w["id"] = rand(0,9999999);
$w["method"] = $method;
$b = "";
if (empty($params)) $w["params"] = new \stdClass;
else {
$w["params"] = $params;
ksort($params);
foreach ($params as $k => $v) $b .= $k.$v;
}
$w["api_key"] = self::$_appkey;
$w["nonce"] = time()*1000;
$presig = $w["method"].$w["id"].$w["api_key"].$b.$w["nonce"];
$w["sig"] = hash_hmac("sha256", $presig, self::$_secret);
/*print_r($params);
echo($b.PHP_EOL);
echo($presig.PHP_EOL);*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $urlroot.$w["method"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($w));
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
//curl_setopt($ch, CURLOPT_VERBOSE, true);
$resp = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$resp2 = json_decode($resp, true);
if ($resp2["code"] == 10002) {
print_r($params);
echo($b.PHP_EOL);
echo($presig.PHP_EOL);
print_r($resp2);
throw new \Exception("Error");
}
$resp2 = json_decode($resp, true);
if ($resp2["code"] == 10004) { //BAD_REQUEST
print_r($params);
echo($b.PHP_EOL);
echo($presig.PHP_EOL);
print_r($resp2);
throw new \Exception("Bad Request");
}
return $resp2;
}
}
}
<file_sep>/src/Currency.php
<?php
namespace cryptocom;
class Currency {
private $_id = null;
public function __construct($v) {
$this->_id = $v;
}
public function __get($name) {
switch (strtolower($name)) {
case "id": return $this->_id;
case "string": return $this->__string();
case "symbol": return $this->symbol();
}
}
public function symbol() :string {
switch ($this->_currency) {
case "BCH": return "Ƀ";
case "BTC": return "₿";
case "DOGE": return "Ð";
case "ETH": return "Ξ";
case "USDT": return "₮";
case "XRP": return "✕";
default: return $this->_id;
}
}
public function __string() {
return $this->_id;
}
}
<file_sep>/src/Price.php
<?php
namespace cryptocom;
class Price {
private $_amount = null;
private $_currency = null;
public function __construct($a1 = null, $a2 = null) {
if (is_numeric($a1) AND is_string($a2)) {
$this->_amount = $a1;
$this->_currency = $a2;
}
}
public function __get($name) {
switch($name) {
case "amount": return $this->_amount;
case "value": return $this->_amount;
case "string": return $this->_amount.$this->currency->symbol;
case "currency": return new Currency($this->_currency);
case "tousdt":
case "inusdt":
if ($this->_currency == "USDT") return $this;
if ($this->amount == 0) return new Price(0, "USDT");
$inst = new Instrument($this->_currency."_USDT");
$book = Common::book($inst, 1);
return new Price((( $book["asks"][0]["price"] + $book["bids"][0]["price"]) / 2) * $this->_amount, "USDT");
}
return null;
}
public function __string() {
return $this->_amount.$this->currency->symbol;
}
public function multiply($value) {
if (is_object($value) AND get_class($value) == "cryptocom\Quantity") return new Price($this->_amount*$value->amount, $this->_currency);
return new Price($this->_amount*$value, $this->_currency);
}
}
| 3332a99b964d1e0fe0ff2baf1c3a2586915a9ee2 | [
"Markdown",
"PHP"
]
| 11 | PHP | andreaskasper/php_lib_cryptocom | a5e2fbd69dddb050aaa51bd065c94e9e6f0c1b90 | b4163a91ab51598d2849d7d97bbedb425b7e878a |
refs/heads/master | <repo_name>ricardopereira/cpp.nana<file_sep>/Source/Classes/WinnerScene.h
//
// WinnerScene.h
// Nana
//
// Created by <NAME> on 14/12/13.
//
//
#ifndef __Nana__WinnerScene__
#define __Nana__WinnerScene__
#include <iostream>
#include "cocos2d.h"
using namespace cocos2d;
class WinnerLayer;
class WinnerScene : public cocos2d::Scene
{
Menu *menu;
public:
WinnerScene():_layer(NULL) {};
~WinnerScene();
bool init();
CREATE_FUNC(WinnerScene);
// a selector callback
virtual void menuPrendaCallback(cocos2d::Object* sender);
void showMenuCallback();
CC_SYNTHESIZE_READONLY(WinnerLayer*, _layer, Layer);
};
class WinnerLayer : public cocos2d::LayerColor
{
public:
WinnerLayer(): _label(NULL) {};
virtual ~WinnerLayer();
bool init();
CREATE_FUNC(WinnerLayer);
void winnerDone();
CC_SYNTHESIZE_READONLY(cocos2d::LabelTTF*, _label, Label);
};
#endif /* defined(__Nana__WinnerScene__) */
<file_sep>/Source/Classes/Common.cpp
//
// Common.cpp
// Nana
//
// Created by <NAME> on 14/12/13.
//
//
#include "Common.h"
int Common::countGameOvers = 0;
string Common::messages[MAXMESSAGES];<file_sep>/Source/Classes/StartScene.h
//
// StartScene.h
// Nana
//
// Created by <NAME> on 14/12/13.
//
//
#ifndef __Nana__StartScene__
#define __Nana__StartScene__
#include <iostream>
#include "cocos2d.h"
class StartLayer;
class StartScene : public cocos2d::Scene
{
void loadMessages();
public:
StartScene() : _layer(NULL) {};
~StartScene();
bool init();
CREATE_FUNC(StartScene);
// there's no 'id' in cpp, so we recommand to return the exactly class pointer
static cocos2d::Scene* scene();
// a selector callback
virtual void menuStartCallback(cocos2d::Object* sender);
CC_SYNTHESIZE_READONLY(StartLayer*, _layer, Layer);
};
class StartLayer : public cocos2d::LayerColor
{
public:
StartLayer(): _label(NULL) {};
virtual ~StartLayer();
bool init();
CREATE_FUNC(StartLayer);
void startDone();
CC_SYNTHESIZE_READONLY(cocos2d::LabelTTF*, _label, Label);
};
#endif /* defined(__Nana__StartScene__) */<file_sep>/Source/Classes/WinnerScene.cpp
//
// WinnerScene.cpp
// Nana
//
// Created by <NAME> on 14/12/13.
//
//
#include "WinnerScene.h"
#include "MainScene.h"
#include "SimpleAudioEngine.h"
#include "WrapperClass.h"
bool WinnerScene::init()
{
if( Scene::init() )
{
auto winSize = Director::getInstance()->getWinSize();
auto visibleSize = Director::getInstance()->getVisibleSize();
auto origin = Director::getInstance()->getVisibleOrigin();
this->_layer = WinnerLayer::create();
this->_layer->retain();
//this->_layer->getLabel()->setString("Ganhaste");
this->addChild(_layer);
// Create a "close" menu item with close icon, it's an auto release object.
auto startItem = cocos2d::MenuItemImage::create(
"Prenda.png",
"Prenda.png",
CC_CALLBACK_1(WinnerScene::menuPrendaCallback,this));
startItem->setPosition(Point(origin.x + (visibleSize.width/2),
origin.y + 60));
// Create a menu with the "close" menu item, it's an auto release object.
menu = Menu::create(startItem, NULL);
// Add the menu to Main layer as a child layer.
this->addChild(menu,1);
menu->setVisible(false);
this->runAction( Sequence::create(
DelayTime::create(3),
CallFunc::create( CC_CALLBACK_0(WinnerScene::showMenuCallback, this)),
NULL));
return true;
}
else
{
return false;
}
}
WinnerScene::~WinnerScene()
{
if (_layer)
{
_layer->release();
_layer = NULL;
}
}
void WinnerScene::menuPrendaCallback(Object* sender)
{
WrapperClass::getShared()->playVideo("video");
}
void WinnerScene::showMenuCallback()
{
menu->setVisible(true);
menu->setPosition(Point::ZERO);
}
bool WinnerLayer::init()
{
if ( LayerColor::initWithColor( Color4B(255,255,255,255) ) )
{
auto winSize = Director::getInstance()->getWinSize();
auto visibleSize = Director::getInstance()->getVisibleSize();
auto origin = Director::getInstance()->getVisibleOrigin();
CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic();
// Background
auto sprite = Sprite::create("Default.png");
sprite->setPosition(Point(visibleSize / 2) + origin);
this->addChild(sprite);
auto wplay = Sprite::create("Parabens.png");
wplay->setPosition(Point(origin.x + (visibleSize.width/2),
origin.y + 200));
this->addChild(wplay);
this->_label = LabelTTF::create("","Artial", 32);
_label->retain();
_label->setColor( Color3B(0, 0, 0) );
_label->setPosition( Point(winSize.width/2, winSize.height/2) );
this->addChild(_label);
return true;
}
else
{
return false;
}
}
void WinnerLayer::winnerDone()
{
Director::getInstance()->replaceScene( MainScene::scene() );
}
WinnerLayer::~WinnerLayer()
{
if (_label)
{
_label->release();
_label = NULL;
}
}<file_sep>/Source/Classes/StartScene.cpp
//
// StartScene.cpp
// Nana
//
// Created by <NAME> on 14/12/13.
//
//
#include "StartScene.h"
#include "Common.h"
#include "MainScene.h"
using namespace cocos2d;
bool StartScene::init()
{
if( Scene::init() )
{
Director::getInstance()->setDisplayStats(false);
auto winSize = Director::getInstance()->getWinSize();
auto visibleSize = Director::getInstance()->getVisibleSize();
auto origin = Director::getInstance()->getVisibleOrigin();
loadMessages();
this->_layer = StartLayer::create();
this->_layer->retain();
this->addChild(_layer);
// Create a "close" menu item with close icon, it's an auto release object.
auto startItem = cocos2d::MenuItemImage::create(
"Sim.png",
"Sim.png",
CC_CALLBACK_1(StartScene::menuStartCallback,this));
startItem->setPosition(Point(origin.x + (visibleSize.width/2),
origin.y + 50));
// Create a menu with the "close" menu item, it's an auto release object.
auto menu = Menu::create(startItem, NULL);
menu->setPosition(Point::ZERO);
// Add the menu to Main layer as a child layer.
this->addChild(menu,1);
return true;
}
else
{
return false;
}
}
StartScene::~StartScene()
{
if (_layer)
{
_layer->release();
_layer = NULL;
}
}
void StartScene::menuStartCallback(Object* sender)
{
Director::getInstance()->replaceScene( MainScene::scene() );
}
Scene* StartScene::scene()
{
Scene * scene = NULL;
do
{
// 'scene' is an autorelease object
scene = Scene::create();
CC_BREAK_IF(! scene);
// 'layer' is an autorelease object
StartScene *layer = StartScene::create();
CC_BREAK_IF(! layer);
// add layer as a child to scene
scene->addChild(layer);
} while (0);
// return the scene
return scene;
}
void StartScene::loadMessages()
{
Common::messages[0] = "Parabéns";
Common::messages[1] = "Ups, já foste";
Common::messages[2] = "Eu sei que tens medo";
Common::messages[3] = "Sem medo, força";
Common::messages[4] = "Tu consegues, não desistas";
Common::messages[5] = "Tu és forte";
Common::messages[6] = "Arrebenta com isso tudo";
Common::messages[7] = "Faz força!";
Common::messages[8] = ":P";
Common::messages[9] = "Ih ih";
}
//Layer
bool StartLayer::init()
{
if ( LayerColor::initWithColor( Color4B(255,255,255,255) ) )
{
auto winSize = Director::getInstance()->getWinSize();
auto visibleSize = Director::getInstance()->getVisibleSize();
auto origin = Director::getInstance()->getVisibleOrigin();
// Background
auto sprite = Sprite::create("Default.png");
sprite->setPosition(Point(visibleSize / 2) + origin);
this->addChild(sprite);
auto wplay = Sprite::create("WantPlay.png");
wplay->setPosition(Point(origin.x + (visibleSize.width/2) + 20,
origin.y + 250));
this->addChild(wplay);
return true;
}
else
{
return false;
}
}
void StartLayer::startDone()
{
Director::getInstance()->replaceScene( MainScene::scene() );
}
StartLayer::~StartLayer()
{
if (_label)
{
_label->release();
_label = NULL;
}
}<file_sep>/Source/Classes/WrapperClass.cpp
#include "WrapperClass.h"
#include "iOSWrapper.h"
static WrapperClass *instance = NULL;
void WrapperClass::playVideo(const char *vidPath)
{
iOSWrapper::getShared()->playVideo(vidPath);
}
WrapperClass *WrapperClass::getShared()
{
if (!instance)
{
instance = new WrapperClass();
}
return instance;
}<file_sep>/Source/Classes/Common.h
//
// Common.h
// Nana
//
// Created by <NAME> on 14/12/13.
//
//
#ifndef __Nana__Common__
#define __Nana__Common__
#define MAXMESSAGES 10
#include <iostream>
using namespace std;
class Common
{
public:
static int countGameOvers;
static string messages[MAXMESSAGES];
};
#endif /* defined(__Nana__Common__) */<file_sep>/Source/Classes/iOSWrapper.h
//
// iOSWrapper.h
// Farmer
//
// Created by Lekshmi on 28/08/13.
//
//
#ifndef __Farmer__iOSWrapper__
#define __Farmer__iOSWrapper__
#include "cocos2d.h"
class iOSWrapper: public cocos2d::CCObject
{
public:
void playVideo(const char *name);
static iOSWrapper *getShared();
};
#endif /* defined(__Farmer__iOSWrapper__) */
| 2b57028c46f9ce711e5bd3bcf7321203cf7f1caf | [
"C++"
]
| 8 | C++ | ricardopereira/cpp.nana | a480ee5535759d82b9fa6d5796a8af23de69c0b8 | 80dcb5c1367032b10d12e00ce60080bd408fe3ee |
refs/heads/master | <file_sep>
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
from lxml import etree
from cStringIO import StringIO
try:
import pytidy
except ImportError:
from pas import pytidy
class Semantics(object):
def __init__(self, sem):
self.semantics = sem
def toxml(self):
semantics = etree.Element('semantics')
attrs = semantics.attrib
attrs['sync'] = str(int(self.sync))
attrs['async'] = str(int(self.async))
attrs['seq'] = str(int(self.seq))
attrs['conc'] = str(int(self.conc))
attrs['mutex'] = str(int(self.mutex))
attrs['construct'] = str(int(self.construct))
return semantics
def __str__(self):
if self.conc:
s = 'conc'
elif self.mutex:
s = 'mutex'
else:
s = 'seq'
s += ' sync' if self.sync else ' async'
if self.construct:
s += ' construct'
return s
@property
def construct(self):
return bool(self.semantics & 4)
@property
def sync(self):
return bool(self.semantics & 1)
@property
def async(self):
return not self.sync
@property
def mutex(self):
return bool(self.semantics & 16)
@property
def conc(self):
return bool(self.semantics & 8)
@property
def seq(self):
return not self.mutex and not self.conc
class POPRequest(object):
type = 'request'
def __init__(self, semantics, klass, method, arguments, buffer):
self.semantics = semantics
self.klass = klass
self.method = method
self.arguments = arguments
def toxml(self):
el = etree.Element('request')
el.attrib['classid'] = str(self.klass.id)
el.attrib['class'] = self.klass.name
mth = self.method.toxml()
for t, a in zip(self.method.args, self.arguments):
arg = etree.SubElement(mth, 'arg')
arg.attrib['type'] = t.__name__
arg.text = repr(a)
el.append(self.semantics.toxml())
el.append(mth)
etree.SubElement(el, 'repr').text = repr(self)
etree.SubElement(el, 'short').text = str(self)
etree.SubElement(el, 'highlighted').append(
etree.fromstring(self.formatted())
)
return el
def __str__(self):
args = map(repr, self.arguments)
s = "{self.klass}.{self.method!s}(".format(self=self)
l = 100 - len(s)
ar = []
for a in args:
if l - len(a) < 0:
s += ', '.join(ar) + (', ' if ar else '') + '...)'
break
ar.append(a)
else:
s += ', '.join(ar) + ')'
return s
def formatted(self):
complete = "{self.klass}.{self.method!s}({args})".format(**{
'self': self,
'args': ', '.join(map(repr, self.arguments)),
})
# Tidy up python code
res = StringIO()
pytidy.tidy_up(StringIO(complete), res)
code = res.getvalue().split('\n', 2)[-1].strip()
# Highlight code
return highlight(
code,
PythonLexer(),
HtmlFormatter(cssclass="codehilite", style="pastie")
)
def __repr__(self):
return "--> {self.klass}.{self.method!s}({args})".format(**{
'self': self,
'args': ', '.join(map(repr, self.arguments)),
})
class POPResponse(object):
type = 'response'
def __init__(self, klass, method, result, buffer):
self.klass = klass
self.method = method
self.result = result
def formatted(self):
complete = "{self.klass}.{self.method!s}({args})".format(**{
'self': self,
'args': ', '.join(map(repr, self.result)),
})
# Tidy up python code
res = StringIO()
pytidy.tidy_up(StringIO(complete), res)
code = res.getvalue().split('\n', 2)[-1].strip()
# Highlight code
return highlight(
code,
PythonLexer(),
HtmlFormatter(cssclass="codehilite", style="pastie")
)
def toxml(self):
el = etree.Element('response')
el.attrib['classid'] = str(self.klass.id)
el.attrib['class'] = self.klass.name
mth = self.method.toxml()
for t, a in zip(self.method.retypes, self.result):
arg = etree.SubElement(mth, 'ret')
arg.attrib['type'] = t.__name__
arg.text = repr(a)
el.append(mth)
etree.SubElement(el, 'repr').text = repr(self)
etree.SubElement(el, 'short').text = str(self)
etree.SubElement(el, 'highlighted').append(etree.fromstring(self.formatted()))
return el
def __str__(self):
args = map(repr, self.result)
s = "{self.klass}.{self.method!s}(".format(self=self)
l = 100 - len(s)
ar = []
for a in args:
if l - len(a) < 0:
s += ', '.join(ar) + (', ' if ar else '') + '...)'
break
ar.append(a)
else:
s += ', '.join(ar) + ')'
return s
def __repr__(self):
return "<-- {self.klass}.{self.method!s}({res})".format(**{
'self': self,
'res': ', '.join(map(repr, self.result)),
})
class POPException(object):
type = 'exception'
def __init__(self, klass, properties, buffer):
self.klass = klass
self.properties = properties
def toxml(self):
return etree.Element('exception')
def __repr__(self):
return "<-x {self.klass}({properties})".format(**{
'self': self,
'properties': ', '.join(map(repr, self.properties)),
})
<file_sep>.. _command-subsystem:
Custom subcommands
==================
The ``pas`` commands can be grouped into 4 areas of interest:
Meta management
Allows to execute all actions to setup and manage a testing environment and
its configuration.
Jobmgr management
Provides a simple interface to manage remote ``jobmgr`` processes (start,
stop, kill,...).
Measuring
Collection of commands to manage the measuring process, such as starting or
stopping a measure.
Processing
Different tools to act upon al already acquired measure, to transform,
simplify, filter, etc. the different assets resulting from a measuring
process.
A fifth group, the **derived commands** group can also be added and contains
all custom defined workflows resulting from the chaining of different
"primitive" commands. This form of custom command creation was already
described in the :ref:`command composition <composed-commands>` section of the
first chapter.
.. _architecture:
Architecture
------------
The various available commands are gathered at runtime by the ``pas`` binary
(oh, well… actually it is a python script) when executed. The entry point
recursively scans the ``pas.commands`` package to retrieve the various commands.
This mechanism allows for great flexibility in the definition of parsers for
single commands and makes the addition of new commands relatively easy.
The next section will show you how to create a new command by adding it
directly to the ``pas`` package.
A simple example, the ``unreported`` subcommand
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A ``pas`` subcommand is built for each module found in the ``pas.commands``
package. For this operation to succeed, some conventions have to be respected;
suppose we want to add a new command to the pas utility (i.e. a command to list
all collected measures with no report), then we want to proceed as follows:
1. Create a new python module inside the ``pas.commands`` package. Name it as
you want to name your command. As we want our command to be named
``unreported``, we create the ``pas/commands/unreported.py`` file.
**Note:** Filenames starting with underscores are automatically filtered
out.
If you run the ``pas`` utility with the ``unreported`` subcommand, then an
error is reported indicating that you don't have implemented the command
correctly::
$ pas unreported
ERROR: No command found in module pas.commands.unreported
usage: pas [-h] [--version] [-v] [-q] [--settings SETTINGS_MODULE]
{authorize,execute,jobmgr,compile,init,measure} ...
pas: error: invalid choice: 'unreported'
2. To provide an implementation for a command, simply define a callable named
``command`` inside your ``unreported`` module. The callable shall accept
one positional argument (which will be set to the command line options) and
return a non-true value if the command succeeded::
# Inside pas/commands/unreported.py
def command(options):
pass
If you run the command now, it should exit cleanly without any message, but
not much will be done. Let's write a simple implementation::
import os
import glob
from pas.conf import settings
def command(options):
a = '{0}/*'.format(settings.PATHS['shared-measures'][0])
r = '{0}/*/report'.format(settings.PATHS['shared-measures'][0])
all_reports = set(glob.glob(a))
already_reported = set([os.path.dirname(d) for d in glob.glob(r)])
not_reported = all_reports - already_reported
if not not_reported:
print "No unreported measures found ({0} total measures)".format(
len(all_reports))
elif len(not_reported) == 1:
print "One unreported measure found ({0} total measures)".format(
len(all_reports))
else:
print "{0} unreported measures found ({1} total measures)".format(
len(not_reported), len(all_reports))
for i, path in enumerate(not_reported):
print "{0:2d}: {1}".format(i+1, os.path.basename(path))
3. Suppose we want now to allow the newly created subcommand to accept some
optional (or required) flags and arguments; how can we add support for
additional command line parsing to the current implementation?
Fortunately the whole ``pas`` commands subsystem is based around the
`argparse <http://docs.python.org/dev/library/argparse.html>`_ module and
adding options and arguments is straightforward. The ``pas`` command line
parser builder looks if the module containing the command also contains a
callable named ``getparser`` and, if it is the case, it calls it during the
parser construction by passing the subcommand specific subparser instance
to it.
If we want to add a ``--no-list`` flag allowing to turn off the list of unreported
measures (thus only showing the total counts), we can proceed as follows::
import os
import glob
from pas.conf import settings
def getparser(parser):
parser.add_argument('-n', '--no-list', dest='show_list', default=True,
action='store_false')
def command(options):
# [...]
if options.show_list:
for i, path in enumerate(not_reported):
print "{0:2d}: {1}".format(i+1, os.path.basename(path))
Refer to the `argparse`_ documentation for the syntax and the usage of the
module (just remember that the ``parser`` argument of the ``getparser``
function is an ``argparse.ArgumentParser`` instance and the ``options``
argument passed to the command is an ``argparse.Namespace`` instance).
The example illustrated above covers the basics of creating a new subcommand
for the ``pas`` command line utility, but some more techniques allows to
achieve an higher degree of flexibility, namely :ref:`recursive subcommands`
and :ref:`external directory scanning`.
.. _recursive subcommands:
Recursive subcommands
---------------------
As stated in the introduction to the :ref:`architecture` section, the ``pas``
entry point *recursively* scans the ``pas.commands`` package for commands. This
allows to define ``pas`` subcommands which have themselves subcommands.
Take as an example the ``jobmgr`` subcommand. It defines different actions to
be taken upon the different instances, such as ``start``, ``stop`` or ``kill``.
These three actions are defined as subcommands of the ``jobmgr`` subcommand.
To create a similar grouping structure for your commands collection, it
suffices to define your actions as modules inside a package named after the
commands collection name.
To reproduce a structure as the one implemented by the ``jobmgr`` command, the
following directory structure may be set up::
+ pas/
\
+ commands/
\
+ __init__.py
+ command1.py
+ command2.py
|
+ jobmgr/
|\
| + __init__.py
| + start.py
| + stop.py
| + kill.py
|
+ command3.py
Then, you can invoke the ``jobmgr``'s ``start``, ``stop`` and ``kill``
subcommands simply by typing this command::
$ pas jobmgr start
All other conventions (``command`` callable, ``getparser`` callable, argument
types,…) presented in the plain command example still hold for nested commands.
.. _external directory scanning:
External directory scanning
---------------------------
The main weak point of the architecture as it was presented until now is
certainly the fact that for the parser to recognize a new command, the command
itself has to be placed inside the ``pas.commands`` package which, depending on
the installation, is buried deeply somewhere in the file system and is easily
overridden by a reinstallation.
Fortunately, a mechanism has been put in place to allow arbitrary directories
to be scanned for commands: the
:data:`COMMAND_DIRECTORIES <pas.conf.basesettings.COMMAND_DIRECTORIES>`
settings directive contains a list of directories to be scanned for commands
*in addition* to the ``pas.commands`` package.
By adding your custom commands directory to the list you can have them
automatically included in the ``pas`` utility without the need to modify the
``pas`` source tree directly.
This is useful if you want to add some commands tied to a particular testing
environment or – if it is the case – to a particular :term:`measure case`.
.. note::
You can override built-in commands simply by specifying a directory
containing a command with the same name. Note although that **no recursive
merge** is done, thus you can't override a single command of a commands
collection while retaining all other collection subcommands.
.. _utilities:
Command utilities
-----------------
The ``pas.commands`` package provides some useful utilities to facilitate
common tasks when working with command definitions.
The API for these utilities is presented below. For each utility its use case
is described and a usage example is provided. To use them in your custom
commands definition simply import them from the ``pas.commands`` package.
Command decorators
~~~~~~~~~~~~~~~~~~
The following group of utilities can be used as decorators for the ``command``
callable:
.. autofunction:: pas.commands.nosettings
.. autofunction:: pas.commands.select_case
.. autofunction:: pas.commands.select_measure
Argument shortcuts
~~~~~~~~~~~~~~~~~~~
The following group of utilities can be used as factories for common/complex
additional arguments/option to bind to a parser instance for a custom
subcommand:
.. autofunction:: pas.commands.host_option
.. autofunction:: pas.commands.case_argument
.. autofunction:: pas.commands.measure_argument
<file_sep>
execute "generate-key" do
command "(yes y | ssh-keygen -qf /home/vagrant/.ssh/id_rsa -N \"\" -C $(getip eth1))"
creates "/home/vagrant/.ssh/id_rsa"
user "vagrant"
end
<file_sep>"""
Collection of utilities to help with the development of the PAS project.
"""
import os
from fabric.api import local, env, cd
from fabric.context_managers import show, settings
def rcd(path):
"""
relative-cd. Changes to the specified path under the basepath given by this
fabfile filename.
"""
return cd(os.path.join(os.path.dirname(__file__), path))
def sass():
"""
Compiles the sass sources to css files.
"""
with rcd("pas/conf/htdocs/sass"):
local("compass compile", capture=False)
def _get_files():
import pas
ignored = set(('.DS_Store', 'pytidy.py', 'parser'))
files = os.listdir(os.path.dirname(pas.__file__))
files = (f for f in files if not f.endswith(".pyc"))
files = (f for f in files if f not in ignored)
files = (f.replace('.py', '') for f in files)
files = ("pas." + f for f in files)
files = ' '.join(files)
return files
def pylint(modules=None, html=False):
"""
Does a syntax and code-style check on the python code of this project
using pylint.
"""
modules = modules or _get_files()
if html:
local('mkdir -p temp')
format = 'html >temp/pylint.html'
else:
format = 'text'
with settings(show('everything'), warn_only=True):
local("pylint --rcfile=pylint.ini {} --output-format={}".format(
modules, format), capture=False)
if html:
local('open temp/pylint.html')<file_sep>"""
Commands suite to remotely manage jobmgr instances.
"""<file_sep>"""
``pas measure stop``
====================
**Usage:** ``pas jobmgr stop [-h]``
optional arguments:
-h, --help Show this help message and exit.
Stops the measures running on all hosts and for each interface as defined in
the :data:`INTERFACES <pas.conf.basesettings.INTERFACES>` and :data:`ROLES
<pas.conf.basesettings.ROLES>` settings directives.
The measures are stopped by sending the ``quit`` command to each named screen
session which matches the MEASURE_NAME and interface couple.
"""
from pas import commands
from pas import measure
# pylint: disable-msg=C0111
# Disable warning for the missing docstrings, there is not much to document
# here. For further information refer directly to the enclosed called function
# documentation.
def command(options):
"""
Stops the measures running on all hosts and for each interface as defined in
the INTERFACES and ROLES settings directives.
"""
measure.stop('pas')
<file_sep>
class UnknownClass(ValueError):
"""
Raised when an unknown class id is encountered.
"""
def __init__(self, classid):
super(UnknownClass, self).__init__()
self.classid = classid
def __str__(self):
return "Unknown class: {}".format(self.classid)
class UnknownException(UnknownClass):
"""
Raised when an unknown exception id is encountered.
"""
pass
class UnknownMethod(ValueError):
"""
Raised when an unknown method id is encountered.
"""
def __init__(self, klass, methodid):
super(UnknownMethod, self).__init__()
self.klass = klass
self.methodid = methodid
def __str__(self):
return "Unknown method for class {0!s}: {1}".format(self.klass,
self.methodid)<file_sep>Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
Array.prototype.removeEl = function (value) {
return this.remove(this.indexOf(value));
}
var updateConversationLabel = function () {
var all = $('.conversation-filter input').size(),
selected = $('.conversation-filter input:checked').size(),
text;
if (all == selected) {
text = "All conversations";
} else if (selected > 1) {
text = selected + " conversations";
} else if (selected == 1) {
text = "1 conversation";
} else {
text = "No conversations";
}
$('.conversation-filter button').text(text);
};
var filter = function (level) {
switch (level) {
case 3:
$('.transactions').addClass('push-only');
case 2:
$('.syn2, .syn1, .fin1, .fin2').addClass('smart');
case 1:
$('.transactions').addClass('no-ack');
}
$('.conversation-filter input:not(:checked)').each(function () {
$("." + $(this).val()).addClass('hidden');
});
};
var unfilter = function (level) {
$('.conversation-filter input:checked').each(function () {
$("." + $(this).val()).removeClass('hidden');
});
switch (level) {
case 0:
$('.transactions').removeClass('no-ack');
case 1:
$('.syn2, .syn1, .fin1, .fin2').removeClass('smart');
case 2:
$('.transactions').removeClass('push-only');
}
};
var applyFilters = function (level) {
level |= $('.frame-filter-bar li.active').index();
unfilter(level);
filter(level);
};
var updatePorts = function () {
var $tr = $('.transactions'),
l = $tr.parent().scrollLeft();
pos = [];
$('.port.hover', $tr).removeClass('hover');
$($tr.data('active')).each(function (el) {
$('.port:nth-child(' + (this + 2) + ')').addClass('hover');
pos.push(-l + this * 26 + 56 + "px");
pos.push(-l + this * 26 + 56 + "px");
});
$($tr.data('sticky')).each(function (el) {
$('.port:nth-child(' + (this + 2) + ')').addClass('hover');
pos.push(-l + this * 26 + 56 + "px");
pos.push(-l + this * 26 + 56 + "px");
});
$tr.css('background-position-x', pos.join(', '));
};
$(function () {
$('nav > ul:first-child > li > a').click(function (e) {
var nav = $(this).closest('nav');
li = $(this).closest('li');
nav.find('> ul > li').removeClass('active');
nav.find('> ul:nth-child > li:nth-child(' + (li.index() + 1) + ')').addClass('active');
li.addClass('active');
});
$('nav > ul:last-child li a').click(function (e) {
var ul = $(this).closest('ul, ol');
li = $(this).closest('li');
ul.find('> li').removeClass('active');
li.addClass('active');
});
$('.file-browser > ul > li > a').click(function (e) {
e.preventDefault();
$(this).closest('section').find('.active').removeClass('active');
var i = $(this).parent().addClass('active').index();
$(this).closest('section').find('section').removeClass('active').eq(i).addClass('active');
});
$('body > section').spawnHeight(window, $('body > nav'));
$('.flags-filter a').click(function (e) {
e.preventDefault();
applyFilters($(this).parent().index());
});
$('.details-switch a').click(function (e) {
e.preventDefault();
$li = $(this).parent();
switch ($li.index()) {
case 0:
$('.transactions tr.details').removeClass('details');
break;
case 1:
$('.transactions tr:not(.no-payload)').addClass('details');
break;
}
});
$('.bindstatus-filter a').click(function (e) {
e.preventDefault();
var level = $(this).parent().index();
switch (level) {
case 0:
$('.bindstatus-request, .bindstatus-response').removeClass('smart');
case 1:
$('.bindstatus-request, .bindstatus-response').removeClass('bindstatus-hidden');
}
switch (level) {
case 2:
$('.bindstatus-request, .bindstatus-response').addClass('bindstatus-hidden');
case 1:
$('.bindstatus-request, .bindstatus-response').addClass('smart');
}
});
$('.conversation-filter button').click(function (e) {
var c = $('.conversation-filter > div');
if (!c.hasClass('open')) {
// Otherwise the event propagation would fire the body callback
// straight away
e.stopPropagation();
c.addClass('open');
$('body').one('click', function () {
c.removeClass('open');
});
} else {
c.removeClass('open');
}
});
$('.conversation-filter ol').click(function(e){
e.stopPropagation();
});
$('.frame-filter-bar').addClass('active');
$('.frame-filter-bar').find('li.active').removeClass('active').find('a').lockDimensions('width').parent().addClass('active');
$('.frame-filter-bar').find('li:not(.active) a').lockDimensions('width');
$('.frame-filter-bar').removeClass('active');
$('.conversation-filter input').change(function () {
applyFilters();
updateConversationLabel();
});
$('.transactions').data('active', []);
$('.transactions').data('sticky', []);
$('.transactions tbody tr:not(:first-child)').hover(function () {
var from = $('td.before', this).attr('colspan'),
span = $('td.transaction', this).attr('colspan');
if (from === undefined) {
from = 0;
}
$('.transactions').data('active', [from, from + span - 1]);
updatePorts();
}, function () {
$('.transactions').data('active', []);
updatePorts();
}).click(function () {
if (!$(this).hasClass('no-payload')) {
$(this).toggleClass('details');
var s = $('.transactions tbody tr.details').size();
$('.details-switch li.active').removeClass('active');
if (s == 0) {
$('.details-switch li:nth-child(1)').addClass('active');
} else if (s == $('.transactions tbody tr:not(.no-payload)').size()) {
$('.details-switch li:nth-child(2)').addClass('active');
}
}
});
$('.transactions tbody td:last-child .details').click(function (e) {
e.stopPropagation();
})
$('.transactions th.port').hover(function () {
$('.transactions').data('active', [$(this).index()-1]);
updatePorts();
}, function () {
$('.transactions').data('active', []);
updatePorts();
}).click(function (e) {
var $this = $(this),
index = $this.index() - 1;
$tr = $('.transactions');
if (e.metaKey || e.altKey) {
// Show only this actor
if ($this.hasClass('this-only')) {
$this.closest('table').find('.actor-only').removeClass('actor-only');
$this.removeClass('this-only');
return;
}
$this.parent().find('.this-only').removeClass('this-only');
$this.addClass('this-only');
$this.closest('table').find('tbody tr:not(:first-child)').each(function () {
var $row = $(this),
$before = $row.find('td.before'),
$transaction = $row.find('td.transaction'),
$after = $row.find('td.after'),
convs = $('thead th.port').size(),
from, to;
if ($before.size() == 0) {
from = 0;
} else {
from = $before.attr('colspan');
}
if ($after.size() == 0) {
to = convs - 1;
} else {
to = convs - 1 - $after.attr('colspan');
}
if (from == index || to == index) {
if (e.metaKey) {
$row.removeClass('actor-only');
} else if (e.altKey) {
$row.addClass('actor-only');
}
} else {
if (e.metaKey) {
$row.addClass('actor-only');
} else if (e.altKey) {
$row.removeClass('actor-only');
}
}
});
return;
}
if ($this.hasClass('active')) {
$this.removeClass('active');
$tr.data('sticky').removeEl(index);
} else {
$this.addClass('active');
$tr.data('sticky').push(index);
}
/*convs = [];
tohide = [];
for (i=$('thead th.port').size(); i > 0; i--) {
convs.push(0);
}
$this.closest('table').find('tbody tr:not(:first-child):visible').each(function () {
var $row = $(this),
$before = $row.find('td.before'),
$transaction = $row.find('td.transaction'),
$after = $row.find('td.after');
if ($before.size() == 0) {
convs[0] = 1;
} else {
convs[$before.attr('colspan')] = 1;
}
if ($after.size() == 0) {
convs[convs.length - 1] = 1;
} else {
convs[convs.length - 1 - $after.attr('colspan')] = 1;
}
});
$.each(convs, function (i, n) {
if (!n) {
tohide.push(i);
}
});
console.log(tohide, convs);*/
updatePorts();
});
$('#diagram').scroll(function (e) {
$('thead', this).css('left', - $(this).scrollLeft() + 'px');
updatePorts();
});
// Activate current tab
document.location.hash = document.location.hash || '#diagram';
$('nav > ul:first-child > li > a[href=' + document.location.hash + ']').click();
// Activate first file
$('.file-browser > ul > li:first-child > a').click()
});
<file_sep>.. _usage:
Usage documentation
===================
.. toctree::
quick-start
execution-model
measure-cases
configuration
composing-commands
report
<file_sep>"""
``pas measure start``
=====================
**Usage:** ``pas jobmgr start [-h]``
optional arguments:
-h, --help Show this help message and exit.
Starts a new measure on all hosts and for each interface as defined in the
:data:`INTERFACES <pas.conf.basesettings.INTERFACES>` and :data:`ROLES
<pas.conf.basesettings.ROLES>` settings directives.
The measure is started in a detached named screen session to be able to
disconnect from the remote host while letting the measure run. The same name
can then also be used to cleanly stop or to kill the measure.
All existing measure files in the remote measure desintation directory will be
erased without asking for confirmations! Make sure to have collected all
previously run measures you don't want to lose.
Note that it is not possible to run parallel measures (and it doesn't make much
sens, as both tshark process will capture all the traffic).
"""
from pas import measure
# pylint: disable-msg=C0111
# Disable warning for the missing docstrings, there is not much to document
# here. For further information refer directly to the enclosed called function
# documentation.
def command(options):
"""
Starts a new measure on all hosts as defined in the settings INTERFACES and
ROLES directives.
"""
measure.start('pas')
<file_sep>#include "simple.ph"
POPCobject::POPCobject() {
count = 0;
}
POPCobject::~POPCobject() {}
int POPCobject::get() {
return count++;
}
@pack(POPCobject);
<file_sep>.. highlight:: bash
.. _quick-start:
Quick start
===========
The steps contained in this short guide should get you up and running in as few
steps as possible. For a full featured environment and for an in-dept
description of all the functionalities of the ``pas`` packages, refer to the
full documentation.
The following instructions assume that you have already installed the ``pas``
packages along with all its dependencies, if this is not the case, refer to the
:ref:`installation` instructions.
You don't need to understand completely what's going on in the following steps,
but the :ref:`execution-model` and the
:ref:`commands-reference` are a great resource to help you to grasp the details.
Step 1: Setup the test environment
----------------------------------
To run a measure, a test environment has to be setup. Fortunately this can
easily be done using the ``init`` command.
The init command tries to create a new environment in the current directory or
using the path provided on the command line and will only succeed if it is
empty. Use it in the following way::
$ pas init <path-to-the-env>
Attempting to create a new environment in '<path-to-the-env>'...
Done.
If the command executed successfully, a newly created directory will be present
at the path you specified. Let's take a look at its content::
$ ls -l <path-to-the-env>
total 8
-rw-r--r-- 1 garetjax staff 878 Jan 25 14:52 Vagrantfile
drwxr-xr-x 4 garetjax staff 136 Jan 3 21:30 cases
drwxr-xr-x 6 garetjax staff 204 Jan 4 00:00 conf
drwxr-xr-x 4 garetjax staff 136 Jan 12 21:51 contrib
drwxr-xr-x 2 garetjax staff 68 Jan 3 14:29 reports
-rw-r--r-- 1 garetjax staff 0 Jan 25 14:52 settings.py
The entries in the listing have the following roles:
* ``Vagrantfile``: Configuration file for the vagrant based virtual machine
setup; already configured for a minimal master-slave setup.
* ``cases``: Directory holding all measure cases which can be run in this
environment. A ``simple`` test case is provided as an example.
* ``conf``: Directory containing all environment specific configurations.
Especially noteworthy is the ``chef`` subdirectory which holds the full VM
configuration scripts. Also contained in this directory are the ``xsl``
templates used for the measure simplification and report generation and a
base ``Makefile`` to facilitate the creation of measure cases.
* ``contrib``: Contributed assets and sources to be used inside the
environment. Already contained in this directory is a patched pop-c++
version to avoid raw encoded communications.
* ``reports``: The destination of all measure results along with the resulting
reports.
* ``settings.py``: An environment specific configuration file to allow to
override the default settings directives.
.. note::
For the remaining part of this quick-start we will assume that your current
working directory corresponds to the environment root. If this is not yet
the case, please ``cd <path-to-the-env>``.
Step 2: Setup the virtual machines
----------------------------------
Once the testing environment is created, the virtual machines on which the
measures will be run have to be created, booted and configured. Fortunately
this task is made simple by the ``vagrant`` tool::
$ vagrant up
When you execute this command for the first time, the preconfigured virtual
machine box will be downloaded from the internet; in this case the following
text will be printed during the execution::
[master] Provisioning enabled with Vagrant::Provisioners::ChefSolo...
[master] Box lucid32 was not found. Fetching box from specified URL...
[master] Downloading with Vagrant::Downloaders::HTTP...
[master] Copying box to temporary location...
Progress: 1% (5288808 / 502810112)
Vagrant is now probably downloading the virtual machine box to your system.
This process and the provisioning process described below take a neat amount of
time so it could be a good time to take a coffee break.
Once a machine is downloaded and booted, vagrant begins the "provisioning
process", which simply means to copy the required chef recipes and resources
to the VM and to execute the set of defined actions to configure the host.
Once the complete process is finished, you have two running headless virtual
machines ready to execute pop-c services and objects.
.. note::
You can play with the virtual machines through ``ssh``. To connect simply
issue::
$ vagrant ssh master # s/master/slave/ if you want to connect to the slave instead
Step 3: Run the measure
-----------------------
In this quick-start we will run the base example bundled with the newly created
environment. Refer to the :ref:`measure-cases` document to get help on how to
create and personalize a new measure case.
The first thing to do when a new measure case is added to the library is to
compile it on each virtual machine. To do so, issue the following command::
$ pas compile
If there is more than one possibility, the ``compile`` subcommand asks you to
choose the measure to compile or, alternatively, you can provide the name of
the measure on the command line directly.
When ran, the ``compile`` subcommand, automatically calls the ``build`` ``make``
target on each known host and makes sure to add the needed informations to a
global ``obj.map`` file.
Once the sources are compiled, we are ready to run our measure. Measuring is
done through one or more ``tshark`` instances per host. ``pas`` provides
commands to start and stop ``tshark`` based measures on all or on selected
hosts/interfaces::
$ pas measure start
Only one test case found: simple.
[33.33.33.10] sudo: rm -rf /measures ; mkdir /measures
[33.33.33.10] sudo: screen -dmS simple.lo.lo tshark -i lo -t e -w ...
[33.33.33.10] sudo: screen -dmS simple.eth1.eth1 tshark -i eth1 -t e ...
[33.33.33.11] sudo: rm -rf /measures ; mkdir /measures
[33.33.33.11] sudo: screen -dmS simple.lo.lo tshark -i lo -t e -w ...
The ``pas measure start`` subcommand cleans up the measure destination
directory on the target-host and starts a detached named screen session to wrap
the ``tshark`` process. This allows to let measures live between different
connections and to terminate them by name.
Now that the measure daemon is running, we can start the ``jobmgr`` and the
actual measure case.
.. note::
If the initialization done by the ``jobmgr`` processes is not relevant for
the measure, it is of course possible to start the job managers before
starting the measure.
To start all job managers on all hosts -- and with some automatically provided
grace period -- issue the following command::
$ pas jobmgr start
Finally we can also start the previously compiled pop binary and measure the
different established connections::
$ pas execute
Once been through these different steps and having waited for the measured
program to terminated, the ``jobmgr``'s can be shut down and the measure
terminated. In short, this comes back to the following two commands::
$ pas jobmgr stop ; pas measure stop
Congratulations, you just measured your first pop program using the POP
Analysis Suite, but the work is not over yet; all of the assets resulting from
the measure process are still dispersed all over your virtual machines. Head up
to the next section to learn how to assemble all the files into a readable
report.
Step 4: Generate the report
---------------------------
As anticipated above, all of the measures are still scattered over the
different virtual machines. The first step which has to be done to generate a
report is to collect them in a unique place::
$ pas measure collect test_measure
This command has the effect to gather all different measure files and place
them in an appropriate tree structure inside the ``report`` directory. The
different measures are first grouped by measure case + collection timestamp and
then by the IP of the originating virtual machine.
Once all files are collected, we can begin to process them::
$ pas report toxml # Converts all measures to xml documents.
$ pas report simplify # Simplifes the xml document by stripping
# unnecessary informations.
$ pas report decode # Annotates the xml documents with the decoded
# POP Protocol payload.
The execution of these commands (the execution order is relevant) produces 3
new files for each ``<measure>.raw`` file:
* A ``<measure>.xml`` file, containing the XML representation of the measure
as returned by the ``tashark`` conversion command.
* A ``<measure>.simple.xml`` file, containing the simplification of the
previously converted measure. Only relevant data is preserved.
* A ``<measure>.decoded.xml`` file, containing the same data of the simple XML
version annotated with the decoded POP Protocol payload.
The final step allows to generated an HTML document containing the visual
representation of the full measure and some additional information. To launch
it run::
$ pas report report
To display the generated report in your browser, simply open one of the
``html`` file files found in the ``reports/<measure-name>_<timestamp>/report``
directory.
Wow, this was the final step! Sounds like a complicated and tedious process but
as you will see by reading the rest of the documentation, much of all this can
be automated, allowing to produce a complete report with a single command;
hand over to the guide on :ref:`composed commands <composed-commands>` to find
out how.
<file_sep>"""
``pas measure collect``
=======================
**Usage:** ``pas measure collect [-h] MEASURE_NAME``
positional arguments:
.. cmdoption:: MEASURE_NAME
The name to give to the collected measure.
optional arguments:
-h, --help Show this help message and exit.
Collects the results of a measure by copying the remote files resulting from
the last run measure to the local measures folder and by organizing them by
host ip address.
In addition to the measures, the log files specified by the :data:`LOG_FILES
<pas.conf.basesettings.LOG_FILES>` settings directive are also copied.
This process does not alter the remote files, it is thus possible to repeat a
``collect`` command different times until a new measure is not started.
"""
from pas import measure
# pylint: disable-msg=C0111
# Disable warning for the missing docstrings, there is not much to document
# here. For further information refer directly to the enclosed called function
# documentation.
def getparser(parser):
parser.add_argument('name', metavar='MEASURE_NAME', help="The name to " \
"give to the collected measure.")
def command(options):
measure.collect(options.name)
<file_sep>.. _glossary:
Glossary
========
.. glossary::
:sorted:
VM
VMs
The abbreviation for *virtual machine* and its plural form, respectively.
PAS
pas
The abbreviation of *POP Analysis Suite*.
virtual machine box
A virtual machine box is a package containing a disk image with a
preconfigured operating system on it. It can either already be present on
the host system or automatically downloads from the internet when needed.
CWD
The abbreviation for *current working directory*.
DSL
The abbreviation for *Domain Specific Language*.
POP
POP model
The abbreviation of *Parallel Object Programming* model.
composer
composers
A function which allows to create complex or composite types using the
:ref:`ppd-reference` syntax.
complex type
complex types
composite type
composite type
compound type
compound types
Special data types for the POP Parsing DSL which are made up of different
scalar or complex types.
measure case
measure cases
A template for a measure. Contains source code, building instructions,
measure workflow and optional commands to run and report the results of
the measure case.
:term:`test case` may be used as a synonym.
test case
test cases
A synonym for :term:`measure case`
testing environment
A directory structure as set up by running the ``pas init`` command
containing all the needed assets to run :term:`measure cases` and report
results.
A testing environment normally contains a set of custom virtual machines,
some related :term:`measure cases`, environment specific settings and the
results of the different :term:`measures`.
role
The role of a remote machine as seen by ``pas``. The default configuration
defines and leverages the usage of a ``client`` role to run the POP
application, a ``master`` role where the master ``jobmgr`` instance is run
on and a ``slave`` role on which the slave ``jobmgr`` instances are run on.
measure
measures
The results of a measure case which has been run.
<file_sep>"""
Commands suite process collected measure results.
"""<file_sep>name "master"
description "Set up the JobMgr for a master POPC node"
run_list(
"recipe[popc]",
"recipe[hosts::getip]",
"recipe[wireshark::tshark]",
"recipe[screen]",
"recipe[ssh::key]"
)
default_attributes :popc => {:config => "master"}
<file_sep>"""
``pas measure kill``
====================
**Usage:** ``pas measure kill [-h] [HOST [HOST ...]]``
positional arguments:
.. cmdoption:: HOST
Use this option to specify one or more hosts on which this command has to
be run.
optional arguments:
-h, --help Show this help message and exit.
Kills all the running measures on the given host (or on all hosts if no host
is given) independently from the capturing interface or the name with which
they were started.
"""
from pas import commands
from pas import tshark
from pas import shell
# pylint: disable-msg=C0111
# Disable warning for the missing docstrings, there is not much to document
# here. For further information refer directly to the enclosed called function
# documentation.
def getparser(parser):
commands.host_option(parser, argument=True)
def command(options):
"""
Kills all the running measures on the given host (or on all hosts if no host
is given) independently from the capturing interface or the name with which
they were started.
"""
with shell.workon(options.hosts):
tshark.kill()
<file_sep>Vagrant::Config.run do |config|
config.vm.box = "lucid32_test"
config.vm.box_url = "http://files.vagrantup.com/lucid32.box"
config.vm.share_folder("test-cases", "/share/test-cases", "./cases")
config.vm.share_folder("contrib", "/share/contrib", "./contrib")
config.vm.share_folder("reports", "/share/measures", "./reports")
config.vm.share_folder("conf", "/share/conf", "./conf")
config.vm.define :master1 do |master_config|
master_config.vm.network "33.33.33.10"
master_config.vm.provision :chef_solo do |chef|
chef.cookbooks_path = "conf/chef/cookbooks"
chef.roles_path = "conf/chef/roles"
chef.add_role "master"
chef.json.merge!({
:popc => {
:version => "popc_1.3.1beta_xdr",
}
})
end
end
config.vm.define :slave1 do |slave1_config|
slave1_config.vm.network "33.33.33.11"
slave1_config.vm.provision :chef_solo do |chef|
chef.cookbooks_path = "conf/chef/cookbooks"
chef.roles_path = "conf/chef/roles"
chef.add_role "slave"
chef.json.merge!({
:popc => {
:version => "popc_1.3.1beta_xdr",
}
})
end
end
end
<file_sep>"""
.. _pas-compile:
``pas compile``
===============
**Usage:** ``pas compile [-h] [--host HOST] [MEASURE_CASE]``
positional arguments:
.. cmdoption:: MEASURE_CASE
Measure case to compile on the different hosts.
optional arguments:
-h, --help Show this help message and exit.
--host HOST Use this option to specify one or more hosts on which this
command has to be run. The --host option can be specifed
multiple times to define multiple hosts.
Compiles the given test case on all hosts (by default) or on the hosts
provided on the command line through the ``--host`` option.
If no measure case is provided and only one is available, it is compiled; if
more are available, the user is presented with a list of available cases and
asked to make a choice.
"""
from pas import case
from pas import commands
# pylint: disable-msg=C0111
# Disable warning for the missing docstrings, there is not much to document
# here. For further information refer directly to the enclosed called function
# documentation.
def getparser(parser):
commands.host_option(parser)
commands.case_argument(parser)
@commands.select_case
def command(options):
"""
Compiles the given test case on all hosts (by default) or on the hosts
provided on the command line through the --host option.
"""
case.compile(options.case[1])
<file_sep>"""
``pas run``
===========
**Usage:** ``pas run [-h] [MEASURE_CASE] [TARGET [TARGET ...]]``
positional arguments:
.. cmdoption:: MEASURE_CASE
The name of the measure case of which run the ``Makefile``.
.. cmdoption:: TARGET
The target to execute, defaults to the default ``Makefile`` target.
optional arguments:
-h, --help Show this help message and exit.
Locally runs the given targets of the ``Makefile`` of the given measure case.
This command is useful to create custom commands by simply combining multiple
togheter. Refer to the :ref:`composing commands <composed-commands>` section
for more informations about this argument.
"""
import os
from pas import shell
from pas import commands
from pas.conf import settings
def getparser(parser):
commands.case_argument(parser)
parser.add_argument('targets', metavar='TARGET', nargs='*', help="The target to " \
"execute, defaults to 'run'.", default=[])
@commands.select_case
def command(options):
"""
Exchanges the public keys between all VMs to allow direct ssh connections
between them without user input.
"""
local, _ = settings.PATHS['test-cases']
shell.local("ENV_BASE='{2}' EXEC={0[1]} make -e -f {0[0]}/Makefile " \
"{1}".format(options.case, " ".join(options.targets), settings.ENV_BASE))
<file_sep>#!/bin/bash
ifconfig $1 | grep -E -o 'inet addr:[0-9.]{7,15}' | awk -F ':' '{print $2}'
<file_sep>.. _configuration:
Configuration
=============
The ``pas`` command line tool can be configured to customize its behavior to
better suit the user's needs. To achieve this, it reads configuration settings
from two distinct python modules:
1. The first loaded module (which is always loaded) is the
:mod:`pas.conf.basesettings` module; it contains all default settings as
documented in the :ref:`settings reference`.
2. Additionally, if a local settings module is found (either in the ``CWD`` or
provided by the :ref:`--settings option <settings options>`), it is loaded
too and overrides the values defined by the previous import.
Using this simple mechanism, it is possible to override the default settings
on a per-environment basis and to provide your own directives if needed by
any custom command.<file_sep>package "libsaxon-java"<file_sep>Running ``pas`` with real machines
==================================
The ``pas`` tool was originally conceived to be run on a especially configured
VM setup, but it is enough flexible to be able to work on any machine if some
requirements are satisfied.
This section deals with the different assumptions the ``pas`` tool makes about
the guest machine and described how a real machine has to be set up in order
to be compatible with ``pas``.
Authentication
--------------
All communication between ``pas`` and the remote host happens through ``ssh``.
As the VMs are especially created for the measures, they don't have strict
security requirements and so password based authentication is used to connect
to them.
Furthermore ``pas`` assumes that all remote machines share the same username
and password.
To configure a real machine to be able to authenticate the ``pas`` tool, two
ways are possible:
a. Configure the local host and the remote machine in order to authenticate
themselves without user interaction (this is often done by using
``publickey`` authentication, but other, less secure, methods exist).
The ``ssh`` transport layer will always try ``publickey`` authentication
first thus different keys can be exchanged between different hosts and a
good security level can be achieved.
b. Create a user for ``pas`` on each machine giving it the same username and
password and set the :data:`VM_USER <pas.conf.basesettings.VM_USER>` and
the :data:`VM_PASSWORD <pas.conf.basesettings.VM_PASSWORD>` directives
accordingly.
Furthermore, ``pas`` requires ``sudo`` permissions to execute certain commands.
On the default VM configurations, it does not need any password to execute
commands as root and the real machines have to be configured to behave the same
way.
The commands for which ``pas`` requires ``sudo`` privileges are to start, stop
and kill the ``jobmgr`` and ``tshark`` processes and to copy and delete the
files created by these.
Dependencies
------------
When using the default VMs, vagrant automatically sets them up to conform to
the ``pas`` requirements. You can directly use the chef configuration bundled
with each environment or manually set up your machines to conform to these
requirements.
The following packages are required by ``pas``:
* A ``popc`` installation, configured in accordance with the role assigned to
the machine.
* The ``tshark`` executable, often provided by the system package manager.
* The ``screen`` executable, often provided by the system package manager, if
not already installed.
* A ``getip`` shell script available on the path which prints the IP address
of the interface given as its only argument.
Shared folders
--------------
Vagrant allows to easily set up shared folders between the host and one or more
guest operating systems. ``pas`` builds upon this feature to be able to
distribute the source code and recover the measure results.
The following folders on the remote hosts have to be shared with the local
host:
* ``/share/test-cases`` on the remote host has to be mapped to the ``cases``
directory of the test environment.
* ``/share/measures`` on the remote host has to be mapped to the ``reports``
directory of the test environment.
* ``/share/conf`` on the remote host has to be mapped to the ``conf``
directory of the test environment.
.. note::
These paths can be configured using the :data:`PATHS
<pas.conf.basesettings.PATHS>` setting directive.
This means that you can adjust these paths to your liking as long as there
are three shared folders between the systems and that the settings file is
configured accordingly.
.. note::
If sharing folders is not an option, you can always build custom subcommands
to override the commands which need shared folders and do the file transfers
over ssh using ``scp`` or with ``rsync``.
<file_sep>Report view
===========
The generated HTML report view presents three different tabs: a *diagram* tab,
a *measure logs* tab and a *source code* tab. For the purpose of this guide,
we will concentrate ourselves on the main tab, the *diagram* tab.
The diagram tab can be split up in 6 logical regions: tabs, filters, actors,
conversations, transactions and details. With the exception of the tab bar, the
other 5 regions are described in detail in the following subsections.
Filters
-------
.. figure:: /assets/region-filters.*
:align: center
:figclass: align-left
:width: 200pt
Diagram view with the *filters* region highlighted.
The filter bar allows to trigger different visualization modes of the different
transactions, by including or excluding one or more transactions based on some
criteria or by rendering a logical group of transactions differently.
The available filters and renderers are:
Display mode
Triggers the visualization of transactions based on their TCP flags.
Possible values are *all* to display all transactions, *hide ACK-only* to
show all transactions but they with only the ``ACK`` flag set,
*smart SYN/FIN* to group transactions belonging to the same three way
handshake (or the same ``FIN`` sequence) into one and rendering it
appropriately or *PSH only* to display only transactions containing actual
POP method calls or responses.
Conversations filter
A simple filter allowing to select or deselect visible conversations.
BindStatus display mode
Triggers the visualization of ``BindStatus`` calls and responses. Possible
values are *normal* to display them as normal transactions, *smart* to group
them into a single transaction and render it appropriately or *hide* to
completely hide any ``BindStatus`` related transaction.
Hide/show all details
A simple switch to either hide all transaction details or to show them all.
Actors
------
.. figure:: /assets/region-actors.*
:align: center
:figclass: align-left
:width: 200pt
Diagram view with the *actors* region highlighted.
The actors region displays the different IP addresses and ports bound to each
conversation. When hovering a transaction, the two peers are automatically
highlighted.
This highlight mode can be fixed by clicking on a node and reset by clicking a
second time.
Additionally it is possible to hide or show all conversations from/to a given
actor or by clicking on it by keeping the ``alt`` or, respectively, the
``meta`` key respectively pressed.
Conversations
-------------
.. figure:: /assets/region-conversations.*
:align: center
:figclass: align-left
:width: 200pt
Diagram view with the *conversations* region highlighted.
The conversations region simply indicates for each transaction to which
conversation it belongs to. A conversation is simply the set of all
transactions which where transmitted on the same TCP connection.
The conversations are numbered, starting at zero, from the oldest to the
youngest and their number corresponds to the number displayed in the
*Conversations filter* too.
Transactions
------------
.. figure:: /assets/region-transactions.*
:align: center
:figclass: align-left
:width: 200pt
Diagram view with the *transactions* region highlighted.
This region displays from which actor to which actor a transaction happened
and, if the respective smart display filters are active, renders SYN/FIN and
BindStatus requests accordingly.
When overing a transaction, its bounds are automatically highlights in the same
way as it was for the actors above.
Details
-------
.. figure:: /assets/region-details.*
:align: center
:figclass: align-left
:width: 200pt
Diagram view with the *details* region highlighted.
This region is the most interesting and informational of the entire report.
It provides details such as TCP flags, POP invocation semantics, transaction
type, called object and method, passed arguments,... simply click on the
corresponding row to expand it and show all details of the transaction.
An example of expanded transaction details is displayed in the figure below;
the different parts composing it are explained in deeper detail after the
screenshot.
.. figure:: /assets/transaction-details.*
:align: center
:figclass: align-left clear
Expanded details region for a single transaction.
Starting at the top-left corner, we are presented with the TCP flags which were
set for this transaction; possible values are ``ACK``, ``SYN``, ``PSH`` and
``FIN``.
Just after them, on the right, the transaction type; possible values are ``→``
for a method call, ``<-`` for a reply and ``×`` for an exception.
The next flags group, in green, represents the POP call semantics; possible
values for them are the well known ``SYNC``, ``ASYNC``, ``CONC``, ``SEQ``,
``MTX`` (for mutex) and ``CONSTRUCT`` (for constructor calls).
The rest of the line is dedicated to a short representation of the method call,
including class name, method name and the arguments if they are not too long
to be represented.
On the following line, inside the *decoded frame* field, the full decoded and
highlighted request is represented.
The original payload shows the hex encoded original content of the payload as
it was captured by ``tshark``.
The last line only remembers, in a textual way, the two involved actors with
the respective IP addresses and port numbers.
Other tabs
----------
Other two tabs are available in the tab bar, and although not providing as much
information as the diagram view, they can provide some useful insight in the
measure constructions, especially for a third party person watching at the
report for the first time.
Both views are file browsers but for two different file type groups:
Logs view
This view groups all collected log files relative to this specific measure
and presents them in a simple to use file browser with no additional
syntax highlighting.
Source code view
This view groups all source code files found in the original measure case
folder and provides syntax highlighting for the different file types such as
makefiles, POP-C++ headers, C++ source code,...
<file_sep>#name "analyzer"
#description "Set up all tools needed to analyze the measure results"
#run_list(
## "recipe[popc::master]"
#)<file_sep>[console_scripts]
pas = pas.bin.pas:main
<file_sep>"""
Various utilities to deal with remote tshark operations with support for
features such as background execution, stop on request, and advanced tshark
interactions.
Note that all of the commands which operate on remote hosts, respect the
current set context to retrieve the host lists. When this list is not set or
is empty, the command will be run on all hosts. Refer to the documentation on
pas.shell to obtain further information.
Most of the command below use the tshark command-line tool directly; refer to
its man page for the details about the usage.
"""
from pas import shell
def start(name, iface="lo", outfile="-", capture_filter=""):
"""
Starts a new tshark capture in background using a named screen session.
The name of the spawned screen session will be the provided name joined
with the interface by a dot.
"""
# tshark command, see `man tshark` for further information about the
# capture_filter syntax
tshark = 'tshark -i {iface} -t e -w {outfile} {filter}'.format(
iface=iface,
outfile=outfile,
filter=capture_filter
)
# Execute the tshark command inside a named screen session to allow
# execution in background and selective termination
screen = 'screen -dmS {name}.{iface} {command}'.format(
name=name,
iface=iface,
command=tshark
)
shell.remote(screen, sudo=True)
def stop(name, interface):
"""
Stops the named tshark capture session on the given interface.
The final name passed to the screen command will be the name joined with
the interface by a dot.
"""
shell.remote('screen -X -S {0}.{1} quit'.format(name, interface), sudo=True)
def kill():
"""
Kills ALL running measures on the hosts provided by the context or
(by default) on all known hosts.
"""
with shell.ignore_warnings():
shell.remote('pkill "tshark"', sudo=True)
def pcaptoxml(infile, outfile, display_filter=""):
"""
Converts the pcap input file to XML and writes the output to outfile while
filtering using the given display filter.
Refer directly to the tshark man page for further informations about the
display filter syntax.
"""
shell.remote('tshark -T pdml -r {infile} -t e {filter} >{outfile}'.format(
infile=infile,
outfile=outfile,
filter=display_filter
))
<file_sep>"""
``pas report report``
=====================
**Usage:** ``pas report report [-h] [MEASURE]``
positional arguments:
.. cmdoption:: MEASURE
The name of the collected measure for which to generate a report.
optional arguments:
-h, --help Show this help message and exit.
Generates an HTML report for each already collected, converted, simplified and
decoded measure files of the measure named ``MEASURE``.
"""
from pas import commands
from pas import measure
# pylint: disable-msg=C0111
# Disable warning for the missing docstrings, there is not much to document
# here. For further information refer directly to the enclosed called function
# documentation.
def getparser(parser):
commands.measure_argument(parser)
commands.case_argument(parser)
@commands.select_measure
@commands.select_case
def command(options):
"""
Generates an HTML report for the already collected, converted, simplified
and decoded measure named MEASURE.
"""
measure.report(options.measure[1], options.case[0])
<file_sep>"""
``pas init``
===============
**Usage:** ``pas init [-h] [DIR]``
positional arguments:
.. cmdoption:: DIR
The directory inside which the environment shall be created.
optional arguments:
-h, --help show this help message and exit
Sets up a new measurement and analysis environment in the selected directory
(or in the CWD if none is provided).
The directory has to be empty or inexistent. The command will fail if the
directory already exists and is non-empty.
The environment is mainly set up by recursively copying all the files inside
pas.conf.suite_template to the newly created directory.
"""
import os
import logging
from pas import env
from pas import commands
# pylint: disable-msg=C0111
# Disable warning for the missing docstrings, there is not much to document
# here. For further information refer directly to the enclosed called function
# documentation.
def getparser(parser):
parser.add_argument('dir', metavar="DIR", nargs='?', default='.', type=str,
help='The directory inside which the environment ' \
'shall be created')
@commands.nosettings
def command(options):
"""
Sets up a new measurement and analysis environment in the selected directory
(or in the CWD if none is provided).
"""
log = logging.getLogger('pas.commands')
dest = os.path.realpath(options.dir)
log.info("Attempting to create a new environment in '%s'...", dest)
if os.path.exists(dest):
# If the path already exists, make sure it is a directory and it is
# empty.
if not os.path.isdir(dest):
log.critical("The selected path is not a directory.")
return 1
if os.listdir(dest):
log.critical("The selected directory is not empty.")
return 1
else:
# Create the directory
try:
os.mkdir(dest)
except OSError as e:
log.critical("An error occurred while creating the directory to" \
" host the environment (%s: %s).", e.errno, e.strerror)
return 1
env.setup(dest)
log.info("Done.")
<file_sep>
import os, itertools
from setuptools import setup, find_packages
version = '0.1'
def read(fname):
"""
Utility function to read the README file.
"""
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def get_files(base):
"""
Utility function to list all files in a data directory.
"""
base = os.path.join(os.path.dirname(__file__), *base.split('.'))
rem = len(os.path.dirname(base)) + 1
for root, dirs, files in os.walk(base):
for name in files:
yield os.path.join(root, name)[rem:]
setup(
name='pas',
version=version,
description="POP Analysis Suite",
long_description=read('README.md'),
classifiers=[
'Development Status :: 4 - Beta',
],
keywords='',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/GaretJax/pop-analysis-suite',
license='MIT',
packages=find_packages(exclude=['tests']),
package_data = {
'pas.conf':
list(get_files('pas.conf.suite_template')) +
list(get_files('pas.conf.htdocs')) +
list(get_files('pas.conf.templates'))
},
install_requires=[
'fabric',
'lxml',
'pygments',
'argparse',
],
entry_points=read('entry_points.ini')
)
<file_sep>"""
``pas report toxml``
====================
**Usage:** ``pas report toxml [-h] [MEASURE]``
positional arguments:
.. cmdoption:: MEASURE
The name of the collected measure to convert to xml.
optional arguments:
-h, --help Show this help message and exit.
Converts the results of an already collected measure from the libpcap format to
the corresponding XML format using the ``tshark`` command line utility.
If ``MEASURE`` is not provided, the user is presented with a list of already
collected measures and asked to make a choice.
"""
from pas import commands
from pas import measure
# pylint: disable-msg=C0111
# Disable warning for the missing docstrings, there is not much to document
# here. For further information refer directly to the enclosed called function
# documentation.
def getparser(parser):
commands.measure_argument(parser)
@commands.select_measure
def command(options):
"""
Converts the results of an already collected measure from the libpcap
format to the corresponding XML format using tshark.
"""
measure.toxml(options.measure[1])
<file_sep>"""
Commands suite to execute measures and collect results.
"""<file_sep>"""
Collection of utilities to deal with the management of the different test
cases of the suite.
"""
import os
from pas import shell
from pas.conf import settings
from pas.conf import all_hosts
from pas.conf import role
def select(name=None, basedir=None):
"""
Scans the basedir (or the test-cases directory defined in the settings)
for directories and returns a choice based on different criteria:
1. No directories are found; raise a RuntimeError
2. The name is set; check if it was found and if so return it
3. Only one directory is found; return the found directory
4. Multiple directories are found; ask the user to pick one
a. If no measure case exist yet, a ``RuntimeError`` is thrown;
b. If only one measure case is found, its path is returned;
c. If more than one measure cases are found, then the user is asked to
choose one between them.
The list presented to the user when asked to choose a case will be
something like the following::
Multiple test cases found:
[0]: simple
[1]: complex
Select a test case: _
"""
if not basedir:
basedir = os.path.join(settings.ENV_BASE,
settings.PATHS['test-cases'][0])
# Get all files in the directory
paths = os.listdir(basedir)
# Rebuild the full path name
paths = [(os.path.join(basedir, p), p) for p in paths]
# Filter out non-directories
paths = [p for p in paths if os.path.isdir(p[0])]
# If no entries remained, there are no test cases which can be run
if not paths:
raise RuntimeError("No test cases found.")
# Check to see if chosen value exists in the available paths
if name:
for path in paths:
if path[1] == name:
return path
else:
# Continue with selecting phase
# @TODO: log
print "The chosen path is not available."
# There is not much to choose here
if len(paths) == 1:
# @TODO: log
print "\nOnly one test case found: {0}.".format(paths[0][1])
return paths[0]
# Present a list of choices to the user (paths must now contain more than
# one item)
print "\nMultiple test cases found:\n"
for i, (path, name) in enumerate(paths):
index = '[{0}]'.format(i)
print '{0:>8s}: {1}'.format(index, name)
def valid(index):
"""
Returns the correct entry in the paths list or asks for a correct
value if the index is outside the boundaries.
"""
try:
return paths[int(index)]
except (IndexError, ValueError):
raise Exception("Enter an integer between 0 " \
"and {0}.".format(len(paths)-1))
print
return shell.prompt("Select a test case:", validate=valid)
# pylint: disable-msg=W0622
# Disable warnings for the overriding of the built in compile function.
# Who is using it, anyway...
def compile(name, localdir=None, remotedir=None):
"""
Compiles the given test case on all the hosts in the system.
The building details and the respect of the convention are enforced by the
Makefile and not further explained here.
"""
# Read the defaults from the settings if the arguments are not provided
if not localdir or not remotedir:
paths = settings.PATHS['test-cases']
if not localdir:
localdir = paths[0]
if not remotedir:
remotedir = paths[1]
local = os.path.join(localdir, name)
remote = os.path.join(remotedir, name)
shell.local('rm -f {0}/build/obj.map'.format(local))
base = os.path.dirname(settings.PATHS['configuration'][1])
with shell.workon(all_hosts()):
with shell.cd(remote):
shell.remote('ENV_BASE={0} make -e clean'.format(base))
shell.remote('ENV_BASE={0} make -e build'.format(base))
def execute(name, remotedir=None):
"""
Executes the given test case on all client hosts (normally onle one).
"""
if not remotedir:
remotedir = settings.PATHS['test-cases'][1]
remote = os.path.join(remotedir, name)
base = os.path.dirname(settings.PATHS['configuration'][1])
with shell.workon(role('client')):
with shell.cd(remote):
shell.remote('ENV_BASE={0} make -e execute'.format(base))
<file_sep>"""
``pas jobmgr stop``
====================
**Usage:** ``pas jobmgr stop [-h] [HOST [HOST ...]]``
positional arguments:
.. cmdoption:: HOST
Use this option to specify one or more hosts on which this command has to
be run.
optional arguments:
-h, --help Show this help message and exit.
Stops the ``jobmgr`` on one or more hosts.
If no hosts are provided, then the command first stops the ``child`` hosts
and then, after accounting for a shutdown delay, the ``master`` hosts.
If one or more hosts are provided, the ``stop`` command is sent to all hosts at
the same time.
"""
from pas import commands
from pas import jobmgr
from pas import shell
# pylint: disable-msg=C0111
# Disable warning for the missing docstrings, there is not much to document
# here. For further information refer directly to the enclosed called function
# documentation.
def getparser(parser):
commands.host_option(parser, argument=True)
def command(options):
"""
Stops the jobmgr on the provided hosts. If no hosts are provided, stops
the jobmgr on all master and client hosts by accounting for a shutdown
delay.
"""
if options.hosts:
# Hosts manually defined, start them all without delays
with shell.workon(options.hosts):
jobmgr.stop()
else:
jobmgr.stopall()
<file_sep>.. highlight:: bash
Introduction
============
About
-----
The PAS package provides a command line utility and a measuring framework for
network analysis for the Parallel Object Programming protocol.
The tool allows to start POP-C++ nodes, run measure cases, capture the traffic
and produce a complete report of the exchanged TCP packets between the peers.
By default, the test infrastructure is set up using vagrant and some virtual
machines automatically configured using chef, but it is possible to use any
remote machine with ssh access and some configuration work (involving mainly
installing the needed dependencies and creating some shared folders).
Although this tool was developed especially for the C++ implementation of the
POP model, it was conceived to make as less assumptions as possible about the
underlying implementation and could easily be adapted to measure POP objects
offered by other implementations such, for example, as POP-Java
Further information about the POP-C++ project and the POP model can be found on
the `project's homepage <http://gridgroup.hefr.ch/popc/>`_.
Requirements
------------
The requirements necessary to install and run the ``pas`` utility are the
following:
* Python >= 2.6 – http://python.org/;
* ``vagrant`` and VirtualBox to run the virtual machines
– http://vagrantup.com/;
* A webkit based browser (Safari, Google Chrome,...) to display the reports.
The following libraries and utilities are optional but add some additional
features:
* ``xmllint`` used to reformat the XML documents produced by the measures;
* ``tidy`` used to cleanup the HTML output of the reports (note that the
absence of this utility will add more entries to the list of unsupported
browsers).
The Python packages that will automatically be installed by setuptools are the
following ones:
* ``fabric`` to dispatch commands to remote machines through ssh
– http://fabfile.org/;
* ``pygments`` to highlight the source code and the decoded transactions
– http://pygments.org/;
* ``lxml`` to transform the different measure xml files
– http://codespeak.net/lxml/.
.. _installation:
Installation
------------
Until a stable release is packaged and uploaded to the cheese shop, the latest
development snapshot can be installed directly from the github hosted sources
using ``easy_install`` or ``pip``::
$ pip install https://github.com/GaretJax/pop-analysis-suite/tarball/master
.. note::
Often, depending on the target system, the installation of a python package
requires ``root`` privileges. If the previous command fails, retry to run it
with ``sudo``.
To check if the package was correctly installed, run the the ``pas`` command on
the command line::
$ pas
You should obtain an incorrect usage error similar to the following::
usage: pas [-h] [--version] [-v] [-q] [--settings SETTINGS_MODULE]
{authorize,execute,jobmgr,compile,init,measure} ...
pas: error: too few arguments
Install from source
~~~~~~~~~~~~~~~~~~~
It is possible to install the PAS package directly from source. The following
commands should get you started::
$ wget --no-check-certificate https://github.com/GaretJax/pop-analysis-suite/tarball/master
$ tar -xzf GaretJax-pop-analysis-suite-*.tar.gz
$ cd GaretJax-pop-analysis-suite-*
$ python setup.py install
Setuptools
~~~~~~~~~~
To install the PAS package, the setuptools package is required (for both source
or remote installation modes). Albeit coming preinstalled on all major unix
based operating systems you may need to install it.
You can obtain further information about ``setuptools`` either on its
`pypi project page <http://pypi.python.org/pypi/setuptools>`_ or on its
`official homepage <http://peak.telecommunity.com/DevCenter/setuptools>`_.
Development
-----------
The whole development of the PAS project happens on github, you can find the
source repository at the following address:
https://github.com/GaretJax/pop-analysis-suite/
Further development/contribution directives will be added as soon as some
interest is manifested by any hacker willing to participate in the development
process.
Structure of this manual
------------------------
This manual is conceived to offer an incremental approach to all feature which
the ``pas`` has to offer. It is structured in three main parts:
1. The first part describes and documents the common usage of the tool, the
assumptions it mades about different aspects such as VM setups, object
communications, file locations and so on.
Once read and understood this first part, a user should be able to complete
a full measure cycle with a custom developed measure case and generate a
report to further analyze.
2. The second part dives in the internals of the ``pas`` libraries and
documents topics such as command customization, custom type parsing or
complex measurement setups, useful if a user want to completely adapt the
offered functionalities to his needs.
3. The third part contains reference documentation useful for both a basic or
an advanced usage. There are references for all built-in commands, for the
different settings directives or for more advanced topics such as the
internal APIs.
This three parts are completed with this introduction, a glossary of common
terms and an alphabetical content index.
Building from source
~~~~~~~~~~~~~~~~~~~~
The present document is written using `Sphinx <http://sphinx.pocoo.org/>`_ and
it can either be `read online <http://readthedocs.org/docs/pas/>`_ thanks to
`readthedocs.org <http://readthedocs.org>`_ or built locally using the
``sphinx`` tool into various different formats.
To create a local build, make sure to have the ``sphinx`` package installed and
run the following commands::
$ git clone https://github.com/GaretJax/pop-analysis-suite/
$ cd pop-analysis-suite/docs
$ make html # or any other format; run make without arguments to find out
# the supported ones
The documentation builds will then be placed in the ``_build/<format>``
subdirectory.
<file_sep>cookbook_file "/usr/local/bin/getip" do
source "getip.sh"
mode 0755
owner "root"
group "root"
end
<file_sep>"""
``pas report simplify``
=======================
**Usage:** ``pas report simplify [-h] [MEASURE]``
positional arguments:
.. cmdoption:: MEASURE
The name of the collected measure to simplify.
optional arguments:
-h, --help Show this help message and exit.
Converts the results of an already collected and converted measure from the
wireshark XML format to a simplified POP oriented XML format.
If ``MEASURE`` is not provided, the user is presented with a list of already
collected measures and asked to make a choice.
"""
from pas import commands
from pas import measure
# pylint: disable-msg=C0111
# Disable warning for the missing docstrings, there is not much to document
# here. For further information refer directly to the enclosed called function
# documentation.
def getparser(parser):
commands.measure_argument(parser)
@commands.select_measure
def command(options):
"""
Converts the results of an already collected and converted measure from the
wireshark XML format to a simplified POP oriented XML format.
"""
measure.simplify(options.measure[1])
<file_sep>.. _composed-commands:
Composing commands
==================
As you might have seen in the :ref:`quick-start`, running a measure from begin
to end is a process involving many different steps. If the environment has
already been set up and you are only tweaking your measure case source,
launching a whole measurement cycle requires more than 10 different commands.
Obviously, running them manually each time rapidly becomes cumbersome.
To solve exactly this problematic, ``pas`` introduced the concept of
*workflow*. A *workflow* is nothing else than a ``Makefile`` target invoked
trough the :mod:`pas run <pas.commands.run>` command.
The :mod:`pas run <pas.commands.run>` command simply takes care to invoke one
or more targets locally with the right environment variables set up and the
right working directory, as defined in the :ref:`make invocation` section.
Now that we know how to leverage the power of a ``make`` inside ``pas``, let's
take a look at a simple example. We want to be able to run a full measure
cycle, from compilation to reporting, with a single command.
This is the command we want to be able to execute::
pas run <case-name> measureall
Then, the targets to add to the measure case specific ``Makefile`` to provide
the needed interface, would be the following:
.. code-block:: make
measureall: compile measure report
compile:
pas compile $(MEASURE_NAME)
measure:
pas measure start
pas jobmgr start
pas execute $(MEASURE_NAME)
pas jobmgr stop
pas measure stop
pas measure collect $(MEASURE_NAME)
report:
pas report toxml $(MEASURE_NAME)
pas report simplify $(MEASURE_NAME)
pas report decode $(MEASURE_NAME)
pas report report $(MEASURE_NAME)
The ``Makefile`` of the bundled ``simple`` measure case already contains three
additional targets:
* A ``run`` target to execute a measure by starting first the measure, then
the job managers and in the end running the measure case by tearing it all
down and collecting the data when finished.
* A ``report`` target to generate the HTML report from the raw measures.
* A ``reset`` target (inherited from the base ``Makefile``) which cleans all
builds, kills all running measures and job managers and recompiles POP
binaries from the sources for all hosts.
This commands composition technique allows us to automate some common workflows
and repetitive tasks. For more advanced commands which don't involve only
composition, the :ref:`custom commands <command-subsystem>` documentation
introduces the creation of commands using the very same tools as the ``pas``
subsytem.
<file_sep>"""
.. _pas-report-decode:
``pas report decode``
=====================
**Usage:** ``pas report decode [-h] [MEASURE] [MEASURE_CASE]``
positional arguments:
.. cmdoption:: MEASURE
The name of the collected measure to decode.
.. cmdoption:: MEASURE_CASE
The name of the measure case from which this measure was run. This is
needed to be able to use the additionally defined types for the measured
binary.
optional arguments:
-h, --help Show this help message and exit.
Decodes the results of an already collected and simplified measure by
annotating the XML structure with the needed POP metadata, as extracted from
the TCP payload.
The decoding of additional custom types can be defined on a per-measure-case
basis and is bast described in the :ref:`parser DSL <ppd-reference>` document.
If ``MEASURE`` is not provided, the user is presented with a list of already
collected measures and asked to make a choice.
"""
from pas import commands
from pas import measure
# pylint: disable-msg=C0111
# Disable warning for the missing docstrings, there is not much to document
# here. For further information refer directly to the enclosed called function
# documentation.
def getparser(parser):
commands.measure_argument(parser)
commands.case_argument(parser)
@commands.select_measure
@commands.select_case
def command(options):
"""
Decodes the results of an already collected and simplified measure by
annotating the XML structure with the needed POP metadata, as extracted from
the TCP payload.
"""
measure.decode(options.measure[1], options.case[0])
<file_sep>
execute "configure-sudo-path" do
command "echo \"alias sudo='sudo env PATH=\\$PATH'\" >>/etc/profile"
not_if "grep \"alias sudo='sudo env PATH=\\$PATH'\" /etc/profile"
end
<file_sep>package "libxml2-utils"<file_sep>.. _commands-reference:
Commands reference
==================
This section is dedicated to the description of the usage and the effects of
the different commands and subcommands bundled with the ``pas`` command line
tool.
The main ``pas`` command
------------------------
All operations involving the use of the ``pas`` command line utility require
the use of a subcommand, nonetheless some options common to all subcommands
can only be set directly on the main ``pas`` command.
The usage of the ``pas`` command (obtained running ``pas --help`` on the
command line) is the following::
pas [-h] [--version] [-v] [-q] [--settings SETTINGS_MODULE]
{authorize,execute,jobmgr,compile,init,measure,report} ...
subcommands:
.. cmdoption:: authorize
Exchanges the public keys between all VMs to allow direct ssh connections
between them without user input.
.. cmdoption:: compile
Compiles the given test case on all hosts (by default) or on the hosts
provided on the command line through the ``--host`` option.
.. cmdoption:: execute
Executes the given test case on all hosts having a role of ``client``
(normally only one).
.. cmdoption:: init
Sets up a new measurement and analysis environment in the selected
directory (or in the CWD if none is provided).
.. cmdoption:: jobmgr
Commands suite to remotely manage jobmgr instances.
.. cmdoption:: measure
Commands suite to execute measures and collect results.
.. cmdoption:: report
Commands suite process collected measure results.
optional arguments:
-h, --help Show this help message and exit.
--version Show program's version number and exit.
-v, --verbose Increments the verbosity (can be used multiple times).
-q, --quiet Decrements the verbosity (can be used multiple times).
--settings SETTINGS_MODULE
The path to the settings module
The next two sections are dedicated to the description of some common arguments
and options and to the documentation of all built-in subcommands, respectively.
Common arguments and options
----------------------------
.. _settings options:
``--settings``
~~~~~~~~~~~~~~
The settings option lets you define the path to a directory containing the
``settings`` module (simply a ``settings.py`` file). This module is needed
by some commands to correctly identify a working environment.
It is possible to use this option when invoking a command from outside the
environment working directory.
It is also possible to set the path in the ``PAS_SETTINGS_MODULE`` shell
environment variable instead.
``--verbose`` and ``--quiet``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
These flags increment and decrement the verbosity respectively and can be used
multiple times.
The short version ``-v`` and ``-q`` flags are also available.
``--host`` and ``[HOST]``
~~~~~~~~~~~~~~~~~~~~~~~~~
The host option or its argument alternative syntax are not a general ``pas``
argument but are used often enough by subcommands to being worth to be
documented here.
Many subcommands execute actions on remote machines. By default these actions
are carried out on a predefined list of hosts (normally all or all members of
a given role). Using this argument or the respective option variant, it is
possible to explicitly define one ore more hosts on which executed the command.
Both variants can be used multiple times to provide more than one host.
``MEASURE_CASE``
~~~~~~~~~~~~~~~~
A similar argument as made for the inclusion of the ``host`` argument or option
in this section can be made for the ``MEASURE_CASE`` argument too.
The ``MEASURE_CASE`` argument takes the name of a measure case from the cases
directory. In most cases the value is then coerced to a valid value using the
:func:`pas.commands.select_case` command decorator, which means that the value
can also be left out and the subcommand will prompt the user to select the
desired value from a list of choices.
Built-in subcommands
--------------------
The following subcommands are already built-in and come bundled with all
``pas`` installations. In the next section is explained how it is possible to
add custom subcommands to an existing ``pas`` installation, on a global or
per-environment basis.
.. automodule:: pas.commands.init
.. automodule:: pas.commands.authorize
.. automodule:: pas.commands.compile
.. automodule:: pas.commands.execute
.. automodule:: pas.commands.jobmgr.start
.. automodule:: pas.commands.jobmgr.stop
.. automodule:: pas.commands.jobmgr.kill
.. automodule:: pas.commands.measure.start
.. automodule:: pas.commands.measure.stop
.. automodule:: pas.commands.measure.kill
.. automodule:: pas.commands.measure.collect
.. automodule:: pas.commands.report.toxml
.. automodule:: pas.commands.report.simplify
.. automodule:: pas.commands.report.decode
.. automodule:: pas.commands.report.report
.. automodule:: pas.commands.run
Custom subcommands
------------------
The ``pas`` utility allows to define custom commands to extend the built-in set
of commands. The process of creating a new command and adding it to the ``pas``
utility is described in detail in the :ref:`command-subsystem` document.<file_sep>"""
``pas authorize``
=================
**Usage:** ``pas authorize [-h]``
optional arguments:
-h, --help Show this help message and exit.
Exchanges the public keys between all VMs and adds each host to the
:file:`known_hosts` file of each other, in order to allow direct ssh
connections between VMs without need for external input.
This command operates only on the default ``rsa`` key and uses the shared
configuration directory to keep a temporary list of all public keys.
The function to which this command is bound doesn't need (and doesn't provide)
any specific command-line options and can thus be called in normal library
usage without any argument, like in the following example::
from pas.commands.authorize import command as authorize
authorize()
"""
import os
from pas import shell
from pas.conf import settings
def command(_=None):
"""
Exchanges the public keys between all VMs to allow direct ssh connections
between them without user input.
"""
local, remote = settings.PATHS['configuration']
local = os.path.join(local, 'authorized_keys')
remote = os.path.join(remote, 'authorized_keys')
with shell.ignore_warnings():
shell.local('rm {0}'.format(local))
# Collect all keys in one file
shell.remote('cat $HOME/.ssh/id_rsa.pub >>{0}'.format(remote))
# Copy first authorized key (host machine) to temp location
shell.remote('head -1 $HOME/.ssh/authorized_keys ' \
'>$HOME/.ssh/authorized_keys.tmp')
# Append all other keys
shell.remote('cat {0} >>$HOME/.ssh/authorized_keys.tmp'.format(remote))
# Move to the original location
shell.remote('mv $HOME/.ssh/authorized_keys.tmp ' \
'$HOME/.ssh/authorized_keys')
# Add all hosts to the known_hosts file
shell.remote('cat $HOME/.ssh/authorized_keys | '\
'awk -F \' \' \'{print $3}\' | ' \
'grep -E \'[0-9.]{7,15}\' | ' \
'ssh-keyscan -f - -H -t rsa >$HOME/.ssh/known_hosts')
shell.local('rm {0}'.format(local))
<file_sep>"""
.. _pas-execute:
``pas execute``
===============
**Usage:** ``pas execute [-h] [MEASURE_CASE]``
positional arguments:
.. cmdoption:: MEASURE_CASE
Measure case to execute on all client hosts.
optional arguments:
-h, --help Show this help message and exit.
Executes the given test case on all hosts having a role of ``client``
(normally only one).
If no measure case is provided and only one is available, it is compiled; if
more are available, the user is presented with a list of available cases and
asked to make a choice.
"""
from pas import case
from pas import commands
# pylint: disable-msg=C0111
# Disable warning for the missing docstrings, there is not much to document
# here. For further information refer directly to the enclosed called function
# documentation.
def getparser(parser):
commands.case_argument(parser)
@commands.select_case
def command(options):
"""
Executes the given test case on all hosts having a role of client
(normally only one).
"""
case.execute(options.case[1])<file_sep>.. _measure-cases:
Creating measure cases
======================
A :term:`measure case` in *PAS* is simply a directory containing a bunch of
special files. As we will see in this section, most of this structure is
based on a simple naming convention.
The default directory structure looks like the following::
+ <environment>/
\
+ cases/
\
+ <case-name-1>/
|\
| + Makefile
| + src/
| |\
| | + source1.ph
| | + source1.cc
| | + main.cc
| |
| + types.py
|
+ <case-name-2>/
|\
| + <...>
|
+ <case-name-n>/
The only conventions which have to be respected for the measure case to
conform to the base model are the following:
1. Each measure case shall be in its own directory inside the ``cases``
subdirectory of the environment base directory;
2. Each measure case shall contain a ``Makefile`` which shall provide some
defined targets, see the :ref:`makefile` section);
3. Each measure case shall contain a ``types.py`` file, defining all the types
of the exchanged or called objects (see the :ref:`types` section).
The fact of placing your sources inside the ``src`` subdirectory is not
obligatory, but as described below, a base ``Makefile`` is provided and, to use
it, some more conventions have to be applied, it is thus better to respect this
rule too.
.. _makefile:
:file:`Makefile` targets
------------------------
As anticipated above, the measure case specific ``Makefile`` has to contain
some predefined targets to complain with the specification. These targets are
explained in greater detail in the next subsections.
To speed up the creation of a new measure case, a base makefile named
``Makefile.base`` is placed in the environment's ``conf`` directory. This file
can be included by the measure case specific ``Makefile`` to inherit the
already defined targets.
All required targets are already defined by the base makefile. If you are
option for the default build process and file organizations and don't need
exotic build configuration, including it should suffice to get you started.
Your measure case specific makefile will thus looks something like this:
.. code-block:: makefile
include $(ENV_BASE)/conf/Makefile.base
.. note::
The ``ENV_BASE`` variable contains the absolute path to the environment base
directory and is automatically set to the correct value (either for local or
remote invocation) by the ``pas`` command line tool.
The required targets (``build``, ``execute``, ``clean`` and ``cleanall``) are
further described below, along with their default implementation:
``build``
~~~~~~~~~
Is responsible to build the sources for the architecture on which it is
run on, by making sure that multiple builds of different architectures can
coexist at the same time. After each build, an ``obj.map`` file containing the
informations relative to *all* builds has also to be created or updated.
The exact location/naming of the produced artifacts is not standardized, as
they are needed only by the ``execute`` target.
The base ``Makefile`` provides this target by implementing it in the following
way:
.. code-block:: make
SRCS=src/*.ph src/*.cc
EXEC=$(notdir $(abspath .))
ARCH=$$(uname -m)-$$(uname -p)-$$(uname -s)
build: bin object
dir:
mkdir -p build/$(ARCH)
bin: dir
popcc -o $(EXEC) $(SRCS)
mv $(EXEC) build/$(ARCH)
object: dir
popcc -object -o $(EXEC).obj $(SRCS)
mv $(EXEC).obj build/$(ARCH)
build/$(ARCH)/$(EXEC).obj -listlong >>build/obj.map
sort -u build/obj.map >build/obj.map.temp
mv build/obj.map.temp build/obj.map
``execute``
~~~~~~~~~~~
Allows to run an already built POP program on the architecture the target is
run on.
This target uses the artifacts produced by a run of the ``build`` target
(thus the binaries and the ``obj.map`` file) by choosing the correct
architecture; it has thus to be able to detect its architecture and to run the
respective binary.
The base makefile provides this target by implementing it in the following way:
.. code-block:: make
EXEC=$(notdir $(abspath .))
ARCH=$$(uname -m)-$$(uname -p)-$$(uname -s)
execute:
popcrun build/obj.map build/$(ARCH)/$(EXEC)
``clean``
~~~~~~~~~
Cleans up the compiled files for the architecture on which it is run on. As
before, this target is also already provided by the base makefile:
.. code-block:: make
ARCH=$$(uname -m)-$$(uname -p)-$$(uname -s)
clean:
rm -rf *.o build/$(ARCH)
``cleanall``
~~~~~~~~~~~~
Cleans up all builds for all architectures for its measure case, simply
implemented as:
.. code-block:: make
cleanall: clean
rm -rf build
.. _make invocation:
How will ``pas`` invoke make
----------------------------
As seen in the previous target definitions, the base ``Makefile`` makes
different assumptions about the ``CWD`` at invocation time and about some
variables which have to be set in the environment. To completely exploit all
features which ``make`` makes available, the details of the invocation have to
be known.
``pas`` differentiates between local (i.e. on the host machine) and remote
(i.e. on a guest or on a remote machine) invocations.
Remote invocations
For remote invocations the path is set to the measure case base directory
(i.e. a ``cd`` to ``ENV_BASE/cases/<case-name>`` is done).
Additionally the ``ENV_BASE`` environment variable is set to the specific
environment base location on the remote host as read from the :data:`PATHS
<pas.conf.basesettings.PATHS>` settings directive.
Remote invocations are executed by the :mod:`pas run <pas.commands.run>` and
:mod:`pas execute <pas.commands.execute>` commands.
Local invocations
For local invocations the path is left untouched, but both the
``ENV_BASE`` and ``EXEC`` environment variables are set and the ``-e`` flag
passed to ``make`` in order to let environment variables override local
defined variables.
.. _types:
Measure case specific types
---------------------------
It will often happen (if not always) that you create your custom POP-C++
classes for a specific measure case.
The python based parser used to decode the TCP payload cannot know what types
are encoded in it without further informations. To fulfill this need, custom
types can be created and registered to the parser using the
:ref:`ppd-reference`.
The :ref:`pas-report-decode` subcommand automatically loads the ``types.py``
file contained in the measure case directory and registers the contained types
for the decoding session.
.. note:
If you don't defined any custom types, you can leave this file empty or
delete it. The parser will automatically load the base types.
The syntax of this file is quite simple and based upon a declarative python
syntax; refer to the :ref:`ppd-reference` document for further information
about it and how to define your custom types.
<file_sep>"""
General test suite environment management functions.
"""
import os
import shutil
import pas.conf
def setup(dstdir):
"""
Sets up a new environment in the given directory by recursively copying
all the files inside pas.conf.suite_template to the given directory.
The destination directory must already exist.
"""
srcdir = os.path.join(os.path.dirname(pas.conf.__file__), 'suite_template')
# Copy each child individually to the exising directory. shutil.copytree
# cannot be used directly because the target directory already exists.
for i in os.listdir(srcdir):
src = os.path.join(srcdir, i)
dst = os.path.join(dstdir, i)
if os.path.isdir(src):
shutil.copytree(src, dst)
else:
shutil.copy(src, dst)
<file_sep>"""
Settings support for the whole pas package.
This module contains methods to load and temporarily store setting directives
for the current execution.
Various shortcuts to access the different settings in a usage-oriented way are
also provided.
"""
from collections import defaultdict
import itertools
import logging
import os
import sys
__all__ = ['settings', 'all_hosts', 'role', 'map_interfaces']
class Settings(object):
"""
A simple settings store which is able to load variables defined in a
module.
"""
def __init__(self, defaults=None):
"""
Creates a new Setting instance by loading the optional defaults from
the given module.
"""
self.last_path = None
if defaults:
if isinstance(defaults, basestring):
self.loadfrompath(module=defaults)
else:
self.load(defaults)
def load(self, module):
"""
Loads the given module by copying all its public defined variables
to the instance.
Older keys are overridden by new ones.
"""
log = logging.getLogger()
log.debug("Loading settings from '{0}'".format(module.__file__))
for key, value in module.__dict__.iteritems():
if not key.startswith('_') and key.isupper():
setattr(self, key, value)
def loadfrompath(self, path=None, module='settings'):
"""
Loads the setting directives from the given module, by looking first
in the provided path.
"""
log = logging.getLogger()
if path:
sys.path.insert(0, path)
try:
__import__(module, level=0)
_settings = sys.modules[module]
except ImportError:
log.debug("Could not load settings, module not found on path:")
for i in sys.path:
log.debug(" - checked: {0}".format(i))
raise
else:
self.ENV_BASE = os.path.dirname(_settings.__file__)
self.load(_settings)
finally:
if path:
sys.path.pop(0)
def get(self, name, default=None):
"""
Gets a setting directive falling back to the provided default, thus
not generating any errors.
"""
return getattr(self, name, default)
def __str__(self):
"""
Returns a string representation of this settings object, containing
the a key=value pair on each line.
"""
directives = []
for key, value in self.__dict__.iteritems():
directives.append('{0}={1}'.format(key, value))
return '\n'.join(directives)
def __getattr__(self, name):
"""
Raises a custom exception if the attribute was not found.
"""
raise AttributeError("The requested setting directive ({0}) is " \
"not set".format(name))
# pylint: disable-msg=C0103
# Uff... module level variables should all be uppercase, but this is a special
# case (hope Guido is not going to read this).
settings = Settings('pas.conf.basesettings')
# pylint: enable-msg=C0103
def stylesheet(name):
"""
Returns the full path to the XSL stylesheet with the given name inside the
directory defined in the confguration path.
"""
return os.path.join(settings.PATHS['configuration'][0], 'templates', name)
def all_hosts():
"""
Returns a set of all hosts obtained by chaining all hosts in the ROLES
settings directive.
"""
return set(itertools.chain(*settings.ROLES.values()))
def role(role_name):
"""
Returns a list of all hosts for a given role.
"""
return settings.ROLES[role_name]
def map_interfaces():
"""
Returns a dict mapping host connection strings to interfaces, obtained by
combining the INTERFACES and ROLES settings directives.
"""
mapping = defaultdict(set)
for role_name, hosts in settings.ROLES.iteritems():
for host in hosts:
try:
mapping[host] |= set(settings.INTERFACES[role_name])
except KeyError:
pass
return mapping.iteritems()
<file_sep>"""
Support for a plug-in commands infrastructure.
Each command is a separate module in this package (pas.commands) and should at
least contain a command function (modules starting with an underscore will be
ignored).
The command function takes one required positional argument: an
argparse.Namespace instance with the parsed command line with which the
command was invoked.
The name of the command will be the same as the name of the module containing
the command function.
To add command-specific arguments to a given command, a getparser function
can be defined in the command module. This function takes an
argparse.SubParser instance and can freely customize it, the only setted
options are the command name and the command function.
This subparser will not be modified after the getparse call, so you can
imagine to do all weird things there in; just remember that for each run, all
getparser functions will be called and this can induce in some overhead when
there are many commands or when the getparse function executes slow or
long-lasting operations.
"""
import argparse
import imp
import functools
import logging
import os
import sys
from pas import VERSION
from pas import case
from pas import measure
from pas.conf import settings
def nosettings(func):
"""
Instructs the command dispatcher to not try to load the settings when
executing this command.
Normally the command invoker will try to load the settings and will
terminate the execution if not able to do so, but some commands don't need
the settings module and are specifically crafted to operate outside of an
active testing environment.
To instruct the invoker not to try to load the settings, a nosettings
attribute with a non-false value can be set on the command function; this
decorator does exactly this.
You can use it like this::
from pas.commands import nosettings
@nosettings
def command(options):
# Do something without the settings
pass
:param func: The command function for which the settings don't have to be
loaded.
"""
func.nosettings = True
return func
def select_case(func):
"""
Adds a ``case`` attribute to the ``Namespace`` instance passed to the
command, containing a tuple of ``(full-path-on-disk-to-the-measure-case,
measure-case-basename)``.
The ``case`` attribute is populated by calling the
:py:func:`pas.case.select` function.
If a ``case`` attribute is already set on the ``Namespace`` its value will
be passed to the the :py:func:`pas.case.select` function as default value
for the selection.
You can use it like this::
from pas.commands import select_case
@select_case
def command(options):
# Do something with the measure case
print options.case
:param func: The command function for which the a case has to be selected.
"""
@functools.wraps(func)
def check_and_ask(options):
"""
Modifies the case attribute of the passed argparse.Namespace instance
to be a valid test case.
"""
options.case = case.select(getattr(options, 'case', None))
return func(options)
return check_and_ask
def select_measure(func):
"""
Adds a ``measure`` attribute to the ``Namespace`` instance passed to the
command, containing a tuple of ``(full-path-on-disk-to-the-measure,
measure-basename)``.
The ``measure`` attribute is populated by calling the
:py:func:`pas.measure.select` function.
If a ``measure`` attribute is already set on the ``Namespace`` its value
will be passed to the the :py:func:`pas.measure.select` function as default
value for the selection.
You can use it like this::
from pas.commands import select_measure
@select_measure
def command(options):
# Do something with the measure
print options.measure
:param func: The command function for which the a case has to be selected.
"""
@functools.wraps(func)
def check_and_ask(options):
"""
Modifies the measure attribute of the passed argparse.Namespace
instance to be a valid measure.
"""
options.measure = measure.select(getattr(options, 'measure', None))
return func(options)
return check_and_ask
def host_option(parser, argument=False):
"""
Adds an optional ``--host`` option to the ``parser`` argument.
The given hosts can be read using the ``hosts`` attribute of the
``Namespace`` instance passed to the command to be executed.
The resulting ``hosts`` attribute will always be a list of the hosts
specified on the command line or an empty list if no hosts were specified.
If the optional ``argument`` flag is set to true, then this decorators adds
an argument insted of an option.
Multiple hosts can be specified using multiple times the ``--host`` option
or by giving multiple ``HOST`` arguments as appropriate.
Use it like this::
from pas.commands import host_option
def getparser(parser):
host_option(parser)
def command(options):
# Do something with it
print options.hosts
:param parser: The ``ArgumentParser`` instance on which the ``--host``
option shall be attached.
:param argument: A flag indicating if the hosts shall be parsed as
arguments instead.
"""
helpmsg = """Use this option to specify one or more hosts on which this
command has to be run."""
if argument:
parser.add_argument(
'hosts',
metavar='HOST',
default=[],
help=helpmsg,
nargs='*'
)
else:
helpmsg += """ The --host option can be specifed multiple times to
define multiple hosts."""
parser.add_argument(
'--host',
metavar='HOST',
dest='hosts',
default=[],
help=helpmsg,
action='append'
)
def case_argument(parser):
"""
Adds an optional ``case`` argument to the given parser.
No validations are done on the parsed value as the settings have to be
loaded to obtain the local measure-cases path and they can't be loaded
before the full command-line parsing process is completed.
To bypass this issue, the :func:`pas.commands.select_case` command
decorator can be used which looks at the ``Namespace`` instance and does all
the necessary steps to provide the command with a valid measure case path.
Use it like this::
from pas.commands import case_argument, select_case
def getparser(parser):
case_argument(parser)
@select_case # Optional
def command(options):
# Do something with it
print options.case
:param parser: The ``ArgumentParser`` instance on which the ``case``
argument shall be attached.
"""
parser.add_argument('case', metavar='MEASURE_CASE', nargs='?')
def measure_argument(parser):
"""
Adds an optional ``measure`` argument to the given parser.
No validations are done on the parsed value as the settings have to be
loaded to obtain the local measures path and they can't be loaded before
the full command-line parsing process is completed.
To bypass this issue, the :func:`pas.commands.select_measure` command
decorator can be used which looks at the ``Namespace`` instance and does all
the necessary steps to provide the command with a valid measure path.
Use it like this::
from pas.commands import measure_argument, select_measure
def getparser(parser):
measure_argument(parser)
@select_measure # Optional
def command(options):
# Do something with it
print options.measure
:param parser: The ``ArgumentParser`` instance on which the ``measure``
argument shall be attached.
"""
parser.add_argument('measure', metavar="MEASURE", nargs='?')
def getdoc(obj):
"""
Gets and formats an object docstring by keeping only the first paragraph
(considering paragraphs separated by an empty line), removing the
indentiation and merging multiple lines together.
If the object had no docstring attached, an empty string will be returned.
"""
docstring = obj.__doc__
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count)
indent = sys.maxint
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special)
trimmed = [lines[0].strip()]
if indent < sys.maxint:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Get the full docstring
fulldoc = '\n'.join(trimmed)
# Return only the first paragraph (joined together)
return "\n\n".join(p.replace('\n', ' ') for p in fulldoc.split('\n\n'))
def settingspath(path):
"""
Validator function to be used in the parser.add_argumet call for the
settings module path.
The retuned path is the realpath of the argument if it points to a
directory and the dirname of the realpath of the argument if it end with
a .py extension.
This means that both the full path to the settings.py (or settings
package, or settings compiled python .pyc) file/directory or to its
containing directory can be specified and will be accepted.
Note that no checks about the real existence of the settings module are
done here.
"""
path = os.path.realpath(path)
# Take the containing directory if the path points directly to the module
if path.endswith(('settings.py', 'settings.pyc', 'settings')):
return os.path.dirname(path)
return path
def load_package_subcommands(subparsers, package):
"""
Recursively loads all the subcommands contained in the given package as
subparsers for the given subparser.
"""
# pylint: disable-msg=W0212
# Disable warning for accessing the _actions member of the ArgumentParser
# class.
log = logging.getLogger('pas.commands_builder')
directory = os.path.dirname(package.__file__)
for cmd in os.listdir(directory):
path = os.path.join(directory, cmd)
if cmd.startswith('_'):
continue
if not cmd.endswith('.py') and not os.path.isdir(path):
continue
name = cmd.rsplit('.', 1)[0]
fullname = '{0}.{1}'.format(package.__name__, name)
if cmd.endswith('.py'):
# ...import the command and getparser function...
module = imp.load_source(fullname, path)
name = module.__name__.rsplit('.', 1)[-1]
try:
command = module.command
except AttributeError:
log = logging.getLogger('pas.commands_builder')
msg = "No command found in module {}".format(module.__name__)
log.error(msg)
else:
subparser = subparsers.add_parser(name, help=getdoc(command))
subparser._actions[0].help = "Show this help message and exit."
subparser.set_defaults(execute=command)
if hasattr(module, 'getparser'):
module.getparser(subparser)
else:
# Recursively load the subpackage
path = os.path.join(path, '__init__.py')
module = imp.load_source(fullname, path)
name = module.__name__.rsplit('.', 1)[-1]
subparser = subparsers.add_parser(name, help=getdoc(module))
subparser._actions[0].help = "Show this help message and exit."
load_package_subcommands(subparser.add_subparsers(), module)
def build_mainparser():
"""
Builds the base parser for the main ``pas`` command, without accounting
for subcommands but already including the --``settings`` directive in
order to be able to load the settings before searching for subcommands.
"""
# Get default path to the settings module
settings = os.getenv('PAS_SETTINGS_MODULE') or os.getcwd()
# Build main parser
parser = argparse.ArgumentParser()
parser.add_argument('--version', action='version',
version='%(prog)s ' + VERSION)
parser.add_argument('-v', '--verbose', default=list(),
action='append_const', const=1, help="Increments the "\
"verbosity (can be used multiple times).")
parser.add_argument('-q', '--quiet', default=list(),
action='append_const', const=1, help="Decrements the "\
"verbosity (can be used multiple times).")
parser.add_argument('--settings', default=settings,
metavar='SETTINGS_MODULE', type=settingspath,
help="The path to the settings module")
# pylint: disable-msg=W0212
# Disable warning for accessing the _actions member of the ArgumentParser
# class.
parser._actions[0].help = "Show this help message and exit."
parser._actions[1].help = "Show program's version number and exit."
return parser
def build_subparsers(parser):
"""
Builds the complete command-line parser for the pas program by asking each
command module inside the pas.commands package for subparser customization
as described in the package docstring.
"""
log = logging.getLogger('pas.commands_builder')
# For each module/package in the pas.commands package...
subparsers = parser.add_subparsers()
load_package_subcommands(subparsers, sys.modules[__name__])
if not settings.ENV_BASE:
return parser
for directory in settings.COMMAND_DIRECTORIES:
directory = os.path.join(settings.ENV_BASE, directory)
log.debug("Scanning external directory '{0}' for commands...".format(
directory))
module = os.path.basename(directory)
module_path = os.path.join(directory, '__init__.py')
if os.path.isfile(module_path):
package = imp.load_source(module, module_path)
load_package_subcommands(subparsers, package)
return parser
<file_sep>
PAS - POP Analysis Suite 0.1a
=============================
.. toctree::
:maxdepth: 2
introduction
documentation/index
advanced/index
references/index
glossary
<file_sep>.. _execution-model:
Execution model
===============
In the :ref:`quick-start` we have seen all steps needed to create an
environment, set up the virtual machines, run a measures and generate a report
from a practical point of view. In this document we will take a deeper look at
the inside workings of the pas tool and its execution model.
Once understood this model and acquired a good overview of the various commands
you will be ready to bend the ``pas`` utility to your will by simply combining
or adding different commands.
The following image will give you an high level overview of the execution model
of a measure in ``pas`` and the description of each step contains shortcuts to
relevant commands and configuration directive references:
.. image:: /assets/execution-model.*
The various steps of the execution model can best be described as follows:
1. **Setup**
This involves the initialization of the environment, the setup of the
virtual machines and the creation of one or more measure cases.
*Related commands:*
:mod:`pas init <pas.commands.init>`,
:mod:`pas authorize <pas.commands.authorize>`
*Related settings:*
:data:`VM_USER <pas.conf.basesettings.VM_USER>`,
:data:`VM_PASSWORD <pas.conf.basesettings.VM_PASSWORD>`
2. **Distribution and compilation**
The first part of this step, the *distribution*, is automatically done by
sharing the used directories between the host (your machine) and the guests
(the virtual machines running on the host).
The second part, the *compilation* is executed sequentially on each host
and produces a binary build of the measure case for each different
architecture in your VM setup.
*Related commands:*
:mod:`pas compile <pas.commands.compile>`
3. **Beginning of the capturing process**
A ``tshark`` instance is started on each configured interface of each guest
and every filtered packet captured to a guest-local file.
The ``tshark`` program is the command-line version of the well known
`wireshark <http://wireshark.org>`_ network protocol analyzer.
*Related commands:*
:mod:`pas measure start <pas.commands.measure.start>`,
:mod:`pas measure stop <pas.commands.measure.stop>`,
:mod:`pas measure kill <pas.commands.measure.kill>`
*Related settings:*
:data:`CAPTURE_FILTER <pas.conf.basesettings.CAPTURE_FILTER>`,
:data:`INTERFACES <pas.conf.basesettings.INTERFACES>`
4. **Job manager startup**
A ``jobmgr`` is started on each guest, with a different configuration based
on their role. The default setup defines a master and a slave role and the
respective configuration to simulate the offloading of objects to a remote
guest.
*Related commands:*
:mod:`pas jobmgr start <pas.commands.jobmgr.start>`,
:mod:`pas jobmgr stop <pas.commands.jobmgr.stop>`,
:mod:`pas jobmgr kill <pas.commands.jobmgr.kill>`
*Related settings:*
:data:`ROLES <pas.conf.basesettings.ROLES>`,
:data:`STARTUP_DELAY <pas.conf.basesettings.STARTUP_DELAY>`,
:data:`SHUTDOWN_DELAY <pas.conf.basesettings.SHUTDOWN_DELAY>`
5. **POP program execution**
The developed POP program is executed and the generated traffic captured by
the different ``tshark`` processes.
*Related commands:*
:mod:`pas execute <pas.commands.execute>`
*Related settings:*
:data:`ROLES <pas.conf.basesettings.ROLES>`
6. **Data collection**
Once the POP program has executed and returned, the measure and the
job managers can be stopped.
The results of each single measure and the different log files are now
spread among all the different involved guests. The collection process
retrieves all these files and copies them to a common shared location where
the host can access them.
*Related commands:*
:mod:`pas measure collect <pas.commands.measure.collect>`
*Related settings:*
:data:`LOG_FILES <pas.conf.basesettings.LOG_FILES>`
7. **Report generation**
Now that the host has all measure results locally available it can process
and assemble them into one or more measure reports.
This process involves multiple steps, such as conversions, simplifications,
payload decoding and the final assembly.
*Related commands:*
:mod:`pas report toxml <pas.commands.report.toxml>`,
:mod:`pas report simplify <pas.commands.report.simplify>`,
:mod:`pas report decode <pas.commands.report.decode>`,
:mod:`pas report report <pas.commands.report.report>`
*Related settings:*
:data:`DISPLAY_FILTER <pas.conf.basesettings.DISPLAY_FILTER>`
Once grasped these concepts you are ready to personalize your testing
environment. If you have not done so yet, hand over to the :ref:`quick-start`
for a step-by-step begin-to-end on how guide to take a measure or continue to
the detailed guide about how to :ref:`create measure cases <measure-cases>`.
The :ref:`advanced usage <advanced>` chapter provides documentation on more
technical and complicated aspected of the POP Analysis Suite needed to
completely customize and adapt an environment to special setups (i.e. a
preexisting setup with real machines).
<file_sep>.. _ppd-reference:
POP Parsing DSL
===============
The informations transmitted in the POP encoded messages don't include the type
of the transmitted values as these are defined at compilation time and known to
both involved parties.
With the use of python and the need to decode message exchanges between
arbitrary peers, information about the transmitted values data-types is not
available and has to be provided somehow.
The implemented python based parser for POP messages introduces the concept of
a *types registry*. Each time a message has to be decoded, the specific types
of the payload are retrieved from the registry using the
``classid``/``methodid`` couple or the exception code contained in the POP
payload header.
As the measuring of arbitrary programs introduces new classes, methods and data
types, it does not suffice to provide a built-in set of known data types and
the need to let the final ``pas`` user specify custom and complex types arises.
For this purpose a special python-based domain specific language as been
defined. The DSL builds upon a few directives to be able to define primitive
types (rarely needed), complex types and new classes and to register them to
the registry in order to let the parser retrieve them when needed.
Refer to the :ref:`ppd-builtin` document for an overview of the already
provided types and classes.
Defining classes and methods
----------------------------
Defining a new class and its corresponding methods is an easy task thanks to
the declarative syntax offered by the POP Parsing DSL.
Each file which will finish up loaded by the types registry shares a common
import::
from pas.parser.types import *
Once imported the different types, it is possible to use the
:func:`pas.parser.types.cls`, :func:`pas.parser.types.func` and
:func:`pas.parser.types.exc` functions to create new classes, methods and
exceptions respectively.
Their API is the following:
.. autofunction:: pas.parser.types.cls
.. autofunction:: pas.parser.types.func
.. autofunction:: pas.parser.types.exc
A possible definition of the ``paroc_service_base`` class using the parser DSL
is the following::
# Import the POP types and the cls and func helpers
from pas.parser.types import *
# Define the class and its methods
cls(0, 'paroc_service_base', [
func(0, 'BindStatus', [], [int, string, string]), # broker_receive.cc:183
func(1, 'AddRef', [], [int]), # broker_receive.cc:218
func(2, 'DecRef', [], [int]), # broker_receive.cc:238
func(3, 'Encoding', [string], [bool]), # broker_receive.cc:260
func(4, 'Kill', [], []), # broker_receive.cc:287
func(5, 'ObjectAlive', [], [bool]), # broker_receive.cc:302
func(6, 'ObjectAlive', [], []), # broker_receive.cc:319
func(14, 'Stop', [string], [bool]), # paroc_service_base.ph:47
])
# Done. No further actions are required
By reading the preceding snippet, a few observations can be made:
1. Not all methods are defined. In fact, the parser doesn't care if the object
is fully defined or not until it doesn't receive a request or a response
for an inexistent method ID.
2. Methods can return multiple values. The first return value is always
mapped to the C++ return value (if non-``void``), while the following
values are mapped to the arguments which were passed as references.
3. The ``bool`` type is often used in responses. The actual C++ return type is
an ``int``, but as it is interpreted only as a success flag a ``bool``
type has more semantic meaning in these particular cases.
Defining complex and composite types
------------------------------------
In the previous section the process of defining a new class and its methods was
presented, but the illustrated example was based on a relative simple class.
What has to be done, if for example, the ``POPCSearchNode`` class has to be
defined (more specifically its ``callbackResult`` method)?
The following is the signature of the ``POPCSearchNode::callbackResult``
method:
.. code-block:: cpp
conc async void callbackResult(Response resp);
As you might have noticed, it takes a ``Response`` object as argument, so a
possible definition using the parser DSL syntax would be::
cls(1001, 'POPCSearchNode', [
# ...other methods here...
func(38, 'callbackResult', [Response], []),
])
But how is the ``Response`` object defined and how does the parser know how to
decode it? The ``Response`` object is what in the python parser domain is
called a :term:`compound type` and fortunately its definition is much easier
than you might think; we know that a ``Response`` object is composed by a
``string``, a ``NodeInfo`` object and an ``ExplorationList`` object, so its
definition becomes::
Response = compound('Response',
('uid', string),
('nodeInfo', NodeInfo),
('explorationList', ExplorationList),
)
This example introduced two new concepts:
1. The ``compound`` function, which allows to create composite objects based
on a list of (``name``, ``type``) tuples;
2. Nested compound objects definition. A compound object can further contain
compound objects (the preceding snippet contains ``NodeInfo`` and
``ExplorationList`` as subtypes).
If we look deeper in detail, we'll see that the ``ExplorationList`` object
isn't actually a compound object, but rather a list of compound objects.
Fortunately, the task of defining a list is also easy using the shortcuts
offered by the DSL::
ExplorationList = array(
compound('ListNode',
('nodeId', string),
('visited', array(string)),
)
)
As you can see, defining new complex types is an easy task once the syntax and
the different :term:`composers` are known. Below you can find the API of the
different composers that come built-in with the python POP parser:
.. autofunction:: pas.parser.types.compound
.. autofunction:: pas.parser.types.dict
.. autofunction:: pas.parser.types.array
.. autofunction:: pas.parser.types.optional
Defining scalars
----------------
In the previous sections we have seen how to create new classes with bound
methods and how to define new argument or return types for those by combining
scalars into more complex structure in different ways.
The last building block needed to fully grasp the parsing details is the
decoding of scalars. It is here that the real work happens, as complex or
compound types only arrange scalars in different orders to decode a full
structure, but don't tell them *how* to decode the single values.
New scalar types are not needed as much as new complex types, but it can
serve to better understand the whole parsing process as well. Furthermore it
allows to define how to decode POP-C++ specific types (e.g. the
:c:type:`popbool` primitive) which don't comply with the standards.
A scalar type, as well as all types returned from the different composers seen
above, is simply a ``callable`` which accepts an `xdrlib.Unpacker`_ object
and returns a decoded python object. Refer to the ``Unpacker`` documentation
for further information about the already supported data types.
As an example, the implementation of the :c:type:`popbool` type is shown
below::
import __builtin__
# Define a callable which taks a single argument
def popbool(stream):
# Read an integer and check that the highest byte is set
result = stream.unpack_int() & 0xff000000
# Coearce the value to a boolean (use the __builtin__ pacakge as the
# previous bool definition overwrote the built-in definition)
return __builtin__.bool(result)
.. _xdrlib.Unpacker: http://docs.python.org/library/xdrlib.html#unpacker-objects
<file_sep>
TODOs for the documentation
===========================
.. todolist::<file_sep>"""
"""
import xdrlib
from pas.parser import messages
class MappingProtocol(object):
request_types = ('request', 'response', 'exception')
def __init__(self, types_registry):
self.types_registry = types_registry
def read_header(self, stream):
return [stream.unpack_uint() for i in range(4)]
def decode_full_frame(self, stream):
req_type, classid, methodid, semantics = self.read_header(stream)
handler = getattr(self, 'handle_' + self.request_types[req_type])
message = handler(classid, methodid, semantics, stream)
try:
stream.done()
except xdrlib.Error as e:
#print "*" * 80
#print repr(message)
#r = decoder.get_buffer()
#rem = decoder.get_position()
#print repr(r)
#print " " * (len(repr(r[:rem]))-3),
#print repr(r[rem:])
#print str(rem) + "/" + str(length)
#print "*" * 80
e.stream = stream
e.message = message
raise
return message
def handle_request(self, classid, methodid, semantics, decoder):
cls = self.types_registry.get_class(classid)
mth = cls.getmethod(methodid)
sem = messages.Semantics(semantics)
args = mth.arguments(decoder)
return messages.POPRequest(sem, cls, mth, args, decoder.get_buffer())
def handle_response(self, classid, methodid, _, decoder):
cls = self.types_registry.get_class(classid)
mth = cls.getmethod(methodid)
result = mth.result(decoder)
return messages.POPResponse(cls, mth, result, decoder.get_buffer())
def handle_exception(self, classid, _1, _2, decoder):
exc = self.types_registry.get_exception(classid)
properties = exc.properties(decoder)
return messages.POPException(exc, properties, decoder)
<file_sep>References & API documentation
==============================
.. toctree::
commands-reference
settings-reference
ppd-builtin
internal-api
<file_sep>"""
Local and remote shell commands execution.
These functions are mainly wrappers around those found in the fabric library.
"""
from pas.conf import settings
from pas.conf import all_hosts
# pylint: disable-msg=W0611
# Disable warning about unused imports, as they are intended to be available
# directly from the shell module to avoid specific fabric imports
from fabric import state
from fabric.context_managers import settings as _context
from fabric.context_managers import hide as _hide
from fabric.context_managers import _setenv
from fabric.context_managers import nested as _nested
from fabric.context_managers import cd
from fabric.contrib.console import confirm
from fabric.operations import local as _local
from fabric.operations import run as _run
from fabric.operations import sudo as _sudo
from fabric.operations import prompt
# pylint: enable-msg=W0611
__all__ = [
# shell module functions
'ignore_warnings', 'workon', 'local', 'remote',
# imported from the fabric library for external use
'cd', 'prompt', 'confirm',
]
def ignore_warnings():
"""
Returns a fabric context manager configured to silently ignore all
warnings about running commands.
"""
return _context(_hide('warnings'), warn_only=True)
def workon(hosts):
"""
Returns a fabric context manager which sets the hosts list to the given
list.
If the passed hosts argument is a single string, it is silently converted
to a list before.
"""
if isinstance(hosts, basestring):
hosts = [hosts]
return _nested(_setenv(hosts=hosts))
def local(cmd):
"""
Executes a local command without capturing and returning the output.
Thin wraper around the fabric.operations.local function
"""
return _local(cmd, capture=False)
def remote(cmd, pty=False, user=None, sudo=False):
"""
Executes the given remote command on the hosts list set in the current
context.
If user is given or sudo evaluates to True, then a fabric.operations.sudo
call is made, otherwise a simple fabric.operations.run.
"""
if state.env.cwd:
cmd = 'cd {0} && {1}'.format(state.env.cwd, cmd)
with _context(user=settings.VM_USER, password=settings.VM_PASSWORD):
for host in state.env.hosts or all_hosts():
with _context(host_string=host):
if user or sudo:
_sudo(cmd, user=user, pty=pty)
else:
_run(cmd, pty=pty)
<file_sep>.. _settings reference:
Settings reference
==================
As seen in the :ref:`configuration` document, ``pas`` provides a global
``Settings`` object which can be populated by loading directives from different
sources.
.. automodule:: pas.conf.basesettings
:members:
:undoc-members:<file_sep>Internal API
============
``pas.case``
------------
.. automodule:: pas.case
:members:
``pas.conf``
------------
.. automodule:: pas.conf
:members:
``pas.env``
-----------
.. automodule:: pas.env
:members:
``pas.jobmgr``
--------------
.. automodule:: pas.jobmgr
:members:
``pas.measure``
---------------
.. automodule:: pas.measure
:members:
``pas.shell``
-------------
.. automodule:: pas.shell
:members:
``pas.tshark``
--------------
.. automodule:: pas.tshark
:members:
``pas.xml``
-----------
.. automodule:: pas.xml
:members:<file_sep>"""
The pas package provides the necessary commands and their underlying libraries
to interact with a VM based POP Analyzing Suite environment.
Most of the functionalities are described by the pas command-line script
documentation and its related subcommands. Take a look to their docstring to
obtain further information about he usage.
The commands are mainly a thin wrapper around library calls to functions
inside the various modules contained in the root pas package. To use pas as a
python library call the functions directly, without invoking the commands. The
functions docstring should provide enough information about their usage. You
may also refer to the various command implementations for examples about their
necessity of some context to be set.
"""
VERSION = '0.1'
<file_sep>#!/usr/bin/env python
"""
Main command line script of the pas package.
The main function contained in this module is used ai main entry point for the
pas command line utility.
The script is automatically created by setuptool, but this file can be
directly invoked with `python path/to/pas.py` or directly if its executable
flag is set.
"""
import itertools
import logging
import logging.handlers
import os
import sys
# pylint: disable-msg=E0611
# I know relative imports are not the holy grail, but here we need them and
# it is a pylint bug not to recognized empty parent paths.
from .. import commands # Relative imports to avoid name clashing
from ..conf import settings # Relative imports to avoid name clashing
# pylint: enable-msg=E0611
# Reenable unknown name detection
from fabric.state import connections
# pylint: disable-msg=W0105
# Docstring for variables are not recognized by pylint, but epydoc parses them
LOGFILE = os.getenv('PAS_LOGFILE') or 'pas.log'
"""Logfile name, settable using the PAS_LOGFILE env variable"""
VERBOSITY = logging.INFO
"""Default verbosity for console output"""
def main():
"""
First function called upon command line invocation. Builds the command
line parser, parses the arguments, configures logging and invokes the
command.
"""
# Configure logging
file_formatter = logging.Formatter("%(asctime)s - %(levelname)10s - " \
"%(message)s (%(pathname)s:%(lineno)d)")
console_formatter = logging.Formatter("%(levelname)10s: %(message)s")
# All console output not explicitly directed to the user should be a log
# message instead
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(console_formatter)
console_handler.setLevel(20) # Don't show debug log messages until the
# verbosity is set
# Buffer the logging until no errors happen
buffered_handler = logging.handlers.MemoryHandler(9999, logging.CRITICAL)
# Capture all logging output and write it to the specified log file
file_handler = logging.FileHandler('pas.log', 'w', delay=True)
file_handler.setFormatter(file_formatter)
file_handler.setLevel(40)
logger = logging.getLogger()
logger.setLevel(1)
logger.addHandler(console_handler)
logger.addHandler(buffered_handler)
# Build base parser
parser = commands.build_mainparser()
arguments = itertools.takewhile(lambda x: x.startswith('-'), sys.argv[1:])
arguments = (arg for arg in arguments if arg not in ('-h', '--help'))
command_line = sys.argv[:1] + list(arguments)
# Parse the base arguments (verbosity and settings)
args, remaining = parser.parse_known_args(command_line)
buffered_handler.setTarget(file_handler)
# Get the verbosity level
verbosity = max(1, VERBOSITY - 10 * (len(args.verbose) - len(args.quiet)))
console_handler.setLevel(verbosity)
file_handler.setLevel(1)
paramiko_logger = logging.getLogger('paramiko.transport')
paramiko_logger.setLevel(verbosity + 10)
# Load settings
try:
settings.loadfrompath(path=args.settings)
nosettings = False
except ImportError:
from ..conf import basesettings
settings.load(basesettings)
nosettings = True
# Build complete parser
parser = commands.build_subparsers(parser)
# Parse arguments
command = args = parser.parse_args()
res = 0
# Check that settings where loaded if needed
if not getattr(command.execute, 'nosettings', False) and nosettings:
logger.critical("This command requires the settings module to be " \
"present on path or defined using the " \
"PAS_SETTINGS_MODULE environment variable.")
res = 1
# Execute command
if not res:
res = command.execute(args)
# Cleanup fabric connections if needed
for key in connections.keys():
connections[key].close()
del connections[key]
# Check execution result
if res:
# ...an error occurred, write the logfile
buffered_handler.flush()
print
print "pas exited with a non-zero exit status (%d). A complete log " \
"was stored in the %s file." % (res, LOGFILE)
print
else:
# ...no errors occurred, avoid to flush the buffer
buffered_handler.setTarget(None)
# Need to close the buffered handler before sysexit is called or it will
# result in an exception
buffered_handler.close()
return res
if __name__ == '__main__':
sys.exit(main())
<file_sep>from pas.parser.types import *
cls(0, 'paroc_service_base', [
func(0, 'BindStatus', [], [int, string, string]), # broker_receive.cc:183
func(1, 'AddRef', [], [int]), # broker_receive.cc:218
func(2, 'DecRef', [], [int]), # broker_receive.cc:238
func(3, 'Encoding', [string], [bool]), # broker_receive.cc:260
func(4, 'Kill', [], []), # broker_receive.cc:287
func(5, 'ObjectAlive', [], [bool]), # broker_receive.cc:302
func(6, 'ObjectAlive', [], []), # broker_receive.cc:319
func(14,'Stop', [string], [bool]), #
])
cls(2, 'CodeMgr', [
func(13, 'RegisterCode', [string, string, string], []),
func(14, 'QueryCode', [string, string], [string,int]),
func(15, 'GetPlatform', [string], [string, int]),
])
cls(3, 'RemoteLog', [
func(13, 'Log', [string], []), # remotelog.cc:17
])
cls(4, 'ObjectMonitor', [
func(14, 'ManageObject', [string], []),
func(15, 'UnManageObject', [string], []),
func(16, 'CheckObjects', [], [int]),
])
cls(10, 'JobCoreService', [
func(12, 'CreateObject', [string, string, ObjectDescription, int], [int, string, int]),
])
cls(15, 'JobMgr', [ # jobmgr.ph:152
#func(11, 'JobMgr', [bool, string, string, string], []),
func(12, 'JobMgr', [bool, string, string, string, string], []),
func(14, 'RegisterNode', [string], []), # jobmgr.ph:164
func(18, 'Reserve', [ObjectDescription, int], [float, int]),
func(20, 'ExecObj', [string, ObjectDescription, int, int, int, string], [int, string, int]),
func(24, 'GetNodeAccessPoint', [], [string]), # jobmgr.ph:196
])
cls(20, 'AppCoreService', [
func(11, 'AppCoreService', [string, bool, string], [])
])
cls(1001, 'POPCSearchNode', [
func(11, 'POPCSearchNode', [string, bool], []), # popc_search_node.ph:51
func(13, 'setJobMgrAccessPoint', [string], []),
func(14, 'getJobMgrAccessPoint', [], [string]),
func(15, 'setPOPCSearchNodeId', [string], []),
func(16, 'getPOPCSearchNodeId', [], [string]),
func(17, 'setOperatingSystem', [string], []),
func(18, 'getOperatingSystem', [], [string]),
func(19, 'setPower', [float], []),
func(20, 'getPower', [], [float]),
func(23, 'setMemorySize', [float], []),
func(24, 'getMemorySize', [], [int]),
func(25, 'setNetworkBandwidth', [int], []),
func(26, 'getNetworkBandwidth', [], [int]),
func(33, 'addNeighbor', [POPCSearchNode], [POPCSearchNode]), # Something is wrong here
func(36, 'launchDiscovery', [Request, int], [array(POPCSearchNodeInfo)]),
func(37, 'askResourcesDiscovery', [Request, string, string], []),
func(38, 'callbackResult', [Response], []),
])
cls(1114117, 'ParentProcess', [
func(0, 'callback', [], [int, string]),
])
<file_sep>.. _advanced:
Advanced usage
==============
This section is intended for users which have already well understood the basic
concepts presented in the :ref:`first part <usage>` of the documentation and
are willing to customize a given testing environment to fulfill special needs.
By personalizing the environment using the directives presented in this
chapter, the ``pas`` tool as to be seen more as a framework for than as a
command line tool as the internals are much more exposed and it is possible
to interact directly with the basic building blocks of the same library used
by the built-in commands.
Four main arguments are presented in this chapter:
1. The creation of subcommands allows to add arbitrary commands to the ``pas``
utility by loading them from different locations and is described in the
first section;
2. The description of the python POP Parsing Domain Specific Language allows
to create new complex types and defines classes to perform payload decoding
of custom developed POP objects. This argument is treated in the second
section;
3. The third section introduces the assumptions the ``pas`` tool makes about
the guest system and indicates therefore how a real machine has to be
configured to being able to interact with the ``pas`` tool;
4. By describing how to add and configure additional virtual machines, the
understanding of the fourth section will let you create complex setups with
different virtual machines and running measures on them.
.. toctree::
command-subsystem
ppd-reference
real-machines
vagrant
<file_sep>project_type = :stand_alone
# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "../styles"
sass_dir = "."
images_dir = "../images"
javascripts_dir = "../scripts"
output_style = :expanded
# To enable relative paths to assets via compass helper functions. Uncomment:
relative_assets = true
<file_sep>Complex VM setups
=================
The standard configuration provides a master-salve virtual machine setup with
two virtual machines. It is clearly possible to add many more machines to a
test environment and the task is made very easy by the means provided by the
``vagrant`` tool.
The process of adding a new virtual machine to the system is a 3-step process:
1. Configure the new virtual machine inside the ``Vagrantfile`` by following
the `vagrant documentation <http://vagrantup.com/docs/multivm.html>`_ or
simply by copying one of the existing configuration blocks inside the
``Vagrantfile``, like the one presented in the following code snippet:
.. code-block:: ruby
config.vm.define :slaveX do |slaveX_config|
slaveX_config.vm.network "33.33.33.15"
slaveX_config.vm.provision :chef_solo do |chef|
chef.cookbooks_path = "conf/chef/cookbooks"
chef.roles_path = "conf/chef/roles"
chef.add_role "slave"
chef.json.merge!({:popc => {:version => "popc_1.3.1beta_xdr",}})
end
end
.. note::
If you opt for the copy and past approach, remember to change the IP
address and the name of the new virtual machine.
2. Boot up and provision the newly created virtual machine. To do so, simply
run::
$ vagrant up
3. Add the IP of the newly created virtual machine to the :data:`ROLES
<pas.conf.basesettings.ROLES>` settings directive inside the environment
specific settings file::
ROLES = {
'master': ['192.168.3.11'],
'client': ['33.33.33.10'],
'slaves': ['33.33.33.11', '33.33.33.15'],
}<file_sep>"""
Remote JobMgr management utilities.
The following functions provide some wrappers around remote shell commands to
easily start, stop, restart or otherwise interact with a POP-C++ job manager.
"""
import time
from pas import shell
from pas.conf import role
from pas.conf import settings
def start():
"""
Starts a JobMgr instance on one or more (depending on the current context)
remote nodes.
This function is intended to be used to start a single node. To start all
nodes of a system, use the startall function, which introduces some delays
to allow a correct registration of the slaves by the master.
"""
# Cleanup previsouly created log files
shell.remote('rm -f {0}'.format(" ".join(settings.LOG_FILES)), sudo=True)
# pty required to be set to true, otherwise the remote invocation hangs
# and never returns
shell.remote('SXXpopc start', pty=True, sudo=True)
def stop():
"""
Stops a currently running JobMgr instance on one or more (depending on the
current context) remote nodes.
This function is intended to be used to stop a single node. To stop all
nodes of a system, use the startall function, which introduces some delays
to allow a correct registration of the slaves by the master.
"""
shell.remote('SXXpopc stop', sudo=True)
def restart():
"""
Stops and restarts a currently running JobMgr instance on one or more
(depending on the current context) remote nodes in a unique command.
This function is intended to be used to restart a single node. To restart
all nodes of a system, use the startall function, which introduces some
delays to allow a correct registration of the slaves by the master.
"""
shell.remote('SXXpopc stop ; SXXpopc start', pty=True, sudo=True)
def kill():
"""
Kills ALL running job managers (and the relative search nodes) on the
hosts provided by the context or (by default) on all known hosts.
"""
with shell.ignore_warnings():
shell.remote('pkill "jobmgr|popc_*"', sudo=True)
def startall():
"""
Starts all nodes of the system grouped by roles with the necessary delays
to allow a proper registration to the parent JobMgr.
The delay between the invocations can be set in the settings.
"""
# Start all masters before, allowing for a proper setup before registering
# a new slave
with shell.workon(role('master')):
start()
# Wait some (configurable) time. One or two seconds should be enough here
time.sleep(settings.STARTUP_DELAY)
# And now start the slaves
with shell.workon(role('slaves')):
start()
# Wait again some time for possible subsequent programs execution
time.sleep(settings.STARTUP_DELAY)
def stopall():
"""
Stops all nodes of the system grouped by roles with the necessary delays
to allow a proper registration to the parent JobMgr.
The delay between the invocations can be set in the settings.
Note that in this case the delays are not as important as in the start
function on could probably safely be omitted. The behavior is preserved to
grant compatibility with future versions of the JobMgr which possibly
wants to execute some cleanup code before terminating.
In the meanwhile it is possible to set the delay to 0 in the settings.
"""
with shell.workon(role('slaves')):
stop()
time.sleep(settings.SHUTDOWN_DELAY)
with shell.workon(role('master')):
stop()
time.sleep(settings.SHUTDOWN_DELAY)
def restartall():
"""
Restarts all nodes in the system using the stopall and startall functions.
Due to the introduction of the delays, the stop and start calls will not
happen in the same command as for the restart function.
"""
stopall()
startall()
def killall():
"""
Alias for the kill function, as no special treatment is needed here.
"""
kill()
<file_sep>#include "simple.ph"
#define OBJCOUNT 2
int main(int argc, char** argv) {
POPCobject o;
for (int i = 0; i < OBJCOUNT; i++) {
printf("The value is: %d\n", o.get());
}
return 0;
}
<file_sep>package "g++"
package "zlib1g-dev"
require_recipe "misc::sudo_path"
path = node[:vagrant][:config][:vm][:shared_folders][:contrib][:guestpath]
version = node[:popc][:version]
config = node[:popc][:config]
execute "get-popc-source" do
user "vagrant"
command <<-EOH
rm -rf /tmp/popc
cp -R #{path}/#{version} /tmp/popc
chmod +x /tmp/popc/configure
EOH
end
# Copy the node config file and install popc
cookbook_file "/tmp/popc-node-config" do
source config
owner "vagrant"
end
cookbook_file "/tmp/popc-node-paths" do
source "paths"
owner "vagrant"
end
execute "compile-popc" do
user "vagrant"
cwd "/tmp/popc"
command <<-EOH
./configure
make
EOH
end
execute "install-popc" do
cwd "/tmp/popc"
command "make install </tmp/popc-node-config"
end
execute "update-popc-path" do
command "cat /tmp/popc-node-paths >>/etc/profile"
not_if "grep \"$(cat /tmp/popc-node-paths)\" /etc/profile"
end
execute "update-root-popc-path" do
command "cat /tmp/popc-node-paths >>/root/.bashrc"
not_if "grep \"$(cat /tmp/popc-node-paths)\" /root/.bashrc"
end
# This configuration step is needed because the `make install` command
# consumes the stdin before reaching the configuration step
execute "setup-popc" do
command "/usr/local/popc/sbin/popc_setup </tmp/popc-node-config"
end
file "/tmp/popc-*" do
action :delete
backup false
end
<file_sep>package "xsltproc"
<file_sep>"""
``pas`` provides a set of default configuration directives (explained in detail
below). All of these settings can be modified (and new directives added) by
overriding them in the environment-specific ``settings.py`` file.
The ``pas`` command line tool automatically loads these directives at startup
and then, once read the ``--settings`` command line options, will load the
environment-specific settings file letting it override the already defined
values or adding new ones (for example for your :ref:`command-subsystem`).
The syntax of the settings file is simple: each uppercase public (not starting
with an underscore) member is set as an attribute of the global ``Settings``
object.
"""
# Please don't alter the values inside this file, as these can be customized
# and overridden in the environment level settings module.
VM_USER = 'vagrant'
"""
Username to use to connect to a remote machine through ``ssh``.
"""
VM_PASSWORD = '<PASSWORD>'
"""
Password to use to connect to a remote machine through ``ssh``, is only used
if ``publickey`` authentication is not available or if it fails.
"""
ROLES = {
'master': [],
'client': [],
'slaves': [],
}
"""
A mapping of role names to IP addresses. The roles are defined as follows:
master
Guest machines running a jobmgr instance configured as a master node. The
job managers on these machines are started before and stopped after the job
managers on slave machines.
Normally these machines run a job manager configured with 0 available object
slots, in order to delegate parallel objects execution to slaves.
slaves
Guest machines running a jobmgr instance configured as a slave node. The job
managers on these machines are started after and stopped before the job
managers on master machines.
client
Machines on which the measure case if first started.
.. note::
An IP address can appear more than one time in different roles. For example,
a master node can also be a client (this is the default for newly created
environments).
"""
INTERFACES = {
'master': ['eth1', 'lo'],
'slaves': ['lo'],
'client': [],
}
"""
A mapping of role names to interfaces. A measure will be started for each
interface of each machine of a given role. The :func:`pas.conf.map_interfaces`
function provides an easy way to create a list of
(``hostname``, ``interfaces``) tuples.
"""
CAPTURE_FILTER = "'tcp and not tcp port 22'"
"""
Capture filter to use with the ``tshark`` command line tool when running a new
measure. Note that this is different from the display filter directive (and
also uses a different syntax).
The `capture filters <http://wiki.wireshark.org/CaptureFilters>`_ page on the
wireshark wiki provides more informations about this specific syntax.
The default filter captures all TCP traffic excluding ``ssh`` connections on
the default port (22).
"""
DISPLAY_FILTER = "'" + ' || '.join((
"tcp.flags.syn == 1",
"tcp.flags.push == 1",
"tcp.flags.fin == 1",
"tcp.flags.ack == 1"
)) + "'"
"""
Display filters to use with the ``tshark`` command line tool when converting
the measures to xml. Note that this is different from the capture filter
directive (and also uses a different syntax).
The `display filters <http://wiki.wireshark.org/DisplayFilters>`_ page on the
wireshark wiki provides more informations about this specific syntax.
The default filter actually does not filter anything (all non tcp traffic is
already filtered out by the capture filter) but provides a good starting point
for advanced tcp filtering.
.. note::
It is considered good practice to move as much filtering as possible to the
capture phase. Sadly the capture filters don't offer the powerful filtering
expressions which are indeed possible using the display filters syntax.
"""
LOG_FILES = (
'/tmp/jobmgr_stdout_*',
'/tmp/jobmgr_stderr_*',
'/tmp/paroc_service_log',
'/tmp/popc_node_log',
)
"""
List of path to log files on the remote host which have to be copied along with
the measures during the collect phase.
The paths are copied using a simple ``cp`` command, it is thus possible to
use shell variables and substitutions pattern therein.
.. note::
The :py:mod:`pas.commands.jobmgr.start` command deletes these files each
time it is executed.
"""
PATHS = {
'test-cases': ['cases', '/share/test-cases'],
'configuration': ['conf', '/share/conf'],
'local-measures': [None, '/measures'],
'shared-measures': ['reports', '/share/measures'],
}
"""
General path configuration. Contains a mapping between symbolic path name (i.e.
``test-cases``) to a tuple of its local (i.e. ``cases``) and remote (i.e.
``/share/test-cases``) equivalent.
With the exception of the ``local-meaures`` entry, these path are all shared
using the ``Vagrantfile`` ``config.vm.share_folder`` directive.
.. note::
This settings directive is available mainly to centralize the path
configuration and is not meant to be modified. Override these values only
if you are sure of what you are doing.
"""
STARTUP_DELAY = 2
"""
Delay to introduce between master ``jobmgr`` startup and slave ``jobmgr``
startup, in seconds.
"""
SHUTDOWN_DELAY = 2
"""
Delay to introduce between slave ``jobmgr`` shutdown and master ``jobmgr``
shutdown, in seconds.
"""
COMMAND_DIRECTORIES = (
'commands',
)
"""
List of external directories to scan for additional commands. Refer to the
:ref:`command-subsystem` document for more information about the creation and
use of custom commands.
"""
<file_sep>PAS - POP Analysis Suite
========================
A protocol and communication analyzer for the POP (Parallel Object Programming)
model.<file_sep># Install from remote location
remote_file "popc" do
path "/tmp/popc.tar.gz"
source "http://gridgroup.hefr.ch/popc_1.3.1beta.tgz"
end
bash "untar-popc" do
code "(rm -rf /tmp/popctmp ; rm -rf /tmp/popc ; mkdir -p /tmp/popctmp)"
code "(tar -zxvf /tmp/popc.tar.gz -C /tmp/popctmp)"
code "(mv /tmp/popctmp/* /tmp/popc ; rm -rf /tmp/popctmp)"
end
<file_sep>.. _ppd-builtin:
Built-in parser types
=====================
The base parser implementation comes with a rich collection of both scalar and
composite built-in types and classes to decode standard POP messages not
involving newly defined classes.
Scalars
-------
The set of provided scalars include:
.. c:type:: string
A simple ``parocstring`` XDR compatible decoder.
.. c:type:: uint
.. c:type:: int
.. c:type:: float
.. c:type:: popbool
POP specific boolean decoder.
The POP-C++ implementation doesn't encode booleans as defined by the XDR RFC.
This alternate implementation provides a workaround.
.. c:type:: bool
The XDR compliant equivalent of the ``popbool`` primitive.
Compound types
--------------
The set of provided complex and compound types include:
.. c:type:: accesspoint
.. c:member:: string endpoint
.. c:type:: NodeInfo
.. c:member:: string nodeId
.. c:member:: string operatingSystem
.. c:member:: float power
.. c:member:: int cpuSpeed
.. c:member:: float memorySize
.. c:member:: int networkBandwidth
.. c:member:: int diskSpace
.. c:member:: string protocol
.. c:member:: string encoding
.. c:member:: ExplorationListNode[] ExplorationList
.. c:type:: ExplorationListNode
.. c:member:: string nodeId
.. c:member:: array(string) visited
.. c:type:: ObjectDescription
.. c:member:: float power0
.. c:member:: float power1
.. c:member:: float memory0
.. c:member:: float memory1
.. c:member:: float bandwidth0
.. c:member:: float bandwidth1
.. c:member:: float walltime
.. c:member:: int manual
.. c:member:: string cwd
.. c:member:: int search0
.. c:member:: int search1
.. c:member:: int search2
.. c:member:: string url
.. c:member:: string user
.. c:member:: string core
.. c:member:: string arch
.. c:member:: string batch
.. c:member:: string joburl
.. c:member:: string executable
.. c:member:: string platforms
.. c:member:: string protocol
.. c:member:: string encoding
.. c:member:: dict(string, string) attributes
.. c:type:: Request
.. c:member:: string uid
.. c:member:: int maxHops
.. c:member:: optional(string) nodeId
.. c:member:: optional(string) operatingSystem
.. c:member:: optional(int) minCpuSpeed
.. c:member:: optional(int) hasExpectedCpuSpeedSet
.. c:member:: optional(float) minMemorySize
.. c:member:: optional(float) expectedMemorySize
.. c:member:: optional(int) minNetworkBandwidth
.. c:member:: optional(int) expectedNetworkBandwidth
.. c:member:: optional(int) minDiskSpace
.. c:member:: optional(int) expectedDiskSpace
.. c:member:: optional(float) minPower
.. c:member:: optional(float) expectedPower
.. c:member:: optional(string) protocol
.. c:member:: optional(string) encoding
.. c:member:: ExplorationList explorationList
.. c:type:: Response
.. c:member:: string uid
.. c:member:: NodeInfo nodeInfo
.. c:member:: ExplorationList explorationList
.. c:type:: POPCSearchNode
.. c:member:: ObjectDescription od
.. c:member:: accesspoint accesspoint
.. c:member:: int refcount
.. c:type:: POPCSearchNodeInfo
.. c:member:: string nodeId
.. c:member:: string operatingSystem
.. c:member:: float power
.. c:member:: int cpuSpeed
.. c:member:: float memorySize
.. c:member:: int networkBandwidth
.. c:member:: int diskSpace
.. c:member:: string protocol
.. c:member:: string encoding
Classes
-------
The set of provided classes include:
.. py:class:: paroc_service_base
.. py:method:: BindStatus() -> int, string, string
.. py:method:: AddRef() -> int
.. py:method:: DecRef() -> int
.. py:method:: Encoding(string) -> bool
.. py:method:: Kill() -> void
.. py:method:: ObjectAlive() -> bool
.. py:method:: ObjectAlive() -> void
.. py:method:: Stop(string) -> bool
.. py:class:: CodeMgr
.. py:method:: RegisterCode(string, string, string) -> void
.. py:method:: QueryCode(string, string) -> string, int
.. py:method:: GetPlatform(string) -> string, int
.. py:class:: RemoteLog
.. py:method:: Log(string) -> void
.. py:class:: ObjectMonitor
.. py:method:: ManageObject(string) -> void
.. py:method:: UnManageObject(string) -> void
.. py:method:: CheckObjects() -> int
.. py:class:: JobCoreService
.. py:method:: CreateObject(string, string, ObjectDescription, int) -> int, string, int
.. py:class:: JobMgr
.. py:method:: JobMgr(bool, string, string, string, string) -> void
.. py:method:: RegisterNode(string) -> void
.. py:method:: Reserve(ObjectDescription, int) -> float, int
.. py:method:: ExecObj(string, ObjectDescription, int, int, int, string) -> int, string, int
.. py:method:: GetNodeAccessPoint() -> string
.. py:class:: AppCoreService
.. py:method:: AppCoreService(string, bool, string) -> void
.. py:class:: POPCSearchNode
.. py:method:: POPCSearchNode(string, bool) -> void
.. py:method:: setJobMgrAccessPoint(string) -> void
.. py:method:: getJobMgrAccessPoint() -> string
.. py:method:: setPOPCSearchNodeId(string) -> void
.. py:method:: getPOPCSearchNodeId() -> string
.. py:method:: setOperatingSystem(string) -> void
.. py:method:: getOperatingSystem() -> string
.. py:method:: setPower(float) -> void
.. py:method:: getPower() -> float
.. py:method:: setMemorySize(float) -> void
.. py:method:: getMemorySize() -> int
.. py:method:: setNetworkBandwidth(int) -> void
.. py:method:: getNetworkBandwidth() -> int
.. py:method:: addNeighbor(POPCSearchNode) -> POPCSearchNode
.. py:method:: launchDiscovery(Request, int) -> array of POPCSearchNodeInfo
.. py:method:: askResourcesDiscovery(Request, string, string) -> void
.. py:method:: callbackResult(Response) -> void
.. py:class:: ParentProcess
.. py:method:: callback() -> int, string
.. note::
For the provided classes not all methods are defined yet. The provided
definitions suffices for most basic measures involving other external
types, but it can be that some requests for more specific measures could not
be decoded without extending the method definitions.
<file_sep>import sys
import os
import imp
from pas.parser import errors
current_registry = None
class TypesRegistry(object):
def __init__(self):
self.classes = dict()
self.exceptions = dict()
def register_class(self, cls):
self.classes[cls.id] = cls
def register_exception(self, exc):
self.exceptions[exc.id] = exc
def get_class(self, classid):
try:
return self.classes[classid]
except KeyError:
raise errors.UnknownClass(classid)
def get_exception(self, excid):
try:
return self.exceptions[excid]
except KeyError:
raise errors.UnknownException(excid)
def load(self, module_name):
global current_registry
current_registry = self
__import__(module_name)
current_registry = None
def parse(self, module_path):
global current_registry
path, module_file = os.path.split(module_path)
module_name = module_file.rsplit('.', 1)[0]
current_registry = self
imp.load_source(module_name, module_path)
current_registry = None
<file_sep>(function ($) {
$.fn.spawnHeight = function (parent) {
var elements = this,
$parent = $(parent),
_blocks = [],
$blocks,
height,
_onResize;
for (var i = 1; i<arguments.length; i++) {
_blocks[i-1] = $(arguments[i]);
}
$blocks = $(_blocks);
_onResize = function () {
height = $blocks.sumHeight()
elements.each(function () {
$(this).height($parent.height() - height);
});
};
$(window).resize(_onResize);
_onResize();
};
$.fn.lockDimensions = function (type) {
return this.each(function() {
var $this = $(this);
if ( !type || type == 'width' ) {
$this.width( $this.width() );
}
if ( !type || type == 'height' ) {
$this.height( $this.height() );
}
});
};
$.fn.sumHeight = function () {
var sum = 0;
this.each(function () {
sum += $(this).outerHeight(true);
});
return sum;
};
})(jQuery);<file_sep>"""
Measure management functions.
"""
import binascii
import errno
import glob
import os
import shutil
import xdrlib
from datetime import datetime
from pas import conf
from pas import tshark
from pas import shell
from pas import xml
from pas.conf import settings
from pas.conf import map_interfaces
from pas.conf import role
from pas.conf import stylesheet
from pas.parser import errors
from pas.parser import registry
from pas.parser import protocol
from lxml import etree
def select(name=None, basedir=None):
"""
Scans the basedir (or the shared-measures directory defined in the
settings) for directories and returns a choice based on different
criteria:
1. No directories are found; raise a RuntimeError
2. The name is set; check if it was found and if so return it
3. Only one directory is found; return the found directory
4. Multiple directories are found; ask the user to pick one
"""
name = name.rsplit('_', 2) if name else ()
if not basedir:
basedir = settings.PATHS['shared-measures'][0]
# Get all files in the directory
paths = os.listdir(basedir)
# Rebuild the full path name
paths = [(os.path.join(basedir, p), p.rsplit('_', 2)) for p in paths]
# Filter out non-directories
paths = [p for p in paths if os.path.isdir(p[0])]
# If no entries remained, there are no test cases which can be run
if not paths:
raise RuntimeError("No test cases found.")
# Check to see if chosen value exists in the available paths
if name:
for path in paths:
if path[1] == name:
return path[0], '_'.join(path[1])
else:
# Continue with selecting phase
# @TODO: log
print "The chosen path is not available."
# There is not much to choose here
if len(paths) == 1:
# @TODO: log
print "\nOnly one measure found: {0} ({1} at {2}).".format(*paths[0][1])
path = paths[0]
return path[0], '_'.join(path[1])
# Present a list of choices to the user (paths must now contain more than
# one item)
print "\nMultiple measures found:\n"
for i, (path, name) in enumerate(paths):
index = '[{}]'.format(i)
print '{0:>8s}: {1} ({2} at {3})'.format(index, *name)
def valid(index):
"""
Returns the correct entry in the paths list or asks for a correct
value if the index is outside the boundaries.
"""
try:
path = paths[int(index)]
return path[0], '_'.join(path[1])
except (IndexError, ValueError):
raise Exception("Enter an integer between 0 " \
"and {0}.".format(len(paths)-1))
print
return shell.prompt("Select a measure:", validate=valid)
def start(name):
"""
Start a new named measure session in background on all interested hosts.
The hosts are retrieved from the ROLES setting directive and a
measure is started for each one.
"""
dest = settings.PATHS['local-measures'][1]
fltr = settings.CAPTURE_FILTER
for host, interfaces in map_interfaces():
with shell.workon(host):
shell.remote('rm -rf {0} ; mkdir {0}'.format(dest), sudo=True)
for i in interfaces:
mname = '{0}.{1}'.format(name, i)
tshark.start(mname, i, '{0}/{1}.raw'.format(dest, mname), fltr)
def stop(name):
"""
Start a new named measure session in background on all interested hosts.
As for the start function, the hosts are retrieved from the interfaces
setting directive and the stop command issued on each one.
"""
for host, interfaces in map_interfaces():
with shell.workon(host):
for i in interfaces:
tshark.stop(name, i)
def kill():
"""
Alias for tshark.kill
"""
return tshark.kill()
def collect(name, overwrite=False):
"""
Moves the relevant files to the shared directory by asking to empty the
destination directory if needed.
"""
ipaddr = '$(getip eth1)'
name = "{0}_{1}".format(name, datetime.now().strftime('%Y-%m-%d_%H:%M'))
guest_local = settings.PATHS['local-measures'][1]
host_shared, guest_shared = settings.PATHS['shared-measures']
destination = os.path.join(guest_shared, name, ipaddr)
local = os.path.realpath(os.path.join(host_shared, name))
try:
if os.listdir(local):
print "A directory with the same name ({0}) already " \
"exists.".format(name)
if overwrite or shell.confirm("Would you like to replace it?"):
shell.local('rm -rf {0}/*'.format(local))
else:
raise OSError(errno.ENOTEMPTY, "Directory not empty")
except OSError as e:
# If the file or directory don't exist, consume the exception
if e.errno != errno.ENOENT:
raise
shell.remote('chown -R {0}:{0} {1}'.format(settings.VM_USER, guest_local),
sudo=True)
shell.remote('mkdir -p "{0}/logs"'.format(destination))
shell.remote('cp {0}/* "{1}"'.format(guest_local, destination))
# Copy log files
for logfile in settings.LOG_FILES:
shell.remote('chown {0}:{0} "{1}" || true'.format(settings.VM_USER,
logfile), sudo=True)
shell.remote('cp "{0}" "{1}/logs" || true'.format(logfile,
destination))
def toxml(name):
"""
Converts all raw measure files for the given measure to xml using a remote
tshark command.
This will overwrite all already converted files with matching names.
"""
host_shared, guest_shared = settings.PATHS['shared-measures']
pattern = os.path.join(host_shared, name, "*", "*.raw")
paths = glob.glob(pattern)
paths = (guest_shared + path[len(host_shared):] for path in paths)
with shell.workon(role('client')):
for path in paths:
tshark.pcaptoxml(path, path.replace('.raw', '.xml'),
settings.DISPLAY_FILTER)
def simplify(name, prettyprint=True):
"""
Simplifies all the measure files in pdxml format of the given measure,
converting them using the simplify XSL stylesheet. Old simplifications
will be overwritten.
If the prettyprint optional argument is True, the result will be formatted
using the xmllint tool.
"""
host_shared = settings.PATHS['shared-measures'][0]
pattern = os.path.join(host_shared, name, "*", "*.xml")
simplifier = xml.Transformation(stylesheet('simplify.xsl'))
for source in glob.glob(pattern):
if len(os.path.basename(source).split('.')) == 3:
dest = source.replace('.xml', '.simple.xml')
simplifier.parameters['loopback'] = str(int(source.endswith(
'.lo.xml')))
simplifier.transform(source, dest)
if prettyprint:
xml.prettyprint(dest)
def decode(name, measure_case, prettyprint=False):
"""
Decodes the simplified XML representation of the given measure by adding
a "decoded" element to each packet containing a payload.
The decoding is done using an XSL transformation coupled with an xslt
python extension function which provides the "decoded" element given a
payload text string.
"""
host_shared = settings.PATHS['shared-measures'][0]
types = os.path.join(measure_case, "types.py")
types_registry = registry.TypesRegistry()
types_registry.load('pas.conf.basetypes')
try:
types_registry.parse(types)
except IOError:
pass
proto = protocol.MappingProtocol(types_registry)
trans = xml.Transformation(stylesheet('decode.xsl'))
def _decode(context, payload):
"""
Decoding callback
"""
# Convert the ascii representation back to binary data
bin_payload = binascii.a2b_hex(''.join(payload))
# Create an xdr stream with the payload
stream = xdrlib.Unpacker(bin_payload)
# Read the full frame length, it is not needed here
_ = stream.unpack_uint()
try:
# Decode the remaining data as a full frame...
# ...hoping that tcp hasn't split the message in more frames
message = proto.decode_full_frame(stream)
# @TODO: Logging, output and error management
except EOFError as e:
print "-" * 80
print context, "Not enough data:", e
print repr(stream.get_buffer())
print "-" * 80
return
except errors.UnknownClass as e:
print "-" * 80
print context.context_node.attrib['timestamp'],
print "Error while decoding packet:", e
print binascii.b2a_hex(stream.get_buffer())
print "-" * 80
return
except errors.UnknownMethod as e:
print "-" * 80
print context.context_node.attrib['timestamp'],
print "Error while decoding packet:", e
print binascii.b2a_hex(stream.get_buffer())
print "-" * 80
return
except xdrlib.Error as e:
print "-" * 80
print context.context_node.attrib['timestamp'], e
print repr(e.message)
rest = stream.get_buffer()
rem = stream.get_position()
print binascii.b2a_hex(rest[rem:])
print
print repr(rest[rem:])
print
print str(rem) + "/" + str(_)
print "*" * 80
return
# Convert the message to xml and send it back to the XSL template
return message.toxml()
trans.register_function('http://gridgroup.eia-fr.ch/popc',
_decode, 'decode')
# Apply transformation to all simplified xml files
pattern = os.path.join(host_shared, name, "*", "*.simple.xml")
for source in glob.glob(pattern):
dest = source.replace('.simple.xml', '.decoded.xml')
trans.transform(source, dest)
if prettyprint:
xml.prettyprint(dest)
def report(name, measure_case):
"""
Assembles all the acquired resources (such as source code, measures and
log files) and generates an html page suitable for human interaction and
analysis.
"""
host_shared = settings.PATHS['shared-measures'][0]
trans = xml.Transformation(stylesheet('report.xsl'))
def sources(_):
els = etree.Element('files')
base = len(measure_case)+1
for root, dirs, files in os.walk(measure_case):
print root
for f in files:
if f.endswith(('.pyc', '.DS_Store', '.o')):
continue
path = os.path.join(root, f)
name = path[base:]
if name.startswith('build/'):
continue
element = etree.SubElement(els, 'file')
element.attrib['path'] = path
element.attrib['name'] = name
return els
trans.register_function('http://gridgroup.eia-fr.ch/popc', sources)
def logs(_):
els = etree.Element('files')
basel = len(os.path.join(settings.ENV_BASE, host_shared, name))
base = os.path.join(settings.ENV_BASE, host_shared, name, '*.*.*.*', 'logs', '*')
for log in glob.glob(base):
element = etree.SubElement(els, 'file')
element.attrib['path'] = log
element.attrib['name'] = log[basel+1:]
return els
trans.register_function('http://gridgroup.eia-fr.ch/popc', logs)
def format_stream(_, payload):
"""
Stream formatting xslt callback
"""
payload = ''.join(payload)
def chunks(seq, n):
""" Yield successive n-sized chunks from l.
"""
for i in xrange(0, len(seq), n):
yield seq[i:i+n]
element = etree.Element('pre')
payload = ' '.join(chunks(payload, 2))
payload = ' '.join(chunks(payload, 12))
payload = '\n'.join(chunks(payload, 104))
for chunk in chunks(payload, 420):
etree.SubElement(element, 'span').text = chunk
return element
trans.register_function('http://gridgroup.eia-fr.ch/popc', format_stream)
class Highlighter(etree.XSLTExtension):
def execute(self, context, self_node, input_node, output_parent):
from pygments import highlight
from pygments import lexers
from pygments.formatters import HtmlFormatter
# Highlight source text with pygments
source = input_node.attrib['path']
with open(source) as fh:
code = fh.read()
# Chose a lexer
name = os.path.split(source)[1]
if name == 'Makefile':
lexer = lexers.BaseMakefileLexer()
elif name.endswith('.py'):
lexer = lexers.PythonLexer()
elif name.endswith(('.cc', '.ph', '.h')):
lexer = lexers.CppLexer()
elif name.endswith(('.c',)):
lexer = lexers.CLexer()
else:
lexer = lexers.TextLexer()
# Highlight code
highlighted = highlight(
code, lexer, HtmlFormatter(cssclass="codehilite", style="pastie", linenos='table')
)
# Convert to xml
root = etree.fromstring(highlighted)
# Add to parent
output_parent.extend(root)
trans.register_element('http://gridgroup.eia-fr.ch/popc', 'highlighted', Highlighter())
destination = os.path.join(host_shared, name, 'report')
shutil.rmtree(destination, True)
shell.local("mkdir -p {0}".format(destination))
pattern = os.path.join(host_shared, name, "*", "*.decoded.xml")
for source in glob.glob(pattern):
base, measure = os.path.split(source)
interface = measure.rsplit('.', 3)[1]
ip = os.path.basename(base).replace('.', '-')
dest = os.path.join(destination, '{0}_{1}.html'.format(ip, interface))
trans.transform(source, dest)
# Tidy
tconf = "conf/tidy/tidy.conf"
shell.local('tidy -config {1} -o {0} {0} || true'.format(dest, tconf))
# Copy resources
htdocs = os.path.join(os.path.dirname(conf.__file__), 'htdocs')
#shell.local("ln -s {0} {1}".format(os.path.join(htdocs, 'styles'),
# os.path.join(destination, 'styles')))
#shell.local("ln -s {0} {1}".format(os.path.join(htdocs, 'images'),
# os.path.join(destination, 'images')))
#shell.local("ln -s {0} {1}".format(os.path.join(htdocs, 'scripts'),
# os.path.join(destination, 'scripts')))
shutil.copytree(
os.path.join(htdocs, 'styles'),
os.path.join(destination, 'styles')
)
shutil.copytree(
os.path.join(htdocs, 'images'),
os.path.join(destination, 'images')
)
shutil.copytree(
os.path.join(htdocs, 'scripts'),
os.path.join(destination, 'scripts')
)
<file_sep>"""
Package containing all command line utilities bound to the pas library.
"""<file_sep>MEASURE_NAME=$(EXEC)
run:
$(call header,Running measure)
@echo "\n 1. Starting measures and services"
@pas measure start $(INDENT)
@pas jobmgr start $(INDENT)
@echo " OK."
@echo "\n 2. Running test case"
@pas execute $(EXEC) $(INDENT)
@echo " OK."
@echo "\n 3. Stopping measures and services"
@pas jobmgr stop $(INDENT)
@pas measure stop $(INDENT)
@echo " OK."
@echo "\n 4. Collecting results"
@pas measure collect $(MEASURE_NAME) $(INDENT)
@echo " OK."
$(call done)
report:
$(call header,Reporting measure)
@echo "\n 1. Converting measures to xml"
@pas report toxml $(MEASURE_NAME) $(INDENT)
@echo " OK."
@echo "\n 2. Simplifying measures"
@pas report simplify $(MEASURE_NAME) $(INDENT)
@echo " OK."
@echo "\n 3. Decoding measures"
@pas report decode $(MEASURE_NAME) $(INDENT)
@echo " OK."
@echo "\n 4. Generating report"
@pas report report $(MEASURE_NAME) $(INDENT)
@echo " OK."
include $(ENV_BASE)/conf/Makefile.base<file_sep>import __builtin__
from pas.parser import registry, errors
import xdrlib
from collections import namedtuple
from lxml import etree
# pylint: disable-msg=C0103,C0111
class cls(object):
"""
Allows to define and automatically register a new POP class.
:param id: The classid to which this class will be mapped.
:param name: The name to use as string representation of this class.
Normally its the original class name.
:param methods: The list of methods bound to an instance of this class.
:type id: int
:type name: ``str`` or ``unicode`` compatible object
:type methods: list of :func:`pas.parser.types.func` objects
"""
def __init__(self, id, name, methods):
self.id = id
self.name = name
self.methods = __builtin__.dict([(m.id, m) for m in methods])
registry.current_registry.register_class(self)
def __str__(self):
return self.name
def getmethod(self, methodid):
try:
return self.methods[methodid]
except KeyError:
raise errors.UnknownMethod(self, methodid)
class exc(cls):
"""
Allows to define and automatically register a new POP exception type.
:param id: The exception ID to which this exception will be mapped.
:param name: The name to use as string representation of this exception.
Normally its always the original exception name.
:param properties: The list of properties bound to an instance of this
exception.
:type id: int
:type name: ``str`` or ``unicode`` compatible object
:type properties: list of POP Parser DSL types
"""
def __init__(self, id, name, properties):
self.id = id
self.name = name
self.properties = properties
registry.current_registry.register_exception(self)
def arguments(self, decoder):
return [p(decoder) for p in self.properties]
class func(object):
"""
Allows to define a new POP method bound to a specific class instance. The
method itself will never know to which class it belongs; to bind a method
to a class insert it in the ``methods`` argument at class declaration time.
:param id: The method ID to which this method will be mapped.
:param name: The name to use as string representation of this method.
Normally its always the original method name.
:param args: A list of arguments taken by this method. The provided types
will be directly used to decode the payload. Any built-in or
custom defined scalar or complex type is accepted.
:param retypes: A list of types of the values returned by this method. The
provided types will be directly used to decode the payload.
Any built-in or custom defined scalar or complex type is
accepted.
Note that an ``[out]`` argument will be present in the
POP response and shall thus be inserted into the
``retypes`` list.
:type id: int
:type name: ``str`` or ``unicode`` compatible object
:type args: list of POP Parser DSL types
:type retypes: list of POP Parser DSL types
"""
def __init__(self, id, name, args, retypes):
self.id = id
self.name = name
self.retypes = retypes
self.args = args
def toxml(self):
el = etree.Element('method')
attrs = el.attrib
attrs['id'] = str(self.id)
attrs['name'] = self.name
return el
def __str__(self):
return self.name
def arguments(self, decoder):
return [a(decoder) for a in self.args]
def result(self, decoder):
return [r(decoder) for r in self.retypes]
def string(stream):
return stream.unpack_string()[:-1]
def uint(stream):
return stream.unpack_uint()
def int(stream):
return stream.unpack_int()
def popbool(stream):
"""
The POP-C++ implementation doesn't encode booleans as defined by the RFC.
This alternate implementation provides a workaround.
"""
return __builtin__.bool(stream.unpack_int() & 0xff000000)
def bool(stream):
return stream.unpack_bool()
def float(stream):
return stream.unpack_float()
def compound(name, *parts):
"""
Creates a new compound type consisting of different parts. The parts are
specified by the ``parts`` argument and read one adter the other from the
POP payload.
:param name: The name to give to the new type, used when pretty printing
the value.
:param parts: The actual definition of the compound type.
:type parts: list of ``(name, type)`` tuples
Use it like this::
NewType = compound('NewTypeName',
('member_1', string),
('member_2', int),
('member_3', float)
# ...
)
"""
model = namedtuple(name, ' '.join(p[0] for p in parts))
def decoder(stream):
return model(**__builtin__.dict([(name, type(stream)) for name, type in parts]))
return decoder
def dict(key, value):
"""
Creates a new complex type mapping keys to values. All keys will share the
same value type and so will all values.
:param key: The type to use to decode the key.
:param value: The type to use to decode the value.
Use it like this::
# SomeCompoundType.dict_member will hold a mapping of strings to integers
SomeCompoundType = compound('SomeCompountTypeName',
# ...other members...
('dict_member', dict(string, float)),
)
"""
def decoder(stream):
return __builtin__.dict([(key(stream), value(stream)) for i in range(int(stream))])
return decoder
def array(type):
"""
Creates a new complex type representing a length prefixed array of
homogeneous items.
:param type: The type of each item in the array.
Use it like this::
# SomeCompoundType.array_member will hold a variable length array of ints
SomeCompoundType = compound('SomeCompountTypeName',
# ...other members...
('array_member', array(int)),
)
"""
# Work around to the standard xdrlib to provide the argument to the type
# function as it is not passed by the unpack_farray method of the Unpacker
# class. @see xdrlib.py:224
# @todo: Discuss on py-dev about a possible improvement.
def unpack(stream):
def unpacker():
return type(stream)
return stream.unpack_array(unpack_item=unpacker)
return unpack
def optional(type, unpack_bool=popbool):
"""
Special composer type which allows to declare a structure member as
optional. An optional member is member prefixed by a ``bool`` flag; the
flag is first read, if it yields ``true``, it means that the value was
encoded and it can be read, if it yields ``false``, it means that no value
was encoded and the member is skipped.
:param type: The type of the optional value.
:param unpack_bool: The type to use to decode the boolean flag. Defaults
to :c:type:`popbool`, but can be changed to ``bool`` if
the encoding is done in an RPC compliant way.
:type unpack_bool: callable
Use it like this::
# SomeCompoundType.optional_member will hold a string if it was encoded
# or None if it was not encoded
SomeCompoundType = compound('SomeCompountTypeName',
# ...other members...
('optional_member', string),
)
"""
def unpack(stream):
if unpack_bool(stream):
return type(stream)
else:
return None
return unpack
accesspoint = compound('AccessPoint',
('endpoint', string)
)
NodeInfo = compound('NodeInfo',
('nodeId', string),
('operatingSystem', string),
('power', float),
('cpuSpeed', int),
('memorySize', float),
('networkBandwidth', int),
('diskSpace', int),
('protocol', string),
('encoding', string)
)
ExplorationList = array(
compound('ListNode',
('nodeId', string),
('visited', array(string))
)
)
ObjectDescription = compound('ObjectDescription',
('power0', float),
('power1', float),
('memory0', float),
('memory1', float),
('bandwidth0', float),
('bandwidth1', float),
('walltime', float),
('manual', int),
('cwd', string),
('search0', int),
('search1', int),
('search2', int),
('url', string),
('user', string),
('core', string),
('arch', string),
('batch', string),
('joburl', string),
('executable', string),
('platforms', string),
('protocol', string),
('encoding', string),
('attributes', dict(string, string))
)
Request = compound('Request',
('uid', string),
('maxHops', int),
('nodeId', optional(string)),
('operatingSystem', optional(string)),
('minCpuSpeed', optional(int)),
('hasExpectedCpuSpeedSet', optional(int)),
('minMemorySize', optional(float)),
('expectedMemorySize', optional(float)),
('minNetworkBandwidth', optional(int)),
('expectedNetworkBandwidth', optional(int)),
('minDiskSpace', optional(int)),
('expectedDiskSpace', optional(int)),
('minPower', optional(float)),
('expectedPower', optional(float)),
('protocol', optional(string)),
('encoding', optional(string)),
('explorationList', ExplorationList)
)
Response = compound('Response',
('uid', string),
('nodeInfo', NodeInfo),
('explorationList', ExplorationList)
)
POPCSearchNode = compound('POPCSearchNode_UnknownSerializationFormat',
('od', ObjectDescription),
('accesspoint', accesspoint),
('refcount', int)
)
POPCSearchNodeInfo = compound('POPCSearchNodeInfo',
('nodeId', string),
('operatingSystem', string),
('power', float),
('cpuSpeed', int),
('memorySize', float),
('networkBandwidth', int),
('diskSpace', int),
('protocol', string),
('encoding', string)
)
<file_sep>from pas.conf.basetypes import *
cls(1500, 'TestClass', [
func(10, 'TestClass', [], []),
func(12, 'get', [], [int]),
])
<file_sep>
from lxml import etree
from pas import shell
class Transformation(object):
"""
Object oriented wrapper for XSL transformations using lxml.
"""
def __init__(self, stylesheet):
self.path = stylesheet
with open(stylesheet) as fh:
self.document = etree.parse(fh)
self.extensions = {}
self.parameters = {}
def register_function(self, namespace, func, name=None):
if not name:
name = func.__name__
self.extensions[(namespace, name)] = func
def register_element(self, namespace, name, element):
self.extensions[(namespace, name)] = element
def transform(self, document_or_path, destination=None):
if isinstance(document_or_path, basestring):
with open(document_or_path) as fh:
document = etree.parse(fh)
else:
try:
document = etree.parse(document_or_path)
except AttributeError:
document = document_or_path
transformation = etree.XSLT(self.document, extensions=self.extensions)
transformed = transformation(document, **self.parameters)
if destination:
with open(destination, 'w') as fh:
fh.write(etree.tostring(transformed))
return transformed
def __call__(self, *args, **kwargs):
return self.transform(*args, **kwargs)
def prettyprint(infile, outfile=None, local=True):
"""
Reformats an xml document using xmllint.
"""
run = shell.local if local else shell.remote
outfile = outfile or infile
run('XMLLINT_INDENT="\t" xmllint --format -o {outfile} {infile}'.format(
infile=infile,
outfile=outfile
))
| 445e4e0d262b31180fc82155b8fefd8dfb26ad01 | [
"Ruby",
"reStructuredText",
"JavaScript",
"Markdown",
"Makefile",
"INI",
"Python",
"C++",
"Shell"
]
| 80 | Python | GaretJax/pop-analysis-suite | f43e1941744ea0c45e2ecf9f7241af5f41c48181 | 2aee319957105d7f67beeedf42df04952d996a61 |
refs/heads/current | <file_sep>export default {
"exposureCheckFrequency": 120,
"serverURL": "your-server-url",
"authToken": "<PASSWORD>",
"refreshToken": "<PASSWORD>",
"storeExposuresFor": 14,
"fileLimit": 1,
"version": "1.0.0",
"notificationTitle": "Close Contact Warning",
"notificationDesc": "The COVID Tracker App has detected that you may have been exposed to someone who has tested positive for COVID-19.",
"callbackNumber": "",
"analyticsOptin": true,
"debug": true
}<file_sep>package ie.gov.tracing.common
import android.content.pm.ApplicationInfo
import android.util.Log
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.modules.core.DeviceEventManagerModule
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.nearby.exposurenotification.ExposureNotificationStatusCodes
import ie.gov.tracing.Tracing
import ie.gov.tracing.storage.SharedPrefs
import java.io.PrintWriter
import java.io.StringWriter
import ie.gov.tracing.network.Fetcher
// central logging and events
class Events {
companion object {
const val INFO = "info"
const val ERROR = "error"
const val STATUS = "status" // start status
const val ON_STATUS_CHANGED = "onStatusChanged" // tracing api status
const val ON_EXPOSURE = "exposure"
private const val TAG = "RNExposureNotificationService"
private fun raiseEvent(map: ReadableMap) {
Tracing.reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)?.emit("exposureEvent", map)
}
private fun allowed(eventName: String): Boolean {
var isDebuggable = false
try {
isDebuggable = 0 != Tracing.currentContext.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE
} catch (ex: Exception) {}
if (eventName == "ERROR" && !isDebuggable) return false // allow all events in debug
// if(eventName == ON_STATUS_CHANGED || eventName == ON_EXPOSURE) return true // allow these debug or release
return true
}
@JvmStatic
fun raiseEvent(eventName: String, eventValue: String?): Boolean {
Log.d(TAG, "$eventName: $eventValue")
if(!allowed(eventName)) return false
val map = Arguments.createMap()
try {
map.putString(eventName, eventValue)
raiseEvent(map)
return true
} catch (ex: Exception) {
Log.d(TAG, "$map")
}
return false
}
@JvmStatic
fun raiseEvent(eventName: String, eventValue: ReadableMap?): Boolean {
Log.d(TAG, eventName)
if(!allowed(eventName)) return false
val map = Arguments.createMap()
try {
map.putMap(eventName, eventValue)
raiseEvent(map)
return true
} catch (ex: Exception) {
Log.d(TAG, "$map")
}
return false
}
@JvmStatic
fun raiseError(message: String, ex: Exception) {
Log.e(TAG, "Error: $message: $ex")
try {
if(allowed(ERROR)) { // if debugging allow stacktrace
var sw = StringWriter()
val pw = PrintWriter(sw)
ex.printStackTrace(pw)
Log.e(TAG, "$message: $sw")
if (ex is ApiException) {
SharedPrefs.setString("lastApiError", ExposureNotificationStatusCodes.getStatusCodeString(ex.statusCode), Tracing.currentContext)
}
SharedPrefs.setString("lastError", "$ex - $sw", Tracing.currentContext)
raiseEvent(ERROR, "$message: $ex - $sw")
} else { // otherwise just log generic message
raiseEvent(ERROR, "$message: $ex")
}
} catch (ex: Exception) {
Log.e(TAG, ex.toString())
}
}
}
}<file_sep>export {
ExposureProvider,
ExposureContext,
ExposureContextValue,
useExposure,
getBundleId,
getVersion
} from './exposure-provider';
export {
TraceConfiguration,
PermissionStatus,
PermissionDetails,
ExposurePermissions,
Version
} from './types';
export {
default,
AuthorisedStatus,
ConfigurationOptions,
DiagnosisKey,
CloseContact,
KeyServerType,
StatusState,
StatusType,
Status
} from './exposure-notification-module';
<file_sep>const {defaults: tsjPreset} = require('ts-jest/presets');
const rtlPreset = require('@testing-library/react-native/jest-preset');
module.exports = {
...tsjPreset,
preset: '@testing-library/react-native',
transform: {
...tsjPreset.transform,
'\\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js'
},
globals: {
'ts-jest': {
babelConfig: true
}
},
testMatch: [
'<rootDir>/src/__tests__/**/*.test.tsx',
'<rootDir>/src/__tests__/**/*.test.ts'
],
setupFiles: [...rtlPreset.setupFiles],
setupFilesAfterEnv: ['@testing-library/react-native/cleanup-after-each'],
// This is the only part which you can keep
// from the above linked tutorial's config:
cacheDirectory: '.jest/cache'
};
<file_sep>include ':mylibrary', ':play-services-nearby-exposurenotification-1.6.1-eap'
<file_sep>
import Foundation
import CoreData
import ExposureNotification
import os.log
import KeychainSwift
public class Storage {
public struct Config: Codable {
let refreshToken: String
let serverURL: String
let keyServerUrl: String
let keyServerType: KeyServerType
let checkExposureInterval: Int
let storeExposuresFor: Int
let notificationTitle: String
let notificationDesc: String
var authToken: String
var fileLimit: Int
var datesLastRan: String!
var lastExposureIndex: Int!
var notificationRaised: Bool!
var paused: Bool!
var callbackNumber: String!
var analyticsOptin: Bool!
var dailyTrace: Date?
var lastError: String?
var lastRunDate: Date?
}
private struct CodableCallback: Decodable {
let code: String
let number: String
}
public enum KeyServerType: String, Codable {
case NearForm = "nearform"
case GoogleRefServer = "google"
}
public static let shared = Storage()
public static func getDomain(_ url: String) -> String {
let url = URL(string: url)
return url!.host!
}
public func version() -> [String: String] {
var version: [String: String] = [:]
version["version"] = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown"
version["build"] = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "unknown"
version["display"] = "\(version["version"] ?? "unknown").\(version["build"] ?? "unknown")"
return version
}
public func readSettings(_ context: NSManagedObjectContext) -> Config! {
var settings: Config!
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Settings")
do {
let data = try context.fetch(fetchRequest)
if data.count > 0 {
let keychain = KeychainSwift()
let callbackData = keychain.get("cti.callBack") ?? "{\"code\":\"\",\"number\":\"\"}"
let callBack = try JSONDecoder().decode(CodableCallback.self, from: callbackData.data(using: .utf8)!)
var callbackNum = keychain.get("nm:callbackNumber") ?? ""
if callbackNum.isEmpty {
callbackNum = "\(callBack.code)\(callBack.number)"
}
let authToken = keychain.get("nm:authToken") ?? ""
let refreshToken = keychain.get("nm:refreshToken") ?? ""
let defaultDate = Date().addingTimeInterval(-1*24*60*60)
let keyType = data[0].value(forKey: "keyServerType") as? String ?? KeyServerType.NearForm.rawValue
settings = Config(
refreshToken:refreshToken,
serverURL: data[0].value(forKey: "serverURL") as! String,
keyServerUrl: data[0].value(forKey: "keyServerUrl") as? String ?? data[0].value(forKey: "serverURL") as! String,
keyServerType: Storage.KeyServerType(rawValue: keyType)!,checkExposureInterval: data[0].value(forKey: "checkExposureInterval") as! Int,
storeExposuresFor: data[0].value(forKey: "storeExposuresFor") as! Int,
notificationTitle: data[0].value(forKey: "notificationTitle") as! String,
notificationDesc: data[0].value(forKey: "notificationDesc") as! String,
authToken: authToken,
fileLimit: data[0].value(forKey: "fileLimit") as! Int,
datesLastRan: data[0].value(forKey: "datesLastRan") as? String ?? "",
lastExposureIndex: data[0].value(forKey: "lastIndex") as? Int,
notificationRaised: data[0].value(forKey: "notificationRaised") as? Bool,
paused: data[0].value(forKey: "servicePaused") as? Bool ?? false,
callbackNumber: callbackNum,
analyticsOptin: data[0].value(forKey: "analyticsOptin") as? Bool,
dailyTrace: data[0].value(forKey: "dailyTrace") as? Date,
lastError: data[0].value(forKey: "errorDetails") as? String,
lastRunDate: data[0].value(forKey: "lastRunDate") as? Date ?? defaultDate
)
}
} catch {
os_log("Could not retrieve settings: %@", log: OSLog.storage, type: .error, error.localizedDescription)
}
os_log("Fetching settings from store", log: OSLog.storage, type: .debug)
return settings
}
public func updateRunData(_ context: NSManagedObjectContext, _ errorDesc: String) {
self.updateRunData(context, errorDesc, nil)
}
public func updateRunData(_ context: NSManagedObjectContext, _ errorDesc: String, _ lastIndex: Int?) {
let currentData = self.readSettings(context)
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Settings")
do {
let settingsResult = try context.fetch(fetchRequest)
if settingsResult.count > 0 {
let managedObject = settingsResult[0]
let lastRanDates = currentData?.datesLastRan ?? ""
let runDate = String(Int64(Date().timeIntervalSince1970 * 1000.0))
var runDates = lastRanDates.components(separatedBy: ",")
runDates.append(runDate)
managedObject.setValue(runDates.suffix(10).joined(separator: ","), forKey: "datesLastRan")
if let index = lastIndex {
managedObject.setValue(index, forKey: "lastIndex")
}
managedObject.setValue(errorDesc, forKey: "errorDetails")
managedObject.setValue(Date(), forKey: "lastRunDate")
try context.save()
} else {
os_log("No settings have been stored, can't update", log: OSLog.storage, type: .debug)
}
} catch {
os_log("Could not update last run settings. %@", log: OSLog.storage, type: .error, error.localizedDescription)
}
os_log("Last run settings stored", log: OSLog.storage, type: .debug)
}
public func updateDailyTrace(_ context: NSManagedObjectContext, date: Date) {
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Settings")
do {
let settingsResult = try context.fetch(fetchRequest)
if settingsResult.count > 0 {
let managedObject = settingsResult[0]
managedObject.setValue(date, forKey: "dailyTrace")
try context.save()
} else {
os_log("No settings have been stored, can't update", log: OSLog.storage, type: .debug)
}
} catch {
os_log("Could not update daily trace settings. %@", log: OSLog.storage, type: .error, error.localizedDescription)
}
os_log("Daily Trace settings stored", log: OSLog.storage, type: .debug)
}
public func flagNotificationRaised(_ context: NSManagedObjectContext) {
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Settings")
do {
let settingsResult = try context.fetch(fetchRequest)
if settingsResult.count > 0 {
let managedObject = settingsResult[0]
managedObject.setValue(true, forKey: "notificationRaised")
try context.save()
} else {
os_log("No settings have been stored, can't flag as notified", log: OSLog.storage, type: .debug)
}
} catch {
os_log("Could not flag as notified. %@", log: OSLog.storage, type: .error, error.localizedDescription)
}
os_log("Flagged that user has been notified", log: OSLog.storage, type: .debug)
}
public func flagPauseStatus(_ context: NSManagedObjectContext, _ paused: Bool) {
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Settings")
do {
let settingsResult = try context.fetch(fetchRequest)
if settingsResult.count > 0 {
let managedObject = settingsResult[0]
managedObject.setValue(paused, forKey: "servicePaused")
try context.save()
} else {
os_log("No settings have been stored, can't flag pause status", log: OSLog.storage, type: .debug)
}
} catch {
os_log("Could not flag as paused. %@", log: OSLog.storage, type: .error, error.localizedDescription)
}
os_log("Flagged that service has been paused - %d", log: OSLog.storage, type: .debug, paused)
}
public func updateAppSettings(_ config: Config) {
let context = PersistentContainer.shared.newBackgroundContext()
var managedObject: NSManagedObject
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Settings")
do {
let settingsResult = try context.fetch(fetchRequest)
if (settingsResult.count > 0) {
os_log("Updating stored settings", log: OSLog.storage, type: .debug)
managedObject = settingsResult[0]
} else {
os_log("Creating settings entity for first time", log: OSLog.storage, type: .debug)
let entity =
NSEntityDescription.entity(forEntityName: "Settings",
in: context)!
managedObject = NSManagedObject(entity: entity,
insertInto: context)
}
let keychain = KeychainSwift()
keychain.set(config.callbackNumber, forKey: "nm:callbackNumber", withAccess: .accessibleAfterFirstUnlock)
keychain.set(config.authToken, forKey: "nm:authToken", withAccess: .accessibleAfterFirstUnlock)
keychain.set(config.refreshToken, forKey: "nm:refreshToken", withAccess: .accessibleAfterFirstUnlock)
managedObject.setValue(config.serverURL, forKey: "serverURL")
managedObject.setValue(config.keyServerUrl, forKey: "keyServerUrl")
managedObject.setValue(config.keyServerType.rawValue, forKey: "keyServerType")
managedObject.setValue(config.checkExposureInterval, forKey: "checkExposureInterval")
managedObject.setValue(config.storeExposuresFor, forKey: "storeExposuresFor")
managedObject.setValue(config.notificationTitle, forKey: "notificationTitle")
managedObject.setValue(config.notificationDesc, forKey: "notificationDesc")
managedObject.setValue(config.analyticsOptin, forKey: "analyticsOptin")
managedObject.setValue(config.fileLimit, forKey: "fileLimit")
try context.save()
} catch {
os_log("Could not create/update settings. %@", log: OSLog.storage, type: .error, error.localizedDescription)
}
os_log("Settings stored", log: OSLog.storage, type: .debug)
}
public func deleteData(_ exposuresOnly: Bool) {
let context = PersistentContainer.shared.newBackgroundContext()
var fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Exposures")
var deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try context.execute(deleteRequest)
} catch let error as NSError {
os_log("Error deleting the stored exposures: %@", log: OSLog.storage, type: .error, error.localizedDescription)
}
if exposuresOnly {
os_log("Exposure details cleared", log: OSLog.storage, type: .info)
return
}
fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Settings")
deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
let keychain = KeychainSwift()
keychain.delete("nm:authToken")
keychain.delete("nm:refreshToken")
keychain.delete("nm:callbackNumber")
do {
try context.execute(deleteRequest)
} catch let error as NSError {
os_log("Error deleting the stored settings: %@", log: OSLog.storage, type: .error, error.localizedDescription)
}
os_log("All stored details cleared", log: OSLog.storage, type: .info)
}
public func deleteOldExposures(_ storeExposuresFor: Int) {
let calendar = Calendar.current
let dateToday = calendar.startOfDay(for: Date())
let oldestAllowed = calendar.date(byAdding: .day, value: (0 - storeExposuresFor), to: dateToday)
let context = PersistentContainer.shared.newBackgroundContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Exposures")
fetchRequest.predicate = NSPredicate(format: "exposureDate < %@", oldestAllowed! as CVarArg)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try context.execute(deleteRequest)
} catch let error as NSError {
os_log("Error deleting the old stored exposures: %@", log: OSLog.storage, type: .error, error.localizedDescription)
}
os_log("Old exposure details cleared", log: OSLog.storage, type: .info)
}
@available(iOS 13.5, *)
public func saveExposureDetails(_ context: NSManagedObjectContext, _ exposureInfo: ExposureProcessor.ExposureInfo) {
var managedObject: NSManagedObject
do {
os_log("Creating exposure entry", log: OSLog.storage, type: .debug)
let entity =
NSEntityDescription.entity(forEntityName: "Exposures",
in: context)!
managedObject = NSManagedObject(entity: entity,
insertInto: context)
let attenuations = exposureInfo.attenuationDurations.map { String($0) }
let customAttenuations = exposureInfo.customAttenuationDurations.map { String($0) }
managedObject.setValue(exposureInfo.exposureDate, forKey: "exposureDate")
managedObject.setValue(exposureInfo.daysSinceLastExposure, forKey: "daysSinceExposure")
managedObject.setValue(exposureInfo.matchedKeyCount, forKey: "matchedKeys")
managedObject.setValue(exposureInfo.maxRiskScore, forKey: "riskScore")
managedObject.setValue(exposureInfo.maximumRiskScoreFullRange, forKey: "maximumRiskScoreFullRange")
managedObject.setValue(exposureInfo.riskScoreSumFullRange, forKey: "riskScoreSumFullRange")
managedObject.setValue(customAttenuations.joined(separator: ","), forKey: "customAttenuationDurations")
managedObject.setValue(attenuations.joined(separator: ","), forKey: "attenuations")
let encoder = JSONEncoder()
if exposureInfo.details != nil {
if let jsonData = try? encoder.encode(exposureInfo.details) {
let coded = String(data: jsonData, encoding: .utf8)
managedObject.setValue(coded, forKey: "exposureDetails")
}
}
try context.save()
} catch {
os_log("Could not create exposure. %@", log: OSLog.storage, type: .error, error.localizedDescription)
}
os_log("Exposure data stored", log: OSLog.storage, type: .debug)
}
@available(iOS 13.5, *)
public func getExposures(_ storeExposuresFor: Int) -> [ExposureProcessor.ExposureInfo] {
let context = PersistentContainer.shared.newBackgroundContext()
var exposures: [ExposureProcessor.ExposureInfo] = []
let calendar = Calendar.current
let dateToday = calendar.startOfDay(for: Date())
let oldestAllowed = calendar.date(byAdding: .day, value: (0 - storeExposuresFor), to: dateToday)
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "Exposures")
fetchRequest.predicate = NSPredicate(format: "exposureDate >= %@", oldestAllowed! as CVarArg)
do {
let data = try context.fetch(fetchRequest)
exposures = data.map{exposure in
let attenuationData = exposure.value(forKey: "attenuations") as! String
let attenuations = attenuationData.split(separator: ",").map { Int($0) ?? 0 }
let customAttenuationData = exposure.value(forKey: "customAttenuationDurations") as? String ?? ""
let customAttenuations = customAttenuationData.split(separator: ",").map { Int($0) ?? 0 }
var info = ExposureProcessor.ExposureInfo(daysSinceLastExposure: exposure.value(forKey: "daysSinceExposure") as! Int, attenuationDurations: attenuations, matchedKeyCount: exposure.value(forKey: "matchedKeys") as! Int, maxRiskScore: exposure.value(forKey: "riskScore") as! Int, exposureDate: exposure.value(forKey: "exposureDate") as! Date,
maximumRiskScoreFullRange: exposure.value(forKey: "maximumRiskScoreFullRange") as? Int ?? 0,
riskScoreSumFullRange: exposure.value(forKey: "riskScoreSumFullRange") as? Int ?? 0,
customAttenuationDurations: customAttenuations)
if exposure.value(forKey: "exposureDetails") != nil {
let details = exposure.value(forKey: "exposureDetails") as! String
let decoder = JSONDecoder()
let data = try? decoder.decode([ExposureProcessor.ExposureDetails].self, from: details.data(using: .utf8)!)
info.details = data
}
return info
}
} catch {
os_log("Could not retrieve exposures: %@", log: OSLog.storage, type: .error, error.localizedDescription)
}
/// os_log("Fetching exposures from store", log: OSLog.storage, type: .debug)
return exposures
}
public class PersistentContainer: NSPersistentContainer {
static let shared: PersistentContainer = {
let modelURL = Bundle(for: Storage.self).url(forResource: "ExposureNotification", withExtension: "momd")!
let managedObjectModel = NSManagedObjectModel(contentsOf: modelURL)!
let container = PersistentContainer(name: "ExposureNotification", managedObjectModel: managedObjectModel)
//let container = PersistentContainer(name: "ExposureNotification")
container.loadPersistentStores { (desc, error) in
if let error = error {
fatalError("Unresolved error \(error)")
}
os_log("Successfully loaded persistent store at: %@", log: OSLog.storage, type: .debug, desc.url?.description ?? "nil")
}
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergePolicy(merge: NSMergePolicyType.mergeByPropertyStoreTrumpMergePolicyType)
return container
}()
public override func newBackgroundContext() -> NSManagedObjectContext {
let backgroundContext = super.newBackgroundContext()
backgroundContext.automaticallyMergesChangesFromParent = true
backgroundContext.mergePolicy = NSMergePolicy(merge: NSMergePolicyType.mergeByPropertyStoreTrumpMergePolicyType)
return backgroundContext
}
}
}
<file_sep>package ie.gov.tracing.nearby;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Build;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.work.Constraints;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.ExistingWorkPolicy;
import androidx.work.ListenableWorker;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.ForegroundInfo;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;
import androidx.work.WorkerParameters;
import com.google.common.io.BaseEncoding;
import com.google.common.util.concurrent.FluentFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.HashMap;
import java.io.File;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import org.threeten.bp.Duration;
import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION;
import ie.gov.tracing.Tracing;
import ie.gov.tracing.common.AppExecutors;
import ie.gov.tracing.common.Events;
import ie.gov.tracing.common.TaskToFutureAdapter;
import ie.gov.tracing.network.DiagnosisKeyDownloader;
import ie.gov.tracing.network.Fetcher;
import ie.gov.tracing.storage.ExposureNotificationRepository;
import ie.gov.tracing.storage.SharedPrefs;
import ie.gov.tracing.storage.TokenEntity;
import ie.gov.tracing.R;
public class ProvideDiagnosisKeysWorker extends ListenableWorker {
static final Duration DEFAULT_API_TIMEOUT = Duration.ofSeconds(15);
private static final String WORKER_NAME = "ProvideDiagnosisKeysWorker";
private static final BaseEncoding BASE64_LOWER = BaseEncoding.base64();
private static final int RANDOM_TOKEN_BYTE_LENGTH = 32;
private static final String FOREGROUND_NOTIFICATION_ID =
"ProvideDiagnosisKeysWorker.FOREGROUND_NOTIFICATION_ID";
private final DiagnosisKeyDownloader diagnosisKeys;
private final DiagnosisKeyFileSubmitter submitter;
private final SecureRandom secureRandom;
private final ExposureNotificationRepository repository;
public static long nextSince = 0;
private final Context context;
public ProvideDiagnosisKeysWorker(@NonNull Context context,
@NonNull WorkerParameters workerParams) {
super(context, workerParams);
diagnosisKeys = new DiagnosisKeyDownloader(context);
submitter = new DiagnosisKeyFileSubmitter(context);
secureRandom = new SecureRandom();
repository = new ExposureNotificationRepository(context);
this.context = context;
setForegroundAsync(createForegroundInfo());
}
private String generateRandomToken() {
byte[] bytes = new byte[RANDOM_TOKEN_BYTE_LENGTH];
secureRandom.nextBytes(bytes);
return BASE64_LOWER.encode(bytes);
}
private void deleteOldData() {
try {
long DAY_IN_MS = 1000 * 60 * 60 * 24;
long storeExposuresFor = SharedPrefs.getLong("storeExposuresFor", this.getApplicationContext());
long daysBeforeNowInMs = System.currentTimeMillis() - storeExposuresFor * DAY_IN_MS;
Events.raiseEvent(Events.INFO, "deleteOldData - delete exposures/tokens before: " +
new Date(daysBeforeNowInMs));
repository.deleteExposuresBefore(daysBeforeNowInMs);
repository.deleteTokensBefore(daysBeforeNowInMs);
} catch(Exception ex) {
Events.raiseError("deleteOldData", ex);
}
}
private void updateLastRun() {
try {
String [] lastRun = SharedPrefs.getString("lastRun", Tracing.currentContext).split("\\s*,\\s*");
List<String> lastRuns = new ArrayList<>(Arrays.asList(lastRun));
lastRuns.add("" + System.currentTimeMillis());
int firstIndex = lastRuns.size() - 10;
if (firstIndex < 0) firstIndex = 0;
String newLastRun = lastRuns.get(firstIndex);
for(int i = firstIndex + 1; i < lastRuns.size(); i++) {
newLastRun += "," + lastRuns.get(i).trim();
}
SharedPrefs.setString("lastRun", newLastRun, Tracing.currentContext);
} catch(Exception ex) {
Events.raiseError("lastRun", ex);
}
}
@NonNull
@Override
public ListenableFuture<Result> startWork() {
Tracing.currentContext = getApplicationContext();
Events.raiseEvent(Events.INFO, "ProvideDiagnosisKeysWorker.startWork");
setForegroundAsync(createForegroundInfo());
updateLastRun();
SharedPrefs.remove("lastApiError", Tracing.currentContext);
SharedPrefs.remove("lastError", Tracing.currentContext);
// validate config set before running
final String auth = SharedPrefs.getString("authToken", this.getApplicationContext());
if (auth.isEmpty()) {
// config not yet populated so don't run
return Futures.immediateFailedFuture(new ConfigNotSetException());
}
final Boolean paused = SharedPrefs.getBoolean("servicePaused", this.getApplicationContext());
if (paused) {
// ENS is paused
return Futures.immediateFailedFuture(new ENSPaused());
}
deleteOldData();
final String token = generateRandomToken();
return FluentFuture.from(TaskToFutureAdapter
.getFutureWithTimeout(
ExposureNotificationClientWrapper.get(getApplicationContext()).isEnabled(),
DEFAULT_API_TIMEOUT.toMillis(),
TimeUnit.MILLISECONDS,
AppExecutors.getScheduledExecutor()))
.transformAsync(isEnabled -> {
// Only continue if it is enabled.
if (isEnabled != null && isEnabled) {
return diagnosisKeys.download();
} else {
// Stop here because things aren't enabled. Will still return successful though.
return Futures.immediateFailedFuture(new NotEnabledException());
}
},
AppExecutors.getBackgroundExecutor())
.transformAsync(files -> submitter.parseFiles(files, token),
AppExecutors.getBackgroundExecutor())
.transformAsync(done -> repository.upsertTokenEntityAsync(TokenEntity.create(token, false)),
AppExecutors.getBackgroundExecutor())
.transform(done -> processSuccess(), // all done, do tidy ups here
AppExecutors.getLightweightExecutor())
.catching(NotEnabledException.class,
ex -> Result.success(), // not enabled, just return success
AppExecutors.getBackgroundExecutor())
.catching(Exception.class, this::processFailure,
AppExecutors.getBackgroundExecutor());
}
@NonNull
private ForegroundInfo createForegroundInfo() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel(FOREGROUND_NOTIFICATION_ID);
}
Events.raiseEvent(Events.INFO, "ProvideDiagnosisKeysWorker.Foreground created");
Notification notification = new NotificationCompat.Builder(this.context, FOREGROUND_NOTIFICATION_ID)
.setContentTitle(this.context.getString(R.string.notification_checking))
.setProgress(1, 0, true)
.setSmallIcon(R.mipmap.ic_notification)
.setOngoing(true)
.build();
return new ForegroundInfo(1, notification, FOREGROUND_SERVICE_TYPE_LOCATION);
}
@RequiresApi(Build.VERSION_CODES.O)
private void createChannel(String id) {
// Create a Notification channel
NotificationChannel channel = new NotificationChannel(
id,
this.context.getString(R.string.notification_channel_name), NotificationManager.IMPORTANCE_LOW
);
NotificationManager notificationManager = (NotificationManager) this.context.getSystemService(
Context.NOTIFICATION_SERVICE
);
notificationManager.createNotificationChannel(channel);
}
private Result processFailure(Exception ex) {
HashMap<String, Object> payload = new HashMap<>();
payload.put("description", "error processing file: " + ex);
Fetcher.saveMetric("LOG_ERROR", context, payload);
Events.raiseError("error processing file: ", ex);
return Result.failure();
}
private void deleteExports() {
try {
File directory = new File(this.getApplicationContext().getFilesDir() + "/diag_keys/");
File[] files = directory.listFiles();
Events.raiseEvent(Events.INFO, "deleteExports - files to delete: " + files.length);
for (File file : files) {
try {
if (file.delete()) {
Events.raiseEvent(Events.INFO, "deleteExports - deleted file:" + file.getName());
} else {
Events.raiseEvent(Events.INFO, "deleteExports - file not deleted:" + file.getName());
}
} catch (Exception ex) {
Events.raiseError("deleteExports - error deleting file: " + file.getName(), ex);
}
}
} catch(Exception ex) {
Events.raiseError("deleteExports - error deleting files", ex);
}
}
private void saveDailyMetric() {
try {
long dailyActiveTrace = SharedPrefs.getLong("dailyActiveTrace", this.getApplicationContext());
Events.raiseEvent(Events.INFO, "saveDailyMetric - last DAILY_ACTIVE_TRACE: " + dailyActiveTrace);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(new Date(dailyActiveTrace));
Calendar cal2 = Calendar.getInstance(); // now
boolean sameDay = cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);
if(dailyActiveTrace > 0 && sameDay) {
Events.raiseEvent(Events.INFO, "saveDailyMetric - already sent today");
return;
}
Events.raiseEvent(Events.INFO, "saveDailyMetric - saving DAILY_ACTIVE_TRACE metric");
Fetcher.saveMetric("DAILY_ACTIVE_TRACE", this.getApplicationContext(), null);
SharedPrefs.setLong("dailyActiveTrace", System.currentTimeMillis(), this.getApplicationContext());
} catch(Exception ex) {
Events.raiseError("saveDailyMetric - error", ex);
}
}
private Result processSuccess() {
if(nextSince > 0) {
Events.raiseEvent(Events.INFO, "success processing exports, setting since index to: " + nextSince);
SharedPrefs.setLong("since", nextSince, Tracing.currentContext);
// try delete, does not affect success
deleteExports();
}
// try save daily metric, does not affect success
saveDailyMetric();
return Result.success();
}
private static boolean isWorkScheduled() {
WorkManager instance = WorkManager.getInstance(Tracing.context);
ListenableFuture<List<WorkInfo>> statuses = instance.getWorkInfosByTag(WORKER_NAME);
try {
List<WorkInfo> workInfoList = statuses.get();
for (WorkInfo workInfo : workInfoList) {
if(workInfo.getState() == WorkInfo.State.RUNNING || workInfo.getState() == WorkInfo.State.ENQUEUED)
return true;
}
} catch (Exception ex) {
Events.raiseError("isWorkScheduled", ex);
}
return false;
}
public static void startScheduler() {
long checkFrequency = SharedPrefs.getLong("exposureCheckFrequency", Tracing.context);
if (checkFrequency <= 0) {
checkFrequency = 120;
}
Events.raiseEvent(Events.INFO, "ProvideDiagnosisKeysWorker.startScheduler: run every " +
checkFrequency + " minutes");
WorkManager workManager = WorkManager.getInstance(Tracing.context);
PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(
ProvideDiagnosisKeysWorker.class, checkFrequency, TimeUnit.MINUTES)
.setInitialDelay(30, TimeUnit.SECONDS) // could offset this, but idle may be good enough
.addTag(WORKER_NAME)
.setConstraints(
new Constraints.Builder()
//.setRequiresBatteryNotLow(true)
//.setRequiresDeviceIdle(true)
.setRequiredNetworkType(NetworkType.CONNECTED)
.build())
.build();
workManager
.enqueueUniquePeriodicWork(WORKER_NAME, ExistingPeriodicWorkPolicy.REPLACE, workRequest);
}
public static void startOneTimeWorkRequest() {
Events.raiseEvent(Events.INFO, "ProvideDiagnosisKeysWorker.startOneTimeWorker");
WorkManager workManager = WorkManager.getInstance(Tracing.context);
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(ProvideDiagnosisKeysWorker.class)
.setConstraints(
new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build())
.build();
workManager.enqueueUniqueWork("OneTimeWorker", ExistingWorkPolicy.REPLACE, workRequest);
}
public static void stopScheduler() {
Events.raiseEvent(Events.INFO, "ProvideDiagnosisKeysWorker.stopScheduler");
WorkManager.getInstance(Tracing.context).cancelAllWorkByTag(WORKER_NAME);
}
private static class NotEnabledException extends Exception {}
private static class ConfigNotSetException extends Exception {}
private static class ENSPaused extends Exception {}
}<file_sep>package ie.gov.tracing.storage;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity
public class ExposureEntity {
@PrimaryKey(autoGenerate = true)
long id;
@ColumnInfo(name = "created_timestamp_ms")
private long createdTimestampMs;
@ColumnInfo(name = "days_since_last_exposure")
private int daysSinceLastExposure;
@ColumnInfo(name = "matched_key_count")
private int matchedKeyCount;
@ColumnInfo(name = "maximum_risk_score")
private int maximumRiskScore;
@ColumnInfo(name = "summation_risk_score")
private int summationRiskScore;
@ColumnInfo(name = "attenuation_durations")
private String attenuationDurations;
ExposureEntity(int daysSinceLastExposure, int matchedKeyCount,
int maximumRiskScore, int summationRiskScore,
String attenuationDurations) {
this.createdTimestampMs = System.currentTimeMillis();
this.daysSinceLastExposure = daysSinceLastExposure;
this.matchedKeyCount = matchedKeyCount;
this.maximumRiskScore = maximumRiskScore;
this.summationRiskScore = summationRiskScore;
this.attenuationDurations = attenuationDurations;
}
public static ExposureEntity create(int daysSinceLastExposure, int matchedKeyCount,
int maximumRiskScore, int summationRiskScore,
String attenuationDurations) {
return new ExposureEntity(daysSinceLastExposure, matchedKeyCount,
maximumRiskScore, summationRiskScore, attenuationDurations);
}
public long getId() {
return id;
}
public long getCreatedTimestampMs() {
return createdTimestampMs;
}
void setCreatedTimestampMs(long ms) {
this.createdTimestampMs = ms;
}
public int daysSinceLastExposure() {
return daysSinceLastExposure;
}
public int matchedKeyCount() {
return matchedKeyCount;
}
public int maximumRiskScore() {
return maximumRiskScore;
}
public int summationRiskScore() {
return summationRiskScore;
}
public String attenuationDurations() {
return this.attenuationDurations;
}
public void setMatchedKeyCount(int matchedKeyCount) {
this.matchedKeyCount = matchedKeyCount;
}
public void setDaysSinceLastExposure(int daysSinceLastExposure) {
this.daysSinceLastExposure = daysSinceLastExposure;
}
public void setMaximumRiskScore(int maximumRiskScore) {
this.maximumRiskScore = maximumRiskScore;
}
public void setSummationRiskScore(int summationRiskScore) {
this.summationRiskScore = summationRiskScore;
}
public void setAttenuationDurations(String attenuationDurations) {
this.attenuationDurations = attenuationDurations;
}
}<file_sep>package ie.gov.tracing.common;
import android.os.Process;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* A simple static repository of {@link java.util.concurrent.Executor}s for use throughout the app.
*/
public final class AppExecutors {
private AppExecutors() {
// Prevent instantiation.
}
// Number of lightweight executor threads is dynamic. See #lightweightThreadCount()
private static final int NUM_BACKGROUND_THREADS = 4;
private static final ThreadPolicy POLICY =
new ThreadPolicy.Builder().detectAll().penaltyLog().build();
private static ListeningExecutorService lightweightExecutor;
private static ListeningExecutorService backgroundExecutor;
private static ListeningScheduledExecutorService scheduledExecutor;
public static synchronized ListeningExecutorService getLightweightExecutor() {
if (lightweightExecutor == null) {
lightweightExecutor =
createFixed(
"Lightweight", lightweightThreadCount(), Process.THREAD_PRIORITY_DEFAULT);
}
return lightweightExecutor;
}
public static synchronized ListeningExecutorService getBackgroundExecutor() {
if (backgroundExecutor == null) {
backgroundExecutor =
createFixed(
"Background", backgroundThreadCount(), Process.THREAD_PRIORITY_BACKGROUND);
}
return backgroundExecutor;
}
public static synchronized ListeningScheduledExecutorService getScheduledExecutor() {
if (scheduledExecutor == null) {
scheduledExecutor =
createScheduled(
backgroundThreadCount());
}
return scheduledExecutor;
}
private static ListeningExecutorService createFixed(
String name, int count, int priority) {
return MoreExecutors.listeningDecorator(
Executors.newFixedThreadPool(count, createThreadFactory(name, priority)));
}
private static ListeningScheduledExecutorService createScheduled(
int minCount) {
return MoreExecutors.listeningDecorator(
Executors.newScheduledThreadPool(minCount, createThreadFactory("Scheduled", Process.THREAD_PRIORITY_BACKGROUND)));
}
private static ThreadFactory createThreadFactory(
String name, int priority) {
return new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(name + " #%d")
.setThreadFactory(
runnable ->
new Thread(
() -> {
//StrictMode.setThreadPolicy(AppExecutors.POLICY);
// Despite what the class name might imply, the Process class
// operates on the current thread.
Process.setThreadPriority(priority);
runnable.run();
}))
.build();
}
private static int lightweightThreadCount() {
// Always use at least two threads, so that clients can't depend on light weight executor tasks
// executing sequentially
return Math.max(2, Runtime.getRuntime().availableProcessors() - 2);
}
private static int backgroundThreadCount() {
return NUM_BACKGROUND_THREADS;
}
}
<file_sep>import Foundation
import os.log
import UserNotifications
import UIKit
import ExposureNotification
@objc(ExposureNotificationModule)
public class ExposureNotificationModule: RCTEventEmitter {
private let notificationCenter = NotificationCenter.default
public override init() {
super.init()
setupNotifications()
}
deinit {
notificationCenter.removeObserver(self)
}
/// list events
public override func supportedEvents() -> [String]! {
return ["exposureEvent"]
}
public override func constantsToExport() -> [AnyHashable : Any]! {
return [:]
}
@objc
public override static func requiresMainQueueSetup() -> Bool {
return true
}
@objc func configure(_ configData: NSDictionary, resolve: RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) -> Void {
os_log("Request to configure module, %{PRIVATE}@", log: OSLog.setup, type: .debug, configData)
guard let configDict = configData as? [String: Any] else {
os_log("Error configuring module, no dictionary passwed in.", log: OSLog.setup, type: .error)
return resolve(false)
}
guard let serverURL = configDict["serverURL"] as? String, let refresh = configDict["refreshToken"] as? String, let token = configDict["authToken"] as? String else {
os_log("Error configuring module, refresh token or auth missing", log: OSLog.setup, type: .error)
return resolve(false)
}
let configData = Storage.Config(
refreshToken: refresh,
serverURL: serverURL,
keyServerUrl: configDict["keyServerUrl"] as? String ?? serverURL,
keyServerType: Storage.KeyServerType (rawValue: configDict["keyServerType"] as! String) ?? Storage.KeyServerType.NearForm,
checkExposureInterval: configDict["exposureCheckFrequency"] as? Int ?? 120,
storeExposuresFor: configDict["storeExposuresFor"] as? Int ?? 14,
notificationTitle: configDict["notificationTitle"] as? String ?? "Close Contact Warning",
notificationDesc: configDict["notificationDesc"] as? String ?? "The COVID Tracker App has detected that you may have been exposed to someone who has tested positive for COVID-19.",
authToken: <PASSWORD>,
fileLimit: configDict["fileLimit"] as? Int ?? 3,
callbackNumber: configDict["callbackNumber"] as? String ?? "",
analyticsOptin: configDict["analyticsOptin"] as? Bool ?? false
)
Storage.shared.updateAppSettings(configData)
resolve(true)
}
@objc public func authoriseExposure(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.authoriseExposure(resolve, rejecter: reject)
} else {
resolve("unavailable")
}
}
@objc public func exposureEnabled(_ resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.exposureEnabled(resolve, rejecter: reject)
} else {
resolve("unavailable")
}
}
@objc public func isAuthorised(_ resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.isAuthorised(resolve, rejecter: reject)
} else {
resolve("unavailable")
}
}
@objc public func isSupported(_ resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
if #available(iOS 13.5, *) {
resolve(true)
} else {
resolve(false)
}
}
@objc public func canSupport(_ resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
resolve(UIDevice.supportsIOS13)
}
@objc public func status(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.status(resolve, rejecter: reject)
} else {
resolve(["state": "unavailable"])
}
}
@objc public func start(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.start(resolve, rejecter: reject)
} else {
//nothing to do here
resolve(false)
}
}
@objc public func pause(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.pause(resolve, rejecter: reject)
} else {
//nothing to do here
resolve(false)
}
}
@objc public func stop(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.stop(resolve, rejecter: reject)
} else {
///nothing to do here
resolve(false)
}
}
@objc public func getDiagnosisKeys(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.getDiagnosisKeys(resolve, rejecter: reject)
} else {
resolve([])
}
}
@objc public func getCloseContacts(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.getCloseContacts(resolve, rejecter: reject)
} else {
resolve([])
}
}
@objc public func getLogData(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.getLogData(resolve, rejecter: reject)
} else {
resolve([])
}
}
@objc public func triggerUpdate(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
resolve(false)
}
@objc public func simulateExposure(_ timeDelay: Int) {
if #available(iOS 13.5, *) {
os_log("Reqwuest to simulate exposure after %f", log: OSLog.setup, type: .debug, timeDelay)
DispatchQueue.main.asyncAfter(deadline: .now() + Double(timeDelay)) {
ExposureProcessor.shared.checkExposureForeground(false, true, true)
}
}
}
@objc static public func registerBackgroundProcessing() {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.registerBackgroundProcessing()
} else {
os_log("Skipping regustering backgroiund as not 13.5 or higher", log: OSLog.setup, type: .debug)
}
}
@objc public func checkExposure(_ readExposureDetails: Bool, _ skipTimeCheck: Bool) {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.checkExposureForeground(readExposureDetails, skipTimeCheck, false)
}
}
@objc public func deleteAllData(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.deleteAllData(resolve, rejecter: reject)
} else {
resolve(true)
}
}
@objc public func deleteExposureData(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
if #available(iOS 13.5, *) {
ExposureProcessor.shared.deleteExposureData(resolve, rejecter: reject)
} else {
resolve(true)
}
}
@objc public func bundleId(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
resolve(Bundle.main.bundleIdentifier!)
}
@objc public func version(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
let version = Storage.shared.version()
resolve(version)
}
private func setupNotifications() {
notificationCenter.addObserver(self,
selector: #selector(onStatusChanged),
name: .onStatusChanged,
object: nil
)
}
@objc private func onStatusChanged(_ notification: Notification) {
var status: [String: Any] = [:]
if #available(iOS 13.5, *) {
guard let item = notification.object as? ENStatus else {
os_log("No data in status change event", log: OSLog.exposure, type: .debug)
return
}
switch item {
case .active:
status["state"] = "active"
case .unknown:
status["state"] = "unknown"
case .disabled:
status["state"] = "disabled"
status["type"] = ["exposure"]
case .bluetoothOff:
status["state"] = "disabled"
status["type"] = ["bluetooth"]
case .restricted:
status["state"] = "restricted"
case .paused:
status["state"] = "disabled"
status["type"] = ["paused"]
case .unauthorized:
status["state"] = "unavailable"
status["type"] = ["unauthorized"]
@unknown default:
status["state"] = "unavailable"
}
if ExposureManager.shared.isPaused() && (status["state"] as! String == "disabled" || status["state"] as! String == "unknown") {
status["state"] = "disabled"
status["type"] = ["paused"]
}
os_log("Status of exposure service has changed %@", log: OSLog.exposure, type: .debug, status)
sendEvent(withName: "exposureEvent", body: ["onStatusChanged": status])
}
}
}
extension OSLog {
private static var subsystem = Bundle.main.bundleIdentifier!
static let setup = OSLog(subsystem: subsystem, category: "setup")
static let exposure = OSLog(subsystem: subsystem, category: "exposure")
static let checkExposure = OSLog(subsystem: subsystem, category: "checkExposure")
static let storage = OSLog(subsystem: subsystem, category: "storage")
}
<file_sep>package ie.gov.tracing.storage
import android.content.Context
import android.content.SharedPreferences
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
import ie.gov.tracing.common.Events
class SharedPrefs {
companion object {
private var INSTANCE: SharedPreferences? = null
private fun getEncryptedSharedPrefs(context: Context): SharedPreferences? {
try {
if (INSTANCE != null) return INSTANCE!!
val masterKeyAlias: String = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
INSTANCE = EncryptedSharedPreferences.create(
"secret_shared_prefs",
masterKeyAlias,
context.applicationContext,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
return INSTANCE!!
} catch(ex: Exception) {
Events.raiseError("getEncryptedSharedPrefs", ex)
}
return null
}
@JvmStatic
fun getLong(key: String, context: Context): Long {
try {
val preferences = getEncryptedSharedPrefs(context)
return preferences!!.getLong(key, 0)
} catch(ex: Exception) {
Events.raiseError("SharedPrefs.getLong", ex)
}
return 0
}
@JvmStatic
fun setLong(key: String, num: Long, context: Context) {
try {
val preferences = getEncryptedSharedPrefs(context)
val editor = preferences!!.edit()
editor.putLong(key, num)
editor.commit() // do not use apply
} catch(ex: Exception) {
Events.raiseError("SharedPrefs.setLong", ex)
}
}
@JvmStatic
fun getBoolean(key: String, context: Context): Boolean {
try {
val preferences = getEncryptedSharedPrefs(context)
return preferences!!.getBoolean(key, false)
} catch(ex: Exception) {
Events.raiseError("SharedPrefs.getBoolean", ex)
}
return false
}
@JvmStatic
fun setBoolean(key: String, bln: Boolean, context: Context) {
try {
val preferences = getEncryptedSharedPrefs(context)
val editor = preferences!!.edit()
editor.putBoolean(key, bln)
editor.commit() // do not use apply
} catch(ex: Exception) {
Events.raiseError("SharedPrefs.setBoolean", ex)
}
}
@JvmStatic
fun getString(key: String, context: Context): String {
try {
val preferences = getEncryptedSharedPrefs(context)
return preferences!!.getString(key, "") ?: return ""
} catch(ex: Exception) {
Events.raiseError("SharedPrefs.getString", ex)
}
return ""
}
@JvmStatic
fun setString(key: String, str: String, context: Context) {
try {
val preferences = getEncryptedSharedPrefs(context)
val editor = preferences!!.edit()
editor.putString(key, str)
editor.commit() // do not use apply
} catch(ex: Exception) {
Events.raiseError("SharedPrefs.setString", ex)
}
}
@JvmStatic
fun remove(key: String, context: Context) {
try {
val preferences = getEncryptedSharedPrefs(context)
val editor = preferences!!.edit()
editor.remove(key)
editor.commit() // do not use apply
} catch(ex: Exception) {
Events.raiseError("SharedPrefs.remove", ex)
}
}
fun clear(context: Context) {
try {
val preferences = getEncryptedSharedPrefs(context)
val editor = preferences!!.edit()
editor.clear()
editor.commit() // do not use apply
} catch(ex: Exception) {
Events.raiseError("SharedPrefs.clear", ex)
}
}
}
}<file_sep>export interface TraceConfiguration {
exposureCheckInterval: number;
storeExposuresFor: number;
fileLimit: number;
fileLimitiOS: number;
}
export enum PermissionStatus {
Unknown = 'unknown',
NotAvailable = 'not_available',
Allowed = 'allowed',
NotAllowed = 'not_allowed'
}
export interface PermissionDetails {
status:
| PermissionStatus.Unknown
| PermissionStatus.NotAvailable
| PermissionStatus.NotAllowed
| PermissionStatus.Allowed;
internal?: any;
}
export interface ExposurePermissions {
exposure: PermissionDetails;
notifications: PermissionDetails;
}
export interface Version {
version: String;
build: String;
display: String;
}
<file_sep>package ie.gov.tracing
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.BroadcastReceiver
import android.content.IntentSender.SendIntentException
import androidx.work.await
import com.facebook.react.bridge.*
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.common.api.AvailabilityException
import com.google.android.gms.nearby.exposurenotification.ExposureNotificationStatusCodes
import com.google.android.gms.nearby.exposurenotification.TemporaryExposureKey
import com.google.common.io.BaseEncoding
import ie.gov.tracing.common.Config
import ie.gov.tracing.common.Events
import ie.gov.tracing.nearby.*
import ie.gov.tracing.nearby.ExposureNotificationHelper.Callback
import ie.gov.tracing.storage.ExposureNotificationDatabase
import ie.gov.tracing.storage.ExposureNotificationRepository
import ie.gov.tracing.storage.SharedPrefs
import ie.gov.tracing.storage.SharedPrefs.Companion.getLong
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import ie.gov.tracing.nearby.StateUpdatedWorker
import android.content.IntentFilter
import android.bluetooth.BluetoothAdapter;
import android.content.pm.PackageInfo
import android.location.LocationManager
import android.os.Build
import androidx.core.content.pm.PackageInfoCompat
import androidx.core.location.LocationManagerCompat
class Listener: ActivityEventListener {
override fun onNewIntent(intent: Intent?) {}
override fun onActivityResult(activty: Activity?, requestCode: Int, resultCode: Int, data: Intent?) {
try {
Events.raiseEvent(Events.INFO, "onActivityResult - requestCode: $requestCode, resultCode: $resultCode")
if (requestCode == RequestCodes.REQUEST_CODE_START_EXPOSURE_NOTIFICATION) {
if (resultCode == Activity.RESULT_OK) {
Events.raiseEvent(Events.INFO, "onActivityResult - START_EXPOSURE_NOTIFICATION_OK")
// call authorize again to resolve the promise if isEnabled set
if(Tracing.status == Tracing.STATUS_STARTING) {
// call start after authorization if starting,
// fulfils promise after successful start
Tracing.start(null)
} else {
// in order for isAuthorised to work, we must start
// start failure will resolve authorisation permissions promise
Tracing.authoriseExposure(null)
}
} else {
Events.raiseEvent(Events.INFO, "onActivityResult - START_EXPOSURE_NOTIFICATION_FAILED: $resultCode")
if(Tracing.status == Tracing.STATUS_STARTING) {
Tracing.resolutionPromise?.resolve(false)
} else {
Tracing.resolutionPromise?.resolve("denied")
}
}
return
}
if (requestCode == RequestCodes.REQUEST_CODE_GET_TEMP_EXPOSURE_KEY_HISTORY) {
if (resultCode == Activity.RESULT_OK) {
Events.raiseEvent(Events.INFO, "onActivityResult - GET_TEMP_EXPOSURE_KEY_HISTORY_OK")
Tracing.getDiagnosisKeys(null)
} else {
Tracing.resolutionPromise?.reject(Throwable("Rejected"))
Events.raiseEvent(Events.ERROR, "onActivityResult - GET_TEMP_EXPOSURE_KEY_HISTORY_FAILED: $resultCode")
}
return
}
if (requestCode == RequestCodes.PLAY_SERVICES_UPDATE) {
if (resultCode == Activity.RESULT_OK) {
val gps = GoogleApiAvailability.getInstance()
val result = gps.isGooglePlayServicesAvailable(Tracing.context.applicationContext, Tracing.MIN_PLAY_SERVICES_VERSION)
Tracing.base.playServicesVersion = gps.getApkVersion(Tracing.context.applicationContext)
Events.raiseEvent(Events.INFO,"triggerUpdate - version after activity: ${Tracing.base.playServicesVersion}")
if(result == ConnectionResult.SUCCESS) {
Events.raiseEvent(Events.INFO,"triggerUpdate - update successful")
Tracing.resolutionPromise?.resolve("success")
} else {
Events.raiseEvent(Events.ERROR,"triggerUpdate - update failed: $result")
Tracing.resolutionPromise?.resolve("failed")
}
} else {
Events.raiseEvent(Events.INFO,"triggerUpdate - update cancelled")
Tracing.resolutionPromise?.resolve("cancelled")
}
}
} catch(ex: Exception) {
Events.raiseError("onActivityResult", ex)
Tracing.resolutionPromise?.resolve(false)
}
}
}
class BleStatusReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (BluetoothAdapter.ACTION_STATE_CHANGED == intent.action) {
Tracing.getExposureStatus(null)
}
Events.raiseEvent(Events.INFO,"bleStatusUpdate - $intent.action")
Tracing.setExposureStatus(Tracing.exposureStatus, Tracing.exposureDisabledReason)
}
}
class Tracing {
companion object {
const val MIN_PLAY_SERVICES_VERSION = 201817017
lateinit var context: Context
lateinit var currentContext: Context
lateinit var base: ExposureNotificationModule
lateinit var reactContext: ReactApplicationContext
const val STATUS_STARTED = "STARTED"
const val STATUS_STARTING = "STARTING"
const val STATUS_STOPPED = "STOPPED"
const val STATUS_PAUSED = "PAUSED"
private const val EXPOSURE_STATUS_UNKNOWN = "unknown"
private const val EXPOSURE_STATUS_ACTIVE = "active"
private const val EXPOSURE_STATUS_DISABLED = "disabled"
//const val EXPOSURE_STATUS_RESTRICTED = "restricted"
private const val EXPOSURE_STATUS_UNAVAILABLE = "unavailable"
private const val STATUS_STOPPING = "STOPPING"
var status = STATUS_STOPPED
var exposureStatus = EXPOSURE_STATUS_UNAVAILABLE
var exposureDisabledReason = "starting"
private lateinit var exposureWrapper: ExposureNotificationClientWrapper
var resolutionPromise: Promise? = null
var startPromise: Promise? = null
private var extraDetails = false
@JvmStatic
fun setExposureStatus(status: String, reason: String = "") {
exposureStatus = status
exposureDisabledReason = reason
Events.raiseEvent(Events.ON_STATUS_CHANGED, getExposureStatus(null))
}
private val authorisationCallback: Callback = object : Callback {
override fun onFailure(t: Throwable) {
try {
// set current status, pre/post resolution
if (t is ApiException) {
handleApiException(t)
} else {
Events.raiseError("authorisation error:", Exception(t))
}
// if authorizationPromise is set, we're trying this post resolution
if (resolutionPromise != null) {
if(status == STATUS_STARTING)
resolutionPromise!!.resolve(false)
else {
if (t is ApiException) {
if (t.statusCode == ExposureNotificationStatusCodes.FAILED_REJECTED_OPT_IN ||
t.statusCode == ExposureNotificationStatusCodes.FAILED_UNAUTHORIZED)
resolutionPromise!!.resolve("denied")
else if (t.statusCode == ExposureNotificationStatusCodes.FAILED_NOT_SUPPORTED)
resolutionPromise!!.resolve("unavailable")
else
resolutionPromise!!.resolve("blocked")
} else {
resolutionPromise!!.resolve("denied")
}
}
return
}
resolutionPromise = startPromise
if (t is ApiException && t.statusCode ==
ExposureNotificationStatusCodes.RESOLUTION_REQUIRED) {
Events.raiseEvent(Events.INFO, "authorisationCallback - resolution required")
try {
// opens dialog box to allow exposure tracing
Events.raiseEvent(Events.INFO, "authorisationCallback - start resolution")
t.status.startResolutionForResult(base.activity,
RequestCodes.REQUEST_CODE_START_EXPOSURE_NOTIFICATION)
} catch (ex: SendIntentException) {
Events.raiseError("authorisationCallback - error starting resolution, " +
"open settings to resolve", ex)
if(status == STATUS_STARTING)
resolutionPromise!!.resolve(false)
else {
resolutionPromise!!.resolve("denied")
}
}
} else {
Events.raiseEvent(Events.INFO, "authorisationCallback - " +
"no resolution required, open settings to authorise")
if(status == STATUS_STARTING)
resolutionPromise!!.resolve(false)
else {
resolutionPromise!!.resolve("denied")
}
}
} catch(ex: Exception) {
Events.raiseError("authorisationCallback.onFailure", ex)
if(status == STATUS_STARTING)
resolutionPromise!!.resolve(false)
else {
resolutionPromise!!.resolve("denied")
}
}
}
override fun onSuccess(message: String) {
try {
Events.raiseEvent(Events.INFO, "authorisationCallback - success")
if (status == STATUS_STARTING) {
setNewStatus(STATUS_STARTED)
startPromise?.resolve(true)
} else {
startPromise!!.resolve("granted")
}
} catch(ex: Exception) {
Events.raiseError("authorisationCallback.onSuccess", ex)
if (status == STATUS_STARTING) {
startPromise?.resolve(false)
} else {
startPromise!!.resolve("denied")
}
}
}
}
@JvmStatic
fun init(appContext: ReactApplicationContext, baseJavaModule: ExposureNotificationModule) {
try {
// don't use these contexts for background stuff like workers/services
base = baseJavaModule
reactContext = appContext
context = reactContext.applicationContext
exposureWrapper = ExposureNotificationClientWrapper.get(context)
reactContext.addActivityEventListener(Listener())
currentContext = context // this is overridden depending on path into codebase
scheduleCheckExposure()
val br: BroadcastReceiver = BleStatusReceiver()
val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED).apply {
addAction(Intent.EXTRA_INTENT)
}
context.registerReceiver(br, filter)
} catch (ex: Exception) {
Events.raiseError("init", ex)
}
}
private fun setNewStatus(newStatus: String) {
status = newStatus
if (status === STATUS_STARTED) {
setExposureStatus(EXPOSURE_STATUS_ACTIVE)
} else if (status === STATUS_STOPPED) {
setExposureStatus(EXPOSURE_STATUS_DISABLED, "exposure")
}
Events.raiseEvent(Events.STATUS, status)
}
@JvmStatic
fun start(promise: Promise?) {
try {
setNewStatus(STATUS_STARTING)
SharedPrefs.setBoolean("servicePaused", false, context)
if (promise != null) {
resolutionPromise = null
startPromise = promise
}
ExposureNotificationHelper(authorisationCallback).startExposure()
} catch (ex: Exception) {
Events.raiseError("start", ex)
promise?.resolve(false)
}
}
@JvmStatic
fun pause(promise: Promise?) {
try {
setNewStatus(STATUS_STOPPING)
SharedPrefs.setBoolean("servicePaused", true, context)
val permissionHelperCallback: Callback = object : Callback {
override fun onFailure(t: Throwable) {
Events.raiseError("paused", Exception(t))
setNewStatus(STATUS_PAUSED)
promise?.resolve(true)
}
override fun onSuccess(status: String) {
Events.raiseEvent(Events.INFO, "exposure tracing $status")
ProvideDiagnosisKeysWorker.stopScheduler()
setNewStatus(STATUS_PAUSED)
promise?.resolve(true)
}
}
ExposureNotificationHelper(permissionHelperCallback).stopExposure()
} catch (ex: Exception) {
Events.raiseError("paused", ex)
promise?.resolve(false)
}
}
@JvmStatic
fun stop() {
try {
setNewStatus(STATUS_STOPPING)
SharedPrefs.setBoolean("servicePaused", false, context)
val permissionHelperCallback: Callback = object : Callback {
override fun onFailure(t: Throwable) {
Events.raiseError("stop", Exception(t))
setNewStatus(STATUS_STOPPED)
}
override fun onSuccess(status: String) {
Events.raiseEvent(Events.INFO, "exposure tracing $status")
ProvideDiagnosisKeysWorker.stopScheduler()
setNewStatus(STATUS_STOPPED)
}
}
ExposureNotificationHelper(permissionHelperCallback).stopExposure()
} catch (ex: Exception) {
Events.raiseError("stop", ex)
}
}
@JvmStatic
fun exposureEnabled(promise: Promise) {
try {
exposureWrapper.isEnabled
.addOnSuccessListener { enabled: Boolean? ->
if (enabled != null) {
promise.resolve(enabled)
} else {
Events.raiseEvent(Events.INFO, "exposureEnabled: null")
promise.resolve(false)
}
}
.addOnFailureListener { ex ->
Events.raiseError("exposureEnabled - onFailure", ex)
handleApiException(ex)
promise.resolve(false)
}
} catch (ex: Exception) {
Events.raiseError("exposureEnabled - exception", ex)
promise.resolve(false)
}
}
@JvmStatic
fun configure(params: ReadableMap) {
try {
val oldCheckFrequency = getLong("exposureCheckFrequency", context)
Config.configure(params)
val newCheckFrequency = getLong("exposureCheckFrequency", context)
Events.raiseEvent(Events.INFO, "old: $oldCheckFrequency, new: $newCheckFrequency")
if(newCheckFrequency != oldCheckFrequency) {
scheduleCheckExposure()
}
} catch (ex: Exception) {
Events.raiseError("configure", ex)
}
}
@JvmStatic
fun checkExposure(readExposureDetails: Boolean = false) {
extraDetails = readExposureDetails
ProvideDiagnosisKeysWorker.startOneTimeWorkRequest()
}
@JvmStatic
fun simulateExposure(timeDelay: Long = 0) {
extraDetails = false
StateUpdatedWorker.simulateExposure(timeDelay)
}
@JvmStatic
fun version(): WritableMap {
var versionName: String
var versionCode: String
try {
val pinfo: PackageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0)
versionName = pinfo.versionName
versionCode = PackageInfoCompat.getLongVersionCode(pinfo).toString()
} catch(e: Exception) {
versionName = "unknown"
versionCode = "unknown"
}
val data = Arguments.createMap()
data.putString("version", versionName)
data.putString("build", versionCode)
data.putString("display", "$versionName.$versionCode")
return data
}
private fun getExposureKeyAsMap(tek: TemporaryExposureKey): WritableMap {
val result: WritableMap = Arguments.createMap()
result.putString("keyData", BaseEncoding.base64().encode(tek.keyData))
result.putInt("rollingPeriod", 144)
result.putInt("rollingStartNumber", tek.rollingStartIntervalNumber)
result.putInt("transmissionRiskLevel", tek.transmissionRiskLevel) // app should overwrite
return result
}
// get the diagnosis keys for this user for the past 14 days (config)
@JvmStatic
fun getDiagnosisKeys(promise: Promise?) {
try {
if (promise != null) { // called from client
resolutionPromise = promise
}
exposureWrapper.temporaryExposureKeyHistory
.addOnSuccessListener {
if (it != null) {
// convert the keys into a structure we can convert to json
val result: WritableArray = Arguments.createArray()
for (temporaryExposureKey in it) {
result.pushMap(getExposureKeyAsMap(temporaryExposureKey))
}
Events.raiseEvent(Events.INFO, "getDiagnosisKeys - exposure key retrieval success, #keys: ${it.size}")
resolutionPromise?.resolve(result)
} else {
Events.raiseEvent(Events.INFO, "getDiagnosisKeys - exposure key retrieval success - no keys")
resolutionPromise?.resolve(Arguments.createArray())
}
}
.addOnFailureListener { ex ->
if (ex is ApiException && ex.statusCode == ExposureNotificationStatusCodes.RESOLUTION_REQUIRED) {
Events.raiseEvent(Events.INFO, "getDiagnosisKeys - exposure api exception: " +
ExposureNotificationStatusCodes.getStatusCodeString(ex.statusCode))
if (promise != null) { // ask permission, if failed and no promise set as param
Events.raiseEvent(Events.INFO, "getDiagnosisKeys - ask user for permission")
try {
ex.status.startResolutionForResult(base.activity,
RequestCodes.REQUEST_CODE_GET_TEMP_EXPOSURE_KEY_HISTORY)
// we will need to resolve promise and attempt to get the keys again
// promise will be resolved if successful in success listener
} catch (ex: Exception) {
resolutionPromise?.resolve(Arguments.createArray())
Events.raiseError("getDiagnosisKeys - exposure api exception", ex)
}
} else {
resolutionPromise?.resolve(Arguments.createArray())
Events.raiseError("getDiagnosisKeys - failed post-resolution, not trying again", ex)
}
} else {
resolutionPromise?.resolve(Arguments.createArray())
Events.raiseError("getDiagnosisKeys - general exception", ex)
}
}
} catch (ex: Exception) {
Events.raiseError("getDiagnosisKeys", ex)
promise?.resolve(Arguments.createArray())
}
}
@JvmStatic
fun isAuthorised(promise: Promise) {
try {
exposureWrapper.isEnabled
.addOnSuccessListener { enabled: Boolean? ->
if (enabled == true) {
Events.raiseEvent(Events.INFO,"isAuthorised: granted")
promise.resolve("granted")
} else {
Events.raiseEvent(Events.INFO,"isAuthorised: denied")
promise.resolve("blocked")
}
}
.addOnFailureListener { ex ->
Events.raiseError("isAuthorised - onFailure", ex)
handleApiException(ex)
promise.resolve("blocked")
}
} catch (ex: Exception) {
Events.raiseError("isAuthorised - exception", ex)
promise.resolve("blocked")
}
}
@JvmStatic
fun authoriseExposure(promise: Promise?) {
// the only way to authorise is to call start, we just resolve promise differently
try {
if (promise != null) {
resolutionPromise = null
startPromise = promise
}
ExposureNotificationHelper(authorisationCallback).startExposure()
} catch (ex: Exception) {
Events.raiseError("authorizeExposure", ex)
promise?.resolve("unavailable")
}
}
@JvmStatic
fun isSupported(promise: Promise) = runBlocking<Unit> {
launch {
try {
val apiResult = ExposureNotificationHelper.checkAvailability().await()
Events.raiseEvent(Events.INFO, "isSupported - checkAvailability: $apiResult")
promise.resolve(true)
} catch (ex: AvailabilityException) {
Events.raiseError("isSupported - AvailabilityException", ex)
promise.resolve(false)
base.setApiError(ExposureNotificationStatusCodes.API_NOT_CONNECTED)
} catch (ex: Exception) {
Events.raiseError("isSupported - Exception", ex)
promise.resolve(false)
base.setApiError(1)
}
}
}
@JvmStatic
fun triggerUpdate(promise: Promise) = runBlocking<Unit> {
launch {
try {
Events.raiseEvent(Events.INFO,"triggerUpdate - trigger update")
val gps = GoogleApiAvailability.getInstance()
base.playServicesVersion = gps.getApkVersion(context.applicationContext)
Events.raiseEvent(Events.INFO,"triggerUpdate - version: ${base.playServicesVersion}")
val result = gps.isGooglePlayServicesAvailable(context.applicationContext, MIN_PLAY_SERVICES_VERSION)
Events.raiseEvent(Events.INFO,"triggerUpdate - result: $result")
if (result == ConnectionResult.SUCCESS) {
try {
val apiResult = ExposureNotificationHelper.checkAvailability().await()
Events.raiseEvent(Events.INFO, "triggerUpdate - checkAvailability: $apiResult")
promise.resolve("already_installed")
} catch (ex: AvailabilityException) {
Events.raiseError("triggerUpdate - AvailabilityException", ex)
promise.resolve("api_not_available")
base.setApiError(ExposureNotificationStatusCodes.API_NOT_CONNECTED)
} catch (ex: Exception) {
Events.raiseError("triggerUpdate - checkAvailability exception", ex)
promise.resolve("api_exception")
base.setApiError(1)
}
}
if (result == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) { // requires update
resolutionPromise = promise
gps.getErrorDialog(base.activity,
ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED,
RequestCodes.PLAY_SERVICES_UPDATE).show()
} else {
promise.resolve("unknown result: $result")
}
} catch (ex: Exception) {
Events.raiseError("triggerUpdate - exception", ex)
promise.resolve("error")
}
}
}
@JvmStatic
fun deleteData(promise: Promise) = runBlocking<Unit> {
launch {
try {
SharedPrefs.clear(context)
// just in case nuke fails
ExposureNotificationRepository(context).deleteAllExposureEntitiesAsync().await()
ExposureNotificationRepository(context).deleteAllTokensAsync().await()
// drop db
ExposureNotificationDatabase.nukeDatabase(context)
promise.resolve(true)
} catch (ex: Exception) {
Events.raiseError("deleteData", ex)
promise.resolve(false)
}
}
}
@JvmStatic
fun deleteExposureData(promise: Promise) = runBlocking<Unit> {
launch {
try {
ExposureNotificationRepository(context).deleteAllExposureEntitiesAsync().await()
promise.resolve(true)
} catch (ex: Exception) {
Events.raiseError("deleteExposureData", ex)
promise.resolve(false)
}
}
}
private fun scheduleCheckExposure() {
try {
// stop and re-start with config value
ProvideDiagnosisKeysWorker.stopScheduler()
ProvideDiagnosisKeysWorker.startScheduler()
} catch (ex: Exception) {
Events.raiseError("scheduleCheckExposure", ex)
}
}
@JvmStatic
fun getCloseContacts(promise: Promise) = runBlocking<Unit> {
launch {
try {
val exposures = ExposureNotificationRepository(context).allExposureEntitiesAsync.await()
val result: WritableArray = Arguments.createArray()
for (exposure in exposures) {
// asynchronously update our summary table while we receive notifications
val ads: List<String> = exposure.attenuationDurations().split(",")
val attenuationDurations = Arguments.createArray()
if (ads.isNotEmpty()) {
for (i in ads.indices) {
attenuationDurations.pushInt(ads[i].toInt())
}
}
val exp: WritableMap = Arguments.createMap()
exp.putDouble("exposureAlertDate", exposure.createdTimestampMs.toDouble())
exp.putArray("attenuationDurations", attenuationDurations)
exp.putInt("daysSinceLastExposure", exposure.daysSinceLastExposure())
exp.putInt("matchedKeyCount", exposure.matchedKeyCount())
exp.putInt("maxRiskScore", exposure.maximumRiskScore())
exp.putInt("summationRiskScore", exposure.summationRiskScore())
result.pushMap(exp)
}
promise.resolve(result)
} catch (ex: Exception) {
Events.raiseError("getCloseContacts", ex)
promise.resolve(Arguments.createArray())
}
}
}
/**
* When it comes to Location and BLE, there are the following conditions:
* - Location on is only necessary to use bluetooth for Android M+.
* - Starting with Android S, there may be support for locationless BLE scanning
* => We only go into an error state if these conditions require us to have location on, but
* it is not activated on device.
*/
private fun isLocationEnableRequired(): Boolean {
val locationManager: LocationManager = Tracing.context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
return (!exposureWrapper.deviceSupportsLocationlessScanning()
&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && locationManager != null && !LocationManagerCompat.isLocationEnabled(locationManager))
}
@JvmStatic
fun getExposureStatus(promise: Promise? = null): ReadableMap {
val result: WritableMap = Arguments.createMap()
val typeData: WritableArray = Arguments.createArray()
val isPaused = SharedPrefs.getBoolean("servicePaused", context)
if (isPaused) {
exposureDisabledReason = "paused"
}
try {
// check bluetooth
val bluetoothAdapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled) {
exposureStatus = EXPOSURE_STATUS_DISABLED
exposureDisabledReason = "bluetooth";
}
if (isLocationEnableRequired()) {
exposureStatus = EXPOSURE_STATUS_DISABLED
exposureDisabledReason = "bluetooth";
}
result.putString("state", exposureStatus)
typeData.pushString(exposureDisabledReason)
result.putArray("type", typeData)
promise?.resolve(result)
} catch (ex: Exception) {
Events.raiseError("getExposureStatus", ex)
result.putString("state", EXPOSURE_STATUS_UNKNOWN)
typeData.pushString("error")
result.putArray("type", typeData)
promise?.resolve(result)
}
return result
}
@JvmStatic
fun getLogData(promise: Promise) {
val map = Arguments.createMap()
map.putInt("installedPlayServicesVersion", base.playServicesVersion)
map.putBoolean("nearbyApiSupported", !base.nearbyNotSupported())
map.putDouble("lastIndex", getLong("since", context).toDouble())
map.putString("lastRun", SharedPrefs.getString("lastRun", context))
map.putString("lastError", SharedPrefs.getString("lastError", context))
map.putString("lastApiError", SharedPrefs.getString("lastApiError", context))
promise.resolve(map)
}
fun handleApiException(ex: Exception) {
if (ex is ApiException) {
Events.raiseEvent(Events.ERROR, "handle api exception: ${ExposureNotificationStatusCodes.getStatusCodeString(ex.statusCode)}")
exposureDisabledReason = ""
when (ex.statusCode) {
ExposureNotificationStatusCodes.RESOLUTION_REQUIRED -> setExposureStatus(EXPOSURE_STATUS_DISABLED, "resolution")
ExposureNotificationStatusCodes.SIGN_IN_REQUIRED -> setExposureStatus(EXPOSURE_STATUS_DISABLED, "signin_required")
ExposureNotificationStatusCodes.FAILED_BLUETOOTH_DISABLED -> setExposureStatus(EXPOSURE_STATUS_DISABLED, "bluetooth")
ExposureNotificationStatusCodes.FAILED_REJECTED_OPT_IN -> setExposureStatus(EXPOSURE_STATUS_DISABLED, "rejected")
ExposureNotificationStatusCodes.FAILED_NOT_SUPPORTED -> setExposureStatus(EXPOSURE_STATUS_DISABLED, "not_supported")
ExposureNotificationStatusCodes.FAILED_SERVICE_DISABLED -> setExposureStatus(EXPOSURE_STATUS_DISABLED, "disabled")
ExposureNotificationStatusCodes.FAILED_UNAUTHORIZED -> setExposureStatus(EXPOSURE_STATUS_DISABLED, "unauthorised")
ExposureNotificationStatusCodes.FAILED_DISK_IO -> setExposureStatus(EXPOSURE_STATUS_DISABLED, "disk")
ExposureNotificationStatusCodes.FAILED_TEMPORARILY_DISABLED -> setExposureStatus(EXPOSURE_STATUS_DISABLED, "temporarily_disabled")
ExposureNotificationStatusCodes.FAILED -> setExposureStatus(EXPOSURE_STATUS_DISABLED, "failed")
ExposureNotificationStatusCodes.API_NOT_CONNECTED -> {
setExposureStatus(EXPOSURE_STATUS_UNAVAILABLE, "not_connected")
base.setApiError(ex.statusCode)
}
}
}
}
}
}<file_sep>package ie.gov.tracing.network
import android.content.Context
import androidx.annotation.Keep
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
import com.google.gson.Gson
import ie.gov.tracing.common.Events
import ie.gov.tracing.nearby.ProvideDiagnosisKeysWorker
import ie.gov.tracing.storage.SharedPrefs
import java.io.File
import kotlin.math.max
import kotlin.math.min
@Keep
data class ServerFile(val id: Long, val path: String)
internal class DiagnosisKeyDownloader(private val context: Context) {
private fun processGoogleList(fileList: List<String>): Array<ServerFile> {
var since = SharedPrefs.getLong("since", context)
var fileLimit = SharedPrefs.getLong("fileLimit", context)
val files = mutableListOf<ServerFile>()
fileList.forEach { serverFile ->
val f = File(serverFile)
val name = f.nameWithoutExtension
val nameParts = name.split("-")
Events.raiseEvent(Events.INFO, "checking google file - ${serverFile} - ${name}, ${nameParts[0]}, ${nameParts[1]}, ${since}")
if (nameParts[0].toLong() >= since) {
val sf = ServerFile(nameParts[1].toLong(), serverFile)
files.add(sf)
}
}
if (files.size == 0) {
return files.toTypedArray()
}
if (since <= 0) {
val startIndex = max(0, files.size - fileLimit.toInt())
val endIndex = min(files.size, startIndex + fileLimit.toInt())
return files.subList(startIndex, endIndex).toTypedArray()
} else {
val endIndex = min(files.size, fileLimit.toInt())
return files.subList(0, endIndex).toTypedArray()
}
}
fun download(): ListenableFuture<List<File>> {
ProvideDiagnosisKeysWorker.nextSince = 0 // this will be greater than 0 on success
var since = SharedPrefs.getLong("since", context)
var fileLimit = SharedPrefs.getLong("fileLimit", context)
val keyServerType = SharedPrefs.getString("keyServerType", context)
Events.raiseEvent(Events.INFO, "download - get exports to process since: $since")
// process:
// 1. list batches from server from since index
// 2. download the files to process
// 3. increment sync to largest processed index
// 4. return the list of files to pass to the submitter
var url = "/exposures/?since=$since&limit=$fileLimit"
if (keyServerType == "google") {
url = "/v1/index.txt"
}
val data = Fetcher.fetch(url, false, true, context)
val files = mutableListOf<File>()
if(data != null) {
var serverFiles: Array<ServerFile>
if (keyServerType == "google") {
val fileList = data.split("\n")
serverFiles = processGoogleList(fileList)
} else {
serverFiles = Gson().fromJson(data, Array<ServerFile>::class.java)
Events.raiseEvent(Events.INFO, "download - success, processing files: ${serverFiles.size}")
}
serverFiles.forEach { serverFile ->
try {
Events.raiseEvent(Events.INFO, "download - downloading file: ${serverFile}")
val file = Fetcher.downloadFile(serverFile.path, context)
if (file != null) {
files.add(file)
// update max since
since = since.coerceAtLeast(serverFile.id)
}
} catch (ex: Exception) {
Events.raiseError("download - Error downloading file: ${serverFile.path}", ex)
}
}
if (files.size > 0) {
Events.raiseEvent(Events.INFO, "success downloading incrementing since to: $since")
ProvideDiagnosisKeysWorker.nextSince = since
}
}
return Futures.immediateFuture(files)
}
}<file_sep>package ie.gov.tracing.storage;
import androidx.room.TypeConverter;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
/**
* TypeConverters for converting to and from {@link ZonedDateTime} instances.
*/
public class ZonedDateTimeTypeConverter {
private ZonedDateTimeTypeConverter() {
// no instantiation
}
private static final DateTimeFormatter sFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
@TypeConverter
public static ZonedDateTime toOffsetDateTime(String timestamp) {
if (timestamp != null) {
return sFormatter.parse(timestamp, ZonedDateTime.FROM);
} else {
return null;
}
}
@TypeConverter
public static String fromOffsetDateTime(ZonedDateTime timestamp) {
if (timestamp != null) {
return timestamp.format(sFormatter);
} else {
return null;
}
}
}
<file_sep>// DO NOT DELETE THIS FILE
import Foundation
<file_sep>package ie.gov.tracing.network
import android.content.Context
import androidx.annotation.Keep
import com.google.common.io.BaseEncoding
import com.google.gson.Gson
import ie.gov.tracing.Tracing
import ie.gov.tracing.common.Events
import ie.gov.tracing.storage.ExpoSecureStoreInterop
import ie.gov.tracing.storage.ExposureEntity
import ie.gov.tracing.storage.SharedPrefs
import org.apache.commons.io.FileUtils
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.security.SecureRandom
import java.util.*
@Keep
data class Token(val token: String)
@Keep
data class Callback(val mobile: String, val closeContactDate: Long, val payload: Map<String, Any>)
@Keep
data class Metric(val os: String, val event: String, val version: String, val payload: Map<String, Any>?)
@Keep
data class CallbackRecovery(val mobile:String, val code: String, val iso: String,val number: String)
class Fetcher {
companion object {
private const val FILE_PATTERN = "/diag_keys/diagnosis_key_file_%s.zip"
fun token(): String {
val bytes = ByteArray(32)
SecureRandom().nextBytes(bytes)
return BaseEncoding.base64().encode(bytes)
}
private fun uniq(): String? {
val bytes = ByteArray(4)
SecureRandom().nextBytes(bytes)
return BaseEncoding.base32().lowerCase().omitPadding().encode(bytes)
}
fun downloadFile(filename: String, context: Context): File? {
try {
val keyServerUrl = SharedPrefs.getString("keyServerUrl", context)
val keyServerType = SharedPrefs.getString("keyServerType", context)
val authToken = SharedPrefs.getString("authToken", context)
var fileUrl = "${keyServerUrl}/data/$filename"
if (keyServerType == "google") {
fileUrl = "${keyServerUrl}/$filename"
}
Events.raiseEvent(Events.INFO, "downloadFile - $fileUrl")
val url = URL(fileUrl)
val urlConnection = url.openConnection() as HttpURLConnection
if (keyServerType == "nearform") {
urlConnection.setRequestProperty("Authorization", "Bearer $authToken")
}
urlConnection.setRequestProperty("Accept", "application/zip")
val keyFile = File(context.filesDir, String.format(FILE_PATTERN, uniq()))
if (urlConnection.responseCode != HttpURLConnection.HTTP_OK) {
Events.raiseEvent(Events.ERROR, "downloadFile - failed: $fileUrl, response code: ${urlConnection.responseCode}")
urlConnection.disconnect()
return null
}
FileUtils.copyInputStreamToFile(urlConnection.inputStream, keyFile)
urlConnection.disconnect()
Events.raiseEvent(Events.INFO, "downloadFile - success: $fileUrl")
return keyFile
} catch (ex: Exception) {
Events.raiseError("downloadFile", ex)
return null
}
}
private fun getNewAuthToken(context: Context): String? {
try {
val serverUrl = SharedPrefs.getString("serverUrl", context)
val refreshToken = SharedPrefs.getString("refreshToken", context)
val url = URL("${serverUrl}/refresh")
val urlConnection = url.openConnection() as HttpURLConnection
urlConnection.doOutput = true
urlConnection.setRequestProperty("Authorization", "Bearer $refreshToken")
urlConnection.requestMethod = "POST"
if (urlConnection.responseCode != HttpURLConnection.HTTP_OK) {
urlConnection.disconnect()
return null
}
val data = urlConnection.inputStream.bufferedReader().use { it.readText() }
urlConnection.disconnect()
val token = Gson().fromJson(data, Token::class.java)
return token.token
} catch(ex: Exception) {
Events.raiseError("refresh token error", ex)
}
return null
}
private fun post(endpoint: String, body: String, context: Context): Boolean {
try {
val serverUrl = SharedPrefs.getString("serverUrl", context)
val authToken = SharedPrefs.getString("authToken", context)
Events.raiseEvent(Events.INFO, "post - sending data to: " +
"${serverUrl}$endpoint, body: $body")
val url = URL("${serverUrl}$endpoint")
val urlConnection = url.openConnection() as HttpURLConnection
urlConnection.doOutput = true
urlConnection.setRequestProperty("Authorization", "Bearer $authToken")
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
urlConnection.setRequestProperty("Accept", "application/json")
urlConnection.requestMethod = "POST"
urlConnection.outputStream.write(body.toByteArray(Charsets.UTF_8))
urlConnection.outputStream.flush()
urlConnection.outputStream.close()
if (urlConnection.responseCode != HttpURLConnection.HTTP_OK &&
urlConnection.responseCode != HttpURLConnection.HTTP_NO_CONTENT) {
Events.raiseEvent(Events.ERROR, "post - HTTP error: ${urlConnection.responseCode}")
urlConnection.disconnect()
return false
}
Events.raiseEvent(Events.INFO, "post - success: ${urlConnection.responseCode}")
urlConnection.disconnect()
return true
} catch(ex: Exception) {
Events.raiseError("post error", ex)
}
return false
}
@JvmStatic
fun fetch(endpoint: String, retry: Boolean = false, keyFile: Boolean = false, context: Context): String? {
try {
var serverUrl = SharedPrefs.getString("serverUrl", context)
if (keyFile) {
serverUrl = SharedPrefs.getString("keyServerUrl", context)
}
val keyServerType = SharedPrefs.getString("keyServerType", context)
val authToken = SharedPrefs.getString("authToken", context)
Events.raiseEvent(Events.INFO, "fetch - fetching from: ${serverUrl}$endpoint")
val url = URL("${serverUrl}$endpoint")
val urlConnection = url.openConnection() as HttpURLConnection
if ((keyServerType == "nearform" && keyFile) || !keyFile) {
urlConnection.setRequestProperty("Authorization", "Bearer $authToken")
}
Events.raiseEvent(Events.INFO, "fetch - response: ${urlConnection.responseCode}")
if (urlConnection.responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
// disconnect immediately
urlConnection.disconnect()
// if this is a retry, do not refresh token again
if (retry) {
Events.raiseEvent(Events.ERROR, "fetch - Unauthorized")
return null
}
Events.raiseEvent(Events.ERROR, "fetch - Unauthorized, refreshing token...")
val newAuthToken = getNewAuthToken(context)
return if (newAuthToken != null) {
SharedPrefs.setString("authToken", newAuthToken, context)
// recursively call again with retry set
fetch(endpoint, true, keyFile, context)
} else {
Events.raiseEvent(Events.ERROR, "fetch - Unauthorized")
null
}
}
if (urlConnection.responseCode != HttpURLConnection.HTTP_OK) {
Events.raiseEvent(Events.ERROR, "fetch - HTTP error: ${urlConnection.responseCode}")
urlConnection.disconnect()
return null
}
val data = urlConnection.inputStream.bufferedReader().use { it.readText() }
urlConnection.disconnect()
Events.raiseEvent(Events.INFO, "fetch - success")
return data
} catch (ex: Exception) {
Events.raiseError("fetch error", ex)
return null
}
}
@JvmStatic
fun triggerCallback(exposureEntity: ExposureEntity, context: Context, payload: Map<String, Any>) {
try {
val notificationSent = SharedPrefs.getLong("notificationSent", context)
var callbackNum = SharedPrefs.getString("callbackNumber", context)
if (notificationSent > 0) {
Events.raiseEvent(Events.INFO, "triggerCallback - notification " +
"already sent: " + notificationSent)
return
}
if (callbackNum.isEmpty()) {
try {
val store = ExpoSecureStoreInterop(context)
val jsonStr = store.getItemImpl("cti.callBack")
if (jsonStr.isEmpty()) {
Events.raiseEvent(Events.INFO, "triggerCallback - no callback recovery")
return;
}
val callBackData = Gson().fromJson(jsonStr, CallbackRecovery::class.java)
if(callBackData.code == null || callBackData.number == null){
Events.raiseEvent(Events.INFO, "triggerCallback - no callback recovery")
return;
}
callbackNum = callBackData.code + callBackData.number
} catch (exExpo: Exception) {
Events.raiseError("ExpoSecureStoreInterop", exExpo)
}
if (callbackNum.isEmpty()) {
Events.raiseEvent(Events.INFO, "triggerCallback - no callback number " +
"set, not sending callback")
return
}
}
val calendar = Calendar.getInstance()
calendar.add(Calendar.DAY_OF_YEAR, 0 - exposureEntity.daysSinceLastExposure())
calendar.set(Calendar.HOUR_OF_DAY, 0)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)
val daysSinceExposure = calendar.time.time
Events.raiseEvent(Events.INFO, "triggerCallback - sending: ${daysSinceExposure} ${Date(daysSinceExposure)}")
val callbackParams = Callback(callbackNum, daysSinceExposure, payload)
val success = post("/callback", Gson().toJson(callbackParams), context)
if (!success) {
Events.raiseEvent(Events.ERROR, "triggerCallback - failed")
return
}
Events.raiseEvent(Events.INFO, "triggerCallback - success")
SharedPrefs.setLong("notificationSent", System.currentTimeMillis(), context)
} catch(ex: Exception) {
Events.raiseError("triggerCallback - error", ex)
}
}
@JvmStatic
fun saveMetric(event: String, context: Context, payload: Map<String, Any>? = null) {
try {
val analytics = SharedPrefs.getBoolean("analyticsOptin", context)
val version = Tracing.version().getString("display").toString()
if(!analytics) {
Events.raiseEvent(Events.INFO, "saveMetric - not saving, no opt in")
return
}
val metric = Metric("android", event, version, payload)
val success = post("/metrics", Gson().toJson(metric), context)
if (!success) {
Events.raiseEvent(Events.ERROR, "saveMetric - failed: $event")
return
}
Events.raiseEvent(Events.INFO, "saveMetric - success, $event, $version")
} catch(ex: Exception) {
Events.raiseError("triggerCallback - error", ex)
}
}
}
}<file_sep><img alttext="COVID Green Logo" src="https://raw.githubusercontent.com/lfph/artwork/master/projects/covidgreen/stacked/color/covidgreen-stacked-color.png" width="300" />
# React Native Exposure Notification Service
React Native Exposure Notification Service is a react native module, which provides a common interface to
Apple/Google's Exposure Notification APIs.
For more on contact tracing see:
- https://www.google.com/covid19/exposurenotifications/
- https://www.apple.com/covid19/contacttracing
## Contents
- [Getting Started](#getting-started)
- [Usage](#usage)
- [ExposureNotificationModule](#exposurenotificationmodule)
- [ExposureProvider](#exposureprovider)
- [Release process](#release-process)
- [Test Application](#test-application)
- [Caveats](#caveats)
- [License](#license)
## Getting started
To integrate with your react-native app:
```
# with npm
npm install --save react-native-exposure-notification-service
# with yarn
yarn add react-native-exposure-notification-service
```
### Mostly automatic installation
React Native Exposure Notifications uses autolinking to allow your project discover and use this code.
On Android there are no further steps.
CocoaPods on iOS needs this extra step:
```
cd ios && pod install && cd ..
```
## Usage
There are multiple ways to use the React Native Exposure Notification Service in your React application. You can use it directly via the [`ExposureNotificationModule`](#-exposurenotificationmodule) and manage the application state yourself, or you can use the [`ExposureProvider`](#-exposure-provider) [React Context](https://reactjs.org/docs/context.html) implementation, where the application state is managed for you.
### `ExposureNotificationModule`
#### Example
```javascript
import ExposureNotificationModule from 'react-native-exposure-notification-service';
ExposureNotificationModule.start();
```
#### Methods
##### `canSupport()`
```javascript
const canSupport = await ExposureNotificationModule.canSupport();
```
Used to check if the device can support the relevant exposure notification API. This returns a promise that resolves a boolean determining if the device can support tracing or not.
---
##### `isSupported()`
exposure api is available on the device.
```javascript
const supported = await ExposureNotificationModule.isSupported();
```
Used to check if the device has the contact tracing APIs installed. This returns a promise that resolves with true if contact tracing is supported.
---
##### `exposureEnabled()`
```javascript
const enabled = await ExposureNotificationModule.exposureEnabled();
```
Use to check if the contact tracing is enabled. This returns a promise that resolves with true if contact tracing is enabled.
**Note:** On android, if enabled is true, tracing has started.
---
##### `isAuthorised()`
```javascript
const authorised = await ExposureNotificationModule.isAuthorised();
```
Use to check if the user has authorised contact tracing. Calling this method will NOT trigger an authorisation request. This returns a promise that resolves with a string representing the current authorisation state and can be one of: `granted`, `denied`, `blocked`, `unavailable` or `unknown`
---
##### `authoriseExposure()`
```javascript
const authorised = await ExposureNotificationModule.authoriseExposure();
```
Use to trigger an authorisation dialogue. This returns a promise that resolves with true if the user has authorised contact tracing, if they denied the request then false is returned.
---
##### `configure()`
```javascript
ExposureNotificationModule.configure(options);
```
Use to configure the module. This method is synchronous, and should be called before start etc. It takes an options object as a parameter with the following properties:
- `exposureCheckFrequency`: a number representing the period between exposure downloads in minutes
- `serverURL`: a string representing the the server api url (should not have trailing /)
- `keyServerUrl`: a string representing the the key server api url (should not have trailing /). Will default to serverURL
- `keyServerType`: a string representing the the key server type, options are nearform or google. Defaults to nearform
- `authToken`: a string representing the current authorization token
- `refreshToken`: a string representing a token used to refresh the authorization token
- `storeExposuresFor`: a number representing the number of days to store data for
- `fileLimit`: a number representing the file limit
- `version`: a string representing the app version number
- `notificationTitle`: a string representing the title for positive exposure notifications popup,
- `notificationDesc`: a string representing the description for positive exposure notifications popup,
- `callbackNumber`: a string representing the phone number of a user if opted into automatic callback on positive exposure notification,
- `analyticsOptin`: a boolean representing whether the user opted in or not
---
##### `start()`
```javascript
const started = await ExposureNotificationModule.start();
```
Use to start exposure notifications. This method should only be called when canSupport(), isSupported() and isAuthorised() all return/resolve positive values and after configure() has been called.
A promise is returned and will resolve to true after a successful start, otherwise it will resolve to false.
---
##### `status()`
```javascript
const status = await ExposureNotificationModule.status();
```
Used to get the current start status. This method returns a promise that resolves to a map containing 2 keys `state` and `type` both with string values.
The state can return as `active`, `disabled`, `unavailable` or `unknown`, and if set to `disabled` will contain the type presenting the reason why.
The type can return as `bluetooth`, `exposure`, `resolution`, `paused`, `starting` and its meaning should be read in combination with `state`, i.e. a state of `disabled` and a type of `bluetooth` indicates that ENS is disabled because bluetooth is off.
State changes also trigger the event `onStatusChanged`.
---
##### `stop()`
```javascript
ExposureNotificationModule.stop();
```
Used to stop contact tracing and all scheduled tasks. Exposure notifications must be authorised again after this method is called.
---
##### `pause()`
```javascript
ExposureNotificationModule.pause();
```
Used to pause contact tracing. Use start() to unpause.
---
##### `deleteAllData()`
```javascript
const result = await ExposureNotificationModule.deleteAllData();
```
Used to delete all app related data including config & exposure data. This returns a promise that resolves true if all data is successfully removed.
---
##### `deleteExposureData()`
```javascript
const result = await ExposureNotificationModule.deleteExposureData();
```
Used to deletes exposure data but leaves configuration data intact. This returns a promise that resolves true if exposure data is successfully removed.
---
##### `getDiagnosisKeys()`
```javascript
const keys = await ExposureNotificationModule.getDiagnosisKeys();
```
Used to retrieve a devices own diagnosis keys (typically all keys before today within a 14 day window). This returns a promise that resolves to an array of maps containing the key `keyData`, encoded as a base64 string. This key should be used in export files for exposure matching. If the user denies the request, the returned promise will reject.
**Note:** this will trigger a dialog from the underlying exposure notifications API, requesting permission from the device user.
---
##### `checkExposure()`
```javascript
ExposureNotificationModule.checkExposure();
```
Used to manually check exposure during testing. Typically checkExposure is performed in background on schedule specified in configure.
This facilitates an immediate check.
On successful matches, this will raise a notification to the user, and also raise an `exposure` event to the app
---
##### `simulateExposure()`
```javascript
ExposureNotificationModule.simulateExposure();
```
Used to manually generate an exposure alert during testing to make it easier to validate UX flows around exposure events.
This will raise a notification to the user, and also raise an `exposure` event to the app.
---
##### `getCloseContacts()`
```javascript
const contacts = await ExposureNotificationModule.getCloseContacts();
```
Used to retrieve the summary array of matches recorded. This async function returns a promise that resolves to a array of maps with the following keys:
- `exposureAlertDate`
- `attenuationDurations`
- `daysSinceLastExposure`
- `matchedKeyCount`
- `maxRiskScore`
- `summationRiskScore`
---
##### `triggerUpdate()` (Android Only)
```javascript
const result = await ExposureNotificationModule.triggerUpdate();
```
Used to trigger play services update should the user be using a version older than `201817017`
---
#### Subscribing to Events
Create an `emitter` object using the `ExposureNotificationModule`
```javascript
import {NativeEventEmitter} from 'react-native';
import ExposureNotificationModule from 'react-native-exposure-notification-service';
const emitter = new NativeEventEmitter(ExposureNotificationModule);
```
In a component or custom hook, you could use an effect to subscribe to the native module's events as follows:
```javascript
useEffect(() => {
function handleEvent(ev) {
if (ev.exposure) {
console.log(
'You have come in contact with someone diagnosed with COVID-19'
);
}
// handle other events...
}
const subscription = emitter.addListener('exposureEvent', handleEvent);
return () => {
subscription.remove();
emitter.removeListener('exposureEvent', handleEvent);
};
}, []);
```
**There are two major events:**
1. `exposure`: fires when an exposure match event happens, which could be used to update the UI (contains a string)
2. `onStatusChange`: fires when the exposure tracing status changes. This event is a map map containing 2 keys `state` and `type` both with string values.
When `exposure` fires, `getCloseContacts()` would typically be called to retrieve the summary information.
When `onStatusChange` fires, it will contain the same data returned from a call to `status()`
**Note:** Other events may fire, depending on the platform and whether debug/release. These are mostly for debug and error logging only and should not be used for triggering application logic.
### `ExposureProvider`
You should add `ExposureProvider` in your app root component.
#### Example
```tsx
import {
ExposureProvider,
useExposure
} from 'react-native-exposure-notification-service';
function Root() {
return (
<ExposureProvider
traceConfiguration={{
exposureCheckInterval: 120,
storeExposuresFor: 14,
fileLimit: 1,
fileLimitiOS: 2
}
serverUrl="https://your.exposure.api/api"
keyServerUrl="https://your.exposure.api/api"
keyServerType=KeyServerType.nearform
authToken="<PASSWORD>"
refreshToken="<PASSWORD>-api-<PASSWORD>-token"
notificationTitle="Close contact detected"
notificationDescription="Open the app for instructions">
<App />
</ExposureProvider>
);
}
```
#### Props
##### `isReady`
`boolean` (default `false`) If true, will start the exposure notification service if the user has given permission
##### `traceConfiguration` (required)
`object` Tracing related configuration options
```ts
{
exposureCheckInterval: number;
storeExposuresFor: number;
fileLimit: number;
fileLimitiOS: number;
}
```
##### `appVersion` (required)
`string` The build version of your application
##### `serverUrl` (required)
`string` The URL of your exposure API
##### `authToken` (required)
`string` The auth token for your exposure API
##### `refreshToken` (required)
`string` The refresh token for your exposure API
##### `notificationTitle` (required)
`string` The title of a close contact push notification
##### `notificationDescription` (required)
`string` The description of a close contact push notification
##### `callbackNumber` (optional)
`string` The phone number to be used for health authority callbacks
##### `analyticsOptin` (optional)
`boolean` (default `false`) Consent to send analytics to your exposure API's `/metrics` endpoint
### `useExposure`
Use the `useExposure` hook in any component to consume the `ExposureProvider` context & methods
#### Example
```tsx
import {useExposure} from 'react-native-exposure-notification-service';
function MyComponent() {
const {status, permissions, requestPermissions} = useExposure();
return (
<View>
<Text>Exposure status: {status}</Text>
<Text>Exposure permissions: {JSON.stringify(permissions, null, 2)}</Text>
<Button onPress={requestPermissions}>Ask for exposure permissions</Button>
</View>
);
}
```
#### Values
All of these values are available on the return value of `useExposure`
##### `status`
`Status` The current status of the exposure service
##### `supported`
`boolean` The exposure API is available on the device.
##### `canSupport`
`boolean` This device can support the exposure API
##### `isAuthorised`
`boolean` The user has authorised the exposure API
##### `enabled`
`boolean` The exposure API is enabled & has started
##### `contacts`
`CloseContact[] | null` An array of recorded matches
##### `initialised`
`boolean` The native module has successfully initialised
##### `permissions`
`ExposurePermissions` The current status of permissions for `exposure` & `notifications`
##### `start()`
`() => void`
Start the exposure API, check & update the status & check for close contacts
Calls `ExposureNotificationModule.start()`
##### `stop()`
`() => void`
Stop the exposure API & check & update status
Calls `ExposureNotificationModule.stop()`
##### `configure()`
`() => void`
Configure the native module (this is called internally once permissions have been granted)
Calls `ExposureNotificationModule.configure()`
##### `checkExposure()`
`(readDetails: boolean, skipTimeCheck: boolean) => void`
Calls `ExposureNotificationModule.checkExposure()`
##### `getDiagnosisKeys()`
`() => Promise<any[]>`
Calls `ExposureNotificationModule.getDiagnosisKeys()`
##### `exposureEnabled()`
`() => Promise<boolean>`
Calls `ExposureNotificationModule.exposureEnabled()`
##### `authoriseExposure()`
`() => Promise<boolean>`
Calls `ExposureNotificationModule.authoriseExposure()`
##### `deleteAllData()`
`() => Promise<void>`
Calls `ExposureNotificationModule.deleteAllData()` & checks & update the status
##### `supportsExposureApi()`
`() => Promise<void>`
Manually check whether the device supports the exposure API and update the context
##### `getCloseContacts()`
`() => Promise<CloseContact[] | null>`
Manually retrieve a summary of matched records and update the context
Calls `ExposureNotificationModule.getCloseContacts()`
##### `getLogData()`
`() => Promise<{[key: string]: any}>`
Get log data from the exposure API
Calls `ExposureNotificationModule.getLogData()`
##### `triggerUpdate()`
`() => Promise<string | undefined>`
Triggers a play services update on Android if possible
Calls `ExposureNotificationModule.triggerUpdate()`
##### `deleteExposureData()`
`() => Promise<void>`
Deletes exposure data & updates the context
Calls `ExposureNotificationModule.deleteExposureData()`
##### `readPermissions()`
`() => Promise<void>`
Checks the current status of `exposure` and `notifications` permissions and updates the context
##### `askPermissions()`
`() => Promise<void>`
Requests permissions from the user for `exposure` and `notifications` permissions and updates the context
##### `getVersion()`
`() => Promise<Version>`
Returns the version number for the app
##### `getBundleId()`
`() => Promise<string>`
Returns the bundle identifier / package name for the app
##### `setExposureState()`
`(setStateAction: SetStateAction<State>) => void`
Not recommended: Manually update the state in the exposure context. Can be useful for development & simulating different states.
## Test Application
A test application to run the methods above, can be found under the `test-app` folder.
To run this, from the terminal:
- `cd test-app`
- `yarn`
- `yarn start`
- and in a separate terminal window `yarn android` or `yarn ios`
Typically, it is better to run the test application on a device rather than a simulator.
_Note_: The check exposure function will not succeed unless connected to a valid server, if you have access to a valid server, modify `./test-app/config.js` with your settings.
To debug in android you will need to generate a debug keystore file, from the terminal execute:
```
cd android/app
```
then
```
keytool -genkey -v -keystore debug.keystore -storepass <PASSWORD> -alias androiddebugkey -keypass <PASSWORD> -keyalg RSA -keysize 2048 -validity 10000
```
```
cd ../..
```
## Caveats
When building/running an app using the native module, several issues can arise.
### Android
#### Google Play Services (Exposure Notifications)
The Exposure Notification API provided by Google uses the Nearby API installed with Google Play Services.
This API is being rolled out by Google so that as many devices as possible support the API.
The minimum android version required is 23 (marshmallow).
The application performs a test to determine if the required API is available on the device using the `isSupported()` method. If it is not installed google play services must be updated with the Nearby API.
If you have trouble with this, try `triggerUpdate()` to see if Play Services can be updated or update manually.
Applications using the Exposure API should be government agencies, and so not all applications can access the API directly.
#### Minify
If using minify when building an .apk on android, classes are often obfuscated, in which case some errors can arise when using reflection.
To keep required classes from being obfuscated, edit you `proguard-rules.pro` and add the following keep rules
```
-keep public class com.horcrux.svg.** {*;}
-keep class com.google.crypto.tink.** { *; }
-keep class net.sqlcipher.** { *; }
-keep class net.sqlcipher.database.* { *; }
-keep class * extends androidx.room.RoomDatabase
-keep class * extends com.google.auto
-keep class org.checkerframework.checker.nullness.qual.** { *; }
```
### iOS
### Common
#### Reloading the Native Module
If you make changes to the native module, and are referencing the package in your project, you may need to re-install it occasionally. You can do this by pointing at a different commit, branch or version in your package.json.
You can link to commit using `#<commit>` at the end of the git reference, or add `#<feature>\/<branch>` or if versioning use, `#semver:<semver>` (if the repo has any tags or refs matching that range). If none of these are specified, then the master branch is used.
eg.
```json
{
"dependencies": {
"react-native-exposure-notification": "git+https://github.com/covidgreen/react-native-exposure-notification.git#semver:^1.0"
}
}
```
If you are developing and make changes to a branch, and are not seeing changes being reflected in your react-native app, you can try reinstall the module as follows:
```
yarn remove react-native-exposure-notification && yarn add git+https://github.com/covidgreen/react-native-exposure-notification.git`
```
You can also link to the module directly on your file system if developing locally:
```
yarn add file:<path-to-module>`
```
#### Server Connectivity for Diagnosis Key Uploads and Exposure Notifications
In order to upload/download diagnosis keys for exposure notifications, an applications using this module needs to connect to a server that accepts upload of tokens, and packages them into valid export zip files.
## Team
### Lead Maintainers
* @colmharte - <NAME> <<EMAIL>>
* @jasnell - <NAME> <<EMAIL>>
* @aspiringarc - <NAME> <<EMAIL>>
### Core Team
* @ShaunBaker - <NAME> <<EMAIL>>
* @floridemai - <NAME> <<EMAIL>>
* @jackdclark - <NAME> <<EMAIL>>
* @andreaforni - <NAME> <<EMAIL>>
* @jackmurdoch - <NAME> <<EMAIL>>
### Contributors
* @moogster31 - <NAME> <<EMAIL>>
* TBD
### Past Contributors
* TBD
* TBD
## Hosted By
<img alttext="Linux Foundation Public Health Logo" src="https://www.lfph.io/wp-content/themes/cncf-theme/images/lfph/faces-w_2000.png" width="100">
[Linux Foundation Public Health](https://lfph.io)
## Acknowledgements
<a href="https://www.hse.ie"><img alttext="HSE Ireland Logo" src="https://www.hse.ie/images/hse.jpg" width="200" /></a><a href="https://nearform.com"><img alttext="NearForm Logo" src="https://openjsf.org/wp-content/uploads/sites/84/2019/04/nearform.png" width="400" /></a>
## License
Copyright (c) 2020 Health Service Executive (HSE)
Copyright (c) The COVID Green Contributors
[Licensed](LICENSE) under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
<file_sep>package ie.gov.tracing.common
import androidx.annotation.Keep
@Keep
data class ExposureConfig(
val minimumRiskScore: Int,
val attenuationLevelValues: IntArray,
val attenuationWeight: Int,
val daysSinceLastExposureLevelValues: IntArray,
val daysSinceLastExposureWeight: Int,
val durationLevelValues: IntArray,
val durationWeight: Int,
val transmissionRiskLevelValues: IntArray,
val transmissionRiskWeight: Int,
val durationAtAttenuationThresholds: IntArray?,
val thresholdWeightings: DoubleArray?,
val timeThreshold: Int)<file_sep>import * as RNPermission from 'react-native-permissions/lib/typescript';
const {
PERMISSIONS,
RESULTS
} = require('react-native-permissions/lib/commonjs/constants.js');
export {PERMISSIONS, RESULTS};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export async function check(permission: RNPermission.Permission) {
jest.fn();
}
<file_sep>import Foundation
import ExposureNotification
import os.log
@available(iOS 13.5, *)
class ExposureManager {
static let shared = ExposureManager()
let manager = ENManager()
init() {
self.manager.activate { error in
if let error = error as? ENError {
os_log("Error activating ENManager, %@", log: OSLog.setup, type: .error, error.localizedDescription)
} else {
// Ensure exposure notifications are enabled if the app is authorized. The app
// could get into a state where it is authorized, but exposure
// notifications are not enabled, if the user initially denied Exposure Notifications
// during onboarding, but then flipped on the "COVID-19 Exposure Notifications" switch
// in Settings.
if ENManager.authorizationStatus == .authorized && !self.manager.exposureNotificationEnabled {
if !ExposureManager.shared.isPaused() {
self.manager.setExposureNotificationEnabled(true) { error in
// No error handling for attempts to enable on launch
if let error = error as? ENError {
os_log("Unable to enable ENS, %@", log: OSLog.setup, type: .error, error.localizedDescription)
}
}
} else {
os_log("Service is paused so don't start", log: OSLog.setup, type: .debug)
}
}
}
}
}
public func isPaused() -> Bool {
let context = Storage.PersistentContainer.shared.newBackgroundContext()
guard let config = Storage.shared.readSettings(context) else {
return false
}
return config.paused
}
deinit {
manager.invalidate()
}
}
<file_sep>import {NativeModules, EventSubscriptionVendor} from 'react-native';
import {Version} from './types';
export enum AuthorisedStatus {
granted = 'granted',
denied = 'denied',
blocked = 'blocked',
unavailable = 'unavailable',
unknown = 'unknown'
}
export enum KeyServerType {
nearform = 'nearform',
google = 'google'
}
export interface ConfigurationOptions {
exposureCheckFrequency: number;
serverURL: string;
keyServerUrl: string;
keyServerType: KeyServerType;
authToken: string;
refreshToken: string;
storeExposuresFor: number;
fileLimit: number;
notificationTitle: string;
notificationDesc: string;
callbackNumber: string;
analyticsOptin: boolean;
}
export interface DiagnosisKey {
keyData: string;
}
export interface CloseContact {
exposureAlertDate: string;
attenuationDurations: number[];
daysSinceLastExposure: number;
matchedKeyCount: number;
maxRiskScore: number;
summationRiskScore: number;
}
export enum StatusState {
unavailable = 'unavailable',
unknown = 'unknown',
restricted = 'restricted',
disabled = 'disabled',
active = 'active'
}
export enum StatusType {
bluetooth = 'bluetooth',
exposure = 'exposure',
resolution = 'resolution',
paused = 'paused',
starting = 'starting'
}
export interface Status {
state: StatusState;
type?: StatusType[];
}
export interface ExposureNotificationModule extends EventSubscriptionVendor {
canSupport(): Promise<boolean>;
isSupported(): Promise<boolean>;
exposureEnabled(): Promise<boolean>;
isAuthorised(): Promise<AuthorisedStatus>;
authoriseExposure(): Promise<boolean>;
configure(options: ConfigurationOptions): void;
start(): Promise<boolean>;
pause(): Promise<boolean>;
stop(): Promise<boolean>;
deleteAllData(): Promise<boolean>;
deleteExposureData(): Promise<boolean>;
getDiagnosisKeys(): Promise<DiagnosisKey[]>;
checkExposure(readDetails?: boolean, skipTimeCheck?: boolean): void;
simulateExposure(timeDelay?: number): void;
getCloseContacts(): Promise<CloseContact[]>;
status(): Promise<Status>;
getLogData(): Promise<any>;
version(): Promise<Version>;
bundleId(): Promise<string>;
/**
* @platform android
*/
triggerUpdate(): Promise<string>;
}
const {
ExposureNotificationModule: NativeExposureNotificationModule
} = NativeModules;
export default NativeExposureNotificationModule as ExposureNotificationModule;
<file_sep>import Foundation
import ExposureNotification
import os.log
import BackgroundTasks
@available(iOS 13.5, *)
public class ExposureProcessor {
public struct ExposureInfo: Codable {
let daysSinceLastExposure: Int
let attenuationDurations: [Int]
let matchedKeyCount: Int
let maxRiskScore: Int
let exposureDate: Date
var maximumRiskScoreFullRange: Int!
var riskScoreSumFullRange: Int!
var customAttenuationDurations: [Int]!
var details: [ExposureDetails]!
}
public struct ExposureDetails: Codable {
let date: Date
let duration: TimeInterval
let totalRiskScore: ENRiskScore
let transmissionRiskLevel: ENRiskLevel
let attenuationDurations: [Int]
let attenuationValue: ENAttenuation
//metadata
}
private let backgroundName = Bundle.main.bundleIdentifier! + ".exposure-notification"
static public let shared = ExposureProcessor()
var keyValueObservers = [NSKeyValueObservation]()
init() {
}
deinit {
self.keyValueObservers.removeAll()
}
public func authoriseExposure(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
ExposureManager.shared.manager.setExposureNotificationEnabled(true) { error in
if let error = error as? ENError {
os_log("Error enabling notification services, %@", log: OSLog.exposure, type: .error, error.localizedDescription)
return reject("AUTH", "Unable to authorise exposure", error)
}
os_log("Exposure authorised: %d", log: OSLog.exposure, type: .debug, ENManager.authorizationStatus.rawValue)
// return if authorised or not
resolve(ENManager.authorizationStatus == .authorized)
}
}
public func exposureEnabled(_ resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
os_log("Exposure enabled: %d", log: OSLog.exposure, type: .debug, ExposureManager.shared.manager.exposureNotificationEnabled)
resolve(ExposureManager.shared.manager.exposureNotificationEnabled)
}
public func isAuthorised(_ resolve: RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
os_log("Is Authorised: %d", log: OSLog.exposure, type: .debug, ENManager.authorizationStatus.rawValue)
switch ENManager.authorizationStatus {
case .authorized:
resolve("granted")
case .notAuthorized:
resolve("blocked")
case .restricted:
resolve("blocked")
default:
resolve("unknown")
}
}
public func status(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: RCTPromiseRejectBlock) {
var result: [String: Any] = [:]
switch ExposureManager.shared.manager.exposureNotificationStatus {
case .active:
result["state"] = "active"
case .unknown:
result["state"] = "unknown"
case .disabled:
result["state"] = "disabled"
result["type"] = ["exposure"]
case .bluetoothOff:
result["state"] = "disabled"
result["type"] = ["bluetooth"]
case .restricted:
result["state"] = "restricted"
case .paused:
result["state"] = "disabled"
result["type"] = ["paused"]
default:
result["state"] = "unavailable"
result["type"] = ["starting"]
}
if ExposureManager.shared.isPaused() && (result["state"] as! String == "disabled" || result["state"] as! String == "unknown") {
result["state"] = "disabled"
result["type"] = ["paused"]
}
os_log("Status is %d", log: OSLog.checkExposure, type: .debug, ExposureManager.shared.manager.exposureNotificationStatus.rawValue)
self.keyValueObservers.append(ExposureManager.shared.manager.observe(\.exposureNotificationStatus) { manager, change in
NotificationCenter.default.post(name: .onStatusChanged, object: ExposureManager.shared.manager.exposureNotificationStatus)
})
resolve(result)
}
public func start(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
guard ENManager.authorizationStatus == .authorized else {
os_log("Not authorised so can't start", log: OSLog.exposure, type: .info)
return reject("NOTAUTH", "Not authorised to start", nil)
}
let context = Storage.PersistentContainer.shared.newBackgroundContext()
Storage.shared.flagPauseStatus(context, false)
ExposureManager.shared.manager.setExposureNotificationEnabled(true) { error in
if let error = error as? ENError {
os_log("Error starting notification services, %@", log: OSLog.exposure, type: .error, error.localizedDescription)
return reject("START", "Error starting notification services", error)
} else {
os_log("Service started", log: OSLog.exposure, type: .debug)
self.scheduleCheckExposure()
resolve(true)
}
}
self.scheduleCheckExposure()
}
public func pause(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
guard ENManager.authorizationStatus == .authorized else {
os_log("Not authorised so can't pause", log: OSLog.exposure, type: .info)
return reject("NOTAUTH", "Not authorised to start", nil)
}
let context = Storage.PersistentContainer.shared.newBackgroundContext()
Storage.shared.flagPauseStatus(context, true)
ExposureManager.shared.manager.setExposureNotificationEnabled(false) { error in
if let error = error as? ENError {
os_log("Error pausing./stopping notification services, %@", log: OSLog.exposure, type: .error, error.localizedDescription)
/// clear pause flag if we failed to stop ens
Storage.shared.flagPauseStatus(context, false)
return reject("PAUSE", "Error pausing notification services", error)
} else {
os_log("Service paused", log: OSLog.exposure, type: .debug)
resolve(true)
}
}
}
public func stop(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
guard ENManager.authorizationStatus == .authorized else {
os_log("Not authorised so can't stop", log: OSLog.exposure, type: .info)
return reject("NOTAUTH", "Not authorised to stop", nil)
}
let context = Storage.PersistentContainer.shared.newBackgroundContext()
Storage.shared.flagPauseStatus(context, false)
ExposureManager.shared.manager.setExposureNotificationEnabled(false) { error in
if let error = error as? ENError {
os_log("Error stopping notification services, %@", log: OSLog.setup, type: .error, error.localizedDescription)
return reject("STOP", "Error stopping notification services", error)
} else {
os_log("Service stopped", log: OSLog.setup, type: .debug)
resolve(true)
}
}
}
public func getDiagnosisKeys(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
guard ENManager.authorizationStatus == .authorized else {
os_log("Not authorised so can't get keys", log: OSLog.exposure, type: .info)
return reject("Auth", "User has not authorised ENS", nil)
}
// getTestDiagnosisKeys
ExposureManager.shared.manager.getDiagnosisKeys { temporaryExposureKeys, error in
if let error = error as? ENError, error.code == .notAuthorized {
os_log("User did authorise the extraction of keys, %@", log: OSLog.exposure, type: .error, error.localizedDescription)
return reject("Auth", "User did not authorize key extraction", error)
} else if let error = error {
os_log("Unexpected error occurred getting the keys, %@", log: OSLog.exposure, type: .error, error.localizedDescription)
return reject("getKeys", "Error extracting keys", error)
} else {
guard temporaryExposureKeys != nil else {
return resolve([])
}
let codableDiagnosisKeys = temporaryExposureKeys!.compactMap { diagnosisKey -> [String: Any]? in
return [
"keyData": diagnosisKey.keyData.base64EncodedString(),
"rollingPeriod": diagnosisKey.rollingPeriod,
"rollingStartNumber": diagnosisKey.rollingStartNumber,
"transmissionRiskLevel": diagnosisKey.transmissionRiskLevel
]
}
resolve(codableDiagnosisKeys)
}
}
}
public func getLogData(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
let context = Storage.PersistentContainer.shared.newBackgroundContext()
guard let config = Storage.shared.readSettings(context) else {
return resolve([])
}
var data:[String: Any] = [:]
data["lastRun"] = config.datesLastRan
data["lastError"] = config.lastError ?? ""
data["lastIndex"] = config.lastExposureIndex ?? 0
resolve(data)
}
public func getCloseContacts(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
let context = Storage.PersistentContainer.shared.newBackgroundContext()
var exposurePeriod:Int = 14
if let config = Storage.shared.readSettings(context) {
exposurePeriod = config.storeExposuresFor
}
let info = Storage.shared.getExposures(exposurePeriod).reversed()
let exposures = info.compactMap { exposure -> [String: Any]? in
var item: [String: Any] = [
"daysSinceLastExposure": exposure.daysSinceLastExposure,
"matchedKeyCount": exposure.matchedKeyCount,
"maxRiskScore": exposure.maxRiskScore,
"attenuationDurations": exposure.attenuationDurations,
"exposureAlertDate": Int64(exposure.exposureDate.timeIntervalSince1970 * 1000.0),
"maximumRiskScoreFullRange": exposure.maximumRiskScoreFullRange ?? 0,
"riskScoreSumFullRange": exposure.riskScoreSumFullRange ?? 0,
"customAttenuationDurations": exposure.customAttenuationDurations ?? []
]
if let details = exposure.details {
let extraInfo = details.compactMap { detail -> [String: Any]? in
return ["date": Int64(detail.date.timeIntervalSince1970 * 1000.0),
"duration": detail.duration,
"totalRiskScore": detail.totalRiskScore,
"attenuationValue": detail.attenuationValue,
"attenuationDurations": detail.attenuationDurations,
"transmissionRiskLevel": detail.transmissionRiskLevel
]
}
item["details"] = extraInfo
}
return item
}
resolve(exposures)
}
public func deleteAllData(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
Storage.shared.deleteData(false)
resolve(true)
}
public func deleteExposureData(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
Storage.shared.deleteData(true)
resolve(true)
}
public func registerBackgroundProcessing() {
BGTaskScheduler.shared.register(
forTaskWithIdentifier: self.backgroundName,
using: .main) { task in
ExposureProcessor.shared.checkExposureBackground(task as! BGProcessingTask)
}
os_log("Registering background task", log: OSLog.exposure, type: .debug)
self.scheduleCheckExposure()
}
private func checkExposureBackground(_ task: BGTask) {
os_log("Running exposure check in background", log: OSLog.exposure, type: .debug)
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
queue.addOperation(ExposureCheck(false, false, false))
task.expirationHandler = {
os_log("Background task expiring", log: OSLog.checkExposure, type: .debug)
queue.cancelAllOperations()
}
let lastOperation = queue.operations.last
lastOperation?.completionBlock = {
os_log("Background exposure check is complete, %d", log: OSLog.exposure, type: .debug, lastOperation?.isCancelled ?? false)
task.setTaskCompleted(success: !(lastOperation?.isCancelled ?? false))
self.scheduleCheckExposure()
}
}
public func checkExposureForeground(_ exposureDetails: Bool, _ skipTimeCheck: Bool, _ simulateExposure: Bool) {
os_log("Running exposure check in foreground", log: OSLog.exposure, type: .debug)
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
queue.addOperation(ExposureCheck(skipTimeCheck, exposureDetails, simulateExposure))
let lastOperation = queue.operations.last
lastOperation?.completionBlock = {
os_log("Foreground exposure check is complete, %d", log: OSLog.exposure, type: .debug, lastOperation?.isCancelled ?? false)
}
}
private func scheduleCheckExposure() {
let context = Storage.PersistentContainer.shared.newBackgroundContext()
do {
let request = BGProcessingTaskRequest(identifier: self.backgroundName)
request.requiresNetworkConnectivity = true
try BGTaskScheduler.shared.submit(request)
os_log("Scheduling background exposure check", log: OSLog.setup, type: .debug)
} catch {
os_log("An error occurred scheduling background task, %@", log: OSLog.setup, type: .error, error.localizedDescription)
Storage.shared.updateRunData(context, "An error occurred scheduling the background task, \(error.localizedDescription)")
}
}
}
extension Notification.Name {
static var onStatusChanged: Notification.Name {
return .init(rawValue: "ExposureProcessor.onStatusChanged")
}
}
<file_sep>import Foundation
import os.log
import ExposureNotification
import SSZipArchive
import Alamofire
@available(iOS 13.5, *)
class ExposureCheck: AsyncOperation {
public enum endPoints {
case metrics
case exposures
case dataFiles
case callback
case settings
case refresh
}
private struct CodableSettings: Decodable {
let exposureConfig: String
}
private struct CodableExposureConfiguration: Codable {
let minimumRiskScore: ENRiskScore
let attenuationLevelValues: [ENRiskLevelValue]
let attenuationWeight: Double
let daysSinceLastExposureLevelValues: [ENRiskLevelValue]
let daysSinceLastExposureWeight: Double
let durationLevelValues: [ENRiskLevelValue]
let durationWeight: Double
let transmissionRiskLevelValues: [ENRiskLevelValue]
let transmissionRiskWeight: Double
let durationAtAttenuationThresholds: [Int]
let thresholdWeightings: [Double]
let timeThreshold: Int
}
private struct Thresholds {
let thresholdWeightings: [Double]
let timeThreshold: Int
}
private struct CodableExposureFiles: Codable {
let id: Int
let path: String
}
private struct FileDownloadTracking {
let remoteURL: URL
let localURL: URL
let unzipPath: URL
}
private func serverURL(_ url: endPoints) -> String {
switch url {
case .metrics:
return self.configData.serverURL + "/metrics"
case .exposures:
switch self.configData.keyServerType {
case .GoogleRefServer:
return self.configData.keyServerUrl + "/v1/index.txt"
default:
return self.configData.serverURL + "/exposures"
}
case .dataFiles:
switch self.configData.keyServerType {
case .GoogleRefServer:
return self.configData.keyServerUrl + "/"
default:
return self.configData.serverURL + "/data/"
}
case .callback:
return self.configData.serverURL + "/callback"
case .settings:
return self.configData.serverURL + "/settings/exposures"
case .refresh:
return self.configData.serverURL + "/refresh"
}
}
private let defaultSession = URLSession(configuration: .default)
private var dataTask: URLSessionDataTask?
private var configData: Storage.Config!
private var readExposureDetails: Bool = false
private var skipTimeCheck: Bool = false
private var simulateExposureOnly: Bool = false
private let storageContext = Storage.PersistentContainer.shared.newBackgroundContext()
private var sessionManager: Session!
init(_ skipTimeCheck: Bool, _ accessDetails: Bool, _ simulateExposureOnly: Bool) {
super.init()
self.skipTimeCheck = skipTimeCheck
self.readExposureDetails = accessDetails
self.simulateExposureOnly = simulateExposureOnly
}
override func cancel() {
super.cancel()
}
override func main() {
self.configData = Storage.shared.readSettings(self.storageContext)
guard self.configData != nil else {
self.finishNoProcessing("No config set so can't proceeed with checking exposures", false)
return
}
let serverDomain: String = Storage.getDomain(self.configData.serverURL)
let keyServerDomain: String = Storage.getDomain(self.configData.keyServerUrl)
var manager: ServerTrustManager
if (self.configData.keyServerType != Storage.KeyServerType.NearForm) {
manager = ServerTrustManager(evaluators: [serverDomain: PinnedCertificatesTrustEvaluator(), keyServerDomain: DefaultTrustEvaluator()])
} else {
manager = ServerTrustManager(evaluators: [serverDomain: PinnedCertificatesTrustEvaluator()])
}
self.sessionManager = Session(interceptor: RequestInterceptor(self.configData, self.serverURL(.refresh)), serverTrustManager: manager)
os_log("Running with params %@, %@, %@", log: OSLog.checkExposure, type: .debug, self.configData.serverURL, self.configData.authToken, self.configData.refreshToken)
guard (self.configData.lastRunDate!.addingTimeInterval(TimeInterval(self.configData.checkExposureInterval * 60)) < Date() || self.skipTimeCheck) else {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
self.finishNoProcessing("Check was run at \(formatter.string(from: self.configData.lastRunDate!)), interval is \(self.configData.checkExposureInterval), its too soon to check again", false)
return
}
guard ENManager.authorizationStatus == .authorized else {
self.finishNoProcessing("Not authorised so can't run exposure checks")
return
}
guard !ExposureManager.shared.isPaused() else {
self.finishNoProcessing("ENS is paused", false)
return
}
// clean out any expired exposures
Storage.shared.deleteOldExposures(self.configData.storeExposuresFor)
if (self.simulateExposureOnly) {
os_log("Simulating exposure alert", log: OSLog.exposure, type: .debug)
simulateExposureEvent()
return
}
os_log("Starting exposure checking", log: OSLog.exposure, type: .debug)
getExposureFiles { result in
switch result {
case let .failure(error):
self.finishNoProcessing("Failed to retrieve exposure files for processing, \(error.localizedDescription)")
case let .success((urls, lastIndex)):
if urls.count > 0 {
self.processExposures(urls, lastIndex)
}
else {
self.finishNoProcessing("No files available to process", false)
}
}
}
}
private func simulateExposureEvent() {
var info = ExposureProcessor.ExposureInfo(daysSinceLastExposure: 2, attenuationDurations: [30, 30, 30], matchedKeyCount: 1, maxRiskScore: 10, exposureDate: Date())
info.maximumRiskScoreFullRange = 10
info.riskScoreSumFullRange = 10
info.customAttenuationDurations = [30, 30, 30]
let thresholds = Thresholds(thresholdWeightings: [1,1,0], timeThreshold: 15)
let lastId = self.configData.lastExposureIndex!
return self.finishProcessing(.success((info, lastId, thresholds)))
}
private func getDomain(_ url: String) -> String {
let url = URL(string: url)
return url!.host!
}
private func finishNoProcessing(_ message: String, _ log: Bool = true) {
os_log("%@", log: OSLog.checkExposure, type: .info, message)
Storage.shared.updateRunData(self.storageContext, message)
if (log) {
let payload:[String: Any] = [
"description": message
]
self.saveMetric(event: "LOG_ERROR", payload: payload) { _ in
self.trackDailyMetrics()
}
} else {
self.trackDailyMetrics()
}
}
private func processExposures(_ files: [URL], _ lastIndex: Int) {
getExposureConfiguration() { result in
switch result {
case let .success((configuration, thresholds)):
os_log("We have files and config, %d, %@", log: OSLog.checkExposure, type: .debug, files.count, files[0].absoluteString)
ExposureManager.shared.manager.detectExposures(configuration: configuration, diagnosisKeyURLs: files) { summary, error in
self.deleteLocalFiles(files)
if let error = error {
return self.finishProcessing(.failure(self.wrapError("Failure in detectExposures", error)))
}
guard let summaryData = summary else {
os_log("No summary data returned", log: OSLog.checkExposure, type: .debug)
return self.finishProcessing(.success((nil, lastIndex, thresholds)))
}
var info = ExposureProcessor.ExposureInfo(daysSinceLastExposure: summaryData.daysSinceLastExposure, attenuationDurations: self.convertDurations(summaryData.attenuationDurations), matchedKeyCount: Int(summaryData.matchedKeyCount), maxRiskScore: Int(summaryData.maximumRiskScore), exposureDate: Date())
if let meta = summaryData.metadata {
info.maximumRiskScoreFullRange = meta["maximumRiskScoreFullRange"] as? Int
info.riskScoreSumFullRange = meta["riskScoreSumFullRange"] as? Int
info.customAttenuationDurations = self.convertDurations(meta["attenuationDurations"] as? [NSNumber])
}
os_log("Success in checking exposures, %d, %d, %d, %d, %d", log: OSLog.checkExposure, type: .debug, info.daysSinceLastExposure, info.matchedKeyCount, info.attenuationDurations.count,
info.maxRiskScore, self.readExposureDetails)
if info.matchedKeyCount > 0 && !self.readExposureDetails {
return self.finishProcessing(.success((info, lastIndex, thresholds)))
}
os_log("Reading exposure details, only used in test", log: OSLog.checkExposure, type: .debug)
let userExplanation = "To help with testing we are requesting more detailed information on the exposure event."
ExposureManager.shared.manager.getExposureInfo(summary: summary!, userExplanation: userExplanation) { exposures, error in
if let error = error {
self.finishProcessing(.failure(self.wrapError("Error calling getExposureInfo", error)))
return
}
let exposureData = exposures!.map { exposure in
ExposureProcessor.ExposureDetails(date: exposure.date,
duration: exposure.duration,
totalRiskScore: exposure.totalRiskScore,
transmissionRiskLevel: exposure.transmissionRiskLevel,
attenuationDurations: self.convertDurations(exposure.attenuationDurations),
attenuationValue: exposure.attenuationValue)
}
info.details = exposureData
self.finishProcessing(.success((info, lastIndex, thresholds)))
}
}
case let .failure(error):
self.finishNoProcessing("Failed to extract settings, \(error.localizedDescription)")
}
}
}
private func wrapError(_ description: String, _ error: Error) -> Error {
let err = error as NSError
return NSError(domain: err.domain, code: err.code, userInfo: [NSLocalizedDescriptionKey: "\(description), \(error.localizedDescription)"])
}
private func deleteLocalFiles(_ files:[URL]) {
for localURL in files {
try? FileManager.default.removeItem(at: localURL)
}
}
private func convertDurations(_ durations: [NSNumber]?) -> [Int] {
let empty: [NSNumber] = []
return (durations ?? empty).compactMap { item in
Int(item.doubleValue / 60.0)
}
}
private func finishProcessing(_ result: Result<(ExposureProcessor.ExposureInfo?, Int, Thresholds), Error>) {
switch result {
case let .success((exposureData, lastFileIndex, thresholds)):
os_log("We successfully completed checks", log: OSLog.checkExposure, type: .info)
Storage.shared.updateRunData(self.storageContext, "", lastFileIndex)
guard let exposures = exposureData, exposures.matchedKeyCount > 0 else {
os_log("No keys matched, no exposures detected", log: OSLog.checkExposure, type: .debug)
return self.trackDailyMetrics()
}
let durations:[Int] = exposures.customAttenuationDurations ?? exposures.attenuationDurations
guard thresholds.thresholdWeightings.count >= durations.count else {
return self.finishNoProcessing("Failure processing exposure keys, thresholds not correctly defined");
}
var contactTime = 0
for (index, element) in durations.enumerated() {
contactTime += Int(Double(element) * thresholds.thresholdWeightings[index])
}
os_log("Calculated contact time, %@, %d, %d", log: OSLog.checkExposure, type: .debug, durations.map { String($0) }, contactTime, thresholds.timeThreshold)
if contactTime >= thresholds.timeThreshold && exposures.maximumRiskScoreFullRange > 0 {
os_log("Detected exposure event", log: OSLog.checkExposure, type: .info)
Storage.shared.saveExposureDetails(self.storageContext, exposures)
self.triggerUserNotification(exposures) { _ in
self.trackDailyMetrics()
}
} else {
os_log("Exposures outside thresholds", log: OSLog.checkExposure, type: .info)
self.trackDailyMetrics()
}
case let .failure(error):
return self.finishNoProcessing("Failure processing exposure keys, \(error.localizedDescription)");
}
}
private func trackDailyMetrics() {
guard !self.isCancelled else {
return self.cancelProcessing()
}
guard self.configData != nil else {
// don't track daily trace if config not setup
return self.finish()
}
let calendar = Calendar.current
let checkDate: Date = self.configData.dailyTrace ?? calendar.date(byAdding: .day, value: -1, to: Date())!
if (!self.isCancelled && !calendar.isDate(Date(), inSameDayAs: checkDate)) {
Storage.shared.updateDailyTrace(self.storageContext, date: Date())
self.saveMetric(event: "DAILY_ACTIVE_TRACE") { _ in
self.finish()
}
} else {
self.finish()
}
}
private func getExposureFiles(_ completion: @escaping (Result<([URL], Int), Error>) -> Void) {
guard !self.isCancelled else {
return self.cancelProcessing()
}
os_log("Key server type set to %@", log: OSLog.checkExposure, type: .debug, self.configData.keyServerType.rawValue)
switch self.configData.keyServerType {
case .GoogleRefServer:
getGoogleExposureFiles(completion)
default:
getNearFormExposureFiles(completion)
}
}
private func getNearFormExposureFiles(_ completion: @escaping (Result<([URL], Int), Error>) -> Void) {
guard !self.isCancelled else {
return self.cancelProcessing()
}
let lastId = self.configData.lastExposureIndex ?? 0
os_log("Checking for exposures against nearform server since %d", log: OSLog.checkExposure, type: .debug, lastId)
self.sessionManager.request(self.serverURL(.exposures), parameters: ["since": lastId, "limit": self.configData.fileLimit])
.validate()
.responseDecodable(of: [CodableExposureFiles].self) { response in
switch response.result {
case .success:
self.processFileLinks(response.value!, completion)
case let .failure(error):
os_log("Failure occurred while reading exposure files %@", log: OSLog.checkExposure, type: .error, error.localizedDescription)
completion(.failure(error))
}
}
}
private func getGoogleExposureFiles(_ completion: @escaping (Result<([URL], Int), Error>) -> Void) {
guard !self.isCancelled else {
return self.cancelProcessing()
}
os_log("Checking for exposures against google server type, %@", log: OSLog.checkExposure, type: .debug, self.serverURL(.exposures))
self.sessionManager.request(self.serverURL(.exposures))
.validate()
.responseString { response in
switch response.result {
case .success:
let files = self.findFilesToProcess(response.value!)
self.processFileLinks(files, completion)
case let .failure(error):
os_log("Failure occurred while reading exposure files %@", log: OSLog.checkExposure, type: .error, error.localizedDescription)
completion(.failure(error))
}
}
}
private func processFileLinks(_ files: [CodableExposureFiles], _ completion: @escaping (Result<([URL], Int), Error>) -> Void) {
var lastId = self.configData.lastExposureIndex ?? 0
if files.count > 0 {
os_log("Files available to process, %d", log: OSLog.checkExposure, type: .debug, files.count)
lastId = files.last!.id
let urls: [URL] = files.map{ url in
lastId = max(url.id, lastId)
return URL(string: self.serverURL(.dataFiles) + url.path)!
}
self.downloadFilesForProcessing(urls) { result in
switch result {
case let .success(localURLS):
completion(.success((localURLS, lastId)))
case let .failure(error):
completion(.failure(error))
}
}
} else {
/// no keys to be processed
os_log("No key files returned from server, last file index: %d", log: OSLog.checkExposure, type: .info, lastId)
completion(.success(([], lastId)))
}
}
private func findFilesToProcess(_ fileList: String) -> [CodableExposureFiles] {
/// fileList if of format
/*
v1/1597846020-1597846080-00001.zip
v1/1597847700-1597847760-00001.zip
v1/1597848660-1597848720-00001.zip
*/
let listData = fileList.split(separator: "\n").map { String($0) }
var filesToProcess: [CodableExposureFiles] = []
for key in listData {
let fileURL = URL(fileURLWithPath: key)
let fileName = fileURL.deletingPathExtension().lastPathComponent
let idVal = self.parseGoogleFileName(fileName)
os_log("Parsing google file entry item %@, %@, %d", log: OSLog.checkExposure, type: .debug, String(key), fileName, idVal)
if idVal > -1 {
let fileItem = CodableExposureFiles(id: idVal, path: String(key))
filesToProcess.append(fileItem)
}
}
if (self.configData.lastExposureIndex <= 0) {
return Array(filesToProcess.suffix(self.configData.fileLimit))
} else {
return Array(filesToProcess.prefix(self.configData.fileLimit))
}
}
private func parseGoogleFileName(_ key: String) -> Int {
/// key format is 1598375820-1598375880-00001
/// start time - end time - ??
/// we look for any start times > than the last end time we stored
/// return the end time as the last id
let keyParts = key.split(separator: "-").map { String($0) }
let lastId = self.configData.lastExposureIndex ?? 0
if (Int(keyParts[0]) ?? 0 >= lastId) {
return Int(keyParts[1]) ?? 0
} else {
return -1
}
}
private func downloadFilesForProcessing(_ files: [URL], _ completion: @escaping (Result<[URL], Error>) -> Void) {
guard !self.isCancelled else {
return self.cancelProcessing()
}
var processedFiles: Int = 0
var validFiles: [URL] = []
let downloadData: [FileDownloadTracking] = files.enumerated().compactMap { (index, file) in
let local = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("diagnosisZip-\(index)")
let unzipPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("diagnosisKeys-\(index)", isDirectory: true)
return FileDownloadTracking(remoteURL: file, localURL: local, unzipPath: unzipPath)
}
func downloadComplete(_ path: String, _ succeeded: Bool, _ error: Error?) {
if error != nil {
os_log("Error unzipping keys file, %@", log: OSLog.checkExposure, type: .error, error!.localizedDescription)
}
os_log("Keys file successfully unzipped, %@, %d", log: OSLog.checkExposure, type: .debug, path, succeeded)
}
downloadData.enumerated().forEach { (index, item) in
self.downloadURL(item.remoteURL, item.localURL) { result in
switch result {
case let .success(url):
do {
if item.remoteURL.path.hasSuffix(".zip") {
try? FileManager.default.createDirectory(at: item.unzipPath, withIntermediateDirectories: false, attributes: nil)
let success = SSZipArchive.unzipFile(atPath: url.path, toDestination: item.unzipPath.path, progressHandler: nil, completionHandler: downloadComplete)
if success {
let fileURLs = try FileManager.default.contentsOfDirectory(at: item.unzipPath, includingPropertiesForKeys: nil)
for (file) in fileURLs.enumerated() {
var renamePath: URL!
if file.element.path.hasSuffix(".sig") {
renamePath = item.unzipPath.appendingPathComponent("export\(index).sig")
} else if file.element.path.hasSuffix(".bin") {
renamePath = item.unzipPath.appendingPathComponent("export\(index).bin")
}
if renamePath != nil {
try? FileManager.default.moveItem(at: file.element, to: renamePath)
validFiles.append(renamePath)
}
}
}
/// remove the zip
try? FileManager.default.removeItem(at: url)
} else {
/// not a zip, used during testing
validFiles.append(url)
}
processedFiles += 1
} catch {
try? FileManager.default.removeItem(at: url)
os_log("Error unzipping, %@", log: OSLog.checkExposure, type: .error, error.localizedDescription)
processedFiles += 1
}
case let .failure(error):
try? FileManager.default.removeItem(at: item.localURL)
os_log("Failed to download the file %@, %@", log: OSLog.checkExposure, type: .error, item.remoteURL.absoluteString, error.localizedDescription)
processedFiles += 1
}
if processedFiles == downloadData.count {
if validFiles.count > 0 {
completion(.success(validFiles))
} else {
completion(.failure(NSError(domain:"download", code: 400, userInfo:nil)))
}
}
}
}
}
private func cancelProcessing() {
Storage.shared.updateRunData(self.storageContext, "Background processing expiring, cancelling")
self.finish()
}
private func downloadURL(_ fileURL: URL, _ destinationFileUrl: URL, _ completion: @escaping (Result<URL, Error>) -> Void) {
guard !self.isCancelled else {
return self.cancelProcessing()
}
let destination: DownloadRequest.Destination = { _, _ in
return (destinationFileUrl, [.removePreviousFile, .createIntermediateDirectories])
}
self.sessionManager.download(
fileURL,
method: .get,
to: destination).downloadProgress(closure: { (progress) in
/// progress closure
})
.validate()
.response() { response in
switch response.result {
case .success:
completion(.success(destinationFileUrl))
case let .failure(error):
os_log("Failed to download file successfully, %@, %@", log: OSLog.checkExposure, type: .error, fileURL.absoluteString, error.localizedDescription)
completion(.failure(error))
}
}
}
private func getExposureConfiguration(_ completion: @escaping (Result<(ENExposureConfiguration, Thresholds), Error>) -> Void) {
guard !self.isCancelled else {
return self.cancelProcessing()
}
self.sessionManager.request(self.serverURL(.settings))
.validate()
.responseDecodable(of: CodableSettings.self) { response in
switch response.result {
case .success:
let exposureData = response.value!
do {
let codableExposureConfiguration = try JSONDecoder().decode(CodableExposureConfiguration.self, from: exposureData.exposureConfig.data(using: .utf8)!)
let exposureConfiguration = ENExposureConfiguration()
exposureConfiguration.minimumRiskScore = codableExposureConfiguration.minimumRiskScore
exposureConfiguration.attenuationLevelValues = codableExposureConfiguration.attenuationLevelValues as [NSNumber]
exposureConfiguration.attenuationWeight = codableExposureConfiguration.attenuationWeight
exposureConfiguration.daysSinceLastExposureLevelValues = codableExposureConfiguration.daysSinceLastExposureLevelValues as [NSNumber]
exposureConfiguration.daysSinceLastExposureWeight = codableExposureConfiguration.daysSinceLastExposureWeight
exposureConfiguration.durationLevelValues = codableExposureConfiguration.durationLevelValues as [NSNumber]
exposureConfiguration.durationWeight = codableExposureConfiguration.durationWeight
exposureConfiguration.transmissionRiskLevelValues = codableExposureConfiguration.transmissionRiskLevelValues as [NSNumber]
exposureConfiguration.transmissionRiskWeight = codableExposureConfiguration.transmissionRiskWeight
let meta:[AnyHashable: Any] = [AnyHashable("attenuationDurationThresholds"): codableExposureConfiguration.durationAtAttenuationThresholds as [NSNumber]]
exposureConfiguration.metadata = meta
let thresholds = Thresholds(thresholdWeightings: codableExposureConfiguration.thresholdWeightings, timeThreshold: codableExposureConfiguration.timeThreshold)
completion(.success((exposureConfiguration, thresholds)))
} catch {
os_log("Unable to decode settings data, %@", log: OSLog.checkExposure, type: .error, error.localizedDescription)
completion(.failure(error))
}
case let .failure(error):
os_log("Error occurred retrieveing settings data, %@", log: OSLog.checkExposure, type: .error, error.localizedDescription)
completion(.failure(error))
}
}
}
private func triggerUserNotification(_ exposures: ExposureProcessor.ExposureInfo, _ completion: @escaping (Result<Bool, Error>) -> Void) {
let content = UNMutableNotificationContent()
let calendar = Calendar.current
let dateToday = calendar.startOfDay(for: Date())
content.title = self.configData.notificationTitle
content.body = self.configData.notificationDesc
content.badge = 1
content.sound = .default
let request = UNNotificationRequest(identifier: "exposure", content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
DispatchQueue.main.async {
if let error = error {
os_log("Notification error %@", log: OSLog.checkExposure, type: .error, error.localizedDescription)
}
}
}
let payload:[String: Any] = [
"matchedKeys": exposures.matchedKeyCount,
"attenuations": exposures.customAttenuationDurations ?? exposures.attenuationDurations,
"maxRiskScore": exposures.maxRiskScore
]
self.saveMetric(event: "CONTACT_NOTIFICATION", payload: payload) { _ in
let lastExposure = calendar.date(byAdding: .day, value: (0 - exposures.daysSinceLastExposure), to: dateToday)
self.triggerCallBack(lastExposure!, payload, completion)
}
}
private func triggerCallBack(_ lastExposure: Date, _ payload: [String: Any], _ completion: @escaping (Result<Bool, Error>) -> Void) {
guard !self.isCancelled else {
return self.cancelProcessing()
}
guard let callbackNum = self.configData.callbackNumber, !callbackNum.isEmpty else {
os_log("No callback number configured", log: OSLog.checkExposure, type: .info)
return completion(.success(true))
}
let notificationRaised = self.configData.notificationRaised
guard !(notificationRaised ?? false) else {
os_log("Callback number already sent to server", log: OSLog.checkExposure, type: .info)
return completion(.success(true))
}
self.sessionManager.request(self.serverURL(.callback), method: .post , parameters: ["mobile": callbackNum, "closeContactDate": Int64(lastExposure.timeIntervalSince1970 * 1000.0), "payload": payload], encoding: JSONEncoding.default)
.validate()
.response() { response in
switch response.result {
case .success:
os_log("Request for callback sent", log: OSLog.checkExposure, type: .debug)
Storage.shared.flagNotificationRaised(self.storageContext)
completion(.success(true))
case let .failure(error):
os_log("Unable to send callback request, %@", log: OSLog.checkExposure, type: .error, error.localizedDescription)
completion(.failure(error))
}
}
}
private func saveMetric(event: String, completion: @escaping (Result<Bool, Error>) -> Void) {
self.saveMetric(event: event, payload: nil, completion: completion)
}
private func saveMetric(event: String, payload: [String:Any]?, completion: @escaping (Result<Bool, Error>) -> Void) {
guard !self.isCancelled else {
return self.cancelProcessing()
}
guard self.configData != nil else {
// don't track daily trace if config not setup
return completion(.success(true))
}
if (!self.configData.analyticsOptin) {
os_log("Metric opt out", log: OSLog.exposure, type: .error)
return completion(.success(true))
}
os_log("Sending metric, %@", log:OSLog.checkExposure, type: .info, event)
var params: Parameters = [:]
params["os"] = "ios"
params["event"] = event
params["version"] = Storage.shared.version()["display"]
if let packet = payload {
params["payload"] = packet
}
self.sessionManager.request(self.serverURL(.metrics), method: .post , parameters: params, encoding: JSONEncoding.default)
.validate()
.response() { response in
switch response.result {
case .success:
os_log("Metric sent, %@", log: OSLog.checkExposure, type: .debug, event)
completion(.success(true))
case let .failure(error):
os_log("Unable to send metric, %@", log: OSLog.checkExposure, type: .error, error.localizedDescription)
completion(.failure(error))
}
}
}
}
class RequestInterceptor: Alamofire.RequestInterceptor {
private struct CodableToken: Codable {
let token: String
}
private var config: Storage.Config
private var refreshURL: String
init(_ config: Storage.Config, _ refreshURL: String ) {
self.config = config
self.refreshURL = refreshURL
}
func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
var urlRequest = urlRequest
let nfServer = Storage.getDomain(self.config.serverURL)
if (urlRequest.url?.host == nfServer) {
/// Set the Authorization header value using the access token, only on nearform server requests
urlRequest.setValue("Bearer " + self.config.authToken, forHTTPHeaderField: "Authorization")
}
completion(.success(urlRequest))
}
func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
guard let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401, request.retryCount == 0 else {
/// The request did not fail due to a 401 Unauthorized response.
/// Return the original error and don't retry the request.
return completion(.doNotRetryWithError(error))
}
refreshToken { result in
switch result {
case .success(_):
/// After updating the token we can retry the original request.
completion(.retry)
case .failure(let error):
completion(.doNotRetryWithError(error))
}
}
}
private func refreshToken(_ completion: @escaping (Result<Bool, Error>) -> Void) {
let headers: HTTPHeaders = [
.accept("application/json"),
.authorization(bearerToken: self.config.refreshToken)
]
AF.request(self.refreshURL, method: .post, headers: headers)
.validate()
.responseDecodable(of: CodableToken.self) { response in
switch response.result {
case .success:
self.config.authToken = response.value!.token
Storage.shared.updateAppSettings(self.config)
completion(.success(true))
case let .failure(error):
completion(.failure(error))
}
}
}
}
<file_sep>package ie.gov.tracing.common
import com.facebook.react.bridge.ReadableMap
import ie.gov.tracing.Tracing
import ie.gov.tracing.storage.SharedPrefs
class Config {
companion object {
fun configure(params: ReadableMap) {
try {
Events.raiseEvent(Events.INFO, "Saving configuration...")
SharedPrefs.setLong("exposureCheckFrequency", params.getInt("exposureCheckFrequency").toLong(), Tracing.context)
SharedPrefs.setLong("storeExposuresFor", params.getInt("storeExposuresFor").toLong(), Tracing.context)
SharedPrefs.setLong("fileLimit", params.getInt("fileLimit").toLong(), Tracing.context)
SharedPrefs.setBoolean("analyticsOptin", params.getBoolean("analyticsOptin"), Tracing.context)
SharedPrefs.setString("serverUrl", params.getString("serverURL")!!, Tracing.context)
var keyServer = params.getString("keyServerUrl")!!
if (keyServer.isEmpty()) {
keyServer = params.getString("serverURL")!!
}
var keyServerType = params.getString("keyServerType")!!
if (keyServerType.isEmpty()) {
keyServerType = "nearform"
}
SharedPrefs.setString("keyServerUrl", keyServer, Tracing.context)
SharedPrefs.setString("keyServerType", keyServerType, Tracing.context)
SharedPrefs.setString("notificationTitle", params.getString("notificationTitle")!!, Tracing.context)
SharedPrefs.setString("notificationDesc", params.getString("notificationDesc")!!, Tracing.context)
// this is sensitive user data, our shared prefs class is uses EncryptedSharedPreferences and MasterKeys
SharedPrefs.setString("refreshToken", params.getString("refreshToken")!!, Tracing.context)
SharedPrefs.setString("authToken", params.getString("authToken")!!, Tracing.context)
SharedPrefs.setString("callbackNumber", params.getString("callbackNumber")!!, Tracing.context)
} catch(ex: Exception) {
Events.raiseError("Error setting configuration: ", ex)
}
}
}
}<file_sep>package ie.gov.tracing.storage;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;
import net.sqlcipher.database.SupportFactory;
import java.util.Date;
import java.util.UUID;
import ie.gov.tracing.common.Events;
@Database(
entities = {
ExposureEntity.class,
TokenEntity.class
},
version = 1,
exportSchema = false)
@TypeConverters({ZonedDateTimeTypeConverter.class})
public abstract class ExposureNotificationDatabase extends RoomDatabase {
private static final String DATABASE_NAME = "exposurenotifications_encrypted";
@SuppressWarnings("ConstantField") // Singleton pattern.
private static volatile ExposureNotificationDatabase INSTANCE;
abstract ExposureDao exposureDao();
abstract TokenDao tokenDao();
static synchronized ExposureNotificationDatabase getInstance(Context context) {
if (INSTANCE == null) {
Events.raiseEvent(Events.INFO, "buildDatabase - start: " + new Date());
INSTANCE = buildDatabase(context);
Events.raiseEvent(Events.INFO, "buildDatabase - done: " + new Date());
}
return INSTANCE;
}
private static ExposureNotificationDatabase buildDatabase(Context context) {
try {
String password = SharedPrefs.getString("password", context);
if (password.isEmpty()) {
Events.raiseEvent(Events.INFO, "buildDatabase - no password, creating...");
nukeDatabase(context); // just in case we had previous one, new password = new database
password = UUID.randomUUID().toString();
SharedPrefs.setString("password", password, context);
Events.raiseEvent(Events.INFO, "buildDatabase - password set");
}
Events.raiseEvent(Events.INFO, "buildDatabase - building...");
SupportFactory sqlcipherFactory = new SupportFactory(password.getBytes());
return Room.databaseBuilder(
context.getApplicationContext(), ExposureNotificationDatabase.class, DATABASE_NAME).openHelperFactory(sqlcipherFactory)
.build();
}
catch (Exception ex) {
Events.raiseError("buildDatabase", ex);
}
return null;
}
public static void nukeDatabase (Context context) {
try {
Events.raiseEvent(Events.INFO, "Nuking database");
context.getApplicationContext().deleteDatabase(DATABASE_NAME);
INSTANCE = null;
Events.raiseEvent(Events.INFO, "Database nuked");
} catch(Exception e) {
Events.raiseError("Error nuking database", e);
}
}
}
<file_sep>module.exports = {
"*.{js,jsx,ts,tsx}": "npm run lint:fix",
// this has to be a function to prevent it from passing the files to tsc
"*.{ts,tsx}": () => "npm run typecheck",
}
<file_sep>// android/build.gradle
// based on:
//
// * https://github.com/facebook/react-native/blob/0.60-stable/template/android/build.gradle
// original location:
// - https://github.com/facebook/react-native/blob/0.58-stable/local-cli/templates/HelloWorld/android/build.gradle
//
// * https://github.com/facebook/react-native/blob/0.60-stable/template/android/app/build.gradle
// original location:
// - https://github.com/facebook/react-native/blob/0.58-stable/local-cli/templates/HelloWorld/android/app/build.gradle
def DEFAULT_COMPILE_SDK_VERSION = 28
def DEFAULT_MIN_SDK_VERSION = 23
def DEFAULT_TARGET_SDK_VERSION = 28
def safeExtGet(prop, fallback) {
rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
}
apply plugin: 'com.android.library'
apply plugin: 'maven'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
buildscript {
ext {
kotlinVersion = '1.3.71'
kotlin_version = '1.3.71'
}
dependencies {
//classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
// The Android Gradle plugin is only required when opening the android folder stand-alone.
// This avoids unnecessary downloads and potential conflicts when the library is included as a
// module dependency in an application project.
// ref: https://docs.gradle.org/current/userguide/tutorial_using_tasks.html#sec:build_script_external_dependencies
// if (project == rootProject) {
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${project.ext.kotlinVersion}"
}
// }
}
android {
compileSdkVersion safeExtGet('compileSdkVersion', DEFAULT_COMPILE_SDK_VERSION)
defaultConfig {
minSdkVersion safeExtGet('minSdkVersion', DEFAULT_MIN_SDK_VERSION)
targetSdkVersion safeExtGet('targetSdkVersion', DEFAULT_TARGET_SDK_VERSION)
versionCode 1
versionName "1.0"
}
lintOptions {
abortOnError false
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions { jvmTarget = "1.8" }
}
repositories {
// ref: https://www.baeldung.com/maven-local-repository
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../../node_modules/react-native/android"
}
maven {
// Android JSC is installed from npm
url "$rootDir/../../node_modules/jsc-android/dist"
}
google()
jcenter()
mavenCentral()
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
//noinspection GradleDynamicVersion
implementation 'com.facebook.react:react-native:+' // From node_modules
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
implementation 'androidx.preference:preference:1.1.0'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
//RX
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.15'
//GSON
implementation 'com.google.code.gson:gson:2.8.5'
// WorkManager
def work_version = "2.4.0"
implementation "androidx.work:work-runtime:$work_version"
implementation "androidx.work:work-runtime-ktx:$work_version"
implementation "androidx.work:work-rxjava2:$work_version"
implementation "androidx.work:work-gcm:$work_version"
implementation 'androidx.concurrent:concurrent-futures:1.0.0'
implementation 'com.google.android.gms:play-services-base:17.2.1'
implementation 'com.google.android.gms:play-services-basement:17.2.1'
implementation 'com.google.android.gms:play-services-safetynet:17.0.0'
implementation 'com.google.android.gms:play-services-tasks:17.0.2'
implementation 'com.google.android.gms:play-services-vision:20.0.0'
implementation 'com.jakewharton.threetenabp:threetenabp:1.2.4'
implementation 'commons-io:commons-io:2.5'
implementation 'org.apache.httpcomponents:httpclient:4.5.6'
// database
implementation 'net.zetetic:android-database-sqlcipher:4.4.0@aar'
implementation 'com.google.guava:guava:29.0-android'
implementation 'androidx.room:room-guava:2.2.5'
implementation 'androidx.room:room-runtime:2.2.5'
kapt 'androidx.room:room-compiler:2.2.5'
// Auto-value
implementation 'com.google.auto.value:auto-value-annotations:1.7'
kapt 'com.google.auto.value:auto-value:1.7'
implementation "androidx.security:security-crypto:1.0.0-rc02"
// test libraries
testImplementation 'junit:junit:4.13'
testImplementation 'androidx.test.ext:junit:1.1.2-beta01'
testImplementation 'androidx.test:core:1.3.0-beta01'
testImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
testImplementation 'com.android.support.test:runner:1.0.2'
testImplementation 'com.google.truth:truth:1.0.1'
testImplementation 'org.robolectric:robolectric:4.3.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation "androidx.work:work-testing:$work_version"
}
def configureReactNativePom(def pom) {
def packageJson = new groovy.json.JsonSlurper().parseText(file('../package.json').text)
pom.project {
name packageJson.title
artifactId packageJson.name
version = packageJson.version
group = "com.reactlibrary"
description packageJson.description
url packageJson.repository.baseUrl
licenses {
license {
name packageJson.license
url packageJson.repository.baseUrl + '/blob/master/' + packageJson.licenseFilename
distribution 'repo'
}
}
developers {
developer {
id packageJson.author.username
name packageJson.author.name
}
}
}
}
afterEvaluate { project ->
// some Gradle build hooks ref:
// https://www.oreilly.com/library/view/gradle-beyond-the/9781449373801/ch03.html
task androidJavadoc(type: Javadoc) {
source = android.sourceSets.main.java.srcDirs
classpath += files(android.bootClasspath)
classpath += files(project.getConfigurations().getByName('compile').asList())
include '**/*.java'
}
task androidJavadocJar(type: Jar, dependsOn: androidJavadoc) {
classifier = 'javadoc'
from androidJavadoc.destinationDir
}
task androidSourcesJar(type: Jar) {
classifier = 'sources'
from android.sourceSets.main.java.srcDirs
include '**/*.java'
}
android.libraryVariants.all { variant ->
def name = variant.name.capitalize()
def javaCompileTask = variant.javaCompileProvider.get()
task "jar${name}"(type: Jar, dependsOn: javaCompileTask) {
from javaCompileTask.destinationDir
}
}
artifacts {
archives androidSourcesJar
archives androidJavadocJar
}
task installArchives(type: Upload) {
configuration = configurations.archives
repositories.mavenDeployer {
// Deploy to react-native-event-bridge/maven, ready to publish to npm
repository url: "file://${projectDir}/../android/maven"
configureReactNativePom pom
}
}
}<file_sep>package ie.gov.tracing.nearby;
import android.content.Context;
import com.google.android.gms.nearby.Nearby;
import com.google.android.gms.nearby.exposurenotification.ExposureConfiguration;
//import com.google.android.gms.nearby.exposurenotification.ExposureInformation;
import com.google.android.gms.nearby.exposurenotification.ExposureNotificationClient;
import com.google.android.gms.nearby.exposurenotification.ExposureSummary;
import com.google.android.gms.nearby.exposurenotification.TemporaryExposureKey;
import com.google.android.gms.tasks.Task;
import com.google.gson.Gson;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import ie.gov.tracing.common.Events;
import ie.gov.tracing.common.ExposureConfig;
import ie.gov.tracing.network.Fetcher;
import ie.gov.tracing.storage.SharedPrefs;
public class ExposureNotificationClientWrapper {
private static ExposureNotificationClientWrapper INSTANCE;
private final Context appContext;
private final ExposureNotificationClient exposureNotificationClient;
public static ExposureNotificationClientWrapper get(Context context) {
if (INSTANCE == null) {
INSTANCE = new ExposureNotificationClientWrapper(context);
}
return INSTANCE;
}
private ExposureNotificationClientWrapper(Context context) {
this.appContext = context.getApplicationContext();
exposureNotificationClient = Nearby.getExposureNotificationClient(appContext);
}
Task<Void> start() {
return exposureNotificationClient.start();
}
Task<Void> stop() {
return exposureNotificationClient.stop();
}
public Task<Boolean> isEnabled() {
return exposureNotificationClient.isEnabled();
}
public Task<List<TemporaryExposureKey>> getTemporaryExposureKeyHistory() {
// will only return inactive keys i.e. not today's
return exposureNotificationClient.getTemporaryExposureKeyHistory();
}
Task<Void> provideDiagnosisKeys(List<File> files, String token) {
String settings = Fetcher.fetch("/settings/exposures", false, false, appContext);
Gson gson = new Gson();
Map map = gson.fromJson(settings, Map.class);
String exposureConfig = (String) map.get("exposureConfig");
ExposureConfig config = gson.fromJson(exposureConfig, ExposureConfig.class);
Events.raiseEvent(Events.INFO, "mapping exposure configuration with " + config);
// error will be thrown here if config is not complete
ExposureConfiguration exposureConfiguration =
new ExposureConfiguration.ExposureConfigurationBuilder()
.setAttenuationScores(config.getAttenuationLevelValues())
.setDaysSinceLastExposureScores(config.getDaysSinceLastExposureLevelValues())
.setTransmissionRiskScores(config.getTransmissionRiskLevelValues())
.setDurationScores(config.getDurationLevelValues())
.setMinimumRiskScore(config.getMinimumRiskScore())
.setDurationWeight(config.getDurationWeight())
.setAttenuationWeight(config.getAttenuationWeight())
.setTransmissionRiskWeight(config.getTransmissionRiskWeight())
.setDaysSinceLastExposureWeight(config.getDaysSinceLastExposureWeight())
.setDurationAtAttenuationThresholds(config.getDurationAtAttenuationThresholds()).build();
// we use these when we receive match broadcasts from exposure API
SharedPrefs.setString("thresholdWeightings", Arrays.toString(config.getThresholdWeightings()), appContext);
SharedPrefs.setLong("timeThreshold", config.getTimeThreshold(), appContext);
Events.raiseEvent(Events.INFO, "processing diagnosis keys with: " + exposureConfiguration);
return exposureNotificationClient
.provideDiagnosisKeys(files, exposureConfiguration, token);
}
Task<ExposureSummary> getExposureSummary(String token) {
return exposureNotificationClient.getExposureSummary(token);
}
public boolean deviceSupportsLocationlessScanning() {
return exposureNotificationClient.deviceSupportsLocationlessScanning();
}
/*
Task<List<ExposureInformation>> getExposureInformation(String token) {
return exposureNotificationClient.getExposureInformation(token);
}
*/
}
| 7c825fac51d66b74fad9efab5ffa608c6dce420c | [
"JavaScript",
"Swift",
"Markdown",
"Gradle",
"Java",
"TypeScript",
"Kotlin"
]
| 29 | JavaScript | HSCNI-GITHUB/react-native-exposure-notification-service | aaf4cce7d4eb590c9bc12bd282113f7cf62e699c | 71591ccad120cb03dd5d05ddc4b12bfff2e196dd |
refs/heads/master | <file_sep>package com.datatype;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
@RunWith(JUnitParamsRunner.class)
public class DateFormatTest {
@Parameters
private static final Object[] getCorrectDate() {
return new Object[] {
new Object[]{"2014-12-13 12:12:12"},
new Object[]{"2014-12-13 12:12:1"},
new Object[]{"2014-12-13 12:12:01"},
new Object[]{"2014-12-13 12:1"},
new Object[]{"2014-12-13 12:01"},
new Object[]{"2014-12-13 12"},
new Object[]{"2014-12-13 1"},
new Object[]{"2014-12-31 12:12:01"},
new Object[]{"2014-12-30 23:59:59"},
};
}
@Parameters
private static final Object[] getWrongDate() {
return new Object[] {
new Object[]{"201-12-13 12:12:12"},
new Object[]{"2014-12- 12:12:12"},
new Object[]{"2014- 12:12:12"},
new Object[]{"3014-12-12 12:12:12"},
new Object[]{"2014-22-12 12:12:12"},
new Object[]{"2014-12-42 12:12:12"},
new Object[]{"2014-12-32 12:12:12"},
new Object[]{"2014-13-31 12:12:12"},
new Object[]{"2014-12-31 32:12:12"},
new Object[]{"2014-12-31 24:12:12"},
new Object[]{"2014-12-31 23:60:12"},
new Object[]{"2014-12-31 23:59:60"},
new Object[]{"2014-12-31 23:59:50."},
new Object[]{"2014-12-31 "},
new Object[]{"2014-12 23:59:50"},
new Object[]{"2014 23:59:50"}
};
}
@Test
@Parameters(method="getCorrectDate")
public void testMethodHasReturnTrueForCorrectDate(String dateToValidate) {
assertTrue(DataType.validateDateTimeFormat(dateToValidate));
}
@Test
@Parameters(method="getWrongDate")
public void testMethodHasReturnFalseForWrongDate(String dateToValidate) {
assertFalse(DataType.validateDateTimeFormat(dateToValidate));
}
}
| c4a77f2e117df1c57d8d96d1059a89b78b287653 | [
"Java"
]
| 1 | Java | skp15121980/JavaDataTypeRND | 7cf0f308c3676d55ceba21c1855b87837132df1a | 6732dec5fe36b6ae97c51bebd67faf84dd74490e |
refs/heads/master | <repo_name>WcMestre/Ex5-PositivosENegativos<file_sep>/Ex5-PositivosENegativos/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ex5_PositivosENegativos
{
class Program
{
static void Main(string[] args)
{
int numero1, positivos=0, negativos=0, contador=1;
while (contador <= 10)
{
Console.WriteLine("Digite um número: ");
numero1 = int.Parse(Console.ReadLine());
if (numero1 > 0)
{
positivos++;
}
else if (numero1 < 0)
{
negativos++;
}
contador++;
}
Console.WriteLine(positivos + " Números positivos");
Console.WriteLine(negativos + " Números negativos");
Console.ReadKey();
}
}
}
| cc6ea871a839ef45015e7426543aae7b997cbd81 | [
"C#"
]
| 1 | C# | WcMestre/Ex5-PositivosENegativos | dc1debcce1193ee08776545626d26d900201c50d | 29f156765abc45d86da41c04a572d64568a38fcf |
refs/heads/master | <file_sep># frozen_string_literal: true
require 'oystercard'
describe Oystercard do
let(:entry_station) { double(:entry_station) }
let(:exit_station) { double(:exit_station) }
let(:journey) { double(:Journey) }
let(:zero_card) { Oystercard.new }
let(:new_card) { Oystercard.new(10, journey) }
it 'starts with an empty list of journeys' do
expect(new_card.journeys).to eq []
end
it 'has a balance' do
expect(Oystercard.new.balance).to eq(Oystercard::DEFAULT_BALANCE)
end
it 'tops up balance with' do
expect { new_card.top_up(10) }.to change { new_card.balance }.by 10
end
it 'errors with over limit' do
message = "Error, card has limit of #{Oystercard::TOP_UP_LIMIT}"
expect { new_card.top_up(Oystercard::TOP_UP_LIMIT + 1) } .to raise_error message
end
it "should raise_error 'No money' if balance is below min_fare" do
expect { zero_card.touch_in(entry_station) }.to raise_error('No money')
end
#it 'new test' do
# allow(journey).to receive(:new) { journey }
#allow(journey).to receive(:nil?) { false}
#new_card.touch_in(entry_station)
#expect { new_card.touch_in(entry_station) }.to change { new_card.balance }.by -Oystercard::PENALTY_FARE
#end
before do
allow(journey).to receive(:new) { journey }
allow(journey).to receive(:calculate_fare) { Oystercard::PENALTY_FARE}
end
it 'deducts from balance when you forget to touch out' do
new_card.touch_in(entry_station)
expect { new_card.touch_in(entry_station) }.to change { new_card.balance }.by -Oystercard::PENALTY_FARE
end
it 'deducts from balance when you forget to touch in' do
allow(journey).to receive(:nil?) { true}
new_card.touch_in(entry_station)
new_card.touch_out(exit_station)
expect { new_card.touch_out(exit_station) }.to change { new_card.balance }.by -Oystercard::PENALTY_FARE
end
end
<file_sep># frozen_string_literal: true
require 'journey'
describe Journey do
let(:entry_station) { double(:entry_station) }
let(:exit_station) { double(:exit_station) }
let(:journey) { Journey.new(entry_station) }
it 'sets entry station' do
expect(journey.entry_station).to eq(entry_station)
end
it 'sets exit station' do
journey.finish_journey(exit_station)
expect(journey.exit_station).to eq(exit_station)
end
it 'knows its in journey' do
expect(journey).to_not be_complete
end
it 'returns itself when exiting a journey' do
expect(journey.finish_journey(exit_station)).to eq(journey)
end
it 'returns penalty fare if journey not complete' do
expect(journey.calculate_fare).to eq(Journey::PENALTY_FARE)
end
it 'returns minimum fare if journey complete' do
journey.finish_journey(exit_station)
expect(journey.calculate_fare).to eq(Journey::MINIMUM_FARE)
end
end
<file_sep># frozen_string_literal: true
class Journey
attr_reader :exit_station, :entry_station
PENALTY_FARE = 5
MINIMUM_FARE = 1
def initialize(entry_station)
@entry_station = entry_station
end
def finish_journey(exit_station)
@exit_station = exit_station
self # this returns the object and its attributes (@entry_station & @exit_station) to oystercard class.
end
def complete?
!!exit_station # journey complete if there is an exit station.
end
def calculate_fare
unless complete?
return PENALTY_FARE
end # gives penalty fare if journey isnt complete.
MINIMUM_FARE
end
end
<file_sep># frozen_string_literal: true
require_relative '../lib/station'
describe Station do
let(:station) { Station.new('Waterloo', 1) }
it 'should have a name' do
expect(station.station_info[:name]).to eq('Waterloo')
end
it 'should have a zone' do
expect(station.station_info[:zone]).to eq(1)
end
end
<file_sep># frozen_string_literal: true
require_relative 'journey.rb'
class Oystercard
TOP_UP_LIMIT = 100
MINIMUM_BALANCE = 1
DEFAULT_BALANCE = 0
PENALTY_FARE = Journey::PENALTY_FARE
attr_reader :balance, :journeys, :journey, :journey_instance
def initialize(balance = DEFAULT_BALANCE, journey_instance = Journey)
@balance = balance
@journeys = [] # list of journeys
@journey_instance = journey_instance
end
def top_up(value)
raise "Error, card has limit of #{TOP_UP_LIMIT}" if over_limit?(value)
@balance += value
end
def touch_in(entry_station)
raise 'No money' if insufficient_funds?
unless journey.nil?
deduct(journey.calculate_fare)
end # deducts penalty fare if person touches in twice without out without touching out
@journey = journey_instance.new(entry_station) # create a new journey instance when touched in.
end
def touch_out(exit_station)
journey.nil? ? deduct(PENALTY_FARE) : finish_journey_process(exit_station) # deducts penalty fare if didnt touch in and @journey object not formed. Otherwise finishes journey correctly.
end
private
def finish_journey_process(exit_station)
@journeys << journey.finish_journey(exit_station) # journey object and its attributes is returned and placed in journeys array.
deduct(journey.calculate_fare) # calculates and deducts fare.
# @journey = nil
end
def deduct(fare)
@balance -= fare
end
def insufficient_funds?
balance < MINIMUM_BALANCE
end
def over_limit?(value)
value + balance > TOP_UP_LIMIT
end
end
<file_sep># frozen_string_literal: true
class Station
attr_reader :station_info
def initialize(name, zone)
@station_info = { name: name, zone: zone }
# @name =name
# @zone = zone
end
end
| 958112ffc572af5fb64b5683346a7c2ac5ebb4b2 | [
"Ruby"
]
| 6 | Ruby | perrinjack/oystercard_challenge | 917cc101c7edfaa164e62a5c6747ad2ed384fb2f | 4d47ca5bee572ca8800573ade081d21b62bc2d61 |
refs/heads/master | <file_sep>package edu.iedu.tictactoe;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TicTacToe_ui {
public TicTacToe tictactoe;
public TicTacToe_ui(int row, int column) {
tictactoe = new TicTacToe(row, column);
}
public void newBoard() {
// This method is for making a new tic tac toe board.
// When you call this method, your board will be refreshed.
tictactoe.board = new ArrayList<>();
for(int row = 0; row < tictactoe.rowSize; row++) {
List<String> subBoard = new ArrayList<>();
// []
for(int column = 0; column < tictactoe.columnSize; column++) {
subBoard.add(".");
}
tictactoe.board.add(subBoard);
}
}
public void drawBoard() {
// This method is for drawing current board
for(int row = 0; row < tictactoe.rowSize; row++) {
List<String> subBoard = tictactoe.board.get(row);
String rowString = "";
String space = " ";
for(int column = 0; column < tictactoe.columnSize; column++) {
String value = subBoard.get(column);
rowString = rowString + value + space;
}
System.out.println(rowString);
}
}
public void play() {
}
public void init() {
tictactoe.player = "X";
newBoard();
drawBoard();
play();
}
}
| bd0dbf6ef5c35b99b72d425505ffb2cb3d78f791 | [
"Java"
]
| 1 | Java | hyungiko/tictactoe_sat | 5dcf510f869fc0f548b8c92b24a1e2b7b286d4b2 | 34084b13ea7c8620d765accaa37825747d12b646 |
refs/heads/master | <repo_name>sharkman/NotificationLogSSE<file_sep>/src/NotificationLogger.cpp
#include "NotificationLogger.h"
#include "REL/Relocation.h"
#include "SKSE/API.h"
void NotificationLogger::Init()
{
InstallHooks();
auto papyrus = SKSE::GetPapyrusInterface();
papyrus->Register(RegisterPapyrusFunctions);
_MESSAGE("NotificationLogger Initialized");
}
bool NotificationLogger::RegisterPapyrusFunctions(RE::BSScript::Internal::VirtualMachine* a_vm)
{
a_vm->RegisterFunction("GetCachedMessages", "NotificationLog", GetCachedMessages);
return true;
}
void NotificationLogger::CreateHUDDataMessage(RE::HUDData::Type a_type, const char* a_message)
{
AddMessage(a_message);
_createHUDDataMessage(a_type, a_message);
}
auto NotificationLogger::GetCachedMessages(RE::StaticFunctionTag*)
-> Array_t
{
Array_t arr;
while (_notificationBuffer.size() >= arr.max_size()) {
_notificationBuffer.pop_back();
}
arr.resize(_notificationBuffer.size());
std::size_t i = 0;
for (auto& notif : _notificationBuffer) {
arr[i++] = notif;
}
return arr;
}
void NotificationLogger::InstallHooks()
{
REL::Offset<std::uintptr_t> hookPoint(REL::ID(52050), 0x19B);
auto trampoline = SKSE::GetTrampoline();
_createHUDDataMessage = trampoline->Write5CallEx(hookPoint.GetAddress(), unrestricted_cast<std::uintptr_t>(&CreateHUDDataMessage));
}
void NotificationLogger::AddMessage(const char* a_message)
{
while (_notificationBuffer.size() >= MAX_BUFFER_SIZE) {
_notificationBuffer.pop_back();
}
_notificationBuffer.push_front(a_message);
}
decltype(NotificationLogger::_notificationBuffer) NotificationLogger::_notificationBuffer;
<file_sep>/include/NotificationLogger.h
#pragma once
#include <list>
#include <string>
#include "RE/Skyrim.h"
#include "REL/Relocation.h"
class NotificationLogger
{
public:
using Array_t = RE::BSScript::VMArray<RE::BSFixedString>;
static void Init();
static bool RegisterPapyrusFunctions(RE::BSScript::Internal::VirtualMachine* a_vm);
static void CreateHUDDataMessage(RE::HUDData::Type a_type, const char* a_message);
static Array_t GetCachedMessages(RE::StaticFunctionTag*);
private:
using CreateHUDDataMessage_t = decltype(&NotificationLogger::CreateHUDDataMessage);
static void InstallHooks();
static void AddMessage(const char* a_message);
static constexpr std::size_t MAX_BUFFER_SIZE = 128;
static std::list<std::string> _notificationBuffer;
static inline REL::Function<CreateHUDDataMessage_t> _createHUDDataMessage;
};
<file_sep>/include/version.h
#ifndef NOTL_VERSION_INCLUDED
#define NOTL_VERSION_INCLUDED
#define MAKE_STR_HELPER(a_str) #a_str
#define MAKE_STR(a_str) MAKE_STR_HELPER(a_str)
#define NOTL_VERSION_MAJOR 1
#define NOTL_VERSION_MINOR 2
#define NOTL_VERSION_PATCH 0
#define NOTL_VERSION_BETA 0
#define NOTL_VERSION_VERSTRING MAKE_STR(NOTL_VERSION_MAJOR) "." MAKE_STR(NOTL_VERSION_MINOR) "." MAKE_STR(NOTL_VERSION_PATCH) "." MAKE_STR(NOTL_VERSION_BETA)
#endif
| ac665c1a54c646aa4c238fa1eec83514fcf09647 | [
"C",
"C++"
]
| 3 | C++ | sharkman/NotificationLogSSE | c74d894933b66ef7e1adbba3e8e420395f2b73ba | 782f8d027f344f23dd7f37f136697c3b41f8c5cd |
refs/heads/main | <repo_name>xabcodex/dotfiles<file_sep>/README.md
# dotfiles
I'm learning about dotfiles.
## Part 1
[Great course!](https://www.udemy.com/course/dotfiles-from-start-to-finish-ish/)
## TODO
- Terminal Preferences
- Changed Shell to ZSH
- Dock Preferences
- Mission control preference (don't rearrange spaces)
- Finder Show path bar
- Trackpad (Three finger drag and tap to click)
- Git (config and SSH)
- Alfred (turn off Spotlight shortcut and use for Alfred)
- Snappy (turn off cmd+shift+4) for screenshots and use for Snappy.
<file_sep>/config/Wondershare/dr.fone/DrFoneSocialApp.ini
[Drivers]
HistoryTableAltered=1
<file_sep>/Brewfile
tap "eth-p/software"
tap "homebrew/bundle"
tap "homebrew/cask"
tap "homebrew/core"
# Search tool like grep, but optimized for programmers
brew "ack"
# Shell extension to jump to frequently used directories
brew "autojump"
# Clone of cat(1) with syntax highlighting and Git integration
brew "bat"
# New way to see and navigate directory trees
brew "broot"
# Modern replacement for 'ls'
brew "exa"
# CLI tool for quick access to files and directories
brew "fasd"
# Simple, fast and user-friendly alternative to find
brew "fd"
# Command-line fuzzy finder written in Go
brew "fzf"
# GNU compiler collection
brew "gcc"
# Distributed revision control system
brew "git", link: false
# GitHub Markdown previewer
brew "grip"
# User-friendly cURL replacement (command-line HTTP client)
brew "httpie"
# Pager program similar to more
brew "less"
# Mac App Store command-line interface
brew "mas"
# Modern programming language in the Lisp/Scheme family
brew "minimal-racket"
# Node version management
brew "n"
# Free (GNU) replacement for the Pico text editor
brew "nano"
# Ambitious Vim-fork focused on extensibility and agility
brew "neovim"
# Tiny, lightning fast, feature-packed file manager
brew "nnn"
# File browser
brew "ranger"
# RC file (dotfile) management
brew "rcm"
# Search tool like grep and The Silver Searcher
brew "ripgrep"
# Lisp installer and launcher for major environments
brew "roswell"
# Rust toolchain installer
brew "rustup-init"
# Static analysis and lint tool, for (ba)sh scripts
brew "shellcheck"
# Code-search similar to ack
brew "the_silver_searcher"
# Simplified and community-driven man pages
brew "tldr"
# Terminal multiplexer
brew "tmux"
# Display directories as trees (with optional color/HTML output)
brew "tree"
# Access X11 clipboards from the command-line
brew "xclip"
# JavaScript package manager
brew "yarn"
# UNIX shell (command interpreter)
brew "zsh"
# Bash scripts that integrate bat with various command-line tools
brew "eth-p/software/bat-extras"
# Application launcher and productivity software
cask "alfred"
# Browser for SQLite databases
cask "db-browser-for-sqlite"
# Git client focusing on productivity
cask "gitkraken"
# Web browser
cask "google-chrome"
# Client for the Google Drive storage service
cask "google-drive"
# PDF reader and note-taking application
cask "skim"
# Open-source code editor
cask "visual-studio-code"
mas "Amphetamine", id: 937984704
mas "Battery Health 2", id: 1120214373
mas "Be Focused", id: 973134470
mas "Endel", id: 1484348796
mas "Evernote", id: 406056744
mas "Fantastical", id: 975937182
mas "Flycut", id: 442160987
mas "GarageBand", id: 682658836
mas "GeoGebra Classic 6", id: 1182481622
mas "GoodNotes", id: 1444383602
mas "Grammarly for Safari", id: 1462114288
mas "HandShaker", id: 1012930195
mas "iMovie", id: 408981434
mas "Jira", id: 1475897096
mas "Keynote", id: 409183694
mas "LispPad", id: 1258939760
mas "Microsoft Excel", id: 462058435
mas "Microsoft OneNote", id: 784801555
mas "Microsoft Outlook", id: 985367838
mas "Microsoft PowerPoint", id: 462062816
mas "Microsoft To Do", id: 1274495053
mas "Microsoft Word", id: 462054704
mas "Notability", id: 360593530
mas "Numbers", id: 409203825
mas "OneDrive", id: 823766827
mas "Pages", id: 409201541
mas "Save to Medium", id: 1485294824
mas "Slack", id: 803453959
mas "Spark", id: 1176895641
mas "Swiftify for Xcode", id: 1183412116
mas "Telegram", id: 747648890
mas "The Unarchiver", id: 425424353
mas "Todoist", id: 585829637
mas "Trello", id: 1278508951
mas "Vectornator Pro", id: 1470168007
mas "WhatsApp", id: 1147396723
mas "Xcode", id: 497799835
<file_sep>/config/Wondershare_DrFone_WhatsApp_Backup/20201227170750/Deivce.ini
[ToolBackInfo]
DeviceName=iPhone
IOSVersion=14.3
DislpayName=iPhone SE (2nd generation)
ProductType=iPhone SE (2nd generation)
CurrenSelectType=WhatsApp_Attachments
FileSizeTotle=19031824
FileSize=18.15 MB
SerialNumber=FFMDN1W2PLK3
BackupDate=2020-12-27 17:08
BackupDateYear=2020
BackupDateMonth=12
BackupDateDay=27
BackupDateHour=17
BackupDateMinute=8
BackupDateSecond=29
UDID=00008030-000154E11132402E
AppVersion=192.168.127.12
IsAndroidPackage=False
<file_sep>/zshrc
echo 'Hello from .zshrc'
# Set Variables
export HOMEBREW_CASK_OPTS="--no-quarantine"
export NULLCMD=bat
export N_PREFIX="$HOME/.n"
export PREFIX="$N_PREFIX"
# Change ZSH Options
# Create Aliases
alias ls='exa -laFh --git'
alias exa='exa -laFh --git'
alias man=batman
alias bbd='brew bundle dump --force --describe'
alias trail='<<<${(F)path}'
alias rm=trash
# Cusotmize Prompt(s)
PROMPT='
%1~ %L %# '
RPROMPT='%*'
# Add Localizations to $path Array
typeset -U path
path=(
"$N_PREFIX/bin"
$path
"/Applications/Visual Studio Code.app/Contents/Resources/app/bin"
)
# Write Handy Functions
function mkcd(){
mkdir -p "$@" && cd "$_";
}
# Use ZSH Plugins
# ...and Other Surprises
<file_sep>/shebang.zsh
#!/usr/bin/env zsh
echo "\n<<< Running $0 >>>\n"
echo "ZSH_VERSION = $ZSH_VERSION"
echo "The current shell is: $(ps $$ -0comm=)"
exists brew && echo "excellent" || echo "bogus"
exists nonexistent && echo "excellent" || echo "bogus!!!"
which exists<file_sep>/test_exists.zsh
#!/usr/bin/env zsh
echo "\n<<< Running $0 >>>\n"
exists brew && echo "excellent" || echo "bogus"
exists nonexistent && echo "excellent" || echo "bogus!!!"
which exists<file_sep>/setup_node.zsh
#!/usr/bin/env zsh
echo "\n<<< Starting Homebrew Setup >>>\n"
# Node versions are managed with `n, which is in the Brewfile.
# See zshrc for N_PREFIX variable and addition to $path Array.
if exists node; then
echo "Node $(node --version)& NPM already installed"
else
echo "Installing Node & NPM with n..."
n latest
fi
# Install Global NPM Packages
npm install --global yarn
npm install --global firebase-tools
npm install --global @angular/cli
npm install --global @ionic/cli
npm install --global typescript
npm install --global json-server
npm install --global http-server
npm install --global trash-cli
echo "Global NPM Packages Installed:"
npm list --global --depth=0
<file_sep>/setup_homebrew.zsh
#!/usr/bin/env zsh
echo "\n<<< Starting Homebrew Setup >>>\n"
if exists brew; then
echo "brew exists, skipping install"
else
echo "brew doesn't exist, continuing with the install"
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
fi
# TODO: Keep an eye out for a different `--no-quarantine`solution.
# Currently, you can't do `brew bundle --no-quarantine`as an option.
# It's currently exported in zshrc:
# export HOMEBREW_CASK_OPTS="--no-quarantine"
# https://github.com/Homebrew/homebrew-bundle/issues/474
brew bundle --verbose<file_sep>/zshenv
echo 'Hello from .zshenv'
function exists(){
# `command -v` is similar to `which`
# https://stackoverflow.com/a/677212/1341838
# $1 is the first argument
command -v $1 >/dev/null 2>&1
# More explicitly written
# & is the output
# command -v $1 1>/dev/null 2>/dev/null
} | 002e12e08d6afacf89c529bb8ba4aec1851f5741 | [
"Markdown",
"Shell",
"Ruby",
"INI"
]
| 10 | Markdown | xabcodex/dotfiles | 9425a8b700dea37534bca62d5cebfc3f33907afb | 16772529cefe117a9756222521d6db2adb95a9c2 |
refs/heads/master | <file_sep>in_file_path = raw_input("Which LTSV file use as input?: ")
out_file_path = raw_input("Enter output file name: ")
in_file = open(in_file_path, 'r')
out_file = open(out_file_path, 'w')
for line in in_file:
stack = []
for elm in line.split('\t'):
stack.append(''.join(elm.split(':')[1:]))
out_file.write(', '.join(stack))
in_file.close()
out_file.close()
<file_sep># LTSV-parser-python | d38721cfe0b69f9ea287de948db4306c83d9ec4c | [
"Markdown",
"Python"
]
| 2 | Python | haginot/LTSV-parser-python | acd2c854a800b0c8a2b547aa117625eb0a05a968 | b8f06d0a12ab3782c1a4ca8c53ca3ff9cc7275e6 |
refs/heads/master | <file_sep>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var mysql = require('mysql');
var conn = mysql.createConnection({
host: 'localhost',
user: 'world',
password: '<PASSWORD>',
database: 'world',
port : 3306
});
var POLLING_INTERVAL = 3000,
polingTimer,
connArray = [];
//app.get('/', function(req,res) {
// res.sendFile(__dirname + '/checker.html');
//});
app.use(express.static('.'));
conn.connect( function(err) {
if (err) {
console.log(err);
}
});
var pollingselect = function() {
var data = [];
var query = conn.query('SELECT * FROM Country');
console.log('pollingselect start..');
query
.on('error', function(err) {
console.log(err);
udpateSockets(err);
})
.on('result', function(row) {
data.push(row);
})
.on('end', function(){
if (connArray.length) {
pollingTimer = setTimeout(pollingselect, POLLING_INTERVAL);
updateSockets({data:data});
}
});
};
io.on('connection', function( socket ) {
console.log('Number of conn: '+ connArray.length );
if (!connArray.length) {
pollingselect();
}
socket.on('disconnect', function() {
var socketIndex = connArray.indexOf(socket);
console.log('socket = ' + socketIndex + ' disconnected');
if (socketIndex >= 0) {
connArray.splice( socketIndex, 1);
}
});
console.log('A new socket is connected!');
connArray.push(socket);
});
var updateSockets = function( data ) {
data.time = new Date();
connArray.forEach( function( socket ) {
socket.emit('data', data);
});
};
http.listen(3000, function() {
console.log('listening on *:3000');
});
<file_sep>var X = require('xlsx');
var wb = X.readFile('TestExcel.xlsx');
var sheetNameList = wb.SheetNames;
sheetNameList.forEach(function(y) {
var ws = wb.Sheets[y];
for (z in ws) {
/* all keys that do not begin with "!" correspond to cell address */
if (z[0] === '!') continue;
console.log(y + "!" + z + "=" + JSON.stringify(ws[z].v));
}
});
<file_sep># react-test-excel
A small program for parsing Excel file and display it on browser using Reactjs.
I created since I need to compare two Excel files if they have same field of data.
<file_sep>/*
* @jsx React.DOM
*/
var React = require('react');
var jszip = require('jszip');
var TicketTable = require('./components/TicketTable.react');
var Dropzone = require('react-dropzone');
var X = XLSX;
var XW = {
/* worker message */
msg: 'js/xlsx',
/* worker scripts */
rABS: 'js/xlsxworker2.js',
norABS: 'js/xlsxworker1.js',
noxfer: 'js/xlsxworker.js'
};
var rABS = typeof FileReader !== "undefined" && typeof FileReader.prototype !== "undefined" && typeof FileReader.prototype.readAsBinaryString !== "undefined";
var use_worker = typeof Worker !== 'undefined';
var transferable = use_worker;
var wtf_mode = false;
function fixdata(data) {
var o = "", l = 0, w = 10240;
for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint8Array(data.slice(l*w,l*w+w)));
o+=String.fromCharCode.apply(null, new Uint8Array(data.slice(l*w)));
return o;
};
function ab2str(data) {
var o = "", l = 0, w = 10240;
for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint16Array(data.slice(l*w,l*w+w)));
o+=String.fromCharCode.apply(null, new Uint16Array(data.slice(l*w)));
return o;
};
function s2ab(s) {
var b = new ArrayBuffer(s.length*2), v = new Uint16Array(b);
for (var i=0; i != s.length; ++i) v[i] = s.charCodeAt(i);
return [v, b];
};
function xw_xfer(data, cb) {
var worker = new Worker(rABS ? XW.rABS : XW.norABS);
worker.onmessage = function(e) {
switch(e.data.t) {
case 'ready': break;
case 'e': console.error(e.data.d); break;
default: xx=ab2str(e.data).replace(/\n/g,"\\n").replace(/\r/g,"\\r"); console.log("done"); cb(JSON.parse(xx)); break;
}
};
if(rABS) {
var val = s2ab(data);
worker.postMessage(val[1], [val[1]]);
} else {
worker.postMessage(data, [data]);
}
};
function xw(data, cb) {
if(transferable) xw_xfer(data, cb);
else xw_noxfer(data, cb);
};
function ticketOrder(tradeRow, colStr, value, fund) {
switch (colStr) {
case 'A':
tradeRow['orderNumber'] = value;
break;
case 'B':
tradeRow['date'] = value;
break;
case 'C':
tradeRow['fund'] = value;
break;
case 'D':
tradeRow['code'] = value;
break;
case 'E':
tradeRow['name'] = value;
break;
case 'F':
tradeRow['orderType'] = value;
break;
case 'G':
tradeRow['orderSize'] = value;
break;
case 'H':
tradeRow['limitPrice'] = value;
break;
case 'I':
tradeRow['tradeType'] = value;
break;
case 'J':
tradeRow['brokerCode'] = value;
break;
} //end switch
}
function execTrade(tradeRow, colStr, value, fund) {
switch (colStr) {
case 'A':
tradeRow['orderNumber'] = value;
break;
case 'B':
tradeRow['code'] = value;
break;
case 'C':
tradeRow['name'] = value;
break;
case 'D':
tradeRow['orderType'] = (value === 'Buy Cover' ? 'COVER' :
(value === 'Sell Short' ? 'SHORT': ( value === 'Sell' ? 'SELL': 'BUY'))) ;
break;
case 'E':
if (fund === 'R') tradeRow['RH'] = value;
else if (fund === 'Y') tradeRow['YA'] = value;
else tradeRow['LR'] = value;
break;
case 'F':
tradeRow['executed'] = value;
break;
case 'G':
tradeRow['avgprice'] = value;
break;
case 'H':
tradeRow['brokerCode'] = value;
break;
case 'I':
tradeRow['rate'] = value;
break;
case 'J':
tradeRow['PB'] = value;
break;
} //end switch
}
function process_wb(wb, selectFunc, startRow, fund) {
var sheetNameList = wb.SheetNames;
var tickets = [];
sheetNameList.forEach(function(y) {
var ws = wb.Sheets[y];
var pattern = /([A-Z]+)([0-9]+)/;
var lastRow = -1;
var tradeRow = {};
for (z in ws) {
// all keys that do not begin with "!" correspond to cell address
if (z[0] === '!') continue;
//console.log(y + "!" + z + "=" + JSON.stringify(ws[z].v) + " type:" + ( typeof z)+ " " + (typeof ws[z].v));
var matches = pattern.exec(z); // extract column string and row number
var colStr, row;
if (matches) {
colStr = matches[1];
row = matches[2];
if (row >= startRow) { // data start from row startRow
//console.log("col="+ colStr + " row="+ row+ " value=" +JSON.stringify(ws[z].v));
if (lastRow !== -1 && lastRow !== row) {
tickets.push(tradeRow);
tradeRow = {};
lastRow = row;
}
if (lastRow === -1) {
lastRow = row;
}
// put right value to tradeRow depends on column char
selectFunc(tradeRow, colStr, ws[z].v, fund);
} //end if
}
}
// add last row
tickets.push(tradeRow);
});
return tickets;
};
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function compareF(a,b) {
if (isNumeric(a.code) && isNumeric(b.code)) {
if (a.code !== b.code) {
return a.code - b.code;
} else {
return a.orderType.localeCompare(b.orderType);
}
} else if (! isNumeric(a.code)) {
return 1;
} else {
return -1;
}
}
function merge( ticket, exec) {
if (! ticket) return exec;
if (! exec) return ticket;
console.log("merge start");
ticket.sort(compareF);
exec.sort(compareF);
var i = 0, j = 0, k = 0;
var data = [];
while (i < ticket.length && j < exec.length) {
//console.log("ticket length ="+ ticket.length +" exelen="+ exec.length+",i ="+i+", j="+j+", k="+k +", comp1=" + (i < ticket.length)+", comp2="+(j<exec.length)+", code1=" + ticket[i].code +", code2="+ exec[j].code);
if (ticket[i].code < exec[j].code) {
data[k] = ticket[i];
i++;
k++;
} else if (ticket[i].code > exec[j].code) {
data[k] = exec[j];
console.log(exec.fund);
if (exec.fund === 'R') {
data[k]['RH'] = exec[j].RH;
} else if (exec.fund === 'Y') {
data[k]['YA'] = exec[j].YA;
} else if (exec.fund === 'Long') {
data[k]['LR'] = exec[j].LR;
} else {
console.log("something wrong");
}
j++;
k++;
} else if (ticket[i].orderType === exec[j].orderType ) {
data[k] = ticket[i];
console.log(exec.fund);
if (exec.fund === 'R') {
data[k]['RH'] = exec[j].RH;
} else if (exec.fund === 'Y') {
data[k]['YA'] = exec[j].YA;
} else if (exec.fund === 'Long') {
data[k]['LR'] = exec[j].LR;
} else {
console.log("something wrong");
}
k++;
i++;
j++;
} else {
console.log(ticket[i].orderType, exec[j].orderType);
break;
}
//if (i === 40) break;
}
console.log("basic comparison end");
while (i < ticket.length) {
console.log("ticket remained");
data[k] = ticket[i];
i++;
k++;
}
while (j < exec.length) {
console.log("exec remaind");
data[k] = exec[j];
j++;
k++;
}
return data;
}
var DropzoneDemo = React.createClass({
getInitialState: function() {
return {data: [], ticketOrder: false, rhexec: false, yaexec: false, lrexec: false};
},
onDrop: function( files ) {
console.log('Received files: ', files[0].name);
var reader = new FileReader();
var f = files[0];
var name = f.name;
var setState = this.setState;
reader.onload = function(e) {
if(typeof console !== 'undefined') console.log("onload", new Date(), rABS, use_worker);
var data = e.target.result;
var wb;
var orderPattern = /Order_[A-Z][a-z]{2}_[0-9]{2}[A-Z]{2}.xlsx/;
var execPattern = /([0-9]{2})([A-Z][a-z]{2})Exe\((R|Y|Long)\).xlsx/;
var matches;
if (matches = orderPattern.exec(name)) {
//xw(data, process_ticket_order_wb,setState);
var arr = fixdata(data);
wb = X.read(btoa(arr), {type: 'base64'});
var tickets = process_wb(wb, ticketOrder, 3, ''); // data start from row 3
if (! this.state.ticketOrder) {
this.setState({data: tickets, ticketOrder: true});
}
} else if (matches = execPattern.exec(name)) {
console.log(matches[1],matches[2],matches[3]);
var arr = fixdata(data);
wb = X.read(btoa(arr), {type: 'base64'});
var exec = process_wb(wb, execTrade, 7, matches[3]); // data start from row 7
exec['fund'] = matches[3];
var newData = [];
if (this.state.ticketOrder) {
newData = merge(this.state.data, exec);
console.log(newData);
} else {
newData = exec;
}
this.setState({ data: newData});
}
}.bind(this);
reader.readAsArrayBuffer(f);
//reader.readAsBinaryString(f);
},
render: function() {
return(
<div>
<Dropzone onDrop={this.onDrop} width={800} height={100}>
<div> Drop Excel files here</div>
</Dropzone>
<TicketTable data={this.state.data} />
</div>
);
}
});
React.render(<DropzoneDemo />, document.body);
| 6dc97a663e11e42c6c06d2f2c74a1ed4f13867c7 | [
"JavaScript",
"Markdown"
]
| 4 | JavaScript | vico/react-test-excel | c2449898f7807a2d3d6d0087dc0a21e37b69469e | e6f355201d39c7308c6234e76b44e7e18ac85cea |
refs/heads/master | <repo_name>Fruscoqq/WeatherAPI<file_sep>/app.js
// Variables
const button = document.querySelector('.btn'),
input = document.querySelector('.search');
// Init objects
const weatherInfo = new WeatherInfo();
const ui = new UI();
// Fetching data button
button.addEventListener('click', function (e) {
ui.buttonAnimation();
if (input.value != '') {
console.log(1)
ui.weatherLoader();
weatherInfo.getWeather(input.value).then(data => {
console.log(data)
let output = `
<ul class="list">
<li>Location: ${data.location.name} <img src="${data.current.weather_icons[0]}"/></li>
<li>Temperature: ${data.current.temperature}°C</li>
<li>Humidity: ${data.current.humidity}%</li>
<li>Condition: ${data.current.weather_descriptions}</li>
</ul>
`;
document.querySelector('#output').innerHTML = output;
});
input.value = '';
} else {
console.log(2)
}
})<file_sep>/weatherinfo.js
class WeatherInfo {
constructor() { }
async getWeather(location) {
const weatherResponse = await fetch(`http://api.weatherstack.com/current?access_key=4632e4e7c0e04285f0e0f32dc223f90e&query=${location}
`);
const weatherData = await weatherResponse.json();
return weatherData;
}
}
// https://api.apixu.com/v1/forecast.json?key=4632e4e7c0e04285f0e0f32dc223f90e&q=${location}&days=4<file_sep>/ui.js
class UI {
constructor() {}
weatherLoader() {
const divLoader = document.querySelector('.loader-wrapper'),
divOutput = document.querySelector('#output');
divLoader.style.display = "block";
divOutput.style.display = "none";
setTimeout(function () {
divLoader.style.display = "none";
divOutput.style.display = "block";
}, 3000)
}
buttonAnimation() {
const output = document.querySelector('#output');
output.classList.remove('btn-anim');
void output.offsetWidth;
output.classList.add('btn-anim')
console.log(123);
}
} | 845c1c70b5d23b9426d4c12b36db97360cfd4131 | [
"JavaScript"
]
| 3 | JavaScript | Fruscoqq/WeatherAPI | 7256dcbd7a6e0a0aaff080c8a060df3c6bdd1930 | b19c17314f190f252f49c1acd75bdee3c9168da4 |
refs/heads/master | <file_sep>class MemoryGame {
constructor(cards) {
this.cards = cards;
this.pickedCards = [];
this.pairsClicked = 0;
this.pairsGuessed = 0;
}
shuffleCards() {
let finalArrayShuffled = [];
let buffer = this.cards;
if(this.cards.length === 0) return undefined;
console.log(">>>>>>>>>>before boucle="+ buffer.length);
for (let index = 0; index <= buffer.length; index++) { // <=buffer.length
let newMixedPosition = Math.floor(Math.random() * buffer.length);
finalArrayShuffled[newMixedPosition] = buffer[newMixedPosition];
buffer.splice(newMixedPosition,1);
console.log(">>>>>>>>>>after boucle="+ buffer.length);
}
console.log("fin boucle>>>>>>>>>>"+ buffer.length);
console.log(">>>>>>>>>>TailleFinale"+finalArrayShuffled.length);
return finalArrayShuffled;
}
checkIfPair(card1, card2) {
this.pairsClicked ++;
if(card1.getAttribute('data-card-name') === card2.getAttribute('data-card-name')){
this.pairsGuessed++;
return true;
} else {
return false;
}
}
checkIfFinished() {
//return (this.pairsGuessed === this.cards.length/2); //return soit true soit false
//Autre methode
if(this.pairsGuessed === this.cards.length/2){
return true;
} else {
return false;
}
}
}
// The following is required for automated testing. Please, ignore it.
if (typeof module !== 'undefined') module.exports = MemoryGame;
<file_sep>//import { MemoryGame } from './memory.js';
const cards = [
{ name: 'aquaman', img: 'aquaman.jpg' },
{ name: 'batman', img: 'batman.jpg' },
{ name: 'captain america', img: 'captain-america.jpg' },
{ name: 'fantastic four', img: 'fantastic-four.jpg' },
{ name: 'flash', img: 'flash.jpg' },
{ name: 'green arrow', img: 'green-arrow.jpg' },
{ name: 'green lantern', img: 'green-lantern.jpg' },
{ name: 'ironman', img: 'ironman.jpg' },
{ name: 'spiderman', img: 'spiderman.jpg' },
{ name: 'superman', img: 'superman.jpg' },
{ name: 'the avengers', img: 'the-avengers.jpg' },
{ name: 'thor', img: 'thor.jpg' },
{ name: 'aquaman', img: 'aquaman.jpg' },
{ name: 'batman', img: 'batman.jpg' },
{ name: 'captain america', img: 'captain-america.jpg' },
{ name: 'fantastic four', img: 'fantastic-four.jpg' },
{ name: 'flash', img: 'flash.jpg' },
{ name: 'green arrow', img: 'green-arrow.jpg' },
{ name: 'green lantern', img: 'green-lantern.jpg' },
{ name: 'ironman', img: 'ironman.jpg' },
{ name: 'spiderman', img: 'spiderman.jpg' },
{ name: 'superman', img: 'superman.jpg' },
{ name: 'the avengers', img: 'the-avengers.jpg' },
{ name: 'thor', img: 'thor.jpg' }
];
const pairsClicked = document.getElementById('pairs-clicked');
const pairsGuessed = document.getElementById('pairs-guessed');
const memoryGame = new MemoryGame(cards);
window.addEventListener('load', (event) => {
let html = '';
memoryGame.cards.forEach((pic) => {
html += `
<div class="card" data-card-name="${pic.name}">
<div class="back" name="${pic.img}"></div>
<div class="front" style="background: url(img/${pic.img}) no-repeat"></div>
</div>
`;
});
// Add all the divs to the HTML
document.querySelector('#memory-board').innerHTML = html;
function cardCliked(card){
card.classList.add("turned");
}
function cardReset(card){
card.classList.remove("turned");
}
// Bind the click event of each element to a function
document.querySelectorAll('.card').forEach((card) => {
card.addEventListener('click', () => {
memoryGame.pickedCards.push(card); // on ajoute la carte à notre arret
console.log("nbout= "+memoryGame.pairsClicked);
//if(memoryGame.pickedCards.length === 3) clearTimeout(intervalId);
if(memoryGame.pickedCards.length < 2){ //si on a que une carte
cardCliked(card); // on la montre
//console.log("nbin1= "+memoryGame.pairsClicked);
//console.log("***dans le if")
} else if (memoryGame.pickedCards.length === 2){ //on a retourné deux cartes on empeche le mec de cliquer 3fois ou plus
cardCliked(card);
//verification de si les cartes sont similaires
if(memoryGame.checkIfPair(memoryGame.pickedCards[0],memoryGame.pickedCards[1])){
memoryGame.pairsGuessed ++;
pairsGuessed.textContent = `${memoryGame.pairsGuessed/2}`;
memoryGame.pickedCards = []; //On réinitialise le tab
//console.log("nbin2.1= "+memoryGame.pairsClicked);
//on ecrit dans le html le nombre de pair guessed
} else {// les cartes ne sont pas les m^mes on les retournes apres un délai
//console.log("***dans le else2")
//console.log("nbin2.2= "+ memoryGame.pairsClicked);
let intervalId = setTimeout(() => {
cardReset(memoryGame.pickedCards[0]); // on enleve la propriété turned
cardReset(memoryGame.pickedCards[1]); // on enleve la propriété turned
memoryGame.pickedCards = []; //vide le tableau
//on retourne les cartes
},3000);
}
pairsClicked.textContent = `${memoryGame.pairsClicked}`;
}
console.log("dans la fonction")
// TODO: write some code here
console.log(`Card clicked: ${card}`);
});
});
console.log("hors la fonction")
});
| 1eca38ec9ddf59d7522d4241473c9e3748a57ea7 | [
"JavaScript"
]
| 2 | JavaScript | HugoLansade/lab-javascript-memory-game | c718645362369e3bbf28680ad6b640d02eb6feec | 8c499744ec8e5273d34747bec6110f42eeacc88e |
refs/heads/master | <file_sep># room.me-android
Roommate management app!
<file_sep>package me.akshaypall.roomme.classes;
import android.content.Context;
import android.support.v7.widget.CardView;
/**
* Created by Akshay on 2016-10-26.
*/
public class NoticeCardView extends CardView {
public NoticeCardView(Context context) {
super(context);
}
@Override
protected void onAnimationEnd() {
//caution, only animation on notice should be
super.onAnimationEnd();
}
}
<file_sep>package me.akshaypall.roomme.classes;
import android.view.View;
/**
* Created by Akshay on 2016-10-21.
*/
public interface NoticeCardListener {
void clickedCard(View card);
void swipedCard(View v, int position);
}
<file_sep>package me.akshaypall.roomme;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.internal.ParcelableSparseArray;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import org.joda.time.DateTime;
import java.util.ArrayList;
import me.akshaypall.roomme.classes.Notice;
import me.akshaypall.roomme.classes.NoticeAdapter;
import me.akshaypall.roomme.classes.NoticeCardListener;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, NoticeCardListener {
public static final String NOTICE_CARDS_MAIN = "notices_main_to_notice_A";
private ArrayList<Notice> mNotices;
private RecyclerView mNoticeView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Template setup for navigation drawer and toolbar **/
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//fake notice data (temporary)
mNotices = new ArrayList<>();
for (int i = -5; i < 5; i++){
DateTime date = (i < 0) ? DateTime.now().minusDays((-i)*6) :
DateTime.now().plusMinutes(i*6*Notice.MINUTES_IN_DAY);
//to test relative datetime string (in past and future)
mNotices.add(i+5, new Notice("Ayy"+i, "afsdsfdhjka j dhsakjdajk " +
"h dksahd kashdjas dkj sajdahskjdhsak kjkdhjkhdak---"+i,
date));
}
/** Setup for Notice recyclerview && adapter **/
mNoticeView = (RecyclerView)findViewById(R.id.main_notices_recyclerview);
mNoticeView.setLayoutManager(new LinearLayoutManager(this));
mNoticeView.setAdapter(new NoticeAdapter(mNotices, true, this));
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_notices) {
// TODO: go to notices
} else if (id == R.id.nav_spending) {
//TODO: go to spending
} else if (id == R.id.nav_settings) {
//TODO: go to settings
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void clickedCard(View card) {
Intent i = new Intent(this, NoticeActivity.class);
Bundle b = new Bundle();
b.putParcelableArrayList(NOTICE_CARDS_MAIN, mNotices);
i.putExtra(NOTICE_CARDS_MAIN, b);
//TODO: start activity with transition of cards
ActivityOptionsCompat transitionOptions = ActivityOptionsCompat.
makeSceneTransitionAnimation(this, (View)mNoticeView,
this.getString(R.string.notice_list_transition_name));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
startActivity(i, transitionOptions.toBundle());
}
}
@Override
public void swipedCard(View v, int position) {
//Nothing happens here, only used in NoticeActivity
}
}
<file_sep>package me.akshaypall.roomme;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.AccelerateInterpolator;
import java.util.ArrayList;
import me.akshaypall.roomme.classes.Notice;
import me.akshaypall.roomme.classes.NoticeAdapter;
import me.akshaypall.roomme.classes.NoticeCardListener;
public class NoticeActivity extends AppCompatActivity implements NoticeCardListener {
private static final String TEST_TAG = "TEST INFO------";
private static final String CLICKED_TAG = "Clicked_Notice_Card";
public static final String DELETE_TAG = "Deleted card";
private ArrayList<Notice> mNotices;
private NoticeAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notice);
mNotices = new ArrayList<>();
//TODO: take input of notice cards from main activity, but check if empty to pull data from
// database (i.e. if go to notice activity from another, non-main activity without crashing)
if (this.getIntent().getExtras() != null){
Bundle b = this.getIntent().getExtras().getBundle(MainActivity.NOTICE_CARDS_MAIN);
mNotices = b.getParcelableArrayList(MainActivity.NOTICE_CARDS_MAIN);
}
//print to console if notice cards passed
Log.d(TEST_TAG,
mNotices.size() > 0 ? mNotices.get(0).getmTitle() : "NO NOTICES PASSED FROM MAIN");
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.notice_activity_recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new NoticeAdapter(mNotices, false, this);
recyclerView.setAdapter(mAdapter);
}
@Override
public void clickedCard(View card) {
Log.d(CLICKED_TAG, "Notice card clicked!");
}
@Override
public void swipedCard(View v, int position) {
final int cardPosition = position;
final View view = v;
//open dialog box asking to remove card
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.delete_notice_dialog_title)
.setMessage(R.string.delete_notice_dialog_message)
.setNegativeButton(R.string.delete_notice_dialog_no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); //do nothing
}
})
.setPositiveButton(R.string.delete_notice_dialog_yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//remove said card
final float oldX = view.getX();
view.postOnAnimationDelayed(new Runnable() {
@Override
public void run() {
mNotices.remove(cardPosition);
mAdapter.notifyDataSetChanged();
Log.wtf(DELETE_TAG,
"Deleted: "+mNotices.get(cardPosition).getmTitle());
}
}, 450);
view.animate()
.setDuration(450)
.setInterpolator(new AccelerateInterpolator())
.x(oldX+1500)
/**.setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
//move first view back to normal spot
view.setVisibility(View.INVISIBLE);
view.setX(oldX);
view.setVisibility(View.VISIBLE);
Log.wtf(DELETE_TAG,
"Deleted: "+mNotices.get(cardPosition).getmTitle());
mNotices.remove(cardPosition);
mAdapter.notifyDataSetChanged();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
})**/;
dialog.dismiss();
}
})
.show();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.home:
supportFinishAfterTransition();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 1ad9993ad2b12e38bba31c11d23393f81b81edc9 | [
"Markdown",
"Java"
]
| 5 | Markdown | AkshayPall/room.me-android | 9d1bf21fa058e4393631a1a97501d06c7197ea1d | 1af9e21e7d77bbb196ed89771f1bb5fd2c7de189 |
refs/heads/main | <repo_name>hilarysn/CG-Dashboard<file_sep>/CEWP_Chart_Enlisted_Accessions_hsn.js
var currentAccessions = [];
var currentMission = [];
var currentContracts = [];
var currentOverunder = [];
var fiscalYears = [];
var options = [];
var CG = CG || {};
CG.AJAX = CG.AJAX || {};
CG.DASHBOARD = CG.MYDASHBOARD || {};
CG.DASHBOARD.CHARTS = CG.DASHBOARD.CHARTS || {};
CG.DASHBOARD.CHARTS.VARIABLES = CG.DASHBOARD.CHARTS.VARIABLES || {};
CG.DASHBOARD.CHARTS.VARIABLES.BUDGET = {
site: null,
loc: String(window.location),
waitmsg: null,
title: null,
ctx: null,
web: null,
list: null,
data: null,
json: null,
listitem: null,
used: 0,
remaining: 0,
pending: 0,
total: 0,
user: null,
userID: null,
qry: null,
html: "",
currentFY: null,
previousFY: null,
totalAccessions: 0,
totalMission: 0,
totalContracts: 0,
overUnder: 0
}
CG.DASHBOARD.CHARTS.ACCESSSIONS = function () {
var v = CG.DASHBOARD.CHARTS.VARIABLES.BUDGET;
function Init(site, qry) {
var inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
if (inDesignMode === "1") {
$("#accessions").html("").append("<div style='margin:5px;text-align:center;font-weight:bold;font-size:14px;font-style:italic;'>Query Suspended During Page Edit Mode</div>");
}
else {
setCurrentFY();
}
}
$(document).ready(function(){
$("#inputFY").change(changeFY);
});
function setCurrentFY() {
//set current fiscal year
var d = new Date();
v.currentYear = d.getFullYear().toString().substr(2, 2);
var month = d.getMonth();
if (month > 9) {
v.currentFY = v.currentYear + 1;
} else {
v.currentFY = v.currentYear;
}
console.log("v.currentFY", v.currentFY);
getFiscalYears();
}
function getFiscalYears() {
var url = 'https://hq.tradoc.army.mil/sites/cpg/_vti_bin/listdata.svc/EnlistedAccessionsByFiscalYear?select=FY&$orderby=FY';
console.log("url in LoadPreviousTripCharges: ", url);
$.ajax({
url: url,
method: "GET",
headers: { "Accept" : "application/json; odata=verbose"},
success: function(data) {
var results = data.d.results;
var j = jQuery.parseJSON(JSON.stringify(results));
//load all entries in the FY column to an array
for (i=0; i < j.length; i++) {
fiscalYears[i] = j[i].FY;
}
//remove the duplicates and load to a new array
for (var i=0; i<fiscalYears.length; i++) {
if (fiscalYears[i]!=fiscalYears[i-1]) options.push(fiscalYears[i]);
}
console.log("options", options);
loadFilter();
},
error: function(data) {
failure(data.responseJSON.error);
}
});
}
function loadFilter(){
//load all entries in the options array to the FY drop down as options
for (i=0; i < options.length; i++) {
//the value is a 2 digit year but the DISPLAY is four
$("#inputFY").append("<option value='" + options[i] + "'" + ">" + "20" + options[i] + "</option>");
//set current selected value to the current FY (this is for display only to reduce confusion. The code sets everything to the current FY by default)
$("#inputFY").val(v.currentFY);
}
getMissionCurrent();
}
function changeFY(){
var selectVal = $("#inputFY").val();
v.currentFY = selectVal;
v.totalMission = 0;
v.totalAccessions = 0;
v.totalContracts = 0;
v.totalOverunder = 0;
v.overUnder = 0;
currentMission = [];
currentAccessions = [];
currentContracts = [];
getMissionCurrent();
}
function getMissionCurrent() {
var maccumulator = 0;
var aaccumulator = 0;
var faccumulator = 0;
var oaccumulator = 0;
var url = 'https://hq.tradoc.army.mil/sites/cpg/_vti_bin/listdata.svc/EnlistedAccessionsByFiscalYear?select=Mission,Accession,Contracts,FY,FYmonthorder&$orderby=FYmonthorder&$filter=FY eq ' + v.currentFY;
$.ajax({
url: url,
method: "GET",
headers: { "Accept" : "application/json; odata=verbose"},
success: function(data) {
var results = data.d.results;
var j = jQuery.parseJSON(JSON.stringify(results));
for (var i = 0; i < j.length; i++) {
currentMission[i] = j[i].Mission;
currentAccessions[i] = j[i].Accession;
currentContracts[i]= j[i].Contracts;
currentOverunder[i]= j[i].Accession - j[i].Mission;
}
for (i = 0; i < currentMission.length; i++) {
maccumulator = currentMission[i];
v.totalMission = v.totalMission + maccumulator;
}
console.log("totalMission" + v.currentFY, v.totalMission);
for (i = 0; i < currentAccessions.length; i++) {
aaccumulator = currentAccessions[i];
v.totalAccessions = v.totalAccessions + aaccumulator;
}
console.log("totalAccessions" + v.currentFY, v.totalAccessions);
for (i = 0; i < currentOverunder.length; i++) {
oaccumulator = currentOverunder[i];
v.totalOverunder = v.totalOverunder + oaccumulator;
}
console.log("totalOverunder" + v.currentFY, v.totalOverunder);
for (i = 0; i < currentContracts.length; i++) {
faccumulator = currentContracts[i];
v.totalContracts = v.totalContracts + faccumulator;
}
console.log("totalMission" + v.currentFY, v.totalContracts);
},
error: function(data) {
failure(data.responseJSON.error);
}
});
}
function DrawChart() {
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: "Enlisted Accessions by Fiscal Year 20" + v.currentFY
},
xAxis: {
categories: [
'Oct',
'Nov',
'Dec',
'Jan',
'Feb',
'March',
'April',
'May',
'June',
'July',
'August',
'Sept'
]
},
yAxis: [{
min: 0,
title: {
text: 'Recruits'
}
}, {
title: {
text: 'Profit (millions)'
},
opposite: true
}],
legend: {
shadow: false
},
tooltip: {
shared: true
},
plotOptions: {
column: {
grouping: false,
shadow: false,
borderWidth: 0
}
},
series: [{
name: 'Mission',
color: 'rgba(243, 117, 43,1)',
data: currentMission,
pointPadding: 0.3,
pointPlacement: -0.2
}, {
name: 'Accessions',
color: 'rgba(39, 126, 39,.9)',
data: currentAccessions,
pointPadding: 0.4,
pointPlacement: -0.2
}, {
name: 'Contracts',
color: 'rgba(213, 100, 40,1)',
data: currentContracts,
pointPadding: 0.3,
pointPlacement: -0.2
}, {
name: 'Over / Under',
color: 'rgba(33, 100, 36,.9)',
data: currentOverunder,
pointPadding: 0.4,
pointPlacement: -0.2
}]
});
updateYTD();
}
function updateYTD(){
$(document).ready(function(){
$("#ytdAccessions h3").remove();
$("#ytdMission h3").remove();
$("#ytdOverUnder h3").remove();
//$("#ytdContracts h3").remove();
$("#ytdAccessions").append("<h3>" + v.totalAccessions + "</h3>");
$("#ytdMission").append("<h3>" + v.totalMission + "</h3>");
//$("#ytdContracts").append("<h3>" + v.totalContracts + "</h3>");
v.overUnder = v.totalAccessions - v.totalMission;
$("#ytdOverUnder").append("<h3>" + v.overUnder + "</h3>");
if(v.overUnder < 0) {
$("#ytdOverUnder").css("color", "red");
}
});
}
return {
Init: Init
}
}
SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs('CEWP_Chart_Enlisted_Accessions.js');<file_sep>/CEWP_Dashboard.js
var DCOS = DCOS || {};
DCOS.DASHBOARD = DCOS.DASHBOARD || {};
DCOS.DASHBOARD.Home = function () {
function Init(site) {
loadscript(site + '/SiteAssets/js/vuecomponents.js', function () {
new Vue({
el: '#app',
components: {
'dashboard-layout': DashboardLayout
}
})
});
}
return {
Init: Init
}
}
SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs('CEWP_Dashboard.js'); | 98286f698dc037eb21a27dd6254eadd191d236d4 | [
"JavaScript"
]
| 2 | JavaScript | hilarysn/CG-Dashboard | ac4a0524cc651bc394723fd0e551e5bc4b0870cb | 10d99bc1d5fcd5e5bda7a7b8c29a900cd2d4e529 |
refs/heads/master | <file_sep>package com.example.hour2hour;
import androidx.appcompat.app.AppCompatActivity;
import android.app.TimePickerDialog;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.*;
import android.os.Bundle;
import java.util.Calendar;
import static java.lang.Math.round;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Time Spinner
Spinner setHour = findViewById(R.id.selectedHour);
Spinner setMinute = findViewById(R.id.selectedMinute);
ArrayAdapter<CharSequence> hourAdapter = ArrayAdapter.createFromResource(this, R.array.hours, android.R.layout.simple_spinner_item);
ArrayAdapter<CharSequence> minuteAdapter = ArrayAdapter.createFromResource(this, R.array.minutes, android.R.layout.simple_spinner_item);
hourAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
minuteAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
setHour.setAdapter(hourAdapter);
setMinute.setAdapter(minuteAdapter);
setHour.setOnItemSelectedListener(this); setMinute.setOnItemSelectedListener(this);
String firstHour = setHour.getSelectedItem().toString();
String firstMinute = setMinute.getSelectedItem().toString();
//TimeZone Spinners
Spinner TZ_input = findViewById(R.id.inputZone);
Spinner TZ_output= findViewById(R.id.outputZone);
ArrayAdapter<CharSequence> timezonesAdapter = ArrayAdapter.createFromResource(this, R.array.time_zones, android.R.layout.simple_spinner_item);
timezonesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
TZ_input.setAdapter(timezonesAdapter);
TZ_output.setAdapter(timezonesAdapter);
TZ_input.setOnItemSelectedListener(this); TZ_output.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String t = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), t, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void Convert_Button(View v) {
Spinner Hour1 = findViewById(R.id.selectedHour);
Spinner Minute1 = findViewById(R.id.selectedMinute);
Spinner Timezone1 = findViewById(R.id.inputZone);
Spinner Timezone2 = findViewById(R.id.outputZone);
int[] hour_min = Convert_Time(Hour1.getSelectedItem().toString(), Minute1.getSelectedItem().toString(), Timezone1.getSelectedItem().toString(),Timezone2.getSelectedItem().toString());
String Hour2 = String.valueOf(hour_min[0]);
String Minute2 = String.valueOf(hour_min[1]);
//am2pm_pm2am(hour_min[2]);
TextView H2 = findViewById(R.id.FinalHour); TextView M2 = findViewById(R.id.FinalMinute);
H2.setText(Hour2); M2.setText(Minute2);
}
public int[] Convert_Time(String h, String m, String TZ1, String TZ2){
int h1 = Integer.parseInt(h);
int minut=Integer.parseInt(m);
int TZ1_int = convert_tz_to_int(TZ1);
int TZ2_int = convert_tz_to_int(TZ2);
int TZ_difference = TZ2_int - TZ1_int;
int h2_full = (h1 + TZ_difference);
int rotation = round(h2_full/12);
int h2 = h2_full%24;
return new int[]{h2, minut, rotation};
}
public int convert_tz_to_int(String TZ){
if (TZ.length()==3){
return 0;
}
else{
return Integer.parseInt(TZ.substring(3,TZ.length()));
}
}
public void am2pm_pm2am(int r){
Button b = findViewById(R.id.am_pm);
TextView t = findViewById(R.id.final_am_pm);
for (int i=0; i<r; ++i){
if (b.getText().equals("AM")){
t.setText("PM");
}
else if (b.getText().equals("PM")){
t.setText("AM");
}
}
}
public String am_pm_switcher(View v){
Button b = (Button) v;
if (b.getText().equals("AM")){
b.setText("PM");
return "PM";
}
else if (b.getText().equals("PM")){
b.setText("AM");
return "AM";
}
else {return null;}
}
} | adeeff10440ab75ad4e806031ff50553726805c1 | [
"Java"
]
| 1 | Java | EfeKaralar/Hour2Hour_reupload | 936f99a5dacd4a644c3de040e1bdd24e18a1c3ef | 370ce7cfea2d74e7682e76e0c529864b1a2a468c |
refs/heads/master | <file_sep>package com.zxf.test3;
public class Main3 {
public static void main(String[] args) {
/*
Customer customer=new DeliveryClierk();
System.out.println(customer.order("鸡腿"));
*/
//顾客
Customer customer=new Customer();
//代理对象,外卖小哥
OrderInterface deliveryClerk=new DeliveryClierk2(customer);
String result= deliveryClerk.order("冷面");
System.out.println(result);
}
}
<file_sep>package com.zxf.dao;
import org.springframework.stereotype.Repository;
@Repository("userDao1")
public class IUserDaoImpl implements IUserDao {
public IUserDaoImpl(){
System.out.println("IUserDaoImpl对象创建了。111111");
}
public void saveUserDao() {
System.out.println("Dao接口中的saveUser()方法执行了。");
}
}
<file_sep>spring.datasource.driver-class-name =com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/online
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 短信接受表; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/tblMessageReceive")
public class TblMessageReceiveController {
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.TblNetdiskUrl;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 网络硬盘路径; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblNetdiskUrlMapper extends BaseMapper<TblNetdiskUrl> {
}
<file_sep>package com.zxf.test1;
import org.springframework.stereotype.Component;
@Component
public interface MyService1 {
public String sayCat();
}
<file_sep>package com.zxf.web.controller;
import com.zxf.web.pojo.Users;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/users")
public class MyController2 {
@RequestMapping("/saveUsers")
public String saveUsers(Users users){
System.out.println(users.getName());
System.out.println(users.getAge());
System.out.println(users.getPwd());
return "ok2";
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.WyCommitteeMetting;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 业委会会议; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyCommitteeMettingMapper extends BaseMapper<WyCommitteeMetting> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.ZhCsHandleSpeed;
import com.zxf.mapper.ZhCsHandleSpeedMapper;
import com.zxf.service.ZhCsHandleSpeedService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 业主服务_办理进度; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class ZhCsHandleSpeedServiceImpl extends ServiceImpl<ZhCsHandleSpeedMapper, ZhCsHandleSpeed> implements ZhCsHandleSpeedService {
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.FyMoneyTemporary01;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 费用临时表1; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface FyMoneyTemporary01Mapper extends BaseMapper<FyMoneyTemporary01> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.ZhConsumerComplain;
import com.zxf.mapper.ZhConsumerComplainMapper;
import com.zxf.service.ZhConsumerComplainService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 业主投诉; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class ZhConsumerComplainServiceImpl extends ServiceImpl<ZhConsumerComplainMapper, ZhConsumerComplain> implements ZhConsumerComplainService {
}
<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 楼盘经费支出明细_审批子表; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/wyEstateOutDetailSub")
public class WyEstateOutDetailSubController {
}
<file_sep>package com.zxf.service;
import com.zxf.dao.CityDao;
import com.zxf.domain.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CityService {
@Autowired
CityDao cityDao;
public List<City> findAll(){
return cityDao.findAll();
}
public String add(Integer id,String name){
City city=new City();
city.setId(id);
city.setName(name);
try{
cityDao.save(city);
return "保存成功。";
}catch (Exception e){
return "保存失败!";
}
}
}<file_sep>package com.zxf.service;
import com.zxf.bean.WyPictureManage;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 图纸管理; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyPictureManageService extends IService<WyPictureManage> {
}
<file_sep>package com.zxf.domain;
public class VideoOrder {
private Integer id;
private String outTradeNo;
private Video video;
public VideoOrder(){
System.out.println("VideoOrder()调用了");
}
public Video getVideo() {
return video;
}
public void setVideo(Video video) {
// System.out.println("videoOrder setVideo方法被调用");
this.video = video;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOutTradeNo() {
return outTradeNo;
}
public void setOutTradeNo(String outTradeNo) {
this.outTradeNo = outTradeNo;
}
}
<file_sep>package com.test;
import com.zxf.pojo.Flower;
import com.zxf.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:beans.xml")
public class Main2 {
@Autowired
private IAccountService ac=null;
@Test
public void testFindAll(){
List<Flower> flowers=ac.findAllFlower();
for(Flower f:flowers){
System.out.print(f.getId()+" ");
System.out.print(f.getProduction()+" ");
System.out.println(f.getName());
}
}
}
<file_sep>package com.zxf;
import com.zxf.mapper.AccountMapper;
import com.zxf.mapper.FlowerMapper;
import com.zxf.pojo.Account;
import com.zxf.pojo.Flower;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.*;
public class Test2 {
private SqlSessionFactory sqlSessionFactory;
private SqlSession session;
private FlowerMapper flowerMapper;
private InputStream is;
@Before //用于测试方法之前执行。
public void init() throws Exception{
is= Resources.getResourceAsStream("zhangMyBatis.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
session=sqlSessionFactory.openSession();
flowerMapper=session.getMapper(FlowerMapper.class);
}
@After //用于测试方法之后执行。
public void destory()throws Exception{
session.commit();
session.close();
is.close();
}
//调用的注解那个方法
@Test
public void test1()throws Exception{
List<Flower> flowers=flowerMapper.getAll();
for(Flower f:flowers){
System.out.println(f.getName());
}
}
//查询所有的方法
@Test
public void test2()throws Exception{
List<Flower> flowers=flowerMapper.getAll2();
for(Flower f:flowers){
System.out.println(f.getId()+"-->"+f.getName()+","+f.getProduction());
}
}
//增加
@Test
public void test3()throws Exception{
Flower flower=new Flower();
flower.setProduction("在看看吧");
flower.setPrice(92.89F);
flower.setName("程序可以不");
int i=flowerMapper.saveFlower(flower);
}
//修改
@Test
public void test4()throws Exception{
Flower flower=new Flower();
flower.setId(1414);
flower.setProduction("开始修改了");
flower.setPrice(63.9F);
flower.setName("看看修改结果吧");
flowerMapper.updateFlower(flower);
}
//删除
@Test
public void test5()throws Exception{
flowerMapper.delFlower(1413);
}
//查询
@Test
public void test6()throws Exception{
Flower byidFlower = flowerMapper.findByidFlower(1);
System.out.println(byidFlower.getId()+":"+byidFlower.getName()+","+byidFlower.getProduction());
}
//模糊查询
@Test
public void test7()throws Exception{
List <Flower>fs = flowerMapper.findBylike("%1%");
for(Flower flower:fs){
System.out.println(flower.getId()+":"+flower.getName()+","+flower.getProduction());
}
}
//返回聚合函数 总记录条数
@Test
public void test8()throws Exception{
int allSize = flowerMapper.getAllSize();
System.out.println(allSize);
}
@Test
public void test9()throws Exception{
Flower f1=new Flower();
f1.setName("小花花100");
f1.setProduction("任何地方都有的小野花100");
Flower flower = flowerMapper.findFlowerByCondition(f1);
System.out.println(flower.getId()+flower.getProduction()+flower.getPrice()+flower.getName());
}
@Test
public void test10()throws Exception{
Flower f1=new Flower();
// f1.setName("小花asdf花100");
f1.setProduction("任何地方都有的小野花100");
Flower flower = flowerMapper.findFlowerByCondition2(f1);
if(flower!=null) {
System.out.println(flower.getId() + flower.getProduction() + flower.getPrice() + flower.getName());
}
}
//////////////////////////////////////////////////
//以下是一对一的练习
//查询account表的所有信息
@Test
public void test11(){
AccountMapper accountMapper=session.getMapper(AccountMapper.class);
List<Account> accounts=accountMapper.findAll();
for(Account a:accounts){
System.out.println(a.getName()+":"+a.getBalance());
}
}
// 查询2个表,users account
@Test
public void test12(){
AccountMapper accountMapper=session.getMapper(AccountMapper.class);
List<Account> accounts=accountMapper.findallA_U();
for(Account a:accounts){
System.out.println(a.getId()+":"+a.getName()+":"+a.getBalance()+"-->"+a.getUser().getUsername()+",年龄:"+a.getUser().getUserage()+","+a.getUser().getUsername());
}
}
// 查询2个表,users account
@Test
public void test13(){
AccountMapper accountMapper=session.getMapper(AccountMapper.class);
List<Account> accounts=accountMapper.findallA_U();
for(Account a:accounts){
System.out.print(a.getId()+":account_name:"+a.getName());
System.out.print("____________________");
System.out.println("users_username:"+a.getUser().getUsername()+" users_userid:"+a.getUser().getUserid());
}
}
}<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblUserRecord;
import com.zxf.mapper.TblUserRecordMapper;
import com.zxf.service.TblUserRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 用户档案; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblUserRecordServiceImpl extends ServiceImpl<TblUserRecordMapper, TblUserRecord> implements TblUserRecordService {
}
<file_sep>package com.zxf.mapper;
import com.zxf.pojo.Employee;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface EmployeeMapper {
//注解方式
// @Select("select * from employee_basic ")
//查询所有
public List<Employee> findAll();
//保存
public void saveEmp(Employee employee);
//修改
public void updateEmp(Employee employee);
//删除
public void delEmp(String emp_no);
//根据ID查询
public Employee findByidEmp(String emp_no);
//模糊查询
public List<Employee> findLikeEmp(String emp_name);
//获得总记录条数
public int getCountEmp();
//查询员工姓名,部门名称
public List<Employee> getallEmp_dep();
}
<file_sep>package com.test;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Random;
public class Test1 {
@Test
public void test1(){
/*
反向输出数组。
*/
int[] arr={1,2,3,4,5,6};
for (int min=0, max=arr.length-1;min<max;min++,max--) {
int temp=arr[min];
arr[min]=arr[max];
arr[max]=temp;
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
@Test
public void test2(){
for (int i = 0; i < 9990; i++) {
Random r=new Random();
System.out.println(r.nextLong());
}
}
@Test
public void test3(){
ArrayList<Integer> list=new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list.add(new Random().nextInt(100)+1);
}
System.out.println(list);
ArrayList<Integer> list_2=new ArrayList<Integer>();
for(Integer i:list){
if(i%2==0){
list_2.add(i);
}
}
System.out.println(list_2);
}
}<file_sep>package com.zxf.spring2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main3 {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring3.xml");
A a=applicationContext.getBean("A",A.class);
System.out.println(a);
System.out.println(a.getB());
System.out.println(a.getB().getC());
System.out.println("-------");
A a1=applicationContext.getBean("A",A.class);
System.out.println(a1);
System.out.println(a1.getB());
System.out.println(a1.getB().getC());
}
}
<file_sep>package com.zxf.bean5;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component //注解方式定义一个类似bean对象标签
@Aspect//标注当前类为切面
public class MyAspect {
/*
前置通知
value属性必须写。
*/
//@Before(value = "execution(* com.zxf.bean5.MathImpl.add(..))")//为某一个方法写aop
//@Before(value = "execution(* com.zxf.bean5.MathImpl.*(..))")//类下的所有方法
@Before(value = "execution(* com.zxf.bean5.*.*(..))")//包下的所有类的所有方法
public void beforeMethod(JoinPoint joinPoint){
Object[] args=joinPoint.getArgs();//获取方法参数
String methodName=joinPoint.getSignature().getName();//获取方法名
System.out.println("方法名:"+methodName+",方法参数:"+ Arrays.toString(args)+".....方法执行之前");
}
/*
后置通知
*/
@After(value = "execution(* com.zxf.bean5.*.*(..))")
public void afterMethod(){
System.out.println("方法执行之后........");
}
/*
也是后置通知,可以带返回值
如果目标方法是void返回null
*/
@AfterReturning(value = "execution(* com.zxf.bean5.*.*(..))",returning = "result")
public void afterReturnMethod(JoinPoint joinPoint,Object result){
System.out.println("后置返回:"+result);
}
/*
异常通知
*/
@AfterThrowing(value = "execution(* com.zxf.bean5.*.*(..))",throwing = "ex")
public void afterThowingMethod(Exception ex){
System.out.println("*******有了异常。。。。。"+ex.getMessage());
}
/*
环绕通知
*/
@Around(value = "execution(* com.zxf.bean5.*.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint){
Object result=null;
try{
System.out.println("环绕前置");
result =joinPoint.proceed();
return result;
}catch (Throwable e){
System.out.println("环绕异常");
}finally {
System.out.println("环绕后置");
}
return null;
}
}
<file_sep>person.last-name=\u6211\u662F\u81EA\u5B9A\u4E49\u6587\u4EF6
person.address=\u5317\u4EAC\u5148
person.age=213
person.birth=2014/6/21
person.boss=true
person.lists=\u6570\u636E,\u7A0B\u5E8F,\u7F13\u5B58,\u7A7A\u95F4
person.maps.k1=\u6211\u662Fmap1
person.maps.k2=\u6211\u662Fmap2
person.dog.name=\u8FD9\u4E2A\u662F\u5C0F\u72D7
person.dog.age=22
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.WyCommitteeMetting;
import com.zxf.mapper.WyCommitteeMettingMapper;
import com.zxf.service.WyCommitteeMettingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 业委会会议; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class WyCommitteeMettingServiceImpl extends ServiceImpl<WyCommitteeMettingMapper, WyCommitteeMetting> implements WyCommitteeMettingService {
}
<file_sep>package com.zxf.inters;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class InterceptorJdkProxyS implements InvocationHandler {
private Object target;//真实对象
private String interceptorClass=null; //拦截器全限定名
public InterceptorJdkProxyS(Object target, String interceptorClass) {
this.target = target;
this.interceptorClass = interceptorClass;
}
/*
绑定委托对象返回一个代理位置
*/
public static Object bind(Object target,String interceptorClass){
//取得代理对象
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InterceptorJdkProxyS(target,interceptorClass));
}
/*
通过代理对象调用方法,首先进入这个方法。
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(interceptorClass==null){
//没有设置拦截器则直接反射原有方法
return method.invoke(target,args);
}
Object result=null;
Interceptors interceptors=(Interceptors)Class.forName(interceptorClass).newInstance();
if(interceptors.before(proxy,target,method,args)){
result=method.invoke(target,args);
}else {
interceptors.around(proxy,target,method,args);
}
interceptors.after(proxy,target,method,args);
return result;
}
}
<file_sep>package com.zxf.pojo;
import java.io.Serializable;
import java.util.List;
public class People implements Serializable {
private Integer p_id;
private String p_name;
private Integer p_age;
private List<Integer> p_ids;
public List<Integer> getP_ids() {
return p_ids;
}
public void setP_ids(List<Integer> p_ids) {
this.p_ids = p_ids;
}
public Integer getP_id() {
return p_id;
}
public void setP_id(Integer p_id) {
this.p_id = p_id;
}
public String getP_name() {
return p_name;
}
public void setP_name(String p_name) {
this.p_name = p_name;
}
public Integer getP_age() {
return p_age;
}
public void setP_age(Integer p_age) {
this.p_age = p_age;
}
}
<file_sep>package com.zxf.main;
class Account9{
String name;
double balance;
public synchronized void set(String name,double balance){
this.name=name;
try{
Thread.sleep(200);
}catch (Exception e){
e.printStackTrace();
}
this.balance=balance;
}
public /*synchronized*/ double getBalances(){
return this.balance;
}
}
public class Main9 {
public static void main(String[] args) {
Account9 account9=new Account9();
new Thread(()->{
account9.set("zhang",100);
}).start();
try{
Thread.sleep(5);
}catch (Exception e){
e.printStackTrace();
}
System.out.println(account9.getBalances());
try{
Thread.sleep(5);
}catch (Exception e){
e.printStackTrace();
}
System.out.println(account9.getBalances());
}
}<file_sep>package com.zxf.mapper;
import com.zxf.bean.ZhRentTransfer;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 租户转兑; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface ZhRentTransferMapper extends BaseMapper<ZhRentTransfer> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.WyFireExercise;
import com.zxf.mapper.WyFireExerciseMapper;
import com.zxf.service.WyFireExerciseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 消防演练; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class WyFireExerciseServiceImpl extends ServiceImpl<WyFireExerciseMapper, WyFireExercise> implements WyFireExerciseService {
}
<file_sep>package com.zxf.spring4.controller;
import com.zxf.spring4.entity.User;
import com.zxf.spring4.service.MainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
@Component("mainController")
public class MainController {
@Autowired
private MainService srv;
public String list(){
String logName="zhang";
String logPwd="abc";
User user = srv.login(logName, logPwd);
if(user==null){
return "登录失败";
}else {
return "登录成功";
}
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.ZhRentContractReturn;
import com.zxf.mapper.ZhRentContractReturnMapper;
import com.zxf.service.ZhRentContractReturnService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 租赁合同返利; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class ZhRentContractReturnServiceImpl extends ServiceImpl<ZhRentContractReturnMapper, ZhRentContractReturn> implements ZhRentContractReturnService {
}
<file_sep>package com.zxf.pojo;
public class Main1 {
static int i=0; //-18950 -19040
public static void main(String[] args){
Long l1=System.currentTimeMillis();
for(int i=0;i<1000000000;i++){
m();
n();
}
System.out.println(l1-System.currentTimeMillis());
}
public static synchronized void m(){}
public static void n(){i=1;
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblDbsource;
import com.zxf.mapper.TblDbsourceMapper;
import com.zxf.service.TblDbsourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 数据库; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblDbsourceServiceImpl extends ServiceImpl<TblDbsourceMapper, TblDbsource> implements TblDbsourceService {
}
<file_sep>package com.zxf.service;
import com.zxf.bean.FyShareUserDetail;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 公摊费用台账用户明细; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface FyShareUserDetailService extends IService<FyShareUserDetail> {
}
<file_sep>package com.zxf.service;
import com.zxf.bean.FcCell;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 房间信息表; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface FcCellService extends IService<FcCell> {
}
<file_sep>package com.zxf.bean;
public interface Animal {
public void sleep();
}
<file_sep>package com.zxf.service;
import com.zxf.bean.WyAskMsgRemindLog;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 催缴短信提醒日志; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyAskMsgRemindLogService extends IService<WyAskMsgRemindLog> {
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.TblGroupsUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 分组用户; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblGroupsUserMapper extends BaseMapper<TblGroupsUser> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.WyEmailReceive;
import com.zxf.mapper.WyEmailReceiveMapper;
import com.zxf.service.WyEmailReceiveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 信件收取; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class WyEmailReceiveServiceImpl extends ServiceImpl<WyEmailReceiveMapper, WyEmailReceive> implements WyEmailReceiveService {
}
<file_sep>package com.zxf.spring2;
public class Audi implements Car {
public String getName() {
return "我是奥迪";
}
public String getPrice() {
return "我的价格:17W";
}
}
<file_sep>package com.zxf.demo8;
public interface EmpService {
public void save();
}
<file_sep>package com.zxf.mapper;
import com.zxf.pojo.Account;
import java.util.List;
public interface AccountMapper {
/*
查询所有账户
*/
List<Account> findAll();
/*
查询account和user表的一对一
*/
List<Account> findallA_U();
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.WyNoteManage;
import com.zxf.mapper.WyNoteManageMapper;
import com.zxf.service.WyNoteManageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 票据管理; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class WyNoteManageServiceImpl extends ServiceImpl<WyNoteManageMapper, WyNoteManage> implements WyNoteManageService {
}
<file_sep>package com.zxf.springcloud.dao;
import com.zxf.springcloud.entities.Payment;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
//import org.springframework.stereotype.Repository;
@Mapper//在DAO层中如果有Mybatis建议使用该注解
//@Repository //在DAO层中如果有mybatis不建议使用 因为插入数据会有写不稳定。
public interface PaymentDao {
public int create(Payment payment);
public Payment getPaymentById(@Param("id") Long id);
}<file_sep>package com.zxf.exception;
import com.zxf.utils.JsonData;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/*
异常处理类
*/
@ControllerAdvice
public class CustomExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public JsonData handle(Exception e){
if(e instanceof XFException){
XFException xfException=(XFException) e;
return JsonData.buildError(xfException.getCode(),xfException.getMsg());
}else {
return JsonData.buildError("全局异常,未知错误!");
}
}
}<file_sep>package com.zxf.test5cglib;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class Main5 {
public static void main(String[] args) {
//创建一个顾客
Customer customer=new Customer();
Customer deliverClier=(Customer) Enhancer.create(customer.getClass(), new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
if("order".equals(method.getName())){
Object result = method.invoke(customer, objects);
System.out.println("11111");
System.out.println("22222");
return result+",添加了不明东西";
}else {
return method.invoke(customer,args);
}
}
});
deliverClier.test();
deliverClier.test2();
String result = deliverClier.order("Spring");
System.out.println(result);
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.TblMyNote;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 我的记事本; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblMyNoteMapper extends BaseMapper<TblMyNote> {
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.FyStandingBookDetail;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 费用台账明细; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface FyStandingBookDetailMapper extends BaseMapper<FyStandingBookDetail> {
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.ZhRentContractReturn;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 租赁合同返利; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface ZhRentContractReturnMapper extends BaseMapper<ZhRentContractReturn> {
}
<file_sep>package com.zxf.bean2;
import org.springframework.stereotype.Component;
@Component
public class Teacher implements Person {
public void eat() {
System.out.println("老师吃饭饭");
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.TblColor;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 颜色管理; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblColorMapper extends BaseMapper<TblColor> {
}
<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 楼盘费用; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/wyEstateMoney")
public class WyEstateMoneyController {
}
<file_sep>package com.zxf.proxy;
public interface PayService {
String callback(String outTradeNo);
int save(int userId,int productId);
}
<file_sep>package com.zxf.test;
import com.zxf.mapper.EmployeeMapper;
import com.zxf.pojo.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class Test_one_one {
private InputStream inputStream=null;
private SqlSession session=null;
private EmployeeMapper mapper=null;
@Before //Test方法之前执行,都是junit提供的方法
public void init()throws IOException {
//加载主配置文件
inputStream= Resources.getResourceAsStream("mybatisConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂获取SqlSession
session=factory.openSession();
mapper = session.getMapper(EmployeeMapper.class);
}
@After//Test方法之后执行,都是junit提供的方法
public void destory()throws IOException{
session.close();
inputStream.close();
}
//测试员工和学历表的一对一查询
@Test
public void test1(){
Employee employee = mapper.selectEmployeeById("HW9808");
System.out.print(employee.getEmp_name()+",");
System.out.print(employee.getEmp_gender()+",");
System.out.print(employee.getEmp_zzmm()+",");
System.out.print(employee.getEmployeeSchool().getEmp_major()+",");
System.out.print(employee.getEmployeeSchool().getEmp_xueli()+",");
System.out.println(employee.getEmployeeSchool().getBy_school());
}
}
<file_sep>package com.zxf.ano.config;
import com.zxf.domain.VideoOrder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean(name = "v1")
public VideoOrder videoOrder(){
System.out.println("Bean标签定义的v1执行了");
return new VideoOrder();
}
}
<file_sep>package com.zxf.springcloud.controller;
import com.zxf.springcloud.entities.CommonResult;
import com.zxf.springcloud.entities.Payment;
import com.zxf.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
@Slf4j
public class PaymentController {
@Resource
private PaymentService paymentService;
@Value("${server.port}")
private String serverPort;
@Resource
private DiscoveryClient discoveryClient;
@PostMapping(value = "/payment/create")
public CommonResult create(@RequestBody Payment payment){//这里必须加@RequestBody。否则提交的数据不能写入数据库
int result = paymentService.create(payment);
log.info("插入结果:"+result);
if(result>0){
return new CommonResult(200,"数据写入成功:"+serverPort);
}else {
return new CommonResult(444,"数据写入失败",null);
}
}
@GetMapping(value = "/payment/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id){
Payment payment = paymentService.getPaymentById(id);
log.info("查询结果为:"+payment);
if(null!=payment){
return new CommonResult(200,"查询成功了:"+serverPort,payment);
}else {
return new CommonResult(444,"查无此人,编号为:"+id,payment);
}
}
@GetMapping(value = "/payment/discovery")
public Object discover(){
List<String> services = discoveryClient.getServices();
for(String element:services){
log.info("@@@@@"+element);
}
List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
for(ServiceInstance serviceInstance:instances){
log.info(serviceInstance.getServiceId()+"\t"+serviceInstance.getHost()+"\t"+serviceInstance.getPort()+"\t"+serviceInstance.getUri());
}
return this.discoveryClient;
}
@GetMapping(value = "/payment/lb")
public String getPaymentLB(){
return serverPort;
}
}
<file_sep>package com.zxf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller//表示controller请求处理层
public class MyController1 {
@RequestMapping("ok1") //请求的名字
public String bean1(){
System.out.println("ok1....执行了");
return "ok1"; //试图名称
}
}
<file_sep>package com.zxf.service;
import com.zxf.bean.ZhCustomerMembers;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 业主成员; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface ZhCustomerMembersService extends IService<ZhCustomerMembers> {
}
<file_sep>package com.zxf;
import com.zxf.demo.Demo1;
import com.zxf.demo.Demo2;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test1 {
@Test
public void test1(){
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Demo1 d_1 = ac.getBean("demo1", Demo1.class);
d_1.demo1();
d_1.demo2();
d_1.demo3();
Demo2 d_2 = ac.getBean("demo2", Demo2.class);
d_2.f();
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblNetdiskUrl;
import com.zxf.mapper.TblNetdiskUrlMapper;
import com.zxf.service.TblNetdiskUrlService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 网络硬盘路径; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblNetdiskUrlServiceImpl extends ServiceImpl<TblNetdiskUrlMapper, TblNetdiskUrl> implements TblNetdiskUrlService {
}
<file_sep>package com.zxf.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
第一定义servlet的方式
*/
@WebServlet(name = "s1",urlPatterns = "/s1")
public class Servlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Servlet1.......");
}
}
<file_sep>package com.zxf.conf;
import com.zxf.service.HelloSerive;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/*
当前类上一个配置类。可以替换之前Spring中的配置文件
以前我们定义Bean标签要这样写
<bean></bean>
这里使用@Bean就可以了。
*/
@Configuration
public class MyAppConfig {
@Bean
public HelloSerive helloSerive(){
System.out.println("MyAppConfig@Bean给容器添加组件了。");
return new HelloSerive();
}
}
<file_sep>package com.zxf.atguigu.dao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl implements UserDao {
public UserDaoImpl() {
System.out.println("UserDaoImpl");
}
public void save() {
System.out.println("dao层的save()方法执行了。");
}
}
<file_sep>artifactId=boot_test1
groupId=com.zxf
version=1.0-SNAPSHOT
<file_sep>package com.zxf.service;
import com.zxf.bean.TblVoteSubject;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 投票题目表; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblVoteSubjectService extends IService<TblVoteSubject> {
}
<file_sep>package com.zxf.c_000;
import java.util.concurrent.TimeUnit;
public class T01_WatIsThread {
private static class T1 extends Thread{
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
try {
TimeUnit.MICROSECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("T1");
}
}
}
public static void main(String[] args) {
new T1().start();
for (int i = 0; i <10 ; i++) {
try{
TimeUnit.MICROSECONDS.sleep(1);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("main");
}
}
}<file_sep>package com.zxf.test1;
public interface UserDao {
public User getUserByName(String u);
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.WyVegetationInformation;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 植被信息; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyVegetationInformationMapper extends BaseMapper<WyVegetationInformation> {
}
<file_sep>package com.test1;
import com.zxf.mapper.EmployeeMapper;
import com.zxf.pojo.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
public class Main2 {
@Test
public void test1()throws Exception{
Class.forName("oracle.jdbc.OracleDriver");
Connection con= DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","abc123");
PreparedStatement pstm=con.prepareStatement("select * from emp");
ResultSet rs=pstm.executeQuery();
while (rs.next()){
System.out.println(rs.getString("ENAME"));
}
}
@Test
public void test2() throws Exception{
InputStream is= Resources.getResourceAsStream("mybatis_config.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
SqlSession session1=factory.openSession();
SqlSession session2=factory.openSession();
EmployeeMapper mapper1 = session1.getMapper(EmployeeMapper.class);
EmployeeMapper mapper2=session2.getMapper(EmployeeMapper.class);
List<Employee> all_1 = mapper1.getAll4();
for(Employee e:all_1){
System.out.println(e.getEmp_name()+":"+e.getEmp_no());
}
session1.close();
/*
这里要记住一个地方,第二次查询必须要等第一次的session关闭以后才可以。
否则二级缓存没有作用,依然还会执行二次select语句发送至数据库
*/
List<Employee> all_2 = mapper2.getAll4();
for(Employee e:all_2){
System.out.println(e.getEmp_name()+"===>"+e.getEmp_no());
}
session2.close();
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.TblRoleMenuPrivi;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 角色菜单权限; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblRoleMenuPriviMapper extends BaseMapper<TblRoleMenuPrivi> {
}
<file_sep>package com.zxf.demo4;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class SpringConfig2 {
@Bean(name = "dataSource")
public DataSource createDataSource(){
DruidDataSource dataSource=new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://192.168.0.148:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("<PASSWORD>");
return dataSource;
}
}
<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 附件; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/tblAttupload")
public class TblAttuploadController {
}
<file_sep>package com.zxf.demo7;
public class MyXmlAspect {
public void log(){
System.out.println("增强方式。。。com.zxf.demo7.MyXmlAspect.log()");
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.pojo.Flower;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface FlowerMapper {
public void addFlower(Flower flower);
public Flower getById_nameFlower(@Param("id")Integer id,@Param("name")String name);
public Flower getByMapFlower(Map map);
public List<Flower> getAllFlower();
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.TblMessageReceive;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 短信接受表; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblMessageReceiveMapper extends BaseMapper<TblMessageReceive> {
}
<file_sep>package com.zxf.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main1 {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("Spring1.xml");
MessageService messageService = context.getBean(MessageService.class);
String message = messageService.getMessage();
System.out.println(message);
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.model.entity.User;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
public int save(User user);
public User findByPhone(@Param("phone")String phone);
public User findByPhoneAndPwd(@Param("phone") String phone, @Param("pwd") String pwd);
public User findByUserId(@Param("user_id") Integer userId);
}
<file_sep>package com.zxf.demoproject1.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/v1/video")
public class VideoController {
@RequestMapping("list")
public Object list(){
Map<String ,String > map=new HashMap<>();
map.put("1","java");
map.put("2","jsp");
map.put("3","oracle");
map.put("4","mysql数据库");
map.put("5","php网站管理");
return map;
}
}
<file_sep>package com.zxf.model.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
import java.util.List;
/*
章对象
*/
public class Chapter {
private Integer id;
private Integer video_id;
private String title;
private Integer ordered;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date create_time;
//章里面包含很多集
private List<Episode> episodeList;
public List<Episode> getEpisodeList() {
return episodeList;
}
public void setEpisodeList(List<Episode> episodeList) {
this.episodeList = episodeList;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getVideo_id() {
return video_id;
}
public void setVideo_id(Integer video_id) {
this.video_id = video_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
}
<file_sep>package com.zxf.spring4;
import com.zxf.spring4.controller.MainController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring4.xml");
MainController m= applicationContext.getBean("mainController", MainController.class);
String info= m.list();
System.out.println(info);
}
}
<file_sep>package com.zxf.interceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zxf.utils.JWTUtils;
import com.zxf.utils.JsonData;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class LoginInterceptor implements HandlerInterceptor {
/*
进入到Controller之前的方法
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
try {
String accesToken = request.getHeader("token");
if (accesToken == null) {
accesToken = request.getParameter("token");
}
if (StringUtils.isNotBlank(accesToken)) {
Claims claims = JWTUtils.chckJWT(accesToken);
if (claims == null) {
//告诉登录过期,重新登录
sendJsonMessage(response, JsonData.buildError("error登录过期,重新登录"));
return false;
}
Integer id = (Integer) claims.get("id");
String name = (String) claims.get("name");
request.setAttribute("user_id", id);
request.setAttribute("name", name);
return true;
}
}catch (Exception e){
e.printStackTrace();
}
sendJsonMessage(response,JsonData.buildError("error登录过期,重新登录"));
return false;
}
/*
响应Json数据给前端
*/
public static void sendJsonMessage(HttpServletResponse response,Object obj){
try {
ObjectMapper objectMapper=new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
PrintWriter writer=response.getWriter();
writer.println(objectMapper.writeValueAsBytes(obj));
writer.close();
response.flushBuffer();
}catch (Exception e){
e.printStackTrace();
}
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.WyOutProject;
import com.zxf.mapper.WyOutProjectMapper;
import com.zxf.service.WyOutProjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 支出项目; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class WyOutProjectServiceImpl extends ServiceImpl<WyOutProjectMapper, WyOutProject> implements WyOutProjectService {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblTodo;
import com.zxf.mapper.TblTodoMapper;
import com.zxf.service.TblTodoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 待办事项; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblTodoServiceImpl extends ServiceImpl<TblTodoMapper, TblTodo> implements TblTodoService {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblVoteDetail;
import com.zxf.mapper.TblVoteDetailMapper;
import com.zxf.service.TblVoteDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 投票数据明细表; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblVoteDetailServiceImpl extends ServiceImpl<TblVoteDetailMapper, TblVoteDetail> implements TblVoteDetailService {
}
<file_sep>package com.zxf.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
/*
自动填充功能的辅助类
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
/*
实现添加操作,自动执行这个方法
*/
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("create_time",new Date(),metaObject);
this.setFieldValByName("update_time",new Date(),metaObject);
/*
给版本号字段添加的时候 自动给添加一个1
然后每次修改的时候都会给该字段+1
这样就保证了乐观锁的执行
*/
this.setFieldValByName("version",1,metaObject);
}
/*
实现修改操作,自动执行这个方法
*/
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("update_time",new Date(),metaObject);
}
}
<file_sep>package com.zxf.test;
import com.zxf.demo6.Customer;
import com.zxf.demo6.SpringConfig6;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig6.class)
public class TestDemo6 {
@Autowired
private Customer customer;
@Test
public void test1(){
customer.save();
}
}
<file_sep>package com.zxf.strategy;
public interface Comparator<T> {
int compare();
}
<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 视频点播; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/tblVod")
public class TblVodController {
}
<file_sep>package com.zxf.utils;
import java.security.MessageDigest;
/*
工具类
*/
public class CommonUtils {
/*
md5
*/
public static String MD5(String data){
try {
java.security.MessageDigest md= MessageDigest.getInstance("MD5");
byte[] array=md.digest(data.getBytes("UTF-8"));
StringBuilder sb=new StringBuilder();
for(byte item:array){
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1,3));
}
return sb.toString().toUpperCase();
}catch (Exception e){
}
return null;
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblDesktop;
import com.zxf.mapper.TblDesktopMapper;
import com.zxf.service.TblDesktopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 桌面; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblDesktopServiceImpl extends ServiceImpl<TblDesktopMapper, TblDesktop> implements TblDesktopService {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblEmailReceive;
import com.zxf.mapper.TblEmailReceiveMapper;
import com.zxf.service.TblEmailReceiveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 邮件接受; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblEmailReceiveServiceImpl extends ServiceImpl<TblEmailReceiveMapper, TblEmailReceive> implements TblEmailReceiveService {
}
<file_sep>package com.zxf.dao;
import com.zxf.pojo.Flower;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.util.List;
public class UserDaoImpl implements IUserDao {
private QueryRunner runner;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public List<Flower> findAllFlower() {
try{
return runner.query("select * from flower",new BeanListHandler<Flower>(Flower.class));
}catch (Exception e){
throw new RuntimeException(e);
}
}
public Flower findFlowerById(Integer id) {
try{
return runner.query("select * from flower where id=?",new BeanHandler<Flower>(Flower.class),id);
}catch (Exception e){
throw new RuntimeException(e);
}
}
public void saveFlower(Flower flower) {
try {
runner.update("insert into flower (name,price,production) values(?,?,?)",flower.getName(),flower.getPrice(),flower.getProduction());
}catch (Exception e){
throw new RuntimeException(e);
}
}
public void updateFlower(Flower flower) {
try {
runner.update("update flower set name=?,price=?,production=? where id=?",flower.getName(),flower.getPrice(),flower.getProduction(),flower.getId());
}catch (Exception e){
throw new RuntimeException(e);
}
}
public void delFlower(Integer id) {
try {
runner.update("delete from flower where id=?",id);
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
<file_sep>package com.zxf.test3;
public class DeliveryClierk2 implements OrderInterface {
private OrderInterface source;
public DeliveryClierk2(OrderInterface source){
this.source=source;
}
@Override
public String order(String foodname) {
String result= source.order(foodname);
System.out.println("已经接受订单,正在前往取餐中。。。");
System.out.println("已经取餐,正在派送。。。");
return result+",已经损坏。。";
}
}
<file_sep>package com.zxf.inters;
import java.lang.reflect.Method;
public interface Interceptors {
public boolean before(Object proxy, Object target, Method method, Object[] args);
public void around(Object proxy, Object target, Method method, Object[] args);
public void after(Object proxy, Object target, Method method, Object[] args);
}
<file_sep>package com.zxf.test;
import com.mysql.jdbc.EscapeTokenizer;
import org.junit.Test;
import javax.swing.text.Style;
import java.security.Permission;
import java.util.*;
public class Test6 {
@Test
public void test1(){
ArrayList<Integer> i1=new ArrayList<Integer>();
i1.add(23);
i1.add(-3);
i1.add(9812);
ArrayList<String> s1=new ArrayList<String>();
ArrayList<Number> s2=new ArrayList<Number>();
s2.add(23);
s1.add("abc");
s1.add("zhang");
printArray(i1);
printArray(s1);
}
public static void printArray(List<?> list){
System.out.println(list);
}
@Test
public void test2(){
ArrayList<String> poker=new ArrayList<String>();
String[] colors={"♠","♥","♣","♦"};
String[] numbers={"2","A","K","Q","J","10","9","8","7","6","5","4","3"};
poker.add("大王");
poker.add("小王");
for(String number:numbers){
for(String color:colors){
// System.out.print(color+number+" ");
poker.add(color+number+" ");
}
}
Collections.shuffle(poker); //随机打乱
System.out.println(poker);
//定义3个玩家
ArrayList<String> p1=new ArrayList<String>();
ArrayList<String> p2=new ArrayList<String>();
ArrayList<String> p3=new ArrayList<String>();
//底牌
ArrayList<String> dipai=new ArrayList<String>();
for(int i=0;i<poker.size();i++){
String p=poker.get(i);
if(i>=51){
dipai.add(p);
}else if(i%3==0){
p1.add(p);
}else if(i%3==1){
p2.add(p);
}else if(i%3==2){
p3.add(p);
}
}
System.out.println("p1:"+p1);
System.out.println("p2:"+p2);
System.out.println("p3:"+p3);
System.out.println("底牌:"+dipai);
}
@Test
public void test3(){
Set<String> s1=new HashSet<String>();
s1.add("zhang");
s1.add("zhang");
s1.add("zhang");
s1.add("aue");
s1.add("feng");
s1.add("java");
s1.add("24bsp");
for(String ss:s1){
System.out.println(ss);
}
System.out.println("(*************");
Iterator<String> iterator=s1.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
@Test
public void test4(){
System.out.println("通话".hashCode());
System.out.println("重地".hashCode());
System.out.println("校长".hashCode());
System.out.println("目录".hashCode());
add(2,345,56,65,76,76,1);
}
public static void add(int ... c){
for(int r:c){
System.out.println(r);
}
}
}
<file_sep>package com.zxf.service;
import com.zxf.domain.Video;
import org.springframework.stereotype.Service;
import java.util.List;
public interface VideoService {
List<Video> listVideo();
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.TblFunctionModel;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 功能模块; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblFunctionModelMapper extends BaseMapper<TblFunctionModel> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.ZhCustomerServiceType;
import com.zxf.mapper.ZhCustomerServiceTypeMapper;
import com.zxf.service.ZhCustomerServiceTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 业主服务类型; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class ZhCustomerServiceTypeServiceImpl extends ServiceImpl<ZhCustomerServiceTypeMapper, ZhCustomerServiceType> implements ZhCustomerServiceTypeService {
}
<file_sep>package com.zxf.conntoller2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController2 {
@ResponseBody
@RequestMapping("/h2")
public String h2(){
return "helloWorld222222!!!!!";
}
}
<file_sep>package com.zxf.service;
import com.zxf.pojo.Users;
public interface UsersService {
public void addUser(Users users);
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.FyPublicBox;
import com.zxf.mapper.FyPublicBoxMapper;
import com.zxf.service.FyPublicBoxService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 公表信息; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class FyPublicBoxServiceImpl extends ServiceImpl<FyPublicBoxMapper, FyPublicBox> implements FyPublicBoxService {
}
<file_sep>package com.zxf;
import com.zxf.ano.service.VideoService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App5 {
public static void main(String[] args) {
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
context.scan("com.zxf");
context.refresh();
VideoService videoService=(VideoService)context.getBean("videoService");
videoService.findById(23);
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblFunctionModel;
import com.zxf.mapper.TblFunctionModelMapper;
import com.zxf.service.TblFunctionModelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 功能模块; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblFunctionModelServiceImpl extends ServiceImpl<TblFunctionModelMapper, TblFunctionModel> implements TblFunctionModelService {
}
<file_sep>package com.zxf.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = {"classpath:emp.properties"})
public class Emp {
@Value("${emp.emp_id}")
private String emp_id;
@Value("${emp.emp_name}")
private String emp_name;
@Override
public String toString() {
return "Emp{" +
"emp_id='" + emp_id + '\'' +
", emp_name='" + emp_name + '\'' +
'}';
}
public String getEmp_id() {
return emp_id;
}
public void setEmp_id(String emp_id) {
this.emp_id = emp_id;
}
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblVoteSubject;
import com.zxf.mapper.TblVoteSubjectMapper;
import com.zxf.service.TblVoteSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 投票题目表; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblVoteSubjectServiceImpl extends ServiceImpl<TblVoteSubjectMapper, TblVoteSubject> implements TblVoteSubjectService {
}
<file_sep>package com.zxf.main;
public class MessageServiceImpl implements MessageService {
@Override
public String getMessage() {
return "Hello!!!!";
}
}
<file_sep>package com.zxf.test;
import com.zxf.pojo.Flower;
import com.zxf.service.FlowerService;
import com.zxf.service.impl.FlowerServiceImpl;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test1 {
@Test
public void test1()throws IOException{
InputStream is=Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
SqlSession session=factory.openSession();
List<Flower> list=session.selectList("a.b.selAll");
for(Flower f:list){
System.out.println(f.getId()+":"+f.getName()+","+f.getProduction()+","+f.getPrice());
}
}
@Test
public void test2(){
FlowerService flowerService=new FlowerServiceImpl();
List<Flower>list=flowerService.getAll();
// Logger logger=Logger.getLogger(Test1.class);
for(Flower f:list){
System.out.println(f.getId()+":"+f.getName()+","+f.getProduction()+","+f.getPrice());
// logger.debug(f.getId()+":"+f.getName()+","+f.getProduction()+","+f.getPrice());
}
}
@Test
public void test3(){
FlowerService flowerService=new FlowerServiceImpl();
int count=flowerService.selById();
// Logger logger=Logger.getLogger(Test1.class);
//logger.debug(count);
System.out.println(count);
}
@Test
public void test4(){
FlowerService flowerService=new FlowerServiceImpl();
Map<Object,Object> map=flowerService.seleMap();
System.out.println(map);
}
@Test
public void test5(){
// Logger logger=Logger.getLogger(Test1.class);
// logger.debug("我是Debug");
// logger.info("我是Info");
FlowerService flowerService=new FlowerServiceImpl();
Flower flower=flowerService.selById2(11);
System.out.println(flower.getProduction());
}
@Test
public void test6(){
Flower flower=new Flower();
flower.setId(8);
FlowerService flowerService=new FlowerServiceImpl();
Flower f=flowerService.selById3(flower);
System.out.println(f.getProduction());
}
@Test
public void test7(){
Map map=new HashMap();
map.put("id",3);
map.put("name","月季");
FlowerService flowerService=new FlowerServiceImpl();
Flower f=flowerService.selById4(map);
System.out.println(f.getProduction());
}
@Test
public void test8(){
FlowerService flowerService=new FlowerServiceImpl();
List<Flower> fs=flowerService.page(3,5);
for(Flower flower:fs){
System.out.println(flower.getName()+","+flower.getProduction());
}
}
@Test
public void test9(){
for(int i=500;i<1500;i++) {
FlowerService flowerService = new FlowerServiceImpl();
Flower flower = new Flower();
flower.setName("你是什么花"+i+"朵");
flower.setPrice(2.7+i);
flower.setProduction("任何地方都有的小野花"+i);
int x= flowerService.insertFlower(flower);
System.out.println(x);
}
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.ZhRentTransfer;
import com.zxf.mapper.ZhRentTransferMapper;
import com.zxf.service.ZhRentTransferService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 租户转兑; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class ZhRentTransferServiceImpl extends ServiceImpl<ZhRentTransferMapper, ZhRentTransfer> implements ZhRentTransferService {
}
<file_sep>package com.zxf;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class Test1 {
Logger logger= LoggerFactory.getLogger(getClass());
@Test
public void test1(){
//由低到高 trace<debug<info<warn<error
/*
spring默认级别是info 默认级别为root级别
logging.level.com.zxf= error 通过配置文件设置改变spring的默认设置级别
这个就只显示了error级别
logging.level.com.zxf=trace
这样就从trace开始显示了所以级别的日志信息。
*/
logger.trace("我是trace");
logger.debug("我是debug");
logger.info("我是info---");
logger.warn("我是warn");
logger.error("我是error");
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblStopDate;
import com.zxf.mapper.TblStopDateMapper;
import com.zxf.service.TblStopDateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 到期日期; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblStopDateServiceImpl extends ServiceImpl<TblStopDateMapper, TblStopDate> implements TblStopDateService {
}
<file_sep>package com.zxf.test;
import com.zxf.mapper.EmployeeMapper;
import com.zxf.pojo.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test1 {
//通过调用配置文件的<select id="findAll" 来查询数据库
@Test
public void test1()throws IOException{
//加载主配置文件
InputStream is= Resources.getResourceAsStream("mybatisConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//通过工厂获取SqlSession
SqlSession session=factory.openSession();
List<Employee> findAll = session.selectList("findAll");
for(Employee e:findAll){
System.out.print(e.getEmp_no()+" ");
System.out.print(e.getEmp_name()+" ");
System.out.print(e.getDept_id()+" ");
System.out.print(e.getEmp_gender()+" ");
System.out.print(e.getEmp_marriage()+" ");
System.out.print(e.getEmp_email()+" ");
System.out.print(e.getEmp_blood()+" ");
System.out.print(e.getEmp_zzmm()+" ");
System.out.print(e.getEmp_nation()+" ");
System.out.println(e.getEmp_state());
}
}
//通过调用Mapper接口的方法findAll 来查询数据库
@Test
public void test2()throws IOException{
//加载主配置文件
InputStream is= Resources.getResourceAsStream("mybatisConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//通过工厂获取SqlSession
SqlSession session=factory.openSession();
EmployeeMapper employeeMapper=session.getMapper(EmployeeMapper.class);
List<Employee> findAll_2 = employeeMapper.findAll();
for(Employee e:findAll_2){
System.out.print(e.getEmp_no()+" ");
System.out.print(e.getEmp_name()+" ");
System.out.print(e.getDept_id()+" ");
System.out.print(e.getEmp_gender()+" ");
System.out.print(e.getEmp_marriage()+" ");
System.out.print(e.getEmp_email()+" ");
System.out.print(e.getEmp_blood()+" ");
System.out.print(e.getEmp_zzmm()+" ");
System.out.print(e.getEmp_nation()+" ");
System.out.println(e.getEmp_state());
}
session.close();
is.close();
}
}
<file_sep>package com.test;
import com.zxf.bean.Animal;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
public class Main3 {
@Test
public void test1(){
ApplicationContext ac=new ClassPathXmlApplicationContext("beans2.xml");
Animal cat = ac.getBean("cat", Animal.class);
cat.sleep();
}
@Test
public void test2(){
ApplicationContext ac=new ClassPathXmlApplicationContext("beans2.xml");
Animal dog=ac.getBean("dog",Animal.class);
dog.sleep();
}
@Test
public void test3(){
ApplicationContext ac=new ClassPathXmlApplicationContext("beans2.xml");
Animal dog=ac.getBean("pig",Animal.class);
dog.sleep();
}
@Test
public void test4(){
ApplicationContext ac=new ClassPathXmlApplicationContext("beans2.xml");
Animal dog=ac.getBean("pig1",Animal.class);
dog.sleep();
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblLoginLog;
import com.zxf.mapper.TblLoginLogMapper;
import com.zxf.service.TblLoginLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 登录日志; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblLoginLogServiceImpl extends ServiceImpl<TblLoginLogMapper, TblLoginLog> implements TblLoginLogService {
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.WyServiceCashierGroup;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 客服收银组; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyServiceCashierGroupMapper extends BaseMapper<WyServiceCashierGroup> {
}
<file_sep>package com.zxf.springcloud.service;
import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.concurrent.TimeUnit;
@Service
public class PaymentService {
/*
降级
*/
public String paymentInfo_ok(Integer id) {
return "线程池:"+Thread.currentThread().getName()+" paymentInfo_ok,id: "+id+"\t"+"***";
}
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
})
//出现问题了;用paymentInfo_TimeOutHandler方法来处理
//timeoutInMilliseconds 正常是3秒的等待;但是我们做了5秒,所有还有超时的问题。
public String paymentInfo_TimeOut(Integer id) {
int timeNumber=10;
//int age=10/0;
try{
TimeUnit.SECONDS.sleep(timeNumber);
}catch (Exception e){
e.printStackTrace();
}
return "线程池:"+Thread.currentThread().getName()+" paymentInfo_TimeOut,********id:"+id+"\t"+"***耗时"+timeNumber+"秒";
}
public String paymentInfo_TimeOutHandler(Integer id){
return "线程池:"+Thread.currentThread().getName()+" paymentInfo_TimeOutHandler排队人数较多,或出现了错误。----->,id:"+id+"\t";
}
/*
熔断
*/
@HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开短路器
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //请求次数
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后跳闸
})
public String paymentCircuitBreaker(@PathVariable("id") Integer id){
if(id<0){
throw new RuntimeException("******id 不能为负数");
}
String serialNumber= IdUtil.simpleUUID();
return Thread.currentThread().getName()+"\t"+"调用成功,流水号:"+serialNumber;
}
public String paymentCircuitBreaker_fallback (@PathVariable("id") Integer id){
return "id 不能负数,请稍后在玩!!!"+id;
}
}<file_sep>package com.zxf.mapper;
import com.zxf.bean.WyVisitManage;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 来访管理; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyVisitManageMapper extends BaseMapper<WyVisitManage> {
}
<file_sep>package com.zxf.test1;
import org.springframework.beans.factory.annotation.Qualifier;
@Qualifier("b")
public class WhiteCat implements Cat {
@Override
public String getName() {
return "白猫";
}
}
<file_sep>package com.zxf.bean5;
import org.springframework.stereotype.Component;
@Component //注解方式定义的bean标签
public class Teacher implements Person {
public void eat() {
System.out.println("老师吃饭");
}
}
<file_sep>package com.zxf.bean5;
import org.springframework.stereotype.Component;
@Component //注解方式定义的bean标签
public class Student implements Person {
public void eat() {
System.out.println("学生吃饭");
}
}
<file_sep>package com.zxf.controller;
import com.zxf.domain.City;
import com.zxf.service.CityService2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("city2")
public class MyController2 {
@Autowired
CityService2 cityService2;
@RequestMapping("list2")
public String list(Model map){
List<City> all = cityService2.findAll();
map.addAttribute("list",all);
return "list";
}
@RequestMapping("list2_one/{id}")
public String getOne(@PathVariable("id")Integer id,Model model){
City city=cityService2.findOne(id);
System.out.println(city.getName());
model.addAttribute("city",model);
return "one";
}
}<file_sep>package com.zxf.service;
import com.zxf.model.entity.VideoOrder;
import java.util.List;
public interface VideoOrderService {
public int save(int userId,int videoId);
public List<VideoOrder> listOrderByUserId(Integer userId);
}
<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 票据管理; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/wyNoteManage")
public class WyNoteManageController {
}
<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 数据库还原; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/tblDbrecovery")
public class TblDbrecoveryController {
}
<file_sep>package com.zxf.demo;
public class Demo2 {
public void f(){
System.out.println("f()");
}
}
<file_sep>package com.zxf.dao;
import com.zxf.domain.City;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class CityDao {
public List<City> findAll(){
List<City> cities=new ArrayList<>();
cities.add(new City(1,"zhang"));
cities.add(new City(2,"li"));
cities.add(new City(3,"zhao"));
cities.add(new City(4,"yang"));
cities.add(new City(5,"吗"));
cities.add(new City(6,"插卡"));
cities.add(new City(7,"显卡"));
cities.add(new City(8,"我现在"));
return cities;
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.WyCleanPlan;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 清洁安排; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyCleanPlanMapper extends BaseMapper<WyCleanPlan> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblVoteProject1;
import com.zxf.mapper.TblVoteProject1Mapper;
import com.zxf.service.TblVoteProject1Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 投票项目表; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblVoteProject1ServiceImpl extends ServiceImpl<TblVoteProject1Mapper, TblVoteProject1> implements TblVoteProject1Service {
}
<file_sep>package com.zxf.demo3;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
@Component(value = "p")
public class Person {
@Value("张三")
private String panme;
@Override
public String toString() {
return "Person{" +
"panme='" + panme + '\'' +
'}';
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.WyCommunityEvent;
import com.zxf.mapper.WyCommunityEventMapper;
import com.zxf.service.WyCommunityEventService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 社区活动; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class WyCommunityEventServiceImpl extends ServiceImpl<WyCommunityEventMapper, WyCommunityEvent> implements WyCommunityEventService {
}
<file_sep>package com.zxf.test;
import com.zxf.mapper.EmployeeMapper;
import com.zxf.pojo.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test2 {
private InputStream inputStream=null;
private SqlSession session=null;
private EmployeeMapper mapper=null;
@Before //Test方法之前执行,都是junit提供的方法
public void init()throws IOException{
//加载主配置文件
inputStream= Resources.getResourceAsStream("mybatisConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂获取SqlSession
session=factory.openSession();
mapper = session.getMapper(EmployeeMapper.class);
}
@After//Test方法之后执行,都是junit提供的方法
public void destory()throws IOException{
session.close();
inputStream.close();
}
@Test
//测试public Employee findEmpByid(String emp_no);
public void test1()throws IOException{
//加载主配置文件
Employee e = mapper.findEmpByid("HW9802");
System.out.print(e.getEmp_no()+" ");
System.out.print(e.getEmp_name()+" ");
System.out.print(e.getDept_id()+" ");
System.out.print(e.getEmp_gender()+" ");
System.out.print(e.getEmp_marriage()+" ");
System.out.print(e.getEmp_email()+" ");
System.out.print(e.getEmp_blood()+" ");
System.out.print(e.getEmp_zzmm()+" ");
System.out.print(e.getEmp_nation()+" ");
System.out.println(e.getEmp_state());
}
//测试 public int saveEmp(Employee employee);
@Test
public void test2()throws IOException{
Employee employee=new Employee();
employee.setEmp_no("test04");
employee.setEmp_name("张兰");
employee.setDept_id("100");
employee.setEmp_gender("男");
employee.setEmp_email("<EMAIL>");
employee.setEmp_nation("民族");
employee.setEmp_marriage("没结婚");
employee.setEmp_health("不咋样");
employee.setEmp_zzmm("老百姓");
employee.setEmp_blood("熊猫血");
employee.setEmp_state("去世了");
int i= mapper.saveEmp(employee);
session.commit(); //提交事务
System.out.println(employee.getEmp_no());
}
//测试 public int updateEmp(Employee employee);
@Test
public void test3(){
Employee employee=new Employee();
employee.setEmp_no("test04");
employee.setEmp_name("张兰1");
employee.setDept_id("a00");
employee.setEmp_gender("男1");
employee.setEmp_email("<EMAIL>");
employee.setEmp_nation("民族1");
employee.setEmp_marriage("没结婚1");
employee.setEmp_health("不咋样1");
employee.setEmp_zzmm("老百姓1");
employee.setEmp_blood("熊猫血1");
employee.setEmp_state("去世了1");
int i=mapper.updateEmp(employee);
session.commit();
}
//测试 public void delEmp(String emp_no);
@Test
public void test4(){
mapper.delEmp("test03");
session.commit();
}
//测试 public List<Employee>findEmpByname(String emp_name);
//这里要注意mapper接口中配置文件是否要求我们这里写%通配符
/*
findEmpByname("%张%"); 如果mapper接口配置文件用的是like #{emp_name} 需要加入通配符
findEmpByname("张"); 如果mapper接口配置文件用的是like '%${value}%' 不需要加入通配符
*/
@Test
public void test5(){
List<Employee> employees = mapper.findEmpByname("张");
for (Employee e:employees){
System.out.println(e.getEmp_name());
}
}
//测试 public int getCount();
@Test
public void test6(){
int employees = mapper.getCount();
System.out.println(employees);
}
}<file_sep>package com.zxf.bean;
/*
yml属性文件的属性值映射到这个组件中
*/
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
@PropertySource(value = {"classpath:p1.properties"})
//@ConfigurationProperties(prefix = "person")//它必须读取全局配置文件,不能读取自(定义文件名)的配置文件。
/*
还可以使用另外一种方式给属性赋值和设置值
@Value
*/
public class Person {
@Value("${person.last-name}") //依然读取属性文件的配置
private String lastName;
@Value("#{11-2}") //当前位置设置值,优先级高于配置文件 #{SpEL}表达式支持
private Integer age;
@Value("#{22==1}")
private Boolean boss;
private Date birth;
private String address;
//由于maps是复杂数据类型,使用@Value不支持读取属性文件的该值属性。
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
@Override
public String toString() {
return "Person{" +
"lastName='" + lastName + '\'' +
", age=" + age +
", boss=" + boss +
", birth=" + birth +
", address='" + address + '\'' +
", maps=" + maps +
", lists=" + lists +
", dog=" + dog +
'}';
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getBoss() {
return boss;
}
public void setBoss(Boolean boss) {
this.boss = boss;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
}
<file_sep>package com.zxf.test;
import com.zxf.demo2.Car;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestDomo2 {
@Test
public void test1(){
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Car car = ac.getBean("c",Car.class);
double d1=car.getMoney();
System.out.println(d1+234);
System.out.println(car);
}
}
<file_sep>artifactId=family_service_platform
groupId=com.zxf
version=0.0.1-SNAPSHOT
<file_sep>package com.zxf.service;
import com.zxf.bean.TblUserDept;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 用户部门表; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblUserDeptService extends IService<TblUserDept> {
}
<file_sep>package com.zxf.mapper;
import com.zxf.domain.User;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Repository
public class UserMapper {
private static Map<String , User>userMap=new HashMap<>();
static {
userMap.put("zhang",new User(1,"zhang","123"));
userMap.put("xdclass-lw",new User(2,"xdclass-lw","123456"));
userMap.put("zxf",new User(3,"zxf","abc"));
userMap.put("xf",new User(4,"xf","qwer"));
userMap.put("zhang613",new User(5,"zhang613","asdf"));
userMap.put("z_613",new User(6,"z_613","qazxsw"));
userMap.put("zxf_1981",new User(7,"zxf_1981","typeucdos_"));
}
public User login(String username,String pwd){
User user=userMap.get(username);
if(user==null){
return null;
}
if(user.getPwd().equals(pwd)){
return user;
}
return null;
}
public List<User> litUser(){
List<User> list=new ArrayList<>();
list.addAll(userMap.values());
return list;
}
}
<file_sep>package com.zxf;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.jupiter.api.Test;
public class TestGenerator {
// @Test
public void testGenerator(){
AutoGenerator autoGenerator=new AutoGenerator();
//全局配置
GlobalConfig globalConfig=new GlobalConfig();
globalConfig.setAuthor("zxf").setOutputDir("H:\\IDEA_work_2020\\family_service_platform\\src\\main\\java")
.setFileOverride(true)
.setIdType(IdType.AUTO)
.setServiceName("%sService")
.setBaseResultMap(true)
.setBaseColumnList(true)
.setControllerName("%sController");
//配置数据源
DataSourceConfig dataSourceConfig=new DataSourceConfig();
dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver").setUrl("jdbc:mysql://192.168.0.89:3306/family_service_platform")
.setUsername("root")
.setPassword("<PASSWORD>");
//策略配置
StrategyConfig strategyConfig=new StrategyConfig();
strategyConfig.setCapitalMode(true)//设置全局大写命名
.setNaming(NamingStrategy.underline_to_camel)//数据库表映射到实体的命名策略
.setInclude();
//包名配置
PackageConfig packageConfig=new PackageConfig();
packageConfig.setParent("com.zxf").setMapper("mapper")
.setService("service").setController("controller")
.setEntity("bean").setXml("mapper");
autoGenerator.setGlobalConfig(globalConfig)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(packageConfig);
autoGenerator.execute();
}
@Test
public void test2(){
}
}
<file_sep>package com.zxf.service;
import com.zxf.bean.WyServiceCashierGroup;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 客服收银组; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyServiceCashierGroupService extends IService<WyServiceCashierGroup> {
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.TblUserDept;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 用户部门表; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblUserDeptMapper extends BaseMapper<TblUserDept> {
}
<file_sep>package com.zxf.bean2;
import org.springframework.stereotype.Component;
@Component
public class Student implements Person {
public void eat() {
System.out.println("学生吃");
}
}
<file_sep>package com.zxf.test2;
public interface Human {
public void eat();
}
<file_sep>package com.zxf.main;
public class Main6_Sleep_Yield_join {
public static void main(String[] args) {
//testSleep();
testYield();
}
static void testSleep(){
new Thread(()->{
for (int i=1;i<100;i++){
System.out.println("A:"+i);
try{
Thread.sleep(500);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
static void testYield(){
new Thread(()->{
for (int i=1;i<=100;i++){
System.out.println("A:"+i);
if(i%7==0){
Thread.yield();
}
}
}).start();
new Thread(()->{
for(int i=1;i<=100;i++){
System.out.println("B............:"+i);
if(i%7==0){
Thread.yield();
System.out.println("b:yield");
}
}
}).start();
}
}
<file_sep>alert("aaabbbccc");<file_sep>package com.zxf.main;
import java.util.ArrayList;
class User{
private String name; //姓名
private int money; //余额,也就是当前用户拥有的钱数。
public User(){}
public User(String name, int money) {
this.name = name;
this.money = money;
}
//展示一下当前用户有多少钱。
public void show(){
System.out.println("我是:"+name+"-->余额:"+money);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
public class Main1 {
public static void main(String[] args){
Manager manager=new Manager("群主",800);
Member member1=new Member("成员A",0);
Member member2=new Member("成员B",0);
Member member3=new Member("成员C",0);
Member member4=new Member("成员D",0);
Member member5=new Member("成员E",0);
Member member6=new Member("成员F",0);
Member member7=new Member("成员G",0);
manager.show();
member1.show();
member2.show();
member3.show();
member4.show();
member5.show();
member6.show();
member7.show();
System.out.println("========================================");
//把10元钱分成了7份。
ArrayList<Integer> redList=manager.send(96,7);
member1.receive(redList);
member2.receive(redList);
member3.receive(redList);
member4.receive(redList);
member5.receive(redList);
member6.receive(redList);
member7.receive(redList);
manager.show();
member1.show();
member2.show();
member3.show();
member4.show();
member5.show();
member6.show();
member7.show();
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblMessageSend;
import com.zxf.mapper.TblMessageSendMapper;
import com.zxf.service.TblMessageSendService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 信息发送; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblMessageSendServiceImpl extends ServiceImpl<TblMessageSendMapper, TblMessageSend> implements TblMessageSendService {
}
<file_sep>package com.zxf.dao;
import com.zxf.pojo.MyIp;
import java.util.List;
public interface MyIpDao {
public List<MyIp> getAll();
}
<file_sep>package com.zxf.test;
import org.junit.Test;
public class TestMain {
public static int i=1; //-19053 -20293
@Test
public void test1(){
Long l1=System.currentTimeMillis();
for(int i=0;i<1000000000;i++){
m();
n();
}
System.out.println(l1-System.currentTimeMillis());
}
public synchronized void m(){i=1;}
public void n(){i=1;
}
}
<file_sep>package com.zxf.proxy;
public class PayServiceImpl implements PayService {
public String callback(String outTradeNo) {
System.out.println("目标类PayServiceImpl...callback()方法");
return outTradeNo;
}
public int save(int userId, int productId) {
System.out.println("目标类PayServiceImpl...save()方法");
return productId;
}
}
<file_sep>package com.test1;
import com.zxf.mapper.DeptMapper;
import com.zxf.mapper.EmployeeMapper;
import com.zxf.pojo.Dept;
import com.zxf.pojo.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test_dept {
/*
测试部门对员工 一对多
*/
@Test
public void test1()throws IOException{
InputStream is= Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
SqlSession session=factory.openSession();
DeptMapper mapper = session.getMapper(DeptMapper.class);
List<Dept> depts = mapper.getall_dept_allemp();
for(Dept d:depts){
System.out.print("《"+d.getDept_name()+"》");
List<Employee> employees = d.getEmployees();
for(Employee e:employees){
System.out.println(e.getEmp_name());
}
}
}
/*
测试部门对员工 一对多 使用延迟加载技术
*/
@Test
public void test2()throws IOException{
InputStream is= Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
SqlSession session=factory.openSession();
DeptMapper mapper = session.getMapper(DeptMapper.class);
List<Dept> depts = mapper.getall_dept_allemp2();
for(Dept d:depts){
System.out.print("《"+d.getDept_name()+"》");
//如果不执行下面的查询,则只执行一条SQL语句,实现了延迟加载。
List<Employee> employees = d.getEmployees();
for(Employee e:employees){
System.out.println(e.getEmp_name());
}
}
}
}
<file_sep>spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML5
spring.thymeleaf.charset=UTF-8
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 待办事项; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/tblTodo")
public class TblTodoController {
}
<file_sep>package com.zxf.pojo;
import java.io.Serializable;
public class Dept implements Serializable {
private String dept_name;
private String dept_desc;
public String getDept_name() {
return dept_name;
}
public void setDept_name(String dept_name) {
this.dept_name = dept_name;
}
public String getDept_desc() {
return dept_desc;
}
public void setDept_desc(String dept_desc) {
this.dept_desc = dept_desc;
}
}
<file_sep>package com.zxf.web.action;
import com.zxf.pojo.PageInfo;
import com.zxf.service.FlowerService;
import com.zxf.service.impl.FlowerServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/page")
public class ShowPageServlet extends HttpServlet {
private FlowerService flowerService=new FlowerServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//第一次访问的验证,如果没有传递参数,设置默认值
String pageSizeStr=request.getParameter("pageSize");
int pageSize=15;
if(pageSizeStr!=null && pageSizeStr.equals("")){
pageSize=Integer.parseInt(pageSizeStr);
}
String pageNumberStr=request.getParameter("pageNumber");
int pageNumber=1;
if(pageNumberStr!=null&&!pageNumberStr.equals("")){
pageNumber = Integer.parseInt(pageNumberStr);
}
PageInfo pi = flowerService.showPage(pageSize, pageNumber);
request.setAttribute("PageInfo",pi);
request.getRequestDispatcher("jsp/show2.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
<file_sep>spring.messages.basename=i18n/login
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zxf</groupId>
<artifactId>Spring_mvc1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!--对依赖的坐标的版本做集中管理-->
<properties>
<jstl.version>1.2</jstl.version>
<servlet.version>3.1.0</servlet.version>
<jsp.version>2.0</jsp.version>
<spring.version>5.0.2.RELEASE</spring.version>
</properties>
<dependencies>
<!--jsp&servlet-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.17.1-GA</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.17.1-GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
</dependencies>
</project><file_sep>package com.zxf.utils;
import com.zxf.model.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
/*
jwt工具
*/
public class JWTUtils {
private static final long EXEPIRE=6000*60*24*7; //过期时间一周
// private static final long EXEPIRE=1;
private static final String SECRET="<KEY>";//加密的秘钥
private static final String TOKEN_PREFIX="zxf";//令牌前缀
private static final String SUBJECT="zhangxf";//主题
/*
根据用户信息,生成令牌
*/
public static String geneJsonWebToken(User user){
String token=Jwts.builder().
setSubject(SUBJECT).
claim("head_img",user.getHead_img()).
claim("id",user.getId()).
claim("name",user.getName()).
setIssuedAt(new Date()).
setExpiration(new Date(System.currentTimeMillis()+EXEPIRE)).
signWith(SignatureAlgorithm.HS256,SECRET).compact();
token=TOKEN_PREFIX+token;
return token;
}
/*
校验token
*/
public static Claims chckJWT(String token){
try{
final Claims claims=Jwts.parser().setSigningKey(SECRET).
parseClaimsJws(token.replace(TOKEN_PREFIX,"")).
getBody();
return claims;
}catch (Exception e){
return null;
}
}
}
<file_sep>package com.zxf.service;
import com.zxf.bean.ZhCustomerService;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 业主服务; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface ZhCustomerServiceService extends IService<ZhCustomerService> {
}
<file_sep>package com.zxf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@RestController
//配置支持跨域请求。。
//@CrossOrigin(origins = "*",allowedHeaders = "*",methods = {},allowCredentials = "true")
public class TestController {
@RequestMapping("/auth/login1")
public String hello(){
System.out.println("!***************************!");
return "";
}
}
<file_sep>package com.zxf.test3;
public class TicketRunnable implements Runnable {
private int ticket=5;
@Override
public void run() {
while (ticket>0){
try{
Thread.sleep(9);
}catch (Exception e){
e.printStackTrace();
}
synchronized (this){
if(ticket>0){
System.out.println(Thread.currentThread().getName()+"正在出售第:"+((5-ticket)+1)+"张票");
ticket--;
}
}
}
}
public static void main(String[] args) {
TicketRunnable ticketRunnable=new TicketRunnable();
new Thread(ticketRunnable).start();
new Thread(ticketRunnable).start();
new Thread(ticketRunnable).start();
new Thread(ticketRunnable).start();
}
}
<file_sep>package com.zxf.singleton;
public class Mgr01 {
private static final Mgr01 INSTANCE=new Mgr01();
private Mgr01(){}
public static Mgr01 getInstance(){
return INSTANCE;
}
}
<file_sep>package com.zxf.service;
import com.zxf.bean.WyCarManage;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 车辆管理; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyCarManageService extends IService<WyCarManage> {
}
<file_sep>package com.zxf.dao.impl;
import com.zxf.dao.MyIpDao;
import com.zxf.pojo.MyIp;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class MyIpDaoImpl implements MyIpDao {
private DataSource datasource;
public void setDatasource(DataSource datasource) {
this.datasource = datasource;
}
public List<MyIp> getAll() {
Connection conn=null;
PreparedStatement pstm=null;
ResultSet rs=null;
List<MyIp> list=new ArrayList<MyIp>();
try{
conn=datasource.getConnection();
pstm=conn.prepareStatement("select * from myip");
rs=pstm.executeQuery();
while (rs.next()){
MyIp myIp=new MyIp();
myIp.setId(rs.getInt("id"));
myIp.setIp_address(rs.getString("ip_address"));
myIp.setIp_date(rs.getTimestamp("ip_date"));
list.add(myIp);
}
}catch (Exception e){
e.getMessage();
}
return list;
}
}
<file_sep>package com.zxf.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zxf.pojo.Users1;
import org.springframework.stereotype.Repository;
@Repository
public interface Users1Mapper extends BaseMapper<Users1> {
}
<file_sep>package com.zxf.service;
import com.zxf.bean.WyCleanCheck;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 清洁检查; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyCleanCheckService extends IService<WyCleanCheck> {
}
<file_sep>package com.zxf.service;
import com.zxf.mapper.EmployeeMapper;
import com.zxf.pojo.Employee;
import com.zxf.pojo.Job;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
public class Test1 {
private SqlSessionFactory sqlSessionFactory;
private SqlSession session;
private InputStream is;
private EmployeeMapper employeeMapper;
@Before //用于测试方法之前执行。
public void init() throws Exception{
is= Resources.getResourceAsStream("zhangMyBatis.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
session=sqlSessionFactory.openSession();
employeeMapper=session.getMapper(EmployeeMapper.class);
}
@After //用于测试方法之后执行。
public void destory()throws Exception{
session.commit();
session.close();
is.close();
}
@Test
public void test1(){
Employee employee = employeeMapper.selectEmployeeById("HW9804");
System.out.println(employee.getEmp_name());
List<Job> jobs = employee.getJobs();
for(Job j:jobs){
System.out.println(j.getJob_name());
}
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.FyReceiptMain;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 收款单主单; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface FyReceiptMainMapper extends BaseMapper<FyReceiptMain> {
}
<file_sep>package com.zxf.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestPerson {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring1.xml");
Person person = (Person)applicationContext.getBean("person");
System.out.println(person.getName()+":"+person.getId());
System.out.println(person.getFood().getFname()+":-->"+person.getFood().getFid());
System.out.println(person.getGift().get("url"));
System.out.println(person.getList());
System.out.println(person.getSet());
System.out.println(person.getMap());
}
}<file_sep>package com.zxf.commonutils;
public interface ResultCode {
public static Integer UCCESS=20000; //成功
public static Integer ERROR=20001; //失败
}
<file_sep>package com.zxf.abstractfactory;
public abstract class Vehicle { //移动设备 交通工具
abstract void go(); //可以走,移动。
}
<file_sep>package com.zxf.service;
import com.zxf.bean.ZhRentInformation;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 租户信息; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface ZhRentInformationService extends IService<ZhRentInformation> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.WyCleanCheck;
import com.zxf.mapper.WyCleanCheckMapper;
import com.zxf.service.WyCleanCheckService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 清洁检查; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class WyCleanCheckServiceImpl extends ServiceImpl<WyCleanCheckMapper, WyCleanCheck> implements WyCleanCheckService {
}
<file_sep>package com.zxf.mapper;
import com.zxf.pojo.Dept;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface DeptMapper {
//插入部门
public void saveDept(Dept dept);
//查询部门
public List<Dept> getAlldept();
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.WyEstateIncomeProject;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 楼盘经费收入项目; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyEstateIncomeProjectMapper extends BaseMapper<WyEstateIncomeProject> {
}
<file_sep>package com.zxf.proxy;
public class ProxyTest {
public static void main(String[] args) {
/*
PayService payService=new PayServiceImpl();
payService.callback("abc123");
*/
//静态代理
/*
PayService payService1=new StaticProxyPayServiceImpl(new PayServiceImpl());
payService1.save(23,12);
payService1.callback("abc");
*/
//JDK代理
/*
JdkProxy jdkProxy=new JdkProxy();
//获取代理对象
PayService payService=(PayService)jdkProxy.newProxyInstance(new PayServiceImpl());
//调用目标方法
payService.callback("abc");
payService.save(23,11);
*/
//Cglib代理
CglibProxy cglibProxy=new CglibProxy();
PayService pc=(PayService)cglibProxy.newProxyInstance(new PayServiceImpl());
//调用目标方法
pc.save(23,2);
pc.callback("aaa");
}
}
<file_sep>package com.zxf.test3;
public class Customer implements OrderInterface{
@Override
public String order(String foodname){
return "已经下单了"+foodname;
}
/*
我增加了东西
要不在写点什么吧。。。。。?
*/
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblPositionRecord;
import com.zxf.mapper.TblPositionRecordMapper;
import com.zxf.service.TblPositionRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 职位档案; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblPositionRecordServiceImpl extends ServiceImpl<TblPositionRecordMapper, TblPositionRecord> implements TblPositionRecordService {
}
<file_sep>package com.zxf.service;
import com.zxf.bean.ZhRentContractCell;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 租赁合同房间; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface ZhRentContractCellService extends IService<ZhRentContractCell> {
}
<file_sep>package com.zxf.mapper;
import com.zxf.pojo.Teacher;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface TeacherMapper {
@Select("select * from teacher")
public List<Teacher> selAll();
}
<file_sep>package com.zxf.springcloud.controller;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zxf.springcloud.service.PaymentHystrixService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")//用了类似全局的降级方案
public class OrderHystrixController {
@Resource
private PaymentHystrixService paymentHystrixService;
@GetMapping("/consumer/payment/hystrix/ok/{id}")
public String paymentInfo_Ok(@PathVariable("id") Integer id){
String result=paymentHystrixService.paymentInfo_ok(id);
return result;
}
@GetMapping("/consumer/payment/hystrix/timeout/{id}")
// @HystrixCommand(fallbackMethod = "paymentTimeOutFallbackMethod",commandProperties = {
// @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")
//})
@HystrixCommand//用这个注解表示用默认的降级方法。不用指定
public String paymentInfo_TimeOut(@PathVariable("id") Integer id){
String result=paymentHystrixService.paymentInfo_TimeOut(id);
return result;
}
public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id){
System.out.println("********");
return "我是消费者80,对方支付系统繁忙请10秒后在试试运行看看!!!";
}
//全局的fallback
public String payment_Global_FallbackMethod(){
return "我是80端全局的降级处理....";
}
}<file_sep>package com.zxf.domain;
import java.util.Date;
import java.util.List;
public class User {
private Integer id;
private String name;
private String pwd;
private String head_img;
private String phone;
private Date create_time;
/////////////////////////////
private List<VideoOrder> videoOrderList;
public List<VideoOrder> getVideoOrderList() {
return videoOrderList;
}
public void setVideoOrderList(List<VideoOrder> videoOrderList) {
this.videoOrderList = videoOrderList;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getHead_img() {
return head_img;
}
public void setHead_img(String head_img) {
this.head_img = head_img;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
", head_img='" + head_img + '\'' +
", phone='" + phone + '\'' +
", create_time=" + create_time +
", videoOrderList=" + videoOrderList +
'}';
}
}
<file_sep>jdbc.jdbcUrl=jdbc:mysql://192.168.0.148:3306/test
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=<PASSWORD><file_sep>package com.zxf.test3;
public interface OrderInterface {
public String order(String foodname);
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.WyEstateIncomeDetail;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 楼盘经费收入明细; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyEstateIncomeDetailMapper extends BaseMapper<WyEstateIncomeDetail> {
}
<file_sep>package com.zxf.test;
import com.zxf.mapper.EmployeeMapper;
import com.zxf.pojo.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.InputStream;
/*
测试Mybatis中的一级缓存
*/
public class Test5 {
@Test
public void test1()throws Exception{
//加载主配置文件
InputStream is= Resources.getResourceAsStream("mybatisConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//通过工厂获取SqlSession
SqlSession session=factory.openSession();
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
//第一次查询HW9801
Employee employee1=mapper.findEmpByid("HW9801");
System.out.println(employee1);
System.out.println("**********************************");
Employee employee2=mapper.findEmpByid("HW9802");
//第二次查询HW9801
// session.commit(); //提交后 ,会清空缓存。(insert update delete)等操作也会清空缓存。
Employee employee3=mapper.findEmpByid("HW9801");
System.out.println(employee2);
System.out.println(employee3);
//通过二次查询相同的信息,所以这个时候用的是Mybatis自己带的一级缓存机制(SqlSession机制)
session.close();
is.close();
}
}
<file_sep>package com.zxf.controller;
import com.zxf.domain.User;
import com.zxf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@RestController
@RequestMapping("api/v1/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("save")
public Object save(){
User user=new User();
user.setName("zhang3");
user.setPwd("<PASSWORD>");
user.setCreate_time(new Date());
user.setPhone("1789238734");
user.setHead_img("aabbddd.jpg");
userService.save(user);
return user;
}
}
<file_sep>package com.zxf.service;
import com.zxf.bean.WyEstateOutDetail;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 楼盘经费支出明细; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyEstateOutDetailService extends IService<WyEstateOutDetail> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.WyEstateMoney;
import com.zxf.mapper.WyEstateMoneyMapper;
import com.zxf.service.WyEstateMoneyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 楼盘费用; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class WyEstateMoneyServiceImpl extends ServiceImpl<WyEstateMoneyMapper, WyEstateMoney> implements WyEstateMoneyService {
}
<file_sep>package com.zxf.abstractfactory;
public abstract class Weapon { //武器
abstract void shoot();//可以打
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblCommonLanguage;
import com.zxf.mapper.TblCommonLanguageMapper;
import com.zxf.service.TblCommonLanguageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 常用语; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblCommonLanguageServiceImpl extends ServiceImpl<TblCommonLanguageMapper, TblCommonLanguage> implements TblCommonLanguageService {
}
<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 员工通讯录; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/tblEmployeeContact")
public class TblEmployeeContactController {
}
<file_sep>jdbc.jdbcUrl=jdbc:mysql://192.168.0.148:3306/test
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=<PASSWORD><file_sep>package com.zxf.service.impl;
import com.zxf.bean.WyEstateOutDetailSub;
import com.zxf.mapper.WyEstateOutDetailSubMapper;
import com.zxf.service.WyEstateOutDetailSubService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 楼盘经费支出明细_审批子表; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class WyEstateOutDetailSubServiceImpl extends ServiceImpl<WyEstateOutDetailSubMapper, WyEstateOutDetailSub> implements WyEstateOutDetailSubService {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblShortcutIcon;
import com.zxf.mapper.TblShortcutIconMapper;
import com.zxf.service.TblShortcutIconService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 快捷方式图标; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblShortcutIconServiceImpl extends ServiceImpl<TblShortcutIconMapper, TblShortcutIcon> implements TblShortcutIconService {
}
<file_sep>package com.zxf;
import com.zxf.domain.Video;
import com.zxf.service.VideoService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Aop1 {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("aop1.xml");
testAop(context);
}
private static void testAop(ApplicationContext context){
VideoService videoService=(VideoService)context.getBean("videoService");
videoService.save(new Video());
videoService.findById(23);
}
}
<file_sep>package com.zxf.strategy;
public class Cat implements Comparable<Cat> {
int weight,height;
public Cat(int weight,int height){
this.weight=weight;
this.height=height;
}
@Override
public int compareTo(Cat o) {
if(this.weight<o.weight) return -1;
else if (this.weight==o.weight) return 0;
else return 0;
}
@Override
public String toString() {
return "Cat{" +
"weight=" + weight +
", height=" + height +
'}';
}
}
<file_sep>package com.zxf.service;
import com.zxf.bean.WyOutDetail;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 支出明细; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyOutDetailService extends IService<WyOutDetail> {
}
<file_sep>package com.zxf.web.test;
import com.zxf.web.pojo.Flower;
import com.zxf.web.service.impl.FlowerServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class Test1 {
@Test
public void test1(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
FlowerServiceImpl flowerService=ac.getBean("flowerSerivce",FlowerServiceImpl.class);
List<Flower> show = flowerService.show();
for(Flower f:show){
System.out.println(f.getProduction());
}
}
}
<file_sep>package com.zxf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class MyController4 {
@RequestMapping(value = "/ok4/{id}",method = RequestMethod.GET)
public String ok4_get(@PathVariable("id")Integer id){
System.out.println("get请求:"+id);
return "ok1";
}
@RequestMapping(value = "/ok4",method = RequestMethod.POST)
public String ok4_post(){
System.out.println("post请求:");
return "ok1";
}
@RequestMapping(value = "/ok4",method = RequestMethod.PUT)
public String ok4_put(){
System.out.println("put请求...:");
return "ok1";
}
@RequestMapping(value = "/ok4",method = RequestMethod.DELETE)
public String ok4_del(){
System.out.println("del请求...:");
return "ok1";
}
}
<file_sep>package com.zxf.singleton;
public class Mgr03 {
private static Mgr03 INSTANCE;
private Mgr03(){}
public static synchronized Mgr03 getInstance(){
if(INSTANCE==null){
try{
Thread.sleep(1);
}catch (Exception e){}
INSTANCE=new Mgr03();
}
return INSTANCE;
}
}
<file_sep>package com.zxf;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class JdbcApp {
public static void main(String[] args) throws Exception{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/online";
String username = "root";
String password = "<PASSWORD>";
Connection connection= DriverManager.getConnection(url,username,password);
PreparedStatement pstm=connection.prepareStatement("select * from video");
ResultSet rs=pstm.executeQuery();
while (rs.next()){
System.out.print(rs.getString("id"));
System.out.print(rs.getString("title"));
System.out.println(rs.getString("summary"));
}
rs.close();
pstm.close();
connection.close();
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.ZhRentShare;
import com.zxf.mapper.ZhRentShareMapper;
import com.zxf.service.ZhRentShareService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 租赁分租信息; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class ZhRentShareServiceImpl extends ServiceImpl<ZhRentShareMapper, ZhRentShare> implements ZhRentShareService {
}
<file_sep>package com.zxf.model.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/*
集对象
*/
public class Episode {
private Integer id;
private String title;
private Integer num;
private Integer ordered;
private String play_url;
private Integer chapter_id;
private Integer video_id;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date create_time;
private Integer free;
@Override
public String toString() {
return "Episode{" +
"id=" + id +
", title='" + title + '\'' +
", num=" + num +
", ordered=" + ordered +
", play_url='" + play_url + '\'' +
", chapter_id=" + chapter_id +
", video_id=" + video_id +
", create_time=" + create_time +
", free=" + free +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public String getPlay_url() {
return play_url;
}
public void setPlay_url(String play_url) {
this.play_url = play_url;
}
public Integer getChapter_id() {
return chapter_id;
}
public void setChapter_id(Integer chapter_id) {
this.chapter_id = chapter_id;
}
public Integer getVideo_id() {
return video_id;
}
public void setVideo_id(Integer video_id) {
this.video_id = video_id;
}
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
public Integer getFree() {
return free;
}
public void setFree(Integer free) {
this.free = free;
}
}
<file_sep>zhang.1=abc1
zhang.2=abc2
zhang.3=abc3<file_sep>package com.zxf.mapper;
import com.zxf.bean.WyPropertyTakeoverSchema;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 物业接管概要; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyPropertyTakeoverSchemaMapper extends BaseMapper<WyPropertyTakeoverSchema> {
}
<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 租赁合同变更; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/zhRentContractChange")
public class ZhRentContractChangeController {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.ZhRentContractCell;
import com.zxf.mapper.ZhRentContractCellMapper;
import com.zxf.service.ZhRentContractCellService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 租赁合同房间; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class ZhRentContractCellServiceImpl extends ServiceImpl<ZhRentContractCellMapper, ZhRentContractCell> implements ZhRentContractCellService {
}
<file_sep>package com.zxf.service;
import com.zxf.bean.TblDbSetting;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 数据库设置; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblDbSettingService extends IService<TblDbSetting> {
}
<file_sep>package com.zxf.test1;
import org.springframework.stereotype.Repository;
@Repository("uu")
public class UserDaoImpl implements UserDao {
@Override
public User getUserByName(String u) {
System.out.println("uu用户查找中。。。");
return new User();
}
}
<file_sep>package com.zxf.service;
import com.zxf.bean.TblCommonLanguage;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 常用语; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblCommonLanguageService extends IService<TblCommonLanguage> {
}
<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 费用临时表2; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/fyMoneyTemporary02")
public class FyMoneyTemporary02Controller {
}
<file_sep>package com.test;
import com.zxf.bean.Bean2;
import com.zxf.bean2.Dept;
import com.zxf.bean2.Employee;
import org.junit.Test;
import org.junit.validator.PublicClassValidator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
import java.util.Map;
public class Test2 {
/*
测试使用scope="singleton" 单例形式
*/
@Test
public void test1(){
ApplicationContext ac=new ClassPathXmlApplicationContext("Spring2.xml");
Bean2 bean2_1 = ac.getBean("bean2", Bean2.class);
Bean2 bean2_2 = ac.getBean("bean2", Bean2.class);
System.out.println(bean2_1==bean2_2);
}
@Test
public void test2(){
ApplicationContext ac=new ClassPathXmlApplicationContext("Spring3.xml");
Dept dept = ac.getBean("dept", Dept.class);
System.out.println(dept.getDept_id());
System.out.println(dept.getDept_name());
List<String> emp_list = dept.getEmp_list();
for(String name:emp_list){
System.out.print(name+" ");
}
System.out.println();
List<Employee> employeeList = dept.getEmployeeList();
for(Employee e:employeeList){
System.out.print(e.getEmp_id()+" ");
System.out.println(e.getEmp_name());
}
Map<String, String> maps = dept.getMaps();
for(String s:maps.keySet()){
System.out.print(s+" ");
System.out.println(maps.get(s));
}
}
}
<file_sep>package com.zxf.factory1;
public class Audi implements Car {
@Override
public String getName() {
return "奥迪";
}
}
<file_sep>package com.zxf.pojo;
import java.io.Serializable;
import java.util.List;
public class Job implements Serializable {
private String job_id;
private String job_name;
private String job_task;
// 这里假定,员工和工作岗位(角色)是多对多的关系,
// 每一个员工可有多于一个的工作岗位(角色),每个工作岗位(角色)可有多个员工
private List<Employee> employees;
public String getJob_id() {
return job_id;
}
public void setJob_id(String job_id) {
this.job_id = job_id;
}
public String getJob_name() {
return job_name;
}
public void setJob_name(String job_name) {
this.job_name = job_name;
}
public String getJob_task() {
return job_task;
}
public void setJob_task(String job_task) {
this.job_task = job_task;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
<file_sep>package com.zxf.zookpeer;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class ZkCreate {
ZooKeeper zooKeeper;
String IP="192.168.0.226:2181";
@Before
public void before() throws Exception{
final CountDownLatch countDownLatch=new CountDownLatch(1);
zooKeeper=new ZooKeeper(IP, 5000, new Watcher() {
public void process(WatchedEvent event) {
if(event.getState()==Event.KeeperState.SyncConnected){
System.out.println("连接OK了");
countDownLatch.countDown();
}
}
});
countDownLatch.await();
}
@After
public void after()throws Exception{
zooKeeper.close();
}
@Test
public void create1()throws Exception{
zooKeeper.create("/create/noe1","node1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
@Test
public void create2()throws Exception{
zooKeeper.create("/create/noe2","node2".getBytes(),ZooDefs.Ids.READ_ACL_UNSAFE,CreateMode.PERSISTENT);
}
@Test
public void create3()throws Exception{
List<ACL> acls=new ArrayList<ACL>();
Id id=new Id("world","anyone");
acls.add(new ACL(ZooDefs.Perms.READ,id));
acls.add(new ACL(ZooDefs.Perms.WRITE,id));
zooKeeper.create("/create/noe3","noe3".getBytes(),acls,CreateMode.PERSISTENT);
}
@Test
public void create4()throws Exception{
List<ACL> acls=new ArrayList<ACL>();
Id id=new Id("ip","192.168.0.226");
acls.add(new ACL(ZooDefs.Perms.ALL,id));
zooKeeper.create("/create/noe4","noe4".getBytes(),acls,CreateMode.PERSISTENT);
}
@Test
public void create5()throws Exception{
zooKeeper.addAuthInfo("digest","itcast:123456".getBytes());
zooKeeper.create("/create/noe5","noe5".getBytes(),ZooDefs.Ids.CREATOR_ALL_ACL,CreateMode.PERSISTENT);
}
@Test
public void create6()throws Exception{
zooKeeper.addAuthInfo("digest","itcast:123456".getBytes());
List<ACL> acls=new ArrayList<ACL>();
Id id=new Id("auth","itcast");
acls.add(new ACL(ZooDefs.Perms.READ,id));
zooKeeper.create("/create/noe6","noe6".getBytes(),acls,CreateMode.PERSISTENT);
}
@Test
public void create7()throws Exception{
List<ACL> acls=new ArrayList<ACL>();
Id id=new Id("digest","itheima:qlzQzCLKhBROghkooLvb+Mlwv4A=");
acls.add(new ACL(ZooDefs.Perms.ALL,id));
zooKeeper.create("/create/noe7","noe7".getBytes(),acls,CreateMode.PERSISTENT);
}
@Test
public void create8()throws Exception{
String result=zooKeeper.create("/create/noe8","noe8".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT_SEQUENTIAL);
System.out.println(result);
}
//临时节点 ,会话关闭以后,该临时节点也不存在了。
@Test
public void create9()throws Exception{
String result=zooKeeper.create("/create/noe9","noe9".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
System.out.println(result);
}
@Test
public void create10()throws Exception{
String result=zooKeeper.create("/create/noe10","noe10".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(result);
}
@Test
public void create11()throws Exception{
zooKeeper.create("/create/noe11","noe11".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT,new AsyncCallback.StringCallback(){
public void processResult(int rc, String path, Object ctx, String name) {
System.out.println(rc);
System.out.println(path);
System.out.println(name);
System.out.println(ctx);
}
},"I am context");
Thread.sleep(1000);
System.out.println("结束");
}
}
<file_sep>jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.0.148:3306/test
jdbc.username=root
jdbc.password=<PASSWORD>
oracle.driver=oracle.jdbc.OracleDriver
oracle.url=jdbc:oracle:thin:@localhost:1521:orcl
oracle.user=scott
oracle.pwd=<PASSWORD><file_sep>package com.zxf.service;
import com.zxf.bean.TblNetdiskUrl;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 网络硬盘路径; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblNetdiskUrlService extends IService<TblNetdiskUrl> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.WyTakeoverDataDetail;
import com.zxf.mapper.WyTakeoverDataDetailMapper;
import com.zxf.service.WyTakeoverDataDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 物业接管资料明细; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class WyTakeoverDataDetailServiceImpl extends ServiceImpl<WyTakeoverDataDetailMapper, WyTakeoverDataDetail> implements WyTakeoverDataDetailService {
}
<file_sep>package com.zxf.domain;
public class InitTest {
private Integer id;
private String title;
public void init(){
System.out.println("我是init初始化方法");
}
public void destory(){
System.out.println("我是destory方法");
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
<file_sep>package com.zxf.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/*
统一配置类
*/
@Configuration
@PropertySource("classpath:pay1.properties")
public class ZxfConfig {
@Value("${zhang.1}")
private String z1;
@Value("${zhang.2}")
private String z2;
@Value("${zhang.3}")
private String z3;
public String getZ1() {
return z1;
}
public void setZ1(String z1) {
this.z1 = z1;
}
public String getZ2() {
return z2;
}
public void setZ2(String z2) {
this.z2 = z2;
}
public String getZ3() {
return z3;
}
public void setZ3(String z3) {
this.z3 = z3;
}
}
<file_sep># \u914D\u7F6Eperson\u5C5E\u6027\u503C
#person.last-name=\u822A\u4E09
#person.address=\u5317\u4EAC\u5148
#person.age=213
#person.birth=2014/6/21
#person.boss=true
#person.lists=\u6570\u636E,\u7A0B\u5E8F,\u7F13\u5B58,\u7A7A\u95F4
#person.maps.k1=\u6211\u662Fmap1
#person.maps.k2=\u6211\u662Fmap2
#person.dog.name=\u8FD9\u4E2A\u662F\u5C0F\u72D7
#person.dog.age=22
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.WyCleanPlan;
import com.zxf.mapper.WyCleanPlanMapper;
import com.zxf.service.WyCleanPlanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 清洁安排; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class WyCleanPlanServiceImpl extends ServiceImpl<WyCleanPlanMapper, WyCleanPlan> implements WyCleanPlanService {
}
<file_sep>package com.zxf.inter;
import java.lang.reflect.Method;
/*
定义拦截器接口
*/
public interface Interceptor {
public boolean before(Object proxy,Object target,Method method,Object[] args);
public void around(Object proxy,Object target,Method method,Object[] args);
public void after(Object proxy,Object target,Method method,Object[] args);
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.WyFireCheck;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 消防巡查; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyFireCheckMapper extends BaseMapper<WyFireCheck> {
}
<file_sep>package com.zxf.mapper;
import com.zxf.pojo.Dept;
import com.zxf.pojo.Employee;
import java.util.List;
public interface DeptMapper {
public Dept getDeptById(String dept_id);
//分步骤用了2个SQL语句完成
public Dept getDeptById_Emp(String dept_id);
//1个联合查询的SQL语句
public Dept getDeptById_Emp2(String dept_id);
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.WyOutDetail;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 支出明细; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyOutDetailMapper extends BaseMapper<WyOutDetail> {
}
<file_sep>package com.zxf.mapper;
import com.zxf.pojo.Log;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface LogMapper {
List<Log> selAll();
/**
* mybatis把参数转换为map了,其中@Param("key") 参数内容就是map的value
* @param accin123
* @param accout3454235
* @return
*/
List<Log> selByAccInAccount(@Param("accin") String accin,@Param("accout") String accout);
List<Log> selByAccinAccout2(@Param("accout")String accout,@Param("accin") String accin);
List<Log> selByAccinAccout3(@Param("accout")String accout,@Param("accin") String accin);
List<Log> selByAccinAccout4(@Param("accout")String accout,@Param("accin") String accin);
int upd1(Log log);
List<Log> selByLog(Log log);
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.WyDutyManage;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 执勤管理; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyDutyManageMapper extends BaseMapper<WyDutyManage> {
}
<file_sep>package com.zxf.strategy;
public class Dog implements Comparable<Dog> {
int food;
public Dog(int food){
this.food=food;
}
@Override
public int compareTo(Dog o) {
if(this.food<o.food) return -1;
else if (this.food>o.food) return 1;
else return 0;
}
@Override
public String toString() {
return "Dog{" +
"food=" + food +
'}';
}
}<file_sep>package com.zxf.bean2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
@Aspect
public class MyAspect {
@Before(value = "execution(* com.zxf.bean2.*.*(..))")
public void beforeMethod(JoinPoint joinPoint){
Object[] args=joinPoint.getArgs();
String methodName=joinPoint.getSignature().getName();
System.out.println("方法名:"+methodName+",方法参数:"+ Arrays.toString(args)+".....方法执行之前");
}
@After(value = "execution(* com.zxf.bean2.*.*(..))")
public void afterMethod(){
System.out.println("方法执行之后........");
}
@AfterReturning(value = "execution(* com.zxf.bean2.*.*(..))",returning = "result")
public void afterRetunMethd(JoinPoint joinPoint,Object result){
System.out.println("后置返回:"+result);
}
@Around(value = "execution(* com.zxf.bean2.*.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint){
Object result=null;
try{
System.out.println("环绕前置");
result=joinPoint.proceed();
return result;
}catch (Throwable e){
System.out.println("环绕异常");
}finally {
System.out.println("环绕后置");
}
return null;
}
}
<file_sep>package com.zxf.service;
import com.zxf.model.entity.User;
import java.util.Map;
public interface UserService {
/*
新增用户
*/
public int save(Map<String,String>userInfo);
public String findByPhoneAndPwd(String phone, String pwd);
public User findByUsesrId(Integer userId);
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.ZhCustomerEstate;
import com.zxf.mapper.ZhCustomerEstateMapper;
import com.zxf.service.ZhCustomerEstateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 业主房产对照表; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class ZhCustomerEstateServiceImpl extends ServiceImpl<ZhCustomerEstateMapper, ZhCustomerEstate> implements ZhCustomerEstateService {
}
<file_sep>package com.zxf.test4jdk.explain;
public interface OrderInterface {
public String order(String foodName);
public void test();
public void test2();
}
<file_sep>package com.zxf.web.service.impl;
import com.zxf.web.mapper.MenuMapper;
import com.zxf.web.pojo.Menu;
import com.zxf.web.service.MenuService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class MenuServiceImpl implements MenuService {
@Resource
private MenuMapper menuMapper;
public List<Menu> show() {
return menuMapper.selByPid(0);
}
}
<file_sep>package com.zxf.atguigu.controller;
import com.zxf.atguigu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class UserController {
@Autowired
private UserService userService;
public void save_user(){
userService.save();
System.out.print("Controller层的save_user()方法执行了");
}
public UserController() {
System.out.println("UserController");
}
}
<file_sep>package com.zxf.test;
import com.zxf.demo5.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//运行器
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext_test.xml")
public class TestDemo5 {
@Autowired
private User user;
@Test
public void test1(){
user.sayHello();
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.pojo.People;
import java.util.List;
public interface PeopleMapper {
//查询所有人员
public List<People> getAll();
//插入
public void savePeople(People people);
//条件查询
public List<People> findbyPe(People people);
// in (id,id,id) 这样的查询
public List<People> finByidS(People people);
}
<file_sep>package com.zxf.service;
import com.zxf.bean.TblGroupsTodo;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 分组待办事项; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblGroupsTodoService extends IService<TblGroupsTodo> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.ZhRentContract;
import com.zxf.mapper.ZhRentContractMapper;
import com.zxf.service.ZhRentContractService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 租赁合同; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class ZhRentContractServiceImpl extends ServiceImpl<ZhRentContractMapper, ZhRentContract> implements ZhRentContractService {
}
<file_sep>package com.zxf.atguigu.dao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl2222 implements UserDao {
public UserDaoImpl2222() {
System.out.println("UserDaoImpl2222构造()方法执行了");
}
public void save() {
System.out.println("UserDaoImpl2222中的save()方法执行了");
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.FyPreReceive;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 预收款管理; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface FyPreReceiveMapper extends BaseMapper<FyPreReceive> {
}
<file_sep>package com.zxf.test;
import com.zxf.demo.Demo1;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test1 {
@Test
public void test1(){
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Demo1 domo1 = ac.getBean("domo1", Demo1.class);
domo1.d1();
}
}
<file_sep>package com.zxf.controller;
public class Phone {
public String color;
}
<file_sep>package com.zxf.service;
import com.zxf.bean.WyFireFacility;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 消防设施; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyFireFacilityService extends IService<WyFireFacility> {
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.WyEstateOutDetailSub;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 楼盘经费支出明细_审批子表; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyEstateOutDetailSubMapper extends BaseMapper<WyEstateOutDetailSub> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblNetdiskDir;
import com.zxf.mapper.TblNetdiskDirMapper;
import com.zxf.service.TblNetdiskDirService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 网络硬盘_文件夹; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblNetdiskDirServiceImpl extends ServiceImpl<TblNetdiskDirMapper, TblNetdiskDir> implements TblNetdiskDirService {
}
<file_sep>package com.zxf.test1;
class TicketThread3 implements Runnable{
private int count=100;
@Override
public void run() {
while (count>0 ){
ticket();
}
}
public synchronized void ticket(){
if(count>0) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
System.out.println(Thread.currentThread().getName() + ",正在出票" + (100 - count + 1) + "张");
count--;
}
}
}
public class Main3 {
public static void main(String[] args) {
TicketThread3 ticketThread3=new TicketThread3();
new Thread(ticketThread3).start();
new Thread(ticketThread3).start();
new Thread(ticketThread3).start();
new Thread(ticketThread3).start();
}
}
<file_sep>package com.zxf.service;
import com.zxf.bean.TblComparyNotice;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 企业公告; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblComparyNoticeService extends IService<TblComparyNotice> {
}
<file_sep>package com.zxf.web.service;
import com.zxf.web.pojo.Flower;
import java.util.List;
public interface FlowerService {
List<Flower> show();
}
<file_sep>package com.zxf.service;
import com.zxf.bean.WyEstateIncomeProject;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 楼盘经费收入项目; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyEstateIncomeProjectService extends IService<WyEstateIncomeProject> {
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.TblDbSetting;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 数据库设置; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblDbSettingMapper extends BaseMapper<TblDbSetting> {
}
<file_sep>package com.zxf.bean;
public class Bean2 {
public Bean2(){
System.out.println("Bean2()构造方法运行了。");
}
}
<file_sep>package com.zxf;
import com.zxf.controller.UserController;
import com.zxf.domain.User;
import com.zxf.utils.JsonData;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public class UsetTest {
@Autowired
private UserController userController;
@Test
public void loginTest(){
User user=new User();
user.setUsername("xdclass-lw");
user.setPwd("<PASSWORD>");
JsonData jsonData=userController.login(user);
// System.out.println(jsonData.toString());
// System.out.println(jsonData.getCode());
System.out.println("code:"+jsonData.getCode());
TestCase.assertEquals(-1,jsonData.getCode());
}
}
<file_sep>package com.zxf.list;
public class SelectionSort {
public static void main(String[] args) {
int[] arr={5,8,9,1,2,7,3,6,4};
int minPos=0;
for(int j=1;j<arr.length;j++){
if(arr[j]<arr[minPos]){
minPos=j;
}
}
System.out.println("最小值:"+arr[minPos]);
int temp=arr[0];
arr[0]=arr[minPos];
arr[minPos]=temp;
for (int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}
}
<file_sep>emp.emp_id=${random.uuid}
emp.emp_name=\u5F20_${random.long}<file_sep>package com.zxf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication//springBoot启动注解,SpringBoot主配置类
public class SpringBoot0817Application {
public static void main(String[] args) {
SpringApplication.run(SpringBoot0817Application.class, args);
}
}
<file_sep>package com.zxf.bean6;
public interface Animal {
public void sleep();
}
<file_sep>package com.zxf.dLambda;
public interface NoneReturnParameter {
//无参 无返回值
void f1();
}
<file_sep>package com.zxf.web.controller;
import com.zxf.web.pojo.Users;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
@Controller
public class MyController1 {
@RequestMapping("c1")
public String execute1(){
System.out.println("c1方法");
return "ok.jsp";
}
@RequestMapping("c2")
public String execute2(String name,int age){
System.out.println("c2方法:"+name+","+age);
return "ok.jsp";
}
@RequestMapping("c3")
public String execute3(Users users){
System.out.println("c3方法:"+users.getName()+","+users.getAge());
return "ok.jsp";
}
@RequestMapping("c4")
public String execute4(Users users, HttpServletRequest req){
System.out.println("c4方法:"+users.getName()+","+users.getAge());
req.setAttribute("uname",users.getName());
return "ok.jsp";
}
@RequestMapping("c5")
public String execute5(@RequestParam("che")List<String> lists){//对应多选
System.out.println(lists);
return "ok.jsp";
}
@RequestMapping("c6/{a1}/{a2}") // a1 a2随便写,但要和@PathVariable(value = "a1")对应上
public String execute6(@PathVariable(value = "a1") String zhang1, @PathVariable(value = "a2") String zhang2){
System.out.println(zhang1+" "+zhang2);
return "/ok.jsp";
}
@RequestMapping("c7")
@ResponseBody
public String execute7(){
Users users=new Users();
users.setAge(23);
users.setName("zhang");
return "users";
}
@RequestMapping("c8")
public String execute8(){//对应多选
System.out.println("c8....execute8");
return "ok2";
}
}
<file_sep>package com.zxf.service;
import com.zxf.bean.FyMoneyTemporary02;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 费用临时表2; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface FyMoneyTemporary02Service extends IService<FyMoneyTemporary02> {
}
<file_sep>package com.zxf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
@Controller
public class MyController5 {
/*
@RequestMapping(value = "/my5",method = RequestMethod.POST)
public ModelAndView param(){
ModelAndView mav=new ModelAndView();
//类似于setAttribute
mav.addObject("username","zhang3");
//跳转页面
mav.setViewName("ok1");
return mav;
}*/
/*
@RequestMapping(value = "/my5",method = RequestMethod.POST)
public String param(Map<String,Object>map){
map.put("username","zhangwangli4");
return "ok1";
}
*/
@RequestMapping(value = "/my5",method = RequestMethod.POST)
public String param(Model model){
model.addAttribute("username","风学长");
return "ok1";
}
}
<file_sep>package com.zxf.main;
class T8 implements Runnable{
private int count=1000;
@Override
public synchronized void run() {
count--;
System.out.println(Thread.currentThread().getName()+"-->count="+count);
}
}
public class Main8 {
public static void main(String[] args) {
T8 t8=new T8();
for (int i=0;i<10;i++){
new Thread(t8,"线程:"+i).start();
}
}
}<file_sep>package com.zxf.dLambda;
public interface NoneReturnMutipleParameter {
//多个参数,无返回值。
public void f1(int x,int y);
}
<file_sep>package com.zxf;
import com.zxf.mapper.Users1Mapper;
import com.zxf.pojo.Users;
import com.zxf.pojo.Users1;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class Test2 {
@Autowired
private Users1Mapper users1Mapper;
@Test
public void saveUser(){
Users1 u1=new Users1();
// u1.setUserid(1);
u1.setUsername("wangha");
u1.setUserage(23);
u1.setText("wo shi benb");
int insert = users1Mapper.insert(u1);
System.out.println("********"+insert);
}
}
<file_sep>package com.zxf.service;
import com.zxf.bean.TblMessageCharge;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 短信充值单; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblMessageChargeService extends IService<TblMessageCharge> {
}
<file_sep>package com.zxf.abstractfactory;
public class Ak47 extends Weapon {
@Override
void shoot() {
System.out.println("tututututuutut.....");
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.TblTodo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 待办事项; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblTodoMapper extends BaseMapper<TblTodo> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.FyPropertyMoneyDist;
import com.zxf.mapper.FyPropertyMoneyDistMapper;
import com.zxf.service.FyPropertyMoneyDistService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 物业费分布; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class FyPropertyMoneyDistServiceImpl extends ServiceImpl<FyPropertyMoneyDistMapper, FyPropertyMoneyDist> implements FyPropertyMoneyDistService {
}
<file_sep>package com.zxf.test4;
/*
消费者
*/
public class Customer implements Runnable {
private Goods goods;
public Customer(Goods goods){
this.goods=goods;
}
@Override
public void run() {
for(int i=0;i<10;i++){
try{
Thread.sleep(20);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("消费者取走了:"+goods.getBrand()+"---"+goods.getName());
}
}
}
<file_sep>package com.zxf;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zxf.mapper.UsersMapper;
import com.zxf.pojo.Users;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.jws.soap.SOAPBinding;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@SpringBootTest
public class ApplicationTests {
@Autowired
private UsersMapper usersMapper;
@Test
public void findAll() {
List<Users> usersList = usersMapper.selectList(null);
for(Users u:usersList){
System.out.println(u.getUsername());
}
}
//添加
@Test
public void addUser(){
/*
在添加的时候会自动调用com.zxf.handler.MyMetaObjectHandler类的insertFill方法
完成里面的2个时间字段自动添加动作
*/
Users users=new Users();
users.setUserid(35);
users.setUsername("1aasdfzsdf");
users.setUserage(30);
users.setText("asdfzzz");
usersMapper.insert(users);
}
//修改
/*
在添加的时候会自动调用com.zxf.handler.MyMetaObjectHandler类的updateFill方法
完成里面的1个时间字段自动修改动作
*/
@Test
public void updateUser(){
Users u=new Users();
//u.setUserid(1);
u.setUsername("hhhdhdhdhdh*");
u.setUserage(-23);
u.setText("----wo shi benb");
u.setUserid(31);
usersMapper.updateById(u);
}
/*
测试乐观锁的修改
*/
@Test
public void updateUserLock(){
//根据ID查询以后才可以修改
Users users=usersMapper.selectById(32);
//修改操作了
users.setUserage(87);
usersMapper.updateById(users);
}
/*
多个ID的批量查询
*/
@Test
public void testSelectDemo1(){
List<Users> usersList = usersMapper.selectBatchIds(Arrays.asList(1, 2, 18,20,3, 4, 5));
for(Users u:usersList){
System.out.println(u.getUsername());
}
}
/*
分页查询
*/
@Test
public void testPage(){
/*
1 创建Page对象
2 传入2个参数 当前页和每页显示记录数
*/
Page<Users> page=new Page<>(2,3);
/*
调用mp分页查询方法
*/
usersMapper.selectPage(page,null);
/*
通过page对象获取分页数据
*/
System.out.println("当前页:"+page.getCurrent()); //当前页
List<Users> records = page.getRecords();//当前页list集合
for(Users u:records){
System.out.println(u.getUsername());
}
//System.out.println("当前页list集合:"+page.getRecords());
System.out.println("显示每页记录数:"+page.getSize()); //显示每页记录数
System.out.println("总记录数:"+page.getTotal()); //总记录数
System.out.println("总页数:"+page.getPages()); //总页数
System.out.println("下一页:"+page.hasNext()); //下一页
System.out.println("上一页:"+page.hasPrevious()); //上一页
}
/*
物理删除:也就是真正的数据记录删除
*/
@Test
public void testDeleteById(){
/*
配置了逻辑删除以后,同样的执行命令;都不会物理删除了
都会在deleted字段有个逻辑标志了,
然后为我们在查询的时候,逻辑删除的记录不会显示。
记录依然会在数据库里保存。
*/
usersMapper.deleteById(1);
}
/*
批量物理删除
*/
@Test
public void testDeleteBatchIds(){
usersMapper.deleteBatchIds(Arrays.asList(2,3));
}
/*
mp 实现复杂查询
*/
@Test
public void testSelectQuery(){
QueryWrapper<Users> wrapper=new QueryWrapper<>();
/*
通过QueryWrapper设置条件
ge >=
gt >
le <=
lt <
eq ==
ne !=
between
like 模糊
orderBydesc 排序
last //后补SQL语句的条件部分
指定查询的列
*/
//wrapper.ne("userage",62);
//wrapper.between("userage",20,40);
//wrapper.like("username","a");
//wrapper.last("limit 6");
wrapper.select("username","text");//指定要查询的列
List<Users> usersList = usersMapper.selectList(wrapper);
for(Users u:usersList){
System.out.println(u.getUsername());
}
}
}
<file_sep>package com.test;
import com.zxf.atguigu.controller.UserController;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test_atguigu {
@Test
public void test1(){
ApplicationContext ac=new ClassPathXmlApplicationContext("Spring5.xml");
UserController userController = ac.getBean("userController", UserController.class);
userController.save_user();
}
}
<file_sep>package com.zxf.factory1;
public class Bwm implements Car {
@Override
public String getName() {
return "宝马";
}
}
<file_sep>package com.zxf.test2;
public class B {
private A a=new A();
public int f1(int a,int b){
return a+b;
}
public int f2(int a,int b){
return f1(a,b)+9;
}
public int f3(int a,int b){
return this.a.f1(a,b);
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.config.CacheKeyManager;
import com.zxf.model.entity.Video;
import com.zxf.model.entity.VideoBanner;
import com.zxf.mapper.VideoMapper;
import com.zxf.service.VideoService;
import com.zxf.utils.BaseCache;
import org.apache.ibatis.cache.CacheKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class VideoServiceImpl implements VideoService {
@Autowired
private VideoMapper videoMapper;
@Autowired
private BaseCache baseCache;
@Override
public List<Video> listVideo() {
try{
Object cacheObj=baseCache.getTenMinuteCache().get(CacheKeyManager.INDEX_VIDEL_LIST,()->{
List<Video> videoList=videoMapper.listVideo();
return videoList;
});
if(cacheObj instanceof List){
List<Video> videoList=(List<Video>)cacheObj;
return videoList;
}
}catch (Exception e){
e.printStackTrace();
}
//可以返回兜底数据,业务系统降级--》SpringCloud专题
return null;
}
static int r;
@Override
public List<VideoBanner> listBanner() {
try {
Object cacheObj = baseCache.getTenMinuteCache().get(CacheKeyManager.INDEX_BANNER_KEY, () -> {
System.out.println(r++);
List<VideoBanner> bannerList = videoMapper.listVideoBanner();
System.out.println("从数据库里面找轮播图列表");
return bannerList;
});
if(cacheObj instanceof List){
List<VideoBanner> bannerList=(List<VideoBanner>)cacheObj;
return bannerList;
}
}catch (Exception e){e.printStackTrace();}
return null;
}
@Override
public Video findDetailByid(int videoId) {
//单独构建一个缓存key ,每个视频的key是不一样的。
String videoCacheKey=String.format(CacheKeyManager.VIDEO_DETAIL,videoId);
try{
Object cacheObject=baseCache.getOneHourCache().get(videoCacheKey,()->{
Video video=videoMapper.findDetailByid(videoId);
return video;
});
if(cacheObject instanceof List){
Video video=(Video)cacheObject;
return video;
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
<file_sep>package com.zxf.service;
import com.zxf.bean.ZhCsHandleSpeed;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 业主服务_办理进度; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface ZhCsHandleSpeedService extends IService<ZhCsHandleSpeed> {
}
<file_sep>package com.zxf.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
@Data
public class Users1 {
@TableId(type = IdType.ID_WORKER)
private Integer userid;
private String username;
private Integer userage;
private String text;
}
<file_sep>package com.zxf.mapper;
import com.zxf.pojo.Product;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface ProductMapper {
//查询所有的产品信息
@Select("select * from product")
public List<Product> findAll() throws Exception;
}
<file_sep>package com.zxf.dao;
public interface IUserDao {
public void saveUserDao();
}
<file_sep>package com.zxf.mapper;
import com.zxf.pojo.Dept;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import sun.swing.MenuItemLayoutHelper;
import java.util.List;
public interface DeptMapper {
@Select("select * from dept")
public List<Dept> getall_dept();
/*
配合多对一查询的第二个SQL语句 根据部门ID进行查询
*/
@Select("select * from dept where dept_id=#{dept_id}")
public List<Dept> finByIdDept(String dept_id);
/*
根据部门查询下面的所有员工 一对多 部门--》员工
*/
@Select("select * from dept")
@Results(id="d_e",value = {
@Result(property="dept_id",column="dept_id"),
@Result(property = "dept_name",column = "dept_name"),
@Result(property = "employees",column = "dept_id",
many = @Many(select = "com.zxf.mapper.EmployeeMapper.findBydeptEmp",
fetchType = FetchType.LAZY))
})
public List<Dept> getall_d_e();
}
<file_sep>package com.zxf.service;
import com.zxf.bean.TblEmailSend;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 邮件发送; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblEmailSendService extends IService<TblEmailSend> {
}
<file_sep>package com.test1;
import com.zxf.dao.IUserDao;
import com.zxf.service.IUserService;
import com.zxf.service.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main1 {
@Test
public void test1(){
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
IUserService bean = ac.getBean(UserServiceImpl.class);
bean.saveUserService();
//IUserDao iUserDao=(IUserDao) ac.getBean("userDao");
// iUserDao.saveUserDao();
}
}<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zxf</groupId>
<artifactId>mybatisProject</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>mybatisProject-mapper</module>
<module>mybatisProject-pojo</module>
<module>mybatisProject-web</module>
<module>mybatisProject-service</module>
</modules>
<name>Maven</name>
<!--对依赖的坐标的版本做集中管理-->
<properties>
<junit.version>4.12</junit.version>
<mybatis.version>3.2.8</mybatis.version>
<mysql.version>5.1.32</mysql.version>
<jstl.version>1.2</jstl.version>
<servlet.version>3.1.0</servlet.version>
<jsp.version>2.0</jsp.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--jsp&servlet-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!--
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
</dependency>
-->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<!--配置资源拷贝插件-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resouces</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<path>/</path>
<port>9090</port>
</configuration>
</plugin>
</plugins>
<!-- Linux远程 -->
<!--
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/zxf</path>
<username>tomcat</username>
<password><PASSWORD></password>
<url>http://192.168.0.216:8080/manager/text</url>
</configuration>
</plugin>
</plugins>
-->
</build>
</project>
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.WyEstateOutDetail;
import com.zxf.mapper.WyEstateOutDetailMapper;
import com.zxf.service.WyEstateOutDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 楼盘经费支出明细; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class WyEstateOutDetailServiceImpl extends ServiceImpl<WyEstateOutDetailMapper, WyEstateOutDetail> implements WyEstateOutDetailService {
}
<file_sep>package com.zxf.service;
import com.zxf.mapper.EmployeeMapper;
import com.zxf.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
public List<Employee> findAll() {
System.out.println("Service....findAll()");
return employeeMapper.findAll();
}
public void saveEmployee(Employee employee) {
System.out.println("Service....saveEmployee()");
employeeMapper.saveEmployee(employee);
}
}
<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 投票数据明细表; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/tblVoteDetail")
public class TblVoteDetailController {
}
<file_sep>package com.zxf.controller;
import com.zxf.domain.City;
import com.zxf.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
//@RestController //它是无效的。不支持模板引擎
@Controller //第一要使用它配置该类
@RequestMapping("my1")
public class MyController1 {
@Autowired
CityService cityService;
@RequestMapping("list")
public String list(ModelMap map){
List<City> list=cityService.findAll();
map.addAttribute("list",list);
return "list";
}
@RequestMapping("add")
public String add(@RequestParam("id") Integer id,@RequestParam("name") String name){
String success=cityService.add(id,name);
System.out.println("__________---2309239032");
return "add";
}
@RequestMapping("addPage")
public String addPage(){
// String success=cityService.add(id,name);
return "add";
}
////
////////////////////////////////////////////
@RequestMapping("hello")
public String hello(ModelMap modelMap){
modelMap.addAttribute("name","小峰6132326");
return "list";
}
}<file_sep>package com.zxf.strategy;
public class Sorter<T> {
public void sort(T[] arr,Comparator<T> comparable){
for(int i=0;i<arr.length-1;i++){
int minPos=i;
for(int j=i+1;j<arr.length;j++){
minPos=comparable.compare();
}
swap(arr,i,minPos);
}
}
void swap(T[]arr,int i,int j){
T temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}<file_sep>package com.zxf.contorller;
import com.zxf.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class DeptController {
}
<file_sep>package com.zxf;
import com.zxf.bean.Emp;
import com.zxf.bean.Person;
import com.zxf.conf.MyAppConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test1 {
@Autowired
Person person;
@Autowired
ApplicationContext ioc;
@Test
public void test1(){
System.out.println(person);
}
@Test
public void test2(){
//测试配置类中添加的Bean组件
//这helloSerive是MyAppConfig配置类定义的一个方法名字
boolean helloSerive = ioc.containsBean("helloSerive");
System.out.println(helloSerive);
}
@Autowired
Emp emp;
@Test
public void test3(){
//测试emp
System.out.println(emp);
}
}
<file_sep>package com.zxf.model.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/*
视频轮播图
*/
public class VideoBanner {
private Integer id;
private String url;
private String img;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date create_time;
private Integer weight;
@Override
public String toString() {
return "VideoBanner{" +
"id=" + id +
", url='" + url + '\'' +
", img='" + img + '\'' +
", create_time=" + create_time +
", weight=" + weight +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zxf</groupId>
<artifactId>SpringProject</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>Spring-web1</module>
<module>Spring-test2</module>
<module>Spring-test3</module>
</modules>
<!--对依赖的坐标的版本做集中管理-->
<properties>
<junit.version>4.12</junit.version>
<mybatis.version>3.2.8</mybatis.version>
<mysql.version>5.1.32</mysql.version>
<jstl.version>1.2</jstl.version>
<servlet.version>3.1.0</servlet.version>
<jsp.version>2.0</jsp.version>
<log4j.version>1.2.17</log4j.version>
<spring-aop.version>4.1.6.RELEASE</spring-aop.version>
<spring-aspects.version>4.1.6.RELEASE</spring-aspects.version>
<spring-beans.version>4.1.6.RELEASE</spring-beans.version>
<spring-context.version>4.1.6.RELEASE</spring-context.version>
<spring-context-support.version>4.1.6.RELEASE</spring-context-support.version>
<spring-core.version>4.1.6.RELEASE</spring-core.version>
<spring-expression.version>4.1.6.RELEASE</spring-expression.version>
<spring-instrument.version>4.1.6.RELEASE</spring-instrument.version>
<spring-instrument-tomcat.version>4.1.6.RELEASE</spring-instrument-tomcat.version>
<spring-jdbc.version>4.1.6.RELEASE</spring-jdbc.version>
<spring-jms.version>4.1.6.RELEASE</spring-jms.version>
<spring-messaging.version>4.1.6.RELEASE</spring-messaging.version>
<spring-orm.version>4.1.6.RELEASE</spring-orm.version>
<spring-oxm.version>4.1.6.RELEASE</spring-oxm.version>
<spring-test.version>4.1.6.RELEASE</spring-test.version>
<spring-tx.version>4.1.6.RELEASE</spring-tx.version>
<spring-webmvc.version>4.1.6.RELEASE</spring-webmvc.version>
<spring-web.version>4.1.6.RELEASE</spring-web.version>
<spring-webmvc-portlet.version>4.1.6.RELEASE</spring-webmvc-portlet.version>
<spring-websocket.version>4.1.6.RELEASE</spring-websocket.version>
<commons-logging.version>1.1.3</commons-logging.version>
<asm.version>3.3.1</asm.version>
<cglib.version>2.2.2</cglib.version>
<javassist.version>3.17.1-GA</javassist.version>
<mybatis-spring.version>1.2.3</mybatis-spring.version>
<standard.version>1.1.2</standard.version>
<aopalliance.version>1.0</aopalliance.version>
<aspectjweaver.version>1.7.4</aspectjweaver.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--jsp&servlet-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- Spring-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-aop.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring-aspects.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-beans.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-context.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring-context-support.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-core.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring-expression.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-instrument -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>${spring-instrument.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-instrument-tomcat -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument-tomcat</artifactId>
<version>${spring-instrument-tomcat.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-jdbc.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jms -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring-jms.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-messaging -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${spring-messaging.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-orm.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-oxm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring-oxm.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-test.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-tx.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-web.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-webmvc.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc-portlet -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>${spring-webmvc-portlet.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-websocket -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${spring-websocket.version}</version>
</dependency>
<!-- 其他-->
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commons-logging.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/asm/asm -->
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>${cglib.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javassist.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>${aopalliance.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resouces</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<path>/</path>
<port>9090</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>package com.zxf.mapper;
import com.zxf.bean.TblCommonMessage;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 常用短信; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblCommonMessageMapper extends BaseMapper<TblCommonMessage> {
}
<file_sep>package com.zxf.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zxf.pojo.Users;
import org.springframework.stereotype.Repository;
@Repository
//@Mapper
public interface UsersMapper extends BaseMapper<Users> {
}
<file_sep>package com.zxf.test;
import com.zxf.demo7.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext_demo7.xml")
public class TestDomo7 {
@Autowired
private UserService userService;
@Test
public void test1(){
userService.save();
}
}
<file_sep>package com.zxf.proJDK;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JDKProxyExample implements InvocationHandler {
//真实对象
private Object target=null;
/*
建立代理对象和真实对象的代理关系,并返回代理对象。
*/
public Object bind(Object target) {
this.target=target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
/*
代理方法逻辑
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("1进入代理逻辑方法");
System.out.println("2在调度真实对象之前的服务");
Object obj=method.invoke(target,args);//相当于调用sayHelloWorld方法
System.out.println("3在调度真实对象之后的服务");
return obj;
}
}
<file_sep>package com.zxf.test2;
public class Base {
}
<file_sep>package com.zxf.pojo;
import java.io.Serializable;
public class Dept implements Serializable {
private String dept_id;
private String dept_name;
private String dept_manager;
public String getDept_id() {
return dept_id;
}
public void setDept_id(String dept_id) {
this.dept_id = dept_id;
}
public String getDept_name() {
return dept_name;
}
public void setDept_name(String dept_name) {
this.dept_name = dept_name;
}
public String getDept_manager() {
return dept_manager;
}
public void setDept_manager(String dept_manager) {
this.dept_manager = dept_manager;
}
@Override
public String toString() {
return "Dept{" +
"dept_id='" + dept_id + '\'' +
", dept_name='" + dept_name + '\'' +
", dept_manager='" + dept_manager + '\'' +
'}';
}
}
<file_sep>package com.zxf.spring2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main2 {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring1.xml");
Car car=applicationContext.getBean("car",Car.class);
System.out.println(car.getName());
System.out.println(car.getPrice());
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.TblCommonLanguage;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 常用语; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblCommonLanguageMapper extends BaseMapper<TblCommonLanguage> {
}
<file_sep>package zhang.t1;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController2 {
@ResponseBody
@RequestMapping("/h3")
public String h3(){
return "abc123";
}
}
<file_sep>package com.zxf.test1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component("yController")
public class MyController {
@Autowired
MyService1 myService1;
public String list(){
return myService1.sayCat();
}
}
<file_sep>package com.zxf.dLambda;
public interface SingleReturnMutipleParameter {
//多个参数,有返回值
public String f1(int a,int b);
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.WyFireFacility;
import com.zxf.mapper.WyFireFacilityMapper;
import com.zxf.service.WyFireFacilityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 消防设施; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class WyFireFacilityServiceImpl extends ServiceImpl<WyFireFacilityMapper, WyFireFacility> implements WyFireFacilityService {
}
<file_sep>package com.zxf.atguigu.service;
import com.zxf.atguigu.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
@Qualifier(value = "userDaoImpl2222")//这里的名字必须是 类的首字母小写
private UserDao userDao;
public UserServiceImpl() {
System.out.print("UserServiceImpl");
}
public void save() {
userDao.save();
System.out.println("Service层的save()方法调用了。");
}
}
<file_sep>package com.zxf.service;
import com.zxf.domain.User;
public interface UserService {
public int save(User user);
}
<file_sep>package com.zxf.model.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/*
订单
*/
public class VideoOrder {
private Integer id;
private String out_trade_no;
private Integer state;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date create_time;
private Integer total_fee;
private Integer video_id;
private String video_title;
private String video_img;
private Integer user_id;
@Override
public String toString() {
return "VideoOrder{" +
"id=" + id +
", out_trade_no='" + out_trade_no + '\'' +
", state=" + state +
", create_time=" + create_time +
", total_fee=" + total_fee +
", video_id=" + video_id +
", video_title='" + video_title + '\'' +
", video_img='" + video_img + '\'' +
", user_id=" + user_id +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOut_trade_no() {
return out_trade_no;
}
public void setOut_trade_no(String out_trade_no) {
this.out_trade_no = out_trade_no;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
public Integer getTotal_fee() {
return total_fee;
}
public void setTotal_fee(Integer total_fee) {
this.total_fee = total_fee;
}
public Integer getVideo_id() {
return video_id;
}
public void setVideo_id(Integer video_id) {
this.video_id = video_id;
}
public String getVideo_title() {
return video_title;
}
public void setVideo_title(String video_title) {
this.video_title = video_title;
}
public String getVideo_img() {
return video_img;
}
public void setVideo_img(String video_img) {
this.video_img = video_img;
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
}
<file_sep>package com.zxf.test4jdk;
public interface OrderInterface {
public String order(String foodName);
public void test();
public void test2();
}
<file_sep>package com.zxf.test4jdk;
public class Customer implements OrderInterface {
@Override
public String order(String foodName) {
return "已经下单:"+foodName;
}
@Override
public void test() {
System.out.println("我是Customer的test()");
}
@Override
public void test2() {
System.out.println("我是Customer的test2()");
}
}
<file_sep>package com.zxf.test1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main1 {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("Main1.xml");
MyController bean = app.getBean("yController", MyController.class);
bean.list();
}
}
<file_sep>package com.zxf.dLambda;
public interface SingleReturnNoneParameter {
//无参,有返回值。
public int f1();
}
<file_sep>package com.zxf.test;
import com.zxf.mapper.EmployeeMapper;
import com.zxf.mapper.JobMapper;
import com.zxf.pojo.Employee;
import com.zxf.pojo.Job;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test_many_many {
private SqlSessionFactory sqlSessionFactory;
private SqlSession session;
private InputStream is;
private EmployeeMapper employeeMapper;
private JobMapper jobMapper;
@Before //Test方法之前执行,都是junit提供的方法
public void init()throws IOException {
//加载主配置文件
is= Resources.getResourceAsStream("mybatisConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//通过工厂获取SqlSession
session=factory.openSession();
employeeMapper = session.getMapper(EmployeeMapper.class);
jobMapper=session.getMapper(JobMapper.class);
}
@After//Test方法之后执行,都是junit提供的方法
public void destory()throws IOException{
session.close();
is.close();
}
@Test
public void test1(){
//通过员工ID查询这个员工都有哪些职务
Employee employee = employeeMapper.selectEmployeeById("HW9801");
System.out.println(employee.getEmp_name());
List<Job> jobs = employee.getJobs();
for(Job j:jobs){
System.out.println(j.getJob_name());
}
}
@Test
public void test2(){
//通过职位ID查询,本职位都有哪些员工
Job job = jobMapper.selectJobById("2602");
System.out.println(job.getJob_name());
System.out.println("****************职位人员*************************");
List<Employee> employees = job.getEmployees();
for(Employee e:employees){
System.out.println(e.getEmp_name());
}
}
}
<file_sep>package com.zxf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/my3")
public class MyController3 {
@RequestMapping("/ok3/{name}/{age}")
public String ok3(@PathVariable("name")String name,@PathVariable("age") Integer age){
System.out.println("name:"+name+",age:"+age);
return "ok1";
}
}
<file_sep>package com.zxf.service;
import com.zxf.bean.FcCellAddbuild;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 房间加建信息; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface FcCellAddbuildService extends IService<FcCellAddbuild> {
}
<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 车位租赁; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/wyCarSpaceRent")
public class WyCarSpaceRentController {
}
<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 楼盘信息; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/fcEstate")
public class FcEstateController {
}
<file_sep>package com.zxf.service;
import com.zxf.bean.TblEnvirSetting;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 环境配置; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblEnvirSettingService extends IService<TblEnvirSetting> {
}
<file_sep>package com.zxf.service;
import com.zxf.bean.FyRefundSub;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 退款单子单; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface FyRefundSubService extends IService<FyRefundSub> {
}
<file_sep>package com.zxf.demo5;
public class User {
public void sayHello(){
System.out.println("User....sayHello()");
}
}
<file_sep>package com.zxf.test;
import com.zxf.demo4.Orcer;
import com.zxf.demo4.SpringConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import javax.sql.DataSource;
public class TestDemo4 {
@Test
public void test1(){
ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfig.class);
Orcer bean = ac.getBean("orcer", Orcer.class);
System.out.println(bean);
}
@Test
public void test2(){
ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfig.class);
DataSource dataSource = ac.getBean("dataSource", DataSource.class);
System.out.println(dataSource);
}
}
<file_sep>userr.name=zhang3
user.age=34
user.sex=man<file_sep>package com.zxf.service.impl;
import com.zxf.bean.FyMoneyTemporary04;
import com.zxf.mapper.FyMoneyTemporary04Mapper;
import com.zxf.service.FyMoneyTemporary04Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 费用临时表4; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class FyMoneyTemporary04ServiceImpl extends ServiceImpl<FyMoneyTemporary04Mapper, FyMoneyTemporary04> implements FyMoneyTemporary04Service {
}
<file_sep>package com.zxf.springcloud.controller;
import com.zxf.springcloud.entities.CommonResult;
import com.zxf.springcloud.entities.Payment;
import com.zxf.springcloud.lib.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.net.URI;
import java.util.List;
@RestController
@Slf4j
public class OrderController {
//public static final String PAYMENT_URL="http://localhost:8001";//远程服务类域名地址
//如果订单服务不是单机了,是集群了。需要这样写。
//http://cloud-payment-service是在8001的yml中定义的名字
public static final String PAYMENT_URL="http://cloud-payment-service";
@Resource
private RestTemplate restTemplate;
@Resource
private LoadBalancer loadBalancer;
@Resource
private DiscoveryClient discoveryClient;
@GetMapping(value = "/consumer/payment/create")
public CommonResult<Payment>create(Payment payment){
/*
PAYMENT_URL+"/payment/create"
就是cloud-provider-payment8001项目中的
com.zxf.springcloud.controller.PaymentController中的
@PostMapping(value = "/payment/create")请求
还有一个就是postForObject表示对数据库增加记录时候用的方法
*/
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
}
/*
PAYMENT_URL+"/payment/create"
就是cloud-provider-payment8001项目中的
com.zxf.springcloud.controller.PaymentController中的
@GetMapping(value = "/payment/get/{id}")
还有一个就是getForObject表示对数据库查询时候用的方法
*/
int i=1;
@GetMapping(value = "/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id")Long id){
System.out.println("我执行了。。。"+(i++));
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
@GetMapping(value = "/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getPayment2(@PathVariable("id")Long id){
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
if(entity.getStatusCode().is2xxSuccessful()){
return entity.getBody();
}else {
return new CommonResult<>(444,"操作失败");
}
}
@GetMapping(value = "/payment/discovery")
public Object discover(){
List<String> services = discoveryClient.getServices();
for(String element:services){
log.info("###"+services);
}
List<ServiceInstance> instances = discoveryClient.getInstances("cloud-order-service");
for(ServiceInstance instance:instances){
log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
}
return this.discoveryClient;
}
@GetMapping(value = "/consumer/payment/lb")
public String getPaymentLB(){
List<ServiceInstance> instances
=discoveryClient.getInstances("cloud-payment-service");
if(instances==null || instances.size()<=0){
return null;
}
ServiceInstance serviceInstance=loadBalancer.instances(instances);
URI uri= serviceInstance.getUri();
/*这里要去找8001 8002 8003中controller层的
@GetMapping(value = "/payment/lb")
public String getPaymentLB(){...}定义的请求地址
*/
return restTemplate.getForObject(uri+"payment/lb",String.class);
}
}<file_sep>package com.zxf.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 业主房产对照表; InnoDB free: 8192 kB 前端控制器
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Controller
@RequestMapping("/zhCustomerEstate")
public class ZhCustomerEstateController {
}
<file_sep>package com.zxf.test;
import java.util.Arrays;
public class Main1 {
public static void main(String[] args) {
for(int i=1;i<=100;i++){
System.out.println(i);
}
int a=2;
int b=4;
int c=6;
int[] arr=new int[4];
arr[0]=-1;
arr[1]=-2;
arr[2]=200;
arr[3]=-3;
Arrays.toString(arr);
int d=eat();
System.out.println(d);
}
private static int eat(){
System.out.println("11111");
System.out.println("22222");
System.out.println("33333");
System.out.println("44444");
System.out.println("55555");
return 10;
}
}<file_sep>login.username=\u7528\u6237\u540D1
login.password=\<PASSWORD>
login.remmber=\u8BB0\u4F4F\u62111
login.sign=\u767B\u5F551<file_sep>package com.zxf.test2;
public class Thread011 {
class Res{
public String userName;
private char sex;
boolean flag=false;
}
class InputThread extends Thread{
Res res;
public InputThread(Res res){
this.res=res;
}
@Override
public void run() {
int count=0;
while (true) {
synchronized (res) {
if(res.flag){
try{
res.wait();
}catch (Exception e){
e.printStackTrace();
}
}
if (count == 0) {
res.userName = "张三";
res.sex = '男';
} else {
res.userName = "王红";
res.sex = '女';
}
//负载均衡 轮训算法
res.flag=true;
res.notify();
count = (count + 1) % 2;
}
}
}
}
class OutThread extends Thread{
Res res;
public OutThread(Res res){
this.res=res;
}
@Override
public void run() {
while (true) {
synchronized (res) {
if(!res.flag){
try{
if(!res.flag){
//释放锁,当前状态为阻塞状态。
res.wait();
}
}catch (Exception e){
e.printStackTrace();
}
}
System.out.println(res.userName + "," + res.sex);
res.flag=false;
res.notify();
}
}
}
}
public static void main(String[] args) {
new Thread011().start();
}
public void start(){
Res res=new Res();
new InputThread(res).start();
new OutThread(res).start();
}
}<file_sep>package com.zxf.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component //表示spring可以扫描到该类
@Aspect //这个是一个切面类,可以定义切入点和通知
public class LogAdvice {
@Pointcut("execution(* com.zxf.service.VideoServiceImpl.*(..))")
public void aspect(){
}
//前置通知
@Before(value = "aspect()")
public void beforeLog(JoinPoint joinPoint){
System.out.println("LogAdvice..beforeLog()");
}
//后置通知
@After(value = "aspect()")
public void afterLog(JoinPoint joinPoint){
System.out.println("LogAdvice..afterLog()");
}
//环绕通知
@Around("aspect()")
public void around(JoinPoint joinPoint) {
Object target = joinPoint.getTarget().getClass().getName();
System.out.println("调用者是:"+target);
System.out.println("调用方法:"+joinPoint.getSignature());
Object[] args = joinPoint.getArgs();
System.out.println("参数是:"+args[0]);
long start=System.currentTimeMillis();
System.out.println("环绕前");
try {
((ProceedingJoinPoint)joinPoint).proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
long end=System.currentTimeMillis();
System.out.println("环绕前");
System.out.println("总共花了:"+(end-start));
}
}
<file_sep>package com.zxf.web.servlet;
import com.zxf.web.service.FlowerService;
import com.zxf.web.service.impl.FlowerServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/flowerServlet")
public class FlowerServlet extends HttpServlet {
private FlowerService flowerService;
@Override
public void init() throws ServletException {
ApplicationContext ac= WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
flowerService=ac.getBean("flowerSerivce", FlowerServiceImpl.class);
}
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
req.setAttribute("list",flowerService.show());
req.getRequestDispatcher("showFlower.jsp").forward(req,res);
}
}
<file_sep>package com.test;
import com.zxf.bean7.Employee;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.util.List;
public class TestBean7 {
//写入数据
@Test
public void test1(){
ApplicationContext ac=new ClassPathXmlApplicationContext("Spring-jdbc.xml");
JdbcTemplate jdbcTemplate=ac.getBean("jdbcTemplate",JdbcTemplate.class);
jdbcTemplate.update(" insert into employee_basic (emp_no,emp_name,dept_id,emp_gender,emp_email,emp_nation,emp_marriage,emp_health,emp_zzmm,emp_blood,emp_state)\n" +
" VALUES\n" +
" ('aa11223','Z3F','106','男','<EMAIL>','胡族','未婚','一般','国民党','A型','退休') ");
}
//查询记录条数
@Test
public void test2(){
ApplicationContext ac=new ClassPathXmlApplicationContext("Spring-jdbc.xml");
JdbcTemplate jdbcTemplate=ac.getBean("jdbcTemplate",JdbcTemplate.class);
String sql="select count(*) from employee_basic";
Integer count=jdbcTemplate.queryForObject(sql,Integer.class);
System.out.println(count);
}
//查询所有
@Test
public void test3(){
ApplicationContext ac=new ClassPathXmlApplicationContext("Spring-jdbc.xml");
JdbcTemplate jdbcTemplate=ac.getBean("jdbcTemplate",JdbcTemplate.class);
String sql="select * from employee_basic";
RowMapper<Employee> employeeRowMapper=new BeanPropertyRowMapper<Employee>(Employee.class);
List<Employee> employeeList = jdbcTemplate.query(sql, employeeRowMapper);
for(Employee e:employeeList){
System.out.print(e.getEmp_name());
System.out.print(e.getEmp_gender());
System.out.print(e.getEmp_health());
System.out.print(e.getEmp_blood());
System.out.print(e.getEmp_state());
System.out.print(e.getEmp_nation());
System.out.print(e.getEmp_marriage());
System.out.print(e.getEmp_no());
System.out.println(e.getEmp_email());
}
}
}
<file_sep>jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.0.148:3306/test
jdbc.username=root
jdbc.password=<PASSWORD><file_sep>package com.zxf.service;
import com.zxf.bean.TblStopDate;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 到期日期; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblStopDateService extends IService<TblStopDate> {
}
<file_sep>flower.fname=\u7261\u4E39${random.uuid}
flower.faddress=\u5317\u4EAC_${flower.fname}
flower.fprice=${random.int}
<file_sep>package com.zxf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloWorld1 {
public static void main(String[] args) {
SpringApplication.run(HelloWorld1.class,args);
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblMydash;
import com.zxf.mapper.TblMydashMapper;
import com.zxf.service.TblMydashService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 我的驾驶舱; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblMydashServiceImpl extends ServiceImpl<TblMydashMapper, TblMydash> implements TblMydashService {
}
<file_sep>package com.zxf.service;
import com.zxf.bean.WyVegetationInformation;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 植被信息; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyVegetationInformationService extends IService<WyVegetationInformation> {
}
<file_sep>package com.zxf.service;
import com.zxf.bean.TblCommonMessage;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 常用短信; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblCommonMessageService extends IService<TblCommonMessage> {
}
<file_sep>package com.zxf.test1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller("mycon1")
public class My1Controller {
@Autowired
My1Service my1Service;
public String list(){
String name="zhang3";
String pwd="123";
User user=my1Service.login(name,pwd);
if(user!=null){
System.out.println("Hello:"+name);
return "登录OK";
}else {
return "登录失败";
}
}
}
<file_sep>package com.zxf.conf;
import com.zxf.service.MyService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig {
@Bean //可以替代@ImportResource(locations = {"classpath:bean.xml"})
/*
然后getBean()的名字和方法的名字一致就可以了myService
*/
public MyService myService222(){
return new MyService();
}
}
<file_sep>package com.zxf.controller;
import com.zxf.pojo.Employee;
import com.zxf.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/emp")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@RequestMapping("/findAll")
public String findAll(Model model){
List<Employee> all = employeeService.findAll();
model.addAttribute("list",all);
return "list";
}
@RequestMapping("/saveEmp")
public String saveEmp(Employee employee){
employeeService.saveEmployee(employee);
return "redirect:/emp/findAll";
}
@RequestMapping("/delemp")
public String delEmp(String emp_no){
employeeService.delEmp(emp_no);
return "redirect:/emp/findAll";
}
@RequestMapping("/findByIdEmp")
public String findByIdEmp(Model model,String emp_no){
Employee byIdEmp = employeeService.findByIdEmp(emp_no);
model.addAttribute("empID",byIdEmp);
return "updateEmp";
}
@RequestMapping("/updateEmp")
public String updateEmp(Employee employee){
employeeService.updateEmp(employee);
return "redirect:/emp/findAll";
}
@RequestMapping("/b1")
public String b1(Model mv){
String uuid= UUID.randomUUID().toString();
Integer i1=9;
Integer i2=11;
Integer i3=18;
Integer i4=2;
Integer i5=15;
Integer i6=20;
mv.addAttribute("m",uuid);
mv.addAttribute("i1",i1);
mv.addAttribute("i2",i2);
mv.addAttribute("i3",i3);
mv.addAttribute("i4",i4);
mv.addAttribute("i5",i5);
mv.addAttribute("i6",i6);
return "bt1";
}
@RequestMapping("/b2")
public String b2(){
return "bt2";
}
@RequestMapping("/b3")
public String b3(){
return "bt3";
}
@RequestMapping("/b4")
public String b4(){
return "bt4";
}
@RequestMapping("/b5")
public String b5(){
return "bt5";
}
@RequestMapping("/b6")
public String b6(){
return "bt6";
}
@RequestMapping("/b7")
public String b7(){
return "bt7_index";
}
@RequestMapping("/b8")
public String b8(){
return "bt8";
}
/*
用户列表页面
*/
@RequestMapping("/userlist")
public String userlist(){
return "user_list";
}
/*
用户搜索页面
*/
@RequestMapping("/userselect")
public String userselect(){
return "user_select";
}
}<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblUserGroup;
import com.zxf.mapper.TblUserGroupMapper;
import com.zxf.service.TblUserGroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 用户分组; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblUserGroupServiceImpl extends ServiceImpl<TblUserGroupMapper, TblUserGroup> implements TblUserGroupService {
}
<file_sep>package com.zxf.service;
import com.zxf.bean.TblAnswerData;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 题目可选答案信息表; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblAnswerDataService extends IService<TblAnswerData> {
}
<file_sep>package com.zxf.spring4.entity;
public class Person {
}
<file_sep>package com.zxf.controller;
public class VideoController {
}
<file_sep>package com.zxf.bean;
import org.springframework.stereotype.Component;
@Component
public class Dog implements Animal {
public void sleep() {
System.out.println("狗睡觉了。。。");
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.pojo.Role;
import java.util.List;
public interface RoleMapper {
public List<Role> finAll();
//查看用户下的所有权限
public List<Role> finall_u_r();
}
<file_sep>package com.zxf.test;
import com.zxf.mapper.EmployeeMapper;
import com.zxf.mapper.StudentMapper;
import com.zxf.pojo.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test3 {
private InputStream inputStream=null;
private SqlSession session=null;
private StudentMapper mapper=null;
@Before //Test方法之前执行,都是junit提供的方法
public void init()throws IOException {
//加载主配置文件
inputStream= Resources.getResourceAsStream("mybatisConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂获取SqlSession
session=factory.openSession();
mapper = session.getMapper(StudentMapper.class);
}
@After//Test方法之后执行,都是junit提供的方法
public void destory()throws IOException{
session.close();
inputStream.close();
}
//测试 public List<Student> getAllStu();
@Test
public void test1(){
List<Student> allStu = mapper.getAllStu();
for(Student s:allStu){
System.out.print(s.getStu_id()+" ");
System.out.print(s.getStu_name()+" ");
System.out.print(s.getStu_age()+" ");
System.out.println(s.getSut_tid_id());
}
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblCommonMessage;
import com.zxf.mapper.TblCommonMessageMapper;
import com.zxf.service.TblCommonMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 常用短信; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblCommonMessageServiceImpl extends ServiceImpl<TblCommonMessageMapper, TblCommonMessage> implements TblCommonMessageService {
}
<file_sep>package com.zxf.test1;
import org.springframework.stereotype.Component;
@Component
public interface Cat {
public String getName();
}
<file_sep>package com.zxf.zookpeer;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.util.concurrent.CountDownLatch;
public class ZookperConnection {
public static void main(String[] args) {
try{
final CountDownLatch countDownLatch=new CountDownLatch(1);
ZooKeeper zooKeeper=new ZooKeeper("192.168.0.226:2181", 5000, new Watcher() {
public void process(WatchedEvent event) {
if(event.getState()==Event.KeeperState.SyncConnected){
System.out.println("连接成功!");
countDownLatch.countDown();
}
}
});
countDownLatch.await();
System.out.println(zooKeeper.getSessionId());
zooKeeper.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
<file_sep>package com.zxf.mapper;
import com.zxf.bean.FyRefundSub;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 退款单子单; InnoDB free: 8192 kB Mapper 接口
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface FyRefundSubMapper extends BaseMapper<FyRefundSub> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.ZhCsHandleResult;
import com.zxf.mapper.ZhCsHandleResultMapper;
import com.zxf.service.ZhCsHandleResultService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 业主服务_办理结果; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class ZhCsHandleResultServiceImpl extends ServiceImpl<ZhCsHandleResultMapper, ZhCsHandleResult> implements ZhCsHandleResultService {
}
<file_sep>package com.zxf.dao;
import com.zxf.domain.User;
import com.zxf.domain.VideoOrder;
import java.util.List;
public interface VideoOrderMapper {
/**
* 查询全部订单,关联用户信息
* @return
*/
public List<VideoOrder> queryVideoOrderList();
/**
* 查询全部用户的全部订单
* @return
*/
public List<User>queryUserOrder();
}
<file_sep>package com.zxf.service;
import com.zxf.bean.WyFireCheck;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 消防巡查; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface WyFireCheckService extends IService<WyFireCheck> {
}
<file_sep>package com.test1;
import com.zxf.mapper.EmployeeMapper;
import com.zxf.pojo.Dept;
import com.zxf.pojo.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test_Emp {
@Test
public void test1() throws IOException{
InputStream is= Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
SqlSession session=factory.openSession();
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
List<Employee> employees = mapper.getall_mep();
for(Employee e:employees){
System.out.println(e.getEmp_name());
}
}
/*
测试多对一
*/
@Test
public void test2()throws IOException{
InputStream is= Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
SqlSession session=factory.openSession();
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
List<Employee> employees = mapper.getall_e_d();
for(Employee e:employees){
System.out.print(e.getEmp_name()+"所在部门为:");
Dept dept = e.getDept();
System.out.println(dept.getDept_name());
}
}
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblMyNote;
import com.zxf.mapper.TblMyNoteMapper;
import com.zxf.service.TblMyNoteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 我的记事本; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblMyNoteServiceImpl extends ServiceImpl<TblMyNoteMapper, TblMyNote> implements TblMyNoteService {
}
<file_sep>package com.zxf.test2;
public class Thread012 {
public static void main(String[] args) {
new Thread012().start();
}
synchronized void start(){
try {
// new Thread012().wait();
this.wait();
}catch (Exception e){
e.printStackTrace();
}
}
}
<file_sep>package com.zxf.service;
import com.zxf.bean.TblMessageReceive;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 短信接受表; InnoDB free: 8192 kB 服务类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
public interface TblMessageReceiveService extends IService<TblMessageReceive> {
}
<file_sep>package com.zxf.service.impl;
import com.zxf.bean.TblEmployeeContactCategory;
import com.zxf.mapper.TblEmployeeContactCategoryMapper;
import com.zxf.service.TblEmployeeContactCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 员工通讯录类别; InnoDB free: 8192 kB 服务实现类
* </p>
*
* @author zxf
* @since 2020-09-19
*/
@Service
public class TblEmployeeContactCategoryServiceImpl extends ServiceImpl<TblEmployeeContactCategoryMapper, TblEmployeeContactCategory> implements TblEmployeeContactCategoryService {
}
| 8b2a1da80f7cf21697a3f3f1c536ea78eb1c7998 | [
"JavaScript",
"Java",
"Maven POM",
"INI"
]
| 356 | Java | zhang6132326/reps4 | 078616768ba8f8c1d37f186b76972c8546eea449 | b7a6053e23d1bac4afeb766ad15f745e0877eaf6 |
refs/heads/main | <file_sep>import board
import digitalio
import time
import busio
MS5611_CMD_RESET = 0x1E # binary rep:
MS5611_CMD_CONV_D1 = 0x40
MS5611_CMD_CONV_D2 = 0x50
MS5611_CMD_ADC_READ = 0x00
MS5611_CMD_PROM_READ = 0xA2 # this will be iterated for different addresses. P10
ct = 0
fc = [0,0,0,0,0,60]
oRes = 0x00
class MS5611:
def __init__(self, MS5611_ADDRESS, i2cPort):
self.MS5611_ADDRESS = MS5611_ADDRESS
self.i2cPort = i2cPort
self.oRes = oRes
self.reset()
self.setOversampling(oRes)
time.sleep(0.1)
self.readPROM()
def setOversampling(self,ouRes):
global cT
if(ouRes == 0x08):
ct = 10
if(ouRes == 0x06):
ct = 5
if(ouRes == 0x04):
ct = 3
if(ouRes == 0x02):
ct = 2
if(ouRes == 0x00):
ct = 1
def reset(self):
self.i2cPort.writeto(self.MS5611_ADDRESS, bytearray([MS5611_CMD_RESET]))
def readPROM(self):
global fc
for i in range(0,6):
fc[i] = self.readRegister16(MS5611_CMD_PROM_READ + i*2)
time.sleep(.1)
def readRegister16(self,register):
myBuf = bytearray(2)
self.i2cPort.writeto(self.MS5611_ADDRESS, bytearray([register]))
self.i2cPort.readfrom_into(self.MS5611_ADDRESS, myBuf)
x = bytes(myBuf)
val = (x[0] << 8) + x[1]
return val
def readRegister24(self,register):
myBuf = bytearray(3)
self.i2cPort.writeto(self.MS5611_ADDRESS, bytearray([register]))
self.i2cPort.readfrom_into(self.MS5611_ADDRESS, myBuf)
x = bytes(myBuf)
val = (x[0] << 16) + (x[1] << 8) + x[0]
return val
def readRawTemperature(self):
self.i2cPort.writeto(self.MS5611_ADDRESS, bytearray([MS5611_CMD_CONV_D2 + self.oRes]))
time.sleep(ct/1000)
return self.readRegister24(MS5611_CMD_ADC_READ)
def readRawPressure(self):
self.i2cPort.writeto(self.MS5611_ADDRESS, bytearray([MS5611_CMD_CONV_D1 + self.oRes]))
time.sleep(ct/1000)
return self.readRegister24(MS5611_CMD_ADC_READ)
def readTemperature(self):
D2 = self.readRawTemperature()
dT = (D2 - fc[4]*256)/1000
Temp = 2.000 + dT*fc[5]/8388608
Temp2 = 0
if(Temp<=2):
Temp2 = dT*dT/2147.483648
Temp = Temp - Temp2
return Temp*10
def readPressure(self):
D1 = self.readRawPressure()
D2 = self.readRawTemperature()
dT = (D2 - fc[4]*256)/1000
OFF = (fc[1] * 65.536 + fc[3] * dT / 128)
SENS = (fc[0] * 32.768 + fc[2] * dT / 256)
P = (D1*SENS / 2097152 - OFF) / 32.768
#P = 1
return P
def getAltitude(self):
P = self.readPressure()
seaLevelP = 101325.0 # Pa
return 44330.0 * (1.0 - pow(P / seaLevelP,0.1902949))
<file_sep>import board
import digitalio
import time
import busio
import MS.adafruit_MS5611 as adafruit_MS5611
i2c = busio.I2C(board.SCL, board.SDA)
while not i2c.try_lock():
pass
MS5611_ADDRESS = i2c.scan()[0]
led = digitalio.DigitalInOut(board.D13)
led.direction = digitalio.Direction.OUTPUT
altimeter = adafruit_MS5611.MS5611(MS5611_ADDRESS, i2c)
while True:
print("Temperature (C): " + str(altimeter.readTemperature()))
print("Pressure (Pa): " + str(altimeter.readPressure()))
print("Alitimeter (m): " + str(altimeter.getAltitude()))
led.value = True
time.sleep(0.3)
led.value = False
time.sleep(0.3) | cd0c623f951ed67c9a0161022fdef97f2267bfb4 | [
"Python"
]
| 2 | Python | MNSGC-Ballooning/CircuitPython_MS5611 | 06ba9fe8698b65517bcd6b01bf1978972e551e69 | 6c368713aedfa854fd3e4e2c02f595351aafb0c8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.