branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^statics/(?P<path>.*)','django.views.static.serve',{'document_root':'member/statics/', 'show_indexes': True}),
# (r'^statics/(?P<path>.*)','django.views.static.serve',{'document_root':'member/statics'}),
# Examples:
url(r'^$', 'member.views.login', name='home'),
# url(r'^member/', include('member.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
#url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^reg/$','member.views.reg'),
url(r'^login$','member.views.login'),
url(r'^index$','member.views.index'),
url(r'^depart/(.+)/$','member.views.depart'),
url(r'^reg_result/$','member.views.reg_result'),
url(r'^reg_result/index/$','member.views.index'),
url(r'^login_result/$','member.views.login_result'),
url(r'^index/(.+)/$','member.views.index_of_others'),
url(r'^edit$','member.views.edit'),
url(r'^edit_result/$','member.views.edit_result'),
url(r'^logout$','member.views.logout'),
url(r'^send_code$','member.views.send_code'),
url(r'^send_code_result$','member.views.send_code_result'),
#url(r'^createsuperuser$','member.views.createsuperuser'),
)
<file_sep># -*- coding: utf-8 -*-
import random
import hashlib
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
from django.template.loader import get_template
from django.http import HttpResponse
from django.template import Context
from database.models import Activity , Code,Log,Section,User,UserTakePartInActivity
from django.core.paginator import Paginator
from django.core.paginator import PageNotAnInteger
from django.core.paginator import EmptyPage,InvalidPage
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponseRedirect
from constant_number import * # 引入常量
def hello(request):
return HttpResponse('hello world')
def home(request):
return HttpResponse('this is home')
def reg(request):#注册
try:
invitecode=request.GET.get('invitecode', '')
except ValueError:
invitecode = ''
reg=get_template('reg.html',)
regHtml=reg.render(Context({'invitecode':invitecode}))
return HttpResponse(regHtml)
def login(request):
user=request.session.get('user')
if user is None:
login=get_template('login.html')
loginHtml=login.render(Context())
return HttpResponse(loginHtml)
else:
return HttpResponseRedirect("/index")# 跳转到个人主页
def index(request):# 显示自己的详细信息
index=get_template('index.html')
user=request.session.get('user')# 从session对象里面拿出user对象,session是运行这个网站时,每个页面
if user is None: #都共有的一个公共对象,所以可以利用它来在各个页面之间传递参数之类
return HttpResponse("请先登录!")# 如果session里面没有user对象,说明用户并没有登陆,所以返回错误页面
#user = {'name': 'Sally', 'depart':'技术部','grade':'大一','college':'软件学园','major':'软件工程','phone':'15224652255','QQ':'7983452798'}
indexHtml=index.render(Context({'user':user}))
return HttpResponse(indexHtml)
def index_of_others(request,offset):# 显示别人的详细信息
# offset是其他用户的name
index=get_template('index_of_others.html')
user=User.objects.get(id=int(offset))# 从数据库里查找所点击的用户
u=request.session.get('user')# 没登陆的话报错
if u is None:
return HttpResponse("请先登录!")
indexHtml=index.render(Context({'user':user}))
return HttpResponse(indexHtml)
@csrf_exempt
def edit(request):
edit=get_template('edit.html')
user=request.session.get('user')
if user is None:
return HttpResponse("请先登录!")
editHtml=edit.render(Context({'user':user}))
return HttpResponse(editHtml)
@csrf_exempt
def edit_result(request):# 编辑页面返回的结果
sex= request.POST['sex']# 从前台的表单中拿回各种数据
sec=request.POST['sec']
college= request.POST['college']
major= request.POST['major']
grade= request.POST['grade']
phone= request.POST['phone']
qq= request.POST['qq']
province= request.POST['province']
city= request.POST['city']
area= request.POST['area']
campus= request.POST['campus']
wechat= request.POST['wechat']
love= request.POST['love']
dormitory= request.POST['dormitory']
u=request.session.get('user')
email=u.email
user=User.objects.get(email=email)#数据库里拿到所编辑的对象
if user is None:
return HttpResponse("请先登录!")
user.sex=sex
user.college=college
user.major=major
user.grade=grade
user.phone=phone
user.qq=qq
user.province=province
user.city=city
user.area=area
user.campus=campus
user.wechat=wechat
user.love=love
user.dormitory=dormitory# 保存修改
user.sec=Section.objects.get(id=sec)
user.save()# 修改后的对象存入数据库
request.session['user']=user# 用新的user替换掉之前旧的session里面的user对象
return HttpResponseRedirect("/index")# 跳转到个人主页
def depart(request,offset):
#depart=get_template('depart.html')
user=request.session.get('user')
if user is None:
return HttpResponse("请先登录!")
if offset=='all' :# 如果访问的网址是 depart/all的话,返回所有的用户信息
#userlst=User.objects.all()
userlst=User.objects.filter(effective = 1)
paginator = Paginator(userlst, 5) # 分页系统,每页显示5个用户
try:
page = int(request.GET.get('page', '1'))# 访问的网址是depart/all/page=?
except ValueError: # 这里的page对象就是“?”后面的数字,用来标记访问的第几页
page = 1# 出错的话直接访问第一页
try:
contacts = paginator.page(page)
except (EmptyPage, InvalidPage):
contacts = paginator.page(paginator.num_pages)
user=request.session.get('user')
#user.name='南微软'
#user.depart='技术部'
isactive='active'
depart=get_template('depart.html')
departHtml=depart.render(Context({'user':user,'contacts':userlst,'isactive1':isactive}));
return HttpResponse(departHtml)
if offset=='pre' or offset=='2':# 如果访问的是depart/pre或者 depart/2,显示主席团的成员信息
userlst=User.objects.filter(sec=2, effective=1)# 主席团的部门id是2,其他与上面相同
user=request.session.get('user')
paginator = Paginator(userlst, 5)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
contacts = paginator.page(page)
except (EmptyPage, InvalidPage):
contacts = paginator.page(paginator.num_pages)
#user.name='南微软'
#user.depart='技术部'
isactive='active'
depart=get_template('depart.html')
departHtml=depart.render(Context({'contacts':userlst,'user':user,'isactive2':isactive}));
return HttpResponse(departHtml)
if offset=='tech' or offset=='1':# 技术部
userlst=User.objects.filter(sec=1, effective=1)
user=request.session.get('user')
paginator = Paginator(userlst, 5)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
contacts = paginator.page(page)
except (EmptyPage, InvalidPage):
contacts = paginator.page(paginator.num_pages)
#user.name='南微软'
#user.depart='技术部'
isactive='active'
depart=get_template('depart.html')
departHtml=depart.render(Context({'contacts':userlst,'user':user,'isactive3':isactive}));
return HttpResponse(departHtml)
if offset=='ope' or offset=='3': #运营部
userlst=User.objects.filter(sec=3, effective=1)
user=request.session.get('user')
paginator = Paginator(userlst, 5)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
contacts = paginator.page(page)
except (EmptyPage, InvalidPage):
contacts = paginator.page(paginator.num_pages)
#user.name='南微软'
#user.depart='技术部'
isactive='active'
depart=get_template('depart.html')
departHtml=depart.render(Context({'contacts':userlst,'user':user,'isactive4':isactive}));
return HttpResponse(departHtml)
if offset=='adv' or offset=='4': #宣传
userlst=User.objects.filter(sec=4, effective=1)
user=request.session.get('user')
paginator = Paginator(userlst, 5)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
contacts = paginator.page(page)
except (EmptyPage, InvalidPage):
contacts = paginator.page(paginator.num_pages)
#user.name='南微软'
#user.depart='技术部'
isactive='active'
depart=get_template('depart.html')
departHtml=depart.render(Context({'contacts':userlst,'user':user,'isactive5':isactive}));
return HttpResponse(departHtml)
# 查询数百具
# 封装对象
#departHtml=depart.render(Context());
#return HttpResponse(departHtml)
if offset=='me':
return HttpResponseRedirect("/index")
if offset=='logout':
return HttpResponseRedirect("/logout")
@csrf_exempt
def reg_result(request): # 注册的结果页面
u=User() # 新建一个User对象,把它存入数据库
password = request.POST['password'] #从表单里拿到密码
if password=='': # 没填密码
return HttpResponse('注册失败!请填写密码')
email = request.POST['email']
if email=='':# 没填邮箱
return HttpResponse('注册失败!请填写邮箱')
name = request.POST['name']
if name=='':
return HttpResponse('注册失败!请填写真实姓名')
invitecode = request.POST['invitecode']
if invitecode=='':
return HttpResponse('注册失败!请填写邀请码')
sec = request.POST['sec']
if sec==u'主席团':
u.sec=Section.objects.get(id=2)
if sec==u'技术部':
u.sec=Section.objects.get(id=1)
if sec==u'运营部':
u.sec=Section.objects.get(id=3)
if sec==u'宣传部':
u.sec=Section.objects.get(id=4)
if sec==u'财务部':
u.sec=Section.objects.get(id=5)
college = request.POST['college']
major = request.POST['major']
entry_year = request.POST['entry_year']
grade = request.POST['grade']
campus = request.POST['campus']
sex = request.POST['sex']
phone = request.POST['phone']
province = request.POST['province']
city = request.POST['city']
area = request.POST['area']
qq = request.POST['qq']
love = request.POST['love']
#city = request.POST['city']
u.school='南开大学'
u.email=email
u.password=hashlib.sha1(password).hexdigest() # 这是生成hash值代替明文的密码
u.name=name
u.college=college
u.major=major
u.entry_year=entry_year
u.grade=grade
u.campus=campus
u.sex=sex
u.phone=phone
u.province=province
u.city=city
u.area=area
u.qq=qq
u.love=love
u.effective=1
u.authority=0
try: # 测试邮箱是否已经被使用过了
User.objects.get(email = email)
except User.DoesNotExist:
pass
else:
return HttpResponse("该邮箱已被注册,请您换一个未被注册过的有效邮箱进行注册!")
try:
c=Code.objects.get(code=invitecode)
if c.effective==0:
return HttpResponse("该邀请码已经被使用过了!请确认您拥有正确的邀请码!")
else:
u.save()
c.effective=0
c.use =User.objects.get(email = email) # 把验证码和用户关联上
c.save()
except Code.DoesNotExist:
return HttpResponse("该邀请码不存在!请确认您拥有正确的邀请码!")
request.session['user']=u # 把user对象放到session里面去
result=get_template('result.html')
resultHtml=result.render(Context())
return HttpResponse(resultHtml)
@csrf_exempt
def login_result(request): # 登陆的结果
password = request.POST['password']
if password=='':
return HttpResponse('登陆失败!请填写密码')
email = request.POST['email']
if email=='':
return HttpResponse('登陆失败!请填写邮箱')
u=User()
u.email=email
u.password=<PASSWORD>
try:
user=User.objects.get(email=email) # user是指从数据库里面查找的邮箱为email的用户
except User.DoesNotExist:
return HttpResponse("账户不存在")
if user.password==hashlib.sha1(u.password).hexdigest(): # u是登陆之时填写的用户
if user.effective == 1:
result=get_template('login_result.html') # 比较数据库的用户的密码和填写的密码是否一致
resultHtml=result.render(Context())
request.session['user']=user
return HttpResponseRedirect("/index")
else:
return HttpResponse("您的帐号已被删除或封停,具体情况请联络技术部负责人予以解决!")
else:
return HttpResponse("密码错误")
def get_paginator(obj,page): # 这个函数不用管它
page_size = 10 #每页显示的数量
after_range_num = 5
before_range_num = 6
context = {}
try:
page = int(page)
if page <1 :
page = 1
except ValueError:
page = 1
paginator = Paginator(obj,page_size)
try:
obj = paginator.page(page)
except(EmptyPage,InvalidPage,PageNotAnInteger):
obj = paginator.page(1)
if page >= after_range_num:
page_range = paginator.page_range[page-after_range_num:page+before_range_num]
else:
page_range = paginator.page_range[0:int(page)+before_range_num]
context["page_objects"]=obj
context["page_range"]=page_range
return context
def logout(requst):# 注销,从session里面删除user对象,并跳转回登陆页面
user=requst.session.get('user')
if user is None:
return HttpResponse("请先登录!")
del requst.session['user']
return HttpResponseRedirect("/login")
def getstr(n):#获得指定长度随机字符串
st = ''
while len(st) < n:
temp = chr(97+random.randint(0,25))
if st.find(temp) == -1 :
st = st.join(['',temp])
return st
def send_mail(to_list,sub,content):
mail_host="smtp.qq.com" #设置服务器
mail_user="<EMAIL>" #用户名
mail_pass="<PASSWORD>" #密码
me="南微软"+"<"+mail_user+">"
msg = MIMEText(content,_subtype='html',_charset='utf-8')
msg['Subject'] = sub
msg['From'] = me
msg['To'] = ";".join(to_list)
try:
server = smtplib.SMTP()
server.connect(mail_host)
server.login(mail_user,mail_pass)
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False
#mailto_list=["<EMAIL>"] # 发送对象的列表
# send_mail(mailto_list,"hello","hello world!")
def send_code(request):
user=request.session.get('user')
if user is None:
return HttpResponse("请先登录!")
elif User.objects.get(id = user.id).authority & AUTHORITY['admin'] == 0: # 这个地方最好以后能改成try形式
return HttpResponse("您不具有管理员资格!")
else:
s_c=get_template('send_code.html',)
s_cHtml=s_c.render(Context())
return HttpResponse(s_cHtml)
@csrf_exempt
def send_code_result(request):
user=request.session.get('user')
if user is None:
return HttpResponse("请先登录!")
elif User.objects.get(id = user.id).authority & AUTHORITY['admin'] == 0: # 这个地方最好以后能改成try形式
return HttpResponse("您不具有管理员资格!")
else:
pass
email_list_raw = request.POST['email_list']
subject = u'南微软通讯录信息录入通知'
msg_t = get_template("mail_invite.html")
email_list = email_list_raw.split('\n')
success = 1
for email_addr in email_list:
code = ''
while True:
code = getstr(8)
try:
Code.objects.get(code=code)
except Code.DoesNotExist:
break
if send_mail([email_addr], subject, msg_t.render(Context({'code':code}))):
c = Code()
c.code = code
c.use = User.objects.get(id=0) # a special user means nobody
c.type = CODE_TYPE['invite']
c.start_time = datetime.now()
c.effective = 1
c.end_time = datetime.now().replace(year=9999) # forever effective
c.save()
else:
success = 0
break
if success:
return HttpResponse("发送邀请码邮件成功!")
else:
return HttpResponse("操作失败!")
|
abe2ae9afc7a5042aad2ac2cb1c3930e963fa4d5
|
[
"Python"
] | 2 |
Python
|
TombRaiderjf/member
|
3bbe2927e76da053af81646d1f61ab6798d1b133
|
e6409a53eecb921a69460734a6fc4746423b5f1b
|
refs/heads/master
|
<file_sep>using Models.CLEM.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Packaging;
namespace Reader
{
public partial class IAT
{
/// <summary>
/// Fodder pools used in the simulation.
/// Keys are the pool ID.
/// Values are the crops stored in the pool
/// </summary>
private static Dictionary<int, string> Pools { get; set; }
/// <summary>
/// Checks if there is fodder that can be bought and ensures there
/// is a pool to store it in
/// </summary>
private void GetBoughtFodderPools()
{
// Look at each fodder type in the table
for (int row = 0; row < Fodder.RowNames.Count; row++)
{
// Check if a fodder type can be bought
double unit = Fodder.GetData<double>(row, 0);
int month = Fodder.GetData<int>(row, 1);
if ((unit > 0) && (month > 0))
{
// Create appropriate storage pool if none exists
int pool = Fodder.GetData<int>(row, 4);
string cropname = FodderSpecs.RowNames[row + 1];
if (!Pools.ContainsKey(pool)) Pools.Add(pool, cropname);
else Pools[pool] = Pools[pool] + $", {cropname}";
}
}
}
/// <summary>
/// Builds the list of animal fodder pools used in the simulation,
/// and stores the ID of the crops grown
/// </summary>
private void GetGrownFodderPools()
{
WorksheetPart crop = (WorksheetPart)Book.GetPartById(SearchSheets("crop_inputs").Id);
var rows = crop.Worksheet.Descendants<Row>().Skip(1);
// Attempt to find the fodder pool for each crop
foreach (int id in GrainIDs)
{
// Check if the crop has residue
if (CropsGrown.GetData<double>(4, id) <= 0) continue;
// Find the cropname
string cropname = CropSpecs.RowNames.ElementAt(id + 1);
// Check data was found
int pool = 0;
if (rows.Any(r => TestRow(id, r)))
{
// Select the first row of the valid inputs
Cell input = rows.First(r => TestRow(id, r)).Descendants<Cell>().ElementAt(10);
// Find what pool the residue uses
int.TryParse(ParseCell(input), out pool);
}
else
{
Shared.WriteError(new ErrorData()
{
FileName = Name,
FileType = "IAT",
Message = $"Crop type {cropname} wasn't found in the inputs sheet",
Severity = "Low",
Table = "-",
Sheet = "crop_inputs"
});
}
// If the pool does not exist, create a new pool with the residue in it
if (!Pools.ContainsKey(pool)) Pools.Add(pool, $"{cropname}_Residue");
// If the pool exists already, add the residue to it.
else Pools[pool] = Pools[pool] + $", {cropname}_Residue";
}
}
/// <summary>
/// Tests a row of input data to see if it contains the desired ID
/// </summary>
/// <param name="id">ID to look for</param>
/// <param name="row">Row to search in</param>
private bool TestRow(int id, Row row)
{
Cell cell = row.Descendants<Cell>().ElementAt(2);
string content = ParseCell(cell);
if (content == id.ToString()) return true;
else return false;
}
/// <summary>
/// Model each fodder pool in the AnimalFoodStore
/// </summary>
public IEnumerable<AnimalFoodStoreType> GetAnimalStoreTypes(AnimalFoodStore store)
{
List<AnimalFoodStoreType> types = new List<AnimalFoodStoreType>();
// Add each fodder pool to the animal food store
foreach (int pool in Pools.Keys)
{
types.Add(new AnimalFoodStoreType(store) { Name = Pools[pool] });
}
return types;
}
/// <summary>
/// Model each pool in the HumanFoodStore
/// </summary>
public IEnumerable<HumanFoodStoreType> GetHumanStoreTypes(HumanFoodStore store)
{
List<HumanFoodStoreType> types = new List<HumanFoodStoreType>();
// Add grain products to the store
foreach (int id in GrainIDs)
{
// Check if the crop is stored at home
double home_storage = CropSpecs.GetData<double>(id + 1, 1);
if (home_storage <= 0) continue;
// Add the grain type to the store
types.Add(new HumanFoodStoreType(store) { Name = CropSpecs.RowNames[id + 1] });
}
// Add milk products to the store
foreach (int id in RumIDs)
{
// Check if milk is stored at home
double home_milk = RumSpecs.GetData<double>(18, id);
if (home_milk <= 0) continue;
// Add the milk type to the store
types.Add(new HumanFoodStoreType(store) { Name = RumSpecs.ColumnNames[id] + "_Milk" });
}
return types;
}
/// <summary>
/// Model products sold
/// </summary>
public IEnumerable<ProductStoreType> GetProductStoreTypes(ProductStore store)
{
List<ProductStoreType> products = new List<ProductStoreType>();
var row = CropsGrown.GetRowData<int>(0);
foreach (var id in GrainIDs)
{
int col = row.IndexOf(id);
var sold = CropsGrown.GetData<double>(5, col);
if (sold > 0)
{
products.Add(new ProductStoreType(store)
{
Name = CropSpecs.RowNames[id + 1]
});
}
}
return products;
}
/// <summary>
/// Model fodder available through grazing
/// </summary>
public GrazeFoodStoreType GetGrazeFoodStore(GrazeFoodStore store)
{
return new GrazeFoodStoreType(store);
}
/// <summary>
/// Model fodder available through the common land
/// </summary>
public CommonLandFoodStoreType GetCommonFoodStore(AnimalFoodStore store)
{
// Checks if there is any yield from the common land before adding it to the foodstore
double yield = Convert.ToDouble(GetCellValue(Part, 81, 4));
if (yield > 0) return new CommonLandFoodStoreType(store);
else return null;
}
}
}
<file_sep>using System;
using System.IO;
namespace Reader
{
public static partial class Shared
{
/// <summary>
/// Creates an error log to write to
/// </summary>
/// <param name="filename">The name of the error log</param>
public static void OpenErrorLog()
{
ErrorStream = new FileStream(
$"{OutDir}/ErrorLog.csv",
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.None);
ErrorWriter = new StreamWriter(ErrorStream);
ErrorReader = new StreamReader(ErrorStream);
ErrorCount = 0;
if (ErrorReader.Peek() == -1)
{
ErrorWriter.WriteLine("Error #, File name, Sheet, Table, Cause, Severity, Date");
}
else
{
while (ErrorReader.ReadLine() != null)
{
ErrorCount++;
}
ErrorCount--;
}
}
/// <summary>
/// Writes an error to the log
/// </summary>
/// <param name="message">The message to be written</param>
public static void WriteError(ErrorData ED)
{
ErrorCount++;
ErrorWriter.WriteLine($"{ErrorCount}, {ED.FileName}, {ED.Sheet}, {ED.Table}, {ED.Message}, {ED.Severity}, {DateTime.Now}");
}
/// <summary>
/// Closes the error log
/// </summary>
public static void CloseErrorLog()
{
ErrorWriter.Close();
return;
}
}
public struct ErrorData
{
public string FileName;
public string FileType;
public string Message;
public string Severity;
public string Table;
public string Sheet;
}
public class ConversionException : Exception
{
public ConversionException() : base()
{ }
}
}
<file_sep>namespace Models.CLEM.Activities
{
/// <summary>
/// Models the payment of an arbitrary expenditure
/// </summary>
public class FinanceActivityPayExpense : Node
{
public double Amount { get; set; } = 1;
public string AccountName { get; set; } = "Finances.Bank";
public bool IsOverhead { get; set; } = false;
public int OnPartialresourcesAvailableAction { get; set; } = 0;
public FinanceActivityPayExpense(Node parent) : base(parent)
{ }
}
/// <summary>
/// Models the calculation of interest
/// </summary>
public class FinanceActivityCalculateInterest : Node
{
public FinanceActivityCalculateInterest(Node parent) : base(parent)
{
Name = "CalculateInterest";
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Windows
{
public partial class FileListItem : UserControl
{
public ComboBox Combo { get { return comboBox; } }
public CheckBox Check { get { return checkBox; } }
public FileListItem(string text)
{
InitializeComponent();
checkBox.Text = text;
}
}
}
<file_sep>using Gtk;
using System;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UI
{
class Program
{
static void Main(string[] args)
{
Tools.SetProjectDirectory();
Application.Init();
MainScreen screen = new MainScreen();
screen.window.ShowAll();
Application.Run();
}
}
}
<file_sep>/*
This file contains all the properties of the IAT class.
*/
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
namespace Reader
{
public partial class IAT
{
public static bool GroupSheets { get; set; }
public static bool GroupSims { get; set; }
/// <summary>
/// Name of the IAT
/// </summary>
public string Name { get; set; }
public SpreadsheetDocument Document { get; set; }
/// <summary>
/// Workbook information derived from a document
/// </summary>
public WorkbookPart Book { get; set; }
/// <summary>
/// The current parameter sheet
/// </summary>
public Sheet ParameterSheet { get; set; }
/// <summary>
/// Data from the current parameter sheet
/// </summary>
private WorksheetPart Part { get; set; }
/// <summary>
/// Contains all unique strings used in cells (accessed via numeric ID)
/// </summary>
private SharedStringTablePart StringTable { get; set; }
/// <summary>
/// Crops grown table
/// </summary>
private SubTable CropsGrown { get; set; }
/// <summary>
/// Crop specifications table
/// </summary>
private SubTable CropSpecs { get; set; }
/// <summary>
/// Forages grown table
/// </summary>
private SubTable ForagesGrown { get; set; }
/// <summary>
/// Forage specification table
/// </summary>
private SubTable ForageSpecs { get; set; }
/// <summary>
/// Land specification table
/// </summary>
private SubTable LandSpecs { get; set; }
/// <summary>
/// Labour supply/hire table
/// </summary>
private SubTable LabourSupply { get; set; }
/// <summary>
/// Startup ruminant numbers table
/// </summary>
private SubTable RumNumbers { get; set; }
/// <summary>
/// Startup ruminant ages table
/// </summary>
private SubTable RumAges { get; set; }
/// <summary>
/// Startup ruminant weights table
/// </summary>
private SubTable RumWeights { get; set; }
/// <summary>
/// Ruminant specifications
/// </summary>
public SubTable RumSpecs { get; set; }
/// <summary>
/// The Ruminant coefficients table
/// </summary>
/// <remarks>
/// This property isn't referenced directly, but through reflection.
/// DO NOT REMOVE.
/// </remarks>
public SubTable RumCoeffs { get; set; }
/// <summary>
/// Ruminant prices
/// </summary>
private SubTable RumPrices { get; set; }
/// <summary>
/// Financial overheads table
/// </summary>
private SubTable Overheads { get; set; }
/// <summary>
/// Bought fodder table
/// </summary>
private SubTable Fodder { get; set; }
/// <summary>
/// Bought fodder specifications table
/// </summary>
private SubTable FodderSpecs { get; set; }
/// <summary>
/// Climate region of the simulation
/// </summary>
private string Climate { get; set; } = "1";
/// <summary>
/// IDs of all grains present in the simulation
/// </summary>
private List<int> GrainIDs { get; set; }
/// <summary>
/// IDs of all ruminant types present in the simulation
/// </summary>
private List<int> RumIDs { get; set; }
private bool disposed = false;
}
}
<file_sep>using Models.CLEM.Groupings;
using Models.CLEM.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Reader
{
public partial class NABSA
{
public IEnumerable<LabourType> GetLabourTypes(Labour labour)
{
List<LabourType> types = new List<LabourType>();
var number = Priority.Elements().ToArray();
for (int i = 2; i < number.Length; i++)
{
var ndata = number[i].Elements().ToArray();
if (number[i].Elements().First().Value != "0")
{
string name = number[i].Name.LocalName;
// Find the age of the labourer
int age = name.Contains("Elderly") ? 65
: (name.Contains("Teenager") ? 15
: (name.Contains("Child") ? 8 : 40));
// Find the gender of the labourer
int gender = name.Contains("F") ? 1 : 0;
types.Add(new LabourType(labour)
{
Name = number[i].Name.LocalName,
InitialAge = age,
Gender = gender,
Individuals = Convert.ToInt32(ndata[0].Value)
});
}
}
return types.AsEnumerable();
}
public IEnumerable<LabourAvailabilityItem> GetAvailabilityItems(LabourAvailabilityList list)
{
List<LabourAvailabilityItem> items = new List<LabourAvailabilityItem>();
for (int i = 2; i < Supply.Elements().Count(); i++)
{
XElement group = Supply.Elements().ElementAt(i);
// Skip this item if it has zero-value
string value = group.Elements().First().Value;
if (value == "0") continue;
string name = group.Name.LocalName;
LabourAvailabilityItem item = new LabourAvailabilityItem(list)
{
Name = name,
Value = Convert.ToDouble(value)
};
item.Add(new LabourFilter(item)
{
Value = name
});
items.Add(item);
}
return items.AsEnumerable();
}
}
}
<file_sep>using System;
using System.ComponentModel;
using System.IO;
namespace Reader
{
public static partial class Shared
{
public static BackgroundWorker Worker = null;
public static string InDir { get; set; } = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
public static string OutDir { get; set; } = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
/// <summary>
/// The error log file stream
/// </summary>
private static FileStream ErrorStream;
private static StreamReader ErrorReader;
/// <summary>
/// The error log stream writer
/// </summary>
private static StreamWriter ErrorWriter;
/// <summary>
/// The number of errors made
/// </summary>
private static int ErrorCount = 0;
}
}
<file_sep>namespace Models.CLEM.Resources
{
/// <summary>
/// Container for land resources
/// </summary>
public class Land : Node
{
public string UnitsOfArea { get; set; } = "hectares";
public double UnitsOfAreaToHaConversion { get; set; } = 1.0;
public Land(ResourcesHolder parent) : base(parent)
{
Name = "Land";
Add(Source.GetLandTypes(this));
}
}
/// <summary>
/// Models a generic land resource type
/// </summary>
public class LandType : Node
{
public double LandArea { get; set; }
public double PortionBuildings { get; set; }
public double ProportionOfTotalArea { get; set; }
public int SoilType { get; set; }
public LandType(Land parent) : base(parent)
{ }
}
}
<file_sep>using Models.Core;
using Newtonsoft.Json;
using System.IO;
namespace Reader
{
public static partial class Shared
{
public static void WriteApsimX(Simulations simulations, string name)
{
using (StreamWriter stream = new StreamWriter($"{OutDir}\\{name}.apsimx"))
using (JsonWriter writer = new JsonTextWriter(stream))
{
writer.CloseOutput = true;
writer.AutoCompleteOnClose = true;
JsonSerializer serializer = new JsonSerializer()
{
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.Objects
};
serializer.Serialize(writer, simulations);
serializer = null;
simulations.Dispose();
}
}
}
}
<file_sep>using Reader;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace Windows
{
public partial class Converter : Form
{
private List<string> nabsa = new List<string>();
private List<Tuple<string, string>> iat = new List<Tuple<string, string>>();
public Converter()
{
InitializeComponent();
backgroundConverter.WorkerReportsProgress = true;
backgroundConverter.WorkerSupportsCancellation = true;
backgroundConverter.DoWork += new DoWorkEventHandler(BeginConversion);
backgroundConverter.ProgressChanged += new ProgressChangedEventHandler(ProgressUpdate);
backgroundConverter.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedConversion);
FormClosed += new FormClosedEventHandler(CloseConverter);
}
public void UpdateSettings()
{
var settings = ConverterSettings.Read();
Shared.InDir = settings.InDirectory;
Shared.OutDir = settings.OutDirectory;
includeIAT.Checked = settings.IncludeIAT;
groupSheets.Checked = settings.GroupSheets;
groupSimulations.Checked = settings.GroupSims;
includeNABSA.Checked = settings.IncludeNABSA;
}
public void UpdateFileList()
{
panel.Controls.Clear();
List<FileListItem> items = new List<FileListItem>();
// Protect against invalid input directory
Directory.CreateDirectory(Shared.InDir);
var files = Directory.EnumerateFiles(Shared.InDir, "*.*", SearchOption.TopDirectoryOnly)
.Select(p => Path.GetFileName(p))
.Where(f => !f.StartsWith("~$"))
.Where(f =>
(includeIAT.Checked && f.EndsWith(".xlsx")) ||
(includeNABSA.Checked && f.EndsWith(".nabsa"))
);
int i = 0;
foreach (string file in files)
{
FileListItem item = new FileListItem(file)
{
Anchor = AnchorStyles.Top,
Location = new Point(0, i * 25)
};
if (file.Contains(".nabsa")) item.Combo.Visible = false;
if (file.Contains(".xlsx"))
{
var sheets = GetSheets(file);
if (sheets != null) item.Combo.Items.AddRange(sheets);
}
items.Add(item);
i++;
}
panel.Controls.AddRange(items.ToArray());
panel.Refresh();
}
private string[] GetSheets(string file)
{
try
{
using (SpreadsheetDocument document = SpreadsheetDocument.Open(file, false))
{
WorkbookPart part = document.WorkbookPart;
var sheets = part.Workbook.Descendants<Sheet>()
.Where(s => !s.Name.ToString().ToLower().Contains("input"))
.Select(s => s.Name.ToString())
.ToArray();
return sheets;
}
}
catch (IOException)
{
}
return null;
}
private void Converter_Load(object sender, EventArgs e)
{
UpdateSettings();
UpdateFileList();
btnInput.ToolTipText = "Directory containing files to convert:\n" + Shared.InDir;
btnOutput.ToolTipText = "Directory where output is saved:\n" + Shared.OutDir;
}
private void BtnInput_Click(object sender, EventArgs e)
{
folderBrowserDialog.SelectedPath = Shared.InDir;
DialogResult result = folderBrowserDialog.ShowDialog();
if(result == DialogResult.OK)
{
Shared.InDir = folderBrowserDialog.SelectedPath;
btnInput.ToolTipText = "Directory containing files to convert:\n" + Shared.InDir;
UpdateFileList();
}
}
private void BtnOutput_Click(object sender, EventArgs e)
{
folderBrowserDialog.SelectedPath = Shared.OutDir;
DialogResult result = folderBrowserDialog.ShowDialog();
if (result == DialogResult.OK)
{
Shared.OutDir = folderBrowserDialog.SelectedPath;
btnOutput.ToolTipText = "Directory where output is saved:\n" + Shared.OutDir;
}
}
private void BtnSelect_Click(object sender, EventArgs e)
{
var items = panel.Controls.OfType<FileListItem>();
bool check = true;
if (!items.Any(i => i.Check.Checked == false)) check = false;
foreach (var item in items) item.Check.Checked = check;
}
private void BtnConvert_Click(object sender, EventArgs e)
{
ToggleEnabled();
// Find all the items which the user selected
var selected = panel.Controls.OfType<FileListItem>()
.Where(i => i.Check.Checked);
// Reset trackers
int sheets = 0;
nabsa.Clear();
iat.Clear();
foreach (var selection in selected)
{
// Find the full file path
string file = Shared.InDir + "/" + selection.Check.Text;
if (file.EndsWith(".nabsa"))
{
nabsa.Add(file);
}
else if(file.EndsWith(".xlsx"))
{
string sheet = selection.Combo.Text;
iat.Add(new Tuple<string, string>(file, sheet));
if (sheet != "All") sheets++;
else
{
int count = selection.Combo.Items
.OfType<string>()
.Where(
s => s
.ToLower()
.Contains("param"))
.Count();
sheets += count;
}
}
}
progressBar.Value = 0;
progressBar.Maximum = iat.Count() + nabsa.Count() + sheets;
// Start the asynchronous operation.
backgroundConverter.RunWorkerAsync();
}
private void BtnCancel_Click(object sender, EventArgs e)
{
// Cancel the asynchronous operation.
backgroundConverter.CancelAsync();
}
private void BeginConversion(object sender, EventArgs e)
{
// Protects against potentially deleted paths
Directory.CreateDirectory(Shared.OutDir);
Shared.Worker = sender as BackgroundWorker;
IAT.GroupSheets = groupSheets.Checked;
IAT.GroupSims = groupSimulations.Checked;
IAT.Run(iat);
NABSA.Run(nabsa);
}
private void ProgressUpdate(object sender, EventArgs e)
{
progressBar.PerformStep();
progressBar.Refresh();
}
private void CompletedConversion(object sender, EventArgs e)
{
progressBar.Value = 0;
ToggleEnabled();
}
private void CloseConverter(object sender, EventArgs e)
{
ConverterSettings settings = new ConverterSettings()
{
InDirectory = Shared.InDir,
OutDirectory = Shared.OutDir,
IncludeIAT = includeIAT.Checked,
GroupSheets = groupSheets.Checked,
GroupSims = groupSimulations.Checked,
IncludeNABSA = includeNABSA.Checked
};
settings.Write();
}
private void ToggleEnabled()
{
btnCancel.Enabled = !btnCancel.Enabled;
btnConvert.Enabled = !btnConvert.Enabled;
toolStrip.Enabled = !toolStrip.Enabled;
menuStrip.Enabled = !menuStrip.Enabled;
panel.Enabled = !panel.Enabled;
}
}
}
<file_sep>using Models;
using Models.CLEM.Activities;
using Models.CLEM.Groupings;
using Models.CLEM.Resources;
using System;
using System.Collections.Generic;
namespace Reader
{
public partial class IAT
{
/// <summary>
/// Tracks the breed that is having its data read
/// </summary>
private int RumActiveID { get; set; }
/// <summary>
/// Contains a mapping from one IAT parameter to one CLEM parameter
/// </summary>
private struct Map
{
public string Table;
public string ParamIAT;
public string ParamCLEM;
public double Proportion;
public Map(string table, string paramIAT, string paramCLEM, double proportion)
{
Table = table;
ParamIAT = paramIAT;
ParamCLEM = paramCLEM;
Proportion = proportion;
}
}
/// <summary>
/// Hardcoded list of all IAT to CLEM mappings.
/// </summary>
private readonly List<Map> Maps = new List<Map>()
{
new Map("RumCoeffs", "SRW", "SRWFemale", 1),
new Map("RumCoeffs", "birth_SRW", "SRWBirth", 1),
new Map("RumCoeffs", "Critical_cow_wt", "CriticalCowWeight", 0.01),
new Map("RumCoeffs", "grwth_coeff1", "AgeGrowthRateCoefficient", 1),
new Map("RumCoeffs", "grwth_coeff2", "SRWGrowthScalar", 1),
new Map("RumCoeffs", "km_coeff", "EMaintEfficiencyCoefficient", 1),
new Map("RumCoeffs", "km_incpt", "EMaintEfficiencyIntercept", 1),
new Map("RumCoeffs", "kg_coeff", "EGrowthEfficiencyCoefficient", 1),
new Map("RumCoeffs", "kg_incpt", "EGrowthEfficiencyIntercept", 1),
new Map("RumCoeffs", "kl_coeff", "ELactationEfficiencyCoefficient", 1),
new Map("RumCoeffs", "kl_incpt", "ELactationEfficiencyIntercept", 1),
new Map("RumCoeffs", "kme", "Kme", 1),
new Map("RumCoeffs", "intake_coeff", "IntakeCoefficient", 1),
new Map("RumCoeffs", "intake_incpt", "IntakeIntercept", 1),
new Map("RumCoeffs", "IPI_coeff", "InterParturitionIntervalCoefficient", 1),
new Map("RumCoeffs", "IPI_incpt", "InterParturitionIntervalIntercept", 1),
new Map("RumCoeffs", "birth_rate_coeff", "ConceptionRateCoefficient", 1),
new Map("RumCoeffs", "birth_rate_incpt", "ConceptionRateIntercept", 1),
new Map("RumCoeffs", "birth_rate_assym", "ConceptionRateAsymptote", 1),
new Map("RumCoeffs", "juvenile_mort_coeff", "JuvenileMortalityCoefficient", 1),
new Map("RumCoeffs", "juvenile_mort_exp", "JuvenileMortalityExponent", 1),
new Map("RumCoeffs", "juvenile_mort_max", "JuvenileMortalityMaximum", 0.01),
new Map("RumCoeffs", "wool_coeff", "WoolCoefficient", 1),
new Map("RumCoeffs", "cashmere_coeff", "CashmereCoefficient", 1),
new Map("RumCoeffs", "Rum_gest_int", "GestationLength", 1),
new Map("RumCoeffs", "Milk_offset_day", "MilkOffsetDay", 1),
new Map("RumCoeffs", "Milk_Peak_day", "MilkPeakDay", 1),
new Map("RumCoeffs", "Milk_Curve_suck", "MilkCurveSuckling", 1),
new Map("RumCoeffs", "Milk_Curve_nonsuck", "MilkCurveNonSuckling", 1),
new Map("RumCoeffs", "protein_coeff", "ProteinCoefficient", 1),
new Map("RumCoeffs", "protein_degrad", "ProteinDegradability", 1),
new Map("RumCoeffs", "milk_intake_coeff", "MilkIntakeCoefficient", 1),
new Map("RumCoeffs", "milk_intake_incpt", "MilkIntakeIntercept", 1),
new Map("RumSpecs", "Mortality_base", "MortalityBase", 0.01),
new Map("RumSpecs", "Twin_rate", "TwinRate", 1),
new Map("RumSpecs", "Joining_age", "MinimumAge1stMating", 1),
new Map("RumSpecs", "Joining_size", "MinimumSize1stMating", 0.01),
new Map("RumSpecs", "Milk_max", "MilkPeakYield", 1),
new Map("RumSpecs", "Milk_end", "MilkingDays", 30)
};
/// <summary>
/// If a breed has any cohorts, add its column to the master list
/// </summary>
private void SetRuminants()
{
RumIDs = new List<int>();
int col = -1;
foreach (string breed in RumNumbers.ColumnNames)
{
col++;
var n = RumNumbers.GetColData<double>(col);
if (n.Exists(v => v > 0)) RumIDs.Add(col);
}
}
/// <summary>
/// Map the IAT parameters to their CLEM counterpart
/// </summary>
public void SetParameters(RuminantType ruminant)
{
foreach(var map in Maps)
{
// Find the subtable which contains the parameter
var table = this.GetType().GetProperty(map.Table).GetValue(this, null) as SubTable;
// Find the row which contains the parameter (if it exists)
int row = table.RowNames.FindIndex(s => s == map.ParamIAT);
if (row < 0) continue;
// Convert the value of the parameter to CLEM
double value = table.GetData<double>(row, RumActiveID) * map.Proportion;
// Set the value of the CLEM parameter
ruminant.GetType().GetProperty(map.ParamCLEM).SetValue(ruminant, value);
}
}
/// <summary>
/// Model all present ruminant breeds
/// </summary>
public IEnumerable<RuminantType> GetRuminants(RuminantHerd parent)
{
List<RuminantType> ruminants = new List<RuminantType>();
// Iterate over all the present breeds
foreach (int id in RumIDs)
{
RumActiveID = id;
string breed = RumNumbers.ColumnNames[id].Replace(".", "");
RuminantType ruminant = new RuminantType(parent)
{
Name = breed,
Breed = breed
};
SetParameters(ruminant);
ruminants.Add(ruminant);
}
return ruminants;
}
/// <summary>
/// Model all present cohorts of a given ruminant breed
/// </summary>
public IEnumerable<RuminantTypeCohort> GetCohorts(RuminantInitialCohorts parent)
{
List<RuminantTypeCohort> cohorts = new List<RuminantTypeCohort>();
int row = -1;
foreach (string cohort in RumNumbers.RowNames)
{
row++;
if (RumNumbers.GetData<string>(row, RumActiveID) != "0")
{
// Check gender
int gender = 0;
if (cohort.Contains("F")) gender = 1;
// Check suckling
bool suckling = false;
if (cohort.Contains("Calf")) suckling = true;
// Check breeding sire
bool sire = false;
if (cohort.Contains("ires")) sire = true;
cohorts.Add(new RuminantTypeCohort(parent)
{
Name = cohort,
Gender = gender,
Age = (int)Math.Ceiling(RumAges.GetData<double>(row, RumActiveID)),
Number = (int)Math.Ceiling(RumNumbers.GetData<double>(row, RumActiveID)),
Weight = RumWeights.GetData<double>(row, RumActiveID),
Suckling = suckling,
Sire = sire
});
}
}
return cohorts;
}
/// <summary>
/// Model the price of each present cohort for a given breed
/// </summary>
/// <param name="parent"></param>
/// <returns></returns>
public IEnumerable<AnimalPriceGroup> GetAnimalPrices(AnimalPricing parent)
{
List<AnimalPriceGroup> prices = new List<AnimalPriceGroup>();
double sire_price = 0;
int row = -1;
foreach (string cohort in RumNumbers.RowNames)
{
row++;
if (RumNumbers.GetData<double>(row, RumActiveID) != 0)
{
if (!cohort.ToLower().Contains("sire")) sire_price = RumPrices.GetData<double>(row, RumActiveID);
var group = new AnimalPriceGroup(parent)
{
Name = cohort,
Value = RumPrices.GetData<double>(row, RumActiveID)
};
// Filter cohort based on gender
group.Add(new RuminantFilter(group)
{
Name = "GenderFilter",
Parameter = 2,
Value = cohort.ToLower().Contains("f") ? "Female" : "Male"
});
// Filter cohort based on age
group.Add(new RuminantFilter(group)
{
Name = "AgeFilter",
Parameter = 3,
Operator = 5,
Value = RumAges.GetData<string>(row, RumActiveID)
});
prices.Add(group);
}
}
parent.SirePrice = sire_price;
return prices;
}
/// <summary>
/// Model the management activities for each breed
/// </summary>
public IEnumerable<ActivityFolder> GetManageBreeds(ActivityFolder herd)
{
List<ActivityFolder> breeds = new List<ActivityFolder>();
foreach (int id in RumIDs)
{
// Add a new folder for individual breed
ActivityFolder breed = new ActivityFolder(herd)
{
Name = "Manage " + RumSpecs.ColumnNames[id]
};
// Manage breed numbers
RuminantActivityManage numbers = new RuminantActivityManage(breed)
{
MaximumBreedersKept = RumSpecs.GetData<int>(2, id),
MinimumBreedersKept = RumSpecs.GetData<int>(38, id),
MaximumBreedingAge = RumSpecs.GetData<int>(3, id),
MaximumBullAge = RumSpecs.GetData<double>(25, id),
MaleSellingAge = RumSpecs.GetData<double>(5, id),
MaleSellingWeight = RumSpecs.GetData<double>(6, id)
};
numbers.Add(new ActivityTimerInterval(numbers)
{
Name = "NumbersTimer",
Interval = 12,
MonthDue = 12
});
breed.Add(numbers);
// Manage breed weaning
breed.Add(new RuminantActivityWean(breed)
{
WeaningAge = RumSpecs.GetData<double>(7, id),
WeaningWeight = RumSpecs.GetData<double>(8, id)
});
// Manage breed milking
if (RumSpecs.GetData<double>(18, id) > 0) breed.Add(new RuminantActivityMilking(breed)
{
Name = "Milk",
ResourceTypeName = "HumanFoodStore." + RumSpecs.ColumnNames[id] + "_Milk"
});
// Manage sale of dry breeders
breed.Add(new RuminantActivitySellDryBreeders(breed)
{
MonthsSinceBirth = RumSpecs.GetData<double>(32, id),
ProportionToRemove = RumSpecs.GetData<double>(4, id) * 0.01
});
breeds.Add(breed);
}
return breeds;
}
}
}<file_sep>namespace Models.CLEM.Resources
{
/// <summary>
/// Container for labour resources
/// </summary>
public class Labour : Node
{
public bool AllowAging { get; set; } = true;
public Labour(ResourcesHolder parent) : base(parent)
{
Name = "Labour";
Add(Source.GetLabourTypes(this));
Add(new LabourAvailabilityList(this));
}
}
/// <summary>
/// Models a generic labour resource type
/// </summary>
public class LabourType : Node
{
public double InitialAge { get; set; }
public int Gender { get; set; } = 0;
public int Individuals { get; set; } = 1;
public string Units { get; set; }
public LabourType(Labour parent) : base(parent)
{ }
}
/// <summary>
/// Models the availability of a given labour resource
/// </summary>
public class LabourAvailabilityList : Node
{
public LabourAvailabilityList(Labour parent) : base(parent)
{
Name = "LabourAvailabilityList";
Add(Source.GetAvailabilityItems(this));
}
}
/// <summary>
/// Models the number of available working days for a labour class
/// </summary>
public class LabourAvailabilityItem : Node
{
public double Value { get; set; }
public LabourAvailabilityItem(LabourAvailabilityList parent) : base(parent)
{
}
}
}
<file_sep>namespace Models.CLEM.Resources
{
/// <summary>
/// Container for financial resources
/// </summary>
public class Finance : Node
{
public string CurrencyName { get; set; }
public Finance(ResourcesHolder parent) : base(parent)
{
Name = "Finance";
Source.SetFinanceData(this);
Add(new FinanceType(this));
}
}
/// <summary>
/// Models a generic financial resource type
/// </summary>
public class FinanceType : Node
{
public double OpeningBalance { get; set; }
public bool EnforceWithdrawalLimt { get; set; }
public double WithdrawalLimit { get; set; } = 0.0;
public double InterestRateCharged { get; set; } = 0.0;
public double InterestRatePaid { get; set; } = 0.0;
public string Units { get; set; }
public FinanceType(Finance parent) : base(parent)
{
Source.SetBankData(this);
}
}
}
<file_sep>namespace Models.CLEM.Activities
{
/// <summary>
/// Models the labour requirement for an activity
/// </summary>
class LabourRequirement : Node
{
public double LabourPerUnit { get; set; } = 0.75;
public double UnitSize { get; set; } = 25.0;
public bool WholeUnitBlocks { get; set; } = false;
public int UnitType { get; set; } = 5;
public double MinimumPerPerson { get; set; } = 1.0;
public double MaximumPerPerson { get; set; } = 100.0;
public bool LabourShortfallAffectsActivity { get; set; } = false;
public bool ApplyToAll { get; set; } = false;
public LabourRequirement(Node parent) : base(parent)
{ }
}
}
<file_sep>using Models.CLEM.Groupings;
namespace Models.CLEM.Activities
{
/// <summary>
/// Models the breeding of ruminants
/// </summary>
public class RuminantActivityBreed : ActivityNode
{
public double MaximumConceptionRateUncontrolled { get; set; } = 0.8;
public RuminantActivityBreed(Node parent) : base(parent)
{
Name = "Breed";
}
}
/// <summary>
/// Models the sale and purchase of ruminants
/// </summary>
public class RuminantActivityBuySell : ActivityNode
{
public string BankAccountName { get; set; } = "Finances.Bank";
public RuminantActivityBuySell(Node parent) : base(parent)
{
Name = "BuySell";
}
}
/// <summary>
/// Models the feeding of ruminants
/// </summary>
public class RuminantActivityFeed : ActivityNode
{
public string FeedTypeName { get; set; }
public double ProportionTramplingWastage { get; set; } = 0.3;
public string FeedStyle { get; set; } = "ProportionOfPotentialIntake";
public RuminantActivityFeed(Node parent) : base(parent)
{ }
}
/// <summary>
/// Models ruminants grazing
/// </summary>
public class RuminantActivityGrazeAll : ActivityNode
{
public double HoursGrazed { get; set; } = 8.0;
public RuminantActivityGrazeAll(Node parent) : base(parent)
{
Name = "GrazeAll";
OnPartialResourcesAvailableAction = 2;
var labour = new LabourRequirement(this);
var group = new LabourFilterGroup(labour);
var filter = new LabourFilter(group)
{
Parameter = 0,
Operator = 0,
Value = "Male"
};
group.Add(filter);
labour.Add(group);
}
}
/// <summary>
/// Models the growth of ruminants
/// </summary>
public class RuminantActivityGrow : ActivityNode
{
public double EnergyGross { get; set; } = 18.4;
public RuminantActivityGrow(Node parent) : base(parent)
{
Name = "GrowAll";
}
}
/// <summary>
/// Models the management of herd numbers/size
/// </summary>
public class RuminantActivityManage : ActivityNode
{
public int MaximumBreedersKept { get; set; } = 8;
public int MinimumBreedersKept { get; set; } = 4;
public int MaximumBreedingAge { get; set; } = 144;
public double MaximumProportionBreedersPerPurchase { get; set; } = 1;
public int NumberOfBreederPurchaseAgeClasses { get; set; } = 1;
public double MaximumSiresKept { get; set; } = 0;
public double MaximumBullAge { get; set; } = 96;
public bool AllowSireReplacement { get; set; } = false;
public int MaximumSiresPerPurchase { get; set; } = 0;
public double MaleSellingAge { get; set; } = 1;
public double MaleSellingWeight { get; set; } = 450;
public string GrazeFoodStoreName { get; set; } = "GrazeFoodStore.NativePasture";
public bool SellFemalesLikeMales { get; set; } = false;
public bool ContinuousMaleSales { get; set; } = false;
public RuminantActivityManage(Node parent) : base(parent)
{
Name = "Manage numbers";
}
}
/// <summary>
/// Models the milking of ruminants
/// </summary>
public class RuminantActivityMilking : ActivityNode
{
public string ResourceTypeName { get; set; } = "HumanFoodStore.Milk";
public RuminantActivityMilking(Node parent) : base(parent)
{ }
}
/// <summary>
/// Models the mustering of ruminants
/// </summary>
public class RuminantActivityMuster : ActivityNode
{
public string ManagedPastureName { get; set; } = "GrazeFoodStore.NativePasture";
public bool PerformAtStartOfSimulation { get; set; } = true;
public bool MoveSucklings { get; set; } = true;
public RuminantActivityMuster(Node parent) : base(parent)
{
Name = "Muster";
}
}
/// <summary>
/// Models the sale of dry breeders
/// </summary>
public class RuminantActivitySellDryBreeders : ActivityNode
{
public double MinimumConceptionBeforeSell { get; set; } = 1.0;
public double MonthsSinceBirth { get; set; } = 0.0;
public double ProportionToRemove { get; set; } = 0.0;
public RuminantActivitySellDryBreeders(Node parent) : base(parent)
{
Name = "SellDryBreeders";
}
}
/// <summary>
/// Models the weaning of calves
/// </summary>
public class RuminantActivityWean : ActivityNode
{
public double WeaningAge { get; set; } = 0.0;
public double WeaningWeight { get; set; } = 0.0;
public string GrazeFoodStoreName { get; set; } = null;
public string HerdFilters { get; set; } = null;
public RuminantActivityWean(Node parent) : base(parent)
{
Name = "Wean";
}
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Reader
{
/// <summary>
/// A collection of methods for querying
/// an XElement object for specific data
/// </summary>
public partial class NABSA
{
/// <summary>
/// Selects the first descendant with the given name
/// (intended for finding descendants with unique names)
/// </summary>
/// <returns></returns>
public static XElement FindFirst(XElement xml, string descendant)
{
var q =
from el
in xml.Descendants(descendant)
select el;
return q.First();
}
/// <summary>
/// Searches an XElement for a descendant which stores
/// its name in a child element called 'Name'
/// </summary>
/// <param name="xml"></param>
/// <param name="name"></param>
public static XElement FindByNameTag(XElement xml, string name)
{
var q =
from el
in xml.Descendants()
where el.Elements().Any(e => e.Value == name)
select el;
return q.First();
}
/// <summary>
///
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static IEnumerable<string> GetElementNames(XElement xml)
{
var q =
from el
in xml.Elements()
select el.Name.LocalName;
return q;
}
/// <summary>
///
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static IEnumerable<string> GetElementValues(XElement xml)
{
var q =
from el
in xml.Elements()
select el.Value;
return q;
}
}
}
<file_sep>using Models.CLEM.Activities;
using Models.CLEM.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Reader
{
// Implements all methods related to IAT finance
public partial class IAT
{
/// <summary>
/// Sets the currency data for a Finance model using IAT data
/// </summary>
/// <param name="finance">The base model</param>
public void SetFinanceData(Finance finance)
{
int id = Convert.ToInt32(GetCellValue(Part, 4, 9));
finance.CurrencyName = GetCellValue(Part, 4 + id, 8);
}
/// <summary>
/// Sets the data for a FinanceType model using IAT data
/// </summary>
/// <param name="bank">The base model</param>
public void SetBankData(FinanceType bank)
{
bank.Name = "Bank";
bank.OpeningBalance = Overheads.GetData<double>(12, 0);
bank.InterestRateCharged = Overheads.GetData<double>(11, 0);
}
/// <summary>
/// Gets the monthly living expenses from the IAT data
/// </summary>
/// <param name="cashflow">The model to attach the data to</param>
public ActivityFolder GetMonthlyExpenses(ActivityFolder cashflow)
{
var monthly = new ActivityFolder(cashflow)
{
Name = "MonthlyExpenses"
};
// Find the monthly living cost
double amount = Overheads.GetData<double>(13, 0);
// Only include if non-zero
if (amount == 0) return null;
monthly.Add(new FinanceActivityPayExpense(monthly)
{
Name = "LivingCost",
Amount = amount
});
return monthly;
}
/// <summary>
/// Return a collection of the annual expenses from the IAT data
/// </summary>
/// <param name="cashflow">The base model</param>
public ActivityFolder GetAnnualExpenses(ActivityFolder cashflow)
{
var annual = new ActivityFolder(cashflow)
{
Name = "AnnualExpenses"
};
// Names of the expenses
var rows = Overheads.RowNames;
// Amounts of the expenses
var amounts = Overheads.GetColData<double>(0);
// Look at each row in the overheads table
foreach (string row in rows)
{
// The overheads table contains more than just annual data,
// so stop at the "Int_rate" row (table is ordered)
if (row == "Int_rate") break;
// Find the upkeep amount
int index = rows.FindIndex(s => s == row);
double amount = amounts.ElementAt(index);
// Only need to add the element if its a non-zero expenditure
if (amount > 0)
{
annual.Add(new FinanceActivityPayExpense(annual)
{
Name = row.Replace("_", ""),
Amount = amount
});
}
}
// If there are no annual expenses, ignore this folder
if (annual.Children.Count == 0) return null;
return annual;
}
/// <summary>
/// Return the interest rate calculation model
/// </summary>
/// <param name="cashflow">The base model</param>
public FinanceActivityCalculateInterest GetInterestRates(ActivityFolder cashflow)
{
// Find the interest amount
int row = Overheads.RowNames.FindIndex(s => s == "Int_rate");
// If the interest is 0, ignore the model
if (Overheads.GetData<int>(row, 0) == 0) return null;
return new FinanceActivityCalculateInterest(cashflow);
}
}
}
<file_sep>using Models.CLEM.Activities;
using Models.CLEM.Resources;
using System.Collections.Generic;
namespace Reader
{
public partial class IAT
{
private double TotalArea { get; set; }
/// <summary>
/// Models the different land types
/// </summary>
/// <param name="parent"></param>
public IEnumerable<LandType> GetLandTypes(Land parent)
{
List<LandType> types = new List<LandType>();
// Iterate over the rows in the table
int row = -1;
foreach (string item in LandSpecs.RowNames)
{
row++;
// Skip empty land types
if (LandSpecs.GetData<string>(row, 0) == "0") continue;
double area = LandSpecs.GetData<double>(row, 0);
// Create a new type model based on the current row
types.Add(new LandType(parent)
{
Name = LandSpecs.RowNames[row],
LandArea = area,
PortionBuildings = LandSpecs.GetData<double>(row, 1),
ProportionOfTotalArea = area / TotalArea,
SoilType = LandSpecs.GetData<int>(row, 3)
});
}
return types;
}
/// <summary>
/// Returns null.
/// </summary>
/// <remarks>
/// Required for the interface, but IAT does not use this component.
/// </remarks>
public PastureActivityManage GetManagePasture(ActivitiesHolder folder)
{
return null;
}
}
}<file_sep>using Models.CLEM.Resources;
using Models.CLEM.Activities;
using Models.CLEM.Reporting;
using System.Collections.Generic;
namespace Models.CLEM
{
/// <summary>
/// Container for a CLEM model
/// </summary>
public class ZoneCLEM : Node
{
public int RandomSeed { get; set; } = 1;
public int ClimateRegion { get; set; }
public int EcologicalIndicatorsCalculationMonth { get; set; } = 12;
public double Area { get; set; }
public double Slope { get; set; } = 0;
public ZoneCLEM(Node parent) : base(parent)
{
Name = "CLEM";
Add(new Memo(this)
{
Name = "Default parameters",
Text = "In the case that the source file is missing values, " +
"most parameters in the simulation have default values. " +
"It is recommended to ensure the validity of all parameters before " +
"running the simulation."
});
Add(Source.GetFiles(this));
Add(new ResourcesHolder(this));
Add(new ActivitiesHolder(this));
AddReports();
}
/// <summary>
/// Adds a series of reports to the CLEM model
/// </summary>
private void AddReports()
{
var reports = new CLEMFolder(this)
{
Name = "Reports"
};
reports.Add(new ReportResourceBalances(reports)
{
VariableNames = new List<string>()
{
"[Clock].Today",
"AnimalFoodStore"
},
EventNames = new List<string>()
{
"[Clock].CLEMEndOfTimeStep"
}
});
reports.Add(new ReportActivitiesPerformed(reports));
reports.Add(new ReportResourceShortfalls(reports));
foreach(Node child in SearchTree<ResourcesHolder>(this).Children)
{
string name = child.Name;
reports.Add(new ReportResourceLedger(reports)
{
VariableNames = new List<string>()
{
name
},
Name = name
});
}
Add(reports);
}
}
/// <summary>
/// A generic container for models inside CLEM
/// </summary>
public class CLEMFolder : Node
{
public bool ShowPageOfGraphs { get; set; } = true;
public CLEMFolder(Node parent) : base(parent)
{ }
}
/// <summary>
/// Contains reference to source data
/// </summary>
public class FileCrop : Node
{
public string FileName { get; set; }
public string ExcelWorkSheetName { get; set; }
public FileCrop(Node parent) : base(parent)
{ }
}
/// <summary>
/// Contains reference to source data
/// </summary>
public class FileSQLiteGRASP : Node
{
public string FileName { get; set; } = "";
public FileSQLiteGRASP(Node parent) : base(parent)
{ }
}
/// <summary>
/// Summary of the ruminant herd
/// </summary>
public class SummariseRuminantHerd : Node
{
public SummariseRuminantHerd(Node parent) : base(parent)
{
Name = "SummariseHerd";
}
}
}
<file_sep>using Models.CLEM.Resources;
using Models.CLEM.Groupings;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Reader
{
public partial class IAT
{
private static readonly Dictionary<string, int> LabourAges = new Dictionary<string, int>()
{
{"Elderly Male", 72},
{"Elderly Female", 68},
{"Adult Male", 42},
{"Adult Female", 31},
{"Teenager Male", 13},
{"Teenager Female", 12},
{"Child Male", 7},
{"Child Female", 7},
};
/// <summary>
/// Creates the a model for each Labour Type
/// </summary>
public IEnumerable<LabourType> GetLabourTypes(Labour parent)
{
List<LabourType> types = new List<LabourType>();
int row = -1;
foreach (string item in LabourSupply.RowNames)
{
row++;
if (LabourSupply.GetData<string>(row, 0) != "0")
{
// Finds the current demographic
string demo = LabourSupply.ExtraNames[row] + " " + LabourSupply.RowNames[row];
// Tries to find an age for the demographic, defaults to 20
int age = 20;
LabourAges.TryGetValue(demo, out age);
int gender = 0;
if (LabourSupply.RowNames[row].Contains("F")) gender = 1;
LabourType type = new LabourType(parent)
{
Name = demo,
InitialAge = age,
Gender = gender,
Individuals = LabourSupply.GetData<int>(row, 0)
};
types.Add(type);
}
}
return types.AsEnumerable();
}
/// <summary>
/// Models the availability of each Labour Type
/// </summary>
public IEnumerable<LabourAvailabilityItem> GetAvailabilityItems(LabourAvailabilityList parent)
{
List<LabourAvailabilityItem> items = new List<LabourAvailabilityItem>();
int count = -1;
foreach (var row in LabourSupply.RowNames)
{
count++;
if (LabourSupply.GetData<string>(count, 0) != "0")
{
string age = LabourSupply.ExtraNames[count];
string gender = LabourSupply.RowNames[count];
double value = Math.Round(LabourSupply.GetData<double>(count, 2));
LabourAvailabilityItem item = new LabourAvailabilityItem(parent)
{
Name = age + " " + gender,
Value = value
};
LabourFilter GenderFilter = new LabourFilter(item)
{
Name = "GenderFilter",
Parameter = 1,
Value = gender
};
LabourAges.TryGetValue(item.Name, out int years);
LabourFilter AgeFilter = new LabourFilter(item)
{
Name = "AgeFilter",
Parameter = 2,
Operator = 5,
Value = years.ToString()
};
item.Children.Add(GenderFilter);
item.Children.Add(AgeFilter);
items.Add(item);
}
}
return items.AsEnumerable();
}
}
}<file_sep>using Models.CLEM.Activities;
using System.Collections.Generic;
namespace Reader
{
public partial class NABSA
{
public IEnumerable<CropActivityManageCrop> GetManageCrops(ActivityFolder folder)
{
return null;
}
public IEnumerable<CropActivityManageCrop> GetManageForages(ActivityFolder forages)
{
return null;
}
public IEnumerable<CropActivityManageCrop> GetNativePasture(ActivityFolder forages)
{
return null;
}
}
}<file_sep>namespace Models.CLEM.Activities
{
/// <summary>
/// Models the sale of an arbitrary resource
/// </summary>
class ResourceActivitySell : Node
{
public string AccountName { get; set; }
public string ResourceTypeName { get; set; }
public double AmountReserved { get; set; }
public int OnPartialResourcesAvailableAction { get; set; }
public ResourceActivitySell(Node parent) : base(parent)
{ }
}
}
<file_sep># CLEM_Converters
This is a tool for converting agricultral models to ApsimX files for use with [ApsimNG](https://github.com/APSIMInitiative/ApsimX). It is comprised of three parts, the Model, the Readers and the GUI's.
It has been developed specifically for implementing CLEM models into ApsimNG, however in theory it could be extended to service other models.
## Model
The model is essentially the 'skeleton' of an .apsimx file. It outlines the components required for the file to be valid. Each model is a tree structure, with each node representing one of the models found in ApsimNG. Only a small subset of the models in ApsimNG are presently available as nodes (specifically the ones required for CLEM). The model is provided with data through an interface, which it then uses to automatically output an .apsimx file using JSON serialization. The interface is implemented through the readers.
## Readers
The following file types/model readers are available at present:
- IAT
- NABSA
The function of a reader is to be able to parse a data file and provide the information the model needs to generate an .apsimx file. The readers project also contains the "Shared" namespace, which contains methods which are shared between readers (such as error tracking/handling).
## GUIs
There are two GUI projects, one using Gtk, one using Windows forms. The Gtk UI is considered deprecated, but has not been removed in case there is a need for a cross-platform interface in the future.
The aim of the UI is to act as an extended file browser, to let the user pick and choose which files they need converted, as well as allow for additional options to be selected. The functionality is basic at present, but is easily extended.
<file_sep>using Models;
using Models.CLEM;
using Models.Core;
using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Reader
{
public partial class NABSA
{
public static void Run(IEnumerable<string> files)
{
Shared.OpenErrorLog();
foreach (string file in files)
{
NABSA nabsa = new NABSA(file);
Simulations simulations = new Simulations(null)
{
Source = nabsa
};
simulations.Add(new Simulation(simulations) { Name = nabsa.Name });
Shared.WriteApsimX(simulations, Path.GetFileNameWithoutExtension(file));
// Update the Progress bar
Shared.Worker?.ReportProgress(0);
}
Shared.CloseErrorLog();
}
public Clock GetClock(Simulation simulation)
{
int year = Convert.ToInt32(SingleParams.Element("Start_year").Value);
int first = Convert.ToInt32(SingleParams.Element("Start_month").Value);
int last = Convert.ToInt32(SingleParams.Element("End_month").Value);
DateTime start = new DateTime(year, first, 1);
DateTime end = start.AddMonths(last);
return new Clock(simulation)
{
StartDate = start,
EndDate = end
};
}
public IEnumerable<Node> GetFiles(ZoneCLEM clem)
{
List<Node> files = new List<Node>();
files.Add(new FileSQLiteGRASP(clem)
{
Name = "FileGrasp",
FileName = Source.Name.LocalName + ".db"
});
XElement forages = FindByNameTag(Source, "Forages File");
string file = FindFirst(forages, "string").Value;
if (file != "")
{
CSVtoPRN(Shared.InDir + "/" + file);
files.Add(new FileCrop(clem)
{
Name = "FileForage",
FileName = Path.ChangeExtension(file, "prn")
});
}
return files;
}
private void CSVtoPRN(string path)
{
string filename = Path.GetFileNameWithoutExtension(path);
FileStream csv = new FileStream(path, FileMode.Open);
StreamReader reader = new StreamReader(csv);
FileStream prn = new FileStream($"{Shared.OutDir}/{filename}.prn", FileMode.Create);
StreamWriter writer = new StreamWriter(prn);
// Add header to document
writer.WriteLine($"{"SoilNum",-36}{"CropName",-36}{"YEAR",-36}{"Month",-36}{"AmtKg",-36}");
writer.WriteLine($"{"()",-36}{"()",-36}{"()",-36}{"()",-36}{"()",-36}");
// Find the climate region
string climate = FindFirst(Source, "ClimRegion").Value;
// Find the list of grown forages
XElement specs = FindByNameTag(Source, "Forage Crop Specs - General");
var crops = specs.Elements().Skip(2);
string line = reader.ReadLine();
while ((line = reader.ReadLine()) != null)
{
// data[0]: Climate region
// data[1]: Soil number
// data[2]: Forage number
// data[7]: Year
// data[9]: Month
// data[10]: ?Growth amount?
string[] data = line.Split(',');
// Check the region matches
if (data[0] != climate) continue;
// Find the name of the forage from the number
int.TryParse(data[2], out int num);
string forage = crops.ElementAt(num).Element("string").Value;
if (data[10] == "") data[10] = "0";
writer.WriteLine($"{data[1],-36}{forage,-36}{data[7],-36}{data[9],-36}{data[10],-36}");
}
reader.Close();
writer.Close();
}
private T GetValue<T>(XElement xml, int index)
{
string value = xml.Elements().ElementAt(index).Value;
return (T)Convert.ChangeType(value, typeof(T));
}
private T GetValue<T>(XElement xml, string name)
{
string value = xml.Element(name).Value;
return (T)Convert.ChangeType(value, typeof(T));
}
}
}
<file_sep>using Models.CLEM;
using Models.Storage;
namespace Models.Core
{
/// <summary>
/// Container for a series of simulations
/// </summary>
public class Simulations : Node
{
public int ExplorerWidth { get; set; } = 300;
public int Version { get; set; } = 54;
public Simulations(Node parent) : base(parent)
{
Name = "Simulations";
Add(new DataStore(this));
}
}
/// <summary>
/// Models a single simulation
/// </summary>
public class Simulation : Node
{
public Simulation(Node parent) : base(parent)
{
Add(Source.GetClock(this));
Add(new Summary(this));
Add(new ZoneCLEM(this));
}
}
/// <summary>
/// Generic container for models
/// </summary>
public class Folder : Node
{
public bool ShowPageOfGraphs { get; set; } = true;
public Folder(Node parent) : base(parent)
{ }
}
}
<file_sep>using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Models
{
/// <summary>
/// Base node in the tree, this should not be instantiated directly
/// </summary>
public class Node : IDisposable
{
public string Name { get; set; }
public List<Node> Children { get; set; } = new List<Node>();
public bool IncludeInDocumentation { get; set; } = true;
public bool Enabled { get; set; } = true;
public bool ReadOnly { get; set; } = false;
[JsonIgnore]
public Node Parent { get; set; }
[JsonIgnore]
public IApsimX Source { get; set; }
[JsonIgnore]
private bool disposed = false;
public Node(Node parent)
{
Parent = parent;
if (parent != null) Source = parent?.Source;
}
/// <summary>
/// Add a child node
/// </summary>
/// <param name="node"></param>
public void Add(Node node)
{
if (node is null) return;
Children.Add(node);
}
/// <summary>
/// Add a collection of child nodes
/// </summary>
public void Add(IEnumerable<Node> nodes)
{
if (nodes is null) return;
foreach (Node node in nodes) Add(node);
}
/// <summary>
/// Use a Depth-first search to find an instance of
/// the given node type. Returns null if none are found.
/// </summary>
/// <typeparam name="Node">The type of node to search for</typeparam>
public Node SearchTree<Node>(Models.Node node) where Node : Models.Node
{
var result = node.Children
.Select(n => (n.GetType() == typeof(Node)) ? n : SearchTree<Node>(n));
return result.OfType<Node>().FirstOrDefault();
}
/// <summary>
/// Iterates over the nodes ancestors until it finds
/// the first instance of the given node type.
/// </summary>
/// <typeparam name="Node">The type of node to search for</typeparam>
public Node GetAncestor<Node>() where Node : Models.Node
{
Models.Node ancestor = Parent;
while (ancestor.Parent.GetType() != typeof(Node))
{
ancestor = ancestor.Parent;
}
return (Node)ancestor.Parent;
}
/// <summary>
/// Implements IDisposable
/// </summary>
public void Dispose()
{
// Dispose of unmanaged resources.
Dispose(true);
// Suppress finalization.
GC.SuppressFinalize(this);
}
/// <summary>
/// Implements IDisposable
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposed) return;
if (disposing)
{
Source?.Dispose();
}
disposed = true;
}
}
}
<file_sep>using Gtk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UI
{
/// <summary>
/// A Gtk interface for dialog boxes
/// </summary>
class DialogBox
{
public MessageDialog dialog = null;
private Button okbtn = null;
public DialogBox(string message, string icon = "gtk-dialog-warning")
{
Builder builder = Tools.ReadGlade("DialogBox");
// The ok button
okbtn = (Button)builder.GetObject("okbtn");
okbtn.Clicked += OnOkClicked;
// The message in the box
dialog = (MessageDialog)builder.GetObject("dialog");
dialog.Text = message;
dialog.Image = new Image(icon, IconSize.Dialog);
dialog.KeepAbove = true;
dialog.ShowAll();
builder.Dispose();
}
/// <summary>
/// Handles the ok button clicked event
/// </summary>
/// <param name="sender">Sending object</param>
/// <param name="e">Event arguments</param>
private void OnOkClicked(object sender, EventArgs e)
{
dialog.Destroy();
}
}
}
<file_sep>using Models.CLEM.Activities;
using Models.CLEM.Groupings;
using Models.CLEM.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Reader
{
public partial class NABSA
{
private void SetParameters(RuminantType ruminant)
{
List<Tuple<string, string, double>> parameters = new List<Tuple<string, string, double>>()
{
new Tuple<string, string, double>("concep_rate_assym", "ConceptionRateAsymptote", 1),
new Tuple<string, string, double>("concep_rate_coeff", "ConceptionRateCoefficient", 1),
new Tuple<string, string, double>("concep_rate_incpt", "ConceptionRateIntercept", 1),
new Tuple<string, string, double>("birth_SRW", "SRWBirth", 1),
new Tuple<string, string, double>("cashmere_coeff", "CashmereCoefficient", 1),
new Tuple<string, string, double>("Critical_cow_wt", "CriticalCowWeight", 0.01),
new Tuple<string, string, double>("grwth_coeff1", "AgeGrowthRateCoefficient", 1),
new Tuple<string, string, double>("grwth_coeff2", "SRWGrowthScalar", 1),
new Tuple<string, string, double>("intake_coeff", "IntakeCoefficient", 1),
new Tuple<string, string, double>("intake_incpt", "IntakeIntercept", 1),
new Tuple<string, string, double>("IPI_coeff", "InterParturitionIntervalCoefficient", 1),
new Tuple<string, string, double>("IPI_incpt", "InterParturitionIntervalIntercept", 1),
new Tuple<string, string, double>("Joining_age", "MinimumAge1stMating", 1),
new Tuple<string, string, double>("Joining_size", "MinimumSize1stMating", 0.01),
new Tuple<string, string, double>("juvenile_mort_coeff", "JuvenileMortalityCoefficient", 1),
new Tuple<string, string, double>("juvenile_mort_exp", "JuvenileMortalityExponent", 1),
new Tuple<string, string, double>("juvenile_mort_max", "JuvenileMortalityMaximum", 0.01),
new Tuple<string, string, double>("kg_coeff", "EGrowthEfficiencyCoefficient", 1),
new Tuple<string, string, double>("kg_incpt", "EGrowthEfficiencyIntercept", 1),
new Tuple<string, string, double>("kl_coeff", "ELactationEfficiencyCoefficient", 1),
new Tuple<string, string, double>("kl_incpt", "ELactationEfficiencyIntercept", 1),
new Tuple<string, string, double>("km_coeff", "EMaintEfficiencyCoefficient", 1),
new Tuple<string, string, double>("km_incpt", "EMaintEfficiencyIntercept", 1),
new Tuple<string, string, double>("kme", "Kme", 1),
new Tuple<string, string, double>("Milk_Curve_nonsuck", "MilkCurveNonSuckling", 1),
new Tuple<string, string, double>("Milk_Curve_suck", "MilkCurveSuckling", 1),
new Tuple<string, string, double>("Milk_end", "MilkingDays", 30),
new Tuple<string, string, double>("Milk_intake_coeff", "MilkIntakeCoefficient", 1),
new Tuple<string, string, double>("Milk_intake_incpt", "MilkIntakeIntercept", 1),
new Tuple<string, string, double>("Milk_max", "MilkPeakYield", 1),
new Tuple<string, string, double>("Milk_offset_day", "MilkOffsetDay", 1),
new Tuple<string, string, double>("Milk_Peak_day", "MilkPeakDay", 1),
new Tuple<string, string, double>("Mortality_base", "MortalityBase", 0.01),
new Tuple<string, string, double>("protein_coeff", "ProteinCoefficient", 1),
new Tuple<string, string, double>("Rum_gest_int", "GestationLength", 1),
new Tuple<string, string, double>("SRW", "SRWFemale", 1),
new Tuple<string, string, double>("Twin_rate", "TwinRate", 1),
new Tuple<string, string, double>("wool_coeff", "WoolCoefficient", 1)
};
int index = Breeds.IndexOf(ruminant.Breed);
foreach (var parameter in parameters)
{
double value = GetValue<double>(FindFirst(Source, parameter.Item1), index) * parameter.Item3;
ruminant.GetType().GetProperty(parameter.Item2).SetValue(ruminant, value);
}
}
public IEnumerable<RuminantType> GetRuminants(RuminantHerd herd)
{
List<RuminantType> types = new List<RuminantType>();
// Iterate over all breeds, adding cohorts and pricing to each
foreach (string breed in PresentBreeds)
{
RuminantType type = new RuminantType(herd, breed);
SetParameters(type);
types.Add(type);
}
return types;
}
public IEnumerable<RuminantTypeCohort> GetCohorts(RuminantInitialCohorts initials)
{
List<RuminantTypeCohort> list = new List<RuminantTypeCohort>();
int index = Breeds.IndexOf((initials.Parent as RuminantType).Breed);
var cohorts = GetElementNames(Numbers).Skip(1);
foreach (string cohort in cohorts)
{
double num = GetValue<double>(Numbers.Element(cohort), index);
if (num <= 0) continue;
list.Add(new RuminantTypeCohort(initials)
{
Name = cohort,
Number = num,
Age = GetValue<int>(Ages.Element(cohort), index),
Weight = GetValue<double>(Weights.Element(cohort), index),
Gender = cohort.Contains("F") ? 1 : 0,
Suckling = cohort.Contains("Calf") ? true : false,
Sire = cohort.Contains("ire") ? true : false
});
}
return list.AsEnumerable();
}
public IEnumerable<ActivityFolder> GetManageBreeds(ActivityFolder folder)
{
List<ActivityFolder> folders = new List<ActivityFolder>();
foreach (string breed in PresentBreeds)
{
string name = breed.Replace(".", " ");
int index = Breeds.IndexOf(breed);
ActivityFolder manage = new ActivityFolder(folder)
{
Name = name
};
manage.Add(new RuminantActivityWean(manage)
{
WeaningAge = GetValue<double>(RumSpecs.Element("Weaning_age"), index),
WeaningWeight = GetValue<double>(RumSpecs.Element("Weaning_weight"), index),
GrazeFoodStoreName = "NativePasture"
});
string homemilk = GetValue<string>(RumSpecs.Element("Home_milk"), index);
if (homemilk != "0")
{
manage.Add(new RuminantActivityMilking(manage)
{
ResourceTypeName = "HumanFoodStore." + name + "_Milk"
});
}
manage.Add(new RuminantActivityManage(manage)
{
MaximumBreedersKept = GetValue<int>(RumSpecs.Element("Max_breeders"), index),
MaximumBreedingAge = GetValue<int>(RumSpecs.Element("Max_breeder_age"), index),
MaximumBullAge = GetValue<int>(RumSpecs.Element("Max_Bull_age"), index),
MaleSellingAge = GetValue<int>(RumSpecs.Element("Anim_sell_age"), index),
MaleSellingWeight = GetValue<int>(RumSpecs.Element("Anim_sell_wt"), index),
GrazeFoodStoreName = "GrazeFoodStore.NativePasture"
});
manage.Add(new RuminantActivitySellDryBreeders(manage)
{
MinimumConceptionBeforeSell = 1,
MonthsSinceBirth = GetValue<int>(RumSpecs.Element("Joining_age"), index),
ProportionToRemove = GetValue<double>(RumSpecs.Element("Dry_breeder_cull_rate"), index) * 0.01
});
folders.Add(manage);
}
return folders;
}
public IEnumerable<AnimalPriceGroup> GetAnimalPrices(AnimalPricing pricing)
{
List<AnimalPriceGroup> prices = new List<AnimalPriceGroup>();
int index = Breeds.IndexOf((pricing.Parent as RuminantType).Breed);
// List of all the present cohorts
var cohorts = pricing.Parent.Children.First().Children;
foreach(var cohort in cohorts)
{
AnimalPriceGroup price = new AnimalPriceGroup(pricing)
{
Name = cohort.Name,
PricingStyle = 1,
Value = GetValue<double>(Prices.Element(cohort.Name), index)
};
price.Add(new RuminantFilter(price)
{
Name = "GenderFilter",
Parameter = 2,
Value = (((RuminantTypeCohort)cohort).Gender == 0) ? "Male" : "Female"
});
price.Add(new RuminantFilter(price)
{
Name = "AgeFilter",
Parameter = 3,
Operator = 5,
Value = ((RuminantTypeCohort)cohort).Age.ToString()
});
prices.Add(price);
}
return prices.AsEnumerable();
}
}
}
<file_sep>using Reader;
using System;
using System.IO;
using System.Web.Script.Serialization;
using System.Windows.Forms;
namespace Windows
{
public class ConverterSettings
{
public string InDirectory { get; set; } = Shared.InDir;
public string OutDirectory { get; set; } = Shared.OutDir;
public bool IncludeIAT { get; set; } = true;
public bool GroupSheets { get; set; } = true;
public bool GroupSims { get; set; } = false;
public bool IncludeNABSA { get; set; } = true;
public ConverterSettings()
{ }
public static ConverterSettings Read()
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
+ "/CLEMConverter/settings.json";
if (File.Exists(path))
{
string json = File.ReadAllText(path);
ConverterSettings settings = (new JavaScriptSerializer()).Deserialize<ConverterSettings>(json);
return settings;
}
return new ConverterSettings();
}
public void Write()
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
+ "/CLEMConverter";
Directory.CreateDirectory(path);
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(this);
File.WriteAllText(path + "/settings.json", json);
}
}
}
<file_sep>using Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace Reader
{
/// <summary>
/// Data sourced from an IAT file
/// </summary>
public partial class IAT : IApsimX
{
/// <summary>
///Constructs a new IAT object with the given name
/// </summary>
/// <param name="path">Path to the IAT file</param>
public IAT(string path)
{
Name = Path.GetFileNameWithoutExtension(path);
Directory.CreateDirectory($"{Shared.OutDir}/{Name}");
// Read the document
try
{
Document = SpreadsheetDocument.Open(path, false);
}
catch (IOException)
{
throw new ConversionException();
}
// Load the workbook
Book = Document.WorkbookPart;
// Find the string table
StringTable = Book.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
// Write PRN files
WriteCropPRN();
WriteForagePRN();
WriteResiduePRN();
// Update the Progress bar
Shared.Worker?.ReportProgress(0);
}
/// <summary>
/// Changes which sheet in the source document IAT data is taken from
/// </summary>
/// <param name="newsheet">The name of the new sheet</param>
public void SetSheet(string name)
{
// This assumes a valid IAT is provided as input and will break otherwise (need to fix)
ParameterSheet = FindSheet(name);
if (ParameterSheet == null) ParameterSheet = SearchSheets(name);
Part = (WorksheetPart)Book.GetPartById(ParameterSheet.Id);
// Initialise the data for the new sheet
PrepareData();
}
/// <summary>
/// Looks through the ExcelPackage for the first sheet containing the given string.
/// </summary>
/// <param name="sheetname">The sheet to search for</param>
/// <returns></returns>
public Sheet FindSheet(string name)
{
return Book.Workbook.Descendants<Sheet>().
Where(s => s.Name.ToString() == name).
FirstOrDefault();
}
public Sheet SearchSheets(string name)
{
return Book.Workbook.Descendants<Sheet>().
Where(s => s.Name.ToString().ToLower().Contains(name.ToLower())).
FirstOrDefault();
}
public void PrepareData()
{
// Load all the sub tables
CropsGrown = new SubTable("Grain Crops Grown", this);
CropSpecs = new SubTable("Grain Crop Specifications", this);
ForagesGrown = new SubTable("Forage Crops Grown", this);
ForageSpecs = new SubTable("Forage Crop Specifications", this);
LandSpecs = new SubTable("Land specifications", this);
LabourSupply = new SubTable("Labour supply/hire", this);
RumNumbers = new SubTable("Startup ruminant numbers", this);
RumAges = new SubTable("Startup ruminant ages", this);
RumWeights = new SubTable("Startup ruminant weights", this);
RumCoeffs = new SubTable("Ruminant coefficients", this);
RumSpecs = new SubTable("Ruminant specifications", this);
RumPrices = new SubTable("Ruminant prices", this);
Overheads = new SubTable("Overheads", this);
Fodder = new SubTable("Bought fodder", this);
FodderSpecs = new SubTable("Bought fodder specs", this);
// Find climate data (assumed to exist in specific cell)
Climate = GetCellValue(Part, 4, 6);
// Find total land area
TotalArea = LandSpecs.GetColData<double>(0).Sum();
// Set values
SetGrains();
SetRuminants();
Pools = new Dictionary<int, string>();
GetGrownFodderPools();
GetBoughtFodderPools();
}
public void ClearTables()
{
CropsGrown = null;
CropSpecs = null;
ForagesGrown = null;
ForageSpecs = null;
LandSpecs = null;
LabourSupply = null;
RumNumbers = null;
RumAges = null;
RumWeights = null;
RumCoeffs = null;
RumSpecs = null;
RumPrices = null;
Overheads = null;
Fodder = null;
FodderSpecs = null;
}
public void Dispose()
{
// Disposal of unmanaged resources.
Dispose(true);
// Suppress finalization.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed) return;
if(disposing)
{
Document.Close();
}
Book = null;
ParameterSheet = null;
Part = null;
ClearTables();
disposed = true;
}
}
}<file_sep>using System;
namespace Models
{
/// <summary>
/// Models the simulation clock
/// </summary>
public class Clock : Node
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public Clock(Node parent) : base(parent)
{
Name = "Clock";
}
}
/// <summary>
/// A memorandum for the user
/// </summary>
public class Memo : Node
{
public string Text { get; set; }
public Memo(Node parent) : base(parent)
{ }
}
/// <summary>
/// A summary of the entire simulation
/// </summary>
public class Summary : Node
{
public bool CaptureErrors { get; set; } = true;
public bool CaptureWarnings { get; set; } = true;
public bool CaptureSummaryText { get; set; } = true;
public Summary(Node parent) : base(parent)
{
Name = "summaryfile";
}
}
}
<file_sep>namespace Models.CLEM.Resources
{
/// <summary>
/// Container for animal prices
/// </summary>
public class AnimalPricing : Node
{
public string PricingStyle { get; set; } = "perKg";
public double SirePrice { get; set; } = 0.0;
public AnimalPricing(Node parent) : base(parent)
{
Name = "AnimalPricing";
Add(Source.GetAnimalPrices(this));
}
}
}
<file_sep>using Gtk;
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UI
{
class Tools
{
/// <summary>
/// Creates a builder from a glade file
/// </summary>
/// <param name="name">Path to the glade file</param>
public static Builder ReadGlade(string name)
{
Builder builder = new Builder();
string path = $"{Directory.GetCurrentDirectory()}/UI/Resources/{name}.glade";
StreamReader reader = new StreamReader(path);
string glade = reader.ReadToEnd();
builder.AddFromString(glade);
return builder;
}
/// <summary>
/// Creates a new text list store for a combo box
/// </summary>
/// <param name="combo">The box to create a store for</param>
public static void AddStoreToCombo(ComboBox combo)
{
// Remove any existing list
combo.Clear();
// Create a new renderer for the text in the box
CellRendererText renderer = new CellRendererText();
combo.PackStart(renderer, false);
combo.AddAttribute(renderer, "text", 0);
// Add a ListStore to the box
ListStore store = new ListStore(typeof(string));
combo.Model = store;
}
public static void SetProjectDirectory()
{
string location = Directory.GetCurrentDirectory();
while (!File.Exists("CLEM_Converters.sln"))
{
location = Directory.GetParent(location).FullName;
Directory.SetCurrentDirectory(location);
}
}
}
}
<file_sep>namespace Models.CLEM.Resources
{
/// <summary>
/// Container for all ruminants
/// </summary>
public class RuminantHerd : Node
{
public RuminantHerd(Node parent) : base(parent)
{
Name = "Ruminants";
Add(Source.GetRuminants(this));
}
}
/// <summary>
/// Models an arbitrary type of ruminant
/// </summary>
public class RuminantType : Node
{
public string Breed { get; set; }
public double EMaintEfficiencyCoefficient { get; set; } = 0.37;
public double EMaintEfficiencyIntercept { get; set; } = 0.538;
public double EGrowthEfficiencyCoefficient { get; set; } = 1.33;
public double EGrowthEfficiencyIntercept { get; set; } = -0.308;
public double ELactationEfficiencyCoefficient { get; set; } = 0.35;
public double ELactationEfficiencyIntercept { get; set; } = 0.42;
public double EMaintExponent { get; set; } = 0.000082;
public double EMaintIntercept { get; set; } = 0.09;
public double EMaintCoefficient { get; set; } = 0.26;
public double EnergyMaintenanceMaximumAge { get; set; } = 6;
public double Kme { get; set; } = 1;
public double GrowthEnergyIntercept1 { get; set; } = 6.7;
public double GrowthEnergyIntercept2 { get; set; } = 20.3;
public double GrowthEfficiency { get; set; } = 1.09;
public double NaturalWeaningAge { get; set; } = 3;
public double SRWFemale { get; set; } = 342;
public double SRWMaleMultiplier { get; set; } = 1.2;
public double SRWBirth { get; set; } = 0.0472;
public double AgeGrowthRateCoefficient { get; set; } = 0.01126;
public double SRWGrowthScalar { get; set; } = 0.32;
public double IntakeCoefficient { get; set; } = 0.024;
public double IntakeIntercept { get; set; } = 1.7;
public double ProteinCoefficient { get; set; } = 110;
public double ProteinDegradability { get; set; } = 0.9;
public double BaseAnimalEquivalent { get; set; } = 450;
public double GreenDietMax { get; set; } = 0.98;
public double GreenDietCoefficient { get; set; } = 0.15;
public double GreenDietZero { get; set; } = 0.04;
public double IntakeTropicalQuality { get; set; } = 0.16;
public double IntakeCoefficientQuality { get; set; } = 1.7;
public double IntakeCoefficientBiomass { get; set; } = 0.01;
public bool StrictFeedingLimits { get; set; } = true;
public double MilkIntakeCoefficient { get; set; } = 0.1206;
public double MilkIntakeIntercept { get; set; } = 3.8146;
public double MilkIntakeMaximum { get; set; } = 20;
public double MilkLWTFodderSubstitutionProportion { get; set; } = 0.2;
public double MaxJuvenileIntake { get; set; } = 0.04;
public double ProportionalDiscountDueToMilk { get; set; } = 0.3;
public double ProportionOfMaxWeightToSurvive { get; set; } = 0.5;
public double LactatingPotentialModifierConstantA { get; set; } = 0.42;
public double LactatingPotentialModifierConstantB { get; set; } = 0.61;
public double LactatingPotentialModifierConstantC { get; set; } = 1.7;
public double MaximumSizeOfIndividual { get; set; } = 1.2;
public double MortalityBase { get; set; } = 0.03;
public double MortalityCoefficient { get; set; } = 2.5;
public double MortalityIntercept { get; set; } = 0.05;
public double MortalityExponent { get; set; } = 3;
public double JuvenileMortalityCoefficient { get; set; } = 3;
public double JuvenileMortalityMaximum { get; set; } = 0.36;
public double JuvenileMortalityExponent { get; set; } = 3;
public double WoolCoefficient { get; set; } = 0.0;
public double CashmereCoefficient { get; set; } = 0.0;
public double MilkCurveSuckling { get; set; } = 0.6;
public double MilkCurveNonSuckling { get; set; } = 0.11;
public double MilkingDays { get; set; } = 304;
public double MilkPeakYield { get; set; } = 8;
public double MilkOffsetDay { get; set; } = 4;
public double MilkPeakDay { get; set; } = 30;
public double InterParturitionIntervalIntercept { get; set; } = 10.847;
public double InterParturitionIntervalCoefficient { get; set; } = -0.7994;
public double GestationLength { get; set; } = 9;
public double MinimumAge1stMating { get; set; } = 24;
public double MinimumSize1stMating { get; set; } = 0.5;
public double MinimumDaysBirthToConception { get; set; } = 61;
public double TwinRate { get; set; } = 0.01;
public double CriticalCowWeight { get; set; } = 0.5;
public double ConceptionRateCoefficient { get; set; } = -9.3353;
public double ConceptionRateIntercept { get; set; } = 5.182;
public double ConceptionRateAsymptote { get; set; } = 81.54;
public double MaximumMaleMatingsPerDay { get; set; } = 30;
public double PrenatalMortality { get; set; } = 0.08;
public double MaximumConceptionUncontrolledBreeding { get; set; } = 0.9;
public double MethaneProductionCoefficient { get; set; } = 20.7;
public string Units { get; set; }
public RuminantType(Node parent) : base(parent)
{
Add(new RuminantInitialCohorts(this));
Add(new AnimalPricing(this));
}
public RuminantType(Node parent, string breed) : base(parent)
{
Name = breed.Replace(".", " ");
Breed = breed;
Add(new RuminantInitialCohorts(this));
Add(new AnimalPricing(this));
}
}
/// <summary>
/// Container for ruminants within a type
/// </summary>
public class RuminantInitialCohorts : Node
{
public RuminantInitialCohorts(RuminantType parent) : base(parent)
{
Name = "InitialCohorts";
Add(Source.GetCohorts(this));
}
}
/// <summary>
/// Models a cohort of similar ruminants for a given type
/// </summary>
public class RuminantTypeCohort : Node
{
public int Gender { get; set; }
public int Age { get; set; }
public double Number { get; set; }
public double Weight { get; set; }
public double WeightSD { get; set; }
public bool Suckling { get; set; }
public bool Sire { get; set; }
public RuminantTypeCohort(Node parent) : base(parent)
{
}
}
}
<file_sep>using Models.Core;
using Models.CLEM;
using Models.CLEM.Activities;
using Models.CLEM.Resources;
using Models.CLEM.Groupings;
using System;
using System.Collections.Generic;
namespace Models
{
/// <summary>
/// Interface for accessing the data needed to generate an ApsimX
/// model from external source.
/// </summary>
public interface IApsimX : IDisposable
{
// PROPERTIES:
/// <summary>
/// Name of the source
/// </summary>
string Name { get; set; }
// RESOURCES:
// Metadata methods
/// <summary>
/// Searches the source for the simulation clock
/// </summary>
Clock GetClock(Simulation simulation);
/// <summary>
/// Construct or attach additional files through the source
/// </summary>
IEnumerable<Node> GetFiles(ZoneCLEM clem);
// Land methods
/// <summary>
/// Search the source for land types
/// </summary>
IEnumerable<LandType> GetLandTypes(Land land);
// Labour methods
/// <summary>
/// Search the source for labour types
/// </summary>
IEnumerable<LabourType> GetLabourTypes(Labour labour);
/// <summary>
/// Search the source for the availability of labour
/// </summary>
IEnumerable<LabourAvailabilityItem> GetAvailabilityItems(LabourAvailabilityList list);
// Ruminant methods
/// <summary>
/// Search the source for present ruminant breeds
/// </summary>
IEnumerable<RuminantType> GetRuminants(RuminantHerd herd);
/// <summary>
/// Search the source for cohorts present in a given ruminant breed
/// </summary>
IEnumerable<RuminantTypeCohort> GetCohorts(RuminantInitialCohorts cohorts);
/// <summary>
/// Search the source for the pricing of ruminants
/// </summary>
IEnumerable<AnimalPriceGroup> GetAnimalPrices(AnimalPricing pricing);
// Finance methods
/// <summary>
/// Set the finance data from the source
/// </summary>
void SetFinanceData(Finance finance);
/// <summary>
/// Set the bank data from the source
/// </summary>
void SetBankData(FinanceType bank);
// Store methods
/// <summary>
/// Search the source for types of animal fodder
/// </summary>
IEnumerable<AnimalFoodStoreType> GetAnimalStoreTypes(AnimalFoodStore store);
/// <summary>
/// Search the source for types of human food
/// </summary>
IEnumerable<HumanFoodStoreType> GetHumanStoreTypes(HumanFoodStore store);
/// <summary>
/// Search the source for miscellaneous products
/// </summary>
IEnumerable<ProductStoreType> GetProductStoreTypes(ProductStore store);
/// <summary>
/// Constructs the graze food store
/// </summary>
GrazeFoodStoreType GetGrazeFoodStore(GrazeFoodStore store);
/// <summary>
/// Constructs the common food store
/// </summary>
CommonLandFoodStoreType GetCommonFoodStore(AnimalFoodStore store);
// ACTIVITIES
// Finance activities
/// <summary>
/// Search the source for monthly expenses
/// </summary>
ActivityFolder GetMonthlyExpenses(ActivityFolder cashflow);
/// <summary>
/// Search the source for annual expenses
/// </summary>
ActivityFolder GetAnnualExpenses(ActivityFolder cashflow);
/// <summary>
/// Search the source for the interest rates
/// </summary>
FinanceActivityCalculateInterest GetInterestRates(ActivityFolder cashflow);
// Crop/Forage activities
/// <summary>
/// Search the source for crops to manage
/// </summary>
IEnumerable<CropActivityManageCrop> GetManageCrops(ActivityFolder folder);
/// <summary>
/// Search the source for forages to manage
/// </summary>
IEnumerable<CropActivityManageCrop> GetManageForages(ActivityFolder forages);
/// <summary>
/// Search the source for native pasture to manage
/// </summary>
IEnumerable<CropActivityManageCrop> GetNativePasture(ActivityFolder forages);
/// <summary>
/// Search the source for normal pasture to manage
/// </summary>
PastureActivityManage GetManagePasture(ActivitiesHolder folder);
// Ruminant activities
/// <summary>
/// Search the source for breeds to manage
/// </summary>
IEnumerable<ActivityFolder> GetManageBreeds(ActivityFolder folder);
}
}
<file_sep>namespace Models.Storage
{
/// <summary>
/// Reference to the SQLite database (.DB) storing output data
/// </summary>
public class DataStore : Node
{
public DataStore(Node parent) : base(parent)
{
Name = "DataStore";
}
}
}
<file_sep>namespace Models.CLEM.Activities
{
/// <summary>
/// Models the management of pastoral land
/// </summary>
public class PastureActivityManage : Node
{
public string LandTypeNameToUse { get; set; } = "";
public string FeedTypeName { get; set; } = "GrazeFoodStore.NativePasture";
public double StartingAmount { get; set; } = 0;
public double StartingStockingRate { get; set; } = 0;
public double AreaRequested { get; set; } = 0;
public bool UseAreaAvailable { get; set; } = true;
public PastureActivityManage(Node parent) : base(parent)
{
Name = "ManagePasture";
}
}
}
<file_sep>namespace Models.CLEM.Activities
{
/// <summary>
/// Models the management of crops
/// </summary>
public class CropActivityManageCrop : ActivityNode
{
public string LandItemNameToUse { get; set; } = "";
public double AreaRequested { get; set; } = 0.0;
public bool UseAreaAvailable { get; set; } = false;
public CropActivityManageCrop(Node parent) : base(parent)
{ }
}
/// <summary>
/// Models the management of crop products
/// </summary>
public class CropActivityManageProduct : ActivityNode
{
public string ModelNameFileCrop { get; set; } = "";
public string CropName { get; set; } = "";
public string StoreItemName { get; set; } = "";
public double ProportionKept { get; set; } = 1.0;
public double TreesPerHa { get; set; } = 0.0;
public double UnitsToHaConverter { get; set; } = 0.0;
public CropActivityManageProduct(CropActivityManageCrop parent) : base(parent)
{ }
}
}
<file_sep>using Models.CLEM.Activities;
using Models.CLEM.Resources;
using System;
namespace Reader
{
public partial class NABSA
{
public void SetFinanceData(Finance finance)
{
finance.CurrencyName = "AU$";
}
public void SetBankData(FinanceType bank)
{
// Find the balance and interest
double balance = Convert.ToDouble(FindFirst(Source, "Cash_balance").Value);
double interest = Convert.ToDouble(FindFirst(Source, "Int_rate").Value);
bank.OpeningBalance = balance;
bank.InterestRateCharged = interest;
}
public ActivityFolder GetAnnualExpenses(ActivityFolder cashflow)
{
ActivityFolder annual = new ActivityFolder(cashflow)
{
Name = "AnnualExpenses"
};
// Names of parameters to search for in the Element
string[] items = new string[]
{
"Farm_maint",
"Mach_maint",
"Fuel",
"Pests",
"Contractors",
"Admin",
"Rates",
"Insurance",
"Electricity",
"Water",
"Other_costs"
};
foreach (string item in items)
{
string value = FindFirst(SingleParams, item).Value;
int.TryParse(value, out int amount);
// Only need to add the element if its a non-zero expenditure
if (amount <= 0) continue;
FinanceActivityPayExpense expense = new FinanceActivityPayExpense(annual)
{
Name = item.Replace("_", ""),
Amount = amount,
AccountName = "Finances.Bank",
IsOverhead = false
};
annual.Add(expense);
}
return annual;
}
public FinanceActivityCalculateInterest GetInterestRates(ActivityFolder cashflow)
{
// Find the interest amount
string value = FindFirst(SingleParams, "Int_rate").Value;
int.TryParse(value, out int rate);
// If the interest is 0, don't add the element
if (rate == 0) return null;
return new FinanceActivityCalculateInterest(cashflow);
}
public ActivityFolder GetMonthlyExpenses(ActivityFolder cashflow)
{
ActivityFolder monthly = new ActivityFolder(cashflow)
{
Name = "MonthlyExpenses"
};
string value = FindFirst(SingleParams, "Living_cost").Value;
double.TryParse(value, out double amount);
monthly.Add(new FinanceActivityPayExpense(monthly)
{
Name = "LivingCost",
Amount = amount,
AccountName = "Finance.Bank"
});
return monthly;
}
}
}<file_sep>using Models.CLEM.Activities;
using System.Collections.Generic;
using System.Linq;
namespace Reader
{
public partial class IAT
{
/// <summary>
/// Constructs the Manage Forages model
/// </summary>
/// <param name="iat">The IAT file to access data from</param>
public IEnumerable<CropActivityManageCrop> GetManageForages(ActivityFolder forages)
{
List<CropActivityManageCrop> manage = new List<CropActivityManageCrop>();
int col = 0;
// Check present forages
var list = ForagesGrown.GetRowData<double>(0);
foreach (var item in list)
{
if (item == 0) continue;
double area = ForagesGrown.GetData<double>(2, col);
if (area > 0)
{
int num = ForagesGrown.GetData<int>(1, col);
int row = ForagesGrown.GetData<int>(0, col);
string name = ForageSpecs.RowNames[row + 1];
CropActivityManageCrop crop = new CropActivityManageCrop(forages)
{
Name = "Manage " + name,
LandItemNameToUse = "Land." + LandSpecs.RowNames[num],
AreaRequested = ForagesGrown.GetData<double>(2, col)
};
crop.Add(new CropActivityManageProduct(crop)
{
Name = "Cut and carry " + name,
ModelNameFileCrop = "FileForage",
CropName = name,
StoreItemName = "AnimalFoodStore"
});
manage.Add(crop);
}
col++;
}
return manage.AsEnumerable();
}
/// <summary>
/// Constructs the Native Pasture model
/// </summary>
public IEnumerable<CropActivityManageCrop> GetNativePasture(ActivityFolder forages)
{
List<CropActivityManageCrop> pastures = new List<CropActivityManageCrop>();
// Check if there are native pasture feeds before proceeding
var feed_type = RumSpecs.GetRowData<int>(28);
var feeds = from breed in feed_type
where RumIDs.Contains(feed_type.IndexOf(breed))
where breed > 1
select breed;
if (feeds.Count() == 0) return null;
CropActivityManageCrop farm = new CropActivityManageCrop(forages)
{
LandItemNameToUse = "Land",
UseAreaAvailable = true,
Name = "NativePastureFarm"
};
farm.Add(new CropActivityManageProduct(farm)
{
ModelNameFileCrop = "FileForage",
CropName = "Native_grass",
StoreItemName = "AnimalFoodStore.NativePasture",
Name = "Cut and carry Native Pasture"
});
CropActivityManageCrop common = new CropActivityManageCrop(forages)
{
LandItemNameToUse = "Land",
Name = "Native Pasture Common Land"
};
common.Add(new CropActivityManageProduct(common)
{
ModelNameFileCrop = "FileForage",
CropName = "Native_grass",
StoreItemName = "GrazeFoodStore.NativePasture",
Name = "Grazed Common Land"
});
pastures.Add(farm);
pastures.Add(common);
return pastures.AsEnumerable();
}
}
}
<file_sep>using Gtk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace UI
{
/// <summary>
/// A Gtk interface for selecting a folder
/// </summary>
class SelectFolder
{
public Window window = null;
public event EventHandler selected;
private FileChooserWidget chooser = null;
private Button selectbtn = null;
private Button cancelbtn = null;
private Widget caller = null;
private Entry entry = null;
public SelectFolder(Widget caller, Entry entry)
{
this.caller = caller;
this.entry = entry;
if ((caller == null) || (entry == null)) throw new ArgumentNullException();
Builder builder = Tools.ReadGlade("SelectFolder");
// Window
window = (Window)builder.GetObject("window");
window.Title = "";
// File chooser
chooser = (FileChooserWidget)builder.GetObject("chooser");
chooser.SetCurrentFolder(entry.Text);
// Buttons
selectbtn = (Button)builder.GetObject("selectbtn");
cancelbtn = (Button)builder.GetObject("cancelbtn");
// Button events
selectbtn.Clicked += OnSelectClicked;
cancelbtn.Clicked += OnCancelClicked;
builder.Dispose();
}
/// <summary>
/// Handels the select button click event
/// </summary>
/// <param name="sender">Sending object</param>
/// <param name="e">Event arguments</param>
private void OnSelectClicked(object sender, EventArgs e)
{
entry.Text = chooser.CurrentFolder;
if (selected != null) selected.Invoke(this, EventArgs.Empty);
caller.Sensitive = true;
window.Destroy();
}
/// <summary>
/// Handles the cancel button click event
/// </summary>
/// <param name="sender">Sending object</param>
/// <param name="e">Event arguments</param>
private void OnCancelClicked(object sender, EventArgs e)
{
caller.Sensitive = true;
window.Destroy();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Text.RegularExpressions;
namespace Reader
{
public partial class IAT
{
/// <summary>
/// Contains data from one of the sub tables in an IAT file
/// </summary>
public class SubTable
{
/// <summary>
/// The IAT object which owns the table
/// </summary>
private readonly IAT iat;
/// <summary>
/// Table name
/// </summary>
public string Name { get; }
/// <summary>
/// Row containing table title
/// </summary>
private int title_row;
/// <summary>
/// Column containing all table titles
/// </summary>
private int title_col = 2;
/// <summary>
/// Number of rows in the table
/// </summary>
private int rows = 0;
/// <summary>
/// Number of columns in the table
/// </summary>
private int cols = 0;
/// <summary>
/// List of row names in the table
/// </summary>
public List<string> RowNames { get; } = new List<string>();
/// <summary>
/// List of column names in the table
/// </summary>
public List<string> ColumnNames { get; } = new List<string>();
/// <summary>
/// List containing secondary row data found in some tables
/// </summary>
public List<string> ExtraNames { get; } = new List<string>();
/// <summary>
/// Grid of table data
/// </summary>
private string[,] data;
/// <summary>
/// Looks through an IAT for the given name and attempts to load data into the object
/// </summary>
/// <param name="name">Name of the table to search for</param>
/// <param name="iat">IAT to search through</param>
public SubTable(string name, IAT iat)
{
this.iat = iat;
Name = name;
// Check the table exists
if (!FindTable()) throw new Exception($"'{name}' table not found, invalid dataset");
// Attenot to find the rows and columns of the table
LoadRows();
LoadCols();
// Attempt to load table data once rows/columns are found
LoadExtra();
LoadData();
}
/// <summary>
/// Checks if the table exists in the IAT file, and sets the title row if it finds the table
/// </summary>
/// <returns></returns>
private bool FindTable()
{
// Find all non-empty cells
var non_empty =
from cells
in iat.Part.Worksheet.Descendants<Cell>()
where cells.DataType != null
select cells;
// Find only the cells which contain text (not numeric data)
// Note: This comparison only works on non_empty cells (not null valued)
var has_text =
from cells
in non_empty
where cells.DataType.Value == CellValues.SharedString
select cells;
// Check if the text in the cells matches the title text
string value;
foreach (var cell in has_text)
{
value = iat.StringTable.SharedStringTable.ElementAt(int.Parse(cell.InnerText)).InnerText;
if (value == Name)
{
// Find the Reference of the Cell containing the title
Regex reg = new Regex(@"([A-Z]+)(\d+)");
Match match = reg.Match(cell.CellReference.InnerText);
// Find the number of the title row
int.TryParse(match.Groups[2].Value, out title_row);
return true;
}
}
return false;
}
/// <summary>
/// Finds the name of each row, assuming at least one row exists in a table
/// </summary>
private void LoadRows()
{
do
{
// Count the number of rows in the table
rows++;
// Add the row name to the list, if name is missing, row is named after rank
string title = iat.GetCellValue(iat.Part, title_row + rows, title_col);
if (title == "") title = rows.ToString();
RowNames.Add(title);
}
// End of the table is marked by empty cells
while (iat.GetCellValue(iat.Part, title_row + 1 + rows, title_col) != "");
return;
}
/// <summary>
/// Finds the title of each column, assuming at least one column exists in a table
/// </summary>
private void LoadCols()
{
do
{
// Count the number of columns in the table
cols++;
// If title is missing, column is named after rank
string title = iat.GetCellValue(iat.Part, title_row, title_col + 1 + cols);
if (title == "") title = cols.ToString();
ColumnNames.Add(title);
}
// End of the table is marked by empty cells
while (iat.GetCellValue(iat.Part, title_row + 1, title_col + 2 + cols) != "");
return;
}
/// <summary>
/// Loads the extra column of row data
/// </summary>
private void LoadExtra()
{
// Find rows containing the table data
var table_rows = iat.Part.Worksheet.Descendants<Row>().Skip(title_row).Take(rows);
Cell cell = null;
// Find the extra data cell in each row
foreach (Row row in table_rows)
{
cell = row.Descendants<Cell>().ElementAt(title_col);
ExtraNames.Add(iat.ParseCell(cell));
}
return;
}
/// <summary>
/// Loads the data contained within the table
/// </summary>
private void LoadData()
{
// Initialise data array *after* the number of rows and columns is found
data = new string[rows, cols];
// Select the rows which contain the table
var table_rows = iat.Part.Worksheet.Descendants<Row>().Skip(title_row).Take(rows);
// Go over each row in the table
int r = 0;
IEnumerable<Cell> cells;
foreach (Row row in table_rows)
{
// Select the cells in the row which are part of the table
cells = row.Descendants<Cell>().Skip(title_col + 1).Take(cols);
// Find the value of the cell data and store it
int c = 0;
foreach (Cell cell in cells)
{
data[r, c] = iat.ParseCell(cell);
c++;
}
r++;
}
}
/// <summary>
/// Converts a string to a new data type, if possible.
/// If not, return the default type and log the error.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="s"></param>
/// <returns></returns>
private T ConvertData<T>(string s)
{
var ED = new ErrorData()
{
FileName = iat.Name,
FileType = "IAT",
Message = $"Unknown",
Severity = "Unknown",
Table = Name,
Sheet = iat.ParameterSheet.Name
};
try
{
T value = (T)Convert.ChangeType(s, typeof(T));
return value;
}
catch (FormatException)
{
ED.Message = "Empty cell";
ED.Severity = "Low";
Shared.WriteError(ED);
return default;
}
catch (IndexOutOfRangeException)
{
ED.Message = "Index out of range";
ED.Severity = "Moderate";
Shared.WriteError(ED);
return default;
}
catch (InvalidCastException)
{
T t = default;
ED.Message = $"Type mismatch, expected {t.GetType().Name}";
ED.Severity = "Moderate";
Shared.WriteError(ED);
return default;
}
catch
{
Shared.WriteError(ED);
return default;
}
}
/// <summary>
/// Accesses the data at the given location
/// </summary>
/// <param name="row">Row position</param>
/// <param name="column">Column position</param>
public T GetData<T>(int row, int column)
{
string s = data[row, column];
var ED = new ErrorData()
{
FileName = iat.Name,
FileType = "IAT",
Message = $"Unknown",
Severity = "Unknown",
Table = Name,
Sheet = iat.ParameterSheet.Name
};
try
{
T value = (T)Convert.ChangeType(s, typeof(T));
return value;
}
catch (FormatException)
{
ED.Message = "Empty cell";
ED.Severity = "Low";
Shared.WriteError(ED);
return default;
}
catch (IndexOutOfRangeException)
{
ED.Message = "Index out of range";
ED.Severity = "Moderate";
Shared.WriteError(ED);
return default;
}
catch (InvalidCastException)
{
T t = default;
ED.Message = $"Type mismatch, expected {t.GetType().Name}";
ED.Severity = "Moderate";
Shared.WriteError(ED);
return default;
}
catch
{
Shared.WriteError(ED);
return default;
}
}
/// <summary>
/// Selects a row of data from the table in the given type.
/// Invalid type casts return default values.
/// </summary>
/// <param name="r">Row number</param>
public List<T> GetRowData<T>(int r)
{
return Enumerable.Range(0, data.GetLength(1))
.Select(c => ConvertData<T>(data[r, c]))
.ToList();
}
/// <summary>
/// Selects a column of data from the table in the given type.
/// Invalid type casts return default values.
/// </summary>
/// <param name="c">Column number</param>
public List<T> GetColData<T>(int c)
{
return Enumerable.Range(0, data.GetLength(0))
.Select(r => ConvertData<T>(data[r, c]))
.ToList();
}
}
}
}
<file_sep>using Models.CLEM.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Reader
{
public partial class NABSA
{
public GrazeFoodStoreType GetGrazeFoodStore(GrazeFoodStore store)
{
return new GrazeFoodStoreType(store)
{
NToDMDCoefficient = GetValue<double>(SingleParams, "Coeff_DMD"),
NToDMDIntercept = GetValue<double>(SingleParams, "Incpt_DMD"),
GreenNitrogen = GetValue<double>(SingleParams, "Native_N"),
DecayNitrogen = GetValue<double>(SingleParams, "Decay_N"),
MinimumNitrogen = GetValue<double>(SingleParams, "Native_N_min"),
DecayDMD = GetValue<double>(SingleParams, "Decay_DMD"),
MinimumDMD = GetValue<double>(SingleParams, "Native_DMD_min"),
DetachRate = GetValue<double>(SingleParams, "Native_detach"),
CarryoverDetachRate = GetValue<double>(SingleParams, "Carryover_detach"),
IntakeTropicalQualityCoefficient = GetValue<double>(SingleParams, "Intake_trop_quality"),
IntakeQualityCoefficient = GetValue<double>(SingleParams, "Intake_coeff_quality")
};
}
public IEnumerable<AnimalFoodStoreType> GetAnimalStoreTypes(AnimalFoodStore store)
{
List<AnimalFoodStoreType> types = new List<AnimalFoodStoreType>();
AddSupplements(types, store);
AddBought(types, store);
return types;
}
private void AddSupplements(List<AnimalFoodStoreType> types, AnimalFoodStore store)
{
// List of all supplement allocations (skipping metadata)
var allocs = SuppAllocs.Elements().Skip(2).ToList();
// Indices of non-zero allocations
var indices = from alloc in allocs
where alloc.Elements().Select(e => e.Value).ToList().Exists(v => v != "0")
select allocs.IndexOf(alloc);
// List of all supplement specifications (skipping metadata)
var supps = SuppSpecs.Elements().Skip(3).ToList();
// Collection of specifications with allocations
var specs = from spec in supps
where indices.Contains(supps.IndexOf(spec))
select new string[3]
{
spec.Name.LocalName,
spec.Elements().ElementAt(1).Value,
spec.Elements().ElementAt(2).Value
};
foreach (var spec in specs)
{
types.Add(new AnimalFoodStoreType(store)
{
Name = spec[0],
DMD = Convert.ToDouble(spec[1]),
Nitrogen = Convert.ToDouble(spec[2])
});
}
}
private void AddBought(List<AnimalFoodStoreType> types, AnimalFoodStore store)
{
var fodders = Fodder.Elements().Skip(2).ToList();
var indices = from fodder in fodders
where fodder.Elements().ElementAt(3).Value == "TRUE"
select fodders.IndexOf(fodder);
var slist = FodderSpecs.Elements().Skip(3).ToList();
var specs = from spec in slist
where indices.Contains(slist.IndexOf(spec))
select new string[3]
{
spec.Name.LocalName,
spec.Elements().ElementAt(1).Value,
spec.Elements().ElementAt(2).Value
};
foreach (var spec in specs)
{
types.Add(new AnimalFoodStoreType(store)
{
Name = spec[0],
DMD = Convert.ToDouble(spec[1]),
Nitrogen = Convert.ToDouble(spec[2])
});
}
}
public IEnumerable<HumanFoodStoreType> GetHumanStoreTypes(HumanFoodStore store)
{
return null;
}
public IEnumerable<ProductStoreType> GetProductStoreTypes(ProductStore store)
{
return null;
}
public CommonLandFoodStoreType GetCommonFoodStore(AnimalFoodStore store)
{
return null;
}
}
}
<file_sep>namespace Models.CLEM.Resources
{
/// <summary>
/// Container for all resources
/// </summary>
public class ResourcesHolder : Node
{
public ResourcesHolder(ZoneCLEM parent) : base(parent)
{
Name = "Resources";
Add(new Land(this));
Add(new Labour(this));
Add(new RuminantHerd(this));
Add(new Finance(this));
Add(new AnimalFoodStore(this));
Add(new GrazeFoodStore(this));
Add(new ProductStore(this));
Add(new HumanFoodStore(this));
}
}
}
<file_sep>using Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Reader
{
public partial class NABSA : IApsimX
{
public NABSA(string path)
{
Source = XElement.Load(path);
Name = Path.GetFileNameWithoutExtension(path);
// General Data
SingleParams = Source.Element("SingleParams");
// Land Data
LandSpecs = Source.Element("LandSpecs");
// Labour Data
Priority = FindByNameTag(Source, "Labour Number and Priority");
Supply = FindByNameTag(Source, "Labour Supply");
// Ruminant Data
SuppAllocs = FindFirst(Source, "SuppAllocs");
SuppSpecs = FindFirst(Source, "SuppSpecs");
RumSpecs = FindFirst(Source, "RumSpecs");
Numbers = FindByNameTag(Source, "Startup ruminant numbers");
Ages = FindByNameTag(Source, "Startup ruminant ages");
Weights = FindByNameTag(Source, "Startup ruminant weights");
Prices = FindByNameTag(Source, "Ruminant prices");
Fodder = FindFirst(Source, "Fodder");
FodderSpecs = FindFirst(Source, "FodderSpecs");
// List of all possible breeds
Breeds = SuppAllocs.Element("ColumnNames").Elements().Select(e => e.Value).ToList();
// Index of each breed
var indices = from breed in Breeds
select Breeds.IndexOf(breed);
// Breeds that have a presence in the simulation
PresentBreeds = from index in indices
where (
// The total number of each breed
from cohort in Numbers.Elements().Skip(1)
select Convert.ToInt32(cohort.Elements().ToList()[index].Value)
).Sum() > 0
// Breeds with a non-zero number of ruminants present
select Breeds.ElementAt(index);
}
public void Dispose()
{
// Dispose of unmanaged resources.
Dispose(true);
// Suppress finalization.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed) return;
if (disposing)
{
}
disposed = true;
}
}
}
<file_sep>using Models;
using Models.CLEM;
using Models.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace Reader
{
public partial class IAT
{
public static void Run(IEnumerable<string> files)
{
Shared.OpenErrorLog();
Simulations simulations = new Simulations(null);
foreach (string file in files)
{
// Read in the IAT
IAT iat = new IAT(file);
Folder folder = new Folder(simulations) { Name = iat.Name };
// Find all the parameter sheets in the IAT
List<string> sheets = new List<string>();
foreach (Sheet sheet in iat.Book.Workbook.Sheets)
{
// Ensure a parameter sheet is selected
string name = sheet.Name.ToString();
if (!name.ToLower().Contains("param")) continue;
iat.SetSheet(name);
}
// Files will already be written if groupSims is false
if (!GroupSims) continue;
// Collect all the IAT files in the same .apsimx file
if (GroupSheets) simulations.Children.Add(folder);
// Only gather parameter sets into the same .apsimx file
else
{
Shared.WriteApsimX(simulations, iat.Name);
simulations = new Simulations(null);
}
}
if (GroupSheets) Shared.WriteApsimX(simulations, "Simulations");
Shared.CloseErrorLog();
}
public static void Run(IEnumerable<Tuple<string, string>> files)
{
Shared.OpenErrorLog();
Simulations simulations = new Simulations(null);
IAT iat;
Folder folder = null;
foreach (var file in files)
{
// Cancel the conversion
if (Shared.Worker.CancellationPending)
{
Shared.CloseErrorLog();
return;
}
// Read in the IAT
try
{
iat = new IAT(file.Item1);
}
catch (ConversionException)
{
Shared.WriteError(new ErrorData()
{
FileName = Path.GetFileName(file.Item1),
FileType = "IAT",
Message = "The file could not be read",
Sheet = "-",
Table = "-",
Severity = "High"
});
continue;
}
if (GroupSims && GroupSheets) folder = new Folder(simulations) { Name = iat.Name };
if (file.Item2 != "All")
{
iat.SetSheet(file.Item2);
AttachParameterSheet(simulations, iat);
// Update the Progress bar
Shared.Worker?.ReportProgress(0);
}
else
{
// Find all the parameter sheets in the IAT
foreach (Sheet sheet in iat.Book.Workbook.Sheets)
{
// Cancel the conversion
if (Shared.Worker.CancellationPending)
{
Shared.CloseErrorLog();
return;
}
// Ensure a parameter sheet is selected
string name = sheet.Name.ToString();
if (!name.ToLower().Contains("param")) continue;
iat.SetSheet(name);
if (GroupSims && GroupSheets) AttachParameterSheet(folder, iat);
else AttachParameterSheet(simulations, iat);
iat.ClearTables();
// Update the Progress bar
Shared.Worker?.ReportProgress(0);
}
}
if (!GroupSims)
{
Shared.WriteApsimX(simulations, iat.Name);
simulations = new Simulations(null);
}
else if (GroupSheets)
{
simulations.Add(folder);
}
iat.Dispose();
GC.WaitForPendingFinalizers();
}
if (GroupSims) Shared.WriteApsimX(simulations, "Simulations");
Shared.CloseErrorLog();
}
// Creates a node structure from the IAT, using the set Sheet
private static void AttachParameterSheet(Node node, IAT iat)
{
node.Source = iat;
Simulation simulation = new Simulation(node)
{
Name = iat.ParameterSheet.Name
};
node.Children.Add(simulation);
iat.ClearTables();
}
public Clock GetClock(Simulation simulation)
{
int start_year = Convert.ToInt32(GetCellValue(Part, 44, 4));
int start_month = Convert.ToInt32(GetCellValue(Part, 45, 4));
int run_time = Convert.ToInt32(GetCellValue(Part, 46, 4));
DateTime start = new DateTime(start_year, start_month, 1, 0, 0, 0, 0);
DateTime end = start.AddYears(run_time);
return new Clock(simulation)
{
StartDate = start,
EndDate = end
};
}
/// <summary>
/// IAT does not use GRASP files, so an empty element is returned
/// </summary>
public IEnumerable<Node> GetFiles(ZoneCLEM clem)
{
List<Node> files = new List<Node>();
// Add the crop
files.Add(new FileCrop(clem)
{
FileName = clem.Source.Name + "\\FileCrop.prn",
Name = "FileCrop"
});
// Add the crop residue
files.Add(new FileCrop(clem)
{
FileName = clem.Source.Name + "\\FileCropResidue.prn",
Name = "FileCropResidue"
});
// Add the forage crop
files.Add(new FileCrop(clem)
{
FileName = clem.Source.Name + "\\FileForage.prn",
Name = "FileForage"
});
return files.AsEnumerable();
}
/// <summary>
/// Accesses the crop inputs of an IAT file and moves the crop data to an independent PRN file
/// </summary>
/// <param name="crop">The worksheet object containing crop inputs</param>
/// <param name="name">The name of the output file</param>
public void WriteCropPRN()
{
string path = $"{Shared.OutDir}/{Name}/FileCrop.prn";
try
{
// Overwrite any exisiting PRN file
using (FileStream stream = new FileStream(path, FileMode.Create))
using (StreamWriter writer = new StreamWriter(stream))
{
// Find the data set
WorksheetPart crop = (WorksheetPart)Book.GetPartById(SearchSheets("crop_inputs").Id);
var rows = crop.Worksheet.Descendants<Row>().Skip(1);
// Write file header to output stream
writer.WriteLine($"{"SoilNum",-35}{"CropName",-35}{"YEAR",-35}{"Month",-35}{"AmtKg",-35}");
writer.WriteLine($"{"()",-35}{"()",-35}{"()",-35}{"()",-35}()");
// Iterate over data, writing to output stream
string SoilNum, CropName, YEAR, Month, AmtKg;
foreach (Row row in rows)
{
var cells = row.Descendants<Cell>();
if (cells.First().InnerText != Climate) continue;
SoilNum = ParseCell(cells.ElementAt(1));
CropName = ParseCell(cells.ElementAt(3)).Replace(" ", "");
YEAR = ParseCell(cells.ElementAt(5));
Month = ParseCell(cells.ElementAt(6));
AmtKg = ParseCell(cells.ElementAt(7));
// Writing row to file
if (AmtKg == "") AmtKg = "0";
writer.WriteLine($"{SoilNum,-35}{CropName,-35}{YEAR,-35}{Month,-35}{AmtKg}");
}
}
}
catch (IOException)
{
// Should only be caught if the file exists and is in use by another program;
// Alerts the user then safely continues with the program.
Shared.WriteError(new ErrorData()
{
FileName = Name,
FileType = "IAT",
Message = "FileCrop.prn was open in another application.",
Severity = "Low",
Table = "-",
Sheet = "crop_inputs"
});
}
catch (Exception e)
{
Shared.WriteError(new ErrorData()
{
FileName = Name,
FileType = "IAT",
Message = e.Message,
Severity = "Moderate",
Table = "-",
Sheet = "crop_inputs"
});
}
}
/// <summary>
/// Accesses the crop inputs of an IAT file and moves the residue data to an independent PRN file
/// </summary>
/// <param name="crop">The worksheet object containing crop inputs</param>
/// <param name="name">The name of the output file</param>
public void WriteResiduePRN()
{
string path = $"{Shared.OutDir}/{Name}/FileCropResidue.prn";
try
{
using (FileStream stream = new FileStream(path, FileMode.Create))
using (StreamWriter writer = new StreamWriter(stream))
{
WorksheetPart residue = (WorksheetPart)Book.GetPartById(SearchSheets("crop_inputs").Id);
// Add header to document
writer.WriteLine($"{"SoilNum",-35}{"CropName",-35}{"YEAR",-35}{"Month",-35}{"AmtKg",-35}Npct");
writer.WriteLine($"{"()",-35}{"()",-35}{"()",-35}{"()",-35}{"()",-35}()");
// Iterate over spreadsheet data and copy to output stream
string SoilNum, ForageName, YEAR, Month, AmtKg, Npct;
var rows = residue.Worksheet.Descendants<Row>().Skip(1);
foreach (Row row in rows)
{
var cells = row.Descendants<Cell>();
if (cells.First().InnerText != Climate) continue;
SoilNum = ParseCell(cells.ElementAt(1));
ForageName = ParseCell(cells.ElementAt(3)).Replace(" ", "");
YEAR = ParseCell(cells.ElementAt(5));
Month = ParseCell(cells.ElementAt(6));
AmtKg = ParseCell(cells.ElementAt(8));
Npct = ParseCell(cells.ElementAt(9));
// Writing row to file
if (AmtKg == "") AmtKg = "0";
writer.WriteLine($"{SoilNum,-35}{ForageName,-35}{YEAR,-35}{Month,-35}{AmtKg,-35}{Npct}");
}
}
}
catch (IOException)
{
// Should only be caught if the file exists and is in use by another program;
// Alerts the user then safely continues with the program.
Shared.WriteError(new ErrorData()
{
FileName = Name,
FileType = "IAT",
Message = "FileCropResidue.prn was open in another application.",
Severity = "Low",
Table = "-",
Sheet = "crop_inputs"
});
}
catch (Exception e)
{
Shared.WriteError(new ErrorData()
{
FileName = Name,
FileType = "IAT",
Message = e.Message,
Severity = "Moderate",
Table = "-",
Sheet = "crop_inputs"
});
}
}
/// <summary>
/// Accesses the forage inputs of an IAT file and moves the data to an independent PRN file
/// </summary>
/// <param name="crop">The worksheet object containing forage inputs</param>
/// <param name="name">The name of the output file</param>
public void WriteForagePRN()
{
string path = $"{Shared.OutDir}/{Name}/FileForage.prn";
try
{
using (FileStream stream = new FileStream(path, FileMode.Create))
using (StreamWriter writer = new StreamWriter(stream))
{
WorksheetPart forage = (WorksheetPart)Book.GetPartById(SearchSheets("forage_inputs").Id);
var rows = forage.Worksheet.Descendants<Row>().Skip(1);
// Add header to document
writer.WriteLine($"{"SoilNum",-36}{"CropName",-36}{"YEAR",-36}{"Month",-36}{"AmtKg",-36}Npct");
writer.WriteLine($"{"()",-36}{"()",-36}{"()",-36}{"()",-36}{"()",-36}()");
// Strings for holding data
string SoilNum, ForageName, YEAR, Month, AmtKg, Npct;
// Iterate over spreadsheet data and copy to output stream
foreach (Row row in rows)
{
var cells = row.Descendants<Cell>();
if (cells.First().InnerText != Climate) continue;
SoilNum = ParseCell(cells.ElementAt(1));
ForageName = ParseCell(cells.ElementAt(3)).Replace(" ", "");
YEAR = ParseCell(cells.ElementAt(5));
Month = ParseCell(cells.ElementAt(7));
AmtKg = ParseCell(cells.ElementAt(8));
Npct = ParseCell(cells.ElementAt(9));
// Write row to file
if (AmtKg == "") AmtKg = "0";
writer.WriteLine($"{SoilNum,-36}{ForageName,-36}{YEAR,-36}{Month,-36}{AmtKg,-36}{Npct}");
}
}
}
catch (IOException)
{
// Should only be caught if the file exists and is in use by another program;
// Alerts the user then safely continues with the program.
Shared.WriteError(new ErrorData()
{
FileName = Name,
FileType = "IAT",
Message = "FileForage.prn was open in another application.",
Severity = "Low",
Table = "-",
Sheet = "forage_inputs"
});
}
catch (Exception e)
{
Shared.WriteError(new ErrorData()
{
FileName = Name,
FileType = "IAT",
Message = e.Message,
Severity = "Moderate",
Table = "-",
Sheet = "forage_inputs"
});
}
}
/// <summary>
/// Parses a cell and returns its value in string representation
/// </summary>
/// <param name="cell">The cell to parse</param>
public string ParseCell(Cell cell)
{
// Access the cell contents
string value = "";
if (cell.CellValue != null) value = cell.CellValue.InnerText;
if (cell.DataType != null)
{
// If the CellValue is a shared string, look through the shared table for its value
if (cell.DataType.Value == CellValues.SharedString)
{
value = StringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
}
// If the CellValue is a bool, convert it into true/false text
else if (cell.DataType.Value == CellValues.Boolean)
{
if (value == "0") value = "False";
else value = "True";
}
// else the CellValue must be numeric, so return the contents directly
}
return value;
}
/// <summary>
/// Return the value of a worksheet cell by position
/// </summary>
/// <param name="part">The part of the worksheet which contains the cells</param>
/// <param name="row">The 1-based row index of the cell in the spreadsheet</param>
/// <param name="col">The 1-based column index of the cell in the spreadsheet</param>
public string GetCellValue(WorksheetPart part, int row, int col)
{
// Convert the cell position into a CellReference (e.g. 3, 2 to B3)
string coord = GetColReference(col) + row.ToString();
// Find the cell by its reference
Cell cell = part.Worksheet.Descendants<Cell>().
Where(c => c.CellReference == coord).FirstOrDefault();
if (cell == null) return "";
// Access the data in the cell
return ParseCell(cell);
}
/// <summary>
/// Converts an integer from base-10 to base-26 (represented by the English alphabet)
/// </summary>
/// <param name="i">Integer to convert</param>
private static string GetColReference(int i)
{
// Consider Z as the 0th letter, rather than the 26th, for safer indexing
const string alphabet = "ZABCDEFGHIJKLMNOPQRSTUVWXY";
string result = "";
char digit;
while (i > 0)
{
// Find the lowest order digit
digit = alphabet[i % 26];
// Prepend the digit to the result
result = digit + result;
// Use integer division to 'delete' the lowest order digit
i = i / 26;
}
return result;
}
}
}
<file_sep>using Models.CLEM.Reporting;
using Models.CLEM.Resources;
namespace Models.CLEM.Activities
{
/// <summary>
/// Generic base node for all activity models.
/// This node should not be instantiated directly.
/// </summary>
public class ActivityNode : Node
{
public object SelectedTab { get; set; } = null;
public int OnPartialResourcesAvailableAction { get; set; } = 0;
public ActivityNode(Node parent) : base(parent)
{ }
}
/// <summary>
/// The activities holder is the model which contains all other activities.
/// </summary>
public class ActivitiesHolder : Node
{
public string LastShortfallResourceRequest { get; set; }
public string LastActivityPerformed { get; set; }
public ActivitiesHolder(ZoneCLEM parent) : base(parent)
{
Name = "Activities";
// Model the finance activities
GetCashFlow();
// Model the crop growth activities
ActivityFolder crops = new ActivityFolder(this) { Name = "Manage crops" };
crops.Add(Source.GetManageCrops(crops));
Add(crops);
// Model the forage growth activities
ActivityFolder forages = new ActivityFolder(this) { Name = "Manage forages" };
forages.Add(Source.GetManageForages(forages));
if (forages.Children.Count > 0) forages.Add(Source.GetNativePasture(forages));
Add(forages);
// Model the ruminant activities
GetHerd();
// Model the pasture management
Add(Source.GetManagePasture(this));
// Attach summary/report
Add(new SummariseRuminantHerd(this));
Add(new ReportRuminantHerd(this));
}
/// <summary>
/// Models the finances in the simulation
/// </summary>
private void GetCashFlow()
{
ActivityFolder cashflow = new ActivityFolder(this)
{
Name = "CashFlow"
};
cashflow.Add(Source.GetMonthlyExpenses(cashflow));
cashflow.Add(Source.GetAnnualExpenses(cashflow));
cashflow.Add(Source.GetInterestRates(cashflow));
Add(cashflow);
}
/// <summary>
/// Models the management of the ruminant herd in the simulation
/// </summary>
private void GetHerd()
{
ActivityFolder herd = new ActivityFolder(this){Name = "Manage herd"};
herd.Add(Source.GetManageBreeds(herd));
herd.Add(GetFeed(herd));
herd.Add(new RuminantActivityGrazeAll(herd));
herd.Add(new RuminantActivityGrow(herd));
herd.Add(new RuminantActivityBreed(herd));
herd.Add(new RuminantActivityBuySell(herd));
herd.Add(new RuminantActivityMuster(herd));
Add(herd);
}
/// <summary>
/// Add a RuminantActivityFeed for each item in the AnimalFoodStore
/// </summary>
private ActivityFolder GetFeed(ActivityFolder herd)
{
AnimalFoodStore store = SearchTree<AnimalFoodStore>((ZoneCLEM)Parent);
if (store.Children.Count == 0) return null;
ActivityFolder feed = new ActivityFolder(herd) { Name = "Feed ruminants" };
foreach (Node child in store.Children)
{
feed.Add(new RuminantActivityFeed(feed)
{
Name = "Feed " + child.Name,
FeedTypeName = "AnimalFoodStore." + child.Name
});
}
return feed;
}
}
/// <summary>
/// A miscellaneous container for activities
/// </summary>
public class ActivityFolder : ActivityNode
{
public ActivityFolder(Node parent) : base(parent)
{ }
}
/// <summary>
/// Models the frequency with which an activity is performed
/// </summary>
public class ActivityTimerInterval : Node
{
public int Interval { get; set; } = 12;
public int MonthDue { get; set; } = 12;
public ActivityTimerInterval(Node parent) : base(parent)
{ }
}
/// <summary>
/// Models the relationship between two variables
/// </summary>
public class Relationship : Node
{
public double StartingValue { get; set; } = 0;
public double Minimum { get; set; } = 0;
public double Maximum { get; set; } = 0;
public double[] XValues { get; set; } = new[] { 0.0, 20.0, 30.0, 100.0 };
public double[] YValues { get; set; } = new[] { -0.625, -0.125, 0, 0.75 };
public Relationship(Node parent) : base(parent)
{ }
}
}
<file_sep>namespace Models.CLEM.Resources
{
/// <summary>
/// Container for different feed given to ruminants
/// </summary>
public class AnimalFoodStore : Node
{
public AnimalFoodStore(Node parent) : base(parent)
{
Name = "AnimalFoodStore";
Add(Source.GetAnimalStoreTypes(this));
Add(Source.GetCommonFoodStore(this));
}
}
/// <summary>
/// Models a generic fodder type
/// </summary>
public class AnimalFoodStoreType : Node
{
public double DMD { get; set; } = 0.01;
public string Units { get; set; } = "kg";
public double Nitrogen { get; set; } = 0.01;
public double StartingAmount { get; set; } = 0.01;
public AnimalFoodStoreType(Node parent) : base(parent)
{ }
}
/// <summary>
/// Models the food type of shared land
/// </summary>
public class CommonLandFoodStoreType : Node
{
public double NToDMDCoefficient { get; set; } = 0;
public double NToDMDIntercept { get; set; } = 0;
public double NToDMDCrudeProteinDenominator { get; set; } = 0;
public double Nitrogen { get; set; } = 0;
public double MinimumNitrogen { get; set; } = 0;
public double MinimumDMD { get; set; } = 0;
public string PastureLink { get; set; } = "GrazeFoodStore.NativePasture";
public double NitrogenReductionFromPasture { get; set; } = 0;
public CommonLandFoodStoreType(Node parent) : base(parent)
{ }
}
/// <summary>
/// Container for feed types found in grazing land
/// </summary>
public class GrazeFoodStore : Node
{
public GrazeFoodStore(Node parent) : base(parent)
{
Name = "GrazeFoodStore";
Add(Source.GetGrazeFoodStore(this));
}
}
/// <summary>
/// Models a generic food type sourced from grazing land
/// </summary>
public class GrazeFoodStoreType : Node
{
public double NToDMDCoefficient { get; set; } = 0.0;
public double NToDMDIntercept { get; set; } = 0.0;
public double NToDMDCrudeProteinDenominator { get; set; } = 0.0;
public double GreenNitrogen { get; set; } = 0.0;
public double DecayNitrogen { get; set; } = 0.0;
public double MinimumNitrogen { get; set; } = 0.0;
public double DecayDMD { get; set; } = 0.0;
public double MinimumDMD { get; set; } = 0.0;
public double DetachRate { get; set; } = 0.0;
public double CarryoverDetachRate { get; set; } = 0.0;
public double IntakeTropicalQualityCoefficient { get; set; } = 0.0;
public double IntakeQualityCoefficient { get; set; } = 0.0;
public string Units { get; set; }
public GrazeFoodStoreType(Node parent) : base(parent)
{
Name = "NativePasture";
}
}
/// <summary>
/// Container for food consumed by humans
/// </summary>
public class HumanFoodStore : Node
{
public HumanFoodStore(Node parent) : base(parent)
{
Name = "HumanFoodStore";
Add(Source.GetHumanStoreTypes(this));
}
}
/// <summary>
/// Models a generic type of human food
/// </summary>
public class HumanFoodStoreType : Node
{
public double StartingAge { get; set; } = 0;
public double StartingAmount { get; set; } = 0;
public HumanFoodStoreType(Node parent) : base(parent)
{ }
}
/// <summary>
/// Container for arbitrary products
/// </summary>
public class ProductStore : Node
{
public ProductStore(ResourcesHolder parent) : base(parent)
{
Name = "ProductStore";
Add(Source.GetProductStoreTypes(this));
}
}
/// <summary>
/// Models an arbitrary product type
/// </summary>
public class ProductStoreType : Node
{
public double StartingAmount { get; set; } = 0.0;
public string Units { get; set; } = "kg";
public ProductStoreType(ProductStore parent) : base(parent)
{ }
}
}
<file_sep>using Models.CLEM.Activities;
using System;
using System.Collections.Generic;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace Reader
{
// Implements all methods related to IAT grain crops
public partial class IAT
{
/// <summary>
/// Search the grown crops for all valid crop types, and track
/// them in the GrainIDs list
/// </summary>
private void SetGrains()
{
GrainIDs = new List<int>();
// Row of crop IDs
var crops = CropsGrown.GetRowData<int>(0);
// Row of area allocated to crop
var areas = CropsGrown.GetRowData<double>(2);
// Select all non-zero IDs
var ids =
from id in crops
where id != 0
select id;
foreach (int id in ids)
{
int index = crops.IndexOf(id);
// Check the crop has growing area
if (areas.ElementAt(index) <= 0) continue;
// Add the crop to the list of grown grains
if (!GrainIDs.Exists(i => i == id)) GrainIDs.Add(id);
}
}
/// <summary>
/// Finds all crops in the source IAT which require management
/// </summary>
public IEnumerable<CropActivityManageCrop> GetManageCrops(ActivityFolder manage)
{
List<CropActivityManageCrop> crops = new List<CropActivityManageCrop>();
int[] ids = CropsGrown.GetRowData<int>(0).ToArray();
// Find the name of the crop in the file
Sheet sheet = SearchSheets("crop_inputs");
WorksheetPart inputs = (WorksheetPart)Book.GetPartById(sheet.Id);
// Find the name of the crop
int rows = sheet.Elements<Row>().Count();
foreach (int id in GrainIDs)
{
string name = "Unknown";
int row = 1;
while (row < rows)
{
if (GetCellValue(inputs, row, 3) == id.ToString())
{
name = GetCellValue(inputs, row, 4);
break;
}
row++;
}
// Find which column holds the data for a given crop ID
int col = Array.IndexOf(ids, id);
// Find names
int land = CropsGrown.GetData<int>(1, col);
string cropname = CropSpecs.RowNames[id + 1];
// Model the crop management
CropActivityManageCrop crop = new CropActivityManageCrop(manage)
{
Name = "Manage " + cropname,
LandItemNameToUse = LandSpecs.RowNames[land - 1],
AreaRequested = CropsGrown.GetData<double>(2, col)
};
// Find the storage pool which the crop uses
string pool = Pools.Values.ToList().Find(s => s.Contains(cropname));
// Add the product management model
crop.Add(new CropActivityManageProduct(crop)
{
Name = "Manage grain",
ModelNameFileCrop = "FileCrop",
CropName = name,
ProportionKept = 1.0 - CropsGrown.GetData<double>(5, col) / 100.0,
StoreItemName = "HumanFoodStore." + pool
});
// Add the residue management
crop.Add(new CropActivityManageProduct(crop)
{
Name = "Manage residue",
ModelNameFileCrop = "FileCropResidue",
CropName = name,
ProportionKept = CropsGrown.GetData<double>(4, col) / 100.0,
StoreItemName = "AnimalFoodStore." + pool
});
crops.Add(crop);
}
return crops;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Reader
{
public partial class NABSA
{
public string Name { get; set; }
private XElement Source { get; set; }
private XElement SingleParams { get; set; }
private XElement LandSpecs { get; set; }
private XElement Priority { get; set; }
private XElement Supply { get; set; }
private XElement SuppAllocs { get; set; }
private XElement SuppSpecs { get; set; }
private XElement RumSpecs { get; set; }
private XElement Numbers { get; set; }
private XElement Ages { get; set; }
private XElement Weights { get; set; }
private XElement Prices { get; set; }
private XElement Fodder { get; set; }
private XElement FodderSpecs { get; set; }
private List<string> Breeds { get; set; }
private IEnumerable<string> PresentBreeds { get; set; }
private bool disposed = false;
}
}
<file_sep>using Gtk;
using Reader;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace UI
{
/// <summary>
/// A Gtk interface for the main screen of the converter
/// </summary>
class MainScreen
{
public Window window = null;
private Builder builder = null;
private Entry inentry = null;
private Entry outentry = null;
private Button aboutbtn = null;
private Button convertbtn = null;
private Button quitbtn = null;
private Button inbtn = null;
private Button outbtn = null;
private CheckButton allcheck = null;
private CheckButton joincheck = null;
private CheckButton splitcheck = null;
private ComboBox combobox = null;
private VBox listbox = null;
private string path = null;
public MainScreen()
{
builder = Tools.ReadGlade("MainMenu");
// Main window
window = (Window)builder.GetObject("window");
window.Title = "CLEM File Converter";
window.Icon = new Gdk.Pixbuf($"{Directory.GetCurrentDirectory()}/UI/Resources/Maize.png");
window.Destroyed += OnQuitClicked;
// Entry boxes
inentry = (Entry)builder.GetObject("inentry");
outentry = (Entry)builder.GetObject("outentry");
path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
inentry.Text = path;
outentry.Text = path;
inentry.Changed += OnInentryChanged;
outentry.Changed += OnOutentryChanged;
// Buttons
aboutbtn = (Button)builder.GetObject("aboutbtn");
convertbtn = (Button)builder.GetObject("convertbtn");
quitbtn = (Button)builder.GetObject("quitbtn");
inbtn = (Button)builder.GetObject("inbtn");
outbtn = (Button)builder.GetObject("outbtn");
// Button events
aboutbtn.Clicked += OnAboutClicked;
convertbtn.Clicked += OnConvertClicked;
quitbtn.Clicked += OnQuitClicked;
inbtn.Clicked += OnInClicked;
outbtn.Clicked += OnOutClicked;
// Check buttons
allcheck = (CheckButton)builder.GetObject("allcheck");
joincheck = (CheckButton)builder.GetObject("joincheck");
splitcheck = (CheckButton)builder.GetObject("splitcheck");
allcheck.Toggled += OnAllToggled;
joincheck.Toggled += OnJoinToggled;
// Combo boxes
combobox = (ComboBox)builder.GetObject("combobox");
Tools.AddStoreToCombo(combobox);
combobox.AppendText("IAT");
combobox.AppendText("NABSA");
combobox.Active = 0;
combobox.Changed += OnComboChanged;
// VBoxes
listbox = (VBox)builder.GetObject("listbox");
SetListItems(null, null);
}
private void OnJoinToggled(object sender, EventArgs e)
{
if (joincheck.Active)
{
splitcheck.Active = false;
splitcheck.Sensitive = false;
}
else
{
splitcheck.Sensitive = true;
}
}
private void OnComboChanged(object sender, EventArgs e)
{
SetListItems(null, null);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnInentryChanged(object sender, EventArgs e)
{
if (Directory.Exists(inentry.Text))
{
Shared.InDir = inentry.Text;
path = inentry.Text;
SetListItems(null, null);
}
}
private void OnOutentryChanged(object sender, EventArgs e)
{
if (Directory.Exists(outentry.Text))
{
Shared.OutDir = outentry.Text;
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnAllToggled(object sender, EventArgs e)
{
foreach (CheckButton child in listbox.AllChildren)
{
child.Active = allcheck.Active;
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SetListItems(object sender, EventArgs e)
{
string pattern;
if (combobox.ActiveText == "IAT") pattern = "*.xlsx";
else pattern = "*.nabsa";
// Clear existing children
foreach (CheckButton child in listbox.AllChildren)
{
listbox.Remove(child);
}
string[] files = Directory.GetFiles(inentry.Text, pattern, SearchOption.TopDirectoryOnly);
foreach (string item in files)
{
string label = Path.GetFileName(item);
CheckButton check = new CheckButton()
{
Sensitive = true,
Visible = true,
Label = label
};
listbox.PackStart(check, false, false, 0);
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnAboutClicked(object sender, EventArgs e)
{
var icon = new Gdk.Pixbuf($"{Directory.GetCurrentDirectory()}/UI/Resources/Maize.png");
AboutDialog about = new AboutDialog()
{
ProgramName = "CLEM File Converter",
Version = "1.0",
Copyright = "(c) CSIRO",
Comments = "A tool for converting IAT & NABSA files to CLEM files (run through ApsimX)",
Logo = icon,
Icon = icon
};
about.Run();
about.Destroy();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnConvertClicked(object sender, EventArgs e)
{
// Ensure the output directory exists
if (!Directory.Exists(outentry.Text))
{
try
{
Directory.CreateDirectory(outentry.Text);
}
catch
{
new DialogBox("Invalid output directory.");
return;
}
}
List<string> files = new List<string>();
foreach (CheckButton child in listbox.AllChildren)
{
if (child.Active)
{
files.Add(path + "/" + child.Label);
}
}
switch (combobox.ActiveText)
{
case "IAT":
IAT.GroupSheets = joincheck.Active;
IAT.GroupSims = splitcheck.Active;
IAT.Run(files);
break;
case "NABSA":
NABSA.Run(files);
break;
default:
break;
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnQuitClicked(object sender, EventArgs e)
{
Detach();
Application.Quit();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnOutClicked(object sender, EventArgs e)
{
outbtn.Sensitive = false;
SelectFolder selecter = new SelectFolder(outbtn, outentry);
selecter.window.ShowAll();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnInClicked(object sender, EventArgs e)
{
inbtn.Sensitive = false;
SelectFolder selecter = new SelectFolder(inbtn, inentry);
selecter.selected += SetListItems;
selecter.window.ShowAll();
}
private void Detach()
{
window.Destroyed -= OnQuitClicked;
inentry.Changed -= OnInentryChanged;
outentry.Changed -= OnOutentryChanged;
aboutbtn.Clicked -= OnAboutClicked;
convertbtn.Clicked -= OnConvertClicked;
quitbtn.Clicked -= OnQuitClicked;
inbtn.Clicked -= OnInClicked;
outbtn.Clicked -= OnOutClicked;
allcheck.Toggled -= OnAllToggled;
}
}
}
<file_sep>namespace Models.CLEM.Groupings
{
/// <summary>
/// The price of a group of ruminants (filters can be applied to the group)
/// </summary>
public class AnimalPriceGroup : Node
{
public int PricingStyle { get; set; } = 0;
public double Value { get; set; } = 0.0;
public int PurchaseOrSale { get; set; } = 0;
public AnimalPriceGroup(Node parent) : base(parent)
{ }
}
/// <summary>
/// Filters the present ruminants by parameter and value
/// </summary>
public class RuminantFilter : Node
{
public int Parameter { get; set; } = 0;
public int Operator { get; set; } = 0;
public string Value { get; set; } = "";
public RuminantFilter(Node parent) : base(parent)
{ }
}
}
<file_sep>using System.Collections.Generic;
namespace Models.CLEM.Reporting
{
/// <summary>
/// The base node for a report, this should not be instantiated directly
/// </summary>
class Report : Node
{
public List<string> ExperimentFactorNames = new List<string>();
public List<string> ExperimentFactorValues = new List<string>();
public List<string> VariableNames = new List<string>();
public List<string> EventNames = new List<string>();
public Report(Node parent) : base(parent)
{ }
}
/// <summary>
/// Report the balance of resources
/// </summary>
class ReportResourceBalances : Report
{
public ReportResourceBalances(Node parent) : base(parent)
{
Name = "ReportResourceBalances";
}
}
/// <summary>
/// Report the activities performed
/// </summary>
class ReportActivitiesPerformed : Report
{
public ReportActivitiesPerformed(Node parent) : base(parent)
{
Name = "ReportActivitiesPerformed";
}
}
/// <summary>
/// Report any shortfalls of a particular resource
/// </summary>
class ReportResourceShortfalls : Report
{
public ReportResourceShortfalls(Node parent) : base(parent)
{
Name = "ReportResourceShortfalls";
}
}
/// <summary>
/// Report the status of an arbitrary resource
/// </summary>
class ReportResourceLedger : Report
{
public ReportResourceLedger(Node parent) : base(parent)
{ }
}
/// <summary>
/// Report the status of the ruminant herd
/// </summary>
public class ReportRuminantHerd : Node
{
public ReportRuminantHerd(Node parent) : base(parent)
{
Name = "ReportHerd";
}
}
}
<file_sep>namespace Models.CLEM.Groupings
{
/// <summary>
/// Filters the labourers by the selected parameter and value
/// </summary>
public class LabourFilter : Node
{
public int Parameter { get; set; } = 0;
public int Operator { get; set; } = 0;
public string Value { get; set; } = "";
public LabourFilter(Node parent) : base(parent)
{
Name = "LabourFilter";
}
}
/// <summary>
/// The result of a collection of individual labour filters
/// </summary>
public class LabourFilterGroup : Node
{
public LabourFilterGroup(Node parent) : base(parent)
{ }
}
}
<file_sep>using Models.CLEM.Activities;
using Models.CLEM.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Reader
{
public partial class NABSA
{
/// <summary>
/// Builds the 'Land' subsection
/// </summary>
/// <param name="nab">Source NABSA</param>
public IEnumerable<LandType> GetLandTypes(Land land)
{
List<LandType> types = new List<LandType>();
var items = LandSpecs.Elements().ToArray();
for (int i = 2; i < items.Length; i++)
{
var data = items[i].Elements().ToArray();
if (data[0].Value != "0")
{
LandType type = new LandType(land)
{
Name = items[i].Name.LocalName,
LandArea = Convert.ToDouble(data[0].Value),
SoilType = Convert.ToInt32(data[3].Value)
};
types.Add(type);
}
}
return types;
}
public PastureActivityManage GetManagePasture(ActivitiesHolder folder)
{
PastureActivityManage pasture = new PastureActivityManage(folder){};
pasture.Add(new Relationship(pasture)
{
Name = "LandConditionIndex",
StartingValue = Convert.ToDouble(FindFirst(Source, "Land_con").Value),
Minimum = 1,
Maximum = 8
});
pasture.Add(new Relationship(pasture)
{
Name = "GrassBasalArea",
StartingValue = Convert.ToDouble(FindFirst(Source, "Grass_BA").Value),
Minimum = 1,
Maximum = Convert.ToDouble(FindFirst(Source, "GBAmax").Value),
YValues = new[] { -0.95, -0.15, 0, 1.05 }
});
return pasture;
}
}
}
|
87ef2b65d0512a68000869c650e50036b900f610
|
[
"Markdown",
"C#"
] | 56 |
C#
|
sto276/CLEM_Converters
|
ad5b080cae13fefca3578811b635cd4cca636c62
|
23b96172a2ed90a49f1c4059577986647bc269c2
|
refs/heads/master
|
<file_sep>// let mainH3 = document.getElementsByClassName("h3-animated")[0];
let textHover1 = document.getElementsByClassName("work__link")[0];
let textHover2 = document.getElementsByClassName("work__link")[1];
let textHover3 = document.getElementsByClassName("work__link")[2];
let hider;
let imgAnimated;
let h3Animated;
let paraAnimated;
let h3,
para,
img,
init,
hover,
hiddenShow,
hiddenHide,
mainShow,
hiddenIcon,
showIcon;
function showWork(num) {
if (hover) {
hideWork();
hiddenIcon.kill();
}
gsap.to(`.h3-animated--${num}`, {
opacity: 1,
y: 0,
duration: 0,
});
gsap.to(`.paragraph-animated--${num}`, {
opacity: 1,
y: 0,
duration: 0,
});
gsap.to(`.img-animated--${num}`, {
y: 0,
opacity: 1,
duration: 0,
});
if (init) {
hiddenHide.kill();
paraAnimated.kill();
imgAnimated.kill();
h3.kill();
para.kill();
img.kill();
}
mainShow = gsap.to(`.work__main--${num}`, {
visibility: "visible",
});
h3 = gsap.from(`.h3-animated--${num}`, {
opacity: 0,
y: 100,
duration: 0.65,
ease: "back.out(1.4)",
});
para = gsap.from(`.paragraph-animated--${num}`, {
opacity: 0,
delay: 0.1,
y: 100,
duration: 0.65,
ease: "back.out(1.4)",
});
img = gsap.from(`.img-animated--${num}`, {
opacity: 0,
delay: 0.18,
y: 100,
duration: 0.65,
ease: "back.out(1.8)",
});
hiddenShow = gsap.to(`.work__hidden`, {
opacity: 0,
duration: 0.25,
});
showIcon = gsap.to(`.work__icon--${num}`, {
opacity: 1,
duration: 0.3,
visibility: "visible",
});
hover = true;
init = true;
}
gsap.to(`.work__main`, {
visibility: "hidden",
});
showWork("1");
hideWork("1");
function hideWork(num) {
for (i = 0; i < 3; i++) {
h3Animated = gsap.to(`.h3-animated--${num}`, {
opacity: 0,
duration: 0.4,
ease: "back.out(1.4)",
});
paraAnimated = gsap.to(`.paragraph-animated--${num}`, {
opacity: 0,
duration: 0.4,
ease: "back.out(1.4)",
});
imgAnimated = gsap.to(`.img-animated--${num}`, {
opacity: 0,
duration: 0.4,
ease: "back.out(1.8)",
onComplete: function () {
gsap.to(`.work__main`, {
duration: 0,
visibility: "hidden",
});
},
});
}
// showIcon.kill();
hiddenIcon = gsap.to(`.work__icon`, {
opacity: 0,
duration: 0.3,
});
hover = false;
hiddenShow.kill();
hiddenHide = gsap.to(`.work__hidden`, {
opacity: 1,
delay: 0.05,
duration: 0.3,
});
h3.kill();
para.kill();
img.kill();
mainShow.kill();
}
textHover1.addEventListener("mouseenter", function () {
showWork("1");
});
textHover1.addEventListener("mouseleave", function () {
hideWork("1");
});
textHover2.addEventListener("mouseenter", function () {
showWork("2");
});
textHover2.addEventListener("mouseleave", function () {
hideWork("2");
});
textHover3.addEventListener("mouseenter", function () {
showWork("3");
});
textHover3.addEventListener("mouseleave", function () {
hideWork("3");
});
function activateAnimations() {
gsap.to("#header-main", {
scrollTrigger: {
trigger: ".header__nav",
start: 1,
scrub: 0.5,
end: "100 bottom",
endTrigger: ".skills ",
pinSpacing: false,
// markers: true,
},
height: "42rem",
y: -240,
});
gsap.to("#header-main", {
scrollTrigger: {
trigger: "body",
start: "top top",
scrub: 0,
end: "400 top",
pin: ".header",
// pinSpacing: false,
// markers: true,
},
});
gsap.to(".skills__main", {
scrollTrigger: {
start: "0px top",
scrub: 0.5,
end: "300 top",
// markers: true,
},
y: -725,
});
gsap.to(
".header__planet--red,.header__planet--moon,.header__planet--bluecircle,.header__planet--yellow,.header__planet--blue",
{
scrollTrigger: {
trigger: "body",
start: "top top",
scrub: 0.5,
end: "300 top",
// markers: true,
},
transform: "translateY(-25rem)",
}
);
gsap.to(".header__planet--green,.header__planet--orange", {
scrollTrigger: {
trigger: "body",
start: "top top",
scrub: 0.5,
end: "300 top",
// markers: true,
},
transform: "translateY(-15rem)",
});
gsap.to(".header__paragraph--hidden", {
scrollTrigger: {
trigger: "body",
start: "100 top",
scrub: 0.5,
end: "+=180",
// markers: true,
},
opacity: 1,
right: "4rem",
});
gsap.to(".header__paragraph--hidden", {
scrollTrigger: {
trigger: "body",
start: "top top",
scrub: true,
end: 0,
// markers: true,
},
visibility: "visible",
});
}
ScrollTrigger.matchMedia({
"(min-width: 1225px)": function () {
gsap.to(".header__main", {
duration: 0,
position: "relative",
left: "29%",
top: "50%",
transform: "translate(-25rem, -10rem)",
// margin: "0 auto",
});
activateAnimations();
},
"(max-width: 1226px)": function () {
gsap.to(".header__main", {
duration: 0,
position: "static",
left: "50%",
top: "50%",
transform: "none",
height: "auto",
// margin: "15rem auto 0 auto",
});
},
});
|
9d6fb82abba797dc1ddd9b4637f7e87b6ed71ec6
|
[
"JavaScript"
] | 1 |
JavaScript
|
deadlyrazer/deadlyrazer.github.io
|
3dd08ce67fa8fff30dcf59a32fdfe52078ebdd5f
|
12c4027752315a3c9c846c12b79a213d287d1729
|
refs/heads/master
|
<file_sep>#ifndef COURSE_WORK_BOOK_NODE_H
#define COURSE_WORK_BOOK_NODE_H
#include "book.h"
struct t_book_node
{
t_book value;
t_book_node *next;
};
namespace book_node
{
void init_node(t_book_node *init, t_book_node *next);
void set_next(t_book_node *node, t_book_node *next);
t_book_node* get_next(t_book_node *node);
}
#endif //COURSE_WORK_BOOK_NODE_H<file_sep># CMAKE generated file: DO NOT EDIT!
# Generated by "MinGW Makefiles" Generator, CMake Version 3.13
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
SHELL = cmd.exe
# The CMake executable.
CMAKE_COMMAND = "C:\Program Files\JetBrains\CLion 2018.3.3\bin\cmake\win\bin\cmake.exe"
# The command to remove a file.
RM = "C:\Program Files\JetBrains\CLion 2018.3.3\bin\cmake\win\bin\cmake.exe" -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = C:\ideaProjects\course_work
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = C:\ideaProjects\course_work\cmake-build-debug
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
"C:\Program Files\JetBrains\CLion 2018.3.3\bin\cmake\win\bin\cmake.exe" -E echo "No interactive CMake dialog available."
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
"C:\Program Files\JetBrains\CLion 2018.3.3\bin\cmake\win\bin\cmake.exe" -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start C:\ideaProjects\course_work\cmake-build-debug\CMakeFiles C:\ideaProjects\course_work\cmake-build-debug\CMakeFiles\progress.marks
$(MAKE) -f CMakeFiles\Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start C:\ideaProjects\course_work\cmake-build-debug\CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles\Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles\Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles\Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles\Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named course_work
# Build rule for target.
course_work: cmake_check_build_system
$(MAKE) -f CMakeFiles\Makefile2 course_work
.PHONY : course_work
# fast build rule for target.
course_work/fast:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/build
.PHONY : course_work/fast
main.obj: main.cpp.obj
.PHONY : main.obj
# target to build an object file
main.cpp.obj:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/main.cpp.obj
.PHONY : main.cpp.obj
main.i: main.cpp.i
.PHONY : main.i
# target to preprocess a source file
main.cpp.i:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/main.cpp.i
.PHONY : main.cpp.i
main.s: main.cpp.s
.PHONY : main.s
# target to generate assembly for a file
main.cpp.s:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/main.cpp.s
.PHONY : main.cpp.s
source_files/book_io.obj: source_files/book_io.cpp.obj
.PHONY : source_files/book_io.obj
# target to build an object file
source_files/book_io.cpp.obj:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/book_io.cpp.obj
.PHONY : source_files/book_io.cpp.obj
source_files/book_io.i: source_files/book_io.cpp.i
.PHONY : source_files/book_io.i
# target to preprocess a source file
source_files/book_io.cpp.i:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/book_io.cpp.i
.PHONY : source_files/book_io.cpp.i
source_files/book_io.s: source_files/book_io.cpp.s
.PHONY : source_files/book_io.s
# target to generate assembly for a file
source_files/book_io.cpp.s:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/book_io.cpp.s
.PHONY : source_files/book_io.cpp.s
source_files/book_list.obj: source_files/book_list.cpp.obj
.PHONY : source_files/book_list.obj
# target to build an object file
source_files/book_list.cpp.obj:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/book_list.cpp.obj
.PHONY : source_files/book_list.cpp.obj
source_files/book_list.i: source_files/book_list.cpp.i
.PHONY : source_files/book_list.i
# target to preprocess a source file
source_files/book_list.cpp.i:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/book_list.cpp.i
.PHONY : source_files/book_list.cpp.i
source_files/book_list.s: source_files/book_list.cpp.s
.PHONY : source_files/book_list.s
# target to generate assembly for a file
source_files/book_list.cpp.s:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/book_list.cpp.s
.PHONY : source_files/book_list.cpp.s
source_files/book_node.obj: source_files/book_node.cpp.obj
.PHONY : source_files/book_node.obj
# target to build an object file
source_files/book_node.cpp.obj:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/book_node.cpp.obj
.PHONY : source_files/book_node.cpp.obj
source_files/book_node.i: source_files/book_node.cpp.i
.PHONY : source_files/book_node.i
# target to preprocess a source file
source_files/book_node.cpp.i:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/book_node.cpp.i
.PHONY : source_files/book_node.cpp.i
source_files/book_node.s: source_files/book_node.cpp.s
.PHONY : source_files/book_node.s
# target to generate assembly for a file
source_files/book_node.cpp.s:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/book_node.cpp.s
.PHONY : source_files/book_node.cpp.s
source_files/ref_list.obj: source_files/ref_list.cpp.obj
.PHONY : source_files/ref_list.obj
# target to build an object file
source_files/ref_list.cpp.obj:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/ref_list.cpp.obj
.PHONY : source_files/ref_list.cpp.obj
source_files/ref_list.i: source_files/ref_list.cpp.i
.PHONY : source_files/ref_list.i
# target to preprocess a source file
source_files/ref_list.cpp.i:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/ref_list.cpp.i
.PHONY : source_files/ref_list.cpp.i
source_files/ref_list.s: source_files/ref_list.cpp.s
.PHONY : source_files/ref_list.s
# target to generate assembly for a file
source_files/ref_list.cpp.s:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/ref_list.cpp.s
.PHONY : source_files/ref_list.cpp.s
source_files/ref_node.obj: source_files/ref_node.cpp.obj
.PHONY : source_files/ref_node.obj
# target to build an object file
source_files/ref_node.cpp.obj:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/ref_node.cpp.obj
.PHONY : source_files/ref_node.cpp.obj
source_files/ref_node.i: source_files/ref_node.cpp.i
.PHONY : source_files/ref_node.i
# target to preprocess a source file
source_files/ref_node.cpp.i:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/ref_node.cpp.i
.PHONY : source_files/ref_node.cpp.i
source_files/ref_node.s: source_files/ref_node.cpp.s
.PHONY : source_files/ref_node.s
# target to generate assembly for a file
source_files/ref_node.cpp.s:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/ref_node.cpp.s
.PHONY : source_files/ref_node.cpp.s
source_files/search.obj: source_files/search.cpp.obj
.PHONY : source_files/search.obj
# target to build an object file
source_files/search.cpp.obj:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/search.cpp.obj
.PHONY : source_files/search.cpp.obj
source_files/search.i: source_files/search.cpp.i
.PHONY : source_files/search.i
# target to preprocess a source file
source_files/search.cpp.i:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/search.cpp.i
.PHONY : source_files/search.cpp.i
source_files/search.s: source_files/search.cpp.s
.PHONY : source_files/search.s
# target to generate assembly for a file
source_files/search.cpp.s:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/search.cpp.s
.PHONY : source_files/search.cpp.s
source_files/str_list.obj: source_files/str_list.cpp.obj
.PHONY : source_files/str_list.obj
# target to build an object file
source_files/str_list.cpp.obj:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/str_list.cpp.obj
.PHONY : source_files/str_list.cpp.obj
source_files/str_list.i: source_files/str_list.cpp.i
.PHONY : source_files/str_list.i
# target to preprocess a source file
source_files/str_list.cpp.i:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/str_list.cpp.i
.PHONY : source_files/str_list.cpp.i
source_files/str_list.s: source_files/str_list.cpp.s
.PHONY : source_files/str_list.s
# target to generate assembly for a file
source_files/str_list.cpp.s:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/str_list.cpp.s
.PHONY : source_files/str_list.cpp.s
source_files/str_node.obj: source_files/str_node.cpp.obj
.PHONY : source_files/str_node.obj
# target to build an object file
source_files/str_node.cpp.obj:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/str_node.cpp.obj
.PHONY : source_files/str_node.cpp.obj
source_files/str_node.i: source_files/str_node.cpp.i
.PHONY : source_files/str_node.i
# target to preprocess a source file
source_files/str_node.cpp.i:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/str_node.cpp.i
.PHONY : source_files/str_node.cpp.i
source_files/str_node.s: source_files/str_node.cpp.s
.PHONY : source_files/str_node.s
# target to generate assembly for a file
source_files/str_node.cpp.s:
$(MAKE) -f CMakeFiles\course_work.dir\build.make CMakeFiles/course_work.dir/source_files/str_node.cpp.s
.PHONY : source_files/str_node.cpp.s
# Help Target
help:
@echo The following are some of the valid targets for this Makefile:
@echo ... all (the default if no target is provided)
@echo ... clean
@echo ... depend
@echo ... edit_cache
@echo ... course_work
@echo ... rebuild_cache
@echo ... main.obj
@echo ... main.i
@echo ... main.s
@echo ... source_files/book_io.obj
@echo ... source_files/book_io.i
@echo ... source_files/book_io.s
@echo ... source_files/book_list.obj
@echo ... source_files/book_list.i
@echo ... source_files/book_list.s
@echo ... source_files/book_node.obj
@echo ... source_files/book_node.i
@echo ... source_files/book_node.s
@echo ... source_files/ref_list.obj
@echo ... source_files/ref_list.i
@echo ... source_files/ref_list.s
@echo ... source_files/ref_node.obj
@echo ... source_files/ref_node.i
@echo ... source_files/ref_node.s
@echo ... source_files/search.obj
@echo ... source_files/search.i
@echo ... source_files/search.s
@echo ... source_files/str_list.obj
@echo ... source_files/str_list.i
@echo ... source_files/str_list.s
@echo ... source_files/str_node.obj
@echo ... source_files/str_node.i
@echo ... source_files/str_node.s
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles\Makefile.cmake 0
.PHONY : cmake_check_build_system
<file_sep>#include "../header_files/ref_list.h"
void ref_list::init(t_ref_list &list)
{
list.head = nullptr;
list.curr = nullptr;
list.prev = nullptr;
list.last = nullptr;
}
void ref_list::set_head(t_ref_list &list, t_ref_node *node)
{
list.head = node;
}
void ref_list::set_prev(t_ref_list &list, t_ref_node *node)
{
list.prev = node;
}
void ref_list::set_curr(t_ref_list &list, t_ref_node *node)
{
list.curr = node;
}
void ref_list::set_last(t_ref_list &list, t_ref_node *node)
{
list.last = node;
}
t_ref_node* ref_list::get_head(t_ref_list &list)
{
return list.head;
}
t_ref_node* ref_list::get_curr(t_ref_list &list)
{
return list.curr;
}
t_ref_node* ref_list::get_last(t_ref_list &list)
{
return list.last;
}
void ref_list::go_beg(t_ref_list &list)
{
set_prev(list, nullptr);
set_curr(list, get_head(list));
}
void ref_list::go_next(t_ref_list &list)
{
set_prev(list, get_curr(list));
set_curr(list, ref_node::get_next(get_curr(list)));
}
void ref_list::insert_end(t_ref_list &list)
{
auto *node = new t_ref_node;
ref_node::init_node(node, nullptr);
ref_node::set_next(get_last(list), node);
set_last(list, node);
}
void ref_list::delete_beg(t_ref_list &list)
{
go_beg(list);
set_head(list, ref_node::get_next(get_curr(list)));
delete get_curr(list);
go_beg(list);
}
void ref_list::delete_all(t_ref_list &list)
{
while (get_head(list) != nullptr) {
delete_beg(list);
}
init(list);
}
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/course_work.dir/main.cpp.obj"
"CMakeFiles/course_work.dir/source_files/str_node.cpp.obj"
"CMakeFiles/course_work.dir/source_files/str_list.cpp.obj"
"CMakeFiles/course_work.dir/source_files/book_node.cpp.obj"
"CMakeFiles/course_work.dir/source_files/book_list.cpp.obj"
"CMakeFiles/course_work.dir/source_files/ref_node.cpp.obj"
"CMakeFiles/course_work.dir/source_files/ref_list.cpp.obj"
"CMakeFiles/course_work.dir/source_files/search.cpp.obj"
"CMakeFiles/course_work.dir/source_files/book_io.cpp.obj"
"course_work.pdb"
"course_work.exe"
"course_work.exe.manifest"
"libcourse_work.dll.a"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/course_work.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#ifndef COURSE_WORK_SEARCH_H
#define COURSE_WORK_SEARCH_H
#include "str_list.h"
#include "ref_list.h"
#include "consts.h"
struct t_search_query
{
t_str_list title;
t_str_list author;
search_by search_type;
storage search_storage;
};
void search(t_ref_list &result, t_search_query &query, t_ref_list title_map[], t_ref_list author_map[]);
void search_book(t_ref_list &result, t_search_query query, t_ref_list map[]);
void search_title(t_ref_list &result, t_search_query query, t_ref_list map[]);
void search_author(t_ref_list &result, t_search_query query, t_ref_list map[]);
bool is_strings_equal(t_str_list first_str, t_str_list second_str);
#endif //COURSE_WORK_SEARCH_H
<file_sep>#include "../header_files/ref_node.h"
void ref_node::init_node(t_ref_node *init, t_ref_node *next)
{
init->next = next;
}
void ref_node::set_next(t_ref_node *node, t_ref_node *next)
{
if (node != nullptr) node->next = next;
}
t_ref_node* ref_node::get_next(t_ref_node *node)
{
return node->next;
}
<file_sep>#ifndef COURSE_WORK_CONSTS_H
#define COURSE_WORK_CONSTS_H
enum search_by {AUTHOR_AND_TITLE = 1, TITLE = 2, AUTHOR = 3};
enum storage {ALL = 1, LIBRARY = 2, OTHER = 3};
int const CHARS_IN_ASKII = 256;
const int UNIT_LENGTH = 15;
#endif //COURSE_WORK_CONSTS_H<file_sep>#include "../header_files/book_list.h"
void book_list::init(t_book_list &list)
{
list.head = nullptr;
list.curr = nullptr;
list.prev = nullptr;
list.last = nullptr;
}
void book_list::set_head(t_book_list &list, t_book_node *t)
{
list.head = t;
}
void book_list::set_prev(t_book_list &list, t_book_node *t)
{
list.prev = t;
}
void book_list::set_curr(t_book_list &list, t_book_node *t)
{
list.curr = t;
}
void book_list::set_last(t_book_list &list, t_book_node *t)
{
list.last = t;
}
t_book_node* book_list::get_head(t_book_list &list)
{
return list.head;
}
t_book_node* book_list::get_prev(t_book_list &list)
{
return list.prev;
}
t_book_node* book_list::get_curr(t_book_list &list)
{
return list.curr;
}
t_book_node* book_list::get_last(t_book_list &list)
{
return list.last;
}
void book_list::go_beg(t_book_list &list)
{
set_prev(list, nullptr);
set_curr(list, get_head(list));
}
void book_list::go_next(t_book_list &list)
{
set_prev(list, get_curr(list));
set_curr(list, book_node::get_next(get_curr(list)));
}
void book_list::go_end(t_book_list &list)
{
go_beg(list);
while (book_node::get_next(get_curr(list)) != nullptr)
{
go_next(list);
}
}
void book_list::insert_end(t_book_list &list)
{
t_book_node *node = new t_book_node;
book_node::init_node(node, nullptr);
book_node::set_next(get_last(list), node);
set_last(list, node);
}
void book_list::delete_beg(t_book_list &list)
{
go_beg(list);
set_head(list, book_node::get_next(get_curr(list)));
delete get_curr(list);
go_beg(list);
}
void book_list::delete_last(t_book_list &list)
{
go_beg(list);
go_end(list);
book_node::set_next(get_prev(list), nullptr);
set_last(list, get_prev(list));
delete (get_curr(list));
go_beg(list);
}
void book_list::delete_all(t_book_list &list)
{
while (get_head(list) != nullptr)
{
delete_beg(list);
}
init(list);
}
<file_sep>#include "header_files/search.h"
#include "header_files/book_list.h"
#include "header_files/book_io.h"
int main()
{
t_book_list lib, other;
book_list::init(lib);
book_list::init(other);
t_ref_list title_map[CHARS_IN_ASKII], author_map[CHARS_IN_ASKII];
read_all_lists(lib, other, title_map, author_map);
std::fstream output;
output.open("../res/output.txt", std::ios::out);
output << "Books in library:\n";
print_book_list(lib, output);
output << "\nBooks in other storage:\n";
print_book_list(other, output);
t_ref_list result;
ref_list::init(result);
t_search_query query;
search(result, query, title_map, author_map);
output << "\n";
print_search_query(query, output);
output << "\n\nSearch result:\n";
print_ref_list(result, output);
output << "\n";
book_list::delete_all(lib);
book_list::delete_all(other);
ref_list::delete_all(result);
return 0;
}<file_sep>#ifndef COURSE_WORK_STR_H
#define COURSE_WORK_STR_H
#include "consts.h"
struct t_str
{
char unit[UNIT_LENGTH];
};
#endif //COURSE_WORK_STR_H
<file_sep>#include <iostream>
#include "../header_files/book_io.h"
void read_all_lists(t_book_list &library, t_book_list &other, t_ref_list title_map[], t_ref_list author_map[])
{
for (int i = 0; i < CHARS_IN_ASKII; i++)
{
ref_list::init(title_map[i]);
ref_list::init(author_map[i]);
}
std::fstream file;
file.open("../res/lib.txt", std::ios::in);
read_book_list(library, file, LIBRARY, title_map, author_map);
file.close();
file.open("../res/other.txt", std::ios::in);
read_book_list(other, file, OTHER, title_map, author_map);
file.close();
}
void read_book_list(t_book_list &list, std::fstream &file, storage book_storage, t_ref_list title_map[],
t_ref_list author_map[])
{
file.unsetf(std::ios::skipws);
while (true)
{
book_list::insert_end(list);
book_list::get_last(list)->value.book_storage = book_storage;
if (book_list::get_head(list) == nullptr)
{
book_list::set_head(list, book_list::get_last(list));
}
book_list::get_last(list)->value.title = read_line(file, '|');
book_list::get_last(list)->value.author = read_line(file, '\n');
bool isTitleNotRead = str_list::get_head(book_list::get_last(list)->value.title)->value.unit[0] ==
book_list::get_last(list)->value.title.marker;
bool isAuthorNotRead = str_list::get_head(book_list::get_last(list)->value.author)->value.unit[0] ==
book_list::get_last(list)->value.author.marker;
if (isTitleNotRead || isAuthorNotRead)
{
book_list::delete_last(list);
return;
}
// Add books in maps for quick searching
char title_first_letter = str_list::get_head(book_list::get_last(list)->value.title)->value.unit[0];
save_reference(title_map[title_first_letter], book_list::get_last(list));
char author_first_letter = str_list::get_head(book_list::get_last(list)->value.author)->value.unit[0];
save_reference(author_map[author_first_letter], book_list::get_last(list));
}
}
t_str_list read_line(std::fstream &file, char to)
{
t_str_list string;
str_list::init(string);
char buffer, marker = '#';
while (true)
{
str_list::insert_end(string);
if (str_list::get_head(string) == nullptr)
{
str_list::set_head(string, str_list::get_last(string));
}
for (char &i : str_list::get_last(string)->value.unit)
{
file >> buffer;
if (buffer == to)
{
i = marker;
string.marker = marker;
return string;
}
else if (file.eof())
{
str_list::get_head(string)->value.unit[0] = string.marker;
return string;
}
else
{
i = buffer;
}
}
}
}
void print_book_list(t_book_list list, std::fstream &file)
{
book_list::go_beg(list);
while (book_list::get_curr(list) != nullptr)
{
file << "\"";
print_line(book_list::get_curr(list)->value.title, file);
file << "\" by ";
print_line(book_list::get_curr(list)->value.author, file);
file << std::endl;
book_list::go_next(list);
}
}
void print_line(t_str_list string, std::fstream &file)
{
str_list::go_beg(string);
while (str_list::get_curr(string) != nullptr)
{
for (char i : str_list::get_curr(string)->value.unit)
{
if (i == string.marker)
{
return;
}
file << i;
}
str_list::go_next(string);
}
}
void save_reference(t_ref_list &list, t_book_node *node)
{
ref_list::insert_end(list);
if (ref_list::get_head(list) == nullptr) {
ref_list::set_head(list, ref_list::get_last(list));
}
ref_list::get_last(list)->original = node;
}
void print_search_query(t_search_query query, std::fstream &file) {
file << "Search book";
switch (query.search_type)
{
case AUTHOR_AND_TITLE:
file << " with title \"";
print_line(query.title, file);
file << "\" by ";
print_line(query.author, file);
break;
case TITLE:
file << " with title \"";
print_line(query.title, file);
file << "\"";
break;
case AUTHOR:
file << " by ";
print_line(query.author, file);
break;
}
switch (query.search_storage)
{
case ALL:
file << " in all storage";
break;
case LIBRARY:
file << " in library only";
break;
case OTHER:
file << " in other storage only";
break;
}
}
void print_ref_list(t_ref_list list, std::fstream &file) {
ref_list::go_beg(list);
while (ref_list::get_curr(list) != nullptr)
{
file << "\"";
print_line(ref_list::get_curr(list)->original->value.title, file);
file << "\" by ";
print_line(ref_list::get_curr(list)->original->value.author, file);
if (ref_list::get_curr(list)->original->value.book_storage == LIBRARY)
{
file << " in library";
} else {
file << " in other storage";
}
file << std::endl;
ref_list::go_next(list);
}
}
t_str_list read_search(std::fstream &file, char to) {
bool exit = false;
char buffer, marker = '#';
t_str_list string = t_str_list();
file.unsetf(std::ios::skipws);
file >> buffer;
while (!exit) {
str_list::insert_end(string);
if (str_list::get_head(string) == nullptr) {
str_list::set_head(string, str_list::get_last(string));
}
for (char &i : str_list::get_last(string)->value.unit) {
file >> buffer;
if (buffer == to) {
i = marker;
string.marker = marker;
exit = true;
break;
} else {
i = buffer;
}
}
}
return string;
}<file_sep>#ifndef COURSE_WORK_BOOK_LIST_H
#define COURSE_WORK_BOOK_LIST_H
#include "book_node.h"
struct t_book_list
{
t_book_node *head; // the first node of linked list
t_book_node *curr; // the current node
t_book_node *prev; // node before current
t_book_node *last; // last node of list
};
namespace book_list
{
void init(t_book_list &list);
void set_head(t_book_list &list, t_book_node *t);
void set_prev(t_book_list &list, t_book_node *t);
void set_curr(t_book_list &list, t_book_node *t);
void set_last(t_book_list &list, t_book_node *t);
t_book_node* get_head(t_book_list &list);
t_book_node* get_prev(t_book_list &list);
t_book_node* get_curr(t_book_list &list);
t_book_node* get_last(t_book_list &list);
void go_beg(t_book_list &list);
void go_next(t_book_list &list);
void go_end(t_book_list &list);
void insert_end(t_book_list &list);
void delete_beg(t_book_list &list);
void delete_last(t_book_list &list);
void delete_all(t_book_list &list);
}
#endif //COURSE_WORK_BOOK_LIST_H<file_sep># Coursework for second semester
Организовать каталог книг, хранящихся в библиотеке, а также тех, которые могут быть получены по запросу из других хранилищ. Необходимо обеспечить эффективную обработку требования читателя по его запросу (наличие конкретной книги, книг определенного автора, подходящих по названию и т. д.).
<file_sep>#include "../header_files/str_node.h"
void str_node::init_node(t_str_node *init, t_str_node *next)
{
init->next = next;
}
void str_node::set_next(t_str_node *node, t_str_node *next)
{
if (node != nullptr) node->next = next;
}
t_str_node* str_node::get_next(t_str_node *node)
{
return node->next;
}
<file_sep>cmake_minimum_required(VERSION 3.13)
project(course_work)
set(CMAKE_CXX_STANDARD 14)
add_executable(course_work main.cpp header_files/str.h header_files/str_node.h source_files/str_node.cpp source_files/str_list.cpp header_files/str_list.h header_files/book.h source_files/book_node.cpp header_files/book_node.h source_files/book_list.cpp header_files/book_list.h source_files/ref_node.cpp header_files/ref_node.h source_files/ref_list.cpp header_files/ref_list.h source_files/search.cpp header_files/search.h source_files/book_io.cpp header_files/book_io.h)<file_sep>#ifndef COURSE_WORK_BOOK_H
#define COURSE_WORK_BOOK_H
#include "str_list.h"
struct t_book
{
t_str_list title;
t_str_list author;
storage book_storage;
};
#endif //COURSE_WORK_BOOK_H
<file_sep>#ifndef COURSE_WORK_BOOK_IO_H
#define COURSE_WORK_BOOK_IO_H
#include "book_list.h"
#include "ref_list.h"
#include "search.h"
#include <fstream>
void read_all_lists(t_book_list &library, t_book_list &other, t_ref_list *title_map, t_ref_list author_map[]);
void read_book_list(t_book_list &list, std::fstream &file, storage book_storage, t_ref_list title_map[],
t_ref_list author_map[]);
t_str_list read_line(std::fstream &file, char to);
void print_book_list(t_book_list list, std::fstream &file);
void print_line(t_str_list string, std::fstream &file);
void print_search_query(t_search_query query, std::fstream &file);
void print_ref_list(t_ref_list list, std::fstream &file);
void save_reference(t_ref_list &list, t_book_node *node);
t_str_list read_search(std::fstream &file, char to);
#endif //COURSE_WORK_BOOK_IO_H<file_sep>#ifndef COURSE_WORK_REF_LIST_H
#define COURSE_WORK_REF_LIST_H
#include "ref_node.h"
struct t_ref_list
{
t_ref_node *head; // the first node of linked list
t_ref_node *curr; // the current node
t_ref_node *prev; // node before current
t_ref_node *last; // last node of list
};
namespace ref_list
{
void init(t_ref_list &list);
void set_head(t_ref_list &list, t_ref_node *node);
void set_prev(t_ref_list &list, t_ref_node *node);
void set_curr(t_ref_list &list, t_ref_node *node);
void set_last(t_ref_list &list, t_ref_node *node);
t_ref_node* get_head(t_ref_list &list);
t_ref_node* get_curr(t_ref_list &list);
t_ref_node* get_last(t_ref_list &list);
void go_beg(t_ref_list &list);
void go_next(t_ref_list &list);
void insert_end(t_ref_list &list);
void delete_beg(t_ref_list &list);
void delete_all(t_ref_list &list);
}
#endif //COURSE_WORK_REF_LIST_H
<file_sep>#ifndef COURSE_WORK_STR_NODE_H
#define COURSE_WORK_STR_NODE_H
#include "str.h"
struct t_str_node
{
t_str value;
t_str_node *next;
};
namespace str_node
{
void init_node(t_str_node *init, t_str_node *next);
void set_next(t_str_node *node, t_str_node *next);
t_str_node* get_next(t_str_node *node);
}
#endif //COURSE_WORK_STR_NODE_H
<file_sep>#include "../header_files/str_list.h"
void str_list::init(t_str_list &list)
{
list.head = nullptr;
list.curr = nullptr;
list.prev = nullptr;
list.last = nullptr;
}
void str_list::set_head(t_str_list &list, t_str_node *node)
{
list.head = node;
}
void str_list::set_prev(t_str_list &list, t_str_node *node)
{
list.prev = node;
}
void str_list::set_curr(t_str_list &list, t_str_node *node)
{
list.curr = node;
}
void str_list::set_last(t_str_list &list, t_str_node *node)
{
list.last = node;
}
t_str_node* str_list::get_head(t_str_list &list)
{
return list.head;
}
t_str_node* str_list::get_curr(t_str_list &list)
{
return list.curr;
}
t_str_node* str_list::get_last(t_str_list &list)
{
return list.last;
}
void str_list::go_beg(t_str_list &list)
{
set_prev(list, nullptr);
set_curr(list, get_head(list));
}
void str_list::go_next(t_str_list &list)
{
set_prev(list, get_curr(list));
set_curr(list, str_node::get_next(get_curr(list)));
}
void str_list::insert_end(t_str_list &list)
{
auto *node = new t_str_node;
str_node::init_node(node, nullptr);
str_node::set_next(get_last(list), node);
set_last(list, node);
}<file_sep>#include "../header_files/book_node.h"
void book_node::init_node(t_book_node *init, t_book_node *next)
{
init->next = next;
}
void book_node::set_next(t_book_node *node, t_book_node *next)
{
if (node != nullptr) node->next = next;
}
t_book_node* book_node::get_next(t_book_node *node)
{
return node->next;
}<file_sep>#ifndef COURSE_WORK_REF_NODE_H
#define COURSE_WORK_REF_NODE_H
#include "book_node.h"
// Structure for sorting and search book nodes from original lists
struct t_ref_node
{
t_book_node *original;
t_ref_node *next;
};
namespace ref_node
{
void init_node(t_ref_node *init, t_ref_node *next);
void set_next(t_ref_node *node, t_ref_node *next);
t_ref_node* get_next(t_ref_node *node);
}
#endif //COURSE_WORK_REF_NODE_H
<file_sep>#include <fstream>
#include "../header_files/search.h"
#include "../header_files/book_io.h"
void search(t_ref_list &result, t_search_query &query, t_ref_list title_map[], t_ref_list author_map[])
{
std::fstream file;
file.open("../res/search.txt", std::ios::in);
int buffer;
file >> buffer;
query.search_type = static_cast<search_by>(buffer);
file >> buffer;
query.search_storage = static_cast<storage>(buffer);
switch (query.search_type) {
case AUTHOR_AND_TITLE:
query.title = read_search(file, '|');
query.author = read_search(file, '\n');
search_book(result, query, title_map);
break;
case TITLE:
query.title = read_search(file, '\n');
search_title(result, query, title_map);
break;
case AUTHOR:
query.author = read_search(file, '\n');
search_author(result, query, author_map);
}
for (int i = 0; i < CHARS_IN_ASKII; i++)
{
ref_list::delete_all(title_map[i]);
ref_list::delete_all(author_map[i]);
}
}
void search_book(t_ref_list &result, t_search_query query, t_ref_list map[])
{
char title_first_letter = str_list::get_head(query.title)->value.unit[0];
t_ref_list search_list = map[title_first_letter];
if (ref_list::get_head(search_list) == nullptr) return;
ref_list::go_beg(search_list);
while (ref_list::get_curr(search_list) != nullptr)
{
if ((query.search_storage != ALL) &&
query.search_storage != ref_list::get_curr(search_list)->original->value.book_storage)
{
ref_list::go_next(search_list);
continue;
}
if (is_strings_equal(ref_list::get_curr(search_list)->original->value.author, query.author) &&
is_strings_equal(ref_list::get_curr(search_list)->original->value.title, query.title))
{
save_reference(result, ref_list::get_curr(search_list)->original);
}
ref_list::go_next(search_list);
}
}
void search_title(t_ref_list &result, t_search_query query, t_ref_list map[])
{
char title_first_letter = str_list::get_head(query.title)->value.unit[0];
t_ref_list search_list = map[title_first_letter];
if (ref_list::get_head(search_list) == nullptr) return;
ref_list::go_beg(search_list);
while (ref_list::get_curr(search_list) != nullptr)
{
if ((query.search_storage != ALL) &&
query.search_storage != ref_list::get_curr(search_list)->original->value.book_storage)
{
ref_list::go_next(search_list);
continue;
}
if (is_strings_equal(ref_list::get_curr(search_list)->original->value.title, query.title))
{
save_reference(result, ref_list::get_curr(search_list)->original);
}
ref_list::go_next(search_list);
}
}
void search_author(t_ref_list &result, t_search_query query, t_ref_list map[])
{
char author_first_letter = str_list::get_head(query.author)->value.unit[0];
t_ref_list search_list = map[author_first_letter];
if (ref_list::get_head(search_list) == nullptr) return;
ref_list::go_beg(search_list);
while (ref_list::get_curr(search_list) != nullptr)
{
if ((query.search_storage != ALL) &&
query.search_storage != ref_list::get_curr(search_list)->original->value.book_storage)
{
ref_list::go_next(search_list);
continue;
}
if (is_strings_equal(ref_list::get_curr(search_list)->original->value.author, query.author))
{
save_reference(result, ref_list::get_curr(search_list)->original);
}
ref_list::go_next(search_list);
}
}
bool is_strings_equal(t_str_list first_str, t_str_list second_str)
{
str_list::go_beg(first_str);
str_list::go_beg(second_str);
while (true) {
for (int i = 0; i < UNIT_LENGTH; i++) {
char first_char = str_list::get_curr(first_str)->value.unit[i];
char second_char = str_list::get_curr(second_str)->value.unit[i];
if (first_char == first_str.marker && second_char == second_str.marker)
{
return true;
}
if (first_char != second_char)
{
return false;
}
}
str_list::go_next(first_str);
str_list::go_next(second_str);
}
}<file_sep>#ifndef COURSE_WORK_STR_LIST_H
#define COURSE_WORK_STR_LIST_H
#include "str_node.h"
struct t_str_list
{
t_str_node *head; // the first node of linked list
t_str_node *curr; // the current node
t_str_node *prev; // node before current
t_str_node *last; // last node of list
char marker; // end of the string
};
namespace str_list
{
void init(t_str_list &list);
void set_head(t_str_list &list, t_str_node *node);
void set_prev(t_str_list &list, t_str_node *node);
void set_curr(t_str_list &list, t_str_node *node);
void set_last(t_str_list &list, t_str_node *node);
t_str_node* get_head(t_str_list &list);
t_str_node* get_curr(t_str_list &list);
t_str_node* get_last(t_str_list &list);
void go_beg(t_str_list &list);
void go_next(t_str_list &list);
void insert_end(t_str_list &list);
}
#endif //COURSE_WORK_STR_LIST_H
|
b6d3e938c1d6a8fde490dfef0bce88420e0bd2a6
|
[
"CMake",
"Markdown",
"Makefile",
"C",
"C++"
] | 24 |
C++
|
msvetkov/Coursework-2-sem
|
4a60f1d2c1a83f82e3d3c3a215d7abf876c0c428
|
65dc1ce79a656ca4f6dce0d429cd3988f7902660
|
refs/heads/master
|
<repo_name>ameek/SocketProgramming<file_sep>/SOCKETProgramming/main_client.py
import socket
port = 8000
# we'll send this message before closing connection
# so that other side can close connection as well
CLOSE = b'--close--'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def host():
sock.bind(('', port))
sock.listen(1)
# is supposed to return the local IP of the computer
# might not always work
hostname = socket.gethostbyname(socket.gethostname())
print('Server started at host: ' + hostname + ' on port: ' + str(port))
client_sock, addr = sock.accept()
print('\nConnection established. Type and press enter to send message.')
print('Press Ctrl+C to end conversation\n')
while True:
try:
message = client_sock.recv(4096)
print('Friend said: ', message.decode())
# closing message received from client
if message == CLOSE:
client_sock.close()
sock.close()
break
reply = input('I say: ')
client_sock.send(reply.encode())
except KeyboardInterrupt:
# Ctrl + C was pressed
# Send closing message before closing socket
client_sock.send(CLOSE)
client_sock.close()
sock.close()
break
def join():
sock.connect((hostname, port))
print('\nConnection established. Type and press enter to send message')
print('Press Ctrl+C to end conversation\n')
while True:
try:
message = input('I say: ')
sock.send(message.encode())
reply = sock.recv(4096)
print('Friend said: ', reply.decode())
if reply == CLOSE:
sock.close()
break
except KeyboardInterrupt:
# Ctrl + C pressed
# Send closing message before closing socket
sock.send(CLOSE)
sock.close()
break
if __name__ == '__main__':
choice = input('1. Host\n2. Join\nYour choice: ')
if choice[0] in '1Hh':
host()
else:
hostname = input('Enter host IP or hostname: ')
join()
<file_sep>/SOCKETProgramming/client.py
import socket
host = 'localhost'
port = 8000
sock = socket.socket(family=socket.AF_INET,type=socket.SOCK_STREAM)
sock.connect((host, port))
sock.send('Ping!'.encode())
message = sock.recv(4096)
print('Server said : ' + message.decode())
sock.close()
<file_sep>/README.md
# SocketProgramming
Clinet and Server model in different Language
<file_sep>/SOCKETProgramming/server.py
import socket
port = 8000
sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
sock.bind(('', port))
sock.listen(1)
hostname = socket.gethostbyname(socket.gethostname())
print('Server started at host: ' + hostname + ' on port: ' + str(port))
client_sock, addr = sock.accept()
message = client_sock.recv(4096)
print('client said : ' + message.decode())
client_sock.send('pong!'.encode())
sock.close()
|
8d05eae5e9c78016542e6e2406dd1e5390fad662
|
[
"Markdown",
"Python"
] | 4 |
Python
|
ameek/SocketProgramming
|
8030eee281a52e500bde41e5368c0690ef138ce7
|
7cd9a7bc288521ce2ffc1572a938cc7cdb242f34
|
refs/heads/master
|
<repo_name>s-u/snippets<file_sep>/man/osmap.Rd
\name{osmap}
\alias{osmap}
\title{
Draw tiles from OpenStreetMap or any other compatible tile source.
}
\description{
\code{osmap} fetches and draws OpenStreetMap tiles (or any compatible
tiles) in the current graphics device assuming latitude and longitude
coordinates.
}
\usage{
osmap(alpha = 1, zoom, area = par()$usr, tiles.url, cache.dir,
tile.coord = FALSE)
}
\arguments{
\item{alpha}{in theory this is the desired opacity of the map but in
practice the final plot is faded to white by this alpha value (1 =
no fading, 0 = entriely white)}
\item{zoom}{zoom level of the map to draw (optional). If missing the
zoom level is determined automatically to cover the area with about
five tiles in the horizontal direction}
\item{area}{minimal area to cover - the required tiles are computed to
cover at least this area}
\item{tiles.url}{URL to the tiles server (excluding the
\code{zoom/x/y.png} part). If missing, \code{osm.tiles.url} option
is consulted and if also missing then an OSM tile server is used.}
\item{cache.dir}{if set, the tiles are first looked up in this
directory and the directory is used for caching downloaded tiles}
\item{tile.coord}{if \code{FALSE} then the plot coordinates are
assumed to be latitude and longitude - this is the
default. Otherwise this must be an integer and it is assumed that
the coordinates of the plot are tile coordinates at the specified
\code{tile.coord} zoom level (this is useful for plotting data
projected in the same Mercator projection as the tiles). Note taht
\code{zoom} and \code{tile.coord} can be different zoom levels.}
}
%\details{
%}
%\value{
%}
\examples{
par(mar=rep(0,4))
# plot any lat/lon data - here just an area around the AT&T Labs
plot(c(-74.44, -74.39), c(40.76, 40.79), type='n')
# draw the map (needs internet connection to get the tiles)
osmap()
# to draw the world, use zoom level=0 as the base so that
# the area is simply [0,1]
plot(c(0,1), c(0,1), type='n')
osmap(tile.coord=0L)
}
\keyword{hplot}
<file_sep>/man/scheme.Rd
\name{scheme}
\alias{scheme}
\alias{advance.scheme}
\alias{pop.scheme}
\alias{print.scheme}
\title{
Scheme hanlding functions
}
\description{
The following functions manage the stack of layout ``schemes'' created
by corresponding scheme constructors such as \code{\link{mfrow}} or
\code{\link{mfcol}}. Most of them are called by the implementation and
are not expected to be used by the user directly.
\code{advance.scheme} is called when a new plot is about to be drawn and
advances to the next scheme layout according to the stack hierarchy.
\code{pop.scheme} removes the topmost scheme from the stack.
}
\usage{
advance.scheme()
pop.scheme()
\method{print}{scheme}(x, \dots)
}
\arguments{
\item{x}{scheme to be printed}
\item{\dots}{additional arguments passed through}
}
%\details{
%}
%\value{
%}
\author{<NAME>}
\note{``scheme'' is not a typo but rather a play on the meaning of
the word `scheme' in the context of something that may be called
`schema' (a grand plan of figure layout if you will) -- the former is
an evolution of the latter word from its original form, anyway.
}
\seealso{
\code{\link{mfrow}}, \code{\link{mfcol}}
}
%\examples{
%}
\keyword{hplot}
<file_sep>/man/screen2data.Rd
\name{screen2data}
\alias{screen2data}
\alias{data2screen}
\title{
Functions converting between pixel and data coordinates.
}
\description{
\code{screen2data} converts between screen (pixel) coordinates of device
output and the data coordinates.
\code{data2screen} performs the inverse conversion.
Both functions can be parametrized manually but default to obtaining all
necessary parameters from the active graphics device. It is most useful
when used with bitmap dvices such as the Cairo device (see \code{Cairo}
package) for the purpose of adding interactivity (e.g., via JavaScript).
}
\usage{
screen2data(x, y, width = par("fin")[1] * dpi, height = par("fin")[2] * dpi,
dpi = 72, plt = par("plt"), usr = par("usr"), flip = FALSE)
data2screen(x, y, width = par("fin")[1] * dpi, height = par("fin")[2] * dpi,
dpi = 72, plt = par("plt"), usr = par("usr"), flip = FALSE)
}
\arguments{
\item{x}{x coordinates of locations to convert or a two-column matrix
(if \code{y} is missing)}
\item{y}{y coordinates of locations to convert (if missing \code{x}
must be a matrix and the second column of \code{x} is interpreted as
\code{y})}
\item{width}{width of the figure region (usually the size of the
resulting file in pixels)}
\item{height}{height of the figure region (usually the size of the
resulting file in pixels)}
\item{dpi}{resolution (only used to compute the width and height from
figure size if they are not specified}
\item{plt}{the `plt' parameter}
\item{usr}{the `usr' parameter}
\item{flip}{if set to \code{TRUE} then \code{y} axis in pixels is
assumed to be flipped (0 on top)}
}
%\details{
%}
\value{
The result is a two-column matrix with the columns \code{x} and
\code{y}. The special case of one row input is returned as a named
vector of length two.
}
%\references{
%}
%\author{
%}
\note{
If \code{x} and \code{y} are vectors they are recycled to match.
}
%\seealso{
%}
\examples{
plot(0:1,0:1)
## where on the bitmap is the data point 0,0 ?
data2screen(0, 0)
## if I click on 200, 100 with flipped coordinates, what coordinates do
## I hit?
screen2data(200, 100, flip=TRUE)
## go there and back
screen2data(data2screen(c(0, 0.5), c(1, 0.5)))
}
\keyword{dplot}
<file_sep>/R/gpx.R
gpx <- function(lat, lon, time, file=NULL) {
o <- c('<gpx version="1.1" creator="R">','<trk>','<trkseg>')
if (missing(time))
o <- c(o, paste('<trkpt lat="',lat,'" lon="',lon,'" />', sep=''))
else
o <- c(o, paste('<trkpt lat="',lat,'" lon="',lon,'"><time>',paste(gsub(' ','T', as.character(time)), 'Z', sep=''),'</time></trkpt>', sep=''))
o <- c(o, '</trkseg>', '</trk>', '</gpx>')
if (is.character(file) || inherits(file, "connection"))
writeLines(o, file)
else
o
}
<file_sep>/man/rfBin.Rd
\name{rfBin}
\alias{rfBin}
\title{
Read binary file
}
\description{
\code{rfBin} is a front-end to \code{readBin} that reads the entire
content of a binary file.
}
\usage{
rfBin(filename, what = 1L, ...)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{filename}{name of the file to read}
\item{what}{either an integer or real vector defining the payload type}
\item{\dots}{additional parameters passed to \code{readBin}}
}
%\details{
%}
\value{
Same as \code{\link{readBin}}
}
%\references{
%}
\author{
<NAME>
}
%\note{
%}
%\examples{
%}
\keyword{io}
<file_sep>/man/gpx.Rd
\name{gpx}
\alias{gpx}
\title{
Create a GPX (GPS Exchange Format) output.
}
\description{
\code{gpx} creates XML output in the GPX format (GPS Exchange Format)
from latitude, longitude and time.
}
\usage{
gpx(lat, lon, time, file = NULL)
}
\arguments{
\item{lat}{latitude of the points}
\item{lon}{longitude of the points}
\item{time}{time of the points (optional)}
\item{file}{destination - can be a character string naming the output
file or a connection to use for output or \code{NULL} in which case
the function return a character vector with teh output.}
}
\details{
The resulting output is in GPX format contining exactly one track with
the specified values (\code{NA}s are currently not supported!). If the
\code{time} value is present then the track entries will include a
time nodes as well. No checking is done on time entries so the user
must ensure that they are exactly of the form
\code{YYYY-MM-DD HH:MM:SS}, assumed to be in UTC.
(Note that OSM requires time stamps to be present in uploaded tracks.)
}
\value{
If \code{file} is \code{NULL} then the value is a character vector
containing the lines of the GPX output.
}
%\references{
%}
\examples{
lat <- c(40.779, 40.777)
lon <- c(-74.428,-74.418)
cat(gpx(lat, lon), sep='\n')
cat(gpx(lat, lon, Sys.time()), sep='\n')
}
\keyword{interface}
<file_sep>/R/scheme.R
.scheme.env <- new.env(parent=emptyenv())
mfrow <- function(rows, cols, n, asp=1, add=FALSE, times=NA, fig = if(add) par("fig") else c(0,1,0,1), ...)
.mfgrid(rows, cols, n, asp, add, times, fig, "gridRowScheme", ...)
mfcol <- function(rows, cols, n, asp=1, add=FALSE, times=NA, fig = if(add) par("fig") else c(0,1,0,1), ...)
.mfgrid(rows, cols, n, asp, add, times, fig, "gridColScheme", ...)
.mfgrid <- function(rows, cols, n, asp=1, add=FALSE, times=NA, fig = if(add) par("fig") else c(0,1,0,1), subclass, ...) {
if (missing(rows) && missing(cols) && !missing(n)) {
t <- 1:as.integer(sqrt(n)) # compute all canidate sizes
t <- unique(c(t, rev(as.integer(n / t + 0.999999))))
din <- par("din") # adjust for device and figure aspect
tasp <- rev(t) / t * din[1] / din[2] * (fig[2] - fig[1]) / (fig[4] - fig[3])
a <- which.min(abs(log(tasp) - log(asp))) # find the closest ratio
cols <- t[a]
rows <- rev(t)[a]
}
if (missing(rows)) rows <- 1L
if (missing(cols)) cols <- 1L
dev.id <- paste(names(dev.cur()), dev.cur(), sep='/')
if (!isTRUE(add)) {
.scheme.env[[dev.id]] <- NULL
.scheme.env[[paste(dev.id,"reset")]] <- TRUE
fig <- c(0,1,0,1)
par(mfrow=c(1,1))
} else fig <- par("fig")
if (length(rows) == 1L) rows <- rep(1, rows)
if (length(cols) == 1L) cols <- rep(1, cols)
rows <- rows / sum(rows)
cols <- cols / sum(cols)
if (isTRUE(times > 1e6)) times <- NA
pars <- list(...)
if (!length(pars)) pars <- NULL
scheme <- structure(list(rows=rows, cols=cols, crows = 1 - cumsum(c(0,rows)), ccols=cumsum(c(0,cols)),
times=times, pars=pars, name=paste(dev.id, "[", length(.scheme.env[[dev.id]]) + 1L, "]: ", subclass, " (", length(cols), " x ", length(rows), ")", sep=''),
fig=fig, index=1L, n=length(rows) * length(cols)),
class=c(subclass,"scheme"))
.scheme.env[[dev.id]][[length(.scheme.env[[dev.id]]) + 1L]] <- scheme
# init is TRUE if we setup a new scheme so that advance is not desired until next figure
.scheme.env[[paste(dev.id,"init")]] <- TRUE
# although the setup is done by the plot.new callback
# it is important to setup the fig parameter now because
# of subsequent calls to scheme routines before plot.new
setup.figure(scheme)
invisible(scheme)
}
# The returned value is the updated scheme
# setup should NOT make any advances as it may be called more than once for the same figure
# it should only set the fig parameter accordingly, no other side-effects are expected
setup.figure <- function(scheme) {
if (!is.null(scheme$pars)) par(scheme$pars)
UseMethod("setup.figure")
}
.setup.figure.gridScheme <- function(scheme, row, col) {
if (missing(row)) row <- scheme$row
if (missing(col)) col <- scheme$col
pf <- scheme$fig
w <- pf[2] - pf[1]
h <- pf[4] - pf[3]
fig <- c(scheme$ccols[col], scheme$ccols[col + 1L],
scheme$crows[row + 1L], scheme$crows[row])
par(fig = c(pf[1] + fig[1] * w, pf[1] + fig[2] * w, pf[3] + fig[3] * h, pf[3] + fig[4] * h))
scheme
}
setup.figure.gridRowScheme <- function(scheme) {
index <- scheme$index
cols <- length(scheme$cols)
col <- 1L + ((index - 1L) %% cols)
row <- 1L + as.integer((index - 1L) / cols)
.setup.figure.gridScheme(scheme, row, col)
}
setup.figure.gridColScheme <- function(scheme) {
index <- scheme$index
rows <- length(scheme$rows)
row <- 1L + ((index - 1L) %% rows)
col <- 1L + as.integer((index - 1L) / rows)
.setup.figure.gridScheme(scheme, row, col)
}
advance.scheme <- function() {
dev.id <- paste(names(dev.cur()), dev.cur(), sep='/')
schemes <- .scheme.env[[dev.id]]
si <- length(schemes)
if (si) {
scheme <- schemes[[si]]
if (!inherits(scheme, "scheme")) {
warning("corrupted scheme, removing from stack")
.scheme.env[[dev.id]] <- if (si > 1L) schemes[1:(si - 1L)] else NULL
return(NULL)
}
scheme$index <- scheme$index + 1L
if (scheme$index > scheme$n) { # end of scheme, reinstall?
scheme$times <- scheme$times - 1L
if (isTRUE(scheme$times < 1L)) { # times expired
# remove from the stack
.scheme.env[[dev.id]][[si]] <- NULL
# and run advance one level up
return(advance.scheme())
}
# re-install requested - need to go one level up
.scheme.env[[dev.id]][[si]] <- NULL
advance.scheme()
scheme$fig <- par("fig")
# check the length - if the parent quit, don't re-install
if (length(.scheme.env[[dev.id]]) != si - 1L) return(NULL)
scheme$index <- 1L
}
# prevent clearing of the device unless the next figure is first at root
if (!isTRUE(.scheme.env[[paste(dev.id,"reset")]]))
tryCatch(par(new = TRUE), error = function(e) TRUE)
# ok, we're ready
scheme <- setup.figure(scheme)
# set state only after advancing in case there is an error
.scheme.env[[dev.id]][[si]] <- scheme
} else {
# advance on the root = reset the plot
par(fig = c(0,1,0,1))
.scheme.env[[paste(dev.id,"reset")]] <- TRUE
NULL
}
}
pop.scheme <- function() {
dev.id <- paste(names(dev.cur()), dev.cur(), sep='/')
schemes <- .scheme.env[[dev.id]]
si <- length(schemes)
if (si) {
.scheme.env[[dev.id]][[si]] <- NULL
if (si > 1L) .scheme.env[[dev.id]][[si - 1L]] else NULL
} else NULL
}
print.scheme <- function(x, ...)
cat(x$name, ", index = ", x$index, "\n", sep='')
# currently we are the only module initializing stuff ...
.onLoad <- .First.lib <- function(libname, pkgname)
setHook("before.plot.new", function() {
dev.id <- paste(names(dev.cur()), dev.cur(), sep='/')
if (length(.scheme.env[[dev.id]])) {
if (!isTRUE(.scheme.env[[paste(dev.id,"init")]])) advance.scheme()
.scheme.env[[paste(dev.id,"reset")]] <- FALSE
.scheme.env[[paste(dev.id,"init")]] <- FALSE
}
})
<file_sep>/R/rfBin.R
rfBin <- function(filename, what=1L, ...) {
if (!is.character(filename)) stop("filename must be a character vector")
if (length(filename) > 1L) {
l <- lapply(filename, rfBin, what, ...)
return (do.call("c", l))
}
con <- file(filename, "rb")
on.exit(close(con))
sm <- match(storage.mode(what), c("integer", "double"))
if (any(is.na(sm))) stop("invalid `what' - must be a double or interger")
sz <- c(4L, 8L)[sm]
n <- file.info(filename)$size / sz
readBin(con, what, n, ...)
}
<file_sep>/R/layout.R
add.layout = function(x, y, w, h, rs = 0.01, as = 0.22, ri = 0, ai = 0, l = NULL) {
add.one = function(l, x, y, w, h) {
r = ri
a = ai
while (TRUE) {
cx = x + sin(a) * r
cy = y + cos(a) * r
# cat("pos: ",x,",",y," par:",a,",",r," res:")
# print(table(cx + w < l$x | x > l$x + l$w | cy + h < l$y | y > l$y + l$h))
if (all(cx + w < l$x | cx > l$x + l$w | cy + h < l$y | cy > l$y + l$h)) {
l$x = c(l$x, cx)
l$y = c(l$y, cy)
l$w = c(l$w, w)
l$h = c(l$h, h)
return(l)
}
r = r + rs
a = a + as
}
}
ml = max(c(length(x),length(y),length(w),length(h)))
x = rep(x, length.out = ml)
y = rep(y, length.out = ml)
w = rep(w, length.out = ml)
h = rep(h, length.out = ml)
if (is.null(l)) {
if (ml == 0L) return(NULL)
l = structure(list(x=x[1], y=y[1], w=w[1], h=h[1]), class="box.layout")
if (ml == 1L) return(l)
x = x[-1L]
y = y[-1L]
w = w[-1L]
h = h[-1L]
ml = ml - 1L
}
for (i in seq.int(ml))
l <- add.one(l, x[i], y[i], w[i], h[i])
l
}
add.labels = function(x, y, txt, w, h, adj = 0.5, mar = 0.1, ...) {
if (missing(w)) w = strwidth(txt)
if (missing(h)) h = strheight(txt)
if (!missing(mar)) {
w = w * (1 + mar)
h = h * (1 + mar)
}
dx = adj[1] * w
dy = ifelse(length(adj) > 1, adj[2], adj[1]) * h
bx = x - dx
by = y - dy
l = add.layout(bx, by, w, h, ...)
if (is.null(l$lx)) { ## lx not there so we're dealing with box.layout
if (length(l$x) != length(dx))
stop("add.labels() cannot be mixed with a previous output of add.layout()")
l$lx = l$x + dx
l$ly = l$y + dy
} else { ## lx is there so it's label.layout - need to add lx,ly
if (length(l$lx) + length(dx) != length(l$x))
stop("sizes mismatch in the layout object - labels layout is inconsistent")
l$lx = c(l$lx, l$x[-(1:length(l$lx))] + dx)
l$ly = c(l$ly, l$y[-(1:length(l$ly))] + dy)
}
class(l) = c("label.layout", "box.layout")
l
}
<file_sep>/R/osm.R
# convert lon/lat (in deg) to OSM tile numbers (x,y)
osm.ll2xy <- function(lon, lat, zoom=16) {
n = 2 ^ zoom
lat.rad = lat / 180 * pi
list(x = (((lon + 180) / 360) * n) %% n, y = ((1 - (log(tan(pi/4 + lat.rad/2)) / pi)) / 2 * n) %% n)
}
# convert OSM tile numbers to lon/lat (in deg)
osm.xy2ll <- function(x, y, zoom=16) {
n = 2 ^ zoom
lon.deg = x / n * 360.0 - 180.0
lat.rad = atan(sinh(pi * (1 - 2 * y / n)))
lat.deg = lat.rad * 180.0 / pi
list(lon = lon.deg, lat = lat.deg)
}
# fill the area with OSM map (by default the area is the whole current device)
# tiles are expected to be <zoom>/<x>-<y>.png files (and already present)
# or the tile.url has to icnlude %x %y and %z which will be replaced by the coordinates
# (requires "png" R package for readPNG and R capable of rasterImage())
osmap <- function(alpha=1, zoom, area = par()$usr, tiles.url, cache.dir, tile.coord=FALSE) {
if (missing(tiles.url)) tiles.url <- getOption("osm.tiles.url")
if (missing(cache.dir)) cache.dir <- getOption("osm.cache.dir")
if (is.null(tiles.url)) tiles.url <- "http://a.tile.openstreetmap.org/"
if (length(area) != 4L || !is.numeric(area)) stop("invalid area specification")
tc <- FALSE
if (!identical(tile.coord, FALSE)) {
tc <- TRUE
tc.zoom <- as.integer(tile.coord)
if (missing(zoom))
zoom <- log(5 * 2^tc.zoom / abs(area[2] - area[1])) / log(2)
}
if (missing(zoom)) # get some reasonable zoom estimation based on the covered area
zoom <- log(5 * 360 / abs(area[2] - area[1])) / log(2)
if (zoom > 19) zoom <- 19L
if (zoom < 0) zoom <- 0L
zoom <- as.integer(zoom)
if (tc)
tcf <- 2^tc.zoom / 2^zoom
if (!is.null(cache.dir)) cache.dir <- path.expand(cache.dir)
# tempfile is unreliable when used in multicore so force a random name
my.tmp <- tempfile(sprintf("R.tile.%f.",runif(1)))
fixed.url <- !isTRUE(grepl("%x", tiles.url, fixed=TRUE))
get.tile <- function(x, y, zoom) {
x <- x %% (2^zoom)
y <- y %% (2^zoom)
## cat("get (",x,",",y,"zoom",zoom,")\n")
cached <- FALSE
if (!is.null(cache.dir)) {
if (cache.dir == "") cache.dir <- "."
cache.fn <- paste(cache.dir, "/", zoom, "/", x, "-", y, ".png", sep='')
if (file.exists(cache.fn)) {
img <- try(readPNG(cache.fn, native=TRUE), silent=TRUE)
if (!inherits(img,"try-error")) return(img)
warning("tile", cache.fn," is corrupt in the cache, re-fetching")
}
if (!file.exists(paste(cache.dir, "/", zoom, sep='')))
dir.create(paste(cache.dir, "/", zoom, sep=''), recursive=TRUE)
tmp <- cache.fn
cached <- TRUE
} else tmp <- my.tmp
url <- if (fixed.url) paste0(tiles.url, zoom, "/", x, "/", y, ".png") else gsub("%x", x, gsub("%y", y, gsub("%z", zoom, tiles.url, fixed=TRUE), fixed=TRUE), fixed=TRUE)
if (download.file(url , tmp, quiet=TRUE, mode="wb") != 0L || isTRUE(is.na(sz <- file.info(tmp)$size))) {
warning("unable to download tile ", url)
return (NULL)
}
f <- file(tmp, "rb")
raw <- readBin(f, raw(), sz)
close(f)
img <- if (length(raw) < 32 || raw[1L] != 0x89 || raw[2L] != 0x50 || raw[3L] != 0x4E) {
## not a PNG file, try JPEG since some tile servers use JPEG tagged as PNG for satellite tiles
if (length(grepRaw("JFIF", raw[1:32], fixed=TRUE)))
readJPEG(raw, native=TRUE) else stop("Invalid file format, neither PNG nor JPEG file (see ", tmp, ")")
} else readPNG(raw, native=TRUE)
if (!cached) unlink(tmp)
img
}
if (tc) {
lo <- c(area[1], -area[4]) / tcf
hi <- c(area[2], -area[3]) / tcf
} else {
lo <- unlist(osm.ll2xy(area[1], area[4], zoom=zoom))
hi <- unlist(osm.ll2xy(area[2], area[3], zoom=zoom))
}
if (lo[1] > hi[1])
hi[1] <- hi[1] + 2^zoom
if (lo[2] > hi[2])
hi[2] <- hi[2] + 2^zoom
lo <- as.integer(floor(lo))
hi <- as.integer(ceiling(hi))
## print(lo); print(hi)
failed <- 0L
for (x in seq.int(lo[1],hi[1]))
for (y in seq.int(lo[2],hi[2])) {
q <- get.tile(x, y, zoom)
if (!is.null(q)) {
if (tile.coord)
rasterImage(q, x * tcf, (-y - 1.004) * tcf, (x + 1.004) * tcf, -y * tcf)
else {
tl <- osm.xy2ll(x,y,zoom=zoom)
br <- osm.xy2ll(x+1.004,y+1.004,zoom=zoom)
rasterImage(q, tl$lon, br$lat, br$lon, tl$lat)
}
} else failed <- failed + 1L
}
if (alpha < 1)
rect(-180, -90, 180, 90, col = rgb(1, 1 , 1 , 1 - alpha))
if (failed) stop("total of ", failed, " tiles could not be retrieved")
}
<file_sep>/R/fd.R
fd <- function(x, ...) UseMethod("fd")
fd.matrix <- fd.table <- function(x, add=FALSE, vals=FALSE, at.x, at.y, axes=TRUE, frame.plot = FALSE, main = NULL, sub = NULL, xlab = NULL, ylab= NULL, zmax=max(x, na.rm=TRUE), xlim, ylim, asp = 1, panel.first = NULL, panel.last = NULL, ann = par("ann"), col="grey", border="black", ...) {
localAxis <- function(..., col, bg, pch, cex, lty, lwd) Axis(...)
localBox <- function(..., col, bg, pch, cex, lty, lwd) box(...)
localWindow <- function(..., col, bg, pch, cex, lty, lwd) plot.window(...)
localTitle <- function(..., col, bg, pch, cex, lty, lwd) title(...)
force(zmax)
m <- x
x <- colnames(m)
if (is.null(x)) x <- seq.int(ncol(m))
if (missing(at.x)) at.x <- seq.int(x)
y <- rownames(m)
if (is.null(y)) y <- seq.int(nrow(m))
if (missing(at.y)) at.y <- seq.int(y)
if (missing(xlim)) xlim <- range(c(at.x + 0.5, at.x - 0.5))
if (missing(ylim)) ylim <- range(c(at.y + 0.5, at.y - 0.5))
## go from dense to sparse
xp <- rep(seq.int(ncol(m)), each=nrow(m))
yp <- rep(seq.int(nrow(m)), rep=ncol(m))
d <- data.frame(x=xp, y=yp, ct=as.vector(m), col=rep(col, length.out=length(xp)), stringsAsFactors=FALSE)
d <- d[!is.na(d$ct),]
d <- d[d$ct > 0,]
d$r <- sqrt(d$ct) / sqrt(zmax) / 2
# if (isTRUE(vals)) text(d$x, d$y, paste(format(100 * d$ct / sapply(d$x, function(x) sum(d$ct[d$x == x])), digits=3, drop0trailing=T),"%",sep=''), cex=v.cex)
if (!add) {
plot.new()
localWindow(xlim, ylim, "", asp, ...)
panel.first
}
rect(d$x - d$r, d$y - d$r, d$x + d$r, d$y + d$r, col=d$col, border=border, ...)
if (!add) {
panel.last
if (axes) {
localAxis(at = at.x, labels=x, side = 1, ...)
localAxis(at = at.y, labels=y, side = 2, ...)
}
if (frame.plot)
localBox(...)
if (ann)
localTitle(main = main, sub = sub, xlab = xlab, ylab = ylab, ...)
}
invisible(d)
}
<file_sep>/man/cloud.Rd
\name{cloud}
\alias{cloud}
\title{
Word cloud (aka tag cloud) plot
}
\description{
\code{cloud} creates a siple word cloud plot
}
\usage{
cloud(w, col, yspace=1.3, xspace=0.01, minh=0, ...)
}
\arguments{
\item{w}{named weights - the acutal data to display. Names are used
as tags, actual weight is used for the size. Note that plotting an
unnamed vector results in an empty plot.}
\item{col}{color for the tags.}
\item{yspace}{space between lines as a multiple of the text height.}
\item{xspace}{space (padding) between tags (in native coordinates).}
\item{minh}{minimal height of a line.}
\item{...}{optional arguments, currently ignored.}
}
\value{
Invisible TRUE.
}
\details{
The coordinates of the plot are [0, 1] in both x and y. The plot is
created by starting in the upper left, proceedeing from left to
right and top to bottom. The algorithm used is simply filling up
Note that resizing a world could usually destroys its
properties. You'll have to re-run \code{cloud} after resizing,
because it relies on exact extents of the text.
}
%\seealso{
% \code{\link{.jcall}}, \code{\link{.jnull}}
%}
\examples{
# a really silly one
words <- c(apple=10, pie=14, orange=5, fruit=4)
cloud(words)
# or with more words - take the license for example
r <- paste(readLines(file.path(R.home(),"COPYING")), collapse=' ')
r <- gsub("[\f\t.,;:`'\\\\\\"\\\\(\\\\)<>]+", " ", r)
w <- tolower(strsplit(r, " +")[[1]])
cloud(sqrt(table(w)))
# remove infrequent words
wt <- table(w)
wt <- log(wt[wt > 8])
cloud(wt, col = col.br(wt, fit=TRUE))
}
\keyword{interface}
<file_sep>/man/add.layout.Rd
\name{add.layout}
\alias{add.layout}
\alias{add.labels}
\title{
Functions designed to create non-overlaping layout of rectangles or labels.
}
\description{
\code{add.layout} creates or adds to a layout of non-overlapping
rectangles.
\code{add.labels} is a front-end to \code{add.layout} which creates a
layout suitable for labels allowing to adjust the placement of the label
with respect to the original points and to add extra margins.
}
\usage{
add.layout(x, y, w, h, rs = 0.01, as = 0.22, ri = 0, ai = 0, l = NULL)
add.labels(x, y, txt, w, h, adj = 0.5, mar = 0.1, ...)
}
\arguments{
\item{x}{x coordinates of the points to add. For rectangles it is the
left edge.}
\item{y}{y coordinates of the points to add. For rectangles it is the
bottom edge.}
\item{w}{width of the rectangles (optional for labels where it
defaults to the label widths)}
\item{h}{height of the rectangles (optional for labels where it
defaults to the label height)}
\item{rs}{radius step for the placement algorithm}
\item{as}{angle step for the placement algorithm}
\item{ri}{initial radius for the placement algorithm}
\item{ai}{initial angle for the placement algorithm}
\item{l}{layout to add to or \code{NULL} if a new layout is to be
created}
\item{txt}{text labels to add}
\item{adj}{adjustment of the text position with respect to the
supplied points (see \code{adj} in \code{\link{text}})}
\item{mar}{additional margins around the text (relative to the width
or height). If present, it will be recycled to length two for
horizontal and vertical margins respectively.}
\item{...}{additional parameters passed through to \code{add.layout}}
}
\details{
The layout attempts to sequentially place rectangles of the given
width and height at the specified points. If a placement of a new
rectangle would overlap with any existing rectangle, it is moved until
it no longer overlaps. The current algorithm defines the movement as a
clockwise spiral.
}
\value{
\code{add.layout} returns an obejct of the class \code{box.layout}
which consists of a list with elements \code{x}, \code{y}, \code{w}
and \code{h}. If the input was non-overlapping it would be equivalent
to the (recycled) arguments. If there are overlaps the \code{x} and
\code{y} coordinates will differ accordingly.
If \code{l} is specified on input, it is expected to be
\code{box.layout} as well and the layout is extended by adding the
rectangles defined in the arguments.
\code{add.labels} returns an object of the class \code{label.layout}
which is a subclass of \code{box.layout}. It adds the components
\code{lx} and \code{ly} which are the label coordinates (as opposed to
the rectangle coordinates). If \code{adj} is zero the label and box
coordinates are equal.
}
%\references{
%}
%\author{
%}
%\note{
%}
%\seealso{
%}
\examples{
x = rnorm(100)
y = rnorm(100)
txt = sprintf("\%.2f", rnorm(100))
plot(x, y, pch=3, col=2)
l = add.labels(x, y, txt, mar=0.2)
rect(l$x, l$y, l$x + l$w, l$y + l$h, col="#00000020", border=NA)
text(l$lx, l$ly, txt, col=4)
segments(x, y, l$lx, l$ly, col=3)
}
\keyword{dplot}
<file_sep>/R/s2d.R
data2screen <- function(x, y, width = par("fin")[1] * dpi, height = par("fin")[2] * dpi, dpi = 72, plt = par("plt"), usr = par("usr"), flip=FALSE) {
if (missing(y) && length(dim(x)) > 1) {
ml = dim(x)[1]
y = x[,2]
x = x[,1]
} else {
if (missing(y)) stop("y is missing and x is not a matrix")
ml = max(length(x), length(y))
if (length(x) != ml) x = rep(x, length.out=ml)
if (length(y) != ml) y = rep(y, length.out=ml)
}
x0 = width * plt[1]
y0 = height * plt[3]
dx = x0 + (x - usr[1]) * (width * (plt[2] - plt[1])) / (usr[2] - usr[1])
dy = y0 + (y - usr[3]) * (height * (plt[4] - plt[3])) / (usr[4] - usr[3])
if (flip) dy = height - dy
if (ml > 1) matrix(c(dx, dy),,2,dimnames=list(NULL,c("x","y"))) else c(x=dx, y=dy)
}
screen2data <- function(x, y, width = par("fin")[1] * dpi, height = par("fin")[2] * dpi, dpi = 72, plt = par("plt"), usr = par("usr"), flip=FALSE) {
if (missing(y) && length(dim(x)) > 1) {
ml = dim(x)[1]
y = x[,2]
x = x[,1]
} else {
if (missing(y)) stop("y is missing and x is not a matrix")
ml = max(length(x), length(y))
if (length(x) != ml) x = rep(x, length.out=ml)
if (length(y) != ml) y = rep(y, length.out=ml)
}
x0 = width * plt[1]
y0 = height * plt[3]
if (flip) y = height - y
dx = usr[1] + (x - x0) / (width * (plt[2] - plt[1])) * (usr[2] - usr[1])
dy = usr[3] + (y - y0) / (height * (plt[4] - plt[3])) * (usr[4] - usr[3])
if (ml > 1) matrix(c(dx, dy),,2,dimnames=list(NULL,c("x","y"))) else c(x=dx, y=dy)
}
<file_sep>/man/setup.figure.Rd
\name{setup.figure}
\alias{setup.figure}
\alias{setup.figure.gridColScheme}
\alias{setup.figure.gridRowScheme}
\title{
Method defining a layout scheme
}
\description{
Layout schemes are defined by the scheme object and the implmentation of
the \code{setup.figure} method for that object.
The purpose of \code{setup.figure} is to set the \code{"fig"} graphical
parameter according to the state represented by the scheme object. This
allows implementation of arbitrary layout schemes.
}
\usage{
setup.figure(scheme)
\method{setup.figure}{gridColScheme}(scheme)
\method{setup.figure}{gridRowScheme}(scheme)
}
\arguments{
\item{scheme}{scheme defining the current state which is to be
reflected in the graphics parameters}
}
\details{
The scheme will contain the enclosing figure region in
\code{scheme$fig} and it is up to the \code{setup.figure} method
implementation to use the advancement index \code{scheme$index} to
determine the appropriate region to set the \code{"fig"} graphics
parameter. Clearly, the scheme object can contain any additonal
necessary needed for the method to perform its function.
For example, the grid layout schemes keep the matrix of the grid in
the scheme object and use simple modulo operation to determine the
approriate column and row to set \code{"fig"} accordingly.
}
\value{
scheme
}
%\references{
%}
\author{<NAME>}
%\note{
%}
%\examples{
%}
\keyword{hplot}
<file_sep>/R/cloud.R
cloud <- function(w, col, yspace=1.3, xspace=0.01, minh=0, ...) {
if (missing(col)) col <- "#000000" # grey(0.8-(w-min(w))/((max(w)-min(w)))
omar <- par("mar")
par(mar=c(0,0,0,0))
plot(0:1,0:1,type='n',axes=FALSE)
x=0; y=0.95; xch=minh;
cm=3/max(w)
.<-lapply(1:length(w), function(i) {
cex=w[i]*cm
ctw=strwidth(names(w[i]),cex=cex)
cth=strheight(names(w[i]),cex=cex)
if (cth > xch) xch <<- cth
if (x+ctw > 0.98) { x<<-0; y<<-y-(yspace*xch); xch<<-minh }
text(x,y,names(w[i]),cex=cex,adj=c(0,0.5),col=col[i]) # grey(0.8-cex/4))
x <<- x + ctw + xspace
})
par(omar)
invisible(TRUE)
}
<file_sep>/man/col.Rd
\name{col}
\alias{col.base}
\alias{col.bbr}
\alias{col.bwr}
\alias{col.br}
\alias{col.bw}
\alias{col.q}
\title{
Flexible quantitative color schemes
}
\description{
\code{col.base} is the base for all other functions and allows full
flexibility in defining arbitrary quantitative color schemes.
\code{col.bbr} provides blue-black-red diverging color scheme
(suitable for text and borderless glyphs on white background).
\code{col.bwr} provides blue-white-red diverging color scheme
(suitable for maps and gryphs with borders).
\code{col.br} provides blue-red color scheme.
\code{col.bw} provides black-white color scheme.
\code{col.q} returns transformed quantity between 0 and 1 for each
datapoint (suitable for pass-though to other color
schemes). \code{gray(col.q(...))} has the same effect (except for
lack of alpha support) as \code{col.bw}.
}
\usage{
col.base(x, alpha=1, lim=c(0, 1), center = mean(lim), fit=FALSE,
trans="id", na.col=NA, FN)
col.bbr (x, alpha=1, lim=c(0, 1), center = mean(lim), fit=FALSE,
trans="id", na.col=NA)
col.bwr (x, alpha=1, lim=c(0, 1), center = mean(lim), fit=FALSE,
trans="id", na.col=NA)
col.br (x, alpha=1, lim=c(0, 1), center = mean(lim), fit=FALSE,
trans="id", na.col=NA)
col.bw (x, alpha=1, lim=c(0, 1), center = mean(lim), fit=FALSE,
trans="id", na.col=NA)
col.q (x, alpha=1, lim=c(0, 1), center = mean(lim), fit=FALSE,
trans="id", na.col=NA)
}
\arguments{
\item{x}{data values (treated as numeric vector).}
\item{alpha}{alpha value. It will be passed directly to the call to
\code{rgb} except for \code{col.q} where is used to multiply the
resulting value.}
\item{lim}{data cut-off limits (range). Values outside this range will be
clipped to the nearest value in the range.}
\item{center}{center of the scale (mostly useful to calibrate
center color of diverging scales).}
\item{fit}{if set to \code{TRUE} then the data is shifted and scaled
to fit the entire \code{lim} range.}
\item{trans}{transformation of the resulting values. It can be
either a function or one of the character strings \code{"id"},
\code{"sin"} or \code{"asin"}. The transformation function may not
return values larger than 1 or smaller than 0.}
\item{na.col}{color (or value when used in \code{col.q}) to use for
missing values, will be used as-is (e.g., alpha is not applied).}
\item{FN}{function accepting three arguments \code{(a, b,
alpha)}. \code{a} is mapped by a linear function descending from 1 to 0
between \code{lim[1]} and \code{center}. \code{b} is a mapped by the
correspondingly increasing function between \code{center} and
\code{lim[2]}. \code{alpha} is passed from the original function call.}
}
\value{
\code{col.base} returns the result of the \code{FN} function.
\code{col.q} returns a vector of numeric values, all other functions
return a vector of colors as created by the \code{rgb} function.
}
%\details{
% The functions in this section allow to map data values to colors in
% a contolled fashion.
%}
%\seealso{
% \code{\link{.jcall}}, \code{\link{.jnull}}
%}
\examples{
plot(0:10, rep(0, 11), ylim=c(0,5), cex=3, pch=19, col=col.bbr(0:10, fit=TRUE))
points(0:10, rep(1,11), cex=3, pch=21, bg=col.br(0:10, fit=TRUE), col=1)
points(0:10, rep(2,11), cex=3, pch=21, bg=col.bw(0:10, fit=TRUE), col=1)
points(0:10, rep(3,11), cex=3, pch=21, bg=col.bwr(0:10, fit=TRUE, trans=sqrt),
col=1)
points(0:10, rep(4,11), cex=3, pch=21, bg=col.bwr(0:10, fit=TRUE), col=1)
points(0:10, rep(5,11), cex=3, pch=21, bg=col.bwr(0:10, fit=TRUE,
trans=function(x) x^2), col=1)
}
\keyword{interface}
<file_sep>/man/mfrow.Rd
\name{mfrow}
\alias{mfrow}
\alias{mfcol}
\title{
Recursive grid layout functions for graphics
}
\description{
\code{mfrow} and \code{mfcol} setup a multi-figure layout scheme on a
grid in the current graphics device. Unlike other layout methods the
schemes can be used recursively to create complex layouts with very
simple commands.
}
\usage{
mfrow(rows, cols, n, asp = 1, add = FALSE, times = NA,
fig = if (add) par("fig") else c(0, 1, 0, 1), \dots)
mfcol(rows, cols, n, asp = 1, add = FALSE, times = NA,
fig = if (add) par("fig") else c(0, 1, 0, 1), \dots)
}
\arguments{
\item{rows}{either a numeric vector of length one defining the number
of equally spaced rows or a vector specifying the relative height of
each row.}
\item{cols}{either a numeric vector of length one defining the number
of equally spaced columns or a vector specifying the relative width of
each row.}
\item{n}{if \code{rows} and \code{cols} are both not specified, then
\code{n} specifies the minimal number of cells that the layout
should contain. In that case \code{rows} and \code{cols} are
computed such that their product is at least \code{n} and the
resulting aspect ratio of the figures is as close to \code{asp} as
possible.}
\item{asp}{numeric, desired aspect ratio of the figures when \code{n}
is used to specify the grid}
\item{add}{logical, if \code{TRUE} then the layout scheme is added to
the layout stack, allowing recursive layouts. Otherwise the
currently layout is replaced with the new grid layout.}
\item{times}{number of times this layout should be applied or
\code{NA} for unlimited. Any number larger than 1e6 is interpreted
as \code{NA}.}
\item{fig}{boundaries of the figure that will be split using this
layout scheme.}
\item{\dots}{additional arguments that will be passed to
\code{\link{par}} when a new figure is setup.}
}
\details{
\code{mfrow} and \code{mfcol} have a similar effect as the
corresponding graphics parameters, but they are more flexible
(allowing individual withs and heights) and construct a scheme that
can be used recursively with \code{add = TRUE}.
Note that the scheme layout method is incompatible with all other
layout methods that are not based on the scheme stack, such as
\code{par(mfrow)} or \code{\link{layout}}. It can be to a degree
combined with \code{\link{split.screen}} with \code{add = TRUE} if
used as a sub-layout thereof since \code{screen} uses a co-operative
manipulation of figures. However, in that case you should make sure
that the stack layout does not overflow (i.e., you plot only at most
as many plots as there are figures) or it will clear the device.
}
\value{
object of the class \code{scheme}.
}
\note{
All layout functions require R 2.13.0 or higher! If plots seemingly
don't move from the first figure then you either have old version or
other code has removed the neessary "before.plot.new" hook.
}
%\references{
%}
\author{
<NAME>
}
%\seealso{
%}
\examples{
## one advantage is that you can simply specify the number of plots
## the layout will then depend on the aspect ratio of the device
mfrow(n=8)
par(mar=c(2,2,0,0))
for (i in 1:8) plot(rnorm(100), rnorm(100), col=i, pch=19)
## or you can create recursive layouts
mfrow(2, 4) ## 4 x 2 base grid
mfrow(c(1, 4), 1, add=TRUE) ## each cell split asymetrically 1:4
par(mar=rep(0,4))
for (i in 1:8) {
plot(0:1, 0:1, type='n', axes=FALSE); rect(0,0,1,1); text(0.5, 0.5, i)
plot(rnorm(100), rnorm(100), col=i, pch=19, axes=FALSE)
}
}
\keyword{hplot}
<file_sep>/man/fd.Rd
\name{fd}
\alias{fd}
\alias{fd.matrix}
\alias{fd.table}
\title{
Fluctuation diagram
}
\description{
Draws a fluctuation diagram.
}
\usage{
fd(x, ...)
\method{fd}{matrix}(x, add = FALSE, vals = FALSE, at.x, at.y, axes = TRUE,
frame.plot = FALSE, main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
zmax = max(x, na.rm = TRUE), xlim, ylim, asp = 1, panel.first = NULL,
panel.last = NULL, ann = par("ann"), col = "grey", border = "black",
\dots)
\method{fd}{table}(x, add = FALSE, vals = FALSE, at.x, at.y, axes = TRUE,
frame.plot = FALSE, main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
zmax = max(x, na.rm = TRUE), xlim, ylim, asp = 1, panel.first = NULL,
panel.last = NULL, ann = par("ann"), col = "grey", border = "black",
\dots)
}
\arguments{
\item{x}{object to draw fluctuation diagram of (most commonly a table)}
\item{add}{a logical value indicating whether to add to an existing
plot (\code{TRUE}) or to create a new plot (\code{FALSE}).}
\item{vals}{a logical value indicating whether to draw values into the
rectangles (discouraged and unimplemented).}
\item{at.x}{locations of the colums (by default \code{1:ncol})}
\item{at.y}{locations of the rows (by default \code{1:nrow})}
\item{axes}{a logical value indicating whether both axes should be
drawn on the plot. Use graphical parameter \code{xaxt} or
\code{yaxt} to suppress just one of the axes.}
\item{frame.plot}{a logical indicating whether a box should be drawn
around the plot.}
\item{main}{a main title for the plot, see also \code{\link{title}}.}
\item{sub}{a subtitle for the plot.}
\item{xlab}{a label for the \code{x} axis.}
\item{ylab}{a label for the \code{y} axis.}
\item{zmax}{value representing the total size of an allocated box.}
\item{xlim}{the x limits (x1, x2) of the plot. The default is the
range of \code{at.x} with an additional 0.5 margin of the ends.}
\item{ylim}{the y limits of the plot.}
\item{asp}{the y/x aspect ratio, see \code{\link{plot.window}}.}
\item{panel.first}{
an expression to be evaluated after the plot axes are set
up but before any plotting takes place. This can be useful
for drawing background grids}
\item{panel.last}{
an expression to be evaluated after plotting has taken
place.}
\item{ann}{see \code{"ann"} graphical parameter}
\item{col}{color of the boxes to be filled with, will be recycled to
match the shape of \code{x}.}
\item{border}{color of the box borders - only scalar value is
supported at the moment.}
\item{\dots}{additional graphical parameters}
}
%\details{
%}
\value{
Returns (invisibly) a data frame describing the sparse representation
of the boxes as location and radius.
}
%\references{
%}
%\author{
%}
%\note{
%}
\examples{
## this is best viewed on a wide-screen device...
par(mfrow=c(1,2))
for (sex in dimnames(HairEyeColor)$Sex)
fd(HairEyeColor[,,sex], main=sex)
}
\keyword{hplot}
<file_sep>/R/col.R
# base for all diverging mixing
col.base <- function(x, alpha=1, lim=c(0, 1), center = mean(lim), fit=FALSE, trans="id", na.col=NA, FN) {
if (all(is.na(x))) return(rep(na.col, length(x)))
nas <- is.na(x)
if (any(nas)) x[nas] <- x[which(!nas)[1]] # replace all NAs with the first non-NA value (we'll fix it later)
if (fit) x <- (x - min(x))/(max(x) - min(x)) * (lim[2] - lim[1]) + lim[1]
x[x > lim[2]] <- lim[2]
x[x < lim[1]] <- lim[1]
r <- (center - x) / (center - lim[1])
r[r < 0] <- 0
if (is.function(trans)) r <- trans(r) else
if (trans == "sin") r <- sin(r * pi / 2) else
if (trans == "asin") r <- asin(r) / pi * 2
b <- (x - center) / (lim[2] - center)
b[b < 0] <- 0
if (is.function(trans)) b <- trans(b) else
if (trans == "sin") b <- sin(b * pi / 2) else
if (trans == "asin") b <- asin(b) / pi * 2
res <- FN(r, b, alpha)
if (any(nas)) res[nas] <- na.col # replace all NAs with na.col
res
}
col.bbr <- function(x, alpha=1, lim=c(0, 1), center = mean(lim), fit=FALSE, trans="id", na.col=NA)
col.base(x, alpha, lim, center, fit, trans, na.col, function(r,b,a) rgb(b, 0, r, a))
col.bwr <- function(x, alpha=1, lim=c(0, 1), center = mean(lim), fit=FALSE, trans="id", na.col=NA)
col.base(x, alpha, lim, center, fit, trans, na.col, function(r,b,a) rgb(1 - r, 1 - (r + b), 1 - b, a))
col.br <- function(x, alpha=1, lim=c(0, 1), center = mean(lim), fit=FALSE, trans="id", na.col=NA)
col.base(x, alpha, lim, center, fit, trans, na.col, function(r,b,a) rgb((b + (1 - r)) / 2, 0, ((1 - b) + r) / 2, a))
col.bw <- function(x, alpha=1, lim=c(0, 1), center = mean(lim), fit=FALSE, trans="id", na.col=NA)
col.base(x, alpha, lim, center, fit, trans, na.col, function(r,b,a) rgb((b + (1 - r)) / 2, (b + (1 - r)) / 2, (b + (1 - r)) / 2, a))
col.q <- function(x, alpha=1, lim=c(0, 1), center = mean(lim), fit=FALSE, trans="id", na.col=NA)
col.base(x, alpha, lim, center, fit, trans, na.col, function(r,b,a) a * ((b + (1 - r)) / 2))
# not good - need to look at Marty's scheme ...
#col.yg <- function(x, alpha=1, lim=c(0, 1), center = mean(lim), fit=FALSE, trans="id", na.col=NA)
# col.base(x, alpha, lim, center, fit, trans, na.col, function(r,b,a) rgb(((1 - b) + r) / 2 , 1, 0, a))
<file_sep>/mkdist
#!/bin/sh
PNAME=snippets
SWD=`pwd`
VER=`sed -n 's/Version: \(.*\)/\1/p' DESCRIPTION`
echo "Removing previous dist ..."
rm -rf /tmp/${PNAME}
echo "Copying package base ..."
cp -pR ../${PNAME} /tmp
rm -f /tmp/${PNAME}/mkdist
cd /tmp/${PNAME}
echo "Removing CVS and backup stuff ..."
find . -name CVS -o -name .svn | xargs rm -rf
find . -name \*~ | xargs rm -f
rm -rf .git*
echo "Creating package ..."
cd ..
R CMD build ${PNAME}
cd ${SWD}
cp /tmp/${PNAME}_${VER}.tar.gz ..
rm -rf /tmp/${PNAME}
echo "Done."
ls -l ../${PNAME}_${VER}.tar.gz
<file_sep>/man/osm-tools.Rd
\name{osm-tools}
\alias{osm.xy2ll}
\alias{osm.ll2xy}
\title{
Tools converting from lat/lon coordinates to OSM tiles and back.
}
\description{
\code{osm.ll2xy} converts lat/lon coordinates to OpenStreetMap tile
numbers. \code{osm.xy2ll} performs the inverse conversion.
}
\usage{
osm.xy2ll(x, y, zoom = 16)
osm.ll2xy(lon, lat, zoom = 16)
}
\arguments{
\item{x}{number of the tile in the x direction}
\item{y}{number of the tile in the y direction}
\item{lon}{longitude}
\item{lat}{latitude}
\item{zoom}{zoom factor of the tiles}
}
\details{
\code{osm.ll2xy} computes tile numbers for given latitude and
longitude, \code{osm.xy2ll} does the inverse.
}
\value{
\code{osm.ll2xy} returns a list with the components \code{x} and \code{y}
\code{osm.xy2ll} returns a list with the components \code{lon} and \code{lat}
}
\seealso{
\code{\link{osmap}}
}
%\examples{
%}
\keyword{manip}
|
e68965e098cf1674fe63335d839d337dd90a3eeb
|
[
"R",
"Shell"
] | 22 |
R
|
s-u/snippets
|
6e638c9e4408aa11572afe1404939df414e2803b
|
91183ba6ecf77c92b81d09c130b54dc66c52026f
|
refs/heads/master
|
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import Modelo.forenKeys;
import Modelo.Conecion;
import coneciones.GetConecion;
import coneciones.poolConecciones;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
/**
*
* @author ASUS_01
*/
public class Pojos extends javax.swing.JFrame {
Properties propiedade;
Conecion c;
Conecion c2;
ArrayList<String> ListTable = new ArrayList();
ArrayList<String> ListTable2 = new ArrayList();
ArrayList<forenKeys> listForenKey = new ArrayList();
String tablas = "";
poolConecciones pool=new poolConecciones();
public Connection con;
public Pojos(Properties p, Conecion c) throws IOException, SQLException, ClassNotFoundException {
initComponents();
this.setLocationRelativeTo(null);
this.propiedade = p;
this.c2 = c;
coneciones.addItem(c.getNombre());
mns.setText(".");
pool = GetConecion.getControllerpool(p);
conectarPojos();
}
public void conectarPojos() throws SQLException, ClassNotFoundException {
ListTable.clear();
try {
System.out.println("Holaaa");
if(pool==null){
System.out.println("poll null");
}
con = pool.dataSource.getConnection();
DatabaseMetaData metaDatos = con.getMetaData();
System.out.println("-----");
String v[] = {"TABLE"};
ResultSet rs = metaDatos.getTables(null, null, null, v);
while (rs.next()) {
ListTable.add(rs.getString(3));
}
listForenKey = forenKeys(1);
for (forenKeys string : listForenKey) {
System.out.println("-- " + string.toString());
}
cargarlist();
} catch (Exception ex) {
System.out.println("Error : " + ex.toString());
} finally {
con.close();
}
}
public void cargarlist() {
DefaultListModel listModel = new DefaultListModel();
for (String string : ListTable) {
listModel.addElement(string);
}
jList2 = new javax.swing.JList<>();
jList2.setModel(listModel);
jScrollPane2.setViewportView(jList2);
}
public void cargarlist2() {
DefaultListModel listModel = new DefaultListModel();
for (String string : ListTable2) {
listModel.addElement(string);
}
jList1 = new javax.swing.JList<>();
jList1.setModel(listModel);
jScrollPane1.setViewportView(jList1);
}
public void pasarListAll() throws SQLException {
DefaultListModel listModel = new DefaultListModel();
ArrayList<String> remove = new ArrayList();
for (String string : ListTable2) {
listModel.addElement(string);
if (buscarTabla(ListTable2, string) == false) {
ListTable2.add(string);
}
}
for (String string : ListTable) {
listModel.addElement(string);
if (buscarTabla(ListTable2, string) == false) {
ListTable2.add(string);
}
}
for (String list1 : ListTable2) {
for (String list2 : ListTable) {
if (list1.trim().equalsIgnoreCase(list2.trim())) {
remove.add(list2);
}
}
}
for (String list1 : remove) {
ListTable.remove(list1);
}
jList1 = new javax.swing.JList<>();
jList1.setModel(listModel);
jScrollPane1.setViewportView(jList1);
cargarlist();
}
public void quitarListAll() throws SQLException {
DefaultListModel listModel = new DefaultListModel();
ArrayList<String> remove = new ArrayList();
for (String string : ListTable) {
listModel.addElement(string);
if (buscarTabla(ListTable, string) == false) {
ListTable.add(string);
}
}
for (String string : ListTable2) {
listModel.addElement(string);
if (buscarTabla(ListTable, string) == false) {
ListTable.add(string);
}
}
for (String list1 : ListTable) {
for (String list2 : ListTable2) {
if (list1.trim().equalsIgnoreCase(list2.trim())) {
remove.add(list2);
}
}
}
for (String list1 : remove) {
ListTable2.remove(list1);
}
jList2 = new javax.swing.JList<>();
jList2.setModel(listModel);
jScrollPane2.setViewportView(jList2);
cargarlist2();
}
public void pasarList() throws SQLException {
DefaultListModel listModel = new DefaultListModel();
ArrayList<String> remove = new ArrayList();
boolean r = false;
for (String tablas : jList2.getSelectedValuesList()) {
for (forenKeys fk : listForenKey) {
if (tablas.trim().equalsIgnoreCase(fk.getTableReference().trim())) {
if (buscarTabla(ListTable2, fk.getTable()) == false) {
ListTable2.add(fk.getTable());
}
}
}
if (buscarTabla(ListTable2, tablas) == false) {
ListTable2.add(tablas);
}
}
remove.clear();
for (String string : ListTable2) {
listModel.addElement(string);
}
for (String list1 : ListTable2) {
for (String list2 : ListTable) {
if (list1.trim().equalsIgnoreCase(list2.trim())) {
remove.add(list2);
}
}
}
for (String list1 : remove) {
ListTable.remove(list1);
}
jList1 = new javax.swing.JList<>();
jList1.setModel(listModel);
jScrollPane1.setViewportView(jList1);
cargarlist();
}
public void quitarList() throws SQLException {
DefaultListModel listModel = new DefaultListModel();
ArrayList<String> remove = new ArrayList();
boolean r = false;
for (String tablas : jList1.getSelectedValuesList()) {
for (forenKeys fk : listForenKey) {
if (tablas.trim().equalsIgnoreCase(fk.getTableReference().trim())) {
if (buscarTabla(ListTable, fk.getTable()) == false) {
ListTable.add(fk.getTable());
}
}
}
if (buscarTabla(ListTable, tablas) == false) {
ListTable.add(tablas);
}
}
remove.clear();
for (String string : ListTable) {
listModel.addElement(string);
}
for (String list1 : ListTable) {
for (String list2 : ListTable2) {
if (list1.trim().equalsIgnoreCase(list2.trim())) {
remove.add(list2);
}
}
}
for (String list1 : remove) {
ListTable2.remove(list1);
}
jList2 = new javax.swing.JList<>();
jList2.setModel(listModel);
jScrollPane2.setViewportView(jList2);
cargarlist2();
}
public int repetido(ArrayList<String> ListTable2, String tabla) {
int b = 0;
for (String tablas : ListTable2) {
if (tablas.trim().equalsIgnoreCase(tabla.trim())) {
b++;
}
}
// if (b > 1) {
//
// for (String tablas : ListTable2) {
// if (tablas.trim().equalsIgnoreCase(tabla.trim())) {
// ListTable2.remove(tablas);
// break;
// }
// }
// }
return b;
}
public boolean buscarTabla(ArrayList<String> ListTable2, String tabla) {
boolean r = false;
for (String tablas : ListTable2) {
if (tablas.trim().equalsIgnoreCase(tabla.trim())) {
r = true;
break;
}
}
// if (b > 1) {
//
// for (String tablas : ListTable2) {
// if (tablas.trim().equalsIgnoreCase(tabla.trim())) {
// ListTable2.remove(tablas);
// break;
// }
// }
// }
return r;
}
public ArrayList<forenKeys> forenKeys(int condicion) throws SQLException {
ArrayList<forenKeys> listForenKey = new ArrayList();
DatabaseMetaData metaDatos = con.getMetaData();
String v[] = {"TABLE"};
ResultSet rs = metaDatos.getTables(null, null, null, v);
while (rs.next()) {
String tabla = rs.getString(3);
ResultSet rs4 = metaDatos.getExportedKeys(null, null, tabla);
while (rs4.next()) {
// fkTableName = fkTableName + "List<" + rs4.getString("FKTABLE_NAME") + "> List_" + rs4.getString("FKTABLE_NAME") + " = new ArrayList();\n";
String forenK = rs4.getString("FKTABLE_NAME");
String fkColumnName = rs4.getString("FKCOLUMN_NAME");
if (condicion == 1) {
listForenKey.add(new forenKeys(tabla, forenK));
System.out.println("reference : " + tabla + " ListTable2 : " + forenK);
// importaciones = importaciones + "import java.util.List;\n";
} else if (condicion == 2) {
listForenKey.add(new forenKeys(tabla, forenK, fkColumnName));
System.out.println("reference : " + tabla + " ListTable2 : " + forenK);
}
}
}
return listForenKey;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jSeparator1 = new javax.swing.JSeparator();
jSeparator2 = new javax.swing.JSeparator();
coneciones = new javax.swing.JComboBox<>();
jButton3 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
mns = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList<>();
jScrollPane2 = new javax.swing.JScrollPane();
jList2 = new javax.swing.JList<>();
controladores = new javax.swing.JCheckBox();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
FolderPojos = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 578, 10));
jPanel1.add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 369, 578, 10));
coneciones.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
conecionesMouseClicked(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
conecionesMousePressed(evt);
}
});
coneciones.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
conecionesActionPerformed(evt);
}
});
jPanel1.add(coneciones, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 30, 420, -1));
jButton3.setText("Finish");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jPanel1.add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 330, -1, -1));
jLabel2.setText("Folder");
jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 60, -1, -1));
jPanel1.add(mns, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 330, 210, -1));
jScrollPane1.setViewportView(jList1);
jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 90, 180, 200));
jScrollPane2.setViewportView(jList2);
jPanel1.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 90, 180, 200));
controladores.setText("Crear Controladores y View");
jPanel1.add(controladores, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 300, -1, -1));
jButton1.setText("<");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 220, -1, -1));
jButton2.setText(">");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jPanel1.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 130, -1, -1));
jButton4.setText(">>");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jPanel1.add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 160, -1, -1));
jButton5.setText("<<");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jPanel1.add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 190, -1, -1));
jLabel3.setText("Date Base");
jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 30, -1, -1));
jPanel1.add(FolderPojos, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 60, 420, -1));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void conecionesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_conecionesMouseClicked
}//GEN-LAST:event_conecionesMouseClicked
private void conecionesMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_conecionesMousePressed
}//GEN-LAST:event_conecionesMousePressed
private void conecionesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_conecionesActionPerformed
}//GEN-LAST:event_conecionesActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
this.dispose();
try {
if (controladores.isSelected()) {
new Controladores(ListTable2, propiedade, this.c2, FolderPojos.getText()).setVisible(true);
} else {
new CreacionJCM(ListTable2, controladores.isSelected(), propiedade, c, FolderPojos.getText(), "", 3).setVisible(true);
}
} catch (IOException ex) {
Logger.getLogger(Pojos.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Pojos.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Pojos.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
try {
pasarList();
} catch (SQLException ex) {
Logger.getLogger(Pojos.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
try {
pasarListAll();
} catch (SQLException ex) {
Logger.getLogger(Pojos.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
quitarList();
} catch (SQLException ex) {
Logger.getLogger(Pojos.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
try {
quitarListAll();
} catch (SQLException ex) {
Logger.getLogger(Pojos.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton5ActionPerformed
public void siguiente() {
System.out.println("Entro");
for (int string : jList2.getSelectedIndices()) {
System.out.println("--- " + string);
}
for (String string : jList2.getSelectedValuesList()) {
System.out.println("--- " + string);
}
}
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField FolderPojos;
private javax.swing.JComboBox<String> coneciones;
private javax.swing.JCheckBox controladores;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JList<String> jList1;
private javax.swing.JList<String> jList2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JLabel mns;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import Modelo.Conecion;
import coneciones.GetConecion;
import coneciones.poolConecciones;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author ASUS_01
*/
public class ParametrosBD extends javax.swing.JFrame {
/**
* Creates new form Configur
*/
String drive1 = "";
ArrayList<Conecion> listConeciones = new ArrayList();
Conecion conecion;
Properties p = new Properties();
boolean validacion;
poolConecciones pool;
public ParametrosBD(Conecion c) throws IOException {
initComponents();
this.setLocationRelativeTo(null);
this.conecion = c;
coneciones.addItem(c.getNombre());
mns.setText(".");
validacion = false;
Host.setText("localhost");
puerto.setText(conecion.getPuerto());
BD.setText("");
user.setText("");
pass.setText("");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jSeparator1 = new javax.swing.JSeparator();
jSeparator2 = new javax.swing.JSeparator();
coneciones = new javax.swing.JComboBox<>();
jButton3 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
Host = new javax.swing.JTextField();
BD = new javax.swing.JTextField();
user = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
pass = new javax.swing.JTextField();
puerto = new javax.swing.JTextField();
mns = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(630, 400));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 578, 10));
jPanel1.add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 369, 578, 10));
coneciones.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
conecionesMouseClicked(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
conecionesMousePressed(evt);
}
});
coneciones.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
conecionesActionPerformed(evt);
}
});
jPanel1.add(coneciones, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 50, 400, -1));
jButton3.setText("Siguiente");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jPanel1.add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 330, -1, -1));
jLabel1.setText("JDBC URL :");
jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 280, -1, -1));
jLabel2.setText("Driver Name");
jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 50, -1, -1));
jLabel3.setText("Host");
jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 90, -1, -1));
jLabel4.setText("Date Base");
jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 130, -1, -1));
jLabel5.setText("Puerto");
jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 90, -1, -1));
jLabel6.setText("User");
jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 170, -1, -1));
jTextField1.setEnabled(false);
jPanel1.add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 270, 400, -1));
Host.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
HostActionPerformed(evt);
}
});
jPanel1.add(Host, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 90, 220, -1));
jPanel1.add(BD, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 130, 400, -1));
jPanel1.add(user, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 170, 400, -1));
jButton1.setText("Test");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 240, -1, -1));
jLabel7.setText("Password");
jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 210, -1, -1));
jPanel1.add(pass, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 210, 400, -1));
jPanel1.add(puerto, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 90, 80, -1));
jPanel1.add(mns, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 330, 210, -1));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void conecionesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_conecionesMouseClicked
}//GEN-LAST:event_conecionesMouseClicked
private void conecionesMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_conecionesMousePressed
}//GEN-LAST:event_conecionesMousePressed
private void conecionesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_conecionesActionPerformed
}//GEN-LAST:event_conecionesActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
if (validacion) {
} else {
}
this.dispose();
try {
new Pojos(p, conecion).setVisible(true);
} catch (IOException ex) {
System.out.println("error : " + ex.toString());
} catch (SQLException ex) {
Logger.getLogger(ParametrosBD.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ParametrosBD.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton3ActionPerformed
private void HostActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HostActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_HostActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
comprobarConecion();
} catch (ClassNotFoundException ex) {
Logger.getLogger(ParametrosBD.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
public void comprobarConecion() throws ClassNotFoundException {
try {
if (Host.getText().length() == 0 || puerto.getText().length() == 0 || BD.getText().length() == 0 || BD.getText().length() == 0
|| user.getText().length() == 0) {
System.out.println("deben estar todos llenos");
mns.setText("Llenar todos los campos");
} else {
System.out.println("todo bn");
p.put("user", user.getText());
p.put("password", <PASSWORD>());
p.put("BD", conecion.getNombre());
p.put("Servidor", Host.getText());
p.put("Puerto", puerto.getText());
p.put("NameBD", BD.getText());
p.put("driver", conecion.getDrive());
pool = GetConecion.getControllerpool(p);
if (pool != null) {
mns.setText("Conecto bien");
validacion = true;
} else {
validacion = false;
mns.setText("Error de conecion");
}
}
} catch (Exception ex) {
} finally {
}
}
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField BD;
private javax.swing.JTextField Host;
private javax.swing.JComboBox<String> coneciones;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
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.JPanel jPanel1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JTextField jTextField1;
private javax.swing.JLabel mns;
private javax.swing.JTextField pass;
private javax.swing.JTextField puerto;
private javax.swing.JTextField user;
// End of variables declaration//GEN-END:variables
}
<file_sep>package coneciones;
//import JAJA.categoria;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class sqlServer {
public static String driver = "org.postgresql.Driver";
public static String connectString = "jdbc:postgresql://localhost:5432/compraventa";
public static String user = "sa";
public static String password = "<PASSWORD>";//ya esta listo
public static String query;
public static Statement stat;
public static ResultSet rs;
public static Connection con;
private static sqlServer db;
private sqlServer() {
boolean r = false;
try {
Class.forName(driver);
String connectionUrl = "jdbc:sqlserver://localhost:1433;"
+ "databaseName=FairPlay;user=" + user + ";password=" + <PASSWORD> + ";";
con = DriverManager.getConnection(connectionUrl);
stat = con.createStatement();
r = true;
System.out.println("conecto");
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException ex) {
Logger.getLogger(sqlServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static synchronized sqlServer getDbCon() {
if (db == null) {
System.out.println("nuevo");
db = new sqlServer();
}
return db;
}
public ResultSet query(String query) throws SQLException {
stat = db.con.createStatement();
ResultSet res = stat.executeQuery(query);
return res;
}
public int transaccion(String insertQuery) throws SQLException {
stat = db.con.createStatement();
int result = stat.executeUpdate(insertQuery);
return result;
}
public Connection getconecion() {
return con;
}
public static boolean ejecuteQuery(String x) throws SQLException {
boolean r = true;
try {
rs = stat.executeQuery(x);
} catch (SQLException e) {
System.out.println("ERROR AL HACER QUERY " + e.toString());
r = false;
}
return r;
}
public static boolean ejecuteUpdate(String query) {
boolean r = true;
try {
stat.executeUpdate(query);
r = true;
} catch (SQLException e) {
System.out.println("ERROR Al HACER UPDTAPE" + e.toString());
r = false;
}
return r;
}
public static void cerrarConexion() {
try {
stat.close();
con.close();
} catch (SQLException e) {
System.out.println("Error en cerrar la base de datos" + e.toString());
}
}
public static void main(String[] args) throws ClassNotFoundException {
////
sqlServer conecion = sqlServer.getDbCon();
// categoria cate=new categoria();
// cate.setidcategoria(new BigDecimal(37));
// cate.setdescripcion("kikiki-----++++-----");
// cate.remove();
//
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Modelo;
/**
*
* @author ASUS_01
*/
public class forenKeys {
public String table;
public String tableReference;
public String column;
public forenKeys() {
}
public forenKeys(String table, String tableReference) {
this.table = table;
this.tableReference = tableReference;
}
public forenKeys(String table, String tableReference, String column) {
this.table = table;
this.tableReference = tableReference;
this.column = column;
}
public String getTable() {
return table;
}
public void setTable(String table) {
this.table = table;
}
public String getTableReference() {
return tableReference;
}
public void setTableReference(String tableReference) {
this.tableReference = tableReference;
}
public String getColumn() {
return column;
}
public void setColumn(String column) {
this.column = column;
}
@Override
public String toString() {
return "forenKeys{" + "table=" + table + ", tableReference=" + tableReference + ", column=" + column + '}';
}
}
|
1adf5c70d0fc75c5c1e691eae94f46f91e98c881
|
[
"Java"
] | 4 |
Java
|
jdcastrillon/JCM
|
2de18ef4c26782665dbe764534bc610b01b67f56
|
5ada3bff806b5bb97f4529bc2f7f1e1e88dca43d
|
refs/heads/master
|
<repo_name>SimarKareer/iron2Radiant<file_sep>/util.py
import cv2
import numpy as np
import os
from matplotlib import pyplot as plt
import imutils
import math
import numpy
from skimage import data
from skimage.feature import match_template
from scipy import stats
ENEMY_COLOR = [91, 85, 249]#[249, 85, 91]
ME_COLOR = [194, 254, 255]
FRIENDLY_COLOR = [252, 253, 152]
GRAY = [146, 149, 146]
VISION = [0,165,255]
template_list = []
for agent_template in os.listdir('./image_templates'):
template_list.append((cv2.imread('./image_templates/' + agent_template), agent_template[:-4]))
def imgToMap(img, streamMode=True):
"""
Returns a cv2 image object that has the relevant map
"""
if streamMode == False:
img = cv2.imread(img)
map_img = img[10:475, 70:455, :]
return map_img
def transition(map, agent, currPos):
"""
"""
def updateProbs(currPred, obs):
"""
Update current predictions based on new obserations, and time step
"""
#for every enemy agent
# for every tile in map
# update predictions of being at that tile
# will need to call transition
def imToObs(map_img, grid_shape, circle_radius, vis=False):
"""
Take in a map image. Return list of [("agent", x, y)]
"""
try:
locs = []
for tmp, name in template_list:
#Open template and get canny
tmp = cv2.Canny(tmp, 10, 25)
(height, width) = tmp.shape[:2]
#open the main image and convert it to gray scale image
gray_image = cv2.cvtColor(map_img, cv2.COLOR_BGR2GRAY)
temp_found = None
for scale in np.linspace(0.8, 1.0, 4)[::-1]:
#resize the image and store the ratio
resized_img = imutils.resize(gray_image, width=int(gray_image.shape[1] * scale))
ratio = gray_image.shape[1] / float(resized_img.shape[1])
#Convert to edged image for checking
e = cv2.Canny(resized_img, 10, 25)
match = cv2.matchTemplate(e, tmp, cv2.TM_CCORR_NORMED)
(_, val_max, _, loc_max) = cv2.minMaxLoc(match)
#get the best for each scale sizing
if temp_found is None or val_max>temp_found[0]:
temp_found = (val_max, loc_max, ratio)
#Get information from temp_found to compute x,y coordinate
(val_max, loc_max, r) = temp_found
#print(name, val_max)
if val_max < 0.52:
continue
(x_start, y_start) = (int(loc_max[0]), int(loc_max[1]))
(x_end, y_end) = (int((loc_max[0] + width)), int((loc_max[1] + height)))
#Draw rectangle around the template
x_pos = round((x_start + x_end) / 2)
y_pos = round((y_start + y_end) / 2)
char_map = map_img[y_pos - circle_radius -1:y_pos + circle_radius + 1,
x_pos - circle_radius - 1: x_pos + circle_radius + 1]
bluest = (442, 0, 0)
reddest = (442, 0, 0)
for degree in range(0, 360, 6):
theta = math.radians(degree)
y_loc = circle_radius - math.floor(circle_radius * math.sin(theta))
x_loc = circle_radius + math.floor(circle_radius * math.cos(theta))
pix = char_map[y_loc, x_loc, :]
blue_diff = np.linalg.norm(pix - FRIENDLY_COLOR)
red_diff = np.linalg.norm(pix - ENEMY_COLOR)
if blue_diff < bluest[0]:
bluest = (blue_diff, degree, pix)
if red_diff < reddest[0]:
reddest = (red_diff, degree, pix)
if name[-1] == 'b' and (reddest[0] < bluest[0]):
continue
if name[-1] == 'r' and (bluest[0] < reddest[0]):
continue
best_pix = bluest[2]
min_degree = bluest[1]
if reddest[0] < bluest[0]:
min_degree = reddest[1]
best_pix = reddest[2]
if vis == True:
cv2.rectangle(map_img, (x_start, y_start), (x_end, y_end), (0, 0, 0), 1)
cv2.imwrite('res.png', map_img)
# TODO: Locs are currently in image map coordinates, need to be converted to grid coordinates
adjusted_x_pos = int((x_pos-14)/3.6)
adjusted_y_pos = int((y_pos-14)/3.6)
locs.append((name, adjusted_x_pos, adjusted_y_pos, min_degree))
except Exception as e:
print(e)
print(locs)
return locs
def findVisionCones(map_img):
"""
Take in a map image. Return 2D array of True/False based on where vision cones are
"""
map_img = map_img[14:-15, 14:-14]
white_lo=np.array([176,176,176])
white_hi=np.array([180,180,180])
# Mask image to only select whites
mask=cv2.inRange(map_img,white_lo,white_hi)
# Change image to black where we found white
map_img[mask>0]=VISION
# cv2.imwrite("test_cell.png",map_img)
y_dim = 120
x_dim = 100
y_chunk = map_img.shape[0] / y_dim
x_chunk = map_img.shape[1] / x_dim
vision_cones = np.zeros([y_dim, x_dim])
for y in range(0, y_dim - 1):
for x in range(0, x_dim - 1):
cell = map_img[math.floor(y*y_chunk):math.floor(y*y_chunk + y_chunk), math.floor(x*x_chunk):math.floor(x*x_chunk + x_chunk)]
# cv2.imwrite('cell_images/test_cell' + str(x) + ',' + str(y) + '.png', cell)
val_dict = {}
for row in cell:
for val in row:
if tuple(val) in val_dict:
val_dict[tuple(val)] += 1
else:
val_dict[tuple(val)] = 1
mode_val = list(max(val_dict, key = val_dict.get))
if mode_val == VISION:
vision_cones[y][x] = 1
return vision_cones
<file_sep>/stream.py
import time
import streamlink
import util
import matplotlib.pyplot as plt
import cv2
import numpy as np
from datetime import datetime
# use live streamer to figure out the stream info
def stream(ping):
streams = streamlink.streams("http://www.twitch.tv/Galaxspheria")
stream = streams['best']
vid = cv2.VideoCapture(stream.url)
ret, frame = vid.read()
count = 20
while ret:
ret, frame = vid.read()
if count % 20 == 0:
map_img = util.imgToMap(np.array(frame))
locs = util.imToObs(map_img, None, 15, vis=True)
now = datetime.now()
vision_cones = util.findVisionCones(map_img)
print((datetime.now()-now).total_seconds())
ping(locs, vision_cones)
count += 1
# open our out file.
#fname = "test.mpg"
#vid_file = open(fname,"wb")
# dump from the stream into an mpg file -- get a buffer going
#fd = stream.open()
#for i in range(0,2*2048):
# if i%256==0:
# print("Buffering...")
# new_bytes = fd.read(1024)
#vid_file.write(new_bytes)
# open the video file from the begining
#print("Done buffering.")
<file_sep>/heatmap.py
import matplotlib
import seaborn as sns
import io
import numpy as np
import base64
from scipy import ndimage
from PIL import Image
def generateMap(data):
wd = matplotlib.cm.plasma #._segmentdata # only has r,g,b
# wd['alpha'] = ((0.0, 0.0, 0.3),
# (0.3, 0.3, 1.0),
# (1.0, 1.0, 1.0))
cmap = wd(np.arange(wd.N))
cmap[:,-1] = np.linspace(0, 1, wd.N)
cmap = matplotlib.colors.ListedColormap(cmap)
# get the map image as an array so we can plot it
map_img = matplotlib.image.imread('rsz_map.png')
sns.set()
matplotlib.pyplot.figure(figsize=(10,10))
hmax = sns.heatmap(data,
cmap = cmap,
alpha = 0.3, # whole heatmap is translucent
zorder = 2,
cbar = False,
linewidths = 0.0,
)
hmax.set(xticklabels=[])
hmax.set(yticklabels=[])
sns.despine(top=True, right=True, left=True, bottom=True)
# heatmap uses pcolormesh instead of imshow, so we can't pass through
# extent as a kwarg, so we can't mmatch the heatmap to the map. Instead,
# match the map to the heatmap:
hmax.imshow(map_img,
aspect = hmax.get_aspect(),
extent = hmax.get_xlim() + hmax.get_ylim(),
zorder = 1) #put the map under the heatmap
buf = io.BytesIO()
matplotlib.pyplot.savefig(buf, format='jpeg')
matplotlib.pyplot.close()
buf.seek(0)
im = Image.open(buf)
return im, buf
def mapLoop():
# create heat map
for i in range(0, 1):
x = np.zeros((100, 100))
x[50, i] = 1
heatmap_data = ndimage.filters.gaussian_filter(x, sigma=16)
url = generateMap(heatmap_data)
print(url)
print('loop ' + str(i), end="\r")
# mapLoop()
<file_sep>/dbn/util.py
def euclideanDistance():
pass<file_sep>/dbn/ProcessMap.py
import pickle
import numpy as np
from dbn.MapLoader import getGrid
# Currently fixed movement to 1 since movement isn't computed shortest to longest distance
# Otherwise, could move through walls
# Future flag can be used to generate function per agent
def preprocess(grid, path, movement=1, flag=0):
mapping = {}
for y in range(grid.shape[0]):
for x in range(grid.shape[1]):
curr = grid[y][x]
allowed = []
# if curr == 0:
# continue
for h in range(-movement, movement + 1):
for w in range(-movement, movement + 1):
if y + h < 0 or y + h >= grid.shape[0] or x + w < 0 or x + w >= grid.shape[1]:
continue
nxt = grid[y + h][x + w]
# Don't allow moving in walls, onto boyes, xes one wax for teleport and heaven
if not ((nxt == 0 and curr != 0) or (curr != 3 and nxt == 3 and not h > 0) or (curr == 2 and nxt == 2 and not w < 1)): #or (nxt == 4 and curr != 4)):
if (nxt == 1 and x == 0):
allowed.append([97, 98])
elif (nxt == 1 and x == 0):
allowed.append([42, 54])
else:
allowed.append((y + h, x + w))
mapping[(y,x)] = np.array(allowed)
# y, x
# print('mapping', mapping[(30, 82)], grid[30][82], grid[30][81])
tester(mapping, (119, 99), grid)
with open(path, 'wb') as handle:
pickle.dump(mapping, handle, protocol=pickle.HIGHEST_PROTOCOL)
def tester(mapping, coord, grid):
''' coords in y, x (rows, col) '''
print('Start at ', coord, 'with color ', grid[coord[0]][coord[1]])
for item in mapping[coord]:
print('Allowed at ', item, 'with color ', grid[item[0]][item[1]])
if __name__ == "__main__":
name = 'bind100'
preprocess(getGrid("dbn/" + name + ".png"), "dbn/" + name + ".db")
<file_sep>/dbn/ObservationModels.py
def sightDistribution(self, observation):
pass
def audioDistribution(self, observation):
pass<file_sep>/dbn/mapLoader.py
from PIL import Image
import numpy as np
def getGrid(map_path):
# load the image
image = Image.open(map_path)
# convert image to numpy array
data = np.asarray(image.convert('L'))
unique_values = np.unique(data.flatten())
grid = data.copy()
count = 1
for val in unique_values:
if val == 255:
grid[data == val] = 0
else:
print(val, count)
grid[data == val] = count
count += 1
return grid
def gridToImg(grid, factor=50):
grid = grid * grid * factor
Image.fromarray(grid).save('dbn/temp.png')
def getLegalPos(grid):
# [ [x,y] ]
pos = []
for x in range(grid.shape[0]):
for y in range(grid.shape[1]):
if grid[x][y] != 0:
pos.append([x, y])
return np.array(pos)
def main():
img = getGrid("dbn/bind100.png")
gridToImg(img)
print(getLegalPos(img)[:8])
# print(img[0], img[:,0])
if __name__ == "__main__":
main()
<file_sep>/dbn/main.py
from dbn.Game import Game
def main():
game = Game(100)
obs = [
[("Raze", 50, 50)], [("Brimstone", 40, 70)], [("Brimstone", 10, 50)]
]
count = 0
while True:
Game.tick(obs[count])
count += 1
main()<file_sep>/README.md
Start the flask server using `python3 webstreaming.py`<file_sep>/dbn/Game.py
from dbn.ParticleFilter import ParticleFilter
from dbn.MapLoader import getGrid, getLegalPos
class Game:
def __init__(self, map_path, numParticles, names):
legalPos = getLegalPos(getGrid(map_path))
transitionPath = "dbn/bind100.db"
self.particleFilters = {name: ParticleFilter(numParticles, [120,100], transitionPath, legalPos) for name in names}
self.first = True
# self.particleFilter = particleFilter(numParticles, [1,1])
def tick(self, observations, visionCones):
print(observations)
# print(self.particleFilters["sage"].particles)
obsNames = []
for observation in observations:
name, x, y, theta = observation
obsNames.append(name)
for name, particleFilter in self.particleFilters.items():
if name + '_r' in obsNames:
idx = obsNames.index(name + '_r')
obsName, x, y, theta = observations[idx]
print("SHouldnt see this")
self.particleFilters[name].observe((x, y, theta))
self.first = False
# you don't need to do a vision code update here. Since seeing an agent will collapse it to one point anyways
else:
print("Should see this")
# Try time epoch first to allow true particles to escape
self.particleFilters[name].timeElapse()
if not self.first:
self.particleFilters[name].visionConeObserve(visionCones)
def getBeliefDist(self):
return [(name, particleFilter.getBeliefDistribution()) for name, particleFilter in self.particleFilters.items()]
<file_sep>/webstreaming.py
from heatmap import generateMap
from stream import stream
from dbn.Game import Game
from flask import Response
from flask import Flask
from flask import render_template
from scipy import ndimage
import numpy as np
import threading
import argparse
import datetime
import time
import io
# initialize the output frame and a lock used to ensure thread-safe
# exchanges of the output frames (useful when multiple browsers/tabs
# are viewing the stream)
outputFrame = None
lock = threading.Lock()
# initialize a flask object
app = Flask(__name__)
@app.route("/")
def index():
# return the rendered template
return render_template("index.html")
def detect_motion(game):
# grab global references to the video stream, output frame, and
# lock variables
global outputFrame, lock
# initialize the total number of frames read thus far
i = 0
# loop over frames from the video stream
while True:
# x = np.zeros((100, 100))
# x[50, i] = 1
heatmap_data = g.getBeliefDist() #ndimage.filters.gaussian_filter(x, sigma=16)
hardCodeAgent = None
for name, heatmap in heatmap_data:
if name == "sage":
hardCodeAgent = heatmap
# print(hardCodeAgent)
frame, buffer = generateMap(hardCodeAgent)
i += 2
if (i > 99):
i = 0
# acquire the lock, set the output frame, and release the
# lock
with lock:
outputFrame = frame.copy()
frame.close()
buffer.close()
def generate():
# grab global references to the output frame and lock variables
global outputFrame, lock
# loop over frames from the output stream
while True:
time.sleep(0.1)
# wait until the lock is acquired
with lock:
# check if the output frame is available, otherwise skip
# the iteration of the loop
if outputFrame is None:
continue
# encode the frame in JPEG format
with io.BytesIO() as output:
outputFrame.save(output, format="JPEG")
encodedImage = output.getvalue()
# yield the output frame in the byte format
yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
bytearray(encodedImage) + b'\r\n')
@app.route("/video_feed")
def video_feed():
# return the response generated along with the specific media
# type (mime type)
return Response(generate(),
mimetype = "multipart/x-mixed-replace; boundary=frame")
# check to see if this is the main thread of execution
if __name__ == '__main__':
numParticles = 1000
g = Game('./dbn/bind100.png', numParticles, ['sage'])
t = threading.Thread(target=detect_motion, args=[g])
t.daemon = True
t.start()
s = threading.Thread(target=stream, args=[g.tick])
s.daemon = True
s.start()
# start the flask app
app.run(port=3000, debug=True,
threaded=True, use_reloader=False)
<file_sep>/main.py
import util
#map_img = util.imgToMap('test_inputs/killjoy2.png', streamMode=False)
#locs = util.imToObs(map_img, None, 12, vis=True)
#print(locs)
<file_sep>/dbn/ParticleFilter.py
from dbn.ObservationModels import sightDistribution, audioDistribution
from dbn.TransitionFunctions import TransitionFunction
import numpy as np
class ParticleFilter:
def __init__(self, numParticles, gridSize, transition_path, legalPositions):
self.gridSize = gridSize
self.numParticles = numParticles
self.legalPositions = legalPositions
# print("HULOOOO?")
self.initParticles(numParticles, gridSize)
self.transitionFunction = TransitionFunction(transition_path)
def visionConeObserve(self, visionCones):
# print("TEST AHOWE")
allPossible = self.getBeliefDistribution()
# print('PPPP', self.particles)
# print((allPossible == 0).sum())
totalWeight = 0
if self.particles is None:
print("reseting particles")
self.initParticles(self.numParticles, self.gridSize)
if visionCones is not None:
for i in range(len(self.particles)):
# print('vision cone', visionCones.shape, self.particles[i], i)
y, x = self.particles[i].astype(int)
if visionCones[y, x]:
allPossible[y, x] = 0
else:
totalWeight += allPossible[y, x]
allPossible = allPossible / np.sum(allPossible) #full grid size with probabilities
self.beliefs = allPossible
# print('Probabilities HELP', allPossible)
choices = np.random.choice(allPossible.size, self.numParticles, p=allPossible.flatten()) #Flattened probs
# print("samples", len(choices), "samples")
## LOOK AT OTHER CODE
newParticles = np.zeros((self.numParticles, 2))
newParticles[:,0] = (choices / self.gridSize[1]).astype(int)
newParticles[:,1] = (choices % self.gridSize[1]).astype(int)
self.particles = newParticles
def observe(self, observations):
"""
let observations be (visual, sound)
TODO: sound
"""
totalWeight = 0
allPossible = np.zeros(self.gridSize)
visualEmission = None
if observations is not None:
y, x, theta = observations
visualEmission = np.array([y, x])
# For now this can start as just one players position
# currPosition = gameState.getFriendlyPos() # TODO: FOR SOUND
for i in range(len(self.particles)):
# distFromParticle = util.euclideanDistance(self.particles[i], currPosition) TODO: Only for sound
weight = 1 if (self.particles[i] == visualEmission).all() else 0
# totalWeight += weight
y, x = self.particles[i].astype(int)
allPossible[y, x] += weight
# newParticles = util.nSample(allPossible, None, self.numParticles)
# newParticles = []
# newParticles = np.zeros(self.numParticles, 2)
if totalWeight == 0:
print("TOTAL WEIGHT ZERO")
self.initParticles(self.numParticles, self.gridSize, visualEmission)
self.beliefs = self.getBeliefDistribution()
return
# for i in range(len(self.numParticles)):
# newParticles += [util.sample(allPossible)]
allPossible = allPossible / np.sum(allPossible) #full grid size with probabilities
self.beliefs = allPossible
choices = np.random.choice(allPossible.size, self.numParticles, p=allPossible.flatten()) #Flattened probs
# print("samples", len(choices), "samples")
newParticles = np.zeros((self.numParticles, 2))
newParticles[:,1] = (choices / self.gridSize[1]).astype(int)
newParticles[:,0] = (choices % self.gridSize[1]).astype(int)
# print('YOLO AAAAAA')
self.particles = newParticles
def timeElapse(self):
''' [ [x,y], [x,y] ]'''
# print('particle length', len(self.particles))
for i in range(len(self.particles)):
y, x = self.particles[i]
posDist, probs = self.transitionFunction.getPosDist((int(y), int(x)))
if len(posDist) == 0:
self.particles[i] = self.particles[i-1]
print("lost a particle somewhere")
else:
index = np.random.choice(len(posDist), p=probs)
self.particles[i] = posDist[index].astype(int)
def getBeliefDistribution(self):
"""
Return the agent's current belief state, a distribution over
ghost locations conditioned on all evidence and time passage. This method
essentially converts a list of particles into a belief distribution (a Counter object)
"""
"*** YOUR CODE HERE ***"
# if self.particles is None:
# self.initParticles(self.numParticles, self.gridSize)
# print("PEEK PARTICLES ON GET BELIEF DIST", self.particles[:5])
# for i in range(len(self.particles)):
# if self.particles[i][0] >= 120 or self.particles[i][1] >= 100:
# print("ILLEGAL PARTICLE IN BELIEF DIST")
distribution = np.zeros(self.gridSize)
for i in range(len(self.particles)):
y, x = self.particles[i].astype(int)
# if y >= 120:
# y = 119
# if x >= 100:
# x = 99
if y >= 120 or x >= 100:
index = np.random.choice(len(self.legalPositions))
self.particles[i] = self.legalPositions[index]
y, x = self.particles[i].astype(int)
# print('ILLEGAL', self.particles[i])
distribution[y][x] += 1
distribution /= distribution.sum()
return distribution
def initParticles(self, numParticles, gridSize, visualEmission=None):
"""
return newly initialized particles
self.legalPositions will be useful
[
[x, y],
[x, y],
[x, y]
]
"""
print("INIT PARTICLE CALL")
if visualEmission is not None:
particles = np.ones((numParticles, 2))
particles[:,1] *= visualEmission[0]
particles[:,0] *= visualEmission[1]
self.particles = particles.astype(int)
return
X, Y = gridSize
print('legal shape', self.legalPositions.shape)
for i in range(len(self.legalPositions)):
if self.legalPositions[i][0] >= 120 or self.legalPositions[i][1] >= 100:
print('Illegal pos at ', self.legalPositions[i], i)
particles = np.zeros((numParticles, 2))
indices = np.random.choice(len(self.legalPositions), numParticles)
self.particles = self.legalPositions[indices].copy().astype(int)
for i in range(len(self.particles)):
if self.particles[i][0] >= 120 or self.particles[i][1] >= 100:
print("ILLEGAL PARTICLE")
print("PEEK PARTICLES ON INIT PARTICLES", self.particles[:5])
<file_sep>/dbn/TransitionFunctions.py
import numpy as np
import pickle
# 0 wall, 1 normal, 2 blue, 3 red, 4 green
class TransitionFunction:
def __init__(self, transition_path):
with open(transition_path, 'rb') as handle:
self.map = pickle.load(handle)
def getPosDist(self, coord, mode='uniform'):
''' coord is (y, x) '''
if mode == 'uniform':
locs = self.map.get(coord)
probs = np.ones(len(locs)) / len(locs)
return locs, probs
|
eba204755b3b08413195749b503a09b57779c0ce
|
[
"Markdown",
"Python"
] | 14 |
Python
|
SimarKareer/iron2Radiant
|
839fdf17af3bfbeb7fd3e4621370cb62ab2d76ea
|
3b90bc7f1f8dabd4df4102c8abad2e0310f8b8cc
|
refs/heads/master
|
<repo_name>karsubhranshu/SQL_SystemTables_Shared<file_sep>/INFORMATION_SCHEMA_All Views.sql
SELECT OBJECT_DEFINITION(OBJECT_ID('<View Name>'))
/*************************************Logic For INFORMATION_SCHEMA.CHECK_CONSTRAINTS********************************/
CREATE VIEW INFORMATION_SCHEMA.CHECK_CONSTRAINTS AS
SELECT DB_NAME() AS CONSTRAINT_CATALOG
,SCHEMA_NAME(schema_id) AS CONSTRAINT_SCHEMA
,name AS CONSTRAINT_NAME
,CONVERT(NVARCHAR(4000), definition) AS CHECK_CLAUSE
FROM sys.check_constraints
/*************************************Logic For INFORMATION_SCHEMA.CHECK_CONSTRAINTS********************************/
/*************************************Logic For INFORMATION_SCHEMA.COLUMN_DOMAIN_USAGE********************************/
CREATE VIEW INFORMATION_SCHEMA.COLUMN_DOMAIN_USAGE AS
SELECT DB_NAME() AS DOMAIN_CATALOG
,SCHEMA_NAME(t.schema_id) AS DOMAIN_SCHEMA
,t.name AS DOMAIN_NAME
,DB_NAME() AS TABLE_CATALOG
,SCHEMA_NAME(o.schema_id) AS TABLE_SCHEMA
,o.name AS TABLE_NAME
,c.name AS COLUMN_NAME
FROM sys.objects o
JOIN sys.columns c ON c.object_id = o.object_id
JOIN sys.types t ON t.user_type_id = c.user_type_id
WHERE c.user_type_id > 256 -- UDT
/*************************************Logic For INFORMATION_SCHEMA.COLUMN_DOMAIN_USAGE********************************/
/*************************************Logic For INFORMATION_SCHEMA.COLUMN_PRIVILEGES********************************/
CREATE VIEW INFORMATION_SCHEMA.COLUMN_PRIVILEGES AS
SELECT USER_NAME(p.grantor_principal_id) AS GRANTOR
,USER_NAME(p.grantee_principal_id) AS GRANTEE
,DB_NAME() AS TABLE_CATALOG
,SCHEMA_NAME(o.schema_id) AS TABLE_SCHEMA
,o.name AS TABLE_NAME
,c.name AS COLUMN_NAME
,convert(varchar(10), CASE p.type WHEN 'SL' THEN 'SELECT' WHEN 'UP' THEN 'UPDATE' WHEN 'RF' THEN 'REFERENCES' END) AS PRIVILEGE_TYPE
,convert(varchar(3), CASE p.state WHEN 'G' THEN 'NO' WHEN 'W' THEN 'YES' END) AS IS_GRANTABLE
FROM sys.database_permissions p
,sys.objects o
,sys.columns c
WHERE o.type IN ('U', 'V')
AND o.object_id = c.object_id
AND p.class = 1
AND p.major_id = o.object_id
AND p.minor_id = c.column_id
AND p.type IN ('RF','SL','UP')
AND p.state IN ('G', 'W')
AND (
p.grantee_principal_id = 0
OR p.grantee_principal_id = DATABASE_PRINCIPAL_ID()
OR p.grantor_principal_id = DATABASE_PRINCIPAL_ID()
)
/*************************************Logic For INFORMATION_SCHEMA.COLUMN_PRIVILEGES********************************/
/*************************************Logic For INFORMATION_SCHEMA.COLUMNS********************************/
CREATE VIEW INFORMATION_SCHEMA.COLUMNS AS
SELECT DB_NAME() AS TABLE_CATALOG
,SCHEMA_NAME(o.schema_id) AS TABLE_SCHEMA
,o.name AS TABLE_NAME
,c.name AS COLUMN_NAME
,ColumnProperty(c.object_id, c.name, 'ordinal') AS ORDINAL_POSITION
,convert(nvarchar(4000)
,object_definition(c.default_object_id)) AS COLUMN_DEFAULT
,convert(varchar(3), CASE c.is_nullable WHEN 1 THEN 'YES' ELSE 'NO' END) AS IS_NULLABLE
,ISNULL(type_name(c.system_type_id), t.name) AS DATA_TYPE
,ColumnProperty(c.object_id, c.name, 'charmaxlen') AS CHARACTER_MAXIMUM_LENGTH
,ColumnProperty(c.object_id, c.name, 'octetmaxlen') AS CHARACTER_OCTET_LENGTH
,convert(tinyint, CASE --int/decimal/numeric/real/float/money
WHEN c.system_type_id IN (48, 52, 56, 59, 60, 62, 106, 108, 122, 127) THEN c.precision END) AS NUMERIC_PRECISION
,convert(smallint, CASE -- int/money/decimal/numeric
WHEN c.system_type_id IN (48, 52, 56, 60, 106, 108, 122, 127) THEN 10
WHEN c.system_type_id IN (59, 62) THEN 2 END) AS NUMERIC_PRECISION_RADIX
,-- real/float
convert(int, CASE -- datetime/smalldatetime
WHEN c.system_type_id IN (40, 41, 42, 43, 58, 61) THEN NULL ELSE odbcscale(c.system_type_id, c.scale) END) AS NUMERIC_SCALE
,convert(smallint, CASE -- datetime/smalldatetime
WHEN c.system_type_id IN (40, 41, 42, 43, 58, 61) THEN odbcscale(c.system_type_id, c.scale) END) AS DATETIME_PRECISION
,convert(sysname, null) AS CHARACTER_SET_CATALOG
,convert(sysname, null) AS CHARACTER_SET_SCHEMA
,convert(sysname, CASE WHEN c.system_type_id IN (35, 167, 175) -- char/varchar/text
THEN CollationProperty(c.collation_name, 'sqlcharsetname')
WHEN c.system_type_id IN (99, 231, 239) -- nchar/nvarchar/ntext
THEN N'UNICODE' END) AS CHARACTER_SET_NAME
,convert(sysname, null) AS COLLATION_CATALOG
,convert(sysname, null) AS COLLATION_SCHEMA
,c.collation_name AS COLLATION_NAME
,convert(sysname, CASE WHEN c.user_type_id > 256 THEN DB_NAME() END) AS DOMAIN_CATALOG
,convert(sysname, CASE WHEN c.user_type_id > 256 THEN SCHEMA_NAME(t.schema_id) END) AS DOMAIN_SCHEMA
, convert(sysname, CASE WHEN c.user_type_id > 256 THEN type_name(c.user_type_id) END) AS DOMAIN_NAME
FROM sys.objects o
JOIN sys.columns c ON c.object_id = o.object_id
LEFT JOIN sys.types t ON c.user_type_id = t.user_type_id
WHERE o.type IN ('U', 'V')
/*************************************Logic For INFORMATION_SCHEMA.COLUMNS********************************/
/*************************************Logic For INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE********************************/
CREATE VIEW INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS
SELECT KCU.TABLE_CATALOG
,KCU.TABLE_SCHEMA
,KCU.TABLE_NAME
,KCU.COLUMN_NAME
,KCU.CONSTRAINT_CATALOG
,KCU.CONSTRAINT_SCHEMA
,KCU.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
UNION ALL
SELECT DB_NAME() AS TABLE_CATALOG
,SCHEMA_NAME(u.schema_id) AS TABLE_SCHEMA
,u.name AS TABLE_NAME
,col_name(d.referenced_major_id, d.referenced_minor_id) AS COLUMN_NAME
,DB_NAME() AS CONSTRAINT_CATALOG
,SCHEMA_NAME(k.schema_id) AS CONSTRAINT_SCHEMA
,k.name AS CONSTRAINT_NAME
FROM sys.check_constraints k
JOIN sys.objects u ON u.object_id = k.parent_object_id
JOIN sys.sql_dependencies d ON d.class = 1
AND d.object_id = k.object_id
AND d.column_id = 0
AND d.referenced_major_id = u.object_id
WHERE u.type <> 'TF' -- skip constraints in TVFs.
UNION ALL
SELECT DB_NAME() AS TABLE_CATALOG
,SCHEMA_NAME(t.schema_id) AS TABLE_SCHEMA
,t.name AS TABLE_NAME
,col_name(f.object_id, f.column_id) AS COLUMN_NAME
,DB_NAME() AS CONSTRAINT_CATALOG
,SCHEMA_NAME(r.schema_id) AS CONSTRAINT_SCHEMA
,r.name AS CONSTRAINT_NAME
FROM sys.objects t
JOIN sys.columns f ON f.object_id = t.object_id
JOIN sys.objects r ON r.object_id = f.rule_object_id
/*************************************Logic For INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE********************************/
/*************************************Logic For INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE********************************/
CREATE VIEW INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE AS
SELECT DB_NAME() AS TABLE_CATALOG
,SCHEMA_NAME(t.schema_id) AS TABLE_SCHEMA
,t.name AS TABLE_NAME
,DB_NAME() AS CONSTRAINT_CATALOG
,SCHEMA_NAME(c.schema_id) AS CONSTRAINT_SCHEMA
,c.name AS CONSTRAINT_NAME
FROM sys.objects c
JOIN sys.tables t ON t.object_id = c.parent_object_id
WHERE c.type IN ('C' ,'UQ' ,'PK' ,'F')
/*************************************Logic For INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE********************************/
/*************************************Logic For INFORMATION_SCHEMA.DOMAIN_CONSTRAINTS********************************/
CREATE VIEW INFORMATION_SCHEMA.DOMAIN_CONSTRAINTS AS
SELECT DB_NAME() AS CONSTRAINT_CATALOG
,SCHEMA_NAME(o.schema_id) AS CONSTRAINT_SCHEMA
,o.name AS CONSTRAINT_NAME
,DB_NAME() AS DOMAIN_CATALOG
,SCHEMA_NAME(t.schema_id) AS DOMAIN_SCHEMA
,t.name AS DOMAIN_NAME
,'NO' AS IS_DEFERRABLE
,'NO' AS INITIALLY_DEFERRED
FROM sys.types t
JOIN sys.objects o ON o.object_id = t.rule_object_id
WHERE t.user_type_id > 256
/*************************************Logic For INFORMATION_SCHEMA.DOMAIN_CONSTRAINTS********************************/
/*************************************Logic For INFORMATION_SCHEMA.DOMAINS********************************/
CREATE VIEW INFORMATION_SCHEMA.DOMAINS AS
SELECT DB_NAME() AS DOMAIN_CATALOG
,SCHEMA_NAME(schema_id) AS DOMAIN_SCHEMA
,name AS DOMAIN_NAME
,type_name(system_type_id) AS DATA_TYPE
,convert(int, TypePropertyEx(user_type_id, 'charmaxlen')) AS CHARACTER_MAXIMUM_LENGTH
,convert(int, TypePropertyEx(user_type_id, 'octetmaxlen')) AS CHARACTER_OCTET_LENGTH
,convert(sysname, null) AS COLLATION_CATALOG
,convert(sysname, null) AS COLLATION_SCHEMA
,collation_name AS COLLATION_NAME
,convert(sysname, null) AS CHARACTER_SET_CATALOG
,convert(sysname, null) AS CHARACTER_SET_SCHEMA
,convert(sysname, CASE WHEN system_type_id IN (35, 167, 175) THEN ServerProperty('sqlcharsetname') -- char/varchar/text
WHEN system_type_id IN (99, 231, 239) THEN N'UNICODE' END) AS CHARACTER_SET_NAME
,-- nchar/nvarchar/ntext
convert(tinyint, CASE -- int/decimal/numeric/real/float/money
WHEN system_type_id IN (48, 52, 56, 59, 60, 62, 106, 108, 122, 127) THEN precision END) AS NUMERIC_PRECISION
,convert(smallint, CASE -- int/money/decimal/numeric
WHEN system_type_id IN (48, 52, 56, 60, 106, 108, 122, 127) THEN 10
WHEN system_type_id IN (59, 62) THEN 2 END) AS NUMERIC_PRECISION_RADIX
,convert(int, CASE -- datetime/smalldatetime
WHEN system_type_id IN (40, 41, 42, 43, 58, 61) THEN NULL
ELSE odbcscale(system_type_id, scale) END) AS NUMERIC_SCALE
,convert(smallint, CASE -- datetime/smalldatetime
WHEN system_type_id IN (40, 41, 42, 43, 58, 61) THEN odbcscale(system_type_id, scale) END) AS DATETIME_PRECISION
,convert(nvarchar(4000), object_definition(default_object_id)) AS DOMAIN_DEFAULT
FROM sys.types
WHERE user_type_id > 256 -- UDT
/*************************************Logic For INFORMATION_SCHEMA.DOMAINS********************************/
/*************************************Logic For INFORMATION_SCHEMA.KEY_COLUMN_USAGE********************************/
CREATE VIEW information_schema.key_column_usage AS
SELECT Db_name() AS CONSTRAINT_CATALOG
,Schema_name(f.schema_id) AS CONSTRAINT_SCHEMA
,f.NAME AS CONSTRAINT_NAME
,Db_name() AS TABLE_CATALOG
,Schema_name(p.schema_id) AS TABLE_SCHEMA
,p.NAME AS TABLE_NAME
,Col_name(k.parent_object_id, k.parent_column_id) AS COLUMN_NAME
,k.constraint_column_id AS ORDINAL_POSITION
FROM sys.foreign_keys f
JOIN sys.foreign_key_columns k ON k.constraint_object_id = f.object_id
JOIN sys.tables p ON p.object_id = f.parent_object_id
UNION
SELECT Db_name() AS CONSTRAINT_CATALOG
,Schema_name(k.schema_id) AS CONSTRAINT_SCHEMA
,k.NAME AS CONSTRAINT_NAME
,Db_name() AS TABLE_CATALOG
,Schema_name(t.schema_id) AS TABLE_SCHEMA
,t.NAME AS TABLE_NAME
,Col_name(c.object_id, c.column_id) AS COLUMN_NAME
,c.key_ordinal AS ORDINAL_POSITION
FROM sys.key_constraints k
JOIN sys.index_columns c ON c.object_id = k.parent_object_id
AND c.index_id = k.unique_index_id
JOIN sys.tables t ON t.object_id = k.parent_object_id
/*************************************Logic For INFORMATION_SCHEMA.KEY_COLUMN_USAGE********************************/
/*************************************Logic For INFORMATION_SCHEMA.PARAMETERS********************************/
CREATE VIEW INFORMATION_SCHEMA.PARAMETERS AS
SELECT DB_NAME() AS SPECIFIC_CATALOG
,SCHEMA_NAME(o.schema_id) AS SPECIFIC_SCHEMA
,o.name AS SPECIFIC_NAME
,c.parameter_id AS ORDINAL_POSITION
,convert(nvarchar(10), CASE WHEN c.parameter_id = 0 THEN 'OUT' WHEN c.is_output = 1 THEN 'INOUT' ELSE 'IN' END) AS PARAMETER_MODE
,convert(nvarchar(10), CASE WHEN c.parameter_id = 0 THEN 'YES' ELSE 'NO' END) AS IS_RESULT
,convert(nvarchar(10), 'NO') AS AS_LOCATOR
,c.name AS PARAMETER_NAME
,ISNULL(type_name(c.system_type_id), u.name) AS DATA_TYPE
,ColumnProperty(c.object_id, c.name, 'charmaxlen') AS CHARACTER_MAXIMUM_LENGTH
,ColumnProperty(c.object_id, c.name, 'octetmaxlen') AS CHARACTER_OCTET_LENGTH
,convert(sysname, null) AS COLLATION_CATALOG
,convert(sysname, null) AS COLLATION_SCHEMA
,convert(sysname, CASE WHEN c.system_type_id IN (35, 99, 167, 175, 231, 239) -- [n]char/[n]varchar/[n]text
THEN ServerProperty('collation') END) AS COLLATION_NAME
,convert(sysname, null) AS CHARACTER_SET_CATALOG
,convert(sysname, null) AS CHARACTER_SET_SCHEMA
,convert(sysname, CASE WHEN c.system_type_id IN (35, 167, 175) THEN ServerProperty('sqlcharsetname') -- char/varchar/text
WHEN c.system_type_id IN (99, 231, 239) THEN N'UNICODE' END) AS CHARACTER_SET_NAME -- nchar/nvarchar/ntext
,convert(tinyint, CASE WHEN c.system_type_id IN (48, 52, 56, 59, 60, 62, 106, 108, 122, 127) -- int/decimal/numeric/real/float/money
THEN c.precision END) AS NUMERIC_PRECISION
,convert(smallint, CASE WHEN c.system_type_id IN (48, 52, 56, 60, 106, 108, 122, 127) THEN 10 -- int/money/decimal/numeric
WHEN c.system_type_id IN (59, 62) THEN 2 END) AS NUMERIC_PRECISION_RADIX -- real/float
,convert(int, CASE WHEN c.system_type_id IN (40, 41, 42, 43, 58, 61) THEN NULL -- datetime/smalldatetime
ELSE odbcscale(c.system_type_id, c.scale) END) AS NUMERIC_SCALE
,convert(smallint, CASE WHEN c.system_type_id IN (40, 41, 42, 43, 58, 61) -- datetime/smalldatetime
THEN odbcscale(c.system_type_id, c.scale) END) AS DATETIME_PRECISION
,convert(nvarchar(30), null) AS INTERVAL_TYPE
,convert(smallint, null) AS INTERVAL_PRECISION
,convert(sysname, CASE WHEN u.schema_id <> 4 THEN DB_NAME() END) AS USER_DEFINED_TYPE_CATALOG
,convert(sysname, CASE WHEN u.schema_id <> 4 THEN SCHEMA_NAME(u.schema_id) END) AS USER_DEFINED_TYPE_SCHEMA
,convert(sysname, CASE WHEN u.schema_id <> 4 THEN u.name END) AS USER_DEFINED_TYPE_NAME
,convert(sysname, null) AS SCOPE_CATALOG
,convert(sysname, null) AS SCOPE_SCHEMA
,convert(sysname, null) AS SCOPE_NAME
FROM sys.objects o
JOIN sys.parameters c ON c.object_id = o.object_id
JOIN sys.types u ON u.user_type_id = c.user_type_id
WHERE o.type IN ('P','FN','TF', 'IF', 'IS', 'AF','PC', 'FS', 'FT')
/*************************************Logic For INFORMATION_SCHEMA.PARAMETERS********************************/
/*************************************Logic For INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS********************************/
CREATE VIEW INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS
SELECT DB_NAME() AS CONSTRAINT_CATALOG
,SCHEMA_NAME(f.schema_id) AS CONSTRAINT_SCHEMA
,f.name AS CONSTRAINT_NAME
,DB_NAME() AS UNIQUE_CONSTRAINT_CATALOG
,SCHEMA_NAME(t.schema_id) AS UNIQUE_CONSTRAINT_SCHEMA
,i.name AS UNIQUE_CONSTRAINT_NAME
,convert(varchar(7), 'SIMPLE') AS MATCH_OPTION
,convert(varchar(11), CASE f.update_referential_action
WHEN 0 THEN 'NO ACTION'
WHEN 1 THEN 'CASCADE'
WHEN 2 THEN 'SET NULL'
WHEN 3 THEN 'SET DEFAULT' END) AS UPDATE_RULE
,convert(varchar(11), CASE f.delete_referential_action
WHEN 0 THEN 'NO ACTION'
WHEN 1 THEN 'CASCADE'
WHEN 2 THEN 'SET NULL'
WHEN 3 THEN 'SET DEFAULT' END) AS DELETE_RULE
FROM sys.foreign_keys f
LEFT JOIN sys.indexes i ON i.object_id = f.referenced_object_id
AND i.index_id = f.key_index_id
LEFT JOIN sys.tables t ON t.object_id = f.referenced_object_id
/*************************************Logic For INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS********************************/
/*************************************Logic For INFORMATION_SCHEMA.ROUTINE_COLUMNS********************************/
CREATE VIEW INFORMATION_SCHEMA.ROUTINE_COLUMNS AS
SELECT DB_NAME() AS TABLE_CATALOG
,SCHEMA_NAME(o.schema_id) AS TABLE_SCHEMA
,o.name AS TABLE_NAME
,c.name AS COLUMN_NAME
,c.column_id AS ORDINAL_POSITION
,convert(nvarchar(4000), object_definition(c.default_object_id)) AS COLUMN_DEFAULT
,convert(varchar(3), CASE WHEN c.is_nullable = 1 THEN 'YES' ELSE 'NO' END) AS IS_NULLABLE
,ISNULL(type_name(c.system_type_id), t.name) AS DATA_TYPE
,ColumnProperty(c.object_id, c.name, 'charmaxlen') AS CHARACTER_MAXIMUM_LENGTH
,ColumnProperty(c.object_id, c.name, 'octetmaxlen') AS CHARACTER_OCTET_LENGTH
,convert(tinyint, CASE WHEN c.system_type_id IN (48, 52, 56, 59, 60, 62, 106, 108, 122, 127)-- int/decimal/numeric/real/float/money
THEN c.precision END) AS NUMERIC_PRECISION
,convert(smallint, CASE WHEN c.system_type_id IN (48, 52, 56, 60, 106, 108, 122, 127) THEN 10 -- int/money/decimal/numeric
WHEN c.system_type_id IN (59, 62) THEN 2 END) AS NUMERIC_PRECISION_RADIX-- real/float
,convert(int, CASE WHEN c.system_type_id IN (40, 41, 42, 43, 58, 61) THEN NULL -- datetime/smalldatetime
ELSE odbcscale(c.system_type_id, c.scale) END) AS NUMERIC_SCALE
,convert(smallint, CASE WHEN c.system_type_id IN (40, 41, 42, 43, 58, 61) -- datetime/smalldatetime
THEN odbcscale(c.system_type_id, c.scale) END) AS DATETIME_PRECISION
,convert( sysname, null) AS CHARACTER_SET_CATALOG
,convert( sysname, null) AS CHARACTER_SET_SCHEMA
,convert( sysname, CASE WHEN c.system_type_id IN (35, 167, 175) -- char/varchar/text
THEN CollationProperty(c.collation_name, 'sqlcharsetname')
WHEN c.system_type_id IN (99, 231, 239) -- nchar/nvarchar/ntext
THEN N'UNICODE' END) AS CHARACTER_SET_NAME
,convert(sysname, null) AS COLLATION_CATALOG
,convert(sysname, null) AS COLLATION_SCHEMA
,c.collation_name AS COLLATION_NAME
,convert(sysname, CASE WHEN c.user_type_id > 256 THEN DB_NAME() END) AS DOMAIN_CATALOG
,convert(sysname, CASE WHEN c.user_type_id > 256 THEN SCHEMA_NAME(t.schema_id) END) AS DOMAIN_SCHEMA
,convert(sysname, CASE WHEN c.user_type_id > 256 THEN type_name(c.user_type_id) END) AS DOMAIN_NAME
FROM sys.objects o
JOIN sys.columns c ON c.object_id = o.object_id
LEFT JOIN sys.types t ON c.user_type_id = t.user_type_id
WHERE o.type IN ('TF','IF', 'FT')
/*************************************Logic For INFORMATION_SCHEMA.ROUTINE_COLUMNS********************************/
/*************************************Logic For INFORMATION_SCHEMA.ROUTINES********************************/
CREATE VIEW INFORMATION_SCHEMA.ROUTINES AS
SELECT DB_NAME() AS SPECIFIC_CATALOG
,SCHEMA_NAME(o.schema_id) AS SPECIFIC_SCHEMA
,o.name AS SPECIFIC_NAME
,DB_NAME() AS ROUTINE_CATALOG
,SCHEMA_NAME(o.schema_id) AS ROUTINE_SCHEMA
,o.name AS ROUTINE_NAME
,convert(nvarchar(20), CASE WHEN o.type IN ('P','PC') THEN 'PROCEDURE' ELSE 'FUNCTION' END) AS ROUTINE_TYPE
,convert(sysname, null) AS MODULE_CATALOG
,convert(sysname, null) AS MODULE_SCHEMA
,convert(sysname, null) AS MODULE_NAME
,convert(sysname, null) AS UDT_CATALOG
,convert(sysname, null) AS UDT_SCHEMA
,convert(sysname, null) AS UDT_NAME
,convert(sysname, CASE WHEN o.type IN ('TF', 'IF', 'FT') THEN N'TABLE'
ELSE ISNULL(type_name(c.system_type_id), type_name(c.user_type_id)) END) AS DATA_TYPE
,ColumnProperty(c.object_id, c.name, 'charmaxlen') AS CHARACTER_MAXIMUM_LENGTH
,ColumnProperty(c.object_id, c.name, 'octetmaxlen') AS CHARACTER_OCTET_LENGTH
,convert(sysname, null) AS COLLATION_CATALOG
,convert(sysname, null) AS COLLATION_SCHEMA
,convert(sysname, CASE WHEN c.system_type_id IN (35, 99, 167, 175, 231, 239) -- [n]char/[n]varchar/[n]text
THEN CollationPropertyFromId(-1, 'name') END) AS COLLATION_NAME
,convert(sysname, null) AS CHARACTER_SET_CATALOG
,convert(sysname, null) AS CHARACTER_SET_SCHEMA
,convert(sysname, CASE WHEN c.system_type_id IN (35, 167, 175) THEN ServerProperty('sqlcharsetname') -- char/varchar/text
WHEN c.system_type_id IN (99, 231, 239) THEN N'UNICODE' END) AS CHARACTER_SET_NAME -- nchar/nvarchar/ntext
,convert(tinyint, CASE WHEN c.system_type_id IN (48, 52, 56, 59, 60, 62, 106, 108, 122, 127) THEN c.precision END) AS NUMERIC_PRECISION-- int/decimal/numeric/real/float/money
,convert(smallint, CASE WHEN c.system_type_id IN (48, 52, 56, 60, 106, 108, 122, 127) THEN 10-- int/money/decimal/numeric
WHEN c.system_type_id IN (59, 62) THEN 2 END) AS NUMERIC_PRECISION_RADIX -- real/float
,convert(int, CASE WHEN c.system_type_id IN (40, 41, 42, 43, 58, 61) THEN NULL -- datetime/smalldatetime
ELSE odbcscale(c.system_type_id, c.scale) END) AS NUMERIC_SCALE
,convert(smallint, CASE WHEN c.system_type_id IN (40, 41, 42, 43, 58, 61) -- datetime/smalldatetime
THEN odbcscale(c.system_type_id, c.scale) END) AS DATETIME_PRECISION
,convert(nvarchar(30), null) AS INTERVAL_TYPE
,convert(smallint, null) AS INTERVAL_PRECISION
,convert(sysname, null) AS TYPE_UDT_CATALOG
,convert(sysname, null) AS TYPE_UDT_SCHEMA
,convert(sysname, null) AS TYPE_UDT_NAME
,convert(sysname, null) AS SCOPE_CATALOG
,convert(sysname, null) AS SCOPE_SCHEMA
,convert(sysname, null) AS SCOPE_NAME
,convert(bigint, null) AS MAXIMUM_CARDINALITY
,convert(sysname, null) AS DTD_IDENTIFIER
,convert(nvarchar(30), CASE WHEN o.type IN ('P ', 'FN', 'TF', 'IF') THEN 'SQL' ELSE 'EXTERNAL' END) AS ROUTINE_BODY
,convert(nvarchar(4000), object_definition(o.object_id)) AS ROUTINE_DEFINITION
,convert(sysname, null) AS EXTERNAL_NAME
,convert(nvarchar(30), null) AS EXTERNAL_LANGUAGE
,convert(nvarchar(30), null) AS PARAMETER_STYLE
,convert(nvarchar(10), CASE WHEN ObjectProperty(o.object_id, 'IsDeterministic') = 1 THEN 'YES' ELSE 'NO' END) AS IS_DETERMINISTIC
,convert(nvarchar(30), CASE WHEN o.type IN ('P', 'PC') THEN 'MODIFIES' ELSE 'READS' END) AS SQL_DATA_ACCESS
,convert(nvarchar(10), CASE WHEN o.type in ('P', 'PC') THEN null WHEN o.null_on_null_input = 1 THEN 'YES' ELSE 'NO' END) AS IS_NULL_CALL
,convert(sysname, null) AS SQL_PATH
,convert(nvarchar(10), 'YES') AS SCHEMA_LEVEL_ROUTINE
,convert(smallint, CASE WHEN o.type IN ('P ', 'PC') THEN -1 ELSE 0 END) AS MAX_DYNAMIC_RESULT_SETS
,convert(nvarchar(10), 'NO') AS IS_USER_DEFINED_CAST
,convert(nvarchar(10), 'NO') AS IS_IMPLICITLY_INVOCABLE
,o.create_date AS CREATED
,o.modify_date AS LAST_ALTERED
FROM sys.objects o
LEFT JOIN sys.parameters c ON (c.object_id = o.object_id AND c.parameter_id = 0)
WHERE o.type IN ('P', 'FN', 'TF', 'IF', 'AF', 'FT', 'IS', 'PC', 'FS')
/*************************************Logic For INFORMATION_SCHEMA.ROUTINES********************************/
/*************************************Logic For INFORMATION_SCHEMA.SCHEMATA********************************/
CREATE VIEW information_schema.schemata AS
SELECT Db_name() AS CATALOG_NAME
,NAME AS SCHEMA_NAME
,User_name(principal_id) AS SCHEMA_OWNER
,CONVERT(SYSNAME, NULL) AS DEFAULT_CHARACTER_SET_CATALOG
,CONVERT(SYSNAME, NULL) AS DEFAULT_CHARACTER_SET_SCHEMA
,CONVERT(SYSNAME, Collationpropertyfromid(-1, 'sqlcharsetname')) AS DEFAULT_CHARACTER_SET_NAME
FROM sys.schemas
/*************************************Logic For INFORMATION_SCHEMA.SCHEMATA********************************/
/*************************************Logic For INFORMATION_SCHEMA.TABLE_CONSTRAINTS********************************/
CREATE VIEW INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS
SELECT DB_NAME() AS CONSTRAINT_CATALOG
,SCHEMA_NAME(c.schema_id) AS CONSTRAINT_SCHEMA
,c.name AS CONSTRAINT_NAME
,DB_NAME() AS TABLE_CATALOG
,SCHEMA_NAME(t.schema_id) AS TABLE_SCHEMA
,t.name AS TABLE_NAME
,CASE c.type WHEN 'C ' THEN 'CHECK'
WHEN 'UQ' THEN 'UNIQUE'
WHEN 'PK' THEN 'PRIMARY KEY'
WHEN 'F ' THEN 'FOREIGN KEY' END AS CONSTRAINT_TYPE
,'NO' AS IS_DEFERRABLE
,'NO' AS INITIALLY_DEFERRED
FROM sys.objects c
LEFT JOIN sys.tables t ON t.object_id = c.parent_object_id
WHERE c.type IN ('C' ,'UQ' ,'PK' ,'F')
/*************************************Logic For INFORMATION_SCHEMA.TABLE_CONSTRAINTS********************************/
/*************************************Logic For INFORMATION_SCHEMA.TABLE_PRIVILEGES********************************/
CREATE VIEW INFORMATION_SCHEMA.TABLE_PRIVILEGES AS
SELECT USER_NAME(p.grantor_principal_id) AS GRANTOR
,USER_NAME(p.grantee_principal_id) AS GRANTEE
,DB_NAME() AS TABLE_CATALOG
,SCHEMA_NAME(o.schema_id) AS TABLE_SCHEMA
,o.name AS TABLE_NAME
,convert(varchar(10), CASE p.type WHEN 'RF' THEN 'REFERENCES'
WHEN 'SL' THEN 'SELECT'
WHEN 'IN' THEN 'INSERT'
WHEN 'DL' THEN 'DELETE'
WHEN 'UP' THEN 'UPDATE' END) AS PRIVILEGE_TYPE
,convert(varchar(3), CASE p.state WHEN 'G' THEN 'NO' WHEN 'W' THEN 'YES' END) AS IS_GRANTABLE
FROM sys.objects o
,sys.database_permissions p
WHERE o.type IN ('U', 'V')
AND p.class = 1
AND p.major_id = o.object_id
AND p.minor_id = 0 -- all columns
AND p.type IN ('RF','IN','SL','UP','DL')
AND p.state IN ('W','G')
AND (
p.grantee_principal_id = 0
OR p.grantee_principal_id = DATABASE_PRINCIPAL_ID()
OR p.grantor_principal_id = DATABASE_PRINCIPAL_ID()
)
/*************************************Logic For INFORMATION_SCHEMA.TABLE_PRIVILEGES********************************/
/*************************************Logic For INFORMATION_SCHEMA.TABLES********************************/
CREATE VIEW INFORMATION_SCHEMA.TABLES AS
SELECT DB_NAME() AS TABLE_CATALOG
,s.name AS TABLE_SCHEMA
,o.name AS TABLE_NAME
,CASE o.type WHEN 'U' THEN 'BASE TABLE' WHEN 'V' THEN 'VIEW' END AS TABLE_TYPE
FROM sys.objects o
LEFT JOIN sys.schemas s ON s.schema_id = o.schema_id
WHERE o.type IN ('U', 'V')
/*************************************Logic For INFORMATION_SCHEMA.TABLES********************************/
/*************************************Logic For INFORMATION_SCHEMA.VIEW_COLUMN_USAGE********************************/
CREATE VIEW INFORMATION_SCHEMA.VIEW_COLUMN_USAGE AS
SELECT DB_NAME() AS VIEW_CATALOG
,SCHEMA_NAME(v.schema_id) AS VIEW_SCHEMA
,v.name AS VIEW_NAME
,DB_NAME() AS TABLE_CATALOG
,SCHEMA_NAME(t.schema_id) AS TABLE_SCHEMA
,t.name AS TABLE_NAME
,c.name AS COLUMN_NAME
FROM sys.views v
JOIN sys.sql_dependencies d ON d.object_id = v.object_id
JOIN sys.objects t ON t.object_id = d.referenced_major_id
JOIN sys.columns c ON c.object_id = d.referenced_major_id
AND c.column_id = d.referenced_minor_id
WHERE d.class < 2
/*************************************Logic For INFORMATION_SCHEMA.VIEW_COLUMN_USAGE********************************/
/*************************************Logic For INFORMATION_SCHEMA.VIEW_TABLE_USAGE********************************/
CREATE VIEW INFORMATION_SCHEMA.VIEW_TABLE_USAGE AS
SELECT DISTINCT DB_NAME() AS VIEW_CATALOG
,SCHEMA_NAME(v.schema_id) AS VIEW_SCHEMA
,v.name AS VIEW_NAME
,DB_NAME() AS TABLE_CATALOG
,SCHEMA_NAME(t.schema_id) AS TABLE_SCHEMA
,t.name AS TABLE_NAME
FROM sys.objects t
,sys.views v
,sys.sql_dependencies d
WHERE d.class < 2
AND d.object_id = v.object_id
AND d.referenced_major_id = t.object_id
/*************************************Logic For INFORMATION_SCHEMA.VIEW_TABLE_USAGE********************************/
/*************************************Logic For INFORMATION_SCHEMA.VIEWS********************************/
CREATE VIEW INFORMATION_SCHEMA.VIEWS AS
SELECT DB_NAME() AS TABLE_CATALOG
,SCHEMA_NAME(schema_id) AS TABLE_SCHEMA
,name AS TABLE_NAME
,convert(nvarchar(4000), object_definition(object_id)) AS VIEW_DEFINITION
,convert(varchar(7), CASE with_check_option WHEN 1 THEN 'CASCADE' ELSE 'NONE' END) AS CHECK_OPTION
,'NO' AS IS_UPDATABLE
FROM sys.views
/*************************************Logic For INFORMATION_SCHEMA.VIEWS********************************/<file_sep>/README.md
# SQL_SystemTables_Shared
sys.objects.docx -> The Description About sys.objects View in SQL Server
sys.all_objects.docx -> The Description About sys.all_objects View in SQL Server
sys.all_columns.docx -> The Description About sys.all_columns View in SQL Server
sys.all_parameters.docx -> The Description About sys.all_parameters View in SQL Server
sys.all_sql_modules.docx -> The Description About sys.all_sql_modules View in SQL Server
sys.all_views.docx -> The Description About sys.all_views View in SQL Server
sys.allocation_units.docx -> The Description About sys.allocation_units View in SQL Server
sys.assembly_modules.docx -> The Description About sys.assembly_modules View in SQL Server
sys.check_constraints.docx -> The Description About sys.check_constraints View in SQL Server
INFORMATION_SCHEMA_All Views.SQL -> All the views of INFORMATION_SCHEMA
|
bccce806543b0f03aaaaadab142d0b5ea0f381df
|
[
"Markdown",
"SQL"
] | 2 |
SQL
|
karsubhranshu/SQL_SystemTables_Shared
|
64b741e3daef01a93463967f6b23af585141ca98
|
1d77c8428299b669dbf84963f86557fe8e2b2dad
|
refs/heads/master
|
<repo_name>johannott/portfolio-angular<file_sep>/README.md
# portfolio-angular
This is a project to create a portfolio website using HTML5, CSS3 and AngularJS
<file_sep>/pages/home.htm
<div class="row vertical-center">
<div class="col-md-2">
</div>
<div class="home-column col-md-12 col-sm-12 col-xs-12">
<img src="../images/jo.jpg" alt="Johanns Pic" class="profile-pic"/>
<h1>Welcome!</h1>
<h3>My name is <NAME>. I live in Kildare, Ireland and work @ IBM.</h3>
<p>
I am a full stack developer with a passion for building large scale dynamic web applications with state of the art web technologies.
I am always looking to keep abreast with changes in technologies and development processes.
</p>
<p>
I joined IBM 8 years ago after completing a B.Eng in Mechical Engineering and M.Sc in Software Development and Design at NUI, Galway.
In my first year at IBM I worked as a Test Automation Enginner before moving into Front-End Development. More recently I have worked on all aspects of projects from front to back.
</p>
<p>
In my spare time I like to play golf, follow national hunt racing and liverpool fc, mess around with the internet of things, build scale model aircraft and listen to electronic music.
</p>
<jo-footer></jo-footer>
</div>
<div class="col-md-2 col-sm-0 col-xs-0">
</div>
</div>
<file_sep>/app.js
// MODULE
var portfolioApp = angular.module('portfolioApp', ['ngRoute', 'ngResource', 'ngAnimate']);
// ROUTES
portfolioApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/home.htm',
controller: 'homeController'
})
.when('/skills', {
templateUrl: 'pages/skills.htm',
controller: 'skillsController'
})
.when('/projects', {
templateUrl: 'pages/projects.htm',
controller: 'projectsController'
})
.when('/interests', {
templateUrl: 'pages/interests.htm',
controller: 'interestsController'
})
.when('/contact', {
templateUrl: 'pages/contact.htm',
controller: 'contactController'
})
});
// CONTROLLERS
portfolioApp.controller('homeController', ['$scope', function($scope) {
$scope.pageClass = 'page-home';
}]);
portfolioApp.controller('skillsController', ['$scope', function($scope) {
$scope.pageClass = 'page-skills';
$scope.toggleClass1 = false;
$scope.toggleClass2 = false;
$scope.toggleClass3 = false;
$scope.toggleClass4 = false;
$scope.toggleClasses = function(num){
if (num === 1){
if (!$scope.toggleClass1) {
$scope.toggleClass1 = true;
$scope.toggleClass2 = false;
$scope.toggleClass3 = false;
$scope.toggleClass4 = false;
} else {
$scope.toggleClass1 = false;
$scope.toggleClass2 = false;
$scope.toggleClass3 = false;
$scope.toggleClass4 = false;
}
} else if (num === 2){
if (!$scope.toggleClass2) {
$scope.toggleClass1 = false;
$scope.toggleClass2 = true;
$scope.toggleClass3 = false;
$scope.toggleClass4 = false;
} else {
$scope.toggleClass1 = false;
$scope.toggleClass2 = false;
$scope.toggleClass3 = false;
$scope.toggleClass4 = false;
}
} else if (num === 3){
if (!$scope.toggleClass3) {
$scope.toggleClass1 = false;
$scope.toggleClass2 = false;
$scope.toggleClass3 = true;
$scope.toggleClass4 = false;
} else {
$scope.toggleClass1 = false;
$scope.toggleClass2 = false;
$scope.toggleClass3 = false;
$scope.toggleClass4 = false;
}
} else if (num === 4){
if (!$scope.toggleClass4) {
$scope.toggleClass1 = false;
$scope.toggleClass2 = false;
$scope.toggleClass3 = false;
$scope.toggleClass4 = true;
} else {
$scope.toggleClass1 = false;
$scope.toggleClass2 = false;
$scope.toggleClass3 = false;
$scope.toggleClass4 = false;
}
}
}
}]);
portfolioApp.controller('projectsController', ['$scope', function($scope) {
$scope.pageClass = 'page-projects';
$scope.selection = 'connections';
}]);
portfolioApp.controller('interestsController', ['$scope', function($scope) {
$scope.pageClass = 'page-interests';
}]);
portfolioApp.controller('contactController', ['$scope', function($scope) {
$scope.pageClass = 'page-contact';
}]);
//DIRECTIVES
portfolioApp.directive('joFooter', function() {
return {
restrict: 'E',
templateUrl: 'directives/footer.html'
};
});
|
af8d40f30c5f462d5ee7fd163755a89d4480f0d8
|
[
"Markdown",
"JavaScript",
"HTML"
] | 3 |
Markdown
|
johannott/portfolio-angular
|
5ca22ec2e11d16cf7fd19225af1955ee959c3381
|
bee06807f280b246e8931059779f3af0cb15ecb8
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web;
using Microsoft.Graph;
namespace AzureAddUserToGroup.Helpers
{
public class GraphHelper
{
// Get an authenticated Microsoft Graph Service client.
public static GraphServiceClient GetAuthenticatedClient()
{
GraphServiceClient graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
string accessToken = await AuthProvider.GetUserAccessTokenAsync();
// Append the access token to the request.
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
// Get event times in the current time zone.
requestMessage.Headers.Add("Prefer", "outlook.timezone=\"" + TimeZoneInfo.Local.Id + "\"");
}));
return graphClient;
}
}
}<file_sep>using AzureAddUserToGroup.Helpers;
using AzureAddUserToGroup.Services;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace AzureAddUserToGroup.Helper
{
internal class GetUsersAndAddToGroupHelper
{
static string authority = String.Format(CultureInfo.InvariantCulture, HiddenConstants.AddInstance, HiddenConstants.Tenant);
private static UsersService userService = new UsersService();
private static GroupsService groupsService = new GroupsService();
internal static async Task<bool> GetUsersAndAddToGroup(ILogger log)
{
GraphServiceClient graphClient = GraphHelper.GetAuthenticatedClient();
var usersOfficeManagerSE = await userService.GetAllOfficeManagers(graphClient, "Kontorschef", "SE");
var usersOfficeManagerES = await userService.GetAllOfficeManagers(graphClient, "Kontorschef", "ES");
var usersFranchiseesSE = await userService.GetAllOfficeManagers(graphClient, "Franchisetagare", "SE");
var usersFranchiseesES = await userService.GetAllOfficeManagers(graphClient, "Franchisetagare", "ES");
if (usersOfficeManagerSE.Count != 0)
{
await groupsService.PutUsersInGroup(graphClient, usersOfficeManagerSE, "SP_Kontorschef", log);
}
if (usersOfficeManagerES.Count != 0)
{
//Byt till utlands AD grupp
//await groupsService.PutUsersInGroup(graphClient, usersOfficeManagerSE, "SP_Kontorschef", log);
}
if (usersFranchiseesSE.Count != 0)
{
await groupsService.PutUsersInGroup(graphClient, usersOfficeManagerSE, "SP_Francheistagare", log);
}
if (usersFranchiseesES.Count != 0)
{
//Byt till utlands AD grupp
//await groupsService.PutUsersInGroup(graphClient, usersOfficeManagerSE, "SP_Kontorschef", log);
}
//var group = await groupsService.PutUsersInGroup(graphClient, usersOfficeManagerSE, "SP_Kontorschef", log);
//var spainUsers = await userService.GetAllCountryUsers(graphClient, "Spanien");
//var spainUsers = await userService.GetAllCountryUsers(graphClient, "Portugal");
return true;
}
}
}
<file_sep>using System.Collections.Generic;
namespace AzureAddUserToGroup.Services
{
public class ResultsItem
{
public string Display { get; internal set; }
public string Id { get; internal set; }
public Dictionary<string, object> Properties { get; internal set; }
}
}<file_sep>using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using AzureAddUserToGroup.Helper;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
namespace AzureAddUserToGroup
{
public static class AddUserToGroup
{
[FunctionName("AddUserToGroup")]
public static async void Run([TimerTrigger("0 0 0 * * *", RunOnStartup = true)]TimerInfo myTimer, ILogger log)
{
log.LogInformation("", null);
_ = await GetUsersAndAddToGroupHelper.GetUsersAndAddToGroup(log);
}
}
}
<file_sep>using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace AzureAddUserToGroup.Helpers
{
public class AuthProvider
{
private static HttpClient client = new HttpClient();
// Gets an access token and its expiration date. First tries to get the token from the token cache.
public static async Task<string> GetUserAccessTokenAsync()
{
var bodyData = BuildBodyData();
var content = new StringContent(bodyData, Encoding.UTF8, "application/x-www-form-urlencoded");
var postUrl = "https://login.microsoftonline.com/smkl.onmicrosoft.com/oauth2/v2.0/token";
var response = await client.PostAsync(postUrl, content);
var responseString = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(responseString);
var token = GetJArrayValue(json, "access_token");
return token;
}
private static string GetJArrayValue(JObject yourJArray, string key)
{
foreach (KeyValuePair<string, JToken> keyValuePair in yourJArray)
{
if (key == keyValuePair.Key)
{
return keyValuePair.Value.ToString();
}
}
return null;
}
private static string BuildBodyData()
{
var sb = new StringBuilder();
sb.Append("client_id=" + HiddenConstants.ClientId);
sb.Append("&");
sb.Append("scope=https%3A%2F%2Fgraph.microsoft.com%2F.default");
sb.Append("&");
sb.Append("client_secret=" + HiddenConstants.ClientSecret);
sb.Append("&");
sb.Append("grant_type=client_credentials");
return sb.ToString();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Graph;
namespace AzureAddUserToGroup.Services
{
public class UsersService
{
public async Task<List<ResultsItem>> GetAllCountryUsers(GraphServiceClient graphClient, string country)
{
List<ResultsItem> items = new List<ResultsItem>();
var url = @"https://graph.microsoft.com/v1.0/users?$filter=country eq '" + country + "'";
IGraphServiceUsersCollectionPage users = await new GraphServiceUsersCollectionRequestBuilder(url, graphClient).Request().GetAsync();
if (users?.Count > 0)
{
foreach (User user in users)
{
items.Add(new ResultsItem
{
Display = user.DisplayName,
Id = user.Id
});
}
}
return items;
}
public async Task<List<ResultsItem>> GetAllOfficeManagers(GraphServiceClient graphClient, string jobTitle, string country)
{
List<ResultsItem> items = new List<ResultsItem>();
var url = @"https://graph.microsoft.com/v1.0/users?$filter=jobTitle eq '"+ jobTitle +"' and country eq '"+ country + "'";
IGraphServiceUsersCollectionPage users = await new GraphServiceUsersCollectionRequestBuilder(url, graphClient).Request().GetAsync();
if (users?.Count > 0)
{
foreach (User user in users)
{
items.Add(new ResultsItem
{
Display = user.DisplayName,
Id = user.Id
});
}
}
return items;
}
// Get all users.
public async Task<List<ResultsItem>> GetAllUsers(GraphServiceClient graphClient)
{
List<ResultsItem> items = new List<ResultsItem>();
IGraphServiceUsersCollectionPage users = await graphClient.Users.Request().GetAsync();
if (users?.Count > 0)
{
foreach (User user in users)
{
items.Add(new ResultsItem
{
Display = user.DisplayName,
Id = user.Id
});
}
}
return items;
}
// Get the current user's profile.
public async Task<List<ResultsItem>> GetMe(GraphServiceClient graphClient)
{
List<ResultsItem> items = new List<ResultsItem>();
// Get the current user's profile.
User me = await graphClient.Me.Request().GetAsync();
if (me != null)
{
// Get user properties.
items.Add(new ResultsItem
{
Display = me.DisplayName,
Id = me.Id,
Properties = new Dictionary<string, object>
{
{ "UPN", me.UserPrincipalName },
{ "ID", me.Id }
}
});
}
return items;
}
// Get the current user's photo.
public async Task<List<ResultsItem>> GetMyPhoto(GraphServiceClient graphClient)
{
List<ResultsItem> items = new List<ResultsItem>();
// Get my photo.
using (Stream photo = await graphClient.Me.Photo.Content.Request().GetAsync())
{
if (photo != null)
{
// Get byte[] for display.
using (BinaryReader reader = new BinaryReader(photo))
{
byte[] data = reader.ReadBytes((int)photo.Length);
items.Add(new ResultsItem
{
Properties = new Dictionary<string, object>
{
{ "Stream", data }
}
});
}
}
}
return items;
}
// Get a specified user.
public async Task<List<ResultsItem>> GetUser(GraphServiceClient graphClient, string id)
{
List<ResultsItem> items = new List<ResultsItem>();
// Get the user.
User user = await graphClient.Users[id].Request().GetAsync();
if (user != null)
{
// Get user properties.
items.Add(new ResultsItem
{
Display = user.DisplayName,
Id = user.Id,
Properties = new Dictionary<string, object>
{
{ "UPN", user.UserPrincipalName },
{ "ID", user.Id }
}
});
}
return items;
}
// Get a specified user's photo.
public async Task<List<ResultsItem>> GetUserPhoto(GraphServiceClient graphClient, string id)
{
List<ResultsItem> items = new List<ResultsItem>();
// Get the user's photo.
using (Stream photo = await graphClient.Users[id].Photo.Content.Request().GetAsync())
{
if (photo != null)
{
// Get byte[] for display.
using (BinaryReader reader = new BinaryReader(photo))
{
byte[] data = reader.ReadBytes((int)photo.Length);
items.Add(new ResultsItem
{
Properties = new Dictionary<string, object>
{
{ "Stream", data }
}
});
}
}
}
return items;
}
// Get the direct reports of a specified user.
// This snippet requires an admin work account.
public async Task<List<ResultsItem>> GetDirectReports(GraphServiceClient graphClient, string id)
{
List<ResultsItem> items = new List<ResultsItem>();
// Get user's direct reports.
IUserDirectReportsCollectionWithReferencesPage directs = await graphClient.Users[id].DirectReports.Request().GetAsync();
if (directs?.Count > 0)
{
foreach (User user in directs)
{
// Get user properties.
items.Add(new ResultsItem
{
Display = user.DisplayName,
Id = user.Id,
Properties = new Dictionary<string, object>
{
{ "UPN", user.UserPrincipalName },
{ "ID", user.Id }
}
});
}
}
return items;
}
// Update a user.
// This snippet changes the user's display name.
// This snippet requires an admin work account.
public async Task<List<ResultsItem>> UpdateUser(GraphServiceClient graphClient, string id, string name)
{
List<ResultsItem> items = new List<ResultsItem>();
// Update the user.
await graphClient.Users[id].Request().UpdateAsync(new User
{
DisplayName = "Updated " + name
});
items.Add(new ResultsItem
{
// This operation doesn't return anything.
Properties = new Dictionary<string, object>
{
{ "Operation completed. This call doesn't return anything.", "" }
}
});
return items;
}
// Delete a user. Warning: This operation cannot be undone.
// This snippet requires an admin work account.
public async Task<List<ResultsItem>> DeleteUser(GraphServiceClient graphClient, string id)
{
List<ResultsItem> items = new List<ResultsItem>();
ResultsItem item = new ResultsItem();
// Make sure that the current user is not selected.
User me = await graphClient.Me.Request().Select("id").GetAsync();
if (id == me.Id)
{
item.Properties.Add("Please choose another user. This snippet doesn't support deleting the current user.", "");
}
else
{
// Delete the user.
await graphClient.Users[id].Request().DeleteAsync();
// This operation doesn't return anything.
item.Properties.Add("Operation completed. This call doesn't return anything.", "");
}
items.Add(item);
return items;
}
}
}<file_sep># Azure Function that uses Microsoft Graph to sync users to O365 groups on a Daily basis (CRON Expression)<file_sep>using Microsoft.Extensions.Logging;
using Microsoft.Graph;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AzureAddUserToGroup.Services
{
public class GroupsService
{
// Get groups.
// This snippet requires an admin work account.
public async Task<List<ResultsItem>> GetGroups(GraphServiceClient graphClient)
{
List<ResultsItem> items = new List<ResultsItem>();
// Get groups.
IGraphServiceGroupsCollectionPage groups = await graphClient.Groups.Request().GetAsync();
if (groups?.Count > 0)
{
foreach (Group group in groups)
{
items.Add(new ResultsItem
{
Display = group.DisplayName,
Id = group.Id
});
}
}
return items;
}
public async Task<bool> PutUsersInGroup(GraphServiceClient graphClient, List<ResultsItem> users, string groupName, ILogger log)
{
var url = @"https://graph.microsoft.com/v1.0/groups?$filter=startswith(displayName,'" + groupName + "')";
IGraphServiceGroupsCollectionPage groups = await new GraphServiceGroupsCollectionRequestBuilder(url, graphClient).Request().GetAsync();
if (groups?.Count > 0)
{
var group = groups.FirstOrDefault();
var getMembersUrl = @"https://graph.microsoft.com/v1.0/groups/" + group.Id + "/members";
var members = await new DirectoryRoleMembersCollectionWithReferencesRequestBuilder(getMembersUrl, graphClient).Request().GetAsync();
var filteredUserList = new List<ResultsItem>();
var membersInGroup = new List<ResultsItem>();
while (members?.Count > 0)
{
foreach (var item in members)
{
membersInGroup.Add(new ResultsItem() { Id = item.Id});
}
if (members.NextPageRequest != null)
{
members = await members.NextPageRequest.GetAsync();
}
else
{
members = null;
}
}
foreach (var user in users)
{
var member = membersInGroup.Where(x => x.Id == user.Id).FirstOrDefault();
if (member == null)
{
filteredUserList.Add(user);
}
}
foreach (var user in filteredUserList)
{
try
{
var directoryObject = new DirectoryObject
{
Id = user.Id
};
await graphClient.Groups[group.Id].Members.References.Request().AddAsync(directoryObject);
}
catch (Exception ex)
{
log.LogError(ex.Message);
}
}
}
else
{
return false;
}
return true;
}
// Get Office 365 (unified) groups.
// This snippet requires an admin work account.
public async Task<List<ResultsItem>> GetUnifiedGroups(GraphServiceClient graphClient)
{
List<ResultsItem> items = new List<ResultsItem>();
// Get unified groups.
IGraphServiceGroupsCollectionPage groups = await graphClient.Groups.Request().Filter("groupTypes /any(a:a%20eq%20'unified')").GetAsync();
if (groups?.Count > 0)
{
foreach (Group group in groups)
{
items.Add(new ResultsItem
{
Display = group.DisplayName,
Id = group.Id
});
}
}
return items;
}
// Get the groups that the current user is a direct member of.
// This snippet requires an admin work account.
public async Task<List<ResultsItem>> GetMyMemberOfGroups(GraphServiceClient graphClient)
{
List<ResultsItem> items = new List<ResultsItem>();
// Get groups the current user is a direct member of.
IUserMemberOfCollectionWithReferencesPage memberOfGroups = await graphClient.Me.MemberOf.Request().GetAsync();
if (memberOfGroups?.Count > 0)
{
foreach (var directoryObject in memberOfGroups)
{
// We only want groups, so ignore DirectoryRole objects.
if (directoryObject is Group)
{
Group group = directoryObject as Group;
items.Add(new ResultsItem
{
Display = group.DisplayName,
Id = group.Id
});
}
}
}
return items;
}
// Create a new group. It can be an Office 365 group, dynamic group, or security group.
// This snippet creates an Office 365 (unified) group.
// This snippet requires an admin work account.
public async Task<List<ResultsItem>> CreateGroup(GraphServiceClient graphClient)
{
List<ResultsItem> items = new List<ResultsItem>();
string guid = Guid.NewGuid().ToString();
// Add the group.
Group group = await graphClient.Groups.Request().AddAsync(new Group
{
GroupTypes = new List<string> { "Unified" },
DisplayName = "Group" + guid.Substring(0, 8),
Description = "Group" + guid,
MailNickname = "group" + guid.Substring(0, 8),
MailEnabled = false,
SecurityEnabled = false
});
if (group != null)
{
// Get group properties.
items.Add(new ResultsItem
{
Display = group.DisplayName,
Id = group.Id,
Properties = new Dictionary<string, object>
{
{ "Description", group.Description },
{ "Email", group.Mail },
{ "Created", group.AdditionalData["createdDateTime"] }, // Temporary workaround for a known SDK issue.
{ "ID", group.Id }
}
});
}
return items;
}
// Get a specified group.
// This snippet requires an admin work account.
public async Task<List<ResultsItem>> GetGroup(GraphServiceClient graphClient, string id)
{
List<ResultsItem> items = new List<ResultsItem>();
// Get the group.
Group group = await graphClient.Groups[id].Request().Expand("members").GetAsync();
if (group != null)
{
// Get group properties.
items.Add(new ResultsItem
{
Display = group.DisplayName,
Id = group.Id,
Properties = new Dictionary<string, object>
{
{ "Email", group.Mail },
{ "Member count", group.Members?.Count },
{ "ID", group.Id }
}
});
}
return items;
}
// Read properties and relationships of group members.
// This snippet requires an admin work account.
public async Task<List<ResultsItem>> GetMembers(GraphServiceClient graphClient, string id)
{
List<ResultsItem> items = new List<ResultsItem>();
// Get group members.
IGroupMembersCollectionWithReferencesPage members = await graphClient.Groups[id].Members.Request().GetAsync();
if (members?.Count > 0)
{
foreach (User user in members)
{
// Get member properties.
items.Add(new ResultsItem
{
Properties = new Dictionary<string, object>
{
{ "UPN", user.UserPrincipalName },
{ "ID", user.Id }
}
});
}
}
return items;
}
// Read properties and relationships of group members.
// This snippet requires an admin work account.
public async Task<List<ResultsItem>> GetOwners(GraphServiceClient graphClient, string id)
{
List<ResultsItem> items = new List<ResultsItem>();
// Get group owners.
IGroupOwnersCollectionWithReferencesPage members = await graphClient.Groups[id].Owners.Request().GetAsync();
if (members?.Count > 0)
{
foreach (User user in members)
{
// Get owner properties.
items.Add(new ResultsItem
{
Properties = new Dictionary<string, object>
{
{ "UPN", user.UserPrincipalName },
{ "ID", user.Id }
}
});
}
}
return items;
}
// Update a group.
// This snippet changes the group name.
// This snippet requires an admin work account.
public async Task<List<ResultsItem>> UpdateGroup(GraphServiceClient graphClient, string id, string name)
{
List<ResultsItem> items = new List<ResultsItem>();
// Update the group.
await graphClient.Groups[id].Request().UpdateAsync(new Group
{
DisplayName = "Updated " + name
});
items.Add(new ResultsItem
{
// This operation doesn't return anything.
Properties = new Dictionary<string, object>
{
{ "Operation completed. This call doesn't return anything.", "" }
}
});
return items;
}
// Delete a group. Warning: This operation cannot be undone.
// This snippet requires an admin work account.
public async Task<List<ResultsItem>> DeleteGroup(GraphServiceClient graphClient, string id)
{
List<ResultsItem> items = new List<ResultsItem>();
// Delete the group.
await graphClient.Groups[id].Request().DeleteAsync();
items.Add(new ResultsItem
{
// This operation doesn't return anything.
Properties = new Dictionary<string, object>
{
{ "Operation completed. This call doesn't return anything.", "" }
}
});
return items;
}
}
}
|
9e4314fa8fb732f72ec5fe3475b707251edc38c3
|
[
"Markdown",
"C#"
] | 8 |
C#
|
SKLM-O365-Projects/MonoRepo
|
23c858c8cccd83dbd33b6514803295660213922b
|
b554a67068dc02efd6d78885d3348405e1175b4e
|
refs/heads/master
|
<repo_name>alexyslozada/WebSocketsDemo<file_sep>/src/java/org/alexys/demo/WSDTodos.java
package org.alexys.demo;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
/**
*
* @author Alexys
*/
@ServerEndpoint("/mensajeATodos")
@Singleton
public class WSDTodos {
private static final Logger LOGGER = Logger.getLogger(WSDTodos.class.getName());
//Lista de sesiones conectados
private static final List<Session> conexiones = new ArrayList<>();
/**
* Evento que se ejecuta cuando un cliente se conecta
*
* @param session La sesion del cliente
*/
@OnOpen
public void iniciaSesion(Session session) {
LOGGER.log(Level.INFO, "Iniciando la conexion de {0}", session.getId());
conexiones.add(session); //Simplemente, lo agregamos a la lista
}
/**
* Evento que se ejecuta cuando se pierde una conexion.
*
* @param session La sesion del cliente
*/
@OnClose
public void finConexion(Session session) {
LOGGER.info("Terminando la conexion");
if (conexiones.contains(session)) { // se averigua si está en la colección
try {
LOGGER.log(Level.INFO, "Terminando la conexion de {0}", session.getId());
session.close(); //se cierra la conexión
conexiones.remove(session); // se retira de la lista
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
}
/**
* Enviaremos un mensaje a todos los conectados
*/
@Schedule(second = "*/10", minute = "*", hour = "*", persistent = false)
public void notificar() {
LOGGER.log(Level.INFO, "Enviando notificacion a {0} conectados", conexiones.size());
String mensaje = "Son las " + (new java.util.Date()) + " y hay " + conexiones.size() + " conectados "; // el mensaje a enviar
for (Session sesion : conexiones) { //recorro toda la lista de conectados
RemoteEndpoint.Basic remote = sesion.getBasicRemote(); //tomo la conexion remota con el cliente...
try {
remote.sendText(mensaje); //... y envío el mensajue
} catch (IOException ex) {
LOGGER.log(Level.WARNING, null, ex);
}
}
}
/**
* Solo es un metodo que atiende las peticiones
*
* @param mensaje
*/
@OnMessage
public void onMessage(String mensaje) {
for(Session sesionAbierta:conexiones){
try {
sesionAbierta.getBasicRemote().sendText("Hola a todos con este mensaje:" + mensaje);
} catch (IOException ex) {
LOGGER.log(Level.WARNING, null, ex);
}
}
}
}
|
17cab5cbb60456d841eed66b2217cb1cc600f55b
|
[
"Java"
] | 1 |
Java
|
alexyslozada/WebSocketsDemo
|
1141ebbc0763f626b4c6825fdf6c9e9d0fe501a1
|
5748670ea664b349b7f72d0cbdc3204c8831c359
|
refs/heads/master
|
<repo_name>jastro2/LAW<file_sep>/.idea/LAW.js
$(function () {
var w = $(window);
w.scroll(function () {
if (w.scrollTop() !== 0) {
$(".d").removeClass("visible");
return;
}
$(".d").addClass("visible");
});
$(".d").addClass("visible");
});<file_sep>/LAW/LAW.js
/* Scroll */
$('a[href^="#scrollHere"]').on('click', function(event) {
var target = $(this.getAttribute('href'));
if( target.length ) {
event.preventDefault();
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 1000);
}
});
/* ======= GOOGLE MAP API ======= */
function myMap() {
var mapProp= {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
}<file_sep>/LAW/README.md
# LAW
Live Action Woodworking website
<h1>LIVE ACTION WOODWORKING</h1>
<p>The website for a small business in Roanoke, Virginia</p>
|
70aaab6dffa2de99560a4ca31a0e398e54f9ff97
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
jastro2/LAW
|
197c02e4f634a470f0e609c586f82c369f8fbbc6
|
8bb759e7ecddefeb322ea36c2a669363740aeb84
|
refs/heads/master
|
<repo_name>42gq/fillit<file_sep>/src/ft_grid.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_grid.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: snedir <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/06 18:25:26 by snedir #+# #+# */
/* Updated: 2017/11/10 00:31:14 by gquerre ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft/libft.h"
#include "../includes/fillit.h"
int ft_size(int lenght)
{
int i;
i = 1;
while (i * i < lenght * 4)
i++;
return (i);
}
void format_grid(char **grid, int taille)
{
int i;
int j;
i = 0;
j = 0;
while (grid[i])
{
while (j < taille)
{
grid[i][j] = '.';
j++;
}
grid[i][j] = '\0';
j = 0;
i++;
}
}
char **create_grid(int taille)
{
char **grid;
int i;
i = 0;
grid = (char**)malloc(sizeof(char*) * taille + 1);
while (i < taille)
{
grid[i] = (char*)malloc(sizeof(char) * taille + 1);
i++;
}
grid[i] = 0;
format_grid(grid, taille);
return (grid);
}
void print_grid(char **grid)
{
int i;
int j;
i = 0;
j = 0;
while (grid[i])
{
while (grid[i][j])
{
ft_putchar(grid[i][j]);
j++;
}
ft_putchar('\n');
j = 0;
i++;
}
}
char **ft_upgrid(int taille, char **grid, int i)
{
int w;
w = 0;
while (w < taille - i)
{
free(grid[w]);
w++;
}
free(grid);
grid = create_grid(taille + i);
return (grid);
}
<file_sep>/src/ft_nodedoublelinks.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_nodedoublelinks.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: snedir <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/08 17:17:50 by snedir #+# #+# */
/* Updated: 2017/03/12 23:58:08 by snedir ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft/libft.h"
#include "../includes/fillit.h"
t_tetr *new_node(char *data)
{
t_tetr *elem;
elem = NULL;
elem = (t_tetr*)malloc(sizeof(t_tetr));
elem->data = data;
elem->next = NULL;
elem->prev = NULL;
return (elem);
}
t_tetr *add_node(t_tetr *elem, char *data, t_head *master)
{
t_tetr *new;
if (elem)
{
new = new_node(data);
new->next = elem;
elem->prev = new;
master->lenght += 1;
}
else
{
new = new_node(data);
master->first_element = new;
master->lenght += 1;
}
return (new);
}
<file_sep>/src/ft_fillgrid.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_fillgrid.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gquerre <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/25 07:56:08 by gquerre #+# #+# */
/* Updated: 2017/03/12 23:57:42 by snedir ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft/libft.h"
#include "../includes/fillit.h"
int ft_lenline(t_tetr *piece, int i)
{
int len;
int k;
int tmp;
len = 0;
k = 0;
while (len < i)
{
if (piece->data[len] == '\n')
k++;
len++;
}
if (k != 0)
{
tmp = len;
len--;
while (piece->data[len] != '\n')
len--;
len = tmp - len - 1;
}
return (len);
}
int ft_searchletter(char **grid, char lettre)
{
int position;
int i;
int j;
i = 0;
j = 0;
position = 0;
while (grid[i])
{
while (grid[i][j] && grid[i][j] != lettre)
{
position++;
j++;
}
if (grid[i][j] == lettre)
return (position);
j = 0;
i++;
}
return (0);
}
void ft_removepoints(char **grid, char lettre)
{
int i;
int j;
i = 0;
j = 0;
while (grid[i])
{
while (grid[i][j])
{
if (grid[i][j] == lettre)
grid[i][j] = '.';
j++;
}
j = 0;
i++;
}
}
<file_sep>/src/main.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: snedir <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/08 17:40:08 by snedir #+# #+# */
/* Updated: 2017/03/12 23:58:28 by snedir ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft/libft.h"
#include "../includes/fillit.h"
int count_points(t_tetr *piece, int k)
{
int i;
i = 0;
while (piece->data[k] && piece->data[k] != '\n')
{
k--;
i++;
}
return (i);
}
char *modify_piece(char *piece)
{
int size;
int i;
char *str;
int j;
i = -1;
size = 0;
j = 0;
while (piece[++i])
if (piece[i] == '\n' || piece[i] == '#' || piece[i] == '.')
size++;
str = (char*)malloc(sizeof(char) * size + 1);
i = 0;
while (piece[i])
{
if (piece[i] == '\n' || piece[i] == '#' || piece[i] == '.')
{
str[j] = piece[i];
j++;
}
i++;
}
str[j] = '\0';
return (str);
}
t_tetr *read_and_copy(char *argv, t_head *sent, t_tetr *elem, t_iter *var)
{
t_buf stock;
char c;
c = 'a';
if ((FD = open(argv, O_RDONLY)) != -1)
{
while ((RET = read(FD, BUF, 21)))
{
BUF[RET] = '\0';
if (ft_checksquare(BUF) == 1 && ft_checkpiece(BUF) == 1)
{
ft_final(&STR, &STR2, BUF, var);
elem = add_node(elem, STR2, sent);
ft_multi(&c, BUF, sent, elem);
ft_strclr(BUF);
}
else
return (NULL);
}
if (c == '\0')
return (sent->first_element);
}
close(FD);
return (NULL);
}
void hashtag_to_alpha(t_tetr *elem)
{
int i;
i = 0;
while (elem)
{
while (elem->data[i])
{
if (elem->data[i] == '#')
elem->data[i] = elem->piece;
i++;
}
i = 0;
elem = elem->prev;
}
}
int main(int argc, char **argv)
{
t_map map;
t_tetr *elem;
t_head sentinel;
int i;
t_iter var;
elem = NULL;
ELEM = elem;
i = 0;
if (ft_argc(argc))
return (0);
if ((ELEM = read_and_copy(argv[1], &sentinel, ELEM, &var)))
{
GRID = create_grid(ft_size(sentinel.lenght));
hashtag_to_alpha(ELEM);
while (ft_grid(&map, 0, sentinel.lenght) == 0)
{
i++;
GRID = ft_upgrid((ft_size(sentinel.lenght)), GRID, i);
}
print_grid(GRID);
}
else
ft_putstr("error\n");
return (0);
}
<file_sep>/src/ft_backtracking.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_backtracking.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: snedir <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/02/06 22:52:04 by snedir #+# #+# */
/* Updated: 2017/03/12 23:52:13 by snedir ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft/libft.h"
#include "../includes/fillit.h"
void ft_points(t_tetr *piece, int *pos, int *k, int size)
{
while (piece->data[*k] && piece->data[*k] == '.')
{
if (*k == 0 || *k == 1)
{
if (md_p(*pos, size) == *k)
{
*k += 1;
*pos += 1;
}
else
*k += 1;
}
else
{
*k += 1;
*pos += 1;
}
}
}
int ft_place(t_map *map, int pos, int k, int count)
{
SIZE = ft_strlen(*GRIDP);
if (count == 4)
return (1);
ft_points(ELEMP, &pos, &k, SIZE);
if (pos > (SIZE * SIZE) - 1)
return (0);
if (EDATA[k] == '\n')
{
pos = pos + SIZE - ft_lenline(ELEMP, k);
return ((pos < SIZE * SIZE) ? (ft_place(map, pos, k + 1, count)) : 0);
}
if (EDATA[k] && GRIDP[dv_p(pos, SIZE)][md_p(pos, SIZE)] == '.')
{
GRIDP[dv_p(pos, SIZE)][md_p(pos, SIZE)] = EDATA[k];
if (md_p(pos, SIZE) == SIZE - 1 && (EDATA[k + 1] != '\n'))
{
GRIDP[dv_p(pos, SIZE)][md_p(pos, SIZE)] = '.';
return (0);
}
if (ft_place(map, pos + 1, k + 1, count + 1))
return (1);
}
if (GRIDP[dv_p(pos, SIZE)][md_p(pos, SIZE)] == PIECE)
GRIDP[dv_p(pos, SIZE)][md_p(pos, SIZE)] = '.';
return (0);
}
int ft_rabbit_hole(t_map *map, int *pos)
{
int k;
int size;
int ret;
k = 0;
ret = 0;
size = ft_strlen(*GRIDP);
while (GRIDP[dv_p(*pos, size)] != 0 && *pos < (size * size))
{
if (GRIDP[dv_p(*pos, size)][md_p(*pos, size)] == '.')
{
if ((ret = ft_place(map, *pos, k, 0)))
return (1);
}
*pos += 1;
}
return (0);
}
int ft_grid(t_map *map, int count, int nbpieces)
{
int pos;
pos = 0;
while (ELEMP && count < nbpieces)
{
if (ft_rabbit_hole(map, &pos))
{
count++;
ELEMP = ELEMP->prev;
pos = 0;
}
else
{
count--;
if (count < 0)
return (0);
ELEMP = ELEMP->next;
pos = ft_searchletter(GRIDP, PIECE) + 1;
ft_removepoints(GRIDP, PIECE);
}
}
if (count == nbpieces)
return (1);
return (0);
}
<file_sep>/src/ft_checkemptyline.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_checkemptyline.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gquerre <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/14 19:08:32 by gquerre #+# #+# */
/* Updated: 2017/03/12 23:53:57 by snedir ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft/libft.h"
#include "../includes/fillit.h"
char *ft_checkemptyline(char *str, t_iter *var)
{
var->count = 0;
var->end = 0;
var->start = 0;
var->i = 0;
while (var->end < 4)
{
while (str[var->i] != '\n')
{
if (str[var->i] == '#')
var->end += 1;
if (str[var->i] == '.' || str[var->i] == '0')
{
var->count += 1;
if (var->i < 4)
ft_checkemptycolumn(&str, var->i);
}
var->i += 1;
}
var->start = ft_checkcount(var->count, var->start);
var->count = 0;
var->i += 1;
}
return (ft_readlines(ft_strsub(str, var->start, var->i - var->start)));
}
char *ft_readlines(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
{
while (str[i] != '\n')
i++;
while (str[--i] != '#')
str[i] = '0';
while (str[i] != '\n')
i++;
i++;
}
return (str);
}
<file_sep>/includes/fillit.h
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fillit.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: snedir <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/08 19:56:47 by snedir #+# #+# */
/* Updated: 2017/03/12 23:43:10 by snedir ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FILLIT_H
# define FILLIT_H
# define ELEM map.node
# define GRID map.grid
# define SIZE map->size
# define ELEMP map->node
# define GRIDP map->grid
# define PIECE ELEMP->piece
# define EDATA ELEMP->data
# define STR stock.str
# define STR2 stock.str2
# define BUF stock.buf
# define FD stock.fd
# define C stock.c
# define RET stock.ret
# define SELEM stock.elem
# define PELEM stock.elem
# include <fcntl.h>
typedef struct s_tetr
{
char *data;
char piece;
struct s_tetr *prev;
struct s_tetr *next;
} t_tetr;
typedef struct s_head
{
t_tetr *first_element;
int lenght;
} t_head;
typedef struct s_map
{
t_tetr *node;
char **grid;
int size;
} t_map;
typedef struct s_iter
{
int start;
int i;
int count;
int end;
} t_iter;
typedef struct s_buf
{
char buf[21];
char c;
int fd;
int ret;
char *str;
char *str2;
t_tetr *elem;
} t_buf;
char *modify_piece(char *piece);
void ft_final(char **str, char **str2, char *buf, t_iter *var);
int ft_put(char c);
int ft_lenline(t_tetr *piece, int i);
int ft_searchletter(char **grid, char lettre);
void ft_removepoints(char **grid, char lettre);
int dv_p(int pos, int taille);
int md_p(int pos, int taille);
int ft_place(t_map *map, int pos, int k, int count);
int ft_rabbithole(char **grid, t_tetr *piece, int *pos);
int ft_grid(t_map *map, int count, int nbpieces);
int ft_checkcount(int count, int start);
void ft_checkemptycolumn(char **str, int i);
char *ft_checkemptyline (char *str, t_iter *var);
int ft_checkpiece(char *str);
int ft_checksquare(char *str);
int ft_lenline(t_tetr *piece, int i);
int put_piece(char **grid, char *piece, int i, int j,
int count, int place);
char **create_grid(int taille);
void format_grid(char **grid, int taille);
int ft_size(int lenght);
void ft_multi(char *c, char *buf, t_head *sent, t_tetr *elem);
void format_grid(char **grid, int taille);
void print_grid(char **grid);
char **ft_upgrid(int taille, char **grid, int i);
t_tetr *new_node(char *data);
t_tetr *add_node(t_tetr *elem, char *data, t_head *master);
int count_points(t_tetr *piece, int k);
t_tetr *read_and_copy(char *argv, t_head *sent, t_tetr *elem,
t_iter *var);
void hashtag_to_alpha(t_tetr *elem);
void ft_points(t_tetr *piece, int *pos, int *k, int size);
void ft_checkemptycolumn(char **str, int i);
int ft_checkcount(int count, int start);
char *ft_readlines(char *str);
int ft_checklinksreverse(char *str);
int ft_checklinks(char *str);
int ft_argc(int argc);
#endif
|
ab2a99226f8296ecb2df795aeeda60dbe6568fe9
|
[
"C"
] | 7 |
C
|
42gq/fillit
|
1063da0858e6db4473fcd12707ee55caa272a9f4
|
d8363c3d6a213696530f87b2d28239425671f13b
|
refs/heads/master
|
<file_sep>
function myFunction() {
document.getElementById("demo").innerHTML = "Liked.";
}
function looper() {
for (var i = 0; i < 10; i++) {
document.getElementById("demo1").innerHTML = "I think so anyways!"
if (i % 2 === 0) {
console.log("this number " + i + " is even")
} else {
console.log("this number " + i + " is odd")
}
console.log(i)
}
}
<file_sep>
// //Preliminaries
// // Write an if statement that prints "is greater than" if 5 is greater than 3
// const x = 5;
// const y = 3;
// if(x>y){
// console.log("is greater than")
// }
// //Write an if statement that prints "is the length" if the length of "cat" is 3
// const z = "cat"
// const a = z.length
// if(a === 3){
// console.log("is the length")
// }
// //Write an if/else statement that checks if "cat" is equal to "dog" and prints, "not the same" when they are not equal.
// const b = "cat"
// const c = "dog"
// if(b === c){
// console.log("the same")
// }
// else{console.log("not the same")}
// //Bronze Medal
// const person = {
// name: "Bobby",
// age: 12
// }
// // The person is only allowed to watch the movie if he is 18 or older
// if(person.age >= 18){
// console.log(person.name + " is allowed to watch the movie")
// }
// else{console.log(person.name + " is not allowed to watch the movie")}
// // The person is only allowed to go into the movie if their name starts with the letter b
// if(person.name[0]=b){
// console.log(person.name + " is allowed to watch the movie")
// }
// else{console.log(person.name + " is not allowed to watch the movie")}
// // The person is only allowed to go into the movie if their name starts with the letter b, and if they are 18 or older
// if(person.name[0]=b && person.age >= 18){
// console.log(person.name + " is allowed to watch the movie")
// }
// else{console.log(person.name + " is not allowed to watch the movie")}
// //Silver Medal
// //Write an if/else if/else statement that prints "strict" if 1 strictly equals "1", prints "loose" or "abstract" if 1 equals "1" without type checking, and prints "not equal at all" if it doesn't print the other stuff.
// if(1 === "1"){
// console.log("strict")
// } else if(1 == "1"){
// console.log("loose")
// }else{
// console.log("not equal at all")
// }
// //Write an if statement that prints "yes" if 1 is less than or equal to 2 AND (&&) 2 is equal to 4
// if(1<=2 && 2 === 4){
// console.log("yes")
// }else{
// console.log("no")
// }
// //Gold Medal
// //Write an if statement that checks to see if "dog" is a string
// const myDog ="dog"
// if(typeof myDog === "string"){
// console.log("it is a string")
// }
// //Write an if statement that checks to see if "true" is a boolean
// const myTrue = "true"
// if(typeof myTrue === "boolean"){
// console.log("It is a boolean")
// }else{
// console.log("it is not a boolean")
// }
// //Write an if statement that checks to see if a constiable has been defined or not
// const myDefine
// if(typeof myDefine !== "undefined"){
// console.log("myDefine is undefined")
// }else{
// console.log("myDefine is defined")
// }
// //Write an if statement asking if "s" is greater than 12?
// if("s">12){
// console.log("s is greater than 12")
// }else{
// console.log("s is not greater than 12")
// }
// //Try it with a few more letters and a few numbers.
// if("a">12){
// console.log("a is greater than 12")
// }else{
// console.log("a is not greater than 12")
// }
// //letters
// if("A">"B"){
// console.log("A is greater than B")
// }else{
// console.log("A is not greater than B")
// }
//Write a ternary statement that console.logs whether a number is odd or even. For example:
//const myNum = 10;
// Write your ternary here to log if `myNum` is odd or even.
const myNum = 4;
const isEvenOdd = myNum % 2 === 0 ? 'even' : 'odd';
//console.log(`${myNum} is ${isEvenOdd}`)
console.log(myNum + ' is' + ' ' + isEvenOdd)
//(It should continue to work correctly even if myNum changes to a different number).
<file_sep>for(var i=0; i<100; i++){
if(i%2 === 0){
console.log("even")
} else {
console.log("odd")
}
}<file_sep><html lang="en">
<head>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>New York News</title>
</head>
<body>
<hr class="new1">
<h1>New York News</h1>
<div class="bold1">
<span>World - Tech - Finance - Lifestyle - Travel - Sports - Weather</span>
</div>
<div>
<span class="issue1">Issue:2501423</span>
<span class="issue2">The Best News Yet!<span>
<span class="issue3">Est. 1987</span>
</div>
<hr class="new2">
<div class="bold2">
<span class="edition1">First Edition</span>
<span class="date1">Monday 6th January</span>
</div>
<div class="box">
<h2>Good News</h2>
<span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus blanditiis asperiores beatae aspernatur optio laborum at perferendis natus voluptas sed ipsa, modi suscipit a autem culpa! Ipsa suscipit unde et. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
</div>
<div class="box">
<h2>Great News</h2>
<span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas molestias mollitia inventore nam deserunt perferendis fuga adipisci omnis? Vel, illo sunt! Itaque officia quia illo voluptates nemo. Facilis, atque odit.Id donec ultrices tincidunt arcu non. Accumsan sit amet nulla facilisi. Lectus arcu bibendum at varius. Ultrices dui sapien eget mi proin sed. Urna neque viverra justo nec ultrices dui. Mauris ultrices eros in cursus turpis massa tincidunt. Integer enim neque volutpat ac tincidunt vitae. Vitae nunc sed velit dignissim. Nisl pretium fusce id velit. </span>
</div>
<div class="box">
<h2>The Best News!</h2>
<span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam id fugit architecto, expedita eveniet ab itaque reprehenderit enim eius vitae nihil voluptatum officia. Sequi totam illo tempore ad expedita culpa.Quis auctor elit sed vulputate mi sit amet mauris commodo. Adipiscing at in tellus integer feugiat. Dapibus ultrices in iaculis nunc sed augue. Dignissim enim sit amet venenatis urna. Sed turpis tincidunt id aliquet risus feugiat in ante metus. Arcu felis bibendum ut tristique. Elementum nisi quis eleifend quam. Mauris augue neque gravida in. </span>
</div>
</body>
</html>
|
6e2f729d4b11b699e8e8ea1fe5ae4a350c2b1bf6
|
[
"JavaScript",
"HTML"
] | 4 |
JavaScript
|
Russell-Dev/assignments
|
f17af60f4d3600f332e2f029caa13d755849059d
|
2d58df65ad016b490d7e2e85a1e25a1321d089e3
|
refs/heads/master
|
<file_sep>from mxnet import init
from mxnet.gluon.model_zoo import vision
from mxnet.gluon import nn
from mxnet import image
import numpy as np
from mxnet import nd
import mxnet as mx
class ConcatNet(nn.HybridBlock):
def __init__(self,net1,net2,**kwargs):
super(ConcatNet,self).__init__(**kwargs)
self.net1 = nn.HybridSequential()
self.net1.add(net1)
self.net1.add(nn.GlobalAvgPool2D())
self.net2 = nn.HybridSequential()
self.net2.add(net2)
self.net2.add(nn.GlobalAvgPool2D())
def hybrid_forward(self,F,x1,x2):
return F.concat(*[self.net1(x1),self.net2(x2)])
class OneNet(nn.HybridBlock):
def __init__(self,features,output,**kwargs):
super(OneNet,self).__init__(**kwargs)
self.features = features
self.output = output
def hybrid_forward(self,F,x1,x2):
return self.output(self.features(x1,x2))
def transform_train(data, label):
im1 = image.imresize(data.astype('float32') / 255, 224, 224)
im2 = image.imresize(data.astype('float32') / 255, 299, 299)
auglist1 = image.CreateAugmenter(data_shape=(3, 224, 224), resize=0,
rand_crop=False, rand_resize=False, rand_mirror=True,
mean=np.array([0.485, 0.456, 0.406]), std=np.array([0.229, 0.224, 0.225]),
brightness=0, contrast=0,
saturation=0, hue=0,
pca_noise=0, rand_gray=0, inter_method=2)
auglist2 = image.CreateAugmenter(data_shape=(3, 299, 299), resize=0,
rand_crop=False, rand_resize=False, rand_mirror=True,
mean=np.array([0.485, 0.456, 0.406]), std=np.array([0.229, 0.224, 0.225]),
brightness=0, contrast=0,
saturation=0, hue=0,
pca_noise=0, rand_gray=0, inter_method=2)
for aug in auglist1:
im1 = aug(im1)
for aug in auglist2:
im2 = aug(im2)
# 将数据格式从"高*宽*通道"改为"通道*高*宽"。
im1 = nd.transpose(im1, (2,0,1))
im2 = nd.transpose(im2, (2,0,1))
return (im1,im2, nd.array([label]).asscalar().astype('float32'))
def transform_test(data, label):
im1 = image.imresize(data.astype('float32') / 255, 224, 224)
im2 = image.imresize(data.astype('float32') / 255, 299, 299)
auglist1 = image.CreateAugmenter(data_shape=(3, 224, 224),
mean=np.array([0.485, 0.456, 0.406]),
std=np.array([0.229, 0.224, 0.225]))
auglist2 = image.CreateAugmenter(data_shape=(3, 299, 299),
mean=np.array([0.485, 0.456, 0.406]),
std=np.array([0.229, 0.224, 0.225]))
for aug in auglist1:
im1 = aug(im1)
for aug in auglist2:
im2 = aug(im2)
# 将数据格式从"高*宽*通道"改为"通道*高*宽"。
im1 = nd.transpose(im1, (2,0,1))
im2 = nd.transpose(im2, (2,0,1))
return (im1,im2, nd.array([label]).asscalar().astype('float32'))
class Net():
def __init__(self,ctx,nameparams=None):
inception = vision.inception_v3(pretrained=True,ctx=ctx).features
resnet = vision.resnet152_v1(pretrained=True,ctx=ctx).features
self.features = ConcatNet(resnet,inception)
self.output = self.__get_output(ctx,nameparams)
self.net = OneNet(self.features,self.output)
def __get_output(self,ctx,ParamsName=None):
net = nn.HybridSequential("output")
with net.name_scope():
net.add(nn.Dense(256,activation='relu'))
net.add(nn.Dropout(.5))
net.add(nn.Dense(120))
if ParamsName is not None:
net.collect_params().load(ParamsName,ctx)
else:
net.initialize(init = init.Xavier(),ctx=ctx)
return net
class Pre():
def __init__(self,nameparams,idx,ctx=0):
self.idx = idx
if ctx == 0:
self.ctx = mx.cpu()
if ctx == 1:
self.ctx = mx.gpu()
self.net = Net(self.ctx,nameparams=nameparams).net
self.Timg = transform_test
def PreImg(self,img):
imgs = self.Timg(img,None)
out = nd.softmax(self.net(nd.reshape(imgs[0],(1,3,224,224)).as_in_context(self.ctx),nd.reshape(imgs[1],(1,3,299,299)).as_in_context(self.ctx))).asnumpy()
return self.idx[np.where(out == out.max())[1][0]]
def PreName(self,Name):
img = image.imread(Name)
return self.PreImg(img)<file_sep>from mxnet import gluon
from mxnet import nd
from mxnet.gluon.data import vision
import numpy as np
import mxnet as mx
import pickle
from tqdm import tqdm
import os
from model import Net,transform_train,transform_test
data_dir = './data'
train_dir = 'train'
test_dir = 'test'
valid_dir = 'valid'
input_dir = 'train_valid_test'
train_valid_dir = 'train_valid'
input_str = data_dir + '/' + input_dir + '/'
batch_size = 32
train_ds = vision.ImageFolderDataset(input_str + train_dir, flag=1,
transform=transform_train)
valid_ds = vision.ImageFolderDataset(input_str + valid_dir, flag=1,
transform=transform_test)
train_valid_ds = vision.ImageFolderDataset(input_str + train_valid_dir,
flag=1, transform=transform_train)
loader = gluon.data.DataLoader
train_data = loader(train_ds, batch_size, shuffle=True, last_batch='keep')
valid_data = loader(valid_ds, batch_size, shuffle=True, last_batch='keep')
train_valid_data = loader(train_valid_ds, batch_size, shuffle=True,
last_batch='keep')
#net = get_features(mx.gpu())
net = Net(mx.gpu()).features
net.hybridize()
def SaveNd(data,net,name):
x =[]
y =[]
print('提取特征 %s' % name)
for fear1,fear2,label in tqdm(data):
fear1 = fear1.as_in_context(mx.gpu())
fear2 = fear2.as_in_context(mx.gpu())
out = net(fear1,fear2).as_in_context(mx.cpu())
x.append(out)
y.append(label)
x = nd.concat(*x,dim=0)
y = nd.concat(*y,dim=0)
print('保存特征 %s' % name)
nd.save(name,[x,y])
SaveNd(train_data,net,'train.nd')
SaveNd(valid_data,net,'valid.nd')
SaveNd(train_valid_data,net,'input.nd')
ids = ids = sorted(os.listdir(os.path.join(data_dir, input_dir, 'test/unknown')))
synsets = train_valid_ds.synsets
f = open('ids_synsets','wb')
pickle.dump([ids,synsets],f)
f.close()<file_sep>import datetime
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from mxnet import autograd
from mxnet import gluon
from mxnet.gluon.data import vision
from mxnet import nd
import mxnet as mx
import pickle
from tqdm import tqdm
from model import Net,transform_test
batch_size = 32
data_dir = './data'
test_dir = 'test'
input_dir = 'train_valid_test'
valid_dir = 'valid'
netparams = 'train.params'
csvname = 'kaggle.csv'
ids_synsets_name = 'ids_synsets'
input_str = data_dir + '/' + input_dir + '/'
f = open(ids_synsets_name,'rb')
ids_synsets = pickle.load(f)
f.close()
test_ds = vision.ImageFolderDataset(input_str + test_dir, flag=1,
transform=transform_test)
valid_ds = vision.ImageFolderDataset(input_str + valid_dir, flag=1,
transform=transform_test)
loader = gluon.data.DataLoader
test_data = loader(test_ds, batch_size, shuffle=False, last_batch='keep')
valid_data = loader(valid_ds, batch_size, shuffle=True, last_batch='keep')
def get_loss(data, net, ctx):
loss = 0.0
for feas1,feas2, label in tqdm(data):
label = label.as_in_context(ctx)
feas1 = feas1.as_in_context(ctx)
feas2 = feas2.as_in_context(ctx)
output = net(feas1,feas2)
cross_entropy = softmax_cross_entropy(output, label)
loss += nd.mean(cross_entropy).asscalar()
return loss / len(data)
def SaveTest(test_data,net,ctx,name,ids,synsets):
outputs = []
for data1,data2, label in tqdm(test_data):
data1 =data1.as_in_context(ctx)
data2 =data2.as_in_context(ctx)
output = nd.softmax(net(data1,data2))
outputs.extend(output.asnumpy())
with open(name, 'w') as f:
f.write('id,' + ','.join(synsets) + '\n')
for i, output in zip(ids, outputs):
f.write(i.split('.')[0] + ',' + ','.join(
[str(num) for num in output]) + '\n')
net = Net(mx.gpu(),netparams).net
#net = get_net(netparams,mx.gpu())
net.hybridize()
softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss()
print(get_loss(valid_data,net,mx.gpu()))
SaveTest(test_data,net,mx.gpu(),csvname,ids_synsets[0],ids_synsets[1])
<file_sep>import datetime
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from mxnet import autograd
from mxnet import gluon
from mxnet import nd
import mxnet as mx
import pickle
from model import Net
train_nd = nd.load('train.nd')
valid_nd = nd.load('valid.nd')
input_nd = nd.load('input.nd')
f = open('ids_synsets','rb')
ids_synsets = pickle.load(f)
f.close()
num_epochs = 100
batch_size = 128
learning_rate = 1e-4
weight_decay = 1e-4
pngname='train.png'
modelparams='train.params'
train_data = gluon.data.DataLoader(gluon.data.ArrayDataset(train_nd[0],train_nd[1]), batch_size=batch_size,shuffle=True)
valid_data = gluon.data.DataLoader(gluon.data.ArrayDataset(valid_nd[0],valid_nd[1]), batch_size=batch_size,shuffle=True)
input_data = gluon.data.DataLoader(gluon.data.ArrayDataset(input_nd[0],input_nd[1]), batch_size=batch_size,shuffle=True)
def get_loss(data, net, ctx):
loss = 0.0
for feas, label in data:
label = label.as_in_context(ctx)
output = net(feas.as_in_context(ctx))
cross_entropy = softmax_cross_entropy(output, label)
loss += nd.mean(cross_entropy).asscalar()
return loss / len(data)
softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss()
def train(net, train_data, valid_data, num_epochs, lr, wd, ctx):
trainer = gluon.Trainer(
net.collect_params(), 'adam', {'learning_rate': lr, 'wd': wd})
train_loss = []
if valid_data is not None:
test_loss = []
prev_time = datetime.datetime.now()
for epoch in range(num_epochs):
_loss = 0.
for data, label in train_data:
label = label.as_in_context(ctx)
with autograd.record():
output = net(data.as_in_context(ctx))
loss = softmax_cross_entropy(output, label)
loss.backward()
trainer.step(batch_size)
_loss += nd.mean(loss).asscalar()
cur_time = datetime.datetime.now()
h, remainder = divmod((cur_time - prev_time).seconds, 3600)
m, s = divmod(remainder, 60)
time_str = "Time %02d:%02d:%02d" % (h, m, s)
__loss = _loss/len(train_data)
train_loss.append(__loss)
if valid_data is not None:
valid_loss = get_loss(valid_data, net, ctx)
epoch_str = ("Epoch %d. Train loss: %f, Valid loss %f, "
% (epoch,__loss , valid_loss))
test_loss.append(valid_loss)
else:
epoch_str = ("Epoch %d. Train loss: %f, "
% (epoch, __loss))
prev_time = cur_time
print(epoch_str + time_str + ', lr ' + str(trainer.learning_rate))
plt.plot(train_loss, 'r')
if valid_data is not None:
plt.plot(test_loss, 'g')
plt.legend(['Train_Loss', 'Test_Loss'], loc=2)
plt.savefig(pngname, dpi=1000)
net.collect_params().save(modelparams)
ctx = mx.gpu()
net = Net(ctx).output
net.hybridize()
train(net, train_data,valid_data, num_epochs, learning_rate, weight_decay, ctx)
|
5efc4f98992f6094207d0906d6f2817c46397e52
|
[
"Python"
] | 4 |
Python
|
LeeYongchao/Dog-Breed-Identification-Gluon
|
55b2fdf3ae5bcfcfcf047428a0082335121240fd
|
f850ee8125aeebcf225f84fc6afcdb6220474227
|
refs/heads/master
|
<file_sep>#include <stdio.h>
int main() {
int a = 1;
int b = 2;
int c = 3;
int d = 5;
return 0;
}
|
62622cfb395fe866641c483c7544db66d1d7a169
|
[
"C"
] | 1 |
C
|
gabeo8/hoc-git
|
eee5ddd0af4fb7c5bf51ebde7eb72241edcda8cb
|
c41ca80538cce5aa1c690d12f4ba7a5d02d47da0
|
refs/heads/master
|
<repo_name>weitinglin/WakeyInRasPi<file_sep>/killmusic.sh
#!/bin/sh
job=$( ps -C omxplayer |tail -n 1 | cut -d " " -f 2 )
job2=$( ps -C omxplayer.bin |tail -n 1 | cut -d " " -f 2 )
echo ${job}
kill -15 ${job}
kill -16 ${job2}
<file_sep>/SetAction.sh
#!/bin/sh
#file save date
#DateDownload=$(ls -l wav/ | cut -d ' ' -f 13 | tail -n1)
#Hour=$(echo ${DateDownload}| cut -d ":" -f 1)
#Min=$(echo ${DateDownload}| cut -d ":" -f 2)
#HourPlus=0
#MinPlus=2
#echo ${Hour}+${HourPlus} |bc
#echo ${Min}+${MinPlus} |bc
#file name
dir="/home/pi/test/version1/Wakey_shell"
n=$(ls -l wav/*.wav |sed 's/ */ /g' |cut -d ' ' -f 9 | wc -l)
k=$(echo ${n}+1|bc)
echo "" > tempSoundlist.txt
#rm tempSoundlist-e.txt
for item in $(ls -hl wav/*.wav |sed 's/ */ /g'|cut -d " " -f 9|cut -d '/' -f 2)
do
echo omxplayer ${dir}/wav/${item}
echo omxplayer ${dir}/wav/${item} >> ${dir}/tempSoundlist.txt
done
for a in $(seq "$k")
do
touch ${dir}/SetPlay${a}.sh
echo \#\!\/bin\/sh >> ${dir}/SetPlay${a}.sh
cat ${dir}/tempSoundlist.txt| head -n ${a}| tail -n 1 >> ${dir}/SetPlay${a}.sh
sh ${dir}/SetPlay${a}.sh
# rm ${dir}/SetPlay${a}.sh
done
#at -f SetPlay.sh
#save the last time playlist
#cp tempSoundlist.txt tempSoundlist-e.txt
#remove the playlist
#echo "" > tempSoundlist.txt
#remove the wav after playing
#rm wav/*.wav
<file_sep>/getMySQLrealTime.sh
#!/bin/sh
#echo $1
#echo $2
userID="0"
date=$(date "+%Y%m%d")
#userID 1 date 20160329
#modify the userID
sed -i -e '2s/[[:digit:]][[:digit:]]*/'$userID'/g' getMySQLrealTimeTalk.php
#cat practice.txt > getMySQLrealTimeTalk.php
#modify the date
sed -i -e '3s/[[:digit:]][[:digit:]]*/'$date'/g' getMySQLrealTimeTalk.php
#modify the userID in updateMySql
sed -i -e '2s/[[:digit:]][[:digit:]]*/'$userID'/g' getMySQLrealTimeMusic.php
#cat practice.txt > getMySQLrealTimeTalk.php
#modify the date in updateMySql
sed -i -e '3s/[[:digit:]][[:digit:]]*/'$date'/g' getMySQLrealTimeMusic.php
sed -i -e '2s/[[:digit:]][[:digit:]]*/'$userID'/g' getMySQLrealTimeMotion.php
#cat practice.txt > getMySQLrealTimeTalk.php
#modify the date in updateMySql
sed -i -e '3s/[[:digit:]][[:digit:]]*/'$date'/g' getMySQLrealTimeMotion.php
#php -f getMySQLrealTimeTalk.php
#php updateMySQLrealTimeTalk.php
<file_sep>/eventType06/event/020160414224029224519.sh
#!/bin/sh
omxplayer ./eventType06/event/recording/020160414224029224519.wav
<file_sep>/eventType06/event/020160414224029224518.sh
#!/bin/sh
omxplayer eventType06/event/wav/020160414224029224518.wav
<file_sep>/eventType04/event/020160414224025224323.sh
#!/bin/sh
omxplayer ./Music/music27.mp3
<file_sep>/eventType03/event/020160414221459224207.sh
#!/bin/sh
omxplayer eventType03/event/wav/020160414221459224207.wav
<file_sep>/getMySQLreact.sh
#!/bin/sh
#echo $1
#echo $2
userID="0"
scheduleID=$(date "+%Y%m%d")
#echo ${scheduleID}
#userID 1 date 20160329
#modify the userID
sed -i -e '2s/[[:digit:]][[:digit:]]*/'$userID'/g' getMySQLreactMusic.php
#cat practice.txt > getMySQLrealTimeTalk.php
#modify the date
sed -i -e '3s/[[:digit:]][[:digit:]]*/'$scheduleID'/g' getMySQLreactMusic.php
#modify the userID
sed -i -e '2s/[[:digit:]][[:digit:]]*/'$userID'/g' getMySQLreactText.php
#cat practice.txt > getMySQLrealTimeTalk.php
#modify the date
sed -i -e '3s/[[:digit:]][[:digit:]]*/'$scheduleID'/g' getMySQLreactText.php
sed -i -e '2s/[[:digit:]][[:digit:]]*/'$userID'/g' getMySQLreactRecording.php
#cat practice.txt > getMySQLrealTimeTalk.php
#modify the date
sed -i -e '3s/[[:digit:]][[:digit:]]*/'$scheduleID'/g' getMySQLreactRecording.php
#print the list
#php getMySQLevent.php
#update the database
#php updateMySQLevent.php
#php
<file_sep>/eventType02/event/020160414224023224251.sh
#!/bin/sh
omxplayer eventType02/event/wav/020160414224023224251.wav
<file_sep>/DailySetMusicAction.sh
#!/bin/sh
#weitinglin
###################################################################################################
#Name: DailySetAction.sh
#Function:pending the file list in Dailywav/ and make a action code with file path output into DailytempSoundlist
# generate the play shell scripts into SetPlay/
##################################################################################################
dir="/home/pi/test/version1/Wakey_shell"
n=$( wc -l Dailymusic.txt | cut -d " " -f 1)
k=$(echo ${n})
echo "" > ${dir}/DailytempMusic.txt
#rm tempSoundlist-e.txt
for item in $(cut -d " " -f 9 Dailymusic.txt)
do
echo omxplayer ${dir}/Music/music${item}.mp3
echo omxplayer ${dir}/Music/music${item}.mp3 >> ${dir}/DailytempMusic.txt
done
sed '1d' DailytempMusic.txt > tDailytempMusic.txt
rm DailytempMusic.txt
mv tDailytempMusic.txt DailytempMusic.txt
for a in $(seq "$k")
do
touch ${dir}/SetMusic/DailySetPlay${a}.sh
echo \#\!\/bin\/sh >> ${dir}/SetMusic/DailySetPlay${a}.sh
cat ${dir}/DailytempMusic.txt| head -n ${a}| tail -n 1 >> ${dir}/SetMusic/DailySetPlay${a}.sh
if [ $a = $k ]
then
echo rm ${dir}/SetMusic/*.sh >> ${dir}/SetMusic/DailySetPlay${a}.sh
fi
done
<file_sep>/eventType03/event/020160414221459224206.sh
#!/bin/sh
omxplayer ./eventType03/event/recording/020160414221459224206.wav
<file_sep>/README.md
#WakeyInRasPi
The purpose of the project is to create a toy which can help the parent
to remind the child what should do in the morning. And parent can setting
the toy in the night, discussing with their child when should wake up, want
to awake by which lovely song.
=====
##Project of the Smart Aging Alliance Course
* **Realtime Text to Speech with the API of ITRI**
- Control.sh
- execute all the component
- getMySQLrealTime.sh
- getMySQLrealTImeTalk.php
- getTextToApi.sh
- getwav.sh
- index.php
- SetAction.sh
* **Daily morning text to speech reminder**
- DailyControl.sh
- DailygetTextToApi.sh
- Dailygetwav.sh
- index.php
- DailySetAction.sh
- DailySetTime.sh
* **Daily morning music**
- getMySQLmusic.php
- DailySetMusicAction.sh
- DailySetMusicTime.sh
<file_sep>/DailySetAction.sh
#!/bin/sh
#weitinglin
###################################################################################################
#Name: DailySetAction.sh
#Function:pending the file list in Dailywav/ and make a action code with file path output into DailytempSoundlist
# generate the play shell scripts into SetPlay/
##################################################################################################
dir="/home/pi/test/version1/Wakey_shell"
n=$(ls -l Dailywav/*.wav |sed 's/ */ /g' |cut -d ' ' -f 9 | wc -l)
k=$(echo ${n})
echo "" > DailytempSoundlist.txt
#rm tempSoundlist-e.txt
for item in $(ls -hl Dailywav/*.wav |sed 's/ */ /g'|cut -d " " -f 9|cut -d '/' -f 2)
do
echo omxplayer ${dir}/Dailywav/${item}
echo omxplayer ${dir}/Dailywav/${item} >> ${dir}/DailytempSoundlist.txt
done
sed '1d' DailytempSoundlist.txt > tDailytempSoundlist.txt
rm DailytempSoundlist.txt
mv tDailytempSoundlist.txt DailytempSoundlist.txt
for a in $(seq "$k")
do
touch ${dir}/SetPlay/DailySetPlay${a}.sh
echo \#\!\/bin\/sh >> ${dir}/SetPlay/DailySetPlay${a}.sh
cat ${dir}/DailytempSoundlist.txt| head -n ${a}| tail -n 1 >> ${dir}/SetPlay/DailySetPlay${a}.sh
cat ${dir}/DailytempSoundlist.txt| head -n ${a}| tail -n 1 >> ${dir}/SetPlay/DailySetPlay${a}.sh
sed -i -e '3s/omxplayer/rm/g' ${dir}/SetPlay/DailySetPlay${a}.sh
done
<file_sep>/getMySQLreactControl.sh
#!/bin/sh
php getMySQLreactMusic.php
php getMySQLreactText.php
php getMySQLreactRecording.php
<file_sep>/DailySetMusicTime.sh
#!/bin/sh
#weitinglin
###################################################################################3
#Name: DailySetTIme.sh
#Function: throw the shell file with at command according to the DailytempACtionDate.txt
##################################################################################
n=$(wc -l Dailymusic.txt|cut -d ' ' -f 1)
cut -d " " -f 11-12 Dailymusic.txt|sed 's/\([0-9][0-9]*\)\( \)\([0-9][0-9]*\)/\1\3 /g'|sed 's/^..//' > DailytempMusicTime.txt
for a in $(seq "$n")
do
#echo $(head -n $a DailytempMusicTime.txt| tail -n 1) |xargs echo at -f SetMusic/DailySetPlay${a}.sh -t
echo $(head -n $a DailytempMusicTime.txt| tail -n 1) | xargs at -f SetMusic/DailySetPlay${a}.sh -t
done
#reference for the at command
#date +"%Y %m %d %H %M"
#at -f SetAction.sh -t 1604040807
<file_sep>/DailyControl.sh
#!/bin/sh
php -f getMySQLevent.php > Dailytext.txt;
sh DailygetTextToApi.sh;
sh DailySetAction.sh;
sh DailySetTime.sh
<file_sep>/SetTime.sh
#!/bin/sh
at -f SetTime.sh
#date +"%Y %m %d %H %M"
#at -f SetAction.sh -t 1604040807
<file_sep>/eventType03/event/020160414221459224205.sh
#!/bin/sh
omxplayer ./Music/music19.mp3
<file_sep>/test.sh
#!/bin/sh
echo "test at function"
<file_sep>/eventType02/event/020160414224023224250.sh
#!/bin/sh
omxplayer ./eventType02/event/recording/020160414224023224250.wav
<file_sep>/eventType06/event/020160414224029224516.sh
#!/bin/sh
omxplayer ./Music/music5.mp3
<file_sep>/eventType01/event/settime.sh
#!/bin/sh
pwd
sh event/020160414221423224047.sh
rm event/020160414221423224047.sh
pwd
sh event/020160414221423224049.sh
rm event/020160414221423224049.sh
pwd
sh event/020160414221423224058.sh
rm event/020160414221423224058.sh
<file_sep>/eventType02/event/020160414224023224248.sh
#!/bin/sh
omxplayer ./Music/music10.mp3
|
8e04bd4190df85b1e5b4133e6f5ed9c1122a9022
|
[
"Markdown",
"Shell"
] | 23 |
Shell
|
weitinglin/WakeyInRasPi
|
f44b04c6b10d90758379497ce7a3e729df90e809
|
85da6ddc5f4cfd6cbccb7ff48b1000a65b0eeb39
|
refs/heads/master
|
<file_sep>package com.asusoftware.wechat.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* we-chat Created by Antonio on 3/16/2021
*/
@Getter
@Setter
@ToString
public class Message {
private String message;
private String fromLogin;
}
|
652680bee92c1c616636bfac171504b3b5d3b220
|
[
"Java"
] | 1 |
Java
|
AsuSoftware/We-Chat
|
707f8eb853c45d119019e4f6f78214d41743dfb5
|
4def0625dd805dd5727b293e149e001382362802
|
refs/heads/master
|
<repo_name>nonlining/DS.Capstone<file_sep>/SplitDataToFiles.R
WD <- getwd()
if (!is.null(WD)) setwd(WD)
smallData = FALSE
set.seed(1000)
sampleRatio <- 0.6
if(smallData){
sampleRatio=.020
}
conTwitter <- file("k://final//en_US//en_US.twitter.txt", "r")
length <- length(dataTwitter <- readLines(conTwitter, encoding="UTF-8", warn = FALSE))
while (length > 0) {
sampleData1 <- sample(dataTwitter,length*sampleRatio)
if(smallData){
write(sampleData1,"D:\\Dropbox\\Coursera\\Data Science\\10_Capstone\\DataSet\\SamllDataSetTwiiter.txt",append=TRUE)
} else {
write(sampleData1,"D:\\Dropbox\\Coursera\\Data Science\\10_Capstone\\BigDataSet\\DataSetTwiiter.txt",append=TRUE)
}
length <- length(dataTwitter <- readLines(conTwitter, encoding="UTF-8", warn = FALSE))
}
conUSBlogs <- file("k://final//en_US//en_US.blogs.txt", "r")
length <- length(dataUSBlogs <- readLines(conUSBlogs, encoding="UTF-8" , warn = FALSE))
while (length> 0) {
sampleData1 <- sample(dataUSBlogs,length*sampleRatio)
if(smallData){
write(sampleData1,"D:\\Dropbox\\Coursera\\Data Science\\10_Capstone\\DataSet\\SamllDataSetBlog.txt",append=TRUE)
} else {
write(sampleData1,"D:\\Dropbox\\Coursera\\Data Science\\10_Capstone\\BigDataSet\\DataSetBlog.txt",append=TRUE)
}
length <- length(dataUSBlogs <- readLines(conUSBlogs, encoding="UTF-8", warn = FALSE))
}
conUSNews <- file("k://final//en_US//en_US.news.txt", "r")
length<- length(dataUSNews <- readLines(conUSNews, encoding="UTF-8", warn = FALSE))
while (length> 0) {
sampleData1 <- sample(dataUSNews,length*sampleRatio)
if(smallData){
write(sampleData1,"D:\\Dropbox\\Coursera\\Data Science\\10_Capstone\\DataSet\\SamllDataSetUSNews.txt",append=TRUE)
} else {
write(sampleData1,"D:\\Dropbox\\Coursera\\Data Science\\10_Capstone\\BigDataSet\\DataSetUSNews.txt",append=TRUE)
}
length<- length(dataUSNews <- readLines(conUSNews, encoding="UTF-8", warn = FALSE))
}
close(conUSNews)
close(conUSBlogs)
close(conTwitter)
<file_sep>/ShinyApp/ui.R
library(shiny)
boxstyle <- "border: 1px solid;box-shadow: 1px 1px 1px #FF0000;"
shinyUI(fluidPage(
titlePanel("Data Science Project"),
mainPanel(
textInput("inputText", "A text box:(must press space key to predict the next word)", width = '100%'),
br(),
div(textOutput("inputText"), style=boxstyle),
br(),
h2("Functionalities:"),
p("1. Predict Next Word (must press space key to predict the next word)"),
p("2. Predict word with incomplete string"),
p("3. Using local data to train model (it will save unigram , bigram and trigram temporarily, after closing the windows all models will be disappeared)"),
p("Source code: https://github.com/nonlining/DS.Capstone ")
)
))<file_sep>/README.md
# Data Science Capstone Project
This is Data Science Capstone Project.
This repo will include my R files and Python files.
## Shiny App url:
https://nonlining.shinyapps.io/ShinyApp/
<file_sep>/ShinyApp/server.R
# Data Science Project Shiny APP
# <NAME>
library(shiny)
library(datasets)
library(stringi)
# load library files for this project
source("CapstoneProjectlib.R")
datadir <- "."
load(file=paste(datadir, "DataUnigram.data", sep="/"), verbose=T)
load(file=paste(datadir, "DataBigram.data", sep="/"), verbose=T)
load(file=paste(datadir, "DataTrigram.data", sep="/"), verbose=T)
# local unigram bigram ,and trigram for online training data
local_Unigram <- data.frame(terms=character(),
counts=as.integer(character()),
stringsAsFactors=FALSE)
local_Bigram <- data.frame(terms=character(),
counts=as.integer(character()),
end=character(),
stringsAsFactors=FALSE)
local_Trigram <- data.frame(terms=character(),
counts=as.integer(character()),
end=character(),
stringsAsFactors=FALSE)
t_unigram <- trained_unigram
t_bigram <- trained_bigram
t_trigram <- trained_trigram
trim.leading <- function (x) sub("^\\s+", "", x)
myTolower <- function(x) stri_trans_tolower(x, "en_US")
getPrediction <-function(string, df1, df2, df3 ,tolower=T){
if(tolower){
string <- myTolower(string)
}
if(substr(string, nchar(string),nchar(string)) == " "){
reverse <- rev(strsplit(string, split=" ")[[1]])
if(!is.na(reverse[2])){
biString = paste(reverse[2],reverse[1], sep =" ")
}
if(!is.na(reverse[3])){
triString = paste(reverse[3], paste(reverse[2],reverse[1], sep =" "), sep =" ")
}
# function to predict next word
res <- PredictnextWord(string, df1, df2, df3, local_Unigram, local_Bigram, local_Trigram)
# online data save to local file
# for unigram -------------------------------------------------------------
if(sum(local_Unigram$terms == reverse[1]) != 0){
local_Unigram[local_Unigram$terms == reverse[1], ]$counts <<- 1 + local_Unigram[local_Unigram$terms == reverse[1], ]$counts
} else {
newRow <- data.frame(terms=reverse[1],counts = 1)
local_Unigram <<- rbind(local_Unigram, newRow)
}
# for bigram --------------------------------------------------------------
if(!is.na(reverse[2])){
if(sum(local_Bigram$terms == biString) != 0){
local_Bigram[local_Bigram$terms == biString, ]$counts <<- 1 + local_Bigram[local_Bigram$terms == biString, ]$counts
} else {
newRow <- data.frame(terms=biString,counts = 1, end = reverse[1])
local_Bigram <<- rbind(local_Bigram, newRow)
}
}
# for trigram -------------------------------------------------------------
if(!is.na(reverse[3])){
if(sum(local_Trigram$terms == triString) != 0){
local_Trigram[local_Trigram$terms == triString, ]$counts <<- 1 + local_Trigram[local_Trigram$terms == triString, ]$counts
} else {
newRow <- data.frame(terms=triString,counts = 1, end = reverse[1])
local_Trigram <<- rbind(local_Trigram, newRow)
}
}
return(res)
}else if (string == ""){
return ("")
}else {
# incompleted string to predict word
res <- PredictWord(string, trained_unigram)
return(res)
}
}
# Define server logic required to summarize and view the selected
# dataset
shinyServer(function(input, output, session) {
updateString <- function(val) updateTextInput(session, "inputText", value = val)
output$inputText <- renderText({
res <- getPrediction(input$inputText, t_unigram, t_bigram, t_trigram, tolower=T)
res <- paste(res, collapse=" , ")
paste0(" ", res)
})
})<file_sep>/DataScienceCapstone.py
#-------------------------------------------------------------------------------
# Name: NLP projects
# Purpose:
#
# Author: Nonlining
#
# Created: 04/12/2016
# Copyright: (c) Nonlining 2016
# Licence: <your licence>
#-------------------------------------------------------------------------------
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
stopwords = []
stopwordFectbit = 1
def ngram(df, n, col):
global stopwordFectbit
global stopwords
word_vectorizer = CountVectorizer(ngram_range=(n,n), analyzer='word', stop_words= 'english')
sparse_matrix = word_vectorizer.fit_transform(df[col])
if stopwordFectbit:
stopwords = word_vectorizer.get_stop_words()
stopwordFectbit = 0
print stopwords
frequencies = sum(sparse_matrix).toarray()[0]
ngram = pd.DataFrame(frequencies, index=word_vectorizer.get_feature_names(), columns=['frequency'])
return ngram
def loadfile(filelist , features, size):
dataframelist = []
for i in filelist:
print 'load file' , i
dataframelist.append(pd.read_table(i, header = None, encoding = 'utf-8'))
dataframelist[-1].columns = [features]
weblines = dataframelist[0]
if len(dataframelist) > 1:
weblines = weblines.append(dataframelist[1:])#, newslines, how = 'outer')
np.random.seed(47)
s = np.random.choice(weblines.index, size, replace = False)
sampleBlogDF =weblines.ix[s]
return sampleBlogDF
def ngramModel(data, features):
unigram = ngram(data, 1, 'description')
unigram['string'] = unigram.index
unigram = unigram[unigram.string.str.contains('^[a-zA-Z]+$')]
#unigram = unigram[unigram['frequency'] > 1]
unigram.sort(columns = 'frequency',ascending = False ,inplace = True)
bigram = ngram(data, 2, 'description')
bigram['string'] = bigram.index
bigram = bigram[bigram.string.str.contains('^[a-zA-Z]+ +[a-zA-Z]+$')]
bigram.sort(columns = 'frequency',ascending = False ,inplace = True)
trigram = ngram(data, 3, 'description')
trigram['string'] = trigram.index
trigram = trigram[trigram.string.str.contains('^[a-zA-Z]+ [a-zA-Z]+ [a-zA-Z]+$')]
trigram.sort(columns = 'frequency',ascending = False ,inplace = True)
print len(unigram), len(bigram),len(trigram)
return [unigram, bigram, trigram]
def StrPredict(s1, strlist, models):
unigramModel = models[0]
twogramModel = models[1]
threegramModel = models[2]
preTwo = s1.split(' ')[-1]
preThree = s1.split(' ')[-2:]
preThree = ' '.join(preThree)
for i in strlist:
p1 = 0
p2 = 0
p3 = 0
if sum(unigramModel['string'] == i) > 0 :
p1 = unigramModel[unigramModel['string'] == i]['frequency']/float(unigramModel['frequency'].sum())
print (preTwo +' ' +i)
if sum(twogramModel['string'] == (preTwo +' ' +i)) > 0 :
p2 = twogramModel[twogramModel['string'] == (preTwo +' ' +i)]['frequency']/float(twogramModel['frequency'].sum())
print (preThree +' ' +i)
if sum(threegramModel['string'] == (preThree +' ' +i)) > 0 :
p3 = threegramModel[threegramModel['string'] == (preThree +' ' +i)]['frequency']/float(threegramModel['frequency'].sum())
print i, p1, p2 ,p3
def StrPredict(st, anslist, models):
unigram = models[0]
bigram = models[1]
trigram = models[2]
def Week3():
filelist = ["K:\\final\\en_US\\en_US.blogs.txt","K:\\final\\en_US\\en_US.news.txt","K:\\final\\en_US\\en_US.twitter.txt" ]
ngramslist = loadfile(filelist,'description', 5000)
Q1 = " ==>The guy in front of me just bought a pound of bacon, a bouquet, and a case of"
print Q1
Option1 = ['cheese', 'beer','soda','pretzels']
StrPredict(Q1, Option1, ngramslist)
Q2 = " ==>You're the reason why I smile everyday. Can you follow me please? It would mean the"
print Q2
Option2 = ['world', 'universe','best','most']
StrPredict(Q2, Option2, ngramslist)
Q3 = " ==>Hey sunshine, can you follow me and make me the"
print Q3
Option3 = ['happiest', 'smellest','saddest','bluest']
StrPredict(Q3, Option3, ngramslist)
Q4 = " ==>Very early observations on the Bills game: Offense still struggling but the"
print Q4
Option4 = ['crowd', 'players','referees','defense']
StrPredict(Q4, Option4, ngramslist)
Q5 = " ==>Go on a romantic date at the"
print Q5
Option5 = ['beach', 'mall','movies','grocery']
StrPredict(Q5, Option5, ngramslist)
Q6 = " ==>Well I'm pretty sure my granny has some old bagpipes in her garage I'll dust them off and be on my"
print Q6
Option6 = ['horse', 'phone','motorcycle','way']
StrPredict(Q6, Option6, ngramslist)
Q7 = " ==>Ohhhhh #PointBreak is on tomorrow. Love that film and haven't seen it in quite some"
print Q7
Option7 = ['thing', 'weeks','time','years']
StrPredict(Q7, Option7, ngramslist)
Q8 = " ==>After the ice bucket challenge Louis will push his long wet hair out of his eyes with his little"
print Q8
Option8 = ['fingers', 'eyes','toes','ears']
StrPredict(Q8, Option8, ngramslist)
Q9 = " ==>Be grateful for the good times and keep the faith during the"
print Q9
Option9 = ['hard', 'bad','sad','worse']
StrPredict(Q9, Option9, ngramslist)
Q10 = " ==>If this isn't the cutest thing you've ever seen, then you must be"
print Q10
Option10 = ['insane', 'insensitive','callous','asleep']
StrPredict(Q10, Option10, ngramslist)
def validationModel(testData, ngramslist, lamda):
print lamda
unigram = ngramslist[0]
bigram = ngramslist[1]
trigram = ngramslist[2]
hitCount = 0
totalData = len(testData)
for i in testData:
words = i.split(' ')
if len(trigram[trigram.string.str.contains('^'+words[0]+' '+words[1]+' .')]) > 0:
d = trigram[trigram.string.str.contains('^'+words[0]+' '+words[1]+' .')]['frequency'].sum()
#d = int(bigram.ix[words[0]+' '+words[1]]['frequency'])
best3string = trigram[trigram.string.str.contains('^'+words[0]+' '+words[1]+' .')].head(3)['string']
best3stringCount = trigram[trigram.string.str.contains('^'+words[0]+' '+words[1]+' .')].head(3)['frequency']
maxWord2 = None
maxWord2P = 0
for k in range(len(best3string)):
word2 = best3string[k].split(' ')
d2 = int(bigram.ix[word2[1]+' '+word2[2]]['frequency'])
singleWordcount = 0
if sum(unigram['string']== word2[2]) > 0:
singleWordcount = int(unigram[unigram['string']== word2[2]]['frequency'])
p = lamda[0]*singleWordcount/float(len(unigram)) + lamda[1]*d2/float(singleWordcount) + lamda[2]*best3stringCount[k]/float(d)
if p > maxWord2P:
maxWord2P = p
maxWord2 = word2[2]
if maxWord2 == words[2]:
print maxWord2
hitCount = hitCount + 1
return hitCount/float(totalData)
def LinearInter_trainData():
filelist = ["K:\\final\\en_US\\en_US.blogs.txt","K:\\final\\en_US\\en_US.news.txt","K:\\final\\en_US\\en_US.twitter.txt" ]
data = loadfile(filelist,'description', 10000)
print len(data)
msk = np.random.rand(len(data)) < 0.8
train = data[msk]
print 'train set ', len(train)
test = data[~msk]
print 'test set ', len(test)
ngramslist = ngramModel(train, 'description')
testData = ngram(test, 3, 'description')
testData['string'] = testData.index
testData = testData[testData.string.str.contains('^[a-zA-Z]+ [a-zA-Z]+ [a-zA-Z]+$')]
testData = list(testData.index)
v1 = validationModel(testData, ngramslist, lamda = [.5, .3 , .2])
v2 = validationModel(testData, ngramslist, lamda = [.6, .3 , .1])
v3 = validationModel(testData, ngramslist, lamda = [.4, .3 , .3])
v4 = validationModel(testData, ngramslist, lamda = [.33, .33 ,.33])
v5 = validationModel(testData, ngramslist, lamda = [.3, .3 , .4])
v6 = validationModel(testData, ngramslist, lamda = [.2, .3 , .5])
v7 = validationModel(testData, ngramslist, lamda = [.1, .3 , .6])
print v1, v2, v3, v4, v5, v6, v7
# 0.00489059556586 0.00481814229822 0.00489059556586 0.00489059556586 0.00489059556586 0.00485436893204 0.00489059556586
# 0.00464522122866 0.00460651105176 0.00468393140557 0.00468393140557 0.00468393140557 0.00464522122866 0.00468393140557
# 0.00909995132584 0.00899413793833 0.00912111400334 0.00914227668085 0.00914227668085 0.00914227668085 0.00914227668085 (10000 size)
def KatzBOO(ngrams, discounts, words, tp = 5):
unigram = ngrams[0]
bigram = ngrams[1]
trigram = ngrams[2]
totoalUnigramSum = unigram['frequency'].sum()
bigramsDiscount = discounts[0]
trigramDiscount = discounts[1]
resultAll = unigram.head(10)
result_bigram = bigram[bigram.string.str.contains('^'+words[1]+' .')]
result_trigram = trigram[trigram.string.str.contains('^'+words[0]+' '+words[1]+' .')]
bigram_a = 1.
trigram_a = 1.
if len(result_bigram) > 0:
totalBigramSum = result_bigram['frequency'].sum()
bigram_a = bigramsDiscount*len(result_bigram)/float(result_bigram['frequency'].sum())
resultAll['frequency'] = resultAll['frequency']*bigram_a/totoalUnigramSum
result_bigram['frequency'] = (result_bigram['frequency'] - bigramsDiscount)/totalBigramSum
result_bigram.index = [i.split(' ')[1] for i in list(result_bigram.index)]
#print result_bigram
resultAll = resultAll.append(result_bigram)
if len(result_trigram) > 0:
totalTrigramSum = result_trigram['frequency'].sum()
trigram_a = trigramDiscount*len(result_trigram)/float(result_trigram['frequency'].sum())
resultAll['frequency'] = resultAll['frequency']*trigram_a/resultAll['frequency'].sum()
result_trigram['frequency'] = (result_trigram['frequency'] - trigramDiscount)/totalTrigramSum
result_trigram.index = [i.split(' ')[2] for i in list(result_trigram.index)]
resultAll = resultAll.append(result_trigram)
return resultAll
def Smoothing_trainData():
discounts = [0.5, 0.5]
filelist = ["K:\\final\\en_US\\en_US.blogs.txt","K:\\final\\en_US\\en_US.news.txt","K:\\final\\en_US\\en_US.twitter.txt" ]
data = loadfile(filelist,'description', 5000)
print len(data)
msk = np.random.rand(len(data)) < 0.8
train = data[msk]
print 'train set ', len(train)
test = data[~msk]
print 'test set ', len(test)
ngramslist = ngramModel(train, 'description')
testData = ngram(test, 3, 'description')
testData['string'] = testData.index
testData = testData[testData.string.str.contains('^[a-zA-Z]+ [a-zA-Z]+ [a-zA-Z]+$')]
testData = list(testData.index)
discountList = [[0.2,0.8],[0.3,0.7],[0.4,0.6],[0.5,0.5],[0.6,0.4],[0.7,0.3],[0.8,0.2],[0.3,0.3],[0.4,0.4],[0.6,0.6],[0.7,0.7]]
#discountList = [[0.5 , 0.5]]
# [0.023696877442711976, 0.023696877442711976, 0.023696877442711976, 0.023696877442711976, 0.023696877442711976, 0.023696877442711976, 0.023696877442711976, 0.023696877442711976, 0.023696877442711976, 0.023696877442711976, 0.023696877442711976]
acclist = []
for d in discountList:
hit = 0
print d
for i in testData:
w = i.split(' ')
pred = KatzBOO(ngramslist, discounts, [w[0],w[1]])
pred.sort(columns = 'frequency',ascending = False ,inplace = True)
if len(pred) > 0:
pred_list = list(pred.index)
if w[2] in pred_list[0]:
hit = hit + 1
print i, d , hit/float(len(testData))
acclist.append(hit/float(len(testData)))
print acclist
def PredictNextWord(str, anslist, models, discounts):
trigram = models[2]
bigram = models[1]
unigram = models[0]
str = str.lower()
s1split = str.split(' ')
newStr = []
for s in s1split:
if s not in stopwords:
newStr.append(s)
print newStr
preThree = newStr[-2:]
preThree = ' '.join(preThree)
plist = dict()
totoalUnigramSum = unigram['frequency'].sum()
bigramsDiscount = discounts[0]
trigramDiscount = discounts[1]
for i in anslist:
bigram_a = 1.
trigram_a = 1.
result_unigram = unigram[unigram['string'] == i]
result_bigram = bigram[bigram.string.str.contains('^'+newStr[-1]+' .')]
result_trigram = trigram[trigram.string.str.contains('^'+newStr[-2]+' '+newStr[-1]+' .')]
print newStr[-2]+' '+newStr[-1] +' '+i
if len(result_trigram[result_trigram['string'] == preThree+' '+i]) > 0:
totalTrigramSum = result_trigram['frequency'].sum()
plist[i] = float(result_trigram[result_trigram['string'] == preThree+' '+i]['frequency'] - trigramDiscount)/totalTrigramSum
print "3 " + preThree+' '+i
continue
elif len(result_trigram) > 0:
totalTrigramSum = result_trigram['frequency'].sum()
trigram_a = trigramDiscount*len(result_trigram)/float(result_trigram['frequency'].sum())
if len(result_bigram[result_bigram['string'] == newStr[-1]+' '+i]) > 0:
totalBigramSum = result_bigram['frequency'].sum()
#print result_bigram[result_bigram['string'] == newStr[-1]+' '+i]['frequency']
plist[i] = trigram_a*float(result_bigram[result_bigram['string'] == newStr[-1]+' '+i]['frequency'] - bigramsDiscount)/totalBigramSum
print "2 " + preThree+' '+i
continue
elif len(result_bigram) > 0:
totalBigramSum = result_bigram['frequency'].sum()
bigram_a = bigramsDiscount*len(result_bigram)/float(totalBigramSum)
if len(result_unigram) > 0:
plist[i] = float(bigram_a*trigram_a*result_unigram['frequency'])/totoalUnigramSum
maxValue = 0
maxItem = None
for i in plist:
if plist[i] > maxValue:
maxValue = plist[i]
maxItem = i
print plist
print maxItem, maxValue
def Week4():
discounts = [0.5, 0.5]
filelist = ["K:\\final\\en_US\\en_US.blogs.txt","K:\\final\\en_US\\en_US.news.txt","K:\\final\\en_US\\en_US.twitter.txt" ]
data = loadfile(filelist,'description', 10000)
ngramslist = ngramModel(data, 'description')
discount = [0.5 , 0.5]
Q1 = "When you breathe, I want to be the air for you. I'll be there for you, I'd live and I'd"
A1 = ["sleep" ,"die","eat","give"]
PredictNextWord(Q1, A1, ngramslist, discount)
Q2 = "Guy at my table's wife got up to go to the bathroom and I asked about dessert and he started telling me about his"
A2 = ["financial" ,"horticultural","marital", "spiritual"]
PredictNextWord(Q2, A2, ngramslist, discount)
Q3 = "I'd give anything to see arctic monkeys this"
A3 = ["decade", "weekend" ,"morning" ,"month"]
PredictNextWord(Q3, A3, ngramslist, discount)
Q4 = "Talking to your mom has the same effect as a hug and helps reduce your"
A4 = ["happiness", "sleepiness" ,"stress" ,"hunger"]
PredictNextWord(Q4, A4, ngramslist, discount)
Q5 = "When you were in Holland you were like 1 inch away from me but you hadn't time to take a"
A5 = ["look", "picture" ,"minute" ,"walk"]
PredictNextWord(Q5, A5, ngramslist, discount)
Q6 = "I'd just like all of these questions answered, a presentation of evidence, and a jury to settle the"
A6 = ["matter", "account" ,"case" ,"incident"]
PredictNextWord(Q6, A6, ngramslist, discount)
Q7 = "I can't deal with unsymetrical things. I can't even hold an uneven number of bags of groceries in each"
A7 = ["toe", "finger" ,"arm" ,"hand"]
PredictNextWord(Q7, A7, ngramslist, discount)
Q8 = "Every inch of you is perfect from the bottom to the"
A8 = ["middle", "side" ,"top" ,"center"]
PredictNextWord(Q8, A8, ngramslist, discount)
Q9 = "I'm thankful my childhood was filled with imagination and bruises from playing"
A9 = ["weekly", "outside" ,"daily" ,"inside"]
PredictNextWord(Q9, A9, ngramslist, discount)
Q10 = "I like how the same people are in almost all of <NAME>"
A10 = ["movies", "pictures" ,"stories" ,"novels"]
PredictNextWord(Q10, A10, ngramslist, discount)
if __name__ == '__main__':
Smoothing_trainData()
#LinearInter_trainData()
#Week4()
<file_sep>/ShinyApp/CapstoneProjectlib.R
# Capstone Project
# 12/23/2016
# <NAME>
# lib for Shiny APP
rm(list=ls())
gc()
WD <- getwd()
if (!is.null(WD)) setwd(WD)
options(java.parameters = "- Xmx10240m")
library(tm)
library(RWeka)
DEBUG = FALSE
PredictWord <- function(word, dictionary){
reverse <- rev(strsplit(word, split=" ")[[1]])
word <- reverse[1]
sub = dictionary[ with(dictionary, grepl(paste('^',word, sep =""), terms)),]
temp = sub[order(-sub$counts),]
count = dim(temp)[1]
if (count > 5)
count = 5
res = temp[1:count,]$terms
if(DEBUG) {print(res)}
return(res)
}
PredictnextWord <- function(sentence, df1, df2, df3, local_unigram, local_Bigram, local_Trigram){
reverse <- rev(strsplit(sentence, split=" ")[[1]])
if(length(reverse)==0){
rc <- df1[order(-df1$Pcont),][1:3,]$term
return(rc)
}
second <- reverse[1]
first <- reverse[2]
bigram <- paste(first, second)
if(sum(df3$pre==bigram)!=0 | dim(local_Trigram[with(local_Trigram,grepl(paste('^',bigram, sep =""), terms)),])[1] != 0){
if(DEBUG) {cat("using trigram\n")}
a <- df3[df3$pre==bigram,]
resTemp <- a[order(-a$PKN),][1:10,]
resTemp$p <- 0.4*resTemp$PKN/sum(resTemp[!is.na(resTemp$PKN),]$PKN)
tempTri <-local_Trigram[with(local_Trigram,grepl(paste('^',bigram, sep =""), terms)),]
tempTri$p = 0.6*tempTri$counts/sum(tempTri$counts)
resTemp <- resTemp[keeps <- c("terms", "counts", "p", "end")]
##################### remove duplicated items ###################
r <- intersect(resTemp$end, tempTri$end)
# remove duplicated item between local bigram and global trained bigram
diff <- setdiff(resTemp$end,tempTri$end)
diff2 <- setdiff(tempTri$end, resTemp$end)
rightside <- resTemp[which(resTemp$end %in% r),]
leftside <- tempTri[which(tempTri$end %in% r),]
# leave the bigger proba.
resTempBigger <- rightside[rightside$p > leftside$p,]
tempBiBigger <- leftside[rightside$p < leftside$p,]
resTemp <- rbind(resTemp[which(resTemp$end %in% diff),], tempTri[which(tempTri$end %in% diff),])
resTemp <- rbind(resTemp, tempTri[which(tempTri$end %in% diff2),])
resTemp <- rbind(resTemp, resTempBigger)
resTemp <- rbind(resTemp, tempBiBigger)
##################### remove duplicated items ###################
resTemp <- resTemp[order(-resTemp$p),][1:5,]
if(DEBUG) {print(resTemp)}
rc <- resTemp$end
}else if(sum(df2$start==second)!=0 | dim(local_Bigram[with(local_Bigram,grepl(paste('^',second, sep =""), terms)),])[1] != 0){
if(DEBUG) {cat("using bigram\n")}
a <- df2[df2$start==second,]
resTemp <- a[order(-a$Pcont2),][1:10,]
resTemp$p <- 0.4*resTemp$Pcont2/sum(resTemp[!is.na(resTemp$Pcont2),]$Pcont2)
tempBi <-local_Bigram[with(local_Bigram,grepl(paste('^',second, sep =""), terms)),]
tempBi$p = 0.6*tempBi$counts/sum(tempBi$counts)
resTemp <- resTemp[keeps <- c("terms", "counts", "p", "end")]
##################### remove duplicated items ###################
r <- intersect(resTemp$end, tempBi$end)
# remove duplicated item between local bigram and global trained bigram
diff <- setdiff(resTemp$end,tempBi$end)
diff2 <- setdiff(tempBi$end, resTemp$end)
rightside <- resTemp[which(resTemp$end %in% r),]
leftside <- tempBi[which(tempBi$end %in% r),]
# leave the bigger proba.
resTempBigger <- rightside[rightside$p > leftside$p,]
tempBiBigger <- leftside[rightside$p < leftside$p,]
resTemp <- rbind(resTemp[which(resTemp$end %in% diff),], tempBi[which(tempBi$end %in% diff),])
resTemp <- rbind(resTemp, tempBi[which(tempBi$end %in% diff2),])
resTemp <- rbind(resTemp, resTempBigger)
resTemp <- rbind(resTemp, tempBiBigger)
##################### remove duplicated items ###################
resTemp <- resTemp[order(-resTemp$p),][1:5,]
if(DEBUG) {print(resTemp)}
rc <- resTemp$end
}else{
if(DEBUG) {cat("using unigram\n")}
resTemp <- df1[order(-df1$Pcont),][1:5,]
# using local unigram to recalculate prob.
# I use weight 0.6 to local unigram and 0.4 for unigram that I trained from web data
resTemp$p <- 0.6*resTemp$Pcont/sum(resTemp$Pcont)
local_unigram$p = 0.4*local_unigram$counts/sum(local_unigram$counts)
resTemp <- resTemp[keeps <- c("terms", "counts", "p")]
resTemp <- rbind(resTemp, local_unigram)
resTemp <- resTemp[order(-resTemp$p),][1:5,]
if(DEBUG) {print(resTemp)}
# It can increaing 'the' with more local data
rc <- resTemp$terms
}
# filling out space
# too many 'the'
if(is.na(rc[1])) {
rc <- df1[order(-df1$Pcont),][1:5,]$terms
}else if(is.na(rc[2])){
rc[2:5] <- df1[order(-df1$Pcont),][1:4,]$terms
}else if(is.na(rc[3])){
rc[3:5] <- df1[order(-df1$Pcont),][1:3,]$terms
} else if(is.na(rc[4])){
rc[4:5] <- df1[order(-df1$Pcont),][1:2,]$terms
} else if(is.na(rc[5])){
rc[5] <- df1[order(-df1$Pcont),][1,]$terms
}
return(rc)
}
|
e533ed64c5e7d609b96b46d0a41d07ddb380e42d
|
[
"Markdown",
"Python",
"R"
] | 6 |
R
|
nonlining/DS.Capstone
|
9fca30f2a9b48a690e90ac885a4f9c481aa0d4db
|
568753afca2c6ca36c8cb1ab84d6e0d1fd718720
|
refs/heads/master
|
<repo_name>smacpher/arduino_tuts<file_sep>/README.md
# Ardunio Tutorials
<file_sep>/SpaceshipInterface/SpaceshipInterface.ino
// Instantiate global variables here
// Have to declare a type, then value. End declarations with a semi-colon (;)
int switch_state = 0;
int input_pin = 2;
int ON = 1;
// at compile time, arduino will place all instances of variable with the value
#define MY_SIZE 2
int red_output_pins[MY_SIZE] = {4,5};
int green_output_pin = 3;
void setup() {
// These three output pins are connected to our three LEDs anode legs
for(int x = 0; x < MY_SIZE; x++) {
pinMode(red_output_pins[x], OUTPUT);
}
pinMode(green_output_pin, OUTPUT);
// This input pin is for reading the state of our switch
// A 10k 'pull-down' resistor is connects our switch to ground when the switch is open
// so that the input pin reads LOW when there is no voltage coming through the switch
pinMode(2, INPUT);
}
void loop() {
switch_state = digitalRead(input_pin); // digitalRead returns either 1 (HIGH) or 0 (LOW)
if (switch_state == ON) {
// write green LED to LOW
digitalWrite(green_output_pin, LOW);
// write first red LED to HIGH and second red LED to LOW
digitalWrite(red_output_pins[0], HIGH);
digitalWrite(red_output_pins[1], LOW);
// wait for a quarter of a second
delay(250);
// write second red LED to HIGH and first red LED to LOW
digitalWrite(red_output_pins[0], LOW);
digitalWrite(red_output_pins[1], HIGH);
delay(250);
} else {
// write both red LEDS to LOW
for(int x = 0; x < MY_SIZE; x++) {
digitalWrite(red_output_pins[x], LOW);
}
// write green LED to HIGH
digitalWrite(green_output_pin, HIGH);
}
}
<file_sep>/Love-O-Meter/Love-O-Meter.ino
/*
This sketch takes advantage of arduino's Analog-to-Digital Converter (ADC).
Analog pins A0-A5 can report back a value between 0-1023, which maps to a range from 0 to 5 volts.
Uses a temperature sensor which outputs a changing voltage depending on the temperature it senses
This sensor has three pins -- one that connects to ground, another that connects to power, and
another one that outputs the variable voltage to arduino. There are several different models
of temperature sensors; we are using a TMP36 which outputs voltage directly proportional to
the temperature it senses in Celsius. The order of the pins matters! If the TMP36 is facing
away form you, the right pin should be connected to power, the middle to an Analog input pin, and
the left pin to ground.
A baud rate (commonly set as 9600 for a serial port) is essentially the bits per second configuration. A 'baud'
can represent any amount of bits. For example, if a baud represents 1 bit, and the baud rate is 9600 bauds/second, then
our media is capable of sending up to 9600 bits per second.
Opening the serial monitor: cmd + shift + M
*/
// Define constants (constants cannot change; at compile time, they are converted to their values permanently)
const int sensorPin = A0;
const float baselineTemp = 20.0;
const int output_pins_size = 3;
const int temp_interval = 2;
// Our outputs pins which will be hooked to 3 LEDS
int outputPins [output_pins_size] = {2, 3, 4};
void setup() {
// open up a serial port to log to my PC
Serial.begin(9600); // set the buad rate to 9600 (9600 bits per second)
// set our outputPins to output
for (int pin = 0; pin < output_pins_size; pin++) {
pinMode(outputPins[pin], OUTPUT);
digitalWrite(outputPins[pin], LOW); // start them out as LOW (off)
}
}
void loop() {
int sensorVal = analogRead(sensorPin); // analogRead will return a value between 0 and 1023, representing the voltage on the pin.
// now to log to the Arduino IDE's serial monitor through our serial connection
Serial.print("Sensor Value: ");
Serial.print(sensorVal);
// calculate voltage ( a fraction of the 5V we are running through our TMP36)
float voltage = (sensorVal / 1024.0) * 5.0;
Serial.print(", Volts: ");
Serial.print(voltage);
/*
* Now let's calculate the Celsius from the voltage. The 'datasheet' (manual for electronic components)
* for this particularsensor describes that every 10 milivolts of change from the sensor is equivalent to
* 1 degree Celsius. It also indicates that the sensor can read temperatures below 0 Celsius.
*/
float temperature = (voltage - 0.5) * 100;
Serial.print(" , degrees C: ");
Serial.println(temperature); // println creates a new line after it prints the value.
// check our temperature and adjust our output LEDs accordingly
if (temperature < baselineTemp) {
digitalWrite(outputPins[0], LOW);
digitalWrite(outputPins[1], LOW);
digitalWrite(outputPins[2], LOW);
} else if ((temperature >= baselineTemp + temp_interval) && (temperature < baselineTemp + (2 * temp_interval))) {
digitalWrite(outputPins[0], HIGH);
digitalWrite(outputPins[1], LOW);
digitalWrite(outputPins[2], LOW);
} else if ((temperature >= baselineTemp + (2 * temp_interval)) && (temperature < baselineTemp + (3 * temp_interval))) {
digitalWrite(outputPins[0], HIGH);
digitalWrite(outputPins[1], HIGH);
digitalWrite(outputPins[2], LOW);
} else if (temperature >= baselineTemp + (3 * temp_interval)) {
digitalWrite(outputPins[0], HIGH);
digitalWrite(outputPins[1], HIGH);
digitalWrite(outputPins[2], HIGH);
}
// Give arduino's ADC some time to process
delay(2);
}
<file_sep>/ColorMixingLamp/ColorMixingLamp.ino
/* Arduino cannot vary the output voltage on its pins, it can only output 5V. We will have
* to use a different technique to fade LEDs called Pulse Width Modulation (PWM). PWM
* rapidly turns the output pin high and low over a fixed period of time. The change
* happens faster than the human eye can see so we don't notice it. When we rapidly turn
* the pin from HIGH to LOW and vice versa, it's as if we were changing the voltage.
* The percentage of time a pin is HIGH in a period is called 'duty cycle.' For
* example is HIGH for half of the period and LOW for the other half, the 'duty cycle'
* if 50%. A lower duty cycle gives you a dimmer LED than a higher duty cycle. The arduino
* has six pins set aside for PWM (they are marked by the ~ next to their number on the
* board). Photoresistors change their resistance depending on the amount of light
* that hits them (a.k.a. photocells or light-dependent resistors). You can measur the
* change in resistance by checking the voltage of the pin. We put different colored
* filters over the three photoresistors. These will only let specific wavelengths of light
* in; this way we can detect the relative color levels in the light that hits
* the sensors. A common cathode RGB LED has separate red, green, and blue elements inside,
* and one common ground -- the longest leg is ground, the only leg to the left of the ground leg
* is red, and the other two from left to right are green and blue, respectively.
*/
// set our pins to their respective PWM digital pins
const int redLEDPin = 11;
const int blueLEDPin = 10;
const int greenLEDPin = 9;
// set our sensor pins to their respective analog inputs. NOTE: couldn't find red filter
const int redSensorPin = A0;
const int greenSensorPin = A1;
const int blueSensorPin = A2;
// instantiate variables for the output LED values used to fade the LED
int redValue = 0;
int greenValue = 0;
int blueValue = 0;
// instantiate variables for the input sensor values
int redSensorValue = 0;
int greenSensorValue = 0;
int blueSensorValue = 0;
void setup() {
// enable serial port for monitoring purposes
Serial.begin(9600);
pinMode(greenLEDPin, OUTPUT);
pinMode(redLEDPin, OUTPUT);
pinMode(blueLEDPin, OUTPUT);
}
void loop() {
redSensorValue = analogRead(redSensorPin); // read the sensor value (will be a value between 0 and 1024)
delay(5); // pause while the ADC -- analog to digital converter -- does its work
greenSensorValue = analogRead(greenSensorPin);
delay(5);
blueSensorValue = analogRead(blueSensorPin);
delay(5);
Serial.print("Raw sensor values \t Red: ");
Serial.print(redSensorValue);
Serial.print("\t Green: ");
Serial.print(greenSensorValue);
Serial.print("\t Blue: ");
Serial.println(blueSensorValue);
// convert the sensor readings to values between 0 and 255 for analogWrite() to change LED's brightness via PWM
redValue = redSensorValue / 4.0;
greenValue = greenSensorValue / 4.0;
blueValue = blueSensorValue / 4.0;
// log the new analog values
Serial.print("Mapped sensor values \t RED: ");
Serial.print(redValue);
Serial.print("\t Green: ");
Serial.print(greenValue);
Serial.print("\t Blue: ");
Serial.println(blueValue);
// now write a value to our pins (will be a value between 0 and 255)
// analogWrite takes two args --> the pin to write to, and a value between 0-255
// ex. a value of 127 (duty cycle = 50%) will set the pin HIGH half the time,
// a value of 0 (duty cycle = 0%) would set the pin to LOW all of the time, etc.
analogWrite(redLEDPin, redValue);
analogWrite(greenLEDPin, greenValue);
analogWrite(blueLEDPin, blueValue);
}
|
2428f9eafd2b1bb7b659629b5d74ad877d13c778
|
[
"Markdown",
"C++"
] | 4 |
Markdown
|
smacpher/arduino_tuts
|
ce411903deb67dea1cef53ebb75a7aea1dbadae6
|
22614c404e379b61864804b597987bf9c4d91db1
|
refs/heads/master
|
<file_sep># macOS setup
--
#### brew
```sh
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
```
#### Ansible
```sh
brew install python3 ansible syncthing
brew services syncthing start
open https://127.0.0.1:8384/
```
```sh
cd ~/SyncT/macos_setup/
./1-ansible.sh
# sync the AC-setup share
```sh
brew install ansible-lint pwgen
```
### iterm and sublime
```sh
brew cask install iterm2 sublime-text
```
#### ssh
- https://help.github.com/en/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent#generating-a-new-ssh-key
```sh
pwgen -s 32
```sh
brew cask install alfred slack google-chrome 1password little-snitch firefox tor-browser popclip hyperdock bettertouchtool flux bartender karabiner-elements keyboard-maestro syncthing lingon-x macdown trash
# security tools
brew cask install blockblock do-not-disturb oversight taskexplorer reikey ransomwhere
brew cask install malwarebytes
# install Little Snitch
open '/usr/local/Caskroom/little-snitch/4.3.2/LittleSnitch-4.3.2.dmg'
```
### enable locate database
```sh
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
```
### BASH customization (provare con .profile e vedere se e' condiviso con zsh)
```sh
touch ~/.profile
cat <<EOF | tee ~/.bash_profile
if [ -r ~/.bashrc ]; then
source ~/.bashrc
fi
export PATH="/usr/local/sbin:$PATH"
export PATH="$PATH:~/bin"
alias ls='ls -GF'
alias l='ls -la'
alias ll='ls -l'
EOF
```
```sh
chmod 600 ~/.bash_profile ~/.profile
```
### basic command line tools
brew install git zsh tmux fzf rsync colordiff
### fzf setup
/usr/local/opt/fzf/install
### some more command line
brew install wget httpie mosh htop grc nmap ripgrep bmon jq most tree watch trash
(non installo Z ma lo uso dai plugin di oh-my-zsh)
### zsh tools
brew install zsh-syntax-highlighting zsh-autosuggestions
git clone https://github.com/zsh-users/zsh-completions ~/.oh-my-zsh/custom/plugins/zsh-completions
autoload -U compinit && compinit
###### add to .zshrc
source /usr/local/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
source /usr/local/share/zsh-autosuggestions/zsh-autosuggestions.zs
###### add zsh-completions to the list of plugins
### ssh
ssh-keygen -t rsa -b 4096
eval "$(ssh-agent -s)"
cat <<EOF | tee .ssh/config
#:
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa
EOF
ssh-add -K ~/.ssh/id_rsa
```
### some macOS settings
* Settings -> Mouse -> Secondary button
* Settings -> Keyboard -> Shortcuts -> Full Keyboard access: All Controls
* Settings -> Keyboard -> Keyboard -> Modifier Keys -> Capslock Key: No action (for internal and external keyboard)
* Settings -> Keyboard -> Shortcuts -> Spotlight -> ALT + CMD + Space
* Accessibility -> enable zoom shortcuts
* Accessibility -> trackpad options -> three finger drag
### Tools
#### Oh-My-Zsh
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
### git config
git config --global user.name "<NAME>"
git config --global user.email <EMAIL>
### python3/2 setup
brew install python python2
### for the colorize zsh plugin (ccat)
pip3 install pygments
### bin (TODO: add to the PATH and make it work)
mkdir ~/bin
### pip for macOS python 2.7 (serve veramente ??)
sudo easy_install pip
sudo pip install --upgrade pip
### mkpasswd.py
pip3 install passlib
##### download mkpasswd.py from
[https://gist.github.com/RichardBronosky/58f1b34d2bcf4c4e5f1cd18a88fdc37d](https://gist.github.com/RichardBronosky/) and save it to ~/bin/
### make it executable
chmod u+x ~/bin/mkpasswd
### Terminfo screen-256color
infocmp screen-256color
wget https://invisible-mirror.net/datafiles/current/terminfo.src.gz
gunzip ~/Downloads/terminfo.src.gz
tic -x terminfo.src
rm -f terminfo.src
infocmp screen-256color
### Fonts (nerdfonts)
brew tap caskroom/fonts
brew cask install font-iosevka-nerd-font
brew cask install font-firacode-nerd-font font-hack-nerd-font font-inconsolata-nerd-font font-meslo-nerd-font font-ubuntu-nerd-font font-sourcecodepro-nerd-font
### Powerlevel9k
### https://github.com/bhilburn/powerlevel9k/wiki/Install-Instructions#macos-with-homebrew
brew tap sambadevi/powerlevel9k
brew install powerlevel9k
git clone https://github.com/bhilburn/powerlevel9k.git ~/.oh-my-zsh/custom/themes/powerlevel9k
vim ~/.zshrc
#:
ZSH_THEME="powerlevel9k/powerlevel9k"
### Powerlevel9k
POWERLEVEL9K_MODE="nerdfont-complete"
POWERLEVEL9K_DISABLE_RPROMPT=false
POWERLEVEL9K_PROMPT_ON_NEWLINE=true
POWERLEVEL9K_MULTILINE_LAST_PROMPT_PREFIX="▶ "
POWERLEVEL9K_MULTILINE_FIRST_PROMPT_PREFIX=""
#POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(context dir vcs)
POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(os_icon context dir vcs)
#POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(status root_indicator background_jobs history time)
POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(status virtualenv root_indicator background_jobs history time)
### onedark tmux theme (BEWARE: I've customized some colors myself, look into my dotfiles repo)
### https://github.com/odedlaz/tmux-onedark-theme
git clone https://github.com/odedlaz/tmux-onedark-theme ~/.config/tmux/themes/
vim ~/.tmux.conf
#:
# themes - onedark
set -g @onedark_time_format "%T"
run-shell ~/.config/tmux/themes/tmux-onedark-theme.tmux
vim ~/.config/tmux/themes/tmux-onedark-theme.tmux
#:
onedark_comment_grey="#737c8c"
### *---- # start under review # ----*
#### tmux-yank plugin [https://github.com/tmux-plugins/tmux-yank](https://github.com/tmux-plugins/tmux-yank)
mkdir -p ~/.config/tmux/plugins
cd ~/.config/tmux/plugins
git clone https://github.com/tmux-plugins/tmux-yank ~/.config/tmux/plugins/tmux-yank/
vim ~/.tmux.conf
### start-vim-paste ###
# plugin - tmux-yank
run-shell ~/.config/tmux/plugins/tmux-yank/yank.tmux
# disable "release mouse drag to copy and exit copy-mode", ref: https://github.com/tmux/tmux/issues/140
unbind-key -T copy-mode-vi MouseDragEnd1Pane
## # since MouseDragEnd1Pane neither exit copy-mode nor clear selection now,
## # let single click do selection clearing for us.
## bind-key -T copy-mode-vi MouseDown1Pane select-pane\; send-keys -X clear-selection
##
## # this line changes the default binding of MouseDrag1Pane, the only difference
## # is that we use `copy-mode -eM` instead of `copy-mode -M`, so that WheelDownPane
## # can trigger copy-mode to exit when copy-mode is entered by MouseDrag1Pane
## bind -n MouseDrag1Pane if -Ft= '#{mouse_any_flag}' 'if -Ft= \"#{pane_in_mode}\" \"copy-mode -eM\" \"send-keys -M\"' 'copy-mode -eM
set -g @yank_action 'copy-pipe' # or 'copy-pipe-and-cancel' for the default
### end-vim-paste ###
### *end under review* : vedi la parte finale di .tmux.conf per capire la situazione
### from the dotfiles repository
cp .vimrc ~/
## DevOps
brew cask install visual-studio-code postman insomnia jetbrains-toolbox
### Goolge Cloud SDK (gcloud)
brew cask install google-cloud-sdk
vim ~/.zshrc
### start-vim-paste ###
# gcloud
source '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/path.zsh.inc'
source '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/completion.zsh.inc'
### end-vim-paste ###
### VMware Fusion
brew cask install vmware-fusion
### Kubernetes, Kustomize, Helm, Operator SDK and other utilities
brew install kubectl kustomize kube-ps1 kubectx
brew install kubernetes-helm
brew install operator-sdk
brew tap derailed/k9s && brew install k9s
echo 'alias k9s="TERM=xterm-256color k9s"' >> ~/.zshrc
### Terraform
brew install terraform terraform-inventory
### Docker Desktop
brew cask install docker kitematic
### start docker
open /Applications/Docker.app
## Minikube Kubernetes (requires Docker Desktop)
### prerequisites
brew install docker-machine-driver-hyperkit
sudo chown root:wheel /usr/local/opt/docker-machine-driver-hyperkit/bin/docker-machine-driver-hyperkit
sudo chmod u+s /usr/local/opt/docker-machine-driver-hyperkit/bin/docker-machine-driver-hyperkit
### Update docker-machine-driver-hyperkit
##### [https://github.com/kubernetes/minikube/issues/4206](https://github.com/kubernetes/minikube/issues/4206)
curl -LO https://storage.googleapis.com/minikube/releases/latest/docker-machine-driver-hyperkit && sudo install -o root -g wheel -m 4755 docker-machine-driver-hyperkit /usr/local/bin/
### install
brew cask install minikube
### upgrade
brew cask upgrade minikube
### configure
minikube config set vm-driver hyperkit
##minikube config set cpus 6
##minikube config set memory 8192
### start
minikube start
##minikube start -v 10
### test
eval $(minikube docker-env)
docker ps -a
kubectl get all --all-namespaces -o wide
### install Helm (Tiller) on Minikube
helm init
### other Kubernetes tools
brew install kompose
### MiniShift (OpenShift)
brew install openshift-cli
brew cask install minishift openshift-cli
minishift config set vm-driver hyperkit
minishift start
### login
oc login -u system:admin
### Backup
brew cask install mountain-duck cryptomator carbon-copy-cloner arq
brew install restic rclone
### VPN
brew cask install viscosity protonvpn
### install Chrome Extensions
The Great Suspender
Session Buddy
Dark Reader
EditThisCookie
DuckDuckGo Privacy Essentials
JSON Viewer
Mailvelope
SSH for Google Cloud Platform
Wappalyzer
Evernote Web Clipper
HTTPS Everywhere
### to fix middle clicks :
Fix Chrome middle click behaviour
Link Fixer
### App Store
The Unarchiver
WiFi Explorer
Amphetamine
PopClip
CPU Led
Disk Led
### PopClip extensions
###############################################
##### TODO
### check zsh plugins:
cp (cpv via rsync)
dotenv
fzf (the file have to be edited to provide the fzf install path from brew)
### altri dotfiles ???
### .tmux.conf
### .zshrc
### Alfred script for terminal
https://github.com/stuartcryan/custom-iterm-applescripts-for-alfred/blob/master/custom_iterm_script_iterm_3.1.1.applescript
<file_sep># macOS setup TODO
- have Fusion VMs (with grafical interface)
- Ubuntu
- Windows 10
- macOS
- fix oh-my-zsh
- fix keyboard at boot
- save .bash*
- switch to zsh
- have aliases shared between bash and zsh
- fix copy on tmux
- change boot desktop image
-
<file_sep>
# change pass
ssh-keygen -p -f ~/.ssh/id_rsa
eval "$(ssh-agent -s)"
ssh-add -K ~/.ssh/id_rsa
# config
cat <<EOF | tee ~/.ssh/config
Host *
UseKeychain yes
AddKeysToAgent yes
IdentityFile ~/.ssh/id_rsa
EOF
chmod 0600 ~/.ssh/config
# ssh pub key
ssh-rsa <KEY>
<file_sep>#!/bin/bash
# MP_UBUNTU_INSTANCE="builder01"
# MP_UBUNTU_IP=$(multipass info --format json ${MP_UBUNTU_INSTANCE} | jq -r ".info.${MP_UBUNTU_INSTANCE}.ipv4[]")
# ANSIBLE_USER="multipass"
ANSIBLE_PLAYBOOK="macos_setup.yml"
# ANSIBLE_INVENTORY="local.ini"
ANSIBLE_FORCE_TAGS=""
# ANSIBLE_FORCE_TAGS="all,remove_docker_image"
# ANSIBLE_FORCE_TAGS="docker-image-build-upload"
# ANSIBLE_FORCE_TAGS="prepare-docker-builder"
ANSIBLE_SKIP_TAGS=""
# ANSIBLE_SKIP_TAGS="apt_upgrade"
# ANSIBLE_SKIP_TAGS="apt_upgrade,build_docker_image,push_docker_image"
# ANSIBLE_SKIP_TAGS="remove_docker_image"
ANSIBLE_VERBOSITY=""
# run ansible
# time ansible-playbook ${ANSIBLE_PLAYBOOK} ${ANSIBLE_VERBOSITY} -i ${ANSIBLE_INVENTORY} -u ${ANSIBLE_USER} -l "${MP_UBUNTU_IP}" --skip-tags=${ANSIBLE_SKIP_TAGS:-\"\"} --tags=${ANSIBLE_FORCE_TAGS:-all} ${@}
echo "...running: time ansible-playbook ${ANSIBLE_PLAYBOOK} ${ANSIBLE_VERBOSITY} --skip-tags=${ANSIBLE_SKIP_TAGS:-\"\"} --tags=${ANSIBLE_FORCE_TAGS:-all} ${@}"
time ansible-playbook ${ANSIBLE_PLAYBOOK} ${ANSIBLE_VERBOSITY} --skip-tags=${ANSIBLE_SKIP_TAGS:-\"\"} --tags=${ANSIBLE_FORCE_TAGS:-all} ${@}
<file_sep>#!/bin/bash
echo "Checking brew..."
if [ -x /usr/local/bin/brew ]; then
echo "Brew is already installed!"
else
echo "Installing Brew..."
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
fi
echo "Checking ansible..."
if [ -x /usr/local/bin/ansible ]; then
echo "Ansible is already installed!"
else
echo "Installing Ansible..."
/usr/local/bin/brew install ansible
fi
echo -e '\n==============================\n\n'
COMMAND="./1-ansible.sh ${@}"
echo "...running: ${COMMAND}"
# eval $(TERM=xterm ${COMMAND})
./1-ansible.sh ${@}
|
790c1e6aef17a1807d93d48a70ab9e873f5218ca
|
[
"Markdown",
"Shell"
] | 5 |
Markdown
|
colangelo/macos_setup
|
aec0718a67901e493c66d33305c22e34949aac8f
|
17a039da7e2b87632f3c443af07991cc3adfd920
|
refs/heads/master
|
<file_sep>installall
==========
A commandline tool that installs a set of applications using chocolatey.
Dependencies
----------
### Windows
[chocolatey](https://chocolatey.org/)
<file_sep>package installers
import (
"fmt"
"io/ioutil"
"os/exec"
"strings"
)
const (
chocoDefaultPath = "C:\\ProgramData\\chocolatey\\chocolateyinstall\\"
chocoInstallLogPath = chocoDefaultPath + "install.log"
chocoErrorLogPath = chocoDefaultPath + "error.log"
)
var (
base = []string{
"git",
"GoogleChrome",
"Firefox",
"7zip",
"Atom",
"vcredist2010",
"skype",
"launchy",
"sumatrapdf",
"spotify",
"lastpass",
"githubforwindows",
"hg",
}
work = []string{
"NuGet.CommandLine",
}
home = []string{
"vlc",
"dropbox",
"filezilla",
}
)
//WindowsInstaller is used to install apps on a windows machine.
type WindowsInstaller struct {
apps []string
}
//NewWinWithEnv initializes a new WindowsInstaller for the specified environment.
func NewWinWithEnv(isWork bool) *WindowsInstaller {
if isWork {
fmt.Printf("\nEnv:\twork\n\n")
return &WindowsInstaller{
apps: append(base, work...),
}
}
fmt.Printf("\nEnv:\thome\n\n")
return &WindowsInstaller{
apps: append(base, home...),
}
}
//NewWinWithApps initializes a new WindowsInstaller for the specified applications.
func NewWinWithApps(providedApps []string) *WindowsInstaller {
return &WindowsInstaller{
apps: providedApps,
}
}
//InstallAll will start the installation of apps using the correct install method.
func (w WindowsInstaller) InstallAll() {
for _, app := range w.apps {
fmt.Println("-----------------------------------------")
fmt.Println("\tInstalling", app)
fmt.Println("-----------------------------------------")
cmd := exec.Command("cinst", "-q", app)
cmd.Run()
installLog, hasMessage := errorsFromFile(chocoInstallLogPath)
errorLog, hasError := errorsFromFile(chocoErrorLogPath)
switch true {
case hasMessage:
fmt.Print(installLog)
case hasError:
fmt.Print(errorLog)
default:
//TODO: Have to give different output for when the app is already installed.
fmt.Printf("%v was successfully installed.\n", app)
}
}
}
func errorsFromFile(filePath string) (message string, hasErrors bool) {
m, err := ioutil.ReadFile(filePath)
if err != nil {
panic(err)
} else if len(message) != 0 {
message = strings.Trim(strings.Replace(string(m), "\x00", "", -1), "\n\xff\xfe")
hasErrors = true
}
return
}
<file_sep>package main
import (
"fmt"
"github.com/hyperremix/installall/installers"
)
//Installer interface.
type Installer interface {
InstallAll()
}
func installApps(os string, apps []string) {
var installer Installer
fmt.Printf("\nInstalling apps for:\n\nOS:\t%v\n\n", os)
switch os {
case "windows":
installer = installers.NewWinWithApps(apps)
case "darwin":
case "linux":
}
installer.InstallAll()
}
func installForEnvironment(os string, isWork bool) {
var installer Installer
fmt.Printf("\nInstalling apps for:\n\nOS:\t%v", os)
switch os {
case "windows":
installer = installers.NewWinWithEnv(isWork)
case "darwin":
case "linux":
}
installer.InstallAll()
}
<file_sep>package main
import (
"os"
"runtime"
"strings"
"github.com/jteeuwen/go-pkg-optarg"
)
var (
isWork bool
apps []string
)
func main() {
optarg.Add("d", "default", "Install the default applications for home environment.", false)
optarg.Add("w", "work", "Install default applications for work environmnent.", false)
optarg.Add("a", "apps", "Comma separated list of applications that will be installed. OBS: Without whitespace", "")
optarg.Add("h", "help", "Information on how to use this tool.", false)
optarg.Add("?", "?", "Information on how to use this tool.", false)
for opt := range optarg.Parse() {
switch opt.ShortName {
case "a":
stringApps := opt.String()
for _, part := range strings.Split(stringApps, ",") {
apps = append(apps, part)
}
installApps(runtime.GOOS, apps)
os.Exit(0)
case "d":
installForEnvironment(runtime.GOOS, isWork)
os.Exit(0)
case "w":
isWork = opt.Bool()
installForEnvironment(runtime.GOOS, isWork)
os.Exit(0)
case "h", "?":
optarg.Usage()
os.Exit(1)
}
}
optarg.Usage()
os.Exit(1)
}
|
59063fe9ffeaf54092b9cfb087ce1620e564ab3a
|
[
"Markdown",
"Go"
] | 4 |
Markdown
|
hyperremix/installall
|
711722750be48dd0e9f4744a2a205092d9d50c29
|
4bc88ed36d2befd1903379a53974e6a89c22ffd1
|
refs/heads/master
|
<file_sep>asgiref==3.2.7
Django==3.0.7
gunicorn==20.0.4
numpy==1.18.4
opencv-python==4.2.0.34
Pillow==7.1.2
pytz==2020.1
sqlparse==0.3.1
whitenoise==5.1.0
<file_sep>"""
Expose a method `tag` that accepts a PIL Image
based image as input
"""
from tensorflow.keras.applications import resnet50
import numpy as np
from tensorflow.keras.applications.imagenet_utils import preprocess_input
import pickle
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from sklearn.preprocessing import MinMaxScaler
IMG_SIZE = 224
NUM_OUTPUTS = 3
EPOCHS = 300
BATCH_SIZE = 100
LEARNING_RATE = 0.00007
NUM_FEATURES = 1000
NUM_CLASSES = NUM_OUTPUTS
class MulticlassClassification2(nn.Module):
def __init__(self, num_feature, num_class):
super(MulticlassClassification2, self).__init__()
self.layer_1 = nn.Linear(num_feature, 512)
self.layer_2 = nn.Linear(512, 256)
self.layer_3 = nn.Linear(256, 128)
self.layer_4 = nn.Linear(128, 64)
self.layer_out = nn.Linear(64, num_class)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(p=0.2)
self.batchnorm1 = nn.BatchNorm1d(512)
self.batchnorm2 = nn.BatchNorm1d(256)
self.batchnorm3 = nn.BatchNorm1d(128)
self.batchnorm4 = nn.BatchNorm1d(64)
def forward(self, x):
x = self.layer_1(x)
x = self.batchnorm1(x)
x = self.relu(x)
x = self.layer_2(x)
x = self.batchnorm2(x)
x = self.relu(x)
x = self.dropout(x)
x = self.layer_3(x)
x = self.batchnorm3(x)
x = self.relu(x)
x = self.dropout(x)
x = self.layer_4(x)
x = self.batchnorm4(x)
x = self.relu(x)
x = self.dropout(x)
x = self.layer_out(x)
return x
torch_model2 = MulticlassClassification2(num_feature = NUM_FEATURES, num_class=NUM_CLASSES)
torch_model2.load_state_dict(torch.load('torch-2-vvlarge.dict', map_location=torch.device('cpu')))
class ClassifierDataset(Dataset):
def __init__(self, X_data, y_data):
self.X_data = X_data
self.y_data = y_data
def __getitem__(self, index):
return self.X_data[index], self.y_data[index]
def __len__ (self):
return len(self.X_data)
resnet50_model = resnet50.ResNet50(weights='imagenet')
# classify_model = pickle.load(open('model.pickle', 'rb'))
scaler_model = pickle.load(open('torch-2-vvlarge.scaler.pickle', 'rb'))
labels = ["Shirt", "TShirt", "Pants"]
# labels = ["T-shirt/top", "Trousers", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]
def tag(image):
image = image.resize((IMG_SIZE, IMG_SIZE))
image = np.array(image)
img_batch = np.expand_dims(image, axis=0)
processed_batch = preprocess_input(img_batch, mode="caffe")
vec_batch = resnet50_model.predict(processed_batch)
testx2 = scaler_model.transform(vec_batch)
testy2 = np.zeros(testx2.shape[0])
test_dataset2 = ClassifierDataset(torch.from_numpy(testx2).float(), torch.from_numpy(testy2).long())
test_loader2 = DataLoader(dataset=test_dataset2, batch_size=1)
y_pred_list = []
with torch.no_grad():
torch_model2.eval()
for X_batch, _ in test_loader2:
y_test_pred = torch_model2(X_batch)
y_pred_softmax = torch.log_softmax(y_test_pred, dim = 1)
_, y_pred_tags = torch.max(y_pred_softmax, dim = 1)
y_pred_list.append(y_pred_tags.cpu().numpy())
y_pred_list = [a.squeeze().tolist() for a in y_pred_list]
print(y_pred_list)
prediction = y_pred_list[0]
# pred_batch = classify_model.predict(vec_batch)
# prediction = pred_batch[0]
print(f'{prediction} - { labels[prediction] }')
return {"tag": str(prediction), "label": labels[prediction]}
# img = cv2.resize(raw_image, (28, 28))
# imgd = prepare(img)
# return labels[np.argmax(model.predict(imgd))]
<file_sep>from django.db import models
# Create your models here.
class TaggedImage(models.Model):
image = models.ImageField(upload_to="images/", height_field=None, width_field=None, max_length=None)
uploaded_at = models.DateTimeField(auto_now_add=True)
class APIEndpoint(models.Model):
url = models.TextField(default="")
name = models.TextField(default="")
<file_sep>absl-py==0.9.0
astunparse==1.6.3
cachetools==4.1.0
certifi==2020.4.5.1
chardet==3.0.4
click==7.1.2
Flask==1.1.2
Flask-Cors==3.0.8
future==0.18.2
gast==0.3.3
google-auth==1.16.1
google-auth-oauthlib==0.4.1
google-pasta==0.2.0
grpcio==1.29.0
gunicorn==20.0.4
h5py==2.10.0
idna==2.9
importlib-metadata==1.6.1
itsdangerous==1.1.0
Jinja2==2.11.2
joblib==0.15.1
Keras-Preprocessing==1.1.2
Markdown==3.2.2
MarkupSafe==1.1.1
numpy==1.18.5
oauthlib==3.1.0
opencv-python==4.2.0.34
opt-einsum==3.2.1
Pillow==7.1.2
protobuf==3.12.2
pyasn1==0.4.8
pyasn1-modules==0.2.8
requests==2.23.0
requests-oauthlib==1.3.0
rsa==4.0
scikit-learn==0.23.1
scipy==1.4.1
six==1.15.0
sklearn==0.0
tensorboard==2.2.2
tensorboard-plugin-wit==1.6.0.post3
tensorflow
tensorflow-estimator
termcolor==1.1.0
threadpoolctl==2.1.0
torch==1.5.0
urllib3==1.25.9
Werkzeug==1.0.1
wrapt==1.12.1
zipp==3.1.0
<file_sep># Apparel-Indetification
<file_sep>import json
from flask import Flask,jsonify,request
from flask_cors import CORS
import numpy as np
from PIL import Image
import requests
from io import BytesIO
from tagger import tag
app = Flask(__name__)
CORS(app)
@app.route("/tag",methods=['GET'])
def return_price():
img = request.args.get('image_url')
if img is None:
return jsonify({"error": "no image provided"})
response = requests.get(img)
pil_img = Image.open(BytesIO(response.content))
pil_img = pil_img.convert("RGB")
return jsonify(tag(pil_img))
@app.route("/",methods=['GET'])
def default():
return "API AVAILABLE"
if __name__ == "__main__":
app.run("0.0.0.0", 5000)<file_sep>from django.shortcuts import render
from . import models
from django import forms
class ImageForm(forms.ModelForm):
class Meta:
model = models.TaggedImage
fields = ('image', )
# Create your views here.
def dashboard(request):
data = {"endpoints": models.APIEndpoint.objects.all()}
if(request.method == "POST") and 'image' in request.FILES:
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
model = form.save()
data['image'] = model.image.url
data['image_id'] = model.id
return render(request, 'web/dashboard.html', data)
|
06710d53e39dd1c396ebee11ec87accc1f98385a
|
[
"Markdown",
"Python",
"Text"
] | 7 |
Text
|
Abhi5hekk/Apparel-Indetification
|
35ccb007322db907e0e0d0a326c9401b87d8ea88
|
e4a82ab5782857787053ec3a5239cf7e2b0b3c9d
|
refs/heads/master
|
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int getMin(int arr[], int n)
{
int res = arr[0];
for (int i = 1; i < n; i++){
res = min(res, arr[i]);
}
return res;
}
int main()
{
int n; // the number of temperatures to analyse
cin >> n; cin.ignore();
int m = 0;
for (int i = 0; i < n; i++) {
int t; // a temperature expressed as an integer ranging from -273 to 5526
cin >> t; cin.ignore();
if (i == 0 || abs(t) < abs(m)) {
m = t;
}
else if (abs(t) == abs(m)) {
m = abs(t);
}
}
// Write an answer using cout. DON'T FORGET THE "<< endl"
// To debug: cerr << "Debug messages..." << endl;
cout << m << endl;
}<file_sep>//Test CESAR: Odd Ocurrences in Array
#include <iostream>
#include <vector>
using namespace std;
int OddOcurrences(vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
int res = 0, size = (int)A.size();
// We just need to verify the unpaired number
for(int i = 0; i < size; i++) {
res ^= A[i];
cout << res <<endl;
}
return res;
}
int main ()
{
auto il = {9, 3, 9, 3, 9, 7, 9};
vector<int> A(il);
cout << OddOcurrences(A) <<endl;
return 0;
}
<file_sep># C++ projects and courses
#### *Just feel projects and courses to improve my C++ skills*
### Setup on Windows:
- Install VS Code
- Install Git
- Install MinGW for the gcc compiler
- Install Python 3.x
### VS Code extensions:
- C/C++ intellisense
- Code Runner
### VS code configurations: (Reference: https://code.visualstudio.com/docs/cpp/config-mingw )
#### Compiler:
- Change the include path of "c_cpp_properties.json" to :
```
{
"configurations": [
{
"name": "Win32",
"intelliSenseMode": "clang-x64",
"includePath": [
"${workspaceRoot}",
"C:/MinGW/lib/gcc/mingw32/9.2.0/include/c++",
"C:/MinGW/lib/gcc/mingw32/9.2.0/include/c++/mingw32",
"C:/MinGW/lib/gcc/mingw32/9.2.0/include/c++/backward",
"C:/MinGW/lib/gcc/mingw32/9.2.0/include",
"C:/MinGW/include",
"C:/MinGW/lib/gcc/mingw32/9.2.0/include-fixed"
],
"defines": [
"_DEBUG",
"UNICODE",
"__GNUC__=6",
"__cdecl=__attribute__((__cdecl__))"
],
"browse": {
"path": [
"C:/MinGW/lib/gcc/mingw32/9.2.0/include",
"C:/MinGW/lib/gcc/mingw32/9.2.0/include-fixed",
"C:/MinGW/include/*"
],
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
},
"cStandard": "c17",
"cppStandard": "c++17"
}
],
"version": 4
}
```
#### Builder:
- From the main menu, choose Terminal > Configure Default Build Task. In the dropdown, which will display a tasks dropdown listing various predefined build tasks for C++ compilers. Choose g++.exe build active file, which will build the file that is currently displayed (active) in the editor.
- This will create a tasks.json file in a .vscode folder and open it in the editor. The new tasks.json file should look similar to the JSON below:
```
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "C/C++: g++.exe build active file",
"command": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe",
"args": ["-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe"],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
```
#### Debugger:
- From the main menu, choose Run > Add Configuration... and then choose C++ (GDB/LLDB).
- You'll then see a dropdown for various predefined debugging configurations. Choose g++.exe build and debug active file.
- VS Code creates a "launch.json" file, opens it in the editor, and builds and runs the file.
```
{
"version": "0.2.0",
"configurations": [
{
"name": "g++.exe - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: g++.exe build active file"
}
]
}
```
<file_sep>#include <stdio.h>
#include <iostream>
using namespace std;
// Driver program
int main()
{
// Declare an array
int v[3] = {10, 100, 200};
int nums[2][3] = { {16, 18, 20}, {25, 26, 27} };
// Declare pointer variable
int *ptr;
// Assign the address of v[0] to ptr
ptr = v;
for (int i = 0; i < 3; i++)
{
printf("Value of *ptr = %d\n", *ptr);
printf("Value of ptr = %p\n\n", ptr);
// Increment pointer ptr by 1
ptr++;
}
ptr = v;
cout << "Elements of the array v are: ";
cout << ptr[0] << " " << ptr[1] << " " << ptr[2];
cout << "\nElements of the array nums are: ";
cout << *(*(nums)) << " " << *(*(nums)+1) << " " << *(*(nums)+2) << "\n" << *(*(nums+1)) << " " << *(*(nums+1)+1) << " " << *(*(nums+1)+2);
} <file_sep>#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<int> v1;
cout << "Initial size = " << v1.size() << endl;
/* 5 integers with value = 100 */
v1.assign(5, 100);
cout << "Modified size = " << v1.size() << endl;
/* display vector values */
for (int i = 0; i < v1.size(); ++i)
cout << v1[i] << endl;
return 0;
}<file_sep>// string::substr
#include <iostream>
#include <string>
using namespace std;
string returnInitials(string &name, string &surname, int age);
int main ()
{
string name="Rafael ", lastname= "Santos", initials_result;
int age = 29;
initials_result = returnInitials(name, lastname, age);
cout << initials_result <<endl;
return 0;
}
// Function to return the two initial letters of name and lastname plus age in the same string.
string returnInitials(string &name, string &surname, int age){ return name.substr (0,2) + surname.substr(0, 2) + std::to_string(age); }<file_sep>#include <vector>
#include <iostream>
using namespace std;
vector<int> solution(vector<int> &A, int K) {
// If vector is empty, return an empty vector
if (A.size() == 0) {
return {};
}
for (int i = 0; i < K; i++) {
A.insert(A.begin(), A.back());
A.pop_back();
}
return A;
}
int main(){
auto il1 = {2,3,5,6,7};
vector<int> A(il1), result;
int K = 4;
cout << "Before rotating: " ;
for (int i = 0; i < A.size(); ++i)
cout << A[i] << " ";
result = solution(A, K);
cout << "\nAfter rotating " << K << " times: ";
for (int i = 0; i < result.size(); ++i)
cout << result[i] << " ";
return 0;
}<file_sep>#include <iostream>
#include <bitset>
using namespace std;
int main(){
size_t const n = 4;
bitset<n> bset;
hash<bitset<n>> hash_fun;
for (int i = 0; i < n; i++){
if (i % 2)
bset[i] = 1;
else
bset[i] = 0;
}
cout << "The sequence is = " << bset << endl;
cout << "The alternate sequence is = " << bset.flip() << endl;
cout << "The number of bit set is = " << bset.count() << endl;
cout << "Decimal representation of " << bset << " = " << bset.to_ullong() << endl;
cout << "Hash function for bset = " << hash_fun(bset) << endl;
return 0;
}<file_sep>//Codility Lesson 1 (Binary Gap)
int max_binary_gap(unsigned N) {
// Init counters of bits for a current gap and a longest gap
int max = 0, count = 0;
//if N < 2 it means we have the only bit which may be set to 1 so we can't have the gap here.
if (N < 2) { return 0; }
/* N % 2 != 0 only in case we have the first bit set to 1.
N % 2 == 0 only in case we have the first bit set to 0.
Division of N by 2 do the same as right shift operation that is move all the bits right to one position,
but integer division operation exists in all programming languages when bit shift operations usually have
low level languages only so division by 2 is more general solution.
Thus this line means "repeat while the first bit is 0 right shift all the bits to one position.
*/
while (N % 2 == 0) { N /= 2; }
// Repeat while we have 1th bits in the N variable
while (N > 0) {
// if the first bit of the N is 1 it means we reached the end of the current gap
if (N % 2 == 1) {
// if the current gap is bigger than the max gap make it the max
if (count > max) { max = count; }
// clean the counter to count the next gap length
count = 0;
}
else {
// if the first bit of the N is 0 just count the current bit to the current gap
count++;
}
// right shift to work with a next bit
N /= 2;
}
return max;
}
<file_sep>// you can use includes, for example:
// #include <algorithm>
#include <string>
#include <vector>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
string solution(string &S, int K) {
// write your code in C++14 (g++ 6.2.0)
vector<string> Days = {"Mon","Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
int size = Days.size(), ind = 0;
for(int i = 0; i < size; i++){
if (Days[i] == S){
ind = i;
}
}
return Days[(ind + K) % 7];
}<file_sep>// you can use includes, for example:
// #include <algorithm>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(string &S) {
// write your code in C++14 (g++ 6.2.0)
int aux = 0, count = 0;
for (int i = 0; S[i] != '\0'; i++)
{
if (S[i] == ' ')
aux++;
if (S[i] == '.' || S[i] == '?' || S[i] == '!'){
if(aux >= count){
count = aux;
aux = 0;
}
}
}
return count;
}<file_sep>//Test CESAR: Multiply two integers and return the number of bits set.
#include <iostream>
#include <string>
#include <bitset>
#include <stdint.h>
using namespace std;
int mult_binary(int N, int M);
int main ()
{
long int a = 100000000, b = 100000000;
cout << mult_binary(a, b) <<endl;
return 0;
}
int mult_binary(int N, int M) {
unsigned long long int R;
unsigned long long int A = static_cast<unsigned long long int>(N);
unsigned long long int B = static_cast<unsigned long long int>(M);
R = A*B;
cout << N <<endl;
cout << M <<endl;
cout << R << endl;
cout << sizeof(R) << endl;
// Init counters of bits for a multiply result and number of bits set.
bitset<96> multiply_result(R);
unsigned int count = 0;
cout << "The sequence is = " << multiply_result << endl;
return multiply_result.count();
}
<file_sep>#include <iostream>
#include <vector>
using namespace std;
int hammingDistance(vector<int> &a){
int count = 0, count2 = 0;
vector<int> v2, v3;
//Creating alternate vectors
for (int i = 0; i < a.size(); ++i){
if (i % 2)
v2.push_back(1);
else
v2.push_back(0);
if (i % 2)
v3.push_back(0);
else
v3.push_back(1);
count += a.at(i) ^ v2.at(i);
count2 += a.at(i) ^ v3.at(i);
}
cout << "\nv2 = ";
for (int i = 0; i < v2.size(); ++i){
cout << v2.at(i) << " ";
}
cout << "\nv3 = ";
for (int i = 0; i < v3.size(); ++i){
cout << v3.at(i) << " ";
}
cout << "\nCount = " << count << endl;
cout << "Count2 = " << count2;
return (count < count2 ? count : count2);
}
int main(){
auto il = {0, 1, 1, 1, 1};
vector<int> v(il);
int result = 0;
//Printing received vector
cout << "v = ";
for (int i = 0; i < v.size(); ++i){
cout << v.at(i) << " ";
}
result = hammingDistance(v);
cout << "\nMin Count = " << result << endl;
return 0;
} <file_sep>//Test CESAR: Multiply two integers and return the number of bits set.
#include <iostream>
#include <string>
#include <bitset>
#include <stdint.h>
using namespace std;
int mult_binary(int N, int M);
int main ()
{
int a = 100000000, b = 100000000;
cout << mult_binary(a, b) <<endl;
return 0;
}
int mult_binary(int N, int M) {
int res = 0;
while (M > 0)
{
// If second number becomes odd, add the first number to result
if (M & 1)
res = res + N;
// Double the first number and halve the second number
N = N << 1;
M = M >> 1;
}
// Init counters of bits for a multiply result and number of bits set.
bitset<96> multiply_result(res);
unsigned int count = 0;
cout << "The sequence is = " << multiply_result << endl;
return multiply_result.count();
}
<file_sep>//Perm Missing Element
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int PermMissingElem(vector<int> &A) {
int size = A.size();
sort(A.begin(), A.end());
// We just need to verify the unpaired number
for(int i = 0; i < size; i++) {
if (A[i] != (i + 1))
{
return (i+1);
}
}
return size + 1;
}
int main ()
{
vector<int> A = {2, 3, 1, 5};
cout << PermMissingElem(A) <<endl;
return 0;
}
<file_sep>//Frog Jumps
#include <iostream>
using namespace std;
int FrogJmp(int X, int Y, int D) {
int count = (Y - X) / D;
return (Y - X) % D == 0 ? count : ++count;
}
int main ()
{
int A = 10, B = 85, C = 30;
cout << FrogJmp(A, B, C) <<endl;
return 0;
}
|
cf7510970b368afd6a60b68bbe1e279c5db7df13
|
[
"Markdown",
"C++"
] | 16 |
C++
|
rafaelmelodev/C-Cpp
|
32e4287d91d62920c379cb7f79a8959146be4b20
|
237ce68738ce5054795de43d9102f783d3ea9674
|
refs/heads/master
|
<file_sep>import React, { Fragment } from "react";
const xx = () => {
return (
<Fragment>
<div class="contenedor seccion contenido-centrado">
<h2 class="fw-300 centrar-texto">Llena el formulario de Contacto</h2>
<form class="contacto" action="">
<fieldset>
<legend>Compartir Info con amigos</legend>
<label for="datos">Lo que le queres compartir:</label>
<input
type="text"
id="datos"
placeholder="Datos que queres compartir "
required
/>
<label for="email">E-mail: </label>
<input
type="email"
id="email"
placeholder="Tu Correo electrónico"
required
/>
<label for="nombre">Nombre:</label>
<input
type="text"
id="nombre"
placeholder="Nombre y Apellido de la persona que envía el mail"
required
/>
<label for="asunto">Asunto:</label>
<input type="tel" id="telefono" placeholder="Tu Asunto" required />
<label for="mensaje">Mensaje: </label>
<textarea id="mensaje" placeholder="Texto del mensaje"></textarea>
</fieldset>
<input type="submit" value="Enviar" class="boton boton-verde" />
</form>
</div>
</Fragment>
);
};
export default xx;
<file_sep>import React, { Fragment } from "react";
import Header from "./components/Header";
import Footer from "./components/Footer";
import Login from "./components/Login";
import Nosotros from "./components/Nosotros";
import Compartir from "./components/Compartir";
import CategoriasProvider from "./context/CategoriasContext";
import RecetasProvider from "./context/RecetasContext";
import ModalProvider from "./context/ModalContext";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
function App() {
return (
<Router>
<Switch>
<CategoriasProvider>
<RecetasProvider>
<ModalProvider>
<Header />
<Route exact path="/" component={Login} />
<Route exact path="/nosotros" component={Nosotros} />
<Route exact path="/compartir" component={Compartir} />
<Footer />
</ModalProvider>
</RecetasProvider>
</CategoriasProvider>
</Switch>
</Router>
);
}
export default App;
<file_sep>export default {
mapsKey: "<KEY>",
};
<file_sep>import React from "react";
const xx = () => {
return (
<footer class="site-footer seccion">
<div class="contenedor contenedor-footer">
<p class="copyright">
Todos los Derechos Reservados Rella Pablo 2020 ©{" "}
</p>
</div>
</footer>
);
};
export default xx;
<file_sep># app-mov-tp1
# React + context
<file_sep>import React, { useContext, Fragment } from "react";
import Receta from "./Receta";
import { RecetasContext } from "../context/RecetasContext";
const ListaRecetas = () => {
// extraer las recetas
const { recetas } = useContext(RecetasContext);
const { paginaactual } = useContext(RecetasContext);
const { guardarPaginaActual } = useContext(RecetasContext);
const { totalpaginas } = useContext(RecetasContext);
const paginaAnterior = () => {
const nuevaPaginaActual = paginaactual - 1;
/* console.log(nuevaPaginaActual); */
if (nuevaPaginaActual === 0) return;
guardarPaginaActual(nuevaPaginaActual);
};
//Definimos la pagina siguiente
const paginaSiguiente = () => {
const nuevaPaginaActual = paginaactual + 1;
/* console.log(nuevaPaginaActual); */
if (nuevaPaginaActual > totalpaginas) return;
guardarPaginaActual(nuevaPaginaActual);
};
return (
<Fragment>
<div className="contenedor-anuncios">
{recetas.map((receta) => (
<Receta key={receta.idDrink} receta={receta} />
))}
</div>
{paginaactual === 1 ? null : (
<button
type="button"
className="boton boton-amarillo mr-1"
onClick={paginaAnterior}
>
«Anterior
</button>
)}
{paginaactual === totalpaginas ? null : (
<button
type="button"
className="boton boton-amarillo"
onClick={paginaSiguiente}
>
Posterior »
</button>
)}
</Fragment>
);
};
export default ListaRecetas;
<file_sep>import React, { Fragment } from "react";
import imggg from "../img/nosotros.jpg";
import { Map, Marker, Popup, TileLayer } from "react-leaflet";
import { Icon } from "leaflet";
import credentials from "../utilidades/credentials";
const xx = () => {
//console.log(credentials.mapsKey);
const mapURL = `https://maps.googleapis.com/maps/api/js?v=3.exp&key=${credentials.mapsKey}`;
return (
<Fragment>
<div className="contenedor">
<h1 className="fw-300 centrar-texto">Conoce Sobre Nosotros</h1>
<div className="contenido-nosotros">
<div className="imagen">
<img src={imggg} alt="Imagen Sobre Nosotros" />
</div>
<div className="texto-nosotros">
<blockquote>25 Años de Experiencia</blockquote>
<p>
Lorem Ipsum es simplemente el texto de relleno de las imprentas y
archivos de texto. Lorem Ipsum ha sido el texto de relleno
estándar de las industrias desde el año 1500, cuando un impresor
(N. del T. persona que se dedica a la imprenta) desconocido usó
una galería de textos y los mezcló de tal manera que logró hacer
un libro de textos especimen. No sólo sobrevivió 500 años, sino
que tambien ingresó como texto de relleno en documentos
electrónicos, quedando esencialmente igual al original. Fue
popularizado en los 60s con la creación de las hojas "Letraset",
las cuales contenian pasajes de Lorem Ipsum, y más recientemente
con software de autoedición, como por ejemplo Aldus PageMaker, el
cual incluye versiones de Lorem Ipsum.
</p>
<p>
Hay muchas variaciones de los pasajes de Lorem Ipsum disponibles,
pero la mayoría sufrió alteraciones en alguna manera, ya sea
porque se le agregó humor, o palabras aleatorias que no parecen ni
un poco creíbles. Si vas a utilizar un pasaje de Lorem Ipsum,
necesitás estar seguro de que no hay nada avergonzante escondido
en el medio del texto. Todos los generadores de Lorem Ipsum que se
encuentran en Internet tienden a repetir trozos predefinidos
cuando sea necesario, haciendo a este el único generador verdadero
(válido) en la Internet. Usa un diccionario de mas de 200 palabras
provenientes del latín, combinadas con estructuras muy útiles de
sentencias, para generar texto de Lorem Ipsum que parezca
razonable. Este Lorem Ipsum generado siempre estará libre de
repeticiones, humor agregado o palabras no características del
lenguaje, etc.
</p>
</div>
</div>
<h1 className="fw-300 centrar-texto containerElement">Ubicacion</h1>
<Map center={[-34.9214, -57.9544]} zoom={15}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={[-34.9214, -57.9544]}>
<Popup>
<span>Estamos Aquí</span>
</Popup>
</Marker>
</Map>
</div>
</Fragment>
);
};
export default xx;
<file_sep>import React, { Fragment } from "react";
import { Link } from "react-router-dom";
const Header = () => {
return (
<Fragment>
<header className="site-header inicio">
<div className="contenedor contenido-header">
<div className="barra">
{/* <Link to="/">
<img src="img/logo.svg" className="" />
</Link> */}
<nav id="" className="navegacion">
<Link to="/">Inicio</Link>
<Link to="Nosotros">Nosotros</Link>
</nav>
<h3>TheCocktailDB</h3>
</div>
</div>
</header>
</Fragment>
);
};
export default Header;
<file_sep>import React from "react";
import Formulario from "./Formulario";
import ListaRecetas from "./ListaRecetas";
const xx = () => {
//Cargamos el localstorage al state inicial
let citasIniciales = JSON.parse(localStorage.getItem("citas"));
if (!citasIniciales) {
citasIniciales = [];
}
return (
<div className="inicio contenedor">
<Formulario />
<ListaRecetas />
</div>
);
};
export default xx;
|
5dfb3729277628b3d5c0a3350dc7193e5c5e98fe
|
[
"JavaScript",
"Markdown"
] | 9 |
JavaScript
|
pablorella/app-mov-tp1
|
9da184bb2d4fca5f2ef853052f5000f4b0c655cf
|
f27e2e9f955dbc5ef7796ba9c94fde6f4d2abef8
|
refs/heads/master
|
<repo_name>carlos-gutier/Intro-Python-II<file_sep>/src/adv.py
from room import Room
from player import Player
from item import Item
# Declare all the rooms
room = {
'outside': Room("Outside Cave Entrance",
"North of you, the cave mount beckons."),
'foyer': Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east."""),
'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling
into the darkness. Ahead to the north, a light flickers in
the distance, but there is no way across the chasm."""),
'narrow': Room("Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air."""),
'treasure': Room("Treasure Chamber", """You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
earlier adventurers. The only exit is to the south."""),
}
# Link rooms together
room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
room['narrow'].n_to = room['treasure']
room['treasure'].s_to = room['narrow']
# Items to add to rooms
item = {
"cheese": Item("cheese", "a piece of cheddar cheese packaged and sealed"),
"bat": Item("bat", "a wood baseball bat for self defense"),
"gum": Item("gum", "a pack of gum for bad breath"),
"lightsaber": Item("lightsaber", "a lightsaber energy sword, the weapon of choice for Jedis"),
"bag": Item("bag", "a bag to collect booty and get rich!"),
"mouse": Item("mouse", "a dead and dry mouse is the only thing left behind..."),
}
# adding items to rooms
room['outside'].add_item(item["cheese"])
room['foyer'].add_item(item["bat"])
room['foyer'].add_item(item["gum"])
room['overlook'].add_item(item["lightsaber"])
room['narrow'].add_item(item["bag"])
room['treasure'].add_item(item["mouse"])
# Main
# Make a new player object that is currently in the 'outside' room.
# _______ Intro Message _____________________
print("//////////////////////////////////")
print("////// Welcome to THE MAZE //////")
print("/////////////////////////////////\n")
# Write a loop that:
#
# * Prints the current room name
# * Prints the current description (the textwrap module might be useful here).
# * Waits for user input and decides what to do.
#
# If the user enters a cardinal direction, attempt to move to the room there.
# Print an error message if the movement isn't allowed.
#
# If the user enters "q", quit the game.
# Begining of REPL (Read, Evaluate, Print, Loop)
# will wait for response from user and according to it
# proceed to process move and print out description of room
# or print out message in case move fails
# then wait for user input again
# print('INPUT GIVEN BY USER:', cmd.strip(' '))
cmds = ['n', 's', 'e', 'w', 'q']
curr_player = Player("P1", room["outside"])
#_____ REPL __________________________________
while True:
room = curr_player.current_room
print(f"------------------\nYour current location is the {room.name}.\n")
print("..."+room.description+"..\n------------------\n")
# checking player inventory
if len(curr_player.player_inventory) < 1:
print("Your inventory of items is null.")
else:
print(f"This is your inventory of items:\n{curr_player.player_inventory}\n")
print(f"Items found here:\n{room.items_list}\n")
# If the user enters a cardinal direction, attempt to move to the room there.
# Print an error message if the movement isn't allowed.
print("To move around choose from [n]North, [s]South, [e]East, or [w]West.\nOr [q] to Quit from The Maze\n")
cmd = input("Where would you like to go to begin?: ")
# splitting inputs/parsing
# getting a list from split()
cmd = cmd.split()
if len(cmd) == 1:
action = cmd[0]
elif len(cmd) == 2:
action = cmd[0]
item = cmd[1]
# quitting if "q" as input
if cmd[0] == "q":
exit()
# moving to room according to direction imput
# by instantiating "move_player" method from "Player" class
elif (action != "q") & (cmd[0] in cmds):
curr_player.move_player(cmd[0])
# getting item: add to "player_inventory" & remove from room
elif (action == "take") or (action == "get"):
if item in room.items_list:
curr_player.get_item(item)
room.remove_item(item)
# dropping item: add to room & remove from "player_inventory"
elif action == "drop":
if item in curr_player.player_inventory:
room.add_item(item)
curr_player.drop_item(item)
else:
print("Invalid command. Please try again.")
# print(f'Your current location is the {curr_player.location.title}.')
# print("..."+curr_player.location.description+"..")
# print(f"Items here:")
# curr_player.location.list_items()
# cmd = input("\nWhere would you like to go now?\n ([n]North, [s]South, [e]East, or [w]West.\nOr [q] to Quit): ")
<file_sep>/src/player.py
# Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, current_room):
self.name = name
self.current_room = current_room
self.player_inventory=[]
# method to move player from one room to another
def move_player(self, direction):
if getattr(self.current_room, f'{direction}_to') != None:
self.current_room = getattr(self.current_room, f'{direction}_to')
else:
print("Invalid move. Please try again.")
# method to add item found in current room to "player_inventory"
def get_item(self, item):
self.player_inventory.append(item)
print(f"You picked up {item}.")
# method to remove item from "player_inventory"
# to then drom in "current_room"
def drop_item(self, item):
self.player_inventory.remove(item)
print(f"You dropped {item}.")
|
8f391a74f2e1fcb42ffcf87592a4cccacd301efa
|
[
"Python"
] | 2 |
Python
|
carlos-gutier/Intro-Python-II
|
b693b3cf5f315b4c93fce35d25c648347c5a4ec1
|
b7593fb3ed3dcd242ef4c3d6329d01cb91035760
|
refs/heads/master
|
<repo_name>rssh-jp/atcoder<file_sep>/abc139_b/main.go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
var A, B int
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
s := scanner.Text()
fmt.Sscanf(s, "%d %d", &A, &B)
}
curr := 1
var count int
for {
if curr >= B {
break
}
curr += A - 1
count++
}
fmt.Println(count)
}
<file_sep>/abc156_c/main.go
package main
import (
"bufio"
"fmt"
"log"
"os"
"sort"
"strconv"
"strings"
)
type Input struct {
N int
X []int
}
func NewInput() (*Input, error) {
var N int
var X []int
scanner := bufio.NewScanner(os.Stdin)
if scanner.Scan() {
s := scanner.Text()
fmt.Sscanf(s, "%d", &N)
}
X = make([]int, 0, N)
if scanner.Scan() {
s := scanner.Text()
for _, item := range strings.Split(s, " ") {
xi, err := strconv.Atoi(item)
if err != nil {
return nil, err
}
X = append(X, xi)
}
}
return &Input{
N: N,
X: X,
}, nil
}
func calc(P int, X []int) int {
var total int
for _, item := range X {
sub := P - item
energy := sub * sub
total += energy
}
return total
}
func main() {
input, err := NewInput()
if err != nil {
log.Fatal(err)
}
sort.Slice(input.X, func(i, j int) bool {
return input.X[i] < input.X[j]
})
sub := input.X[input.N-1] - input.X[0]
var min int
for i := 0; i < sub; i++ {
P := input.X[0] + i
total := calc(P, input.X)
if min == 0 || min > total {
min = total
}
}
fmt.Println(min)
}
|
f8a6d4c76eba85fa4572d1ae571462fb0abd8874
|
[
"Go"
] | 2 |
Go
|
rssh-jp/atcoder
|
a91da93a594b563bd975efb5167ff53cac9bbe0b
|
d78bab9ab145ad4755aa983b5211843f064e7fa3
|
refs/heads/main
|
<file_sep>require(["esri/Map", "esri/views/MapView", "esri/layers/FeatureLayer", "esri/layers/Layer", "esri/widgets/Search","esri/widgets/BasemapGallery", "esri/widgets/Expand", "esri/widgets/Print", "esri/widgets/LayerList", "esri/layers/MapImageLayer", "esri/widgets/Home", "esri/widgets/DistanceMeasurement2D", "esri/widgets/AreaMeasurement2D", "esri/core/watchUtils", "esri/layers/GroupLayer"],
(Map, MapView, FeatureLayer, Layer, Search, BasemapGallery, Expand, Print, LayerList, MapImageLayer, Home, DistanceMeasurement2D, AreaMeasurement2D, watchUtils, GroupLayer) => {
theMap = new Map({
basemap: "topo-vector"
});
theView = new MapView({
container: "viewDiv",
map: theMap,
zoom: 11,
center: [-94.35, 39.01]
});
var getPropertyInfoThisAction = {
className: "decoy_button",
id: "propertyInfo",
};
var popuptemplAddrPts = {
title: "<h6><b>Basic Information</b></h6>",
outFields: ["*"],
expressionInfos: [{
name: "address-inside-parcels-arcade",
title: "<b>Address:</b>",
visible: true,
expression: "var addressintersect = Intersects(FeatureSetByName($map,'Address Points'), $feature); var cnt = Count(addressintersect);var result = 'There are ' + cnt + ' addresses at this parcel:';for (var addressloc in addressintersect){result += TextFormatting.NewLine + TextFormatting.NewLine + addressloc.FULLADDR + ' ' + addressloc.MUNICIPALITY + ' MO, ' + addressloc.ZIP;}return result + TextFormatting.NewLine",
},
{
name: "tca-arcade",
title: "<b>Tax Code Area:</b>",
visible: true,
expression: "var tcaintersect = First(Intersects($feature, FeatureSetByName($map, 'Tax Code Areas'))); return tcaintersect.Name;",
},
{
name: "school-arcade",
title: "<b>School District:</b>",
visible: true,
expression: "var schoolintersect = First(Intersects($feature, FeatureSetByName($map, 'School District'))); return schoolintersect.SCHOOL;",
},
{
name: "water-arcade",
title: "<b>Water District:</b>",
visible: true,
expression: "var waterintersect = First(Intersects($feature, FeatureSetByName($map, 'Water District'))); return waterintersect.WATER;",
},
{
name: "fire-arcade",
title: "<b>Fire District:</b>",
visible: true,
expression: "var fireintersect = First(Intersects($feature, FeatureSetByName($map, 'Fire District'))); return fireintersect.FIRE;",
},
{
name: "library-arcade",
title: "<b>Library District:</b>",
visible: true,
expression: "var libraryintersect = First(Intersects($feature, FeatureSetByName($map, 'Library District'))); return libraryintersect.LIBRARY;",
},
{
name: "measurement-arcade",
title: "<b>Parcel Area:</b>",
visible: true,
expression: "var acres = Round(AreaGeodetic($feature, 'acres'), 2) + ' Acres'; var sqft = Text(AreaGeodetic($feature, 'square-feet'), '#,###.0') + ' Sq Ft'; var result = sqft + TextFormatting.NewLine + acres; return result;",
}],
lastEditInfoEnabled: false,
content: [
{
type: "fields",
fieldInfos: [
{
fieldName: "ADDPTKEY",
visible: true,
label: "<b>Parcel Number:</b>",
},
{
fieldName: "expression/address-inside-parcels-arcade",
visible: true
},
{
fieldName: "expression/tca-arcade",
visible: true
},
{
fieldName: "expression/school-arcade",
visible: true
},
{
fieldName: "expression/water-arcade",
visible: true
},
{
fieldName: "expression/fire-arcade",
visible: true
},
{
fieldName: "expression/library-arcade",
visible: true
},
{
fieldName: "expression/measurement-arcade",
visible: true
}
]}
],
actions: [getPropertyInfoThisAction]
};
var popuptemplParcels = {
title: "<h6><b>Basic Information</b></h6>",
outFields: ["*"],
expressionInfos: [{
name: "address-inside-parcels-arcade",
title: "<b>Address:</b>",
visible: true,
expression: "var addressintersect = Intersects(FeatureSetByName($map,'Address Points'), $feature); var cnt = Count(addressintersect);var result = 'There are ' + cnt + ' addresses at this parcel:';for (var addressloc in addressintersect){result += TextFormatting.NewLine + TextFormatting.NewLine + addressloc.FULLADDR + ' ' + addressloc.MUNICIPALITY + ' MO, ' + addressloc.ZIP;}return result + TextFormatting.NewLine",
},
{
name: "tca-arcade",
title: "<b>Tax Code Area:</b>",
visible: true,
expression: "var tcaintersect = First(Intersects($feature, FeatureSetByName($map, 'Tax Code Areas'))); return tcaintersect.Name;",
},
{
name: "school-arcade",
title: "<b>School District:</b>",
visible: true,
expression: "var schoolintersect = First(Intersects($feature, FeatureSetByName($map, 'School District'))); return schoolintersect.SCHOOL;",
},
{
name: "water-arcade",
title: "<b>Water District:</b>",
visible: true,
expression: "var waterintersect = First(Intersects($feature, FeatureSetByName($map, 'Water District'))); return waterintersect.WATER;",
},
{
name: "fire-arcade",
title: "<b>Fire District:</b>",
visible: true,
expression: "var fireintersect = First(Intersects($feature, FeatureSetByName($map, 'Fire District'))); return fireintersect.FIRE;",
},
{
name: "library-arcade",
title: "<b>Library District:</b>",
visible: true,
expression: "var libraryintersect = First(Intersects($feature, FeatureSetByName($map, 'Library District'))); return libraryintersect.LIBRARY;",
},
{
name: "measurement-arcade",
title: "<b>Parcel Area:</b>",
visible: true,
expression: "var acres = Round(AreaGeodetic($feature, 'acres'), 2) + ' Acres'; var sqft = Text(AreaGeodetic($feature, 'square-feet'), '#,###.0') + ' Sq Ft'; var result = sqft + TextFormatting.NewLine + acres; return result;",
}],
lastEditInfoEnabled: false,
content: [
{
type: "fields",
fieldInfos: [
{
fieldName: "Name",
visible: true,
label: "<b>Parcel Number:</b>",
},
{
fieldName: "expression/address-inside-parcels-arcade",
visible: true
},
{
fieldName: "expression/tca-arcade",
visible: true
},
{
fieldName: "expression/school-arcade",
visible: true
},
{
fieldName: "expression/water-arcade",
visible: true
},
{
fieldName: "expression/fire-arcade",
visible: true
},
{
fieldName: "expression/library-arcade",
visible: true
},
{
fieldName: "expression/measurement-arcade",
visible: true
}
]}
],
actions: [getPropertyInfoThisAction]
};
theView.popup.on("trigger-action", function(event)
{
if (event.action.id === "propertyInfo")
{
getData();
}
});
// this is needed to prevent the popup from automatically collapsing on mobile devices
theView.popup.collapseEnabled = false;
var addressPtsLayer = new FeatureLayer({
url: "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer_Pub/FeatureServer/17",
minScale: 10000,
title: "Address Points",
popupTemplate: popuptemplAddrPts
});
var parcelsren = {
type: "simple",
symbol: {
type: "simple-fill",
outline: { width: 1.5, color: [255, 170, 0, 0.5] },
color: [255, 255, 255, 0]
}};
parcelsLayer = new FeatureLayer({
url: "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer_Pub/FeatureServer/18",
outFields: ["Name"],
minScale: 10000,
title: "Tax Parcels",
popupTemplate: popuptemplParcels,
renderer: parcelsren
});
var dimensions = new MapImageLayer({
url: "https://jcgis.jacksongov.org/arcgis/rest/services/Cadastral/LotsAndDimensions/MapServer",
title:"Property Features",
visible: false,
sublayers: [
{
id: 1,
visible: true,
title: "Builder Block Number",
},{
id: 3,
visible: true,
title: "Property Dimensions",
},{
id: 4,
visible: true,
title: "Lot Corners",
},{
id: 7,
visible: true,
title: "Lot Numbers",
}]
});
var pastyearparcels = new MapImageLayer({
url: "https://jcgis.jacksongov.org/arcgis/rest/services/Cadastral/PastYearParcels/MapServer",
outFields: ["Name"],
minScale: 5000,
title:"Past Year Parcels",
visible: false
});
var oldLots = new FeatureLayer({
url: "https://jcgis.jacksongov.org/arcgis/rest/services/Cadastral/LotsAndDimensions/MapServer/8",
visible: true,
minScale: 5000,
title: "Old Lots"
});
var newLots = new FeatureLayer({
url: "https://jcgis.jacksongov.org/portal/rest/services/Hosted/LotsPubView/FeatureServer/0",
visible: true,
minScale: 5000,
title: "New Lots"
});
var lotsLayers = new GroupLayer({
layers: [oldLots, newLots],
visible: false,
title: "Old and New Lots"
});
var cityboundaries = new FeatureLayer({
url: "https://jcgis.jacksongov.org/portal/rest/services/Hosted/MunicipalitiesPublic/FeatureServer/29",
title:"City Boundaries",
visible: true
});
var zoning = new MapImageLayer({
url: "https://jcgis.jacksongov.org/arcgis/rest/services/PublicWorks/UnincorporatedZoning/MapServer",
title:"Unincorporated Zoning",
visible: false
});
var TIFplan = new FeatureLayer({
url: "https://jcgis.jacksongov.org/portal/rest/services/Hosted/TIF_District_Public_View/FeatureServer/0",
//url: "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer/FeatureServer/33",
title: "Tax Increment Financing (TIF) Districts",
visible: false
});
var TIFproject = new FeatureLayer({
url: "https://jcgis.jacksongov.org/portal/rest/services/Hosted/TIF_Projects/FeatureServer/0",
//url: "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer/FeatureServer/36",
title: "Tax Increment Financing (TIF) Projects",
visible: false
});
var CIDlayer = new FeatureLayer({
url: "https://jcgis.jacksongov.org/portal/rest/services/Hosted/CID/FeatureServer/0",
//url: "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer/FeatureServer/35",
title: "Community Improvement Districts",
visible: false
});
var TDDlayer = new FeatureLayer({
url: "https://jcgis.jacksongov.org/portal/rest/services/Hosted/TDD_Public_View/FeatureServer/0",
//url: "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer/FeatureServer/34",
title: "Transportation Development Districts",
visible: false
});
var specialassessment = new GroupLayer({
layers: [TDDlayer, TIFproject, TIFplan, CIDlayer],
title: "Special Assessment Districts",
visible: false
});
var tcaren = {
type: "simple",
symbol: {
type: "simple-fill",
outline: { width: 2, color: [197, 63, 0, 0.5] },
color: [255, 255, 255, 0]
}
};
var tcalayer = new FeatureLayer({
url: "https://jcgis.jacksongov.org/portal/rest/services/Hosted/TaxDistrictsPublicView/FeatureServer/0",
//url: "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer/FeatureServer/30",
title:"Tax Code Areas",
visible: false,
renderer: tcaren
});
// --------- this is lame to have to do this - can u not access layers in a group layer in Arcade??? ------
var schoollayer = new FeatureLayer({
url: "https://jcgis.jacksongov.org/arcgis/rest/services/Cadastral/Parcel_Viewer_Layers/FeatureServer/28",
//url: "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer/FeatureServer/28",
title:"School District",
visible: false
});
schoollayer.listMode = "hide";
var firelayer = new FeatureLayer({
url: "https://jcgis.jacksongov.org/arcgis/rest/services/Cadastral/Parcel_Viewer_Layers/FeatureServer/27",
//url: "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer/FeatureServer/27",
title:"Fire District",
visible: false
});
firelayer.listMode = "hide";
var waterlayer = new FeatureLayer({
url: "https://jcgis.jacksongov.org/arcgis/rest/services/Cadastral/Parcel_Viewer_Layers/FeatureServer/26",
//url: "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer/FeatureServer/26",
title:"Water District",
visible: false
});
waterlayer.listMode = "hide";
var librarylayer = new FeatureLayer({
url: "https://jcgis.jacksongov.org/arcgis/rest/services/Cadastral/Parcel_Viewer_Layers/FeatureServer/31",
//url: "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer/FeatureServer/31",
title:"Library District",
visible: false
});
librarylayer.listMode = "hide";
// ----------------------- End of lame stuff ----------------
var districtLayers = new MapImageLayer({
url: "https://jcgis.jacksongov.org/arcgis/rest/services/Cadastral/Parcel_Viewer_Layers/MapServer",
title: "School, Water, Library & Fire Districts",
visible: false,
sublayers: [
{
id: 27,
visible: false,
title: "Fire Districts"
},{
id: 31,
visible: false,
title: "Library Districts",
},{
id: 26,
visible: false,
title: "Water Districts"
},{
id: 28,
visible: false,
title: "School Districts"
}]
});
var townshipsection = new MapImageLayer({
url: "https://gis.blm.gov/arcgis/rest/services/Cadastral/BLM_Natl_PLSS_CadNSDI/MapServer",
title: "Section-Township-Range",
visible: false
});
const book = "$feature.Book";
var subdivisionRen = {
type: "unique-value",
valueExpression: `When(${book}[3] == '1', 1, ${book}[3] == '2', 2, ${book}[3] == '2', 2, ${book}[3] == '3', 3, ${book}[3] == '4', 4, ${book}[3] == '5', 5, ${book}[3] == '6', 6, ${book}[3] == '7', 7, ${book}[3] == '8', 8, ${book}[3] == '9', 9, 0)`,
uniqueValueInfos: [
{
value: "0",
symbol: {
type: "simple-fill",
outline: { width: 2, color: [128, 128, 128, 1] },
color: [128, 128, 128, 0.6] // gray
}
},{
value: "1",
symbol: {
type: "simple-fill",
outline: { width: 2, color: [255, 0, 0, 1] },
color: [255, 0, 0, 0.6] // red
}
},{
value: "2",
symbol: {
type: "simple-fill",
outline: { width: 2, color: [0, 255, 0, 1] },
color: [0, 255, 0, 0.6] // green
}
},{
value: "3",
symbol: {
type: "simple-fill",
outline: { width: 2, color: [0, 0, 255, 1] },
color: [0, 0, 255, 0.6] // blue
}
},{
value: "4",
symbol: {
type: "simple-fill",
outline: { width: 2, color: [128, 0, 0, 1] },
color: [128, 0, 0, 0.6] // maroon
}
},{
value: "5",
symbol: {
type: "simple-fill",
outline: { width: 2, color: [128, 0, 128, 1] },
color: [128, 0, 128, 0.6] // purple
}
},{
value: "6",
symbol: {
type: "simple-fill",
outline: { width: 2, color: [255, 255, 0, 1] },
color: [255, 255, 0, 0.6] // yellow
}
},{
value: "7",
symbol: {
type: "simple-fill",
outline: { width: 2, color: [0, 255, 255, 1] },
color: [0, 255, 255, 0.6] // aqua
}
},{
value: "8",
symbol: {
type: "simple-fill",
outline: { width: 2, color: [255, 0, 255, 1] },
color: [255, 0, 255, 0.6] // fuschia
}
},{
value: "9",
symbol: {
type: "simple-fill",
outline: { width: 2, color: [0, 128, 128, 1] },
color: [0, 128, 128, 0.6] // teal
}
}
]
}; // end of subdivisionRen
var subdivisionsLayer = new FeatureLayer({
url: "https://jcgis.jacksongov.org/portal/rest/services/Hosted/SubdivisionsPublic/FeatureServer/0",
title: "Subdivisions",
renderer: subdivisionRen,
visible: false
});
var CountyOutlineLayer = Layer.fromPortalItem({
portalItem: { id: "bb4ba391fbfa4e74881ed659fa54ee14" }
});
theMap.add(CountyOutlineLayer);
theMap.add(townshipsection);
theMap.add(districtLayers);
theMap.add(tcalayer);
theMap.add(specialassessment);
theMap.add(subdivisionsLayer);
theMap.add(zoning);
theMap.add(cityboundaries);
theMap.add(lotsLayers);
theMap.add(pastyearparcels);
theMap.add(dimensions);
theMap.add(addressPtsLayer);
theMap.add(parcelsLayer);
// ---- lame layers ---
theMap.add(schoollayer);
theMap.add(firelayer);
theMap.add(waterlayer);
theMap.add(librarylayer);
// end of lame layers ---
var homeBtn = new Home({
view: theView
});
theView.ui.add(homeBtn, "top-leading");
// Search widget
searchWidget = new Search({
view: theView,
sources:
[{
layer: addressPtsLayer,
searchFields: ["FULLADDR"],
searchTerm: ["FULLADDR"],
suggestionTemplate: "{FULLADDR}, {MUNICIPALITY} {ZIP}",
exactMatch: false,
placeholder: "Search by street address",
name: "Search by Street Address",
maxResults: 12,
maxSuggestions: 12,
suggestionsEnabled: true,
minSuggestCharacters: 3,
popupEnabled: true,
sourceIndex: 0
},{
layer: parcelsLayer,
searchFields: ["Name"],
searchTerm: ["Name"],
suggestionTemplate: "{Name}",
exactMatch: true,
placeholder: "Search by tax parcel #",
name: "Search by Parcel #",
maxResults: 12,
maxSuggestions: 12,
suggestionsEnabled: true,
minSuggestCharacters: 3,
popupEnabled: true,
sourceIndex: 1
}],
searchAllEnabled: true,
allPlaceholder: "Search by street address or tax parcel #",
includeDefaultSources: false
})
// Basemap widget
var basemapGallery = new BasemapGallery({
view: theView,
container: document.createElement("div")
});
var bgExpand = new Expand({
view: theView,
expandTooltip: "Basemap",
content: basemapGallery
});
// Layer list widget
var layerList = new LayerList({
view: theView
});
var layerlistExpand = new Expand({
view: theView,
expandTooltip: "Layer List",
content: layerList
});
// Measure widget functions
// ------------------------------------
var activeWidget = null;
document.getElementById("distanceButton").addEventListener("click", function()
{
setActiveWidget(null);
if (!this.classList.contains("active")) setActiveWidget("distance");
else setActiveButton(null);
});
document.getElementById("areaButton").addEventListener("click", function()
{
setActiveWidget(null);
if (!this.classList.contains("active")) setActiveWidget("area");
else setActiveButton(null);
});
function setActiveWidget(type)
{
switch (type)
{
case "distance":
activeWidget = new DistanceMeasurement2D({
view: theView,
unit: "us-feet"
});
activeWidget.viewModel.start();
theView.ui.add(activeWidget, "top-right");
setActiveButton(document.getElementById("distanceButton"));
break;
case "area":
activeWidget = new AreaMeasurement2D({
view: theView,
unit: "square-us-feet"
});
activeWidget.viewModel.start();
theView.ui.add(activeWidget, "top-right");
setActiveButton(document.getElementById("areaButton"));
break;
case null:
if (activeWidget)
{
theView.ui.remove(activeWidget);
activeWidget.destroy();
activeWidget = null;
}
break;
}
}
function setActiveButton(selectedButton)
{
theView.focus();
var elements = document.getElementsByClassName("active");
for (var i = 0; i < elements.length; i++)
elements[i].classList.remove("active");
if (selectedButton)
selectedButton.classList.add("active");
}
var measureExpand = new Expand({
view: theView,
expandIconClass: "esri-icon-measure",
expandTooltip: "Measurement",
content: measureDiv
});
// end of measure widget functions
// --------------------------------------------
// Print widget
var thePrint = new Print({
view: theView,
printServiceUrl: "https://utility.arcgisonline.com/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task"
});
var printExpand = new Expand({
view: theView,
content: thePrint
});
//-------------------------------------------------------------------
// The next section collapses the other tools when one is selected
//-------------------------------------------------------------------
OnlyBasemap = watchUtils.pausable(bgExpand, "expanded", function(newValue, oldValue)
{
if(newValue == true)
{
if(bgExpand.expanded)
{
printExpand.collapse();
layerlistExpand.collapse();
measureExpand.collapse();
}
}
});
OnlyLayer = watchUtils.pausable(layerlistExpand, "expanded", function(newValue, oldValue)
{
if(newValue == true)
{
if(layerlistExpand.expanded)
{
bgExpand.collapse();
printExpand.collapse();
measureExpand.collapse();
}
}
});
OnlyMeasure = watchUtils.pausable(measureExpand, "expanded", function(newValue, oldValue)
{
if(newValue == true)
{
if(measureExpand.expanded)
{
bgExpand.collapse();
printExpand.collapse();
layerlistExpand.collapse();
}
}
});
OnlyPrint = watchUtils.pausable(printExpand, "expanded", function(newValue, oldValue)
{
if(newValue == true)
{
if(printExpand.expanded)
{
bgExpand.collapse();
layerlistExpand.collapse();
measureExpand.collapse();
}
}
});
//-------------------------------------------------------------------
// End of widget collapse section
//-------------------------------------------------------------------
// This adds the widgets to the view
theView.ui.add([
{
component: searchWidget,
position: "top-right",
index: 0
}, {
component: bgExpand,
position: "top-right",
index: 1
}, {
component: layerlistExpand,
position: "top-right",
index: 2
}, {
component: measureExpand,
position: "top-right",
index: 3
}, {
component: printExpand,
position: "top-right",
index: 4
}, {
component: helpbutton,
position: "top-right",
index: 5
}, {
component: questionsbutton,
position: "top-right",
index: 6
}
]);
// this is exclusively for handling clicking on a parcel
theView.on("click", (event) =>
{
// first, unselect any currently selected parcels (except if it's the first thing a user does after a page load)
if(parcelnum != null) unselectParcel();
// turn off info panel when new search is made
document.getElementById("infoDiv").style.display = "none";
// get the parcel number from the selected parcel
theView.hitTest(event).then((response) =>
{
// get the parcel number
parcelnum = response.results[0].graphic.attributes.Name;
// then select the parcel
selectParcel();
});
});
searchWidget.on("search-start", function()
{
// unselect any currently selected parcels when the user starts a new search (except if it's the first thing a user does after a page load)
if(parcelnum != null) unselectParcel();
// turn off info panel when new search is made
document.getElementById("infoDiv").style.display = "none";
});
// this handles getting the address or tax parcel # from the search widget
searchWidget.on("select-result", function()
{
var searchexpression = new RegExp("^([0-9]{2}-)");
var testexp = searchexpression.test(searchWidget.searchTerm);
if(testexp == false) // searching address points layer
{
selectParcelFromAddressPts();
// Zoom to the selected parcel
theView.goTo({ scale: 800 });
//theView.goTo(theExtent);
}
if(testexp == true) // searching tax parcels layer
{
parcelnum = searchWidget.searchTerm;
selectParcel();
}
});
/*
if(searchWidget.selectedResult == -1) // searching address points layer
{
selectParcelFromAddressPts();
// Zoom to the selected parcel
theView.goTo({ scale: 800 });
//theView.goTo(theExtent);
}
if(searchWidget.activeSourceIndex == 1) // searching tax parcels layer
{
parcelnum = searchWidget.searchTerm;
selectParcel();
}
}); */
// this is called from the searchWidget.on handler above when user searches via address
function selectParcelFromAddressPts()
{
var temp = searchWidget.searchTerm;
var addr = temp.split(",")[0];
var ptsQuery = addressPtsLayer.createQuery();
ptsQuery.where = "FULLADDR = '" + addr + "'";
ptsQuery.outFields = ["ADDPTKEY"];
addressPtsLayer.queryFeatures(ptsQuery).then(function(response)
{
parcelsQuery = parcelsLayer.createQuery();
parcelnum = response.features[0].attributes["ADDPTKEY"];
parcelsQuery.where = "Name = '" + parcelnum + "'";
parcelsLayer.queryFeatures(parcelsQuery).then(function(newresponse)
{
theView.whenLayerView(parcelsLayer).then(function(layerView)
{
var feature = newresponse.features[0];
selectedParcel = layerView.highlight(feature.attributes["OBJECTID"]);
// open the popup
theView.popup.open(
{
features: newresponse.features
});
});
});
});
}
}); // end of require
function getData()
{
// first get the xcoord and ycoord for the econ districts and elected officials, then need to call the other functions from inside the fetch statement to make it wait for xcoord and ycoord to finish
// this is done by getting the centroid of the parcel using the parcel number
var XYurl = "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer_Pub/FeatureServer/18/query?where=Name%3D%27" + parcelnum + "%27&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelIntersects&resultType=none&distance=0.0&units=esriSRUnit_Meter&returnGeodetic=true&outFields=*&returnGeometry=true&returnCentroid=true&featureEncoding=esriDefault&multipatchOption=xyFootprint&applyVCSProjection=false&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&returnQueryGeometry=false&returnDistinctValues=false&cacheHint=false&returnZ=false&returnM=false&returnExceededLimitFeatures=true&sqlFormat=none&f=pjson";
spinner.style.display = "block";
fetch(XYurl).then(data => data.json()).then((result) =>
{
var obj1 = JSON.stringify(result);
var obj2 = JSON.parse(obj1);
xcoord = obj2.features[0].centroid.x;
ycoord = obj2.features[0].centroid.y;
getInfoAndPhotos();
getEconDistricts();
getElectedOfficials();
document.getElementById("basicvalueinfo").className = "container-fluid tab-pane active";
document.getElementById("basicvaluetab").className = "nav-link active";
document.getElementById("ownertab").className = "nav-link";
document.getElementById("econtab").className = "nav-link";
document.getElementById("photostab").className = "nav-link";
document.getElementById("toolstab").className = "nav-link";
document.getElementById("electedtab").className = "nav-link";
document.getElementById("faqtab").className = "nav-link";
}).then(() => // doing this, plus the one second delay below, makes the bottom info panel delay showing long enough to wait for all the data to load
{
setTimeout(function()
{
spinner.style.display = "none";
infoDiv.style.display = "block";
},1000);
});
theView.popup.close(); // hide the popup
}
function selectParcel()
{
parcelsQuery = parcelsLayer.createQuery();
parcelsQuery.where = "Name = '" + parcelnum + "'";
parcelsLayer.queryFeatures(parcelsQuery).then(function(response)
{
theView.whenLayerView(parcelsLayer).then(function(layerView)
{
var feature = response.features[0];
selectedParcel = layerView.highlight(feature.attributes["OBJECTID"]);
});
});
}
function unselectParcel()
{
if(selectedParcel) selectedParcel.remove();
}
// This is for the info container resizing functionality
$(document).ready(function ()
{
$(".resizable").resizable({ handles: {'n': '#infoDivHeader' }});
});
function closeMe(id)
{
if(id == "videoContainer")
{
helpVideo.pause();
helpVideo.currentTime = 0;
}
document.getElementById(id).style.display = "none";
}
function openHelp()
{
helpContainer.style.display = "block";
}
function openVideo()
{
videoContainer.style.display = "block";
}
function question()
{
window.open("https://arcg.is/1zWmnK");
}
function correctPropertyInfo()
{
window.open("https://survey123.arcgis.com/share/6f3b43141488445688e75d6aeb816cc6?" + "field:parcelnum=" + parcelnum + "&field:mailaddress=" + situs_address + "&field:land_area=" + lot_sqft); // done
}
function changeAddress()
{
window.open("https://survey123.arcgis.com/share/080b056084104f4399fc75f3620f0e41?" + "field:property_number_from_tax_bill=" + parcelnum); // done
}
function mergeProperty()
{
window.open("http://www.google.com"); // placeholder
}
function PrintStuff()
{
var mapImg;
var printWindow = window.open('', '', 'height=600px,width=800px');
printWindow.document.write('<html><body>');
var timestamp = Date(Date.now());
printWindow.document.write('<b>Report Created: </b> ' + timestamp.toString() + '<br/>');
if (chkInfo.checked == true)
{
var divParcelNum = document.getElementById("lblParcelNum").innerText;
var divSitusAddr = document.getElementById("lblSitusAddr").innerText;
var divSitusCityStateZip = document.getElementById("lblSitusCityStateZip").innerText;
var divLotSize = document.getElementById("lblLotSize").innerText;
var divBldgSqFt = document.getElementById("lblBldgSqFt").innerText;
var divNumBeds = document.getElementById("lblNumBR").innerText;
var divNumBaths = document.getElementById("lblNumBaths").innerText;
var divYearBuilt = document.getElementById("lblYearBuilt").innerText;
var divTCA = document.getElementById("lblTCA").innerText;
var divusecode = document.getElementById("lblUseCode").innerText;
var divExemption = document.getElementById("lblExemption").innerText;
var divLegalDescr = document.getElementById("lblLegalDescr").innerText;
printWindow.document.write('<table style="width:100%">');
printWindow.document.write('<tr><h1><b>Basic Information</b></h1></tr>');
printWindow.document.write('<tr><td><b>Parcel #</b></td><td>' + divParcelNum + '</td></tr>');
printWindow.document.write('<tr><td><b>Address:</b></td><td>' + divSitusAddr + '</td></tr>');
printWindow.document.write('<tr><td></td><td>' + divSitusCityStateZip + '</td></tr>');
printWindow.document.write('<tr><td><b>Lot Size:</b></td><td>' + divLotSize + '</td></tr>');
printWindow.document.write('<tr><td><b>Bldg sq ft:</b></td><td>' + divBldgSqFt + '</td></tr>');
printWindow.document.write('<tr><td><b>#Beds:   </b>' + divNumBeds + '</td><td><b>#Baths:   </b>' + divNumBaths + '</td></tr>');
printWindow.document.write('<tr><td><b>Year Built:</b></td><td>' + divYearBuilt + '</td></tr>');
printWindow.document.write('<tr><td><b>Tax Code Area:</b></td><td>' + divTCA + '</td></tr>');
printWindow.document.write('<tr><td><b>Land Use Code:</b></td><td>' + divusecode + '</td></tr>');
printWindow.document.write('<tr><td><b>Exemption:</b></td><td>' + divExemption + '</td></tr>');
printWindow.document.write('<tr><td colspan=2><b>Legal Description:</b></td></tr>');
printWindow.document.write('<tr><td colspan=2>' + divLegalDescr + '</td></tr>');
printWindow.document.write('</table>');
var divYear0 = document.getElementById("lblYear0").innerText;
var divYear1 = document.getElementById("lblYear1").innerText;
var divYear2 = document.getElementById("lblYear2").innerText;
var divYear3 = document.getElementById("lblYear3").innerText;
var divYear0AgLand = document.getElementById("lblYear0AgLand").innerText; var divYear1AgLand = document.getElementById("lblYear1AgLand").innerText; var divYear2AgLand = document.getElementById("lblYear2AgLand").innerText; var divYear3AgLand = document.getElementById("lblYear3AgLand").innerText;
var divYear0CommLand = document.getElementById("lblYear0CommLand").innerText; var divYear1CommLand = document.getElementById("lblYear1CommLand").innerText; var divYear2CommLand = document.getElementById("lblYear2CommLand").innerText; var divYear3CommLand = document.getElementById("lblYear3CommLand").innerText;
var divYear0ResLand = document.getElementById("lblYear0ResLand").innerText; var divYear1ResLand = document.getElementById("lblYear1ResLand").innerText; var divYear2ResLand = document.getElementById("lblYear2ResLand").innerText; var divYear3ResLand = document.getElementById("lblYear3ResLand").innerText;
var divYear0AgImp = document.getElementById("lblYear0AgImp").innerText; var divYear1AgImp = document.getElementById("lblYear1AgImp").innerText; var divYear2AgImp = document.getElementById("lblYear2AgImp").innerText; var divYear3AgImp = document.getElementById("lblYear3AgImp").innerText;
var divYear0CommImp = document.getElementById("lblYear0CommImp").innerText; var divYear1CommImp = document.getElementById("lblYear1CommImp").innerText; var divYear2CommImp = document.getElementById("lblYear2CommImp").innerText; var divYear3CommImp = document.getElementById("lblYear3CommImp").innerText;
var divYear0ResImp = document.getElementById("lblYear0ResImp").innerText; var divYear1ResImp = document.getElementById("lblYear1ResImp").innerText; var divYear2ResImp = document.getElementById("lblYear2ResImp").innerText; var divYear3ResImp = document.getElementById("lblYear3ResImp").innerText;
var divYear0AgNC = document.getElementById("lblYear0AgNC").innerText; var divYear1AgNC = document.getElementById("lblYear1AgNC").innerText; var divYear2AgNC = document.getElementById("lblYear2AgNC").innerText; var divYear3AgNC = document.getElementById("lblYear3AgNC").innerText;
var divlblYear0CommNC = document.getElementById("lblYear0CommNC").innerText; var divlblYear1CommNC = document.getElementById("lblYear1CommNC").innerText; var divlblYear2CommNC = document.getElementById("lblYear2CommNC").innerText; var divlblYear3CommNC = document.getElementById("lblYear3CommNC").innerText;
var divYear0ResNC = document.getElementById("lblYear0ResNC").innerText; var divYear1ResNC = document.getElementById("lblYear1ResNC").innerText; var divYear2ResNC = document.getElementById("lblYear2ResNC").innerText; var divYear3ResNC = document.getElementById("lblYear3ResNC").innerText;
var divYear0TMV = document.getElementById("lblYear0TMV").innerText; var divYear1TMV = document.getElementById("lblYear1TMV").innerText; var divYear2TMV = document.getElementById("lblYear2TMV").innerText; var divYear3TMV = document.getElementById("lblYear3TMV").innerText;
var divYear0TAV = document.getElementById("lblYear0TAV").innerText; var divYear1TAV = document.getElementById("lblYear1TAV").innerText; var divYear2TAV = document.getElementById("lblYear2TAV").innerText; var divYear3TAV = document.getElementById("lblYear3TAV").innerText;
var divYear0TTV = document.getElementById("lblYear0TTV").innerText; var divYear1TTV = document.getElementById("lblYear1TTV").innerText; var divYear2TTV = document.getElementById("lblYear2TTV").innerText; var divYear3TTV = document.getElementById("lblYear3TTV").innerText;
var divOwner1Name = document.getElementById("lblOwner1Name").innerText;
var divOwner1Addr = document.getElementById("lblOwner1Address").innerText;
//var divOwner1CityStateZip = document.getElementById("lblowner1citystatezipcountry").innerText;
printWindow.document.write('<table style="width:100%">');
printWindow.document.write('<tr><h1><b>Property Values</b></h1></tr>');
printWindow.document.write('<tr><td colspan=2><b>Value Type</b></td><td><b>' + divYear0 + '</b></td><td><b>' + divYear1 + '</b></td><td><b>' + divYear2 + '</b></td><td><b>' + divYear3 + '</b></td></tr>');
printWindow.document.write('<tr><td colspan=2><u>Land Value</u></td><td colspan=4></td></tr>');
printWindow.document.write('<tr><td colspan=2>Agricultural:</td><td>' + divYear0AgLand + '</td><td>' + divYear1AgLand + '</td><td>' + divYear2AgLand + '</td><td>' + divYear3AgLand + '</td></tr>');
printWindow.document.write('<tr><td colspan=2>Commercial:</td><td>' + divYear0CommLand + '</td><td>' + divYear1CommLand + '</td><td>' + divYear2CommLand + '</td><td>' + divYear3CommLand + '</td></tr>');
printWindow.document.write('<tr><td colspan=2>Residential:</td><td>' + divYear0ResLand + '</td><td>' + divYear1ResLand + '</td><td>' + divYear2ResLand + '</td><td>' + divYear3ResLand + '</td></tr>');
printWindow.document.write('<tr><td colspan=2><u>Improvements Value</u></td><td colspan=4</td></tr>');
printWindow.document.write('<tr><td colspan=2>Agricultural:</td><td>' + divYear0AgImp + '</td><td>' + divYear1AgImp + '</td><td>' + divYear2AgImp + '</td><td>' + divYear3AgImp + '</td></tr>');
printWindow.document.write('<tr><td colspan=2>Commercial:</td><td>' + divYear0CommImp + '</td><td>' + divYear1CommImp + '</td><td>' + divYear2CommImp + '</td><td>' + divYear3CommImp + '</td></tr>');
printWindow.document.write('<tr><td colspan=2>Residential:</td><td>' + divYear0ResImp + '</td><td>' + divYear1ResImp + '</td><td>' + divYear2ResImp + '</td><td>' + divYear3ResImp + '</td></tr>');
printWindow.document.write('<tr><td colspan=2><u>New Construction Value</u></td><td colspan=4</td></tr>');
printWindow.document.write('<tr><td colspan=2>Agricultural:</td><td>' + divYear0AgNC + '</td><td>' + divYear1AgNC + '</td><td>' + divYear2AgNC + '</td><td>' + divYear3AgNC + '</td></tr>');
printWindow.document.write('<tr><td colspan=2>Commercial:</td><td>' + divlblYear0CommNC + '</td><td>' + divlblYear1CommNC + '</td><td>' + divlblYear2CommNC + '</td><td>' + divlblYear3CommNC + '</td></tr>');
printWindow.document.write('<tr><td colspan=2>Residential:</td><td>' + divYear0ResNC + '</td><td>' + divYear1ResNC + '</td><td>' + divYear2ResNC + '</td><td>' + divYear3ResNC + '</td></tr>');
printWindow.document.write('</table>');
printWindow.document.write('<hr>');
printWindow.document.write('<table style="width:100%">');
printWindow.document.write('<tr><td colspan=2>Total Market Value:</td><td>' + divYear0TMV + '</td><td>' + divYear1TMV + '</td><td>' + divYear2TMV + '</td><td>' + divYear3TMV + '</td></tr>');
printWindow.document.write('<tr><td colspan=2>Total Assessed Value:</td><td>' + divYear0TAV + '</td><td>' + divYear1TAV + '</td><td>' + divYear2TAV + '</td><td>' + divYear3TAV + '</td></tr>');
printWindow.document.write('<tr><td colspan=2>Total Taxable Value:</td><td>' + divYear0TTV + '</td><td>' + divYear1TTV + '</td><td>' + divYear2TTV + '</td><td>' + divYear3TTV + '</td></tr>');
printWindow.document.write('</table>');
printWindow.document.write('<table style="width:100%">');
printWindow.document.write('<tr><h1><b>Primary Owner</b></h1></tr>');
printWindow.document.write('<tr><td>' + divOwner1Name + '</td></tr>');
printWindow.document.write('<tr><td>' + divOwner1Addr + '</td></tr>');
//printWindow.document.write('<tr><td>' + divOwner1CityStateZip + '</td></tr>');
printWindow.document.write('</table>');
}
if (chkPhotos.checked == true)
{
// always put this on a new page
printWindow.document.write('<p style="page-break-before: always;"> </p>');
printWindow.document.write('<h1><b>Photos</b></h1>');
for(var i = 0; i < photoCount; i++)
{
printWindow.document.write("<img src='" + photos_array[i] + "' style='width:100%'/>");
}
}
if (chkMap.checked == true)
{
// always put this on a new page
printWindow.document.write('<p style="page-break-before: always;"> </p>');
theView.takeScreenshot().then(function(screenshot)
{
mapImg = screenshot.dataUrl;
printWindow.document.write('<h1><b>Map</b></h1>');
printWindow.document.write("<img src='" + mapImg + "' style='width:100%,height:100%;'/>");
});
}
printWindow.document.write('</body></html>');
//delay just slightly - 0.5 seconds - this ensures that map and photos load into browser's print preview
printWindow.setTimeout(function()
{
printWindow.print();
}, 500);
} // end of PrintStuff function
// This is called when the user clicks on one of the buttons to do a BOE appeal
function doAppeal(appealtype)
{
var LatLongServiceURL = "https://jcgis.jacksongov.org/arcgis/rest/services/Utilities/Geometry/GeometryServer/project?inSR=102698&outSR=4326&geometries=%7B%0D%0A++%22geometryType%22+%3A+%22esriGeometryPoint%22%2C%0D%0A++%22geometries%22+%3A+%5B%0D%0A+++++%7B%0D%0A+++++++%22x%22+%3A+" + xcoord + "%2C++++++++%22y%22+%3A+" + ycoord + "%0D%0A+++++%7D%0D%0A++%5D%0D%0A%7D&transformation=&transformForward=true&vertical=false&f=pjson";
fetch(LatLongServiceURL).then(data => data.json()).then((result) =>
{
var obj1 = JSON.stringify(result);
var obj2 = JSON.parse(obj1);
lat = obj2.geometries[0].x;
lon = obj2.geometries[0].y;
}).then(() => // force it to wait for lat and lon to arrive
{
if(appealtype == "formal")
window.open("https://survey123.arcgis.com/share/717d975e6b914f53b2a0fa7c546331a7?" + "field:situs_or_location_address=" + situs_address +
"&field:parcel_number=" + parcelnum + "&field:tax2=" + legaldescription + "&field:ownerappellant=" + owner +
"&field:prop_use_jan=" + landusecode + "&field:tca=" + TCA + "&field:nbhd=" + nhood + "&field:exemption=" + exemption + "&field:ascend_bldg_sqft=" + bldg_sqft +
"&field:ascend_num_beds=" + num_beds + "&field:ascend_num_baths=" + num_baths + "&field:bv_ag_lnd=" + land_ag_val +
"&field:bv_com_lnd=" + land_com_val + "&field:bv_res_lnd=" + land_res_val + "&field:bv_ag_imp=" + imp_ag_val + "&field:bv_com_imp=" + imp_com_val +
"&field:bv_res_imp=" + imp_res_val + "&field:bv_ag_nc=" + newcon_ag_val + "&field:bv_com_nc=" + newcon_com_val + "&field:bv_res_nc=" + newcon_res_val +
"&field:bv_tm=" + TMV + "&field:bv_ta=" + TAV + "&field:bv_tt=" + TTV + "&field:ascend_year_built=" + year_built + "¢er=" + lon + "," + lat, '_self');
else //appealtype == "informal"
window.open("https://survey123.arcgis.com/share/5d04b51f6a4748568e64cc86c1462183?" + "field:situs_or_location_address=" + situs_address +
"&field:parcel_number=" + parcelnum + "&field:tax2=" + legaldescription + "&field:ownerappellant=" + owner +
"&field:prop_use_jan=" + landusecode + "&field:tca=" + TCA + "&field:nbhd=" + nhood + "&field:exemption=" + exemption + "&field:ascend_bldg_sqft=" + bldg_sqft +
"&field:ascend_num_beds=" + num_beds + "&field:ascend_num_baths=" + num_baths + "&field:bv_ag_lnd=" + land_ag_val +
"&field:bv_com_lnd=" + land_com_val + "&field:bv_res_lnd=" + land_res_val + "&field:bv_ag_imp=" + imp_ag_val + "&field:bv_com_imp=" + imp_com_val +
"&field:bv_res_imp=" + imp_res_val + "&field:bv_ag_nc=" + newcon_ag_val + "&field:bv_com_nc=" + newcon_com_val + "&field:bv_res_nc=" + newcon_res_val +
"&field:bv_tm=" + TMV + "&field:bv_ta=" + TAV + "&field:bv_tt=" + TTV + "&field:ascend_year_built=" + year_built + "¢er=" + lon + "," + lat, '_self');
});
}<file_sep>function getInfoAndPhotos()
{
var url = "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer_Pub/FeatureServer/38/query?where=Name%3D%27" + parcelnum + "%27&objectIds=&time=&resultType=none&outFields=*&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnDistinctValues=true&cacheHint=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&having=&resultOffset=&resultRecordCount=&sqlFormat=none&f=pjson&token=";
fetch(url).then(data => data.json()).then((result) =>
{
/////////////// BASIC INFORMATION ///////////////
var obj1 = JSON.stringify(result);
var obj2 = JSON.parse(obj1);
document.getElementById("lblParcelNum").innerHTML = parcelnum;
document.getElementById("lblSitusAddr").innerHTML = obj2.features[0].attributes.primary_situs_addr; situs_address = obj2.features[0].attributes.primary_situs_addr;
document.getElementById("lblLotSize").innerHTML = obj2.features[0].attributes.tot_sqf_l_area.toLocaleString() + " Sq. Ft.";
document.getElementById("lblBldgSqFt").innerHTML = obj2.features[0].attributes.base_fl_area.toLocaleString() + " Sq. Ft."; bldg_sqft = obj2.features[0].attributes.base_fl_area; // used for appeals form
document.getElementById("lblNumBR").innerHTML = obj2.features[0].attributes.num_bedrooms; num_beds = obj2.features[0].attributes.num_bedrooms; // used for appeals form
var half_baths = parseFloat(obj2.features[0].attributes.half_baths) * 0.5;
var full_baths = parseFloat(obj2.features[0].attributes.full_baths);
num_baths = full_baths + half_baths; // also used for appeals form
document.getElementById("lblNumBaths").innerHTML = num_baths;
if(obj2.features[0].attributes.year_built != "0") document.getElementById("lblYearBuilt").innerHTML = obj2.features[0].attributes.year_built;
else document.getElementById("lblYearBuilt").innerHTML = "N/A";
year_built = obj2.features[0].attributes.year_built; // used for appeals form
document.getElementById("lblTCA").innerHTML = obj2.features[0].attributes.tcacode; TCA = obj2.features[0].attributes.tcacode; // used for appeals form
document.getElementById("lblUseCode").innerHTML = obj2.features[0].attributes.landuse_cd_descr; landusecode = obj2.features[0].attributes.landuse_cd_descr; // used for appeals form
if(obj2.features[0].attributes.exmpt_descr != "0") document.getElementById("lblExemption").innerHTML = obj2.features[0].attributes.exmpt_descr;
else document.getElementById("lblExemption").innerHTML = "None";
exemption = obj2.features[0].attributes.exmpt_descr; // used for appeals form
document.getElementById("lblLegalDescr").innerHTML = obj2.features[0].attributes.tax_legal_descr; legaldescription = obj2.features[0].attributes.tax_legal_descr; // used for appeals form
nhood = ""; // need to get this somewhere // used for appeals form
/////////////// TAX YEAR TABLE COLUMN HEADINGS ///////////////
document.getElementById("lblYear0").innerHTML = obj2.features[0].attributes.tax_year;
document.getElementById("lblYear1").innerHTML = obj2.features[0].attributes.tax_year_pastyr1;
document.getElementById("lblYear2").innerHTML = obj2.features[0].attributes.tax_year_pastyr2;
document.getElementById("lblYear3").innerHTML = obj2.features[0].attributes.tax_year_pastyr3;
/////////////// YEAR 0 ITEMS ///////////////
document.getElementById("lblYear0AgLand").innerHTML = "$" + obj2.features[0].attributes.Ag_Land.toLocaleString(); land_ag_val = obj2.features[0].attributes.Ag_Land.toLocaleString(); // used for appeals form
document.getElementById("lblYear0CommLand").innerHTML = "$" + obj2.features[0].attributes.Comm_Land.toLocaleString(); land_com_val = obj2.features[0].attributes.Comm_Land.toLocaleString(); // used for appeals form
document.getElementById("lblYear0ResLand").innerHTML = "$" + obj2.features[0].attributes.Res_Land.toLocaleString(); land_res_val = obj2.features[0].attributes.Res_Land.toLocaleString(); // used for appeals form
document.getElementById("lblYear0AgImp").innerHTML = "$" + obj2.features[0].attributes.Ag_Impr.toLocaleString(); imp_ag_val = obj2.features[0].attributes.Ag_Impr.toLocaleString(); // used for appeals form
document.getElementById("lblYear0CommImp").innerHTML = "$" + obj2.features[0].attributes.Comm_Impr.toLocaleString(); imp_com_val = obj2.features[0].attributes.Comm_Impr.toLocaleString(); // used for appeals form
document.getElementById("lblYear0ResImp").innerHTML = "$" + obj2.features[0].attributes.Res_Impr.toLocaleString(); imp_res_val = obj2.features[0].attributes.Res_Impr.toLocaleString(); // used for appeals form
document.getElementById("lblYear0AgNC").innerHTML = "$" + obj2.features[0].attributes.Ag_Impr_New_Constr.toLocaleString(); newcon_ag_val = obj2.features[0].attributes.Ag_Impr_New_Constr.toLocaleString(); // is there an ag impr new construction? used for appeals form
var Comm_Land_New_Constr = parseFloat(obj2.features[0].attributes.Comm_Land_New_Constr);
var Comm_Impr_New_Constr = parseFloat(obj2.features[0].attributes.Comm_Impr_New_Constr);
newcon_com_val = Comm_Land_New_Constr + Comm_Impr_New_Constr; // also used for appeals form
document.getElementById("lblYear0CommNC").innerHTML = "$" + newcon_com_val.toLocaleString();
var Res_Land_New_Const = parseFloat(obj2.features[0].attributes.Res_Land_New_Const);
var Res_Impr_New_Const = parseFloat(obj2.features[0].attributes.Res_Impr_New_Constr);
newcon_res_val = Res_Land_New_Const + Res_Impr_New_Const; // also used for appeals form
document.getElementById("lblYear0ResNC").innerHTML = "$" + newcon_res_val.toLocaleString();
document.getElementById("lblYear0TMV").innerHTML = "$" + obj2.features[0].attributes.Market_Value_Total.toLocaleString(); TMV = obj2.features[0].attributes.Market_Value_Total.toLocaleString(); // used for appeals form
document.getElementById("lblYear0TAV").innerHTML = "$" + obj2.features[0].attributes.Assessed_Val_Total.toLocaleString(); TAV = obj2.features[0].attributes.Assessed_Val_Total.toLocaleString(); // used for appeals form
document.getElementById("lblYear0TTV").innerHTML = "$" + obj2.features[0].attributes.Taxable_Value_Total.toLocaleString(); TTV = obj2.features[0].attributes.Taxable_Value_Total.toLocaleString(); // used for appeals form
/////////////// YEAR 1 ITEMS ///////////////
document.getElementById("lblYear1AgLand").innerHTML = "$" + obj2.features[0].attributes.Ag_Land_pastyr1.toLocaleString();
document.getElementById("lblYear1CommLand").innerHTML = "$" + obj2.features[0].attributes.Comm_Land_pastyr1.toLocaleString();
document.getElementById("lblYear1ResLand").innerHTML = "$" + obj2.features[0].attributes.Res_Land_pastyr1.toLocaleString();
document.getElementById("lblYear1AgImp").innerHTML = "$" + obj2.features[0].attributes.Ag_Impr_pastyr1.toLocaleString();
document.getElementById("lblYear1CommImp").innerHTML = "$" + obj2.features[0].attributes.Comm_Impr_pastyr1.toLocaleString();
document.getElementById("lblYear1ResImp").innerHTML = "$" + obj2.features[0].attributes.Res_Impr_pastyr1.toLocaleString();
document.getElementById("lblYear1AgNC").innerHTML = "$" + obj2.features[0].attributes.Ag_Impr_New_Constr_pastyr1.toLocaleString();
var Comm_Land_New_Constr_pastyr1 = parseFloat(obj2.features[0].attributes.Comm_Land_New_Constr_pastyr1);
var Comm_Impr_New_Constr_pastyr1 = parseFloat(obj2.features[0].attributes.Comm_Impr_New_Constr_pastyr1);
var Comm_New_Constr_pastyr1 = Comm_Land_New_Constr_pastyr1 + Comm_Impr_New_Constr_pastyr1;
document.getElementById("lblYear1CommNC").innerHTML = "$" + Comm_New_Constr_pastyr1.toLocaleString();
var Res_Land_New_Const_pastyr1 = parseFloat(obj2.features[0].attributes.Res_Land_New_Const_pastyr1);
var Res_Impr_New_Const_pastyr1 = parseFloat(obj2.features[0].attributes.Res_Impr_New_Constr_pastyr1);
var Res_New_Const_pastyr1 = Res_Land_New_Const_pastyr1 + Res_Impr_New_Const_pastyr1;
document.getElementById("lblYear1ResNC").innerHTML = "$" + Res_New_Const_pastyr1.toLocaleString();
document.getElementById("lblYear1TMV").innerHTML = "$" + obj2.features[0].attributes.Market_Value_Total_pastyr1.toLocaleString();
document.getElementById("lblYear1TAV").innerHTML = "$" + obj2.features[0].attributes.Assessed_Val_Total_pastyr1.toLocaleString();
document.getElementById("lblYear1TTV").innerHTML = "$" + obj2.features[0].attributes.Taxable_Value_Total_pastyr1.toLocaleString();
/////////////// YEAR 2 ITEMS ///////////////
document.getElementById("lblYear2AgLand").innerHTML = "$" + obj2.features[0].attributes.Ag_Land_pastyr2.toLocaleString();
document.getElementById("lblYear2CommLand").innerHTML = "$" + obj2.features[0].attributes.Comm_Land_pastyr2.toLocaleString();
document.getElementById("lblYear2ResLand").innerHTML = "$" + obj2.features[0].attributes.Res_Land_pastyr2.toLocaleString();
document.getElementById("lblYear2AgImp").innerHTML = "$" + obj2.features[0].attributes.Ag_Impr_pastyr2.toLocaleString();
document.getElementById("lblYear2CommImp").innerHTML = "$" + obj2.features[0].attributes.Comm_Impr_pastyr2.toLocaleString();
document.getElementById("lblYear2ResImp").innerHTML = "$" + obj2.features[0].attributes.Res_Impr_pastyr2.toLocaleString();
document.getElementById("lblYear2AgNC").innerHTML = "$" + obj2.features[0].attributes.Ag_Impr_New_Constr_pastyr2.toLocaleString();
var Comm_Land_New_Constr_pastyr2 = parseFloat(obj2.features[0].attributes.Comm_Land_New_Constr_pastyr2);
var Comm_Impr_New_Constr_pastyr2 = parseFloat(obj2.features[0].attributes.Comm_Impr_New_Constr_pastyr2);
var Comm_New_Constr_pastyr2 = Comm_Land_New_Constr_pastyr2 + Comm_Impr_New_Constr_pastyr2;
document.getElementById("lblYear2CommNC").innerHTML = "$" + Comm_New_Constr_pastyr2.toLocaleString();
var Res_Land_New_Const_pastyr2 = parseFloat(obj2.features[0].attributes.Res_Land_New_Const_pastyr2);
var Res_Impr_New_Const_pastyr2 = parseFloat(obj2.features[0].attributes.Res_Impr_New_Constr_pastyr2);
var Res_New_Const_pastyr2 = Res_Land_New_Const_pastyr2 + Res_Impr_New_Const_pastyr2;
document.getElementById("lblYear2ResNC").innerHTML = "$" + Res_New_Const_pastyr2.toLocaleString();
document.getElementById("lblYear2TMV").innerHTML = "$" + obj2.features[0].attributes.Market_Value_Total_pastyr2.toLocaleString();
document.getElementById("lblYear2TAV").innerHTML = "$" + obj2.features[0].attributes.Assessed_Val_Total_pastyr2.toLocaleString();
document.getElementById("lblYear2TTV").innerHTML = "$" + obj2.features[0].attributes.Taxable_Value_Total_pastyr2.toLocaleString();
/////////////// YEAR 3 ITEMS ///////////////
document.getElementById("lblYear3AgLand").innerHTML = "$" + obj2.features[0].attributes.Ag_Land_pastyr3.toLocaleString();
document.getElementById("lblYear3CommLand").innerHTML = "$" + obj2.features[0].attributes.Comm_Land_pastyr3.toLocaleString();
document.getElementById("lblYear3ResLand").innerHTML = "$" + obj2.features[0].attributes.Res_Land_pastyr3.toLocaleString();
document.getElementById("lblYear3AgImp").innerHTML = "$" + obj2.features[0].attributes.Ag_Impr_pastyr3.toLocaleString();
document.getElementById("lblYear3CommImp").innerHTML = "$" + obj2.features[0].attributes.Comm_Impr_pastyr3.toLocaleString();
document.getElementById("lblYear3ResImp").innerHTML = "$" + obj2.features[0].attributes.Res_Impr_pastyr3.toLocaleString();
document.getElementById("lblYear3AgNC").innerHTML = "$" + obj2.features[0].attributes.Ag_Impr_New_Constr_pastyr3.toLocaleString();
var Comm_Land_New_Constr_pastyr3 = parseFloat(obj2.features[0].attributes.Comm_Land_New_Constr_pastyr3);
var Comm_Impr_New_Constr_pastyr3 = parseFloat(obj2.features[0].attributes.Comm_Impr_New_Constr_pastyr3);
var Comm_New_Constr_pastyr3 = Comm_Land_New_Constr_pastyr3 + Comm_Impr_New_Constr_pastyr3;
document.getElementById("lblYear3CommNC").innerHTML = "$" + Comm_New_Constr_pastyr3.toLocaleString();
var Res_Land_New_Const_pastyr3 = parseFloat(obj2.features[0].attributes.Res_Land_New_Const_pastyr3);
var Res_Impr_New_Const_pastyr3 = parseFloat(obj2.features[0].attributes.Res_Impr_New_Constr_pastyr3);
var Res_New_Const_pastyr3 = Res_Land_New_Const_pastyr3 + Res_Impr_New_Const_pastyr3;
document.getElementById("lblYear3ResNC").innerHTML = "$" + Res_New_Const_pastyr3.toLocaleString();
document.getElementById("lblYear3TMV").innerHTML = "$" + obj2.features[0].attributes.Market_Value_Total_pastyr3.toLocaleString();
document.getElementById("lblYear3TAV").innerHTML = "$" + obj2.features[0].attributes.Assessed_Val_Total_pastyr3.toLocaleString();
document.getElementById("lblYear3TTV").innerHTML = "$" + obj2.features[0].attributes.Taxable_Value_Total_pastyr3.toLocaleString();
/////////////// OWNER INFO ///////////////
var owners_temp = obj2.features[0].attributes.owner;
var ownaddr_temp = obj2.features[0].attributes.address_compl;
var owners_array = owners_temp.split('|');
var ownaddr_array = ownaddr_temp.split('|');
owner = owners_array[0]; // for BOE appeal forms
if(owners_array.length == 1)
{
firstowner.style.display = "block";
secondowner.style.display = "none";
otherowners.style.display = "none";
}
if(owners_array.length == 2)
{
firstowner.style.display = "block";
secondowner.style.display = "block";
otherowners.style.display = "none";
}
if(owners_array.length > 2)
{
firstowner.style.display = "block";
secondowner.style.display = "block";
otherowners.style.display = "block";
}
for(var i = 0; i < owners_array.length; i++)
{
if(i == 0)
{
document.getElementById("lblOwner1Name").innerHTML = owners_array[i];
document.getElementById("lblOwner1Address").innerHTML = ownaddr_array[i];
}
if(i == 1)
{
// this is a cheesy way to clear the other owners list but whatever ...
document.getElementById("lblOtherOwnersList").innerHTML = "";
// back to the usual stuff ...
document.getElementById("lblOwner2Name").innerHTML = owners_array[i];
document.getElementById("lblOwner2Address").innerHTML = ownaddr_array[i];
}
if(i > 1)
{
document.getElementById("lblOtherOwnersList").innerHTML += owners_array[i] + "<br/>";
}
}
//document.getElementById("lblOwner1CityStateZipCountry").innerHTML = obj2.features[0].attributes.// might not need this?
//document.getElementById("lblOwner2Name").innerHTML = obj2.features[0].attributes.
//document.getElementById("lblOwner2Address").innerHTML = obj2.features[0].attributes.
//document.getElementById("lblOwner2CityStateZipCountry").innerHTML = obj2.features[0].attributes.
//document.getElementById("lblOtherOwnersList").innerHTML = obj2.features[0].attributes.
//////////////// PHOTOS //////////////////
var photos_temp = obj2.features[0].attributes.full_pict_path;
var photos_temp_array = photos_temp.split('|');
photoCount = photos_temp_array.length;
for(var i = 0; i < photos_temp_array.length; i++)
{
var temp1 = photos_temp_array[i].trim();
var temp2 = temp1.replace("O:\\Pictures", "https://jcgis.jacksongov.org/AscendPics/Pictures");
var temp3 = temp2.replace("O:\\MobileAssessorPhotos", "https://jcgis.jacksongov.org/AscendPics/MobileAssessorPhotos");
var temp4 = temp3.replace("O:\\CameraPhotos", "https://jcgis.jacksongov.org/AscendPics/CameraPhotos");
photos_array[i] = temp4.replace(/\\/g, "/");
if (i == 0) document.getElementById("photos").innerHTML = "<img src='" + photos_array[i] + "' style='height:80%;margin:1%;' onclick='doModal(this.src);'/>";
else document.getElementById("photos").innerHTML += "  <img src='" + photos_array[i] + "' style='height:80%;margin:1%;' onclick='doModal(this.src);'/>";
}
});
}
// This is called from the photos section above
function doModal(imgsrc)
{
theModal.style.display = "block";
modalPhotos.src = imgsrc;
}
function getEconDistricts()
{
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
//var CIDurl = "https://jcgis.jacksongov.org/arcgis/rest/services/Cadastral/Parcel_Viewer_Layers/MapServer/35/query?where=&geometry=" + xcoord + "%2C+" + ycoord + "&geometryType=esriGeometryPoint&spatialRel=esriSpatialRelIntersects&units=esriSRUnit_Foot&outFields=&returnGeometry=false&returnTrueCurves=false&returnIdsOnly=false&returnCountOnly=false&returnZ=false&returnM=false&returnDistinctValues=false&returnExtentOnly=false&featureEncoding=esriDefault&f=pjson";
var CIDurl = "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer_Pub/FeatureServer/35/query?where=&geometry=" + xcoord + "%2C+" + ycoord + "&geometryType=esriGeometryPoint&spatialRel=esriSpatialRelIntersects&units=esriSRUnit_Foot&outFields=&returnGeometry=false&returnTrueCurves=false&returnIdsOnly=false&returnCountOnly=false&returnZ=false&returnM=false&returnDistinctValues=false&returnExtentOnly=false&featureEncoding=esriDefault&f=pjson";
//var TIFdistURL = "https://jcgis.jacksongov.org/arcgis/rest/services/Cadastral/Parcel_Viewer_Layers/MapServer/33/query?where=EFFECTIVEYEARFROM+<%3D%27" + currentYear + "%27+AND+EFFECTIVEYEARTO+>%3D%27" + currentYear + "%27&geometry=" + xcoord + "%2C+" + ycoord + "&geometryType=esriGeometryPoint&spatialRel=esriSpatialRelIntersects&units=esriSRUnit_Foot&outFields=Name%2C+EFFECTIVEYEARFROM%2C+EFFECTIVEYEARTO%2C+DURATION&returnGeometry=false&returnTrueCurves=false&returnIdsOnly=false&returnCountOnly=false&returnZ=false&returnM=false&returnDistinctValues=false&returnExtentOnly=false&featureEncoding=esriDefault&f=json";
var TIFdistURL = "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer_Pub/FeatureServer/33/query?where=EFFECTIVEYEARFROM+<%3D%27" + currentYear + "%27+AND+EFFECTIVEYEARTO+>%3D%27" + currentYear + "%27&geometry=" + xcoord + "%2C+" + ycoord + "&geometryType=esriGeometryPoint&spatialRel=esriSpatialRelIntersects&units=esriSRUnit_Foot&outFields=Name%2C+EFFECTIVEYEARFROM%2C+EFFECTIVEYEARTO%2C+DURATION&returnGeometry=false&returnTrueCurves=false&returnIdsOnly=false&returnCountOnly=false&returnZ=false&returnM=false&returnDistinctValues=false&returnExtentOnly=false&featureEncoding=esriDefault&f=json";
//var TIFprojURL = "https://jcgis.jacksongov.org/arcgis/rest/services/Cadastral/Parcel_Viewer_Layers/MapServer/36/query?where=EFFECTIVEYEARFROM+<%3D%27" + currentYear + "%27+AND+EFFECTIVEYEARTO+>%3D%27" + currentYear + "%27&geometry=" + xcoord + "%2C+" + ycoord + "&geometryType=esriGeometryPoint&spatialRel=esriSpatialRelIntersects&units=esriSRUnit_Foot&outFields=Name%2C+EFFECTIVEYEARFROM%2C+EFFECTIVEYEARTO%2C+DURATION&returnGeometry=false&returnTrueCurves=false&returnIdsOnly=false&returnCountOnly=false&returnZ=false&returnM=false&returnDistinctValues=false&returnExtentOnly=false&featureEncoding=esriDefault&f=json";
var TIFprojURL = "https://services3.arcgis.com/4LOAHoFXfea6Y3Et/arcgis/rest/services/ParcelViewer_Pub/FeatureServer/36/query?where=EFFECTIVEYEARFROM+<%3D%27" + currentYear + "%27+AND+EFFECTIVEYEARTO+>%3D%27" + currentYear + "%27&geometry=" + xcoord + "%2C+" + ycoord + "&geometryType=esriGeometryPoint&spatialRel=esriSpatialRelIntersects&units=esriSRUnit_Foot&outFields=Name%2C+EFFECTIVEYEARFROM%2C+EFFECTIVEYEARTO%2C+DURATION&returnGeometry=false&returnTrueCurves=false&returnIdsOnly=false&returnCountOnly=false&returnZ=false&returnM=false&returnDistinctValues=false&returnExtentOnly=false&featureEncoding=esriDefault&f=json";
fetch(CIDurl).then(data => data.json()).then((resultCID) =>
{
var objCID = JSON.stringify(resultCID);
if(objCID.includes("attributes"))
{
var objCIDparsed = JSON.parse(objCID);
document.getElementById("lblCID").innerHTML = objCIDparsed.features[0].attributes.Name; // Community Improvement District name
}
else document.getElementById("lblCID").innerHTML = "Property is not in a CID for which Jackson County collects a tax or assessment";
});
fetch(TIFdistURL).then(data => data.json()).then((resultTIFdist) =>
{
var objTIFdist = JSON.stringify(resultTIFdist);
if(objTIFdist.includes("attributes"))
{
var objTIFdistparsed = JSON.parse(objTIFdist);
document.getElementById("lblTIFdist").innerHTML = objTIFdistparsed.features[0].attributes.Name; // TIF District name
// start date stuff
var rawfromdateDist = objTIFdistparsed.features[0].attributes.EFFECTIVEYEARFROM; // TIF District start date
var datefromDist = new Date(rawfromdateDist);
var yearfromDist = new Date(datefromDist);
document.getElementById("lblTIFdistStartDate").innerHTML = yearfromDist.getFullYear();
// end date stuff:
var rawenddateDist = objTIFdistparsed.features[0].attributes.EFFECTIVEYEARTO; // TIF District end date
var datetoDist = new Date(rawenddateDist);
var yeartoDist = new Date(datetoDist);
document.getElementById("lblTIFdistEndDate").innerHTML = yeartoDist.getFullYear();
document.getElementById("lblTIFdistDuration").innerHTML = objTIFdistparsed.features[0].attributes.DURATION; // TIF District duration in years
}
else
{
document.getElementById("lblTIFdist").innerHTML = "No known TIF district for this parcel";
document.getElementById("lblTIFdistStartDate").innerHTML = "N/A";
document.getElementById("lblTIFdistEndDate").innerHTML = "N/A";
document.getElementById("lblTIFdistDuration").innerHTML = "N/A";
}
});
fetch(TIFprojURL).then(data => data.json()).then((resultTIFproj) =>
{
var objTIFproj = JSON.stringify(resultTIFproj);
if(objTIFproj.includes("attributes"))
{
var objTIFprojparsed = JSON.parse(objTIFproj);
document.getElementById("lblTIFprojOrd").innerHTML = objTIFprojparsed.features[0].attributes.Name; // TIF Project name
// start date stuff
var rawfromdateProj = objTIFprojparsed.features[0].attributes.EFFECTIVEYEARFROM; // TIF Project start date
var datefromProj = new Date(rawfromdateProj);
var yearfromProj = new Date(datefromProj);
document.getElementById("lblTIFprojStartDate").innerHTML = yearfromProj.getFullYear();
// end date stuff
var rawtodateProj = objTIFprojparsed.features[0].attributes.EFFECTIVEYEARTO; // TIF Project end date
var datetoProj = new Date(rawtodateProj);
var yeartoProj = new Date(datetoProj);
document.getElementById("lblTIFprojEndDate").innerHTML = yeartoProj.getFullYear();
document.getElementById("lblTIFprojDuration").innerHTML = objTIFprojparsed.features[0].attributes.DURATION; // TIF Project duration in years
}
else
{
document.getElementById("lblTIFprojOrd").innerHTML = "No known TIF project for this parcel";
document.getElementById("lblTIFprojStartDate").innerHTML = "N/A";
document.getElementById("lblTIFprojEndDate").innerHTML = "N/A";
document.getElementById("lblTIFprojDuration").innerHTML = "N/A";
}
});
/*
document.getElementById("lbl353descr").innerHTML = obj2.features[0].attributes.; // 353 description, if any
document.getElementById("lbl353fromYr").innerHTML = obj2.features[0].attributes.; // 353 abatement from year
document.getElementById("lbl353toYr").innerHTML = obj2.features[0].attributes.; // 353 abatement to year
document.getElementById("lbl99descr").innerHTML = obj2.features[0].attributes.; // 99 description, if any
document.getElementById("lbl99fromYr").innerHTML = obj2.features[0].attributes.; // 99 abatement from year
document.getElementById("lbl99toYr").innerHTML = obj2.features[0].attributes.; // 99 abatement to year
*/
}
function getElectedOfficials()
{
// These are elected officials common to the entire county and can be hard-coded here
// ----------------------------------------------------------------------------------
$('#lblJaCoExecName').text("<NAME>");
$('#lblJaCoExecParty').text("D");
document.getElementById("hlJaCoExecWebsite").innerHTML = "<a href='http://www.jacksongov.org/395/County-Executive' target='_blank' style='color:blue;margin:0;padding:0'>View Website</a>";
$('#lblMOgovName').text("<NAME>");
$('#lblMOgovParty').text("R");
document.getElementById("hlMOgovWebsite").innerHTML = "<a href='https://governor.mo.gov/' target='_blank' style='color:blue;margin:0;padding:0'>View Website</a>";
$('#lblUSsen1Name').text("<NAME>");
$('#lblUSsen1Party').text("R");
document.getElementById("hlUSsen1Website").innerHTML = "<a href='http://blunt.senate.gov/public/' target='_blank' style='color:blue;margin:0;padding:0'>View Website</a>";
$('#lblUSsen2Name').text("<NAME>");
$('#lblUSsen2Party').text("R");
document.getElementById("hlUSsen2Website").innerHTML = "<a href='https://www.hawley.senate.gov/' target='_blank' style='color:blue;margin:0;padding:0'>View Website</a>";
// ----------------------------------------------------------------------------------
// string URLs and json objects for county council, MO house of reps, MO senate and US rep
// ------------------------------------------------------------------------------------------
var JaCoAtLargeUrl = "https://jcgis.jacksongov.org/arcgis/rest/services/ElectionAdministration/LegislativeDistricts/MapServer/0/query?where=&text=&objectIds=&time=&geometry=" + xcoord + "%2C" + ycoord + "&geometryType=esriGeometryPoint&inSR=102698&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=DISTRICT%2C+Name%2C+Party%2C+WebSite&returnGeometry=false&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&resultOffset=&resultRecordCount=&f=json";
var JaCoIndivUrl = "https://jcgis.jacksongov.org/arcgis/rest/services/ElectionAdministration/LegislativeDistricts/MapServer/1/query?where=&text=&objectIds=&time=&geometry=" + xcoord + "%2C" + ycoord + "&geometryType=esriGeometryPoint&inSR=102698&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=DISTRICT%2C+name%2C+Party%2C+WebSite&returnGeometry=false&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&resultOffset=&resultRecordCount=&f=json";
var MoSenUrl = "https://jcgis.jacksongov.org/arcgis/rest/services/ElectionAdministration/ElectedOfficials/MapServer/1/query?where=&objectIds=&time=&geometry=" + xcoord + "%2C" + ycoord + "&geometryType=esriGeometryPoint&inSR=102698&spatialRel=esriSpatialRelIntersects&distance=&units=esriSRUnit_Foot&relationParam=&outFields=DISTRICT%2C+REPNAME%2C+Party%2C+WebSite&returnGeometry=false&maxAllowableOffset=&geometryPrecision=&outSR=&gdbVersion=&returnDistinctValues=false&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&multipatchOption=&f=json";
var MoRepUrl = "https://jcgis.jacksongov.org/arcgis/rest/services/ElectionAdministration/ElectedOfficials/MapServer/0/query?where=&text=&objectIds=&time=&geometry=" + xcoord + "%2C" + ycoord + "&geometryType=esriGeometryPoint&inSR=102698&spatialRel=esriSpatialRelWithin&relationParam=&outFields=DISTRICT%2C+REPNAME%2C+Party%2C+WebSite&returnGeometry=false&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&resultOffset=&resultRecordCount=&f=pjson";
var UShouseUrl = "https://jcgis.jacksongov.org/arcgis/rest/services/ElectionAdministration/ElectedOfficials/MapServer/2/query?where=&text=&objectIds=&time=&geometry=" + xcoord + "%2C" + ycoord + "&geometryType=esriGeometryPoint&inSR=102698&spatialRel=esriSpatialRelWithin&distance=&units=esriSRUnit_Meter&relationParam=&outFields=DISTRICT%2C+REPNAME%2C+Party%2C+WebSite&returnGeometry=false&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&havingClause=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&historicMoment=&returnDistinctValues=false&resultOffset=&resultRecordCount=&returnExtentOnly=false&datumTransformation=¶meterValues=&rangeValues=&quantizationParameters=&featureEncoding=esriDefault&f=pjson";
// County at-large districts
fetch(JaCoAtLargeUrl).then(data => data.json()).then((result) =>
{
var obj1 = JSON.stringify(result);
var obj2 = JSON.parse(obj1);
document.getElementById("lblJaCoAtLargeName").innerHTML = obj2.features[0].attributes.Name;
document.getElementById("lblJaCoAtLargeParty").innerHTML = obj2.features[0].attributes.Party;
document.getElementById("lblJaCoAtLargeDist").innerHTML = obj2.features[0].attributes.DISTRICT;
if(obj2.features[0].attributes.WebSite == "" || obj2.features[0].attributes.WebSite == null || obj2.features[0].attributes.WebSite == " "|| obj2.features[0].attributes.WebSite == "N/A") document.getElementById("hlJaCoAtLargeWebsite").innerHTML = "Website N/A";
else document.getElementById("hlJaCoAtLargeWebsite").innerHTML = "<a href='" + obj2.features[0].attributes.WebSite + "' target='_blank' style='color:blue'>View Website</a>";
});
// County individual districts
fetch(JaCoIndivUrl).then(data => data.json()).then((result) =>
{
var obj1 = JSON.stringify(result);
var obj2 = JSON.parse(obj1);
document.getElementById("lblJaCoIndivName").innerHTML = obj2.features[0].attributes.name;
document.getElementById("lblJaCoIndivParty").innerHTML = obj2.features[0].attributes.Party;
document.getElementById("lblJaCoIndivDist").innerHTML = obj2.features[0].attributes.DISTRICT;
if(obj2.features[0].attributes.WebSite == "" || obj2.features[0].attributes.WebSite == null || obj2.features[0].attributes.WebSite == " "|| obj2.features[0].attributes.WebSite == "N/A") document.getElementById("hlJaCoIndivWebsite").innerHTML = "Website N/A";
else document.getElementById("hlJaCoIndivWebsite").innerHTML = "<a href='" + obj2.features[0].attributes.WebSite + "' target='_blank' style='color:blue;margin:0;padding:0'>View Website</a>";
});
// State senators
fetch(MoSenUrl).then(data => data.json()).then((result) =>
{
var obj1 = JSON.stringify(result);
var obj2 = JSON.parse(obj1);
document.getElementById("lblMOsenName").innerHTML = obj2.features[0].attributes.REPNAME;
document.getElementById("lblMOsenParty").innerHTML = obj2.features[0].attributes.Party;
document.getElementById("lblMOsenDist").innerHTML = obj2.features[0].attributes.DISTRICT;
if(obj2.features[0].attributes.WebSite == "" || obj2.features[0].attributes.WebSite == null || obj2.features[0].attributes.WebSite == " "|| obj2.features[0].attributes.WebSite == "N/A") document.getElementById("hlMOsenWebsite").innerHTML = "Website N/A";
else document.getElementById("hlMOsenWebsite").innerHTML = "<a href='" + obj2.features[0].attributes.WebSite + "' target='_blank' style='color:blue'>View Website</a>";
});
// State representatives
fetch(MoRepUrl).then(data => data.json()).then((result) =>
{
var obj1 = JSON.stringify(result);
var obj2 = JSON.parse(obj1);
document.getElementById("lblMOrepName").innerHTML = obj2.features[0].attributes.REPNAME;
document.getElementById("lblMOrepParty").innerHTML = obj2.features[0].attributes.Party;
document.getElementById("lblMOrepDist").innerHTML = obj2.features[0].attributes.DISTRICT;
if(obj2.features[0].attributes.WebSite == "" || obj2.features[0].attributes.WebSite == null || obj2.features[0].attributes.WebSite == " "|| obj2.features[0].attributes.WebSite == "N/A") document.getElementById("hlMOrepWebsite").innerHTML = "Website N/A";
else document.getElementById("hlMOrepWebsite").innerHTML = "<a href='" + obj2.features[0].attributes.WebSite + "' target='_blank' style='color:blue'>View Website</a>";
});
// Federal (US House)
fetch(UShouseUrl).then(data => data.json()).then((result) =>
{
var obj1 = JSON.stringify(result);
var obj2 = JSON.parse(obj1);
document.getElementById("lblUSHouseName").innerHTML = obj2.features[0].attributes.REPNAME;
document.getElementById("lblUSHouseParty").innerHTML = obj2.features[0].attributes.Party;
document.getElementById("lblUSHouseDist").innerHTML = obj2.features[0].attributes.DISTRICT;
if(obj2.features[0].attributes.WebSite == "" || obj2.features[0].attributes.WebSite == null || obj2.features[0].attributes.WebSite == " "|| obj2.features[0].attributes.WebSite == "N/A") document.getElementById("hlUSHouseWebsite").innerHTML = "Website N/A";
else document.getElementById("hlUSHouseWebsite").innerHTML = "<a href='" + obj2.features[0].attributes.WebSite + "' target='_blank' style='color:blue'>View Website</a>";
});
}
|
d7caf8594fc9ebc04b2afc665b4cad13656afcc3
|
[
"JavaScript"
] | 2 |
JavaScript
|
jqadams3/parcelvieweraws
|
6b0fafe72641177ae4844cc07457782ad8966f03
|
4436df114bc1820eff5d67908be5ea2451743516
|
refs/heads/master
|
<file_sep>
# input
PV = float(input("Enter the starting principle: "))
R = float(input("Enter the annual interest rate: "))
T = float(input("For how many years will the account earn interest?: "))
M = float(input("How many times per year is the intertest compounded?: "))
# compute
FV = PV * (1 + (R/100) / M)**(M*T)
# output
print("At the end of the year you will have: $", end = '')
print(round(FV, 2))<file_sep># Planets
fMERCURY = .38
fVENUS = .91
fMOON = .165
fMARS = .38
fJUPITER = 2.34
fSATURN = .93
fURANUS = .92
fNEPTUNE = 1.12
fPLUTO = .066
# input
sName = input("What is your name: ")
fWeight = float(input("what is your weight: "))
# compute
fSpaceWeight1 = fWeight * fMERCURY
fSpaceWeight2 = fWeight * fVENUS
fSpaceWeight3 = fWeight * fMOON
fSpaceWeight4 = fWeight * fMARS
fSpaceWeight5 = fWeight * fJUPITER
fSpaceWeight6 = fWeight * fSATURN
fSpaceWeight7 = fWeight * fURANUS
fSpaceWeight8 = fWeight * fNEPTUNE
fSpaceWeight9 = fWeight * fPLUTO
# Output
print("Here are your weights on our Solar System's Planets: ")
print("Weight on Mercury: ", format(fSpaceWeight1, '10.2f'))
print("Weight on Venus: ", format(fSpaceWeight2, '10.2f'))
print("Weight on the Moon:", format(fSpaceWeight3, '10.2f'))
print("Weight on Mars: ", format(fSpaceWeight4, '10.2f'))
print("Weight on Jupiter: ", format(fSpaceWeight5, '10.2f'))
print("Weight on Saturn: ", format(fSpaceWeight6, '10.2f'))
print("Weight on Uranus: ", format(fSpaceWeight7, '10.2f'))
print("Weight on Neptune: ", format(fSpaceWeight8, '10.2f'))
print("Weight on Pluto: ", format(fSpaceWeight9, '10.2f'))
|
2d033126564b78874737be04c66f5ab302874b9f
|
[
"Python"
] | 2 |
Python
|
Charpie2/python_class
|
1c457c6ca6e58861f55e95784c1291e4795c48a7
|
bd62895430edbcd9efb11e8a322ed7bd82733100
|
refs/heads/master
|
<file_sep>var express = require('express');
var app = express();
app.listen(3002, function(res) {
console.log('hi, 监听端口3002');
});
<file_sep># react_end
React 对应的 NodeJs 后台
## 搭建环境
npm init 初始化一个项目
安装依赖 npm install express(mongoose)等
新建 index.js, 写个 demo
```
var express = require('express');
var app = express();
app.listen(3002, function(res) {
console.log('hi, 请打开浏览器 localhost:3002 进行测试');
});
```
新建一个测试 mongoose 的 demo
```
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mongoose_test');
var Schema = mongoose.Schema;
var blogSchema = new Schema({
title: String,
});
var Blog = mongoose.model('Blog', blogSchema);
var blog = new Blog({title:'xxx'});
blog.save();
```
|
043095f972d2fd64f17cc22c496f8621da434be8
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
luckystar12/react_end
|
352274918450e42e47b900fa96382ccf264b913e
|
e6ced9214279002912e4802421b02ffcab1de459
|
refs/heads/master
|
<file_sep>// run scripts when document loaded
$(document).ready(function(){
$('#widget').draggable();
//declare variables
var answer1;
var answer2;
var answer3;
var answer4;
var answer5;
var answer6;
//empty array
var answerArray = [];
//initialize score
var score = 0;
// jQuery selector variables
var $moustacheDiv = $('.moustache-wrapper');
var $moustacheActual = $('.moustache-actual');
var $resultsH2 = $('.resultsH2');
var $resultsImg = $('.resultsImg');
var $resultsDesc = $('.resultsDesc');
//initialize functions
function unCheckAll(){
$('input[type="radio"]:checked').prop('checked', false);
}
function resetAnswers(){
answer1 = undefined;
answer2 = undefined;
answer3 = undefined;
answer4 = undefined;
answer5 = undefined;
answer6 = undefined;
}
$moustacheDiv.hide();
$('.results').hide();
// when a radio button gets clicked run a value check
$('input[type="radio"]').on('click',function(){
// add value of radio to a variable
answer1 = $('input[name="question1"]:checked').val();
answer2 = $('input[name="question2"]:checked').val();
answer3 = $('input[name="question3"]:checked').val();
answer4 = $('input[name="question4"]:checked').val();
answer5 = $('input[name="question5"]:checked').val();
answer6 = $('input[name="question6"]:checked').val();
// log out the value to see it working!
console.log(answer1);
console.log(answer2);
console.log(answer3);
console.log(answer4);
console.log(answer5);
console.log(answer6);
}); // radio listener
// SUBMIT button IS PRESSED
//===============================================================
//listen for the submit button being pressed
$('input[type="submit"]').on('click', function(e){
// prevent page from reloading
e.preventDefault();
//check all answers have a value
if (typeof answer1 === 'undefined' ||
typeof answer2 === 'undefined' ||
typeof answer3 === 'undefined' ||
typeof answer4 === 'undefined' ||
typeof answer5 === 'undefined' ||
typeof answer6 === 'undefined'){
alert('Whoops! You missed a question or two! Please try again!');
} else{
//push final answers into answerArray
answerArray.push(answer1);
answerArray.push(answer2);
answerArray.push(answer3);
answerArray.push(answer4);
answerArray.push(answer5);
answerArray.push(answer6);
// log out to see listener working
console.log('button pressed!');
console.log(answerArray);
//check answers and create a score
//loop through each item in the array
for (var i = 0; i < answerArray.length; i++){
// make sure there is value in the radio if not break
if ( typeof answerArray[i] === 'undefined' ){
alert('You forgot to answer a question!');
answerArray = [];
break;
// check values and add or subtract from score
} else if ( answerArray[i] === "positive" ){
score++;
console.log(score);
} else if ( answerArray[i] === "negative" ){
console.log(score);
}
} //looping through answerArray
if (score === 0){
// show the moustache
$moustacheDiv.show();
// change the source of the moustace image based on score
$moustacheActual.attr("src", "assets/moustache.png");
// inject the text
$resultsH2.text('\"The He Who Shall Not Be Named\"');
$resultsImg.attr('src', 'assets/results.jpg');
$resultsDesc.text("Once a representation of laughter, this stache now typifies a true antagonist. No one wants this stache... do you? We won't judge.");
}
else if (score === 1){
$moustacheDiv.show();
$moustacheActual.attr("src", "assets/moustache1.png");
$resultsH2.text('\"The Goatee\"');
$resultsImg.attr('src', 'assets/results1.jpg');
$resultsDesc.text("Nothing says gun-toting Texas oil baron more than this stache. Yosemite Sam would be proud.");
}
// else if (score === 0){
// $moustacheDiv.show();
// $moustacheActual.attr("src", "assets/moustache2.png");
// $resultsH2.text('\"The Fu Manchu\"');
// $resultsImg.attr('src', 'assets/results2.gif');
// $resultsDesc.text("Love the retro look? Love comics or kung fu flicks? This is old school evil stache is you.");
// }
else if (score === 2){
$moustacheDiv.show();
$moustacheActual.attr("src", "assets/moustache3.png");
$resultsH2.text('\"The Pervert\"');
$resultsImg.attr('src', 'assets/results3.jpg');
$resultsDesc.text("You should be ashamed of yourself. (Ya... we don't get our logic either)");
}
// else if (score === 0){
// $moustacheDiv.show();
// $moustacheActual.attr("src", "assets/moustache4.png");
// $resultsH2.text('\"The Dali\"');
// $resultsImg.attr('src', 'assets/results4.gif');
// $resultsDesc.text("Congradulations! You have the same creepy moustache as Salvador Dali! You know...that guy who pained the melting clocks?");
// }
else if (score === 3){
$moustacheDiv.show();
$moustacheActual.attr("src", "assets/moustache5.png");
$resultsH2.text('\"The Captian Hook\"');
$resultsImg.attr('src', 'assets/results5.gif');
$resultsDesc.text("While Captain Hook is pretty BADA55 his moustache is just plain bad. Maybe if he spent less time waxing it, he could actually catch Peter Pan...but probably not.");
}
else if (score === 4){
$moustacheDiv.show();
$moustacheActual.attr("src", "assets/moustache6.png");
$resultsH2.text('\"The Hulkamania\"');
$resultsImg.attr('src', 'assets/results6.jpg');
$resultsDesc.text("Because of Hulk Hogan, no one takes this stache seriously. Perfect if you want to look tough without having to act tough.");
}
else if (score === 5){
$moustacheDiv.show();
$moustacheActual.attr("src", "assets/moustache7.png");
$resultsH2.text('\"The Selleck\"');
$resultsImg.attr('src', 'assets/results7.gif');
$resultsDesc.text("Now this is a stache. Full yet clean. So lovable, even Flanders approves.");
}
// else if (score === 0){
// $moustacheDiv.show();
// $moustacheActual.attr("src", "assets/moustache8.png");
// $resultsH2.text('\"The Super Mario\"');
// $resultsImg.attr('src', 'assets/results8.png');
// $resultsDesc.text("Itsa me! Mario!");
// }
else{
$moustacheDiv.show();
$moustacheActual.attr("src", "assets/moustache9.png");
$resultsH2.text('\"<NAME>\"');
$resultsImg.attr('src', 'assets/results9.jpg');
$resultsDesc.text("One facial hair style to rule them all! This style has been known to cause a person to spontaneously clap, \"woo\" and chant \"JavaScript, JavaScript\".");
}
// hide the questions and show the results
$('.questions').hide();
$('.results').show();
} //end of undefined checker!
}); // submit listener
//reset button
//==============================================================================================================
$('.reset').on('click', function(){
$('.questions').show();
$('.results').hide();
//reset variables
score = 0;
$moustacheDiv.hide();
answerArray = [];
resetAnswers();
unCheckAll();
console.log(score);
}); // reset listener
// run draggable jQuery UI
$(function(){
$(".moustache-wrapper").draggable();
});
// run resizable UI
$(function() {
$( ".moustache-wrapper" ).resizable();
});
function touchHandler(event) {
var touch = event.changedTouches[0];
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent({
touchstart: "mousedown",
touchmove: "mousemove",
touchend: "mouseup"
}[event.type], true, true, window, 1,
touch.screenX, touch.screenY,
touch.clientX, touch.clientY, false,
false, false, false, 0, null);
touch.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
function init() {
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
}
init();
}); // document ready function
|
e626181d6a15487b4b7b2eb82d3189d7657b85bb
|
[
"JavaScript"
] | 1 |
JavaScript
|
Jimsaurus/week-4-project
|
225fd12fe5d29d3df787ca50c5ac9bb2a1e3b67e
|
6f0689aee5d08a80c024872803a46eb5f9066d82
|
refs/heads/master
|
<file_sep>#!/bin/bash
# start monitor mode
sudo ifconfig wlan0 down
sudo airmon-ng check kill
sudo iwconfig wlan0 mode monitor
sudo ifconfig wlan0 up
sudo iwconfig wlan0 | grep Mode
exit 0
|
e4d4936fbfe9a8a3685874422e2c49c55765427f
|
[
"Shell"
] | 1 |
Shell
|
L4ll1p0p/kali_hacking
|
693879fc4cb6f3076019c2b3a8d10daee6013b0a
|
a953ba654647ec3142cf9f4a9d399e80ad85cb71
|
refs/heads/master
|
<repo_name>artisxn/health<file_sep>/src/Support/Constants.php
<?php
namespace codicastudio\Health\Support;
class Constants
{
const RESOURCES_ENABLED_ALL = ['.*']; // regex
}
<file_sep>/src/Checkers/Framework.php
<?php
namespace codicastudio\Health\Checkers;
use codicastudio\Health\Support\Result;
class Framework extends Base
{
/**
* @return Result
*/
public function check()
{
return $this->makeHealthyResult();
}
}
|
819a951e6018e0b1ba2baaab439d56e7aa268e84
|
[
"PHP"
] | 2 |
PHP
|
artisxn/health
|
f26f9e203aead8f0d44901a91d4d5d67e8d515c6
|
ceff7ef595651d6f861262b0438c0e17444d4c3a
|
refs/heads/master
|
<repo_name>phpid/intercom<file_sep>/spec/distance_spec.rb
require 'distance'
describe Foo do
before(:each) do
@distance = Foo::Distance.new
end
describe '.parse_customers' do
context 'correct URL' do
it 'loads external content' do
expect(Net::HTTP).to receive(:get).and_return('first')
expect(@distance.load_customers).to be_a(String)
end
end
context 'incorrect URL' do
it 'returns nil' do
expect(Net::HTTP).to receive(:get).and_raise('bang')
expect(@distance.load_customers).to be_nil
end
end
context 'JSON is available' do
it 'returns content as hash' do
content = '{"latitude": "52.986375", "user_id": 12, "name": "<NAME>", "longitude": "-6.043701"}'
customers = @distance.parse_customers(content)
expect(customers).to be_a(Hash)
expect(customers.first[1]).to include('user_id', 'name', 'latitude', 'longitude')
end
end
end
describe '.distance_vincenty' do
it 'returns 0 for point zero' do
expect(@distance.distance_vincenty(
Foo::ZERO_LATITUDE,
Foo::ZERO_LONGITUDE,
Foo::ZERO_LATITUDE,
Foo::ZERO_LONGITUDE)
).to eq(0)
end
it 'returns 5115km for New York and Dublin' do
expect(@distance.distance_vincenty(40.7127, -74.0059, 53.3478, -6.2597)).to eq(5115)
end
it 'returns 9671km for London and Cape Town' do
expect(@distance.distance_vincenty(51.5072, -0.1275, -33.9253, 18.4239)).to eq(9671)
end
context 'give JSON with customers' do
let(:selected) { @distance.list_customers }
it 'returns list of customers within 100km' do
expect(selected).to be_a(Hash)
end
it 'returns correct number of customers (16)' do
expect(selected.size).to eq(16)
end
it 'returns hash sorted by user_id ascending' do
expect(selected.keys.first).to be < selected.keys.last
expect(selected.values.first['name']).to eq('<NAME>')
expect(selected.values.last['name']).to eq('<NAME>')
end
end
end
end<file_sep>/spec/flatten_spec.rb
require 'flatten'
describe 'Foo::flatten' do
context 'when given [[1,2,[3]],4]' do
let(:input) { [[1, 2, [3]], 4] }
let(:output) { Foo::flatten(input) }
it 'returns array' do
expect(output).to be_a(Array)
end
it 'has same number of elements' do
expect(output.length).to eq(input.length)
end
end
context 'when given empty array []' do
let(:input) { [] }
let(:output) { Foo::flatten(input) }
it 'returns empty array' do
expect(output).to be_a(Array)
expect(output.length).to eq(0)
end
end
context 'when given array with duplicate elements [[1,2],[1,2,3],1,2,3]' do
let(:input) { [[1, 2], [1, 2, 3], 1, 2, 3] }
let(:output) { Foo::flatten(input) }
it 'returns array' do
expect(output).to be_a(Array)
end
it 'has same number of elements' do
expect(output.length).to eq(input.length)
end
end
context 'when given array with mixed elements [1,"1",nil,2,3]' do
let(:input) { [1, 'string', nil, 2, 3] }
let(:output) { Foo::flatten(input) }
it 'raises ArgumentError for non-integer elements in array' do
expect { output }.to raise_error(ArgumentError, 'Element must be an integer')
end
end
end<file_sep>/lib/distance.rb
require 'foo/version'
require 'net/http'
require 'json'
module Foo
RADIUS = 6371 # in km
ZERO_LATITUDE = 53.3381985
ZERO_LONGITUDE = -6.2592576
URL = 'https://gist.githubusercontent.com/brianw/19896c50afa89ad4dec3/raw/6c11047887a03483c50017c1d451667fd62a53ca/gistfile1.txt'
class Distance
def load_customers(url = URL)
uri = URI(url)
Net::HTTP.get(uri)
rescue
nil
end
def parse_customers(content)
customers = {}
content.each_line do |line|
customer = JSON.parse(line)
customers[customer['user_id']] = customer if customer.key?('user_id')
end
customers
end
# http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
def distance_vincenty(lat1, long1, lat2, long2)
@delta_lambda = deg2rad(long1 - long2)
lat1 = deg2rad(lat1)
lat2 = deg2rad(lat2)
@delta = Math.atan2(
Math.sqrt(
(Math.cos(lat2) * Math.sin(@delta_lambda)) ** 2 +
(Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(@delta_lambda)) ** 2
),
Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(@delta_lambda)
)
(RADIUS * @delta).round
end
def deg2rad(degrees)
degrees * Math::PI / 180
end
def list_customers
content = load_customers
customers = parse_customers(content) unless content.is_a?(Hash) || content.empty?
selected = customers.select { |k,v| distance_vincenty(ZERO_LATITUDE, ZERO_LONGITUDE, v['latitude'].to_f, v['longitude'].to_f) <= 100 }
selected.sort.to_h
end
end
end
<file_sep>/bin/distance
#!/usr/bin/env ruby
require "foo"
distance = Foo::Distance.new
distance.list_customers
<file_sep>/lib/flatten.rb
require 'foo/version'
module Foo
def self.flatten(arr, buf = [])
arr.each do |el|
if el.is_a?(Array)
flatten(el, buf)
else
raise ArgumentError.new('Element must be an integer') unless el.is_a?(Integer)
buf << el
end
end
end
end
|
c88ecfa7f6f30ca4213eb32fe6ea7be80fde90ea
|
[
"Ruby"
] | 5 |
Ruby
|
phpid/intercom
|
55d7ac7096ccbed4b3fcc691f247aafef1820448
|
587edd48a3aba6f3b9d205d68718f25b958ea19a
|
refs/heads/master
|
<file_sep>#include"stdafx.h"
#include<iostream>
using namespace std;
int main()
{
unsigned int year;
cout << "Input a year"<<endl;
cin >> year;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0 )){ /*判断是否是闰年*/
cout << year << "Year" << "is a leap year.\n" << endl;
}else{
cout << year << "is not a leap year." << endl;
}
return 0;
}
<file_sep>#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
bool seive[101];
for (int i = 2; i < 101; i++)//枚举前100个数
{
seive[i] = true;
}
for (int d = 2; d*d <= 100; d++)//枚举从2到sqrt(100)的数,并且把它们的倍数都标记为false
{
if (seive[d])
{
for (int n = d*d; n <= 100; n = n + d)//用d的倍数去筛选100以内的数,刚好晒到的话就标记为false
seive[n] = false; // 用d*d是因为前面的都已经被前面的筛子给筛掉了,没有必要进行重复筛选
}
}
for (int n = 2; n <=100; n++)//输出素数
{
if (seive[n])
{
cout << n << endl;
}
}
return 0;
}
<file_sep>// project.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
int m;
void InsertionSort(int A[], int n)
{
int temp;
for (int i = 1; i < n; i++)//从第二个数开始都需要进行扫描插入
{
for (int j = i - 1; j>-1; j--)//这个数需要和前面已经排序好了的数进行对比
{
if (A[j + 1] > A[j])//如果已经排序好,就跳出这个for循环,因为它对比的前面的都是已经排序好了的
{
m++;//计算出,对比了多少次
break;
}
if (A[j] > A[j + 1]) //如果这个数据较小,就把它们换一下
{
temp = A[j + 1];
A[j + 1] = A[j];
A[j] = temp;
m++;
}
}
}
}
int main()
{
int cards[15] = { 326,101, 1012, 113, 206, 207, 208, 303, 3094, 309, 311, 402, 405, 410,0 };
InsertionSort(cards, 15);
int id = -1, low = 0, high = 15;
for (int i = 0; i < 15; i++)
{
cout << cards[i]<<endl;
}
while (low<=high)
{
int middle = (low + high) / 2;//先到一半的地方进行查找一下
if (cards[middle]==30)
{
id = middle;
break;
}
else if (cards[middle] > 30)//此时的303在左边继续向小的范围查找
{
high = middle - 1;
}
else//此时303在右边,往右边进行排查
{
low = middle + 1;
}
}
cout<<"Q in"<<id+1 <<"zhang"<<endl;
return 0;
}
|
c59662655f819fbc58cf39c9075424a5f3d2cc4a
|
[
"C++"
] | 3 |
C++
|
shiyongsway/shiyong
|
e5d73d339dfea0937f90d3ff68aadec0c51d19de
|
5ad2abea3135e61c9e017809e80bd3fe7fd9be65
|
refs/heads/main
|
<repo_name>murphymen/ComputeChunkMesh<file_sep>/Chunk.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class Chunk : MonoBehaviour
{
public ComputeShader chunkShader;
//int PopulateVoxelMap;
int AddVoxelDataToChunk;
static Vector3Int dimms = new (8,8,8);
[SerializeField]
static int dimmsVolume = dimms.x * dimms.y * dimms.z;
public static int maxVertexCount = dimmsVolume * 6 * 4;
readonly int maxTriangleCount = dimmsVolume * 6 * 2;
Mesh mesh;
//ComputeBuffer voxelMap;
GraphicsBuffer vertexBuffer;
GraphicsBuffer normalBuffer;
GraphicsBuffer texcoordBuffer;
GraphicsBuffer indexBuffer;
// DEBUG
ComputeBuffer vertexDebugBuffer;
ComputeBuffer indexDebugBuffer;
ComputeBuffer idDebugBuffer;
[SerializeField]
Vector3[] vertexDebug;
[SerializeField]
Vector3Int[] indexDebug;
[SerializeField]
uint[] idDebug;
void Start()
{
//PopulateVoxelMap = chunkShader.FindKernel("PopulateVoxelMap");
AddVoxelDataToChunk = chunkShader.FindKernel("AddVoxelDataToChunk");
AllocateBuffers();
AllocateMesh();
}
void AllocateBuffers()
{
//_voxelMap = new ComputeBuffer(dimmsVolume, 4, ComputeBufferType.Structured);
//chunkShader.SetInts("_dimms", dimms.x, dimms.y, dimms.z);
chunkShader.SetInt("_dimmX", dimms.x);
chunkShader.SetInt("_dimmY", dimms.y);
chunkShader.SetInt("_dimmZ", dimms.z);
// Debug buffers
vertexDebugBuffer = new ComputeBuffer(maxVertexCount*3, sizeof(float));
indexDebugBuffer = new ComputeBuffer(maxTriangleCount, sizeof(uint)*3);
vertexDebug = new Vector3[maxVertexCount];
indexDebug = new Vector3Int[maxTriangleCount];
idDebugBuffer = new ComputeBuffer(dimmsVolume, sizeof(uint));
idDebug = new uint[dimmsVolume];
Debug.Log("dimmsVolume: "+dimmsVolume);
}
void RelaseBuffers()
{
//_voxelMap.Dispose();
}
void AllocateMesh()
{
mesh = new Mesh
{
name = "ChunkMesh"
};
mesh.vertexBufferTarget |= GraphicsBuffer.Target.Raw;
mesh.indexBufferTarget |= GraphicsBuffer.Target.Raw;
var vertexLayout = new[]
{
new VertexAttributeDescriptor(VertexAttribute.Position,
VertexAttributeFormat.Float32, 3, stream:0),
new VertexAttributeDescriptor(VertexAttribute.Normal,
VertexAttributeFormat.Float32, 3, stream:1),
new VertexAttributeDescriptor(VertexAttribute.TexCoord0,
VertexAttributeFormat.Float32, 2, stream:2),
};
mesh.SetVertexBufferParams(maxVertexCount, vertexLayout);
mesh.SetIndexBufferParams(maxTriangleCount*3, IndexFormat.UInt32);
//??????????????????????????????????????????????????????????????????????????????????????????
mesh.SetSubMesh(0, new SubMeshDescriptor(0, maxVertexCount),
MeshUpdateFlags.DontRecalculateBounds);
vertexBuffer ??= mesh.GetVertexBuffer(0);
normalBuffer ??= mesh.GetVertexBuffer(1);
texcoordBuffer ??= mesh.GetVertexBuffer(2);
indexBuffer ??= mesh.GetIndexBuffer();
}
void RelaseMesh()
{
vertexBuffer?.Dispose();
normalBuffer?.Dispose();
texcoordBuffer?.Dispose();
indexBuffer?.Dispose();
vertexDebugBuffer?.Dispose();
indexDebugBuffer?.Dispose();
idDebugBuffer?.Dispose();
Object.Destroy(mesh);
}
void DrawMesh()
{
uint xc, yc, zc;
chunkShader.GetKernelThreadGroupSizes(AddVoxelDataToChunk, out xc, out yc, out zc);
//int x = (dimms.x + (int)xc - 1) / (int)xc;
//int y = (dimms.y + (int)yc - 1) / (int)yc;
//int z = (dimms.z + (int)zc - 1) / (int)zc;
int x = dimms.x / (int)xc;
int y = dimms.y / (int)yc;
int z = dimms.z / (int)zc;
vertexBuffer ??= mesh.GetVertexBuffer(0);
normalBuffer ??= mesh.GetVertexBuffer(1);
texcoordBuffer ??= mesh.GetVertexBuffer(2);
indexBuffer ??= mesh.GetIndexBuffer();
chunkShader.SetInt("_dimmX", dimms.x);
chunkShader.SetInt("_dimmY", dimms.y);
chunkShader.SetInt("_dimmZ", dimms.z);
chunkShader.SetBuffer(AddVoxelDataToChunk, "_vertexBuffer", vertexBuffer);
chunkShader.SetBuffer(AddVoxelDataToChunk, "_normalBuffer", normalBuffer);
chunkShader.SetBuffer(AddVoxelDataToChunk, "_texcoordBuffer", texcoordBuffer);
chunkShader.SetBuffer(AddVoxelDataToChunk, "_indexBuffer", indexBuffer);
//chunkShader.SetBuffer(AddVoxelDataToChunk, "_voxelMap", voxelMap);
chunkShader.SetBuffer(AddVoxelDataToChunk, "_vertexDebugBuffer", vertexDebugBuffer);
chunkShader.SetBuffer(AddVoxelDataToChunk, "_indexDebugBuffer", indexDebugBuffer);
chunkShader.SetBuffer(AddVoxelDataToChunk, "_idDebugBuffer", idDebugBuffer);
chunkShader.Dispatch(AddVoxelDataToChunk,x,y,z);
GetComponent<MeshFilter>().sharedMesh = mesh;
vertexBuffer.GetData(vertexDebug);
indexBuffer.GetData(indexDebug);
idDebugBuffer.GetData(idDebug);
}
void Update()
{
DrawMesh();
}
void OnDestroy()
{
RelaseBuffers();
RelaseMesh();
}
}
|
210a91c2b5db18446df5a3fbf5ba5a2776d6be58
|
[
"C#"
] | 1 |
C#
|
murphymen/ComputeChunkMesh
|
e2eb603342bd25b1fdc7287ad8c397689621e597
|
32a1d9e27ed9492afb51088bc58de99f2277e3d2
|
refs/heads/main
|
<repo_name>SansanM/coffee_note<file_sep>/src/component/NotesComponent.js
import React from 'react';
import { withCookies } from 'react-cookie';
import MainContentsHead from "./mainContentsHead";
import PrintNoteData from "./PrintNoteData";
//Notesを取り出し繰り返し処理で描画
const NotesComponent = (props) => {
return (
<div>
<MainContentsHead pageTitle={props.isPublicPage?"みんなのNote":"My Note"} toUrl={props.isPublicPage?"/AddNotePublic":"/AddNoteMyNote"} buttonName="ADD NOTE"/>
{props.notesData.map(
(data) => {
return (
<PrintNoteData noteData={data} key={data.uuid} setNote={props.setNote} isPublicPage={props.isPublicPage}/>
)
}
)}
</div>
)
}
export default withCookies(NotesComponent);<file_sep>/src/NoteDetail.js
import Axios from 'axios';
import React from 'react';
import { withCookies } from 'react-cookie';
import DateTimePrint from "./component/DateTimePrtint";
import {apiBaseUrl} from "./config";
import { Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Button } from '@material-ui/core';
//詳細ダイアログ内部の動作 公開状況の変更 削除ができる
const NoteDetail = (props) => {
let url ="";
//みんなのNoteだとuuidが返却されない
if(props.noteData.uuid){
url = `${apiBaseUrl}/note/note/${props.noteData.uuid}`;
}
const data = props.noteData
const [open, setOpen] = React.useState(false);
const baseUrl = `${apiBaseUrl}/note/note/`;
const token = props.cookies.get('coffeeNote-token');
let isPublic = false;
if(data.public==="true"){
isPublic = true;
}
else{
isPublic = false;
}
const getList = (props) => {
const url = `${apiBaseUrl}/note/note/`;
const token = props.cookies.get('coffeeNote-token');
Axios.get(url, {
headers: {
"Authorization": "jwt " + token
},
mode: 'cors',
credentials: 'include'
})
.then(res => {
//全体のNoteデータをリロード 削除と変更を反映
props.setNote(res.data);
})
.catch(error => {
console.log(error.response.data);
});
}
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
//公開と非公開の切り替えを行う
const handlePublicChange = (props) => {
let form_data = new FormData();
form_data.append('title', data.title);
//
if(data.body){
form_data.append('body', data.body);
}
else{
form_data.append('body',"");
}
form_data.append('sanmi', data.sanmi);
form_data.append('nigami', data.nigami);
form_data.append('like', data.like);
form_data.append('user', data.user.username);
console.log(data.user.username);
if(isPublic){
form_data.append('public',"false")
}
else{
form_data.append('public',"true");
}
Axios.post(baseUrl,form_data,{
headers: {
'Content-Type': 'application/json',
"Authorization": "jwt " + token
},
mode: 'cors',
credentials: 'include'
})
.then(res => {
handleDelete(props);
setOpen(false);
})
.catch(error => {
console.log(error.response.data);
});
}
const handleDelete = () => {
Axios.delete(url, {
headers: {
"Authorization": "jwt " + token
},
mode: 'cors',
credentials: 'include'
})
.then(res => {
setOpen(false);
getList(props);
})
.catch(error => {
console.log(error.response.data);
});
}
//自分のNoteに対して行える操作
const PrintMyNoteDetail = () =>{
return(
<React.Fragment>
<Button onClick={handlePublicChange} color="primary">
{isPublic?"公開をやめる":"公開する"}
</Button>
<Button onClick={handleDelete} color="primary">
削除する
</Button>
<Button onClick={handleClose} color="primary">
閉じる
</Button>
</React.Fragment>
)
}
//他人のNoteに対して行える操作
const PrintPublicNoteDetail = () =>{
return(
<Button onClick={handleClose} color="primary">
閉じる
</Button>
)
}
return (
<React.Fragment>
<Button variant="outlined" color="primary" onClick={handleClickOpen}>
詳細を見る
</Button>
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="simple-dialog-title"
aria-describedby="simple-dialog-description"
>
<DialogTitle id="simple-dialog-title">{data.title}</DialogTitle>
<DialogContent>
<DialogContentText id="simple-dialog-description">
酸味:{data.sanmi}<br />
苦味:{data.nigami}<br />
評価:{data.like}<br />
感想:{data.body}<br />
公開状況:{isPublic?"公開中":"未公開"}<br /><br />
作成者:{data.user?data.user.username:null}<br />
<DateTimePrint data={data} /><br />
</DialogContentText>
</DialogContent>
<DialogActions>
{props.isPublicPage?<PrintPublicNoteDetail />:<PrintMyNoteDetail />}
</DialogActions>
</Dialog>
</React.Fragment>
)
}
export default withCookies(NoteDetail);<file_sep>/src/Layout.js
import { Row, Col, Container } from "react-bootstrap";
import HeaderComponrts from "./component/header";
import classes from "./css/Layout.module.css"
const Layout = (props) => {
const { title, children } = props
const siteTitle = "coffee note"
return (
<div className={classes.page}>
<title>{title ? `${title} | ${siteTitle}` : siteTitle}l
<link rel="icon" href="/favicon.ico" /></title>
<header>
<HeaderComponrts title={props.title}/>
</header>
<br/>
<main>
<div className="page-main">
<Container>
<Row className={classes.contents} >
<Col>
{children}
</Col>
</Row>
</Container>
</div>
</main>
<footer className={classes.footer}>
© {siteTitle}
</footer>
</div>
)
}
export default Layout<file_sep>/src/component/header.js
import React from "react";
import { Navbar, Nav } from "react-bootstrap";
import LoginComponent from "./HeaderLoginComponent";
import { withCookies } from 'react-cookie';
//ヘッダー要素の描画
const myHeader = (props) => {
document.title = props.title;
return (
<Navbar collapseOnSelect expand="sm" bg="dark" variant="dark">
<Navbar.Brand href="/">
Coffee Note
</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto">
<Nav.Link href="/">Home</Nav.Link>
<LoginComponent />
</Nav>
</Navbar.Collapse>
</Navbar>
)
}
export default withCookies(myHeader);<file_sep>/src/AddNote.js
import Axios from 'axios';
import React, { useState } from 'react';
import { withCookies } from 'react-cookie';
import { Button, TextField ,Switch , FormControlLabel} from '@material-ui/core/';
import {apiBaseUrl} from "./config";
import Formstyle from "./css/AddNoteForm.module.css"
import MainContentsHead from "./component/mainContentsHead";
import { makeStyles } from '@material-ui/core/styles';
//フォーム同士の隙間の設定
const useStyles = makeStyles((theme) => ({
root: {
'& .MuiTextField-root': {
margin: theme.spacing(1),
width: '25ch',
},
},
}));
//新規noteの投稿
const AddNote = (props) => {
console.log(props.isPublic)
const [title, setTitle] = useState("");
const [note, setNote] = useState("");
const [sanmi, setSanmi] = useState(3);
const [nigami, setNigami] = useState(3);
//遷移元のページによってデフォルトが変わる
//MyNoteからはfalse みんなのNoteからはtrueがデフォルト
const [isPublic, setIsPublic] = useState(props.isPublic);
const [like, setLike] = useState(3);
const classes = useStyles();
const [ErrorMessage, setErrorMessage] = useState("");
//投稿の非同期通信の処理
const NotePost = () =>{
const token = props.cookies.get('coffeeNote-token');
const url = `${apiBaseUrl}/note/note/`;
let form_data = new FormData();
form_data.append('title', title);
form_data.append('body', note);
form_data.append('sanmi', sanmi);
form_data.append('nigami', nigami);
form_data.append('like', like);
if(isPublic){
form_data.append('public',"true")
}
else{
form_data.append('public',"false");
}
Axios.post(url,form_data, {
headers: {
'Content-Type': 'application/json',
"Authorization": "jwt " + token,
},
mode: 'cors',
credentials: 'include'
})
.then( res => {
console.log(res)
if(props.isPublic){
window.location.href = "/Public";
}
else{
window.location.href = "/";
}
})
.catch( error =>{
console.log(error.response.data);
setErrorMessage(error.response.data);
})
}
//入力フォーム
return (
<div>
<MainContentsHead pageTitle="Add Note" toUrl={props.isPublic?"/Public":"/"} buttonName={props.isPublic?"みんなのNote":"My Note"}/>
<div className={Formstyle.root +" "+ classes.root}>
<TextField
onChange={(e) => setTitle(e.target.value)}
value={title}
label="タイトル"
variant="outlined"
helperText={ErrorMessage.title}
/><br />
<TextField
onChange={(e) => setSanmi(e.target.value)}
value={sanmi}
type="number"
inputProps={{min: 1 , max:5}}
label="酸味"
variant="outlined"
helperText={ErrorMessage.sanmi}
/><br />
<TextField
onChange={(e) => setNigami(e.target.value)}
value={nigami}
type="number"
inputProps={{min: 1 , max:5}}
label="苦味"
variant="outlined"
helperText={ErrorMessage.nigami}
/><br />
<TextField
onChange={(e) => setLike(e.target.value)}
value={like}
type="number"
inputProps={{min: 1 , max:5}}
label="評価"
variant="outlined"
helperText={ErrorMessage.like}
/><br />
<TextField
onChange={(e) => setNote(e.target.value)}
value={note}
multiline
label="メモ"
variant="outlined"
helperText={ErrorMessage.note}
/><br />
<FormControlLabel
control={ <Switch
onChange={(e) => setIsPublic(e.target.checked)}
checked={isPublic}
/>}
label="公開する"
/>
<br />
<Button onClick ={NotePost}>
投稿する
</Button>
</div>
</div>
)
}
export default withCookies(AddNote);<file_sep>/src/component/isLogout.js
import { withCookies } from 'react-cookie';
//トークンの確認
const IsLogout = (props) =>{
if(props.cookies.get('coffeeNote-token')){
return(null)
}
else{
return(props.children)
}
}
export default withCookies(IsLogout)
<file_sep>/src/component/PrintNoteData.js
import React from 'react'
import { withCookies } from 'react-cookie';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';
import NoteDetail from '../NoteDetail';
const useStyles = makeStyles({
root: {
minWidth: 275,
margin: 30
},
bullet: {
display: 'inline-block',
margin: '0 2px',
transform: 'scale(0.8)',
},
title: {
fontSize: 14,
},
pos: {
marginBottom: 12,
},
});
//Noteデータの描画処理を行う
const PrintNoteData = (props) => {
const year = props.noteData.updated_at.substring(0, 4);
const month = props.noteData.updated_at.substring(5, 7);
const day = props.noteData.updated_at.substring(8, 10);
const classes = useStyles();
return (
<React.Fragment>
<Card className={classes.root}>
<CardContent>
<Typography variant="h5" component="h2">
{props.noteData.title}
</Typography>
<Typography className={classes.pos} color="textSecondary">
{year}年{month}月{day}日
</Typography>
<Typography variant="body2" component="p">
評価:{props.noteData.like}
<br />
感想:{props.noteData.body}
<br /><br />
ユーザ:{props.noteData.user.username}
</Typography>
</CardContent>
<CardActions>
<NoteDetail noteData={props.noteData} setNote={props.setNote} isPublicPage={props.isPublicPage}/>
</CardActions>
</Card>
</React.Fragment>
)
}
export default withCookies(PrintNoteData)<file_sep>/src/component/GetList.js
import Axios from 'axios';
import {apiBaseUrl} from "../config";
const GetList = (props) =>{
const url = `${apiBaseUrl}/note/note/`;
const token = props.cookies.get('coffeeNote-token');
Axios.get(url, {
headers: {
"Authorization": "jwt " + token
},
mode: 'cors',
credentials: 'include'
})
.then(res => {
props.setNote(res.data);
})
.catch(error => {
console.log(error.response.data);
});
}
export default GetList
<file_sep>/src/index.js
import Layout from "./Layout";
import React from 'react';
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route ,Switch} from 'react-router-dom';
import { CookiesProvider } from 'react-cookie';
import 'bootstrap/dist/css/bootstrap.min.css';
import Home from "./Home";
import Public from "./Public"
import Login from "./Login";
import AddNote from "./AddNote";
import IsLogin from "./component/isLogin";
import IsLogout from "./component/isLogout";
const LoginOnly = () =>{
return(
<React.Fragment>
<Switch>
<Route exact path="/AddNoteMyNote" render={() => <AddNote isPublic={false}/>}/>
<Route exact path="/AddNotePublic" render={() => <AddNote isPublic={true}/>}/>
<Route exact path="/Home" render={() => <Home />} />
<Route exact path="/Public" render={() => <Public />} />
<Route path="/" render={() => <Home />} />
</Switch>
</React.Fragment>
)
}
const LogoutOnly = () =>{
return(
<React.Fragment>
<Switch>
<Route exact path="/Login" render={() => <Login isLogin={true} />} />
<Route exact path="/Signup" render={() => <Login isLogin={false} />} />
<Route path="/" render={() => <Login isLogin={true} />} />
</Switch>
</React.Fragment>
)
}
const RoutingComponent = () => {
return (
<React.Fragment>
<IsLogin>
<LoginOnly />
</IsLogin>
<IsLogout>
<LogoutOnly />
</IsLogout>
</React.Fragment>
)
}
export default function APP() {
return (
<Layout title="CoffeeNote">
<Router basename={process.env.PUBLIC_URL}>
<RoutingComponent />
</Router>
</Layout>
)
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<CookiesProvider>
<APP />
</CookiesProvider>
, rootElement);
|
e233894fd0fd83e7f583629d42135b5b802f77d4
|
[
"JavaScript"
] | 9 |
JavaScript
|
SansanM/coffee_note
|
b7d7d73f8ed1d7f029bba706e8ba2af014e3428f
|
7b801afbc228db6a1fc60aaebca8afd2ffc13a99
|
refs/heads/master
|
<repo_name>balazsgrill/junk<file_sep>/query.test.model/src/package_/subpackage/impl/SubpackageFactoryImpl.java
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package package_.subpackage.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import package_.subpackage.*;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class SubpackageFactoryImpl extends EFactoryImpl implements SubpackageFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static SubpackageFactory init() {
try {
SubpackageFactory theSubpackageFactory = (SubpackageFactory)EPackage.Registry.INSTANCE.getEFactory("http://Some.package/subpackage");
if (theSubpackageFactory != null) {
return theSubpackageFactory;
}
}
catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new SubpackageFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SubpackageFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case SubpackagePackage.A: return createA();
case SubpackagePackage.B: return createB();
case SubpackagePackage.C: return createC();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public A createA() {
AImpl a = new AImpl();
return a;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public B createB() {
BImpl b = new BImpl();
return b;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public C createC() {
CImpl c = new CImpl();
return c;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SubpackagePackage getSubpackagePackage() {
return (SubpackagePackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
public static SubpackagePackage getPackage() {
return SubpackagePackage.eINSTANCE;
}
} //SubpackageFactoryImpl
<file_sep>/query.test.model/src/package_/subpackage/SubpackagePackage.java
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package package_.subpackage;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
/**
* <!-- begin-user-doc -->
* The <b>Package</b> for the model.
* It contains accessors for the meta objects to represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @see package_.subpackage.SubpackageFactory
* @model kind="package"
* @generated
*/
public interface SubpackagePackage extends EPackage {
/**
* The package name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNAME = "subpackage";
/**
* The package namespace URI.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_URI = "http://Some.package/subpackage";
/**
* The package namespace name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_PREFIX = "package.subpackage";
/**
* The singleton instance of the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
SubpackagePackage eINSTANCE = package_.subpackage.impl.SubpackagePackageImpl.init();
/**
* The meta object id for the '{@link package_.subpackage.impl.AImpl <em>A</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see package_.subpackage.impl.AImpl
* @see package_.subpackage.impl.SubpackagePackageImpl#getA()
* @generated
*/
int A = 0;
/**
* The number of structural features of the '<em>A</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int A_FEATURE_COUNT = 0;
/**
* The meta object id for the '{@link package_.subpackage.impl.BImpl <em>B</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see package_.subpackage.impl.BImpl
* @see package_.subpackage.impl.SubpackagePackageImpl#getB()
* @generated
*/
int B = 1;
/**
* The number of structural features of the '<em>B</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int B_FEATURE_COUNT = 0;
/**
* The meta object id for the '{@link package_.subpackage.impl.CImpl <em>C</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see package_.subpackage.impl.CImpl
* @see package_.subpackage.impl.SubpackagePackageImpl#getC()
* @generated
*/
int C = 2;
/**
* The number of structural features of the '<em>C</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int C_FEATURE_COUNT = A_FEATURE_COUNT + 0;
/**
* Returns the meta object for class '{@link package_.subpackage.A <em>A</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>A</em>'.
* @see package_.subpackage.A
* @generated
*/
EClass getA();
/**
* Returns the meta object for class '{@link package_.subpackage.B <em>B</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>B</em>'.
* @see package_.subpackage.B
* @generated
*/
EClass getB();
/**
* Returns the meta object for class '{@link package_.subpackage.C <em>C</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>C</em>'.
* @see package_.subpackage.C
* @generated
*/
EClass getC();
/**
* Returns the factory that creates the instances of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the factory that creates the instances of the model.
* @generated
*/
SubpackageFactory getSubpackageFactory();
/**
* <!-- begin-user-doc -->
* Defines literals for the meta objects that represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @generated
*/
interface Literals {
/**
* The meta object literal for the '{@link package_.subpackage.impl.AImpl <em>A</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see package_.subpackage.impl.AImpl
* @see package_.subpackage.impl.SubpackagePackageImpl#getA()
* @generated
*/
EClass A = eINSTANCE.getA();
/**
* The meta object literal for the '{@link package_.subpackage.impl.BImpl <em>B</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see package_.subpackage.impl.BImpl
* @see package_.subpackage.impl.SubpackagePackageImpl#getB()
* @generated
*/
EClass B = eINSTANCE.getB();
/**
* The meta object literal for the '{@link package_.subpackage.impl.CImpl <em>C</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see package_.subpackage.impl.CImpl
* @see package_.subpackage.impl.SubpackagePackageImpl#getC()
* @generated
*/
EClass C = eINSTANCE.getC();
}
} //SubpackagePackage
|
ce78b3d54e7a382e6db8d179c6e786061096b579
|
[
"Java"
] | 2 |
Java
|
balazsgrill/junk
|
6bf8ab05a069c8d8ea3bf98a1a2e2a53578d199c
|
d177a2fcd37b2f449d7e428de5c5d566a7d81848
|
refs/heads/main
|
<repo_name>JudsenHembree/Clash<file_sep>/Clash.c
/*Project 1 Clash
<NAME>
July 4th 2021
Module 6
*/
#define _GNU_SOURCE
#define MAX_ARGS 32
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char* argv[]){
char *in=NULL;
size_t len = 0;
ssize_t nread;
char* tokens[MAX_ARGS];
void parse(char*, char**);
void execute(char**);
//error excessive args
if(argc>2){
fprintf(stderr,"%s","Invalid clash call.\nInteractive Usage: ./clash \nBatch Usage: ./clash example.txt\n");
free(in);
exit(EXIT_SUCCESS);
}
//interactive mode
if(argc==1){
fprintf(stdout,"%s","\nYou're in interactive mode.\n");
fprintf(stdout,"%s", "\nClash> ");
while((nread = getline(&in,&len,stdin)) !=-1){
parse(in,tokens);
if(strcmp(tokens[0],"exit")==0){
//printf("detect exit");
free(in);
exit(EXIT_SUCCESS);
}else if(strcmp(tokens[0],"cd")==0){
char cdbuf[100];
//printf("detect cd");
if(tokens[2]!=NULL){
printf("***Error cd passed with too many arguements.\n");
free(in);
exit(EXIT_FAILURE);
}
if(tokens[1]==NULL){
printf("***Be advised passing cd without an arguement will set cwd to the HOME environment.\n");
chdir(getenv("HOME"));
printf("cwd: %s ",getcwd(cdbuf, 100));
printf("\n");
}else{
if(chdir(tokens[1])==-1){
fprintf(stderr,"That directory doesn't exist.\n");
}
printf("cwd: %s ",getcwd(cdbuf, 100));
printf("\n");
}
}else if(strcmp(tokens[0],"path")==0){
unsigned tokenCount=1;
while (tokens[tokenCount]!=NULL){
tokenCount++;
}
if(tokenCount < 2){
fprintf(stderr, "Usage: %s list-of-directories-for-path \n\n", argv[0]);
free(in);
exit(EXIT_FAILURE);
}
int new_string_size = 0;
int counter=1;
while (tokens[counter] != NULL){
// for each argument add the size of the argument plus 1 for the ":"
new_string_size += strlen(tokens[counter]) + 1;
counter++;
}
/* allocate memory for the new string */
char * new_string = malloc(sizeof(char) * new_string_size);
new_string[0] = '\0';
counter=1;
while (tokens[counter] != NULL){
strncat(new_string, tokens[counter], strlen(tokens[counter]) + 1);
counter++;
// and add a ":" to separate the elements of the string for all
// but the last part
// You need 2 so you have room for the '\0'
if (tokens[counter] != NULL) strncat(new_string, ":",2);
}
// ... do whatever you're going to do with the string
//printf("You built this string: %s \n", new_string);
setenv("PATH",new_string,1);
printf("PATH: %s\n", getenv("PATH"));
// avoid a memory leak ...
free(new_string);
}else{
execute(tokens);
}
fprintf(stdout,"%s","\nClash> ");
}
//batch mode
}else{
fprintf(stdout,"%s","You're in batch mode\n\n");
char *line_buf = NULL;
size_t line_buf_size = 0;
int line_count = 0;
ssize_t line_size;
char *filename=argv[1];
FILE *fp;
fp= fopen(filename, "r");
if(!fp){
fprintf(stderr,"Error opening file\n");
free(line_buf);
free(filename);
free(fp);
exit(EXIT_FAILURE);
}
/* Get the first line of the file. */
line_size = getline(&line_buf, &line_buf_size, fp);
/* Loop through until we are done with the file. */
while (line_size >= 0){
parse(line_buf, tokens);
/* Increment our line count */
line_count++;
/* Show the line details */
printf("Commands: ");
unsigned i=0;
while(tokens[i]!=NULL){
printf("%s ", tokens[i]);
i++;
}
printf("\n");
if(strcmp(tokens[0],"exit")==0){
//printf("detect exit");
free(line_buf);
free(fp);
exit(EXIT_SUCCESS);
}else if(strcmp(tokens[0],"cd")==0){
char cdbuf[100];
//printf("detect cd");
if(tokens[2]!=NULL){
fprintf(stderr,"***Error cd passed with too many arguements.\n");
free(line_buf);
free(filename);
free(fp);
exit(EXIT_FAILURE);
}
if(tokens[1]==NULL){
//printf("***Be advised passing cd without an arguement will set cwd to the HOME environment.\n");
//not passing this printf cause its batch mode and it would be weird in my opinion.
chdir(getenv("HOME"));
printf("cwd: %s ",getcwd(cdbuf, 100));
printf("\n");
}else{
if(chdir(tokens[1])==-1){
fprintf(stderr,"That directory doesn't exist.\n");
}
printf("cwd: %s ",getcwd(cdbuf, 100));
printf("\n");
}
}else if(strcmp(tokens[0],"path")==0){
unsigned tokenCount=1;
while (tokens[tokenCount]!=NULL){
tokenCount++;
}
if(tokenCount < 2){
fprintf(stderr, "Usage: %s list-of-directories-for-path \n\n", argv[0]);
exit(EXIT_FAILURE);
}
int new_string_size = 0;
int counter=1;
while (tokens[counter] != NULL){
// for each argument add the size of the argument plus 1 for the ":"
new_string_size += strlen(tokens[counter]) + 1;
counter++;
}
/* allocate memory for the new string */
char * new_string = malloc(sizeof(char) * new_string_size);
new_string[0] = '\0';
counter=1;
while (tokens[counter] != NULL){
//concatenate the argument onto the string you're building// and leave space for a '\0' at the end //strncat is safer than strcat - it takes a parameter that limits the // number of characters copies from source to destination
strncat(new_string, tokens[counter], strlen(tokens[counter]) + 1);
counter++;
// and add a ":" to separate the elements of the string for all
// but the last part
// You need 2 so you have room for the '\0'
if (tokens[counter] != NULL) strncat(new_string, ":",2);
}
//printf("You built this string: %s \n", new_string);
setenv("PATH",new_string,1);
printf("PATH: %s\n", getenv("PATH"));
// avoid a memory leak ...
free(new_string);
}else{
execute(tokens);
}
printf("\n");
/* Get the next line */
line_size = getline(&line_buf, &line_buf_size, fp);
}
/* Free the allocated line buffer */
free(line_buf);
line_buf = NULL;
/* Close the file now that we are done with it */
fclose(fp);
}
free(in);
exit(EXIT_SUCCESS);
}
void parse(char* in, char* tokens[]){
unsigned i=0;
bzero(tokens,MAX_ARGS);
char* token;
/* get the first token */
token = strtok(in, " \n");
/* walk through other tokens */
while( token != NULL ) {
if(i>32){
fprintf(stderr,"%s\n", "Must use less than 32 sequential commands.");
free(in);
exit(EXIT_SUCCESS);
}
tokens[i]=token;
token = strtok(NULL, " \n");
i++;
}
}
void execute(char **argv){
pid_t return_pid = fork();
pid_t wait_result;
int stat_loc;
if (return_pid < 0){
fprintf(stderr, "***Error forking child process failed.\n");
exit(EXIT_FAILURE);
}
if (return_pid == 0){
if(execvp(argv[0], argv)==-1){
fprintf(stderr, "***Error exec failed.\n");
exit(EXIT_FAILURE);
}else{
exit(EXIT_SUCCESS);
}
}else{
while(wait_result= waitpid(return_pid,&stat_loc,WUNTRACED)==0);
}
}<file_sep>/Makefile
all: Clash.c
gcc -o Clash Clash.c
zip:
zip -o proj1 Clash.c Makefile
|
baba98339230f2165c9d942eb84418901b9cbace
|
[
"C",
"Makefile"
] | 2 |
C
|
JudsenHembree/Clash
|
7efa440dcf7aa2c6a95e8c9dc8931ffa1a0f0c9e
|
1fbd9ed48030628a248bdbb97acc8def4db06a12
|
refs/heads/master
|
<repo_name>moisutsu/chip8-emulator<file_sep>/src/lib.rs
pub mod cpu;
pub mod display;
pub use cpu::*;
pub use display::*;
<file_sep>/src/cpu.rs
use rand;
use std::fs::File;
use std::io::Read;
pub struct Cpu {
v: [u8; 16],
i: u16,
delay: u8,
sound: u8,
pc: u16,
sp: u8,
stack: [u16; 16],
ram: [u8; 0xFFF],
}
pub enum NextPc {
Next,
Skip,
Jump(u16),
}
impl Cpu {
pub fn new() -> Cpu {
Cpu {
v: [0; 16],
i: 0,
delay: 0,
sound: 0,
pc: 0x200,
sp: 0,
stack: [0; 16],
ram: [0; 0xFFF],
}
}
pub fn init_ram(&mut self) {
let fontpreset = vec![
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80, // F
];
self.ram[..fontpreset.len()].copy_from_slice(&fontpreset);
}
pub fn print_registers(&self) {
for i in 0..16 {
print!("V{:X}: {:X}, ", i, self.v[i]);
}
print!("I: {:X}, ", self.i);
print!("PC: {:X}, ", self.pc);
println!("SP: {:X}", self.sp);
}
pub fn print_instruction_code(&self) {
let (b1, b2): (u8, u8) = (self.ram[self.pc as usize], self.ram[(self.pc + 1) as usize]);
let v1 = b1 >> 4;
let v2 = b1 & 0b00001111;
let v3 = b2 >> 4;
let v4 = b2 & 0b00001111;
println!("命令コード: {:X}{:X}{:X}{:X}", v1, v2, v3, v4);
}
pub fn load_rom(&mut self, file_path: &str) -> std::io::Result<()> {
let mut file = File::open(file_path)?;
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
self.ram[0x200..0x200 + buf.len()].copy_from_slice(&buf);
Ok(())
}
/// pcが指す16ビットの命令コードをフェッチし,4ビットずつにわけて返す
pub fn fetch_instruction_code(&self) -> (u8, u8, u8, u8) {
let (b1, b2): (u8, u8) = (self.ram[self.pc as usize], self.ram[(self.pc + 1) as usize]);
let v1 = b1 >> 4;
let v2 = b1 & 0b00001111;
let v3 = b2 >> 4;
let v4 = b2 & 0b00001111;
(v1, v2, v3, v4)
}
pub fn set_pc(&mut self, next_pc: NextPc) {
match next_pc {
NextPc::Next => {
self.pc += 2;
}
NextPc::Skip => {
self.pc += 4;
}
NextPc::Jump(addr) => self.pc = addr,
}
}
// 命令セットの定義
pub fn ret(&mut self) -> NextPc {
let next_pc = self.stack[self.sp as usize];
self.sp -= 1;
NextPc::Jump(next_pc)
}
pub fn jp_addr(&mut self, n1: u8, n2: u8, n3: u8) -> NextPc {
let next_pc = ((n1 as u16) << 8) + ((n2 as u16) << 4) + n3 as u16;
NextPc::Jump(next_pc)
}
pub fn call_addr(&mut self, n1: u8, n2: u8, n3: u8) -> NextPc {
self.sp += 1;
self.stack[self.sp as usize] = self.pc;
let next_pc = ((n1 as u16) << 8) + ((n2 as u16) << 4) + n3 as u16;
NextPc::Jump(next_pc)
}
pub fn se_vx_byte(&self, x: u8, k1: u8, k2: u8) -> NextPc {
if self.v[x as usize] == (k1 << 4) + k2 {
NextPc::Skip
} else {
NextPc::Next
}
}
pub fn sne_vx_byte(&self, x: u8, k1: u8, k2: u8) -> NextPc {
if self.v[x as usize] != (k1 << 4) + k2 {
NextPc::Skip
} else {
NextPc::Next
}
}
pub fn se_vx_vy(&self, x: u8, y: u8) -> NextPc {
if self.v[x as usize] == self.v[y as usize] {
NextPc::Skip
} else {
NextPc::Next
}
}
pub fn ld_vx_byte(&mut self, x: u8, k1: u8, k2: u8) -> NextPc {
self.v[x as usize] = (k1 << 4) + k2;
NextPc::Next
}
pub fn add_vx_byte(&mut self, x: u8, k1: u8, k2: u8) -> NextPc {
self.v[x as usize] = self.v[x as usize] + (k1 << 4) + k2;
NextPc::Next
}
pub fn ld_vx_vy(&mut self, x: u8, y: u8) -> NextPc {
self.v[x as usize] = self.v[y as usize];
NextPc::Next
}
pub fn or_vx_vy(&mut self, x: u8, y: u8) -> NextPc {
self.v[x as usize] = self.v[x as usize] | self.v[y as usize];
NextPc::Next
}
pub fn and_vx_vy(&mut self, x: u8, y: u8) -> NextPc {
self.v[x as usize] &= self.v[y as usize];
NextPc::Next
}
pub fn xor_vx_vy(&mut self, x: u8, y: u8) -> NextPc {
self.v[x as usize] ^= self.v[y as usize];
NextPc::Next
}
pub fn add_vx_vy(&mut self, x: u8, y: u8) -> NextPc {
// 16bitに変換してから255より大きいかを判定する
let retval: u16 = self.v[x as usize] as u16 + self.v[y as usize] as u16;
self.v[0xF] = if retval > 255 { 1 } else { 0 };
// as u8 より下位8bitのみ保持
self.v[x as usize] = retval as u8;
NextPc::Next
}
pub fn sub_vx_vy(&mut self, x: u8, y: u8) -> NextPc {
self.v[0xF] = if self.v[x as usize] > self.v[y as usize] {
1
} else {
0
};
// u8 - u8 で負になる場合の代入は未実装
if self.v[x as usize] >= self.v[y as usize] {
self.v[x as usize] = self.v[x as usize] - self.v[y as usize];
}
NextPc::Next
}
pub fn shr_vx_vy(&mut self, x: u8, _y: u8) -> NextPc {
self.v[0xF] = if self.v[x as usize] % 2 == 1 { 1 } else { 0 };
self.v[x as usize] >>= 1;
NextPc::Next
}
pub fn subn_vx_vy(&mut self, x: u8, y: u8) -> NextPc {
self.v[0xF] = if self.v[y as usize] > self.v[x as usize] {
1
} else {
0
};
// u8 - u8 が負になる場合は未実装
if self.v[y as usize] >= self.v[x as usize] {
self.v[x as usize] = self.v[y as usize] - self.v[x as usize];
}
NextPc::Next
}
pub fn shl_vx_vy(&mut self, x: u8, _y: u8) -> NextPc {
self.v[0xF] = if self.v[x as usize] >= 128 { 1 } else { 0 };
self.v[x as usize] <<= 1;
NextPc::Next
}
pub fn sne_vx_vy(&self, x: u8, y: u8) -> NextPc {
if self.v[x as usize] != self.v[y as usize] {
NextPc::Skip
} else {
NextPc::Next
}
}
pub fn ld_i_addr(&mut self, n1: u8, n2: u8, n3: u8) -> NextPc {
self.i = ((n1 as u16) << 8) + ((n2 as u16) << 4) + n3 as u16;
NextPc::Next
}
pub fn jp_v0_addr(&self, n1: u8, n2: u8, n3: u8) -> NextPc {
let next_pc: u16 = ((n1 as u16) << 8) + ((n2 as u16) << 4) + n3 as u16 + self.v[0x0] as u16;
NextPc::Jump(next_pc)
}
pub fn rnd_vx_byte(&mut self, x: u8, k1: u8, k2: u8) -> NextPc {
let kk: u8 = (k1 << 4) + k2;
self.v[x as usize] = kk & rand::random::<u8>();
NextPc::Next
}
pub fn ld_vx_dt(&mut self, x: u8) -> NextPc {
self.v[x as usize] = self.delay;
NextPc::Next
}
pub fn ld_dt_vx(&mut self, x: u8) -> NextPc {
self.delay = self.v[x as usize];
NextPc::Next
}
pub fn ld_st_vx(&mut self, x: u8) -> NextPc {
self.sound = self.v[x as usize];
NextPc::Next
}
pub fn add_i_vx(&mut self, x: u8) -> NextPc {
self.i += self.v[x as usize] as u16;
NextPc::Next
}
}
<file_sep>/src/display.rs
extern crate termion;
use std::io::{stdout, Write};
use termion::raw::IntoRawMode;
pub struct Display {
stdout: termion::raw::RawTerminal<std::io::Stdout>,
}
impl Display {
pub fn new() -> Display {
Display {
stdout: stdout().into_raw_mode().unwrap(),
}
}
pub fn draw_byte(&mut self, byte: u8, x: u16, y: u16) {
write!(
self.stdout,
"{}{}",
termion::cursor::Goto(x, y),
from_byte(byte)
)
.unwrap();
self.stdout.flush().unwrap();
}
pub fn clear(&mut self) {
write!(self.stdout, "{}", termion::clear::All).unwrap();
self.stdout.flush().unwrap();
}
}
// 01010000 -> " * *"
fn from_byte(mut byte: u8) -> String {
let one = if byte >= 128 { "*" } else { " " };
byte <<= 1;
let two = if byte >= 128 { "*" } else { " " };
byte <<= 1;
let three = if byte >= 128 { "*" } else { " " };
byte <<= 1;
let four = if byte >= 128 { "*" } else { " " };
format!("{}{}{}{}", one, two, three, four)
}
<file_sep>/README.md
# chip8-emulator
RustによるChip8エミュレーターの実装
[こちら](https://qiita.com/yukinarit/items/4bdc821f1e46b0688d0d)をとても参考にしています.
<file_sep>/src/main.rs
extern crate chip8;
use std::env;
use std::process::exit;
use std::{thread, time};
fn main() {
let mut cpu = chip8::Cpu::new();
cpu.init_ram();
let argv: Vec<String> = env::args().collect();
if argv.len() != 2 {
eprintln!("[Error] No input file.");
exit(1);
}
cpu.load_rom(&argv[1]).unwrap();
let sleep_time = time::Duration::from_millis(1000);
loop {
cpu.print_instruction_code();
let next_pc = match cpu.fetch_instruction_code() {
(0x0, 0x0, 0xE, 0xE) => cpu.ret(),
(0x1, n1, n2, n3) => cpu.jp_addr(n1, n2, n3),
(0x2, n1, n2, n3) => cpu.call_addr(n1, n2, n3),
(0x3, x, k1, k2) => cpu.se_vx_byte(x, k1, k2),
(0x4, x, k1, k2) => cpu.sne_vx_byte(x, k1, k2),
(0x5, x, y, 0x0) => cpu.se_vx_vy(x, y),
(0x6, x, k1, k2) => cpu.ld_vx_byte(x, k1, k2),
(0x7, x, k1, k2) => cpu.add_vx_byte(x, k1, k2),
(0x8, x, y, 0x0) => cpu.ld_vx_vy(x, y),
(0x8, x, y, 0x1) => cpu.or_vx_vy(x, y),
(0x8, x, y, 0x2) => cpu.and_vx_vy(x, y),
(0x8, x, y, 0x3) => cpu.xor_vx_vy(x, y),
(0x8, x, y, 0x4) => cpu.add_vx_vy(x, y),
(0x8, x, y, 0x5) => cpu.sub_vx_vy(x, y),
(0x8, x, y, 0x6) => cpu.shr_vx_vy(x, y),
(0x8, x, y, 0x7) => cpu.subn_vx_vy(x, y),
(0x8, x, y, 0xE) => cpu.shl_vx_vy(x, y),
(0x9, x, y, 0x0) => cpu.sne_vx_vy(x, y),
(0xA, n1, n2, n3) => cpu.ld_i_addr(n1, n2, n3),
(0xB, n1, n2, n3) => cpu.jp_v0_addr(n1, n2, n3),
(0xC, x, k1, k2) => cpu.rnd_vx_byte(x, k1, k2),
(0xF, x, 0x0, 0x7) => cpu.ld_vx_dt(x),
(0xF, x, 0x1, 0x5) => cpu.ld_dt_vx(x),
(0xF, x, 0x1, 0x8) => cpu.ld_st_vx(x),
(0xF, x, 0x1, 0xE) => cpu.add_i_vx(x),
_ => chip8::cpu::NextPc::Next,
};
cpu.set_pc(next_pc);
cpu.print_registers();
thread::sleep(sleep_time);
}
}
|
b3aecdfadf5471723b401e21d0035c15fa2477db
|
[
"Markdown",
"Rust"
] | 5 |
Rust
|
moisutsu/chip8-emulator
|
bf031661f27f4bb51158ad36e761699a0f9f3dc3
|
be603873328fd17c7f87ec2e201411747958100f
|
refs/heads/master
|
<file_sep>class LinkedListNode
attr_accessor :value, :next_node
def initialize(value, next_node=nil)
@value = value
@next_node = next_node
end
end
def print_values(list_node)
if list_node
print "#{list_node.value} --> "
print_values(list_node.next_node)
else
print "nil\n"
return
end
end
class Stack
attr_reader :data
def initialize
@data=nil
end
#pushing a value onto the stack
def push(value)
@data=LinkedListNode.new(value,@data)
end
#pop an item from the stack, remove last item pushed onto the stack
#and return the value
def pop
if @data.nil?
nil
else
@[email protected]_node
end
end
end
#reverse a list
def reverse_list(list)
stack= Stack.new
while list
stack.push(list.value)
list = list.next_node
end
return stack.data
end
node1 = LinkedListNode.new(37)
node2 = LinkedListNode.new(99, node1)
node3 = LinkedListNode.new(12, node2)
print_values(node3)
puts "-------"
revlist = reverse_list(node3)
print_values(revlist)
<file_sep>class LinkedListNode
attr_accessor :value, :next_node
def initialize(value, next_node=nil)
@value = value
@next_node = next_node
end
end
#print the values from a linked list
def print_values(list_node)
if list_node
print "#{list_node.value} --> "
print_values(list_node.next_node)
else
print "nil\n"
return
end
end
#infinite list or not
def infinite_list(list)
tortoise = list.next_node
hare = list.next_node
until hare.nil?
if hare.nil?
return false
end
hare=hare.next_node
tortoise = tortoise.next_node
if hare == tortoise
return true
end
end
return false
end
#reverse a list
def reverse_list(list, previous=nil)
if list
next_node = list.next_node
list.next_node = previous
reverse_list(next_node, list)
end
end
node1 = LinkedListNode.new(37)
node2 = LinkedListNode.new(99, node1)
node3 = LinkedListNode.new(12, node2)
puts 'The linked list is'
print_values(node3)
puts 'The reversed linked list is'
reverse_list(node3)
print_values(node1)
puts 'Is it an Infinite list ?'
node3.next_node=node1
puts infinite_list(node3)
|
fbc0d45fdfa5abc54e3f810b92dcaa8b39a1f1f6
|
[
"Ruby"
] | 2 |
Ruby
|
bhavanisarma/linkedlistruby
|
3d37c617fe10e85da9f53478c98baeb78be34741
|
f806dbc10b0b8f42dea0181602c90f5344382252
|
refs/heads/master
|
<file_sep>var tdTotalCursos = document.querySelector('.js-total-de-cursos');
var tdTotalHoras = document.querySelector('.js-total-de-horas');
var btnConfirmar = document.querySelector('button.btn');
var checkboxes = document.querySelectorAll('input[type=checkbox]');
var totalHoras = 0;
var totalCursos = 0;
btnConfirmar.onclick = function() {
if (totalCursos === 0) {
alert('Por favor, selecione ao menos 1 curso!');
}
else {
alert('Matricula confirmada com sucesso!');
window.location = 'index.html';
}
}
checkboxes.forEach(function(checkboxCurso) {
checkboxCurso.onchange = function() {
if (this.checked) {
totalCursos++;
totalHoras += parseInt(this.value);
}
else {
totalCursos--;
totalHoras -= parseInt(this.value);
}
tdTotalHoras.textContent = totalHoras + 'h';
tdTotalCursos.textContent = totalCursos + ' curso(s)';
}
});
|
21cb787d5973a64fe79df6819b38563b0231a5b8
|
[
"JavaScript"
] | 1 |
JavaScript
|
jhonatanjacinto/web8883
|
6714b24241b46aef7d7bb39e2b16500cf19e8b71
|
40d37a27b9c8a4ddcf4510b0188031847d373b13
|
refs/heads/master
|
<repo_name>brettz9/safer-route<file_sep>/lib/main.js
/*globals exports, require, XPCOMUtils */
/*jslint todo: true, vars: true*/
/*
Todos for later
1. When available, replace with https://developer.mozilla.org/en-US/Add-ons/SDK/Low-Level_APIs/places_history
*/
(function () {'use strict';
function l (msg) {
console.log(msg);
}
var modifyRequest;
exports.main = function () {
var gBrowser = require('sdk/window/utils').getMostRecentBrowserWindow().gBrowser;
var chrome = require('chrome'), Cc = chrome.Cc, Ci = chrome.Ci, Cu = chrome.Cu, Cr = chrome.Cr;
var prefs = require('sdk/simple-prefs').prefs;
var XMLHttpRequest = require('sdk/net/xhr').XMLHttpRequest;
Cu['import']('resource://gre/modules/XPCOMUtils.jsm');
function makeURI(aURL, aOriginCharset, aBaseURI) {
var ioService = Cc['@mozilla.org/network/io-service;1']
.getService(Ci.nsIIOService);
return ioService.newURI(aURL, aOriginCharset, aBaseURI);
}
function getHTTPSForLocation (url) {
return url.replace(/^http:/, 'https:');
}
/*
function redirect (subject, uri) {
subject.redirectTo(makeURI(uri));
}
*/
function historyAlteration (aURI) {
switch (prefs.httpInHistory) {
// Todo: Allowing an option for alteration of HTTP into HTTPS would be great, but mapping mozIPlaceInfo (and mozIVisitInfo) needed by mozIAsyncHistory.updatePlaces to nsINavHistoryResultNode (and subclasses?) seems less than clear
/*
Add to httpInHistory "description" in package.json and properties: "or modify them to show as if HTTPS had been visited"
Add to properties: httpInHistory_options.alter_in_history=Check history for equivalent HTTPS support and alter any equivalent HTTP files in history to use HTTPS upon discovery
{
"value": "alter_in_history",
"label": "Check history for equivalent HTTPS support and alter any equivalent HTTP files in history to use HTTPS upon discovery"
},
*/
/*
case 'alter_in_history':
var asyncHistory = Cc['@mozilla.org/browser/history;1'].
getService(Ci.mozIAsyncHistory);
cont.getChild(0);
asyncHistory.updatePlaces({placeId: , uri: getHTTPSForLocation(aURL)});
// Fall-through
*/
case 'delete_from_history':
// Not needed?
//var ac = Cc['@mozilla.org/autocomplete/search;1?name=history'].getService(Ci.mozIPlacesAutoComplete);
//ac.unregisterOpenPage(aURI);
var browserHistory = Cc['@mozilla.org/browser/nav-history-service;1'].
getService(Ci.nsIBrowserHistory);
browserHistory.removePage(aURI);
break;
default:
throw 'Unexpected httpInHistory value';
}
}
modifyRequest = {
init: function() {
gBrowser.addProgressListener(this);
},
uninit: function() {
gBrowser.removeProgressListener(this);
},
// nsIWebProgressListener
QueryInterface: XPCOMUtils.generateQI(['nsIWebProgressListener',
'nsISupportsWeakReference']),
onLocationChange: function(aProgress, aRequest, aURI) {
if (!aURI.schemeIs('http')) {return;}
var aURL = aURI.spec;
var hasHTTPS;
function getWindow () {
return aProgress.DOMWindow;
}
function processLocation (resume) {
var win;
if (hasHTTPS || prefs.paranoiaMode === 'load_https') {
try {
aRequest.cancel(Cr.NS_BINDING_ABORTED);
}
catch(e) {
console.log("Couldn't cancel: " + aURL);
}
// redirect(subject, getHTTPSForLocation(aURL)); // Leaves a non-HTTPS item in history, so we instead change location
win = getWindow();
win.location = getHTTPSForLocation(aURL);
}
else if (prefs.paranoiaMode === 'load_empty') {
aRequest.cancel(Cr.NS_BINDING_ABORTED);
// redirect(subject, 'about:newtab'); // Leaves a non-HTTPS item in history, so we instead change location
win = getWindow();
win.location = 'about:newtab';
}
else if (resume) {
aRequest.resume();
}
// Otherwise, go ahead with requested HTTP load
// else { // prefs.paranoiaMode === 'load_http'
// }
}
if (prefs.paranoiaMode !== 'load_https') {
if (prefs.historyChecking) {
// Check for whether an https version exists for this domain in the history
var domain = aURI.host;
var historyService = Cc['@mozilla.org/browser/nav-history-service;1']
.getService(Ci.nsINavHistoryService);
// No query options set will get all history, sorted in database order,
// which is nsINavHistoryQueryOptions.SORT_BY_NONE.
var options = historyService.getNewQueryOptions();
// No query parameters will return everything
var query = historyService.getNewQuery();
//query.domainIsHost = 0;
//query.domain = domain;
query.uriIsPrefix = true;
query.uri = makeURI('https://' + domain); // If domain is found with https://, probably safe for any URL
var result = historyService.executeQuery(query, options);
var cont = result.root;
cont.containerOpen = true;
hasHTTPS = cont.childCount;
cont.containerOpen = false;
if (prefs.httpInHistory !== 'do_not_alter') {
// Look for an exact match this time
query = historyService.getNewQuery();
query.uri = aURI;
result = historyService.executeQuery(query, options);
cont = result.root;
cont.containerOpen = true;
var hasChildren = cont.childCount;
l('http to delete:' + hasChildren + '::' + aURI.spec);
if (hasChildren) {
try {
historyAlteration(aURI);
}
finally {
cont.containerOpen = false;
}
}
else {
cont.containerOpen = false;
}
}
}
if (!hasHTTPS && prefs.headRequest) {
var xhr = new XMLHttpRequest();
aRequest.suspend();
xhr.open('HEAD', getHTTPSForLocation(aURL), true);
xhr.onload = function () {
hasHTTPS = !!this.getResponseHeader('Last-Modified');
processLocation(true);
if (hasHTTPS && prefs.httpInHistory !== 'do_not_alter') {
historyAlteration(aURI);
}
};
xhr.onerror = function () {
processLocation(true);
};
xhr.send();
return;
}
}
processLocation();
},
onStateChange: function() {},
onProgressChange: function() {},
onStatusChange: function() {},
onSecurityChange: function() {}
};
modifyRequest.init();
};
exports.onUnLoad = function () {
if (modifyRequest) {
modifyRequest.uninit();
}
};
}());
<file_sep>/CHANGES.md
# 0.2.0
- Add support for private window browsing
# 0.1.5
- jpm packaging
# 0.1.4
- Update to SDK 1.16
# 0.1.3
- Prevent cancellation errors
# 0.1.2
- Ensure HEAD request is indeed asynchronous
# 0.1.1
- Critical bug fix (using wrong type of listener)
<file_sep>/README.md
# Safer Route
This is a simple Firefox add-on which, upon an HTTP request, optionally
checks user history and/or makes a HEAD request to detect whether a
site supports HTTPS, and if so, changes the request to use the HTTPS
protocol, otherwise keeping the URL the same (and also optionally deleting
the HTTP version from the history).
Also provides two optional "paranoia modes", one which will replace all
HTTP requests with HTTPS and one which will lead to a blank page
when not found.
IMPORTANT NOTE: Some well-used sites, like Amazon.com may
use the practice of mixing http and https for the same domain
and redirecting https requests back to http for pages deemed not
to be sensitive, thereby potentially compromising at least your
privacy. This practice will currently cause my add-on to have a
major hiccup when such a site is visited, as my add-on keeps
trying to go to the https version, but the site keeps forwarding
it back to the http version. I may build in a system to prevent
this, such as allowing site-specific exceptions in the future, but
as I do not have time at the moment, you may wish to forgo
using this add-on until it supports exceptions or disable it when
visiting such a site.
# Alternatives
* https://addons.mozilla.org/en-US/firefox/addon/http-nowhere/
* https://www.eff.org/https-everywhere
# Possible todos
1. Support alteration of history to use HTTPS in place of HTTP (as
opposed to deletion).
|
904819e796fa4b759e232d56c30e1fa9abbe2127
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
brettz9/safer-route
|
ea719e9de81be7098cd3de004c8f8b04badb3ffb
|
2e2b36718eca9d0038e7d8e3e8ee07fa0385f3e4
|
refs/heads/main
|
<file_sep>document.addEventListener("DOMContentLoaded", function () {
// Поиск родителя
function findAncestor(el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
function closeSelects() {
const selects = document.querySelectorAll(".exchange__select");
selects.forEach((select) => {
select.classList.remove("exchange__select--active");
});
}
const selectsHead = document.querySelectorAll(".exchange__select__head");
if (selectsHead) {
selectsHead.forEach((selectHead) => {
selectHead.addEventListener("click", () => {
const currSelect = selectHead.parentNode;
if (currSelect.classList.contains("exchange__select--active")) {
currSelect.classList.remove("exchange__select--active");
} else {
closeSelects();
currSelect.classList.add("exchange__select--active");
}
});
});
}
if (selectsHead) {
document.onclick = function (evt) {
if (
evt.target.className != "exchange__select" &&
!findAncestor(evt.target, "exchange__select")
) {
closeSelects();
}
};
}
const selectItems = document.querySelectorAll(".exchange__select__item");
if (selectItems) {
selectItems.forEach((selectItem) => {
selectItem.addEventListener("click", () => {
const currSelect = findAncestor(selectItem, "exchange__select");
const currSelectHead = currSelect.querySelector(
".exchange__select__head"
);
currSelectHead.innerHTML = selectItem.innerHTML;
currSelect.classList.remove("exchange__select--active");
});
});
}
const openSelect = document.querySelector("#openSelect");
if (openSelect) {
openSelect.addEventListener("click", (evt) => {
evt.preventDefault();
openSelect.parentNode.classList.toggle("exchange__inner__choose--active");
});
}
// Tooltip
tippy("[data-tippy-content]");
});
|
c72776e4e3b4351476ab35b027165012a0c872bf
|
[
"JavaScript"
] | 1 |
JavaScript
|
MaximProger/crypt-mining-2
|
59f653302b67c2b56a9a2401788ab642beb20405
|
ebd8fda5422c348630970d5ea6f9e8fdd3702b7b
|
refs/heads/master
|
<file_sep>/*****************
Coded by @bachors
******************/
$(document).ready(function () {
tweet('bachors');
instagram('261199158');
google('100217793741516090316');
facebook('203532783129859');
vk('324573775');
soundcloud('118174461');
github('bachors');
youtube('bachorsan');
$('#setting').click(function () {
$('#form').toggleClass('show');
});
$('#go').click(function () {
$('#feed').empty();
tweet(($('#twitter').val() != '' ? $('#twitter').val() : 'bachors'));
instagram(($('#instagram').val() != '' ? $('#instagram').val() : '261199158'));
google(($('#google').val() != '' ? $('#google').val() : '100217793741516090316'));
facebook(($('#facebook').val() != '' ? $('#facebook').val() : '203532783129859'));
vk(($('#vk').val() != '' ? $('#vk').val() : '324573775'));
soundcloud(($('#soundcloud').val() != '' ? $('#soundcloud').val() : '118174461'));
github(($('#github').val() != '' ? $('#github').val() : 'bachors'));
youtube(($('#youtube').val() != '' ? $('#youtube').val() : 'bachorsan'));
return false;
});
});
function tweet(id) {
$.ajax({
url: 'http://ibacor.com/api/twitter-stream?screen_name=' + id + '&count=1&k=cb9020c4747f32673915aa1caccf1ecd',
crossDomain: true,
dataType: 'json'
}).done(function (json) {
var data = json.data[0],
date = new Date(data.created_at),
time = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + (date.getMinutes() + 1) + ':' + date.getSeconds(),
poto = '',
html = '';
if (data.extended_entities != null || data.extended_entities != undefined) {
if (data.extended_entities.media != null || data.extended_entities.media != undefined) {
if (data.extended_entities.media[0].media_url != null || data.extended_entities.media[0].media_url != undefined) {
poto += '<img src="' + data.extended_entities.media[0].media_url + '" class="media"/>';
}
}
} else if (data.retweeted_status != null || data.retweeted_status != undefined) {
if (data.retweeted_status.entities.media != null || data.retweeted_status.entities.media != undefined) {
if (data.retweeted_status.entities.media[0].media_url != null || data.retweeted_status.entities.media[0].media_url != undefined) {
poto += '<img src="' + data.retweeted_status.entities.media[0].media_url + '" class="media"/>';
}
}
}
var url = {
link: 'https://twitter.com/',
tag: 'https://twitter.com/hashtag/'
}
html += '<div class="post twitter">';
html += ' <div class="content">';
html += ' <div class="left">';
html += ' <i class="fa fa-twitter"></i>';
html += ' </div>';
html += ' <div class="right">';
html += ' <div class="top">';
html += ' <a class="user" href="https://twitter.com/' + data.user.screen_name + '" target="_blank">@' + data.user.screen_name + '</a>';
html += ' <a class="date" href="https://twitter.com/' + id + '/status/' + data.id_str + '" target="_blank">' + relative_time(time) + ' ago</a>';
html += ' </div>';
html += ' <div class="bottom">';
html += urltag(data.text, url);
html += ' </div>';
html += ' </div>';
html += ' </div>';
html += poto;
html += '</div>';
$('#feed').append(html);
})
}
function instagram(id) {
$.ajax({
url: 'https://api.instagram.com/v1/users/' + id + '/media/recent/?access_token=222743<PASSWORD>&count=1',
crossDomain: true,
dataType: 'jsonp'
}).done(function (c) {
var data = c.data[0],
date = new Date(parseInt(data.created_time) * 1000),
time = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + (date.getMinutes() + 1) + ':' + date.getSeconds(),
des = '',
html = '';
des += (data.caption == null || data.caption == undefined ? '' : data.caption.text);
var url = {
link: 'https://instagram.com/',
tag: 'https://instagram.com/explore/tags/'
}
html += '<div class="post instagram">';
html += ' <div class="content">';
html += ' <div class="left">';
html += ' <i class="fa fa-instagram"></i>';
html += ' </div>';
html += ' <div class="right">';
html += ' <div class="top">';
html += ' <a class="user" href="http://instagram.com/' + data.caption.from.username + '" target="_blank">@' + data.caption.from.username + '</a>';
html += ' <a class="date" href="' + data.link + '" target="_blank">' + relative_time(time) + ' ago</a>';
html += ' </div>';
html += ' <div class="bottom">';
html += urltag(des, url);
html += ' </div>';
html += ' </div>';
html += ' </div>';
html += ' <img src="' + data.images.standard_resolution.url + '" class="media"/>';
html += '</div>';
$('#feed').append(html);
});
}
function google(id) {
$.ajax({
url: 'https://www.googleapis.com/plus/v1/people/' + id + '/activities/public?key=AIzaSyCj2GrDSBy6ISeGg3aWUM4mn3izlA1wgt0',
crossDomain: true,
dataType: 'jsonp'
}).done(function (json) {
var data = json.items[0],
poto = '',
title = '',
html = '';
if (data.object.attachments != '' && data.object.attachments != null && data.object.attachments != undefined) {
if (data.object.attachments[0].objectType == 'video' && data.object.attachments[0].embed != null) {
poto += '<iframe src="' + data.object.attachments[0].embed.url + '" class="media"></iframe>';
} else if (data.object.attachments[0].objectType == 'photo') {
poto += '<img src="' + data.object.attachments[0].fullImage.url + '" class="media"/>';
} else if (data.object.attachments[0].objectType == 'article') {
if (data.object.attachments[0].fullImage != null && data.object.attachments[0].fullImage != undefined) {
poto += '<img src="' + data.object.attachments[0].fullImage.url + '" class="media"/>';
} else if (data.object.attachments[0].image != null && data.object.attachments[0].image != undefined) {
poto += '<img src="' + data.object.attachments[0].image.url + '" class="media"/>';
}
}
}
if (data.object.attachments != null && data.object.attachments[0].objectType == 'article') {
title += data.object.attachments[0].url;
}
html += '<div class="post google">';
html += ' <div class="content">';
html += ' <div class="left">';
html += ' <i class="fa fa-google-plus-official"></i>';
html += ' </div>';
html += ' <div class="right">';
html += ' <div class="top">';
html += ' <a class="user" href="https://plus.google.com/' + data.actor.id + '" target="_blank">' + data.actor.displayName + '</a>';
html += ' <a class="date" href="' + data.url + '" target="_blank">' + relative_time(data.published) + ' ago</a>';
html += ' </div>';
html += ' <div class="bottom">';
html += data.object.content;
html += ' </div>';
html += ' </div>';
html += ' </div>';
html += poto;
html += '</div>';
$('#feed').append(html);
});
}
function facebook(id) {
$.ajax({
url: 'https://graph.facebook.com/v2.2/' + id + '/feed?limit=1&access_token=443213172472393|l<PASSWORD>Y<PASSWORD>NAg<PASSWORD>',
crossDomain: true,
dataType: 'json'
}).done(function (json) {
var data = json.data[0],
poto = '',
html = '';
if (data.picture != null && data.picture != undefined) {
poto += '<img src="https://graph.facebook.com/' + data.object_id + '/picture" class="media">'
}
var url = {
link: 'https://facebook.com/',
tag: 'https://facebook.com/hashtag/'
}
html += '<div class="post facebook">';
html += ' <div class="content">';
html += ' <div class="left">';
html += ' <i class="fa fa-facebook-official"></i>';
html += ' </div>';
html += ' <div class="right">';
html += ' <div class="top">';
html += ' <a class="user" href="https://facebook.com/' + data.from.id + '" target="_blank">' + data.from.name + '</a>';
html += ' <a class="date" href="' + data.link + '" target="_blank">' + relative_time(data.created_time) + ' ago</a>';
html += ' </div>';
if (data.message != null && data.message != undefined) {
html += ' <div class="bottom">';
html += urltag(data.message, url);
html += ' </div>';
}
html += ' </div>';
html += ' </div>';
html += poto;
html += '</div>';
$('#feed').append(html);
});
}
function vk(id) {
$.ajax({
url: 'https://api.vk.com/method/wall.get?owner_id=' + id + '&filter=all&count=1',
crossDomain: true,
dataType: 'jsonp'
}).done(function (json) {
var data = json.response[1],
date = new Date(parseInt(data.date) * 1000),
time = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + (date.getMinutes() + 1) + ':' + date.getSeconds(),
poto = '',
html = '';
if (data.attachment != null && data.attachment != undefined) {
if (data.attachment.type == 'photo') {
poto += '<img src="' + data.attachment.photo.src_big + '" class="media">'
}
}
var url = {
link: 'https://vk.com/',
tag: 'https://vk.com/feed?section=search&q=%23'
}
html += '<div class="post vk">';
html += ' <div class="content">';
html += ' <div class="left">';
html += ' <i class="fa fa-vk"></i>';
html += ' </div>';
html += ' <div class="right">';
html += ' <div class="top">';
html += ' <a class="user" href="https://vk.com/id' + data.from_id + '" target="_blank"></a>';
html += ' <a class="date" href="https://vk.com/wall' + data.from_id + '_' + data.id + '" target="_blank">' + relative_time(time) + ' ago</a>';
html += ' </div>';
if (data.text != null && data.text != undefined) {
html += ' <div class="bottom">';
html += urltag(data.text, url);
html += ' </div>';
}
html += ' </div>';
html += ' </div>';
html += poto;
html += '</div>';
$('#feed').append(html);
_vk('324573775');
});
}
function soundcloud(id) {
$.ajax({
url: 'https://api.soundcloud.com/tracks?user_id=' + id + '&format=json&client_id=158d3e1ba760d77b323fdf7a79b77730',
crossDomain: true,
dataType: 'json'
}).done(function (json) {
var data = json[0],
html = '';
var url = {
link: 'https://vk.com/',
tag: 'https://vk.com/feed?section=search&q=%23'
}
html += '<div class="post soundcloud">';
html += ' <div class="content">';
html += ' <div class="left">';
html += ' <i class="fa fa-soundcloud"></i>';
html += ' </div>';
html += ' <div class="right">';
html += ' <div class="top">';
html += ' <a class="user" href="https://soundcloud.com/' + data.user.permalink + '" target="_blank">@' + data.user.permalink + '</a>';
html += ' <a class="date" href="' + data.permalink_url + '" target="_blank">' + relative_time(data.created_at) + ' ago</a>';
html += ' </div>';
html += ' <div class="bottom">';
html += data.title + (data.description != null && data.description != undefined && data.description != '' ? ' - ' + urltag(data.description, url) : '');
html += ' </div>';
html += ' </div>';
html += ' </div>';
html += '<iframe class="media" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/' + data.id + '&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true"></iframe>';
html += '</div>';
$('#feed').append(html);
});
}
function github(id) {
$.ajax({
url: 'https://api.github.com/users/' + id + '/events',
crossDomain: true,
dataType: 'json'
}).done(function (json) {
var data = json[0],
comit = '',
html = '';
if (data.type == "WatchEvent") {
comit += data.payload.action + ' <a href="https://github.com/' + data.repo.name + '" target="_blank">' + data.repo.name + '</a>';
} else if (data.type == "ForkEvent") {
comit += 'forked <a href="https://github.com/' + data.repo.name + '" target="_blank">' + data.repo.name + '</a> to <a href="https://github.com/' + data.payload.forkee.full_name + '" target="_blank">' + data.payload.forkee.full_name + '</a>';
} else if (data.type == "ReleaseEvent") {
comit += 'released <a href="https://github.com/' + data.repo.name + '/release/tag/' + data.payload.release.tag_name + '" target="_blank">' + data.payload.release.tag_name + '</a> at <a href="https://github.com/' + data.repo.name + '" target="_blank">' + data.repo.name + '</a>';
} else if (data.type == "IssueCommentEvent") {
comit += 'commented on issue <a href="' + data.payload.issue.html_url + '" target="_blank">' + data.repo.name + '#' + data.payload.issue.number + '</a><br>' + data.payload.comment.body;
} else if (data.type == "IssuesEvent") {
var b = "";
if (data.payload.action == "closed") {
b += "closed issue"
} else if (data.payload.action == "opened") {
b += "opened issue"
}
comit += b + ' <a href="' + data.payload.issue.html_url + '" target="_blank">' + data.repo.name + '#' + data.payload.issue.number + '</a><br>' + data.payload.issue.title;
} else if (data.type == "PushEvent") {
var rep = "";
if (data.payload.ref.substring(0, 11) === 'refs/heads/') {
rep = data.payload.ref.substring(11);
} else {
rep = data.payload.ref;
}
comit += 'pushed to <a href="https://github.com/' + data.repo.name + '/tree/' + data.payload.ref + '" target="_blank">' + rep + '</a> at <a href="https://github.com/' + data.repo.name + '" target="_blank">' + data.repo.name + '</a>';
} else if (data.type == "CreateEvent") {
if (data.payload.ref_type == "branch") {
comit += 'created branch <a href="https://github.com/' + data.repo.name + '/tree/' + data.payload.ref + '" target="_blank">' + data.payload.ref + '</a> at <a href="https://github.com/' + data.repo.name + '" target="_blank">' + data.repo.name + '</a>';
} else if (data.payload.ref_type == "repository") {
comit += 'created repository <a href="https://github.com/' + data.repo.name + '" target="_blank">' + data.repo.name + '</a>';
} else if (data.payload.ref_type == "tag") {
comit += 'created tag <a href="https://github.com/' + data.repo.name + '/tree/' + data.payload.ref + '" target="_blank">' + data.payload.ref + '</a> at <a href="https://github.com/' + data.repo.name + '" target="_blank">' + data.repo.name + '</a>';
}
}
html += '<div class="post github">';
html += ' <div class="content">';
html += ' <div class="left">';
html += ' <i class="fa fa-github"></i>';
html += ' </div>';
html += ' <div class="right">';
html += ' <div class="top">';
html += ' <a class="user" href="https://github.com/' + id + '" target="_blank">@' + id + '</a>';
html += ' <a class="date" href="https://github.com/' + id + '" target="_blank">' + relative_time(data.created_at) + ' ago</a>';
html += ' </div>';
html += ' <div class="bottom">';
html += comit;
html += ' </div>';
html += ' </div>';
html += ' </div>';
html += '</div>';
$('#feed').append(html);
})
}
function youtube(id) {
$.ajax({
url: 'https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=' + id + '&key=AIzaSyCj2GrDSBy6ISeGg3aWUM4mn3izlA1wgt0',
crossDomain: true,
dataType: 'json'
}).done(function (a) {
var b = a.items[0].contentDetails.relatedPlaylists.uploads;
_youtube(b)
})
}
function _vk(id) {
$.ajax({
url: 'https://api.vk.com/method/users.get?name_case=nom&user_ids=' + id,
crossDomain: true,
dataType: 'jsonp'
}).done(function (data) {
$('.post.vk .user').html(data.response[0].first_name + ' ' + data.response[0].last_name);
});
}
function _youtube(b) {
$.ajax({
url: 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=1&playlistId=' + b + '&key=AIzaSyCj2GrDSBy6ISeGg3aWUM4mn3izlA1wgt0',
dataType: 'json'
}).done(function (json) {
var data = json.items[0],
html = '';
html += '<div class="post youtube">';
html += ' <div class="content">';
html += ' <div class="left">';
html += ' <i class="fa fa-youtube"></i>';
html += ' </div>';
html += ' <div class="right">';
html += ' <div class="top">';
html += ' <a class="user" href="https://twitter.com/" target="_blank">' + data.snippet.channelTitle + '</a>';
html += ' <a class="date" href="https://vk.com/wall">' + _timeSince(new Date(data.snippet.publishedAt).getTime()) + '</a>';
html += ' </div>';
html += ' <div class="bottom">';
html += data.snippet.title;
html += ' </div>';
html += ' </div>';
html += ' </div>';
html += '<iframe src="https://www.youtube.com/embed/' + data.snippet.resourceId.videoId + '" class="media"></iframe>';
html += '</div>';
$('#feed').append(html);
})
}
function relative_time(a) {
if (!a) {
return
}
a = $.trim(a);
a = a.replace(/\.\d\d\d+/, "");
a = a.replace(/-/, "/").replace(/-/, "/");
a = a.replace(/T/, " ").replace(/Z/, " UTC");
a = a.replace(/([\+\-]\d\d)\:?(\d\d)/, " $1$2");
var b = new Date(a);
var c = (arguments.length > 1) ? arguments[1] : new Date();
var d = parseInt((c.getTime() - b) / 1000);
d = (d < 2) ? 2 : d;
var r = '';
if (d < 60) {
r = 'jst now'
} else if (d < 120) {
r = 'a min'
} else if (d < (45 * 60)) {
r = (parseInt(d / 60, 10)).toString() + ' min'
} else if (d < (2 * 60 * 60)) {
r = 'an hr'
} else if (d < (24 * 60 * 60)) {
r = (parseInt(d / 3600, 10)).toString() + ' hrs'
} else if (d < (48 * 60 * 60)) {
r = 'a day'
} else {
dd = (parseInt(d / 86400, 10)).toString();
if (dd <= 30) {
r = dd + ' dys'
} else {
mm = (parseInt(dd / 30, 10)).toString();
if (mm <= 12) {
r = mm + ' mon'
} else {
r = (parseInt(mm / 12, 10)).toString() + ' yrs'
}
}
}
return r
}
function _timeSince(a) {
var s = Math.floor((new Date() - a) / 1000),
i = Math.floor(s / 31536000);
if (i > 1) {
return i + " yrs ago"
}
i = Math.floor(s / 2592000);
if (i > 1) {
return i + " mon ago"
}
i = Math.floor(s / 86400);
if (i > 1) {
return i + " dys ago"
}
i = Math.floor(s / 3600);
if (i > 1) {
return i + " hrs ago"
}
i = Math.floor(s / 60);
if (i > 1) {
return i + " min ago"
}
return Math.floor(s) + " sec ago"
}
function strip_tags(input, allowed) {
allowed = (((allowed || '') + '')
.toLowerCase()
.match(/<[a-z][a-z0-9]*>/g) || [])
.join('');
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '')
.replace(tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
}
function urltag(d, u, e) {
var f = {
link: {
regex: /((^|)(https|http|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
template: "<a href='$1' target='_BLANK'>$1</a>"
},
etdag: {
regex: /(^|\s)@(\w+)/g,
template: '$1<a href="' + u.link + '$2" target="_blank">@$2</a>'
},
hash: {
regex: /(^|)#(\w+)/g,
template: '$1<a href="' + u.tag + '$2" target="_blank">#$2</a>'
}
};
var g = $.extend(f, e);
$.each(g, function (a, b) {
d = d.replace(b.regex, b.template)
});
return d
}
<file_sep><html>
<head>
<title>Welcome to my Try Your Druck About Page</title>
<h1 style="color: skyblue"><a style="font-family: serif">
<center>About Us and What we stand for:</center>
</a></h1>
<link rel="stylesheet" href="../Try_Your_Druck/Stylesheets_For_Website/main_About.css">
</head>
<body>
<nav>
<ul>
<li class="Home.html" style="color: black"><a href="../index.html" style="color: coral">Back to my Website</a></li>
<li class="Home_Page.html" style="color: blanchedalmond"><a href="Index_T_Y_D.html">Home Page</a></li>
<li class="Event.html" style="color: darkgray"><a href="Events_T_Y_D.html">Events</a></li>
<li class="Images.html" style="color: blueviolet"><a href="Where_I_Got_Images_From_T_Y_D.html">Work Cite Page</a></li>
</ul>
</nav>
<h2 style="color: azure"><a style="font-family: monospace">About US</a></h2>
<p1>
<center>
Try Your Druck was founded by <NAME>. Built-in January 1985 in New York, Brooklyn.
</center>
</p1>
<p2>
<center>"Here at Try Your Druck We Try to have a creative enviroment where we can all come together and create something magicial"-Yoko Nui December 12,1985</center>
</p2>
<h3>
<center>Location</center>
</h3>
<p3>
<center>Brooklyn NY, 78 Bayridge, 89th Street 11209</center>
</p3>
<h4 style="color: aliceblue">
<center>Hours</center>
</h4>
<p4>
<center>10 am to 7 pm Weekdays, 11 am to 6 pm Weekends</center>
</p4>
<h5 style="color: cyan">
<center>Contact</center>
</h5>
<p5>
<center>Email: <EMAIL></center>
</p5>
<p5>
<center>Phone: 678-258-5822</center>
</p5>
<img src="T_Y_D_Pics/Animation_Place.jpg" class="center">
</body>
</html>
<file_sep><!doctype html>
<html>
<head>
<title>Welcome to Social Com's</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="Stylesheets/Social_Com's_index_main.css">
<link rel="stylesheet" href="Stylesheets/Sigin.css">
<link href="https://fonts.googleapis.com/css?family=Orbitron:700" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Concert+One" rel="stylesheet">
</head>
<body>
<header>
<h1>Hello and welcome to Social Com's</h1>
</header>
<ul>
<li><a class="active" href="https://jordan721.github.io/Jordan_Alexis/">Home</a></li>
<li><a href="Account.html">Account</a></li>
<li><a href="Feed.html">Feed Page</a></li>
<li><a href="Mod.html">Moderators Page</a></li>
<li><a href="https://xd.adobe.com/view/6e99b10d-df17-41ca-67e6-7951044d61a5-18a8/">Wireframes of Soical coms in Adobe XD</a></li>
</ul>
<div id="main">
<p>You must be asking yourself "what is Social Coms" was as the creator of the site I am here to tell you to go up to the navigation bar and click About Us.</p>
<h2>About Us</h2>
<p>Social Coms is a new and innovative Social Media website that will replace Facebook and other media Websites that give out information illegally. Social Coms was founded by <NAME> in the year 2018 when the scandal broke out with Facebook coming out they tried to sway voters. Their location is DownTown Brooklyn.</p>
<img src="Pics/Social%20Com's%20Logo.png" class="center">
</div>
<h3>Hello click button to login in</h3>
<div style="text-align: center;">
<button onclick="document.getElementById('id01').style.display='block'">Sign-In</button>
</div>
<div id="id01" class="modal">
<form class="modal-content animate" action="/action_page.php">
<div class="imgcontainer">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<img src="Pics/elena-koycheva-1054933-unsplash.jpg" alt="Avatar" class="avatar">
</div>
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="<PASSWORD>" placeholder="Enter Password" name="psw" required>
<a href="Account.html"><button type="submit">Login</button></a>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:silver">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<span class="psw">Forgot <a href="#">password?</a></span>
</div>
</form>
</div>
<script>
// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
|
906bb43426159d5f36f1d9fd98b4e682302af9bc
|
[
"JavaScript",
"HTML"
] | 3 |
JavaScript
|
Jordan721/MMP240
|
8219d717c2f342b5e151dba3e034d1ee11b84414
|
b23305ef91de4215db8b8b37a6ef02c5bc50c7bd
|
refs/heads/master
|
<repo_name>mehtabbal/shuffleCards<file_sep>/settings.gradle
include ':app'
rootProject.name='shuffleCards'
<file_sep>/app/src/main/java/com/example/shufflecards/MainActivity.java
package com.example.shufflecards;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int score;
Button shuffle;
TextView shuffleResults, remainingCardTv;
Random rand;
int cardNum;
int totalCardsLeft = 52;
String[] cardValues = {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Jack", "Queen", "King", "Ace"};
String[] cardSuits = {"Hearts", "Diamond", "Spade", "Club"};
ArrayList<String> cardsArray = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
score = 0;
//create greeting
Toast.makeText(getApplicationContext(), "Welcome to the game", Toast.LENGTH_SHORT).show();
shuffleResults = (TextView) findViewById(R.id.shuffleResults);
remainingCardTv = (TextView)findViewById(R.id.remainingCards);
remainingCardTv.setText("Remaining Cards: "+totalCardsLeft);
shuffle = (Button) findViewById(R.id.shuffle);
//rand = new Random();
//cardNum = rand.nextInt(51)+1;
populateCardsDeck();
}
public void shuffleCards(View v){
displayCard();
}
public void displayCard(){
rand = new Random();
cardNum = rand.nextInt(totalCardsLeft);
shuffleResults.setText(cardsArray.get(cardNum));
cardsArray.remove(cardNum);
totalCardsLeft--;
remainingCardTv.setText("Remaining Cards: "+totalCardsLeft);
if(totalCardsLeft==0){
totalCardsLeft=52;
remainingCardTv.setText("Remaining Cards: "+totalCardsLeft);
populateCardsDeck();
}
}
public void populateCardsDeck(){
for( int i=0; i<cardSuits.length; i++){
for(int j=0; j<cardValues.length; j++){
cardsArray.add(cardValues[j]+" of "+cardSuits[i]);
}
}
}
}
|
bf43563ae18a321d74add819975d8dcd75cd7628
|
[
"Java",
"Gradle"
] | 2 |
Gradle
|
mehtabbal/shuffleCards
|
93873fdb5adc6907542fa5b16826d4cc83e9a63a
|
cd9504e01e453b3083bd9470760a719a09060743
|
refs/heads/master
|
<repo_name>HasanSuhaimi/TwitterAPI<file_sep>/DataAccess/ReadData.py
##ur Oath1 keys, remember to update for every push, better yet do some credential handling
client_key = '<KEY>'
client_secret = '<KEY>'
import base64
key_secret = '{}:{}'.format(client_key, client_secret).encode('ascii')
b64_encoded_key = base64.b64encode(key_secret)
b64_encoded_key = b64_encoded_key.decode('ascii')
import requests
base_url = 'https://api.twitter.com/'
auth_url = '{}oauth2/token'.format(base_url)
auth_headers = {
'Authorization': 'Basic {}'.format(b64_encoded_key),
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
auth_data = {
'grant_type': 'client_credentials'
}
auth_resp = requests.post(auth_url, headers=auth_headers, data=auth_data)
# Check status code okay
print(auth_resp.status_code)
access_token = auth_resp.json()['access_token']
search_headers = {
'Authorization': 'Bearer {}'.format(access_token)
}
#the search_params specify the data request parameter
search_params = {'query': '#Metoo lang:en place_country:us',
'maxResults': '100',
'fromDate': '201703010000',
'toDate': '201803010000',
}
search_url = '{}1.1/tweets/search/fullarchive/tutorial.json'.format(base_url)
search_resp = requests.get(search_url, headers=search_headers, params=search_params)
#check search response
print(search_resp.status_code)
tweet_data = search_resp.json()
# ... tweet_data
import ast
import json
#storing the data in dataset text file
dataset = open("Dataset.txt",'w')
#pull out 100 Tweets from Wed Feb 28 23:58:46 +0000 2018 to Wed Feb 28 13:07:51 +0000 2018
for val in tweet_data['results']:
val1 = json.dumps(val)
dataset.write(val1 + '\n')
#close the text file
dataset.close()
#storing the key in keyset text file
keyset = open("Keyset.txt",'w')
#get the next parameter for the next list
keyset.write(tweet_data['next']+'\n')
#close the text file
keyset.close()
<file_sep>/README.md
# Brief
Handling request for Search Tweets: 30-day endpoint Search API,
Storage of dataset and analysation.
<file_sep>/DataAccess/AnalyzeData.py
import yaml
import datetime
import networkx as nx
import matplotlib.pyplot as plt
# storing the variables for plotting
dates_list = []
rtwt_count = []
idA_list = []
idB_list = []
num_twt = 0
num_links = 0
############################################################################################
# open dataset for reading
with open("fullOct18.txt", 'r') as dataset:
# split every string ended with '\n' into a list of a string ['*']
line_list = dataset.read().split('\n')
end = ''
for line in line_list:
if line != end:
# count the number of tweets
num_twt = num_twt + 1
# convert stringed dict into dict "*" -> {*:**}
line_dict = yaml.load(line)
# accessing the key
# print(line_dict['created_at'],)
# extract the dates for plotting value (x)
dates_list.append(line_dict['created_at'])
# extract the rtwt count for plotting value (y)
rtwt_count.append(line_dict['retweet_count'])
# check if link exist
if 'quoted_status' in line_dict:
# count the number of links
num_links = num_links + 1
idA = line_dict['quoted_status']['user']["id"]
idA_list.append(str(idA))
idB = line_dict['user']["id"]
idB_list.append(str(idB))
else:
break
# close the text file
dataset.close()
############################################################################################
# this function takes a list of String of vals and write it in text file
def writeText(list1, path):
dataset = open(path, 'w')
# pull out 100 Tweets from Wed Feb 28 23:58:46 +0000 2018 to Wed Feb 28 13:07:51 +0000 2018
for val in list1:
dataset.write('"' + val + '", ')
# close the text file
dataset.close()
############################################################################################
# this function takes a list of String of date in the format "Wed Aug 27 13:08:45 +0000 2008"
def getDate(date_list):
xlist = []
for date in date_list:
# split the whole string on whitespace (this is a list)
date_split = date.split()
# split time on ':' (this is a list)
time_split = date_split[3].split(':')
year = int(date_split[5])
# since only in October(13,14,15,16,17,18)
month = 10
day = int(date_split[2])
hour = int(time_split[0])
minute = int(time_split[1])
second = int(time_split[2])
x = datetime.datetime(year, month, day, hour, minute, second)
xlist.append(x)
return xlist
############################################################################################
# this function takes id, idList, the current element position of idList and return status string
def checkId(id, idList, linkNum):
for x in range(linkNum):
if x == 0:
print('')
if id == idList[x]:
print(id)
print(idList[x])
return 'existed'
return 'none'
############################################################################################
# plotting the Network function
def plotNetwork(listA, listB):
nodeID = 0
fullid_list = listA + listB
itter = len(fullid_list)
G = nx.DiGraph()
for x in range(itter):
print("iteration: ", x)
# create nodes
G.add_node(fullid_list[x], id = fullid_list[x])
nodeID = nodeID + 1
print(G.number_of_nodes())
idDict = nx.get_node_attributes(G, 'id')
print(idDict)
print('')
return G
############################################################################################
#set the plot Edges
def setEdges(graph,numLink,listA,listB):
for x in range(numLink):
graph.add_edge(listA[x],listB[x])
############################################################################################
G = plotNetwork(idA_list, idB_list)
setEdges(G,num_links,idA_list,idB_list)
print(G.edges())
#save the network as .gexf file and read it with Gephi tool
nx.write_gexf(G, "file.gexf", version="1.2draft")
|
b93c06fa07eed47037efb3dbb304f737694638cb
|
[
"Markdown",
"Python"
] | 3 |
Python
|
HasanSuhaimi/TwitterAPI
|
0efff7ec7ad03e1b4b5dfa74043b58076b6fb63c
|
31ff3c56da509b00ce3b65c4460ed31c481caee5
|
refs/heads/master
|
<file_sep>int VU;
void setup()
{
Serial.begin(9600); //set baud rate
//set pins attached to LEDs as outputs
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
}
void loop()
{
VU=analogRead(5); //set VU as value of pin A5 reading
//glow the LEDs depending on the ammount of sound detected by the electret
if (VU>455&&VU<555)
{//glow first LED
Clear(4);
Glow(4);
}
else if (VU>378&&VU<624)
{//glow 2nd LED
Clear(5);
Glow(5);
}
else if (VU>311&&VU<693)
{//glow 3rd LED
Clear(6);
Glow(6);
}
else if (VU>244&&VU<762)
{//glow 4th LED
Clear(7);
Glow(7);
}
else if (VU>177&&VU<831)
{//glow 5th LED
Clear(8);
Glow(8);
}
else if (VU<177||VU>831)
{//glow 6th LED
Clear(9);
Glow(9);
}
}
void Glow(int initial)//function to glow LEDs
{
for(int i=3;i<initial;i++)digitalWrite(i,HIGH);
}
void Clear(int initial)//function to clear LEDs
{
for(int i=initial;i<9;i++)digitalWrite(i,LOW);
}
<file_sep>/*
PIN SEQUENCE
HC05 VCC - 5V
HC05 GND - GND
HC05 TX - PIN 0
PIN 1 - 1.5K - 3.3K - GND
HC05 RX - Voltage Divider
LM293D
2 - PIN 8
7 - PIN 9
10 - PIN 10
11 - PIN 15
*/
// TRANSMISSION
/*
int counter =0;
void setup() {
Serial.begin(9600);
delay(50);
}
void loop() {
counter++;
Serial.print("Arduino counter: ");
Serial.println(counter);
delay(500); // wait half a sec
}
*/
char input,init,spd;
int LED = 13; // LED on pin 13
int ip1 = 8;
int ip2 = 9;
int ip3 = 10;
int ip4 = 11;
int sp= -1;
void setup() {
Serial.begin(9600);
Serial.println("Awesomeness Bot v2 ....... ....... :D");
pinMode(LED, OUTPUT);
pinMode(ip1, OUTPUT);
pinMode(ip2, OUTPUT);
pinMode(ip3, OUTPUT);
pinMode(ip4, OUTPUT);
}
void botstop()
{
digitalWrite(LED, LOW);
digitalWrite(ip1, HIGH);
digitalWrite(ip2, HIGH);
digitalWrite(ip3, HIGH);
digitalWrite(ip4, HIGH);
}
void forward()
{
digitalWrite(LED, HIGH);
digitalWrite(ip1, LOW);
digitalWrite(ip2, HIGH);
digitalWrite(ip3, HIGH);
digitalWrite(ip4, LOW);
}
void reverse()
{
digitalWrite(LED, HIGH);
digitalWrite(ip1, HIGH);
digitalWrite(ip2, LOW);
digitalWrite(ip3, LOW);
digitalWrite(ip4, HIGH);
}
void left()
{
digitalWrite(LED, HIGH);
digitalWrite(ip1, HIGH);
digitalWrite(ip2, LOW);
digitalWrite(ip3, HIGH);
digitalWrite(ip4, LOW);
}
void right()
{
digitalWrite(LED, HIGH);
digitalWrite(ip1, LOW);
digitalWrite(ip2, HIGH);
digitalWrite(ip3, LOW);
digitalWrite(ip4, HIGH);
}
void speedset(char spd)
{
sp = (int)spd;
}
void loop() {
Serial.println("Bot Begin!");
while (!Serial.available()); // stay here so long as COM port is empty
if(sp == -1)
{
Serial.println("Awesomeness Bot Interface.");
Serial.println("Do you want to set speed ? y/n");
init = Serial.read();
if (init == 'y')
{
Serial.println("Set the value of Speed. 10-100");
spd = Serial.read();
speedset(spd);
}
else
{
Serial.println("Setting Default Full Speed....");
sp = 100;
}
}
else
{
Serial.println("Press 'w' to move forward.\n 'a' to move left. \n 'd' to move right.\n 's' to move reverse.\n '0' to stop. \n 'b' back to menu.");
input = Serial.read();
if( input == '0' )
{
botstop();
}
if( input == 'w' ) //Forward
{
forward();
}
if( input == 'a' ) //LEFT
{
left();
delay(400);
input = 1;
}
if( input == 'd' ) //RIGHT
{
right();
delay(400);
input = 1;
}
if( input == 's' ) //Reverse
{
reverse();
}
if( input == 'b' ) //Back to menu
{
sp = -1;
}
}
delay(50);
}
<file_sep>char directions[30];
#include<LiquidCrystal.h> //header for lcd
LiquidCrystal lcd(12,11,5,4,3,2);
int rm1=24; //naming motor pins
int rm2=25;
int lm1=0;
int lm2=1;
int l,c1,c2,c3,r; //sensor pins4
int i=0;
int tdelay=750; // turn delay
int fdelay=500; //forward delay
void Stop() //stop function
{
digitalWrite(lm1,0);
digitalWrite(lm2,0);
digitalWrite(rm1,0);
digitalWrite(rm2,0);
}
void forward() //forward function
{
digitalWrite(lm1,1);
digitalWrite(lm2,0);
digitalWrite(rm1,1);
digitalWrite(rm2,0);
}
void smallright() //right for lfr
{
digitalWrite(lm1,1);
digitalWrite(lm2,0);
digitalWrite(rm1,0);
digitalWrite(rm2,0);
}
void smallleft() //left for lfr
{
digitalWrite(lm1,0);
digitalWrite(lm2,0);
digitalWrite(rm1,1);
digitalWrite(rm2,0);
}
void right() //differential run
{
digitalWrite(lm1,1);
digitalWrite(lm2,0);
digitalWrite(rm1,0);
digitalWrite(rm2,1);
}
void left() //differential left
{
digitalWrite(lm1,0);
digitalWrite(lm2,1);
digitalWrite(rm1,1);
digitalWrite(rm2,0);
}
int eosens()
{
readsens();
if(((c1+c2+c3)==1)||((c1+c2+c3)==2))
return 1;
else
return 0;
}
void readsens() // read sensor values
{
l=digitalRead(26);
c1=digitalRead(27);
c2=digitalRead(28);
c3=digitalRead(29);
r=digitalRead(30);
lcd.print(l);
lcd.print("--");
lcd.print(c1);
lcd.print("--");
lcd.print(c2);
lcd.print("--");
lcd.print(c3);
lcd.print("--");
lcd.print(r);
lcd.print("--");
}
void inch() //perform inch function
{
lcd.print("Inch Function");
Stop(); //stop
delay(100);
forward(); //fwd
delay(500);
readsens(); //read sensor values
delay(100);
lcd.clear();
}
void align() //align function
{
Stop(); //stop
delay(500);
forward(); //fwd
delay(85);
lcd.clear();
readsens(); //read sensor values
}
void printing(char prtdirection[]) // func to print values on lcd
{
lcd.clear();
for(i=0;prtdirection[i]!='E';i++)
{
lcd.print(prtdirection[i]);
}
delay(2000);
}
void setup()
{
lcd.begin(16,2); //initialise lcd
lcd.print("Awesome");
delay(500);
lcd.clear(); //clear lcd
pinMode(lm1,OUTPUT); //declare output pins
pinMode(lm2,OUTPUT);
pinMode(rm1,OUTPUT);
pinMode(rm2,OUTPUT);
pinMode(26,INPUT); //declare input pins
pinMode(27,INPUT);
pinMode(28,INPUT);
pinMode(29,INPUT);
pinMode(30,INPUT);
}
void loop()
{
lcd.clear(); //clear lcd
readsens(); //read sensor values
lcd.clear(); //clear lcd
//-------------------line follower-----//
//fwd
if((l==1)&&(c1==1)&&(c2==0)&&(c3==1)&&(r==1))
{
lcd.print("Forward");
forward(); //forward
}
//left
else if(((l==1)&&(c1==0)&&(c2==0)&&(c3==1)&&(r==1)) || ((l==1)&&(c1==0)&&(c2==1)&&(c3==1)&&(r==1)))
{
lcd.print("left");
smallleft(); //small left
}
//right
else if(((l==1)&&(c1==1)&&(c2==0)&&(c3==0)&&(r==1))||((l==1)&&(c1==1)&&(c2==1)&&(c3==0)&&(r==1)))
{
lcd.print("Right");
smallright(); //smallright
}
//--------------dead end-------------
else if((l==1)&&(c1==1)&&(c2==1)&&(c3==1)&&(r==1))
{
lcd.print("U turn");
right(); //U turn
delay(850); //delay for u trun
directions[i]='U'; //store 'U' in the arraay
i++; //increment the position
}
//--------------Maze cases-----------
else if(((l==0)&&(c1==0))||((c3==0)&&(r==0)))
{
align(); //align
//----------right only and strt and right
if(((l==1)&&(c1==0)&&(c2==0)&&(c3==0)&&(r==0))||((l==1)&&(c1==1)&&(c2==0)&&(c3==0)&&(r==0)))
{
lcd.print("RT/Strt n rt?");
inch();
if((l==1)&&(c1==1)&&(c2==1)&&(c3==1)&&(r==1))
{
lcd.print("right");
right(); //turn right
delay(tdelay); //turn delay
}
else if((l==1)&&(r==1)&&(eosens()))
{
lcd.print("straight");
directions[i]='S'; //store 'S' in array
i++; //increment to the next position
forward(); //fwd
delay(fdelay); //fwd delay
}
}
//---------left and strt left
else if(((l==0)&&(c1==0)&&(c2==0)&&(c3==0)&&(r==1)) ||((l==0)&&(c1==0)&&(c2==0)&&(c3==1)&&(r==1)))
{
lcd.print("lft/strt n left");
inch(); //inch
if((l==1)&&(c1==1)&&(c2==1)&&(c3==1)&&(r==1))
{
lcd.print("Left");
left(); //left
delay(tdelay); //turn delay
}
else if((l==1)&&(r==1)&&(eosens()))
{
lcd.print("left");
directions[i]='L'; //store 'L' in array
i++; //increment to the next position
left();
delay(tdelay);
}
}
//----------4 way /t intersection/ finish
else if((l==0)&&(c1==0)&&(c2==0)&&(c3==0)&&(r==0))
{
lcd.print("T/END/4");
inch(); //inch
if((l==1)&&(r==1)&&(eosens()))
{
lcd.print("4 Way");
directions[i]='L'; //store 'L' into the array
i++; //increment
left(); ///left
delay(tdelay); //turn delay
}
else if((l==1)&&(c1==1)&&(c2==1)&&(c3==1)&&(r==1))
{
lcd.print("T-int");
directions[i]='L'; //store 'L' in to the aray
i++; //increment
left(); // left
delay(tdelay); //turn delay
}
else if((l==0)&&(c1==0)&&(c2==0)&&(c3==0)&&(r==0))
{
lcd.print("End of maze");
directions[i]='E'; //store 'E' in to the array
printing(directions); //printing the final path
while (1)
{
Stop();
}
}
}
}
}
<file_sep>/*
Pin 4 ,Pin 5,Pin 12 and Pin 13 from L293D Chip Connect to Ground (Negative On Breadboard)
Pin 1,Pin 9 and Pin 16 from L293D Chip Connect to 5 Volts (Positive On Breadboard)
Pin 8 from L293D Chip Connects to 6 Volts (Positive On Breadboard)
Pin 3 from L293D Chip Connects to Right Motor positive
Pin 6 from L293D Chip Connects to Right Motor negative
Pin 11 from L293D Chip Connects to Left Motor Positive
Pin 14 from L293D Chip Connects to Left Motor Negative
Output pins on Arduino to control Right Motor :
Pin 2 from L293D Chip Connects to Output Pin on Arduino 13
Pin 7 from L293D Chip Connects to Output Pin on Arduino 12
Output pins on Arduino to control Left Motor :
Pin 10 from L293D Chip Connects to Output Pin on Arduino 10
Pin 15 from L293D Chip Connects to Output Pin on Arduino11
*/
int LeftMotorForward = 11; // Pin 10 has Left Motor connected on Arduino boards.
int LeftMotorReverse = 10; // Pin 9 has Left Motor connected on Arduino boards.
int RightMotorForward = 13; // Pin 12 has Right Motor connected on Arduino boards.
int RightMotorReverse = 12; // Pin 13 has Right Motor connected on Arduino boards.
void setup()
{
pinMode(LeftMotorForward, OUTPUT); // initialize the pin as an output.
pinMode(RightMotorForward, OUTPUT); // initialize the pin as an output.
pinMode(LeftMotorReverse, OUTPUT); // initialize the pin as an output.
pinMode(RightMotorReverse, OUTPUT); // initialize the pin as an output.
}
// The following Loop is to make the Robot go staright
void loop()
{
digitalWrite(RightMotorForward, HIGH); // turn the Right Motor ON
digitalWrite(LeftMotorForward, HIGH); // turn the Left Motor ON
delay(5000); // wait for 10 seconds
digitalWrite(RightMotorForward,LOW); // turn the Right Motor OFF
digitalWrite(LeftMotorForward, LOW); // turn the Left Motor OFF
delay(1000); // wait for 10 seconds
}
<file_sep>int maximum=0; //declare and initialize maximum as zero
int minimum=1023; //declare and initialize minimum as 1023
int track=0; //variable to keep track
void setup()
{
Serial.begin(9600); //set baud rate
}
void loop()
{
//record the highest value recieved on A5
if (analogRead(5)>maximum) maximum=analogRead(A5);
//record the lowest value recieved on A5
if (analogRead(5)<minimum) minimum=analogRead(A5);
track++;//increase track by 1 after every iteration
//display both the maximum and minimum value after 5 second
//track is used to determine the time interval it takes for
//the program to display the maximum and minimum values
//e.g. here i use 1000 so as to display the min and max values
//after every 5 second
if (track==5000)
{
Serial.print("Maximum:\t");
Serial.println(maximum);
Serial.print("Minimum:\t");
Serial.println(minimum);
track=0; //set back track to zero
}
}
<file_sep>int rm1=24; //naming motor pins
int rm2=25;
int lm1=0;
int lm2=1;
int r1[10];
int o[10];
int x;
int l,c1,c2,c3,r; //sensor pins4
int i=0;
int j=0;
int tdelay=750; // turn delay
int fdelay=500; //forward delay
void Stop() //stop function
{
digitalWrite(lm1,0);
digitalWrite(lm2,0);
digitalWrite(rm1,0);
digitalWrite(rm2,0);
digitalWrite(4,HIGH);
}
void forward() //forward function
{
digitalWrite(lm1,1);
digitalWrite(lm2,0);
digitalWrite(rm1,1);
digitalWrite(rm2,0);
}
void smallright() //right for lfr
{
digitalWrite(lm1,1);
digitalWrite(lm2,0);
digitalWrite(rm1,0);
digitalWrite(rm2,0);
}
void smallleft() //left for lfr
{
digitalWrite(lm1,0);
digitalWrite(lm2,0);
digitalWrite(rm1,1);
digitalWrite(rm2,0);
}
void right() //differential run
{
digitalWrite(lm1,1);
digitalWrite(lm2,0);
digitalWrite(rm1,0);
digitalWrite(rm2,1);
}
void left() //differential left
{
digitalWrite(lm1,0);
digitalWrite(lm2,1);
digitalWrite(rm1,1);
digitalWrite(rm2,0);
}
int eosens()
{
readsens();
if(((c1+c2+c3)==1)||((c1+c2+c3)==2))
return 1;
else
return 0;
}
void readsens() // read sensor values
{
l=digitalRead(26);
c1=digitalRead(27);
c2=digitalRead(28);
c3=digitalRead(29);
r=digitalRead(30);
x=digitalRead(31); //obstacle sensor pin
}
void inch() //perform inch function
{
Stop(); //stop
delay(100);
forward(); //fwd
delay(500);
readsens(); //read sensor values
delay(100);
}
void align() //align function
{
Stop(); //stop
delay(500);
forward(); //fwd
delay(85);
readsens(); //read sensor values
}
void setup()
{
pinMode(lm1,OUTPUT);
pinMode(lm2,OUTPUT);
pinMode(rm1,OUTPUT);
pinMode(rm2,OUTPUT);
pinMode(3,OUTPUT);//Red Led
pinMode(4,OUTPUT);//Green Led
pinMode(26,INPUT); //declare input pins
pinMode(27,INPUT);
pinMode(28,INPUT);
pinMode(29,INPUT);
pinMode(30,INPUT);
pinMode(31,INPUT);
}
void loop()
{ //clear lcd
readsens(); //read sensor values
//clear lcd
//-------------------line follower-----//
//fwd
while(x!=1) // when no obstacle is present
{
if((l==1)&&(c1==1)&&(c2==0)&&(c3==1)&&(r==1))
{
digitalWrite(3,LOW);
forward(); //forward
}
//left
else if(((l==1)&&(c1==0)&&(c2==0)&&(c3==1)&&(r==1)) || ((l==1)&&(c1==0)&&(c2==1)&&(c3==1)&&(r==1)))
{
digitalWrite(3,LOW);
smallleft(); //small left
}
//right
else if(((l==1)&&(c1==1)&&(c2==0)&&(c3==0)&&(r==1))||((l==1)&&(c1==1)&&(c2==1)&&(c3==0)&&(r==1)))
{
digitalWrite(3,LOW);
smallright(); //smallright
}
//right
else if(((l==1)&&(c1==1)&&(c2==0)&&(c3==0)&&(r==0))||((l==1)&&(c1==1)&&(c2==0)&&(c3==1)&&(r==0)))
{
right();
r1[i++];
digitalWrite(3,HIGH); //right
}
else if(((l==0)&&(c1==0)&&(c2==0)&&(c3==1)&&(r==1))||((l==0)&&(c1==1)&&(c2==0)&&(c3==1)&&(r==1)))
{
left();
digitalWrite(3,LOW); //left
}
//--------------dead end-------------
else if((l==1)&&(c1==1)&&(c2==1)&&(c3==1)&&(r==1))
{
digitalWrite(3,LOW);
right(); //U turn
delay(850); //delay for u trun
// directions[i]='U'; //store 'U' in the arraay
//inward circular strip //increment the position
}
}
Stop();
o[j++];
//no of obstacles counter is incremented
}
<file_sep>#define trigPin1 13
#define echoPin1 12
#define trigPin2 9
#define echoPin2 8
#define ledr 11
#define ledg 10
void setup() {
Serial.begin (9600);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(ledg, OUTPUT);
pinMode(ledr, OUTPUT);
}
void loop() {
long duration1, distance1, duration2, distance2;
// digitalWrite(trigPin1, LOW); // Added this line
digitalWrite(trigPin2, LOW); // Added this line
// delayMicroseconds(2); // Added this line
delayMicroseconds(2); // Added this line
// digitalWrite(trigPin1, HIGH);
digitalWrite(trigPin2, HIGH);
// delayMicroseconds(10); // Added this line
delayMicroseconds(10); // Added this line
//digitalWrite(trigPin1, LOW);
digitalWrite(trigPin2, LOW);
// duration1 = pulseIn(echoPin1, HIGH);
duration2 = pulseIn(echoPin2, HIGH);
// distance1 = (duration1/2) / 29.1;
distance2 = (duration2/2) / 29.1;
if (distance2 > 4) {// if (distance1 < distance2) { // This is where the LED On/Off happens
digitalWrite(ledg,HIGH); // When the Red condition is met, the Green LED should turn off
digitalWrite(ledr,LOW);
}
else {
digitalWrite(ledg,LOW);
digitalWrite(ledr,HIGH);
}
if (distance2 >= 200 || distance2 <= 0){
Serial.println("Out of range");
}
else {
Serial.println(" Distance2 = ");
Serial.print(distance2);
Serial.println(" cm");
}
delay(500);
}
<file_sep>#include "SIM900.h"
#include <SoftwareSerial.h>
//If not used, is better to exclude the HTTP library,
//for RAM saving.
//If your sketch reboots itself proprably you have finished,
//your memory available.
//#include "inetGSM.h"
//If you want to use the Arduino functions to manage SMS, uncomment the lines below.
#include "sms.h"
SMSGSM sms;
//To change pins for Software Serial, use the two lines in GSM.cpp.
//GSM Shield for Arduino
//www.open-electronics.org
//this code is based on the example of Arduino Labs.
//Simple sketch to send and receive SMS.
int numdata;
boolean started=false;
char smsbuffer[160];
char n[20];
int count = 1;
void setup()
{
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
//Serial connection.
Serial.begin(9600);
//Start configuration of shield with baudrate.
//For http uses is raccomanded to use 4800 or slower.
if (gsm.begin(2400)){
Serial.println("\nstatus=READY");
started=true;
}
else Serial.println("\nstatus=IDLE");
};
void loop()
{
char INBYTE = Serial.read();
if( INBYTE == 's' )
{
if(count > 0)
{
if(started){
//Enable this two lines if you want to send an SMS.
if (sms.SendSMS("+xxxxxx", "Arduino SMS"))
Serial.println("\nSMS sent OK");
count--;
}
}
}
if( INBYTE == 'l' ) //LEFT LED
{ digitalWrite(13, HIGH);
digitalWrite(12, LOW);
digitalWrite(11, LOW);
}
if( INBYTE == 'c' ) //CENTER LED
{ digitalWrite(13, LOW);
digitalWrite(12, HIGH);
digitalWrite(11, LOW);
}
if( INBYTE == 'r' ) //RIGHT LED
{ digitalWrite(13, LOW);
digitalWrite(12, LOW);
digitalWrite(11, HIGH);
}
};
<file_sep>#define trigPin1 13
#define echoPin1 12
#define trigPin2 9
#define echoPin2 8
#define ledr 11
#define ledg 10
void setup() {
Serial.begin (9600);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(ledg, OUTPUT);
pinMode(ledr, OUTPUT);
}
void loop() {
long distance1,distance2;
// distance1=us1();
distance2=us2();
if (distance2 < 4) { // This is where the LED On/Off happens
digitalWrite(ledr,HIGH); // When the Red condition is met, the Green LED should turn off
digitalWrite(ledg,LOW);
}
else {
digitalWrite(ledr,LOW);
digitalWrite(ledg,HIGH);
}
delay(500);
}
long us1()
{
long duration, distance;
digitalWrite(trigPin1, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin1, HIGH);
// delayMicroseconds(1000); - Removed this line
delayMicroseconds(10); // Added this line
digitalWrite(trigPin1, LOW);
duration = pulseIn(echoPin1, HIGH);
if (distance >= 200 || distance <= 0){
Serial.println("D1 Out of range");
}
else {
Serial.println(" Distance 1 = ");
Serial.print(distance);
Serial.println(" cm;");
}
return distance;
}
long us2()
{
long duration, distance;
digitalWrite(trigPin2, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin2, HIGH);
// delayMicroseconds(1000); - Removed this line
delayMicroseconds(10); // Added this line
digitalWrite(trigPin2, LOW);
duration = pulseIn(echoPin2, HIGH);
if (distance >= 200 || distance <= 0){
Serial.println("D2 Out of range");
}
else {
Serial.println(" Distance 2 = ");
Serial.print(distance);
Serial.println(" cm;");
}
if (distance < 4) { // This is where the LED On/Off happens
digitalWrite(ledr,HIGH); // When the Red condition is met, the Green LED should turn off
digitalWrite(ledg,LOW);
}
else {
digitalWrite(ledr,LOW);
digitalWrite(ledg,HIGH);
}
return distance;
}
<file_sep>
char INBYTE;
void setup() {
Serial.begin(9600);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
}
void loop() {
INBYTE = Serial.read(); // read next available byte
if( INBYTE == 'l' ) //LEFT LED
{ digitalWrite(3, HIGH);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
}
if( INBYTE == 'c' ) //CENTER LED
{ digitalWrite(3, LOW);
digitalWrite(4, HIGH);
digitalWrite(5, LOW);
}
if( INBYTE == 'r' ) //RIGHT LED
{ digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, HIGH);
}
if( INBYTE == 'o' ) //OFF
{ digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
}
if( INBYTE == 'n' ) //ON
{ digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
}
}
<file_sep>
char INBYTE;
void setup() {
Serial.begin(9600);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
}
void loop() {
INBYTE = Serial.read(); // read next available byte
if( INBYTE == '0' )
{ digitalWrite(3, LOW);
digitalWrite(4, HIGH);
}
if( INBYTE == '1' ) //Forward
{ digitalWrite(3, HIGH);
digitalWrite(4, LOW);
}
delay(50);
}
<file_sep>/*
PIN SEQUENCE
HC05 VCC - 5V
HC05 GND - GND
HC05 TX - PIN 0
PIN 1 - 1.5K - 3.3K - GND
HC05 RX - Voltage Divider
LM293D
2 - PIN 8
7 - PIN 9
10 - PIN 10
15 - PIN 11
*/
// TRANSMISSION
/*
int counter =0;
void setup() {
Serial.begin(9600);
delay(50);
}
void loop() {
counter++;
Serial.print("Arduino counter: ");
Serial.println(counter);
delay(500); // wait half a sec
}
*/
char input;
int LED = 13; // LED on pin 13
int ip1 = 8;
int ip2 = 9;
int ip3 = 10;
int ip4 = 11;
void setup() {
Serial.begin(9600);
Serial.println("Awesomeness Bot v2 ....... ....... :D");
pinMode(LED, OUTPUT);
pinMode(ip1, OUTPUT);
pinMode(ip2, OUTPUT);
pinMode(ip3, OUTPUT);
pinMode(ip4, OUTPUT);
}
void botstop()
{
digitalWrite(LED, LOW);
digitalWrite(ip1, HIGH);
digitalWrite(ip2, HIGH);
digitalWrite(ip3, HIGH);
digitalWrite(ip4, HIGH);
}
void forward()
{
digitalWrite(LED, HIGH);
digitalWrite(ip1, LOW);
digitalWrite(ip2, HIGH);
digitalWrite(ip3, HIGH);
digitalWrite(ip4, LOW);
}
void reverse()
{
digitalWrite(LED, HIGH);
digitalWrite(ip1, HIGH);
digitalWrite(ip2, LOW);
digitalWrite(ip3, LOW);
digitalWrite(ip4, HIGH);
}
void left()
{
digitalWrite(LED, HIGH);
digitalWrite(ip1, HIGH);
digitalWrite(ip2, LOW);
digitalWrite(ip3, HIGH);
digitalWrite(ip4, LOW);
}
void right()
{
digitalWrite(LED, HIGH);
digitalWrite(ip1, LOW);
digitalWrite(ip2, HIGH);
digitalWrite(ip3, LOW);
digitalWrite(ip4, HIGH);
}
void loop() {
while(!Serial.available());
input = Serial.read();
if( input == '0' )
{
botstop();
}
if( input == 'w' ) //Forward
{
forward();
delay(5);
botstop();
delay(5);
}
if( input == 'a' ) //LEFT
{
left();
delay(5);
botstop();
delay(5);
}
if( input == 'd' ) //RIGHT
{
right();
delay(5);
botstop();
delay(5);
}
if( input == 's' ) //Reverse
{
reverse();
delay(5);
botstop();
delay(5);
}
delay(50);
}
|
1c07024f522d024e1a78506200741c0d6c9ab7e6
|
[
"C++"
] | 12 |
C++
|
Xnkr/ic-enigma
|
d0c054ab48db4bc9e18d0e7574d8743814ecdfb2
|
59272dc688f040083e51708407aaf8d54c4da2bf
|
refs/heads/master
|
<file_sep>docker run -p 8080:8080 -p 50000:50000 -v jenkins_home:/var/jenkins_home $1
|
cff959f69e476a2c4bc4fb25a9f9dad04b59d6a2
|
[
"Shell"
] | 1 |
Shell
|
twa16/jenkins-docker
|
770fdf7a1d5185a4e3921b2cd5a4b92610cafac3
|
e4142b4460db7e42f875a33f29a4184738557fb9
|
refs/heads/master
|
<file_sep>package com.example.weatherapp;
import com.google.gson.annotations.SerializedName;
public class Temp {
@SerializedName("temp")
float temp;
@SerializedName("temp_min")
float temp_min;
@SerializedName("temp_max")
float temp_max;
public float getTemp() {
return temp;
}
public void setTemp(float temp) {
this.temp = temp;
}
public float getTemp_min() {
return temp_min;
}
public void setTemp_min(float temp_min) {
this.temp_min = temp_min;
}
public float getTemp_max() {
return temp_max;
}
public void setTemp_max(float temp_max) {
this.temp_max = temp_max;
}
}
<file_sep># WeatherApp
An android application which gives you the informtion of weather of all the cities around the world.
It is a simple API based application.
<file_sep>package com.example.weatherapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
EditText cityname;
TextView mintemp,maxtemp,temp,weather;
Button go;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityname=findViewById(R.id.cityname);
maxtemp=findViewById(R.id.maxtemparauter);
mintemp=findViewById(R.id.mintemperature);
weather=findViewById(R.id.weathercast);
temp=findViewById(R.id.temperature);
go=findViewById(R.id.go);
go.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("clicked","true"+" "+cityname.getText().toString());
Call<Stream> call=APIClient.getInstance().getApi().getWeather(cityname.getText().toString(),"6eef6e4d32741b61f84430ba292b8fc3");
call.enqueue(new Callback<Stream>() {
@Override
public void onResponse(Call<Stream> call, Response<Stream> response) {
Log.i("success",response.isSuccessful()+" "+response.raw().toString());
if(response.isSuccessful()&&response.body()!=null){
maxtemp.setText((int)(response.body().getTemp().getTemp_max()-273)+" C");
mintemp.setText((int)(response.body().getTemp().getTemp_min()-273)+" C");
temp.setText((int)(response.body().getTemp().getTemp()-273)+" C");
weather.setText(response.body().getWeaher().get(0).getMain());
}else{
Toast.makeText(getApplicationContext(),"Please enter a valid city",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<Stream> call, Throwable t) {
Log.i("fail",t.toString());
}
});
}
});
}
}
|
a2e057248912149f802bbb7cda9635d28e7c2cb4
|
[
"Markdown",
"Java"
] | 3 |
Java
|
prince-09/WeatherApp
|
d1dc99d4bcb9047447937da146423352de8f21e2
|
7edd5f971f30c63418542c155259d2621688b94e
|
refs/heads/master
|
<file_sep><?php
/**
* Формируем форму настроек модуля
* @param $form
* @param $form_state
* @return array
*/
function install_modules_config_form($form, &$form_state)
{
$form = array();
$form['description'] = array(
'#type' => 'markup',
'#markup' => '<h3 class="description">'.t('Пожалуйста укажите кол-во шагов для загрузки модулей').'</h3>',
);
$form['batch_step'] = array(
'#type' => 'textfield',
'#default_value' => 1,
'#size' => 3,
'#suffix' => '<h6 class="description_step">'.t('По умолчанию кол-во 1, в одном шаге загружается 20 описаний, модуля').'</h6>',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Загрузить модули'),
'#submit' => array('install_modules_config_form_submit'),
);
return $form;
}
/**
* описываем событие по кнопке на форме настроек модуля
* @param $form
* @param $form_state
*/
function install_modules_config_form_submit($form, &$form_state)
{
$operations = array();
for ($i = 0; $i < $form_state['input']['batch_step']; $i++) {
$operations[] = array(
'install_modules_batch_importing', array($i));
}
$batch = array(
'operations' => $operations,
'finished' => 'install_modules_batch_finished',
'title' => t('Получение описаний модулей'),
'file' => drupal_get_path('module', 'install_modules') . '/install_modules.admin.inc',
);
batch_set($batch);
}
function install_modules_batch_importing($step,&$context)
{
$new_json = array();
$json = drupal_http_request('https://www.drupal.org/api-d7/node.json?type=project_module&sort=field_download_count&direction=DESC&field_project_type=full&limit=20&page='.$step);
$modules_array = drupal_json_decode($json->data);
foreach ($modules_array['list'] as $key_one => $modules) {
$new_json_two = array();
foreach ($modules as $key => $module) {
if ($key == 'field_download_count' or $key == 'title' or $key == 'url' or $key == 'nid' or $key == 'field_project_machine_name') {
$new_json_two[$key] = $module;
}
if ($key == 'field_project_images' and count($module) > 0) {
$json_img = drupal_http_request('https://www.drupal.org/api-d7/file/' . $module['0']['file']['id'] . '.json');
$img_url = drupal_json_decode($json_img->data);
$new_json_two[$key] = $img_url['url'];
}
}
array_push($new_json, $new_json_two);
}
$context['results']['new_json'][] = $new_json;
}
function install_modules_batch_finished($success, $results, $operations)
{
if ($success) {
$new_json = drupal_json_encode($results['new_json']);
file_put_contents(__DIR__ . '/modules_array.json', $new_json);
drupal_set_message(t('Описание модулей успешно загружены'));
} else {
drupal_set_message(t('An error occurred while processing @operation with arguments'));
}
}
|
b69793effc65687150eadabc6130cf91a3bdc237
|
[
"PHP"
] | 1 |
PHP
|
batkor/install_modules
|
3c2327500c61f78f31366d0d12b17db9145f6dd3
|
9ec9536e28bd298f1d7e1812ca2da8da339e437a
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Lab21.Views.Home
{
public class UserInfo
{
[Required]
public string First { get; set; }
[Required]
public string Last { get; set; }
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
[RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$
", ErrorMessage = "Bad Email!")]
public string Email { get; set; }
public string Address { get; set; }
public string State { get; set; }
public DateTime Bday { get; set; }
public string Male { get; set; }
public string Female { get; set; }
public string Other { get; set; }
public UserInfo()
{
}
public UserInfo(string first, string last, string username, string password,
string email, string address, string state, DateTime bday, string male, string female, string other)
{
First = first;
Last = last;
Username = username;
Password = <PASSWORD>;
Email = email;
Address = address;
State = state;
Bday = bday;
Male = male;
Female = female;
Other = other;
}
}
}
|
3d74247559d16d09468cd39885c1f84474fde230
|
[
"C#"
] | 1 |
C#
|
ThisDudeAbides/Lab21
|
5d7e5b073dc88f29e899091969636b4d9f939933
|
6bc041bb209fbcc1c32baeeb19ce8b64f09ed518
|
refs/heads/main
|
<repo_name>itata222/Todo_Front<file_sep>/src/components/Home.js
import React, { useContext, useEffect, useState } from 'react';
import { addTaskAction, setTasksAction } from '../actions/tasksActions';
import { TasksContext } from '../contexts/tasksContext';
import { addTaskToDB, getAllTasksTFromDB } from '../services/taskService';
import Button from './Button';
import Modal from './Modal';
import Spinner from './Spinner';
import Task from './Task';
const Home = () => {
const [taskContent, setTaskContent] = useState('');
const [showModal, setShowModal] = useState(false);
const [showSpinner, setShowSpinner] = useState(false);
const {tasksData,dispatchTasksData}=useContext(TasksContext)
const [showErrorMessage, setShowErrorMessage] = useState(false)
useEffect(() => {
setShowSpinner(true)
getAllTasksTFromDB().then((res)=>{
setShowSpinner(false)
dispatchTasksData(setTasksAction(res))
})
}, [dispatchTasksData])
const submitTask=(e)=>{
e.preventDefault();
if(taskContent.length>0){
setShowSpinner(true);
setTaskContent('')
addTaskToDB({task:taskContent,complete:false}).then((res)=>{
dispatchTasksData(addTaskAction(res))
setShowSpinner(false)
setShowModal(true);
}).catch(e=>alert(e))
}
else{
setShowErrorMessage(true)
}
}
return (
<div className="home">
{showSpinner&&<Spinner />}
{showModal&&<Modal text="Task Added" setShowModal={setShowModal}/>}
<h2>TODO List</h2>
<div>Current Tasks : {tasksData.length}</div>
<div className="todoContainer">
{
tasksData.length>0?
tasksData.map((task,i)=>(
<Task key={`${task}${i}`} task={task}/>
)):
<div>Your list is empty</div>
}
</div>
<form className="todoForm" onSubmit={submitTask}>
<input
type="text"
placeholder="Write your task..."
value={taskContent}
onChange={(e)=>{
if(e.target.value.length>0)
setShowErrorMessage(false)
setTaskContent(e.target.value)
}}
/>
{showErrorMessage&&<div className="errorMessage">Task cant be empty</div>}
<Button
className="addTaskButton"
content={'Add Task'}
backgroundColor={'#1ebcf5'}
color={'#FFFFFF'}/>
</form>
</div>
)
}
export default Home
<file_sep>/src/components/Task.js
import React , { useContext, useState }from 'react'
import {TasksContext} from '../contexts/tasksContext'
import { deleteTaskAction, toggleTaskAction } from '../actions/tasksActions';
import { deleteTaskFromDB ,toggleTaskInDB} from '../services/taskService';
import Modal from './Modal';
const Task = ({task}) => {
const {dispatchTasksData}=useContext(TasksContext)
const [showModal, setShowModal] = useState(false);
const deleteTask=(e)=>{
e.preventDefault();
dispatchTasksData(deleteTaskAction(task._id))
deleteTaskFromDB(task).then((res)=>{
setShowModal(true)
}).catch((e)=>console.log(e))
}
const taskClicked=(e)=>{
toggleTaskInDB(task).then((res)=>{
dispatchTasksData(toggleTaskAction(res))
}).catch((e)=>console.log(e))
}
return (
<div className="task">
{showModal&&<Modal text="Task Removed" setShowModal={setShowModal}/>}
<div className={task.complete===true?"contentDone":"content"}>
{task.task}
</div>
<input
type="checkbox"
className="checkBox"
onChange={taskClicked}
checked={task.complete}
>
</input>
<button
className="submitButton"
onClick={deleteTask}
>
Delete
</button>
</div>
)
}
export default Task
<file_sep>/src/reducers/tasksReducer.js
export const tasksInitialState = [];
const taskReducer = (tasks, action) => {
switch (action.type) {
case "ADD_TASK":
return [...tasks,action.task];
case 'DELETE_TASK':
const newTasks=tasks.filter(todo=>todo._id!==action.id)
return [...newTasks]
case 'SET_TASKS':
return [...action.tasks]
case 'TOGGLE_TASK':
tasks.forEach(task => {
if(task._id===action.taskObj._id)
task.complete=action.taskObj.complete
});
return [...tasks]
default:
return [ ...tasks ];
}
};
export default taskReducer;<file_sep>/src/contexts/tasksContext.js
import React, { createContext, useReducer } from 'react';
import taskReducer, { tasksInitialState } from '../reducers/tasksReducer';
export const TasksContext = createContext();
const TasksContextProvider = (props) => {
const [tasksData, dispatchTasksData] = useReducer(taskReducer, tasksInitialState );
return (
<TasksContext.Provider value={{ tasksData, dispatchTasksData }}>
{props.children}
</TasksContext.Provider>
);
};
export default TasksContextProvider;<file_sep>/src/routers/AppRoute.js
import { Route, Switch, Redirect } from 'react-router-dom'
import { BrowserRouter } from 'react-router-dom'
import React from 'react'
import Home from '../components/Home'
import TasksContextProvider from '../contexts/tasksContext';
const AppRoute = () => {
return (
<BrowserRouter>
<TasksContextProvider>
<Switch>
<Route path="/" exact>
<Redirect to="/home" />
</Route>
<Route path="/home" component={Home} />
</Switch>
</TasksContextProvider>
</BrowserRouter>
)
}
export default AppRoute
<file_sep>/src/components/Button.js
import React from 'react'
const Button = ({content,backgroundColor,color,className}) => {
const defaultBgColor="orange";
const defaultColor="blue";
return (
<>
<button
className={className}
style={{backgroundColor:backgroundColor||defaultBgColor,color:color||defaultColor}}
>
{content}
</button>
</>
)
}
export default Button
<file_sep>/src/services/taskService.js
import Axios from 'axios';
const developmentDB = process.env.REACT_APP_DB;
export const addTaskToDB = async (todo) => {
try {
const res = await Axios.put(developmentDB + "/create-todo", todo);
console.log(res.data)
return res.data;
} catch (err) {
return err.response.data.message;
}
};
export const toggleTaskInDB = async (todo) => {
try {
const res = await Axios.patch(developmentDB + "/toggle-todo?id="+ todo._id);
return res.data;
} catch (err) {
return err.response.data.message;
}
};
export const deleteTaskFromDB = async (todo) => {
try {
const res = await Axios.delete(developmentDB + "/delete-todo?id="+todo._id);
return res.data;
} catch (err) {
return err.response.data.message;
}
};
export const getAllTasksTFromDB = async () => {
try {
const res = await Axios.get(developmentDB + "/get-todo");
return res.data;
} catch (err) {
return err.response.data.message;
}
};
|
31e35e062450dd8d430eff92298616be9663707c
|
[
"JavaScript"
] | 7 |
JavaScript
|
itata222/Todo_Front
|
abde73aea18c3a8f1bc41e6ce821ecac93b505ad
|
189d5582ae4100ffb5f40514a87c77c2d83b7799
|
refs/heads/master
|
<repo_name>jiyfhust/monitoring<file_sep>/platform-monitoring/operator/init.sh
#!/bin/sh
if [ ! -d $GF_PROVISIONING_PATH/dashboards ];then
mkdir -p $GF_PROVISIONING_PATH/dashboards
else
rm -rf $GF_PROVISIONING_PATH/dashboards/*
fi
# TiDB dashboard
cp /tmp/tidb.json $GF_PROVISIONING_PATH/dashboards
sed -i 's/Test-Cluster-TiDB/Cluster-TiDB/g' $GF_PROVISIONING_PATH/dashboards/tidb.json
sed -i 's/label_values(pd_cluster_status, tidb_cluster)/label_values(tidb_server_connections, tidb_cluster)/g' $GF_PROVISIONING_PATH/dashboards/tidb.json
# Overview dashboard
cp /tmp/overview.json $GF_PROVISIONING_PATH/dashboards
sed -i 's/Test-Cluster-Overview/Cluster-Overview/g' $GF_PROVISIONING_PATH/dashboards/overview.json
sed -i 's/label_values(pd_cluster_status, tidb_cluster)/label_values(process_start_time_seconds, tidb_cluster)/g' $GF_PROVISIONING_PATH/dashboards/overview.json
# PD dashboard
cp /tmp/pd.json $GF_PROVISIONING_PATH/dashboards
sed -i 's/Test-Cluster-PD/Cluster-PD/g' $GF_PROVISIONING_PATH/dashboards/pd.json
# TiKV dashboard
cp /tmp/tikv*.json $GF_PROVISIONING_PATH/dashboards
if [ ! -f /tmp/tikv_pull.json ];then
sed -i 's/Test-Cluster-TiKV-Details/Cluster-TiKV-Details/g' $GF_PROVISIONING_PATH/dashboards/tikv_details.json
sed -i 's/Test-Cluster-TiKV-Summary/Cluster-TiKV-Summary/g' $GF_PROVISIONING_PATH/dashboards/tikv_summary.json
sed -i 's/Test-Cluster-TiKV-Trouble-Shooting/Cluster-TiKV-Trouble-Shooting/g' $GF_PROVISIONING_PATH/dashboards/tikv_trouble_shooting.json
else
sed -i 's/Test-Cluster-TiKV/Cluster-TiKV/g' $GF_PROVISIONING_PATH/dashboards/tikv_pull.json
fi
# Binlog dashboard
cp /tmp/binlog.json $GF_PROVISIONING_PATH/dashboards
sed -i 's/Test-Cluster-Binlog/Cluster-Binlog/g' $GF_PROVISIONING_PATH/dashboards/binlog.json
# Lighting
cp /tmp/lightning.json $GF_PROVISIONING_PATH/dashboards
sed -i 's/Test-Cluster-Lightning/Cluster-Lightning/g' $GF_PROVISIONING_PATH/dashboards/lightning.json
# TiFlash
cp /tmp/tiflash_summary.json $GF_PROVISIONING_PATH/dashboards
sed -i 's/Test-Cluster-TiFlash-Summary/Cluster-TiFlash-Summary/g' $GF_PROVISIONING_PATH/dashboards/tiflash_summary.json
cp /tmp/tiflash_proxy_summary.json $GF_PROVISIONING_PATH/dashboards
sed -i 's/Test-Cluster-TiFlash-Proxy-Summary/Cluster-TiFlash-Proxy-Summary/g' $GF_PROVISIONING_PATH/dashboards/tiflash_proxy_summary.json
cp /tmp/tiflash_proxy_details.json $GF_PROVISIONING_PATH/dashboards
sed -i 's/Test-Cluster-TiFlash-Proxy-Details/Cluster-TiFlash-Proxy-Details/g' $GF_PROVISIONING_PATH/dashboards/tiflash_proxy_details.json
# TiCDC dashboard
cp /tmp/ticdc.json $GF_PROVISIONING_PATH/dashboards
sed -i 's/Test-Cluster-TiCDC/Cluster-TiCDC/g' $GF_PROVISIONING_PATH/dashboards/ticdc.json
sed -i 's/label_values(go_goroutines, tidb_cluster)/label_values(ticdc_kvclient_event_feed_count, tidb_cluster)/g' $GF_PROVISIONING_PATH/dashboards/ticdc.json
# To support monitoring multiple clusters with one TidbMonitor, change the job label to component
sed -i 's%job=\\\"tiflash\\\"%component=\\"tiflash\\"%g' $GF_PROVISIONING_PATH/dashboards/*.json
sed -i 's%job=\\\"tikv-importer\\\"%component=\\"importer\\"%g' $GF_PROVISIONING_PATH/dashboards/*.json
sed -i 's%job=\\\"lightning\\\"%component=\\"tidb-lightning\\"%g' $GF_PROVISIONING_PATH/dashboards/*.json
sed -i 's/\"hide\":\s2/"hide": 0/g' $GF_PROVISIONING_PATH/dashboards/*.json
fs=`ls $GF_PROVISIONING_PATH/dashboards/*.json`
for f in $fs
do
if [ "${f}" != "$GF_PROVISIONING_PATH/dashboards/nodes.json" ] &&
[ "${f}" != "$GF_PROVISIONING_PATH/dashboards/pods.json" ]; then
sed -i 's%job=%component=%g' ${f}
sed -i 's%{{job}}%{{component}}%g' ${f}
sed -i -e 's%\(by\s(\)job\(,.*)\)%\1component\2%g' -e 's%\(by\s(.*\),job,\(.*)\)%\1,component,\2%g' -e 's%\(by\s(.*,\)job)%\1component)%g' -e 's%\(by\s(\)job)%\1component)%g' ${f}
fi
done
# Rules
if [ ! -d $PROM_CONFIG_PATH/rules ];then
mkdir -p $PROM_CONFIG_PATH/rules
else
rm -rf $PROM_CONFIG_PATH/rules/*
fi
echo $META_TYPE
echo $META_INSTANCE
echo $META_VALUE
cp /tmp/*.rules.yml $PROM_CONFIG_PATH/rules
for file in $PROM_CONFIG_PATH/rules/*
do
sed -i 's/ENV_LABELS_ENV/Cluster/g' $file
sed -i 's%job=%component=%g' $file
sed -i -e 's%\(by\s(\)job\(,.*)\)%\1component\2%g' -e 's%\(by\s(.*\),job,\(.*)\)%\1,component,\2%g' -e 's%\(by\s(.*,\)job)%\1component)%g' -e 's%\(by\s(\)job)%\1component)%g' $file
done
# Copy Persistent rules to override raw files
if [ ! -z $PROM_PERSISTENT_DIR ];
then
if [ -d $PROM_PERSISTENT_DIR/latest-rules/${TIDB_VERSION##*/} ];then
cp -f $PROM_PERSISTENT_DIR/latest-rules/${TIDB_VERSION##*/}/*.rules.yml $PROM_CONFIG_PATH/rules
fi
fi
# Datasources
if [ ! -z $GF_DATASOURCE_PATH ];
then
if [ ! -z $GF_K8S_PROMETHEUS_URL ];
then
sed -i 's,http://prometheus-k8s.monitoring.svc:9090,'$GF_K8S_PROMETHEUS_URL',g' /tmp/k8s-datasource.yaml
fi
if [ ! -z $GF_TIDB_PROMETHEUS_URL ];
then
sed -i 's,http://127.0.0.1:9090,'$GF_TIDB_PROMETHEUS_URL',g' /tmp/tidb-cluster-datasource.yaml
fi
cp /tmp/k8s-datasource.yaml $GF_DATASOURCE_PATH/
cp /tmp/tidb-cluster-datasource.yaml $GF_DATASOURCE_PATH/
# pods
if [ ! -z $TIDB_CLUSTER_NAMESPACE ];
then
sed -i 's/$namespace/'$TIDB_CLUSTER_NAMESPACE'/g' /tmp/pods.json
else
sed -i 's/$namespace/default/g' /tmp/pods.json
fi
sed -i 's/Test-Cluster-Pods-Info/Cluster-Pods-Info/g' /tmp/pods.json
cp /tmp/pods.json $GF_PROVISIONING_PATH/dashboards
# nodes
cp /tmp/nodes.json $GF_PROVISIONING_PATH/dashboards
fi
|
da44a5fcac1891eab9284274237a9ced9d1097b1
|
[
"Shell"
] | 1 |
Shell
|
jiyfhust/monitoring
|
ea039934e1cf5a07b37bc3ae6b5cd45553a1599f
|
21fc5856f0d198cd26e124fda07b131621581161
|
refs/heads/master
|
<repo_name>Annubis1709/ExData_Plotting1<file_sep>/plot4.R
#---Assignment: Course Project 1---#
## 4). plot4.R
# To change your working directory, use setwd and specify the path to the desired folder.
# setwd(dir), dir – Specify a working directory.
setwd("/home/draconis/Documentos/COURSERA/DATA SCIENCE/4. Exploratory Data Analysis/WEEK_1/Course Project 1")
## Load and clean the table:
electric_power <- data.table::fread(input = "household_power_consumption.txt",
na.strings="?")
#Prevents the histogram from being printed in scientific notation:
electric_power[, Global_active_power := lapply(.SD, as.numeric),
.SDcols = c("Global_active_power")]
#Format dateTime Column
electric_power[, date_time := as.POSIXct(paste(Date, Time),
format = "%d/%m/%Y %H:%M:%S")]
#Format date to Type Date:
electric_power[, Date := lapply(.SD, as.Date, "%d/%m/%Y"),
.SDcols = c("Date")]
#Filter data set from Feb. 1, 2007 to Feb. 2, 2007
electric_power <- electric_power[(Date >= "2007-02-01") & (Date <= "2007-02-02")]
#Create plot.4:
par(mfrow = c(2,2), mar = c(4,4,2,1), oma = c(0,0,2,0))
with(electric_power, {
plot(Global_active_power~date_time, type = "l",
ylab = "Global Active Power (kilowatts)", xlab = "")
plot(Voltage~date_time, type = "l", ylab = "Voltage (volt)", xlab = "")
plot(Sub_metering_1~date_time, type = "l",
ylab = "Global Active Power (kilowatts)", xlab = "")
lines(Sub_metering_2~date_time, col = 'Red')
lines(Sub_metering_3~date_time, col = 'Blue')
legend("topright", col = c("black", "red", "blue"), lty = 1, lwd = 2,
bty = "n", legend = c("Sub_metering_1", "Sub_metering_2",
"Sub_metering_3"))
plot(Global_reactive_power~date_time, type = "l",
ylab = "Global Rective Power (kilowatts)", xlab = "")
})
#Save file and close device:
dev.copy(png, file = "plot4.png", width=480, height=480)
dev.off()
<file_sep>/plot1.R
#---Assignment: Course Project 1---#
## 1). plot1.R
# To change your working directory, use setwd and specify the path to the desired folder.
# setwd(dir), dir – Specify a working directory.
setwd("/home/draconis/Documentos/COURSERA/DATA SCIENCE/4. Exploratory Data Analysis/WEEK_1/Course Project 1")
## Load and clean the table:
electric_power <- data.table::fread(input = "household_power_consumption.txt",
na.strings="?")
#Prevents the histogram from being printed in scientific notation:
electric_power[, Global_active_power := lapply(.SD, as.numeric),
.SDcols = c("Global_active_power")]
#Format date to Type Date:
electric_power[, Date := lapply(.SD, as.Date, "%d/%m/%Y"), .SDcols = c("Date")]
#Filter data set from Feb. 1, 2007 to Feb. 2, 2007
electric_power <- electric_power[(Date >= "2007-02-01") & (Date <= "2007-02-02")]
#Create the histogram plot.1:
hist(electric_power$Global_active_power, main="Global Active Power",
xlab = "Global Active Power (kilowatts)", col="red")
#Save file and close device:
dev.copy(png,"plot1.png", width=480, height=480)
dev.off()
|
010150c38ce00ba524d52930547a1875c1d2668d
|
[
"R"
] | 2 |
R
|
Annubis1709/ExData_Plotting1
|
72603eee4027fbbad59125ccbdd20afa4f6c60ad
|
6f450171a860bee2c92294e44498c412d8722bda
|
refs/heads/master
|
<file_sep>using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
namespace QOLTweaksPack.rimworld
{
[DefOf]
public static class NewOrderJobDefOf
{
public static JobDef QOL_DropObject;
public static JobDef QOL_PickupObject;
}
}
<file_sep>using HugsLib;
using HugsLib.Settings;
using HugsLib.Utils;
using QOLTweaksPack.hugsLibSettings;
using QOLTweaksPack.rimworld;
using QOLTweaksPack.tweaks;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using Verse;
namespace QOLTweaksPack
{
public class QOLTweaksPack : ModBase
{
public override string ModIdentifier { get { return "QOLTweaksPack"; } }
public enum SurgeryEstimateMode { AlwaysAccurate, AccurateIfDoctor, AccurateIfGoodDoctor, AccurateIfAmazingDoctor, NeverAccurate }
public static SavedData savedData;
internal static SettingHandle<bool> ButcherSpace;
internal static SettingHandle<bool> DeadlockProtection;
internal static SettingHandle<bool> CookingEquivalency;
internal static SettingHandle<MealSetHandler> MealSelection;
internal static SettingHandle<bool> MoveOrder;
internal static SettingHandle<bool> PickupDropOrders;
internal static SettingHandle<bool> TradingStockpiles;
internal static SettingHandle<bool> SurgeryEstimates;
internal static SettingHandle<SurgeryEstimateMode> SurgeryEstimationMode;
internal static SettingHandle<bool> SurgeryEstimateAccountForTraits;
internal static SettingHandle<bool> BruiseWalkingOff;
private static Color noHighlight = new Color(0, 0, 0, 0);
private static Color highlight1 = new Color(0.5f, 0, 0, 0.1f);
private static Color highlight2 = new Color(0, 0.5f, 0, 0.1f);
private static Color highlight3 = new Color(0, 0, 0.5f, 0.1f);
private static Color highlight4 = new Color(0.5f, 0, 0.5f, 0.1f);
private static Color highlight5 = new Color(0.5f, 0.5f, 0, 0.1f);
private static Color highlight6 = new Color(0, 0.5f, 0.5f, 0.1f);
public override void DefsLoaded()
{
base.DefsLoaded();
ButcherSpace = Settings.GetHandle<bool>("ButcherSpace", "ButcherSpace_title".Translate(), "ButcherSpace_desc".Translate(), true);
DeadlockProtection = Settings.GetHandle<bool>("DeadlockProtection", "DeadlockProtection_title".Translate(), "DeadlockProtection_desc".Translate(), true);
DeadlockProtection.VisibilityPredicate = delegate { return ButcherSpace.Value == true; };
ButcherSpace.CustomDrawer = rect => { return SettingUIs.HugsDrawerRebuild_Checkbox(ButcherSpace, rect, highlight1); };
DeadlockProtection.CustomDrawer = rect => { return SettingUIs.HugsDrawerRebuild_Checkbox(DeadlockProtection, rect, highlight1); };
CookingEquivalency = Settings.GetHandle<bool>("CookingEquivalency", "CookingEquivalency_title".Translate(), "CookingEquivalency_desc".Translate(), true);
CookingEquivalency.CustomDrawer = rect => { return SettingUIs.HugsDrawerRebuild_Checkbox(CookingEquivalency, rect, highlight2); };
MealSelection = Settings.GetHandle<MealSetHandler>("MealSelection", "MealSelection_title".Translate(), "MealSelection_desc".Translate(), null);
MealSelection.VisibilityPredicate = delegate { return CookingEquivalency.Value == true; };
MealSelection.CustomDrawer = rect => { return SettingUIs.CustomDrawer_MatchingMeals_active(rect, MealSelection, highlight2, "SelectedMeals".Translate(), "UnselectedMeals".Translate()); };
MealSelection.Value = new MealSetHandler();
MoveOrder = Settings.GetHandle<bool>("MoveOrder", "MoveOrder_title".Translate(), "MoveOrder_desc".Translate(), true);
MoveOrder.CustomDrawer = rect => { return SettingUIs.HugsDrawerRebuild_Checkbox(MoveOrder, rect, highlight3); };
PickupDropOrders = Settings.GetHandle<bool>("PickupDropOrders", "PickupDropOrders_title".Translate(), "PickupDropOrders_desc".Translate(), true);
PickupDropOrders.CustomDrawer = rect => { return SettingUIs.HugsDrawerRebuild_Checkbox(PickupDropOrders, rect, highlight3); };
TradingStockpiles = Settings.GetHandle<bool>("TradingStockpiles", "TradingStockpiles_title".Translate(), "TradingStockpiles_desc".Translate(), true);
TradingStockpiles.CustomDrawer = rect => { return SettingUIs.HugsDrawerRebuild_Checkbox(TradingStockpiles, rect, highlight4); };
SurgeryEstimates = Settings.GetHandle<bool>("SurgeryEstimates", "SurgeryEstimates_title".Translate(), "SurgeryEstimates_desc".Translate(), true);
SurgeryEstimates.CustomDrawer = rect => { return SettingUIs.HugsDrawerRebuild_Checkbox(SurgeryEstimates, rect, highlight5); };
SurgeryEstimationMode = Settings.GetHandle<SurgeryEstimateMode>("SurgeryEstimationMode", "SurgeryEstimationMode_title".Translate(), "SurgeryEstimationMode_desc".Translate(), SurgeryEstimateMode.AccurateIfGoodDoctor, null, "SurgeryEstimationMode_option_");
SurgeryEstimationMode.CustomDrawer = rect => {
string[] names = Enum.GetNames(SurgeryEstimationMode.Value.GetType());
float[] forcedWidths = new float[names.Length];
return SettingUIs.CustomDrawer_Enumlist(SurgeryEstimationMode, rect, names, forcedWidths, true, SettingUIs.ExpansionMode.Vertical, highlight5);
};
SurgeryEstimateAccountForTraits = Settings.GetHandle<bool>("SurgeryEstimateAccountForTraits", "SurgeryEstimateAccountForTraits_title".Translate(), "SurgeryEstimateAccountForTraits_desc".Translate(), true);
SurgeryEstimateAccountForTraits.CustomDrawer = rect => { return SettingUIs.HugsDrawerRebuild_Checkbox(SurgeryEstimateAccountForTraits, rect, highlight5); };
BruiseWalkingOff = Settings.GetHandle<bool>("BruiseWalkingOff", "BruiseWalkingOff_title".Translate(), "BruiseWalkingOff_desc".Translate(), true);
BruiseWalkingOff.CustomDrawer = rect => { return SettingUIs.HugsDrawerRebuild_Checkbox(BruiseWalkingOff, rect, highlight5); };
}
public override void WorldLoaded()
{
savedData = UtilityWorldObjectManager.GetUtilityWorldObject<SavedData>();
}
public override void Update()
{
base.Update();
if (GenScene.InPlayScene)
{
UIRoot_Play_UIRootOnGUI_Prefix.Validate();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Verse.AI;
namespace QOLTweaksPack.rimworld
{
class JobDriver_DropObject : JobDriver
{
[DebuggerHidden]
protected override IEnumerable<Toil> MakeNewToils()
{
Toil carryToCell = Toils_Haul.CarryHauledThingToCell(TargetIndex.A);
yield return carryToCell;
yield return Toils_Haul.PlaceHauledThingInCell(TargetIndex.A, carryToCell, true);
}
}
}
<file_sep>using QOLTweaksPack.utilities;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using Verse;
using Verse.Sound;
namespace QOLTweaksPack.rimworld
{
class Gizmo_TradeStockpileToggle : Gizmo
{
public override float Width { get{ return 75; } }
private Zone_Stockpile parentZone;
public Gizmo_TradeStockpileToggle(Zone_Stockpile zone)
{
parentZone = zone;
}
public override GizmoResult GizmoOnGUI(Vector2 topLeft)
{
var gizmoRect = new Rect(topLeft.x, topLeft.y, Width, Width);
Widgets.DrawWindowBackground(gizmoRect);
Texture2D gizmoTex;
string gizmoLabel;
string gizmoMouseover;
bool isTradeStockpile = QOLTweaksPack.savedData.StockpileIsTradeStockpile(parentZone);
if (isTradeStockpile)
{
gizmoTex = TextureResources.tradeStockpileOn;
gizmoLabel = "TradeStockpileOn_label".Translate();
gizmoMouseover = "TradeStockpileOn_mouseOver".Translate();
}
else
{
gizmoTex = TextureResources.tradeStockpileOff;
gizmoLabel = "TradeStockpileOff_label".Translate();
gizmoMouseover = "TradeStockpileOff_mouseOver".Translate();
}
GUI.DrawTexture(gizmoRect, gizmoTex);
// Log.Warning(gizmoRect.ToString());
TooltipHandler.TipRegion(gizmoRect, gizmoMouseover);
MouseoverSounds.DoRegion(gizmoRect, SoundDefOf.MouseoverCommand);
WidgetsExtensions.DrawGizmoLabel(gizmoLabel, gizmoRect);
bool interacted;
if (Widgets.ButtonInvisible(gizmoRect, true))
{
if (isTradeStockpile)
QOLTweaksPack.savedData.RemoveTradeStockpile(parentZone);
else
QOLTweaksPack.savedData.AddTradeStockpile(parentZone);
interacted = true;
}
else
interacted = false;
return interacted ? new GizmoResult(GizmoState.Interacted, Event.current) : new GizmoResult(GizmoState.Clear);
}
}
}
<file_sep>using HugsLib.Settings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QOLTweaksPack.hugsLibSettings
{
internal class StringHashSetHandler : SettingHandleConvertible
{
protected HashSet<string> strings = new HashSet<string>();
internal HashSet<string> InnerList { get { return strings; } set { strings = value; } }
private const string EmptySet = "EmptySet";
public StringHashSetHandler()
{
SetToDefault();
}
protected virtual void SetToDefault()
{
}
public override void FromString(string settingValue)
{
strings = new HashSet<string>();
if (settingValue.Equals(string.Empty))
{
SetToDefault();
}
else
{
if (!settingValue.Equals(EmptySet))
{
foreach (string str in settingValue.Split('|'))
{
strings.Add(str);
}
}
}
}
public override string ToString()
{
return strings.Count != 0 ? String.Join("|", strings.ToArray()) : "EmptySet";
}
}
}
<file_sep>using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QOLTweaksPack.hugsLibSettings
{
class MealSetHandler : StringHashSetHandler
{
protected override void SetToDefault()
{
strings.Add(ThingDefOf.MealSimple.defName);
strings.Add(ThingDefOf.MealFine.defName);
}
}
}
<file_sep>using HugsLib.Utils;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
namespace QOLTweaksPack.rimworld
{
public class SavedData : UtilityWorldObject
{
public List<string> TradeStockpileNames = new List<string>();
public List<int> TradeStockpileMapIds = new List<int>();
public override void ExposeData()
{
base.ExposeData();
Scribe_Collections.Look<string>(ref TradeStockpileNames, "TradeStockpileNames", LookMode.Value, LookMode.Deep);
Scribe_Collections.Look<int>(ref TradeStockpileMapIds, "TradeStockpileMapIds", LookMode.Value, LookMode.Deep);
if (Scribe.mode == LoadSaveMode.LoadingVars)
{
if (TradeStockpileNames == null) TradeStockpileNames = new List<string>();
if (TradeStockpileMapIds == null) TradeStockpileMapIds = new List<int>();
}
}
#region stockpile
public bool StockpileIsTradeStockpile(Zone_Stockpile stockpile)
{
for(int i = 0; i < TradeStockpileNames.Count; i++)
{
if (TradeStockpileNames[i].Equals(stockpile.label) && TradeStockpileMapIds[i] == stockpile.Map.Index)
return true;
}
return false;
}
public void AddTradeStockpile(Zone_Stockpile stockpile)
{
TradeStockpileNames.Add(stockpile.label);
TradeStockpileMapIds.Add(stockpile.Map.Index);
}
public void RemoveTradeStockpile(Zone_Stockpile stockpile)
{
for (int i = 0; i < TradeStockpileNames.Count; i++)
{
if(TradeStockpileNames[i].Equals(stockpile.label) && TradeStockpileMapIds[i] == stockpile.Map.Index)
{
TradeStockpileNames.RemoveAt(i);
TradeStockpileMapIds.RemoveAt(i);
return;
}
}
}
public void TradeStockpileRenamed(Zone_Stockpile stockpile, string newName)
{
for (int i = 0; i < TradeStockpileNames.Count; i++)
{
if (TradeStockpileNames[i].Equals(stockpile.label) && TradeStockpileMapIds[i] == stockpile.Map.Index)
{
TradeStockpileNames.RemoveAt(i);
TradeStockpileMapIds.RemoveAt(i);
TradeStockpileNames.Add(newName);
TradeStockpileMapIds.Add(stockpile.Map.Index);
return;
}
}
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace QOLTweaksPack.utilities
{
internal static class Reflection
{
internal static object GetFieldValue(object src, string fieldName)
{
return src.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(src);
}
}
}
<file_sep>using Harmony;
using HugsLib.Utils;
using QOLTweaksPack.rimworld;
using QOLTweaksPack.utilities;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
using Verse;
using Verse.AI;
namespace QOLTweaksPack.tweaks
{
[HarmonyPatch(typeof(FloatMenuMakerMap), "AddHumanlikeOrders")]
static class FloatMenuMakerMap_AddHumanLikeOrders_Postfix
{
[HarmonyPostfix]
private static void AddHumanlikeOrders(Vector3 clickPos, Pawn pawn, List<FloatMenuOption> opts)
{
if (QOLTweaksPack.MoveOrder.Value == true)
DoMoveOrder(clickPos, pawn, opts);
if (QOLTweaksPack.PickupDropOrders.Value == true)
DoPickupOrder(clickPos, pawn, opts);
if (QOLTweaksPack.PickupDropOrders.Value == true)
DoDropOrder(clickPos, pawn, opts);
}
private static void DoMoveOrder(Vector3 clickPos, Pawn pawn, List<FloatMenuOption> opts)
{
if (!HugsLibUtility.ShiftIsHeld)
return;
FloatMenuOption item;
IntVec3 c = IntVec3.FromVector3(clickPos);
string text = "MoveToOrder".Translate();
item = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, delegate
{
pawn.jobs.TryTakeOrderedJob(new Job(JobDefOf.Goto, c), JobTag.Misc);
MoteMaker.MakeStaticMote(c, pawn.Map, ThingDefOf.Mote_FeedbackGoto, 1f);
}, MenuOptionPriority.High, null, null, 0f, null, null), pawn, c, "ReservedBy");
opts.Add(item);
}
internal static bool forceKeep = false;
private static void DoDropOrder(Vector3 clickPos, Pawn pawn, List<FloatMenuOption> opts)
{
if (!HugsLibUtility.ShiftIsHeld)
return;
if (pawn.carryTracker.CarriedThing != null && pawn.jobs.curDriver is JobDriver_PickupObject)
{
IntVec3 c = IntVec3.FromVector3(clickPos);
opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("DropCarriedAt".Translate(), delegate
{
Job job = new Job(NewOrderJobDefOf.QOL_DropObject, c);
forceKeep = true;
pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc);
forceKeep = false;
}, MenuOptionPriority.High, null, null, 0f, null, null), pawn, c, "ReservedBy"));
}
}
private static void DoPickupOrder(Vector3 clickPos, Pawn pawn, List<FloatMenuOption> opts)
{
if (!HugsLibUtility.ShiftIsHeld)
return;
IntVec3 c = IntVec3.FromVector3(clickPos);
Thing item = c.GetFirstItem(pawn.Map);
if (item != null && item.def.EverHaulable)
{
if (!pawn.CanReach(item, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn))
{
opts.Add(new FloatMenuOption("CannotPickUp".Translate(new object[]
{
item.Label
}) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null));
}
else if (MassUtility.WillBeOverEncumberedAfterPickingUp(pawn, item, 1))
{
opts.Add(new FloatMenuOption("CannotPickUp".Translate(new object[]
{
item.Label
}) + " (" + "TooHeavy".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null));
}
else if (item.stackCount == 1)
{
opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("PickUp".Translate(new object[]
{
item.Label
}), delegate
{
item.SetForbidden(false, false);
Job job = new Job(NewOrderJobDefOf.QOL_PickupObject, item);
job.count = 1;
pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc);
}, MenuOptionPriority.High, null, null, 0f, null, null), pawn, item, "ReservedBy"));
}
else
{
opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("PickUpAll".Translate(new object[]
{
item.Label
}), delegate
{
item.SetForbidden(false, false);
Job job = new Job(NewOrderJobDefOf.QOL_PickupObject, item);
job.count = item.stackCount;
pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc);
}, MenuOptionPriority.High, null, null, 0f, null, null), pawn, item, "ReservedBy"));
}
}
}
}
[HarmonyPatch(typeof(Pawn_JobTracker), "CleanupCurrentJob")]
static class Pawn_JobTracker_CleanupCurrentJob_PrefixReplacement
{
[HarmonyPrefix]
public static bool CleanupCurrentJob(Pawn_JobTracker __instance, JobCondition condition, bool releaseReservations, bool cancelBusyStancesSoft = true)
{
if (QOLTweaksPack.PickupDropOrders.Value == false)
return true;
if (!FloatMenuMakerMap_AddHumanLikeOrders_Postfix.forceKeep)
return true;
if (!(__instance.curDriver is JobDriver_PickupObject))
return true;
if (__instance.curJob == null)
return true;
if (__instance.debugLog)
{
__instance.DebugLogEvent(string.Concat(new object[]
{
"CleanupCurrentJob ",
(__instance.curJob == null) ? "null" : __instance.curJob.def.ToString(),
" condition ",
condition
}));
}
Pawn pawn = (Pawn)Reflection.GetFieldValue(__instance, "pawn");
__instance.curDriver.ended = true;
__instance.curDriver.Cleanup(condition);
__instance.curDriver = null;
__instance.curJob = null;
if (releaseReservations)
{
pawn.ClearReservations(false);
}
if (cancelBusyStancesSoft)
{
pawn.stances.CancelBusyStanceSoft();
}
if (!pawn.Destroyed && pawn.carryTracker != null && pawn.carryTracker.CarriedThing != null)
{
//Thing thing;
//pawn.carryTracker.TryDropCarriedThing(pawn.Position, ThingPlaceMode.Near, out thing, null);
//Do not do this thing
}
return false;
}
}
}
<file_sep>using Harmony;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
namespace QOLTweaksPack.tweaks
{
[HarmonyPatch(typeof(WorkGiver_DoBill), "TryFindBestBillIngredientsInSet")]
static class WorkGiver_DoBill_TryFindBestBillIngredientsInSet_Postfix
{
[HarmonyPostfix]
private static void TryFindBestBillIngredientsInSet(ref bool __result, List<Thing> availableThings, Bill bill, List<ThingAmount> chosen)
{
if (QOLTweaksPack.ButcherSpace.Value == false)
return;
if (bill.recipe.specialProducts != null)
{
foreach (SpecialProductType specialProductType in bill.recipe.specialProducts)
{
if (specialProductType == SpecialProductType.Butchery)
{
TryFindBestBillIngredientsInSetButchery(ref __result, availableThings, bill, chosen);
return;
}
}
}
List<ThingCountClass> rottableProducts = new List<ThingCountClass>();
if (bill.recipe.products != null)
{
foreach (ThingCountClass product in bill.recipe.products)
{
if (product.thingDef.HasComp(typeof(CompRottable)))
{
rottableProducts.Add(product);
}
}
}
TryFindBestBillIngredientsInSetRottable(ref __result, availableThings, bill, chosen, rottableProducts);
}
private static void TryFindBestBillIngredientsInSetButchery(ref bool __result, List<Thing> availableThings, Bill bill, List<ThingAmount> chosen)
{
if (QOLTweaksPack.DeadlockProtection.Value == true && bill.Map.resourceCounter.GetCountIn(ThingCategoryDefOf.MeatRaw) < 10)
return;
if (chosen.Count < 1 || chosen.Count > 1 || chosen[0].count != 1)
{
return;
}
Thing corpse = chosen[0].thing;
if (corpse as Corpse == null)
return;
if (!CanStoreCount(bill.Map, MeatDefFor(corpse as Corpse), EstimatedMeatCount(corpse as Corpse)))
{
__result = false;
chosen.Clear();
List<ThingDef> testedRaces = new List<ThingDef>();
testedRaces.Add((corpse as Corpse).InnerPawn.def);
foreach(Thing alternativeCorpse in availableThings)
{
if (testedRaces.Contains((alternativeCorpse as Corpse).InnerPawn.def))
continue;
else
testedRaces.Add((alternativeCorpse as Corpse).InnerPawn.def);
if (alternativeCorpse as Corpse == null)
continue;
if (CanStoreCount(bill.Map, MeatDefFor(alternativeCorpse as Corpse), EstimatedMeatCount(alternativeCorpse as Corpse)))
{
__result = true;
chosen.Add(new ThingAmount(alternativeCorpse, 1));
return;
}
}
}
}
private static bool CanStoreCount(Map map, ThingDef thingDef, int requiredAmount)
{
List<SlotGroup> storageList = map.slotGroupManager.AllGroupsListInPriorityOrder;
List<SlotGroup> storageFiltered = new List<SlotGroup>();
int total = 0;
foreach (SlotGroup storage in storageList)
{
if (StorageAllowedToAccept(storage.Settings, thingDef))
{
foreach(IntVec3 cell in storage.CellsList)
{
int local = MaximumStorageInCellFor(cell, map, thingDef);
total += local;
if (total >= requiredAmount)
return true;
}
}
}
return false;
}
private static int MaximumStorageInCellFor(IntVec3 c, Map map, ThingDef thing)
{
List<Thing> list = map.thingGrid.ThingsListAt(c);
for (int i = 0; i < list.Count; i++)
{
Thing thing2 = list[i];
if (thing2.def.EverStoreable)
{
if (!CanStackWith(thing, thing2.def))
{
return 0;
}
if (thing2.stackCount >= thing.stackLimit)
{
return 0;
}
else
{
return thing.stackLimit - thing2.stackCount;
}
}
if (thing2.def.entityDefToBuild != null && thing2.def.entityDefToBuild.passability != Traversability.Standable)
{
return 0;
}
if (thing2.def.surfaceType == SurfaceType.None && thing2.def.passability != Traversability.Standable)
{
return 0;
}
}
return thing.stackLimit;
}
private static bool CanStackWith(ThingDef thing, ThingDef other)
{
return thing == other;
}
private static ThingDef MeatDefFor(Corpse corpse)
{
return (corpse as Corpse).InnerPawn.RaceProps.meatDef;
}
private static int EstimatedMeatCount(Corpse corpse)
{
int meatCount = (int)corpse.InnerPawn.GetStatValue(StatDefOf.MeatAmount, true);
return meatCount;
}
private static void TryFindBestBillIngredientsInSetRottable(ref bool __result, List<Thing> availableThings, Bill bill, List<ThingAmount> chosen, List<ThingCountClass> rottableProducts)
{
if(QOLTweaksPack.DeadlockProtection.Value == true)
{
foreach (ThingCountClass product in rottableProducts)
{
if (bill.Map.resourceCounter.GetCount(product.thingDef) < 1)
return;
}
}
foreach (ThingCountClass product in rottableProducts)
{
if (!CanStoreCount(bill.Map, product.thingDef, product.count))
{
__result = false;
chosen.Clear();
return;
}
}
}
private static bool StorageAllowedToAccept(StorageSettings storage, ThingDef def)
{
if (!storage.filter.Allows(def))
{
return false;
}
if (storage.owner != null)
{
StorageSettings parentStoreSettings = storage.owner.GetParentStoreSettings();
if (parentStoreSettings != null && !StorageAllowedToAccept(parentStoreSettings, def))
{
return false;
}
}
return true;
}
}
}
<file_sep>using Harmony;
using QOLTweaksPack.utilities;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using Verse;
namespace QOLTweaksPack.tweaks
{
[HarmonyPatch(typeof(Bill_Production), "ShouldDoNow")]
static class WorkGiver_ShouldDoNow_Postfix
{
[HarmonyPostfix]
private static void ShouldDoNow(Bill_Production __instance, ref bool __result)
{
if (__result == false)
return;
if (QOLTweaksPack.CookingEquivalency.Value == false)
return;
if(__instance.repeatMode == BillRepeatModeDefOf.TargetCount)
{
if (__instance.recipe.products == null || __instance.recipe.products.Count == 0)
return;
ThingDef product = __instance.recipe.products[0].thingDef;
if (QOLTweaksPack.MealSelection.Value.InnerList.Contains(product.defName))
{
int num = ItemCounter.CountProductsWithEquivalency(__instance, __instance.recipe.WorkerCounter);
if (__instance.pauseWhenSatisfied && num >= __instance.targetCount)
{
__instance.paused = true;
}
if (num <= __instance.unpauseWhenYouHave || !__instance.pauseWhenSatisfied)
{
__instance.paused = false;
}
__result = !__instance.paused && num < __instance.targetCount;
}
}
}
}
[HarmonyPatch(typeof(Bill_Production), "DoConfigInterface")]
static class WorkGiver_DoConfigInterface_Postfix
{
[HarmonyPostfix]
private static void DoConfigInterface(Bill_Production __instance, Rect baseRect, Color baseColor)
{
if (QOLTweaksPack.CookingEquivalency.Value == false)
return;
if (__instance.repeatMode != BillRepeatModeDefOf.TargetCount)
return;
if (__instance.recipe.products.Count() <= 0)
return;
ThingDef product = __instance.recipe.products[0].thingDef;
if (QOLTweaksPack.MealSelection.Value.InnerList.Contains(product.defName))
{
int num = ItemCounter.CountProductsWithEquivalency(__instance, __instance.recipe.WorkerCounter);
Rect rect = new Rect(78f, 32f, 30f, 30f);
GUI.color = new Color(0.75f, 1f, 0.5f, 0.75f);
Widgets.Label(rect, "/"+num);
GUI.color = baseColor;
}
}
}
}
<file_sep>using Harmony;
using QOLTweaksPack.rimworld;
using QOLTweaksPack.utilities;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
namespace QOLTweaksPack.tweaks
{
[HarmonyPatch(typeof(Zone), "Delete")]
static class Zone_Delete_Prefix
{
[HarmonyPrefix]
private static void Delete(Zone __instance)
{
if (!(__instance is Zone_Stockpile))
return;
if (QOLTweaksPack.savedData.StockpileIsTradeStockpile(__instance as Zone_Stockpile))
{
QOLTweaksPack.savedData.RemoveTradeStockpile(__instance as Zone_Stockpile);
}
}
}
[HarmonyPatch(typeof(Dialog_Trade), "PostOpen")]
static class Dialog_Trade_PostOpen_Postfix
{
[HarmonyPostfix]
private static void PostOpen(Dialog_Trade __instance)
{
if (QOLTweaksPack.TradingStockpiles.Value == false)
return;
List<Tradeable> cachedTradeables = Reflection.GetFieldValue(__instance, "cachedTradeables") as List<Tradeable>;
if (cachedTradeables == null)
{
Log.Warning("Could not grab cachedTradeables via reflection");
}
foreach (Tradeable tradeable in cachedTradeables)
{
foreach (Thing tradeableThing in tradeable.thingsColony)
{
if (tradeableThing is Pawn)
continue;
if (tradeableThing.holdingOwner != null)
{
SlotGroup storage = StoreUtility.GetSlotGroup(tradeableThing);
if (storage == null || storage.parent == null)
continue;
if (storage.parent is Zone_Stockpile)
{
if (QOLTweaksPack.savedData.StockpileIsTradeStockpile(storage.parent as Zone_Stockpile))
{
if (tradeable.CanAdjustBy(-tradeableThing.stackCount).Accepted & tradeable.TraderWillTrade)
tradeable.AdjustBy(-tradeableThing.stackCount);
}
}
}
}
}
}
}
[HarmonyPatch(typeof(Dialog_RenameZone), "NameIsValid")]
static class Dialog_RenameZone_NameIsValid_Postfix
{
[HarmonyPostfix]
private static void NameIsValid(Dialog_RenameZone __instance, string name, AcceptanceReport __result)
{
Zone zone = Reflection.GetFieldValue(__instance, "zone") as Zone;
if (zone == null)
{
Log.Warning("Could not grab zone via reflection");
}
if (!(zone is Zone_Stockpile))
return;
if (__result.Accepted)
QOLTweaksPack.savedData.TradeStockpileRenamed(zone as Zone_Stockpile, name);
}
}
[HarmonyPatch(typeof(Zone_Stockpile), "GetGizmos")]
static class Zone_Stockpile_GetGizmos_Postfix
{
[HarmonyPostfix]
private static void GetGizmos(Zone_Stockpile __instance, ref IEnumerable<Gizmo> __result)
{
if (QOLTweaksPack.TradingStockpiles.Value == false)
return;
List<Gizmo> results = new List<Gizmo>();
foreach(Gizmo gizmo in __result)
{
results.Add(gizmo);
}
results.Add(new Gizmo_TradeStockpileToggle(__instance));
__result = results;
}
}
}
<file_sep>using Harmony;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
namespace QOLTweaksPack.tweaks
{
[HarmonyPatch(typeof(TendUtility), "DoTend")]
static class TendUtility_DoTend_PrePostfix
{
[HarmonyPrefix]
private static void DoTendPrefix(Pawn doctor, Pawn patient, ref Medicine medicine, Medicine __state)
{
if (QOLTweaksPack.BruiseWalkingOff.Value == false)
return;
//Log.Message("tending prefix");
if (medicine == null || doctor == null || patient == null || doctor.Faction.IsPlayer == false)
return;
List<Hediff> tmpHediffsToTend = new List<Hediff>();
TendUtility.GetOptimalHediffsToTendWithSingleTreatment(patient, true, tmpHediffsToTend, null);
foreach(Hediff tendable in tmpHediffsToTend)
{
//Log.Message("tending " + tendable.GetType().ToString());
if (!(tendable is Hediff_Injury))
return;
Hediff_Injury injury = (tendable as Hediff_Injury);
if (injury.Bleeding)
{
//Log.Message("is bleeding");
return;
}
if (injury.TryGetComp<HediffComp_Infecter>() != null)
{
//Log.Message("has infecter");
return;
}
if (injury.TryGetComp<HediffComp_GetsOld>() != null)
{
//Log.Message("has scarring");
return;
}
//Log.Message("match");
}
__state = medicine;
medicine = null;
}
[HarmonyPostfix]
private static void DoTendPostfix(Pawn doctor, Pawn patient, ref Medicine medicine, Medicine __state)
{
if (QOLTweaksPack.BruiseWalkingOff.Value == false)
return;
Thing eh;
if (__state != null)
doctor.carryTracker.TryDropCarriedThing(doctor.Position, ThingPlaceMode.Direct, out eh);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using Verse;
namespace QOLTweaksPack
{
[StaticConstructorOnStartup]
class TextureResources
{
public static readonly Texture2D drawPocket = ContentFinder<Texture2D>.Get("drawPocket", true);
public static readonly Texture2D tradeStockpileOn = ContentFinder<Texture2D>.Get("tradeStockpileOn", true);
public static readonly Texture2D tradeStockpileOff = ContentFinder<Texture2D>.Get("tradeStockpileOff", true);
public static readonly Texture2D missingMedicine = ContentFinder<Texture2D>.Get("missingMedicine", true);
}
}
<file_sep>using Harmony;
using QOLTweaksPack.rimworld;
using QOLTweaksPack.utilities;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using Verse;
using Verse.AI;
using static QOLTweaksPack.tweaks.UIRoot_Play_UIRootOnGUI_Prefix;
namespace QOLTweaksPack.tweaks
{
[HarmonyPatch(typeof(JobDriver_DoBill), "GetReport")]
static class JobDriver_DoBill_GetReport_Postfix
{
[HarmonyPostfix]
private static void GetReport(JobDriver_DoBill __instance)
{
bool isSurgery = (hasSurgeryAsJob(__instance.pawn));
//Log.Message("isSurgery:" + isSurgery + " (" + __instance.pawn.jobs.curJob.RecipeDef.workerClass + ")");
if (!isSurgery)
{
UIRoot_Play_UIRootOnGUI_Prefix.shouldDrawSurgeryRect = false;
return;
}
Bill bill = __instance.pawn.jobs.curJob.bill;
Recipe_Surgery surgery = bill.recipe.Worker as Recipe_Surgery;
Pawn surgeon = __instance.pawn;
Pawn patient = bill.billStack.billGiver as Pawn;
if (surgeon != UIRoot_Play_UIRootOnGUI_Prefix.surgeon || patient != UIRoot_Play_UIRootOnGUI_Prefix.patient)
UIRoot_Play_UIRootOnGUI_Prefix.ResetToEmpty();
Medicine medicine = null;
BodyPartRecord part = (bill as Bill_Medical).Part;
if(surgeon.CurJob.placedThings != null)
{
List<ThingStackPartClass> placedThings = surgeon.CurJob.placedThings;
for (int i = 0; i < placedThings.Count; i++)
{
if (placedThings[i].thing is Medicine)
{
medicine = placedThings[i].thing as Medicine;
break;
}
}
}
if (medicine == null)
{
if (surgeon.carryTracker.CarriedThing != null)
medicine = surgeon.carryTracker.CarriedThing as Medicine;
}
if (medicine != null)
{
cachedMedicine = medicine;
}
SurgeryOdds data = new SurgeryOdds() {};
SurgeryFailChance(data, surgeon, patient, cachedMedicine, part, surgery);
}
private static void SurgeryFailChance(SurgeryOdds data, Pawn surgeon, Pawn patient, Medicine medicine, BodyPartRecord part, Recipe_Surgery surgery)
{
float num = 1f;
num *= surgeon.GetStatValue((!patient.RaceProps.IsMechanoid) ? StatDefOf.MedicalSurgerySuccessChance : StatDefOf.MechanoidOperationSuccessChance, true);
Room room = patient.GetRoom(RegionType.Set_Passable);
if (room != null && !patient.RaceProps.IsMechanoid)
{
num *= room.GetStat(RoomStatDefOf.SurgerySuccessChanceFactor);
}
num *= GetMedicalPotency(medicine);
num *= surgery.recipe.surgerySuccessChanceFactor;
calculateChances(num, surgery.recipe.deathOnFailedSurgeryChance, ref data);
SetSurgeryChancesForDisplay(data, surgeon, patient);
}
private static void SetSurgeryChancesForDisplay(SurgeryOdds data, Pawn surgeon, Pawn patient)
{
UIRoot_Play_UIRootOnGUI_Prefix.shouldDrawSurgeryRect = true;
UIRoot_Play_UIRootOnGUI_Prefix.sentSurgeryOdds = data;
UIRoot_Play_UIRootOnGUI_Prefix.surgeon = surgeon;
UIRoot_Play_UIRootOnGUI_Prefix.patient = patient;
}
public static void calculateChances(float randNum, float deathOdds, ref SurgeryOdds data)
{
if (randNum > 1f)
randNum = 1f;
data.chanceSuccess = randNum;
data.chanceFailDeadly = (1f - data.chanceSuccess) * deathOdds;
float evens = ((1f - data.chanceSuccess) * (1f - deathOdds)) / 2f;
data.chanceFailRidiculous = evens * 0.1f;
data.chanceFailCatastrophic = evens * 0.9f;
data.chanceFailMinor = evens;
}
private static float GetMedicalPotency(Medicine medicine)
{
return 1f;
//TODO: remove when the bug is fixed
if (medicine == null)
{
return 1f;
}
//herbal: 0.6
//regular: 1.0
//glitterworld: 2.2
return medicine.GetStatValue(StatDefOf.MedicalPotency, true);
}
}
[HarmonyPatch(typeof(UIRoot_Play), "UIRootOnGUI")]
static class UIRoot_Play_UIRootOnGUI_Prefix
{
public struct SurgeryOdds
{
public float chanceSuccess;
public float chanceFailMinor;
public float chanceFailCatastrophic;
public float chanceFailRidiculous;
public float chanceFailDeadly;
public void Clamp(float min, float max)
{
chanceSuccess = chanceSuccess.Clamp(min, max);
chanceFailMinor = chanceFailMinor.Clamp(min, max);
chanceFailCatastrophic = chanceFailCatastrophic.Clamp(min, max);
chanceFailRidiculous = chanceFailRidiculous.Clamp(min, max);
chanceFailDeadly = chanceFailDeadly.Clamp(min, max);
}
public SurgeryOdds addSpec(float addition)
{
float newChanceSuccess = chanceSuccess + addition;
SurgeryOdds newOdds = new SurgeryOdds();
if (newChanceSuccess >= 1f)
{
newOdds.chanceSuccess = 1f; //div by 0 protection
newOdds.chanceFailMinor = 0;
newOdds.chanceFailCatastrophic = 0;
newOdds.chanceFailRidiculous = 0;
newOdds.chanceFailDeadly = 0;
return newOdds;
}
if (newChanceSuccess <= 0f)
{
newChanceSuccess = 0f;
}
float mult = (1f - newChanceSuccess) / (1f - chanceSuccess);
newOdds.chanceSuccess = newChanceSuccess;
newOdds.chanceFailMinor = chanceFailMinor * mult;
newOdds.chanceFailCatastrophic = chanceFailCatastrophic * mult;
newOdds.chanceFailRidiculous = chanceFailRidiculous * mult;
newOdds.chanceFailDeadly = chanceFailDeadly * mult;
return newOdds;
}
public SurgeryOdds multSpec(float mod)
{
float newChanceSuccess = chanceSuccess + (1f - chanceSuccess) * mod;
//float diff = newChanceSuccess - chanceSuccess;
float mult = (1f - mod);
SurgeryOdds newOdds = new SurgeryOdds();
newOdds.chanceSuccess = newChanceSuccess;
newOdds.chanceFailMinor = chanceFailMinor * mult;
newOdds.chanceFailCatastrophic = chanceFailCatastrophic * mult;
newOdds.chanceFailRidiculous = chanceFailRidiculous * mult;
newOdds.chanceFailDeadly = chanceFailDeadly * mult;
return newOdds;
}
}
public static bool shouldDrawSurgeryRect = false;
public static Pawn surgeon = null;
public static Pawn patient = null;
public static Medicine cachedMedicine = null;
public static SurgeryOdds sentSurgeryOdds;
private const float InfoboxHeight = 100f;
private const float InfoboxWidth = 172f;
private const float InfoboxItemWidth = 42f;
private const float InfoboxVerticalOffset = 80f;
private const float ReportBarStart = 5f;
private const float ReportBarEnd = 5f;
private const float ReportBarHeight = 15f;
private const float ReportBarOffset = 2f;
private const float ReportTextOffsetVert = 3f;
private const float ReportTextOffsetHori = 5f;
private static readonly Color BarColorSuccess = new Color(0.0f, 0.8f, 0.0f, 0.75f);
private static readonly Color BarColorFailMinor = new Color(0.8f, 0.8f, 0.0f, 0.75f);
private static readonly Color BarColorFailCatastrophic = new Color(0.8f, 0.4f, 0.0f, 0.75f);
private static readonly Color BarColorFailRidiculous = new Color(0.8f, 0.0f, 0.0f, 0.75f);
private static readonly Color BarColorFailDeadly = new Color(0.8f, 0.0f, 0.4f, 0.75f);
private static readonly Color TextColorSuccess = new Color(0.3f, 1.0f, 0.3f, 1f);
private static readonly Color TextColorFailMinor = new Color(1.0f, 1.0f, 0.3f, 1f);
private static readonly Color TextColorFailCatastrophic = new Color(1.0f, 0.7f, 0.3f, 1f);
private static readonly Color TextColorFailRidiculous = new Color(1.0f, 0.3f, 0.3f, 1f);
private static readonly Color TextColorFailDeadly = new Color(1.0f, 0.3f, 0.7f, 1f);
[HarmonyPrefix]
private static void UIRootOnGUI()
{
if (!shouldDrawSurgeryRect)
return;
else
{
CameraZoomRange zoom = Find.CameraDriver.CurrentZoom;
if (!(zoom == CameraZoomRange.Closest || zoom == CameraZoomRange.Close))
return;
Vector2 pawnPosScreenSpace = patient.DrawPos.MapToUIPosition();
Rect surgeryRect = new Rect(pawnPosScreenSpace.x - InfoboxWidth / 2f, (pawnPosScreenSpace.y - (InfoboxHeight / 2f)) - InfoboxVerticalOffset, InfoboxWidth, InfoboxHeight);
WidgetsExtensions.DrawWindowBackgroundTransparent(surgeryRect,0.75f);
float bottom;
WidgetsExtensions.DrawGadgetWindowLabel("SurgeryEstimateWindowLabel".Translate(), surgeryRect, Color.white, out bottom);
WidgetsExtensions.DrawHorizontalDivider(surgeryRect, bottom);
Rect innerRect = new Rect(surgeryRect);
innerRect.y += bottom;
innerRect.height -= bottom;
innerRect = innerRect.ContractedBy(1f);
Rect medicineRect = new Rect(innerRect);
medicineRect.width = 42;
Rect reportRect = new Rect(innerRect);
reportRect.width = reportRect.width - InfoboxItemWidth;
reportRect.x = reportRect.x + InfoboxItemWidth;
WidgetsExtensions.DrawGadgetWindowLabel("UsingMedicineKind".Translate(), medicineRect, Color.white, out bottom);
GUI.color = Color.white;
Rect itemIconRect = new Rect(medicineRect.x + 5, medicineRect.yMax - ((InfoboxItemWidth - 10) + 5), 32, 32);
if (cachedMedicine != null)
Widgets.ThingIcon(itemIconRect, cachedMedicine.def);
else
{
GUI.DrawTexture(itemIconRect, TextureResources.missingMedicine);
}
WidgetsExtensions.DrawVerticalDivider(reportRect, 0);
DrawReport(reportRect);
}
}
private static void DrawReport(Rect reportRect)
{
GameFont activeFont = Text.Font;
Text.Font = GameFont.Small;
bool detailed = false;
switch (QOLTweaksPack.SurgeryEstimationMode.Value)
{
case QOLTweaksPack.SurgeryEstimateMode.AlwaysAccurate:
detailed = true;
break;
case QOLTweaksPack.SurgeryEstimateMode.AccurateIfDoctor:
detailed = (surgeon.skills.GetSkill(SkillDefOf.Medicine).Level >= 5) ? true : false;
break;
case QOLTweaksPack.SurgeryEstimateMode.AccurateIfGoodDoctor:
detailed = (surgeon.skills.GetSkill(SkillDefOf.Medicine).Level >= 10) ? true : false;
break;
case QOLTweaksPack.SurgeryEstimateMode.AccurateIfAmazingDoctor:
detailed = (surgeon.skills.GetSkill(SkillDefOf.Medicine).Level >= 15) ? true : false;
break;
case QOLTweaksPack.SurgeryEstimateMode.NeverAccurate:
detailed = false;
break;
}
//Log.Message("chances:" + surgeryOdds.chanceSuccess + " " + surgeryOdds.chanceFailMinor + " " + surgeryOdds.chanceFailCatastrophic + " " + surgeryOdds.chanceFailRidiculous + " " + surgeryOdds.chanceFailDeadly);
Color textColor;
string text;
bool usesSpecialText;
bool usesSpecialColor;
SurgeryOdds surgeryOdds = ModifiedOdds(sentSurgeryOdds, surgeon, patient, out usesSpecialText, out usesSpecialColor, out text, out textColor);
if (detailed)
{
float acc = 0;
float diff = reportRect.width - ReportBarStart - ReportBarEnd;
Rect reportTextRect = new Rect(reportRect.x, reportRect.y, reportRect.width, reportRect.height - (ReportBarHeight + ReportBarOffset * 2));
float oneTextWidth = (reportTextRect.width - 4) / 3f;
float oneTextHeight = (reportTextRect.height - 4) / 2f;
if (surgeryOdds.chanceSuccess > 0.0f)
{
GUI.color = BarColorSuccess;
GUI.DrawTexture(new Rect(reportRect.x + ReportBarStart + (diff * acc), reportRect.yMax - (ReportBarHeight + ReportBarOffset), diff * surgeryOdds.chanceSuccess, ReportBarHeight), BaseContent.WhiteTex);
GUI.color = TextColorSuccess;
Rect localRect = new Rect(reportTextRect.x + ReportTextOffsetHori, reportTextRect.y + ReportTextOffsetVert, oneTextWidth, oneTextHeight);
GUI.Label(localRect, ((Mathf.Round(surgeryOdds.chanceSuccess * 100)).ToString("F0") + "%"));
TooltipHandler.TipRegion(localRect, "Surgery_detailedMouseover_OddsOfSuccess".Translate());
acc += surgeryOdds.chanceSuccess;
}
if (surgeryOdds.chanceFailMinor > 0.0f)
{
GUI.color = BarColorFailMinor;
GUI.DrawTexture(new Rect(reportRect.x + ReportBarStart + (diff * acc), reportRect.yMax - (ReportBarHeight + ReportBarOffset), diff * surgeryOdds.chanceFailMinor, ReportBarHeight), BaseContent.WhiteTex);
GUI.color = TextColorFailMinor;
Rect localRect = new Rect(reportTextRect.x + ReportTextOffsetHori + oneTextWidth, reportTextRect.y + ReportTextOffsetVert, oneTextWidth, oneTextHeight);
GUI.Label(localRect, ((Mathf.Round(surgeryOdds.chanceFailMinor * 100)).ToString("F0") + "%"));
TooltipHandler.TipRegion(localRect, "Surgery_detailedMouseover_OddsOfFailMinor".Translate());
acc += surgeryOdds.chanceFailMinor;
}
if (surgeryOdds.chanceFailCatastrophic > 0.0f)
{
GUI.color = BarColorFailCatastrophic;
GUI.DrawTexture(new Rect(reportRect.x + ReportBarStart + (diff * acc), reportRect.yMax - (ReportBarHeight + ReportBarOffset), diff * surgeryOdds.chanceFailCatastrophic, ReportBarHeight), BaseContent.WhiteTex);
GUI.color = TextColorFailCatastrophic;
Rect localRect = new Rect(reportTextRect.x + ReportTextOffsetHori + oneTextWidth * 2, reportTextRect.y + ReportTextOffsetVert, oneTextWidth, oneTextHeight);
GUI.Label(localRect, ((Mathf.Round(surgeryOdds.chanceFailCatastrophic * 100)).ToString("F0") + "%"));
TooltipHandler.TipRegion(localRect, "Surgery_detailedMouseover_OddsOfFailCatastrophic".Translate());
acc += surgeryOdds.chanceFailCatastrophic;
}
if (surgeryOdds.chanceFailRidiculous > 0.0f)
{
GUI.color = BarColorFailRidiculous;
GUI.DrawTexture(new Rect(reportRect.x + ReportBarStart + (diff * acc), reportRect.yMax - (ReportBarHeight + ReportBarOffset), diff * surgeryOdds.chanceFailRidiculous, ReportBarHeight), BaseContent.WhiteTex);
GUI.color = TextColorFailRidiculous;
Rect localRect = new Rect(reportTextRect.x + ReportTextOffsetHori + oneTextWidth, reportTextRect.y + ReportTextOffsetVert + oneTextHeight, oneTextWidth, oneTextHeight);
GUI.Label(localRect, ((Mathf.Round(surgeryOdds.chanceFailRidiculous * 100)).ToString("F0") + "%"));
TooltipHandler.TipRegion(localRect, "Surgery_detailedMouseover_OddsOfFailRidiculous".Translate());
acc += surgeryOdds.chanceFailRidiculous;
}
if(surgeryOdds.chanceFailDeadly > 0.0f)
{
GUI.color = BarColorFailDeadly;
GUI.DrawTexture(new Rect(reportRect.x + ReportBarStart + (diff * acc), reportRect.yMax - (ReportBarHeight + ReportBarOffset), diff * surgeryOdds.chanceFailDeadly, ReportBarHeight), BaseContent.WhiteTex);
GUI.color = TextColorFailDeadly;
Rect localRect = new Rect(reportTextRect.x + ReportTextOffsetHori + oneTextWidth * 2, reportTextRect.y + ReportTextOffsetVert + oneTextHeight, oneTextWidth, oneTextHeight);
GUI.Label(localRect, ((Mathf.Round(surgeryOdds.chanceFailDeadly * 100)).ToString("F0") + "%"));
TooltipHandler.TipRegion(localRect, "Surgery_detailedMouseover_OddsOfFailDeadly".Translate());
acc += surgeryOdds.chanceFailDeadly;
}
GUI.color = Color.white;
}
else
{
float assumedOdds = surgeryOdds.chanceSuccess + surgeryOdds.chanceFailMinor * MinorFailAllowanceMult;
if (assumedOdds < ImpossibleOdds)
{
if (!usesSpecialText) text = ImpossibleOddsText;
if (!usesSpecialColor) textColor = ImpossibleOddsColor;
}
else if (assumedOdds < TerribleOdds)
{
if (!usesSpecialText) text = TerribleOddsText;
if (!usesSpecialColor) textColor = TerribleOddsColor;
}
else if (assumedOdds < BadOdds)
{
if (!usesSpecialText) text = BadOddsText;
if (!usesSpecialColor) textColor = BadOddsColor;
}
else if (assumedOdds < AcceptableOdds)
{
if (!usesSpecialText) text = AcceptableOddsText;
if (!usesSpecialColor) textColor = AcceptableOddsColor;
}
else if (assumedOdds < GoodOdds)
{
if (!usesSpecialText) text = GoodOddsText;
if (!usesSpecialColor) textColor = GoodOddsColor;
}
else if (assumedOdds < GreatOdds)
{
if (!usesSpecialText) text = GreatOddsText;
if (!usesSpecialColor) textColor = GreatOddsColor;
}
else
{
if (!usesSpecialText) text = AmazingOddsText;
if (!usesSpecialColor) textColor = AmazingOddsColor;
}
float bottom;
reportRect = reportRect.ContractedBy(2f);
WidgetsExtensions.DrawGadgetWindowLabel(text.Translate(), reportRect, textColor, out bottom);
}
Text.Font = activeFont;
}
private static SurgeryOdds ModifiedOdds(SurgeryOdds surgeryOdds, Pawn surgeon, Pawn patient, out bool usesSpecialText, out bool usesSpecialColor, out string specialText, out Color specialColor)
{
if (!QOLTweaksPack.SurgeryEstimateAccountForTraits)
{
usesSpecialText = false;
usesSpecialColor = false;
specialText = "";
specialColor = Color.white;
return surgeryOdds;
}
else
{
//Log.Message("trait check");
float skillMod = ((20f - surgeon.skills.GetSkill(SkillDefOf.Medicine).Level) / 20f);
//first apply modifiers
/*foreach(Trait trait in surgeon.story.traits.allTraits)
{
Log.Message(trait.Label);
}*/
if (surgeon.story.traits.HasTrait(TraitDefOf.NaturalMood))
{
float addition = (surgeon.story.traits.GetTrait(TraitDefOf.NaturalMood).Degree * 0.2f * skillMod);
surgeryOdds = surgeryOdds.addSpec(addition);
//Log.Message("modified odds by " + addition + " due to mood trait");
}
if (surgeon.story.traits.HasTrait(TraitDefOf.Psychopath)
|| (surgeon.story.traits.HasTrait(TraitDefOf.Bloodlust) && patient.Faction != null && !patient.Faction.IsPlayer))
{
usesSpecialText = true;
usesSpecialColor = true;
specialText = "SurgerySpecial_Psychopath";
specialColor = new Color(0.9f, 0.1f, 0.1f);
float mult = skillMod;
surgeryOdds = surgeryOdds.multSpec(mult);
//Log.Message("modified odds by " + mult + " due to psychopath trait");
return surgeryOdds;
}
usesSpecialText = false;
usesSpecialColor = false;
specialText = "";
specialColor = Color.white;
return surgeryOdds;
}
}
private const float MinorFailAllowanceMult = 1f / 3f;
private const float ImpossibleOdds = 0.15f;
private const string ImpossibleOddsText = "Surgery_ImpossibleOdds";
private static Color ImpossibleOddsColor = new Color(0.7f, 0.1f, 0.1f);
private const float TerribleOdds = 0.3f;
private const string TerribleOddsText = "Surgery_TerribleOdds";
private static Color TerribleOddsColor = new Color(1.0f, 0.3f, 0.3f);
private const float BadOdds = 0.45f;
private const string BadOddsText = "Surgery_BadOdds";
private static Color BadOddsColor = new Color(1.0f, 0.7f, 0.3f);
private const float AcceptableOdds = 0.6f;
private const string AcceptableOddsText = "Surgery_AcceptableOdds";
private static Color AcceptableOddsColor = new Color(1.0f, 1.0f, 0.3f);
private const float GoodOdds = 0.75f;
private const string GoodOddsText = "Surgery_GoodOdds";
private static Color GoodOddsColor = new Color(0.7f, 1.0f, 0.3f);
private const float GreatOdds = 0.9f;
private const string GreatOddsText = "Surgery_GreatOdds";
private static Color GreatOddsColor = new Color(0.3f, 1.0f, 0.3f);
private const float AmazingOdds = 1.0f;
private const string AmazingOddsText = "Surgery_AmazingOdds";
private static Color AmazingOddsColor = new Color(0.3f, 1.0f, 0.7f);
internal static void Validate()
{
if(surgeon == null || Find.Selector.FirstSelectedObject != surgeon || !hasSurgeryAsJob(surgeon))
{
ResetToEmpty();
}
}
public static void ResetToEmpty()
{
surgeon = null;
patient = null;
cachedMedicine = null;
shouldDrawSurgeryRect = false;
}
public static bool hasSurgeryAsJob(Pawn pawn)
{
if (pawn.jobs == null || pawn.jobs.curJob == null || pawn.jobs.curJob.bill == null || pawn.jobs.curJob.RecipeDef == null || pawn.jobs.curJob.RecipeDef.workerClass == null)
return false;
return pawn.jobs.curJob.RecipeDef.workerClass.IsSubclassOf(typeof(Recipe_Surgery)) || pawn.jobs.curJob.RecipeDef.workerClass == typeof(Recipe_Surgery);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QOLTweaksPack.utilities
{
public static class Extensions
{
public static float Clamp(this float val, float min, float max)
{
float newVal = val;
if (newVal < min)
newVal = min;
if (newVal > max)
newVal = max;
return newVal;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using Verse;
namespace QOLTweaksPack.utilities
{
class WidgetsExtensions
{
private static Color WindowBGFillColor = new ColorInt(21, 25, 29).ToColor;
private static Color WindowBGBorderColor = new ColorInt(97, 108, 122).ToColor;
public static void DrawWindowBackgroundTransparent(Rect rect, float alpha)
{
GUI.color = WindowBGFillColor;
GUI.color = new Color(GUI.color.r, GUI.color.g, GUI.color.b, alpha);
GUI.DrawTexture(rect, BaseContent.WhiteTex);
GUI.color = WindowBGBorderColor;
Widgets.DrawBox(rect, 1);
GUI.color = Color.white;
}
public static void DrawHorizontalDivider(Rect rect, float yPos)
{
GUI.color = WindowBGBorderColor;
GUI.DrawTexture(new Rect(rect.x, rect.y + yPos, rect.width, 1), BaseContent.WhiteTex);
GUI.color = Color.white;
}
public static void DrawVerticalDivider(Rect rect, float xPos)
{
GUI.color = WindowBGBorderColor;
GUI.DrawTexture(new Rect(rect.x + xPos, rect.y, 1, rect.height), BaseContent.WhiteTex);
GUI.color = Color.white;
}
public static void DrawGizmoLabel(string labelText, Rect gizmoRect)
{
var labelHeight = Text.CalcHeight(labelText, gizmoRect.width);
labelHeight -= 2f;
var labelRect = new Rect(gizmoRect.x, gizmoRect.yMax - labelHeight + 12f, gizmoRect.width, labelHeight);
GUI.DrawTexture(labelRect, TexUI.GrayTextBG);
GUI.color = Color.white;
Text.Anchor = TextAnchor.UpperCenter;
Widgets.Label(labelRect, labelText);
Text.Anchor = TextAnchor.UpperLeft;
GUI.color = Color.white;
}
public static void DrawGadgetWindowLabel(string labelText, Rect windowRect, Color color, out float bottom)
{
var labelHeight = Text.CalcHeight(labelText, windowRect.width);
labelHeight -= 2f;
var labelRect = new Rect(windowRect.x, windowRect.y, windowRect.width, labelHeight);
//GUI.DrawTexture(labelRect, TexUI.GrayTextBG);
GUI.color = color;
Text.Anchor = TextAnchor.UpperCenter;
Widgets.Label(labelRect, labelText);
Text.Anchor = TextAnchor.UpperLeft;
GUI.color = Color.white;
bottom = labelHeight;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Verse;
using Verse.AI;
using Verse.Sound;
namespace QOLTweaksPack.rimworld
{
class JobDriver_PickupObject : JobDriver
{
[DebuggerHidden]
protected override IEnumerable<Toil> MakeNewToils()
{
Toil reserveItem = Toils_Reserve.Reserve(TargetIndex.A, 1, -1, null);
yield return reserveItem;
yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch).FailOnDespawnedNullOrForbidden(TargetIndex.A);
yield return Toils_Haul.StartCarryThing(TargetIndex.A);
yield return Toils_Haul.CheckForGetOpportunityDuplicate(reserveItem, TargetIndex.A, TargetIndex.None, true);
yield return Toils_General.Wait(500).FailOnDestroyedNullOrForbidden(TargetIndex.A).WithProgressBarToilDelay(TargetIndex.A, false, -0.5f);
}
}
}
<file_sep>using HugsLib.Settings;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using Verse;
using Verse.Sound;
namespace QOLTweaksPack.hugsLibSettings
{
class SettingUIs
{
private const float ContentPadding = 5f;
private const float MinGizmoSize = 75f;
private const float IconSize = 32f;
private const float IconGap = 1f;
private const float TextMargin = 20f;
private const float BottomMargin = 2f;
private static readonly Color iconBaseColor = new Color(0.5f, 0.5f, 0.5f, 1f);
private static readonly Color iconMouseOverColor = new Color(0.6f, 0.6f, 0.4f, 1f);
private static readonly Color SelectedOptionColor = new Color(0.5f, 1f, 0.5f, 1f);
private static readonly Color constGrey = new Color(0.8f, 0.8f, 0.8f, 1f);
private static List<ThingDef> meals;
internal static List<ThingDef> Meals { get
{
if (meals != null)
return meals;
meals = new List<ThingDef>();
foreach (ThingDef def in DefDatabase<ThingDef>.AllDefs)
{
if (def.IsWithinCategory(ThingCategoryDefOf.FoodMeals))
meals.Add(def);
}
return meals;
}
}
public static bool HugsDrawerRebuild_Checkbox(SettingHandle<bool> handle, Rect controlRect, Color background)
{
drawBackground(controlRect, background);
const float defaultCheckboxHeight = 24f;
var checkOn = handle.Value;
Widgets.Checkbox(controlRect.x, controlRect.y + (controlRect.height - defaultCheckboxHeight) / 2, ref checkOn);
if (checkOn != handle.Value)
{
handle.Value = checkOn;
return true;
}
return false;
}
internal enum ExpansionMode { None, Vertical, Horizontal };
internal static bool CustomDrawer_Enumlist(SettingHandle handle, Rect controlRect, string[] enumNames, float[] forcedWidths, bool alsoMouseovers, ExpansionMode expansionMode, Color background)
{
drawBackground(controlRect, background);
if (enumNames == null) return false;
if (enumNames.Length != forcedWidths.Length) return false;
if (expansionMode == ExpansionMode.Horizontal)
throw new NotImplementedException("Horizontal scrolling not yet implemented.");
float buttonWidth = controlRect.width;
int forcedButtons = 0;
for (int i = 0; i < forcedWidths.Length; i++)
{
if (forcedWidths[i] != 0f)
{
forcedButtons++;
buttonWidth -= forcedWidths[i];
}
}
if (forcedButtons != enumNames.Length)
buttonWidth /= (float)(enumNames.Length - forcedButtons);
float position = controlRect.position.x;
bool changed = false;
for (int i = 0; i < enumNames.Length; i++)
{
float width = (forcedWidths[i] == 0f) ? buttonWidth : forcedWidths[i];
Rect buttonRect = new Rect(controlRect);
buttonRect.position = new Vector2(position, buttonRect.position.y);
buttonRect.width = width;
//buttonRect = buttonRect.ContractedBy(2f);
bool interacted = false;
bool selected = handle.StringValue.Equals(enumNames[i]);
string label = (handle.EnumStringPrefix + enumNames[i]).Translate();
string mouseOver = (handle.EnumStringPrefix + enumNames[i]+"_mouseover").Translate();
if (expansionMode == ExpansionMode.Vertical)
{
float height = Text.CalcHeight(label, width);
if (handle.CustomDrawerHeight < height) handle.CustomDrawerHeight = height;
}
Color activeColor = GUI.color;
if (selected)
GUI.color = SelectedOptionColor;
if(alsoMouseovers)
TooltipHandler.TipRegion(buttonRect, mouseOver);
interacted = Widgets.ButtonText(buttonRect, label);
if (selected)
GUI.color = activeColor;
if (interacted)
{
handle.StringValue = enumNames[i];
changed = true;
}
position += width;
}
return changed;
}
internal static bool CustomDrawer_MatchingMeals_active(Rect wholeRect, SettingHandle<MealSetHandler> setting, Color background, string yesText = "Selected meals", string noText = "Other meals")
{
drawBackground(wholeRect, background);
if (setting.Value == null)
setting.Value = new MealSetHandler();
GUI.color = Color.white;
Rect leftRect = new Rect(wholeRect);
leftRect.width = leftRect.width / 2;
leftRect.height = wholeRect.height - TextMargin + BottomMargin;
leftRect.position = new Vector2(leftRect.position.x, leftRect.position.y);
Rect rightRect = new Rect(wholeRect);
rightRect.width = rightRect.width / 2;
leftRect.height = wholeRect.height - TextMargin + BottomMargin;
rightRect.position = new Vector2(rightRect.position.x + leftRect.width, rightRect.position.y);
DrawLabel(yesText, leftRect, TextMargin);
DrawLabel(noText, rightRect, TextMargin);
leftRect.position = new Vector2(leftRect.position.x, leftRect.position.y + TextMargin);
rightRect.position = new Vector2(rightRect.position.x, rightRect.position.y + TextMargin);
int iconsPerRow = (int)(leftRect.width / (IconGap + IconSize));
HashSet<string> selection = setting.Value.InnerList;
List<ThingDef> allMeals = Meals.ListFullCopy();
List<ThingDef> selectedMeals = new List<ThingDef>();
List<ThingDef> unselectedMeals = new List<ThingDef>();
foreach(ThingDef thing in allMeals)
{
if (selection.Contains(thing.defName))
selectedMeals.Add(thing);
else
unselectedMeals.Add(thing);
}
bool change = false;
int biggerRows = Math.Max((selectedMeals.Count - 1) / iconsPerRow, (unselectedMeals.Count - 1) / iconsPerRow) + 1;
setting.CustomDrawerHeight = (biggerRows * IconSize) + ((biggerRows) * IconGap) + TextMargin;
for (int i = 0; i < selectedMeals.Count; i++)
{
int collum = (i % iconsPerRow);
int row = (i / iconsPerRow);
bool interacted = DrawIconForItem(selectedMeals[i], leftRect, new Vector2(IconSize * collum + collum * IconGap, IconSize * row + row * IconGap), i);
if (interacted)
{
change = true;
selection.Remove(selectedMeals[i].defName);
i--; //to prevent skipping
}
}
for (int i = 0; i < unselectedMeals.Count; i++)
{
int collum = (i % iconsPerRow);
int row = (i / iconsPerRow);
bool interacted = DrawIconForItem(unselectedMeals[i], rightRect, new Vector2(IconSize * collum + collum * IconGap, IconSize * row + row * IconGap), i);
if (interacted)
{
change = true;
selection.Add(unselectedMeals[i].defName);
}
}
if (change)
{
setting.Value.InnerList = selection;
//Log.Message("selected list change");
}
return change;
}
private static void DrawLabel(string labelText, Rect textRect, float offset)
{
var labelHeight = Text.CalcHeight(labelText, textRect.width);
labelHeight -= 2f;
var labelRect = new Rect(textRect.x, textRect.yMin - labelHeight + offset, textRect.width, labelHeight);
GUI.DrawTexture(labelRect, TexUI.GrayTextBG);
GUI.color = Color.white;
Text.Anchor = TextAnchor.UpperCenter;
Widgets.Label(labelRect, labelText);
Text.Anchor = TextAnchor.UpperLeft;
GUI.color = Color.white;
}
private static bool DrawIconForItem(ThingDef item, Rect contentRect, Vector2 iconOffset, int buttonID)
{
var iconTex = item.uiIcon;
Graphic g = item.graphicData.Graphic;
Color color = getColor(item);
Color colorTwo = getColor(item);
Graphic g2 = item.graphicData.Graphic.GetColoredVersion(g.Shader, color, colorTwo);
var iconRect = new Rect(contentRect.x + iconOffset.x, contentRect.y + iconOffset.y, IconSize, IconSize);
string label = item.label;
TooltipHandler.TipRegion(iconRect, label);
MouseoverSounds.DoRegion(iconRect, SoundDefOf.MouseoverCommand);
if (Mouse.IsOver(iconRect))
{
GUI.color = iconMouseOverColor;
GUI.DrawTexture(iconRect, TextureResources.drawPocket);
//Graphics.DrawTexture(iconRect, TextureResources.drawPocket, new Rect(0, 0, 1f, 1f), 0, 0, 0, 0, iconMouseOverColor);
}
else
{
GUI.color = iconBaseColor;
GUI.DrawTexture(iconRect, TextureResources.drawPocket);
//Graphics.DrawTexture(iconRect, TextureResources.drawPocket, new Rect(0, 0, 1f, 1f), 0, 0, 0, 0, iconBaseColor);
}
Texture resolvedIcon;
if (!item.uiIconPath.NullOrEmpty())
{
resolvedIcon = item.uiIcon;
}
else
{
resolvedIcon = g2.MatSingle.mainTexture;
}
GUI.color = color;
GUI.DrawTexture(iconRect, resolvedIcon);
GUI.color = Color.white;
if (Widgets.ButtonInvisible(iconRect, true))
{
Event.current.button = buttonID;
return true;
}
else
return false;
}
private static Color getColor(ThingDef item)
{
if (item.graphicData != null)
{
return item.graphicData.color;
}
return Color.white;
}
private static void drawBackground(Rect rect, Color background)
{
Color save = GUI.color;
GUI.color = background;
GUI.DrawTexture(rect, TexUI.FastFillTex);
GUI.color = save;
}
}
}
<file_sep>using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Verse;
namespace QOLTweaksPack.utilities
{
static class ItemCounter
{
internal static int CountProductsWithEquivalency(Bill_Production bill, RecipeWorkerCounter counter)
{
HashSet<string> eqNames = QOLTweaksPack.MealSelection.Value.InnerList;
ThingCountClass thingCountClass = counter.recipe.products[0];
//Log.Message("Looking for equivalencies to " + thingCountClass.thingDef);
if (thingCountClass.thingDef.CountAsResource)
{
int total = 0;
foreach (string eqName in eqNames)
{
ThingDef def = DefDatabase<ThingDef>.GetNamed(eqName);
int local = bill.Map.resourceCounter.GetCount(def);
total += local;
//Log.Message("Counted " + local + " of " + def.defName);
}
return total;
}
int num = bill.Map.listerThings.ThingsOfDef(thingCountClass.thingDef).Count;
if (thingCountClass.thingDef.Minifiable)
{
List<Thing> list = bill.Map.listerThings.ThingsInGroup(ThingRequestGroup.MinifiedThing);
for (int i = 0; i < list.Count; i++)
{
MinifiedThing minifiedThing = (MinifiedThing)list[i];
if (eqNames.Contains(minifiedThing.InnerThing.def.defName))
{
num++;
}
}
}
return num;
}
}
}
|
0fe24e3958aeedf23335143b394d02d2d9fd0370
|
[
"C#"
] | 20 |
C#
|
PeteTimesSix/QOLTweaksPack
|
77fee9afddab9e2371c7f25e341e5a9370da1b05
|
cd36edad1ea4a8d92e52533ef7b54631dff2d2fa
|
refs/heads/master
|
<file_sep>package uk.co.gotenxiao.androidmpdserver;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class AndroidMPDServerService extends Service
{
private static final String LOG_TAG = "AndroidMPDServer";
private int NOTIFICATION = R.string.server_running;
MPDServer server = null;
@Override
public void onCreate()
{
Log.d(LOG_TAG, "Service starting");
}
@Override
public void onDestroy()
{
Log.d(LOG_TAG, "Service stopping");
stopServer();
}
@Override
public int onStartCommand(Intent intent, int flags, int startid)
{
startServer();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent)
{
return mBinder;
}
public class LocalBinder extends Binder
{
AndroidMPDServerService getService()
{
return AndroidMPDServerService.this;
}
}
private final IBinder mBinder = new LocalBinder();
private void showNotification()
{
CharSequence text = getText(NOTIFICATION);
Notification notification = new Notification(R.drawable.ic_stat_mpd_server, text, 0);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, AndroidMPDServerMain.class), 0);
notification.setLatestEventInfo(this, text, "", contentIntent);
startForeground(NOTIFICATION, notification);
}
public void startServer()
{
showNotification();
if (server != null && server.running)
{
return;
}
server = new MPDServer(this);
server.start();
}
public void stopServer()
{
if (server == null)
{
return;
}
server.close();
server = null;
stopForeground(true);
}
}
<file_sep>package uk.co.gotenxiao.androidmpdserver;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ToggleButton;
public class AndroidMPDServerMain extends Activity implements OnClickListener
{
private static final String LOG_TAG = "AndroidMPDServer";
private ToggleButton toggleButton = null;
private AndroidMPDServerService mService = null;
private boolean mIsBound = false;
private Intent mServiceIntent = null;
private ServiceConnection mConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
mService = ((AndroidMPDServerService.LocalBinder)service).getService();
updateButtonChecked();
}
public void onServiceDisconnected(ComponentName className)
{
mService = null;
updateButtonChecked();
}
};
void doBindService()
{
bindService(mServiceIntent, mConnection, 0);
mIsBound = true;
}
void doUnbindService()
{
if (mIsBound)
{
unbindService(mConnection);
mIsBound = false;
}
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mServiceIntent = new Intent(this, AndroidMPDServerService.class);
toggleButton = (ToggleButton) findViewById(R.id.button);
toggleButton.setOnClickListener(this);
}
@Override
public void onDestroy()
{
super.onDestroy();
if (!isRunning())
{
stopService(mServiceIntent);
}
doUnbindService();
}
@Override
public void onPause()
{
super.onPause();
}
@Override
public void onResume()
{
super.onResume();
doBindService();
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
}
public boolean isRunning()
{
return (mService != null && mService.server != null && mService.server.running);
}
public void startServer()
{
if (isRunning())
{
return;
}
startService(mServiceIntent);
}
public void stopServer()
{
if (!isRunning())
{
return;
}
stopService(mServiceIntent);
}
public void toggleServer()
{
if (!isRunning())
{
startServer();
} else
{
stopServer();
}
}
public void onClick(View v)
{
toggleServer();
}
public void updateButtonChecked()
{
toggleButton.setChecked(isRunning());
}
}
<file_sep>package uk.co.gotenxiao.androidmpdserver;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayDeque;
import android.content.Intent;
import android.content.Context;
import android.text.TextUtils.SimpleStringSplitter;
import android.util.Log;
import uk.co.gotenxiao.androidmpdserver.players.PlayerAPI;
import uk.co.gotenxiao.androidmpdserver.players.PowerAMP;
import java.util.ArrayList;
public class MPDServerWorker extends Thread
{
static final String LOG_TAG = "AndroidMPDServer";
static final int ACK_ERROR_NOT_LIST = 1;
static final int ACK_ERROR_ARG = 2;
static final int ACK_ERROR_PASSWORD = 3;
static final int ACK_ERROR_PERMISSION = 4;
static final int ACK_ERROR_UNKNOWN = 5;
static final int ACK_ERROR_NO_EXIST = 50;
static final int ACK_ERROR_PLAYLIST_MAX = 51;
static final int ACK_ERROR_SYSTEM = 52;
static final int ACK_ERROR_PLAYLIST_LOAD = 53;
static final int ACK_ERROR_UPDATE_ALREADY = 54;
static final int ACK_ERROR_PLAYER_SYNC = 55;
static final int ACK_ERROR_EXIST = 56;
static final String PROTO_MPD_ACK = "ACK [%d@%d] {%s} %s";
static final String PROTO_MPD_ALBUM = "Album";
static final String PROTO_MPD_ARTIST = "Artist";
static final String PROTO_MPD_AUDIO = "audio";
static final String PROTO_MPD_BITRATE = "bitrate";
static final String PROTO_MPD_CLOSE = "close";
static final String PROTO_MPD_COMMAND_LIST_BEGIN = "command_list_begin";
static final String PROTO_MPD_COMMAND_LIST_END = "command_list_end";
static final String PROTO_MPD_COMMAND_LIST_OK_BEGIN = "command_list_ok_begin";
static final String PROTO_MPD_COMMANDS = "commands";
static final String PROTO_MPD_CONSUME = "consume";
static final String PROTO_MPD_CROSSFADE = "crossfade";
static final String PROTO_MPD_CURRENTSONG = "currentsong";
static final String PROTO_MPD_DATE = "Date";
static final String PROTO_MPD_DELIMITER = ": ";
static final String PROTO_MPD_ELAPSED = "elapsed";
static final String PROTO_MPD_FILE = "file";
static final String PROTO_MPD_GENRE = "Genre";
static final String PROTO_MPD_HANDSHAKE = "OK MPD 0.16.0";
static final String PROTO_MPD_ID = "Id";
static final String PROTO_MPD_KILL = "kill";
static final String PROTO_MPD_LAST_MODIFIED = "Last-Modified";
static final String PROTO_MPD_LIST_OK = "list_OK";
static final String PROTO_MPD_MIXRAMPDB = "mixrampdb";
static final String PROTO_MPD_MIXRAMPDELAY = "mixrampdelay";
static final String PROTO_MPD_NAME = "Name";
static final String PROTO_MPD_NEXT = "next";
static final String PROTO_MPD_NEXTSONGID = "nextsongid";
static final String PROTO_MPD_NEXTSONG = "nextsong";
static final String PROTO_MPD_NOTCOMMANDS = "notcommands";
static final String PROTO_MPD_OK = "OK";
static final String PROTO_MPD_PAUSE = "pause";
static final String PROTO_MPD_PING = "ping";
static final String PROTO_MPD_PLAYLIST_LENGTH = "playlistlength";
static final String PROTO_MPD_PLAYLIST = "playlist";
static final String PROTO_MPD_PLAY = "play";
static final String PROTO_MPD_POS = "Pos";
static final String PROTO_MPD_PREVIOUS = "previous";
static final String PROTO_MPD_RANDOM = "random";
static final String PROTO_MPD_REPEAT = "repeat";
static final String PROTO_MPD_SETVOL = "setvol";
static final String PROTO_MPD_SINGLE = "single";
static final String PROTO_MPD_SONGID = "songid";
static final String PROTO_MPD_STATE = "state";
static final String PROTO_MPD_STATE_STOP = "stop";
static final String PROTO_MPD_STATUS = "status";
static final String PROTO_MPD_STOP = "stop";
static final String PROTO_MPD_TITLE = "Title";
static final String PROTO_MPD_TRACK_LENGTH = "Time";
static final String PROTO_MPD_TRACK = "Track";
static final String PROTO_MPD_VOLUME = "volume";
static final String PROTO_MPD_XFADE = "xfade";
private MPDServer mServer = null;
private Context mContext = null;
private Socket mSocket = null;
private BufferedReader mBufRecv = null;
private DataOutputStream mBufSend = null;
public volatile boolean running = true;
private SimpleStringSplitter mSplitter = new SimpleStringSplitter(' ');
private String mCommand = null;
private ArrayDeque<String> mCommandStack = null;
// Are we currently processing the command stack?
private boolean mProcessingCommandStack = false;
// Are we currently processing a command_list_ok_begin stack?
private boolean mCommandListOK = false;
private int mCommandStackIndex = 0;
private PlayerAPI mPlayerAPI = null;
public MPDServerWorker(MPDServer server, Context context, Socket socket)
{
mServer = server;
mContext = context;
mSocket = socket;
mCommandStack = new ArrayDeque<String>();
mPlayerAPI = new PowerAMP(mContext);
}
public void close()
{
Log.d(LOG_TAG, "Worker closing");
try
{
if (mSocket != null && !mSocket.isClosed())
{
Log.d(LOG_TAG, "Closing client socket");
mSocket.close();
}
}
catch (IOException e)
{
}
finally
{
running = false;
mSocket = null;
mServer.removeWorker(this);
}
}
private void sendServerStop()
{
mContext.stopService(new Intent(mContext, AndroidMPDServerService.class));
}
private void error(int error_num, int command_num, String command, String message)
{
String msg = String.format(PROTO_MPD_ACK, error_num, command_num, command, message);
send(msg);
}
private void error(int error_num, String command, String message)
{
int currentIdx = mCommandStack.size();
if (mProcessingCommandStack)
{
currentIdx = mCommandStackIndex;
}
error(error_num, currentIdx, command, message);
}
private void send(String message)
{
try
{
message += '\n';
Log.d(LOG_TAG, String.format("Sending message: %s", message));
mBufSend.writeBytes(message);
}
catch (IOException e)
{
Log.e(LOG_TAG, "Failed to send message", e);
}
}
private void send(String message, boolean flush)
{
send(message);
if (flush)
{
try
{
mBufSend.flush();
} catch (IOException e)
{
Log.e(LOG_TAG, "Exception raised flushing send buffer!", e);
}
}
}
private void sendField(String fieldName, int value)
{
send(String.format("%s%s%d", fieldName, PROTO_MPD_DELIMITER, value));
}
private void sendField(String fieldName, String value)
{
send(String.format("%s%s%s", fieldName, PROTO_MPD_DELIMITER, value));
}
private void sendField(String fieldName, boolean value)
{
send(String.format("%s%s%d", fieldName, PROTO_MPD_DELIMITER, value ? 1 : 0));
}
private void ok(boolean flush)
{
if (mCommandListOK)
{
send(PROTO_MPD_LIST_OK);
return;
}
if (mProcessingCommandStack)
{
return;
}
send(PROTO_MPD_OK, flush);
}
private void ok()
{
ok(false);
}
private void handleStatus()
{
int volume = 0;
int single = 0;
int consume = 0;
int playlist = 0;
int playlist_length = 0;
int crossfade = 0;
int songid = 0;
sendField(PROTO_MPD_VOLUME, volume);
sendField(PROTO_MPD_REPEAT, mPlayerAPI.repeat());
sendField(PROTO_MPD_RANDOM, mPlayerAPI.random());
sendField(PROTO_MPD_SINGLE, single);
sendField(PROTO_MPD_CONSUME, consume);
sendField(PROTO_MPD_PLAYLIST, playlist);
sendField(PROTO_MPD_PLAYLIST_LENGTH, playlist_length);
sendField(PROTO_MPD_CROSSFADE, crossfade);
sendField(PROTO_MPD_STATE, mPlayerAPI.state());
sendField(PROTO_MPD_SONGID, songid);
ok();
}
private void handleCurrentSong()
{
String filename = mPlayerAPI.filename();
int trackLength = mPlayerAPI.trackLength();
String artist = mPlayerAPI.artist();
String track = mPlayerAPI.track();
String album = mPlayerAPI.album();
int trackNo = mPlayerAPI.trackNo();
if (!filename.equals(""))
{
sendField(PROTO_MPD_FILE, mPlayerAPI.filename());
}
if (trackLength != 0)
{
sendField(PROTO_MPD_TRACK_LENGTH, mPlayerAPI.trackLength());
}
if (!artist.equals(""))
{
sendField(PROTO_MPD_ARTIST, mPlayerAPI.artist());
}
if (!track.equals(""))
{
sendField(PROTO_MPD_TITLE, mPlayerAPI.track());
}
if (!album.equals(""))
{
sendField(PROTO_MPD_ALBUM, mPlayerAPI.album());
}
if (trackNo != 0)
{
sendField(PROTO_MPD_TRACK, mPlayerAPI.trackNo());
}
sendField(PROTO_MPD_POS, 0);
sendField(PROTO_MPD_ID, 0);
ok();
}
private boolean handleCommand(String line)
{
if (!mProcessingCommandStack)
{
Log.d(LOG_TAG, String.format("Received command: %s", line));
}
mCommand = "";
line = line.trim();
if (mCommandStack.size() > 0 && !mProcessingCommandStack)
{
mCommandStack.add(line);
if (!line.equals(PROTO_MPD_COMMAND_LIST_END))
{
Log.d(LOG_TAG, "Command queued");
// Don't process any commands until we received the command list end
return true;
}
}
mSplitter.setString(line);
if (mSplitter.hasNext())
{
mCommand = mSplitter.next();
} else
{
error(ACK_ERROR_UNKNOWN, "", String.format("unknown command \"%s\"", line));
return false;
}
if (mCommand.equals(PROTO_MPD_PING))
{
ok(true);
return true;
} else if (mCommand.equals(PROTO_MPD_CLOSE))
{
close();
return true;
} else if (mCommand.equals(PROTO_MPD_KILL))
{
sendServerStop();
return true;
} else if (mCommand.equals(PROTO_MPD_COMMAND_LIST_OK_BEGIN))
{
Log.d(LOG_TAG, PROTO_MPD_COMMAND_LIST_OK_BEGIN);
mCommandStack.add(line);
return true;
} else if (mCommand.equals(PROTO_MPD_COMMAND_LIST_BEGIN))
{
Log.d(LOG_TAG, PROTO_MPD_COMMAND_LIST_BEGIN);
if (mProcessingCommandStack)
{
return false;
}
mCommandStack.add(line);
return true;
} else if (mCommand.equals(PROTO_MPD_COMMAND_LIST_END))
{
Log.d(LOG_TAG, "Processing queued commands");
mProcessingCommandStack = true;
mCommandStack.removeLast();
String startCommand = mCommandStack.removeFirst();
mCommandListOK = startCommand.equals(PROTO_MPD_COMMAND_LIST_OK_BEGIN);
boolean result = false;
boolean any_failed = false;
mCommandStackIndex = 1; // This starts at 1 to account for the missing command_list_begin
for (String list_command : mCommandStack)
{
result = handleCommand(list_command);
if (!mCommandListOK && !result)
{
mCommandStack.clear();
any_failed = true;
break;
}
mCommandStackIndex += 1;
}
mProcessingCommandStack = false;
if (!mCommandListOK)
{
if (any_failed)
{
error(ACK_ERROR_UNKNOWN, mCommandStackIndex, mCommand, "");
}
}
mCommandStack.clear();
mCommandListOK = false;
mCommandStackIndex = 0;
ok();
} else if (mCommand.equals(PROTO_MPD_STATUS))
{
handleStatus();
} else if (mCommand.equals(PROTO_MPD_CURRENTSONG))
{
handleCurrentSong();
} else if (mCommand.equals(PROTO_MPD_PLAY))
{
mPlayerAPI.play();
ok();
} else if (mCommand.equals(PROTO_MPD_PAUSE))
{
mPlayerAPI.pause();
ok();
} else if (mCommand.equals(PROTO_MPD_NEXT))
{
mPlayerAPI.next();
ok();
} else if (mCommand.equals(PROTO_MPD_PREVIOUS))
{
mPlayerAPI.previous();
ok();
} else if (mCommand.equals(PROTO_MPD_STOP))
{
mPlayerAPI.stop();
ok();
} else
{
error(ACK_ERROR_UNKNOWN, mCommand, String.format("unknown command \"%s\"", line));
}
return false;
}
public void run()
{
try
{
mBufRecv = new BufferedReader(
new InputStreamReader(
mSocket.getInputStream()
)
);
mBufSend = new DataOutputStream(
mSocket.getOutputStream()
);
send(PROTO_MPD_HANDSHAKE, true);
while (running)
{
String line = mBufRecv.readLine();
if (line != null)
{
handleCommand(line);
} else
{
break;
}
}
} catch (Exception e)
{
Log.e(LOG_TAG, "Exception raised!", e);
} finally
{
close();
}
}
}
<file_sep>package uk.co.gotenxiao.androidmpdserver.players;
import com.maxmpz.audioplayer.player.PowerAMPiAPI;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
public class PowerAMP implements PlayerAPI
{
static final String LOG_TAG = "AndroidMPDServer";
static final String ACTION_API_COMMAND = "com.maxmpz.audioplayer.API_COMMAND";
private Context mContext;
private Intent mPlayIntent;
private Intent mPauseIntent;
private Intent mPreviousIntent;
private Intent mNextIntent;
private Intent mStopIntent;
private Intent mTrackIntent;
private Intent mStatusIntent;
private Intent mPlayingModeIntent;
private BroadcastReceiver mTrackReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
mTrackIntent = intent;
mCurrentTrack = mTrackIntent.getBundleExtra(PowerAMPiAPI.TRACK);
Log.d(LOG_TAG, "Received track intent: " + intent);
}
};
private BroadcastReceiver mStatusReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
mStatusIntent = intent;
Log.d(LOG_TAG, "Received status intent: " + intent);
}
};
private BroadcastReceiver mPlayingModeReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
mPlayingModeIntent = intent;
Log.d(LOG_TAG, "Received playing mode intent: " + intent);
}
};
private Bundle mCurrentTrack;
public PowerAMP(Context context)
{
mContext = context;
mPlayIntent = (
new Intent(PowerAMPiAPI.ACTION_API_COMMAND)
.putExtra(PowerAMPiAPI.COMMAND, PowerAMPiAPI.Commands.TOGGLE_PLAY_PAUSE)
);
mPauseIntent = (
new Intent(PowerAMPiAPI.ACTION_API_COMMAND)
.putExtra(PowerAMPiAPI.COMMAND, PowerAMPiAPI.Commands.PAUSE)
);
mPreviousIntent = (
new Intent(PowerAMPiAPI.ACTION_API_COMMAND)
.putExtra(PowerAMPiAPI.COMMAND, PowerAMPiAPI.Commands.PREVIOUS)
);
mNextIntent = (
new Intent(PowerAMPiAPI.ACTION_API_COMMAND)
.putExtra(PowerAMPiAPI.COMMAND, PowerAMPiAPI.Commands.NEXT)
);
mStopIntent = (
new Intent(PowerAMPiAPI.ACTION_API_COMMAND)
.putExtra(PowerAMPiAPI.COMMAND, PowerAMPiAPI.Commands.STOP)
);
register();
}
public void register()
{
mTrackIntent = mContext.registerReceiver(mTrackReceiver, new IntentFilter(PowerAMPiAPI.ACTION_TRACK_CHANGED));
mStatusIntent = mContext.registerReceiver(mStatusReceiver, new IntentFilter(PowerAMPiAPI.ACTION_STATUS_CHANGED));
mPlayingModeIntent = mContext.registerReceiver(mPlayingModeReceiver, new IntentFilter(PowerAMPiAPI.ACTION_PLAYING_MODE_CHANGED));
}
public void unregister()
{
if (mTrackIntent != null)
{
try
{
mContext.unregisterReceiver(mTrackReceiver);
} catch (Exception e) {}
}
if (mStatusReceiver != null)
{
try
{
mContext.unregisterReceiver(mStatusReceiver);
} catch (Exception e) {}
}
if (mPlayingModeReceiver != null)
{
try
{
mContext.unregisterReceiver(mPlayingModeReceiver);
} catch (Exception e) {}
}
}
private boolean hasMetadata()
{
return (mTrackIntent != null && mCurrentTrack != null);
}
private boolean hasStatus()
{
return (mStatusIntent != null);
}
private boolean hasPlayingMode()
{
return (mPlayingModeIntent != null);
}
public void play()
{
mContext.startService(mPlayIntent);
}
public void pause()
{
mContext.startService(mPauseIntent);
}
public void previous()
{
mContext.startService(mPreviousIntent);
}
public void next()
{
mContext.startService(mNextIntent);
}
public void stop()
{
mContext.startService(mStopIntent);
}
public void setRandom(boolean random)
{
}
public boolean random()
{
if (hasPlayingMode())
{
if (mPlayingModeIntent.getIntExtra(PowerAMPiAPI.SHUFFLE, 0) != 0)
{
return true;
}
}
return false;
}
public void setRepeat(boolean repeat)
{
}
public boolean repeat()
{
if (hasPlayingMode())
{
if (mPlayingModeIntent.getIntExtra(PowerAMPiAPI.REPEAT, 0) != 0)
{
return true;
}
}
return false;
}
public String state()
{
if (hasStatus())
{
int status = mStatusIntent.getIntExtra(PowerAMPiAPI.STATUS, -1);
if (status == PowerAMPiAPI.Status.TRACK_PLAYING)
{
boolean paused = mStatusIntent.getBooleanExtra(PowerAMPiAPI.PAUSED, false);
if (paused)
{
return "pause";
} else
{
return "play";
}
}
}
return "stop";
}
public String filename()
{
if (hasMetadata())
{
return mCurrentTrack.getString(PowerAMPiAPI.Track.PATH);
}
return "";
}
public String artist()
{
if (hasMetadata())
{
return mCurrentTrack.getString(PowerAMPiAPI.Track.ARTIST);
}
return "";
}
public String album()
{
if (hasMetadata())
{
return mCurrentTrack.getString(PowerAMPiAPI.Track.ALBUM);
}
return "";
}
public int trackNo()
{
// PowerAMP API does not currently support track number.
return 0;
}
public String track()
{
if (hasMetadata())
{
return mCurrentTrack.getString(PowerAMPiAPI.Track.TITLE);
}
return "";
}
public int trackLength()
{
if (hasMetadata())
{
return mCurrentTrack.getInt(PowerAMPiAPI.Track.DURATION);
}
return 0;
}
}
<file_sep>package uk.co.gotenxiao.androidmpdserver.players;
import android.content.Context;
public interface PlayerAPI
{
public void play();
public void pause();
public void previous();
public void next();
public void stop();
public void setRandom(boolean random);
public boolean random();
public void setRepeat(boolean repeat);
public boolean repeat();
public String state();
public String filename();
public String artist();
public String album();
public int trackNo();
public String track();
public int trackLength();
}
|
d9108f5f1c44792b86eb0fac791a86e9d72c42ef
|
[
"Java"
] | 5 |
Java
|
GotenXiao/androidmpdserver
|
97f23c1af2f76c6b08e37f5683b676c7b57852f4
|
ae9b7c3e05f28e5f71b5b95b7665fe4c0c500bd1
|
refs/heads/master
|
<repo_name>EtienneAdrien/videoo-backend<file_sep>/src/dependencies.php
<?php
// DIC configuration
$container = $app->getContainer();
// view renderer
$container['renderer'] = function ($c) {
$settings = $c->get('settings')['renderer'];
return new Slim\Views\PhpRenderer($settings['template_path']);
};
// monolog
$container['logger'] = function ($c) {
$settings = $c->get('settings')['logger'];
$logger = new Monolog\Logger($settings['name']);
$logger->pushProcessor(new Monolog\Processor\UidProcessor());
$logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
return $logger;
};
$container['pdo'] = function ($c) {
$settings = $c->get('settings')['db'];
try {
$conn = new PDO("mysql:host={$settings['servername']};dbname={$settings['databaseName']};charset=utf8", $settings['username'], $settings['password']);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
echo "Connected successfully";
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
};
/**
* ROUTES CONTAINER RESOLUTION
*/
$container['AuthController'] = function ($c) {
$jwt = new \Firebase\JWT\JWT();
$settings = $c->get('settings')['jwt'];
$pdo = $c->get('pdo');
return new App\Controllers\AuthController($jwt, $settings, $pdo);
};
$container['UsersController'] = function ($c) {
$pdo = $c->get('pdo');
return new App\Controllers\UsersController($pdo);
};
$container['TemplatesController'] = function ($c) {
$pdo = $c->get('pdo');
return new App\Controllers\TemplatesController($pdo);
};<file_sep>/src/Controllers/TemplatesController.php
<?php
namespace App\Controllers;
use App\Models\Templates as Model;
class TemplatesController
{
function __construct($pdo)
{
$this->pdo = $pdo;
}
public function addTemplate($req, $res, $args)
{
$files = $req->getUploadedFiles();
$params = $req->getParsedBody();
if($files) {
return $res->withJson(["Files" => $files, "Params" => $params]);
} else {
return $res->withJson($req->GetParsedBody());
}
}
public function getTemplates($req, $res, $args)
{
return $res->withJson(Model::getAll($this->pdo));
}
public function getTemplate($req, $res, $args) {
$id = $args['id'];
return $res->withJson(Model::get($this->pdo, $id));
}
public function removeTemplate($req, $res, $args) {
$id = $args['id'];
return $res->withJson(Model::delete($this->pdo, $id));
}
}
<file_sep>/src/Controllers/AuthController.php
<?php
namespace App\Controllers;
use App\Models\User as User;
class AuthController
{
function __construct($jwt, $settings, $pdo) {
$this->jwt = $jwt;
$this->settings = $settings;
$this->pdo = $pdo;
}
public function login($req, $res, $args)
{
$params = $req->getParsedBody();
$user = new User($this->pdo, $params['email'], $params['password']);
/**
* Return an error if the fields are not filled or if the user doesn't exist
*/
if(
!isset($params['email'], $params['password']) ||
!$user->exist
)
return $res->withStatus(400);
$privateKey = $this->settings['privateKey'];
$token = array(
"iss" => $this->settings['iss'],
"iat" => time(),
"nbf" => time(),
"typ" => 'JWT',
"name" => $user->info['username']
);
/**
* IMPORTANT:
* You must specify supported algorithms for your application. See
* https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
* for a list of spec-compliant algorithms.
*/
$jwt = $this->jwt::encode($token, $privateKey, 'HS256');
return $res->withJson(array('token' => $jwt));
}
public function signUp($req, $res, $args)
{
}
}
<file_sep>/src/Models/Templates.php
<?php
namespace App\Models;
class Templates
{
function __construct()
{
}
public static function getAll($pdo) {
$stmt = $pdo->prepare('SELECT * FROM templates');
$stmt->execute();
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $results;
}
public static function get($pdo, $id) {
$stmt = $pdo->prepare('SELECT * FROM templates WHERE id = :id');
$stmt->execute(["id" => $id]);
$results = $stmt->fetch(\PDO::FETCH_ASSOC);
return $results;
}
public static function delete($pdo, $id) {
$stmt = $pdo->prepare('DELETE FROM templates WHERE id = :id');
$result = $stmt->execute(array(
"id" => $id
));
return $result;
}
}<file_sep>/src/Models/User.php
<?php
namespace App\Models;
class User
{
public $info;
public $exist;
function __construct($pdo, $email, $password) {
$this->pdo = $pdo;
$this->init($email, $password);
}
private function init($email, $password)
{
$stmt = $this->pdo->prepare('SELECT * FROM users WHERE mail = :email');
$stmt->execute(array(
'email' => $email,
));
$result = $stmt->fetch(\PDO::FETCH_ASSOC);
if(
$result === false ||
/** Check if the password sent by the user is the same as in the database */
password_verify($password, $result['password']) === false
)
$this->info = false;
$this->exist = false;
$this->info = $result;
$this->exist = true;
}
public static function getAll($pdo)
{
$stmt = $pdo->prepare('SELECT id, username, mail, type FROM users');
$stmt->execute();
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $results;
}
public static function remove($pdo, $id) {
$stmt = $pdo->prepare('DELETE FROM users WHERE id = :id');
$stmt->execute(array(
"id" => $id
));
}
public static function add($pdo, $params)
{
$stmt = $pdo->prepare('INSERT INTO users (username, password, mail, type) VALUES (:username, :password, :mail, :type)');
$stmt->execute(array(
"username" => $params['username'],
"password" => $params['<PASSWORD>'],
"mail" => $params['mail'],
"type" => $params['type']
));
return $pdo->lastInsertId();
}
public static function exist($pdo, $mail) {
$stmt = $pdo->prepare('SELECT id FROM users WHERE mail = :mail');
$stmt->execute(array("mail" => $mail));
$result = $stmt->fetch(\PDO::FETCH_ASSOC);
return ($result) ? true : false;
}
public static function update($pdo, $params) {
$id = $params['id'];
unset($params['id']);
$keys = array_keys($params);
$values = array_values($params);
$values[] = $id;
$stmt = $pdo->prepare('UPDATE users SET ' . join(' = ?, ', $keys) . ' = ?' . 'WHERE id = ?');
$stmt->execute($values);
}
}<file_sep>/src/Controllers/UsersController.php
<?php
namespace App\Controllers;
use App\Models\User as User;
class UsersController
{
function __construct($pdo) {
$this->pdo = $pdo;
}
public function getUsers($req, $res, $args) {
return $res->withJson(User::getAll($this->pdo));
}
public function addUser($req, $res, $args) {
$params = $req->getParsedBody();
if(User::exist($this->pdo, $params['mail'])) {
return $res->withJson(["error" => "Nom ou mail indisponnible"]);
}
$id = User::add($this->pdo, $params);
return $res->withJson(["success" => "Le compte a été créer", "id" => $id]);
}
public function removeUser($req, $res, $args) {
$id = $args['id'];
User::remove($this->pdo, $id);
}
public function updateUser($req, $res, $args) {
$id = $args['id'];
$params = $req->getParsedBody();
if(!User::exist($this->pdo, $params['mail'])) {
return $req->withJson(['error' => "L'utilisateur n'existe pas"]);
}
User::update($this->pdo, $params);
}
}
|
67d23336c1b6d1484dbad1e328cd93094c7ee86a
|
[
"PHP"
] | 6 |
PHP
|
EtienneAdrien/videoo-backend
|
aefadc4eb0cfac1c24142d31c46586090b72d18d
|
f581a983c6909be1af7b0188b1a690d4c1b53913
|
refs/heads/main
|
<file_sep>// COIN
export interface ICoin {
Symbol: string
Price: string
}
export type CoinState = {
coins: ICoin[]
lastCoin: ICoin
}
export type CoinAction = {
type: string
coin: ICoin
}
// THEME
export enum Mode {
dark = 'dark',
light = 'light',
system = 'system'
}
export interface ITheme {
mode: Mode
}
export type ThemeState = {
mode: Mode
}
export type ThemeAction = {
type: string
theme: ITheme
}
// UI
export type UIState = {
settings: boolean
}
export type UIAction = {
type: string
ui: UIState
}
export type DispatchCoin = (args: CoinAction) => CoinAction
export type DispatchTheme = (args: ThemeAction) => ThemeAction
export type DispatchUI = (args: UIAction) => UIAction<file_sep>export { default as RenderLineChart } from './LineChart'<file_sep>package utils
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"github.com/sarmirim/ebisu/settings"
)
type Coin struct {
Symbol string `json:"symbol"`
Price string `json:"price"`
}
func Price(symbol string) Coin {
client := &http.Client{}
coin := Coin{}
symbol = strings.ToUpper(symbol)
if len(symbol) < 5 {
symbol = symbol + "USDT"
}
link := fmt.Sprintf("https://api.binance.com/api/v3/ticker/price?symbol=%s", symbol)
req, err := http.NewRequest("GET", link, nil)
if err != nil {
println(err)
return Coin{}
}
req.Header.Set("User-Agent", "Ebisu")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
return Coin{}
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return Coin{}
}
jsonErr := json.Unmarshal(body, &coin)
if jsonErr != nil {
return Coin{}
}
println("Symbol=", coin.Symbol, "Price=", coin.Price)
return coin
}
func Time() map[string]int64 {
body := GetToData("https://api.binance.com/api/v3/time")
answer := map[string]int64{}
jsonErr := json.Unmarshal(body, &answer)
if jsonErr != nil {
return nil
}
return answer
}
func Ping() map[string]interface{} {
body := GetToData("https://api.binance.com/api/v3/ping")
answer := map[string]interface{}{}
// var answer map[string]interface{}
jsonErr := json.Unmarshal(body, &answer)
if jsonErr != nil {
return nil
}
return answer
}
func GetToData(link string) []byte {
client := &http.Client{}
req, err := http.NewRequest("GET", link, nil)
if err != nil {
println(err)
return nil
}
req.Header.Set("User-Agent", "Ebisu")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
return nil
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil
}
return body
}
func (c *Coin) PriceToFloat() float32 {
value, err := strconv.ParseFloat(c.Price, 32)
if err != nil {
return -1
}
return float32(value)
}
func ColorPrint(value string) {
fmt.Println(settings.Red + value + settings.Reset)
}
func GreenPrint(value string) {
ColorPrint(settings.Green + value + settings.Reset)
}
func RedPrint(value string) {
ColorPrint(settings.Red + value + settings.Reset)
}
// TODO: add generic version of color print (go >= v1.17)
<file_sep>FROM golang:1.16-alpine as build
WORKDIR /src/
COPY . /src
RUN GO111MODULE=on CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /src/out/ebisu .
FROM scratch
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=build /src/assets /assets
COPY --from=build /src/resources /resources
COPY --from=build /src/out/ebisu /
ENTRYPOINT ["./ebisu"]<file_sep># Ebisu
Ebisu is the Japanese god of fishermen and luck ([wiki](https://en.wikipedia.org/wiki/Ebisu_(mythology))).
Table of Contents
- [Ebisu](#ebisu)
- [Download](#download)
- [Features](#features)
- [Docker](#docker)
- [Variables](#variables)
- [DEV](#dev)
---
## Download
```bash
git clone https://github.com/Sarmirim/Ebisu.git
```
---
## Features
* REST (Currently only GET)
* WEBSOCKET (Subscribe/Unsubscribe to a stream, Listing Subscriptions) control via REST API
---
## Docker
```bash
docker-compose up
```
---
## Variables
```
.env/BOT="put your telegram bot key" //works with docker only
.env/PORT=8765 //by default
```
---
## DEV
```go
go tool dist list
go env GOOS GOARCH
go env -w GOOS=linux/windows
```<file_sep>import * as actionTypes from "./actionTypes"
import { ThemeAction, ThemeState, Mode } from './type'
const initialState: ThemeState = {
mode: Mode.system
// theme: Mode,
}
const reducer = (
state: ThemeState = initialState,
action: ThemeAction
): ThemeState => {
switch (action.type) {
case actionTypes.SWITCH_THEME:
return {
...state,
mode: action.theme.mode,
}
}
return state
}
export default reducer<file_sep>package db
import (
"fmt"
)
func PrintAffectedRows(rows int64) {
fmt.Println("Number of affected rows: ", rows)
}
type EasyToken struct {
Symbol string
Price string
}
<file_sep>package db
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type Token struct {
ID int
Symbol string
Price float32
Trade string
Time string
}
// var dsn = "host=localhost user=admin password=<PASSWORD> dbname=ebisu port=32000 sslmode=disable TimeZone=Etc/UTC"
// var DB, ERROR = gorm.Open(postgres.Open(dsn), &gorm.Config{})
var (
dsn = "host=localhost user=admin password=<PASSWORD> dbname=ebisu port=32001 sslmode=disable TimeZone=Etc/UTC"
DB = &gorm.DB{}
ERROR = &DB.Error
ERR = *new(error)
)
func init() {
DB, ERR = gorm.Open(postgres.Open(dsn), &gorm.Config{})
}
func Prepare() {
if ERR != nil {
println("DB ERROR")
} else {
println("DB CONNECTED")
}
}
func PrintAll() {
var tokens []Token
DB.Table("tokens").Select("*").Scan(&tokens)
println()
for _, value := range tokens {
fmt.Println(value)
}
}
func GetTokens() (tokens []Token) {
DB.Table("tokens").Select("*").Scan(&tokens)
return tokens
}
func DeleteToken(token *Token) {
result := DB.Delete(Token{}, &token)
PrintAffectedRows(result.RowsAffected)
}
// TODO: make generic in go v1.17
func BatchDeleteToken(some map[string]interface{}) (result *gorm.DB) {
for k, v := range some {
query := fmt.Sprintf("%v like '%%%v%%'", k, v)
println(query)
result = DB.Where(query).Delete(&Token{})
}
return result
}
func AddToken(token *Token) {
result := DB.Create(&token)
if result.RowsAffected <= 0 {
println("ERROR")
return
}
PrintAffectedRows(result.RowsAffected)
}
func UpdateToken(some map[string]interface{}) (result *gorm.DB) {
for k, v := range some {
query := fmt.Sprintf("%v = '%v'", k, v)
println(query)
result = DB.Where(query).Delete(&Token{})
}
return result
}
func GetArray(link string) {
client := &http.Client{}
newArray := &[]EasyToken{}
// newArray := &easyArray{}
req, err := http.NewRequest("GET", link, nil)
if err != nil {
println(err)
}
req.Header.Set("User-Agent", "Ebisu")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
println(err)
}
er := json.Unmarshal(body, &newArray)
if er != nil {
fmt.Printf("err = %v\n", er)
}
fmt.Printf("members = %#v\n", newArray)
println("a")
}
func ParseTokensArray(array *[]Token) {
}
// func main() {
// // PrintAll()
// // AddToken(&Token{Symbol: "mytest", Time: "2021-06-16 18:39:54+02"})
// DeleteToken(&Token{ID: 15})
// // PrintAll()
// // AddToken(&Token{ID: 4, Symbol: "mytest", Time: "2021-06-16 18:39:54+02"})
// PrintAll()
// }
<file_sep>package channels
import (
"os"
"os/signal"
)
var RequestChannel = make(chan RESTCommand)
var ResponseChannel = make(chan RESTCommand)
var Interrupt = make(chan os.Signal, 1)
type RESTCommand struct {
Action string
Data string
ID int
Status bool
}
func Prepare() {
signal.Notify(Interrupt, os.Interrupt)
}
<file_sep>export { CoinCard } from './CoinCard'<file_sep>import * as actionTypes from "./actionTypes"
import { ICoin, CoinState, CoinAction } from './type'
const initialState: CoinState = {
coins: [
{
Symbol: "",
Price: "",
},
],
lastCoin: {
Symbol: "",
Price: "",
}
}
const reducer = (
state: CoinState = initialState,
action: CoinAction
): CoinState => {
switch (action.type) {
case actionTypes.ADD_COIN:
// const newCoin: ICoin = {
// // id: state.coins.length,
// Symbol: action.coin.Symbol,
// Price: action.coin.Price,
// }
return {
...state,
coins: state.coins.concat(action.coin),
}
case actionTypes.CHANGE_LAST_COIN:
// const newLast: ICoin = {
// Symbol: action.coin.Symbol,
// Price: action.coin.Price,
// }
return {
...state,
lastCoin: action.coin,
}
case actionTypes.REMOVE_COIN:
const updateCoins: ICoin[] = state.coins.filter(
coin => coin.Symbol !== action.coin.Symbol
)
return {
...state,
coins: updateCoins,
}
}
return state
}
export default reducer<file_sep>package websocket_test
import (
"testing"
)
func TestMain(t *testing.T) {
// var c = new(websocket.WSController)
// go c.Start()
// time.Sleep(6 * time.Second)
// c.Stop()
// log.Print("TestMain done")
}
<file_sep>-- CREATE DATABASE mydb;
-- use mydb;
CREATE TABLE tokens (
id SERIAL NOT NULL PRIMARY KEY,
symbol TEXT NOT NULL,
price DOUBLE PRECISION,
trade TEXT,
time TIMESTAMP WITH TIME ZONE
-- PRIMARY KEY (id),
-- UNIQUE (symbol)
);
INSERT INTO tokens
(id, symbol, price, trade, time)
VALUES
(0, 'mytest', NULL, NULL, NULL),
(1, 'bitcoin', 40000, '{"btcbusd": 38800.0001}', '2021-06-16 18:39:54+02'),
(2, 'ethereum', 2500.66, '{"ethbtc": 0.062375, "ethbusd": 2420}', '2021-06-16 18:39:54+02'),
(3, 'dogecoin', 0.31030, '{"dogerub": 22.327, "dogebtc": 0.000008}', '2021-06-16 18:39:54+02');<file_sep>package main_test
import (
"strings"
"testing"
"github.com/sarmirim/ebisu/utils"
)
type testpair struct {
symbol string
price float32
}
var tests = []testpair{
{symbol: "dogeusdt", price: 0.02},
{"btcusdt", 10000.0},
{"ethusdt", 1000.0},
{price: 0.000001, symbol: "iqbnb"},
}
func TestMain(t *testing.T) {
for _, test := range tests {
// go func(a testpair) {
coin := utils.Price(test.symbol)
if float32(coin.PriceToFloat()) < test.price {
t.Error(
"\nFor", strings.ToUpper(test.symbol),
"\nexpected", ">", test.price,
"\ngot", coin.Price,
)
}
// }(test)
}
}
<file_sep>module github.com/sarmirim/ebisu
go 1.16
require (
github.com/gin-gonic/gin v1.6.3
github.com/go-telegram-bot-api/telegram-bot-api v4.6.4+incompatible
github.com/gorilla/websocket v1.4.2
github.com/jackc/pgproto3/v2 v2.1.0 // indirect
github.com/lib/pq v1.6.0 // indirect
github.com/mattn/go-sqlite3 v1.14.7 // indirect
github.com/technoweenie/multipartstreamer v1.0.1 // indirect
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a // indirect
golang.org/x/text v0.3.6 // indirect
gorm.io/driver/postgres v1.1.0 // indirect
gorm.io/driver/sqlite v1.1.4 // indirect
gorm.io/gorm v1.21.11 // indirect
)
<file_sep>export const ADD_COIN = "ADD_COIN"
export const CHANGE_LAST_COIN = "CHANGE_LAST_COIN"
export const REMOVE_COIN = "REMOVE_COIN"
export const SWITCH_THEME = "SWITCH_THEME"
export const SWITCH_SETTINGS = "SWITCH_SETTINGS"<file_sep>import * as actionTypes from "./actionTypes"
import { UIAction, UIState } from './type'
const initialState: UIState = {
settings: false
}
const reducer = (
state: UIState = initialState,
action: UIAction
): UIState => {
switch (action.type) {
case actionTypes.SWITCH_SETTINGS:
return {
...state,
settings: action.ui.settings,
}
}
return state
}
export default reducer<file_sep>import * as actionTypes from "./actionTypes"
import { ICoin, CoinAction, DispatchCoin, ThemeAction, Mode, UIAction } from './type'
export function addCoin(coin: ICoin) {
const action: CoinAction = {
type: actionTypes.ADD_COIN,
coin,
}
return action
// return simulateHttpRequest(action)
}
export function changeLastCoin(coin: ICoin) {
const action: CoinAction = {
type: actionTypes.CHANGE_LAST_COIN,
coin,
}
return action
// return simulateHttpRequest(action)
}
export function removeCoin(coin: ICoin) {
const action: CoinAction = {
type: actionTypes.REMOVE_COIN,
coin,
}
return simulateHttpRequest(action)
}
export function simulateHttpRequest(action: CoinAction) {
return (dispatch: DispatchCoin) => {
setTimeout(() => {
dispatch(action)
}, 500)
}
}
export function switchTheme(mode: Mode) {
const action: ThemeAction = {
type: actionTypes.SWITCH_THEME,
theme: {mode},
}
return action
}
export function switchSettings(settings: boolean) {
const action: UIAction = {
type: actionTypes.SWITCH_SETTINGS,
ui: {settings},
}
return action
}<file_sep>export {default as Header} from './Header'
export {default as Body} from './Body'<file_sep>import { createStore, applyMiddleware, compose, combineReducers } from "redux" // { createStore, applyMiddleware, Store }
import thunk from "redux-thunk"
import coinReducer from './coinReducer'
import themeReducer from './themeReducer'
import uiReducer from './uiReducer'
const rootReducer = combineReducers({
coins: coinReducer,
theme: themeReducer,
ui: uiReducer,
})
export const store = createStore(
rootReducer,
compose(
applyMiddleware(thunk, ),
(window as any).__REDUX_DEVTOOLS_EXTENSION__ && (window as any).__REDUX_DEVTOOLS_EXTENSION__(),
)
)<file_sep>package db_test
import (
"fmt"
"testing"
"time"
db "github.com/sarmirim/ebisu/gorm"
)
var testTokens = []db.Token{
{Symbol: "AddedToBeingDeleted0", Price: 0, Time: time.Now().Format(time.RFC3339)},
{Symbol: "AddedToBeingDeleted1", Price: 100, Time: time.Now().Format(time.RFC3339)},
{Symbol: "AddedToBeingDeleted2", Price: -100, Time: time.Now().Format(time.RFC3339)},
{Symbol: "AddedToBeingDeleted3", Price: 0.2314734, Time: time.Now().Format(time.RFC3339)},
}
func TestMain(t *testing.T) {
// db.PrintAll()
// t.Error()
}
func TestPrintAll(t *testing.T) {
for _, token := range db.GetTokens() {
fmt.Println(token)
t.Log(token)
}
db.PrintAll()
}
func TestGetTokens(t *testing.T) {
db.GetTokens()
}
func TestAddToken(t *testing.T) {
affectedRows := 0
for _, token := range testTokens {
db.AddToken(&token)
affectedRows++
}
db.PrintAll()
}
func TestDeleteToken(t *testing.T) {
var query = map[string]interface{}{
"symbol": "AddedToBeingDeleted",
}
result := db.BatchDeleteToken(query)
println("Rows affected: ", result.RowsAffected)
// if int(result.RowsAffected) != len(query) {
// t.Error(
// "\nTestDeleteToken ERROR",
// )
// }
}
func TestGetArray(t *testing.T) {
db.GetArray("https://api.binance.com/api/v3/ticker/price")
}
<file_sep>package main
import (
"fmt"
"math/rand"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/sarmirim/ebisu/api"
"github.com/sarmirim/ebisu/bot"
"github.com/sarmirim/ebisu/channels"
db "github.com/sarmirim/ebisu/gorm"
"github.com/sarmirim/ebisu/websocket"
)
func main() {
prepare()
}
func CORS() gin.HandlerFunc {
return func(c *gin.Context) {
// allowedOrigin := os.Getenv("ALLOWED_ORIGIN")
// c.Writer.Header().Set("Access-Control-Allow-Origin", allowedOrigin)
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
// c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Headers", "*")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
// Handle browser preflight requests, where it asks for allowed origin.
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
func prepare() {
// bot launch
go bot.Prepare()
// websocket launch
go websocket.Prepare()
go channels.Prepare()
go db.Prepare()
// TODO: check jsoniter (gin-gonic/gin/readme.md Build with jsoniter)
r := gin.Default()
// TODO: make/find solution for CORS
r.Use(CORS())
r.StaticFile("/favicon.ico", "./resources/favicon.ico")
r.LoadHTMLGlob("resources/*")
r.Static("/assets", "./assets")
r.GET("/", slash)
api.Connect(r.Group("/api"))
r.GET("/ws", websocketAPI)
r.Run(":8765")
// go r.Run(":9876") goroutine for second server
}
func slash(c *gin.Context) {
now := time.Now().Format("15:04:05 02/01/2006")
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "SLASH",
"time": now,
"message": "WELCOME TO EBISU",
})
}
func websocketAPI(c *gin.Context) {
action := c.Query("action")
data := c.Query("data")
println("Action=", action, "Data=", data)
newID := rand.Intn(100)
request := &channels.RESTCommand{
Action: action,
Data: data,
ID: newID,
}
go func() {
channels.RequestChannel <- *request
}()
for {
response := <-channels.ResponseChannel
fmt.Printf("resp %+v\n", response)
if response.ID == newID { //response.ID == newID
c.JSON(200, gin.H{
"Action": response.Action,
"Data": response.Data,
"Status": response.Status,
})
return
}
// else {
// channels.ResponseChannel <- response
// }
}
}
<file_sep>Connect via db platform (pgAdmin, ...) or docker cli.
Default connection:
* Name: ebisu
* Host: localhost
* Port: 32000
* Username: admin
* Password: <PASSWORD>
PostgreSQL commands:
```
psql -h localhost -p 5432 -U admin -d ebisu
select * from tokens;
```<file_sep>package bot
import (
"fmt"
"log"
"os"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/sarmirim/ebisu/utils"
)
func Prepare() {
go Start()
}
func getENV(name string) string {
value := os.Getenv(name)
return value
// return "you_can_add_your_bot_key_on_return"
}
func printBotName(botName string) {
if botName != "" {
line := fmt.Sprintf("Authorized on account: %v\n", botName)
utils.GreenPrint(line)
} else {
utils.RedPrint("BOT token: empty")
}
}
func Start() {
token := getENV("BOT")
// TODO: test recover
defer func() {
if err := recover(); err != nil {
log.Println("Panic occurred:", err)
}
}()
bot, err := tgbotapi.NewBotAPI(token)
if err != nil {
utils.RedPrint("BOT ERROR")
}
bot.Debug = true
printBotName(bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
if err != nil {
println(err)
}
for update := range updates {
print("Channel ")
println(update.ChannelPost)
if update.Message == nil { // ignore any non-Message Updates
continue
}
fmt.Printf("Message %+v\n", update.Message)
// println("type" + update.ChannelPost.Chat.Type)
// TODO: add Channel chat
// if update.ChannelPost.Chat.Type == "channel" {
// println("YEEP")
// msg := tgbotapi.NewMessage(update.Message.Chat.ID, "answer")
// msg.ReplyToMessageID = update.ChannelPost.ReplyToMessage.MessageID
// bot.Send(msg)
// }
log.Printf("[%s] %s\n", update.Message.From.UserName, update.Message.Text)
answer := BotRequest(update.Message.Text)
msg := tgbotapi.NewMessage(update.Message.Chat.ID, answer)
msg.ParseMode = "HTML"
msg.ReplyToMessageID = update.Message.MessageID
bot.Send(msg)
}
}
func BotRequest(symbol string) string {
coin := utils.Price(symbol)
answer := MessageParser(coin.Symbol, coin.Price)
return answer
}
func MessageParser(symbol, price string) string {
if len(price) < 1 {
return "Pair doesn't exist\nPlease try something like \"doge\" or \"dogebtc\" or \"dogeusdt\""
}
// return fmt.Sprintf("Pair: %s \nPrice: <b>%f</b>", symbol, price)
return "Pair: " + symbol + " \nPrice: <b>" + price + "</b>"
}
<file_sep>package websocket
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/url"
"time"
"github.com/gorilla/websocket"
"github.com/sarmirim/ebisu/channels"
structs "github.com/sarmirim/ebisu/etc"
)
var addr = flag.String("addr", "fstream.binance.com", "Ebisu")
// addr := "stream.binance.com:9443"
var (
done = make(chan struct{})
)
// func main() {
// Prepare()
// }
type WSController struct {
Conn *websocket.Conn
}
func Prepare() {
var ws = new(WSController)
ws.Start()
}
func (ws *WSController) Start() {
flag.Parse()
log.SetFlags(0)
connection := "/stream" // "/ws" or "/stream"
u := url.URL{Scheme: "wss", Host: *addr, Path: connection}
log.Printf("connecting to %s", u.String())
var err error
ws.Conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer ws.Conn.Close()
go func() {
defer close(done)
for {
_, message, err := ws.Conn.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
var answer structs.Answer
var data structs.Data
if connection == "/ws" {
var data structs.Data
if err := json.Unmarshal(message, &data); err != nil {
fmt.Println(err)
}
log.Printf("\\ws: %s", message)
} else {
if err := json.Unmarshal(message, &answer); err != nil {
fmt.Println(err)
}
data = answer.Data
log.Printf("\\stream: %s", message)
}
if data.ID > 0 {
go data.SendToResponseChannel()
}
}
}()
go func() {
for {
data := <-channels.RequestChannel
switch data.Action {
case "subscribe":
subErr := ws.Conn.WriteJSON(Sub(data.Data))
if subErr != nil {
log.Println("Subscription error:", subErr)
}
data.Status = true
channels.ResponseChannel <- data
case "unsubscribe":
unsubErr := ws.Conn.WriteJSON(Unsub(data.Data))
if unsubErr != nil {
log.Println("Unsubscription error:", unsubErr)
}
data.Status = true
channels.ResponseChannel <- data
case "listing":
listSub := ws.Conn.WriteJSON(List())
if listSub != nil {
log.Println("List of subscriptions error:", listSub)
}
data.Status = true
channels.ResponseChannel <- data
}
fmt.Printf("GlobalChannel websocket info: %+v\n", data)
}
}()
ticker := time.NewTicker(time.Second * 5)
defer ticker.Stop()
// sub := &structs.JSONStruct{
// Method: "SUBSCRIBE",
// Params: []string{"btcusdt@trade"},
// ID: 5}
// json, _ := json.Marshal(sub)
// stringJSON := string(json)
// fmt.Println("JSON:", stringJSON)
// ws.Conn.WriteJSON(Sub("btcusdt@trade"))
// listSub := ws.Conn.WriteJSON(List())
// if listSub != nil {
// log.Println("List of subscriptions error:", listSub)
// }
for {
select {
case <-done:
return
// case t := <-ticker.C:
// err := ws.Conn.WriteMessage(websocket.TextMessage, []byte(t.String()))
// if err != nil {
// log.Println("write:", err)
// return
// }
case <-channels.Interrupt:
log.Println("interrupt")
// Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection.
err := ws.Conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
select {
case <-done:
case <-time.After(time.Second):
}
return
}
}
}
func (ws *WSController) Stop() {
log.Println("ws.Close")
err := ws.Conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
ws.Conn.Close()
}
func List() structs.JSONStruct {
request := &structs.JSONStruct{
Method: "LIST_SUBSCRIPTIONS",
ID: 999}
request.Print()
return *request
}
func Unsub(params string) structs.JSONStruct {
request := &structs.JSONStruct{
Method: "UNSUBSCRIBE",
Params: []string{params},
ID: 100}
request.Print()
return *request
}
func Sub(params string) structs.JSONStruct {
request := &structs.JSONStruct{
Method: "SUBSCRIBE",
Params: []string{params},
ID: 1}
request.Print()
return *request
}
func Universal(method, params string) structs.JSONStruct {
return structs.JSONStruct{
Method: method,
Params: []string{params},
ID: 0}
}
<file_sep>package api
import (
"fmt"
gotime "time"
"github.com/gin-gonic/gin"
"github.com/sarmirim/ebisu/utils"
)
func Connect(c *gin.RouterGroup) {
c.GET("/ping", ping)
c.GET("/time", time)
c.GET("/trade", trade)
}
func ping(c *gin.Context) {
answer := utils.Ping()
fmt.Printf("ANSWER %+v\n", &answer)
response := gin.H{"ping": false}
if len(answer) == 0 {
response = gin.H{"ping": true}
}
c.JSON(200, response)
}
func time(c *gin.Context) {
answer := utils.Time()
fmt.Printf("ANSWER %+v\n", &answer)
for k, v := range answer {
c.JSON(200, gin.H{
k: gotime.Unix(v/1000, 0),
})
}
// enc := json.NewEncoder(os.Stdout)
// err := enc.Encode(answer)
// if err != nil {
// fmt.Println(err.Error())
// }
}
func trade(c *gin.Context) {
symbol := c.Query("symbol")
println("Symbol=", symbol)
answer := utils.Price(symbol)
c.JSON(200, gin.H{
"Symbol": answer.Symbol,
"Price": answer.Price,
})
}
<file_sep>package structs
import (
"fmt"
"strings"
"github.com/sarmirim/ebisu/channels"
)
type JSONStruct struct {
Method string `json:"method"`
Params []string `json:"params"`
ID int `json:"id"`
}
type Answer struct {
Stream string `json:"stream"`
Data Data `json:"data"`
ID int16 `json:"id"`
Error Error `json:"error"`
}
type Data struct {
EType string `json:"e"`
ETime int64 `json:"E"`
TTime int64 `json:"T"`
Symbol string `json:"s"`
Number int32 `json:"t"`
Price string `json:"p"`
Quantity string `json:"q"`
What string `json:"X"`
Isthebuyerthemarketmaker bool `json:"m"`
Error Error `json:"error"`
ID int `json:"id"`
Result []string `json:"result"`
}
type Error struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
type PrintME interface {
Print()
}
func (object JSONStruct) Print() {
fmt.Printf("%+v\n", object)
}
func (object Data) SendToResponseChannel() {
channels.ResponseChannel <- channels.RESTCommand{
Data: strings.Join(object.Result[:], ","),
Action: "Listing",
Status: true,
}
}
|
b1d0a1eb7c3e151a2d23c41791cce9f6376b4887
|
[
"SQL",
"Markdown",
"Go Module",
"TypeScript",
"Go",
"Dockerfile"
] | 27 |
TypeScript
|
Sarmirim/ebisu
|
15d202b289b9f50bffe5966091ba8282221107a9
|
2cd432760c534030e9c008dc99b6880ce0c4e983
|
refs/heads/master
|
<repo_name>trayio/pollen<file_sep>/main.go
// pollen, the stupid file watcher
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"os"
"os/exec"
"path"
"strings"
"syscall"
"time"
)
const (
Unknown fileType = iota
File
Dir
)
// last seen mtimes of all the files we know about
var mtimes = make(map[string]time.Time)
type nothing struct{}
type fileType uint8
type ignoredFunc func(string) bool
type paths struct {
files []string
dirs []string
}
type set struct {
entries map[string]nothing
}
func newSet(keys []string) *set {
s := &set{entries: make(map[string]nothing)}
s.addAll(keys)
return s
}
func (s *set) addAll(keys []string) {
for _, k := range keys {
s.add(k)
}
}
func (s *set) add(key string) {
s.entries[key] = nothing{}
}
func (s *set) del(key string) {
delete(s.entries, key)
}
func (s set) exists(key string) bool {
_, ok := s.entries[key]
return ok
}
type stringFlags []string
func (s *stringFlags) String() string {
return fmt.Sprint(*s)
}
func (s *stringFlags) Set(value string) error {
for _, v := range strings.Split(value, ",") {
*s = append(*s, v)
}
return nil
}
func execTimeout(name string, command string) error {
fmt.Printf("%sing...\n", name)
cmd := exec.Command("/bin/sh", "-c", command)
var b bytes.Buffer
cmd.Stdout = &b
cmd.Stderr = &b
err := cmd.Start()
if err != nil {
fmt.Fprintln(os.Stderr, name, err)
return err
}
done := make(chan error)
go func() { done <- cmd.Wait() }()
select {
case err := <-done:
if err != nil {
fmt.Fprintln(os.Stderr, name, err)
return err
}
case <-time.After(20 * time.Second):
fmt.Fprintln(os.Stderr, name, "timed out")
return errors.New(fmt.Sprintf("%s timed out"))
}
fmt.Println(b.String())
return nil
}
// runs in its own goroutine
func actionLoop(actions <-chan nothing, buildCmd, restartCmd string) {
for _ = range actions {
if err := execTimeout("build", buildCmd); err == nil {
execTimeout("restart", restartCmd)
}
}
}
// runs in its own goroutine
func mtimeLoop(input <-chan *paths, actions chan<- nothing, debug bool) {
current := <-input
previous := current
{
// we are only interested in changes since the start of the program so we
// let this be the start time for comparisons because it's easier than
// going in and stat everything right at the start
initTime := time.Now()
for _, entry := range current.files {
mtimes[entry] = initTime
}
}
tick := time.NewTicker(3 * time.Second)
defer tick.Stop()
for {
select {
case <-tick.C:
if debug {
fmt.Println("scanning for modifications")
}
if needsAction(previous, current) {
select {
case actions <- nothing{}:
default:
// ensure non-blocking send
}
}
previous = current
case p := <-input:
if debug {
fmt.Printf("crawl result: %#v\n", p)
}
current = p
}
}
}
func walk(dir string, ignoredf ignoredFunc) *paths {
var files, dirs []string
files, dirs, _ = doWalk(dir, ignoredf, files, dirs)
return &paths{files: files, dirs: dirs}
}
func doWalk(dir string, ignoredf ignoredFunc, files []string, dirs []string) ([]string, []string, fileType) {
var ft fileType
f, err := os.Open(dir)
if err != nil {
fmt.Fprintf(os.Stderr, "open dir %s: %s\n", dir, err)
return files, dirs, ft
}
names, err := f.Readdirnames(-1)
f.Close()
if err != nil {
// On Linux calling Readdirnames with a file returns an error
if serr, ok := err.(*os.SyscallError); ok && serr.Err == syscall.ENOTDIR {
ft = File
} else {
fmt.Fprintln(os.Stderr, "Readdirnames", err)
return files, dirs, ft
}
}
// On OS X Readdirnames doesn't return an error if we call it on a file so we
// assume it's a file if we found nothing. While this is incorrect people
// don't often have empty directories and worst case we'll just stat the
// directory as if it were a file later
if len(names) == 0 {
ft = File
}
if ft != File {
ft = Dir
}
for _, n := range names {
p := path.Join(dir, n)
if ignoredf(p) {
continue
}
var ft fileType
files, dirs, ft = doWalk(p, ignoredf, files, dirs)
if ft == Dir {
dirs = append(dirs, p)
} else if ft == File {
files = append(files, p)
}
}
return files, dirs, ft
}
func needsAction(previous *paths, current *paths) bool {
// we only take these shortcuts for dirs because we want to keep the file
// mtimes updated
if len(previous.dirs) != len(current.dirs) {
return true
}
{
uniondirs := newSet(previous.dirs)
uniondirs.addAll(current.dirs)
if len(uniondirs.entries) != len(previous.dirs) {
return true
}
}
// check if files have been modified since last time we saw them
now := time.Now()
var changed bool
for _, entry := range current.files {
prevMtime, ok := mtimes[entry]
if !ok {
// arbitrary time sufficiently in the past - new file so always modified
prevMtime = now.Add(-30 * time.Minute)
}
if info, err := os.Stat(entry); err == nil {
if info.ModTime().After(now) {
fmt.Fprintf(os.Stderr, "WARNING: Skipping '%s' as it was modified in the future: file '%s', system '%s'\n",
entry, formatTime(info.ModTime()), formatTime(now))
continue
}
if info.ModTime().After(prevMtime) {
fmt.Println("changed:", entry)
changed = true
}
mtimes[entry] = info.ModTime()
}
}
return changed
}
func formatTime(t time.Time) string {
return t.Format("15:04:05.000")
}
func ignored(v string, ignore []string) bool {
for _, ignore := range ignore {
if v == ignore {
return true
}
}
return false
}
func main() {
var ignore stringFlags
var dir, buildCmd, restartCmd string
var debug bool
flag.Var(&ignore, "ignore", "comma-separated list of locations to ignore (relative to dir)")
flag.StringVar(&dir, "dir", ".", "directory to watch")
flag.StringVar(&buildCmd, "buildCmd", "echo default build command", "build command")
flag.StringVar(&restartCmd, "restartCmd", "echo default restart command", "restart command")
flag.BoolVar(&debug, "debug", false, "debug logging")
flag.Parse()
for k, v := range ignore {
ignore[k] = path.Join(dir, v)
}
// buffered so we can always accept the next one while running an action
actionCh := make(chan nothing, 1)
go actionLoop(actionCh, buildCmd, restartCmd)
ignoredf := ignoredFunc(func(v string) bool {
return ignored(v, ignore)
})
mtimeCh := make(chan *paths)
go mtimeLoop(mtimeCh, actionCh, debug)
mtimeCh <- walk(dir, ignoredf)
// dir tree crawl loop
tick := time.NewTicker(6 * time.Second)
defer tick.Stop()
for {
select {
case <-tick.C:
mtimeCh <- walk(dir, ignoredf)
}
}
}
|
323eb878498adf65206584710fcf996bc9dcd4bd
|
[
"Go"
] | 1 |
Go
|
trayio/pollen
|
2017284c61f2bb8d3cc3223d6e916519917a30bb
|
1b0f6a8aa5a5b3d3f9b4b3a69a844ae892479b04
|
refs/heads/master
|
<repo_name>Fedejp/TaTeTi<file_sep>/app/src/main/java/com/example/tateti/MainActivity.java
package com.example.tateti;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
public class MainActivity extends AppCompatActivity {
EditText txtNombre;
RadioButton btnCirculo, btnCruz;
Button Empezar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtNombre = (EditText) findViewById(R.id.txtNombre);
btnCirculo = (RadioButton) findViewById(R.id.btnCirculo);
btnCruz = (RadioButton) findViewById(R.id.btnCruz);
Empezar = (Button) findViewById(R.id.Empezar);
Empezar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, GameActivity.class );
String nombre = txtNombre.getText().toString();
if(nombre.isEmpty()) {
nombre = "Extraño";
}
intent.putExtra("nombre", nombre);
if(btnCirculo.isChecked()) {
intent.putExtra("usa", "circulo");
} else {
intent.putExtra("usa", "cruz");
}
startActivity(intent);
}
});
}
}
|
e8dd96be7343cd3b988156ecce018fbe45a292f1
|
[
"Java"
] | 1 |
Java
|
Fedejp/TaTeTi
|
be54e5325cd07b5d8e5a08c15615e056bd65be87
|
abd8d6733fe0d7fddc201354c2d437edba73292e
|
refs/heads/master
|
<repo_name>13bscsmahmad/APLab8<file_sep>/src/java/coinchange/CoinChange.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 coinchange;
import java.util.Random;
/**
*
* @author MMA
*/
public class CoinChange {
static int money;
public static void main(String[] args) {
int totalCoinsGreedy = 0;
int totalCoins = 0;
// Due to the nature of the denominations (multiples of 5), there will never be a case where the
// dynamic programming algorithm produces a better result result than the greedy one.
for (int j = 0; j < 10; j++){
totalCoins = 0;
totalCoinsGreedy = 0;
Random rand = new Random();
money = rand.nextInt(1000);
System.out.println("random: " + money);
//money = 200;
System.out.println("####### Greedy #######");
int[] coins = changeGreedy(money);
//print(coins);
for (int i = 0; i < coins.length; i++) {
totalCoinsGreedy += coins[i];
}
System.out.println("Total coins greedy: " + totalCoinsGreedy);
/////////////////////////////////////////
System.out.println("####### Dynamic Programming #######");
int [] denominations = {1,5,10,25};
totalCoins = minChange(denominations, money);
System.out.println("Total coins by DP: " + totalCoins);
System.out.println("$$$$$$$");
}
}
public static int[] changeGreedy(int money) {
int[] denominations = new int[4];
// int dollars = (int) Math.floor(money/1);
// money -= dollars * 1;
// int quarters = (int) Math.floor(money / 0.25);
// money -= quarters * 0.25;
int quarters = (int) Math.floor(money / 25);
money -= quarters * 25;
int dimes = (int) Math.floor(money / 10);
money -= dimes * 10;
int nickels = (int) Math.floor(money / 5);
money -= nickels * 5;
int pennies = (int) Math.round(money * 1);
denominations[0] = quarters;
denominations[1] = dimes;
denominations[2] = nickels;
denominations[3] = pennies;
return denominations;
}
// public static int dynamic(int[] v, int amount) {
// int[][] solution = new int[v.length + 1][amount + 1];
//
// // if amount=0 then just return empty set to make the change
// for (int i = 0; i <= v.length; i++) {
// solution[i][0] = 1;
// }
//
// // if no coins given, 0 ways to change the amount
// for (int i = 1; i <= amount; i++) {
// solution[0][i] = 0;
// }
//
// // now fill rest of the matrix.
//
// for (int i = 1; i <= v.length; i++) {
// for (int j = 1; j <= amount; j++) {
// // check if the coin value is less than the amount needed
// if (v[i - 1] <= j) {
// // reduce the amount by coin value and
// // use the subproblem solution (amount-v[i]) and
// // add the solution from the top to it
// solution[i][j] = solution[i - 1][j]
// + solution[i][j - v[i - 1]];
// } else {
// // just copy the value from the top
// solution[i][j] = solution[i - 1][j];
// }
// }
// }
// return solution[v.length][amount];
// }
public static int minChange(int[] denominations, int amount) {
int actualAmount;
int m = denominations.length+1;
int n = amount + 1;
int max = Integer.MAX_VALUE-1;
int[][] table = new int[m][n];
for (int j = 1; j < n; j++)
table[0][j] = max;
for (int denomPosition = 1; denomPosition < m; denomPosition++) {
for (int currentAmount = 1; currentAmount < n; currentAmount++) {
if (currentAmount - denominations[denomPosition-1] >= 0)
actualAmount = table[denomPosition][currentAmount - denominations[denomPosition-1]];
else
actualAmount = max;
table[denomPosition][currentAmount] = Math.min(table[denomPosition-1][currentAmount], 1 + actualAmount);
}
}
return table[m-1][n-1];
}
public static void print(int[] denominations) {
System.out.println("(25) coins: " + denominations[0]);
System.out.println("(10) coins: " + denominations[1]);
System.out.println("(5) coins: " + denominations[2]);
System.out.println("(1) coins: " + denominations[3]);
}
}
<file_sep>/README.md
Coin Change Problem
===================
Introduction
------------
The objective of this lab is to implement the coin change problem using a greedy algorithm, and then using dynamic programming to solve it.
How to Run
----------
Find the source file in `src/coinchange` dir. Compile, and run `CoinChange.java`.
Both methods run, first greedy, then dp.
Analysis
--------
Due to the nature of the denominations (multiples of 5), there is never such a case where the dynamic programming algorithm produces
a more optimal result than the greedy algorithm.
Github link: https://github.com/13bscsmahmad/APLab8.git
|
437979453311ef515b8ec7664b73d96cc9b0cd6b
|
[
"Markdown",
"Java"
] | 2 |
Java
|
13bscsmahmad/APLab8
|
f0b621d9f532832476255a92698c442edcd238fa
|
09ee1b6aee56be0d61e906ffa7441aad809509b2
|
refs/heads/master
|
<file_sep>package com.github.danielfelgar.drawreceiptlib;
import android.graphics.Canvas;
import android.graphics.Paint;
/**
* Created by daniel on 15/08/2016.
*/
public class DrawLine implements IDrawItem {
private Paint paint = new Paint();
private int size;
public DrawLine(int size) {
this.size = size;
}
@Override
public void drawOnCanvas(Canvas canvas, float x, float y) {
float xPos = getX(canvas, x);
canvas.drawLine(xPos, y + 5, xPos + size, y + 5, paint);
}
private float getX(Canvas canvas, float x) {
float xPos = x;
if (paint.getTextAlign().equals(Paint.Align.CENTER)) {
xPos += (canvas.getWidth() - size) / 2;
} else if (paint.getTextAlign().equals(Paint.Align.RIGHT)) {
xPos += canvas.getWidth() - size;
}
return xPos;
}
@Override
public int getHeight() {
return 6;
}
public int getColor() {
return paint.getColor();
}
public void setColor(int color) {
paint.setColor(color);
}
public void setAlign(Paint.Align align) {
paint.setTextAlign(align);
}
public Paint.Align getAlign() {
return paint.getTextAlign();
}
}
<file_sep>include ':sample', ':draw-receipt'
|
0520421dc96058e0dda3a328b521100f0f0375de
|
[
"Java",
"Gradle"
] | 2 |
Java
|
tisistema/DrawReceipt
|
d377d7c275053db0f8b963e43d5d8e3d84604e86
|
9ef4f4b681142298df66e408559303e900fc3a42
|
refs/heads/master
|
<repo_name>MohamedAbdultawab/events<file_sep>/events/events/doctype/custom_event/custom_event.py
# -*- coding: utf-8 -*-
# Copyright (c) 2020, <NAME> and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import nowdate, nowtime
from frappe.website.website_generator import WebsiteGenerator
class CustomEvent(WebsiteGenerator):
def validate(self):
self.validate_invitees()
self.validate_date_and_time()
def validate_date_and_time(self):
"""
Validate date of event to be after now.
"""
if isinstance(self.date, str):
if self.date < nowdate() or (self.date == nowdate() and self.start_time < nowtime()):
frappe.throw(_("Cannot create event on past date"))
else:
if self.date.strftime("%Y-%m-%d") < nowdate() or (self.date.strftime("%Y-%m-%d") == nowdate() and self.start_time.strftime("%H:%M:%S.%f") < nowtime()):
frappe.throw(_("Cannot create event on past date"))
def validate_invitees(self):
"""Set missing names and warn if duplicate"""
found = []
for invitee in self.invitees:
if invitee.invitee in found:
frappe.throw(
_("Invitee {0} entered twice").format(invitee.invitee))
if not invitee.full_name:
invitee.full_name = get_full_name(invitee.invitee)
found.append(invitee.invitee)
@frappe.whitelist()
def get_full_name(invitee):
"""
Return full name of a user"""
user = frappe.get_doc("User", invitee)
return " ".join(filter(None, (user.first_name, user.middle_name, user.last_name)))
<file_sep>/README.md
## Events
Event Management Module
#### License
MIT<file_sep>/events/events/doctype/custom_event/custom_event.js
// Copyright (c) 2020, <NAME> and contributors
// For license information, please see license.txt
frappe.ui.form.on('Custom Event', {
send_invitations: function(frm) {
if (frm.doc.status==="Planned") {
frappe.call({
method: "events.api.send_invitation_emails",
args: {
event: frm.doc.name
}
});
}
},
});
frappe.ui.form.on("Event Invitee", {
invitee: function(frm, cdt, cdn) {
var invitee = frappe.model.get_doc(cdt, cdn);
if (invitee.invitee) {
// if invitee, get full name
frappe.call({
method: "events.events.doctype.custom_event.custom_event.get_full_name",
args: {
invitee: invitee.invitee
},
callback: function(r) {
frappe.model.set_value(cdt, cdn, "full_name", r.message);
}
});
} else {
// if no invitee, clear full name
frappe.model.set_value(cdt, cdn, "full_name", null);
}
},
});<file_sep>/events/www/events.py
import frappe
def get_context(context):
"""
Context for events.html jinja2 template
"""
context['docs'] = {}
events = frappe.get_all('Custom Event',
fields=['name', 'title', 'status', 'date'])
for event in events:
if event.get('status') not in context['docs']:
context['docs'][event.get('status')] = []
context['docs'][event.get('status')].append(event)
<file_sep>/events/api.py
import frappe
from frappe import _
from frappe.utils import add_days, nowdate
@frappe.whitelist()
def send_invitation_emails(event):
"""
Send Email Invitations to event invitees.
"""
event = frappe.get_doc("Custom Event", event)
# event.check_permission("email")
if event.status == "Planned":
frappe.sendmail(
recipients=[d.invitee for d in event.invitees],
sender='<EMAIL>',
subject=event.invitation_subject or event.title,
message=event.invitation_message,
reference_doctype=event.doctype,
reference_name=event.name,
)
event.status = "Invitations Sent"
event.save()
frappe.msgprint(_("Invitation Sent"))
else:
frappe.msgprint(_("Event Status must be 'Planned'"))
@frappe.whitelist()
def get_events(start, end):
"""
Return Event list.
"""
if not frappe.has_permission("Custom Event", "read"):
raise frappe.PermissionError
data = frappe.db.sql("""select
timestamp(timestamp(`date`), start_time) as start,
timestamp(timestamp(`date`), end_time) as end,
name,
title,
status,
0 as all_day
from `tabCustom Event`
where `date` between %(start)s and %(end)s""", {
"start": start,
"end": end
}, as_dict=True)
return data
def create_welcome_party_event(doc, method):
"""
Create a welcome party event when a new User is added.
"""
event = frappe.get_doc({
"doctype": "Custom Event",
"title": "Welcome Party for {0}".format(doc.first_name),
"date": add_days(nowdate(), 7),
"from_time": "09:00",
"to_time": "09:30",
"status": "Planned",
"invitees": [{
"invitee": doc.name
}]
})
# the System Manager might not have permission to create a Meeting
event.flags.ignore_permissions = True
event.insert()
frappe.msgprint(_("Welcome party event created"))
<file_sep>/events/events/doctype/custom_event/test_custom_event.py
# -*- coding: utf-8 -*-
# Copyright (c) 2020, <NAME> and Contributors
# See license.txt
from __future__ import unicode_literals
import unittest
import frappe
from frappe.test_runner import make_test_objects
class TestCustomEvent(unittest.TestCase):
def setUp(self):
# GIVEN
# Make Sure db is clean
frappe.db.sql('delete from `tabCustom Event` where title like "_Test Event%"')
frappe.db.sql('delete from `tabCustom Event` where name like "welcome-party-for-test%"')
frappe.db.sql('delete from `tabUser` where email like "test_%"')
frappe.db.sql('delete from `tabEvent Invitee` where invitee like "test_%"')
# Create User
user = frappe.get_doc({
"doctype": "User",
"email": "<EMAIL>",
"first_name": "<NAME>",
}).insert()
# Deleting new user automatic welcome party event to not interfere with the test logic.
frappe.db.sql('delete from `tabCustom Event` where name like "welcome-party-for-test-manager"')
user.add_roles('Event Manager')
frappe.set_user('<EMAIL>')
# Create events
make_test_objects('Custom Event', reset=True)
self.test_records = frappe.get_test_records('Custom Event')
def tearDown(self):
frappe.set_user("Administrator")
def test_event_list(self):
"""
Test event listing
"""
# WHEN
res = frappe.get_list("Custom Event", fields=["name", "title"])
# THEN
self.assertEqual(len(res), 3)
titles = [r.title for r in res]
self.assertTrue("_Test Event 1" in titles)
self.assertTrue("_Test Event 3" in titles)
self.assertTrue("_Test Event 2" in titles)
self.assertFalse("_Test Event 4" in titles)
# WHEN
frappe.db.sql(
'delete from `tabCustom Event` where title = "_Test Event 2"')
frappe.db.commit()
res = frappe.get_list("Custom Event", fields=["name", "title"])
# THEN
self.assertEqual(len(res), 2)
titles = [r.title for r in res]
self.assertTrue("_Test Event 1" in titles)
self.assertTrue("_Test Event 3" in titles)
self.assertFalse("_Test Event 2" in titles)
def test_create_events_in_the_past(self):
"""
Test can't create events in the past.
"""
# WHEN, THEN
with self.assertRaises(frappe.exceptions.ValidationError):
doc = frappe.get_doc({
"doctype": "Custom Event",
"title": "_Test Event 4",
"date": "2014-01-01",
"start_time": "20:00:00",
"end_time": "22:00:00",
}).insert()
# THEN
res = frappe.get_list("Custom Event", fields=["name", "title"])
self.assertEqual(len(res), 3)
titles = [r.title for r in res]
self.assertFalse("_Test Event 4" in titles)
def test_create_events_on_user_creation(self):
"""
Test a welcome party event is created for every new user.
"""
# WHEN
doc = frappe.get_doc({
"doctype": "User",
"email": "<EMAIL>",
"first_name": "Test",
}).insert()
# THEN
res = frappe.get_list("Custom Event", fields=["name", "title"])
self.assertEqual(len(res), 4)
titles = [r.title for r in res]
self.assertTrue("Welcome Party for Test" in titles)
def test_full_name_in_invitee(self):
"""
Test invitee full name is present in invitee table.
"""
# WHEN
doc = frappe.get_doc({
"doctype": "User",
"email": "<EMAIL>",
"first_name": "TestFisrtName",
"last_name": "TestLastName"
}).insert()
# THEN
res = frappe.db.sql(
'select full_name from `tabEvent Invitee` where parent = "welcome-party-for-testfisrtname"')
self.assertEqual(len(res), 1)
self.assertEqual(res[0][0], "TestFisrtName TestLastName")
<file_sep>/events/config/events.py
from __future__ import unicode_literals
from frappe import _
def get_data():
"""
Add evetns module to desk home screen."""
return [
{
"label": _("Events"),
"icon": "octicon octicon-briefcase",
"items": [
{
"type": "doctype",
"name": "Custom Event",
"label": _("Custom Event"),
"description": _("Custom Events Module Description."),
},
]
}
]
|
e79aa2ad9fbf27694fa37af4b596c648e55254f5
|
[
"Markdown",
"Python",
"JavaScript"
] | 7 |
Python
|
MohamedAbdultawab/events
|
3d4acaf73628135addb7f1e98b4351cbba50c27e
|
f8926beaf3491f733251f895470bda33de137449
|
refs/heads/master
|
<repo_name>twlk-jzy/NiceDialogDemo<file_sep>/app/src/main/java/com/twlk/nicedialogdemo/MainActivity.java
package com.twlk.nicedialogdemo;
import android.annotation.SuppressLint;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;
import com.twlk.nicedialog.BottomDialog;
import com.twlk.nicedialog.NiceDialog;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.tv_bottom_dialog).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
BottomDialog bottomDialog = new BottomDialog(MainActivity.this);
bottomDialog.setItems(new String[]{"相机","相册"});
bottomDialog.showAtLocation(view, Gravity.BOTTOM,0,0);
bottomDialog.setOnItemClickListener(new BottomDialog.OnItemClickListener() {
@Override
public void onItemClick(String item, int position) {
Toast.makeText(MainActivity.this,item,Toast.LENGTH_SHORT).show();
}
});
}
});
findViewById(R.id.btn_confirm_dialog).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
NiceDialog dialog = new NiceDialog();
dialog.setContent("的都是发顺丰").show(getSupportFragmentManager(),"dialgo");
dialog.setOnBtnClickListener(new NiceDialog.OnBtnClickListener() {
@Override
public void confirmClick() {
Toast.makeText(MainActivity.this,"确定",Toast.LENGTH_SHORT).show();
}
@Override
public void cancelClick() {
Toast.makeText(MainActivity.this,"取消",Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
<file_sep>/nicedialog/src/main/java/com/twlk/nicedialog/BaseNicPPW.java
package com.twlk.nicedialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
/**
* Created by xyb on 2017/9/5.
*/
public abstract class BaseNicPPW extends PopupWindow {
protected Context context;
public abstract View initLayout();
public abstract void initData();
public BaseNicPPW(Context context) {
this(context, null);
}
public BaseNicPPW(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BaseNicPPW(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
setPopupWindow();
initData();
}
private void setPopupWindow() {
this.setContentView(initLayout());
this.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
this.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
this.setFocusable(true);
this.setOutsideTouchable(true);
this.setAnimationStyle(R.style.mypopwindow_anim_style);// 设置动画
//实例化一个ColorDrawable颜色为半透明
ColorDrawable dw = new ColorDrawable(0xb0000000);
dw.setAlpha(155);
//设置SelectPicPopupWindow弹出窗体的背景
this.setBackgroundDrawable(dw);
}
}
<file_sep>/nicedialog/src/main/java/com/twlk/nicedialog/DialogInterface.java
package com.twlk.nicedialog;
/**
* Created by xyb on 2017/9/5.
*/
public interface DialogInterface {
interface setOnItemClicklistener {
void onItemClick(String item);
}
interface setCancelClickListener{
void onClick();
}
}
|
d4a74c8e6136335fbbec9b8d6796d48ef80d034c
|
[
"Java"
] | 3 |
Java
|
twlk-jzy/NiceDialogDemo
|
a6b2031dad176ceb64acd53bd720ccd994f46fa6
|
6e3648371331835027514b0be8e8dd5deb2ac39b
|
refs/heads/master
|
<file_sep>## REPS Platform Instructions
To incorporate the REPS platform into your subsite project you need to
copy the file `resources/composer/scripts/post-install-cmd/reps-platform.sh`
to the same location into your subsite project. Make sure that this
file is executable.
This script will install the reps platform in your `lib/` directory.
<file_sep>#!/bin/sh
JSON="lib/composer.json"
MAKE="resources/site.make"
TYPE="reps"
VERSION="~1.0"
# Expand lib folder with reps-platform.
if [ ! -e $JSON ] ; then
composer init --working-dir="lib"
composer require "ec-europa/ec-$TYPE-platform:$VERSION" --working-dir="lib"
elif grep -q "ec-europa/ec-$TYPE-platform" $JSON ; then
composer install --working-dir="lib"
else
composer require "ec-europa/ec-$TYPE-platform:$VERSION" --working-dir="lib"
fi
# If the package is present update the lib source code.
if [ -d "lib/vendor/ec-europa/ec-$TYPE-platform" ] ; then
# Remove $TYPE related sources if any.
rm -rf lib/*/$TYPE
# Create clean folders.
mkdir -p lib/features/$TYPE
mkdir -p lib/themes/$TYPE
mkdir -p lib/modules/$TYPE
# Copy the sources in place.
cp -r lib/vendor/ec-europa/ec-$TYPE-platform/lib/features/* lib/features/$TYPE
cp -r lib/vendor/ec-europa/ec-$TYPE-platform/lib/modules/* lib/modules/$TYPE
cp -r lib/vendor/ec-europa/ec-$TYPE-platform/lib/themes/* lib/themes/$TYPE
cp -f lib/vendor/ec-europa/ec-$TYPE-platform/resources/$TYPE-platform.make resources/$TYPE-platform.make
# Include the $TYPE-platform.make file.
if ! [ -e $MAKE ] 2> /dev/null && [ -e $MAKE".example" ] ; then
mv $MAKE".example" $MAKE;
elif [ -e $MAKE ] ; then
COMMENT="\n\n; ============="
COMMENT="$COMMENT\n; ${TYPE^} platform"
COMMENT="$COMMENT\n; =============\n"
INCLUDE='includes[] = "$TYPE-platform.make"'
grep -q "$INCLUDE" "$MAKE" || echo "$COMMENT$INCLUDE" >> "$MAKE"
else
echo "No site.make file found, $TYPE-platform.make not included!"
fi
fi
|
856f9e1cc37f759ed9a2b3bbdd45fab9610485e2
|
[
"Markdown",
"Shell"
] | 2 |
Markdown
|
verbruggenalex/ec-reps-platform
|
6ea903854161206177033074615373e405de1e87
|
973aad1b0ed67cb2b4543e83af646ede03700716
|
refs/heads/master
|
<file_sep>#!/bin/sh
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[1;31m'
NC='\033[0m' # No Color
PID=$(ps aux | grep -m 1 $1 | grep -v grep | grep -v "terminatePrcs.sh" | awk '{print $2}')
if [ "$PID" != "" ]; then
echo -e "${YELLOW}[WARN]${NC} Executing => kill -SIGTERM $PID"
kill -TERM "$PID"
if [ "$?" = 0 ]; then
echo -e "${GREEN}[SUCCESS]${NC} Process \""$1"\" killed."
else
echo -e "${RED}[ERROR]${NC} Process \""$1"\" could not be killed.\n\tMaybe you need admin privileges?"
fi
else
echo -e "${RED}[ERROR]${NC} Process \""$1"\" doesn't exist."
fi
<file_sep>#!/usr/bin/sh
echo "Status port $1: $(netstat -tulpn | grep ":$1 " | awk '{print $6}')"
<file_sep>#!/usr/bin/sh
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
URL_P1="https://github.com/"
URL_P2=".git"
if [ -d "$2" ]; then
echo -e "${GREEN}[INFO]${NC} Folder $2 found."
cd "$2"
if [ -d "$URL_P2" ]; then
echo -e "${GREEN}[INFO]${NC} Folder $2 contains a valid GitHub repository."
git pull
else
echo -e "${GREEN}[INFO]${NC} Folder $2 is not a valid GitHub repository"
cd ..
git clone $URL_P1$1"/"$2$URL_P2
fi
else
echo -e "${YELLOW}[WARN]${NC} Folder $2 doesn't exist; creating and cloning repository..."
git clone $URL_P1$1"/"$2$URL_P2
fi
echo -e "${GREEN}[INFO]${NC} All done."
<file_sep># bash-collection
A collection of bash scripts
### portStatus
Purpose: show status of given port
Usage: `./portStatus.sh portNumber`
Example run:
```
$ ./portStatus.sh 53
Status port 53: LISTEN
```
### gitManager
Purpose: clone or pull a GitHub repository (keeping it up to date)
Usage: `./gitManager.sh userName repositoryName`
Example run:
```
$ ./gitManager.sh gallorob sisop_program
[WARN] Folder sisop_program doesn't exist; creating and cloning repository...
Cloning into 'sisop_program'...
remote: Enumerating objects: 9, done.
remote: Total 9 (delta 0), reused 0 (delta 0), pack-reused 9
Unpacking objects: 100% (9/9), done.
[INFO] All done.
```
```
$ ./gitManager.sh gallorob sisop_program
[INFO] Folder sisop_program found.
[INFO] Folder sisop_program contains a valid GitHub repository.
Already up to date.
[INFO] All done.
```
### terminatePrcs
Purpose: kill a process by its name
Usage: `./terminatePrcs.sh processName`
Example run:
```
$ ./terminatePrcs.sh gedit
[WARN] Executing => kill -SIGTERM 4807
[SUCCESS] Process "gedit" killed.
```
```
$ ./terminatePrcs.sh gedit
[ERROR] Process "gedit" doesn't exist.
```
|
63dd95f0397497c79d6481ba86864301af2548e0
|
[
"Markdown",
"Shell"
] | 4 |
Shell
|
gallorob/bash-collection
|
b4303461ab396f447bbe2a095150c8aa29638899
|
044a68a1a054e98c67449027d8ffdc0cb9390f0a
|
refs/heads/master
|
<repo_name>bcanvural/spring-security-basic-registration-login-logout<file_sep>/README.md
# Spring Security Basic Registration / Login / Logout
Simple user registration, login, logout using Spring Boot, Spring Security 5.x, Spring MVC, JPA, H2<file_sep>/src/main/resources/messages.properties
label.form.title = Registeration Form
label.form.submit=Submit
label.form.loginLink=Submit
label.user.firstName=First Name
label.user.lastName=Last name
label.user.email=Email
label.user.password=<PASSWORD>
label.user.confirmPass=<PASSWORD>
message.regError = Registration error
<file_sep>/src/main/java/com/github/bcanvural/basicregistration/MyUserDetailsService.java
package com.github.bcanvural.basicregistration;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
@Service
@Transactional
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository repository;
@Autowired
private BCryptPasswordEncoder encoder;
@Override
public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException {
User user = repository.findByEmail(email);
if (user == null) {
throw new UsernameNotFoundException("Username cannot be found");
}
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_authenticated"); //hardcoded
return new org.springframework.security.core.userdetails.User(user.getEmail(),
encoder.encode(user.getPassword()), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
}
|
5617d0e025a42215f85d737830a4e1ee5b307f47
|
[
"Markdown",
"Java",
"INI"
] | 3 |
Markdown
|
bcanvural/spring-security-basic-registration-login-logout
|
c30a7c531706cba8a2dff1280f07ee80402cfede
|
03e335ff61fb4839ad1e49635e7d3d2e0f51ed5a
|
refs/heads/master
|
<file_sep>#include "TimerOne.h"
#include "SevSeg.h"
int count = 0;
SevSeg sevseg;
void setup() {
byte numDigits = 4;
// What pins are your "digit" lines hooked up to?
byte digitPins[] = {2, 3, 4, 5};
// What pins are your "segment" lines hooked up to?
byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
// If COMMON_ANODE makes your display act weird, try COMMON_CATHODE
sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
sevseg.setBrightness(90);
Timer1.initialize(100000);
Timer1.attachInterrupt( tick );
}
void loop() {
// Print the number in "count", put the decimal point in the 1st position
sevseg.setNumber(count, 1);
sevseg.refreshDisplay();
}
void tick() {
count = (count + 1) % 10000;
}
|
b535468247f9e801bc385d703d77b2265d068457
|
[
"C++"
] | 1 |
C++
|
joonyeechuah/tinkering-timer
|
ccbf212de55953eabd438df21cc279aa4be41429
|
dab5b44d1887ca1037c9875e4863953355c1a41e
|
refs/heads/master
|
<repo_name>LionRoar/Head-First-Design-Patterns-PHP<file_sep>/ch11/MightyGumball/Service/SoldOutState.php
<?php
namespace MG\Service;
class SoldOutState implements StateInterface {
private $machine;
public function __construct(GumballMachine $machine) {
$this->machine = $machine;
}
public function insertQuarter() {
echo "You can't insert a quarter , the machine is sold out\n";
}
public function ejectQuarter() {
echo "You can't eject, You haven't inserted a quarter yet\n";
}
public function turnCrank() {
echo "You turned, but there are no gumballs\n";
}
public function dispense() {
echo "No gumball dispensed \n";
}
public function description(): string {
return "Sold out.";
}
}<file_sep>/ch11/MightyGumball/Client/GumballMachineProxy.php
<?php
namespace MG\Client;
use MG\GumballMachineInterface;
class GumballMachineProxy implements GumballMachineInterface {
private $machine;
public function __construct(RequestInterface $remoteMachine) {
$this->machine = $remoteMachine->get();
}
public function getCount(): int {
return $this->machine['count'];
}
public function getLocation(): string {
return $this->machine['location'];
}
public function getState(): string {
return $this->machine['state'];
}
public function getRemotePath(): string {
return $this->machine['path'];
}
}<file_sep>/ch04/PizzaStore/ChicagoPizzaIngredientFactory.php
<?php
#region use
use Ingredients\Dough;
use Ingredients\Sauce;
use Ingredients\Cheese;
use Ingredients\Clams;
use Ingredients\Pepperoni;
use Ingredients\Dough\ThickCrustDough;
use Ingredients\Sauce\PulmTomatoSauce;
use Ingredients\Cheese\MozzarellaCheese;
use Ingredients\Pepperoni\SlicedPepperoni;
use Ingredients\Clams\FrozenClams;
use Ingredients\Veggies\BlackOlives;
use Ingredients\Veggies\Spinach;
use Ingredients\Veggies\EggPlant;
#endregion
class ChicagoPizzaIngredientFactory implements PizzaIngredientFactory {
public function createDough(): Dough
{
return new ThickCrustDough();
}
public function createSauce(): Sauce
{
return new PulmTomatoSauce();
}
public function createCheese(): Cheese
{
return new MozzarellaCheese();
}
public function createVeggies(): array
{
return [new BlackOlives(), new Spinach() , new EggPlant()];
}
public function createPepperoni(): Pepperoni
{
return new SlicedPepperoni();
}
public function createClam(): Clams
{
return new FrozenClams();
}
}<file_sep>/ch11/MightyGumball/Client/RequestInterface.php
<?php
namespace MG\Client;
interface RequestInterface {
public function get(): array;
}<file_sep>/ch01/ShoppingCart/PaypalStrategy.php
<?php
class PaypalStrategy implements PaymentStrategy {
private $email;
private $password;
public function __construct(string $email , string $passwd)
{
$this->email = $email;
$this->password = $passwd;
}
public function pay(int $amount){
echo "$amount paid using paypal.\n";
}
}<file_sep>/ch09/ObjectvilleDinerPancakeHouse/UnsupportedException.php
<?php
class UnsupportedException extends Exception {
public function __construct(){
parent::__construct("Unsupported Operation");
}
}<file_sep>/ch07/TurkeyAdapter/index.php
<?php
require_once './vendor/autoload.php';
#region use
#endregion
$duck = new MallardDuck();
$turkey = new WildTurkey();
$just_a_normal_duck = new TurkeyAdapter($turkey);
echo "The Turkey says.. \n";
$turkey->gobble();
$turkey->fly();
echo PHP_EOL;
echo "The Duck says.. \n";
$duck->quack();
$duck->fly();
echo PHP_EOL;
echo "The Turkey Adapter says..\n";
legitDuckTest($just_a_normal_duck);
echo PHP_EOL;
function legitDuckTest(Duck $duck){
$duck->quack();
$duck->fly();
}
echo "\nwhat does the fox say ?\n";<file_sep>/ch07/HomeTheaterFacade/Components/DvdPlayer.php
<?php
namespace Components;
class DvdPlayer
{
private $movie;
public function on(){
echo "DVD player on " . PHP_EOL;
}
public function play(string $movie){
$this->movie = $movie;
echo "DVD Player playing '$movie' " . PHP_EOL;
}
public function stop(){
echo "DVD Player stopped '". $this->movie . "'". PHP_EOL;
}
public function eject(){
echo "DVD Player eject " . PHP_EOL;
}
public function off(){
echo "DVD Player off " . PHP_EOL;
}
}
<file_sep>/ch09/ObjectvilleDinerPancakeHouse/NullIterator.php
<?php
class NullIterator implements IteratorInterface {
public function next(){
return NULL;
}
public function hasNext() : bool {
return false;
}
}<file_sep>/ch06/BankTransaction/Debit.php
<?php
class Debit implements Transaction {
private $debitAmount = 0;
public function setAmount(int $amount){
if($amount > 0 ){
$this->debitAmount = $amount;
}
}
public function execute(): bool
{
echo "Processing debit with the bank : " . $this->debitAmount .
PHP_EOL;
return false;
}
public function rollback()
{
echo "request cancellation of debit to the bank fot amount : " .
$this->debitAmount . PHP_EOL;
}
}<file_sep>/ch02/Weather-O-Rama/DisplayElement.php
<?php
abstract class DisplayElement implements SplObserver {
/**
* for $weatherSubject
* In the future you may want to un-register this observer
* and it would be handy to already have a reference to the subject.
*
*/
private $weatherSubject;
public function __construct(SplSubject $subject){
$this->weatherSubject = $subject;
$this->weatherSubject->attach($this); //register
}
public function unsubscribe(){
$this->weatherSubject->detach($this);
}
public function resubscribe(){
$this->weatherSubject->attach($this);
}
abstract public function display();
}<file_sep>/ch07/TurkeyAdapter/Duck.php
<?php
interface Duck {
public function quack();
public function fly();
}<file_sep>/ch08/StarbuzzCoffeeRecipe/CaffeineBeverage.php
<?php
abstract class CaffeineBeverage {
/**
* Template method
* declared as final to prevent subclasses from changing the algorithm
*
* @return void
*/
final public function prepareRecipe(){//Template method
$this->boilWater();
$this->brew();
$this->pourInCup();
$this->addCondiments();
}
abstract protected function brew();
abstract protected function addCondiments();
private function boilWater(){
echo "Boiling water " . PHP_EOL;
}
private function pourInCup(){
echo "Pouring in cup " . PHP_EOL;
}
}<file_sep>/ch07/HomeTheaterFacade/Components/Tuner.php
<?php
namespace Components;
class Tuner
{
}
<file_sep>/ch06/HomeAutomation/Commands/CeilingFanOffCommand.php
<?php
namespace Commands;
use Receiver\CeilingFan;
use \Command;
class CeilingFanOffCommand implements Command {
private $fan;
private $prevSpeed;
public function __construct(CeilingFan $fan) {
$this->fan = $fan;
}
public function execute() {
$this->prevSpeed = $this->fan->getSpeed();
$this->fan->off();
}
public function undo(){
$this->ceilingFan->setSpeed($this->prevSpeed);
}
}<file_sep>/ch08/StarbuzzCoffeeRecipe/index.php
<?php
require_once './vendor/autoload.php';
#region use
#endregion
//$myTea = new Tea();
//$myTea->prepareRecipe();
$teaHook = new TeaWithHook();
$coffeeHook = new CoffeeWithHook();
echo "\nMaking tea...\n";
$teaHook->prepareRecipe();
echo "\nMaking coffee...\n";
$coffeeHook->prepareRecipe();
<file_sep>/ch04/PizzaStore/NYPizzaIngredientFactory.php
<?php
#region use
use Ingredients\Dough;
use Ingredients\Sauce;
use Ingredients\Cheese;
use Ingredients\Clams;
use Ingredients\Pepperoni;
use Ingredients\Veggies\Garlic;
use Ingredients\Veggies\RedPepper;
use Ingredients\Veggies\Onion;
use Ingredients\Veggies\Mushroom;
use Ingredients\Dough\ThinCrustDough;
use Ingredients\Sauce\MarinaraSauce;
use Ingredients\Cheese\ReggianCheese;
use Ingredients\Pepperoni\SlicedPepperoni;
use Ingredients\Clams\FreshClams;
#endregion
class NYPizzaIngredientFactory implements PizzaIngredientFactory {
public function createDough(): Dough
{
return new ThinCrustDough();
}
public function createSauce(): Sauce
{
return new MarinaraSauce();
}
public function createCheese(): Cheese
{
return new ReggianCheese();
}
public function createVeggies(): array
{
return [new Garlic(), new Onion() , new Mushroom() , new RedPepper()];
}
public function createPepperoni(): Pepperoni
{
return new SlicedPepperoni();
}
public function createClam(): Clams
{
return new FreshClams();
}
}<file_sep>/ch06/BankTransaction/index.php
<?php
require_once './vendor/autoload.php';
$executioner = new TransactionExecutioner();
$executioner->setCommand(new ShareData());
$executioner->setCommand(new Authenticate());
$executioner->setCommand(new Debit());
$executioner->setCommand(new Acknowledge());
$executioner->runCommands();
<file_sep>/ch02/Weather-O-Rama/WeatherData.php
<?php
/**
* * Implements built-in subject(publisher) interface SplSubject
* see: http://php.net/manual/en/class.splsubject.php
*/
class WeatherData implements SplSubject {
private $temperature;
private $humidity;
private $pressure;
private $observers = array();
public function attach(SplObserver $observer)
{ /**
* spl_object_hash
* This function returns a unique identifier for the object.
*/
$uid = spl_object_hash($observer);
$this->observers[$uid] = $observer;
}
public function detach(SplObserver $observer)
{
$uid = spl_object_hash($observer);
unset($this->observers[$uid]);
}
public function notify()
{
foreach($this->observers as $observer){
$observer->update($this);
}
}
public function setWeatherData(array $data){
$this->temperature = $data["temperature"];
$this->humidity = $data["humidity"];
$this->pressure = $data["pressure"];
$this->notify();
}
public function getWeatherData() : array {
return array(
"temperature" => $this->temperature,
"humidity" => $this->humidity,
"pressure" => $this->pressure
);
}
}<file_sep>/ch04/PizzaStore/ChicagoPizzaStore.php
<?php
class ChicagoPizzaStore extends PizzaStore {
protected function createPizza(string $type): Pizza
{
$pizza = null;
$pizzaIngredientFactory = new ChicagoPizzaIngredientFactory();
switch ($type) {
case 'cheese':
$pizza = new CheesePizza($pizzaIngredientFactory);
$pizza->setName("Chicago Style Deep Dish Cheese Pizza");
break;
default:
throw new Exception("We dont have $type Pizza");
break;
}
return $pizza;
}
}<file_sep>/ch06/HomeAutomation/Receiver/GarageDoor.php
<?php namespace Receiver;
class GarageDoor {
public function up(){
echo 'Garage door opened.' . PHP_EOL;
}
public function down(){
echo 'Garage door is closed. '. PHP_EOL;
}
}<file_sep>/ch09/ObjectvilleDinerPancakeHouse/Menu.php
<?php
class Menu extends MenuComponent {
private $menuComponents = array();
private $name;
private $description;
private $compositeIterator = NULL;
public function __construct(string $name , string $description){
$this->name = $name;
$this->description = $description;
}
public function add(MenuComponent $menuComponent){
array_push($this->menuComponents , $menuComponent);
}
public function remove(MenuComponent $menuComponent){
$this->menuComponents = array_diff($this->menuComponents , array($menuComponent));
}
public function getChild(int $i) : MenuComponent {
return $this->menuComponents[$i];
}
public function getName() : string {
return $this->name;
}
public function getDescription() : string {
return $this->description;
}
public function print(){
echo PHP_EOL . $this->getName();
echo ", " . $this->getDescription() . PHP_EOL;
echo "-----------------------------". PHP_EOL;
$iterator = new MenuComponentsIterator($this->menuComponents);
while($iterator->hasNext()){
$menuComponent = $iterator->next();
$menuComponent->print();
}
}
public function createIterator() : IteratorInterface {
if(is_null($this->compositeIterator))
$this->compositeIterator = new CompositeIterator(
new MenuComponentsIterator($this->menuComponents)
);
return $this->compositeIterator;
}
}<file_sep>/ch01/simUDuck/Squeak.php
<?php
class Squeak implements QuackBehavior {
public function quack() {
echo 'Squeak' . PHP_EOL;
}
}
<file_sep>/ch04/PizzaStore/Ingredients/Veggies/Mushroom.php
<?php
namespace Ingredients\Veggies;
class Mushroom {
}<file_sep>/ch06/HomeAutomation/Receiver/Light.php
<?php
namespace Receiver;
class Light {
private $name = '' ;
public function __construct(string $name)
{
if(isset($name))
$this->name = $name;
}
public function on(){
echo $this->name . ' Light is ON.' . PHP_EOL;
}
public function off(){
echo $this->name . ' Light is OFF. ' . PHP_EOL;
}
}<file_sep>/ch06/HomeAutomation/Commands/StereoOffCommand.php
<?php
namespace Commands;
use \Command;
use Receiver\Stereo;
class StereoOffCommand implements Command {
private $stereo;
public function __construct(Stereo $stereo){
$this->stereo = $stereo;
}
public function execute(){
$this->stereo->off();
}
public function undo(){
$this->stereo->on();
}
}<file_sep>/ch11/MightyGumball/GumballMachineInterface.php
<?php
namespace MG;
interface GumballMachineInterface {
public function getCount(): int;
public function getLocation(): string;
public function getState(): string;
}<file_sep>/ch06/HomeAutomation/Commands/NoCommand.php
<?php namespace Commands;
class NoCommand implements \Command {
public function execute()
{
echo 'No command is set.' . PHP_EOL;
}
public function undo(){}
}<file_sep>/ch06/BankTransaction/TransactionExecutioner.php
<?php
class TransactionExecutioner {
private $commandQueue = Array();
private $executeStack = Array();
public function setCommand(Transaction $command){
array_push($this->commandQueue , $command);
}
public function runCommands(){
try{
while(count($this->commandQueue) > 0 ){
$command = array_shift($this->commandQueue);
if($command->execute()){
array_push($this->executeStack,$command);
}else{
$this->rollbackCommands(); break;
}
}
}catch(Exception $e){
$this->rollbackCommands();
}finally {
$this->commandQueue = array();
$this->executeStack = array();
}
}
public function rollbackCommands(){
//roll back the commands in reverse
//order of their execution
while(count($this->executeStack) > 0 ){
$command = array_pop($this->executeStack);
$command->rollback();
}
}
}<file_sep>/ch03/StarbuzzCoffee/Mocha.php
<?php
class Mocha extends CondimentDecorator {
public function __construct(Beverage $beverage)
{
$this->description ="Mocha";
$this->beverage = $beverage;
}
public function cost(): float{
return 0.20 + $this->beverage->cost();
}
}<file_sep>/ch04/PizzaStoreFactoryMethod/ChicagoCheesePizza.php
<?php
class ChicagoCheesePizza extends Pizza {
public function __construct(){
$this->name ="Chicago Style Deep Dish Cheese Pizza";
$this->dough = "Extra Thick Crust Dough";
$this->sauce = "Plum Tomato Sauce";
$this->toppings = ['Shredded Mozzarella Cheese'];
}
public function cut(){
echo "Cutting the pizza into square slices\n";
}
}<file_sep>/ch02/Weather-O-Rama/ForecastDisplay.php
<?php
class ForecastDisplay extends DisplayElement {
private $temperature;
private $humidity;
private $pressure;
public function update(SplSubject $subject)
{
$data = $subject->getWeatherData();
$this->temperature = $data["temperature"];
$this->humidity = $data["humidity"];
$this->pressure = $data["pressure"];
$this->display();
}
public function display()
{
echo "\n~~~~Forecast~~~~\n".
"$this->temperature"."F degree and".
" Humidity $this->humidity% also Pressure is $this->pressure".
"Pa\n~~~~~~~~~~~~~~~~\n";
}
}
<file_sep>/ch10/MightyGumball/NoQuarterState.php
<?php
class NoQuarterState implements StateInterface {
private $machine;
public function __construct(GumballMachine $machine) {
$this->machine = $machine;
}
public function insertQuarter() {
echo "You inserted a quarter.\n";
$this->machine->setState($this->machine->getHasQuarterState());
}
public function ejectQuarter() {
echo "You haven't inserted a quarter\n";
}
public function turnCrank() {
echo "You turned but there's no quarter\n";
}
public function dispense() {
echo "You need to pay for your balls\n";
}
public function description(): string {
return "has no quarter.";
}
}<file_sep>/ch03/StarbuzzCoffee/CondimentPrettyPrint.php
<?php
class CondimentPrettyPrint extends Beverage {
protected $beverage;
public function __construct(Beverage $beverage)
{
$this->beverage = $beverage;
}
public function getDescription(): string
{
$description = '';
$array = explode(', ', $this->beverage->getDescription());
$mix = array_count_values($array);
foreach($mix as $condiment => $count){
$description .= $count == 2 ? 'Double ' . $condiment . ', ' : $condiment . ', ';
}
return $description;
}
public function cost() : float {
return $this->beverage->cost();
}
}<file_sep>/ch04/PizzaStore/Ingredients/Sauce/MarinaraSauce.php
<?php
namespace Ingredients\Sauce;
use Ingredients\Sauce;
class MarinaraSauce implements Sauce {
public function __construct()
{
echo "Marinara Sauce \n";
}
}<file_sep>/ch04/PizzaStore/CheesePizza.php
<?php
class CheesePizza extends Pizza {
//ingredient Factory
private $iFac;
public function __construct(PizzaIngredientFactory $pif){
$this->iFac = $pif;
}
public function prepare()
{
echo "Preparing $this->name\n";
$this->dough = $this->iFac->createDough();
$this->sauce = $this->iFac->createSauce();
$this->cheese =$this->iFac->createCheese();
}
}<file_sep>/ch04/PizzaStoreFactoryMethod/NYPizzaStore.php
<?php
class NYPizzaStore extends PizzaStore {
protected function createPizza(string $type) : Pizza {
switch ($type) {
case 'cheese':
return new NYCheesePizza();
break;
// case 'veggie':
// return new NYVeggiePizza();
// break;
// case 'pepperoni':
// return new NYPepperoniPizza();
break;
default:
return null;
break;
}
}
}<file_sep>/ch04/PizzaStore/Ingredients/Veggies/Garlic.php
<?php
namespace Ingredients\Veggies;
class Garlic {
}<file_sep>/ch06/HomeAutomation/Commands/StereoOnWithCDCommand.php
<?php
namespace Commands;
use \Command;
use Receiver\Stereo;
class StereoOnWithCDCommand implements Command {
private $stereo;
public function __construct(Stereo $stereo){
$this->stereo = $stereo;
}
public function execute(){
$this->stereo->on();
$this->stereo->setCD();
$this->stereo->setVolume(11);
}
public function undo(){
$this->stereo->off();
}
}<file_sep>/ch03/PHP_IO_DECORATOR/index.php
<?php
require_once './vendor/autoload.php';
/* Register our filter with PHP */
stream_filter_register("strtolower", LowerCaseInputStream::class)
or die("Failed to register filter");
/* Open file for read */
$fp = fopen("test.txt", "r");
/* Attach the registered filter to the stream just opened */
stream_filter_append($fp, "strtolower");
/* Read the contents back out */
echo stream_get_contents($fp);
<file_sep>/ch07/TurkeyAdapter/DuckAdapter.php
<?php
//Sharp-your-pencil challenge
class DuckAdapter implements Turkey {
private $duck;//Adaptee
public function __construct(Duck $duck){
$this->duck = $duck;
}
public function gobble(){
$this->duck->quack();
}
public function fly(){
$this->duck->fly();
}
}<file_sep>/ch04/PizzaStore/NYPizzaStore.php
<?php
class NYPizzaStore extends PizzaStore {
protected function createPizza(string $type): Pizza
{
$pizza = null;
$pizzaIngredientFactory = new NYPizzaIngredientFactory();
switch ($type) {
case 'cheese':
$pizza = new CheesePizza($pizzaIngredientFactory);
$pizza->setName("New York Style Cheese Pizza");
break;
default:
throw new Exception("We dont have $type Pizza");
break;
}
return $pizza;
}
}<file_sep>/ch07/TurkeyAdapter/TurkeyAdapter.php
<?php
/**
* you’re short on Duck objects and you’d like to use some
* Turkey objects in their place
*/
class TurkeyAdapter implements Duck {
private $turkey;
public function __construct(Turkey $turkey){
$this->turkey = $turkey;
}
public function quack(){
$this->turkey->gobble();
}
public function fly(){
/**
* Turkeys fly in short spurts - they
* can’t do long-distance flying like ducks. To
* map between a Duck’s fly() method and a
* Turkey’s, we need to call the Turkey’s fly()
* method five times to make up for it.
*/
for($i = 0 ; $i < 5 ; $i++){
$this->turkey->fly();
}
}
}<file_sep>/ch01/ShoppingCart/index.php
<?php
require_once './vendor/autoload.php';
$cart = new ShoppingCart();
$item1 = new Item('4545', 10);
$item2 = new Item('5656', 40);
$cart->addItem($item1);
$cart->addItem($item2);
$cart->pay(new PaypalStrategy('<EMAIL>','<PASSWORD>'));
$cart->removeItem($item2);
$cart->pay(new CreditCardStrategy('leone ateniese', '45568888888900','555','12/01'));
<file_sep>/ch07/HomeTheaterFacade/Components/TheaterLights.php
<?php
namespace Components;
class TheaterLights
{
public function dim(int $value){
echo "Theater Lights are dimmed to $value%" . PHP_EOL;
}
public function on(){
echo "Theater Lights on " . PHP_EOL;
}
}
<file_sep>/ch08/StarbuzzCoffeeRecipe/Coffee.php
<?php
class Coffee extends CaffeineBeverage {
protected function brew(){
echo "Dripping coffee through filter " . PHP_EOL;
}
protected function addCondiments(){
echo "Adding sugar and milk " . PHP_EOL;
}
}<file_sep>/ch04/PizzaStore/Ingredients/Veggies/Onion.php
<?php
namespace Ingredients\Veggies;
class Onion {
}<file_sep>/ch11/MightyGumball/Service/GumballMachine.php
<?php
namespace MG\Service;
class GumballMachine implements \MG\GumballMachineInterface {
private $soldOutState;
private $noQuarterState;
private $hasQuarterState;
private $soldState;
private $location;
private $winnerState;
private $state;
private $count = 0;
public function __construct(string $location, int $numberOfGumballs) {
$this->soldOutState = new SoldOutState($this);
$this->noQuarterState = new NoQuarterState($this);
$this->hasQuarterState = new HasQuarterState($this);
$this->soldState = new SoldState($this);
$this->winnerState = new WinnerState($this);
$this->location = $location;
$this->count = $numberOfGumballs;
if ($this->count > 0) {
$this->state = $this->noQuarterState;
} else {
$this->state = $this->soldOutState;
}
}
public function insertQuarter() {
$this->state->insertQuarter();
}
public function ejectQuarter() {
$this->state->ejectQuarter();
}
public function turnCrank() {
$this->state->turnCrank();
$this->state->dispense();
}
public function setState(StateInterface $state) {
$this->state = $state;
}
public function releaseBall() {
echo "A gumball comes rolling out the slot...\n";
if ($this->count !== 0) {
$this->count -= 1;
}
}
public function getCount(): int {
return $this->count;
}
public function getNoQuarterState() {
return $this->noQuarterState;
}
public function getHasQuarterState() {
return $this->hasQuarterState;
}
public function getSoldOutState() {
return $this->soldOutState;
}
public function getSoldState() {
return $this->soldState;
}
public function getWinnerState() {
return $this->winnerState;
}
public function getState(): string {
return $this->state->description() . "\n";
}
public function getLocation(): string {
return $this->location;
}
public function refill(int $numberOfGumballs) {
$this->count += $numberOfGumballs;
$this->setState($this->getNoQuarterState());
}
public function __toString() {
$gumballMachine = "\nMighty Gumball, Inc.\n"
. "PHP-enabled Standing Gumball Model #2018\n"
. "Inventory: " . $this->getCount() . " gumballs\n"
. $this->getState();
return $gumballMachine;
}
}<file_sep>/ch07/HomeTheaterFacade/Components/Amplifier.php
<?php
namespace Components;
class Amplifier
{
public function on(){
echo "Amplifier on " . PHP_EOL;
}
public function setDvd(DvdPlayer $dvd){
echo "Amplifier is set to dvd ". PHP_EOL;
}
public function setSurroundSound(){
echo "Amplifier surround sound on (5 speakers , 1 subwoofer) " . PHP_EOL;
}
public function setVolume(int $volume){
echo "Amplifier volume is set to $volume " . PHP_EOL ;
}
public function off(){
echo "Amplifier turned off " . PHP_EOL;
}
}
<file_sep>/ch05/Choc-O-Holic/ChocolateBoiler.php
<?php
/**
* Singleton class
*/
class ChocolateBoiler {
//Private static variable to store the only instance of the class.
private static $instance;
//props
private $empty;
private $boiled;
/**
* Private constructor
*/
private function __construct(){
$this->empty = true;
$this->boiled = false;
}
/**
* Public static method that returns the instance of the class,
*
* @return ChocolateBoiler
*/
public static function getInstance() : ChocolateBoiler {
if( self::$instance == null ){
self::$instance = new ChocolateBoiler();
}
return self::$instance;
}
public function isEmpty() : bool{
return $this->empty;
}
public function isBoiled() : bool{
return $this->boiled;
}
public function fill(){
if($this->isEmpty()){
$this->empty = false;
$this->boiled = false;
// fill the boiler with a milk/chocolate mixture
}
}
public function drain(){
if(!$this->isEmpty() && $this->isBoiled()){
// drain the boiled milk and chocolate
$this->empty = true;
}
}
public function boil(){
if(!$this->isEmpty() && !$this->isBoiled()){
// bring the contents to a boil
$this->boiled = true;
}
}
}<file_sep>/ch09/ObjectvilleDinerPancakeHouse/Waitress.php
<?php
class Waitress {
private $menus;
public function __construct(MenuComponent $allMenus){
$this->menus = $allMenus;
}
public function printMenu(){
$this->menus->print();
}
public function printVegetarianMenu(){
$iterator = $this->menus->createIterator();
echo "\nVEGETARIAN MENU\n---------------\n";
while($iterator->hasNext()){
$menuComponent = $iterator->next();
try {
if($menuComponent->isVegetarian())
$menuComponent->print();
} catch (UnsupportedException $e) {
//var_dump($menuComponent->getName());
}
}
}
}<file_sep>/ch01/ShoppingCart/PaymentStrategy.php
<?php
interface PaymentStrategy {
public function pay(int $amount);
}<file_sep>/ch04/PizzaStore/Ingredients/Cheese/MozzarellaCheese.php
<?php
namespace Ingredients\Cheese;
use Ingredients\Cheese;
class MozzarellaCheese implements Cheese {
public function __construct()
{
echo "Mozzarella Cheese \n";
}
}<file_sep>/ch04/PizzaStore/Ingredients/Clams/FrozenClams.php
<?php
namespace Ingredients\Clams;
use Ingredients\Clams;
class FrozenClams implements Clams {
public function __construct()
{
echo "Frozen Clams\n";
}
}<file_sep>/ch01/ShoppingCart/CreditCardStrategy.php
<?php
class CreditCardStrategy implements PaymentStrategy {
private $name;
private $cardNo;
private $cvv;
private $expDate;
public function __construct(
string $name , string $ccno ,
string $cvv, string $exp){
$this->name = $name;
$this->cardNo = $ccno;
$this->cvv = $cvv;
$this->expDate = $exp;
}
public function pay(int $amount){
echo "$amount paid with credit/debit card. \n";
}
}<file_sep>/ch10/MightyGumball/SoldState.php
<?php
class SoldState implements StateInterface {
private $machine;
public function __construct(GumballMachine $machine) {
$this->machine = $machine;
}
public function insertQuarter() {
echo "Please wait, We're already giving you a gumball\n";
}
public function ejectQuarter() {
echo "Sorry, you already turned the crank\n";
}
public function turnCrank() {
echo "Turning Twice doesn't get you another gumball\n";
}
public function dispense() {
$this->machine->releaseBall();
if ($this->machine->getCount() <= 0) {
echo "Oops, out of gumballs\n";
$this->machine->setState($this->machine->getSoldOutState());
} else {
$this->machine->setState($this->machine->getNoQuarterState());
}
}
public function description(): string {
return "Gumball sold.";
}
}<file_sep>/ch04/PizzaStore/Pizza.php
<?php
abstract class Pizza {
protected $name;
protected $dough;
protected $sauce;
protected $veggies = array();
protected $cheese;
protected $pepperoni;
protected $clams;
abstract public function prepare() ;
public function bake(){
echo "Bake for 25 minute at 350\n";
}
public function cut(){
echo "Cutting the pizza into diagonal slices\n";
}
public function box(){
echo "Place Pizza in official PizzaStore box\n\n";
}
public function setName(string $name){
$this->name = $name;
}
public function getName() : string {
return $this->name;
}
public function __toString()
{
return $this->name ;
}
}<file_sep>/ch02/Weather-O-Rama/CurrentConditionDisplay.php
<?php
class CurrentConditionDisplay extends DisplayElement {
private $temperature;
private $humidity;
public function update(SplSubject $subject)
{
$data = $subject->getWeatherData();
$this->temperature = $data["temperature"];
$this->humidity = $data["humidity"];
$this->display();
}
public function display()
{
echo "\nCurrent condition: $this->temperature"."F degree and".
" Humidity $this->humidity%\n";
}
}
<file_sep>/ch07/HomeTheaterFacade/Components/Screen.php
<?php
namespace Components;
class Screen
{
public function up(){
echo "Screen is going up " . PHP_EOL;
}
public function down(){
echo "Screen is going down " . PHP_EOL;
}
}
<file_sep>/ch11/MightyGumball/Client/JsonRequest.php
<?php
namespace MG\Client;
class JsonRequest implements RequestInterface {
private $path;
public function __construct($path) {
$this->path = $path;
}
public function get(): array{
$curl = curl_init($this->path);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
if (!isset($response)) {
throw Exception('failed to connect to remote object ' . $response['error']);
}
$response = json_decode($response, true);
$response['path'] = $this->path;
return $response;
}
}<file_sep>/ch04/PizzaStore/Ingredients/Veggies/RedPepper.php
<?php
namespace Ingredients\Veggies;
class RedPepper {
}<file_sep>/ch01/simUDuck/index.php
<?php
require_once './vendor/autoload.php';
$mallard = new MallardDuck();
$mallard->display();
$mallard->preformQuack();
$mallard->preformFly();
$duck = new ModelDuck();
$duck->display();
$duck->preformFly();
$duck->preformQuack();
$duck->setFlyBehavior(new FlyRocketPowered());
$duck->preformFly();
<file_sep>/ch04/PizzaStore/Ingredients/Veggies/Spinach.php
<?php
namespace Ingredients\Veggies;
class Spinach {
}<file_sep>/ch04/PizzaStore/Ingredients/Sauce.php
<?php
namespace Ingredients;
interface Sauce {
}<file_sep>/ch07/HomeTheaterFacade/Components/CdPlayer.php
<?php
namespace Components;
class CdPlayer
{
}
<file_sep>/ch01/simUDuck/FlyRocketPowered.php
<?php
class FlyRocketPowered implements FlyBehavior {
public function fly() {
echo 'flying rocket 🚀' . PHP_EOL;
}
}<file_sep>/ch06/BankTransaction/Transaction.php
<?php
//* Command interface
interface Transaction {
public function execute() : bool;
public function rollback();
}<file_sep>/ch03/StarbuzzCoffee/index.php
<?php
require_once './vendor/autoload.php';
//* Order up an espresso, no condiments
$beverage = new Espresso();
echo $beverage->getDescription() . " $". $beverage->cost() . PHP_EOL;
//* Make DarkRoast with double mocha and whip
$beverage2 = new DarkRoast();
$beverage2 = new Mocha($beverage2);
$beverage2 = new Mocha($beverage2);
$beverage2 = new Whip($beverage2);
echo $beverage2->getDescription() . " $". $beverage2->cost() . PHP_EOL;
//* give us a HouseBlend with Soy, Mocha, and Whip
$beverage3 = new HouseBlend();
$beverage3 = new Soy($beverage3);
$beverage3 = new Mocha($beverage3);
$beverage3 = new Whip($beverage3);
echo $beverage3->getDescription() . " $". $beverage3->cost() . PHP_EOL;
//* PrettyPrint Make DarkRoast with double mocha and whip
$beverage4 = new DarkRoast();
$beverage4 = new Whip($beverage4);
$beverage4 = new Mocha($beverage4);
$beverage4 = new Mocha($beverage4);
$beverage4 = new CondimentPrettyPrint($beverage4);
echo $beverage4->getDescription() . " $". $beverage4->cost() . PHP_EOL;<file_sep>/ch06/HomeAutomation/RemoteControl.php
<?php
use Commands\NoCommand;
class RemoteControl
{
/**
* @var Command[]
*/
private $onCommands = [];
/**
* @var Command[]
*/
private $offCommands = [];
/**
* @var Command
*/
private $undoCommand; // track the last command
public function __construct()
{
$NoCommand = new NoCommand;
for ($i = 0; $i < 7; $i++) {
$this->onCommands[$i] = $NoCommand;
$this->offCommands[$i] = $NoCommand;
}
$undoCommand = $NoCommand;
}
public function setCommand(int $slot, Command $on, Command $off)
{
$this->onCommands[$slot] = $on;
$this->offCommands[$slot] = $off;
}
public function onButtonWasPushed(int $slot)
{
if (isset($this->onCommands[$slot])) {
$this->onCommands[$slot]->execute();
$this->undoCommand = $this->onCommands[$slot];
} else throw new Exception('Slot is empty.');
}
public function offButtonWasPushed(int $slot)
{
if (isset($this->offCommands[$slot])) {
$this->offCommands[$slot]->execute();
$this->undoCommand = $this->offCommands[$slot];
} else throw new Exception('Slot is empty.');
}
public function undoButtonWasPushed()
{
echo "[ <-undo ] : \n";
$this->undoCommand->undo();
}
private function class_name($class): string
{
$className = get_class($class);
$lastSlash = strpos($className, '\\') + 1;
$className = substr($className, $lastSlash);
return $className;
}
public function __toString()
{
$str = "\n-------- Remote Control --------\n";
for ($i = 0; $i < count($this->onCommands); $i++) {
$str .= "[slot $i] | " .
$this->class_name($this->onCommands[$i])
. " | " . $this->class_name($this->offCommands[$i]) . "\n";
}
$str .= "[undo] " . $this->class_name($this->undoCommand) . "\n"
. "--------------------------------\n\n";
return $str;
}
}
<file_sep>/ch04/PizzaStore/Ingredients/Cheese.php
<?php
namespace Ingredients;
interface Cheese {
}<file_sep>/README.md
# Head-First-Design-Patterns-PHP
## Head First Design Patterns : A Brain-Friendly Guide book examples code in PHP
---
**The original code in the book is in java.**
**I chose this book because it has a really unique way of describing things and making them easy to understand maybe somebody else will find it useful.**
---
## Run the code
First you have to generate the auto loader with composer
note: __*Do this step for each folder that have composer.json within*__
> *All examples are tested with php7.2*
``` bash
$ composer dump-autoload
$ php index.php
```
e.g: if we want to run the `simUDuck` example of chapter 1 `ch01` then
``` bash
1. $ cd /ch01/simUDuck
2. $ composer dump-autoload
3. $ php index.php
```
---
## Notes index
* [chapter 1 : Strategy Pattern](#ch1)
* [chapter 2 : Observer Pattern](#ch2)
* [chapter 3 : Decorator Pattern (Design Eye for The Inheritance Guy)](#ch3)
* [chapter 4 : Factory method , Abstract factory , Dependency Inversion](#ch4)
* [chapter 5 : Singleton](#ch5)
* [chapter 6 : Command pattern](#ch6)
* [chapter 7 : The Adapter and The Facade Patterns](#ch7)
* [chapter 8 : Template Method Pattern [Encapsulating Algorithms]](#ch8)
* [chapter 9 : The Iterator and Composite Patterns **Well-Managed Collection**](#ch9)
* [chapter 10 : The State Pattern *The State of Things* ](#ch10)
* [chapter 11 : The Proxy Pattern *Controlling Object Access* ](#ch11)
---
# MY-NOTES
---
<h1 id="ch1">chapter 1: Strategy Pattern</h1>
`aka Policy Pattern`
> Defines a set of encapsulated algorithms that can be swapped to carry out a specific behavior.
__more formal definition:__
> The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable.
> Strategy lets the algorithm vary independently from
clients that use it.
## Strategy pattern used when
Strategy pattern is used when we have multiple algorithms for specific task and the client decides the actual implementation to be used at runtime.
### Notes
* `CHANGE` is the one constant in software development.
* The Example in the book shows that when inheritance hasn’t worked out very well, since the behavior keeps changing across the subclasses and it's not appropriate for all subclasses to have those behaviors, The interface solution sounds promising and can be done in PHP using [Traits](https://www.php.net/manual/en/language.oop5.traits.php) but cant be done in java because java have no code reuse so in java if there's a change you have to track down all the subclasses where that behavior is defined *probably introducing new bugs along the way!*
> 1.Design Principle **Enacapsulate** :
> Identify the aspects of your application that vary and separate them from what stays the same.
> Another way to think about this principle:
> take the parts that vary and encapsulate them, so that later you can alter or > extend the parts that vary without affecting those that don’t.
* Encapsulate what change and you will have flexible system.
* Separate the code that will be changed.
* When you have subclasses that differ in a behavior(s) pull out what varies and (encapsulate) create new set of classes to represent each behavior.
> 2.Design Principle :
> Program to an **interface** not an implementation
> *An interface in this context could also refers to an abstract class or class that implements particular behavior*
* Use an interface to represent each behavior and Each implementation of a *behavior* will implement one of those interface.
* if you can add more behaviors without modifying any of the existing behavior classes or touching any of the superclasses we've achieved a good strategy design pattern.
* Represent the behavior of things and not the thing. themselves
* Think of *set of behaviors* as a *set of algorithms*.
> 3.Design Principle :
> Favor composition over inheritance
* creating systems using composition gives you a lot more flexibility. it lets you encapsulate a family of algorithms into their own set of classes, and lets you change behavior at runtime as long as the object you’re composing with implements the correct behavior interface.
* The principles and patterns can be applied at any stage of the
development lifecycle.
* Design patterns don’t go directly into your code, they fi rst go into your BRAIN.

* The secrets to creating maintainable OO systems is thinking about how they might change in the future.
---
Strategy Pattern examples:
* SimUDuck app
* Bounce+ **ShoppingCart example is not from the book**
---
<h1 id="ch2"> chapter 2: Observer Pattern</h1>
`aka Pub/Sub`
According to GoF, observer design pattern intent is;
> Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
### Observer used when
State changes in one or more objects should trigger behavior in other object
one-to-many relationship between objects so that when one object changes state all it's dependents are notified and updated automatically.
PHP provides Stander PHP Library (SPL) Observer Pattern through [SplObserver interface](http://php.net/manual/en/class.splobserver.php) and [SplSubject interface](http://php.net/manual/en/class.splsubject.php)
Model-View-Controller (MVC) frameworks also use Observer pattern where _Model_ is the __Subject__ and _Views_ are __observers__ that can register to get notified of any change to the model.
### The Power of Loos Coupling
When two objects are loosely coupled, the can interact, but have very little knowledge of each other.
The Observer Pattern provides an object design where subject and observers are loosely coupled.
>4. Design Principle :
> STRIVE FOR LOOSELY COUPLE DESIGN BETWEEN OBJECT THAT INTERACT
* best usage when there's single source of truth one object with many unknown dependents.
* This single source of truth is an Object's state that's many objects care of knowing it.
* defines one-to-many relationship between objects.
* the Publisher aka the **Subject** updates the observer using common interface.
* the Subscribers aka the **Observers** are loosely coupled and the subject no nothing about then except that they are implement the observer interface.
---
<h1 id="ch3" > chapter 3 : Decorator Pattern (Design Eye for The Inheritance Guy) </h1>
> Attaches additional responsibilities to an object dynamically.
> Decorators provide a flexible alternative to sub-classing for existing functionality.
Allows for the dynamic wrapping of objects in order to modify their existing responsibilities and behaviors.
>5. Design Principle : (The Open-Closed Principle) :
> Classes should be open for extensions, but closed for modifications.
### Decorator used when
Decorator pattern is best used when we introduced to existing code that we want to extend its functionality, Or when we want to extend the functionality for the clients without exposing the code.
Since Decorators are basically wrappers around objects PHP I/O classes same as Java I/O uses decorator pattern to add more functionality to the stream. read more on [Wrappers in php](http://php.net/manual/en/wrappers.php) and you can register a custom wrapper (decorators) to add your own filter/wrapper to I/O stream. @see [this example](https://github.com/LionRoar/Head-First-Design-Patterns-PHP/tree/master/ch03/PHP_IO_DECORATOR) on chapter 03.
* Inheritance is one form of extension, but not necessarily the best way to achieve flexibility in our designs.
* Inheritance makes static behavior but Composition make the behavior dynamic and it can change at runtime .
* Decorator gives the object new responsibility/functionality dynamically at runtime by using composition.
* It's Vital for Decorators to have the same type (superclass/interface) as the objects the are going to decorate/wrap.
* Decorator reduce the chance of bugs and side effects in legacy code.
* General speaking design patterns add abstraction level that's in result adds some level of complexity to the code, that's why we should always use it on the parts that changes and don't overusing it.
* Decorators can result in many small objects in our design, and overuse can be complex.
* Introducing Decorators can increase the complexity of the code; because not only you need to instantiate the component, but also wrap it with (n) number of decorators this can be tackled by using `Factory` and `Builder` Patterns.
---
<h1 id="ch4">chapter 4 : The Factory Pattern </h1>
`Factory method , Abstract factory , Dependency Inversion ?`
## Contents
1. Factory Method Pattern.
2. Abstract Factory Pattern.
There's more to making objects than just using the `new` operator, instantiation is an activity that shouldn't always done in public and can often lead to `coupling problems`.
The Problem : When you have a code that requires you to make a lot of concrete classes this code probably will need to add new classes and thus will NOT be `Closed for Modification`.
All Factory Patterns encapsulate object creation.
## The Factory Method Pattern
> The Factory Method Patter defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
The Factory Method Pattern encapsulates object creation by letting subclasses decide what objects to create.
A Factory Method handles the object creation and encapsulates it in a subclass.

```php
+----------------------+
| PizzaStore | <- [abstract creator]
+----------------------+ <- abstract class defines
| | abstract factory method `createPizza()`
|abstract createPizza()| that the sub-class implements to produce product.
| |
| orderPizza() | <abstract product>
| | +-------+
+-----^--------------^-+ | Pizza |<-------+
| | +-^-----+ |
| | | |
| |_______ | |
| | | |
| | | |
[concrete creator] [concrete creator] | |
+---------+------+ +------------------+ +------------------+ |
| NYPizzaStore | |ChicagoPizzaStore | |ChicagoCheesePizza| |
+----------------+ +------------------+ +--------^---------+ |
| createPizza() | | createPizza() | | |
| | | +--[creates]->>-+ |
+-------------+--+ +------------------+ |
[creator] | [creator] +-------------+ |
+---------------------[creates]--->>|NYCheesePizza|---------+
+-------------+
```
### Factory Method Pattern used when
When there's a need to make a lot of concrete classes or a desire to add new concrete classes in the future we isolate the creation of the classes to an abstract method in an abstract class to obligate the creation to the subclasses.
In other words it's used to decouple your client code from the concrete classes you need to instantiate, or if you don’t know ahead of time all the concrete classes you are going to need
---
>6. Design Principle : The Dependency Inversion Principle
> Depend upon abstraction. Do not depend upon concrete classes.
#### **Dependency Inversion Principle**
`Depend upon abstractions. Do not depend upon concrete classes.`
* High-level components should not depend on low-level components; rather, they should _both_ depend on abstractions.
* Instantiation is an activity that should not be in public and can often lead to coupling problems.
* `new` keyword __===__ an Implementation _(not an Interface)_.
* Factory method lets subclasses decide what class instantiate not because it allows rather than it does not know the product .
* **Strive for guidelines** `The following guidelines can help you avoid OO designs that violate the Dependency Inversion Principle` :
1. **No variable should hold reference for a concrete class.** If you use `new` you’ll be holding a reference to a concrete class, Use a factory to get around that
1. **No class should derive form concrete class.** If you derive from a concrete class, you’re depending on a concrete class. Derive from an abstraction, like an interface or an abstract class.
1. **No method should override method on base class.** if so then the base class not really an abstraction. If you override an implemented method, then your base class wasn’t really an abstraction to start with. Those methods implemented in the base class are meant to be shared by all your subclasses.
---
## Abstract Factory Pattern
Abstract Factory encapsulates the creation of a `family` of products by providing an interface for the product creation.
> Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.


The methods of an Abstract Factory are implemented as **factory methods**.
### Abstract Factory Pattern used when
it's used to construct objects such that they can be decoupled from the implementing system.
The pattern is best utilized when your system has to create multiple families of products or you want to provide a library of products without exposing the implementation details.
whenever you have families of products you need to create and you want to make sure your clients create products that belong together.
* The methods of the **Abstract Factory** are often **Factory Methods**.
---
* The job of an Abstract Factory is to define an interface for creating a set of products.
* Both the **Abstract factory** and **Factory method** are great in terms of decoupling application from specific implementations.
* **Factory method** create objects using (inheritance), while **Abstract Factory** creates objects using (composition). that means to create object using Factory method you need to *extend* class and override a factory method, and for the Abstract Factory it provides an abstract type for creating family of products subclasses define how those products are created and to use the factory you instantiate it and inject it to code written against the abstract type.
---
<h1 id="ch5">chapter 5 : Singleton</h1>
> The singleton pattern ensures a class has only one instance and provide global access to it .
The one, only and unique object.
* The Singleton Pattern ensures you have at most one instance of a class in your application.
* The Singleton Pattern also provides a global access point to that instance.
### Singleton Pattern used when
When we only need one object such as: thread pools, caches, dialog boxes, objects that handle
preferences and registry settings, objects used for logging, and objects that act as device drivers to devices like printers and graphics cards, for many of these types of objects, if we were to instantiate more than one we’d run into all sorts of problems like incorrect program behavior, overuse of resources, or inconsistent results.
We use the singleton pattern in order to restrict the number of instances that can be created from a resource consuming class to only one.
Resource consuming classes are classes that might slow down our website or cost money. For example:
Some external service providers (APIs) charge money per each use.
Some classes that detect mobile devices might slow down our website.
Establishing a connection with a database is time consuming and slows down our app.
### Singleton **violates** the *Single Responsibility Principle* “One Class, One Responsibility”
```
The singleton pattern is probably the most infamous pattern to exist, and is considered an anti-pattern because it creates global variables that can be accessed and changed from anywhere in the code.
Yet, The use of the singleton pattern is justified in those cases where we want to restrict the number of instances that we create from a class in order to save the system resources. Such cases include data base connections as well as external APIs that devour our system resources.
```
I encourage you to read more about the Singleton pattern [in this article by <NAME>](https://phpenthusiast.com/blog/the-singleton-design-pattern-in-php)
---
<h1 id="ch6">chapter 6 : Command Pattern</h1>
```also sometimes called the Action Pattern or Transaction Pattern```
> Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
* Decouples the requester of an action from the object that preform that action.
* Encapsulates the requests as an object `(command object)`.
* A Command object is at the center of this decoupling and encapsulates a receiver with its action `method` (or set of actions).
### The command pattern used when
It's used for history tracking, to implement logging and transactional systems, also used to Simplify Distributed System [Read more](https://docs.microsoft.com/en-us/archive/msdn-magazine/2004/september/distributed-system-design-using-command-pattern-msmq-and-net)
Also The Command Pattern has evolved with alternative designs,`Architectural Patterns` such as `CQS` [(Command-query Separation)](https://martinfowler.com/bliki/CommandQuerySeparation.html) and `CQRS` [(Command Query Responsibility Segregation)](https://martinfowler.com/bliki/CQRS.html) and in their context the command basically a message and the new pattern called called `Command Bus` / `Simple Bus` [Read more](https://matthiasnoback.nl/2015/01/a-wave-of-command-buses/)
* BOUNCE Example: Using command in transactional manner **The `BankTransaction` example is not from the book**
* Extra Tips : A `NULL Object` is an object that implements an interface to do nothing, is useful when you don't have meaningful object to `return` and yet you want to remove the responsibility of handling `NULL` from the client.
---
<h1 id="ch7">The Adapter and The Facade Patterns</h1>
## Adapter Pattern
`aka Wrapper Pattern`
> **The Adapter Pattern** converts the interface of a class into another interface the client expects. Adapters lets classes work together that couldn't otherwise because of incompatible interfaces.
### Adapter Pattern used when
When a class that you need to use doesn't meet the requirements of an interface.
Exposed to legacy code may encounter an old interface needs to be converted to match new client code *Adapters* allows programming components to work together that otherwise wouldn't because of mismatched interfaces.
Adapter pattern motivation is that we can reuse existing software if we can modify the interface.
#### There are two kinds of Adapters
1. **Class Adapter**
*uses `inheritance`* [multiple inheritance] *not supported in *java* nor *php*.
can only wrap a class It cannot wrap an interface since by definition it must derive from some base class.
1. **Object Adapter**
*uses `Object composition`* composition and can wrap classes or interfaces, or both. It can do this since it contains, as a private, encapsulated member,the class or interface object instance it wraps.
> "Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation'". (Gang of Four 1995:19)
* DON'T MIX _DECORATORS_ WITH _ADAPTERS_ THEY'RE BOTH WRAPPERS BUT
_DECORATORS_ ADD NEW RESPONSIBILITIES WHILE _ADAPTERS_ CONVERT AN INTERFACE.
---
## Facade Pattern
> The Facade Pattern provides a unified interface to a set of interfaces in subsystem. Facade defines a higher-level interface that make the subsystem easier to use.
### Facade used when
when you want to simplify a complex system.
* Facades don't encapsulate .
* Facade Pattern allows to avoid tight coupling between client and subsystem.
* **Design Principle**
Principle of Least Knowledge - talk only to your immediate friends.
`{Least Knowledge principle} aka Law of Demeter`
Least Knowledge principle guidelines :
* take any object.
* from any method on that object we should only instantiate :
* The object itself.
* Objects passed as a parameter to the method.
* Any object the method creates or instantiate.
* Any components of the object *by instance variable **has-A-relationship***.
* NOT TO CALL METHODS ON OBJECTS THAT WERE RETURNED FROM ANOTHER METHODS!.
```PHP
$Q = "What’s the harm in calling the method of an object we get back from another call?"
$A = "if we were to do that, then we’d be making a request
of another object’s subpart (and increasing the number of objects
we directly know). In such cases, the principle forces us to ask
the object to make the request for us; that way we don’t have
to know about its component objects
(and we keep our circle of friends small)."
```
Without the principle
```PHP
public function getTemp() : float {
$thermometer = $this->station->getThermometer();
//we get thermometer OBJECT for
//the station then we call get temperature
return $thermometer->getTemperature();
}
```
With Least Knowledge principle
```PHP
public function getTemp() : float {
//we add a method to the station class with
//that we reduce the number of classes we're dependent on
return $this->station->getTemperature();
}
```
### Wrappers
PATTERN | INTENT
---------|---------
Decorator|Doesn't alter the interface but adds responsibilities.
Adapter |converts one interface to another.
Facade |Makes an interface simpler.
---
<h1 id="ch8">Template Method Pattern [Encapsulating Algorithms] </h1>
### Template Method Pattern
`aka Hollywood pattern`
> The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
It's all about creating `Template` form an `Algorithm`
```PHP
$q = "What's a `Template` ?"
$a = "it's just a method that defines an algorithm as steps"
```
### Hooked on Template
A **Hook** is a method that declared in the abstract class but given an empty on default implementation ; giving the subclass the ability to `hook into` _override_ the algorithm on various points.
When to use what ?
`abstract methods` _VS_`hooks.`
use __abstract methods__ when the implementation is a __MUST__ in the subclass.
for the __hooks__ it's optional for the subclass.
### Hollywood Principle
> Don't call us, we'll call you.
* **Hollywood principle** helps prevents `Dependency rot`. huh ..what!?
* **Dependency rot:** it's bad and a mess !
it's when high-level components depending on low-level components depending on high-level components ...and so on.
it's hard to understand system with such a flaw.
* **Hollywood principle :** is a `Technique` for building frameworks or components so that low-level components can be `Hooked` into the computation without creating dependency between the low-level components and high-level components.
* **Hollywood principle** guides us to put `decision-making` in high-level modules that can decide how and when to call low level modules.
* **The Factory Method is a specialization of Template Method**
### Who does what ?
Pattern | Description
----------------|-------------
Template Method | Subclasses decide how to implement steps in an algorithm.
Strategy | Encapsulate interchangeable behavior and use delegation to decide which behavior to use.
Factory Method | Subclasses decide which concrete classes to create.
#### Bounce
another great example from [journaldev](https://www.journaldev.com/1763/template-method-design-pattern-in-java)
to understand the method template pattern
> suppose we want to provide an algorithm to build a house. The steps need to be performed to build a house are – building foundation, building pillars, building walls and windows. The important point is that the **we can’t change the order of execution** because we can’t build windows before building the foundation. So in this case we can create a template method that will use different methods to build the house.
### Template Method Pattern used when
* Template Methods are frequently used in general purpose frameworks or libraries that will be used by other developer.
* When the behavior of an algorithm can vary but not the order.
* When there's a code duplication *this is always gives a clear sign of bad design decisions and there's always room for improvement*.
---
<h1 id="ch9">The Iterator and Composite Patterns [Well-Managed Collection]</h1>
## Iterator Pattern
> The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
* Iterator provide a standard way *common interface* to traverse through a group of Objects *aggregate*.
* Iterator allows access to an aggregate's elements without exposing its internal structure.
### checkout iterator branch for iterator implementation
```bash
$ git checkout iteratorPattern
Switched to branch 'iteratorPattern'
```

* The **Aggregate** defines an interface for the creation of the Iterator object.
* The **ConcreteAggregate** implements this interface, and returns an instance of the ConcreteIterator.
* The **Iterator** defines the interface for access and traversal of the elements, and the **ConcreteIterator** implements this interface while keeping track of the current position in the traversal of the Aggregate.
### Iterator used when
* When you need access to elements in a set without access to the entire representation.
* When you need a uniform traversal interface, and multiple traversals may happen across elements.
---
### implementations notes
Unlike java , PHP Array can be treated as an array, list, hash-table, stack, queue, dictionary, collection,...and probably more.
The original example uses both Java Array and ArrayList.
#### PHP implementation specifics
For the sake of **`Objectville`** example :
* I will use [SplFixedArray](http://php.net/manual/en/class.splfixedarray.php) to mimic (static)fixed size arrays.
* We will ignore the fact that both **normal php `array`** and **`SplFixedArray`** implement the [Traversable *interface*](http://php.net/manual/en/class.traversable.php)
and that both can be easily traversed using a [`foreach`](http://php.net/manual/en/control-structures.foreach.php).
* You cannot implement `Traversable` interface it's an abstract base interface, you can't implement it alone but you can implement interfaces called [`Iterator`](http://php.net/manual/en/class.iterator.php) or [`IteratorAggregate`](http://php.net/manual/en/class.iteratoraggregate.php) By implementing either of these interfaces you make a class `iterable` and `traversable` using `foreach`
* For the sake of this example we're going to make our own interface and we call it `IteratorInterface`.
---
### Single Responsibility Principle (**S**OLID)
> A Class should have only one reason to change.
Separating responsibilities in design is one of the most difficult things to do, to succeed is to be diligent in examining your designs and watchout for signals that a class is changing in more than one way as your system grows.
`We should strive to assign only one responsibility to each class.`
---
## The Composite Pattern
> The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

```
The << Component >> abstract class define all objects in composed system.
The Leaf has no children.
The Composite contains components.
```
* Composite pattern comes into play when developing a system where a component could either be an individual object or a representation of a collection of objects.
* Composite pattern provides a structure to hold both individual objects an composites.
* A **Component** is any object in a **Composite structure**.
* **Components** may be other *composites* or *leaf* nodes.
* Remember to balance `transparency` and `safety`.
## Is `Composite Pattern` really follow the single responsibility principle
The Composite Pattern
1. manages a hierarchy
1. performs operations related to Menus
that's __2__ responsibilities.
The Composite Pattern trades **Single Responsibility Principle** for *transparency*
Transparency: Since the Composite interface contain child management operations and the leaf _(items non iterable)_ operations The client can treat both the composites and leaf nodes uniformly, both are _transparent_ to the client.
Having both operations in the Component class will cause a bit loss of *safety* because the client might try to do Composite related operation e.g _add_ to a leaf _item_ which is invalid.
## Composite Pattern used when
* Graphics frameworks are the most common use of this pattern.
* The Composite pattern is frequently used for abstract syntax tree representations.
* when dealing with tree structures *Anything that can be modelled as a tree structure can be considered an example of Composite*.
* when you have collection of objects with whole-part relationships and you want to be able to treat those objects uniformly.
### `what's whole-part relationships ?`
also known as `aggregation relationship` it's a relationship between two classes in which one represent the larger class (whole) that consists of smaller classes (parts)
---
* We call components that contain other components `composite objects` and components that don't contain other components `leaf objects`.
* By treating objects uniformly that means there's a common methods can be called on both `composite` or `leaf` that implies that both must have the same `interface`.
---
### Who does what ?
Pattern | Description
----------------|-------------
Strategy | Encapsulate interchangeable behavior and use delegation to decide which behavior to use.
Adapter | Changes the interface of one or more classes.
Iterator | Provides a way to traverse a collection of objects without exposing the collection's implementation.
Facade | Simplifies the interface of a group of classes.
Composite | Clients treat collections of objects and individual objects uniformly.
Observer | Allow a group of objects to be notified when some state changes.
---
<h1 id="ch10">chapter 10: The State Pattern *The State of Things*</h1>
> Allows an object to alter its behaviour when its internal state changes. The object will appear to change its class.
---

* The **Context** have number of internal states.
* The **State** << interface >> defines a common interface for all concrete states.
* Each *Behavior* correspond with **ConcreteState** implements its own logic for the request.
* When **Context** changes state a different **ConcreteState** associate with it.
* Simply change the state object in context to change the behavior.
This is similar to **Strategy Pattern** except changes happens internally rather than the client deciding the strategy.
key-points:
Think of Strategy Pattern as a flexible alternative to sub-classing.
Think of State Pattern as an alternative to putting lots of conditionals.
## State Pattern used when
* You need a class to behave differently based on some condition.
* If you are using *if-else* condition block to perform different actions based on the state.
### Who does what ?
Pattern | Description
----------------|-------------
State | Encapsulate state-based behavior and delegate behavior to the current state.
Strategy | Encapsulate interchangeable behavior and use delegation to decide which behavior to use.
Template Method | Subclasses decide how to implement steps in an algorithm.
---
<h1 id="ch11">The Proxy Pattern *Controlling Object Access* </h1>
<file_sep>/ch10/MightyGumball/index.php
<?php
require_once './vendor/autoload.php';
$gumballMachine = new GumballMachine(5);
echo $gumballMachine . PHP_EOL;
//A quarter in
$gumballMachine->insertQuarter();
//get the gumball
$gumballMachine->turnCrank();
echo $gumballMachine . PHP_EOL;
$gumballMachine->insertQuarter();
$gumballMachine->turnCrank();
$gumballMachine->insertQuarter();
$gumballMachine->turnCrank();
$gumballMachine->refill(10);
echo $gumballMachine . PHP_EOL;
<file_sep>/ch02/Weather-O-Rama/index.php
<?php
require_once './vendor/autoload.php';
$weatherData = new WeatherData();
$currentDisplay = new CurrentConditionDisplay($weatherData);
$statsDisplay = new StatisticsDisplay($weatherData);
$forecast = new ForecastDisplay($weatherData);
$heatIndex = new HeatIndexDisplay($weatherData);
$data = array(
"temperature"=> 80,
"humidity" => 65,
"pressure"=>30.5
);
$weatherData->setWeatherData($data);<file_sep>/ch05/singletonDb/index.php
<?php
require_once './vendor/autoload.php';
/**
* @see https://phpenthusiast.com/blog/the-singleton-design-pattern-in-php
*/
$instance = SingletonConnect::getInstance();
$conn = $instance->getConnection();
var_dump($conn);
$instance = SingletonConnect::getInstance();
$conn = $instance->getConnection();
var_dump($conn);
$instance = SingletonConnect::getInstance();
$conn = $instance->getConnection();
var_dump($conn);
<file_sep>/ch04/PizzaStore/Ingredients/Dough.php
<?php
namespace Ingredients;
interface Dough {
}<file_sep>/ch02/Weather-O-Rama/StatisticsDisplay.php
<?php
class StatisticsDisplay extends DisplayElement {
private $temperature;
public function update(SplSubject $subject)
{
$data = $subject->getWeatherData();
$this->temperature = $data["temperature"];
$this->display();
}
public function display()
{
echo "\nSTATS: AVG/MAX/MIN TEMPERATURE: $this->temperature\n";;
}
}
<file_sep>/ch06/HomeAutomation/Receiver/Stereo.php
<?php
namespace Receiver;
class Stereo {
private $name = '' ;
public function __construct(string $name)
{
if(isset($name))
$this->name = $name;
}
public function on(){
echo $this->name . ' Stereo is ON.' . PHP_EOL;
}
public function setCD(){
echo $this->name . ' Stereo CD is set.' . PHP_EOL;
}
public function setVolume(int $vol){
echo $this->name . ' Stereo volume is '. $vol . PHP_EOL;
}
public function off(){
echo $this->name . ' Stereo is OFF. ' . PHP_EOL;
}
}<file_sep>/ch05/Choc-O-Holic/TestSingleton.php
<?php
class TestSingleton {
public function testFillChocolateBoiler(){
echo "Filling the boiler from TestSingleton class.\n" . PHP_EOL;
$boiler = ChocolateBoiler::getInstance();
$boiler->fill();
}
}<file_sep>/ch04/PizzaStoreFactoryMethod/index.php
<?php
require_once './vendor/autoload.php';
$nyStore = new NYPizzaStore();
$chicagoStore = new ChicagoPizzaStore();
$nyStore->orderPizza("cheese");
$chicagoStore->orderPizza("cheese");
<file_sep>/ch06/BankTransaction/ShareData.php
<?php
class ShareData implements Transaction {
public function execute() : bool
{
echo "Sharing data with the bank ..\n";
//if something goes wrong return false
return true;
}
public function rollback()
{
echo "clean up session.\n";
}
}<file_sep>/ch06/BankTransaction/Authenticate.php
<?php
class Authenticate implements Transaction {
public function execute(): bool
{
echo "authenticating ..\n";
return true;
}
public function rollback()
{
echo "clean up auth cookie..\n";
}
}<file_sep>/ch08/StarbuzzCoffeeRecipe/CoffeeWithHook.php
<?php
class CoffeeWithHook extends CaffeineBeverageWithHook {
protected function brew(){
echo "Dripping coffee through filter " . PHP_EOL;
}
protected function addCondiments(){
echo "Adding sugar and milk " . PHP_EOL;
}
protected function customerWantsCondiments() : bool {
$answer = $this->getUserInput();
if(strtolower($answer)[0] == 'y')
return true;
return false;
}
private function getUserInput() : string {
$answer = null;
$answer = readline("Would you like milk and sugar with your coffee (y/n) ? \n");
if($answer == null)
return "no";
return $answer;
}
}<file_sep>/ch04/PizzaStore/Ingredients/Clams.php
<?php
namespace Ingredients;
interface Clams {
}<file_sep>/ch04/PizzaStoreFactoryMethod/Pizza.php
<?php
abstract class Pizza {
protected $name;
protected $dough;
protected $sauce;
protected $toppings = array();
public function prepare() : void {
echo "Preparing " . $this->name . PHP_EOL .
"Tossing dough..." . PHP_EOL .
"Adding sauce..." . PHP_EOL .
"Adding toppings:";
foreach($this->toppings as $k => $t){
echo " " . $t;
}
echo PHP_EOL;
}
public function bake(){
echo "Bake for 25 minute at 350\n";
}
public function cut(){
echo "Cutting the pizza into diagonal slices\n";
}
public function box(){
echo "Place Pizza in official PizzaStore box\n\n";
}
public function setName(string $name){
$this->name = $name;
}
public function getName() : string {
return $this->name;
}
public function __toString()
{
return $this->name ;
}
}<file_sep>/ch04/PizzaStore/Ingredients/Sauce/PulmTomatoSauce.php
<?php
namespace Ingredients\Sauce;
use Ingredients\Sauce;
class PulmTomatoSauce implements Sauce {
public function __construct()
{
echo "Pulm Tomato Sauce \n";
}
}<file_sep>/ch04/PizzaStore/Ingredients/Dough/ThickCrustDough.php
<?php
namespace Ingredients\Dough;
use Ingredients\Dough;
class ThickCrustDough implements Dough {
public function __construct()
{
echo "Thick Crust Dough\n";
}
}<file_sep>/ch11/MightyGumball/Client/GumballMonitor.php
<?php
namespace MG\Client;
use MG\GumballMachineInterface;
class GumballMonitor {
private $machine;
public function __construct(GumballMachineInterface $machine) {
$this->machine = $machine;
}
public function report() {
echo "Address : " . $this->machine->getRemotePath() . PHP_EOL;
echo "Gumball Machine: " . $this->machine->getLocation() . PHP_EOL
. "Current inventory: " . $this->machine->getCount() . PHP_EOL
. "Current State: " . $this->machine->getState() . PHP_EOL;
}
}<file_sep>/ch07/TurkeyAdapter/WildTurkey.php
<?php
class WildTurkey implements Turkey {
public function gobble(){
echo "Gobble gobble " . PHP_EOL;
}
public function fly(){
echo "Short distance but I'm flying " . PHP_EOL;
}
}<file_sep>/ch04/PizzaStoreFactoryMethod/ChicagoPizzaStore.php
<?php
class ChicagoPizzaStore extends PizzaStore {
protected function createPizza(string $type) : Pizza {
switch ($type) {
case 'cheese':
return new ChicagoCheesePizza();
break;
// case 'veggie':
// return new ChicagoVeggiePizza();
// break;
// case 'pepperoni':
// return new ChicagoPepperoniPizza();
break;
default:
return null;
break;
}
}
}<file_sep>/ch03/StarbuzzCoffee/CondimentDecorator.php
<?php
abstract class CondimentDecorator extends Beverage {
protected $beverage;
public function getDescription() : string {
return $this->beverage->getDescription() .
", " .$this->description;
}
}<file_sep>/ch07/TurkeyAdapter/Turkey.php
<?php
interface Turkey {
//turkeys don't quack they gobble
public function gobble();
//turkeys can fly short-distance
public function fly();
}<file_sep>/ch01/simUDuck/QuackBehavior.php
<?php
interface QuackBehavior {
public function quack();
}
<file_sep>/ch04/PizzaStore/Ingredients/Veggies/BlackOlives.php
<?php
namespace Ingredients\Veggies;
class BlackOlives {
}<file_sep>/ch06/HomeAutomation/index.php
<?php
require_once './vendor/autoload.php';
#region use
use \Receiver\Light;
use \Receiver\GarageDoor;
use Receiver\CeilingFan;
use Receiver\Stereo;
use Commands\LightOnCommand;
use Commands\LightOffCommand;
use Commands\GarageDoorCloseCommand;
use Commands\GarageDoorOpenCommand;
use Commands\CeilingFanOffCommand;
use Commands\CeilingFanOnCommand;
use Commands\CeilingFanHighCommand;
use Commands\CeilingFanMediumCommand;
use Commands\MacroCommand;
use Commands\StereoOnWithCDCommand;
use Commands\StereoOffCommand;
use Commands\PartyModeCommand;
use Commands\PartyModeOffCommand;
#endregion
//* index.php [the client] also acts as The RemoteLoader
//* The RemoteControl [the invoker] (holds commands to execute a request by calling execute() )
$remote = new RemoteControl();
//* The Receivers (have no knowledge of what to do to carry out request)
$ceilingFan = new CeilingFan("Living Room");
$light = new Light("Living room");
$stereo = new Stereo("Living room");
//* The Requests encapsulated with objects [commands] (sets a Receiver for a Command)
$partyOn = [
new CeilingFanOnCommand($ceilingFan),
new LightOnCommand($light),
new StereoOnWithCDCommand($stereo)
];
$partyOf = [
new CeilingFanOffCommand($ceilingFan),
new LightOffCommand($light),
new StereoOffCommand($stereo)
];
$partyOnMacro = new MacroCommand($partyOn);
$partyOffMacro = new MacroCommand($partyOf);
$remote->setCommand(0 , $partyOnMacro , $partyOffMacro);
$remote->onButtonWasPushed(0);
echo $remote;
$remote->undoButtonWasPushed();
/**
* Undo Ceiling fan test
*/
// $ceilingFanBedroom = new CeilingFan("Bedroom");
// $cfHighCommand = new CeilingFanHighCommand($ceilingFanBedroom);
// $cfMidCommand = new CeilingFanMediumCommand($ceilingFanBedroom);
// $cfOffCommand = new CeilingFanOffCommand($ceilingFanBedroom);
// $remote->setCommand(1, $cfHighCommand, $cfOffCommand);
// $remote->setCommand(2, $cfMidCommand, $cfOffCommand);
// $remote->onButtonWasPushed(1);
// $remote->onButtonWasPushed(2);
// $remote->undoButtonWasPushed();
// echo $remote;
<file_sep>/ch04/PizzaStore/Ingredients/Pepperoni.php
<?php
namespace Ingredients;
interface Pepperoni {
}<file_sep>/ch11/MightyGumball/Client/index.php
<?php
namespace MG\Client;
require_once '../vendor/autoload.php';
$location = [
"http://localhost:3001",
"http://localhost:3002",
"http://localhost:3003",
];
$monitor = [];
for ($i = 0; $i < count($location); $i++) {
try {
$machine = new GumballMachineProxy(new JsonRequest($location[$i]));
$monitor[$i] = new GumballMonitor($machine);
} catch (\Exception $e) {
echo $e->message . PHP_EOL;
}
}
for ($i = 0; $i < count($location); $i++) {
$monitor[$i]->report();
}
// $machine01 = new GumballMachineProxy(new Http("http://localhost:3001"));
// $machine02 = new GumballMachineProxy(new Http("http://localhost:3002"));
// $machine03 = new GumballMachineProxy(new Http("http://localhost:3003"));
// $gumballMonitor01 = new GumballMonitor($machine01);
// $gumballMonitor02 = new GumballMonitor($machine02);
// $gumballMonitor03 = new GumballMonitor($machine03);
// $gumballMonitor01->report();
// $gumballMonitor02->report();
// $gumballMonitor03->report();<file_sep>/ch02/Weather-O-Rama/HeatIndexDisplay.php
<?php
class HeatIndexDisplay extends DisplayElement {
private $temperature;
private $humidity;
private $heatIndex;
public function update(SplSubject $subject)
{
$data = $subject->getWeatherData();
$this->temperature = $data["temperature"];
$this->humidity = $data["humidity"];
$this->heatIndex = $this->computeHeatIndex(
$this->temperature,
$this->humidity
);
$this->display();
}
public function display(){
echo "\n+++++HEAT_INDEX+++++\n"
. $this->heatIndex
. "\n++++++++++++++++++++\n";
}
/**
* How does it work? You’d have to refer to Head First Meteorology, or try asking someone at the National
* Weather Service (or try a Google search).
* (I don't know either :P )
* @param float $t temperature
* @param float $rh humidity
* @return float
*/
private function computeHeatIndex(float $t, float $rh) : float {
$index = ((16.923 + (0.185212 * $t) + (5.37941 * $rh) - (0.100254 * $t * $rh) +
(0.00941695 * ($t * $t)) + (0.00728898 * ($rh * $rh)) +
(0.000345372 * ($t * $t * $rh)) - (0.000814971 * ($t * $rh * $rh)) +
(0.0000102102 * ($t * $t * $rh * $rh)) - (0.000038646 * ($t * $t * $t)) + (0.0000291583 *
($rh * $rh * $rh)) + (0.00000142721 * ($t * $t * $t * $rh)) +
(0.000000197483 * ($t * $rh * $rh * $rh)) - (0.0000000218429 * ($t * $t * $t * $rh * $rh)) +
0.000000000843296 * ($t * $t * $rh * $rh * $rh)) -
(0.0000000000481975 * ($t * $t * $t * $rh * $rh * $rh)));
return $index;
}
}<file_sep>/ch09/ObjectvilleDinerPancakeHouse/MenuComponent.php
<?php
abstract class MenuComponent {
// hierarchy operations
public function add(MenuComponent $menuComponent){
throw new UnsupportedException();
}
public function remove(MenuComponent $menuComponent){
throw new UnsupportedException();
}
public function getChild(int $i) : MenuComponent {
throw new UnsupportedException();
}
// operations related to menus / menu items
public function getName() : string {
throw new UnsupportedException();
}
public function getDescription() : string {
throw new UnsupportedException();
}
public function getPrice() : float {
throw new UnsupportedException();
}
public function isVegetarian() : bool {
throw new UnsupportedException();
}
public function print(){
throw new UnsupportedException();
}
abstract public function createIterator() : IteratorInterface ;
}<file_sep>/ch07/HomeTheaterFacade/Components/Projector.php
<?php
namespace Components;
class Projector
{
public function on(){
echo "Projector on " . PHP_EOL;
}
public function wideScreenMode(){
echo "Projector in to widescreen mode (16x9 aspect ratio) " . PHP_EOL;
}
public function off(){
echo "Projector is off " . PHP_EOL;
}
}
<file_sep>/ch09/ObjectvilleDinerPancakeHouse/index.php
<?php
require_once './vendor/autoload.php';
//Create all menus
$pancakeHouseMenu = new Menu("PANCAKE HOUSE MENU", "Breakfast");
$dinerMenu = new Menu("DINER MENU","Lunch");
$cafeMenu = new Menu("CAFE MENU", "Dinner");
$dessertMenu = new Menu("DESSERT MENU", "Dessert if course!");
//top level menu Root
$allMenus = new Menu("ALL MENUS", "All menus combined");
//composite add() to add each menu to the top level menu
$allMenus->add($pancakeHouseMenu);
$allMenus->add($dinerMenu);
$allMenus->add($cafeMenu);
//add pancake house menu items
$pancakeHouseMenu->add(new MenuItem("K&B’s Pancake Breakfast",
"Pancakes with scrambled eggs, and toast ",
true,
2.99));
$pancakeHouseMenu->add(new MenuItem("Regular Pancake Breakfast",
"Pancakes with fried eggs, sausage",
false,
2.99));
$pancakeHouseMenu->add(new MenuItem("Blueberry Pancakes",
"Pancakes made with fresh blueberries",
true,
3.49));
//add dinermenu menu oitems
$dinerMenu->add(new MenuItem("Vegetarian BLT",
"(Fakin’) Bacon with lettuce & tomato on whole wheat", true, 2.99));
$dinerMenu->add(new MenuItem("BLT",
"Bacon with lettuce & tomato on whole wheat", false, 2.99));
$dinerMenu->add(new MenuItem(
"Pasta","Spaghetti with Marinara Sauce, and a slice of sourdough bread",
true, 3.89));
//add dessert menu to diner menu
$dinerMenu->add($dessertMenu);
//add dessert menu items
$dessertMenu->add(new MenuItem(
"Apple Pie","Apple pie with a flakey crust, topped with vanilla ice-cream",
true, 1.59));
$dessertMenu->add(new MenuItem(
"Cheesecake","Creamy New York cheesecake, with a chocolate graham crust",
true, 1.99));
$dessertMenu->add(new MenuItem(
"Sorbet","A scoop of raspberry and a scoop of lime",
true, 1.89));
//add cafe menu items
$cafeMenu->add(new MenuItem("Veggie Burger and Air Fries",
"Veggie burger on a whole wheat bun, lettuce, tomato, and fries",
true, 3.99));
$cafeMenu->add(new MenuItem("Soup of the day",
"A cup of the soup of the day, with a side salad",
false, 3.69));
$cafeMenu->add(new MenuItem("Burrito",
"A large burrito, with whole pinto beans, salsa, guacamole",
true, 4.29));
//call the waitress give her the hierarchy of menus for her to print
$waitress = new Waitress($allMenus);
//$waitress->printMenu();
$waitress->printVegetarianMenu();
<file_sep>/ch04/PizzaStore/Ingredients/Pepperoni/SlicedPepperoni.php
<?php
namespace Ingredients\Pepperoni;
use Ingredients\Pepperoni;;
class SlicedPepperoni implements Pepperoni {
public function __construct()
{
echo "Sliced Pepperoni\n";
}
}<file_sep>/ch04/PizzaStore/Ingredients/Dough/ThinCrustDough.php
<?php
namespace Ingredients\Dough;
use Ingredients\Dough;
class ThinCrustDough implements Dough {
public function __construct()
{
echo "Thin Crust Dough\n";
}
}<file_sep>/ch04/PizzaStore/PizzaIngredientFactory.php
<?php
use Ingredients\Dough;
use Ingredients\Cheese;
use Ingredients\Clams;
use Ingredients\Pepperoni;
use Ingredients\Sauce;
//abstract factory
interface PizzaIngredientFactory {
//set of related products
public function createDough() : Dough;
public function createSauce() : Sauce;
public function createCheese(): Cheese;
public function createVeggies() : array;
public function createPepperoni() : Pepperoni;
public function createClam() : Clams;
}<file_sep>/ch01/ShoppingCart/Item.php
<?php
class Item {
private static $IDx = 0;
private $id;
private $upcCode;
private $price;
public function __construct(string $upc, int $cost){
$this->id = ++self::$IDx;
$this->upcCode = $upc;
$this->price = $cost;
}
public function getUpcCode():string {
return $this->upcCode;
}
public function getPrice():int{
return $this->price;
}
public function getId():int{
return $this->id;
}
}<file_sep>/ch04/PizzaStore/Ingredients/Cheese/ReggianCheese.php
<?php
namespace Ingredients\Cheese;
use Ingredients\Cheese;
class ReggianCheese implements Cheese {
public function __construct()
{
echo "Reggian Cheese \n";
}
}<file_sep>/ch11/MightyGumball/gm_seattle/index.php
<?php
require_once '../vendor/autoload.php';
use MG\Service\GumballMachine;
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$machine = new GumballMachine('seattle', 51);
$gumballMachineJson = json_encode([
'count' => $machine->getCount(),
'state' => $machine->getState(),
'location' => $machine->getLocation(),
]);
echo $gumballMachineJson;
<file_sep>/ch06/HomeAutomation/Commands/CeilingFanHighCommand.php
<?php
namespace Commands;
use \Command;
use Receiver\CeilingFan;
class CeilingFanHighCommand implements Command {
private $ceilingFan;
private $prevSpeed;
public function __construct(CeilingFan $cf){
$this->ceilingFan = $cf;
}
public function execute(){
$this->prevSpeed = $this->ceilingFan->getSpeed();
$this->ceilingFan->high();
}
public function undo(){
$this->ceilingFan->setSpeed($this->prevSpeed);
}
}<file_sep>/ch06/HomeAutomation/Receiver/CeilingFan.php
<?php
namespace Receiver;
class CeilingFan {
private $name = '' ;
const HIGH = 3;
const MEDIUM = 2;
const LOW = 1;
const OFF = 0;
private $speedArr = ['Off','Low','Medium','High'];
private $speed ;
public function __construct(string $name)
{
if(isset($name))
$this->name = $name;
$this->speed = self::OFF;
}
public function high(){
$this->speed =self::HIGH;
echo $this->name . " CeilingFan is On speed is set to " .
$this->speedArr[$this->getSpeed()]
. PHP_EOL;
}
public function medium(){
$this->speed = self::MEDIUM;
echo $this->name . " CeilingFan is On speed is set to " .
$this->speedArr[$this->getSpeed()] . PHP_EOL;
}
public function low(){
$this->speed =self::LOW;
echo $this->name . " CeilingFan is On speed is set to " .
$this->speedArr[$this->getSpeed()] . PHP_EOL;
}
public function off(){
echo $this->name . ' CeilingFan is OFF. ' . PHP_EOL;
$this->speed = self::OFF;
}
public function getSpeed() {
return $this->speed;
}
public function setSpeed($toSpeed){
switch ($toSpeed) {
case self::HIGH:
$this->high();
break;
case self::MEDIUM:
$this->medium();
break;
case self::LOW:
$this->low();
break;
case self::OFF:
$this->off();
break;
}
}
public function on(){
$this->low();
}
}<file_sep>/ch07/HomeTheaterFacade/index.php
<?php
require_once './vendor/autoload.php';
#region use
use Components\Amplifier;
use Components\Tuner;
use Components\DvdPlayer;
use Components\CdPlayer;
use Components\Projector;
use Components\TheaterLights;
use Components\Screen;
use Components\PopcornPopper;
#endregion
$amp = new Amplifier();
$tuner = new Tuner();
$dvd = new DvdPlayer();
$cd = new CdPlayer;
$projector = new Projector();
$screen = new Screen();
$lights = new TheaterLights();
$popper = new PopcornPopper();
$homeTheater = new HomeTheaterFacade(
$amp , $tuner , $dvd , $cd ,
$projector , $screen , $lights ,$popper
);
$homeTheater->watchMovie("Dude Where's My Car");
echo PHP_EOL;
$homeTheater->endMovie();
<file_sep>/ch01/simUDuck/FlyBehavior.php
<?php
interface FlyBehavior {
public function fly();
}<file_sep>/ch07/HomeTheaterFacade/Components/PopcornPopper.php
<?php
namespace Components;
class PopcornPopper
{
public function on(){
echo "Popcorn popper on " . PHP_EOL;
}
public function pop(){
echo "Popcorn popper is popping pop popcorn " . PHP_EOL;
}
public function off(){
echo "Popcorn popper off " . PHP_EOL;
}
}
<file_sep>/ch05/Choc-O-Holic/index.php
<?php
require_once './vendor/autoload.php';
//get singleton instance
$boiler = ChocolateBoiler::getInstance();
//Is the boiler empty
echo "Is the boiler empty ? => " ;
var_dump($boiler->isEmpty()) ;
echo PHP_EOL;
//fill from other class
(new TestSingleton())->testFillChocolateBoiler();
//check if the single boiler is filled
echo "Is the boiler empty ? => " ;
var_dump($boiler->isEmpty()) ;
echo PHP_EOL;
<file_sep>/ch09/ObjectvilleDinerPancakeHouse/MenuComponentsIterator.php
<?php
class MenuComponentsIterator implements IteratorInterface {
private $menuItems;
private $index = 0;
public function __construct(array $array){
$this->menuItems = $array;
}
public function next(){
return $this->menuItems[$this->index++];
}
public function hasNext() : bool {
if($this->index >= count($this->menuItems))
return false;
return true;
}
}<file_sep>/ch04/PizzaStore/Ingredients/Clams/FreshClams.php
<?php
namespace Ingredients\Clams;
use Ingredients\Clams;
class FreshClams implements Clams {
public function __construct()
{
echo "Fresh Clams\n";
}
}<file_sep>/ch06/HomeAutomation/Commands/MacroCommand.php
<?php namespace Commands;
use Command;
class MacroCommand implements Command {
private $commands = array();
public function __construct(array $cmds) {
$this->commands = $cmds;
}
public function execute() {
for ($i = 0; $i < count($this->commands); $i++) {
$this->commands[$i]->execute();
}
}
public function undo() {
for ($i = 0; $i < count($this->commands); $i++) {
$this->commands[$i]->undo();
}
}
}<file_sep>/ch11/MightyGumball/Service/HasQuarterState.php
<?php
namespace MG\Service;
class HasQuarterState implements StateInterface {
private $machine;
public function __construct(GumballMachine $machine) {
$this->machine = $machine;
}
public function insertQuarter() {
echo "You can't insert another quarter \n";
}
public function ejectQuarter() {
echo "Quarter returned \n";
$this->machine->setState($this->machine->getNoQuarterState());
}
public function turnCrank() {
echo "You turned...\n";
$winner = rand(1, 10);
//echo "By chance : $winner \n";
if ($winner === 1 && $this->machine->getCount() > 1) {
$this->machine->setState($this->machine->getWinnerState());
return;
}
$this->machine->setState($this->machine->getSoldState());
}
public function dispense() {
echo "No gumball dispensed \n";
}
public function description(): string {
return "has a quarter. ";
}
}<file_sep>/ch01/ShoppingCart/ShoppingCart.php
<?php
class ShoppingCart {
private $items = array();
public function addItem(Item $i){
$this->items[$i->getId()] = $i;
}
public function removeItem(Item $i){
unset($this->items[$i->getId()]);
}
public function calculateTotal(){
$sum = 0;
foreach ($this->items as $key => $i) {
$sum += $i->getPrice();
}
return $sum;
}
public function pay(PaymentStrategy $paymentMethod){
$amount = $this->calculateTotal();
$paymentMethod->pay($amount);
}
}<file_sep>/ch08/StarbuzzCoffeeRecipe/TeaWithHook.php
<?php
class TeaWithHook extends CaffeineBeverageWithHook {
protected function brew(){
echo "Steeping the tea " . PHP_EOL;
}
protected function addCondiments(){
echo "Adding Lemon " . PHP_EOL;
}
protected function customerWantsCondiments() : bool {
$answer = $this->getUserInput();
if(strtolower($answer)[0] == 'y')
return true;
return false;
}
private function getUserInput(): string {
$answer = null;
$answer = readline("Would you like lemon with your tea (y/n) ? \n");
if($answer == null)
return "no";
return $answer;
}
}<file_sep>/ch03/PHP_IO_DECORATOR/LowerCaseInputStream.php
<?php
/**
* * php_user_filter class is an abstract decorator
* @see https://www.php.net/manual/en/class.php-user-filter.php
* @see https://www.php.net/manual/en/php-user-filter.filter.php
* @see http://php.net/manual/en/function.stream-filter-register.php
* @see http://etutorials.org/Server+Administration/upgrading+php+5/Chapter+8.+Streams+Wrappers+and+Filters/8.6+Creating+Filters/
*/
class LowerCaseInputStream extends php_user_filter
{
function filter($in, $out, &$consumed, $closing)
{
/**
* * Your primary goal inside filter( ) is to take data from the input bucket, convert it, and then add it to the output bucket. However, you can't just operate on the bucket resources directly; instead, you need to call a few helper functions to convert the data from a resource to an object that is modifiable in PHP.
*
* * The stream_bucket_make_writable( ) function retrieves a portion of the data from the input bucket and converts it to a PHP bucket object. This object has two properties: data and datalen. The data property is a string holding the bucket's data, whereas datalen is its length.
* ...
*
* @see http://etutorials.org/Server+Administration/upgrading+php+5/Chapter+8.+Streams+Wrappers+and+Filters/8.6+Creating+Filters/
* ...
* * This entire process takes place inside a while loop because the stream passes data to you in chunks instead of sending the entire dataset at once.
*/
while ($bucket = stream_bucket_make_writeable($in)) {
$bucket->data = strtolower($bucket->data);
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON; //Filter processed successfully with data available in the out bucket brigade. @see https://www.php.net/manual/en/php-user-filter.filter.php
}
}
<file_sep>/ch04/PizzaStoreFactoryMethod/NYCheesePizza.php
<?php
class NYCheesePizza extends Pizza {
public function __construct(){
$this->name ="New york Style sauce and cheese pizza";
$this->dough = "Thin crust dough";
$this->sauce = "Marinara sauce";
$this->toppings = ['Grated Reggiano Cheese'];
}
}<file_sep>/ch06/BankTransaction/Acknowledge.php
<?php
class Acknowledge implements Transaction {
public function execute(): bool
{
echo "get acknowledgement from the bank \n";
return true;
}
public function rollback()
{
echo "things went sideways, initiating rollback .. \n";
}
}<file_sep>/ch03/StarbuzzCoffee/Beverage.php
<?php
/**
* @abstract
* We got this code that Starbuzz already had.
* an abstract Beverage class.
*/
abstract class Beverage {
protected $description = "Unknown Beverage";
public function getDescription() : string {
return $this->description;
}
abstract public function cost() : float ;
}<file_sep>/ch09/ObjectvilleDinerPancakeHouse/CompositeIterator.php
<?php
class CompositeIterator implements IteratorInterface {
private $stack = array();
public function __construct(IteratorInterface $iterator){
array_push($this->stack, $iterator);
}
public function next(){
if($this->hasNext()){
$iterator = $this->array_peek($this->stack);
$component = $iterator->next();
if($component instanceof Menu) {
array_push($this->stack , $component->createIterator());
}
return $component;
}
return NULL;
}
public function hasNext() : bool {
if(count($this->stack) <= 0 ) return false;
$iterator = $this->array_peek($this->stack);
if(!$iterator->hasNext()){
array_pop($this->stack);
return $this->hasNext();
}
return true;
}
private function array_peek(array $array){
return $array[count($array) - 1];
}
}<file_sep>/ch08/StarbuzzCoffeeRecipe/Tea.php
<?php
class Tea extends CaffeineBeverage {
protected function brew(){
echo "Steeping the tea " . PHP_EOL;
}
protected function addCondiments(){
echo "Adding Lemon " . PHP_EOL;
}
}<file_sep>/ch10/MightyGumball/WinnerState.php
<?php
class WinnerState implements StateInterface {
private $machine;
public function __construct(GumballMachine $machine) {
$this->machine = $machine;
}
public function insertQuarter() {
echo "Can't do that .\n";
}
public function ejectQuarter() {
echo "Can't do that .\n";
}
public function turnCrank() {
echo "Can't do that .\n";
}
public function dispense() {
echo "YOU'RE A WINNER! You get two gumballs for a quarter\n";
$this->machine->releaseBall();
if ($this->machine->getCount() === 0) {
$this->machine->setState($this->machine->getSoldOutState());
} else {
$this->machine->releaseBall();
if ($this->machine->getCount() > 0) {
$this->machine->setState($this->machine->getNoQuarterState());
} else {
echo "Oops, out of gumballs\n";
$this->machine->setState($this->machine->getSoldOutState());
}
}
}
public function description(): string {
return "got a winner.";
}
}<file_sep>/ch06/HomeAutomation/Commands/CeilingFanOnCommand.php
<?php
namespace Commands;
use \Command;
use Receiver\CeilingFan;
class CeilingFanOnCommand implements Command {
private $fan;
public function __construct(CeilingFan $fan){
$this->fan = $fan;
}
public function execute(){
$this->fan->on();
}
public function undo(){
$this->fan->off();
}
}
|
0a62e8450ccd59137203e88df3b0ca1bf74e605d
|
[
"Markdown",
"PHP"
] | 126 |
PHP
|
LionRoar/Head-First-Design-Patterns-PHP
|
e5e43662e419a227feac4d8897912ab0998019b5
|
261a378fff0cfda87f7daeef17c61f2ccb42d432
|
refs/heads/main
|
<file_sep># Professional Readme Generator
This readme generator was created using node.js and inquirer. Inquirer was used to create every single question and prompt that shows up in the command terminal and saves the responses. Node.js allows the user to run this through the terminal and prompts each user at every step until reaching the end.
## Table of Contents
-[Description](#description)<br/>
-[Installation](#installation)<br/>
-[Usage](#usage)<br/>
-[License](#license)<br/>
-[Contribution](#contribution)<br/>
-[Testing](#testing)<br/>
-[Questions](#questions)<br/>
## Description
This is a basic node application where a user is prompted with several questions, that when answered, will generate into a readme file.
## Installation
To run this application, please type in "npm i inquirer" into the terminal in order to install the inquirer node package.
## Usage
When the application is needed to be ran, simply type "node index.js" into the terminal and several questions will appear. Answer each one and at the end, all of the data will be stored and transfered to a new readme file.
## License
The license for this application is:
## Contribution
If you would like to contribute to this application, please contact me in my questions section.
## Testing
No testing needed.
## Questions
You can find my repositories on GitHub: [https://github.com/kevinphan97]
If you have any questions feel free to email me at: <EMAIL>
<file_sep>// TODO: Create a function that returns a license badge based on which license is passed in
// If there is no license, return an empty string
// TODO: Create a function that returns the license link
// If there is no license, return an empty string
// function renderLicenseLink(license) {}
// TODO: Create a function that returns the license section of README
// If there is no license, return an empty string
// function renderLicenseSection(license) {}
// TODO: Create a function to generate markdown for README
function generateMarkdown(data) {
return `# ${data.title}
## Table of Contents
-[Description](#description)<br/>
-[Installation](#installation)<br/>
-[Usage](#usage)<br/>
-[License](#license)<br/>
-[Contribution](#contribution)<br/>
-[Testing](#testing)<br/>
-[Questions](#questions)<br/>
## Description
${data.description}
## Installation
${data.installation}
## Usage
${data.usage}
## License
The license for this application is:
## Contribution
${data.contribution}
## Testing
${data.test}
## Questions
You can find my repositories on GitHub: [https://github.com/${data.github}]
If you have any questions feel free to email me at: ${data.email}
`};
module.exports = generateMarkdown;
|
062bcc5e2d40c3c7ae46e667a52f797ac2cb605e
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
kevinphan97/professional-readme
|
8f7ed9e4c8a17399b71aeaec45fe6b2628a37dd5
|
4ee106ad20578da6c8448b9d5121e2e39e6294a7
|
refs/heads/master
|
<file_sep>version=1.0
server.servlet.context-path=/api<file_sep>package com.company.model.country;
import java.util.List;
/**
* Created on 7/23/18.
*
* @author <NAME>
* @since JDK1.8
*/
public interface CountryService {
List<Country> get();
Country get(Long id);
}
<file_sep>lang.en=English
lang.ch=Swiss
lang.de=Germany
lang.fr=France
lang.it=Italy
<file_sep>package com.company.model.country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created on 7/23/18.
*
* @author <NAME>
* @since JDK1.8
*/
@Service
public class CountryServiceImpl implements CountryService {
private CountryRepository repository;
@Autowired
public CountryServiceImpl(final CountryRepository repository) {
this.repository = repository;
}
@Override
public List<Country> get() {
return repository.findAll();
}
@Override
public Country get(final Long id) {
return repository.getOne(id);
}
}
<file_sep>package com.company;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class MainController {
private static final Map<String, String> VERSION;
static {
VERSION = new HashMap<>();
VERSION.put("version", "1.0");
}
@Value("${version}")
private String version;
@RequestMapping(value = "/version", method = RequestMethod.GET)
public Map<String, String> version() {
return VERSION;
}
@RequestMapping(value = "/transactiontypes", method = RequestMethod.GET)
public Object getSupportedTransactionTypes() {
return null;
}
@RequestMapping(value = "/execute", method = RequestMethod.POST)
public Object greeting(@RequestBody Object ipRequest) {
return null;
}
}
<file_sep>package com.company.model.country;
import com.company.model.BaseEntity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
/**
* Created on 7/20/18.
*
* @author <NAME>
* @since JDK1.8
*/
@Getter
@Setter
@Entity
public class Country extends BaseEntity {
private static final long serialVersionUID = -9171280139473224408L;
private String name;
@JsonIgnore
private int square;
}
|
b80431a2bc566bc6550836e29383c0efa65cce98
|
[
"Java",
"INI"
] | 6 |
INI
|
dkuhta/spring-boot-rest
|
eb5a303f0a1fe6ec9f823ed8084d0988aecb6408
|
388936cf6825168a7ca81ba80744efcad64a4327
|
refs/heads/master
|
<file_sep>from PIL import Image
#ouverture de l'image
img = Image.open("img/1-intro.jpg")
img2 = Image.new("RGB", (img.size[0]-5, img.size[1]-4), "black")
imgWidth = img.size[0]
imgHeigth = img.size[1]
level = 8
i = 0
x = 0
y = 0
while i <= imgWidth-level:
j = 0
while j <= imgHeigth-level:
moy = [0,0,0]
for u in range(level):
x +=1
for y in range(level):
y +=1
pixelColor = img.getpixel((i+u+2,j+y+2))
moy[0] = moy[0]+pixelColor[0]
moy[1] = moy[1]+pixelColor[1]
moy[2] = moy[2]+pixelColor[2]
moy[0] = moy[0]/(level*level)
moy[1] = moy[1]/(level*level)
moy[2] = moy[2]/(level*level)
for u in range(level):
for y in range(level):
print(i+u,j+y)
img2.putpixel((i+u,j+y),(moy[0],moy[1],moy[2]))
j += level;
i += level;
img2.save("test1.jpg")
|
24918e26801536073025834b6b9fc259cedb7f7d
|
[
"Python"
] | 1 |
Python
|
thewrath/simple-python-fuzzy-image-transfo
|
d5950332331937090ee913d3d3468e3646595c32
|
927e1b62a3f21d0df8a28cbe15033613b2a00c14
|
refs/heads/master
|
<repo_name>BrunoGodefroy/theodo-form-printer<file_sep>/src/services/reduxSagaFirebase.js
import firebase from 'firebase'
import ReduxSagaFirebase from 'redux-saga-firebase'
const myFirebaseApp = firebase.initializeApp({
apiKey: '<KEY>',
authDomain: 'm33-performance-32c4d.firebaseapp.com',
databaseURL: 'https://m33-performance-32c4d.firebaseio.com',
storageBucket: 'm33-performance-32c4d.appspot.com'
})
const reduxSagaFirebase = new ReduxSagaFirebase(myFirebaseApp)
export default reduxSagaFirebase
<file_sep>/src/config/questionSlugs.js
export default {
SPEED: 'speed',
COLLABORATION: 'collaboration',
CLIENT_VOICE: 'clientVoice',
MAGIC_WAND: 'magicWand',
RECOMMENDATION: 'recommendation',
SALE_APPOINTMENT: 'saleAppointment',
EXPLANATION: 'explanation'
}
<file_sep>/src/components/logic/index.js
import LoginButton from './LoginButton'
import SelectCompanyButtons from './SelectCompanyButtons'
import ListForms from './ListForms'
module.exports = {
LoginButton,
SelectCompanyButtons,
ListForms
}
<file_sep>/src/components/logic/LoginButton.jsx
import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { Button } from 'semantic-ui-react'
import { loginRequest, logoutRequest } from '@redux/actions'
class LoginButton extends PureComponent {
constructor (props) {
super(props)
this.handleLogin = this.handleLogin.bind(this)
this.handleLogout = this.handleLogout.bind(this)
}
handleLogin (event) {
event.preventDefault()
this.props.loginRequest()
}
handleLogout (event) {
event.preventDefault()
this.props.logoutRequest()
}
render () {
return this.props.loggedIn
? <Button className={this.props.className} onClick={this.handleLogout} content='Logout' icon='log out' />
: <Button className={this.props.className} onClick={this.handleLogin} content='Login' icon='sign in' />
}
}
LoginButton.propTypes = {
loggedIn: PropTypes.bool.isRequired,
loginRequest: PropTypes.func.isRequired,
logoutRequest: PropTypes.func.isRequired,
loading: PropTypes.bool.isRequired,
className: PropTypes.string
}
const mapStateToProps = ({ loggedIn, loading }) => ({
loggedIn,
loading
})
const mapDispatchToProps = {
loginRequest,
logoutRequest
}
export default connect(mapStateToProps, mapDispatchToProps)(LoginButton)
<file_sep>/src/config/index.js
import companies from './companies'
import formStatus from './formStatus'
import questionSlugs from './questionSlugs'
import questionTypes from './questionTypes'
module.exports = {
companies,
formStatus,
questionSlugs,
questionTypes
}
<file_sep>/src/components/App.jsx
import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { Header, Container, Loader, Dimmer, Divider } from 'semantic-ui-react'
import {
LoginButton,
SelectCompanyButtons,
ListForms
} from '@components/logic'
import { Error } from '@components/ui'
class App extends PureComponent {
render () {
return <Container text textAlign='center'>
<Container className='no-print' textAlign='center'>
<Dimmer className='no-print' active={this.props.loading} inverted>
<Loader inverted>Loading</Loader>
</Dimmer>
</Container>
<Header className='no-print' as='h1' textAlign='center'> { this.props.selectedCompany.name } Project Form - Print Me</Header>
<Container className='no-print'>
<LoginButton />
</Container>
<Divider className='no-print' />
<Container className='no-print'>
{ this.props.loggedIn && <SelectCompanyButtons /> }
</Container>
{ this.props.error && <Error className='no-print'>{ this.props.errorMessage }</Error> }
<Container>
{ this.props.isCompanyChosen && <ListForms /> }
</Container>
</Container>
}
}
App.propTypes = {
error: PropTypes.bool.isRequired,
loading: PropTypes.bool.isRequired,
errorMessage: PropTypes.string.isRequired,
loggedIn: PropTypes.bool.isRequired,
isCompanyChosen: PropTypes.bool.isRequired,
selectedCompany: PropTypes.object
}
const mapStateToProps = ({
loading,
loggedIn,
error,
errorMessage,
isCompanyChosen,
selectedCompany
}) => ({
loading,
error,
errorMessage,
loggedIn,
isCompanyChosen,
selectedCompany
})
const mapDispatchToProps = {}
export default connect(mapStateToProps, mapDispatchToProps)(App)
<file_sep>/src/config/formStatus.js
export default {
WOW: 'WOW',
OK: 'OK',
KO: 'KO'
}
<file_sep>/src/config/forms/fastit.js
import types from '@config/questionTypes'
import questionSlugs from '@config/questionSlugs'
export default {
questions: [
{
slug: questionSlugs.SPEED,
label: 'Quelle est votre appréciation sur la qualité de l\'accompagnement de Fast IT ?',
type: types.MULTIPLE_CHOICE,
choices: [
{
slug: 5,
label: '5 - Excellente'
},
{
slug: 4,
label: '4 - Très bonne'
},
{
slug: 3,
label: '3 - Bonne'
},
{
slug: 2,
label: '2 - Moyenne'
},
{
slug: 1,
label: '1 - Insuffisante'
},
{
slug: 0,
label: '0 - Très insuffisante'
}
]
},
{
slug: questionSlugs.COLLABORATION,
label: 'Quelle est votre appréciation sur la vitesse d\'avancement de l\'équipe Fast IT?',
type: types.MULTIPLE_CHOICE,
choices: [
{
slug: 5,
label: '5 - Excellente'
},
{
slug: 4,
label: '4 - Très bonne'
},
{
slug: 3,
label: '3 - Bonne'
},
{
slug: 2,
label: '2 - Moyenne'
},
{
slug: 1,
label: '1 - Insuffisante'
},
{
slug: 0,
label: '0 - Très insuffisante'
}
]
},
{
slug: questionSlugs.CLIENT_VOICE,
label: 'Quel changementamélioration prioritaire pourrait vous amener à améliorer votre appréciation ?',
type: types.TEXT
},
{
slug: questionSlugs.MAGIC_WAND,
label: 'Si vous aviez une baguette magique, quelle est "la" chose que vous changeriez chez Fast IT ?',
type: types.TEXT
},
{
slug: questionSlugs.RECOMMENDATION,
label: 'Seriez-vous prêt à recommander Fast IT ?',
type: types.MULTIPLE_CHOICE,
choices: [
{
slug: 'yesAbs',
label: 'Oui bien sûr'
},
{
slug: 'yes',
label: 'Oui'
},
{
slug: 'notReally',
label: 'Pas vraiment'
},
{
slug: 'notAtAll',
label: 'Pas du tout'
}
]
},
{
slug: questionSlugs.SALE_APPOINTMENT,
label: 'Souhaitez-vous rencontrer un chef de projet Fast IT dans la semaine à venir pour échanger sur le déroulement du projet ?',
type: types.MULTIPLE_CHOICE,
choices: [
{
slug: 'yes',
label: 'Oui'
},
{
slug: 'no',
label: 'Non, ce n’est pas nécessaire pour l’instant'
}
]
}
],
PROJECT: 'Equipe',
SPRINT: 'Sprint n°',
YES_ABS: 'Oui bien sûr'
}
<file_sep>/src/services/formTransformer.js
import moment from 'moment'
import {
formStatus,
questionSlugs
} from '@config'
export default (data, company) => {
const { questions, YES_ABS, SPRINT, PROJECT } = company.config
const collaborationLabel = questions.find(question => question.slug === questionSlugs.COLLABORATION).label
const speedLabel = questions.find(question => question.slug === questionSlugs.SPEED).label
const recommendationLabel = questions.find(question => question.slug === questionSlugs.RECOMMENDATION).label
const parseFormTheodoUk = form => {
const collaboration = typeof form[collaborationLabel] !== 'undefined' ? parseInt(form[collaborationLabel][0]) : 0
const speed = typeof form[speedLabel] !== 'undefined' ? parseInt(form[speedLabel][0]) : 0
const recomendation = form[recommendationLabel] === YES_ABS
let status
if (recomendation && collaboration + speed >= 8) {
if (collaboration + speed === 10) {
status = formStatus.WOW
numberOfWow++
} else {
status = formStatus.OK
numberOfOk++
}
} else {
status = formStatus.KO
numberOfKo++
}
return {
questions: questions.map(question => ({
...question,
answer: form[question.label]
})),
project: form[PROJECT],
sprint: form[SPRINT],
timestamp: moment(form.timestamp),
status
}
}
let numberOfWow = 0
let numberOfOk = 0
let numberOfKo = 0
let forms = Object.values(data).map(parseFormTheodoUk)
const compareFormDate = (formA, formB) => formA.timestamp.isBefore(formB.timestamp) ? 1 : -1
forms.sort(compareFormDate)
return { forms, numberOfWow, numberOfOk, numberOfKo }
}
<file_sep>/src/components/logic/ListForms.jsx
import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { Accordion, Label, Container } from 'semantic-ui-react'
import { ProjectForm } from '@components/ui'
import formStatus from '@config/formStatus'
class ListForms extends PureComponent {
render () {
const panels = this.props.forms.map((form, index) => {
let label
switch (form.status) {
case formStatus.WOW:
label = <Label color='green' className='pinned'>WOW!</Label>
break
case formStatus.OK:
label = <Label color='olive' className='pinned'>Success</Label>
break
case formStatus.KO:
label = <Label color='red' className='pinned'>Red bucket</Label>
break
default:
label = <Label color='pink' className='pinned'>error</Label>
}
const formTitle = form.sprint ? `${form.project} - Sprint ${form.sprint}` : `${form.project}`
return {
title: <span>{formTitle} {label}</span>,
content: <ProjectForm form={form} company={this.props.selectedCompany.name} />,
key: `${form.project} - Sprint ${form.sprint} - ${index}`
}
})
if (this.props.forms.length > 0) {
return <Container className={`company-${this.props.selectedCompany.name}`} >
<Container style={{ margin: '10px', display: 'flex', flexDirection: 'column' }} className='no-print'>
<Container textAlign='center'>
<Label color='green' >WOW: {this.props.numberOfWow} / {this.props.forms.length} - {Math.round(this.props.numberOfWow * 100 / this.props.forms.length)}%</Label>
<Label color='olive' >Success: {this.props.numberOfOk} / {this.props.forms.length} - {Math.round(this.props.numberOfOk * 100 / this.props.forms.length)}%</Label>
<Label color='red' >Red Bucket: {this.props.numberOfKo} / {this.props.forms.length} - {Math.round(this.props.numberOfKo * 100 / this.props.forms.length)}%</Label>
</Container>
</Container>
<Container style={{ display: 'flex', justifyContent: 'center' }} textAlign='left'>
<Accordion panels={panels} styled />
</Container>
</Container>
} else {
return <Container as='p'>To load the latest form, please click on "update the latest forms"</Container>
}
}
}
ListForms.propTypes = {
forms: PropTypes.array.isRequired,
selectedCompany: PropTypes.object.isRequired,
numberOfWow: PropTypes.number.isRequired,
numberOfOk: PropTypes.number.isRequired,
numberOfKo: PropTypes.number.isRequired,
loading: PropTypes.bool.isRequired
}
const mapStateToProps = ({
loading,
forms,
questions,
selectedCompany,
numberOfWow,
numberOfOk,
numberOfKo
}) => ({
loading,
forms,
questions,
selectedCompany,
numberOfWow,
numberOfOk,
numberOfKo
})
const mapDispatchToProps = {}
export default connect(mapStateToProps, mapDispatchToProps)(ListForms)
<file_sep>/src/config/forms/bam.js
import types from '@config/questionTypes'
import questionSlugs from '@config/questionSlugs'
export default {
questions: [
{
slug: questionSlugs.SPEED,
label: 'Quelle est votre appréciation sur la vitesse d\'avancement de l\'équipe ? ',
type: types.MULTIPLE_CHOICE,
choices: [
{
slug: 5,
label: '5 - Excellente'
},
{
slug: 4,
label: '4 - Très bien'
},
{
slug: 3,
label: '3 - Bien'
},
{
slug: 2,
label: '2 - Moyenne'
},
{
slug: 1,
label: '1 - Insuffisante'
},
{
slug: 0,
label: '0 - Très insuffisante'
}
]
},
{
slug: questionSlugs.COLLABORATION,
label: 'Quelle est votre appréciation sur la qualité de l\'accompagnement BAM ?',
type: types.MULTIPLE_CHOICE,
choices: [
{
slug: 5,
label: '5 - Excellente'
},
{
slug: 4,
label: '4 - Très bonne'
},
{
slug: 3,
label: '3 - Bonne'
},
{
slug: 2,
label: '2 - Moyenne'
},
{
slug: 1,
label: '1 - Insuffisante'
},
{
slug: 0,
label: '0 - Très insuffisante'
}
]
},
{
slug: questionSlugs.CLIENT_VOICE,
label: 'Quel changementamélioration prioritaire pourrait vous amener à améliorer votre appréciation ?',
type: types.TEXT
},
{
slug: questionSlugs.MAGIC_WAND,
label: 'Si vous aviez une baguette magique quel changement apporteriez vous chez BAM ?',
type: types.TEXT
},
{
slug: questionSlugs.RECOMMENDATION,
label: 'Seriez-vous prêt à recommander BAM ?',
type: types.MULTIPLE_CHOICE,
choices: [
{
slug: 'yesAbs',
label: 'Oui bien sur'
},
{
slug: 'yes',
label: 'Oui'
},
{
slug: 'notReally',
label: 'Pas vraiment'
},
{
slug: 'notAtAll',
label: 'Pas du tout'
}
]
},
{
slug: questionSlugs.EXPLANATION,
label: 'Si vous n\'avez pas répondu "oui bien sûr" à la question précédente, pourquoi ?',
type: types.TEXT
},
{
slug: questionSlugs.SALE_APPOINTMENT,
label: 'Souhaitez-vous faire un point commercial avec BAM dans la semaine à venir ?',
type: types.MULTIPLE_CHOICE,
choices: [
{
slug: 'yes',
label: 'Oui'
},
{
slug: 'no',
label: 'Non ce n\'est pas nécessaire pour l\'instant'
}
]
}
],
PROJECT: 'Nom du projet',
SPRINT: 'Sprint n°',
YES_ABS: 'Oui bien sur'
}
<file_sep>/src/redux/reducer.js
import { types } from '@redux/actions'
import formTransformer from '@services/formTransformer'
const initialState = {
loggedIn: false,
loading: false,
error: false,
forms: [],
isCompanyChosen: false,
selectedCompany: { name: '', path: '', config: null },
errorMessage: '',
numberOfWow: 0,
numberOfOk: 0,
numberOfKo: 0
}
export default function reducer (state = initialState, action = {}) {
switch (action.type) {
case types.LOGIN.REQUEST:
case types.LOGOUT.REQUEST:
case types.FETCH_FORMS.REQUEST:
return {
...state,
loading: true
}
case types.LOGIN.FAILURE:
case types.LOGOUT.FAILURE:
case types.FETCH_FORMS.FAILURE:
return {
...state,
loading: false,
error: true,
errorMessage: action.error
}
case types.LOGIN.SUCCESS:
return {
...state,
loading: false,
loggedIn: true,
error: false
}
case types.LOGOUT.SUCCESS:
return initialState
case types.FETCH_FORMS.SUCCESS:
const {
forms,
numberOfWow,
numberOfOk,
numberOfKo
} = formTransformer(action.payload, action.company)
return {
...state,
loading: false,
error: false,
forms,
numberOfWow,
numberOfOk,
numberOfKo
}
case types.COMPANY_SELECTED:
return {
...state,
isCompanyChosen: true,
selectedCompany: action.company
}
default:
return state
}
}
<file_sep>/README.md
[](https://circleci.com/gh/BrunoGodefroy/theodo-form-printer/tree/master)
# Theodo forms printer
This projects aims at make it easier for anyone at Theodo to print their project form. No more excuses to have a board out of date.
## Installation
```bash
yarn
```
## Development
Launch the dev server:
```bash
yarn dev
```
The dev server is listening on `localhost:8000`
## Deployment
Merge `master` in `gh-pages`
then run on the `gh-pages` branch:
```bash
./deploy.sh
```
The new version of the website is available at [https://brunogodefroy.github.io/theodo-form-printer/](https://brunogodefroy.github.io/theodo-form-printer/)
<file_sep>/src/components/ui/ProjectForm.jsx
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { Form, Segment, Header, Button, Icon } from 'semantic-ui-react'
import ReactGA from 'react-ga'
import { questionTypes } from '@config'
class ProjectForm extends PureComponent {
constructor (props) {
super(props)
this.printForm = this.printForm.bind(this)
}
printForm (event) {
event.preventDefault()
ReactGA.event({
category: 'Forms',
action: 'Print',
label: this.props.form.project,
})
window.print()
}
render () {
return <Form>
<Button className='no-print' onClick={this.printForm} icon>
<Icon name='print' />
</Button>
{ this.props.form.questions.map(question => {
switch (question.type) {
case questionTypes.MULTIPLE_CHOICE:
return <Segment key={`segment-${question.slug}`} vertical>
<Header as='h3'>{ question.label }</Header>
{ question.choices.map(choice => {
return (<Form.Radio key={`${question.slug}-${choice.slug}`} label={choice.label} checked={question.answer === choice.label} />)
}) }
</Segment>
default:
return <Segment key={`segment-${question.slug}`} vertical>
<Header as='h3'>{ question.label }</Header>
{ question.answer.split(/\n/).map((string, index) => <p key={`${question.questionSlug}-${index}`}>{ string }</p>) }
</Segment>
}
})
}
</Form>
}
}
ProjectForm.propTypes = {
form: PropTypes.object.isRequired
}
export default ProjectForm
<file_sep>/src/redux/sagas.js
import { call, put, takeEvery, takeLatest, select, fork, take, cancel, cancelled } from 'redux-saga/effects'
import firebase from 'firebase'
import {
types,
loginSuccess,
loginFailure,
logoutSuccess,
logoutFailure,
fetchFormsRequest,
fetchFormsSuccess,
fetchFormsFailure
} from '@redux/actions'
import reduxSagaFirebase from '@services/reduxSagaFirebase'
const authProvider = new firebase.auth.GoogleAuthProvider()
function * loginSaga (action) {
try {
yield call(reduxSagaFirebase.auth.signInWithPopup, authProvider)
yield put(loginSuccess())
} catch (e) {
yield put(loginFailure('Authentication failed. Please try again'))
}
}
function * logoutSaga (action) {
try {
yield call(reduxSagaFirebase.auth.signOut)
yield put(logoutSuccess())
} catch (e) {
yield put(logoutFailure('Logout failed. Please try again'))
}
}
function * syncUserSaga () {
const channel = yield call(reduxSagaFirebase.auth.channel)
while (true) {
const { user } = yield take(channel)
if (user) yield put(loginSuccess())
else yield put(logoutSuccess())
}
}
function * syncLatestFormsSaga (channel, company) {
while (true) {
try {
const { value: data } = yield take(channel)
yield put(fetchFormsSuccess(data, company))
} catch (e) {
yield put(fetchFormsFailure('The latest project forms could not be retrieved. Please check you have the permission to view them'))
} finally {
if (yield cancelled()) channel.close()
}
}
}
function * handleFormsSyncSaga (action) {
const company = yield select(state => state.selectedCompany)
const channel = yield call(reduxSagaFirebase.database.channel, firebase.database().ref(`forms/${company.path}`).orderByChild('timestamp').limitToLast(30))
const syncTask = yield fork(syncLatestFormsSaga, channel, company)
}
function * triggerFetchFormSaga (action) {
const loggedIn = yield select(state => state.loggedIn)
if (loggedIn) yield put(fetchFormsRequest())
}
function * rootSaga () {
yield fork(syncUserSaga)
yield takeEvery(types.LOGIN.REQUEST, loginSaga)
yield takeEvery(types.LOGOUT.REQUEST, logoutSaga)
yield takeLatest(types.FETCH_FORMS.REQUEST, handleFormsSyncSaga)
yield takeEvery(types.COMPANY_SELECTED, triggerFetchFormSaga)
}
export default rootSaga
<file_sep>/deploy.sh
CURRENT_BRANCH=`git rev-parse --abbrev-ref HEAD`
if [ -z "$(git status --porcelain)" ]
then
echo "Clean directory."
else
echo "Uncommited changes."
exit 1
fi
if [ "$CURRENT_BRANCH" != "gh-pages" ]
then
echo "Wrong branch, checkout gh-pages to deploy."
exit 1
fi
git pull
git merge origin/master --no-edit
rm bundle.*.js
yarn build
git add 'bundle.*.js'
git add index.html
git commit -m 'Deployment'
git push
<file_sep>/src/config/questionTypes.js
export default {
MULTIPLE_CHOICE: 'MULTIPLE_CHOICE',
TEXT: 'TEXT'
}
<file_sep>/webpack.config.js
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin')
const ROOT_PATH = path.resolve(__dirname)
module.exports = function (env) {
let plugins = [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: './index_template.html',
alwaysWriteToDisk: true
}),
new HtmlWebpackHarddiskPlugin()
]
if (env && env.production) {
plugins.push(new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
minimize: true,
comments: false,
sourceMap: true
}))
plugins.push(new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}))
}
return {
entry: ['babel-polyfill', './src/index.jsx'],
output: {
path: path.resolve(ROOT_PATH, './'),
publicPath: '',
filename: 'bundle.[hash].js'
},
module: {
rules: [
{
test: /\.(gif|png|svg)$/,
use: ['url-loader', 'img-loader']
},
{
test: /\.jsx?$/,
use: ['react-hot-loader', 'babel-loader'],
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
'@components': path.resolve(ROOT_PATH, 'src/components'),
'@images': path.resolve(ROOT_PATH, 'src/images'),
'@redux': path.resolve(ROOT_PATH, 'src/redux'),
'@services': path.resolve(ROOT_PATH, 'src/services'),
'@style': path.resolve(ROOT_PATH, 'src/style'),
'@config': path.resolve(ROOT_PATH, 'src/config')
}
},
devServer: {
contentBase: path.resolve(ROOT_PATH, './'),
historyApiFallback: true,
hot: true,
inline: true,
port: 8000
},
plugins: plugins
}
}
<file_sep>/src/index.jsx
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import ReactGA from 'react-ga'
import store from '@redux/store'
import App from '@components/App'
ReactGA.initialize('UA-102505380-1')
ReactGA.pageview('/')
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
)
<file_sep>/src/components/ui/index.js
import Error from './Error.jsx'
import ProjectForm from './ProjectForm.jsx'
module.exports = {
Error,
ProjectForm
}
|
fe1ef5cd71dca2ae19e6e7ec35b952e212ca9fd9
|
[
"JavaScript",
"Markdown",
"Shell"
] | 20 |
JavaScript
|
BrunoGodefroy/theodo-form-printer
|
b2e2f10b0bc31e88ad8b4a4addea9bbeba47de40
|
461d6cff36faa6122a94012d84bf801d70cdec3c
|
refs/heads/master
|
<repo_name>fox2402/vampireGuns<file_sep>/Assets/Scripts/TR100script.cs
using UnityEngine;
using System.Collections;
public class TR100script : basicControl {
[SerializeField]
protected float recoil;
[SerializeField]
GameObject rtPoint;
public Vector3 lerping;
protected override void Update()
{
base.Update();
lerping = Vector3.Lerp(rtPoint.transform.position, canon.transform.position, (shootTime - Time.time) / shootCD);
canon.transform.position = lerping;
}
protected override void shootAnim()
{
Debug.Log("anim");
canon.transform.Translate(0,0,-recoil);
}
protected override void Shoot()
{
if (Time.time > shootTime)
{
Debug.Log("ute!");
shootAnim();
Instantiate(bullet, muzzle.transform.position, muzzle.transform.rotation);
shootTime = Time.time + shootCD;
}
}
}
<file_sep>/Assets/Scripts/bulletMain.cs
using UnityEngine;
using System.Collections;
public class bulletMain : MonoBehaviour {
[SerializeField]
protected float speed;
[SerializeField]
protected float lifeSpan;
private float deathTime;
// Use this for initialization
void Start () {
deathTime = Time.time + lifeSpan;
}
// Update is called once per frame
void Update () {
gameObject.transform.Translate(0,0,speed);
if(Time.time>deathTime)
{
Destroy(gameObject);
}
}
void OnCollisionEnter(Collision collision)
{
Destroy(gameObject);
}
}
<file_sep>/Assets/Scripts/basicControl.cs
using UnityEngine;
using System.Collections;
public class basicControl : MonoBehaviour {
[SerializeField]
protected GameObject turret;
[SerializeField]
protected GameObject turretB;
[SerializeField]
protected GameObject canon;
[SerializeField]
protected GameObject muzzle;
[SerializeField]
protected GameObject bullet;
[SerializeField]
protected float roSpeed = 50.0f;
[SerializeField]
protected float shootCD;
[SerializeField]
protected float upperLim;
[SerializeField]
protected float lowerLim;
public float t;
protected float shootTime;
// Use this for initialization
protected virtual void Start () {
shootTime = 0;
}
// Update is called once per frame
protected virtual void Update () {
t = turretB.transform.eulerAngles.z;
turretB.transform.Rotate(0,0, -Input.GetAxis("Mouse Y"), Space.Self);
turret.transform.Rotate(this.transform.up, Input.GetAxis("Mouse X"));
if (turretB.transform.eulerAngles.z > lowerLim && turretB.transform.eulerAngles.z < 150)
{
float temp = turretB.transform.eulerAngles.z - lowerLim ;
turretB.transform.Rotate(0, 0, -temp);
Debug.Log("bang");
}
if(turretB.transform.eulerAngles.z < upperLim && turretB.transform.eulerAngles.z > 150)
{
float temp = turretB.transform.eulerAngles.z - upperLim;
turretB.transform.Rotate(0, 0, -temp);
Debug.Log("bang");
}
if(Input.GetMouseButton(0))
{
Shoot();
}
}
protected virtual void shootAnim()
{
canon.transform.Rotate(0, 0, roSpeed);
}
protected virtual void Shoot()
{
if(Time.time>shootTime)
{
shootAnim();
Instantiate(bullet, muzzle.transform.position, muzzle.transform.rotation);
shootTime = Time.time + shootCD;
}
}
}
|
e26452c282895127ef46d10082f2e7a2dcef3cad
|
[
"C#"
] | 3 |
C#
|
fox2402/vampireGuns
|
9fbc469dbb378156003fff410dcd7c1c7eef749d
|
b6d0b468735afc44785f3946556db0ab88419aa7
|
refs/heads/main
|
<repo_name>prasasti8015/PGDDS_IIITBangalore<file_sep>/Retail Click Stream Data/README.md
**Retail Click Stream Data**
**Introduction**
So far, in this course, you have learned about the Hadoop Framework, RDBMS design, and Hive Querying. You have understood how to work with an EMR cluster and write optimized queries on Hive.
This assignment aims at testing your skills in Hive and Hadoop concepts learned throughout this course. Similar to Big Data Analysts, you will be required to extract the data, load them into Hive tables, and gather insights from the dataset.
**Problem Statement**
With online sales gaining popularity, tech companies are exploring ways to improve their sales by analyzing customer behavior and gaining insights about product trends. Furthermore, the websites make it easier for customers to find the products that they require without much scavenging. Needless to say, the role of big data analysts is among the most sought-after job profiles of this decade. Therefore, as part of this assignment, we will be challenging you, as a big data analyst, to extract data and gather insights from a real-life data set of an e-commerce company.
One of the most popular use cases of Big Data is in eCommerce companies such as Amazon or Flipkart. So before we get into the details of the dataset, let us understand how eCommerce companies make use of these concepts to give customers product recommendations. This is done by tracking your clicks on their website and searching for patterns within them. This kind of data is called a clickstream data. Let us understand how it works in detail.
The clickstream data contains all the logs as to how you navigated through the website. It also contains other details such as time spent on every page, etc. From this, they make use of data ingesting frameworks such as Apache Kafka or AWS Kinesis in order to store it in frameworks such as Hadoop. From there, machine learning engineers or business analysts use this data to derive valuable insights.
For this assignment, you will be working with a public clickstream dataset of a cosmetics store. Using this dataset, your job is to extract valuable insights which generally data engineers come up with in an e-retail company. So now, let us understand the dataset in detail.
You will find the data in the link given below.
https://e-commerce-events-ml.s3.amazonaws.com/2019-Oct.csv
https://e-commerce-events-ml.s3.amazonaws.com/2019-Nov.csv
<file_sep>/RSVP Movie Assignment/IMDB+question.sql
USE imdb;
/* Now that you have imported the data sets, let’s explore some of the tables.
To begin with, it is beneficial to know the shape of the tables and whether any column has null values.
Further in this segment, you will take a look at 'movies' and 'genre' tables.*/
-- Segment 1:
-- Q1. Find the total number of rows in each table of the schema?
-- Type your code below:
-- query to find out the number of rows in each table
(SELECT 'director_mapping' AS TableName, COUNT(*) AS row_cnt FROM director_mapping) UNION ALL
(SELECT 'genre' AS TableName, COUNT(*) AS row_cnt FROM genre) UNION ALL
(SELECT 'movie' AS TableName, COUNT(*) AS row_cnt FROM movie) UNION ALL
(SELECT 'names' AS TableName, COUNT(*) AS row_cnt FROM names) UNION ALL
(SELECT 'ratings' AS TableName, COUNT(*) AS row_cnt FROM ratings) UNION ALL
(SELECT 'role_mapping' AS TableName, COUNT(*) AS row_cnt FROM role_mapping);
-- Q2. Which columns in the movie table have null values?
-- Type your code below:
WITH null_count AS
(
(SELECT "id" AS ColumnName, SUM(CASE WHEN id IS NULL THEN 1 ELSE 0 END) AS null_cnt FROM movie) UNION ALL
(SELECT "title" AS ColumnName, SUM(CASE WHEN title IS NULL THEN 1 ELSE 0 END) AS null_cnt FROM movie) UNION ALL
(SELECT "year" AS ColumnName, SUM(CASE WHEN year IS NULL THEN 1 ELSE 0 END) AS null_cnt FROM movie) UNION ALL
(SELECT "date_published" AS ColumnName, SUM(CASE WHEN date_published IS NULL THEN 1 ELSE 0 END) AS null_cnt FROM movie) UNION ALL
(SELECT "duration" AS ColumnName, SUM(CASE WHEN duration IS NULL THEN 1 ELSE 0 END) AS null_cnt FROM movie) UNION ALL
(SELECT "country" AS ColumnName, SUM(CASE WHEN country IS NULL THEN 1 ELSE 0 END) AS null_cnt FROM movie) UNION ALL
(SELECT "worlwide_gross_income" AS ColumnName, SUM(CASE WHEN worlwide_gross_income IS NULL THEN 1 ELSE 0 END) AS null_cnt FROM movie) UNION ALL
(SELECT "languages" AS ColumnName, SUM(CASE WHEN languages IS NULL THEN 1 ELSE 0 END) AS null_cnt FROM movie) UNION ALL
(SELECT "production_company" AS ColumnName, SUM(CASE WHEN production_company IS NULL THEN 1 ELSE 0 END) AS null_cnt FROM movie)
)
SELECT ColumnName
FROM null_count
WHERE null_cnt >0;
-- ANS: The columns that have null values are country, world_gross_income, languages and production_company.
-- Now as you can see four columns of the movie table has null values. Let's look at the at the movies released each year.
-- Q3. Find the total number of movies released each year? How does the trend look month wise? (Output expected)
/* Output format for the first part:
+---------------+-------------------+
| Year | number_of_movies|
+-------------------+----------------
| 2017 | 2134 |
| 2018 | . |
| 2019 | . |
+---------------+-------------------+
Output format for the second part of the question:
+---------------+-------------------+
| month_num | number_of_movies|
+---------------+----------------
| 1 | 134 |
| 2 | 231 |
| . | . |
+---------------+-------------------+ */
-- Type your code below:
-- Query to check the total number of movies released each year
SELECT Year,
COUNT(id) AS number_of_movies
FROM movie
GROUP BY Year;
-- The highest number of movies have been produced in the year of 2017. More movies have been produced in the past year than in the recent years.
-- Query to check the trend monthwise
SELECT MONTH(date_published) AS month_num,
COUNT(id) AS number_of_movies
FROM movie
GROUP BY month_num
ORDER BY month_num;
-- Most number of movies have been produced in the month of March
/*The highest number of movies is produced in the month of March.
So, now that you have understood the month-wise trend of movies, let’s take a look at the other details in the movies table.
We know USA and India produces huge number of movies each year. Lets find the number of movies produced by USA or India for the last year.*/
-- Q4. How many movies were produced in the USA or India in the year 2019??
-- Type your code below:
SELECT count(id) AS count_movies
FROM movie
WHERE (year = 2019) AND
(country LIKE "%USA%" OR country LIKE "%India%");
-- 1059 number of movies have been produced in USA or INDIA in the year 2019.
/* USA and India produced more than a thousand movies(you know the exact number!) in the year 2019.
Exploring table Genre would be fun!!
Let’s find out the different genres in the dataset.*/
-- Q5. Find the unique list of the genres present in the data set?
-- Type your code below:
SELECT genre
FROM genre
GROUP BY genre;
-- The unique list of Genre consists of : Drama, Fantasy, Thriller, Comedy, Horror, Family, Romance, Adventure, Action,
-- Sci-Fi, Crime, Mystery and Others
/* So, RSVP Movies plans to make a movie of one of these genres.
Now, wouldn’t you want to know which genre had the highest number of movies produced in the last year?
Combining both the movie and genres table can give more interesting insights. */
-- Q6.Which genre had the highest number of movies produced overall?
-- Type your code below:
SELECT g.genre,
count(DISTINCT m.id) AS movie_cnt
FROM movie AS m
INNER JOIN genre AS g
ON m.id = g.movie_id
GROUP BY g.genre
ORDER BY movie_cnt DESC
LIMIT 1;
-- "Drama" genre has the highest number of movies.
/* So, based on the insight that you just drew, RSVP Movies should focus on the ‘Drama’ genre.
But wait, it is too early to decide. A movie can belong to two or more genres.
So, let’s find out the count of movies that belong to only one genre.*/
-- Q7. How many movies belong to only one genre?
-- Type your code below:
WITH one_genre AS
(
SELECT movie_id,
count(genre) AS genre_cnt
FROM genre
GROUP BY movie_id
HAVING genre_cnt = 1
)
SELECT count(*) AS count_movie
FROM one_genre;
-- 3289 number of movies are there which belong to only one genre
/* There are more than three thousand movies which has only one genre associated with them.
So, this figure appears significant.
Now, let's find out the possible duration of RSVP Movies’ next project.*/
-- Q8.What is the average duration of movies in each genre?
-- (Note: The same movie can belong to multiple genres.)
/* Output format:
+---------------+-------------------+
| genre | avg_duration |
+-------------------+----------------
| thriller | 105 |
| . | . |
| . | . |
+---------------+-------------------+ */
-- Type your code below:
SELECT g.genre,
ROUND(AVG(m.duration),2) AS avg_duration
FROM movie AS m
INNER JOIN genre AS g
ON m.id = g.movie_id
GROUP BY g.genre
ORDER BY avg_duration DESC;
-- "Action" genre has the highest average duration of movies
/* Now you know, movies of genre 'Drama' (produced highest in number in 2019) has the average duration of 106.77 mins.
Lets find where the movies of genre 'thriller' on the basis of number of movies.*/
-- Q9.What is the rank of the ‘thriller’ genre of movies among all the genres in terms of number of movies produced?
-- (Hint: Use the Rank function)
/* Output format:
+---------------+-------------------+---------------------+
| genre | movie_count | genre_rank |
+---------------+-------------------+---------------------+
|drama | 2312 | 2 |
+---------------+-------------------+---------------------+*/
-- Type your code below:
SELECT g.genre,
COUNT(DISTINCT m.id) AS movie_count,
RANK() OVER(ORDER BY COUNT(DISTINCT m.id) DESC) AS genre_rank
FROM movie AS m
INNER JOIN genre AS g
ON m.id = g.movie_id
GROUP BY g.genre;
-- The rank of the ‘thriller’ genre of movies among all the genres in terms of number of movies produced is 3.
/*Thriller movies is in top 3 among all genres in terms of number of movies
In the previous segment, you analysed the movies and genres tables.
In this segment, you will analyse the ratings table as well.
To start with lets get the min and max values of different columns in the table*/
-- Segment 2:
-- Q10. Find the minimum and maximum values in each column of the ratings table except the movie_id column?
/* Output format:
+---------------+-------------------+---------------------+----------------------+-----------------+-----------------+
| min_avg_rating| max_avg_rating | min_total_votes | max_total_votes |min_median_rating|min_median_rating|
+---------------+-------------------+---------------------+----------------------+-----------------+-----------------+
| 0 | 5 | 177 | 2000 | 0 | 8 |
+---------------+-------------------+---------------------+----------------------+-----------------+-----------------+*/
-- Type your code below:
SELECT MIN(avg_rating) AS min_avg_rating,
MAX(avg_rating) AS max_avg_rating,
MIN(total_votes) AS min_total_votes,
MAX(total_votes) AS max_total_votes,
MIN(median_rating) AS min_median_rating,
MAX(median_rating) AS max_median_rating
FROM ratings;
/* So, the minimum and maximum values in each column of the ratings table are in the expected range.
This implies there are no outliers in the table.
Now, let’s find out the top 10 movies based on average rating.*/
-- Q11. Which are the top 10 movies based on average rating?
/* Output format:
+---------------+-------------------+---------------------+
| title | avg_rating | movie_rank |
+---------------+-------------------+---------------------+
| Fan | 9.6 | 5 |
| . | . | . |
| . | . | . |
| . | . | . |
+---------------+-------------------+---------------------+*/
-- Type your code below:
-- It's ok if RANK() or DENSE_RANK() is used too
WITH rating_rank AS
(
SELECT m.title,
r.avg_rating,
DENSE_RANK() OVER(ORDER BY r.avg_rating DESC) as movie_rank
FROM movie AS m
INNER JOIN ratings AS r
ON m.id = r.movie_id
)
SELECT *
FROM rating_rank
WHERE movie_rank <=10;
/* Do you find you favourite movie FAN in the top 10 movies with an average rating of 9.6? If not, please check your code again!!
So, now that you know the top 10 movies, do you think character actors and filler actors can be from these movies?
Summarising the ratings table based on the movie counts by median rating can give an excellent insight.*/
-- Q12. Summarise the ratings table based on the movie counts by median ratings.
/* Output format:
+---------------+-------------------+
| median_rating | movie_count |
+-------------------+----------------
| 1 | 105 |
| . | . |
| . | . |
+---------------+-------------------+ */
-- Type your code below:
-- Order by is good to have
SELECT median_rating,
COUNT(DISTINCT movie_id) AS movie_count
FROM ratings
GROUP BY median_rating
ORDER BY movie_count DESC;
-- Movies with median_rating 7 is the highest in number.
/* Movies with a median rating of 7 is highest in number.
Now, let's find out the production house with which RSVP Movies can partner for its next project.*/
-- Q13. Which production house has produced the most number of hit movies (average rating > 8)??
/* Output format:
+------------------+-------------------+---------------------+
|production_company|movie_count | prod_company_rank|
+------------------+-------------------+---------------------+
| The Archers | 1 | 1 |
+------------------+-------------------+---------------------+*/
-- Type your code below:
WITH prod_rank_summary AS
(
SELECT m.production_company,
COUNT(DISTINCT m.id) AS movie_count,
DENSE_RANK() OVER(ORDER BY COUNT(DISTINCT m.id) DESC) AS prod_company_rank
FROM movie AS m
INNER JOIN ratings AS r
ON m.id = r.movie_id
WHERE (m.production_company IS NOT NULL) AND (r.avg_rating > 8)
GROUP BY m.production_company
)
SELECT *
FROM prod_rank_summary
WHERE prod_company_rank = 1;
-- Dream Warrior Pictures and National Theatre Live are the production companies that have produced the most number of hits
-- It's ok if RANK() or DENSE_RANK() is used too
-- Answer can be Dream Warrior Pictures or National Theatre Live or both
-- Q14. How many movies released in each genre during March 2017 in the USA had more than 1,000 votes?
/* Output format:
+---------------+-------------------+
| genre | movie_count |
+-------------------+----------------
| thriller | 105 |
| . | . |
| . | . |
+---------------+-------------------+ */
-- Type your code below:
SELECT g.genre,
COUNT(DISTINCT m.id) AS movie_count
FROM genre AS g
INNER JOIN movie AS m
ON g.movie_id = m.id
LEFT JOIN ratings AS r
ON m.id = r.movie_id
WHERE ((MONTH(m.date_published) = 3) AND (m.year = 2017) AND (m.country LIKE "%USA%") AND (r.total_votes > 1000))
GROUP BY g.genre
ORDER BY movie_count DESC;
-- Lets try to analyse with a unique problem statement.
-- Q15. Find movies of each genre that start with the word ‘The’ and which have an average rating > 8?
/* Output format:
+---------------+-------------------+---------------------+
| title | avg_rating | genre |
+---------------+-------------------+---------------------+
| Theeran | 8.3 | Thriller |
| . | . | . |
| . | . | . |
| . | . | . |
+---------------+-------------------+---------------------+*/
-- Type your code below:
SELECT m.title,
r.avg_rating,
g.genre
FROM movie AS m
INNER JOIN genre AS g
ON m.id = g.movie_id
INNER JOIN ratings AS r
ON g.movie_id = r.movie_id
WHERE ((m.title LIKE "The%") AND (r.avg_rating > 8))
ORDER BY r.avg_rating DESC;
-- The movies having the highest average rating belongs to the "Drama" genre
-- Checking for median rating
SELECT m.title,
r.median_rating,
g.genre
FROM movie AS m
INNER JOIN genre AS g
ON m.id = g.movie_id
INNER JOIN ratings AS r
ON g.movie_id = r.movie_id
WHERE ((m.title LIKE "The%") AND (r.median_rating > 8))
ORDER BY r.median_rating DESC;
-- The result of using median rating is same as the one done with average rating
-- You should also try your hand at median rating and check whether the ‘median rating’ column gives any significant insights.
-- Q16. Of the movies released between 1 April 2018 and 1 April 2019, how many were given a median rating of 8?
-- Type your code below:
SELECT COUNT(r.movie_id) AS movie_count
FROM movie AS m
LEFT JOIN ratings AS r
ON m.id = r.movie_id
WHERE ((m.date_published BETWEEN '2018-04-01' AND '2019-04-01') AND (r.median_rating = 8));
-- 361 movies have a median rating 8 between the mentioned dates.
-- Once again, try to solve the problem given below.
-- Q17. Do German movies get more votes than Italian movies?
-- Hint: Here you have to find the total number of votes for both German and Italian movies.
-- Type your code below:
SELECT SUM(r.total_votes) AS german_votes
FROM movie AS m
INNER JOIN ratings AS r
ON m.id = r.movie_id
WHERE m.languages LIKE "%German%";
-- The total number of votes for the German movies is 4421525.
SELECT SUM(r.total_votes) AS italian_votes
FROM movie AS m
INNER JOIN ratings AS r
ON m.id = r.movie_id
WHERE m.languages LIKE "%Italian%";
-- The total number of votes for the Italian movies is 2559540.
-- So German movies get greater votes than Italian movies.
-- Answer is Yes
/* Now that you have analysed the movies, genres and ratings tables, let us now analyse another table, the names table.
Let’s begin by searching for null values in the tables.*/
-- Segment 3:
-- Q18. Which columns in the names table have null values??
/*Hint: You can find null values for individual columns or follow below output format
+---------------+-------------------+---------------------+----------------------+
| name_nulls | height_nulls |date_of_birth_nulls |known_for_movies_nulls|
+---------------+-------------------+---------------------+----------------------+
| 0 | 123 | 1234 | 12345 |
+---------------+-------------------+---------------------+----------------------+*/
-- Type your code below:
SELECT SUM(CASE WHEN name IS NULL THEN 1 ELSE 0 END) AS name_nulls,
SUM(CASE WHEN height IS NULL THEN 1 ELSE 0 END) AS height_nulls,
SUM(CASE WHEN date_of_birth IS NULL THEN 1 ELSE 0 END) AS date_of_birth_nulls,
SUM(CASE WHEN known_for_movies IS NULL THEN 1 ELSE 0 END) AS known_for_movies_nulls
FROM names;
-- The "name" column doen't contain any null values.
/* There are no Null value in the column 'name'.
The director is the most important person in a movie crew.
Let’s find out the top three directors in the top three genres who can be hired by RSVP Movies.*/
-- Q19. Who are the top three directors in the top three genres whose movies have an average rating > 8?
-- (Hint: The top three genres would have the most number of movies with an average rating > 8.)
/* Output format:
+---------------+-------------------+
| director_name | movie_count |
+---------------+-------------------|
|<NAME> | 4 |
| . | . |
| . | . |
+---------------+-------------------+ */
-- Type your code below:
-- Getting the top three genres having most number of movies with an average rating > 8
SELECT g.genre,
COUNT(DISTINCT g.movie_id) AS movie_count,
r.avg_rating
FROM genre AS g
INNER JOIN ratings AS r
ON g.movie_id = r.movie_id
WHERE r.avg_rating > 8
GROUP BY g.genre
ORDER BY movie_count DESC
LIMIT 3;
-- The top three genres are Drama, Action and Comedy
-- Getting the top three directors from the top three genres
(SELECT n.name AS director_name,
COUNT(DISTINCT r.movie_id) AS movie_count
FROM names AS n
INNER JOIN director_mapping AS dm
ON n.id = dm.name_id
INNER JOIN ratings AS r
ON dm.movie_id = r.movie_id
INNER JOIN genre AS g
ON r.movie_id = g.movie_id
WHERE g.genre = 'Drama' AND r.avg_rating >8
GROUP BY director_name
ORDER BY movie_count DESC
LIMIT 1)
UNION
(SELECT n.name AS director_name,
COUNT(DISTINCT r.movie_id) AS movie_count
FROM names AS n
INNER JOIN director_mapping AS dm
ON n.id = dm.name_id
INNER JOIN ratings AS r
ON dm.movie_id = r.movie_id
INNER JOIN genre AS g
ON r.movie_id = g.movie_id
WHERE g.genre = 'Action' AND r.avg_rating >8
GROUP BY director_name
ORDER BY movie_count DESC
LIMIT 1)
UNION
(SELECT n.name AS director_name,
COUNT(DISTINCT r.movie_id) AS movie_count
FROM names AS n
INNER JOIN director_mapping AS dm
ON n.id = dm.name_id
INNER JOIN ratings AS r
ON dm.movie_id = r.movie_id
INNER JOIN genre AS g
ON r.movie_id = g.movie_id
WHERE g.genre = 'Comedy' AND r.avg_rating >8
GROUP BY director_name
ORDER BY movie_count DESC
LIMIT 1);
-- <NAME>, <NAME> and <NAME> are the top 3 directors
/* <NAME> can be hired as the director for RSVP's next project. Do you remeber his movies, 'Logan' and 'The Wolverine'.
Now, let’s find out the top two actors.*/
-- Q20. Who are the top two actors whose movies have a median rating >= 8?
/* Output format:
+---------------+-------------------+
| actor_name | movie_count |
+-------------------+----------------
|<NAME> | 10 |
| . | . |
+---------------+-------------------+ */
-- Type your code below:
SELECT n.name AS actor_name,
COUNT(r.movie_id) AS movie_count
FROM names AS n
INNER JOIN role_mapping AS rm
ON n.id = rm.name_id
INNER JOIN ratings As r
ON rm.movie_id = r.movie_id
WHERE r.median_rating >=8
GROUP BY actor_name
ORDER BY movie_count DESC
LIMIT 2;
-- The top two actors are Mammootty and Mohanlal.
/* Have you find your favourite actor 'Mohanlal' in the list. If no, please check your code again.
RSVP Movies plans to partner with other global production houses.
Let’s find out the top three production houses in the world.*/
-- Q21. Which are the top three production houses based on the number of votes received by their movies?
/* Output format:
+------------------+--------------------+---------------------+
|production_company|vote_count | prod_comp_rank|
+------------------+--------------------+---------------------+
| The Archers | 830 | 1 |
| . | . | . |
| . | . | . |
+-------------------+-------------------+---------------------+*/
-- Type your code below:
WITH prod_comp_summary AS
(
SELECT m.production_company,
SUM(r.total_votes) AS vote_count,
DENSE_RANK() OVER(ORDER BY SUM(r.total_votes) DESC) AS prod_comp_rank
FROM movie AS m
INNER JOIN ratings AS r
ON m.id = r.movie_id
GROUP BY m.production_company
)
SELECT *
FROM prod_comp_summary
WHERE prod_comp_rank <=3;
-- Marvel Studios, Twentieth Century Fox and Warner Bros. are the top three production company
/*Yes Marvel Studios rules the movie world.
So, these are the top three production houses based on the number of votes received by the movies they have produced.
Since RSVP Movies is based out of Mumbai, India also wants to woo its local audience.
RSVP Movies also wants to hire a few Indian actors for its upcoming project to give a regional feel.
Let’s find who these actors could be.*/
-- Q22. Rank actors with movies released in India based on their average ratings. Which actor is at the top of the list?
-- Note: The actor should have acted in at least five Indian movies.
-- (Hint: You should use the weighted average based on votes. If the ratings clash, then the total number of votes should act as the tie breaker.)
/* Output format:
+---------------+-------------------+---------------------+----------------------+-----------------+
| actor_name | total_votes | movie_count | actor_avg_rating |actor_rank |
+---------------+-------------------+---------------------+----------------------+-----------------+
| <NAME> | 3455 | 11 | 8.42 | 1 |
| . | . | . | . | . |
| . | . | . | . | . |
| . | . | . | . | . |
+---------------+-------------------+---------------------+----------------------+-----------------+*/
-- Type your code below:
SELECT n.name AS actor_name,
SUM(r.total_votes) AS total_votes,
COUNT(r.movie_id) AS movie_count,
(SUM(r.total_votes*r.avg_rating)/SUM(r.total_votes)) AS actor_avg_rating,
DENSE_RANK() OVER(ORDER BY (SUM(r.total_votes*r.avg_rating)/SUM(r.total_votes)) DESC, r.total_votes DESC) AS actor_rank
FROM names AS n
INNER JOIN role_mapping AS rm
ON n.id = rm.name_id
INNER JOIN movie AS m
ON rm.movie_id = m.id
INNER JOIN ratings As r
ON m.id = r.movie_id
WHERE (rm.category = 'actor') AND (m.country LIKE "%India%")
GROUP BY actor_name
HAVING movie_count >= 5;
-- <NAME> is the top actor
-- Top actor is <NAME>
-- Q23.Find out the top five actresses in Hindi movies released in India based on their average ratings?
-- Note: The actresses should have acted in at least three Indian movies.
-- (Hint: You should use the weighted average based on votes. If the ratings clash, then the total number of votes should act as the tie breaker.)
/* Output format:
+---------------+-------------------+---------------------+----------------------+-----------------+
| actress_name | total_votes | movie_count | actress_avg_rating |actress_rank |
+---------------+-------------------+---------------------+----------------------+-----------------+
| Tabu | 3455 | 11 | 8.42 | 1 |
| . | . | . | . | . |
| . | . | . | . | . |
| . | . | . | . | . |
+---------------+-------------------+---------------------+----------------------+-----------------+*/
-- Type your code below:
SELECT n.name AS actress_name,
SUM(r.total_votes) AS total_votes,
COUNT(r.movie_id) AS movie_count,
ROUND(SUM(r.total_votes*r.avg_rating)/SUM(r.total_votes),2) AS actress_avg_rating,
DENSE_RANK() OVER(ORDER BY (SUM(r.total_votes*r.avg_rating)/SUM(r.total_votes)) DESC, r.total_votes DESC) AS actress_rank
FROM names AS n
INNER JOIN role_mapping AS rm
ON n.id = rm.name_id
INNER JOIN movie AS m
ON rm.movie_id = m.id
INNER JOIN ratings As r
ON m.id = r.movie_id
WHERE (rm.category = 'actress') AND (m.country LIKE "%India%") AND (m.languages LIKE "Hindi")
GROUP BY actress_name
HAVING movie_count >= 3
LIMIT 5;
-- The top 4 actresses are <NAME>u, <NAME>, <NAME> and <NAME>.
/* Taapsee Pannu tops with average rating 7.74.
Now let us divide all the thriller movies in the following categories and find out their numbers.*/
/* Q24. Select thriller movies as per avg rating and classify them in the following category:
Rating > 8: Superhit movies
Rating between 7 and 8: Hit movies
Rating between 5 and 7: One-time-watch movies
Rating < 5: Flop movies
--------------------------------------------------------------------------------------------*/
-- Type your code below:
-- Creating an UDF for the classification
DELIMITER $$
CREATE FUNCTION movie_category(avg_rating float)
RETURNS VARCHAR(30) DETERMINISTIC
BEGIN
DECLARE class VARCHAR(30);
IF avg_rating > 8 THEN
SET class = 'Superhit Movie';
ELSEIF avg_rating BETWEEN 7 AND 8 THEN
SET class = 'Hit Movie';
ELSEIF avg_rating BETWEEN 5 AND 7 THEN
SET class = 'One-time-watch Movie';
ELSE
SET class = 'Flop Movie';
END IF;
RETURN class;
END;
$$
DELIMITER ;
SELECT m.title,
r.avg_rating,
movie_category(r.avg_rating) AS movie_category
FROM genre AS g
INNER JOIN movie AS m
ON g.movie_id = m.id
INNER JOIN ratings AS r
ON m.id = r.movie_id
WHERE g.genre = "Thriller";
/* Until now, you have analysed various tables of the data set.
Now, you will perform some tasks that will give you a broader understanding of the data in this segment.*/
-- Segment 4:
-- Q25. What is the genre-wise running total and moving average of the average movie duration?
-- (Note: You need to show the output table in the question.)
/* Output format:
+---------------+-------------------+---------------------+----------------------+
| genre | avg_duration |running_total_duration|moving_avg_duration |
+---------------+-------------------+---------------------+----------------------+
| comdy | 145 | 106.2 | 128.42 |
| . | . | . | . |
| . | . | . | . |
| . | . | . | . |
+---------------+-------------------+---------------------+----------------------+*/
-- Type your code below:
WITH genre_duration_summary AS
(
SELECT g.genre AS genre,
AVG(m.duration) AS avg_duration
FROM genre AS g
INNER JOIN movie AS m
ON g.movie_id = m.id
GROUP BY g.genre
)
SELECT genre,
avg_duration,
ROUND(SUM(avg_duration) OVER(ORDER BY genre),2) AS running_total_duration,
ROUND(AVG(avg_duration) OVER(ORDER BY genre),2) AS moving_avg_duration
FROM genre_duration_summary;
-- Round is good to have and not a must have; Same thing applies to sorting
-- Let us find top 5 movies of each year with top 3 genres.
-- Q26. Which are the five highest-grossing movies of each year that belong to the top three genres?
-- (Note: The top 3 genres would have the most number of movies.)
/* Output format:
+---------------+-------------------+---------------------+----------------------+-----------------+
| genre | year | movie_name |worldwide_gross_income|movie_rank |
+---------------+-------------------+---------------------+----------------------+-----------------+
| comedy | 2017 | indian | $103244842 | 1 |
| . | . | . | . | . |
| . | . | . | . | . |
| . | . | . | . | . |
+---------------+-------------------+---------------------+----------------------+-----------------+*/
-- Type your code below:
SELECT * FROM(
WITH top_genre AS(
SELECT g.genre,
COUNT(g.movie_id) AS movie_cnt
FROM genre AS g
INNER JOIN movie AS m
ON g.movie_id = m.id
GROUP BY g.genre
ORDER By movie_cnt DESC
LIMIT 3
)
SELECT g.genre,
m.year,
m.title AS movie_name,
m.worlwide_gross_income AS worldwide_gross_income,
ROW_NUMBER() OVER(PARTITION BY m.year ORDER BY m.worlwide_gross_income DESC) AS movie_rank
FROM genre AS g
INNER JOIN movie AS m
ON g.movie_id = m.id
WHERE (m.worlwide_gross_income IS NOT NULL) AND (g.genre IN (SELECT genre FROM top_genre)) AND (m.worlwide_gross_income LIKE "$%")
)s
WHERE s.movie_rank <=5;
-- Finally, let’s find out the names of the top two production houses that have produced the highest number of hits among multilingual movies.
-- Q27. Which are the top two production houses that have produced the highest number of hits (median rating >= 8) among multilingual movies?
/* Output format:
+-------------------+-------------------+---------------------+
|production_company |movie_count | prod_comp_rank|
+-------------------+-------------------+---------------------+
| The Archers | 830 | 1 |
| . | . | . |
| . | . | . |
+-------------------+-------------------+---------------------+*/
-- Type your code below:
SELECT m.production_company,
COUNT(DISTINCT m.id) AS movie_count,
DENSE_RANK() OVER(ORDER BY COUNT(DISTINCT m.id) DESC) AS prod_comp_rank
FROM movie AS m
INNER JOIN ratings AS r
ON m.id = r.movie_id
WHERE (r.median_rating >= 8) AND (POSITION(',' IN m.languages)>0) AND (m.production_company IS NOT NULL)
GROUP BY m.production_company
LIMIT 2;
-- The top two production companies with highest number of hits are Star Cinema and Twentieth Century Fox
-- Multilingual is the important piece in the above question. It was created using POSITION(',' IN languages)>0 logic
-- If there is a comma, that means the movie is of more than one language
-- Q28. Who are the top 3 actresses based on number of Super Hit movies (average rating >8) in drama genre?
/* Output format:
+---------------+-------------------+---------------------+----------------------+-----------------+
| actress_name | total_votes | movie_count |actress_avg_rating |actress_rank |
+---------------+-------------------+---------------------+----------------------+-----------------+
| <NAME> | 1016 | 1 | 9.60 | 1 |
| . | . | . | . | . |
| . | . | . | . | . |
+---------------+-------------------+---------------------+----------------------+-----------------+*/
-- Type your code below:
SELECT n.name AS actress_name,
SUM(r.total_votes) AS total_votes,
COUNT(r.movie_id) AS movie_count,
ROUND(AVG(avg_rating),2) AS actress_avg_rating,
DENSE_RANK() OVER(ORDER BY COUNT(r.movie_id) DESC) AS actress_rank
FROM names AS n
INNER JOIN role_mapping AS rm
ON n.id = rm.name_id
INNER JOIN genre AS g
ON rm.movie_id = g.movie_id
INNER JOIN ratings As r
ON g.movie_id = r.movie_id
WHERE (rm.category = 'actress') AND (r.avg_rating > 8) AND (g.genre = 'Drama')
GROUP BY actress_name
LIMIT 3;
-- The top three actress with the highest number of superhit movies are : <NAME>, <NAME> and <NAME>
/* Q29. Get the following details for top 9 directors (based on number of movies)
Director id
Name
Number of movies
Average inter movie duration in days
Average movie ratings
Total votes
Min rating
Max rating
total movie durations
Format:
+---------------+-------------------+---------------------+----------------------+--------------+--------------+------------+------------+----------------+
| director_id | director_name | number_of_movies | avg_inter_movie_days | avg_rating | total_votes | min_rating | max_rating | total_duration |
+---------------+-------------------+---------------------+----------------------+--------------+--------------+------------+------------+----------------+
|nm1777967 | <NAME> | 5 | 177 | 5.65 | 1754 | 3.7 | 6.9 | 613 |
| . | . | . | . | . | . | . | . | . |
| . | . | . | . | . | . | . | . | . |
| . | . | . | . | . | . | . | . | . |
| . | . | . | . | . | . | . | . | . |
| . | . | . | . | . | . | . | . | . |
| . | . | . | . | . | . | . | . | . |
| . | . | . | . | . | . | . | . | . |
| . | . | . | . | . | . | . | . | . |
+---------------+-------------------+---------------------+----------------------+--------------+--------------+------------+------------+----------------+
--------------------------------------------------------------------------------------------*/
-- Type you code below:
WITH inter_movie_days AS
(
SELECT n.id AS director_id,
n.name AS director_name,
m.id,
m.title,
m.date_published,
LEAD(date_published,1,'2020-01-01') OVER(PARTITION BY n.name ORDER BY n.name,date_published) AS next_publish_date,
r.avg_rating,
r.total_votes,
m.duration
FROM names AS n
INNER JOIN director_mapping AS dm
ON n.id = dm.name_id
INNER JOIN movie AS m
ON dm.movie_id = m.id
INNER JOIN ratings As r
ON m.id = r.movie_id
)
SELECT director_id,
director_name,
COUNT(id) AS number_of_movies,
ROUND(AVG(DATEDIFF(next_publish_date, date_published)),2) as avg_inter_movie_days,
ROUND(AVG(avg_rating),2) AS avg_rating,
SUM(total_votes) AS total_votes,
MIN(avg_rating) AS min_rating,
MAX(avg_rating) AS max_rating,
SUM(duration) AS total_duration
FROM inter_movie_days
GROUP BY director_name
ORDER BY number_of_movies DESC
LIMIT 9;
/* From the above it can be seen that most of the top 9 directors have movies with an average rating of around or more,
total votes of more than thousands, with minimum rating not less than 2.5 and maximum rating above 5, duration of each
movie not extending the duration more than 2.5 hours. Also the average diff between the movie dates is approximately
above 150 for all the successful top directors.
<file_sep>/AirBnB CaseStudy/README.md
**AirBnB CaseStudy**
**Problem Statement**
**Problem background**
Suppose that you are working as a data analyst at Airbnb. For the past few months, Airbnb has seen a major decline in revenue. Now that the restrictions have started lifting and people have started to travel more, Airbnb wants to make sure that it is fully prepared for this change.
The different leaders at Airbnb want to understand some important insights based on various attributes in the dataset so as to increase the revenue such as -
Which type of hosts to acquire more and where?
The categorisation of customers based on their preferences.
What are the neighbourhoods they need to target?
What is the pricing ranges preferred by customers?
The various kinds of properties that exist w.r.t. customer preferences.
Adjustments in the existing properties to make it more customer-oriented.
What are the most popular localities and properties in New York currently?
How to get unpopular properties more traction? and so on...
Note: These points are just to give you an initial understanding of how to proceed with the analysis and the kind of questions you need to ask. In addition to this, you would need to further understand the data (attached below in this page) and analyse important insights that you feel are required for the audiences mentioned for each of the two presentations.
**End Objective**
To prepare for the next best steps that Airbnb needs to take as a business, you have been asked to analyse a dataset consisting of various Airbnb listings in New York. Based on this analysis, you need to give two presentations to the following groups.
**Presentation - I**
Data Analysis Managers: These people manage the data analysts directly for processes and their technical expertise is basic.
Lead Data Analyst: The lead data analyst looks after the entire team of data and business analysts and is technically sound.
**Presentation - II**
Head of Acquisitions and Operations, NYC: This head looks after all the property and host acquisitions and operations. Acquisition of the best properties, price negotiation, and negotiating the services the properties offer falls under the purview of this role.
Head of User Experience, NYC: The head of user experience looks after the customer preferences and also handles the properties listed on the website and the Airbnb app. Basically, the head of user experience tries to optimise the order of property listing in certain neighbourhoods and cities in order to get every property the optimal amount of traction.
<file_sep>/Credit Card Fraud Detection/README.md
**Credit Card Fraud Detection**
In the banking industry, detecting credit card fraud using machine learning is not just a trend; it is a necessity for the banks, as they need to put proactive monitoring and fraud prevention mechanisms in place. Machine learning helps these institutions reduce time-consuming manual reviews, costly chargebacks and fees, and denial of legitimate transactions.
Suppose you are part of the analytics team working on a fraud detection model and its cost-benefit analysis. You need to develop a machine learning model to detect fraudulent transactions based on the historical transactional data of customers with a pool of merchants. You can learn more about transactional data and the creation of historical variables from the link attached here. You may find this helpful in the capstone project while building the fraud detection model. Based on your understanding of the model, you have to analyse the business impact of these fraudulent transactions and recommend the optimal ways that the bank can adopt to mitigate the fraud risks.
**Understanding and Defining Fraud**
Credit card fraud is any dishonest act or behaviour to obtain information without the proper authorisation of the account holder for financial gain. Among the different ways of committing fraud, skimming is the most common one. Skimming is a method used for duplicating information located on the magnetic stripe of the card. Apart from this, other ways of making fraudulent transactions are as follows:
Manipulation or alteration of genuine cards
Creation of counterfeit cards
Stolen or lost credit cards
Fraudulent telemarketing
**Data Understanding:**
This is a simulated data set taken from the Kaggle website and contains both legitimate and fraudulent transactions. You can download the data set using this link. https://www.kaggle.com/kartik2112/fraud-detection
The data set contains credit card transactions of around 1,000 cardholders with a pool of 800 merchants from 1 Jan 2019 to 31 Dec 2020. It contains a total of 18,52,394 transactions, out of which 9,651 are fraudulent transactions. The data set is highly imbalanced, with the positive class (frauds) accounting for 0.52% of the total transactions. Now, since the data set is highly imbalanced, it needs to be handled before model building. The feature 'amt' represents the transaction amount. The feature 'is_fraud' represents class labelling and takes the value 1 the transaction is a fraudulent transaction and 0, otherwise.
**Project Pipeline:**
The project pipeline can be briefly summarised in the following steps:
**Understanding Data:** In this step, you need to load the data and understand the features present in it. This will help you choose the features that you need for your final model.
**Exploratory data analytics (EDA):** Normally, in this step, you need to perform univariate and bivariate analyses of the data, followed by feature transformations, if necessary. You can also check whether or not there is any skewness in the data and try to mitigate it, as skewed data can cause problems during the model-building phase.
**Train/Test Data Splitting:** In this step, you need to split the data set into training data and testing data in order to check the performance of your models with unseen data. You can use the stratified k-fold cross-validation method at this stage. For this, you need to choose an appropriate k value such that the minority class is correctly represented in the test folds.
**Model Building or Hyperparameter Tuning:** This is the final step, at which you can try different models and fine-tune their hyperparameters until you get the desired level of performance out of the model on the given data set. Ensure that you start with a baseline linear model before going towards ensembles. You should check if you can get a better performance out of the model by using various sampling techniques.
**Model Evaluation:** Evaluate the performance of the models using appropriate evaluation metrics. Note that since the data is imbalanced, it is important to identify which transactions are fraudulent transactions more accurately than identifying non-fraudulent transactions. Choose an appropriate evaluation metric that reflects this business goal.
**Business Impact:**
After the model has been built and evaluated with the appropriate metrics, you need to demonstrate its potential benefits by performing a cost-benefit analysis which can then be presented to the relevant business stakeholders.
To perform this analysis, you need to compare the costs incurred before and after the model is deployed. Earlier, the bank paid the entire transaction amount to the customer for every fraudulent transaction which accounted for a heavy loss to the bank.
Now after the model has been deployed, the bank plans to provide a second layer of authentication for each of the transactions that the model predicts as fraudulent. If a payment gets flagged by the model, an SMS will be sent to the customer requesting them to call on a toll-free number to confirm the authenticity of the transaction. A customer experience executive will also be made available to respond to any queries if necessary. Developing this service would cost the bank $1.5 per fraudulent transaction.
For the fraudulent transactions that are still not identified by the model, the bank will need to pay the customer the entire transaction amount as it was doing earlier.
Thus, the cost incurred now is due to the left out fraudulent transactions that the model fails to detect and the installation cost of the second level authentication service. Hence, the total savings for the bank would be the difference of costs incurred after and before the model deployment.
|
6969f1e1a72c30676f31f03380f950c0ffc8d1dc
|
[
"Markdown",
"SQL"
] | 4 |
Markdown
|
prasasti8015/PGDDS_IIITBangalore
|
307b19efd43ccaf76a9dee94b35165da2862f542
|
fd57f63e1eaa46beae8d5c99926379de60d0c51c
|
refs/heads/master
|
<file_sep>//
// ViewController.swift
// PullsEye
//
// Created by <NAME> on 4/8/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var currentValue = 0
var randomVal = 0
var score = 0
var roundNumber = 0
@IBOutlet var slider : UISlider!
@IBOutlet var randLabel : UILabel!
@IBOutlet var scoreLabel : UILabel!
@IBOutlet var roundNumberLabel : UILabel!
override func viewDidLoad() {
super.viewDidLoad()
StartNewRound();
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func hitMeClicked(){
var msgTitle = ""
var currentScore = 0
if currentValue == randomVal{
currentScore = 100
msgTitle = "perfect!"
}
else if abs(currentValue - randomVal) < 5{
currentScore = 50
msgTitle = "You almost had it!"
}
else if abs(currentValue - randomVal) < 10{
msgTitle = "Pretty good!"
}
else{
msgTitle = "Not even close..."
}
score += currentScore
scoreLabel.text = String(score)
let msg = "You scored \(currentScore) points\n your value is \(currentValue) \n your target is \(randomVal)"
ShowAlert(title : msgTitle,msg : msg,actionName : "OK")
GenerateRandom()
}
@IBAction func sliderMoved(_ slider: UISlider){
print("Slider value is \(slider.value)")
currentValue = lroundf(slider.value)
}
@IBAction func startRound() {
StartNewRound()
}
func ShowAlert(title : String, msg : String, actionName : String){
let alert = UIAlertController(title : title , message : msg, preferredStyle : .alert)
let action = UIAlertAction(title: actionName, style: .default,handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
func StartNewRound() {
roundNumber += 1
slider.value = 50
score = 0
currentValue = lroundf(slider.value)
GenerateRandom()
roundNumberLabel.text = String(roundNumber)
scoreLabel.text = String(score)
}
func GenerateRandom() {
randomVal = 1 + Int(arc4random_uniform(100))
randLabel.text = String(randomVal)
}
}
|
a2c8d5924858e61cd29eae7a4f125e84a87b7ee1
|
[
"Swift"
] | 1 |
Swift
|
yassminTaha/PullsEye
|
b027328e3d772a2a5f282ccbf490411a45bc0d49
|
ae0f7be12c6c8184034c5dfda568562c0200663d
|
refs/heads/master
|
<repo_name>karlkumbier/stat133-summer2014<file_sep>/pelicanconf.py
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'<NAME>'
SITENAME = u"UC Berkeley's Statistics 133 (summer 2014)"
SITEURL = ''
TIMEZONE = 'US/Pacific'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
THEME = '_theme/'
## Title menu options (this isn't necessary, but I wanted to have more control)
DISPLAY_CATEGORIES_ON_MENU = False
DISPLAY_PAGES_ON_MENU = True
DISPLAY_TAGS_ON_SIDEBAR = False
# Blogroll
LINKS = (('Command line', 'http://www.jarrodmillman.com/commandline'),
('Python', 'http://docs.python.org/2/'),
('NumPy & SciPy', 'http://docs.scipy.org/'),
('matplotlib', 'http://matplotlib.org/'),
('Software Carpentry', 'http://software-carpentry.org'),)
PLUGIN_PATH = '_plugins/'
PLUGINS = ['latex']
CC_LICENSE = "CC-BY-NC-SA"
<file_sep>/content/pages/about.md
Title: About
Slug: about
* Instructor
* [<NAME>](http://jarrodmillman.com)
* OH: TBD
* GSI
* <NAME>
* OH: TBD
* Session Dates: 06/09-08/15/14
* Class meets MTWTF 9-10A in [155 DONNER LAB](https://maps.google.com/maps?q=155-donner+lab+berkeley+ca&hl=en&ll=37.8757,-122.25631&spn=0.01045,0.021136&sll=37.870775,-122.30098&sspn=0.083609,0.169086&t=h&hnear=Donner+Lab,+Berkeley,+California+94709&z=16)
* Lab meets TuTh 10-11A or 12-1P in [340 EVANS](https://maps.google.com/maps?q=340+evans+statistics+berkeley+ca&hl=en&sll=37.8757,-122.25631&sspn=0.01045,0.021136&t=h&hq=340+evans+statistics+berkeley+ca&z=16)
* CNN: [79690](http://osoc.berkeley.edu/OSOC/osoc?p_ccn=79690&p_term=SU)
## Course Description
An introduction to computationally intensive applied statistics. Topics may
include organization and use of databases, visualization and graphics,
statistical learning and data mining, model validation procedures, and the
presentation of results.
**Prerequisites**: Familiarity with basic concepts in probability and
statistics is important. Being comfortable with matrices, vectors, basic set
theory, functions, and graphs will also help. There is no prerequisite for
programming.
### Topics
The goal of this course is to introduce you to a variety of programs and
technologies that are useful for organizing, manipulating, and visualizing
data. This includes:
* Basic understanding of computers and networks
* Working at the (Bash) command line
* Implementing reproducible research
* Open source development practice
* Version control using Git and GitHub
* Understanding regular expressions
* Basics of programming (data structures, control flow, debugging, etc.)
* Scientific computing with Python including NumPy, SciPy, and matplotlib
* Simulation and random number generation
* Exploratory data analysis and dimension reduction (PCA)
* File formats including CSV, JSON, HDF5, and XML
* Process automation with Make
* Document generation using $\LaTeX$, Markdown, reStructuredText, Sphinx, and Pelican
* Clustering, classification, and linear regression
* Basic knowledge of R
## Grading
Your final grade will be a weighted average of grades in the following areas:
* 5% participation
* 40% labs and/or homework
* 15% midterm
* 20% group project - due at the end of semester
* 20% final exam
## Course Policies
**Attendance and behavior in class:** You are expected to attend all lectures
and labs. Any known or potential extracurricular conflicts should be discussed
in person with the instructor during the first two weeks of the semester, or as
soon as they arise. *Cellphones* are to be turned off during class time.
*Laptop* use during class is recommend, but it is expected that you will be
using your laptop to type along with the lecture.
**Submission of assignments:** Assignments will be accepted by electronic
submission to GitHub only. There will be no makeup midterm nor final exam. No
late labs or homework will be accepted. Grades of Incomplete will be granted
only for dire medical or personal emergencies that cause you to miss the final,
and only if your work up to that point has been satisfactory.
**Academic integrity:** Any test, paper, or report submitted by you is presumed
to be your own original work that has not previously been submitted for credit
in another course. While you are encouraged to work together on homework
assignments, the work and writeup must be your own. For example, suggesting a
function to another student is acceptable, whereas simply giving him or her
your own code is not. If you are not clear about the expectations for
completing an assignment or taking an exam, be sure to seek clarification from
the instructor or GSI beforehand. Any evidence of cheating and plagiarism will
be subject to disciplinary action. Please read the [Honor
Code](http://asuc.org/honorcode/index.php) carefully.
**Students with disabilities:** If you need accommodations for any physical,
psychological, or learning disability, please speak to me after class or during
office hours so that we can make the necessary arrangements.
|
d4781ecd2e72a61e19bc48c5380eab5aaeab3b30
|
[
"Markdown",
"Python"
] | 2 |
Python
|
karlkumbier/stat133-summer2014
|
8d4663ac0a2a5a38f33baf7943f739f64259282d
|
452f65cf38e7d2849107193befcd3430691bd658
|
refs/heads/master
|
<repo_name>mariaulfa33/_blitix<file_sep>/helpers/randomSecreten.js
const crypto = require('crypto');
function randomSecreten () {
const buf = crypto.randomBytes(5);
const secret = buf.toString('hex')
return secret
}
module.exports = randomSecreten<file_sep>/models/user.js
'use strict';
const encrypt = require('../helpers/encrypt')
const sequelize = require('sequelize')
const Op = sequelize.Op
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
userName: {type : DataTypes.STRING,
validate : {
isUnique : function (value) {
console.log(this)
return User
.findOne({where: {userName : value, id: {[Op.ne]:this.id}}})
.then(data => {
if(data != null) {
throw new Error ('sorry, Username is taker')
}
})
.catch(function(err) {
throw err
})
}
}},
email : {type : DataTypes.STRING,
validate : {
isEmail: true,
isUnique : function (value) {
return User
.findOne({where: {email : value, id: {[Op.ne]:this.id}}})
.then(data => {
if(data != null) {
throw new Error ('Email already exists!')
}
})
.catch(function(err) {
throw err
})
}
}},
password: DataTypes.STRING,
phoneNumber: DataTypes.STRING,
secret: DataTypes.STRING
}, {
hooks : {
beforeCreate : (value) => {
value.password = encrypt(value.password, value.secret)
}
}
});
User.associate = function(models) {
User.belongsToMany(models.Event, { through: models.Transaction });
User.hasMany(models.Transaction)
};
return User;
};<file_sep>/models/transaction.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const Transaction = sequelize.define('Transaction', {
EventId: DataTypes.INTEGER,
UserId: DataTypes.INTEGER
}, {});
Transaction.associate = function(models) {
Transaction.belongsTo(models.User)
Transaction.belongsTo(models.Event)
// associations can be defined here
};
Transaction.getLimitSeat = function(eventId) {
return new Promise (function(resolve, reject) {
let seat = 0;
Transaction
.findAll({
where: {EventId : eventId},
attributes: ['EventId', [sequelize.fn('COUNT', sequelize.col('Transaction.EventId')), 'ticket']],
group: ['EventId']
})
.then(trans => {
seat = Number(trans[0].dataValues.ticket);
return trans[0].getEvent()
})
.then(event => {
console.log(event)
let hasil = event.dataValues.capacity - seat
resolve(hasil)
})
.catch(err => {
reject(err)
})
})
}
return Transaction;
};<file_sep>/models/event.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const Event = sequelize.define('Event', {
Event_name: DataTypes.STRING,
capacity : { type :DataTypes.INTEGER,
allowNull : false },
eventDate : DataTypes.STRING,
PromotorId : DataTypes.INTEGER,
waitingList : DataTypes.INTEGER
}, {});
Event.associate = function(models) {
Event.belongsTo(models.Promotor)
Event.belongsToMany(models.User, { through: models.Transaction })
Event.hasMany(models.Transaction)
// associations can be defined here
};
return Event;
};<file_sep>/app.js
const express = require('express')
const app = express()
const session = require('express-session')
const port = 3000
const promotors = require('./routes/promotors.js')
const user = require('./routes/user')
const public = require('./routes/public')
app.set('view engine', 'ejs');
app.use(session({
secret: 'blitix',
}))
app.use(express.urlencoded({extended: false}))
app.use('/', public)
app.use('/user', user)
app.use('/promotors', promotors)
app.listen(port, function(){
console.log(`listen to ${port}`)
})
<file_sep>/models/promotor.js
'use strict';
const sequelize = require('sequelize');
const Op = sequelize.Op
const encrypt = require('../helpers/encrypt')
module.exports = (sequelize, DataTypes) => {
const Promotor = sequelize.define('Promotor', {
PromotorName: DataTypes.STRING,
Email: DataTypes.STRING,
Password: DataTypes.STRING,
secret: DataTypes.STRING
},{
hooks : {
beforeCreate : (value) => {
value.Password = encrypt(value.Password, value.secret)
}
}
});
Promotor.associate = function(models) {
Promotor.hasMany(models.Event)
// Promotor.belongsTo(models.Event)
};
return Promotor;
};<file_sep>/routes/public.js
const Model = require('../models')
const express = require('express')
const router = express.Router()
const randomSecret = require('../helpers/randomSecret')
const encrypt = require('../helpers/encrypt')
router.get('/event', function(req, res) {
})
router.get('/', function(req, res) {
res.render('userPage.ejs')
})
router.get('/promotors/register',function(req,res){
res.render('promotor.ejs' ,{msg : req.query})
})
router.get('/user/login', function(req, res) {
let msg = req.query.msg || null
res.render('userlogin.ejs', {msg})
})
router.post('/user/login', function(req, res) {
let msg = req.query.msg || null
console.log(req.body.username)
Model.User.findOne({where: {userName : req.body.username}})
.then(function(user) {
console.log(user)
if(user.password == encrypt(req.body.password, user.secret)) {
req.session.user = {name: user.userName, id:user.id}
res.redirect('/user/home')
}else {
res.redirect('/user/login?msg=password')
}
})
.catch(function(err) {
console.log(err)
res.redirect('/user/login?msg=username salah')
})
})
router.get('/user/signup', function(req, res) {
let msg = req.query.msg
res.render('userRegister.ejs', {msg})
})
router.post('/user/signup', function(req, res) {
let msg = ''
let newUser = {
firstName : req.body.firstname,
lastName : req.body.lastname,
userName : req.body.username,
email : req.body.email,
phoneNumber : req.body.phone,
password : <PASSWORD>,
secret : randomSecret()
}
Model.User
.create(newUser)
.then(function(user) {
msg = 'thankyou for signing up'
res.render('userlogin.ejs', {msg})
})
.catch(function(err) {
res.redirect(`/user/signup/?msg=${err}`)
})
})
module.exports = router<file_sep>/helpers/randomSecret.js
const crypto = require('crypto');
function randomSecrete () {
// let random = Math.floor(Math.random()*100 + 10)
const buf = crypto.randomBytes(5);
const secret = buf.toString('hex')
return secret
}
module.exports = randomSecrete
<file_sep>/routes/promotors.js
const express = require('express')
const router = express.Router()
const Model = require('../models')
const encrypt = require('../helpers/encrypt')
const randomSecret = require('../helpers/randomSecret')
const session = require('express-session');
router.post('/register',function(req,res){
let obj = {
PromotorName: req.body.promotor_name,
Email: req.body.email,
Password: <PASSWORD>,
secret: randomSecret()
}
console.log(obj)
Model.Promotor.create(obj)
.then(data => {
console.log('=====DATA:', data)
res.redirect('/promotors/login')
})
.catch(err => {
console.log(err)
res.send(err)
// res.redirect('/promotors/register/?err="register failed, pleased check your name and password"')
})
})
router.get('/login',function(req,res){
res.render('promotorslogin.ejs')
})
router.post('/login', function(req,res){
//res.send(req.body)
Model.Promotor.findOne({where : {Email : req.body.Email},include: [{model: Model.Event}]})
.then(function(data) {
res.render('frontpage.ejs' ,{promotors : data})
})
.catch(function(err){
res.send(err)
})
})
router.post('/dashboard/:id',function(req,res) {
let obj = {
Event_name : req.body.acara,
capacity : Number(req.body.capacity),
eventDate : req.body.eventdate,
PromotorId : Number(req.params.id),
createdAt : new Date,
updatedAt : new Date,
price : req.body.price
}
Model.Event.create(obj)
.then(events => {
return Model.Promotor.findOne({include : [{model:Model.Event}], where : {id : req.params.id}})
})
.then(data => {
res.render('mainmenu.ejs', { data})
})
.catch(err => {
res.send(err)
})
})
module.exports = router
|
9bc8590104455394918865ef92a19f12ce2fb18f
|
[
"JavaScript"
] | 9 |
JavaScript
|
mariaulfa33/_blitix
|
97f4242fb14a146881bff3edf84abc41ef17c26a
|
828516dc7e996a8ecf070fe1348a3f8dc54bcf77
|
refs/heads/master
|
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
/// <summary>
/// TabControl UI Tool
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[AddComponentMenu("UI Tools/Tab Control", 6), DisallowMultipleComponent]
public class TabControl : MonoBehaviour
{
public Transform tabsContainer, contentContainer;
public GameObject tabTemplate, containerTemplate;
public ScrollRect tabsScrollRect;
[Tooltip("The method used when Tab buttons will overflow its parent.\nNone - no affects will be applied, and Overflow will happen.\nScale - Tabs will be resized to fit in the parent.\nScroll - A invisible scrollbar will be created with a mask, so Tabs will be scrollable on overflow.")]
public TabOverflowMethod overflow = TabOverflowMethod.Scroll;
[Tooltip("Dertmines if the selected tab will force the repositioning of the tabs container so the object is completely on screen. Only applicible if overflow is set to Scroll.")]
public bool repositionOverflow = true;
public List<TabData> tabs = new List<TabData>();
[System.Serializable]
public class TabData
{
public string tabTitle;
public Transform tabContent;
public Button tabButton;
};
private static TabData _selectedTab = null;
public static TabData selectedTab
{
get { return _selectedTab; }
}
// Use this for initialization
void Start()
{
_selectedTab = null;
if(tabs.Count > 0)
{
List<TabData> tab = new List<TabData>();
tab.AddRange(tabs);
ClearTabs();
for (int i = 0; i < tab.Count; i++)
{
AddTab(tab[i].tabTitle);
}
}
if (tabs.Count > 0) { ShowTab(tabs[0]); }
}
#region Public Functions
/// <summary>
/// Add a tab to the Tab Control.
/// </summary>
public void AddTab()
{
TabData tabData = new TabData();
tabData.tabTitle = "Tab " + tabsContainer.childCount;
Button btn = Instantiate(tabTemplate).GetComponent<Button>();
btn.name = "Tab: " + tabsContainer.childCount;
Text btnChild = btn.GetComponentInChildren<Text>();
if (btnChild != null) { btnChild.text = "Tab " + tabsContainer.childCount; }
btn.gameObject.SetActive(true);
int index = tabsContainer.childCount - 1;
btn.onClick.AddListener(delegate { SwitchTabs(index); });
btn.transform.SetParent(tabsContainer);
RectTransform content = Instantiate(containerTemplate).GetComponent<RectTransform>();
content.name = "Content: " + contentContainer.childCount;
content.gameObject.SetActive(false);
content.SetParent(contentContainer);
content.transform.localScale = containerTemplate.transform.localScale;
content.anchoredPosition3D = Vector3.zero;
content.offsetMin = Vector2.zero;
content.offsetMax = Vector2.zero;
content.anchorMin = Vector2.zero;
content.anchorMax = Vector2.one;
tabData.tabButton = btn;
tabData.tabContent = content;
tabs.Add(tabData);
ApplyOverflowMethod();
}
/// <summary>
/// Add a tab to the Tab Control.
/// </summary>
/// <param name="select">Selects the tab once its added</param>
public void AddTab(bool select)
{
TabData tabData = new TabData();
tabData.tabTitle = "Tab " + tabsContainer.childCount;
Button btn = Instantiate(tabTemplate).GetComponent<Button>();
btn.name = "Tab: " + tabsContainer.childCount;
Text btnChild = btn.GetComponentInChildren<Text>();
if (btnChild != null) { btnChild.text = "Tab " + tabsContainer.childCount; }
btn.gameObject.SetActive(true);
int index = tabsContainer.childCount - 1;
btn.onClick.AddListener(delegate { SwitchTabs(index); });
btn.transform.SetParent(tabsContainer);
RectTransform content = Instantiate(containerTemplate).GetComponent<RectTransform>();
content.name = "Content: " + contentContainer.childCount;
content.gameObject.SetActive(false);
content.SetParent(contentContainer);
content.transform.localScale = containerTemplate.transform.localScale;
content.anchoredPosition3D = Vector3.zero;
content.offsetMin = Vector2.zero;
content.offsetMax = Vector2.zero;
content.anchorMin = Vector2.zero;
content.anchorMax = Vector2.one;
tabData.tabButton = btn;
tabData.tabContent = content;
tabs.Add(tabData);
ApplyOverflowMethod();
if (select) { SelectTab(tabData); }
}
/// <summary>
/// Add a tab to the Tab Control.
/// </summary>
/// <param name="name">Name to set for this tab</param>
public void AddTab(string name)
{
TabData tabData = new TabData();
tabData.tabTitle = name;
Button btn = Instantiate(tabTemplate).GetComponent<Button>();
btn.name = "Tab: " + name;
Text btnChild = btn.GetComponentInChildren<Text>();
if (btnChild != null) { btnChild.text = name; }
btn.gameObject.SetActive(true);
int index = tabsContainer.childCount - 1;
btn.onClick.AddListener(delegate { SwitchTabs(index); });
btn.transform.SetParent(tabsContainer);
RectTransform content = Instantiate(containerTemplate).GetComponent<RectTransform>();
content.name = "Content: " + name;
content.gameObject.SetActive(false);
content.SetParent(contentContainer);
content.transform.localScale = containerTemplate.transform.localScale;
content.anchoredPosition3D = Vector3.zero;
content.offsetMin = Vector2.zero;
content.offsetMax = Vector2.zero;
content.anchorMin = Vector2.zero;
content.anchorMax = Vector2.one;
tabData.tabButton = btn;
tabData.tabContent = content;
tabs.Add(tabData);
ApplyOverflowMethod();
}
/// <summary>
/// Add a tab to the Tab Control.
/// </summary>
/// <param name="name">Name to set for this tab</param>
/// <param name="size">Width to set for this tab</param>
public void AddTab(string name, float size = 150f)
{
TabData tabData = new TabData();
tabData.tabTitle = name;
Button btn = Instantiate(tabTemplate).GetComponent<Button>();
btn.name = "Tab: " + name;
Text btnChild = btn.GetComponentInChildren<Text>();
if (btnChild != null) { btnChild.text = name; }
btn.GetComponent<LayoutElement>().minWidth = (size <= 0f) ? 150f : size;
btn.gameObject.SetActive(true);
int index = tabsContainer.childCount - 1;
btn.onClick.AddListener(delegate { SwitchTabs(index); });
btn.transform.SetParent(tabsContainer);
RectTransform content = Instantiate(containerTemplate).GetComponent<RectTransform>();
content.name = "Content: " + name;
content.gameObject.SetActive(false);
content.SetParent(contentContainer);
content.transform.localScale = containerTemplate.transform.localScale;
content.anchoredPosition3D = Vector3.zero;
content.offsetMin = Vector2.zero;
content.offsetMax = Vector2.zero;
content.anchorMin = Vector2.zero;
content.anchorMax = Vector2.one;
tabData.tabButton = btn;
tabData.tabContent = content;
tabs.Add(tabData);
ApplyOverflowMethod();
}
/// <summary>
/// Add a tab to the Tab Control.
/// </summary>
/// <param name="name">Name to set for this tab</param>
/// <param name="size">Width to set for this tab</param>
/// <param name="select">Selects the tab once its added</param>
public void AddTab(string name, float size = 150f, bool select = true)
{
TabData tabData = new TabData();
tabData.tabTitle = name;
Button btn = Instantiate(tabTemplate).GetComponent<Button>();
btn.name = "Tab: " + name;
Text btnChild = btn.GetComponentInChildren<Text>();
if (btnChild != null) { btnChild.text = name; }
btn.GetComponent<LayoutElement>().minWidth = (size <= 0f) ? 150f : size;
btn.gameObject.SetActive(true);
int index = tabsContainer.childCount - 1;
btn.onClick.AddListener(delegate { SwitchTabs(index); });
btn.transform.SetParent(tabsContainer);
RectTransform content = Instantiate(containerTemplate).GetComponent<RectTransform>();
content.name = "Content: " + name;
content.gameObject.SetActive(false);
content.SetParent(contentContainer);
content.transform.localScale = containerTemplate.transform.localScale;
content.anchoredPosition3D = Vector3.zero;
content.offsetMin = Vector2.zero;
content.offsetMax = Vector2.zero;
content.anchorMin = Vector2.zero;
content.anchorMax = Vector2.one;
tabData.tabButton = btn;
tabData.tabContent = content;
tabs.Add(tabData);
ApplyOverflowMethod();
if (select) { SelectTab(tabData); }
}
/// <summary>
/// Add a tab to the Tab Control.
/// </summary>
/// <param name="name">Name to set for this tab</param>
/// <param name="select">Selects the tab once its added</param>
public void AddTab(string name, bool select = true)
{
TabData tabData = new TabData();
tabData.tabTitle = name;
Button btn = Instantiate(tabTemplate).GetComponent<Button>();
btn.name = "Tab: " + name;
Text btnChild = btn.GetComponentInChildren<Text>();
if (btnChild != null) { btnChild.text = name; }
btn.gameObject.SetActive(true);
int index = tabsContainer.childCount - 1;
btn.onClick.AddListener(delegate { SwitchTabs(index); });
btn.transform.SetParent(tabsContainer);
RectTransform content = Instantiate(containerTemplate).GetComponent<RectTransform>();
content.name = "Content: " + name;
content.gameObject.SetActive(false);
content.SetParent(contentContainer);
content.transform.localScale = containerTemplate.transform.localScale;
content.anchoredPosition3D = Vector3.zero;
content.offsetMin = Vector2.zero;
content.offsetMax = Vector2.zero;
content.anchorMin = Vector2.zero;
content.anchorMax = Vector2.one;
tabData.tabButton = btn;
tabData.tabContent = content;
tabs.Add(tabData);
ApplyOverflowMethod();
if (select) { SelectTab(tabData); }
}
/// <summary>
/// Add a tab to the Tab Control.
/// </summary>
/// <param name="atIndex">Index to insert this tab at</param>
public void AddTab(int atIndex)
{
TabData tabData = new TabData();
tabData.tabTitle = name;
Button btn = Instantiate(tabTemplate).GetComponent<Button>();
btn.name = "Tab: " + name;
Text btnChild = btn.GetComponentInChildren<Text>();
if (btnChild != null) { btnChild.text = name; }
btn.gameObject.SetActive(true);
int index = tabsContainer.childCount - 1;
btn.onClick.AddListener(delegate { SwitchTabs(index); });
btn.transform.SetParent(tabsContainer);
RectTransform content = Instantiate(containerTemplate).GetComponent<RectTransform>();
content.name = "Content: " + name;
content.gameObject.SetActive(false);
content.SetParent(contentContainer);
content.transform.localScale = containerTemplate.transform.localScale;
content.anchoredPosition3D = Vector3.zero;
content.offsetMin = Vector2.zero;
content.offsetMax = Vector2.zero;
content.anchorMin = Vector2.zero;
content.anchorMax = Vector2.one;
tabData.tabButton = btn;
tabData.tabContent = content;
tabs.Insert(atIndex, tabData);
ApplyOverflowMethod();
}
/// <summary>
/// Add a tab to the Tab Control.
/// </summary>
/// <param name="atIndex">Index to insert this tab at</param>
/// <param name="select">Selects the tab once its added</param>
public void AddTab(int atIndex, bool select)
{
TabData tabData = new TabData();
tabData.tabTitle = name;
Button btn = Instantiate(tabTemplate).GetComponent<Button>();
btn.name = "Tab: " + name;
Text btnChild = btn.GetComponentInChildren<Text>();
if (btnChild != null) { btnChild.text = name; }
btn.gameObject.SetActive(true);
int index = tabsContainer.childCount - 1;
btn.onClick.AddListener(delegate { SwitchTabs(index); });
btn.transform.SetParent(tabsContainer);
RectTransform content = Instantiate(containerTemplate).GetComponent<RectTransform>();
content.name = "Content: " + name;
content.gameObject.SetActive(false);
content.SetParent(contentContainer);
content.transform.localScale = containerTemplate.transform.localScale;
content.anchoredPosition3D = Vector3.zero;
content.offsetMin = Vector2.zero;
content.offsetMax = Vector2.zero;
content.anchorMin = Vector2.zero;
content.anchorMax = Vector2.one;
tabData.tabButton = btn;
tabData.tabContent = content;
tabs.Insert(atIndex, tabData);
ApplyOverflowMethod();
if (select) { SelectTab(tabData); }
}
/// <summary>
/// Add a tab to the Tab Control.
/// </summary>
/// <param name="name">Name to set for this tab</param>
/// <param name="size">Width to set for this tab</param>
/// <param name="atIndex">Index to insert this tab at</param>
public void AddTab(string name, float size, int atIndex)
{
TabData tabData = new TabData();
tabData.tabTitle = name;
Button btn = Instantiate(tabTemplate).GetComponent<Button>();
btn.name = "Tab: " + name;
Text btnChild = btn.GetComponentInChildren<Text>();
if (btnChild != null) { btnChild.text = name; }
btn.GetComponent<LayoutElement>().minWidth = (size <= 0f) ? 150f : size;
btn.gameObject.SetActive(true);
int index = tabsContainer.childCount - 1;
btn.onClick.AddListener(delegate { SwitchTabs(index); });
btn.transform.SetParent(tabsContainer);
RectTransform content = Instantiate(containerTemplate).GetComponent<RectTransform>();
content.name = "Content: " + name;
content.gameObject.SetActive(false);
content.SetParent(contentContainer);
content.transform.localScale = containerTemplate.transform.localScale;
content.anchoredPosition3D = Vector3.zero;
content.offsetMin = Vector2.zero;
content.offsetMax = Vector2.zero;
content.anchorMin = Vector2.zero;
content.anchorMax = Vector2.one;
tabData.tabButton = btn;
tabData.tabContent = content;
tabs.Insert(atIndex, tabData);
ApplyOverflowMethod();
}
/// <summary>
/// Add a tab to the Tab Control.
/// </summary>
/// <param name="name">Name to set for this tab</param>
/// <param name="size">Width to set for this tab</param>
/// <param name="atIndex">Index to insert this tab at</param>
/// <param name="select">Selects the tab once its added</param>
public void AddTab(string name, float size, int atIndex, bool select)
{
TabData tabData = new TabData();
tabData.tabTitle = name;
Button btn = Instantiate(tabTemplate).GetComponent<Button>();
btn.name = "Tab: " + name;
Text btnChild = btn.GetComponentInChildren<Text>();
if (btnChild != null) { btnChild.text = name; }
btn.GetComponent<LayoutElement>().minWidth = (size <= 0f) ? 150f : size;
btn.gameObject.SetActive(true);
int index = tabsContainer.childCount - 1;
btn.onClick.AddListener(delegate { SwitchTabs(index); });
btn.transform.SetParent(tabsContainer);
RectTransform content = Instantiate(containerTemplate).GetComponent<RectTransform>();
content.name = "Content: " + name;
content.gameObject.SetActive(false);
content.SetParent(contentContainer);
content.transform.localScale = containerTemplate.transform.localScale;
content.anchoredPosition3D = Vector3.zero;
content.offsetMin = Vector2.zero;
content.offsetMax = Vector2.zero;
content.anchorMin = Vector2.zero;
content.anchorMax = Vector2.one;
tabData.tabButton = btn;
tabData.tabContent = content;
tabs.Insert(atIndex, tabData);
ApplyOverflowMethod();
if (select) { SelectTab(tabData); }
}
/// <summary>
/// Remove a tab by its index.
/// </summary>
/// <param name="index">Index of the tab to remove.</param>
public void RemoveTab(int index)
{
if (index < tabs.Count - 1) { tabs.RemoveAt(index); Destroy(tabsContainer.GetChild(index).gameObject); Destroy(contentContainer.GetChild(index).gameObject); }
}
/// <summary>
/// Remove a tab by its name.
/// </summary>
/// <param name="name">Name of the tab to remove.</param>
public void RemoveTab(string name)
{
TabData data = FindTab(name);
if (data != null) { tabs.Remove(data); Destroy(data.tabContent.gameObject); Destroy(data.tabButton.gameObject); }
}
/// <summary>
/// Find a tab by its index.
/// </summary>
/// <param name="index">The index of the tab to find.</param>
/// <returns></returns>
public TabData FindTab(int index)
{
return (index < tabs.Count - 1) ? tabs[index] : null;
}
/// <summary>
/// Find a tab by its name.
/// </summary>
/// <param name="name">The name of the tab to find.</param>
/// <returns></returns>
public TabData FindTab(string name)
{
for (int i = 0; i < tabs.Count; i++) { if (name.ToLower() == tabs[i].tabTitle.ToLower()) { return tabs[i]; } }
return null;
}
/// <summary>
/// Determines if the tab is locked in the Tab Control.
/// </summary>
/// <param name="index">The index of the control to toggle the lock state of.</param>
/// <param name="unlock">If checked the tab will be locked. If false, it will be unlocked.</param>
public void ToggleTabLock(int index, bool unlock)
{
if (index < tabs.Count - 1)
{
tabs[index].tabButton.interactable = unlock;
}
}
/// <summary>
/// Determines if the tab is locked in the Tab Control.
/// </summary>
/// <param name="name">The name of the control to toggle the lock state of.</param>
/// <param name="unlock">If checked the tab will be locked. If false, it will be unlocked.</param>
public void ToggleTabLock(string name, bool unlock)
{
TabData data = FindTab(name);
if (data != null)
{
data.tabButton.interactable = unlock;
}
}
/// <summary>
/// Determines if the tab is visible in the Tab Control.
/// </summary>
/// <param name="index">Index of the tab to change visibility of.</param>
/// <param name="show">If checked, the tab will be visible. If set to false, the tab will be hidden.</param>
public void ToggleTabVisibility(int index, bool show)
{
if (index < tabs.Count - 1)
{
tabs[index].tabButton.gameObject.SetActive(show);
}
}
/// <summary>
/// Determines if the tab is visible in the Tab Control.
/// </summary>
/// <param name="name">Name of the tab to change visibility of.</param>
/// <param name="show">If checked, the tab will be visible. If set to false, the tab will be hidden.</param>
public void ToggleTabVisibility(string name, bool show)
{
TabData data = FindTab(name);
if (data != null)
{
data.tabButton.gameObject.SetActive(show);
}
}
/// <summary>
/// Select a tab by its TabData.
/// </summary>
/// <param name="tab">The TabData of the tab.</param>
public void SelectTab(TabData tab)
{
ShowTab(tab);
}
/// <summary>
/// Select a tab by its index.
/// </summary>
/// <param name="tabIndex">The index of the tab.</param>
public void SelectTab(int tabIndex)
{
if (tabIndex < tabs.Count - 1) { ShowTab(tabs[tabIndex]); }
}
/// <summary>
/// Select a tab by its name.
/// </summary>
/// <param name="tabName">The name of the tab.</param>
public void SelectTab(string tabName)
{
TabData data = FindTab(name);
if (data != null)
{
ShowTab(data);
}
}
/// <summary>
/// Clear all tabs from the Tab Control.
/// </summary>
public void ClearTabs()
{
for (int i = 0; i < tabs.Count; i++)
{
try { Destroy(tabsContainer.GetChild(i).gameObject); } catch { }
try { Destroy(contentContainer.GetChild(i).gameObject); } catch { }
}
tabs.Clear();
}
/// <summary>
/// Automatically called whenever a tab is added, but can be manually called if modified.
/// </summary>
public void ApplyOverflowMethod()
{
if (GetComponent<ScrollRect>())
{
float tabsWidth = 0f;
for (int i = 0; i < tabs.Count; i++) { tabsWidth += tabs[i].tabButton.GetComponent<LayoutElement>().minWidth; }
if (tabsWidth < contentContainer.GetComponent<RectTransform>().rect.width) { tabsWidth = contentContainer.GetComponent<RectTransform>().rect.width; }
tabsContainer.GetComponent<RectTransform>().sizeDelta = new Vector2(tabsWidth, tabsContainer.GetComponent<RectTransform>().sizeDelta.y);
}
if (overflow == TabOverflowMethod.Scale) { tabsContainer.GetComponent<HorizontalLayoutGroup>().childForceExpandWidth = true; }
else { tabsContainer.GetComponent<HorizontalLayoutGroup>().childForceExpandWidth = false; }
}
/// <summary>
/// Switch to the indexed tab.
/// </summary>
/// <param name="tabIndex">The index to switch to.</param>
public void SwitchTabs(int tabIndex)
{
ShowTab(tabs[tabIndex]);
if (repositionOverflow) { tabsScrollRect.horizontalNormalizedPosition = (tabIndex + 1) / tabs.Count; }
}
#endregion
void ShowTab(TabData tab)
{
if (selectedTab != null)
{
selectedTab.tabButton.GetComponent<Image>().color = selectedTab.tabButton.colors.normalColor;
}
for (int i = 0; i < tabs.Count; i++) { tabs[i].tabContent.gameObject.SetActive(false); }
tab.tabContent.gameObject.SetActive(true);
_selectedTab = tab;
selectedTab.tabButton.GetComponent<Image>().color = selectedTab.tabButton.colors.pressedColor;
}
}
public enum TabOverflowMethod { None, Scale, Scroll };<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Boomberman_Boomb : MonoBehaviour {
public GameObject fier;
Vector3 pos;
// Use this for initialization
void Start () {
pos = gameObject.transform.position;
}
// Update is called once per frame
void Update()
{
Destroy(gameObject, 3.0f);
}
private void OnDestroy()
{
Boomberman_gameController.ins.removeBomb();
Instantiate(fier, pos, Quaternion.identity);
Instantiate(fier,new Vector3(pos.x-1,pos.y,pos.z), Quaternion.identity);
Instantiate(fier, new Vector3(pos.x + 1, pos.y, pos.z), Quaternion.identity);
Instantiate(fier, new Vector3(pos.x, pos.y, pos.z-1), Quaternion.identity);
Instantiate(fier, new Vector3(pos.x , pos.y, pos.z+1), Quaternion.identity);
if(Boomberman_gameController.ins.getBigBombActive()){
Instantiate(fier, new Vector3(pos.x - 1, pos.y, pos.z-1), Quaternion.identity);
Instantiate(fier, new Vector3(pos.x - 1, pos.y, pos.z+1), Quaternion.identity);
Instantiate(fier, new Vector3(pos.x +1, pos.y, pos.z-1), Quaternion.identity);
Instantiate(fier, new Vector3(pos.x + 1, pos.y, pos.z+1), Quaternion.identity);
Instantiate(fier, new Vector3(pos.x + 1, pos.y, pos.z + 2), Quaternion.identity);
Instantiate(fier, new Vector3(pos.x , pos.y, pos.z + 2), Quaternion.identity);
Instantiate(fier, new Vector3(pos.x - 1, pos.y, pos.z + 2), Quaternion.identity);
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
/// <summary>
/// Ingame Cursor UI Tool
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[AddComponentMenu("UI Tools/Extentions/In-game Cursor", 2), DisallowMultipleComponent]
public class IngameCursor : UICursor, IPointerClickHandler
{
[Tooltip("The source object to use as the UI cursor.")]
public Image cursor;
[Tooltip("Size of the cursor.")]
public float size = 1f;
[Tooltip("Speed the cursor will constantly maintin when following the exact position of the system cursor. Set to 0 for instant following.")]
public float followSpeed = 0f;
[Space]
[Tooltip("The image to use on the cursor.")]
public Sprite icon;
[Tooltip("The array of sprites to use instead of a single icon. The icon must be unset before this array can be used.")]
public Sprite[] spriteIcons;
[Tooltip("The array of textures to use instead of a single icon. The icon must be unset before this array can be used.")]
public Texture2D[] textureIcons;
[Tooltip("How fast the icon iterates through the provided array.")]
public float animationSpeed = 1f;
[Tooltip("The range of the array to use. For example: in an array of 10 elements with a range of [2, 8], means only elements 2 through 8 will be used, and 0, 1 and 9 will be exempt.")]
public Vector2 range = new Vector2(-1, -1);
[Tooltip("Hides the system cursor while in-game so only the UI cursor is visible.")]
public bool hideSystemCursor;
[Tooltip("Hides the UI cursor while in-game so only the system cursor is visisble")]
public bool hideGameCursor;
/// <summary>
/// The PointerEventData of the last object the UI cursor clicked.
/// </summary>
public static PointerEventData clickData;
/// <summary>
/// The GameObject of the last object the UI Cursor clicked.
/// </summary>
public static GameObject lastClicked;
private int index;
private bool set;
private RectTransform cursorRect;
#region Public Functions
/// <summary>
/// Set the UI cursor to a single sprite.
/// </summary>
/// <param name="cursorIcon">The sprite to use as the new UI cursor.</param>
public void SetCursor(Sprite cursorIcon)
{
cursor.sprite = cursorIcon;
range.x = (range.x > spriteIcons.Length - 1) ? -1 : range.x;
index = (range.x < 0) ? 0 : (int)range.x;
set = true;
}
/// <summary>
/// Set the UI cursor to an array of sprites.
/// </summary>
/// <param name="cursorIcons">The sprite array to use as the new UI cursor. The cursor will cycle through this array at an anitmationSpeed.</param>
public void SetCursor(Sprite[] cursorIcons)
{
spriteIcons = cursorIcons;
range.x = (range.x > spriteIcons.Length - 1) ? -1 : range.x;
index = (range.x < 0) ? 0 : (int)range.x;
set = true;
}
/// <summary>
/// Set the UI cursor to an array of textures.
/// </summary>
/// <param name="cursorIcons">The texture array to use as the new UI cursor. The cursor will cycle through this array at an anitmationSpeed.</param>
public void SetCursor(Texture2D[] cursorIcons)
{
textureIcons = cursorIcons;
range.x = (range.x > spriteIcons.Length - 1) ? -1 : range.x;
index = (range.x < 0) ? 0 : (int)range.x;
set = true;
}
#endregion
#region Private Functions
void Start()
{
if(icon != null) { SetCursor(icon); }
else if(spriteIcons.Length > 0) { SetCursor(spriteIcons); }
else if(textureIcons.Length > 0) { SetCursor(textureIcons); }
cursorRect = cursor.GetComponent<RectTransform>();
StartCoroutine(AnimateCursor());
}
void LateUpdate()
{
if (icon != null) { cursor.sprite = icon; }
if(size < 1) { size = 1f; }
cursor.rectTransform.sizeDelta = new Vector2(size, size);
Cursor.visible = !hideSystemCursor;
cursor.enabled = !hideGameCursor;
}
void FixedUpdate()
{
if (followSpeed <= 0f) { cursor.transform.position = Input.mousePosition - new Vector3(cursorRect.rect.xMin, cursorRect.rect.yMax); }
else { cursor.transform.position = Vector3.MoveTowards(cursor.transform.position, Input.mousePosition - new Vector3(cursorRect.rect.xMin, cursorRect.rect.yMax), followSpeed * Time.deltaTime); }
}
IEnumerator AnimateCursor()
{
while (set)
{
if (icon == null)
{
if (spriteIcons.Length > 0)
{
cursor.sprite = spriteIcons[index];
yield return new WaitForSecondsRealtime(1 / animationSpeed);
index++;
range.x = (range.x > spriteIcons.Length - 1) ? -1 : range.x;
range.y = (range.y > spriteIcons.Length - 1) ? -1 : range.y;
if (index > ((range.y < 0) ? spriteIcons.Length - 1 : (int)range.y)) { index = (range.x < 0) ? 0 : (int)range.x; }
}
else if (textureIcons.Length > 0)
{
Sprite textureSprite = Sprite.Create(textureIcons[index], new Rect(0,0,textureIcons[index].width, textureIcons[index].height), Vector2.zero);
cursor.sprite = textureSprite;
yield return new WaitForSecondsRealtime(1 / animationSpeed);
index++;
range.x = (range.x > textureIcons.Length - 1) ? -1 : range.x;
range.y = (range.y > textureIcons.Length - 1) ? -1 : range.y;
if (index > ((range.y < 0) ? textureIcons.Length - 1 : (int)range.y)) { index = (range.x < 0) ? 0 : (int)range.x; }
}
}
else { yield return new WaitForSecondsRealtime(1 / animationSpeed); }
}
}
public void OnPointerClick(PointerEventData eventData)
{
clickData = eventData;
lastClicked = clickData.pointerCurrentRaycast.gameObject;
}
#endregion
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
[CustomEditor(typeof(OptionSelector))]
public class OptionSelectorEditor : Editor {
SerializedProperty loopback, dataType, fitText, includeObjectType;
OptionSelector.DataType dt;
private void OnEnable()
{
//default elements to draw first
loopback = serializedObject.FindProperty("loopback");
dataType = serializedObject.FindProperty("dataType");
fitText = serializedObject.FindProperty("fitText");
includeObjectType = serializedObject.FindProperty("includeType");
OptionSelector options = target as OptionSelector;
dt = options.dataType;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawDefaultElements();
OptionSelector options = target as OptionSelector;
if(dt != options.dataType && Application.isPlaying) { options.FireEvent(); dt = options.dataType; }
if (options.dataType == OptionSelector.DataType.Numeric)
{
options.minInt = EditorGUILayout.IntField("Min", options.minInt);
options.maxInt = EditorGUILayout.IntField("Max", options.maxInt);
}
else if (options.dataType == OptionSelector.DataType.Decimal)
{
options.minFloat = EditorGUILayout.FloatField("Min", options.minFloat);
options.maxFloat = EditorGUILayout.FloatField("Max", options.maxFloat);
options.increment = EditorGUILayout.FloatField("Increment", options.increment);
}
else if (options.dataType == OptionSelector.DataType.String)
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("stringValues"), true);
}
else if (options.dataType == OptionSelector.DataType.Enum)
{
EditorGUILayout.LabelField("Set Enum by script: OptionSelector.SetEnumType(Enum);");
}
else if (options.dataType == OptionSelector.DataType.Object)
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("objectValues"), true);
EditorGUILayout.PropertyField(includeObjectType);
}
else if (options.dataType == OptionSelector.DataType.Custom)
{
EditorGUILayout.LabelField("Set custom data by script: OptionSelector.SetCustomType(object);");
}
EditorGUILayout.Space();
serializedObject.ApplyModifiedProperties();
}
void DrawDefaultElements()
{
EditorGUILayout.PropertyField(loopback);
EditorGUILayout.PropertyField(dataType);
EditorGUILayout.PropertyField(fitText);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Tooltip UI Tool - Modal
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[DisallowMultipleComponent]
public class TooltipModal : MonoBehaviour
{
/// <summary>
/// Sets up the paramaters on the Tooltip prefab itself.
/// </summary>
public Image icon;
public Text header, body;
private RectTransform target;
private bool followMouse;
private RectTransform self;
private Vector3 size, offset;
private TooltipAlignment alignment;
void Awake()
{
self = GetComponent<RectTransform>();
}
void Update()
{
SetPosition();
}
void SetPosition()
{
if (followMouse)
{
transform.position = Input.mousePosition + offset;
}
else
{
if (target != null)
{
if (alignment == TooltipAlignment.Default) { size = Vector2.zero; }
else if (alignment == TooltipAlignment.Above) { size = new Vector2(0f, target.rect.height / 2f); }
else if (alignment == TooltipAlignment.Below) { size = new Vector2(0f, -target.rect.height / 2f); }
else if (alignment == TooltipAlignment.Left) { size = new Vector2(-target.rect.width / 2f, target.rect.height / 2f); }
else if (alignment == TooltipAlignment.Right) { size = new Vector2(target.rect.width / 2f, target.rect.height / 2f); }
transform.position = target.position + size + offset;
}
else { transform.position = offset; }
}
}
#region Public Functions
/// <summary>
/// Update the data of the tooltip with the provided source data.
/// </summary>
/// <param name="source">Tooltip object to pull the data from.</param>
public void UpdateTooltip(Tooltip source)
{
if (header != null) { header.text = source.header; }
if (body != null) { body.text = source.text; }
if (icon != null)
{
icon.sprite = source.icon;
icon.enabled = (source.icon != null);
}
followMouse = source.followMouse;
alignment = source.alignment;
target = source.GetComponent<RectTransform>();
if (source.offset == Vector2.zero) { offset = Vector2.zero; }
else
{
if (alignment == TooltipAlignment.Default) { offset = (target != null) ? (target.position / 2f) - (Input.mousePosition / 2f) : Vector3.zero; }
else if (alignment == TooltipAlignment.Above) { offset = new Vector2(0f, self.rect.height / 2f) + source.offset; }
else if (alignment == TooltipAlignment.Below) { offset = new Vector2(0f, -self.rect.height / 2f) + source.offset; }
else if (alignment == TooltipAlignment.Left) { offset = new Vector2(-self.rect.width / 2f, -self.rect.height / 2f) + source.offset; }
else if (alignment == TooltipAlignment.Right) { offset = new Vector2(self.rect.width / 2f, -self.rect.height / 2f) + source.offset; }
}
}
/// <summary>
/// Update the title header text of the tooltip.
/// </summary>
/// <param name="newText">The new text to use in replacement of the previous.</param>
public void UpdateHeader(string newText)
{
if (header != null) { header.text = newText; }
}
/// <summary>
/// Update the body text of the tooltip.
/// </summary>
/// <param name="newText">The new text to use in replacement of the previous.</param>
public void UpdateBody(string newText)
{
if (body != null) { body.text = newText; }
}
/// <summary>
/// Update the icon image of the tooltip.
/// </summary>
/// <param name="newImage">The new sprite image to use in replacement of the previous.</param>
public void UpdateImage(Sprite newImage)
{
if (icon != null) { icon.sprite = newImage; }
}
/// <summary>
/// Set the target this tooltip should appear on. This is only relevant when "followMouse" is disabled, for better accuracy.
/// </summary>
/// <param name="targetObject">The object to target the tooltips positioning on.</param>
public void SetTarget(RectTransform targetObject) { target = targetObject; }
/// <summary>
/// Display a tooltip with specified paramaters for positioning.
/// </summary>
/// <param name="text">Body text of the tooltip</param>
/// <param name="title">Header title of the tooltip</param>
/// <param name="image">Icon sprite image of the tooltip, displayed next to the header</param>
/// <param name="updatePosition">Should the position of the tooltip be updated to the mouse position per frame?</param>
/// <param name="mouseOffset">Offset value from its origin point (mouse or object, depending on upatePosition)</param>
/// <param name="alignmentPosition">Position alignment in relation to the origin point of the object</param>
/// <param name="targetObject">Object to be displaying this tooltip on</param>
public void ShowTooltip(string text, string title = "", Sprite image = null, bool updatePosition = false, Vector2 mouseOffset = new Vector2(), TooltipAlignment alignmentPosition = TooltipAlignment.Default, RectTransform targetObject = null)
{
if (header != null) { header.text = title; }
if (body != null) { body.text = text; }
if (icon != null)
{
icon.sprite = image;
icon.enabled = (image != null);
}
followMouse = updatePosition;
alignment = alignmentPosition;
target = targetObject;
if (alignment == TooltipAlignment.Default) { offset = (target != null) ? (target.position / 2f) - (Input.mousePosition / 2f) : Vector3.zero; }
else if (alignment == TooltipAlignment.Above) { offset = new Vector2(0f, self.rect.height / 2f) + mouseOffset; }
else if (alignment == TooltipAlignment.Below) { FlipOffset(ref mouseOffset); offset = new Vector2(0f, -self.rect.height / 2f) + mouseOffset; }
else if (alignment == TooltipAlignment.Left) { FlipOffset(ref mouseOffset); offset = new Vector2(-self.rect.width / 2f, -self.rect.height / 2f) + mouseOffset; }
else if (alignment == TooltipAlignment.Right) { offset = new Vector2(self.rect.width / 2f, -self.rect.height / 2f) + mouseOffset; }
SetPosition();
gameObject.SetActive(true);
gameObject.GetComponent<ContentSizeFitter>().SetLayoutVertical();
}
/// <summary>
/// Hide the tooltip display.
/// </summary>
public void HideTooltip()
{
gameObject.SetActive(false);
}
/// <summary>
/// Simply flips the offset of negative directions so positive values are treated as negatives for opposite directions.
/// </summary>
/// <param name="targetOffset">Reference to the offset to affect</param>
void FlipOffset(ref Vector2 targetOffset)
{
if(alignment == TooltipAlignment.Left) { if (targetOffset.x > 0f) { targetOffset.x = -targetOffset.x; } }
else if (alignment == TooltipAlignment.Below) { if (targetOffset.y > 0f) { targetOffset.y = -targetOffset.y; } }
}
#endregion
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Boomberman_Enemy : MonoBehaviour {
string moveto;
public float timetomove = 1;
Vector3 pos;
Boomberman_gameController temp;
private void Start()
{
moveto = "";
temp = Boomberman_gameController.ins;
}
// Update is called once per frame
void Update () {
pos = transform.position;
int index = -1;
Dictionary<string, bool> allow = new Dictionary<string, bool>();
if (gameObject.name == "orangeEnemy(Clone)")
{
allow = temp.allowMoves("enemy2");
index = 1;
}
else if (gameObject.name == "enemyRed(Clone)")
{
allow = temp.allowMoves("enemy1");
index = 0;
}
else if (gameObject.name == "purpleEnemy(Clone)") {
allow = temp.allowMoves("enemy3");
index = 2;
}
else{
Destroy(gameObject);
}
KeyValuePair<int,int>enemyPos= temp.getenemyPos(index);
int k = enemyPos.Key, v = enemyPos.Value;
if(moveto==""){
{
List<string> moves = new List<string>();
if (allow["right"])
moves.Add("right");
if (allow["up"])
moves.Add("up");
if (allow["left"])
moves.Add("left");
if (allow["down"])
moves.Add("down");
int i = Random.Range(0, moves.Count);
moveto = moves[i];
}
}
else if (!allow[moveto])
{
List<string> moves = new List<string>();
if (allow["right"])
moves.Add("right");
if (allow["up"])
moves.Add("up");
if (allow["left"])
moves.Add("left");
if (allow["down"])
moves.Add("down");
int i = Random.Range(0, moves.Count);
moveto = moves[i];
}
if (timetomove < 0)
{
timetomove = 1;
if (moveto == "up")
{
gameObject.transform.position = new Vector3(pos.x, pos.y, pos.z + 1f);
temp.setEnemyPos(index,k - 1, v);
}
if (moveto == "down")
{
gameObject.transform.position = new Vector3(pos.x, pos.y, pos.z - 1f);
temp.setEnemyPos(index,k + 1, v);
}
if (moveto == "right")
{
gameObject.transform.position = new Vector3(pos.x + 1f, pos.y, pos.z);
temp.setEnemyPos(index,k, v + 1);
}
if (moveto == "left")
{
gameObject.transform.position = new Vector3(pos.x - 1f, pos.y, pos.z);
temp.setEnemyPos(index,k, v - 1);
}
}
else{
timetomove -= 0.01f;
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
/// <summary>
/// Listbox UI Tool
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[AddComponentMenu("UI Tools/Listbox", 1), DisallowMultipleComponent]
public class ListBox : MonoBehaviour, IPointerClickHandler
{
public RectTransform content;
public RectTransform selectionBox;
[Space]
public List<ListItem> items = new List<ListItem>();
[Header("Text Preferences")]
[Tooltip("If you supply text for a new ListItem, this will be the font used.")]
public Font defaultFont;
[Tooltip("If you supply text for a new ListItem, this will be the color used.")]
public Color defaultColor = Color.black;
/// <summary>
/// The currently selected item in the listbox
/// </summary>
[System.NonSerialized]
public ListItem selection;
[System.Serializable]
public class ListItem
{
[Tooltip("Creates a new UI Text element with the specified text to it. This is seperate from a provided object and will be displayed instead of a object, if the object is null.")]
public string text;
[Space]
[Tooltip("Provide a object to be displayed and added to the ListBox. This is seperate from a provided text, and will be used instead of text. If this field is null, the provided text will be used instead.")]
public GameObject _object;
[Tooltip("Determines if the object (or text) will be given a fixed height while in the ListBox hierarchy, or if it will be controlled by a Layout Element.")]
public bool useFixedHeight;
[Tooltip("The fixed height to maintain for the object (or text) when added to the ListBox.")]
public float fixedHeight;
/// <summary>
/// Create a new ListBox.ListItem with a specific object.
/// </summary>
/// <param name="gameObject">The actual GameObject to add to this ListItem ListBox.</param>
public ListItem(GameObject gameObject)
{
_object = gameObject;
}
/// <summary>
/// Create a new ListBox.ListItem with a specific object, and the objects height, that will be maintained when added to the ListBox.
/// </summary>
/// <param name="gameObject">The actual GameObject to add to this ListItem ListBox.</param>
/// <param name="objectFixedHeight">The height of the object to maintain, when created and added to the ListBox.</param>
public ListItem(GameObject gameObject, float objectFixedHeight)
{
_object = gameObject;
useFixedHeight = true;
fixedHeight = objectFixedHeight;
}
/// <summary>
/// Create a new ListBox.ListItem with a specific object, that will also add a LayoutElement to it when added to the ListBox, to control height.
/// </summary>
/// <param name="gameObject">The actual GameObject to add to this ListItem ListBox.</param>
/// <param name="includeLayoutElement">Should this GameObject have a LayoutElement added to it, when being created and added to the ListBox?</param>
public ListItem(GameObject gameObject, bool includeLayoutElement)
{
_object = gameObject;
if (!_object.GetComponent<LayoutElement>()) { _object.AddComponent<LayoutElement>().preferredHeight = GetObjectHeight(); }
else
{
if (_object.AddComponent<LayoutElement>().preferredHeight <= 0f) { _object.AddComponent<LayoutElement>().preferredHeight = GetObjectHeight(); }
}
}
/// <summary>
/// Create a new ListBox.ListItem with specific text. This works seperately from a object.
/// </summary>
/// <param name="objectText">The string contents to add to the new UI Text element.</param>
public ListItem(string objectText)
{
text = objectText;
_object = null;
}
/// <summary>
/// Create a new ListBox.ListItem with specific text, and a set fixed height for the new text. This works seperately from a object.
/// </summary>
/// <param name="objectText">The string contents to add to the new UI Text element.</param>
/// <param name="objectFixedHeight">The height of the UI Text object to maintain, when created and added to the ListBox.</param>
public ListItem(string objectText, float objectFixedHeight)
{
text = objectText;
_object = null;
useFixedHeight = true;
fixedHeight = objectFixedHeight;
}
float GetObjectHeight()
{
if (useFixedHeight)
{
return fixedHeight;
}
else
{
return _object.GetComponent<RectTransform>().rect.height;
}
}
};
void Awake()
{
selectionBox.gameObject.SetActive(false);
RefreshListBox();
}
#region Common Functions
/// <summary>
/// Add an existing ListItem to the ListBox.
/// </summary>
/// <param name="item">The actual ListItem to add to the ListBox.</param>
public void AddItem(ListItem item)
{
items.Add(item);
RefreshListBox();
}
/// <summary>
/// Add an existing ListItem to the ListBox, with a LayoutElement, if it does not already have one.
/// </summary>
/// <param name="item">The actual ListItem to add to the ListBox.</param>
/// <param name="includeLayoutElement">Should a LayoutElement be added to the ListItem being added?</param>
public void AddItem(ListItem item, bool includeLayoutElement)
{
if (!item._object.GetComponent<LayoutElement>())
{
item._object.AddComponent<LayoutElement>().preferredHeight = GetPreference(item);
}
else
{
if (item._object.AddComponent<LayoutElement>().preferredHeight <= 0f)
{
item._object.AddComponent<LayoutElement>().preferredHeight = GetPreference(item);
}
}
items.Add(item);
RefreshListBox();
}
/// <summary>
/// Remove an existing ListItem from the ListBox.
/// </summary>
/// <param name="item">The actual ListItem to remove from the ListBox.</param>
public void RemoveItem(ListItem item)
{
if (item._object != null) { Destroy(item._object); }
items.Remove(item);
RefreshListBox();
}
/// <summary>
/// Remove an existing ListItem from the ListBox.
/// </summary>
/// <param name="itemIndex">The index of the ListItem to remove from the ListBox.</param>
public void RemoveItem(int itemIndex)
{
if (items[itemIndex]._object != null) { Destroy(items[itemIndex]._object); }
items.RemoveAt(itemIndex);
RefreshListBox();
}
/// <summary>
/// Clear the visible displayed ListBox to appear empty. The items array containing the data will still remain.
/// </summary>
public void ClearListBox()
{
for (int i = 0; i < content.childCount; i++)
{
Destroy(content.GetChild(i).gameObject);
items.RemoveAt(i);
}
}
#endregion
#region Public Functions
/// <summary>
/// Reload the entire listbox to account for newly added or removed items and their hierarchical positioning.
/// This function is automatically called on Add/Remove events.
/// </summary>
public void RefreshListBox()
{
ClearListBox();
float masterHeight = 0f;
SetToDefaultFont();
for (int i = 0; i < items.Count; i++)
{
if (items[i]._object != null)
{
//move obj to listbox
items[i]._object.transform.SetParent(content);
if (items[i]._object.GetComponent<LayoutElement>() == null) { items[i]._object.AddComponent<LayoutElement>().preferredHeight = GetPreference(items[i]); }
masterHeight += items[i]._object.GetComponent<RectTransform>().rect.height;
}
else
{
//make text, set it, move it to listbox
Text label = new GameObject("Text: " + items[i].text).AddComponent<Text>().GetComponent<Text>();
label.font = defaultFont;
label.color = defaultColor;
label.GetComponent<RectTransform>().sizeDelta = new Vector2(0, label.preferredHeight + 2f);
items[i]._object = label.gameObject;
label.gameObject.AddComponent<LayoutElement>().preferredHeight = GetPreference(items[i]);
label.text = items[i].text;
label.transform.SetParent(content);
masterHeight += label.GetComponent<RectTransform>().rect.height;
}
}
}
/// <summary>
/// Checks if a font is provided. If not, the default font "Arial" will be used.
/// </summary>
public void SetToDefaultFont()
{
if (defaultFont == null) { defaultFont = Resources.GetBuiltinResource<Font>("Arial.ttf"); }
}
#endregion
#region Helper Functions
float GetPreference(ListItem item)
{
if (item.useFixedHeight)
{
return item.fixedHeight;
}
else
{
return item._object.GetComponent<RectTransform>().rect.height;
}
}
bool ClickedItemExistsInList(GameObject obj)
{
foreach (ListItem item in items)
{
if (obj == item._object) { return true; }
}
return false;
}
public void OnPointerClick(PointerEventData eventData)
{
selectionBox.gameObject.SetActive(false);
GameObject clickedObj = eventData.pointerCurrentRaycast.gameObject;
RectTransform objRect = clickedObj.GetComponent<RectTransform>();
if (ClickedItemExistsInList(clickedObj))
{
selectionBox.gameObject.SetActive(true);
selectionBox.sizeDelta = objRect.sizeDelta;
selectionBox.position = objRect.position;
}
}
#endregion
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
/// <summary>
/// Game Cursor UI Tool (not a UI element)
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[AddComponentMenu("UI Tools/Extentions/Game Cursor", 3), DisallowMultipleComponent]
public class GameCursor : UICursor
{
[Tooltip("Auto - will set the size to match a 'System' cursor size.\nForce Software - will set the size to match the import settings of the texture.")]
public CursorMode cursorType;
[Tooltip("Determines if the Editor will auto-update Player Settings cursor information, whenever anything is changed.")]
public bool ApplyInEditor;
[Space]
[Header("Static Cursor")]
[Tooltip("Set a static texture to use as the cursor. Doing so will use the static cursor instead of any animated settings.")]
public Texture2D cursor;
[Tooltip("Set the hotspot where the cursor starts to register as a pointer.")]
public Vector2 hotspot = Vector2.zero;
[Space]
[Header("Animated Cursor")]
[Tooltip("Optionally load the Animated Cursor array with textures from a Resource folder. Specify the name of the folder within Resources these textures exist.\nFor example: If you had 5 textures inside 'Assets > Resources > Game Cursors', youd specify 'Game Cursors'.")]
public string loadFromResources;
[Tooltip("The textures to animate the cursor with.")]
public Texture2D[] animatedCursor;
[Tooltip("Optionally set the range of the provided texture array, to use.\nThe first value represents the 'min' range, and the second represents the 'max' range.\nFor example: If you had 10 textures set, and you set the range to [2, 8], only the textures from index 2, up to index 8 will play, skipping 0, 1 and 9.\nSet to default [-1,-1] to use all textures and ignore any range settings.")]
public Vector2 range = new Vector2(-1, -1);
[Tooltip("The speed to play the animation by. 1 is default normal speed.\nAnything higher than 1 is faster, anything less than 1 is slower than the default speed.")]
public float animationSpeed = 1f;
private int step = 0;
#region Public Functions
/// <summary>
/// Set the cursor to an animated array of Texture2D.
/// </summary>
/// <param name="animation">Array of Texture2D to animate the cursor with.</param>
/// <param name="initialSpeed">Speed to animate the cursor by.</param>
public void SetAnimatedCursor(Texture2D[] animation, float initialSpeed)
{
animatedCursor = animation;
animationSpeed = initialSpeed;
range.x = (range.x > animation.Length - 1) ? -1 : range.x;
step = (range.x < 0) ? 0 : (int)range.x;
StopCoroutine(AnimateCursor());
if (animation.Length > 0) { StartCoroutine(AnimateCursor()); }
}
/// <summary>
/// Set the cursor to an animated array from the Resources folder.
/// </summary>
/// <param name="resourceAnimation">Path to the folder starting in Assets/Resources.</param>
/// <param name="initialSpeed">Speed to animate the cursor by.</param>
public void SetAnimatedCursor(string resourceAnimation, float initialSpeed)
{
Texture2D[] animation = Resources.LoadAll<Texture2D>(resourceAnimation);
animatedCursor = animation;
animationSpeed = initialSpeed;
range.x = (range.x > animation.Length - 1) ? -1 : range.x;
step = (range.x < 0) ? 0 : (int)range.x;
StopCoroutine(AnimateCursor());
if (animation.Length > 0) { StartCoroutine(AnimateCursor()); }
}
#endregion
private void OnValidate()
{
if (ApplyInEditor)
{
Cursor.SetCursor(cursor, hotspot, cursorType);
if (!string.IsNullOrEmpty(loadFromResources))
{ SetAnimatedCursor(loadFromResources, animationSpeed); }
else { SetAnimatedCursor(animatedCursor, animationSpeed); }
}
}
void Start()
{
if (!string.IsNullOrEmpty(loadFromResources))
{ SetAnimatedCursor(loadFromResources, animationSpeed); }
else { SetAnimatedCursor(animatedCursor, animationSpeed); }
}
void FixedUpdate()
{
if(cursor != null) { Cursor.SetCursor(cursor, Vector2.zero, cursorType); }
}
IEnumerator AnimateCursor()
{
while (true)
{
if (cursor == null)
{
Cursor.SetCursor(animatedCursor[step], hotspot, cursorType);
yield return new WaitForSecondsRealtime(1 / animationSpeed);
step++;
range.x = (range.x > animatedCursor.Length - 1) ? -1 : range.x;
range.y = (range.y > animatedCursor.Length - 1) ? -1 : range.y;
if (step > ((range.y < 0) ? animatedCursor.Length - 1 : (int)range.y)) { step = (range.x < 0) ? 0 : (int)range.x; }
}
else { yield return new WaitForSecondsRealtime(1 / animationSpeed); }
}
}
}
[DisallowMultipleComponent]
public class UICursor : MonoBehaviour
{
//empty class used for Cursor's to prevent multiple types of cursors being used.
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class boxScript : MonoBehaviour {
private void OnDestroy()
{
GameObject temp=null;
if(this.transform.childCount>0){
temp=this.transform.GetChild(0).gameObject;
temp.transform.parent=null;
temp.gameObject.SetActive(true);
}
}
}<file_sep>using UnityEngine;
using System.Collections;
using System;
using UnityEngine.UI;
using UnityEngine.Events;
using System.Collections.Generic;
/// <summary>
/// Message Box UI Tool - Data Class
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
namespace CustomMessageBox
{
public enum MessageBoxResponse { None, Yes, No, Cancel, OK, Custom };
public enum MessageBoxButtons { None, YesNo, YesNoCancel, OK, Custom };
public enum MessageBoxCustomButtons { Button1, Button2, Button3 };
public class CustomButton
{
public Action buttonAction;
public string buttonText;
public ButtonLocation location;
public enum ButtonLocation { Default, Left, Right, Center };
public CustomButton(Action listenEvent, string buttonTxt = "", ButtonLocation buttonLocation = ButtonLocation.Default)
{ buttonAction = listenEvent; buttonText = buttonTxt; location = buttonLocation; }
};
public class MessageBox
{
/// <summary>
/// The response returned after the event has fired on the button.
/// </summary>
public static MessageBoxResponse response;
/// <summary>
/// The GameObject this MessageBox logic is being applied to.
/// </summary>
public static GameObject gameObject;
static Action BtnActionYes, BtnActionNo, BtnActionCancel, BtnActionOK;
static GameObject msgBox;
static Text header, body;
static Button btnYes, btnNo, btnCancel, btnOK;
static Button btnCustom1, btnCustom2, btnCustom3;
public static void Initalize(GameObject static_MsgBox)
{
msgBox = (GameObject)MonoBehaviour.Instantiate(static_MsgBox, static_MsgBox.transform.position, static_MsgBox.transform.rotation);
msgBox.transform.SetParent(static_MsgBox.transform.parent);
msgBox.GetComponent<RectTransform>().sizeDelta = static_MsgBox.GetComponent<RectTransform>().sizeDelta;
msgBox.name = "MessageBox Dialog " + static_MsgBox.transform.parent.childCount;
header = msgBox.transform.GetChild(0).GetComponent<Text>();
body = msgBox.transform.GetChild(1).GetComponent<Text>();
btnYes = msgBox.transform.GetChild(2).GetComponent<Button>();
btnNo = msgBox.transform.GetChild(3).GetComponent<Button>();
btnCancel = msgBox.transform.GetChild(4).GetComponent<Button>();
btnOK = msgBox.transform.GetChild(5).GetComponent<Button>();
msgBox.SetActive(false);
}
#region Public Functions
/// <summary>
/// Update the text of a specified button on the message box display.
/// </summary>
/// <param name="btn">The message box button to affect</param>
/// <param name="newText">The text to set to this button</param>
public void UpdateButtonText(MessageBoxCustomButtons btn, string newText)
{
if (btn == MessageBoxCustomButtons.Button1)
{
if (btnCustom1.gameObject.activeSelf) { btnCustom1.gameObject.transform.GetChild(0).GetComponent<Text>().text = newText; }
}
else if (btn == MessageBoxCustomButtons.Button2)
{
if (btnCustom2.gameObject.activeSelf) { btnCustom2.gameObject.transform.GetChild(0).GetComponent<Text>().text = newText; }
}
else if (btn == MessageBoxCustomButtons.Button3)
{
if (btnCustom3.gameObject.activeSelf) { btnCustom3.gameObject.transform.GetChild(0).GetComponent<Text>().text = newText; }
}
}
/// <summary>
/// Set the lock state of a specified button on the message box display.
/// </summary>
/// <param name="btn">The message box button to affect</param>
/// <param name="lockButton">Should this button be locked/unclickable or unlocked/clickable</param>
public void LockButtonInteraction(MessageBoxCustomButtons btn, bool lockButton = true)
{
if (btn == MessageBoxCustomButtons.Button1)
{
if (btnCustom1.gameObject.activeSelf) { btnCustom1.interactable = !lockButton; }
}
else if (btn == MessageBoxCustomButtons.Button2)
{
if (btnCustom2.gameObject.activeSelf) { btnCustom2.interactable = !lockButton; }
}
else if (btn == MessageBoxCustomButtons.Button3)
{
if (btnCustom3.gameObject.activeSelf) { btnCustom3.interactable = !lockButton; }
}
}
/// <summary>
/// Get the center of the screen where this message box should sit, taking in account its size.
/// </summary>
public Vector2 GetCenter()
{
float width = (msgBox.transform.parent.GetComponent<RectTransform>().rect.xMax / 2f) - msgBox.GetComponent<RectTransform>().rect.width / 2f;
float height = (msgBox.transform.parent.GetComponent<RectTransform>().rect.yMax / 2f) - msgBox.GetComponent<RectTransform>().rect.height / 2f;
msgBox.transform.localPosition = new Vector2(width, height);
return msgBox.transform.localPosition;
}
/// <summary>
/// Get or set the position of this message box on the Canvas.
/// </summary>
public Vector2 Position
{
get { return msgBox.transform.localPosition; }
set { msgBox.transform.localPosition = value; }
}
/// <summary>
/// Get or set the parent of this message box on the Canvas.
/// </summary>
public Transform Parent
{
get { return msgBox.transform.parent; }
set { msgBox.transform.SetParent(value); }
}
#endregion
#region "Show" Overloads (Static Functions)
/// <summary>
/// Actually show the message box.
/// </summary>
/// <param name="message">Text to display in the body of the box</param>
/// <param name="title">Text to display in the header of the box</param>
/// <param name="response">Buttons to display on this box</param>
/// <returns></returns>
public static MessageBox Show(string message, string title = "", MessageBoxButtons response = MessageBoxButtons.OK)
{
ToggleMessageBoxDisplay(true, message, title, response);
if (response == MessageBoxButtons.OK) { BtnActionOK = DefaultActionCancel; }
else if (response == MessageBoxButtons.YesNo) { BtnActionYes = DefaultActionCancel; BtnActionNo = DefaultActionCancel; }
else if (response == MessageBoxButtons.YesNoCancel) { BtnActionYes = DefaultActionCancel; BtnActionNo = DefaultActionCancel; BtnActionCancel = DefaultActionCancel; }
gameObject = msgBox;
return new MessageBox();
}
/// <summary>
/// Actually show the message box.
/// </summary>
/// <param name="message">Text to display in the body of the box</param>
/// <param name="title">Text to display in the header of the box</param>
/// <param name="response">Buttons to display on this box</param>
/// <param name="listenEvent">Event to fire when the response button is clicked</param>
/// <returns></returns>
public static MessageBox Show(string message, string title = "", MessageBoxButtons response = MessageBoxButtons.OK, Action listenEvent = null)
{
if (listenEvent == null) { listenEvent = BtnActionOK; }
ToggleMessageBoxDisplay(true, message, title, response);
if (response == MessageBoxButtons.OK) { BtnActionOK = listenEvent; BtnActionOK += DefaultActionCancel; }
else if (response == MessageBoxButtons.YesNo) { BtnActionYes = listenEvent; BtnActionYes += DefaultActionCancel; BtnActionNo = listenEvent; BtnActionNo += DefaultActionCancel; }
else if (response == MessageBoxButtons.YesNoCancel) { BtnActionYes = listenEvent; BtnActionYes += DefaultActionCancel; BtnActionNo = listenEvent; BtnActionNo += DefaultActionCancel; BtnActionCancel = listenEvent; BtnActionCancel += DefaultActionCancel; }
gameObject = msgBox;
return new MessageBox();
}
/// <summary>
/// Actually show the message box.
/// </summary>
/// <param name="message">Text to display in the body of the box</param>
/// <param name="title">Text to display in the header of the box</param>
/// <param name="option1">Event to fire when the first (center) button is clicked</param>
/// <param name="option2">Event to fire when the first (left) button is clicked</param>
/// <param name="option3">Event to fire when the first (right) button is clicked</param>
/// <returns></returns>
public static MessageBox Show(string message, string title = "", Action option1 = null, Action option2 = null, Action option3 = null)
{
int options = 0;
if (option1 == null) { option1 = BtnActionOK; }
options = ((option1 != null) ? 1 : 0) + ((option2 != null) ? 1 : 0) + ((option3 != null) ? 1 : 0);
ToggleMessageBoxDisplay(true, message, title, MessageBoxButtons.Custom, options);
if (option1 != null && option2 == null && option3 == null) { BtnActionOK = option1; BtnActionOK += DefaultActionCancel; }
else if (option1 != null && option2 != null && option3 == null) { BtnActionYes = option1; BtnActionYes += DefaultActionCancel; BtnActionNo = option2; BtnActionNo += DefaultActionCancel; }
else if (option1 != null && option2 != null && option3 != null) { BtnActionYes = option1; BtnActionYes += DefaultActionCancel; BtnActionNo = option2; BtnActionNo += DefaultActionCancel; BtnActionCancel = option3; BtnActionCancel += DefaultActionCancel; }
gameObject = msgBox;
return new MessageBox();
}
/// <summary>
/// Actually show the message box.
/// </summary>
/// <param name="message">Text to display in the body of the box</param>
/// <param name="title">Text to display in the header of the box</param>
/// <param name="option1">Details for the first (center) custom button option (optional)</param>
/// <param name="option2">Details for the second (left) custom button option (optional)</param>
/// <param name="option3">Details for the third (right) custom button option (optional)</param>
/// <returns></returns>
public static MessageBox Show(string message, string title = "", CustomButton option1 = null, CustomButton option2 = null, CustomButton option3 = null)
{
int options = 0;
btnCustom1 = null;
btnCustom2 = null;
btnCustom3 = null;
if (option1 == null) { option1.buttonAction = BtnActionOK; option1.buttonText = "OK"; }
options = ((option1 != null) ? 1 : 0) + ((option2 != null) ? 1 : 0) + ((option3 != null) ? 1 : 0);
ToggleMessageBoxDisplay(true, message, title, MessageBoxButtons.Custom, options);
if (option1 != null && option2 == null && option3 == null) { btnCustom1 = btnOK; SetButtonText(btnOK, option1.buttonText, option1.location); BtnActionOK = option1.buttonAction; BtnActionOK += DefaultActionCancel; }
else if (option1 != null && option2 != null && option3 == null) { btnCustom1 = btnYes; btnCustom2 = btnNo; SetButtonText(btnYes, option1.buttonText, option1.location); SetButtonText(btnNo, option2.buttonText, option2.location); BtnActionYes = option1.buttonAction; BtnActionYes += DefaultActionCancel; BtnActionNo = option2.buttonAction; BtnActionNo += DefaultActionCancel; }
else if (option1 != null && option2 != null && option3 != null) { btnCustom1 = btnYes; btnCustom2 = btnCancel; btnCustom3 = btnNo; SetButtonText(btnYes, option1.buttonText, option1.location); SetButtonText(btnNo, option3.buttonText, option3.location); SetButtonText(btnCancel, option2.buttonText, option2.location); BtnActionYes = option1.buttonAction; BtnActionYes += DefaultActionCancel; BtnActionNo = option3.buttonAction; BtnActionNo += DefaultActionCancel; BtnActionCancel = option2.buttonAction; BtnActionCancel += DefaultActionCancel; }
gameObject = msgBox;
return new MessageBox();
}
#endregion
/// <summary>
/// Called by MessageResponse on each button when clicked.
/// </summary>
/// <param name="actionResponse">Response of button clicked</param>
public static void InvokeAction(MessageBoxResponse actionResponse)
{
response = actionResponse;
if (actionResponse == MessageBoxResponse.Yes) { if(BtnActionYes != null) BtnActionYes.Invoke(); }
else if (actionResponse == MessageBoxResponse.No) { if (BtnActionNo != null) BtnActionNo.Invoke(); }
else if (actionResponse == MessageBoxResponse.Cancel) { if (BtnActionCancel != null) BtnActionCancel.Invoke(); }
else if (actionResponse == MessageBoxResponse.OK) { if (BtnActionOK != null) BtnActionOK.Invoke(); }
}
#region Helper Functions
static void SetButtonText(Button btn, string txt, CustomButton.ButtonLocation loc = CustomButton.ButtonLocation.Default)
{
if (btn == null) { return; }
if (string.IsNullOrEmpty(txt))
{
if (btn == btnOK) { txt = "OK"; }
else if (btn == btnYes) { txt = "Yes"; }
else if (btn == btnNo) { txt = "No"; }
else if (btn == btnCancel) { txt = "Cancel"; }
}
btn.gameObject.transform.GetChild(0).GetComponent<Text>().text = txt;
float maxWidth = msgBox.GetComponent<RectTransform>().rect.xMax;
float btnWidth = btn.GetComponent<RectTransform>().rect.width;
if (btn == btnOK) { btn.transform.localPosition = new Vector2((maxWidth / 2f) - btnWidth, btn.transform.localPosition.y); }
if (btn == btnYes) { btn.transform.localPosition = new Vector2(-btnWidth - 25f, btn.transform.localPosition.y); }
if (btn == btnNo) { btn.transform.localPosition = new Vector2(btnWidth + 25f, btn.transform.localPosition.y); }
if (btn == btnCancel) { btn.transform.localPosition = new Vector2((maxWidth / 2f) - btnWidth, btn.transform.localPosition.y); }
if (loc == CustomButton.ButtonLocation.Left)
{
if (btn == btnOK) { btn.transform.localPosition = new Vector2(-btnWidth - 25f, btn.transform.localPosition.y); }
if (btn == btnYes) { btn.transform.localPosition = new Vector2(-btnWidth - 25f, btn.transform.localPosition.y); }
if (btn == btnNo) { btn.transform.localPosition = new Vector2(-btnWidth - 25f, btn.transform.localPosition.y); }
if (btn == btnCancel) { btn.transform.localPosition = new Vector2(-btnWidth - 25f, btn.transform.localPosition.y); }
}
else if (loc == CustomButton.ButtonLocation.Right)
{
if (btn == btnOK) { btn.transform.localPosition = new Vector2(btnWidth + 25f, btn.transform.localPosition.y); }
if (btn == btnYes) { btn.transform.localPosition = new Vector2(btnWidth + 25f, btn.transform.localPosition.y); }
if (btn == btnNo) { btn.transform.localPosition = new Vector2(btnWidth + 25f, btn.transform.localPosition.y); }
if (btn == btnCancel) { btn.transform.localPosition = new Vector2(btnWidth + 25f, btn.transform.localPosition.y); }
}
else if (loc == CustomButton.ButtonLocation.Center)
{
if (btn == btnOK) { btn.transform.localPosition = new Vector2((maxWidth / 2f) - btnWidth, btn.transform.localPosition.y); }
if (btn == btnYes) { btn.transform.localPosition = new Vector2((maxWidth / 2f) - btnWidth, btn.transform.localPosition.y); }
if (btn == btnNo) { btn.transform.localPosition = new Vector2((maxWidth / 2f) - btnWidth, btn.transform.localPosition.y); }
if (btn == btnCancel) { btn.transform.localPosition = new Vector2((maxWidth / 2f) - btnWidth, btn.transform.localPosition.y); }
}
}
static void ToggleMessageBoxDisplay(bool show, string msg = "", string title = "", MessageBoxButtons response = MessageBoxButtons.None, int options = 0)
{
msgBox.SetActive(show);
header.text = title;
body.text = msg;
btnYes.gameObject.SetActive(false);
btnNo.gameObject.SetActive(false);
btnCancel.gameObject.SetActive(false);
btnOK.gameObject.SetActive(false);
if (response == MessageBoxButtons.YesNo) { btnYes.gameObject.SetActive(true); btnNo.gameObject.SetActive(true); }
if (response == MessageBoxButtons.YesNoCancel) { btnYes.gameObject.SetActive(true); btnNo.gameObject.SetActive(true); btnCancel.gameObject.SetActive(true); }
if (response == MessageBoxButtons.OK) { btnOK.gameObject.SetActive(true); }
if (response == MessageBoxButtons.Custom) { if (options == 1) { btnOK.gameObject.SetActive(true); } else if (options == 2) { btnYes.gameObject.SetActive(true); btnNo.gameObject.SetActive(true); } else if (options == 3) { btnYes.gameObject.SetActive(true); btnNo.gameObject.SetActive(true); btnCancel.gameObject.SetActive(true); } }
}
static void DefaultActionCancel()
{
ToggleMessageBoxDisplay(false);
}
#endregion
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class menuScript : MonoBehaviour {
//the game object hold the GameController GameObject
public GameObject game;
//the mainMenu object hold the RawImage that have the buttons of the menu as it's child
public RawImage mainMenu;
//this function will be called when the player prass the start button on the main menu , it disactivat the main menu and active the GameController
public void startGame()
{
mainMenu.gameObject.SetActive(false);
game.gameObject.SetActive(true);
}
//this function will be called when the player prass the quit button on the main menu , it will step the game
public void quit(){
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying=false;
#else
Application.Quit();
#endif
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
/// <summary>
/// Listbox UI Tool
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[AddComponentMenu("UI Tools/Combobox (Advanced Dropbox)", 1), DisallowMultipleComponent]
public class Combobox : MonoBehaviour
{
[Header("Design")]
[Tooltip("The direction to display the Dropdown list. By default, this is set to 'Below'.")]
public DropdownDirection direction = DropdownDirection.Below;
[Tooltip("The height of each element inside the Dropdown list.")]
public float elementHeight;
[Tooltip("If checked, the checkmark image to the far-left of the text will be hidden for the selected element in the Dropdown list.")]
public bool hideCheckmark;
[Tooltip("If checked, the Dropdown will adjust to accomidate for the Item Image on the far-right.")]
public bool useThumbnailImage = true;
[Tooltip("If checked, the selected element in the Dropdown list will remain highlighted, even after mouse events are active on it.")]
public bool keepSelectionHighlighted = true;
[Space]
public CustomData theme = new CustomData();
[Space]
public Init initalization = new Init();
private Dropdown dropdown;
private Toggle toggle;
private RectTransform toggleRT;
private Image image;
private Text text;
private ScrollRect scrollRect;
private ColorBlock colors;
[System.Serializable]
public class CustomData
{
[Tooltip("The background color of the actual selection box.")]
public Color selection;
[Tooltip("The background color of the element when no mouse events are influencing it.")]
public Color element;
[Tooltip("The background color of the element the mouse is under.")]
public Color highlight;
[Tooltip("The background color of the clicked or 'pressed' element.")]
public Color pressed;
[Tooltip("The color of the Text Elements in the Dropbox.")]
public Color text;
[Header("Scrollbar Specific")]
[Tooltip("If checked, the Scoll Space variable will be a ratio of the Scrollbar's color. It will always be dimmer/darker than the Scrollbar color.")]
public bool dimWithScrollbar = true;
[Tooltip("The color of the scrollbar visual itself.")]
public Color scrollbar;
[Tooltip("The color of the scrollable space.")]
public Color scrollSpace;
[Space]
public FontData fontData = new FontData();
};
[System.Serializable]
public class OptionData
{
[Tooltip("Normal = Regular Element text.\nHeader = Special Element (non-clickable) text.\nSplitter = Special Element (non-clickable) image")]
public OptionType type;
public string text;
public Sprite image;
/// <summary>
/// Create an OptionData Element with passed data.
/// </summary>
/// <param name="text">Text to set in the element</param>
/// <param name="type">The type of OptionData Element this pertains to</param>
public OptionData(string text, OptionType type)
{
this.type = type;
this.text = text;
}
/// <summary>
/// Create an OptionData Element with passed data.
/// </summary>
/// <param name="text">Text to set in the element</param>
public OptionData(string text)
{
this.text = text;
}
/// <summary>
/// Create an OptionData Element with passed data.
/// </summary>
/// <param name="image">Image to set in the element</param>
/// <param name="type">The type of OptionData Element this pertains to</param>
public OptionData(Sprite image, OptionType type)
{
this.type = type;
this.image = image;
}
/// <summary>
/// Create an OptionData Element with passed data.
/// </summary>
/// <param name="image">Image to set in the element</param>
public OptionData(Sprite image)
{
this.image = image;
}
/// <summary>
/// Create an OptionData Element with passed data.
/// </summary>
/// <param name="text">Text to set in the element</param>
/// <param name="image">Image to set in the element</param>
/// <param name="type">The type of OptionData Element this pertains to</param>
public OptionData(string text, Sprite image, OptionType type)
{
this.type = type;
this.text = text;
this.image = image;
}
/// <summary>
/// Create an OptionData Element with passed data.
/// </summary>
/// <param name="text">Text to set in the element</param>
/// <param name="image">Image to set in the element</param>
public OptionData(string text, Sprite image)
{
this.text = text;
this.image = image;
}
};
[System.Serializable]
public class Init
{
[Tooltip("If checked, the options list below will update the Dropdown Options list when first entering Play Mode (on Awake). This can be ignored (left unchecked) for manual initialization.")]
public bool initalizeOnAwake;
[Tooltip("If checked, the options list below will update the Dropdown Options list in the Editor (outside Play Mode). It will also prevent Headers from being selected as the first element.")]
public bool updateInEditor;
[Tooltip("The color to apply to Special Elements, such as Headers and (optionally) Splitters.")]
public Color specialColor = Color.white;
[Tooltip("Should the Special Color be applied to the Splitter image, as well as the Header text?")]
public bool applyColorToSplitters;
[Tooltip("List all elements to be created for initialization.")]
public List<OptionData> options;
};
public enum DropdownDirection { Below, Above, Left, Right };
public enum OptionType { Normal, Header, Splitter };
#region Private Functions
void OnValidate()
{
if (dropdown == null) { dropdown = GetComponent<Dropdown>(); }
if (toggle == null) { toggle = transform.Find("Template").GetComponentInChildren<Toggle>(); }
if (toggleRT == null) { toggleRT = toggle.GetComponent<RectTransform>(); }
if (image == null) { image = toggle.transform.GetChild(0).GetComponent<Image>(); }
if (text == null) { text = toggle.transform.GetChild(2).GetComponent<Text>(); }
if (scrollRect == null) { scrollRect = transform.Find("Template").GetComponent<ScrollRect>(); }
if (initalization.updateInEditor)
{
SetOptions(initalization.options);
if (dropdown.value == 0 && dropdown.options.Count > 1 && dropdown.options[0].text.EndsWith("[h]")) { dropdown.value = 1; }
}
if (elementHeight <= 0f)
{
elementHeight = toggleRT.rect.height;
}
else
{
RectTransform element = toggle.transform.parent.GetComponent<RectTransform>();
element.anchoredPosition = Vector2.zero;
element.sizeDelta = new Vector2(element.sizeDelta.x, elementHeight);
transform.Find("Template").GetComponent<ScrollRect>().scrollSensitivity = elementHeight;
}
if (theme.fontData.font == null)
{
theme.fontData.alignByGeometry = text.alignByGeometry;
theme.fontData.alignment = text.alignment;
theme.fontData.bestFit = text.resizeTextForBestFit;
theme.fontData.font = text.font;
theme.fontData.fontSize = text.fontSize;
theme.fontData.fontStyle = text.fontStyle;
theme.fontData.horizontalOverflow = text.horizontalOverflow;
theme.fontData.lineSpacing = text.lineSpacing;
theme.fontData.maxSize = text.resizeTextMaxSize;
theme.fontData.minSize = text.resizeTextMinSize;
theme.fontData.richText = text.supportRichText;
theme.fontData.verticalOverflow = text.verticalOverflow;
}
else
{
text.alignByGeometry = theme.fontData.alignByGeometry;
text.alignment = theme.fontData.alignment;
text.resizeTextForBestFit = theme.fontData.bestFit;
text.font = theme.fontData.font;
text.fontSize = theme.fontData.fontSize;
text.fontStyle = theme.fontData.fontStyle;
text.horizontalOverflow = theme.fontData.horizontalOverflow;
text.lineSpacing = theme.fontData.lineSpacing;
text.resizeTextMaxSize = theme.fontData.maxSize;
text.resizeTextMinSize = theme.fontData.minSize;
text.supportRichText = theme.fontData.richText;
text.verticalOverflow = theme.fontData.verticalOverflow;
}
colors = dropdown.colors;
if (theme.selection == Color.clear)
{
theme.selection = toggle.colors.normalColor;
}
else { colors.normalColor = theme.selection; dropdown.colors = colors; }
if (theme.element == Color.clear)
{
theme.element = image.color;
}
else { image.color = theme.element; }
colors = toggle.colors;
if (theme.highlight == Color.clear)
{
theme.highlight = toggle.colors.highlightedColor;
}
else { colors.highlightedColor = theme.highlight; toggle.colors = colors; }
if (theme.pressed == Color.clear)
{
theme.pressed = toggle.colors.pressedColor;
}
else { colors.pressedColor = theme.pressed; toggle.colors = colors; }
if (theme.text == Color.clear)
{
theme.text = text.color;
}
else { text.color = theme.text; }
colors = scrollRect.verticalScrollbar.colors;
if (theme.scrollbar == Color.clear)
{
theme.scrollbar = scrollRect.verticalScrollbar.colors.normalColor;
theme.scrollSpace = theme.scrollbar * 0.45f;
theme.scrollSpace.a = theme.scrollbar.a;
}
else
{
colors.normalColor = theme.scrollbar;
scrollRect.verticalScrollbar.colors = colors;
if (theme.dimWithScrollbar)
{
theme.scrollSpace = theme.scrollbar * 0.45f;
theme.scrollSpace.a = theme.scrollbar.a;
}
scrollRect.verticalScrollbar.transform.GetComponent<Image>().color = theme.scrollSpace;
}
}
void Awake()
{
dropdown = GetComponent<Dropdown>();
transform.Find("Template").GetComponent<Image>().enabled = false; //hide background of dropdown list
if (initalization.initalizeOnAwake)
{
SetOptions(initalization.options);
}
}
private void Update()
{
if (EventSystem.current.currentSelectedGameObject == dropdown.gameObject)
{
EventSystem.current.SetSelectedGameObject(dropdown.transform.GetChild(0).gameObject);
Invoke("UpdateDropdown", 0.15f); //delay update to allow Dropdown List to be created by Dropdown event (Unity)
}
//prevent headers from appearing as default on selection 0
if (dropdown.value == 0 && dropdown.options[0].text.EndsWith("[h]") && dropdown.options.Count > 1) { dropdown.value = 1; }
}
void UpdateDropdown()
{
RectTransform dropdownDisplay = null;
try
{
dropdownDisplay = dropdown.transform.Find("Dropdown List").GetComponent<RectTransform>();
}
catch { UpdateDropdown(); return; }
if (dropdownDisplay != null)
{
//direction
Vector2 containerSize = GetComponent<RectTransform>().rect.size;
float dropdownHeight = dropdownDisplay.rect.height;
if(direction == DropdownDirection.Below) { dropdownDisplay.anchoredPosition = new Vector2(0f, 2f); }
else if (direction == DropdownDirection.Above) { dropdownDisplay.anchoredPosition = new Vector2(0f, (containerSize.y + dropdownHeight) - 2f); }
else if (direction == DropdownDirection.Left) { dropdownDisplay.anchoredPosition = new Vector2(-containerSize.x + 2f, containerSize.y); }
else if (direction == DropdownDirection.Right) { dropdownDisplay.anchoredPosition = new Vector2(containerSize.x - 2f, containerSize.y); }
for (int i = 1; i < dropdownDisplay.GetChild(0).GetChild(0).childCount; i++)
{
Transform child = dropdownDisplay.GetChild(0).GetChild(0).GetChild(i);
//headers
if (child.name.EndsWith("[h]"))
{
child.GetComponentInChildren<Text>().text = child.GetComponentInChildren<Text>().text.Replace("[h]", string.Empty);
child.GetComponent<Toggle>().interactable = false;
ColorBlock colors = child.GetComponent<Toggle>().colors;
colors.normalColor = initalization.specialColor;
colors.disabledColor = colors.normalColor;
child.GetComponent<Toggle>().colors = colors;
}
//splitters
else if (child.name.EndsWith("[s]"))
{
if (child.childCount == 4) { child.GetChild(3).gameObject.SetActive(false); }
child.GetChild(0).GetComponent<Image>().sprite = dropdown.options[i - 1].image;
child.GetChild(0).GetComponent<Image>().color = Color.white;
child.GetComponentInChildren<Text>().text = string.Empty;
child.GetComponent<Toggle>().interactable = false;
ColorBlock colors = child.GetComponent<Toggle>().colors;
if (initalization.applyColorToSplitters) { colors.normalColor = initalization.specialColor; }
colors.disabledColor = colors.normalColor;
child.GetComponent<Toggle>().colors = colors;
}
//checkmarks... Check
child.GetChild(1).GetComponent<Image>().enabled = !hideCheckmark;
//thumbnails
if (child.childCount == 4 && useThumbnailImage)
{
Vector2 pos = child.GetChild(2).GetComponent<RectTransform>().offsetMax;
pos.x -= child.GetChild(3).GetComponent<RectTransform>().rect.width;
child.GetChild(2).GetComponent<RectTransform>().offsetMax = pos;
}
}
if (keepSelectionHighlighted)
{
Toggle dropdownElement = dropdownDisplay.GetChild(0).GetChild(0).GetChild(dropdown.value + 1).GetComponent<Toggle>();
ColorBlock colors = dropdownElement.colors;
colors.normalColor = colors.pressedColor;
dropdownElement.colors = colors;
}
}
}
#endregion
#region Common Functions
/// <summary>
/// Add a Header element to the Options List of this Dropdown.
/// Headers are considered "Special Elements" and are not selectable in the Dropdown.
/// </summary>
/// <param name="text"></param>
public void AddHeader(string text)
{
dropdown.AddOptions(new List<Dropdown.OptionData>() { new Dropdown.OptionData(text + "[h]") });
}
/// <summary>
/// Add a Splitter image element to the Options List of this Dropdown.
/// Splitters are considered "Special Elements" and are not selectable in the Dropdown.
/// </summary>
/// <param name="splitter"></param>
public void AddSplitter(Sprite splitter)
{
dropdown.AddOptions(new List<Dropdown.OptionData>() { new Dropdown.OptionData("[s]", splitter) });
}
/// <summary>
/// Add an Item as an element to the Options List of this Dropdown.
/// </summary>
/// <param name="data">The data to pull information from for this element. Only the text and/or image is read.</param>
public void AddItem(OptionData data)
{
dropdown.AddOptions(new List<Dropdown.OptionData>() { new Dropdown.OptionData(data.text, data.image) });
}
/// <summary>
/// Add multiple elements to the Options List of this Dropdown.
/// This method allows you to add Special Elements (Headers or Splitters) in addition to regular text/image provided by Dropdown.OptionData already.
/// </summary>
/// <param name="list">List of information to read from, and add as elements.</param>
public void AddOptions(List<OptionData> list)
{
for(int i = 0; i < list.Count; i++)
{
if(list[i].type == OptionType.Header) { AddHeader(list[i].text); }
else if (list[i].type == OptionType.Splitter) { AddSplitter(list[i].image); }
else if (list[i].type == OptionType.Normal) { AddItem(list[i]); }
}
}
/// <summary>
/// Set the Options List in this Dropdown to the list of elements provided.
/// This method allows you to add Special Elements (Headers or Splitters) in addition to regular text/image provided by Dropdown.OptionData already.
/// </summary>
/// <param name="list">List of information to read from, and add as elements. This will be the list that Options will be set to.</param>
public void SetOptions(List<OptionData> list)
{
dropdown.options.Clear();
for (int i = 0; i < list.Count; i++)
{
if (list[i].type == OptionType.Header) { AddHeader(list[i].text); }
else if (list[i].type == OptionType.Splitter) { AddSplitter(list[i].image); }
else if (list[i].type == OptionType.Normal) { AddItem(list[i]); }
}
}
#endregion
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using UnityEngine.UI;
/// <summary>
/// Draggable UI Tool - Extention Tool
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[AddComponentMenu("UI Tools/Extentions/Draggable", 0), DisallowMultipleComponent]
public class Draggable : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler, IDragHandler
{
[Tooltip("The only space dragging of this object is allowed. If left empty, then anywhere is considered drag space.")]
public RectTransform dragSpace;
[Tooltip("Prevents the dragging object from leaving the canvas.")]
public bool screenBound;
[Tooltip("The canvas to keep the dragging object inside of.")]
public Canvas canvas;
private List<GameObject> hoveredElements;
private RectTransform hovered;
private Vector3 startPoint;
private RectTransform rect;
private RectTransform canvasBounds;
private void Start()
{
rect = GetComponent<RectTransform>();
if(canvas == null) { canvas = GetComponent<MaskableGraphic>().canvas; }
canvasBounds = canvas.GetComponent<RectTransform>();
}
private void Update()
{
if (dragSpace != null && hoveredElements.Contains(dragSpace.gameObject))
{
for(int i = 0; i < hoveredElements.Count; i++)
{
if(hoveredElements[i] == dragSpace.gameObject) { hovered = hoveredElements[i].GetComponent<RectTransform>(); }
}
}
else { hovered = null; }
}
public void OnPointerEnter(PointerEventData eventData)
{
hoveredElements = eventData.hovered;
}
public void OnPointerExit(PointerEventData eventData)
{
hovered = null;
}
public void OnPointerDown(PointerEventData eventData)
{
if (dragSpace == null) { startPoint = Vector2.zero; }
else { startPoint = dragSpace.localPosition; }
}
public void OnDrag(PointerEventData eventData)
{
if (dragSpace == null)
{
AllowDrag();
}
else
{
if (hovered != null && hovered == dragSpace)
{
AllowDrag();
}
}
}
void AllowDrag()
{
Vector3 pos = Input.mousePosition;
Vector3 finalPos;
pos.z = rect.position.z;
finalPos = pos - startPoint;
if (screenBound)
{
finalPos.x = Mathf.Clamp(finalPos.x, rect.rect.width / 2f, canvasBounds.rect.width - (rect.rect.width / 2f));
finalPos.y = Mathf.Clamp(finalPos.y, rect.rect.height / 2f, canvasBounds.rect.height - (rect.rect.height / 2f));
}
rect.position = finalPos;
}
}<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using System.Collections.Generic;
/// <summary>
/// Option Selector UI Tool
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[AddComponentMenu("UI Tools/Option Selector", 1), DisallowMultipleComponent, Serializable]
public class OptionSelector : MonoBehaviour
{
#region Common Variables
[Tooltip("Determines if the up/down will continue from the beginning once it reaches the end, or stop.")]
public bool loopback;
public DataType dataType;
[Tooltip("Determines if 'Best Fit' applies to the text to fit it in its container.")]
public bool fitText;
#endregion
#region Events
public delegate void OnTypeChangedDelegate(DataType type);
public delegate void OnValueChangedDelegate(object value);
/// <summary>
/// Called every time the dataType is changed. You can subscribe your own calls to this event in Start or Awake.
/// </summary>
public event OnTypeChangedDelegate OnTypeChanged;
/// <summary>
/// Called every time the up/down arrows are pressed. You can subscribe your own calls to this event in Start or Awake.
/// </summary>
public event OnValueChangedDelegate OnValueChanged;
#endregion
#region Variable Data Types
//Numeric
public int minInt, maxInt;
//Decimal
public float minFloat, maxFloat;
[Tooltip("How much to increase the value by, each iteration.")]
public float increment = 0.5f;
//String
public List<string> stringValues = new List<string>();
//Enum
public Enum enumType;
//Object
public List<UnityEngine.Object> objectValues = new List<UnityEngine.Object>();
[Tooltip("Should the Object type also be displayed?")]
public bool includeType = true;
//Custom
public List<object> customValues = new List<object>();
public int valueIndex { get; set; }
#endregion
#region Private (class) Variables
public enum DataType { Numeric, Decimal, String, Enum, Object, Custom };
private InputField option;
private float floatValueIndex;
private Array enumArray;
#endregion
#region Private (class) Functions
void Awake()
{
option = GetComponent<InputField>();
UpdateSelector();
}
public void BtnUp()
{
valueIndex++;
UpdateSelector(1);
}
public void BtnDown()
{
valueIndex--;
UpdateSelector(-1);
}
void UpdateSelector(int add)
{
if (fitText) { option.textComponent.horizontalOverflow = HorizontalWrapMode.Wrap; }
if (dataType == DataType.Numeric)
{
valueIndex = Mathf.Clamp(valueIndex, minInt, maxInt);
option.contentType = InputField.ContentType.IntegerNumber;
option.text = (valueIndex).ToString();
if (OnValueChanged != null) { OnValueChanged(valueIndex); }
}
else if (dataType == DataType.Decimal)
{
if (add > 0) { floatValueIndex += increment; } else { floatValueIndex -= increment; }
floatValueIndex = Mathf.Clamp(floatValueIndex, minFloat, maxFloat);
option.contentType = InputField.ContentType.DecimalNumber;
option.text = (floatValueIndex).ToString();
if (OnValueChanged != null) { OnValueChanged(floatValueIndex); }
}
else if (dataType == DataType.String)
{
valueIndex = Mathf.Clamp(valueIndex, 0, stringValues.Count - 1);
string value = stringValues[valueIndex];
option.contentType = InputField.ContentType.Standard;
option.text = value;
if (OnValueChanged != null) { OnValueChanged(value); }
}
else if (dataType == DataType.Enum)
{
valueIndex = Mathf.Clamp(valueIndex, 0, enumArray.Length - 1);
Enum value = (Enum)enumArray.GetValue(valueIndex);
option.contentType = InputField.ContentType.Standard;
option.text = value.ToString();
if (OnValueChanged != null) { OnValueChanged(value); }
}
else if (dataType == DataType.Object)
{
valueIndex = Mathf.Clamp(valueIndex, 0, objectValues.Count - 1);
UnityEngine.Object value = objectValues[valueIndex];
option.contentType = InputField.ContentType.Standard;
option.text = (includeType) ? value.ToString() : value.name;
if (OnValueChanged != null) { OnValueChanged(value); }
}
else if (dataType == DataType.Custom)
{
valueIndex = Mathf.Clamp(valueIndex, 0, customValues.Count - 1);
object value = customValues[valueIndex];
option.contentType = InputField.ContentType.Custom;
option.text = value.ToString();
if (OnValueChanged != null) { OnValueChanged(value); }
}
}
void SetRange(Vector2Int range)
{
minInt = range.x;
maxInt = range.y;
} //Apply int range
void SetRange(Vector2 range)
{
minFloat = range.x;
maxFloat = range.y;
} //Apply float range
#endregion
#region Public Functions (Overloads)
/// <summary>
/// Update the Selector to show the relevant data. Automatically called on Awake and every time the Inspector or the dataType is changed.
/// The value updated will always be "floored" or reset to lowest-index.
/// </summary>
public void UpdateSelector()
{
valueIndex = -1;
floatValueIndex = minFloat - increment;
if (fitText) { option.textComponent.horizontalOverflow = HorizontalWrapMode.Wrap; }
BtnDown();
}
/// <summary>
/// Set the Enum to be used by the Selector.
/// </summary>
/// <param name="enumData">The enum to use. This can be any type of enum data. The order of the data will be the order of the enums values.</param>
public void SetEnumType(Enum enumData)
{
enumType = enumData;
enumArray = Enum.GetValues(enumType.GetType());
}
/// <summary>
/// Set the Enum to be used by the Selector.
/// </summary>
/// <param name="enumData">The enum to use. This can be any type of enum data. The order of the data will be the order of the enums values.</param>
/// <param name="applyTypeChange">Should the type be auto-changed to DataType.Enum when setting the Enum data as well?</param>
public void SetEnumType(Enum enumData, bool applyTypeChange = false)
{
if (applyTypeChange) { dataType = DataType.Enum; UpdateSelector(); }
enumType = enumData;
enumArray = Enum.GetValues(enumType.GetType());
}
/// <summary>
/// Set the Custom datatype to the specified list of object data.
/// </summary>
/// <param name="objectData">The object list data that the Selector will use to iterate through.</param>
public void SetCustomType(List<object> objectData)
{
customValues = objectData;
}
/// <summary>
/// Set the Custom data type to the specified list of object data.
/// </summary>
/// <param name="objectData">The object list data that the Selector will use to iterate through.</param>
/// <param name="applyTypeChange">Should the type be auto-changed to DataType.Object when setting the Object data as well?</param>
public void SetCustomType(List<object> objectData, bool applyTypeChange = false)
{
if (applyTypeChange) { dataType = DataType.Object; UpdateSelector(); }
customValues = objectData;
}
/// <summary>
/// Set the values and data type to a Numeric (int) range.
/// </summary>
/// <param name="range">The min (x) and max (y) range for Numeric values.</param>
public void SetType(Vector2Int range)
{
dataType = DataType.Numeric;
SetRange(range);
}
/// <summary>
/// Set the values and data type to a Decimal (float) range.
/// </summary>
/// <param name="range">The min (x) and max (y) range for Decimal values.</param>
public void SetType(Vector2 range)
{
dataType = DataType.Decimal;
SetRange(range);
}
/// <summary>
/// Set the String data type to the specified list of string data.
/// </summary>
/// <param name="stringList">The list of strings that the Selector will use to iterate through.</param>
public void SetType(List<string> stringList)
{
dataType = DataType.String;
stringValues = stringList;
}
/// <summary>
/// Set the Object data type to the specified list of Unity Object data.
/// </summary>
/// <param name="objectList">The list of Unity Object that the Selector will use to iterate through.</param>
public void SetType(List<UnityEngine.Object> objectList)
{
dataType = DataType.Object;
objectValues = objectList;
}
#endregion
#region Editor Event
//Used by the Editor to call OnTypeChanged event.
public void FireEvent()
{
if (OnTypeChanged != null) { OnTypeChanged(dataType); }
if (!IsInvoking("UpdateSelector")) { Invoke("UpdateSelector", 0.01f); } //prevents Layout from attempting to do Repaint jobs, after Unity updates all events
}
#endregion
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class doorScript : MonoBehaviour {
public Texture opendoor;
public static doorScript ins;
void Awake(){
//singlize the object door so i can call the same door from any class
ins=this;
//set the door angel to face the main camera
this.transform.Rotate(new Vector3(0,180,0));
}
//this function called when the player take the key
public void openDoor(){
this.GetComponent<MeshCollider>().enabled=true;
this.GetComponent<MeshRenderer>().material.SetTexture("_MainTex",opendoor);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Boomberman_playerMovement : MonoBehaviour
{
Vector3 pos;
Dictionary<string,bool> canMove;
public GameObject boomb;
// Update is called once per frame
void Update()
{
//refrence for the object ins in gameController class so the playerMovement can deal with the gameController
Boomberman_gameController temp = Boomberman_gameController.ins;
//call the allowMoves function to know what dirction can the player go
canMove = temp.allowMoves("player");
//call the getPlayerPos function to know the indexs of player in thegame array in gameController class
KeyValuePair<int, int> playerPos = temp.getPlayerPos();
int k = playerPos.Key, v = playerPos.Value;
pos = gameObject.transform.position;
//check the input and the canMove List to move the player
if (Input.GetKeyDown(KeyCode.UpArrow)&&canMove["up"])
{
gameObject.transform.position = new Vector3(pos.x, pos.y, pos.z + 1f);
temp.setPlayerPos(k - 1, v);
}
if (Input.GetKeyDown(KeyCode.DownArrow) && canMove["down"])
{
gameObject.transform.position = new Vector3(pos.x, pos.y, pos.z - 1f);
temp.setPlayerPos(k + 1, v);
}
if (Input.GetKeyDown(KeyCode.LeftArrow)&&canMove["left"]){
gameObject.transform.position = new Vector3(pos.x-1f, pos.y, pos.z);
temp.setPlayerPos(k , v-1);
}
if(Input.GetKeyDown(KeyCode.RightArrow)&&canMove["right"]){
gameObject.transform.position = new Vector3(pos.x +1f, pos.y, pos.z);
temp.setPlayerPos(k, v+1);
}
if (Input.GetKeyDown(KeyCode.Space))
{
if (temp.canPutBomb())
{
GameObject b = Instantiate(boomb, pos, Quaternion.identity);
if(b!=null){
temp.addBomb();
}
}
}
}
private void OnTriggerEnter(Collider other)
{
Boomberman_gameController temp = Boomberman_gameController.ins;
switch (other.gameObject.tag)
{
case "doubleBomb":
temp.activeDuobleBomb();
Destroy(other.gameObject);
break;
case "bigBomb":
temp.activeBigBomb();
Destroy(other.gameObject);
break;
case "key":
doorScript.ins.openDoor();
Destroy(other.gameObject);
break;
case "Finish":
temp.gameOver("win");
break;
case "enemy":
Destroy(gameObject);
break;
}
}
private void OnDestroy()
{
Boomberman_gameController.ins.gameOver("lost");
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
/// <summary>
/// Tooltip UI Tool
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[AddComponentMenu("UI Tools/Extentions/Tooltip", 1), DisallowMultipleComponent]
public class Tooltip : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler
{
/// <summary>
/// Allows any UI object to accept a tooltip.
/// </summary>
#region Variables
[Tooltip("The tooltip prefab to use as a template. Depending on the prefab used, the style, formatting, and preferences below may not all be applicable.")]
public TooltipModal tooltipTarget;
[Tooltip("The image to display next to the header of the tooltip. This will have no effect on Tooltip Targets without an icon.")]
public Sprite icon;
[Tooltip("The title to display in the header of the tooltip. This will have no effect on Tooltip Targets without a header.")]
public string header;
[TextArea(3, 5), Tooltip("The block of text to display in the body of the tooltip.")]
public string text;
[Space, Tooltip("Determines if the tooltip will follow the mouse on the object or stay in a fixed position.")]
public bool followMouse;
[Tooltip("Determines if the tooltip will only be shown if the object it belongs to is clicked rather than hovered.")]
public bool displayOnClick;
[Tooltip("Determines the default fixed positioning of the tooltip, relative to the object.")]
public TooltipAlignment alignment = TooltipAlignment.Right;
[Tooltip("Additional positioning to add to the placement of the tooltip. No offset will place the top-left corner of the tooltip to the cursor or object.")]
public Vector2 offset;
[Space, Tooltip("Events to fire when the mouse enters the object, and the tooltip is shown.")]
public UnityEvent onMouseEnter;
[Tooltip("Events to fire when the mouse leaves the object, and the tooltip is hidden.")]
public UnityEvent onMouseExit;
[Tooltip("Events to fire when the mouse clicks the object, and the tooltip is shown. These events will only be fired when displayOnClick is on.")]
public UnityEvent onMouseClick;
private static bool isValidated;
private RectTransform rectTransform;
#endregion
private void Awake()
{
if (isValidated == false)
{
if (tooltipTarget == null) { Debug.LogError("Tooltip Target is not set in the Inspector. A ToolipModal prefab must be assigned for this tooltip to function.", this); return; }
else { if (!tooltipTarget.gameObject.activeInHierarchy) { tooltipTarget = Instantiate(tooltipTarget, transform.parent); Debug.LogWarning("The prefab TooltipModal was used instead of an instance. An instance of the prefab has been created and assigned."); } }
if (tooltipTarget.gameObject.activeInHierarchy) { tooltipTarget.HideTooltip(); isValidated = true; }
else { tooltipTarget.gameObject.SetActive(true); tooltipTarget.HideTooltip(); isValidated = true; }
rectTransform = GetComponent<RectTransform>();
}
}
#region Mouse Events
public void OnPointerClick(PointerEventData eventData)
{
if (displayOnClick && tooltipTarget != null)
{
tooltipTarget.SetTarget(GetComponent<RectTransform>());
tooltipTarget.ShowTooltip(text, header, icon, followMouse, offset, alignment, rectTransform);
if (onMouseClick != null) { onMouseClick.Invoke(); }
}
}
public void OnPointerEnter(PointerEventData eventData)
{
if (!displayOnClick && tooltipTarget != null)
{
tooltipTarget.SetTarget(GetComponent<RectTransform>());
tooltipTarget.ShowTooltip(text, header, icon, followMouse, offset, alignment, rectTransform);
if (onMouseEnter != null) { onMouseEnter.Invoke(); }
}
}
public void OnPointerExit(PointerEventData eventData)
{
if (tooltipTarget != null)
{
tooltipTarget.HideTooltip();
if (onMouseExit != null) { onMouseExit.Invoke(); }
}
}
#endregion
}
public enum TooltipAlignment { Default, Left, Right, Above, Below };
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class frerscript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Destroy(gameObject, 0.8f);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag!="border"&&other.gameObject.tag!="Finish"&&other.gameObject.tag!="pickup"&&other.gameObject.tag!="key"){
Destroy(other.gameObject);
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Calendar UI Tool - Data Class
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
public class ButtonEventData
{
public Sprite eventImage;
public List<ButtonEvent> buttonEvents = new List<ButtonEvent>();
/// <summary>
/// Automatically set when Calendar.OnCalendarUpdated
/// </summary>
public Button button;
public ButtonEventData()
{
buttonEvents = new List<ButtonEvent>();
}
};
public class ButtonEvent
{
public string name;
public DateTime time;
public Sprite image;
public bool useAsPreviewPicture;
public ButtonEvent(string eventName, DateTime eventDate)
{
name = eventName;
time = eventDate;
}
public ButtonEvent(string eventName, DateTime eventDate, Sprite eventImage)
{
name = eventName;
time = eventDate;
image = eventImage;
}
};
public class SelectedButton
{
public Button gameObject;
public DateTime date;
public ButtonEventData eventData;
};
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
/// <summary>
/// UI Focus UI Tool - Extention Tool
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[AddComponentMenu("UI Tools/Extentions/UI Focus", 2), DisallowMultipleComponent]
public class UIFocus : MonoBehaviour
{
[Tooltip("If set, the specified UI object will be set as the initial focused object in the event system, on start.")]
public RectTransform initialFocus;
[Tooltip("If set, everytime Unselect() is called, this object will be the focus set in the event system.")]
public RectTransform defaultFocus;
/// <summary>
/// Get or set the currently selected/focused gameobject of the UI Event system.
/// </summary>
public GameObject Focus { get { return EventSystem.current.currentSelectedGameObject; } set { if (Focus != value) { EventSystem.current.SetSelectedGameObject(value); Focus = value; } } }
/// <summary>
/// A direct reference to the UI Focus class, from the global/static call.
/// </summary>
public static UIFocus reference { get; protected set; }
void Awake()
{
reference = this;
if (defaultFocus == null) { try { defaultFocus = FindObjectOfType<Text>().GetComponent<RectTransform>(); } catch { defaultFocus = FindObjectOfType<RectTransform>(); } }
EventSystem.current.SetSelectedGameObject((initialFocus != null) ? initialFocus.gameObject : null);
}
/// <summary>
/// Unselect the currently selected UI element from the event system.
/// </summary>
/// <param name="selectDefault">Determines if the event system should select the defaultFocus or set to null</param>
public void Unselect(bool selectDefault = true)
{
if (selectDefault)
{
if (defaultFocus == null) { try { defaultFocus = FindObjectOfType<Text>().GetComponent<RectTransform>(); } catch { defaultFocus = FindObjectOfType<RectTransform>(); } }
Focus = (defaultFocus != null) ? defaultFocus.gameObject : null;
}
else
{
Focus = null;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Listbox UI Tool
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[AddComponentMenu("UI Tools/Radio Group", 0), DisallowMultipleComponent]
public class RadioButtonGroup : MonoBehaviour
{
[Tooltip("Optional. Set a radio button as default to be selected on start. Leaving blank will cause no buttons to be selected at start.")]
public Toggle defaultRadioButton;
/// <summary>
/// Automatically sets to the last radio button selected.
/// </summary>
[HideInInspector]
public Toggle selectedRadioButton;
private ToggleGroup defaultToggleGroup;
private Toggle defaultToggleButton;
void Awake()
{
defaultToggleGroup = GetComponent<ToggleGroup>();
if (transform.childCount > 0)
{
Toggle firstToggle = transform.GetChild(0).GetComponent<Toggle>();
if (firstToggle != null) { defaultToggleButton = firstToggle; }
}
UncheckAllAndSubscribe();
ReassignRadioGroup(defaultToggleGroup);
SelectRadioButton(defaultRadioButton);
}
void UncheckAllAndSubscribe()
{
foreach (Toggle radio in transform.GetComponentsInChildren<Toggle>())
{
radio.isOn = false;
radio.onValueChanged.AddListener(delegate { SetSelectedToCurrent(radio); });
}
}
void SetSelectedToCurrent(Toggle current)
{
if (current.isOn && selectedRadioButton != current) { selectedRadioButton = current; }
}
#region Public Functions
/// <summary>
/// Sets the specified toggle as the currently selected radio button.
/// </summary>
/// <param name="radioButton">Toggle to select.</param>
public void SelectRadioButton(Toggle radioButton)
{
if(radioButton != null) { radioButton.isOn = true; }
}
/// <summary>
/// Set all radio buttons to the specified ToggleGroup. This is also automatically called when calling AddRadioButton.
/// </summary>
/// <param name="group">Toggle Group to reassign every radio button to.</param>
public void ReassignRadioGroup(ToggleGroup group)
{
foreach(Toggle radio in transform.GetComponentsInChildren<Toggle>())
{
radio.group = group;
}
}
/// <summary>
/// Add/Instantiate a radio button.
/// </summary>
public void AddRadioButton()
{
Instantiate(defaultToggleButton, transform);
ReassignRadioGroup(defaultToggleGroup);
}
/// <summary>
/// Add/Instantiate a radio button, at a set index.
/// </summary>
/// <param name="index">Index to insert this new radio button at.</param>
public void AddRadioButton(int index)
{
Instantiate(defaultToggleButton, transform).transform.SetSiblingIndex(index);
ReassignRadioGroup(defaultToggleGroup);
}
/// <summary>
/// Add/Instantiate a radio button, with a set name.
/// </summary>
/// <param name="name">Name to set this new radio button to.</param>
public void AddRadioButton(string name)
{
Instantiate(defaultToggleButton, transform).name = name;
ReassignRadioGroup(defaultToggleGroup);
}
/// <summary>
/// Add/Instantiate a radio button, with a set name at index.
/// </summary>
/// <param name="name">Name to set this new radio button to.</param>
/// <param name="index">Index to insert this new radio button at.</param>
public void AddRadioButton(string name, int index)
{
Toggle toggle = Instantiate(defaultToggleButton, transform) as Toggle;
toggle.transform.name = name;
toggle.transform.SetSiblingIndex(index);
ReassignRadioGroup(defaultToggleGroup);
}
/// <summary>
/// Remove/Destroy a radio button. This will destroy the last indexed radio button by default.
/// </summary>
public void RemoveRadioButton()
{
if (transform.childCount > 0) { Destroy(transform.GetChild(transform.childCount - 1)); }
}
/// <summary>
/// Remove/Destroy a radio button at index.
/// </summary>
/// <param name="index">Index to remove a radio button from.</param>
public void RemoveRadioButton(int index)
{
if (transform.childCount > index) { Destroy(transform.GetChild(index)); }
}
#endregion
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Boomberman_gameController : MonoBehaviour
{
public GameObject floar;
public GameObject floarParent;
public GameObject border;
public GameObject borderParent;
public List<GameObject> pickups;
public GameObject enemy1;
public GameObject enemy2;
public GameObject enemy3;
public GameObject player;
public GameObject box;
public GameObject boxParent;
public Image bigBombImage;
public Image doubleBombImage;
GameObject[][] thegame;
public static Boomberman_gameController ins = null;
KeyValuePair<int, int> playerPos;
List<KeyValuePair<int, int>> enemyPos;
GameObject doorBox;
const int size = 17;
Vector3 Pos;
List<KeyValuePair<int, int>> boxPos;
float bigBombTimer = 0,doubleBombTimer=0;
int bombCount = 0,bombcapicity = 1, boxNum = 20;
bool bigBombIsActive = false;
// Use this for initialization
private void Awake()
{
ins = this;
bigBombImage.gameObject.SetActive(false);
doubleBombImage.gameObject.SetActive(false);
}
void Start()
{
//genarate indexs for the boxs
boxPos = new List<KeyValuePair<int, int>>();
enemyPos = new List<KeyValuePair<int, int>>();
while (boxNum > 0)
{
int a, b;
a = Random.Range(2, size - 1);
b = Random.Range(2, size - 1);
if ((a % 2 != 0 ^ b % 2 != 0) && boxPos.IndexOf(new KeyValuePair<int, int>(a, b)) < 0)
{
boxPos.Add(new KeyValuePair<int, int>(a, b));
boxNum--;
}
}
//instantiate a 2d array of gameobjects to hold the gameobjects like {borders,players,enemys,...}
thegame = new GameObject[size][];
for (int i = 0; i < size; i++)
{
thegame[i] = new GameObject[size];
}
//the point to start build the scene from
float startX = -8.5f, startY = -8.1f, startZ = -4.1f;
Pos = new Vector3(startX, startY, startZ);
//instantiate the groundfloar
GameObject temp=null;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
temp=Instantiate(floar, Pos, Quaternion.identity);
temp.transform.parent=floarParent.transform;
Pos = new Vector3(Pos.x, Pos.y, Pos.z - 1f);
}
Pos = new Vector3(Pos.x + 1f, Pos.y, -4.1f);
}
//free the object temp to use it in other places
temp=null;
//instantiate the borders and boxs
Pos = new Vector3(startX, startY + 1, startZ);
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (i == 0 || j == 0 || i == size - 1 || j == size - 1 || (i % 2 == 0 && j % 2 == 0))
{
thegame[i][j] = Instantiate(border, Pos, Quaternion.identity);
thegame[i][j].transform.parent=borderParent.transform;
}
else
{
if (boxPos.Contains(new KeyValuePair<int, int>(i, j)))
{
thegame[j][i] = Instantiate(box, Pos, Quaternion.identity);
thegame[j][i].transform.parent=boxParent.transform;
}
}
Pos = new Vector3(Pos.x, Pos.y, Pos.z - 1f);
}
Pos = new Vector3(Pos.x + 1f, Pos.y, -4.1f);
}
//instantiate pickups inside boxs as there child
while(pickups.Count>0)
{
int boxIndex=Random.Range(0,boxParent.transform.childCount);
temp=boxParent.transform.GetChild(boxIndex).gameObject;
if(temp.transform.childCount==0)
{
int pickupIndex=Random.Range(0,pickups.Count);
GameObject pickup=pickups[pickupIndex];
Pos=boxParent.transform.GetChild(boxIndex).position;
pickup= Instantiate(pickups[pickupIndex],Pos,Quaternion.identity);
pickup.transform.parent=temp.transform;
pickup.gameObject.SetActive(false);
if(pickup.gameObject.tag=="key")
{
pickup.transform.rotation = new Quaternion(0f, 200f, 200f, 20f);
pickup.transform.localScale = new Vector3(1.5f, 1.5f, 1.5f);
pickup.transform.position=new Vector3(Pos.x-0.5f,-7.5f,Pos.z-0.5f);
}
pickups.RemoveAt(pickupIndex);
}
}
//instantiate the player and the enemy
thegame[1][1] = Instantiate(player, new Vector3(startX + 1, startY + 1, startZ - 1), Quaternion.identity);
playerPos = new KeyValuePair<int, int>(1, 1);
enemy1 = Instantiate(enemy1, new Vector3(startX + 1, startY + 1, startZ - 15), new Quaternion(0f, 100f, 100f, 0f));
enemyPos.Add(new KeyValuePair<int, int>(15, 1));
enemy2 = Instantiate(enemy2, new Vector3(startX + 15, startY + 1, startZ - 15), new Quaternion(0f, 100f, 100f, 0f));
enemyPos.Add( new KeyValuePair<int, int>(15, 15));
enemy3 = Instantiate(enemy3, new Vector3(startX + 15, startY + 1, startZ - 1), new Quaternion(0f, 100f, 100f, 0f));
enemyPos.Add(new KeyValuePair<int, int>(1, 15));
}
//function that look for directiones that the object can move to it
public Dictionary<string,bool> allowMoves(string name)
{
int k=0, v=0;
//store the player index in thegame array
if (name == "player")
{
k = playerPos.Key;
v = playerPos.Value;
}
else if(name=="enemy1"){
k = enemyPos[0].Key;
v = enemyPos[0].Value;
}
else if(name=="enemy2"){
k= enemyPos[1].Key;
v= enemyPos[1].Value;
}
else if(name=="enemy3"){
k = enemyPos[2].Key;
v = enemyPos[2].Value;
}
//List of bool false=can't move there true=can moce there can't move if there a border or box in the index
Dictionary<string,bool> allowed = new Dictionary<string, bool>();
if (thegame[k - 1][v] != null)
if (thegame[k - 1][v].tag == "border" || thegame[k - 1][v].tag == "box")
allowed.Add("up",false);
else
{
allowed.Add("up",true);
}
else
{
allowed.Add("up",true);
}
if (thegame[k][v - 1] != null)
if (thegame[k][v - 1].tag == "border" || thegame[k][v - 1].tag == "box")
allowed.Add("left",false);
else
allowed.Add("left",true);
else
allowed.Add("left",true);
if (thegame[k + 1][v] != null)
if (thegame[k + 1][v].tag == "border" || thegame[k + 1][v].tag == "box")
allowed.Add("down",false);
else
allowed.Add("down",true);
else
allowed.Add("down",true);
if (thegame[k][v + 1] != null)
if (thegame[k][v + 1].tag == "border" || thegame[k][v + 1].tag == "box")
allowed.Add("right",false);
else
allowed.Add("right",true);
else
allowed.Add("right",true);
return allowed;
}
// Update is called once per frame
void Update()
{
if(bigBombTimer<=0&&bigBombIsActive){
disactiveBigBomb();
}
else{
bigBombTimer -= Time.deltaTime;
bigBombImage.fillAmount=bigBombTimer / 60;
}
if(doubleBombTimer<=0&&bombCount>1){
disactiveDoubleBomb();
}
else{
doubleBombTimer -= Time.deltaTime;
doubleBombImage.fillAmount = doubleBombTimer / 60;
}
}
//called to chick if the player can put a bomb or not
public bool canPutBomb()
{
return bombCount < bombcapicity;
}
//called whene player put a bomb
public void addBomb()
{
bombCount++;
}
//called whene the bomb explode
public void removeBomb()
{
bombCount--;
}
//called whene the player moved to set his new position
public void setPlayerPos(int k, int v)
{
playerPos = new KeyValuePair<int, int>(k, v);
}
//called whene the player pickup the double bomb bonus
public void activeDuobleBomb()
{
bombcapicity = 2;
doubleBombImage.gameObject.SetActive(true);
doubleBombTimer = 60;
}
//called whene double bomb timer is over
public void disactiveDoubleBomb(){
bombcapicity = 1;
doubleBombImage.gameObject.SetActive(false);
}
//called whene the player pickup the big bomb bouns
public void activeBigBomb(){
bigBombIsActive = true;
bigBombImage.gameObject.SetActive(true);
bigBombTimer = 60;
}
//called whene big Bomb Timer is over
public void disactiveBigBomb(){
bigBombIsActive = false;
bigBombImage.gameObject.SetActive(false);
// bigBombImage.transform.GetChild(0).gameObject.SetActive(false);
}
//called to chick if the player own the big bomb bouns
public bool getBigBombActive()
{
return bigBombIsActive;
}
//return the player indexs on thegame array
public KeyValuePair<int, int> getPlayerPos()
{
return playerPos;
}
//return the enemy indexs on thegame array
public KeyValuePair<int,int> getenemyPos(int i){
return enemyPos[i];
}
//called whene the enemy moved to set his new position
public void setEnemyPos(int i,int k,int v){
enemyPos[i] = new KeyValuePair<int, int>(k, v);
}
//called to step the game , status it win or lost
public void gameOver(string status)
{
#if UnityEditor
if(status=="win"){
UnityEditor.EditorApplication.isPlaying = false;
}
else{
UnityEditor.EditorApplication.isPlaying = false;
}
#endif
}
}
<file_sep># bombermanUnity
this game was made as training on game development , a unity free assets has been used to create this game
<file_sep>using UnityEngine;
/// <summary>
/// UI Tool For Unity
///
/// Developed by Dibbie.
/// Developer Website: http://www.simpleminded.x10host.com
/// Developer Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
///
/// Artwork by Caroldot.
/// Artist Website: https://www.instagram.com/caroldot.art/
/// Artist Email: mailto:<EMAIL>
///
/// - You can send an email to the developer for any technical support, assistance or bug reports with the asset.
/// - Feel free to join the Discord server and say hi. Directly communicate with the developer & some of my dev friends who help work
/// on amazing games, assets and ideas with me. You can also make suggestions and report bugs there, as well as ask for assistance.
/// </summary>
public class AssetCredits : MonoBehaviour {
public void OnMouseOver(Texture2D icon)
{
Cursor.SetCursor(icon, Vector2.zero, CursorMode.Auto);
}
public void OnMouseExit()
{
Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto);
}
public void OnMouseClick(string website)
{
print("Loading external link: " + website + " (" + name + " website)");
Application.OpenURL(website);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
/// <summary>
/// Groupbox UI Tool
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[AddComponentMenu("UI Tools/Groupbox", 1), DisallowMultipleComponent]
public class Groupbox : MonoBehaviour
{
[Tooltip("(Optional) the text to display in the header of this groupbox. Leave blank to not include a header.")]
public string header;
[Tooltip("The alignment positioning of the header to the left, right, or center of the groupbox. Stacks with the Text properties and most RectTransform properties.")]
public HeaderAlignment alignment = HeaderAlignment.Center;
[Tooltip("(Optional) additional offset to the alignment of the header.")]
public Vector2 offset;
[Space]
[Tooltip("The Text object of the Header itself. This should exist inside the groubox.")]
public Text headerComponent;
[Tooltip("The Transform object that all gameobjects in the groupbox will be validated. This should exist inside the groupbox.")]
public Transform contentsContainer;
public enum HeaderAlignment { Left, Center, Right };
//all children of the contents, stored
private List<GameObject> contents = new List<GameObject>();
void Start()
{
contents.Clear();
UpdateHeader();
}
#region Public Functions
/// <summary>
/// Update the text and position changes of the Header text.
/// </summary>
public void UpdateHeader()
{
if (headerComponent != null)
{
headerComponent.text = header;
RepositionHeader();
}
}
/// <summary>
/// Gets all the gameobjects inside the groupbox's "ContentsContainer" child.
/// </summary>
/// <returns></returns>
public List<GameObject> GetContents()
{
return contents;
}
#endregion
#region Private Functions
void RepositionHeader()
{
RectTransform headerRect = headerComponent.GetComponent<RectTransform>();
float side = 2f;
if (alignment == HeaderAlignment.Center)
{
headerRect.anchorMin = new Vector2(0.5f, headerRect.anchorMin.y);
headerRect.anchorMax = new Vector2(0.5f, headerRect.anchorMax.y);
side = 0f;
}
else if (alignment == HeaderAlignment.Left)
{
headerRect.anchorMin = new Vector2(0f, headerRect.anchorMin.y);
headerRect.anchorMax = new Vector2(0f, headerRect.anchorMax.y);
side = headerRect.rect.width / 2f;
}
else //Right
{
headerRect.anchorMin = new Vector2(1f, headerRect.anchorMin.y);
headerRect.anchorMax = new Vector2(1f, headerRect.anchorMax.y);
side = headerRect.rect.width / -2f;
}
headerRect.anchoredPosition = new Vector2(side + offset.x, headerRect.anchoredPosition.y + offset.y);
}
private void OnTransformChildrenChanged()
{
contents.Clear();
for (int i = 0; i < contentsContainer.childCount; i++)
{
contents.Add(contentsContainer.GetChild(i).gameObject);
}
}
#endregion
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/// <summary>
/// Progress Bar UI Tool
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[AddComponentMenu("UI Tools/Progressbar", 1), DisallowMultipleComponent]
public class ProgressBar : MonoBehaviour {
[Range(0f, 100f)]
public float progress;
[Range(0, 12), Tooltip("Number of decimal places to display. If this is an int-based bar, set to 0.")]
public int decimalPlaces = 0;
[Tooltip("Optonally set custom text to be used instead of the default percentage text. Use #value to get the actual value in string.\nFor example: 'Progress is at #value percent.'")]
public string percentText;
[Tooltip("Determines if a 0 is added before the number, to appear as 05. If not check, it will appear as just 5.")]
public bool precedingZero;
private Slider bar;
private Text percentage;
void Awake()
{
bar = GetComponent<Slider>();
bar.minValue = 0f;
bar.maxValue = 1f;
bar.wholeNumbers = false;
percentage = transform.GetChild(2).GetComponent<Text>();
}
void FixedUpdate()
{
bar.value = progress / 100f;
string decimals = (precedingZero) ? "00." : "0.";
for (int i = 0; i < decimalPlaces; i++) { decimals += "0"; }
if(decimals == "0.") { decimals = (precedingZero) ? "00" : "0"; }
percentage.text = (string.IsNullOrEmpty(percentText) ? progress + "%" : percentText.Replace("#value", progress.ToString(decimals)));
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Editor script used to create each UI Tool prefab, from GameObject > UI top menu
/// </summary>
public class UIToolsMaker : MonoBehaviour
{
[MenuItem("UI Tools/Combobox (Advanced Dropdown)", menuItem = "GameObject/UI/Combox (Advanced Dropdown)", priority = 0)]
static void UIToolsDropdown()
{
Create(Resources.Load("Dropdown") as GameObject);
}
[MenuItem("UI Tools/Radio Button", menuItem = "GameObject/UI/Radio Button", priority = 1)]
static void UIToolsRadioButton()
{
Create(Resources.Load("Radio Button") as GameObject);
}
[MenuItem("UI Tools/Option Selector", menuItem = "GameObject/UI/Option Selector", priority = 2)]
static void UIToolsOptionSelector()
{
Create(Resources.Load("Option Selector") as GameObject);
}
[MenuItem("UI Tools/Progress Bar", menuItem = "GameObject/UI/Progress Bar", priority = 3)]
static void UIToolsProgressbar()
{
Create(Resources.Load("Progress Bar") as GameObject);
}
[MenuItem("UI Tools/Listbox", menuItem = "GameObject/UI/Listbox", priority = 4)]
static void UIToolsListbox()
{
Create(Resources.Load("Listbox") as GameObject);
}
[MenuItem("UI Tools/Tab Control", menuItem = "GameObject/UI/Tab Control", priority = 5)]
static void UIToolsTabControl()
{
Create(Resources.Load("Tab Control") as GameObject);
}
[MenuItem("UI Tools/Table", menuItem = "GameObject/UI/Table", priority = 6)]
static void UIToolsTabTable()
{
Create(Resources.Load("Table") as GameObject);
}
[MenuItem("UI Tools/GroupBox", menuItem = "GameObject/UI/Groupbox", priority = 7)]
static void UIToolsGroupbox()
{
Create(Resources.Load("Groupbox") as GameObject);
}
[MenuItem("UI Tools/Extras/Radio Button Group", menuItem = "GameObject/UI/Extras/Radio Button Group", priority = 8)]
static void UIToolsRadioGroup()
{
Create(Resources.Load("Radio Button Group") as GameObject);
}
[MenuItem("UI Tools/Extras/Message Box", menuItem = "GameObject/UI/Extras/Message Box", priority = 9)]
static void UIToolsMessagebox()
{
Create(Resources.Load("Extentions/MessageBox Dialog") as GameObject);
}
[MenuItem("UI Tools/Extras/Tooltip", menuItem = "GameObject/UI/Extras/Tooltip", priority = 10)]
static void UIToolsTooltip()
{
Create(Resources.Load("Extentions/Tooltips/Tooltip (+Icon)") as GameObject);
}
[MenuItem("UI Tools/Extras/Calendar", menuItem = "GameObject/UI/Extras/Calendar", priority = 11)]
static void UIToolsCalendar()
{
Create(Resources.Load("Extentions/Calendar") as GameObject);
}
static void Create(GameObject uiTool)
{
GameObject ui = null;
int count = FindObjectsOfType<GameObject>().Count(obj => ((obj.name.Contains('(')) ? obj.name.Substring(0, obj.name.LastIndexOf('(') - 1) : obj.name) == uiTool.name);
if (Selection.activeGameObject != null && Selection.activeGameObject.activeInHierarchy)
{
if (Selection.activeGameObject.transform.parent != null)
{
//spawn on parent
ui = Instantiate(uiTool, Selection.activeGameObject.transform.parent);
}
else
{
//spawn on object, add as child
ui = Instantiate(uiTool, Selection.activeGameObject.transform);
}
}
else
{
//spawn in hierarchy (anywhere), no parent
ui = Instantiate(uiTool, FindObjectOfType<Canvas>().transform);
}
ui.name = uiTool.name + ((count > 0) ? " (" + count + ")" : ""); //add count to name
Selection.activeGameObject = ui; //select object in Hierarchy
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
/// <summary>
/// Calendar UI Tool - Data Class
/// Placed on each button of a Calendar.
///
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
public class CalendarButton : MonoBehaviour, IPointerClickHandler {
protected Calendar calendar;
protected ButtonEventData data;
public void SetCalendar(Calendar targetCalendar, ButtonEventData eventData)
{
calendar = targetCalendar;
data = eventData;
}
public void OnPointerClick(PointerEventData eventData)
{
calendar.SendClickEvents(eventData, data);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
/// <summary>
/// Table UI Tool
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
[AddComponentMenu("UI Tools/Table", 5), DisallowMultipleComponent]
public class Table : MonoBehaviour
{
[Header("Templates")]
public GridLayoutGroup header_Template;
public GridLayoutGroup content_Template;
public HorizontalLayoutGroup headerContainer_Template;
public VerticalLayoutGroup contentContainer_Template;
public LayoutElement contentContainerItemElement_Template;
public ScrollRect contentContainerScrollView_Template;
[Space]
[Header("Preferences")]
[Tooltip("The number of colums to create.")]
public int columns = 2;
[Tooltip("Should the contents of a colum exceed its height, that column will become scrollable.")]
public bool scrollColumns;
private List<GameObject> col_headers = new List<GameObject>();
private List<GameObject> col_contents = new List<GameObject>();
private float tableWidth;
#region Initalization
void OnDrawGizmos()
{
if (header_Template != null && content_Template != null) { RecalculateWidth(); }
}
// Use this for initialization
void Start()
{
headerContainer_Template.gameObject.SetActive(false);
contentContainer_Template.gameObject.SetActive(false);
headerContainer_Template.transform.SetParent(transform);
contentContainer_Template.transform.SetParent(transform);
ClearTable();
RecalculateWidth();
for (int i = 0; i < columns; i++)
{
GameObject header = (GameObject)Instantiate(headerContainer_Template.gameObject);
header.name = "[Header " + (i + 1) + " Container]";
header.transform.SetParent(header_Template.transform);
header.SetActive(true);
col_headers.Add(header);
if (scrollColumns)
{
GameObject content = (GameObject)Instantiate(contentContainer_Template.gameObject);
GameObject scrollContent = (GameObject)Instantiate(contentContainerScrollView_Template.gameObject);
content.name = "Column " + (i + 1);
scrollContent.name = "Column " + (i + 1) + " Scrollable";
Destroy(content.GetComponent<VerticalLayoutGroup>());
scrollContent.transform.GetChild(0).GetChild(0).gameObject.AddComponent<VerticalLayoutGroup>();
scrollContent.transform.GetChild(0).GetChild(0).gameObject.GetComponent<VerticalLayoutGroup>().childForceExpandWidth = true;
scrollContent.transform.SetParent(content.transform);
scrollContent.GetComponent<RectTransform>().anchorMin = new Vector2(0f, 0f);
scrollContent.GetComponent<RectTransform>().anchorMax = new Vector2(1f, 1f);
scrollContent.GetComponent<RectTransform>().offsetMin = new Vector2(0f, 0f);
scrollContent.GetComponent<RectTransform>().offsetMax = new Vector2(0f, 0f);
scrollContent.transform.SetAsFirstSibling();
content.transform.SetParent(content_Template.transform);
content.SetActive(true);
scrollContent.SetActive(true);
ClearColumn(content.GetComponent<VerticalLayoutGroup>());
col_contents.Add(scrollContent);
}
else
{
GameObject content = (GameObject)Instantiate(contentContainer_Template.gameObject);
content.name = "Column " + (i + 1);
content.transform.SetParent(content_Template.transform);
content.SetActive(true);
ClearColumn(content.GetComponent<VerticalLayoutGroup>());
col_contents.Add(content);
}
}
}
void ClearTable()
{
for (int i = 1; i < header_Template.transform.childCount; i++) { Destroy(header_Template.transform.GetChild(i).gameObject); }
for (int i = 1; i < content_Template.transform.childCount; i++) { Destroy(content_Template.transform.GetChild(i).gameObject); }
}
#endregion
#region Public Functions
/// <summary>
/// Recalculate the total width of the table, which will also re-adjust table columns widths, based on 'columns' count.
/// </summary>
public void RecalculateWidth()
{
header_Template.constraintCount = columns;
content_Template.constraintCount = columns;
tableWidth = GetComponent<RectTransform>().rect.width;
header_Template.cellSize = new Vector2(tableWidth / columns, header_Template.GetComponent<RectTransform>().rect.height);
content_Template.cellSize = new Vector2(tableWidth / columns, content_Template.GetComponent<RectTransform>().rect.height);
}
/// <summary>
/// Add a column to the table, with default paramaters.
/// </summary>
public void AddColumn()
{
columns++;
RecalculateWidth();
GameObject header = (GameObject)Instantiate(headerContainer_Template.gameObject);
header.name = "[Header " + (col_headers.Count + 1) + " Container]";
header.transform.SetParent(header_Template.transform);
header.SetActive(true);
col_headers.Add(header);
if (scrollColumns)
{
GameObject content = (GameObject)Instantiate(contentContainer_Template.gameObject);
GameObject scrollContent = (GameObject)Instantiate(contentContainerScrollView_Template.gameObject);
content.name = "Column " + (col_contents.Count + 1);
scrollContent.name = "Column " + (col_contents.Count + 1) + " Scrollable";
Destroy(content.GetComponent<VerticalLayoutGroup>());
scrollContent.transform.GetChild(0).GetChild(0).gameObject.AddComponent<VerticalLayoutGroup>();
scrollContent.transform.GetChild(0).GetChild(0).gameObject.GetComponent<VerticalLayoutGroup>().childForceExpandWidth = true;
scrollContent.transform.SetParent(content.transform);
scrollContent.GetComponent<RectTransform>().anchorMin = new Vector2(0f, 0f);
scrollContent.GetComponent<RectTransform>().anchorMax = new Vector2(1f, 1f);
scrollContent.GetComponent<RectTransform>().offsetMin = new Vector2(0f, 0f);
scrollContent.GetComponent<RectTransform>().offsetMax = new Vector2(0f, 0f);
scrollContent.transform.SetAsFirstSibling();
content.transform.SetParent(content_Template.transform);
content.SetActive(true);
scrollContent.SetActive(true);
ClearColumn(content.GetComponent<VerticalLayoutGroup>());
col_contents.Add(scrollContent);
}
else
{
GameObject content = (GameObject)Instantiate(contentContainer_Template.gameObject);
content.name = "Column " + (col_contents.Count + 1);
content.transform.SetParent(content_Template.transform);
content.SetActive(true);
ClearColumn(content.GetComponent<VerticalLayoutGroup>());
col_contents.Add(content);
}
}
/// <summary>
/// Add a column to the table, with a specified name.
/// </summary>
/// <param name="name">The name of this colmn to set, when created.</param>
public void AddColumn(string name)
{
columns++;
RecalculateWidth();
GameObject header = (GameObject)Instantiate(headerContainer_Template.gameObject);
header.name = "[Header " + (col_headers.Count + 1) + " Container]";
header.GetComponentInChildren<Text>().text = name;
header.transform.SetParent(header_Template.transform);
header.SetActive(true);
col_headers.Add(header);
if (scrollColumns)
{
GameObject content = (GameObject)Instantiate(contentContainer_Template.gameObject);
GameObject scrollContent = (GameObject)Instantiate(contentContainerScrollView_Template.gameObject);
content.name = "Column " + (col_contents.Count + 1);
scrollContent.name = "Column " + (col_contents.Count + 1) + " Scrollable";
Destroy(content.GetComponent<VerticalLayoutGroup>());
scrollContent.transform.GetChild(0).GetChild(0).gameObject.AddComponent<VerticalLayoutGroup>();
scrollContent.transform.GetChild(0).GetChild(0).gameObject.GetComponent<VerticalLayoutGroup>().childForceExpandWidth = true;
scrollContent.transform.SetParent(content.transform);
scrollContent.GetComponent<RectTransform>().anchorMin = new Vector2(0f, 0f);
scrollContent.GetComponent<RectTransform>().anchorMax = new Vector2(1f, 1f);
scrollContent.GetComponent<RectTransform>().offsetMin = new Vector2(0f, 0f);
scrollContent.GetComponent<RectTransform>().offsetMax = new Vector2(0f, 0f);
scrollContent.transform.SetAsFirstSibling();
content.transform.SetParent(content_Template.transform);
content.SetActive(true);
scrollContent.SetActive(true);
ClearColumn(content.GetComponent<VerticalLayoutGroup>());
col_contents.Add(scrollContent);
}
else
{
GameObject content = (GameObject)Instantiate(contentContainer_Template.gameObject);
content.name = "Column " + (col_contents.Count + 1);
content.transform.SetParent(content_Template.transform);
content.SetActive(true);
ClearColumn(content.GetComponent<VerticalLayoutGroup>());
col_contents.Add(content);
}
}
/// <summary>
/// Remove the specified column from the table, and all its children.
/// </summary>
/// <param name="col">The column to remove.</param>
public void RemoveColumn(VerticalLayoutGroup col)
{
columns--;
RecalculateWidth();
int index = col.transform.GetSiblingIndex();
GameObject header, contents;
header = col_headers[index];
contents = col_contents[index];
col_contents.RemoveAt(index);
col_headers.RemoveAt(index);
Destroy(header);
Destroy(contents);
}
/// <summary>
/// Remove the specified column from the table, and all its children.
/// </summary>
/// <param name="col">The column to remove.</param>
public void RemoveColumn(GameObject col)
{
columns--;
RecalculateWidth();
int index = col.transform.GetSiblingIndex();
GameObject header, contents;
header = col_headers[index];
contents = col_contents[index];
col_contents.RemoveAt(index);
col_headers.RemoveAt(index);
Destroy(header);
Destroy(contents);
}
/// <summary>
/// Remove the specified column from the table, and all its children, by the columns index.
/// </summary>
/// <param name="col_index">The index of the column to remove.</param>
public void RemoveColumn(int col_index)
{
columns--;
RecalculateWidth();
GameObject header, contents;
header = col_headers[col_index];
contents = col_contents[col_index];
col_contents.RemoveAt(col_index);
col_headers.RemoveAt(col_index);
Destroy(header);
Destroy(contents);
}
/// <summary>
/// Remove all children of the specified column.
/// </summary>
/// <param name="col">The column to clear the contents of.</param>
public void ClearColumn(VerticalLayoutGroup col)
{
for (int i = 0; i < col.transform.childCount; i++)
{
if (scrollColumns && i == 0) { i = 1; }
Destroy(col.transform.GetChild(i).gameObject);
}
}
/// <summary>
/// Remove all children of the specified column.
/// </summary>
/// <param name="col">The column to clear the contents of.</param>
public void ClearColumn(GameObject col)
{
for (int i = 0; i < col.transform.childCount; i++)
{
if (scrollColumns && i == 0) { i = 1; }
Destroy(col.transform.GetChild(i).gameObject);
}
}
/// <summary>
/// Remove all children of the specified column, by the columns index.
/// </summary>
/// <param name="col_index">The index of the column to clear the contents of.</param>
public void ClearColumn(int col_index)
{
GameObject col = col_contents[col_index];
for (int i = 0; i < col.transform.childCount; i++)
{
if (scrollColumns && i == 0) { i = 1; }
Destroy(col.transform.GetChild(i).gameObject);
}
}
/// <summary>
/// Add an item to the specified column.
/// </summary>
/// <param name="item">The item to add to the column.</param>
/// <param name="col">The column to add the item to.</param>
public void AddToColumn(GameObject item, VerticalLayoutGroup col)
{
GameObject obj = (GameObject)Instantiate(contentContainerItemElement_Template.gameObject);
obj.transform.SetParent(col.transform);
item.transform.SetParent(obj.transform);
item.transform.position = Vector3.zero;
}
/// <summary>
/// Add an item to the specified column.
/// </summary>
/// <param name="item">The item to add to the column.</param>
/// <param name="col">The column to add the item to.</param>
public void AddToColumn(GameObject item, GameObject col)
{
GameObject obj = (GameObject)Instantiate(contentContainerItemElement_Template.gameObject);
obj.transform.SetParent(col.transform);
item.transform.SetParent(obj.transform);
item.transform.position = Vector3.zero;
if (obj.transform.parent.name == "Content") { obj.transform.parent.GetComponent<RectTransform>().sizeDelta = new Vector2(obj.transform.parent.GetComponent<RectTransform>().sizeDelta.x, obj.transform.parent.GetChild(0).GetComponent<LayoutElement>().preferredHeight * obj.transform.parent.childCount); }
}
/// <summary>
/// Add an item to the specified column, by the columns index.
/// </summary>
/// <param name="item">The item to add to the column.</param>
/// <param name="col_index">The index of the column to add the item to.</param>
public void AddToColumn(GameObject item, int col_index)
{
GameObject obj = (GameObject)Instantiate(contentContainerItemElement_Template.gameObject);
obj.transform.SetParent(col_contents[col_index].transform);
item.transform.SetParent(obj.transform);
item.transform.position = Vector3.zero;
if (obj.transform.parent.name == "Content") { obj.transform.parent.GetComponent<RectTransform>().sizeDelta = new Vector2(obj.transform.parent.GetComponent<RectTransform>().sizeDelta.x, obj.transform.parent.GetChild(0).GetComponent<LayoutElement>().preferredHeight * obj.transform.parent.childCount); }
}
/// <summary>
/// Remove an item from its column.
/// </summary>
/// <param name="item">The item to remove from the table.</param>
public void RemoveFromColumn(GameObject item)
{
Destroy(item);
}
/// <summary>
/// Remove an item by the items index, from the specified column.
/// </summary>
/// <param name="item_index">The index of the item to remove from the column.</param>
/// <param name="col">The column that the item belongs to.</param>
public void RemoveFromColumn(int item_index, VerticalLayoutGroup col)
{
GameObject item = col.transform.GetChild(item_index).gameObject;
Destroy(item);
}
/// <summary>
/// Remove an item by the items index, from the specified column
/// </summary>
/// <param name="item_index">The index of the item to remove from the column.</param>
/// <param name="col">The column that the item belongs to.</param>
public void RemoveFromColumn(int item_index, GameObject col)
{
GameObject item = col.transform.GetChild(item_index).gameObject;
Destroy(item);
}
/// <summary>
/// Remove an item by the items index, from the specified column, by the columns index.
/// </summary>
/// <param name="item_index">The index of the item to remove from the column.</param>
/// <param name="col_index">The index of the column that the item belongs to, for removal.</param>
public void RemoveFromColumn(int item_index, int col_index)
{
GameObject item = col_contents[col_index].transform.GetChild(item_index).gameObject;
Destroy(item);
}
/// <summary>
/// Get the column that the specified item belongs to.
/// </summary>
/// <param name="item">The item to find the column of.</param>
public GameObject GetColumnOf(GameObject item)
{
return col_contents[item.transform.parent.GetSiblingIndex()];
}
/// <summary>
/// Get the header/column index that the specified item belongs to. The header will always be the same as the column contents.
/// </summary>
/// <param name="item">The item to find the column of.</param>
public int GetHeaderColumnIndexOf(GameObject item)
{
return item.transform.parent.GetSiblingIndex();
}
/// <summary>
/// Get the header that the specified item belongs to.
/// </summary>
/// <param name="item">The item to find the header of.</param>
public GameObject GetHeaderOf(GameObject item)
{
return col_headers[item.transform.parent.GetSiblingIndex()];
}
/// <summary>
/// Get a header by index.
/// </summary>
/// <param name="index">The index of the header to retrieve.</param>
public GameObject GetHeader(int index)
{
return col_headers[index];
}
/// <summary>
/// Get a column contents by index.
/// </summary>
/// <param name="index">The index of the column to retrieve.</param>
public GameObject GetColumn(int index)
{
return col_contents[index];
}
#endregion
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using CustomMessageBox;
/// <summary>
/// Message Box UI Tool - Data Class
/// Placed on each button of a Message Box.
///
/// Developed by Dibbie.
/// Website: http://www.simpleminded.x10host.com
/// Email: mailto:<EMAIL>
/// Discord Server: https://discord.gg/33PFeMv
/// </summary>
public class MessageResponse : MonoBehaviour
{
public MessageBoxResponse response;
public void BtnMsgButton()
{
MessageBox.InvokeAction(response);
}
}
|
d34e8cd533f61e03577fb263dd32dd01d7159936
|
[
"Markdown",
"C#"
] | 30 |
C#
|
Asumreen/bombermanUnity
|
04317dc6bfd5d2f211d9d1419a5290013b038700
|
5c46566c488b055b5460d749328704ff6aa8e7d3
|
refs/heads/master
|
<file_sep>package socketio
import (
"github.com/googollee/go-engine.io"
"net/http"
"time"
)
type Config struct {
PingTimeout time.Duration
PingInterval time.Duration
MaxHttpBufferSize int
AllowRequest func(*http.Request) (bool, error)
Transports []string
AllowUpgrades bool
Cookie string
}
var DefaultConfig = Config{
PingTimeout: 60000 * time.Millisecond,
PingInterval: 25000 * time.Millisecond,
MaxHttpBufferSize: 0x10E7,
AllowRequest: func(*http.Request) (bool, error) { return true, nil },
Transports: []string{"polling", "websocket"},
AllowUpgrades: true,
Cookie: "io",
}
type Server struct {
*namespace
eio *engineio.Server
}
func NewServer(conf Config) *Server {
econf := engineio.Config{
PingTimeout: conf.PingTimeout,
PingInterval: conf.PingInterval,
MaxHttpBufferSize: conf.MaxHttpBufferSize,
AllowRequest: conf.AllowRequest,
Transports: conf.Transports,
AllowUpgrades: conf.AllowUpgrades,
Cookie: conf.Cookie,
}
ret := &Server{
namespace: newNamespace(),
eio: engineio.NewServer(econf),
}
go ret.loop()
return ret
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.eio.ServeHTTP(w, r)
}
func (s *Server) loop() {
for {
conn, err := s.eio.Accept()
if err != nil {
return
}
s := newSocket(conn, s.baseHandler)
go func(s *socket) {
s.loop()
}(s)
}
}
<file_sep># socket.io
CHECKING OUT 1.0
socket.io for golang. Supported room.
It compatible with latest implement of socket.io in node.js.
## Example
Please check example folder
## TODO
- More unit tests
- Error handler
- Document<file_sep>package socketio
type Namespace interface {
Name() string
Of(namespace string) Namespace
On(message string, f interface{}) error
BroadcastTo(room, message string, args ...interface{}) error
}
type namespace struct {
*baseHandler
name string
root map[string]Namespace
}
func newNamespace() *namespace {
ret := &namespace{
baseHandler: newBaseHandler(),
name: "",
root: make(map[string]Namespace),
}
ret.root[ret.name] = ret
return ret
}
func (n *namespace) Name() string {
return n.name
}
func (n *namespace) Of(name string) Namespace {
if name == "/" {
name = ""
}
if ret, ok := n.root[name]; ok {
return ret
}
ret := &namespace{
baseHandler: newBaseHandler(),
name: name,
root: n.root,
}
n.root[name] = ret
return ret
}
|
6d86bd52edea44b156ff06ae8de03a63505308d3
|
[
"Markdown",
"Go"
] | 3 |
Go
|
izqui/go-socket.io
|
32d3029ac13f559833cda22ea4f939d4fe14ab48
|
3b89926ae0be348906e6a64930fbd1ab53e43df2
|
refs/heads/master
|
<repo_name>vinayakkgarg/myflaskapp<file_sep>/app.py
from flask import Flask, render_template
from data import Articles
# create object of class Flask
app = Flask(__name__)
Articles = Articles()
# defining routes ie url
# we generally return a template
@app.route('/')
def index():
return render_template('home.html')
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/articles')
def articles():
return render_template('articles.html', articles=Articles)
@app.route('/articles/<string:id>/')
def article(id):
return render_template('article.html', id=id)
# debug = True then we don't need to restart server to view changes
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/templates/home.html
{% extends 'layout.html' %}
{% block body %}
<div class="jumbotron text-center">
<h1>Welcome to Flask App</h1>
<p class="lead">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates cupiditate reprehenderit nihil asperiores
voluptatem incidunt molestiae numquam quod, debitis alias perferendis id veniam modi voluptatum consequatur ad
nisi quia dolore?
</p>
</div>
{% endblock %}<file_sep>/README.md
# myflaskapp
Practice Blogging website using Flask and mysql
<file_sep>/data.py
def Articles():
articles = [
{
'id': 1,
'title': 'Articel One',
'body': 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. ',
'author': '<NAME>',
'create_date': '10-06-2019'
},
{
'id': 2,
'title': 'Articel Two',
'body': 'Lorem ipsum, dolor sit amet consectetur adipisicing elit.',
'author': '<NAME>',
'create_date': '10-06-2020'
},
{
'id': 3,
'title': 'Articel Three',
'body': 'Lorem ipsum, dolor sit amet consectetur adipisicing elit.',
'author': '<NAME>',
'create_date': '10-06-2021'
}
]
return articles
|
116f268d5d7454484a505cdbf05ab525eb939f7c
|
[
"Markdown",
"Python",
"HTML"
] | 4 |
Python
|
vinayakkgarg/myflaskapp
|
c95264d20f7db74e0c25899f3354840e7ccbdeaa
|
d11fd0985d371e925ff15b56e7605e5935a830ab
|
refs/heads/master
|
<repo_name>nbenoit3/ajax-exercise<file_sep>/main.js
var container = document.getElementById("container");
var button = document.getElementById("dogButton");
var selectBox = document.getElementById("dropDown");
var dogHTML = ``;
axios.get("https://dog.ceo/api/breeds/list").then(function(response) {
response.data.message.forEach(function(dogBreed) {
dogHTML = `
<option value="${dogBreed}">${dogBreed}</option>
`
selectBox.innerHTML += dogHTML;
});
});
selectBox.addEventListener("change", function() {
axios.get(`https://dog.ceo/api/breed/${this.value}/images/random`).then(function(response) {
container.innerHTML = `<img src="${response.data.message}"/>`
});
});
button.addEventListener("click", function() {
button.innerHTML = "Generating Doggo...";
axios.get("https://dog.ceo/api/breeds/image/random").then(function(response){
var dogImageURL = response.data.message;
container.innerHTML = `
<img src="${dogImageURL}"/>
`
button.innerHTML = "Generate Doggo!!!"
});
});
|
7af631cabf18e5f8f334b9ee26b703eb056ed1c6
|
[
"JavaScript"
] | 1 |
JavaScript
|
nbenoit3/ajax-exercise
|
19d17e909866dad534f5d54476513e0c882b291d
|
9e19f6d8ef17601507ed62d34b4f514a027a3645
|
refs/heads/master
|
<repo_name>schornakj/rviz2_camera_ray_tool<file_sep>/rviz2_camera_ray_tool/src/rviz2_camera_ray_tool/camera_ray_tool.cpp
#include <rviz2_camera_ray_tool/camera_ray_tool.h>
#include <OgreCamera.h>
#include <OgreRay.h>
#include <OgreVector3.h>
#include <OgreViewport.h>
//#pragma GCC diagnostic push // Supress warnings from library files
//#pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
//#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <rviz_common/viewport_mouse_event.hpp>
#include <rviz_common/display_context.hpp>
#include <rviz_common/interaction/selection_manager.hpp>
#include <rviz_common/view_controller.hpp>
#include <rviz_common/render_panel.hpp>
#include <rviz_rendering/render_window.hpp>
#pragma GCC diagnostic pop // Un-supress warnings
#include <Eigen/Dense>
#include <rviz2_camera_ray_tool_msgs/msg/ray.hpp>
namespace rviz2_camera_ray_tool
{
CameraRayTool::CameraRayTool()
: Node("rviz2_camera_ray_tool")
, pub_(this->create_publisher<rviz2_camera_ray_tool_msgs::msg::Ray>("/clicked_ray", 1))
{
shortcut_key_ = 'r';
}
CameraRayTool::~CameraRayTool()
{
}
void CameraRayTool::onInitialize()
{
}
void CameraRayTool::activate()
{
}
void CameraRayTool::deactivate()
{
}
int CameraRayTool::processMouseEvent(rviz_common::ViewportMouseEvent& event)
{
if (event.leftUp())
{
auto viewport = rviz_rendering::RenderWindowOgreAdapter::getOgreViewport(event.panel->getRenderWindow());
Ogre::Ray mouse_ray = viewport->getCamera()->getCameraToViewportRay(
static_cast<float>(event.x) / static_cast<float>(viewport->getActualWidth()),
static_cast<float>(event.y) / static_cast<float>(viewport->getActualHeight()));
rviz2_camera_ray_tool_msgs::msg::Ray msg;
msg.header.stamp = this->now();
msg.header.frame_id = context_->getFixedFrame().toStdString();
msg.origin.x = static_cast<double>( mouse_ray.getOrigin().x);
msg.origin.y = static_cast<double>( mouse_ray.getOrigin().y);
msg.origin.z = static_cast<double>( mouse_ray.getOrigin().z);
msg.direction.x = static_cast<double>( mouse_ray.getDirection().x);
msg.direction.y = static_cast<double>( mouse_ray.getDirection().y);
msg.direction.z = static_cast<double>( mouse_ray.getDirection().z);
pub_->publish(msg);
if (event.shift()) // Hold down shift to pick many points
return Render;
else
return Finished;
}
return Render;
}
}
#include <pluginlib/class_list_macros.hpp> // NOLINT
PLUGINLIB_EXPORT_CLASS(rviz2_camera_ray_tool::CameraRayTool, rviz_common::Tool)
<file_sep>/rviz2_camera_ray_tool_msgs/CMakeLists.txt
cmake_minimum_required(VERSION 3.5.0)
project(rviz2_camera_ray_tool_msgs)
if(NOT CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 17)
endif()
find_package(rosidl_default_generators REQUIRED)
find_package(ament_cmake REQUIRED)
find_package(std_msgs REQUIRED)
find_package(geometry_msgs REQUIRED)
set(msg_files
"msg/Ray.msg"
)
rosidl_generate_interfaces(${PROJECT_NAME}
${msg_files}
${srv_files}
${action_files}
DEPENDENCIES std_msgs geometry_msgs)
ament_export_dependencies(rosidl_default_runtime)
ament_package()
<file_sep>/rviz2_camera_ray_tool/CMakeLists.txt
cmake_minimum_required(VERSION 3.5.0)
project(rviz2_camera_ray_tool)
if(NOT CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 14)
endif()
find_package(ament_cmake REQUIRED)
find_package(rviz_ogre_vendor REQUIRED)
find_package(pluginlib REQUIRED)
find_package(rclcpp REQUIRED)
find_package(rviz_common REQUIRED)
find_package(rviz_rendering REQUIRED)
find_package(rviz2_camera_ray_tool_msgs REQUIRED)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
find_package(Qt5 REQUIRED COMPONENTS Core Gui Widgets)
qt5_wrap_cpp(MOC_FILES include/${PROJECT_NAME}/camera_ray_tool.h)
add_library(${PROJECT_NAME} SHARED
src/${PROJECT_NAME}/camera_ray_tool.cpp
${MOC_FILES}
)
ament_target_dependencies(${PROJECT_NAME}
rclcpp
rviz_common
rviz_rendering
rviz2_camera_ray_tool_msgs
)
target_link_libraries(${PROJECT_NAME}
rviz_common::rviz_common
)
target_include_directories(${PROJECT_NAME} PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>")
target_include_directories(${PROJECT_NAME} PUBLIC
${rviz2_camera_ray_tool_msgs_INCLUDE_DIRS}
${Qt5Widgets_INCLUDE_DIRS}
${OGRE_INCLUDE_DIRS}
)
target_compile_definitions(${PROJECT_NAME} PRIVATE "RVIZ_DEFAULT_PLUGINS_BUILDING_LIBRARY")
target_compile_definitions(${PROJECT_NAME} PUBLIC "PLUGINLIB__DISABLE_BOOST_FUNCTIONS")
pluginlib_export_plugin_description_file(rviz_common plugin_description.xml)
## Mark executables and/or libraries for installation
install(TARGETS ${PROJECT_NAME}
EXPORT ${PROJECT_NAME}
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
RUNTIME DESTINATION bin
INCLUDES DESTINATION include
)
## Mark cpp header files for installation
install(DIRECTORY include/
DESTINATION include/
)
ament_export_include_directories(include)
ament_export_interfaces(${PROJECT_NAME} HAS_LIBRARY_TARGET)
ament_export_dependencies(
Qt5
rviz_common
geometry_msgs
map_msgs
rclcpp
)
ament_package()
<file_sep>/rviz2_camera_ray_tool/include/rviz2_camera_ray_tool/camera_ray_tool.h
#pragma once
#include <rviz_common/tool.hpp>
#include <rclcpp/rclcpp.hpp>
#include <rviz2_camera_ray_tool_msgs/msg/ray.hpp>
namespace rviz2_camera_ray_tool
{
class CameraRayTool : public rviz_common::Tool, public rclcpp::Node
{
Q_OBJECT
public:
CameraRayTool();
virtual ~CameraRayTool();
virtual void onInitialize() override;
virtual void activate() override;
virtual void deactivate() override;
virtual int processMouseEvent(rviz_common::ViewportMouseEvent& event) override;
private:
rclcpp::Publisher<rviz2_camera_ray_tool_msgs::msg::Ray>::SharedPtr pub_;
};
}
<file_sep>/README.md
# rviz2_camera_ray_tool
A simple ROS2 Rviz plugin that publishes a ray from the camera to a clicked point.
This is a direct port of [<NAME>'s `rviz_camera_ray_tool` plugin](https://github.com/Jmeyer1292/rviz_camera_ray_tool).
|
6a087c67a01cabe291e589c91a80673285939b04
|
[
"Markdown",
"CMake",
"C++"
] | 5 |
C++
|
schornakj/rviz2_camera_ray_tool
|
bead06de2a3e59e10b850a0561485bf353a20891
|
263b9d1f0b0dc4b77aa13e711bfa45a9ab3211ae
|
refs/heads/master
|
<file_sep>def my_module():
print("Test du module")<file_sep>import dbconfig as db
try:
mydb = db.open()
#print(mydb)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
mycursor.execute("SELECT * FROM todoitems")
print(mycursor.fetchall())
finally:
db.close(mydb)
<file_sep>import mysql.connector
# Put your DB configuration
def open():
return mysql.connector.connect(host="XXXX",
user="XXXX",
passwd="<PASSWORD>",
db="XXXX")
def close(mydb):
mydb.close()
|
2594f4d5f5bc68c778960749c77846fd177c215f
|
[
"Python"
] | 3 |
Python
|
nicogid/my_python_project
|
381336d95fc6d98190c2a3702869e8c3526de2df
|
655af38817e8a793877250f5befa3c3b657292bc
|
refs/heads/master
|
<file_sep>#include "CAF.h"
#include "TRandom3.h"
#include "TVector2.h"
#include "TVector3.h"
#include "TLorentzVector.h"
#include "TH1F.h"
#include "TRandom.h"
#include "TF1.h"
#include "TDatabasePDG.h"
#include "TParticlePDG.h"
#include <stdio.h>
#include <vector>
#include <iostream>
#include <string>
#include <stdlib.h>
#include <numeric>
#include <functional>
#include <exception>
CAF::CAF()
: cafFile(nullptr), _intfile(nullptr), _inttree(nullptr), _util(new Utils()), _inputfile(""), _outputFile(""), _correct4origin(0)
{
}
CAF::CAF( std::string infile, std::string filename, int correct4origin, double *originTPC)
: cafFile(nullptr), _intfile(nullptr), _inttree(nullptr), _util(new Utils()), _inputfile(infile), _outputFile(filename), _correct4origin(correct4origin)
{
_util->SetOrigin(originTPC);
}
CAF::~CAF()
{
delete _util;
delete cafMVA;
delete cafFile;
delete _inttree;
delete _intfile;
}
bool CAF::BookTFile()
{
_intfile = new TFile( _inputfile.c_str() );
if(nullptr == _intfile){
std::cout << "Cannot open file " << _inputfile.c_str() << std::endl;
return false;
}
_inttree = (TTree*) _intfile->Get( "anatree/GArAnaTree" );
if(nullptr == _inttree){
std::cout << "Cannot find tree anatree/GArAnaTree" << std::endl;
return false;
}
cafFile = new TFile(_outputFile.c_str(), "RECREATE");
if(nullptr == cafFile){
return false;
}
else
{
cafMVA = new TTree( "caf", "caf tree" );
cafMVA->SetDirectory(0);
//Event number
cafMVA->Branch("Event", &_Event);
//Run number
cafMVA->Branch("Run", &_Run);
//Sub Run number
cafMVA->Branch("SubRun", &_SubRun);
//MC Truth info (Generator)
cafMVA->Branch("mode", &mode);
cafMVA->Branch("q2", &q2);
cafMVA->Branch("w", &w);
cafMVA->Branch("y", &y);
cafMVA->Branch("x", &x);
cafMVA->Branch("theta", &theta);
cafMVA->Branch("t", &t);
cafMVA->Branch("ntype", &ntype);
cafMVA->Branch("ccnc", &ccnc);
cafMVA->Branch("gint", &gint);
cafMVA->Branch("tgtpdg", &tgtpdg);
cafMVA->Branch("weight", &weight);
cafMVA->Branch("gt_t", >_t);
cafMVA->Branch("intert", &intert);
cafMVA->Branch("mcnupx", &mcnupx);
cafMVA->Branch("mcnupy", &mcnupy);
cafMVA->Branch("mcnupz", &mcnupz);
cafMVA->Branch("vertx", &vertx);
cafMVA->Branch("verty", &verty);
cafMVA->Branch("vertz", &vertz);
//List of particles from GENIE from the interaction and their status flag
cafMVA->Branch("nGPart", &nGPart);
cafMVA->Branch("GPartName", &GPartName);
cafMVA->Branch("GPartPdg", &GPartPdg);
cafMVA->Branch("GPartStatus", &GPartStatus);
cafMVA->Branch("GPartFirstMom", &GPartFirstMom);
cafMVA->Branch("GPartLastMom", &GPartLastMom);
cafMVA->Branch("GPartFirstDaugh", &GPartFirstDaugh);
cafMVA->Branch("GPartLastDaugh", &GPartLastDaugh);
cafMVA->Branch("GPartPx", &GPartPx);
cafMVA->Branch("GPartPy", &GPartPy);
cafMVA->Branch("GPartPz", &GPartPz);
cafMVA->Branch("GPartE", &GPartE);
cafMVA->Branch("GPartMass", &GPartMass);
//Number of final state particle (primaries)
cafMVA->Branch("nFSP", &_nFSP);
//MC Particle info
cafMVA->Branch("detected", &detected);
cafMVA->Branch("pdgmother", &pdgmother);
cafMVA->Branch("MCPTime", &mctime);
cafMVA->Branch("MCPStartX", &_MCPStartX);
cafMVA->Branch("MCPStartY", &_MCPStartY);
cafMVA->Branch("MCPStartZ", &_MCPStartZ);
cafMVA->Branch("motherid", &motherid);
cafMVA->Branch("mctrkid", &mctrkid);
cafMVA->Branch("truepx", &truepx);
cafMVA->Branch("truepy", &truepy);
cafMVA->Branch("truepz", &truepz);
cafMVA->Branch("MCPEndX", &_MCPEndX);
cafMVA->Branch("MCPEndY", &_MCPEndY);
cafMVA->Branch("MCPEndZ", &_MCPEndZ);
cafMVA->Branch("MCProc", &_MCProc);
cafMVA->Branch("MCEndProc", &_MCEndProc);
cafMVA->Branch("angle", &_angle);
cafMVA->Branch("truep", &truep);
cafMVA->Branch("truepdg", &truepdg);
//Reco info
cafMVA->Branch("recopid", &recopid);
cafMVA->Branch("recopidecal", &recopidecal);
cafMVA->Branch("trkLen", &trkLen);
cafMVA->Branch("trkLenPerp", &trkLenPerp);
cafMVA->Branch("preco", &_preco);
cafMVA->Branch("anglereco", &anglereco);
cafMVA->Branch("erecon", &erecon);
cafMVA->Branch("etime", &etime);
cafMVA->Branch("prob_arr", &prob_arr);
//Geometry
cafMVA->Branch("isFidStart", &isFidStart);
cafMVA->Branch("isTPCStart", &isTPCStart);
cafMVA->Branch("isCaloStart", &isCaloStart);
cafMVA->Branch("isInBetweenStart", &isInBetweenStart);
cafMVA->Branch("isThroughCaloStart", &isThroughCaloStart);
cafMVA->Branch("isBarrelStart", &isBarrelStart);
cafMVA->Branch("isEndcapStart", &isEndcapStart);
cafMVA->Branch("isFidEnd", &isFidEnd);
cafMVA->Branch("isTPCEnd", &isTPCEnd);
cafMVA->Branch("isCaloEnd", &isCaloEnd);
cafMVA->Branch("isThroughCaloEnd", &isThroughCaloEnd);
cafMVA->Branch("isInBetweenEnd", &isInBetweenEnd);
cafMVA->Branch("isBarrelEnd", &isBarrelEnd);
cafMVA->Branch("isEndcapEnd", &isEndcapEnd);
return true;
}
}
void CAF::CloseTFile()
{
if(cafFile != nullptr) {
cafFile->Close();
return;
}
else{ return; }
}
void CAF::WriteTTree()
{
if(cafMVA != nullptr) {
cafFile->cd();
cafMVA->Write();
cafFile->Close();
}
return;
}
void CAF::FillTTree()
{
if(cafMVA != nullptr) {
cafFile->cd();
cafMVA->Fill();
}
return;
}
void CAF::ClearVectors()
{
//Generator values
mode.clear();
ccnc.clear();
ntype.clear();
gint.clear();
weight.clear();
tgtpdg.clear();
gt_t.clear();
intert.clear();
q2.clear();
w.clear();
y.clear();
x.clear();
theta.clear();
t.clear();
mcnupx.clear();
mcnupy.clear();
mcnupz.clear();
vertx.clear();
verty.clear();
vertz.clear();
nGPart.clear();
GPartPdg.clear();
GPartStatus.clear();
GPartName.clear();
GPartFirstMom.clear();
GPartLastMom.clear();
GPartFirstDaugh.clear();
GPartLastDaugh.clear();
GPartPx.clear();
GPartPy.clear();
GPartPz.clear();
GPartE.clear();
GPartMass.clear();
//MC Particle values
_nFSP.clear();
pdgmother.clear();
truepdg.clear();
mctime.clear();
mctrkid.clear();
motherid.clear();
_MCPStartX.clear();
_MCPStartY.clear();
_MCPStartZ.clear();
_MCPEndX.clear();
_MCPEndY.clear();
_MCPEndZ.clear();
_MCProc.clear();
_MCEndProc.clear();
trkLen.clear();
trkLenPerp.clear();
truep.clear();
truepx.clear();
truepy.clear();
truepz.clear();
_angle.clear();
//Reco values
detected.clear();
recopid.clear();
recopidecal.clear();
prob_arr.clear();
anglereco.clear();
_preco.clear();
erecon.clear();
etime.clear();
//Geometry
isFidStart.clear();
isTPCStart.clear();
isCaloStart.clear();
isThroughCaloStart.clear();
isInBetweenStart.clear();
isBarrelStart.clear();
isEndcapStart.clear();
isFidEnd.clear();
isTPCEnd.clear();
isCaloEnd.clear();
isThroughCaloEnd.clear();
isInBetweenEnd.clear();
isBarrelEnd.clear();
isEndcapEnd.clear();
}
bool CAF::CheckVectorSize()
{
bool isOK = true;
if(_nFSP.at(0) != pdgmother.size()) isOK = false;
if(_nFSP.at(0) != truepdg.size()) isOK = false;
if(_nFSP.at(0) != mctime.size()) isOK = false;
if(_nFSP.at(0) != mctrkid.size()) isOK = false;
if(_nFSP.at(0) != motherid.size()) isOK = false;
if(_nFSP.at(0) != _MCPStartX.size()) isOK = false;
if(_nFSP.at(0) != _MCPStartY.size()) isOK = false;
if(_nFSP.at(0) != _MCPStartZ.size()) isOK = false;
if(_nFSP.at(0) != _MCPEndX.size()) isOK = false;
if(_nFSP.at(0) != _MCPEndY.size()) isOK = false;
if(_nFSP.at(0) != _MCPEndZ.size()) isOK = false;
if(_nFSP.at(0) != _MCProc.size()) isOK = false;
if(_nFSP.at(0) != _MCEndProc.size()) isOK = false;
if(_nFSP.at(0) != trkLen.size()) isOK = false;
if(_nFSP.at(0) != trkLenPerp.size()) isOK = false;
if(_nFSP.at(0) != truep.size()) isOK = false;
if(_nFSP.at(0) != truepx.size()) isOK = false;
if(_nFSP.at(0) != truepy.size()) isOK = false;
if(_nFSP.at(0) != truepz.size()) isOK = false;
if(_nFSP.at(0) != _angle.size()) isOK = false;
//Reco values
if(_nFSP.at(0) != recopid.size()) isOK = false;
if(_nFSP.at(0) != detected.size()) isOK = false;
if(_nFSP.at(0) != recopidecal.size()) isOK = false;
// if(_nFSP.at(0) != prob_arr.size()) isOK = false;
if(_nFSP.at(0) != anglereco.size()) isOK = false;
if(_nFSP.at(0) != _preco.size()) isOK = false;
if(_nFSP.at(0) != erecon.size()) isOK = false;
if(_nFSP.at(0) != etime.size()) isOK = false;
//Geometry
if(_nFSP.at(0) != isFidStart.size()) isOK = false;
if(_nFSP.at(0) != isTPCStart.size()) isOK = false;
if(_nFSP.at(0) != isCaloStart.size()) isOK = false;
if(_nFSP.at(0) != isThroughCaloStart.size()) isOK = false;
if(_nFSP.at(0) != isInBetweenStart.size()) isOK = false;
if(_nFSP.at(0) != isBarrelStart.size()) isOK = false;
if(_nFSP.at(0) != isEndcapStart.size()) isOK = false;
if(_nFSP.at(0) != isFidEnd.size()) isOK = false;
if(_nFSP.at(0) != isTPCEnd.size()) isOK = false;
if(_nFSP.at(0) != isCaloEnd.size()) isOK = false;
if(_nFSP.at(0) != isThroughCaloEnd.size()) isOK = false;
if(_nFSP.at(0) != isInBetweenEnd.size()) isOK = false;
if(_nFSP.at(0) != isBarrelEnd.size()) isOK = false;
if(_nFSP.at(0) != isEndcapEnd.size()) isOK = false;
return isOK;
}
float CAF::calcGluck(double sigmaX, double B, double X0, float nHits, double mom, double length, double& ratio)
{
double sig_meas = sqrt(720./(nHits+4))*( (0.01*sigmaX*mom)/(0.0001*0.3*B*length*length) );
double sig_mcs = (0.052/B)*sqrt( 1.43/(0.0001*X0*length) );
double sigma = sqrt(sig_meas*sig_meas + sig_mcs*sig_mcs);
ratio = sig_meas/sig_mcs;
return sigma;
}
// main loop function
void CAF::loop()
{
//double gastpc_len = 5.; // track length cut in cm
const float gastpc_len = 2.; // new track length cut in cm based on Thomas' study of low energy protons
// dont care about electrons -- check momentum and see if hit ECAL
const float gastpc_B = 0.5; // B field strength in Tesla
const float gastpc_padPitch = 1.0; // 1 mm. Actual pad pitch varies, which is going to be impossible to implement
const float gastpc_X0 = 1300.; // cm = 13m radiation length
//Resolution for short tracks //TODO check this numbers!
const float sigmaP_short = 0.1; //in GeV
// point resolution
const float sigma_x = 0.1;
std::vector<float> v;
for (float pit = 0.040; pit < 20.0; pit += 0.001)
{
v.push_back(pit);
}
//as function of KE
//0 -> 50 MeV ~ 20%
//> 50 MeV ~ 40%
const float NeutronECAL_detEff[2] = {0.2, 0.4};
const float sigmaNeutronECAL_first = 0.11;
//TODO fraction of rescatters
// float sigmaNeutronECAL_rescatter = 0.26;
//ECAL energy resolution sigmaE/E
const float ECAL_stock = 0.06; //in %
const float ECAL_const = 0.02;
TF1 *fRes = new TF1("fRes", "TMath::Sqrt ( [0]*[0]/x + [1]*[1] )");
fRes->FixParameter(0, ECAL_stock);
fRes->FixParameter(1, ECAL_const);
//ECAL sampling fraction
// double sampling_frac = 4.32;
//ECAL nlayers
const int nLayers = 60;
//ECAL MIP resolution (based on AHCAL numbers)
const double ECAL_MIP_Res = 0.23;
//MIP2GeV conversion factor
const double MIP2GeV_factor = 0.814 / 1000;
//float ECAL_pi0_resolution = 0.13; //sigmaE/E in between at rest (17%) and high energy (~few %)
const float ECAL_time_resolution = 1.; // 1 ns time resolution
TParticlePDG *neutron = TDatabasePDG::Instance()->GetParticle(2112);
const float neutron_mass = neutron->Mass(); //in GeV
//TParticlePDG *pi0 = TDatabasePDG::Instance()->GetParticle(111);
//float pi0_mass = pi0->Mass(); //in GeV
TString filename="${DUNE_PARDATA_DIR}/MPD/dedxPID/dedxpidmatrices8kevcm.root";
TFile infile(filename,"READ");
m_pidinterp.clear();
char str[11];
for (int q = 0; q < 501; ++q)
{
sprintf(str, "%d", q);
std::string s = "pidmatrix";
s.append(str);
// read the 500 histograms one by one; each histogram is a
// 6 by 6 matrix of probabilities for a given momentum value
m_pidinterp.insert( std::make_pair(q, (TH2F*) infile.Get(s.c_str())->Clone("pidinterp")) );
}
// infile.Close();
//------------------------------------------------------------------------
int Event = 0;
int SubRun = 0;
int Run = 0;
std::vector<float> *MC_Q2 = 0;
TBranch *b_MC_Q2 = 0;
std::vector<float> *MC_W = 0;
TBranch *b_MC_W = 0;
std::vector<float> *MC_Y = 0;
TBranch *b_MC_Y = 0;
std::vector<float> *MC_X = 0;
TBranch *b_MC_X = 0;
std::vector<float> *MC_Theta = 0;
TBranch *b_MC_Theta = 0;
std::vector<float> *MCVertX = 0;
TBranch *b_MCVertX = 0;
std::vector<float> *MCVertY = 0;
TBranch *b_MCVertY = 0;
std::vector<float> *MCVertZ = 0;
TBranch *b_MCVertZ = 0;
std::vector<float> *MCNuPx = 0;
TBranch *b_MCNuPx = 0;
std::vector<float> *MCNuPy = 0;
TBranch *b_MCNuPy = 0;
std::vector<float> *MCNuPz = 0;
TBranch *b_MCNuPz = 0;
std::vector<int> *NType = 0;
TBranch *b_NType = 0;
std::vector<int> *CCNC = 0;
TBranch *b_CCNC = 0;
std::vector<int> *Mode = 0;
TBranch *b_Mode = 0;
std::vector<int> *Gint=0;
TBranch *b_Gint = 0;
std::vector<int> *TgtPDG = 0;
TBranch *b_TgtPDG = 0;
std::vector<int> *GT_T = 0;
TBranch *b_GT_T = 0;
std::vector<int> *InterT=0;
TBranch *b_InterT = 0;
std::vector<float> *Weight = 0;
TBranch *b_Weight = 0;
std::vector<int> *_nGPart = 0;
TBranch *b_nGPart = 0;
std::vector<int> *_GPartPdg = 0;
TBranch *b_GPartPdg = 0;
std::vector<int> *_GPartStatus = 0;
TBranch *b_GPartStatus = 0;
std::vector<std::string> *_GPartName = 0;
TBranch *b_GPartName = 0;
std::vector<int> *_GPartFirstMom = 0;
TBranch *b_GPartFirstMom = 0;
std::vector<int> *_GPartLastMom = 0;
TBranch *b_GPartLastMom = 0;
std::vector<int> *_GPartFirstDaugh = 0;
TBranch *b_GPartFirstDaugh = 0;
std::vector<int> *_GPartLastDaugh = 0;
TBranch *b_GPartLastDaugh = 0;
std::vector<float> *_GPartPx = 0;
TBranch *b_GPartPx = 0;
std::vector<float> *_GPartPy = 0;
TBranch *b_GPartPy = 0;
std::vector<float> *_GPartPz = 0;
TBranch *b_GPartPz = 0;
std::vector<float> *_GPartE = 0;
TBranch *b_GPartE = 0;
std::vector<float> *_GPartMass = 0;
TBranch *b_GPartMass = 0;
std::vector<int> *PDG = 0;
TBranch *b_PDG = 0;
std::vector<int> *MCPTrkID = 0;
TBranch *b_MCPTrkID = 0;
std::vector<int> *MCMotherTrkID = 0;
TBranch *b_MCMotherTrkID = 0;
std::vector<int> *PDGMother = 0;
TBranch *b_PDGMother = 0;
std::vector<float> *MCPTime = 0;
TBranch *b_MCPTime = 0;
std::vector<float> *MCPStartX = 0;
TBranch *b_MCPStartX = 0;
std::vector<float> *MCPStartY = 0;
TBranch *b_MCPStartY = 0;
std::vector<float> *MCPStartZ = 0;
TBranch *b_MCPStartZ = 0;
std::vector<float> *MCPStartPX = 0;
TBranch *b_MCPStartPX = 0;
std::vector<float> *MCPStartPY = 0;
TBranch *b_MCPStartPY = 0;
std::vector<float> *MCPStartPZ = 0;
TBranch *b_MCPStartPZ = 0;
std::vector<std::string> *MCPProc = 0;
TBranch *b_MCPProc = 0;
std::vector<std::string> *MCPEndProc = 0;
TBranch *b_MCPEndProc = 0;
std::vector<float> *MCPEndX = 0;
TBranch *b_MCPEndX = 0;
std::vector<float> *MCPEndY = 0;
TBranch *b_MCPEndY = 0;
std::vector<float> *MCPEndZ = 0;
TBranch *b_MCPEndZ = 0;
std::vector<float> *TrajMCPX = 0;
TBranch *b_TrajMCPX = 0;
std::vector<float> *TrajMCPY = 0;
TBranch *b_TrajMCPY = 0;
std::vector<float> *TrajMCPZ = 0;
TBranch *b_TrajMCPZ = 0;
std::vector<int> *TrajMCPTrajIndex = 0;
TBranch *b_TrajMCPTrajIndex = 0;
_inttree->SetBranchAddress("Event", &Event);
_inttree->SetBranchAddress("SubRun", &SubRun);
_inttree->SetBranchAddress("Run", &Run);
//Generator info
_inttree->SetBranchAddress("NType", &NType, &b_NType);
_inttree->SetBranchAddress("CCNC", &CCNC, &b_CCNC);
_inttree->SetBranchAddress("MC_Q2", &MC_Q2, &b_MC_Q2);
_inttree->SetBranchAddress("MC_W", &MC_W, &b_MC_W);
_inttree->SetBranchAddress("MC_Y", &MC_Y, &b_MC_Y);
_inttree->SetBranchAddress("MC_X", &MC_X, &b_MC_X);
_inttree->SetBranchAddress("MC_Theta", &MC_Theta, &b_MC_Theta);
_inttree->SetBranchAddress("Mode", &Mode, &b_Mode);
_inttree->SetBranchAddress("Gint", &Gint, &b_Gint);
_inttree->SetBranchAddress("TgtPDG", &TgtPDG, &b_TgtPDG);
_inttree->SetBranchAddress("GT_T", >_T, &b_GT_T);
_inttree->SetBranchAddress("MCVertX", &MCVertX, &b_MCVertX);
_inttree->SetBranchAddress("MCVertY", &MCVertY, &b_MCVertY);
_inttree->SetBranchAddress("MCVertZ", &MCVertZ, &b_MCVertZ);
_inttree->SetBranchAddress("MCNuPx", &MCNuPx, &b_MCNuPx);
_inttree->SetBranchAddress("MCNuPy", &MCNuPy, &b_MCNuPy);
_inttree->SetBranchAddress("MCNuPz", &MCNuPz, &b_MCNuPz);
_inttree->SetBranchAddress("InterT", &InterT, &b_InterT);
_inttree->SetBranchAddress("Weight", &Weight, &b_Weight);
_inttree->SetBranchAddress("nGPart", &_nGPart, &b_nGPart);
_inttree->SetBranchAddress("GPartPdg", &_GPartPdg, &b_GPartPdg);
_inttree->SetBranchAddress("GPartStatus", &_GPartStatus, &b_GPartStatus);
_inttree->SetBranchAddress("GPartName", &_GPartName, &b_GPartName);
_inttree->SetBranchAddress("GPartFirstMom", &_GPartFirstMom, &b_GPartFirstMom);
_inttree->SetBranchAddress("GPartLastMom", &_GPartLastMom, &b_GPartLastMom);
_inttree->SetBranchAddress("GPartFirstDaugh", &_GPartFirstDaugh, &b_GPartFirstDaugh);
_inttree->SetBranchAddress("GPartLastDaugh", &_GPartLastDaugh, &b_GPartLastDaugh);
_inttree->SetBranchAddress("GPartPx", &_GPartPx, &b_GPartPx);
_inttree->SetBranchAddress("GPartPy", &_GPartPy, &b_GPartPy);
_inttree->SetBranchAddress("GPartPz", &_GPartPz, &b_GPartPz);
_inttree->SetBranchAddress("GPartE", &_GPartE, &b_GPartE);
_inttree->SetBranchAddress("GPartMass", &_GPartMass, &b_GPartMass);
//MC info
_inttree->SetBranchAddress("PDG", &PDG, &b_PDG);
_inttree->SetBranchAddress("MCTrkID", &MCPTrkID, &b_MCPTrkID);
_inttree->SetBranchAddress("MotherTrkID", &MCMotherTrkID, &b_MCMotherTrkID);
_inttree->SetBranchAddress("MCPTime", &MCPTime, &b_MCPTime);
_inttree->SetBranchAddress("MCPStartX", &MCPStartX, &b_MCPStartX);
_inttree->SetBranchAddress("MCPStartY", &MCPStartY, &b_MCPStartY);
_inttree->SetBranchAddress("MCPStartZ", &MCPStartZ, &b_MCPStartZ);
_inttree->SetBranchAddress("MCPEndX", &MCPEndX, &b_MCPEndX);
_inttree->SetBranchAddress("MCPEndY", &MCPEndY, &b_MCPEndY);
_inttree->SetBranchAddress("MCPEndZ", &MCPEndZ, &b_MCPEndZ);
_inttree->SetBranchAddress("PDGMother", &PDGMother, &b_PDGMother);
_inttree->SetBranchAddress("MCPStartPX", &MCPStartPX, &b_MCPStartPX);
_inttree->SetBranchAddress("MCPStartPY", &MCPStartPY, &b_MCPStartPY);
_inttree->SetBranchAddress("MCPStartPZ", &MCPStartPZ, &b_MCPStartPZ);
_inttree->SetBranchAddress("MCPProc", &MCPProc, &b_MCPProc);
_inttree->SetBranchAddress("MCPEndProc", &MCPEndProc, &b_MCPEndProc);
_inttree->SetBranchAddress("TrajMCPX", &TrajMCPX, &b_TrajMCPX);
_inttree->SetBranchAddress("TrajMCPY", &TrajMCPY, &b_TrajMCPY);
_inttree->SetBranchAddress("TrajMCPZ", &TrajMCPZ, &b_TrajMCPZ);
// _inttree->SetBranchAddress("TrajMCPTrajIndex", &TrajMCPTrajIndex);
_inttree->SetBranchAddress("TrajMCPTrackID", &TrajMCPTrajIndex, &b_TrajMCPTrajIndex);
//gamma, neutron, pi0, k0L, k0S, k0, delta0
std::vector<int> neutrinos = {12, 14, 16};
std::vector<int> pdg_neutral = {22, 2112, 111, 130, 310, 311, 2114};
//pion, muon, proton, kaon, deuteron, electron
std::vector<int> pdg_charged = {211, 13, 2212, 321, 1000010020, 11};
//-------------------------------------------------------------------
// Main event loop
for( int entry = 0; entry < _inttree->GetEntries(); entry++ )
{
_inttree->GetEntry(entry);
this->ClearVectors();
//Filling MCTruth values
// std::cout << "Event " << Event << " Run " << Run << std::endl;
// if(Event < 259) continue;
_Event = Event;
_Run = Run;
_SubRun = SubRun;
for(size_t i = 0; i < NType->size(); i++)
{
ccnc.push_back(CCNC->at(i));
ntype.push_back(NType->at(i));
q2.push_back(MC_Q2->at(i));
w.push_back(MC_W->at(i));
y.push_back(MC_Y->at(i));
x.push_back(MC_X->at(i));
theta.push_back(MC_Theta->at(i));
mode.push_back(Mode->at(i));
intert.push_back(InterT->at(i));
if(_correct4origin){
vertx.push_back(MCVertX->at(i) - _util->GetOrigin()[0]);
verty.push_back(MCVertY->at(i) - _util->GetOrigin()[1]);
vertz.push_back(MCVertZ->at(i) - _util->GetOrigin()[2]);
} else {
vertx.push_back(MCVertX->at(i));
verty.push_back(MCVertY->at(i));
vertz.push_back(MCVertZ->at(i));
}
mcnupx.push_back(MCNuPx->at(i));
mcnupy.push_back(MCNuPy->at(i));
mcnupz.push_back(MCNuPz->at(i));
}
for(size_t i = 0; i < Gint->size(); i++)
{
gint.push_back(Gint->at(i));
tgtpdg.push_back(TgtPDG->at(i));//target pdg
gt_t.push_back(GT_T->at(i));
weight.push_back(Weight->at(i));
}
for(size_t i = 0; i < _nGPart->size(); i++)
{
nGPart.push_back(_nGPart->at(i));
for(int j = 0; j < _nGPart->at(i); j++) {
GPartPdg.push_back(_GPartPdg->at(j));
GPartStatus.push_back(_GPartStatus->at(j));
GPartName.push_back(_GPartName->at(j));
GPartFirstMom.push_back(_GPartFirstMom->at(j));
GPartLastMom.push_back(_GPartLastMom->at(j));
GPartFirstDaugh.push_back(_GPartFirstDaugh->at(j));
GPartLastDaugh.push_back(_GPartLastDaugh->at(j));
GPartPx.push_back(_GPartPx->at(j));
GPartPy.push_back(_GPartPy->at(j));
GPartPz.push_back(_GPartPz->at(j));
GPartE.push_back(_GPartE->at(j));
GPartMass.push_back(_GPartMass->at(j));
}
}
//--------------------------------------------------------------------------
// Start of Parameterized Reconstruction
//--------------------------------------------------------------------------
unsigned int nFSP = 0;
//TODO we should skip particles that we don't see or cannot reconstruct! change filling caf with i to index counting the particle
//have to be careful with indexes and continue
//---------------------------------------------------------------
// all Gluckstern calculations happen in the following loop
for(size_t i = 0; i < MCPStartPX->size(); i++ )
{
//Get the creating process
std::string mcp_process = MCPProc->at(i);
//Get ending process
std::string mcp_endprocess = MCPEndProc->at(i);
int mctrackid = MCPTrkID->at(i);
int pdg = PDG->at(i);
const TVector3 spoint(MCPStartX->at(i) - _util->GetOrigin()[0], MCPStartY->at(i) - _util->GetOrigin()[1], MCPStartZ->at(i) - _util->GetOrigin()[2]);
const TVector3 epoint(MCPEndX->at(i) - _util->GetOrigin()[0], MCPEndY->at(i) - _util->GetOrigin()[1], MCPEndZ->at(i) - _util->GetOrigin()[2]);
TVector3 mcp(MCPStartPX->at(i), MCPStartPY->at(i), MCPStartPZ->at(i));
float ptrue = (mcp).Mag();
float pypz = std::sqrt( MCPStartPY->at(i)*MCPStartPY->at(i) + MCPStartPZ->at(i)*MCPStartPZ->at(i));
//need to ignore neutrals for this - put the value to 0
auto result = std::find(pdg_neutral.begin(), pdg_neutral.end(), abs(pdg));
bool isNeutral = (result != pdg_neutral.end()) ? true : false;
//start track length
//***************************************************************************************************************/
if( isNeutral )
{
trkLen.push_back(-1);
trkLenPerp.push_back(-1);
}
else
{
// calculate the total and the transverse track lengths and restrict the
// tracklength to be above the gas TPC track length threshold
double tracklen = 0.;
double tracklen_perp = 0.;
//CAREFUL No offset for the trajectory points (origin for them is the TPC?)??????
//TODO check if the mcp point is within the TPC volume! Skip for mcp in the ECAL (showers)
//TODO Link showers to original mcp?
for(size_t itraj = 1; itraj < TrajMCPX->size(); itraj++)
{
//check that it is the correct mcp
if(TrajMCPTrajIndex->at(itraj) == mctrackid)
{
//Traj point+1
TVector3 point(TrajMCPX->at(itraj) - _util->GetOrigin()[0], TrajMCPY->at(itraj) - _util->GetOrigin()[1], TrajMCPZ->at(itraj) - _util->GetOrigin()[2]);
//point is not in the TPC anymore - stop traj loop
if(not _util->PointInTPC(point))
{
// // std::cout << "Point not within the TPC: " << point.X() << " r " << std::sqrt(point.Y()*point.Y() + point.Z()*point.Z()) << std::endl;
continue;
}
// find the length of the track by getting the distance between each hit
TVector3 diff(TrajMCPX->at(itraj) - TrajMCPX->at(itraj-1), TrajMCPY->at(itraj) - TrajMCPY->at(itraj-1), TrajMCPZ->at(itraj) - TrajMCPZ->at(itraj-1));
// perp length
TVector2 tracklen_perp_vec(TrajMCPZ->at(itraj) - TrajMCPZ->at(itraj-1), TrajMCPY->at(itraj) - TrajMCPY->at(itraj-1));
// Summing up
tracklen += diff.Mag();
tracklen_perp += tracklen_perp_vec.Mod();
}
}
trkLen.push_back(tracklen);
trkLenPerp.push_back(tracklen_perp);
}
//end track length
//***************************************************************************************************************/
TVector3 xhat(1, 0, 0);
// float pz = mcp.Z();
// float pt = (mcp.Cross(xhat)).Mag();
// float px = mcp.X();
// float py = mcp.Y();
//float mctrackid = MCPTrkID->at(i);
// angle with respect to the incoming neutrino
float angle = atan(mcp.X() / mcp.Z());
float ecaltime = _util->GaussianSmearing(MCPTime->at(i), ECAL_time_resolution);
float time = MCPTime->at(i);
//Check where start point is for the mcp
isFidStart.push_back(_util->PointInFiducial(spoint));
isTPCStart.push_back(_util->PointInTPC(spoint));
isCaloStart.push_back(_util->PointInCalo(spoint));
isThroughCaloStart.push_back(_util->isThroughCalo(spoint));
isInBetweenStart.push_back(_util->PointStopBetween(spoint));
isBarrelStart.push_back(_util->isBarrel(spoint));
isEndcapStart.push_back(_util->isEndcap(spoint));
//Check where endpoint of mcp is
isFidEnd.push_back(_util->PointInFiducial(epoint));
isTPCEnd.push_back(_util->PointInTPC(epoint));
isCaloEnd.push_back(_util->PointInCalo(epoint));
isThroughCaloEnd.push_back(_util->isThroughCalo(epoint));
isInBetweenEnd.push_back(_util->PointStopBetween(epoint));
isBarrelEnd.push_back(_util->isBarrel(epoint));
isEndcapEnd.push_back(_util->isEndcap(epoint));
//start tpc
//***************************************************************************************************************/
//Visible in the TPC
if( trkLen.at(nFSP) > gastpc_len )
{
for (int pidm = 0; pidm < 6; ++pidm)
{
if ( abs(pdg) == pdg_charged.at(pidm) )
{
// // std::cout << "Entered reco TPC" << std::endl;
//Use range instead of Gluckstern for stopping tracks
//TODO is that correct? What if it is a scatter in the TPC? Need to check if daughter is same particle
float preco = 0;
// save the true PDG, parametrized PID comes later
truepdg.push_back(pdg);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
// save the true momentum
truep.push_back(ptrue);
// save the true angle
_angle.push_back(angle);
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
//Case for range, the end point of the mcp is in the TPC, does not reach the ecal
if( _util->PointInTPC(epoint) )
{
// calculate number of trackpoints
float nHits = round (trkLen.at(nFSP) / gastpc_padPitch);
// angular resolution first term
float sigma_angle_1 = ((sigma_x * sigma_x * 0.0001) / trkLen.at(nFSP)*trkLen.at(nFSP)*0.0001) * (12*(nHits-1))/(nHits*(nHits+1));
// scattering term in Gluckstern formula
float sigma_angle_2 = (0.015*0.015 / (3. * ptrue * ptrue)) * (trkLen.at(nFSP)/gastpc_X0);
// angular resolution from the two terms above
float sigma_angle_short = sqrt(sigma_angle_1 + sigma_angle_2);
//reconstructed angle
float angle_reco = _util->GaussianSmearing(angle, sigma_angle_short);
//reconstructed momentum
preco = _util->GaussianSmearing( ptrue, sigmaP_short );
if(preco > 0)
_preco.push_back(preco);
else
_preco.push_back(-1);
anglereco.push_back(angle_reco);
erecon.push_back(-1);
recopidecal.push_back(-1);
etime.push_back(-1);
detected.push_back(-1);
}
else
{
//Case where the endpoint is not in the TPC, should be able to use the Gluckstern formula
// calculate number of trackpoints
// float nHits = round (trkLen.at(nFSP) / gastpc_padPitch);
// // measurement term in Gluckstern formula
// float fracSig_meas = sqrt(720./(nHits+4)) * ((0.01*gastpc_padPitch*ptrue) / (0.3 * gastpc_B * 0.0001 *trkLenPerp.at(nFSP)*trkLenPerp.at(nFSP)));
// // multiple Coulomb scattering term in Gluckstern formula
// float fracSig_MCS = (0.052*sqrt(1.43)) / (gastpc_B * sqrt(gastpc_X0*trkLenPerp.at(nFSP)*0.0001));
// // momentum resoltion from the two terms above
// float sigmaP = ptrue * sqrt( fracSig_meas*fracSig_meas + fracSig_MCS*fracSig_MCS );
// // now Gaussian smear the true momentum using the momentum resolution
// preco = _util->GaussianSmearing( ptrue, sigmaP );
//<NAME>
int nHits = round (trkLen.at(nFSP) / gastpc_padPitch);
double ratio = 0.;
float sigmaPt = pypz*calcGluck(sigma_x, gastpc_B, gastpc_X0, nHits, pypz, trkLenPerp.at(nFSP), ratio);
float tan_lambda = MCPStartPX->at(i)/pypz;
float lambda = atan2(MCPStartPX->at(i), pypz); // between -pi and +pi
float del_lambda = 0.0062;
float temp = pypz*tan_lambda*del_lambda;
float sigmaP = (1./cos(lambda))*sqrt(sigmaPt*sigmaPt + temp*temp);
// now Gaussian smear the true momentum using the momentum resolution
preco = _util->GaussianSmearing( ptrue, sigmaP );
// measurement term in the Gluckstern formula for calculating the
// angular resolution
float sigma_angle_1 = ((sigma_x * sigma_x * 0.0001) / trkLen.at(nFSP)*trkLen.at(nFSP)*0.0001) * (12*(nHits-1))/(nHits*(nHits+1));
// scattering term in Gluckstern formula
float sigma_angle_2 = (0.015*0.015 / (3. * ptrue * ptrue)) * (trkLen.at(nFSP)/gastpc_X0);
// angular resolution from the two terms above
float sigma_angle = sqrt(sigma_angle_1 + sigma_angle_2);
// now Gaussian smear the true angle using the angular resolution
float angle_reco = _util->GaussianSmearing(angle, sigma_angle);
// save reconstructed momentum and angle to cafanatree
if(preco > 0)
_preco.push_back(preco);
else
_preco.push_back(-1);
anglereco.push_back(angle_reco);
//Reaches the ECAL and stops there
if( _util->PointInCalo(epoint) )
{
//Need energy measurement in ecal
TParticlePDG *part = TDatabasePDG::Instance()->GetParticle(abs(pdg));
if(nullptr == part)
{
// std::cout << "Could not find particle in root pdg table, pdg " << pdg << std::endl;
//deuteron
if( pdg == 1000010020 ) {
float mass = 1.8756;//in GeV mass deuteron
float etrue = std::sqrt(ptrue*ptrue + mass*mass) - mass;//needs to be KE here
float ECAL_resolution = fRes->Eval(etrue)*etrue;
float ereco = _util->GaussianSmearing(etrue, ECAL_resolution);
erecon.push_back(ereco);
recopidecal.push_back(-1);
detected.push_back(1);
etime.push_back(ecaltime);
}
else
{
erecon.push_back(-1);
recopidecal.push_back(-1);
detected.push_back(0);
etime.push_back(-1);
}
}
else
{
//by default should be tagged as an electron as it has a track,
//otherwise tag as gamma if not track -> need mis association rate, and use dE/dX in Scintillator?
//separation between e and mu/pi should be around 100%
//separation mu/pi -> based on Chris study with only the ECAL (no Muon ID detector)
//separation with p and mu/pi/e ?? high energy -> confusion with mu/pi, low energy confusion with e
//using E/p to ID?
float mass = part->Mass();//in GeV
float etrue = std::sqrt(ptrue*ptrue + mass*mass);//Just energy here is fine
float ECAL_resolution = fRes->Eval(etrue)*etrue;
float ereco = _util->GaussianSmearing(etrue, ECAL_resolution);
erecon.push_back((ereco > 0) ? ereco : 0.);
detected.push_back(1);
etime.push_back(ecaltime);
// // std::cout << "E/p " << ereco/preco << " true pdg " << pdg << std::endl;
//Electron
if( abs(pdg) == 11 ){
recopidecal.push_back(11);
}
else if( abs(pdg) == 13 || abs(pdg) == 211 )
{
//Muons and Pions
//ptrue < 480 MeV/c 100% separation
//80% from 480 to 750
//90% up to 750 to 900
//95% over 900
float random_number = _util->GetRamdomNumber();
if(ptrue < 0.48) {
recopidecal.push_back(abs(pdg));//100% efficiency by range
}
else if(ptrue >= 0.48 && ptrue < 0.75)
{
//case muon
if(abs(pdg) == 13)
{
if(random_number > (1 - 0.8)) {
recopidecal.push_back(13);
}
else{
recopidecal.push_back(211);
}
}
//case pion
if(abs(pdg) == 211)
{
if(random_number > (1 - 0.8)) {
recopidecal.push_back(211);
}
else{
recopidecal.push_back(13);
}
}
}
else if(ptrue >= 0.75 && ptrue < 0.9)
{
//case muon
if(abs(pdg) == 13){
if(random_number > (1 - 0.9)) {
recopidecal.push_back(13);
}
else{
recopidecal.push_back(211);
}
}
//case pion
if(abs(pdg) == 211) {
if(random_number > (1 - 0.9)) {
recopidecal.push_back(211);
}
else{
recopidecal.push_back(13);
}
}
}
else
{
//case muon
if(abs(pdg) == 13){
if(random_number > (1 - 0.95)) {
recopidecal.push_back(13);
}
else{
recopidecal.push_back(211);
}
}
//case pion
if(abs(pdg) == 211){
if(random_number > (1 - 0.95)) {
recopidecal.push_back(211);
}
else{
recopidecal.push_back(13);
}
}
}
}
else if( abs(pdg) == 2212 )
{
recopidecal.push_back(2212);//TODO for p/pi separation
}
else {
recopidecal.push_back(-1);
}
}
}
else if( _util->isThroughCalo(epoint) )
{
//Case the endpoint is outside the CALO -> it went through the ECAL (mu/pi/p possible)
//the ECAL will see 60 MIPs on average
double Evis = (double)nLayers; //in MIP
//Smearing to account for Gaussian detector noise (Landau negligible)
Evis = _util->GaussianSmearing(Evis, ECAL_MIP_Res);
//1 MIP = 0.814 MeV
double Erec = Evis * MIP2GeV_factor;
erecon.push_back((Erec > 0) ? Erec : 0.);
etime.push_back(ecaltime);
detected.push_back(1);
//Muon/Pions/Protons are reco as Muons (without MuID detector)
if( abs(pdg) == 13 || abs(pdg) == 211 || abs(pdg) == 2212 ) {
recopidecal.push_back(13);
}
else{
recopidecal.push_back(-1);
}
}
else
{
//Does not reach the ECAL???
erecon.push_back(-1);
recopidecal.push_back(-1);
etime.push_back(-1);
detected.push_back(0);
}
} //end endpoint is not in TPC
//end tpc
//***************************************************************************************************************/
//start pid
//***************************************************************************************************************/
//--------------------------------------------------------------------------
// Start of PID Parametrization
//--------------------------------------------------------------------------
float p = preco;
// read the PID parametrization ntuple from <NAME>
// TString filename="pid.root";
std::vector<double> vec;
std::vector<std::string> pnamelist = {"#pi", "#mu", "p", "K", "d", "e"};
std::vector<std::string> recopnamelist = {"#pi", "#mu", "p", "K", "d", "e"};
int qclosest = 0;
float dist = 100000000.;
// // std::cout << "preco " << p << " qclosest " << qclosest << std::endl;
for (int q = 0; q < 501; ++q)
{
//Check the title and the reco momentum take only the one that fits
std::string fulltitle = m_pidinterp[q]->GetTitle();
unsigned first = fulltitle.find("=");
unsigned last = fulltitle.find("GeV");
std::string substr = fulltitle.substr(first+1, last - first-1);
float pidinterp_mom = std::atof(substr.c_str());
//calculate the distance between the bin and mom, store the q the closest
float disttemp = std::abs(pidinterp_mom - p);
//// std::cout << disttemp << " " << dist << std::endl;
// // std::cout << "preco " << p << " ptitle " << pidinterp_mom << " dist " << disttemp << " q " << q << std::endl;
if( disttemp < dist ){
dist = disttemp;
qclosest = q;
// // std::cout << "pid mom " << pidinterp_mom << " reco mom " << p << " dist " << dist << " qclosest " << qclosest << std::endl;
}
} // closes the "pidmatrix" loop
// // std::cout << "Started pid" << std::endl;
//loop over the columns (true pid)
std::vector< std::pair<float, std::string> > v_prob;
// // std::cout << "pidm " << pidm << std::endl;
//get true particle name
std::string trueparticlename = m_pidinterp[qclosest]->GetXaxis()->GetBinLabel(pidm+1);
// // std::cout << trueparticlename << std::endl;
if ( trueparticlename == pnamelist[pidm] )
{
//loop over the rows (reco pid)
for (int pidr = 0; pidr < 6; ++pidr)
{
// // std::cout << "pidr " << pidr << std::endl;
std::string recoparticlename = m_pidinterp[qclosest]->GetYaxis()->GetBinLabel(pidr+1);
if (recoparticlename == recopnamelist[pidr])
{
float prob = m_pidinterp[qclosest]->GetBinContent(pidm+1,pidr+1);
prob_arr.push_back(prob);
// // std::cout << "true part " << trueparticlename << " true pid " << pdg_charged.at(pidm) << " reco name " << recoparticlename << " reco part list "
// << recopnamelist[pidr] << " true mom " << ptrue << " reco mom " << p << " prob " << pidinterp->GetBinContent(pidm+1,pidr+1) << '\n';
//Need to check random number value and prob value then associate the recopdg to the reco prob
v_prob.push_back( std::make_pair(prob, recoparticlename) );
}
}
int pid = -1;
if(v_prob.size() > 1)
{
//Order the vector of prob
std::sort(v_prob.begin(), v_prob.end());
//Throw a random number between 0 and 1
float random_number = _util->GetRamdomNumber();
//Make cumulative sum to get the range
std::partial_sum(v_prob.begin(), v_prob.end(), v_prob.begin(), [](const P& _x, const P& _y){return P(_x.first + _y.first, _y.second);});
for(size_t ivec = 0; ivec < v_prob.size()-1; ivec++)
{
if( random_number < v_prob.at(ivec+1).first && random_number >= v_prob.at(ivec).first )
{
pid = pdg_charged.at( std::distance( recopnamelist.begin(), std::find(recopnamelist.begin(), recopnamelist.end(), v_prob.at(ivec+1).second) ) );
}
}
}
else
{
pid = pdg_charged.at( std::distance( recopnamelist.begin(), std::find(recopnamelist.begin(), recopnamelist.end(), v_prob.at(0).second) ) );
}
recopid.push_back( pid );
} // closes the if statement
//end pid
//***************************************************************************************************************/
} // closes the conditional statement of trueparticlename == MC true pdg
else
{
//not in the pdglist of particles but visible in TPC?
auto found = std::find(pdg_charged.begin(), pdg_charged.end(), abs(pdg));
if(found == pdg_charged.end())
{
// // std::cout << "Maybe visible but not {#pi, #mu, p, K, d, e};" << std::endl;
// // std::cout << "pdg " << pdg << std::endl;
truepdg.push_back(pdg);
detected.push_back(0);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
// save the true momentum
truep.push_back(ptrue);
// save the true angle
_angle.push_back(angle);
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
etime.push_back(-1);
erecon.push_back(-1);
_preco.push_back(-1);
anglereco.push_back(-1);
recopid.push_back(-1);
recopidecal.push_back(-1);
for (int pidr = 0; pidr < 6; ++pidr) prob_arr.push_back(-1);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
break; //break out of the loop over the vertical bining!
}
}
} // closes the vertical bining loop of the pid matrix
}//close if track_length > tpc_min_length
else
{
//Not visible in the TPC
//for neutrons
if(std::abs(pdg) == 2112)
{
//start neutrons
//***************************************************************************************************************/
if(_util->PointInCalo(epoint)) //needs to stop in the ECAL
{
//check if it can be detected by the ECAL
//Assumes 40% efficiency to detect
float random_number = _util->GetRamdomNumber();
float true_KE = std::sqrt(ptrue*ptrue + neutron_mass*neutron_mass) - neutron_mass;//KE here
// float true_KE = ptrue*ptrue / (2*neutron_mass); // in GeV
int index = (true_KE >= 0.05) ? 1 : 0;
// // std::cout << "KE " << true_KE << " index " << index << " 1 - eff " << 1-NeutronECAL_detEff[index] << " rdnm " << random_number << std::endl;
if(random_number > (1 - NeutronECAL_detEff[index]) && true_KE > 0.003)//Threshold of 3 MeV
{
//TODO random is first interaction or rescatter and smear accordingly to Chris's study
//Detected in the ECAL
// recopid.push_back(2112);
recopid.push_back(-1); //reco pid set to 0?
detected.push_back(1);
float eres = sigmaNeutronECAL_first * true_KE;
float ereco_KE = _util->GaussianSmearing( true_KE, eres );
float ereco = ereco_KE + neutron_mass;
erecon.push_back(ereco > 0 ? ereco : 0.);
// // std::cout << "true part n true energy " << std::sqrt(ptrue*ptrue + neutron_mass*neutron_mass) << " ereco " << erecon[i] << std::endl;
truepdg.push_back(pdg);
truep.push_back(ptrue);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
etime.push_back(ecaltime);
_angle.push_back(angle);
_preco.push_back(-1);
anglereco.push_back(-1);
recopidecal.push_back(2112);
for (int pidr = 0; pidr < 6; ++pidr) prob_arr.push_back(-1);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
}
else
{
//neutron not detected
detected.push_back(0);
truep.push_back(ptrue);
recopid.push_back(-1);
erecon.push_back(-1);
truepdg.push_back(pdg);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
etime.push_back(-1);
_angle.push_back(angle);
_preco.push_back(-1);
anglereco.push_back(-1);
recopidecal.push_back(-1);
for (int pidr = 0; pidr < 6; ++pidr) prob_arr.push_back(-1);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
}
} //endpoint is in ECAL
else
{
//Endpoint is not in calo (TPC/isInBetween or outside Calo)
detected.push_back(0);
truep.push_back(ptrue);
recopid.push_back(-1);
erecon.push_back(-1);
truepdg.push_back(pdg);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
etime.push_back(-1);
_angle.push_back(angle);
_preco.push_back(-1);
anglereco.push_back(-1);
recopidecal.push_back(-1);
for (int pidr = 0; pidr < 6; ++pidr) prob_arr.push_back(-1);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
}
//End neutrons
//***************************************************************************************************************/
}
else if(std::abs(pdg) == 111) //for pi0s
{
//start pi0s
//***************************************************************************************************************/
erecon.push_back(-1);
recopid.push_back(-1);
detected.push_back(0);
recopidecal.push_back(-1);
truep.push_back(ptrue);
truepdg.push_back(pdg);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
_angle.push_back(angle);
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
etime.push_back(-1);
_preco.push_back(-1);
anglereco.push_back(-1);
for (int pidr = 0; pidr < 6; ++pidr) prob_arr.push_back(-1);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
//end pi0s
//***************************************************************************************************************/
}
else if(std::abs(pdg) == 22)//for gammas
{
//start gammas
//***************************************************************************************************************/
if( PDGMother->at(i) != 111 )
{
//Endpoint is in the ECAL
if(_util->PointInCalo(epoint))
{
//if they hit the ECAL and smear their energy
float ECAL_resolution = fRes->Eval(ptrue)*ptrue;
float ereco = _util->GaussianSmearing(ptrue, ECAL_resolution);
erecon.push_back( (ereco > 0) ? ereco : 0. );
recopid.push_back(-1);
detected.push_back(1);
truep.push_back(ptrue);
truepdg.push_back(pdg);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
_angle.push_back(angle);
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
etime.push_back(ecaltime);
_preco.push_back(-1);
anglereco.push_back(-1);
//reach the ECAL, should be tagged as gamma
recopidecal.push_back(22);
for (int pidr = 0; pidr < 6; ++pidr) prob_arr.push_back(-1);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
}
else if(_util->PointInTPC(epoint) || _util->PointStopBetween(epoint) || _util->isThroughCalo(epoint))
{
//case endpoint is in the TPC (Converted!) or in between the TPC/ECAL
erecon.push_back(-1);
recopid.push_back(-1);
detected.push_back(0);
truep.push_back(ptrue);
truepdg.push_back(pdg);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
_angle.push_back(angle);
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
etime.push_back(-1);
_preco.push_back(-1);
anglereco.push_back(-1);
//converted so not seen in ECAL
recopidecal.push_back(-1);
for (int pidr = 0; pidr < 6; ++pidr) prob_arr.push_back(-1);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
}
else{
}
}
else
{
//case they are from pi0
//Endpoint is not in the tracker, reaches the ecal
if(_util->PointInCalo(epoint))
{
//if they hit the ECAL and smear their energy
float ECAL_resolution = fRes->Eval(ptrue)*ptrue;
float ereco = _util->GaussianSmearing(ptrue, ECAL_resolution);
erecon.push_back((ereco > 0) ? ereco : 0.);
recopid.push_back(-1);
detected.push_back(1);
truep.push_back(ptrue);
truepdg.push_back(pdg);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
_angle.push_back(angle);
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
etime.push_back(ecaltime);
_preco.push_back(-1);
anglereco.push_back(-1);
//reaches the ecal
recopidecal.push_back(22);
for (int pidr = 0; pidr < 6; ++pidr) prob_arr.push_back(-1);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
}
else if(_util->PointInTPC(epoint) || _util->PointStopBetween(epoint) || _util->isThroughCalo(epoint))
{
//from pi0 and converted in TPC or stopped between TPC/ECAL
erecon.push_back(-1);
recopid.push_back(-1);
detected.push_back(0);
truep.push_back(ptrue);
truepdg.push_back(pdg);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
_angle.push_back(angle);
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
etime.push_back(-1);
_preco.push_back(-1);
anglereco.push_back(-1);
//converted not seen by ecal
recopidecal.push_back(-1);
for (int pidr = 0; pidr < 6; ++pidr) prob_arr.push_back(-1);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
}
else{
}
}
//end gammas
//***************************************************************************************************************/
}
else if(std::find(neutrinos.begin(), neutrinos.end(), abs(pdg)) != neutrinos.end())
{
//Case for neutrinos from NC interactions
truepdg.push_back(pdg);
detected.push_back(0);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
// save the true momentum
truep.push_back(ptrue);
// save the true angle
_angle.push_back(angle);
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
etime.push_back(-1);
erecon.push_back(0.);
recopidecal.push_back(-1);
_preco.push_back(-1);
anglereco.push_back(-1);
recopid.push_back(-1);
for (int pidr = 0; pidr < 6; ++pidr) prob_arr.push_back(-1);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
}
else
{
//Case for particles that stop or go through ECAL (problematic particles with no track length????)
//Not visible in the TPC and not neutron or gamma or pi0 (otherwise it has been already done above)
if(_util->PointInCalo(epoint))
{
truepdg.push_back(pdg);
detected.push_back(1);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
// save the true momentum
truep.push_back(ptrue);
// save the true angle
_angle.push_back(angle);
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
etime.push_back(ecaltime);
TParticlePDG *part = TDatabasePDG::Instance()->GetParticle(abs(pdg));
float mass = 0.;
if(nullptr != part)
mass = part->Mass();//in GeV
float etrue = std::sqrt(ptrue*ptrue + mass*mass);
float ECAL_resolution = fRes->Eval(etrue)*etrue;
float ereco = _util->GaussianSmearing(etrue, ECAL_resolution);
erecon.push_back((ereco > 0) ? ereco : 0.);
//Electron
if( abs(pdg) == 11 ){
recopidecal.push_back(11);
}
else if( abs(pdg) == 13 || abs(pdg) == 211 )
{
//Muons and Pions
//ptrue < 480 MeV/c 100% separation
//80% from 480 to 750
//90% up to 750 to 900
//95% over 900
float random_number = _util->GetRamdomNumber();
if(ptrue < 0.48) {
recopidecal.push_back(abs(pdg));//100% efficiency by range
}
else if(ptrue >= 0.48 && ptrue < 0.75)
{
//case muon
if(abs(pdg) == 13)
{
if(random_number > (1 - 0.8)) {
recopidecal.push_back(13);
}
else{
recopidecal.push_back(211);
}
}
//case pion
if(abs(pdg) == 211)
{
if(random_number > (1 - 0.8)) {
recopidecal.push_back(211);
}
else{
recopidecal.push_back(13);
}
}
}
else if(ptrue >= 0.75 && ptrue < 0.9)
{
//case muon
if(abs(pdg) == 13){
if(random_number > (1 - 0.9)) {
recopidecal.push_back(13);
}
else{
recopidecal.push_back(211);
}
}
//case pion
if(abs(pdg) == 211) {
if(random_number > (1 - 0.9)) {
recopidecal.push_back(211);
}
else{
recopidecal.push_back(13);
}
}
}
else
{
//case muon
if(abs(pdg) == 13){
if(random_number > (1 - 0.95)) {
recopidecal.push_back(13);
}
else{
recopidecal.push_back(211);
}
}
//case pion
if(abs(pdg) == 211){
if(random_number > (1 - 0.95)) {
recopidecal.push_back(211);
}
else{
recopidecal.push_back(13);
}
}
}
}
else if( abs(pdg) == 2212 )
{
recopidecal.push_back(2212);//TODO for p/pi separation
}
else {
recopidecal.push_back(-1);
}
_preco.push_back(-1);
anglereco.push_back(-1);
recopid.push_back(-1);
for (int pidr = 0; pidr < 6; ++pidr) prob_arr.push_back(-1);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
}
else if (_util->isThroughCalo(epoint))
{
truepdg.push_back(pdg);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
// save the true momentum
truep.push_back(ptrue);
// save the true angle
_angle.push_back(angle);
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
//Case the endpoint is outside the CALO -> it went through the ECAL (mu/pi/p possible)
//the ECAL will see 60 MIPs on average
double Evis = (double)nLayers; //in MIP
//Smearing to account for Gaussian detector noise (Landau negligible)
Evis = _util->GaussianSmearing(Evis, ECAL_MIP_Res);
//1 MIP = 0.814 MeV
double Erec = Evis * MIP2GeV_factor;
erecon.push_back((Erec > 0) ? Erec : 0.);
etime.push_back(ecaltime);
detected.push_back(1);
//Muon/Pions/Protons are reco as Muons (without MuID detector)
if( abs(pdg) == 13 || abs(pdg) == 211 || abs(pdg) == 2212 ) {
recopidecal.push_back(13);
}
else {
recopidecal.push_back(-1);
}
_preco.push_back(-1);
anglereco.push_back(-1);
recopid.push_back(-1);
for (int pidr = 0; pidr < 6; ++pidr) prob_arr.push_back(-1);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
}
else if(_util->PointInTPC(epoint) || _util->PointStopBetween(epoint))
{
truepdg.push_back(pdg);
detected.push_back(0);
truepx.push_back(MCPStartPX->at(i));
truepy.push_back(MCPStartPY->at(i));
truepz.push_back(MCPStartPZ->at(i));
if(_correct4origin){
_MCPStartX.push_back(MCPStartX->at(i) - _util->GetOrigin()[0]);
_MCPStartY.push_back(MCPStartY->at(i) - _util->GetOrigin()[1]);
_MCPStartZ.push_back(MCPStartZ->at(i) - _util->GetOrigin()[2]);
_MCPEndX.push_back(MCPEndX->at(i) - _util->GetOrigin()[0]);
_MCPEndY.push_back(MCPEndY->at(i) - _util->GetOrigin()[1]);
_MCPEndZ.push_back(MCPEndZ->at(i) - _util->GetOrigin()[2]);
} else {
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
}
pdgmother.push_back(PDGMother->at(i));
// save the true momentum
truep.push_back(ptrue);
// save the true angle
_angle.push_back(angle);
//Save MC process
_MCProc.push_back(mcp_process);
_MCEndProc.push_back(mcp_endprocess);
mctime.push_back(time);
etime.push_back(-1);
erecon.push_back(-1);
_preco.push_back(-1);
anglereco.push_back(-1);
recopid.push_back(-1);
recopidecal.push_back(-1);
for (int pidr = 0; pidr < 6; ++pidr) prob_arr.push_back(-1);
mctrkid.push_back(MCPTrkID->at(i));
motherid.push_back(MCMotherTrkID->at(i));
}
else {
}
}// end is not neutron, pi0 or gamma
}// end not visible in TPC
nFSP++;
} // closes the MC truth loop
_nFSP.push_back(nFSP);
//Check if vectors have good size
if(this->CheckVectorSize()) {
this->FillTTree();
} else {
std::cerr << "Event " << _Event << std::endl;
std::cerr << "Number of FSP " << nFSP << std::endl;
std::cerr << "Size of pdgmother " << pdgmother.size() << std::endl;
std::cerr << "Size of truepdg " << truepdg.size() << std::endl;
std::cerr << "Size of mctime " << mctime.size() << std::endl;
std::cerr << "Size of mctrkid " << mctrkid.size() << std::endl;
std::cerr << "Size of motherid " << motherid.size() << std::endl;
std::cerr << "Size of _MCPStartX " << _MCPStartX.size() << std::endl;
std::cerr << "Size of _MCPStartY " << _MCPStartY.size() << std::endl;
std::cerr << "Size of _MCPStartZ " << _MCPStartZ.size() << std::endl;
std::cerr << "Size of _MCPEndX " << _MCPEndX.size() << std::endl;
std::cerr << "Size of _MCPEndY " << _MCPEndY.size() << std::endl;
std::cerr << "Size of _MCPEndZ " << _MCPEndZ.size() << std::endl;
std::cerr << "Size of _MCProc " << _MCProc.size() << std::endl;
std::cerr << "Size of _MCEndProc " << _MCEndProc.size() << std::endl;
std::cerr << "Size of trkLen " << trkLen.size() << std::endl;
std::cerr << "Size of trkLenPerp " << trkLenPerp.size() << std::endl;
std::cerr << "Size of truep " << truep.size() << std::endl;
std::cerr << "Size of truepx " << truepx.size() << std::endl;
std::cerr << "Size of truepy " << truepy.size() << std::endl;
std::cerr << "Size of truepz " << truepz.size() << std::endl;
std::cerr << "Size of _angle " << _angle.size() << std::endl;
//Reco values
std::cerr << "Size of detected " << detected.size() << std::endl;
std::cerr << "Size of recopid " << recopid.size() << std::endl;
std::cerr << "Size of recopidecal " << recopidecal.size() << std::endl;
// std::cerr << "Size of prob_arr " << prob_arr.size() << std::endl;
std::cerr << "Size of anglereco " << anglereco.size() << std::endl;
std::cerr << "Size of _preco " << _preco.size() << std::endl;
std::cerr << "Size of erecon " << erecon.size() << std::endl;
std::cerr << "Size of etime " << etime.size() << std::endl;
//Geometry
std::cerr << "Size of isFidStart " << isFidStart.size() << std::endl;
std::cerr << "Size of isTPCStart " << isTPCStart.size() << std::endl;
std::cerr << "Size of isCaloStart " << isCaloStart.size() << std::endl;
std::cerr << "Size of isThroughCaloStart " << isThroughCaloStart.size() << std::endl;
std::cerr << "Size of isInBetweenStart " << isInBetweenStart.size() << std::endl;
std::cerr << "Size of isBarrelStart " << isBarrelStart.size() << std::endl;
std::cerr << "Size of isEndcapStart " << isEndcapStart.size() << std::endl;
std::cerr << "Size of isFidEnd " << isFidEnd.size() << std::endl;
std::cerr << "Size of isTPCEnd " << isTPCEnd.size() << std::endl;
std::cerr << "Size of isCaloEnd " << isCaloEnd.size() << std::endl;
std::cerr << "Size of isThroughCaloEnd " << isThroughCaloEnd.size() << std::endl;
std::cerr << "Size of isInBetweenEnd " << isInBetweenEnd.size() << std::endl;
std::cerr << "Size of isBarrelEnd " << isBarrelEnd.size() << std::endl;
std::cerr << "Size of isEndcapEnd " << isEndcapEnd.size() << std::endl;
std::cerr << "Event with wrong vector sizes... skipped" << std::endl;
}
} // closes the event loop
} // closes the main loop function
<file_sep>#include "MCP_Skimmer.h"
#include <iostream>
#include <TFile.h>
#include <TTree.h>
void ShowHelp()
{
std::cout << "./mcp_skimmer --infile <inputfile> --outfile <outputfile> --debug <0/1>" << std::endl;
}
int main(int argc, char **argv)
{
if( argc == 1 || ((argc == 2) && ((std::string("--help") == argv[1]) || (std::string("-h") == argv[1]))) || argc < 7 ){
ShowHelp();
return 2;
}
if( argv[1] != std::string("--infile") || argv[3] != std::string("--outfile") || argv[5] != std::string("--debug") ) {
ShowHelp();
return -2;
}
// get command line options
std::string outfile = "";
std::string infile = "";
std::string debug = "";
int p = 0;
while( p < argc )
{
if( argv[p] == std::string("--infile") ){
infile = argv[p+1];
p++;
}
else if( argv[p] == std::string("--outfile") ){
outfile = argv[p+1];
p++;
}
else if( argv[p] == std::string("--debug") ){
debug = argv[p+1];
p++;
}
else{
p++;
}
}
printf( "Skimming from tree dump: %s\n", infile.c_str() );
printf( "Output Skimmed file: %s\n", outfile.c_str() );
printf( "Debug mode: %s\n", debug.c_str() );
MCP_Skimmer *skimmer = new MCP_Skimmer(infile, outfile);
if(debug == "1")
skimmer->SetDebug(true);
if(not skimmer->BookTFile()) return -1;
skimmer->SkimMCParticle();
skimmer->WriteTTree();
skimmer->CloseTFile();
printf( "-30-\n" );
return 0;
}
<file_sep>#include "MCP_Skimmer.h"
#include "TDirectory.h"
#include "TVector3.h"
#include <iostream>
#include <algorithm>
#include <functional>
#include <map>
MCP_Skimmer::MCP_Skimmer()
: _intfile(nullptr), _skimfile(nullptr), _skimtree(nullptr), _inttree(nullptr), _debug(false), _util(new Utils()), _infile(""), _outfile("")
{
}
MCP_Skimmer::MCP_Skimmer(std::string infilename, std::string outfilename)
: _skimfile(nullptr), _skimtree(nullptr), _debug(false), _util(new Utils()), _infile(infilename), _outfile(outfilename)
{
}
MCP_Skimmer::~MCP_Skimmer()
{
}
void MCP_Skimmer::ClearVectors()
{
_MC_Q2.clear();
_MC_W.clear();
_MC_Y.clear();
_MC_X.clear();
_MC_Theta.clear();
_MC_T.clear();
_MCVertX.clear();
_MCVertY.clear();
_MCVertZ.clear();
_MCNuPx.clear();
_MCNuPy.clear();
_MCNuPz.clear();
_NType.clear();
_CCNC.clear();
_Mode.clear();
_Gint.clear();
_TgtPDG.clear();
_GT_T.clear();
_InterT.clear();
_Weight.clear();
_PDG.clear();
_Mother.clear();
_PDGMother.clear();
_MCPTrkID.clear();
_MCPTime.clear();
_MCPStartX.clear();
_MCPStartY.clear();
_MCPStartZ.clear();
_MCPStartPX.clear();
_MCPStartPY.clear();
_MCPStartPZ.clear();
_MCPProc.clear();
_MCPEndProc.clear();
_MCPEndX.clear();
_MCPEndY.clear();
_MCPEndZ.clear();
_TrajMCPX.clear();
_TrajMCPY.clear();
_TrajMCPZ.clear();
_TrajMCPTrajIndex.clear();
}
void MCP_Skimmer::SkimMCParticle()
{
int Event = 0;
int SubRun = 0;
int Run = 0;
std::vector<float> *MC_Q2 = 0;
std::vector<float> *MC_W = 0;
std::vector<float> *MC_Y = 0;
std::vector<float> *MC_X = 0;
std::vector<float> *MC_Theta = 0;
std::vector<float> *MC_T = 0;
std::vector<float> *MCVertX = 0;
std::vector<float> *MCVertY = 0;
std::vector<float> *MCVertZ = 0;
std::vector<float> *MCNuPx = 0;
std::vector<float> *MCNuPy = 0;
std::vector<float> *MCNuPz = 0;
std::vector<int> *NType = 0;
std::vector<int> *CCNC = 0;
std::vector<int> *Mode = 0;
std::vector<int> *Gint=0;
std::vector<int> *TgtPDG=0;
std::vector<int> *GT_T=0;
std::vector<int> *InterT=0;
std::vector<float> *Weight=0;
std::vector<int> *PDG = 0;
std::vector<int> *Mother=0;
std::vector<int> *PDGMother=0;
std::vector<int> *MCPTrkID = 0;
std::vector<float> *MCPTime = 0;
std::vector<float> *MCPStartX = 0;
std::vector<float> *MCPStartY = 0;
std::vector<float> *MCPStartZ = 0;
std::vector<float> *MCPStartPX = 0;
std::vector<float> *MCPStartPY = 0;
std::vector<float> *MCPStartPZ = 0;
std::vector<std::string> *MCPProc = 0;
std::vector<std::string> *MCPEndProc = 0;
std::vector<float> *MCPEndX = 0;
std::vector<float> *MCPEndY = 0;
std::vector<float> *MCPEndZ = 0;
std::vector<float> *TrajMCPX = 0;
std::vector<float> *TrajMCPY = 0;
std::vector<float> *TrajMCPZ = 0;
std::vector<int> *TrajMCPTrajIndex = 0;
_inttree->SetBranchStatus("*", 0);
_inttree->SetBranchStatus("Event", 1);
_inttree->SetBranchStatus("SubRun", 1);
_inttree->SetBranchStatus("Run", 1);
_inttree->SetBranchStatus("NType", 1);
_inttree->SetBranchStatus("CCNC", 1);
_inttree->SetBranchStatus("MC_Q2", 1);
_inttree->SetBranchStatus("MC_W", 1);
_inttree->SetBranchStatus("MC_Y", 1);
_inttree->SetBranchStatus("MC_X", 1);
_inttree->SetBranchStatus("MC_Theta", 1);
_inttree->SetBranchStatus("MC_T", 1);
_inttree->SetBranchStatus("Mode", 1);
_inttree->SetBranchStatus("Gint", 1);
_inttree->SetBranchStatus("TgtPDG", 1);
_inttree->SetBranchStatus("GT_T", 1);
_inttree->SetBranchStatus("MCVertX", 1);
_inttree->SetBranchStatus("MCVertY", 1);
_inttree->SetBranchStatus("MCVertZ", 1);
_inttree->SetBranchStatus("MCNuPx", 1);
_inttree->SetBranchStatus("MCNuPy", 1);
_inttree->SetBranchStatus("MCNuPz", 1);
_inttree->SetBranchStatus("InterT", 1);
_inttree->SetBranchStatus("Weight", 1);
//MC info
_inttree->SetBranchStatus("PDG", 1);
_inttree->SetBranchStatus("MCPTrkID", 1);
_inttree->SetBranchStatus("MCPTime", 1);
_inttree->SetBranchStatus("MCPStartX", 1);
_inttree->SetBranchStatus("MCPStartY", 1);
_inttree->SetBranchStatus("MCPStartZ", 1);
_inttree->SetBranchStatus("MCPEndX", 1);
_inttree->SetBranchStatus("MCPEndY", 1);
_inttree->SetBranchStatus("MCPEndZ", 1);
_inttree->SetBranchStatus("Mother", 1);
_inttree->SetBranchStatus("PDGMother", 1);
_inttree->SetBranchStatus("MCPStartPX", 1);
_inttree->SetBranchStatus("MCPStartPY", 1);
_inttree->SetBranchStatus("MCPStartPZ", 1);
_inttree->SetBranchStatus("MCPProc", 1);
_inttree->SetBranchStatus("MCPEndProc", 1);
_inttree->SetBranchStatus("TrajMCPX", 1);
_inttree->SetBranchStatus("TrajMCPY", 1);
_inttree->SetBranchStatus("TrajMCPZ", 1);
_inttree->SetBranchStatus("TrajMCPTrajIndex", 1);
//-------------------
_inttree->SetBranchAddress("Event", &Event);
_inttree->SetBranchAddress("SubRun", &SubRun);
_inttree->SetBranchAddress("Run", &Run);
//Generator info
_inttree->SetBranchAddress("NType", &NType);
_inttree->SetBranchAddress("CCNC", &CCNC);
_inttree->SetBranchAddress("MC_Q2", &MC_Q2);
_inttree->SetBranchAddress("MC_W", &MC_W);
_inttree->SetBranchAddress("MC_Y", &MC_Y);
_inttree->SetBranchAddress("MC_X", &MC_X);
_inttree->SetBranchAddress("MC_Theta", &MC_Theta);
_inttree->SetBranchAddress("MC_T", &MC_T);
_inttree->SetBranchAddress("Mode", &Mode);
_inttree->SetBranchAddress("Gint", &Gint);
_inttree->SetBranchAddress("TgtPDG", &TgtPDG);
_inttree->SetBranchAddress("GT_T", >_T);
_inttree->SetBranchAddress("MCVertX", &MCVertX);
_inttree->SetBranchAddress("MCVertY", &MCVertY);
_inttree->SetBranchAddress("MCVertZ", &MCVertZ);
_inttree->SetBranchAddress("MCNuPx", &MCNuPx);
_inttree->SetBranchAddress("MCNuPy", &MCNuPy);
_inttree->SetBranchAddress("MCNuPz", &MCNuPz);
_inttree->SetBranchAddress("InterT", &InterT);
_inttree->SetBranchAddress("Weight", &Weight);
//MC info
_inttree->SetBranchAddress("PDG", &PDG);
_inttree->SetBranchAddress("MCPTrkID", &MCPTrkID);
_inttree->SetBranchAddress("MCPTime", &MCPTime);
_inttree->SetBranchAddress("MCPStartX", &MCPStartX);
_inttree->SetBranchAddress("MCPStartY", &MCPStartY);
_inttree->SetBranchAddress("MCPStartZ", &MCPStartZ);
_inttree->SetBranchAddress("MCPEndX", &MCPEndX);
_inttree->SetBranchAddress("MCPEndY", &MCPEndY);
_inttree->SetBranchAddress("MCPEndZ", &MCPEndZ);
_inttree->SetBranchAddress("Mother", &Mother);
_inttree->SetBranchAddress("PDGMother", &PDGMother);
_inttree->SetBranchAddress("MCPStartPX", &MCPStartPX);
_inttree->SetBranchAddress("MCPStartPY", &MCPStartPY);
_inttree->SetBranchAddress("MCPStartPZ", &MCPStartPZ);
_inttree->SetBranchAddress("MCPProc", &MCPProc);
_inttree->SetBranchAddress("MCPEndProc", &MCPEndProc);
_inttree->SetBranchAddress("TrajMCPX", &TrajMCPX);
_inttree->SetBranchAddress("TrajMCPY", &TrajMCPY);
_inttree->SetBranchAddress("TrajMCPZ", &TrajMCPZ);
_inttree->SetBranchAddress("TrajMCPTrajIndex", &TrajMCPTrajIndex);
// Main event loop
for( int entry = 0; entry < _inttree->GetEntries(); entry++ )
{
_inttree->GetEntry(entry);
this->ClearVectors();
if(Event%100 == 0)
std::cout << "Treating Evt " << Event << std::endl;
_Event = Event;
_Run = Run;
_SubRun = SubRun;
for(size_t i = 0; i < NType->size(); i++)
{
_CCNC.push_back(CCNC->at(i));
_NType.push_back(NType->at(i));
_MC_Q2.push_back(MC_Q2->at(i));
_MC_W.push_back(MC_W->at(i));
_MC_Y.push_back(MC_Y->at(i));
_MC_X.push_back(MC_X->at(i));
_MC_Theta.push_back(MC_Theta->at(i));
_Mode.push_back(Mode->at(i));
_MC_T.push_back(MC_T->at(i));
_InterT.push_back(InterT->at(i));
_MCVertX.push_back(MCVertX->at(i));
_MCVertY.push_back(MCVertY->at(i));
_MCVertZ.push_back(MCVertZ->at(i));
_MCNuPx.push_back(MCNuPx->at(i));
_MCNuPy.push_back(MCNuPy->at(i));
_MCNuPz.push_back(MCNuPz->at(i));
}
for(size_t i = 0; i < Gint->size(); i++)
{
_Gint.push_back(Gint->at(i));
_TgtPDG.push_back(TgtPDG->at(i));
_GT_T.push_back(GT_T->at(i));
_Weight.push_back(Weight->at(i));
}
std::map<int, int> mcp_kid_mother_map;
for(size_t i = 0; i < MCPStartPX->size(); i++ )
{
//check if daughter has mother until we find the original mother
//get current kid trk id
int this_kid_trkid = MCPTrkID->at(i);
int this_kid_mother = Mother->at(i);
//Mother->at(i) returns the mother trkid
//Has no mother -> primaries
if(this_kid_mother == 0) {
// std::cout << "Kid " << this_kid_trkid << " Mother " << this_kid_mother << std::endl;
continue;
}
//loop over the mcp again and go back in history need to check Mother->at(j) until it is 0 then we found the original mcp
for(size_t j = 0; j < MCPStartPX->size(); j++ )
{
int mother_trk_id = MCPTrkID->at(j);
int mother = Mother->at(j);
//found the mother
if(mother_trk_id == this_kid_mother)
{
//need to check if it has mother if yes loop until mother is 0
if(mother == 0)
{
//found the original particle
// std::cout << "Kid " << this_kid_trkid << " Mother " << this_kid_mother << std::endl;
//fill a map linking kid track id to mother track id to know which ones to skip and replace their mother by the original one
mcp_kid_mother_map[this_kid_trkid] = this_kid_mother;
break;
}
else
{
this_kid_mother = mother;
j = 0;
}
}
}
}
//Vector of indexes to keep
std::vector<int> IndexesToKeep;
//Check which indexes to keep
for(size_t i = 0; i < MCPStartPX->size(); i++)
{
TVector3 spoint(MCPStartX->at(i), MCPStartY->at(i), MCPStartZ->at(i));//start point
TVector3 epoint(MCPEndX->at(i), MCPEndY->at(i), MCPEndZ->at(i));//end point
std::string process = MCPProc->at(i);
std::string endprocess = MCPEndProc->at(i);
//found a particle that has already an ancestor
if( mcp_kid_mother_map.find(MCPTrkID->at(i)) != mcp_kid_mother_map.end() )
{
// However keep the daughters for specific ones
// - D0s and V0s (kinks and decays) such as gamma, pi0, K0, muon, pion and kaon
// - backscatters from calo to tracker important for background
// - breamstrahlung photons / delta rays
//keep D0s and V0s from decays, conversions (a lot of compton or Ioni)
if( std::find(daughtersToKeep.begin(), daughtersToKeep.end(), PDGMother->at(i)) != daughtersToKeep.end() && _util->PointInTPC(spoint) && (process == "Decay" || process == "conv") ) {
if(_debug){
std::cout << "Keeping D0 or V0" << std::endl;
std::cout << "Index " << i << " TrkID " << MCPTrkID->at(i) << " pdg " << PDG->at(i) << " mother pdg " << PDGMother->at(i);
std::cout << " process " << process << " endprocess " << endprocess << std::endl;
std::cout << " Start point X: " << spoint.X() << " Y: " << spoint.Y() << " Z: " << spoint.Z() << std::endl;
std::cout << " End point X: " << epoint.X() << " Y: " << epoint.Y() << " Z: " << epoint.Z() << std::endl;
std::cout << " Origin in tracker " << _util->PointInTPC(spoint) << std::endl;
std::cout << " Decayed in Calo " << _util->hasDecayedInCalo(epoint) << std::endl;
}
IndexesToKeep.push_back(i);
}
//check for backscatter
else if( _util->isBackscatter(spoint, epoint) ) {
if(_debug){
std::cout << "Keeping Backscatter" << std::endl;
std::cout << "Index " << i << " TrkID " << MCPTrkID->at(i) << " pdg " << PDG->at(i) << " mother pdg " << PDGMother->at(i);
std::cout << " process " << process << " endprocess " << endprocess << std::endl;
std::cout << " Start point X: " << spoint.X() << " Y: " << spoint.Y() << " Z: " << spoint.Z() << std::endl;
std::cout << " End point X: " << epoint.X() << " Y: " << epoint.Y() << " Z: " << epoint.Z() << std::endl;
std::cout << " Origin in tracker " << _util->PointInTPC(spoint) << std::endl;
std::cout << " Decayed in Calo " << _util->hasDecayedInCalo(epoint) << std::endl;
}
IndexesToKeep.push_back(i);
}
//if Bremsstrahlung photon
else if ( _util->isBremsstrahlung(spoint, PDG->at(i), PDGMother->at(i)) && process == "eBrem" ) {
if(_debug){
std::cout << "Keeping Bremsstrahlung" << std::endl;
std::cout << "Index " << i << " TrkID " << MCPTrkID->at(i) << " pdg " << PDG->at(i) << " mother pdg " << PDGMother->at(i);
std::cout << " process " << process << " endprocess " << endprocess << std::endl;
std::cout << " Start point X: " << spoint.X() << " Y: " << spoint.Y() << " Z: " << spoint.Z() << std::endl;
std::cout << " End point X: " << epoint.X() << " Y: " << epoint.Y() << " Z: " << epoint.Z() << std::endl;
std::cout << " Origin in tracker " << _util->PointInTPC(spoint) << std::endl;
std::cout << " Decayed in Calo " << _util->hasDecayedInCalo(epoint) << std::endl;
}
IndexesToKeep.push_back(i);
}
else {
continue;
}
}
//keep only primaries whatever they are from (inside TPC or outside)
if(MCPProc->at(i) == "primary"){
if(_debug){
std::cout << "Keeping Primary particle" << std::endl;
std::cout << "Index " << i << " TrkID " << MCPTrkID->at(i) << " pdg " << PDG->at(i) << " mother pdg " << PDGMother->at(i);
std::cout << " process " << process << " endprocess " << endprocess << std::endl;
std::cout << " Start point X: " << spoint.X() << " Y: " << spoint.Y() << " Z: " << spoint.Z() << std::endl;
std::cout << " End point X: " << epoint.X() << " Y: " << epoint.Y() << " Z: " << epoint.Z() << std::endl;
std::cout << " Origin in tracker " << _util->PointInTPC(spoint) << std::endl;
std::cout << " Decayed in Calo " << _util->hasDecayedInCalo(epoint) << std::endl;
}
IndexesToKeep.push_back(i);
}
}
for(size_t i = 0; i < IndexesToKeep.size(); i++)
{
_PDG.push_back(PDG->at(i));
_MCPStartPX.push_back(MCPStartPX->at(i));
_MCPStartPY.push_back(MCPStartPY->at(i));
_MCPStartPZ.push_back(MCPStartPZ->at(i));
_MCPTrkID.push_back(MCPTrkID->at(i));
_MCPTime.push_back(MCPTime->at(i));
_MCPStartX.push_back(MCPStartX->at(i));
_MCPStartY.push_back(MCPStartY->at(i));
_MCPStartZ.push_back(MCPStartZ->at(i));
_MCPEndX.push_back(MCPEndX->at(i));
_MCPEndY.push_back(MCPEndY->at(i));
_MCPEndZ.push_back(MCPEndZ->at(i));
_MCPProc.push_back(MCPProc->at(i));
_MCPEndProc.push_back(MCPEndProc->at(i));
_Mother.push_back(Mother->at(i));
_PDGMother.push_back(PDGMother->at(i));
for(size_t itraj = 0; itraj < TrajMCPX->size(); itraj++){
//keep only traj from kept mcp
if(TrajMCPTrajIndex->at(itraj) == (int) i){
_TrajMCPX.push_back(TrajMCPX->at(itraj));
_TrajMCPY.push_back(TrajMCPY->at(itraj));
_TrajMCPZ.push_back(TrajMCPZ->at(itraj));
_TrajMCPTrajIndex.push_back(TrajMCPTrajIndex->at(itraj));
}
}
}
this->FillTTree();
}//end tree loop
}
bool MCP_Skimmer::BookTFile()
{
_intfile = new TFile( _infile.c_str() );
if(nullptr == _intfile)
return false;
_inttree = (TTree*) _intfile->Get( "anatree/GArAnaTree" );
if(nullptr == _inttree)
return false;
_skimfile = new TFile(_outfile.c_str(), "RECREATE");
if(nullptr == _skimfile){
return false;
}
else
{
TDirectory *anatree = _skimfile->mkdir("anatree");
anatree->cd();
_skimtree = new TTree( "GArAnaTree", "GArAnaTree" );
_skimtree->Branch("Event", &_Event);
_skimtree->Branch("SubRun", &_SubRun);
_skimtree->Branch("Run", &_Run);
//Generator info
_skimtree->Branch("NType", &_NType);
_skimtree->Branch("CCNC", &_CCNC);
_skimtree->Branch("MC_Q2", &_MC_Q2);
_skimtree->Branch("MC_W", &_MC_W);
_skimtree->Branch("MC_Y", &_MC_Y);
_skimtree->Branch("MC_X", &_MC_X);
_skimtree->Branch("MC_Theta", &_MC_Theta);
_skimtree->Branch("MC_T", &_MC_T);
_skimtree->Branch("Mode", &_Mode);
_skimtree->Branch("Gint", &_Gint);
_skimtree->Branch("TgtPDG", &_TgtPDG);
_skimtree->Branch("GT_T", &_GT_T);
_skimtree->Branch("MCVertX", &_MCVertX);
_skimtree->Branch("MCVertY", &_MCVertY);
_skimtree->Branch("MCVertZ", &_MCVertZ);
_skimtree->Branch("MCNuPx", &_MCNuPx);
_skimtree->Branch("MCNuPy", &_MCNuPy);
_skimtree->Branch("MCNuPz", &_MCNuPz);
_skimtree->Branch("InterT", &_InterT);
_skimtree->Branch("Weight", &_Weight);
//MC info
_skimtree->Branch("PDG", &_PDG);
_skimtree->Branch("MCPTrkID", &_MCPTrkID);
_skimtree->Branch("MCPTime", &_MCPTime);
_skimtree->Branch("MCPStartX", &_MCPStartX);
_skimtree->Branch("MCPStartY", &_MCPStartY);
_skimtree->Branch("MCPStartZ", &_MCPStartZ);
_skimtree->Branch("MCPEndX", &_MCPEndX);
_skimtree->Branch("MCPEndY", &_MCPEndY);
_skimtree->Branch("MCPEndZ", &_MCPEndZ);
_skimtree->Branch("Mother", &_Mother);
_skimtree->Branch("PDGMother", &_PDGMother);
_skimtree->Branch("MCPStartPX", &_MCPStartPX);
_skimtree->Branch("MCPStartPY", &_MCPStartPY);
_skimtree->Branch("MCPStartPZ", &_MCPStartPZ);
_skimtree->Branch("MCPProc", &_MCPProc);
_skimtree->Branch("MCPEndProc", &_MCPEndProc);
_skimtree->Branch("TrajMCPX", &_TrajMCPX);
_skimtree->Branch("TrajMCPY", &_TrajMCPY);
_skimtree->Branch("TrajMCPZ", &_TrajMCPZ);
_skimtree->Branch("TrajMCPTrajIndex", &_TrajMCPTrajIndex);
return true;
}
}
void MCP_Skimmer::FillTTree()
{
if(_skimtree != nullptr) {
_skimfile->cd("anatree");
_skimtree->Fill();
}
return;
}
void MCP_Skimmer::CloseTFile()
{
if(_skimfile != nullptr) {
_skimfile->Close();
return;
}
else{ return; }
}
void MCP_Skimmer::WriteTTree()
{
if(_skimtree != nullptr) {
_skimfile->cd("anatree");
_skimtree->Write();
_skimfile->Close();
}
return;
}
<file_sep>#########################################################
# cmake module for finding GENIE
#
#
# returns:
# GENIE_FOUND : set to TRUE or FALSE
# GENIE_INCLUDE_DIRS : paths to gsl includes
# GENIE_LIBRARIES : list of gsl libraries
#
# @author <NAME>, DESY
#########################################################
# find genie-config
SET( GENIE_CONFIG_EXECUTABLE GENIE_CONFIG_EXECUTABLE-NOTFOUND )
MARK_AS_ADVANCED( GENIE_CONFIG_EXECUTABLE )
FIND_PROGRAM( GENIE_CONFIG_EXECUTABLE genie-config PATHS $ENV{GENIE_FQ_DIR}/bin NO_DEFAULT_PATH )
IF( NOT GENIE_FQ_DIR )
FIND_PROGRAM( GENIE_CONFIG_EXECUTABLE genie-config )
ENDIF()
IF( GENIE_CONFIG_EXECUTABLE )
# ==============================================
# === GENIE_LIBRARIES ===
# ==============================================
EXECUTE_PROCESS( COMMAND "${GENIE_CONFIG_EXECUTABLE}" --libs
OUTPUT_VARIABLE GENIE_LIBRARIES
OUTPUT_STRIP_TRAILING_WHITESPACE
)
ENDIF( GENIE_CONFIG_EXECUTABLE )
SET( GENIE_ROOT GENIE_ROOT-NOTFOUND )
MARK_AS_ADVANCED( GENIE_ROOT )
SET( GENIE_ROOT $ENV{GENIE_FQ_DIR} )
# ---------- includes ---------------------------------------------------------
SET( GENIE_INCLUDE_DIRS GENIE_INCLUDE_DIRS-NOTFOUND )
MARK_AS_ADVANCED( GENIE_INCLUDE_DIRS )
SET( GENIE_INCLUDE_DIRS NAMES Framework/Utils/AppInit.h PATHS ${GENIE_ROOT}/include/GENIE NO_DEFAULT_PATH )
IF( NOT GENIE_ROOT )
FIND_PATH( GENIE_INCLUDE_DIRS NAMES Framework/Utils/AppInit.h )
ENDIF()
# ---------- final checking ---------------------------------------------------
INCLUDE( FindPackageHandleStandardArgs )
# set GENIE_FOUND to TRUE if all listed variables are TRUE and not empty
FIND_PACKAGE_HANDLE_STANDARD_ARGS( GENIE DEFAULT_MSG GENIE_ROOT GENIE_LIBRARIES GENIE_INCLUDE_DIRS )
<file_sep># ParamSim
[](https://github.com/ebrianne/ParamSim/actions/workflows/linux.yml)
The parametrized simulation, currently a module in GArSoft v02_04_00 and GArSoft development branch is complementary to GArSoft's full reconstruction approach. GArSoft is Multipurpose Detector's (MPD) official simulation, reconstruction, and analysis software framework (https://cdcvs.fnal.gov/redmine/projects/garsoft/wiki), and v02_04_00 of GArSoft is the version tagged for DUNE near detector Conceptual Design Report. In GArSoft development branch, you may find this module under the Ana/ParamSim directory.
Following is the reconstruction approach taken to parametrize the detector response:
1) Gluckstern relation (https://www.sciencedirect.com/science/article/pii/S0168900209009474) for reconstructing long tracks curling up in magnetic field
2) Particle range for reconstructing short tracks that stop in the high pressure gas argon TPC (HPgTPC) component of the MPD and do not curl up in magnetic field
In addition to reconstructing tracks, a dE/dx-based PID is implemented in the module. This is based on Tom Junk's parametrization of PEP-4's dE/dx curve: https://home.fnal.gov/~trj/mpd/dedx_sep2019/ (PID matrices are in pid.root file)
*Units are in cm, GeV, ns.*
*For vectors that are not filled, a default value of -1 is set in order to keep the vector length the same (nFSP)*
The module is designed to take GArSoft's analysis tree, anatree as input and produce a so called "cafanatree" ntuple as output. A description of cafanatree tree variables are as the following:
* Event: an art event (not neutrino-interaction event rather the spill number)
* Run: run #
* SubRun: subrun #
- Generator-level information (more information about generator-level variables can be found at: https://internal.dunescience.org/doxygen/classsimb_1_1MCNeutrino.html)
* nFSP: number of monte-carlo particle in the event, not only primaries but all particles (includes shower particles)
* mode: interaction mode
* q2: momentum transfer
* w: hadronic invariant mass
* y: inelasticity
* x: Bjorken-x variable
* theta: angle between incoming and outgoing lepton
* t: a variable used in coherent pion analysis
* ntype: neutrino PDG
* ccnc: charged current (ccnc == 0) or neutral current (ccnc == 1)
* gint: a variable used in coherent pion analysis
* tgtpdg: target PDG (nucleus-level variable)
* weight: number of protons-on-target
* gt_t: a variable used in coherent pion analysis
* intert: interaction type
* mcnupx: x-component momentum of neutrino in GeV/c
* mcnupy: y-component momentum of neutrino in GeV/c
* mcnupz: z-component momentum of neutrino in GeV/c
* vertx: vertex of primary mc particle in x in cm
* verty: vertex of primary mc particle in y in cm
* vertz: vertex of primary mc particle in z in cm
- GEANT4-level information:
* pdgmother: pdg code of the particle that created the particle under consideration
* mctrkid: number created in G4 to track the particles (relations mother <-> daughters). The original neutrino has a track id of -1 and then it is incremented by G4.
* motherid: id number associated with the mother mc particle -> returns the index in the MCP vector of the mother of this particle
* mctime: detector response time/time information of the particle with respect to neutrino interaction time (which is 0 nano seconds)
* MCPStartX: starting position of the particle along the x-direction (starting position of the track) in cm
* MCPStartY: starting position of the particle along the y-direction (starting position of the track) in cm
* MCPStartZ: starting position of the particle along the z-direction (starting position of the track) in cm
* truepx: truth-level x-component momentum of the particle in GeV/c
* truepy: truth-level y-component momentum of the particle in GeV/c
* truepz: truth-level z-component momentum of the particle in GeV/c
* MCPEndX: end position of the particle along the x-direction (end position of the track) in cm
* MCPEndY: end position of the particle along the y-direction (end position of the track) in cm
* MCPEndZ: end position of the particle along the z-direction (end position of the track) in cm
* MCProc: a vector containing a string of the GEANT4 process that created a particle (e.g. for particles emerging from a neutrino interaction, the GEANT4 process is "primary")
* MCEndProc: a vector containing a string of the GEANT4 end process of a particle (e.g. for e+e- pairs emerging from a photon conversion, the end process is "conv")
* angle: truth-level angle with respect to the beam direction (along the z)
* truep: truth-level momentum of the particle in GeV/c
* truepdg: truth-level PDG code of the particle
- Reconstruction-level information (note that this is different from GArSoft reconstruction -- see above for more information about the parametrized reconstruction in the ParamSim module):
* recopid: reconstructed PDG code of the particle using the parametrized dE/dx
* trkLen: length of the track
* trkLenPerp: length of the track in the direction transverse to the beam
* preco: reconstructed particle momentum
* anglereco: reconstructed angle of the particle with respect to the beam direction (wrt the z-direction)
* erecon: reconstructed energy of neutral and charged particles that reach the ECAL (when track length != 0 and endpoint is in the calo). Particles that are not reconstructed in the ECAL have erecon of 0. Calculated from ECAL parametrisation using E = sqrt( p*p + m*m ) - m (kinetic energy)
* prob_arr: array of PID scores/probabilities (using log-likelihood) for reconstructed particles
* recopidecal: reconstructed PDG code of the neutral and charged particles with the ECAL. A value of 0 is considered if the particle does not reach ECAL.
* detected: whether the particle is seen by the ECAL
* etime: smeared mc time by 1 ns, reco by the ECAL (if reaches or seen in ECAL only)
- Geometry information (simple flags 0 or 1)
* isFidStart/End: Check if the particle start/end point is in the fiducial volume of the TPC
* isTPCStart/End: Check if the particle start/end point is in the volume of the TPC (includes fiducial and out of fiducial)
* isCaloStart/End: Check if the particle start/end point is in the ECAL
* isThroughCaloStart/End: Check if the particle start/end point is not in the TPC and the ECAL (assumes went through the ECAL)
* isInBetweenStart/End: Check if the particle start/end point is in between the TPC and the ECAL
* isBarrelStart/End: Flag to tell if the particle start/end point is in the *Barrel region*
* isEndcapStart/End: Flag to tell if the particle start/end point is in the *Endcap region*
Check out the test directory for an example macro on how to read the cafanatree analysis ntuples that are produced as outputs of running the ParamSim module.
**Hardcoded values!!**
```C++
double _TPCFidRadius = 222.5;
double _TPCFidLength = 215.;
double _TPCRadius = 273.;
double _TPCLength = 259.;
double _ECALInnerRadius = 278.;
double _ECALOuterRadius = 321.;
double _ECALStartX = 364.;
double _ECALEndX = 406.;
```
The volumes are defined as the following:
```C++
bool Utils::PointInFiducial(TVector3 point)
{
bool isInFiducial = true;
float r_point = std::sqrt( point.Y()*point.Y() + point.Z()*point.Z() );
if( r_point > _TPCFidRadius ) isInFiducial = false;
if( r_point < _TPCFidRadius && std::abs(point.X()) > _TPCFidLength ) isInFiducial = false;
return isInFiducial;
}
```
```C++
bool Utils::PointInTPC(TVector3 point)
{
if(PointInFiducial(point)) return true;
bool isInTPC = true;
float r_point = std::sqrt( point.Y()*point.Y() + point.Z()*point.Z() );
if( r_point > _TPCRadius ) isInTPC = false;
if( r_point < _TPCRadius && std::abs(point.X()) > _TPCLength ) isInTPC = false;
return isInTPC;
}
```
```C++
bool Utils::PointInCalo(TVector3 point)
{
bool isInCalo = false;
float r_point = std::sqrt( point.Y()*point.Y() + point.Z()*point.Z() );
//in the Barrel
if( r_point > _ECALInnerRadius && r_point < _ECALOuterRadius && std::abs(point.X()) < _ECALStartX ) isInCalo = true;
//in the Endcap
if( r_point < _ECALInnerRadius && std::abs(point.X()) > _ECALStartX && std::abs(point.X()) < _ECALEndX ) isInCalo = true;
return isInCalo;
}
```
```C++
bool Utils::PointStopBetween(TVector3 point)
{
//Barrel Radius 278 cm
//Endcap starts at 364 cm
bool isStopBetween = false;
float r_point = std::sqrt( point.Y()*point.Y() + point.Z()*point.Z() );
//in the Barrel
if( r_point < _ECALInnerRadius && r_point > _TPCRadius && std::abs(point.X()) < _TPCLength ) isStopBetween = true;
//in the Endcap
if( r_point < _ECALInnerRadius && std::abs(point.X()) > _TPCLength && std::abs(point.X()) < _ECALStartX ) isStopBetween = true;
return isStopBetween;
}
```
```C++
bool Utils::isThroughCalo(TVector3 point)
{
return !PointInTPC(point) && !PointStopBetween(point) && !PointInCalo(point);
}
```
```C++
bool Utils::isBarrel(TVector3 point)
{
bool isBarrel = false;
float theta = std::atan(_ECALInnerRadius / _ECALStartX ); //angle for barrel/endcap transition
float r_point = std::sqrt( point.Y()*point.Y() + point.Z()*point.Z() );
float theta_point = std::atan(r_point / point.X() ); //angle for barrel/endcap transition for the point
if( theta_point > theta ) isBarrel = true;
return isBarrel;
}
```
```C++
bool Utils::isEndcap(TVector3 point)
{
bool isEndcap = false;
if( !isBarrel(point) ) isEndcap = true;
return isEndcap;
}
```
<file_sep>#################################################
cmake_minimum_required( VERSION 2.6 FATAL_ERROR )
#################################################
# ----- project name -----
PROJECT( CAFAnaModule )
set( ${PROJECT_NAME}_VERSION_MAJOR 1 )
set( ${PROJECT_NAME}_VERSION_MINOR 0 )
set( ${PROJECT_NAME}_VERSION_PATCH 0 )
if( NOT CMAKE_BUILD_TYPE )
set( CMAKE_BUILD_TYPE Debug CACHE STRING
"Choose the type of build, options are: None Debug Release RelWithDebInfo
MinSizeRel."
FORCE )
endif()
if( CMAKE_INSTALL_PREFIX STREQUAL "/usr/local" )
set( CMAKE_INSTALL_PREFIX "${PROJECT_SOURCE_DIR}" )
endif()
# write this variable to cache
set( CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}" CACHE PATH "Where to install ${PROJECT_NAME}" FORCE )
set( CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" )
mark_as_advanced( CMAKE_INSTALL_RPATH )
#append link pathes to rpath list
set( CMAKE_INSTALL_RPATH_USE_LINK_PATH 1 )
mark_as_advanced( CMAKE_INSTALL_RPATH_USE_LINK_PATH )
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake )
# Find packages
find_package (GSL REQUIRED )
find_package( GENIE REQUIRED )
IF( GENIE_FOUND )
find_package( LIBXML2 REQUIRED )
find_package( PYTHIA6 REQUIRED )
find_package( LOG4CPP REQUIRED )
ENDIF()
find_package( ROOT REQUIRED COMPONENTS Core RIO Hist Tree Rint XMLIO Geom Physics EGPythia6 GenVector )
add_definitions( ${ROOT_DEFINITIONS} )
set(CMAKE_CXX_FLAGS "-Werror -pedantic -Wno-long-long -Wno-sign-compare -Wshadow -fno-strict-aliasing -std=c++17 ${CMAKE_CXX_FLAGS}")
include(CheckCXXCompilerFlag)
unset(COMPILER_SUPPORTS_CXX_FLAGS CACHE)
CHECK_CXX_COMPILER_FLAG(${CMAKE_CXX_FLAGS} COMPILER_SUPPORTS_CXX_FLAGS)
if(NOT COMPILER_SUPPORTS_CXX_FLAGS)
message(FATAL_ERROR "The compiler ${CMAKE_CXX_COMPILER} does not support cxx flags ${CMAKE_CXX_FLAGS}")
endif()
#make libs
include_directories( BEFORE include ${ROOT_INCLUDE_DIRS} ${GENIE_INCLUDE_DIRS} ${LOG4CPP_INCLUDE_DIRS} ${PYTHIA6_INCLUDE_DIRS} ${LIBXML2_INCLUDE_DIRS} ${GSL_INCLUDE_DIRS} )
aux_source_directory( src SRC_FILES )
add_library( ${PROJECT_NAME} SHARED ${SRC_FILES} )
target_link_libraries(${PROJECT_NAME} ${ROOT_LIBRARIES} ${GENIE_LIBRARIES} ${LOG4CPP_LIBRARIES} ${PYTHIA6_LIBRARIES} ${LIBXML2_LIBRARIES} ${GSL_LIBRARIES} )
install( TARGETS ${PROJECT_NAME} LIBRARY DESTINATION lib )
#skimmer
add_executable(mcp_skimmer main/mcp_skimmer.cxx)
target_link_libraries(mcp_skimmer ${PROJECT_NAME})
#caf module
add_executable(cafanatree_module main/cafanatree_module.cxx)
target_link_libraries(cafanatree_module ${PROJECT_NAME})
#install in the bin folder
install( TARGETS mcp_skimmer RUNTIME DESTINATION bin )
install( TARGETS cafanatree_module RUNTIME DESTINATION bin )
<file_sep>#include "Utils.h"
Utils::Utils()
: _seed(0), _rando(new TRandom3(0))
{
_origin[0] = 0.;
_origin[1] = 0.;
_origin[2] = 0.;
}
Utils::~Utils()
{
delete _rando;
}
void Utils::SetSeed(int seed)
{
_seed = seed;
_rando->SetSeed(_seed);
}
void Utils::SetOrigin(double *origin)
{
_origin[0] = origin[0];
_origin[1] = origin[1];
_origin[2] = origin[2];
}
bool Utils::PointInFiducial(const TVector3 &point)
{
//TPC Fiducial volume defined as
//R < 260 cm
//|X| < 250 cm
bool isInFiducial = true;
float r_point = std::sqrt( point.Y()*point.Y() + point.Z()*point.Z() );
if( r_point > _TPCFidRadius ) isInFiducial = false;
if( r_point < _TPCFidRadius && std::abs(point.X()) > _TPCFidLength ) isInFiducial = false;
return isInFiducial;
}
bool Utils::PointInTPC(const TVector3 &point)
{
//TPC volume defined as
//R < 260 cm
//|X| < 250 cm
if(PointInFiducial(point)) return true;
bool isInTPC = true;
float r_point = std::sqrt( point.Y()*point.Y() + point.Z()*point.Z() );
if( r_point > _TPCRadius ) isInTPC = false;
if( r_point < _TPCRadius && std::abs(point.X()) > _TPCLength ) isInTPC = false;
return isInTPC;
}
bool Utils::PointInCalo(const TVector3 &point)
{
//Barrel Radius 278 cm
//Endcap starts at 364 cm
bool isInCalo = false;
float r_point = std::sqrt( point.Y()*point.Y() + point.Z()*point.Z() );
//in the Barrel
if( r_point > _ECALInnerRadius && r_point < _ECALOuterRadius && std::abs(point.X()) < _ECALStartX ) isInCalo = true;
//in the Endcap
if( r_point < _ECALInnerRadius && std::abs(point.X()) > _ECALStartX && std::abs(point.X()) < _ECALEndX ) isInCalo = true;
return isInCalo;
}
bool Utils::PointStopBetween(const TVector3 &point)
{
//Barrel Radius 278 cm
//Endcap starts at 364 cm
bool isStopBetween = false;
float r_point = std::sqrt( point.Y()*point.Y() + point.Z()*point.Z() );
//in the Barrel
if( r_point < _ECALInnerRadius && r_point > _TPCRadius && std::abs(point.X()) < _TPCLength ) isStopBetween = true;
//in the Endcap
if( r_point < _ECALInnerRadius && std::abs(point.X()) > _TPCLength && std::abs(point.X()) < _ECALStartX ) isStopBetween = true;
return isStopBetween;
}
bool Utils::isThroughCalo(const TVector3 &point)
{
return !PointInTPC(point) && !PointStopBetween(point) && !PointInCalo(point);
}
bool Utils::hasDecayedInCalo(const TVector3 &point)
{
return PointInCalo(point);
}
bool Utils::isBarrel(const TVector3 &point)
{
bool isBarrel = false;
float theta = std::atan(_ECALInnerRadius / std::abs(_ECALStartX) ); //angle for barrel/endcap transition
float r_point = std::sqrt( point.Y()*point.Y() + point.Z()*point.Z() );
float theta_point = std::atan(r_point / std::abs(point.X()) ); //angle for barrel/endcap transition for the point
if( theta_point > theta ) isBarrel = true;
return isBarrel;
}
bool Utils::isEndcap(const TVector3 &point)
{
bool isEndcap = false;
if( !isBarrel(point) ) isEndcap = true;
return isEndcap;
}
bool Utils::isBackscatter(const TVector3 &spoint, const TVector3 &epoint)
{
bool isBackscatter = false;
//check if started in the ECAL but made it to the tracker
float r_spoint = std::sqrt( spoint.Y()*spoint.Y() + spoint.Z()*spoint.Z() );
float r_epoint = std::sqrt( epoint.Y()*epoint.Y() + epoint.Z()*epoint.Z() );
//in the Barrel
if( r_spoint > _ECALInnerRadius && r_epoint < _TPCRadius ) isBackscatter = true;
//in the Endcap
if( (r_spoint < _ECALInnerRadius && r_epoint < _TPCRadius) && ( std::abs(spoint.X()) > _ECALStartX && std::abs(epoint.X()) < _TPCLength ) ) isBackscatter = true;
return isBackscatter;
}
bool Utils::isBremsstrahlung(const TVector3 &spoint, const int& pdg, const int& motherpdg)
{
bool isBremsstrahlung = false;
//Check if it has origin in the tracker and that the pdg is photon and mother is electron/positron (most probable)
if(PointInFiducial(spoint) && pdg == 22 && std::abs(motherpdg) == 11) isBremsstrahlung = true;
return isBremsstrahlung;
}
<file_sep>void CheckSizeBranches()
{
// CaliceStyle();
//Read sizes of the caf tree vectors and check that the sizes are consistent
//if you are reading only one file, for debugging purposes: 1) comment out lines 8 through 39
//and then again lines 145 and 146, 2) un-comment lines 41 and 42.
const char *dirname="/pnfs/dune/persistent/users/ND_GAr/2020_06_21/neutrino/";
const char *ext=".root";
std::vector<const char*> lista;
lista.clear();
TChain *chain = new TChain("caf");
TSystemDirectory dir(dirname, dirname);
TList *files = dir.GetListOfFiles();
TSystemFile *file;
TString fname;
TIter next(files);
while ((file = (TSystemFile*)next())) {
fname = file->GetName();
if (file->IsDirectory() && fname.EndsWith(ext)) continue;
char result[255]; // array to hold the result.
strcpy(result,dirname); // copy string one into the result.
strcat(result,fname.Data()); // append string two to the result.
lista.push_back(result);
for(std::vector<const char*>::iterator it = lista.begin(); it != lista.end(); it++)
{
std::cout << *it << std::endl;
string a(*it);
TFile * tf = new TFile ( Form("%s",a.c_str() ) );
chain->Add( Form("%s/caf", a.c_str()) );
//TChain *chain = new TChain("caf");
//chain->Add("/pnfs/dune/persistent/users/ND_GAr/2020_06_21/neutrino/neutrino.nd_hall_mpd_only.volTPCGas.Ev336000.Ev336999.11141.caf.root");
//std::cout << *it << std::endl;
int evt;
std::vector<double>* mctime = 0;
std::vector<int> *_nFSP = 0;
std::vector<double> *theta = 0;
std::vector<int> *detected = 0;
std::vector<int> *pdgmother = 0;
std::vector<int> *truepdg = 0;
std::vector<int> * _MCPStartX = 0;
std::vector<int> *_MCPStartY = 0;
std::vector<int> *_MCPStartZ = 0;
std::vector<int> *_MCPEndX = 0;
std::vector<int> *_MCPEndY = 0;
std::vector<int> *_MCPEndZ = 0;
std::vector<std::string> *_MCProc = 0;
std::vector<std::string> *_MCEndProc = 0;
std::vector<float> *trkLen = 0;
std::vector<float> *trkLenPerp = 0;
std::vector<float> *truep = 0;
std::vector<float> *truepx = 0;
std::vector<float> *truepy = 0;
std::vector<float> *truepz = 0;
std::vector<float> *_angle = 0;
//Reco values
std::vector<int> *recopid = 0;
std::vector<float> *prob_arr = 0;
std::vector<float> *partereco = 0;
std::vector<float> *anglereco = 0;
std::vector<float> *_preco = 0;
std::vector<float> *erecon = 0;
chain->SetBranchAddress("Event", &evt);
chain->SetBranchAddress("theta", &theta);
chain->SetBranchAddress("nFSP", &_nFSP);
chain->SetBranchAddress("detected", &detected);
chain->SetBranchAddress("pdgmother", &pdgmother);
chain->SetBranchAddress("MCPTime", &mctime);
chain->SetBranchAddress("MCPStartX", &_MCPStartX);
chain->SetBranchAddress("MCPStartY", &_MCPStartY);
chain->SetBranchAddress("MCPStartZ", &_MCPStartZ);
chain->SetBranchAddress("truepx", &truepx);
chain->SetBranchAddress("truepy", &truepy);
chain->SetBranchAddress("truepz", &truepz);
chain->SetBranchAddress("MCPEndX", &_MCPEndX);
chain->SetBranchAddress("MCPEndY", &_MCPEndY);
chain->SetBranchAddress("MCPEndZ", &_MCPEndZ);
chain->SetBranchAddress("MCProc", &_MCProc);
chain->SetBranchAddress("MCEndProc", &_MCEndProc);
chain->SetBranchAddress("angle", &_angle);
chain->SetBranchAddress("truep", &truep);
chain->SetBranchAddress("truepdg", &truepdg);
//Reco info
chain->SetBranchAddress("recopid", &recopid);
chain->SetBranchAddress("trkLen", &trkLen);
chain->SetBranchAddress("trkLenPerp", &trkLenPerp);
chain->SetBranchAddress("preco", &_preco);
chain->SetBranchAddress("anglereco", &anglereco);
chain->SetBranchAddress("erecon", &erecon);
chain->SetBranchAddress("prob_arr", &prob_arr);
for(int itree = 0; itree < chain->GetEntries(); itree++)
{
chain->GetEntry(itree);
std::cout << "Event " << evt << std::endl;
std::cout << "theta " << theta->size() << std::endl;
std::cout << "Size pdgmother: " << pdgmother->size() << std::endl;
std::cout << "Size MCPTime: " << mctime->size() << std::endl;
std::cout << "Size MCPStartX: " << _MCPStartX->size() << std::endl;
std::cout << "Size MCPStartY: " << _MCPStartY->size() << std::endl;
std::cout << "Size MCPStartZ: " << _MCPStartZ->size() << std::endl;
std::cout << "Size truepx: " << truepx->size() << std::endl;
std::cout << "Size truepy: " << truepy->size() << std::endl;
std::cout << "Size truepz: " << truepz->size() << std::endl;
std::cout << "Size MCPEndX: " << _MCPEndX->size() << std::endl;
std::cout << "Size MCPEndY: " << _MCPEndY->size() << std::endl;
std::cout << "Size MCPEndZ: " << _MCPEndZ->size() << std::endl;
std::cout << "Size _MCProc: " << _MCProc->size() << std::endl;
std::cout << "Size _MCEndProc: " << _MCEndProc->size() << std::endl;
std::cout << "Size _angle: " << _angle->size() << std::endl;
std::cout << "Size truep: " << truep->size() << std::endl;
std::cout << "Size truepdg: " << truepdg->size() << std::endl;
std::cout << "Size recopid: " << recopid->size() << std::endl;
std::cout << "Size trkLen: " << trkLen->size() << std::endl;
std::cout << "Size trkLenPerp: " << trkLenPerp->size() << std::endl;
std::cout << "Size _preco: " << _preco->size() << std::endl;
std::cout << "Size anglereco: " << anglereco->size() << std::endl;
std::cout << "Size erecon: " << erecon->size() << std::endl;
std::cout << "Size prob_arr: " << prob_arr->size() << std::endl;
std::cout << "Size _nFSP: " << _nFSP->size() << " value " << _nFSP->at(0) << std::endl;
std::cout << "Size detected: " << detected->size() << std::endl;
for(int i = 0; i < theta->size(); i++)
{
std::cout << "value of theta is: " << theta->at(i) << std::endl;
}
}
}
}
}
<file_sep>#!/bin/bash
source /cvmfs/dune.opensciencegrid.org/products/dune/setup_dune.sh
setup cmake v3_14_3
setup genie v3_00_06i -q e19:prof
cd /Package
mkdir build
cd build
cmake -GNinja -DCMAKE_CXX_FLAGS="-fdiagnostics-color=always" .. && \
ninja && \
ninja install
<file_sep>#include "CAF.h"
#include "TFile.h"
#include "TTree.h"
#include <iostream>
#include <string>
////////////////////////////////////////////////////////////////////////
//// Class: cafanatree
//// File Name: cafanatree_module.cc
////
//// Authors: <NAME> and <NAME>
//// To run this module:
//// 1) cd Build
//// 2) rm -rf *
//// 3) cmake ${module home direcory}
//// 4) make install
//// 5) cd ${module home direcory}
//// 6) bin/cafanatree_module --infile ${name of the anatree file that is output from anatree module, not to be confused with edepsim file} --outfile ${a name of your choosing for the output file}
//////////////////////////////////////////////////////////////////////////
void ShowHelp()
{
std::cout << "./cafanatree_module --infile <inputfile> --outfile <outputfile> --correct4origin <0/1> --originTPC <x> <y> <z> (in cm)" << std::endl;
}
int main( int argc, char const *argv[] )
{
if( argc == 1 || ((argc == 2) && ((std::string("--help") == argv[1]) || (std::string("-h") == argv[1]))) || argc < 8 ){
ShowHelp();
return 2;
}
if( argv[1] != std::string("--infile") || argv[3] != std::string("--outfile") || argv[5] != std::string("--correct4origin") || argv[7] != std::string("--originTPC") ) {
ShowHelp();
return -2;
}
// get command line options
std::string outfile = "";
std::string infile = "";
std::string correct4origin = "";
std::string x, y, z = "";
int p = 0;
while( p < argc )
{
if( argv[p] == std::string("--infile") ){
infile = argv[p+1];
p++;
}
else if( argv[p] == std::string("--outfile") ){
outfile = argv[p+1];
p++;
}
else if( argv[p] == std::string("--correct4origin") ){
correct4origin = argv[p+1];
p++;
}
else if( argv[p] == std::string("--originTPC") ){
//origin fixed
if( argc == 11 )
{
x = argv[p+1];
y = argv[p+2];
z = argv[p+3];
p += 3;
}
else{
std::cout << "Missing an origin coordinate!" << std::endl;
ShowHelp();
return -2;
}
}
else{
p++;
}
}
if(correct4origin != "0" && correct4origin != "1")
{
ShowHelp();
return -2;
}
if( x == "" && y == "" && z == "" )
{
printf("No TPC offset given, defaulting to (0, 0, 0)!!\n");
x = y = z = "0";
}
printf( "Making CAF from tree dump: %s\n", infile.c_str() );
printf( "Output CAF file: %s\n", outfile.c_str() );
printf( "Correct for Origin: %s\n", correct4origin.c_str() );
printf( "TPC offset: (%s, %s, %s) cm\n", x.c_str(), y.c_str(), z.c_str() );
double originTPC[3] = {std::atof(x.c_str()), std::atof(y.c_str()), std::atof(z.c_str())};
CAF *caf = new CAF(infile, outfile, std::atoi(correct4origin.c_str()), &originTPC[0]);
if(not caf->BookTFile()) return -1;
caf->loop();
caf->WriteTTree();
printf( "-30-\n" );
caf->CloseTFile();
return 0;
}
<file_sep>#########################################################
# cmake module for finding PYTHIA6
#
#
# returns:
# PYTHIA6_FOUND : set to TRUE or FALSE
# PYTHIA6_INCLUDE_DIRS : paths to gsl includes
# PYTHIA6_LIBRARIES : list of gsl libraries
#
# @author <NAME>, DESY
#########################################################
SET( PYTHIA6_ROOT PYTHIA6_ROOT-NOTFOUND )
MARK_AS_ADVANCED( PYTHIA6_ROOT )
SET( PYTHIA6_ROOT $ENV{PYTHIA_FQ_DIR} )
FIND_LIBRARY(PYTHIA6_LIBRARIES NAMES Pythia6 pythia6 PATHS ${PYTHIA6_ROOT} PATH_SUFFIXES lib lib64 NO_DEFAULT_PATH)
# ---------- includes ---------------------------------------------------------
SET( PYTHIA6_INCLUDE_DIRS PYTHIA6_INCLUDE_DIRS-NOTFOUND )
MARK_AS_ADVANCED( PYTHIA6_INCLUDE_DIRS )
SET( PYTHIA6_INCLUDE_DIRS NAMES pyjets.inc PATHS ${PYTHIA6_ROOT}/include NO_DEFAULT_PATH )
IF( NOT PYTHIA6_ROOT )
FIND_PATH( PYTHIA6_INCLUDE_DIRS NAMES pyjets.inc )
ENDIF()
# ---------- final checking ---------------------------------------------------
INCLUDE( FindPackageHandleStandardArgs )
# set GENIE_FOUND to TRUE if all listed variables are TRUE and not empty
FIND_PACKAGE_HANDLE_STANDARD_ARGS( PYTHIA6 DEFAULT_MSG PYTHIA6_ROOT PYTHIA6_LIBRARIES PYTHIA6_INCLUDE_DIRS )
<file_sep>#ifndef UTILS_H
#define UTILS_H 1
#include "TVector3.h"
#include "TRandom3.h"
class Utils
{
public:
/* Default constructor */
Utils();
/* Copy constructor */
Utils(const Utils &) = default;
/* Destructor */
~Utils();
/* Set the seed */
void SetSeed(int seed);
/* Set the origin */
void SetOrigin(double *origin);
/* Check if MCP point is in fiducial */
bool PointInFiducial(const TVector3 &point);
/* Check if MCP point is in TPC Volume (can be outside Fid) */
bool PointInTPC(const TVector3 &point);
/* Check if MCP point is in the ECAL */
bool PointInCalo(const TVector3 &point);
/* Check if MCP point is in between the TPC and the ECAL */
bool PointStopBetween(const TVector3 &point);
/* Check if MCP point is not in the fiducial and not in the ECAL */
bool isThroughCalo(const TVector3 &point);
/* Check if MCP decayed in calo */
bool hasDecayedInCalo(const TVector3 &point);
/* Check if MCP is in the Barrel region */
bool isBarrel(const TVector3 &point);
/* Check if MCP is in the Endcap region */
bool isEndcap(const TVector3 &point);
/* Check if the mcp is a backscatter */
bool isBackscatter(const TVector3 &spoint, const TVector3 &epoint);
/* Check if it is a Bremsstrahlung photon */
bool isBremsstrahlung(const TVector3 &spoint, const int& pdg, const int& motherpdg);
float GetRamdomNumber() { return _rando->Rndm(); }
float GaussianSmearing(const float& mean, const float& sigma) { return _rando->Gaus(mean, sigma); }
double* GetOrigin() { return &_origin[0]; }
private:
double _origin[3]; ///< coordinates of the origin
unsigned long int _seed; ///< seed
TRandom3 *_rando; ///< random generator
/* HARDCODED */
double _TPCFidRadius = 222.5;
double _TPCFidLength = 215.;
double _TPCRadius = 273.;
double _TPCLength = 259.;
double _ECALInnerRadius = 278.;
double _ECALOuterRadius = 321.;
double _ECALStartX = 364.;
double _ECALEndX = 406.;
};
#endif
<file_sep>void checkmuons()
{
// CaliceStyle();
//Compare between ptrue <-> preco and angle <-> anglereco
TH1F* hPullMomentum = new TH1F("hPullMomentum", "hPullMomentum", 300, -1, 1);
hPullMomentum->SetLineWidth(2);
hPullMomentum->SetLineColor(kBlack);
TH2F* hMomemtumTruevsReco = new TH2F("hMomemtumTruevsReco", "hMomemtumTruevsReco", 100, 0, 5, 100, 0, 5);
TH1F* hPullAngle = new TH1F("hPullAngle", "hPullAngle", 100, -1, 1);
hPullAngle->SetLineWidth(2);
hPullAngle->SetLineColor(kBlack);
TH2F* hAngleTruevsReco = new TH2F("hAngleTruevsReco", "hAngleTruevsReco", 100, -1, 1, 100, -1, 1);
TH1F* hPullNeutrons = new TH1F("hPullNeutrons", "hPullNeutrons", 100, -1, 1);
hPullNeutrons->SetLineWidth(2);
hPullNeutrons->SetLineColor(kBlack);
//if you are reading only one file, for debugging purposes: 1) comment out lines 24 through 57 and then lines 94 and 95,
//then 2) un-comment lines 59 and 60
const char *dirname="/pnfs/dune/persistent/users/ND_GAr/2020_06_21/neutrino/";
const char *ext=".root";
std::vector<const char*> lista;
lista.clear();
TChain *chain = new TChain("caf");
TSystemDirectory dir(dirname, dirname);
TList *files = dir.GetListOfFiles();
TSystemFile *file;
TString fname;
TIter next(files);
while ((file = (TSystemFile*)next())) {
fname = file->GetName();
if (file->IsDirectory() && fname.EndsWith(ext)) continue;
char result[255]; // array to hold the result.
strcpy(result,dirname); // copy string one into the result.
strcat(result,fname.Data()); // append string two to the result.
lista.push_back(result);
for(std::vector<const char*>::iterator it = lista.begin(); it != lista.end(); it++)
{
std::cout << *it << std::endl;
string a(*it);
TFile * tf = new TFile ( Form("%s",a.c_str() ) );
chain->Add( Form("%s/caf", a.c_str()) );
//TChain *chain = new TChain("caf");
//chain->Add("/pnfs/dune/persistent/users/ND_GAr/2020_06_21/neutrino/neutrino.nd_hall_mpd_only.volTPCGas.Ev336000.Ev336999.11141.caf.root");
std::vector<float> *truep = 0;
std::vector<float> *preco = 0;
std::vector<int> *truepdg = 0;
std::vector<int> *recopid = 0;
std::vector<float> *angle = 0;
std::vector<float> *anglereco = 0;
std::vector<float> *erecon = 0;
chain->SetBranchAddress("truep", &truep);
chain->SetBranchAddress("preco", &preco);
chain->SetBranchAddress("truepdg", &truepdg);
chain->SetBranchAddress("recopid", &recopid);
chain->SetBranchAddress("angle", &angle);
chain->SetBranchAddress("anglereco", &anglereco);
chain->SetBranchAddress("erecon", &erecon);
for(int itree = 0; itree < chain->GetEntries(); itree++)
{
chain->GetEntry(itree);
for(int i = 0; i < truep->size(); i++)
{
//Muons
if( std::abs(truepdg->at(i)) == 13 && std::abs(recopid->at(i)) == 13){
hPullMomentum->Fill( (truep->at(i) - preco->at(i)) / truep->at(i) );
hMomemtumTruevsReco->Fill(truep->at(i), preco->at(i));
hPullAngle->Fill( (angle->at(i) - anglereco->at(i)) / angle->at(i) );
hAngleTruevsReco->Fill(angle->at(i), anglereco->at(i));
}
}
}
}
}
gStyle->SetOptStat(1110);
gStyle->SetOptFit(1);
hPullMomentum->Scale(1./hPullMomentum->Integral());
hPullMomentum->SetStats(kTRUE);
hPullMomentum->Fit("gaus", "EMR+", "", -0.8, 0.8);
TCanvas *c1 = new TCanvas("c1", "Pull p", 800, 600);
hPullMomentum->GetXaxis()->SetTitle( "(p_{true} - p_{reco}) / p_{true}" );
hPullMomentum->GetYaxis()->SetTitle( "Normalized Events" );
hPullMomentum->Draw("hist");
hPullMomentum->GetFunction("gaus")->SetLineColor(kRed);
hPullMomentum->GetFunction("gaus")->SetLineStyle(2);
hPullMomentum->GetFunction("gaus")->Draw("same");
c1->SaveAs("PullMomentumMuons.pdf");
TCanvas *c2 = new TCanvas("c2", "Mom truth vs reco", 800, 600);
gPad->SetRightMargin(0.12);
hMomemtumTruevsReco->GetXaxis()->SetTitle( "p_{true} [GeV]" );
hMomemtumTruevsReco->GetYaxis()->SetTitle( "p_{reco} [GeV]" );
hMomemtumTruevsReco->Draw("COLZ");
c2->SaveAs("MomentumMuons_TruevsReco.pdf");
hPullAngle->Scale(1./hPullAngle->Integral());
hPullAngle->SetStats(kTRUE);
TCanvas *c3 = new TCanvas("c3", "Pull angle", 800, 600);
hPullAngle->GetXaxis()->SetTitle( "(angle_{true} - angle_{reco}) / angle_{true}" );
hPullAngle->GetYaxis()->SetTitle( "Normalized Events" );
hPullAngle->Draw("hist");
c3->SaveAs("PullAngleMuons.pdf");
TCanvas *c4 = new TCanvas("c4", "Angle truth vs reco", 800, 600);
gPad->SetRightMargin(0.12);
hAngleTruevsReco->GetXaxis()->SetTitle( "angle_{true} [GeV]" );
hAngleTruevsReco->GetYaxis()->SetTitle( "angle_{reco} [GeV]" );
hAngleTruevsReco->Draw("COLZ");
c4->SaveAs("AngleMuons_TruevsReco.pdf");
// TCanvas *c5 = new TCanvas("c5", "Pull Neutrons", 800, 600);
// hPullNeutrons->GetXaxis()->SetTitle( "(E_{true} - E_{reco}) / E_{true}" );
// hPullNeutrons->GetYaxis()->SetTitle( "Normalized Events" );
// hPullNeutrons->Draw("hist");
// c5->SaveAs("PullEnergyNeutrons.pdf");
}
<file_sep>#ifndef MCP_SKIMMER_H
#define MCP_SKIMMER_H 1
#include <string>
#include "TFile.h"
#include "TTree.h"
#include "Utils.h"
class MCP_Skimmer
{
public:
/* Default Constructor */
MCP_Skimmer();
/* Constructor */
MCP_Skimmer(std::string infilename, std::string outfilename);
/* Default Copy Constructor */
MCP_Skimmer(const MCP_Skimmer &) = default;
/* Destructor */
~MCP_Skimmer();
/* Method to skim the MCPs from the TFile */
void SkimMCParticle();
/* Method to book the output TFile */
bool BookTFile();
/* Method to fill the TTree */
void FillTTree();
/* Method to write the TTree */
void WriteTTree();
/* Method to close the TFile */
void CloseTFile();
/* Method to clear the event variables */
void ClearVectors();
/* Set debug flag */
void SetDebug(bool debug) { _debug = debug; }
protected:
private:
TFile* _intfile;
TFile* _skimfile;
TTree* _skimtree;
TTree* _inttree;
bool _debug;
Utils *_util;
std::string _infile;
std::string _outfile;
int _Event;
int _SubRun;
int _Run;
std::vector<float> _MC_Q2;
std::vector<float> _MC_W;
std::vector<float> _MC_Y;
std::vector<float> _MC_X;
std::vector<float> _MC_Theta;
std::vector<float> _MC_T;
std::vector<float> _MCVertX;
std::vector<float> _MCVertY;
std::vector<float> _MCVertZ;
std::vector<float> _MCNuPx;
std::vector<float> _MCNuPy;
std::vector<float> _MCNuPz;
std::vector<int> _NType;
std::vector<int> _CCNC;
std::vector<int> _Mode;
std::vector<int> _Gint;
std::vector<int> _TgtPDG;
std::vector<int> _GT_T;
std::vector<int> _InterT;
std::vector<float> _Weight;
std::vector<int> _PDG;
std::vector<int> _Mother;
std::vector<int> _PDGMother;
std::vector<int> _MCPTrkID;
std::vector<float> _MCPTime;
std::vector<float> _MCPStartX;
std::vector<float> _MCPStartY;
std::vector<float> _MCPStartZ;
std::vector<float> _MCPStartPX;
std::vector<float> _MCPStartPY;
std::vector<float> _MCPStartPZ;
std::vector<std::string> _MCPProc;
std::vector<std::string> _MCPEndProc;
std::vector<float> _MCPEndX;
std::vector<float> _MCPEndY;
std::vector<float> _MCPEndZ;
std::vector<float> _TrajMCPX;
std::vector<float> _TrajMCPY;
std::vector<float> _TrajMCPZ;
std::vector<int> _TrajMCPTrajIndex;
//vector of pdg values where we should keep the daughter
std::vector<int> daughtersToKeep = {22, 111, 310, 13, 211, 321};
};
#endif /* MCP_SKIMMER_H */
<file_sep>#########################################################
# cmake module for finding LOG4CPP
#
#
# returns:
# LOG4CPP_FOUND : set to TRUE or FALSE
# LOG4CPP_INCLUDE_DIRS : paths to gsl includes
# LOG4CPP_LIBRARIES : list of gsl libraries
#
# @author <NAME>, DESY
#########################################################
# find log4cpp-config (seems that there is a problem currently on cvmfs to execute it)
# SET( LOG4CPP_CONFIG_EXECUTABLE LOG4CPP_CONFIG_EXECUTABLE-NOTFOUND )
# MARK_AS_ADVANCED( LOG4CPP_CONFIG_EXECUTABLE )
# FIND_PROGRAM( LOG4CPP_CONFIG_EXECUTABLE log4cpp-config PATHS $ENV{LOG4CPP_FQ_DIR}/bin NO_DEFAULT_PATH )
# IF( NOT LOG4CPP_FQ_DIR )
# FIND_PROGRAM( LOG4CPP_CONFIG_EXECUTABLE log4cpp-config )
# ENDIF()
#
# IF( LOG4CPP_CONFIG_EXECUTABLE )
#
# # ==============================================
# # === LOG4CPP_PREFIX ===
# # ==============================================
#
# EXECUTE_PROCESS( COMMAND "${LOG4CPP_CONFIG_EXECUTABLE}" --prefix
# OUTPUT_VARIABLE LOG4CPP_ROOT
# OUTPUT_STRIP_TRAILING_WHITESPACE
# )
#
# # ==============================================
# # === LIBXML2_LIBRARIES ===
# # ==============================================
#
# EXECUTE_PROCESS( COMMAND "${LOG4CPP_CONFIG_EXECUTABLE}" --libs
# OUTPUT_VARIABLE LOG4CPP_LIBRARIES
# OUTPUT_STRIP_TRAILING_WHITESPACE
# )
#
# ENDIF( LOG4CPP_CONFIG_EXECUTABLE )
SET( LOG4CPP_ROOT LOG4CPP_ROOT-NOTFOUND )
MARK_AS_ADVANCED( LOG4CPP_ROOT )
SET( LOG4CPP_ROOT $ENV{LOG4CPP_FQ_DIR} )
FIND_LIBRARY(LOG4CPP_LIBRARIES NAMES log4cpp PATHS ${LOG4CPP_ROOT} PATH_SUFFIXES lib lib64 NO_DEFAULT_PATH)
# ---------- includes ---------------------------------------------------------
SET( LOG4CPP_INCLUDE_DIRS LOG4CPP_INCLUDE_DIRS-NOTFOUND )
MARK_AS_ADVANCED( LOG4CPP_INCLUDE_DIRS )
SET( LOG4CPP_INCLUDE_DIRS NAMES log4cpp/config.h PATHS ${LOG4CPP_ROOT}/include NO_DEFAULT_PATH )
IF( NOT LOG4CPP_ROOT )
FIND_PATH( LOG4CPP_INCLUDE_DIRS NAMES log4cpp/config.h )
ENDIF()
# ---------- final checking ---------------------------------------------------
INCLUDE( FindPackageHandleStandardArgs )
# set GENIE_FOUND to TRUE if all listed variables are TRUE and not empty
FIND_PACKAGE_HANDLE_STANDARD_ARGS( LOG4CPP DEFAULT_MSG LOG4CPP_ROOT LOG4CPP_LIBRARIES LOG4CPP_INCLUDE_DIRS )
<file_sep>#!/bin/bash
#bin/mcp_skimmer --infile anatree_100.root --outfile skimmed.root --debug 0
#echo "done with running skimming module"
#### For CDR production sample, where the TPC is not in (0, 0, 0), correction for mcp position wrt TPC center
#cafanatree_module --infile andytree.root --outfile caf.root --correct4origin 1 --originTPC 0.00012207 -150.473 1486
#### For CDR production sample, where the TPC is not in (0, 0, 0), no correction for mcp position wrt TPC center
#cafanatree_module --infile andytree.root --outfile caf.root --correct4origin 0 --originTPC 0.00012207 -150.473 1486
#### For any sample, where the TPC is in (0, 0, 0)
#cafanatree_module --infile andytree.root --outfile caf.root --correct4origin 0 --originTPC 0 0 0
echo "done with running cafanatree module"
<file_sep>#########################################################
# cmake module for finding LIBXML2
#
#
# returns:
# LIBXML2_FOUND : set to TRUE or FALSE
# LIBXML2_INCLUDE_DIRS : paths to gsl includes
# LIBXML2_LIBRARIES : list of gsl libraries
#
# @author <NAME>, DESY
#########################################################
# find genie-config
SET( LIBXML2_CONFIG_EXECUTABLE LIBXML2_CONFIG_EXECUTABLE-NOTFOUND )
MARK_AS_ADVANCED( LIBXML2_CONFIG_EXECUTABLE )
FIND_PROGRAM( LIBXML2_CONFIG_EXECUTABLE xml2-config PATHS $ENV{LIBXML2_FQ_DIR}/bin NO_DEFAULT_PATH )
IF( NOT LIBXML2_FQ_DIR )
FIND_PROGRAM( LIBXML2_CONFIG_EXECUTABLE xml2-config )
ENDIF()
IF( LIBXML2_CONFIG_EXECUTABLE )
# ==============================================
# === LIBXML2_PREFIX ===
# ==============================================
EXECUTE_PROCESS( COMMAND "${LIBXML2_CONFIG_EXECUTABLE}" --prefix
OUTPUT_VARIABLE LIBXML2_ROOT
OUTPUT_STRIP_TRAILING_WHITESPACE
)
# ==============================================
# === LIBXML2_LIBRARIES ===
# ==============================================
EXECUTE_PROCESS( COMMAND "${LIBXML2_CONFIG_EXECUTABLE}" --libs
OUTPUT_VARIABLE LIBXML2_LIBRARIES
OUTPUT_STRIP_TRAILING_WHITESPACE
)
ENDIF( LIBXML2_CONFIG_EXECUTABLE )
# ---------- includes ---------------------------------------------------------
SET( LIBXML2_INCLUDE_DIRS LIBXML2_INCLUDE_DIRS-NOTFOUND )
MARK_AS_ADVANCED( LIBXML2_INCLUDE_DIRS )
SET( LIBXML2_INCLUDE_DIRS NAMES libxml/xmlversion.h PATHS ${LIBXML2_ROOT}/include NO_DEFAULT_PATH )
IF( NOT LIBXML2_ROOT )
FIND_PATH( LIBXML2_INCLUDE_DIRS NAMES libxml/xmlversion.h )
ENDIF()
# ---------- final checking ---------------------------------------------------
INCLUDE( FindPackageHandleStandardArgs )
# set GENIE_FOUND to TRUE if all listed variables are TRUE and not empty
FIND_PACKAGE_HANDLE_STANDARD_ARGS( LIBXML2 DEFAULT_MSG LIBXML2_ROOT LIBXML2_LIBRARIES LIBXML2_INCLUDE_DIRS )
<file_sep>#ifndef CAF_h
#define CAF_h
#include "TFile.h"
#include "TTree.h"
#include "TH2F.h"
#include "Utils.h"
#include <unordered_map>
class CAF {
typedef std::pair<float, std::string> P;
public:
/* Default Constructor */
CAF();
/* Constructor */
CAF( std::string infile, std::string filename, int correct4origin, double *originTPC);
/* Default Copy Constructor */
CAF(const CAF &) = default;
/* Destructor */
~CAF();
/* Method to book the output TFile */
bool BookTFile();
/* Method to fill the output TTree */
void FillTTree();
/* Method to write the output TTree */
void WriteTTree();
/* Method to close the output TTree */
void CloseTFile();
/* Method to clear the event variables */
void ClearVectors();
/* Method to loop */
void loop();
/* Method to check vector size */
bool CheckVectorSize();
private:
TFile * cafFile; ///< The output TFile pointer */
TTree * cafMVA; ///< The output TTree pointer */
std::unordered_map<int, TH2F*> m_pidinterp;
TFile* _intfile;
TTree* _inttree;
Utils *_util;
std::string _inputfile;
std::string _outputFile; ///< The output TFile name */
unsigned int _correct4origin; ///< sets the string for the coordinates origins (World or TPC)
//Event-wise values
unsigned int _Run, _Event, _SubRun;
//Generator values
std::vector<int> mode, ccnc, ntype, gint, weight, tgtpdg, gt_t, intert, detected;
std::vector<int> nGPart, GPartPdg, GPartStatus, GPartFirstMom, GPartLastMom, GPartFirstDaugh, GPartLastDaugh;
std::vector<float> GPartPx, GPartPy, GPartPz, GPartE, GPartMass;
std::vector<std::string> GPartName;
std::vector<double> q2, w, y, x, theta, t, mctime, mcnupx, mcnupy, mcnupz, vertx, verty, vertz;
//MC Particle Values, with motherid added
std::vector<unsigned int> _nFSP;
std::vector<int> mctrkid, motherid, pdgmother, truepdg, _MCPStartX, _MCPStartY, _MCPStartZ, _MCPEndX, _MCPEndY, _MCPEndZ;
std::vector<std::string> _MCProc, _MCEndProc;
std::vector<double> trkLen, trkLenPerp, truep, truepx, truepy, truepz, _angle;
//Reco values
std::vector<int> recopid, recopidecal;
std::vector<double> prob_arr, anglereco, _preco, erecon, etime;
//Geometry
std::vector<unsigned int> isFidStart, isTPCStart, isCaloStart, isInBetweenStart, isThroughCaloStart;
std::vector<unsigned int> isFidEnd, isTPCEnd, isCaloEnd, isInBetweenEnd, isThroughCaloEnd;
std::vector<unsigned int> isBarrelStart, isEndcapStart, isBarrelEnd, isEndcapEnd;
float calcGluck(double sigmaX, double B, double X0, float nHits, double mom, double length, double& ratio);
};
#endif
|
1d0d9b7502b6c6f4475fee9d088517866690c33d
|
[
"Markdown",
"CMake",
"C++",
"Shell"
] | 18 |
C++
|
tmohayai/ParamSim
|
69563d0fb4b88bfd18bf0a5756b21e68d77bc94d
|
c5f526c93ea5cb78780df654477af76ba1739818
|
refs/heads/master
|
<file_sep>!function () {
var jiShiQi=0;
function lunbo () {
var $ul = $('.lunBo-ul'),
$ulli = $ul.find('li'),
len = $ulli.length,
$ol = $('.lunBo-ol'),
$olli = $ol.find('li'),
width= $ulli.width();
$ul.width(len*width);
setInterval(function() {
jiShiQi ++;
if (jiShiQi >len-1) {
jiShiQi=0;
};
$lis = $olli.eq(jiShiQi);
$lis.addClass('on').siblings('.on').removeClass('on');
$ul.animate({'marginLeft':-width},500,function () {
$ul
.append($ul.find('li:first'))
.css('margin-left',0)
})
},2000)
};
lunbo();
function tab () {
var $ul = $('.div-ul');
setInterval(function () {
$ul
.animate({'marginTop':'-50px'},1000,function () {
$ul
.append($ul.find('li:first'))
.css('margin-top',0)
})
});
};
tab();
}();
|
c8004fc2cb89c08808f74de87c25de092a5943fd
|
[
"JavaScript"
] | 1 |
JavaScript
|
zhouYue946821/zhouYue946821.github.io
|
1f8df01fbdebd45b41aaea4b4ceda674da1528f4
|
7fc23f52f38f651732d3df078c379e9671538e05
|
refs/heads/master
|
<repo_name>gnudrew/udemy-big-10<file_sep>/basic_fib.py
def fib(n):
'''Calculate the fibonnaci sequence up to or less than n'''
a, b = 1, 1
print(a)
while b < n:
print(b)
a, b = b, a + b
max = int(input("Enter the max number for fib:"))
fib(max)
<file_sep>/section8_problem/textpro.py
def sentify(sometext):
cap = sometext.capitalize()
Interrogatives = ("Who", "What", "When", "Where", "Why", "How")
if cap.startswith(Interrogatives):
return("%s?" % cap)
else:
return("%s." % cap)
# initialize a list of strings to store the data.
sentences = []
# Build the data from user input.
# user enters /end to terminate the input.
while True:
nextSentence = input("Enter some text:")
if nextSentence == '/end':
break
else:
sentences.append(sentify(nextSentence))
continue
# join and print the sentences.
print(sentences)
print(' '.join(sentences))
<file_sep>/basic_compListCond.py
def foo(myList):
newList = [
0 if isinstance(value, str) else value
for value in myList
]
return newList
data = [1.1, 2.2, 'no data', 4.4, 'no data', 5.5,]
print('Foo input: ', data)
print('Foo output: ', foo(data))<file_sep>/basic_sortAndCap.py
def sortAndCap(*args):
# assume *args are all strings.
newList = []
length = len(args)
startList = list(args)
while True: #we'll pop args down to empty to build our new list
# get lowest in current startList
im_first = 0
for i in range(len(startList)):
a = startList[i].lower()
b = startList[im_first].lower()
if a < b:
im_first = i # a new winner in the current list!
new = startList.pop(im_first)
newList.append(new.upper())
if len(newList) == length:
break
return newList
print(sortAndCap("Zedd", "Corbin", "Andrew", "Peter", "Gregg", "Puff"))
# print(sortAndCap(1, 3, 2))
# testList = input("Type a few comma-separated strings to sort and capitalize: ")
# testList = [
# str(i)
# for i in testList
# ]
# print(sortAndCap(testList))
<file_sep>/section23_OOP/account/script.py
class Account:
def __init__(self, filepath):
self.filepath = filepath
with open(filepath, 'r') as fp:
self.balance = int(fp.read())
def withdraw(self, amount):
self.balance = self.balance - int(amount)
def deposit(self, amount):
self.balance = self.balance + int(amount)
def commit(self):
with open(self.filepath, 'w') as file:
file.write(str(self.balance))
class Checking(Account):
type="checking"
def overdraft(self, amount):
print("Your account overdrafted by... "+str(amount))
pass
act = Account("balance.txt")
print(act.balance)
act.withdraw(100)
print(act.balance)
act.deposit(200)
print(act.balance)
act.commit()
# chk = Checking("balance.txt")
# print(chk.balance)
# print(chk.overdraft(145))<file_sep>/basic_compList.py
def uncompress_temps(temperatures):
new_temps = [
temp / 10
for temp in temperatures
]
return new_temps
# Data stored by omitting the decimel. Divide by 10 to get it back.
temps = [120, 132, 153, 214]
print(temps)
print(uncompress_temps(temps))<file_sep>/basics.py
monday_temps = [9.2, 8.5, 7.2]
student_grades = {"Mary": 9.2, "Sim": 8.5, "John": 7.2}
mysum = sum(student_grades.values())
length = len(student_grades)
mean = mysum / length
print(mean)<file_sep>/section26_image-processing/face_detection/face_detector.py
import cv2
face_cascade=cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
img=cv2.imread("news.jpg")
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=face_cascade.detectMultiScale(gray_img,
scaleFactor=1.01,
minNeighbors=5)
for x, y, w, h in faces:
img=cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 3)
print(type(faces))
print(faces)
cv2.imshow("Gray",img)
cv2.waitKey(0)
cv2.destroyAllWindows()<file_sep>/basics2.py
def foo(temp):
if temp > 7:
return 'Hot'
else:
return 'Cold'
user_input = float(input("Enter some input:"))
feels = foo(user_input)
print(user_input, ' feels ', feels)<file_sep>/README.md
# udemy-big-10
Sandbox for self-directed learning based on Udemy course "Python: Big 10". My activities here will include:
* Watch lectures
* Do homework problems in "sections"
* Follow along step-by-step code design of applications in "projects"
* Tinker to modify functionality of the apps
* Make some templates for future ideas
<file_sep>/section21_problem/script1.py
from tkinter import *
window = Tk()
def convKg():
inp = float(e1_value.get())
g = inp*1000
lb = inp*2.20462
oz = inp*35.274
t1.delete("1.0",END)
t1.insert(END,g)
t2.delete("1.0",END)
t2.insert(END,lb)
t3.delete("1.0",END)
t3.insert(END,oz)
e0 = Label(window,text="Kg")
e0.grid(row=0,column=0)
e1_value=StringVar()
e1 = Entry(window,textvariable=e1_value)
e1.grid(row=0,column=1)
b1 = Button(window,text="Convert",command=convKg)
b1.grid(row=0,column=2)
t1 = Text(window,height=1,width=20)
t1.grid(row=1,column=0)
t2 = Text(window,height=1,width=20)
t2.grid(row=1,column=1)
t3 = Text(window,height=1,width=20)
t3.grid(row=1,column=2)
window.mainloop()<file_sep>/basic_greet.py
def sayHi(username):
#msg = "Hi %s" % username
msg = f"Hi {username}"
return msg
inp = str(input("Enter your username:"))
print(sayHi(inp))
<file_sep>/Project7_WebScraper/main.py
import requests
from bs4 import BeautifulSoup
import pandas
base_url="http://www.pyclass.com/real-estate/rock-springs-wy/LCWYROCKSPRINGS/"
r = requests.get(base_url, headers={'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'})
c = r.content
soup = BeautifulSoup(c, "html.parser")
pages = soup.find_all("a",{"class":"Page"})
last_page = pages[-1].text
l=[]
for page in range(0,int(last_page)*10,10):
r = requests.get(base_url+"t=0&s="+str(page)+".html", headers={'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'})
c = r.content
soup=BeautifulSoup(c,"html.parser")
all=soup.find_all("div",{"class":"propertyRow"})
for item in all:
d = {}
d["Price"]=item.find("h4",{"class":"propPrice"}).text.replace("\n","").replace(" ","")
d["Address_1"]=item.find_all("span",{"class":"propAddressCollapse"})[0].text
d["Address_2"]=item.find_all("span",{"class":"propAddressCollapse"})[1].text
try:
d["Beds"]=item.find("span",{"class":"infoBed"}).find("b").text
except:
d["Beds"]=None
try:
d["SqFt"]=item.find("span",{"class":"infoSqFt"}).find("b").text
except:
d["SqFt"]=None
try:
d["Bathrooms"]=item.find("span",{"class":"infoValueFullBath"}).find("b").text
except:
d["Bathrooms"]=None
try:
d["Half Bathrooms"]=item.find("span",{"class":"infoValueHalfBath"}).find("b").text
except:
d["Half Bathrooms"]=None
for colGroup in item.find_all("div", {"class":"columnGroup"}):
for featureGroup, featureName in zip(colGroup.find_all("span",{"class":"featureGroup"}),colGroup.find_all("span",{"class":"featureName"})):
if "Lot Size" in featureGroup.text:
d["Lot Size"]=featureName.text
l.append(d)
df = pandas.DataFrame(l)
df.to_csv("Output.csv")<file_sep>/Project3_PublishWebApp/README.txt
This project utilizes Python: Flask framework for website backend, and publishes using Heroku toolset and web hosting server.
HTML front end and CSS styling are employed.<file_sep>/section23_OOP/exercise/frontend.py
from tkinter import *
from backend import Database
class GUI:
def __init__(self, name, database):
self.name = name
self.database = database #created from imported class Database
self.window=Tk()
self.window.wm_title(self.name)
self.l1=Label(self.window,text="Title")
self.l1.grid(row=0,column=0)
self.l2=Label(self.window,text="Author")
self.l2.grid(row=0,column=2)
self.l3=Label(self.window,text="Year")
self.l3.grid(row=1,column=0)
self.l4=Label(self.window,text="ISBN")
self.l4.grid(row=1,column=2)
self.title_text=StringVar()
self.e1=Entry(self.window,textvariable=self.title_text)
self.e1.grid(row=0,column=1)
self.author_text=StringVar()
self.e2=Entry(self.window,textvariable=self.author_text)
self.e2.grid(row=0,column=3)
self.year_text=StringVar()
self.e3=Entry(self.window,textvariable=self.year_text)
self.e3.grid(row=1,column=1)
self.isbn_text=StringVar()
self.e4=Entry(self.window,textvariable=self.isbn_text)
self.e4.grid(row=1,column=3)
self.list1=Listbox(self.window, height=6,width=35)
self.list1.grid(row=2,column=0,rowspan=6,columnspan=2)
self.sb1=Scrollbar(self.window)
self.sb1.grid(row=2,column=2,rowspan=6)
self.list1.configure(yscrollcommand=self.sb1.set)
self.sb1.configure(command=self.list1.yview)
self.list1.bind('<<ListboxSelect>>',self.get_selected_row)
self.b1=Button(self.window,text="View all", width=12,command=self.view_command)
self.b1.grid(row=2,column=3)
self.b2=Button(self.window,text="Search entry", width=12,command=self.search_command)
self.b2.grid(row=3,column=3)
self.b3=Button(self.window,text="Add entry", width=12,command=self.add_command)
self.b3.grid(row=4,column=3)
self.b4=Button(self.window,text="Update selected", width=12,command=self.update_command)
self.b4.grid(row=5,column=3)
self.b5=Button(self.window,text="Delete selected", width=12,command=self.delete_command)
self.b5.grid(row=6,column=3)
self.b6=Button(self.window,text="Close", width=12,command=self.window.destroy)
self.b6.grid(row=7,column=3)
self.window.mainloop()
def get_selected_row(self, event):
global selected_tuple
index=self.list1.curselection()[0]
selected_tuple=self.list1.get(index)
self.e1.delete(0,END)
self.e1.insert(END,selected_tuple[1])
self.e2.delete(0,END)
self.e2.insert(END,selected_tuple[2])
self.e3.delete(0,END)
self.e3.insert(END,selected_tuple[3])
self.e4.delete(0,END)
self.e4.insert(END,selected_tuple[4])
def view_command(self):
self.list1.delete(0,END)
for row in self.database.view():
self.list1.insert(END,row)
def search_command(self):
self.list1.delete(0,END)
for row in self.database.search(self.title_text.get(),self.author_text.get(),self.year_text.get(),self.isbn_text.get()):
self.list1.insert(END,row)
def add_command(self):
self.database.insert(self.title_text.get(),self.author_text.get(),self.year_text.get(),self.isbn_text.get())
self.list1.delete(0,END)
self.list1.insert(END,(self.title_text.get(),self.author_text.get(),self.year_text.get(),self.isbn_text.get()))
def delete_command(self):
self.database.delete(selected_tuple[0])
def update_command(self):
self.database.update(selected_tuple[0],self.title_text.get(),self.author_text.get(),self.year_text.get(),self.isbn_text.get())
database=Database("books.db")
gui = GUI("bookstore", database)<file_sep>/section26_image-processing/script2.py
import cv2 as c
import glob
from pathlib import Path
file_list = glob.glob("images/*.jpg")
for file in file_list:
img=c.imread(file)
resized_image=c.resize(img,(100,100))
obj=Path(file)
c.imwrite(f"{obj.parent}\\{obj.stem}_resized.jpg",resized_image)
c.imshow("",resized_image)
c.waitKey(0)
c.destroyAllWindows()<file_sep>/Project2_GeocoderMap/README.txt
This app utilizes Python: Pandas, <mapStuff> frameworks to create multi-layer interactive map with database-sourced labels.<file_sep>/Project6_WebcamMotionDetector/motion_detector.py
import cv2, time
from datetime import datetime
import pandas
video=cv2.VideoCapture(0)
first_frame=None
status_list=[None, None]
times=[]
while True:
check, frame = video.read()
status=0
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
gray2=cv2.GaussianBlur(gray,(21,21),0)
if first_frame is None:
first_frame=gray2
continue
delta_frame=cv2.absdiff(first_frame,gray2)
thresh_delta=cv2.threshold(delta_frame,30, 255, cv2.THRESH_BINARY)[1]
thresh_frame=cv2.dilate(thresh_delta, None, iterations=2)
(cnts,_) = cv2.findContours(thresh_frame.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in cnts:
if cv2.contourArea(contour) < 10000:
continue
status=1
(x,y,w,h)=cv2.boundingRect(contour)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0,255,0), 3)
status_list.append(status)
if status_list[-1]==1 and status_list[-2]==0:
times.append(datetime.now())
if status_list[-1]==0 and status_list[-2]==1:
times.append(datetime.now())
# cv2.imshow("Color", frame)
cv2.imshow("Gray Frame",gray)
cv2.imshow("Delta Frame",delta_frame)
cv2.imshow("Threshold Frame",thresh_delta)
cv2.imshow("Color Frame", frame)
key = cv2.waitKey(1)
# print(gray)
# print(delta_frame)
if key==ord('q'):
if status == 1:
times.append(datetime.now())
break
write_using_pandas = True
if write_using_pandas == False:
# Save times data to .csv WITHOUT Pandas
f = open("times.csv", "w")
f.write("Enter, Exit\n")
for i in range(0,len(times),2):
f.write(str(times[i])+", "+str(times[i+1])+"\n")
f.close()
elif write_using_pandas == True:
# Save times data to .csv WITH Pandas
df = pandas.DataFrame(columns=["Enter", "Exit"])
for i in range(0,len(times),2):
df = df.append({"Enter": times[i],"Exit": times[i+1]}, ignore_index=True)
df.to_csv("times.csv")
# print(status_list,"\n")
# print(times,"\n")
# print(df,"\n")
video.release()
cv2.destroyAllWindows()
|
56b3a5d316bd02e176ec5a1a407ec304e27dc6e5
|
[
"Markdown",
"Python",
"Text"
] | 18 |
Python
|
gnudrew/udemy-big-10
|
6df8854f49e35ff5e83c469cb12dbcc30df89376
|
6a151f6b930333ee42bf93080ebee6de790944c6
|
refs/heads/master
|
<file_sep>package com.mycompany.app;
import lombok.Data;
import lombok.Builder;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
Test te = Test.builder().x(44).build();
System.out.println( te.getX());
}
}
@Builder
@Data
class Test
{
private int x;
}
|
8b8b42ba53d51725a0d0ded29a736fe0ab4c49bc
|
[
"Java"
] | 1 |
Java
|
mroczek-203951/Java
|
8fe2475fffb933b83e53b1ab31f8d117f2a0b4c0
|
c768fccd51b4d8055e42f47f3b14db197b9cba7f
|
refs/heads/master
|
<repo_name>tmarschall/spherocyls<file_sep>/src/cuda/dat_file_input.cpp
/*
* dat_file_input.cpp
*
*
* Created by <NAME> on 7/9/10.
* Copyright 2010 __MyCompanyName__. All rights reserved.
*
*/
#include "file_input.h"
#include <fstream>
#include <string>
#include <iostream>
#include <cstdlib> //for exit, atoi etc
using namespace std;
//constructors
DatFileInput::DatFileInput(const char* szFile)
{
m_szFileName = szFile;
m_bHeader = 0;
m_nHeadLen = 0;
m_strHeader = 0;
m_nColumns = datGetColumns();
m_nFileLength = datGetRows();
if (m_nFileLength * m_nColumns < 5000000)
m_nRows = m_nFileLength;
else
m_nRows = 5000000 / m_nColumns;
m_strArray = new string[m_nRows * m_nColumns];
m_nArrayLine1 = 0;
datFillArray();
}
DatFileInput::DatFileInput(const char* szFile, bool bHeader)
{
m_szFileName = szFile;
m_bHeader = bHeader;
if (bHeader) {
m_nHeadLen = datGetHeadLen();
m_strHeader = new string[m_nHeadLen];
datFillHeader();
}
else {
m_nHeadLen = 0;
m_strHeader = 0;
}
m_nColumns = datGetColumns();
m_nFileLength = datGetRows();
if (m_nFileLength * m_nColumns < 5000000)
m_nRows = m_nFileLength - static_cast<int>(m_bHeader);
else
m_nRows = 5000000 / m_nColumns;
m_strArray = new string[m_nRows * m_nColumns];
m_nArrayLine1 = 0;
datFillArray();
}
DatFileInput::DatFileInput(const char* szFile, int nRows, int nColumns)
{
m_szFileName = szFile;
m_bHeader = 0;
m_nColumns = nColumns;
m_nFileLength = nRows;
if (nRows * nColumns < 5000000)
m_nRows = nRows;
else
m_nRows = 5000000 / nColumns;
m_strArray = new string[m_nRows * m_nColumns];
m_nArrayLine1 = 0;
datFillArray();
}
DatFileInput::DatFileInput(const char* szFile, bool bHeader, int nRows, int nColumns)
{
m_szFileName = szFile;
m_bHeader = bHeader;
if (bHeader) {
m_nHeadLen = datGetHeadLen();
m_strHeader = new string[m_nHeadLen];
datFillHeader();
}
else {
m_nHeadLen = 0;
m_strHeader = 0;
}
m_nColumns = nColumns;
m_nFileLength = nRows + static_cast<int>(m_bHeader);
if (nRows * nColumns < 5000000)
m_nRows = nRows;
else
m_nRows = 5000000 / nColumns;
m_strArray = new string[m_nRows * m_nColumns];
m_nArrayLine1 = 0;
datFillArray();
//cout << "'" << szFile << "' Loaded Successfully" << endl;
}
//find the number of rows by reading the file
int DatFileInput::datGetRows()
{
ifstream inf(m_szFileName);
if (!inf)
{
cerr << "Could not load, check file name and directory" << endl;
exit(1);
}
int nRows = 0;
while (inf)
{
nRows += 1;
string strLine;
getline(inf, strLine);
}
//while loop returns an extra line with no data so we must subtract 1
return nRows - 1;
}
//find the number of columns by reading the file
//the number of columns will be based on the FIRST LINE OF THE FILE
int DatFileInput::datGetColumns()
{
ifstream inf(m_szFileName);
if (!inf)
{
cerr << "Could not load, check file name and directory" << endl;
exit(1);
}
string strLine;
getline(inf, strLine);
if (m_bHeader) {
getline(inf, strLine);
}
int nColumns = 1;
size_t spaceIndex = strLine.find_first_of(" ");
while (spaceIndex != string::npos)
{
nColumns += 1;
spaceIndex = strLine.find_first_of(" ", spaceIndex + 1);
}
return nColumns;
}
int DatFileInput::datGetHeadLen()
{
if (!m_bHeader)
return 0;
else {
ifstream inf(m_szFileName);
if (!inf)
{
cerr << "Could not load, check file name and directory" << endl;
exit(1);
}
string strLine;
getline(inf, strLine);
int nLen = 1;
size_t spaceIndex = strLine.find_first_of(" ");
while (spaceIndex != string::npos)
{
nLen += 1;
spaceIndex = strLine.find_first_of(" ", spaceIndex + 1);
}
inf.close();
return nLen;
}
}
void DatFileInput::datFillHeader()
{
ifstream inf(m_szFileName);
if (!inf)
{
cerr << "Could not load, check file name and directory" << endl;
exit(1);
}
string strLine;
getline(inf, strLine);
int nColId = 0;
size_t leftSpace = -1;
size_t rightSpace = strLine.find_first_of(" ");
m_strHeader[nColId] = strLine.substr(0, rightSpace);
for (nColId = 1; nColId < m_nHeadLen; nColId++)
{
if (rightSpace == string::npos)
m_strHeader[nColId] = "0";
else
{
leftSpace = rightSpace;
rightSpace = strLine.find_first_of(" ", leftSpace + 1);
m_strHeader[nColId] = strLine.substr(leftSpace + 1, rightSpace - leftSpace - 1);
}
}
inf.close();
}
//fill a 1D array with strings from the file
void DatFileInput::datFillArray()
{
ifstream inf(m_szFileName);
if (!inf)
{
cerr << "Could not load, check file name and directory" << endl;
exit(1);
}
for (int n = 0; n < m_nArrayLine1 + static_cast<int>(m_bHeader); n++)
{
string strLine;
getline(inf, strLine);
}
for (int nRowIndex = 0; nRowIndex < m_nRows; nRowIndex++)
{
if (m_nArrayLine1 + nRowIndex + static_cast<int>(m_bHeader) >= m_nFileLength)
break;
int nColIndex = 0;
string strLine;
getline(inf, strLine);
size_t leftSpace = -1;
size_t rightSpace = strLine.find_first_of(" ");
m_strArray[nRowIndex * m_nColumns + nColIndex] = strLine.substr(0, rightSpace);
for (nColIndex = 1; nColIndex < m_nColumns; nColIndex++)
{
if (rightSpace == string::npos)
m_strArray[nRowIndex * m_nColumns + nColIndex] = "0";
else
{
leftSpace = rightSpace;
rightSpace = strLine.find_first_of(" ", leftSpace + 1);
m_strArray[nRowIndex * m_nColumns + nColIndex] = strLine.substr(leftSpace + 1, rightSpace - leftSpace - 1);
}
}
}
inf.close();
}
void DatFileInput::datDisplayArray()
{
for (int nR = 0; nR < m_nRows; nR++)
{
for (int nC = 0; nC < m_nColumns; nC++)
{
cout << m_strArray[m_nColumns * nR + nC] << "\t";
}
cout << "\n";
}
}
void DatFileInput::getHeader(string strHead[])
{
for (int h = 0; h < m_nHeadLen; h++) {
strHead[h] = m_strHeader[h];
}
}
void DatFileInput::getColumn(int anColumn[], int nColumn)
{
int nR = 0;
while (nR < m_nFileLength - static_cast<int>(m_bHeader))
{
//cout << "Get column, row: " << nR << endl;
anColumn[nR] = getInt(nR, nColumn);
nR++;
}
}
//get column as long
void DatFileInput::getColumn(long alColumn[], int nColumn)
{
int nR = 0;
while (nR < m_nFileLength - static_cast<int>(m_bHeader))
{
alColumn[nR] = getLong(nR, nColumn);
nR++;
}
}
//get column as double, float
void DatFileInput::getColumn(double adColumn[], int nColumn)
{
int nR = 0;
while (nR < m_nFileLength - static_cast<int>(m_bHeader))
{
adColumn[nR] = getFloat(nR, nColumn);
nR++;
}
}
//get column as string
void DatFileInput::getColumn(string astrColumn[], int nColumn)
{
int nR = 0;
while (nR < m_nFileLength - static_cast<int>(m_bHeader))
{
astrColumn[nR] = getString(nR, nColumn);
nR++;
}
}
void DatFileInput::getRow(int anRow[], int nRow)
{
for (int nC = 0; nC < m_nColumns; nC++) {
anRow[nC] = getInt(nRow, nC);
}
}
void DatFileInput::getRow(long alRow[], int nRow)
{
for (int nC = 0; nC < m_nColumns; nC++) {
alRow[nC] = getLong(nRow, nC);
}
}
void DatFileInput::getRow(double adRow[], int nRow)
{
for (int nC = 0; nC < m_nColumns; nC++) {
adRow[nC] = getFloat(nRow, nC);
}
}
void DatFileInput::getRow(string astrRow[], int nRow)
{
for (int nC = 0; nC < m_nColumns; nC++) {
astrRow[nC] = getString(nRow, nC);
}
}
int DatFileInput::getInt(int nRow, int nColumn)
{
int nARow = nRow - m_nArrayLine1;
if (nARow < 0 || nARow >= m_nRows)
{
m_nArrayLine1 = nRow;
datFillArray();
nARow = 0;
//cout << "Getting row: " << nRow << endl;
}
return atoi(m_strArray[nARow * m_nColumns + nColumn].c_str());
}
long DatFileInput::getLong(int nRow, int nColumn)
{
int nARow = nRow - m_nArrayLine1;
if (nARow < 0 || nARow >= m_nRows)
{
m_nArrayLine1 = nRow;
datFillArray();
nARow = 0;
}
return atol(m_strArray[nARow * m_nColumns + nColumn].c_str());
}
double DatFileInput::getFloat(int nRow, int nColumn)
{
int nARow = nRow - m_nArrayLine1;
if (nARow < 0 || nARow >= m_nRows)
{
m_nArrayLine1 = nRow;
datFillArray();
nARow = 0;
//cout << "Getting row: " << nRow << endl;
}
return atof(m_strArray[nARow * m_nColumns + nColumn].c_str());
}
string DatFileInput::getString(int nRow, int nColumn)
{
int nARow = nRow - m_nArrayLine1;
if (nARow < 0 || nARow >= m_nRows)
{
m_nArrayLine1 = nRow;
datFillArray();
nARow = 0;
}
return m_strArray[nARow * m_nColumns + nColumn];
}
int DatFileInput::getHeadInt(int nCol)
{
return atoi(m_strHeader[nCol].c_str());
}
long DatFileInput::getHeadLong(int nCol)
{
return atol(m_strHeader[nCol].c_str());
}
double DatFileInput::getHeadFloat(int nCol)
{
return atof(m_strHeader[nCol].c_str());
}
string DatFileInput::getHeadString(int nCol)
{
return m_strHeader[nCol].c_str();
}
<file_sep>/src/cuda/data_primitives_2.cu
// -*- c++ -*-
/*
* data_primitives.cu
*
* kernels for primitive data operations used in several functions
*
*
*/
#include "data_primitives.h"
#include <cuda.h>
#include <sm_20_atomic_functions.h>
#include "cudaErr.h"
#include <stdio.h>
__global__ void block_scan(int nLength, int nBlockSize, int *pnIn, int *pnOut, int nBlocks, int *pnSums)
{
extern __shared__ int sMem[];
int thid = threadIdx.x;
int blid = blockIdx.x;
while (blid < nBlocks)
{
int offset = 1;
int globalId = thid + blid * nBlockSize;
int sharedId = thid + thid / 32;
if (globalId < nLength)
{
sMem[sharedId] = pnIn[globalId];
globalId += nBlockSize / 2;
sharedId = thid + nBlockSize / 2;
sharedId += sharedId / 32;
if (globalId < nLength)
sMem[sharedId] = pnIn[globalId];
else
sMem[sharedId] = 0;
}
else
{
sMem[sharedId] = 0;
sharedId = thid + nBlockSize / 2;
sharedId += sharedId / 32;
sMem[sharedId] = 0;
}
for (int d = nBlockSize / 2; d > 0; d /= 2)
{
__syncthreads();
if (thid < d)
{
int ai = offset*(2*thid + 1) - 1;
int bi = offset*(2*thid + 2) - 1;
ai += ai / 32;
bi += bi / 32;
sMem[bi] += sMem[ai];
}
offset *= 2;
}
__syncthreads();
int nSID = thid + blid + 1;
int nLastID = nBlockSize - 1;
nLastID += nLastID / 32;
if (nSID < nBlocks)
int nPartSum = atomicAdd(pnSums+nSID, sMem[nLastID]);
__syncthreads();
if (thid == 0)
sMem[nLastID] = 0;
for (int d = 1; d < nBlockSize; d *= 2)
{
offset /= 2;
__syncthreads();
if (thid < d)
{
int ai = offset*(2*thid + 1) - 1;
int bi = offset*(2*thid + 2) - 1;
ai += ai / 32;
bi += bi / 32;
int temp = sMem[ai];
sMem[ai] = sMem[bi];
sMem[bi] += temp;
}
}
__syncthreads();
globalId = blid * nBlockSize + thid;
sharedId = thid + thid / 32;
pnOut[globalId] = sMem[sharedId];
sharedId = thid + nBlockSize / 2;
sharedId += sharedId / 32;
pnOut[globalId + nBlockSize / 2] = sMem[sharedId];
blid += gridDim.x;
}
}
__global__ void finish_scan(int nLength, int nBlockSize, int *pnOut, int nBlocks, int *pnSums)
{
int blid = blockIdx.x;
while (blid < nBlocks)
{
int globalId = threadIdx.x + blid * nBlockSize;
if (globalId < nLength)
{
pnOut[globalId] += pnSums[blid];
globalId += nBlockSize / 2;
if (globalId < nLength)
pnOut[globalId] += pnSums[blid];
}
blid += gridDim.x;
}
}
void exclusive_scan(int *d_pnIn, int *d_pnOut, int nSize)
{
int nBlockSize = 512;
int nBlocks = nSize / nBlockSize + ((nSize % nBlockSize != 0) ? 1 : 0);
int *d_pnSums;
cudaMalloc((void **) &d_pnSums, sizeof(int) * nBlocks);
cudaMemset((void *) d_pnSums, 0, sizeof(int) * nBlocks);
int nGridDim = ((nBlocks <= 16) ? nBlocks : 16);
int nBlockDim = nBlockSize / 2;
int sMemSize = (nBlockSize + nBlockSize / 32) * sizeof(int);
//printf("Scanning %d x %d with %d bytes smem\n", nGridDim, nBlockDim, sMemSize);
block_scan <<<nGridDim, nBlockDim, sMemSize>>> (nSize, nBlockSize, d_pnIn, d_pnOut, nBlocks, d_pnSums);
cudaThreadSynchronize();
checkCudaError("Performing exclusive scan on blocks");
if (nBlocks > 1)
{
//int *h_pnSums = (int*) malloc(sizeof(int) * nBlocks);
finish_scan <<<nGridDim, nBlockDim>>> (nSize, nBlockSize, d_pnOut, nBlocks, d_pnSums);
cudaThreadSynchronize();
checkCudaError("Adding block sums to block scans");
//cudaMemcpy(h_pnSums, d_pnSums, sizeof(int) * nBlocks)
}
cudaFree(d_pnSums);
}
__global__ void ordered_arr(int *pnArr, int nSize)
{
int thid = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
while (thid < nSize)
{
pnArr[thid] = thid;
thid += nThreads;
}
}
void ordered_array(int *pnArray, int nSize, int gridSize, int blockSize)
{
int nBlockSize;
int nGridSize;
if (gridSize == 0 || blockSize == 0)
{
if (nSize > 16 * 128)
nBlockSize = 256;
else
nBlockSize = 128;
nGridSize = nSize / nBlockSize + ((nSize % nBlockSize != 0) ? 1 : 0);
}
else
{
nGridSize = gridSize;
nBlockSize = blockSize;
}
ordered_arr <<<nGridSize, nBlockSize>>> (pnArray, nSize);
cudaThreadSynchronize();
checkCudaError("Creating ordered array");
}
<file_sep>/src/cuda/energy_minimize.cu
// -*- c++ -*-
/*
* strain_dynamics.cu
*
*
*/
#include <cuda.h>
#include "spherocyl_box.h"
#include "cudaErr.h"
#include <math.h>
#include <sm_20_atomic_functions.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
using namespace std;
const double D_PI = 3.14159265358979;
///////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
// Energy Minimization //
///////////////////////////
template<Potential ePot>
__global__ void calc_fe(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy, double dGamma,
double *pdX, double *pdY, double *pdPhi, double *pdR, double *pdA, double *pdMOI,
double *pdFx, double *pdFy, double *pdFt, float *pfEnergy, double *pdEnergyBlocks)
{
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
extern __shared__ double sData[];
sData[thid] = 0.0;
__syncthreads(); // synchronizes every thread in the block before going on
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dFt = 0.0;
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dAdjX = pdX[nAdjPID];
double dAdjY = pdY[nAdjPID];
double dDeltaX = dX - dAdjX;
double dDeltaY = dY - dAdjY;
double dPhiB = pdPhi[nAdjPID];
//if (dPhi == dPhiB) {
//printf("Spherocyls %d, %d parallel\n", nPID, nAdjPID);
//}
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double s,t;
if (delta <= 5e-14) {
double s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
double s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
if (s1 == s2) {
s = s1;
t = fmin(fmax( -(s*b+e)/c, -1.0), 1.0);
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx * dDVij / dDij;
double dPfy = dDy * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
dFt += s*nxA * dPfy - s*nyA * dPfx;
sData[thid] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
else {
double t1,t2;
if (b < 0) {
t1 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
t2 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
}
else {
t1 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
t2 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
}
double dDx1 = dDeltaX + s1*nxA - t1*nxB;
double dDy1 = dDeltaY + s1*nyA - t1*nyB;
double dDSqr1 = dDx1 * dDx1 + dDy1 * dDy1;
if (dDSqr1 < dSigma*dSigma)
{
double dDij = sqrt(dDSqr1);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = 0.5*(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = 0.5*(1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx1 * dDVij / dDij;
double dPfy = dDy1 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
dFt += s1*nxA * dPfy - s1*nyA * dPfx;
sData[thid] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
double dDx2 = dDeltaX + s2*nxA - t2*nxB;
double dDy2 = dDeltaY + s2*nyA - t2*nyB;
double dDSqr2 = dDx2 * dDx2 + dDy2 * dDy2;
if (dDSqr2 < dSigma*dSigma)
{
double dDij = sqrt(dDSqr2);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = 0.5*(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = 0.5*(1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx2 * dDVij / dDij;
double dPfy = dDy2 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
dFt += s2*nxA * dPfy - s2*nyA * dPfx;
sData[thid] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
else {
t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx * dDVij / dDij;
double dPfy = dDy * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
// Find the point of contact (with respect to the center of the spherocyl)
//double dCx = s*nxA - 0.5*dDx;
//double dCy = s*nyA - 0.5*dDy;
//double dCx = s*nxA;
//double dCy = s*nyA;
dFt += s*nxA * dPfy - s*nyA * dPfx;
sData[thid] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
pdFx[nPID] = dFx;
pdFy[nPID] = dFy;
pdFt[nPID] = dFt;
nPID += nThreads;
}
__syncthreads();
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size, all threads perform two adds
int base = thid;
while (stride > 32)
{
if (thid < stride)
{
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 32) {
sData[base] += sData[base + 32];
if (thid < 16) {
sData[base] += sData[base + 16];
if (thid < 8) {
sData[base] += sData[base + 8];
if (thid < 4) {
sData[base] += sData[base + 4];
if (thid < 2) {
sData[base] += sData[base + 2];
if (thid == 0) {
sData[0] += sData[1];
pdEnergyBlocks[blockIdx.x] = sData[0];
float tot = atomicAdd(pfEnergy, (float)sData[0]);
}
}
}
}
}
}
}
template<Potential ePot>
__global__ void calc_energy(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy, double dGamma,
double *pdX, double *pdY, double *pdPhi, double *pdR, double *pdA, float *pfEnergy,
double *pdEnergyBlocks)
{
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
extern __shared__ double sData[];
sData[thid] = 0.0;
__syncthreads(); // synchronizes every thread in the block before going on
while (nPID < nSpherocyls)
{
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dAdjX = pdX[nAdjPID];
double dAdjY = pdY[nAdjPID];
double dDeltaX = dX - dAdjX;
double dDeltaY = dY - dAdjY;
double dPhiB = pdPhi[nAdjPID];
//if (dPhi == dPhiB) {
//printf("Spherocyls %d, %d parallel\n", nPID, nAdjPID);
//}
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double s,t;
if (delta <= 5e-14) {
double s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
double s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
if (s1 == s2) {
s = s1;
t = fmin(fmax( -(s*b+e)/c, -1.0), 1.0);
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
sData[thid] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
else {
double t1,t2;
if (b < 0) {
t1 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
t2 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
}
else {
t1 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
t2 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
}
double dDx1 = dDeltaX + s1*nxA - t1*nxB;
double dDy1 = dDeltaY + s1*nyA - t1*nyB;
double dDSqr1 = dDx1 * dDx1 + dDy1 * dDy1;
if (dDSqr1 < dSigma*dSigma)
{
double dDij = sqrt(dDSqr1);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = 0.5*(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = 0.5*(1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
sData[thid] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
double dDx2 = dDeltaX + s2*nxA - t2*nxB;
double dDy2 = dDeltaY + s2*nyA - t2*nyB;
double dDSqr2 = dDx2 * dDx2 + dDy2 * dDy2;
if (dDSqr2 < dSigma*dSigma)
{
double dDij = sqrt(dDSqr2);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = 0.5*(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = 0.5*(1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
sData[thid] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
else {
t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
sData[thid] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
nPID += nThreads;
}
__syncthreads();
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size
int base = thid;
while (stride > 32)
{
if (thid < stride)
{
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 32) {
sData[base] += sData[base + 32];
if (thid < 16) {
sData[base] += sData[base + 16];
if (thid < 8) {
sData[base] += sData[base + 8];
if (thid < 4) {
sData[base] += sData[base + 4];
if (thid < 2) {
sData[base] += sData[base + 2];
if (thid == 0) {
sData[0] += sData[1];
pdEnergyBlocks[blockIdx.x] = sData[0];
float tot = atomicAdd(pfEnergy, (float)sData[0]);
}
}
}
}
}
}
}
template<Potential ePot>
__global__ void calc_ftsq(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy, double dGamma,
double *pdX, double *pdY, double *pdPhi, double *pdR, double *pdA, float *pfFtSq,
double *pdBlockSums)
{
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
extern __shared__ double sData[];
sData[thid] = 0.0;
__syncthreads(); // synchronizes every thread in the block before going on
while (nPID < nSpherocyls)
{
//double dFx = 0;
//double dFy = 0;
double dFt = 0;
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dAdjX = pdX[nAdjPID];
double dAdjY = pdY[nAdjPID];
double dDeltaX = dX - dAdjX;
double dDeltaY = dY - dAdjY;
double dPhiB = pdPhi[nAdjPID];
//if (dPhi == dPhiB) {
//printf("Spherocyls %d, %d parallel\n", nPID, nAdjPID);
//}
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double s, t;
if (dA == 0) {
s = 0;
if (dB == 0) {
t = 0;
}
else {
double c = dB*dB;
double e = nxB * dDeltaX + nyB * dDeltaY;
t = fmin(fmax(e/c, -1), 1);
}
}
else {
if (dB == 0) {
t = 0;
double a = dA*dA;
double d = nxA * dDeltaX + nyA * dDeltaY;
s = fmin(fmax(-d/a, -1), 1);
}
else {
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
if (delta <= 0) {
double s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
double s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
s = (s1 + s2) / 2;
t = fmin(fmax( -(b*s+e)/c, -1.0), 1.0);
}
else {
t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
}
}
}
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx * dDVij / dDij;
double dPfy = dDy * dDVij / dDij;
//dFx += dPfx;
//dFy += dPfy;
dFt += s*nxA * dPfy - s*nyA * dPfx;
}
}
sData[thid] += dFt*dFt / nSpherocyls;
nPID += nThreads;
}
__syncthreads();
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size
int base = thid;
while (stride > 32)
{
if (thid < stride)
{
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 32) {
sData[base] += sData[base + 32];
if (thid < 16) {
sData[base] += sData[base + 16];
if (thid < 8) {
sData[base] += sData[base + 8];
if (thid < 4) {
sData[base] += sData[base + 4];
if (thid < 2) {
sData[base] += sData[base + 2];
if (thid == 0) {
sData[0] += sData[1];
pdBlockSums[blockIdx.x] = sData[0];
float tot = atomicAdd(pfFtSq, (float)sData[0]);
}
}
}
}
}
}
}
__global__ void square_forces(int nDim, double *pdFx, double *pdFy, double *pdFt, double *pdMOI, float *pfSquare)
{
int thid = threadIdx.x;
int blid = blockIdx.x;
int nThreads = blockDim.x * gridDim.x / 3;
int arrid = thid + (blid/3) * blockDim.x;
extern __shared__ double sData[];
sData[thid] = 0;
double val;
while (arrid < nDim) {
if (blid % 3 == 0)
val = pdFx[arrid];
else if (blid % 3 == 1)
val = pdFy[arrid];
else
val = pdFt[arrid];
//val = pdFt[arrid] / pdMOI[arrid];
sData[thid] += val*val;
arrid += nThreads;
}
__syncthreads();
int stride = blockDim.x / 2;
while (stride > 32) {
if (thid < stride) {
sData[thid] += sData[thid + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 32) {
sData[thid] += sData[thid + 32];
if (thid < 16) {
sData[thid] += sData[thid + 16];
if (thid < 8) {
sData[thid] += sData[thid + 8];
if (thid < 4) {
sData[thid] += sData[thid + 4];
if (thid < 2) {
sData[thid] += sData[thid + 2];
if (thid == 0) {
sData[0] += sData[1];
float tot = atomicAdd(pfSquare, (float)sData[0]);
}
}
}
}
}
}
}
__global__ void dbl_square_forces(int nDim, double *pdFx, double *pdFy, double *pdFt, double *pdMOI, double *pdBlockSums)
{
int thid = threadIdx.x;
int blid = blockIdx.x;
int nThreads = blockDim.x * gridDim.x / 3;
int arrid = thid + (blid/3) * blockDim.x;
extern __shared__ double sData[];
sData[thid] = 0;
double val;
while (arrid < nDim) {
if (blid % 3 == 0)
val = pdFx[arrid];
else if (blid % 3 == 1)
val = pdFy[arrid];
else
val = pdFt[arrid];
//val = pdFt[arrid] / pdMOI[arrid];
sData[thid] += val*val;
arrid += nThreads;
}
__syncthreads();
int stride = blockDim.x / 2;
while (stride > 32) {
if (thid < stride) {
sData[thid] += sData[thid + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 32) {
sData[thid] += sData[thid + 32];
if (thid < 16) {
sData[thid] += sData[thid + 16];
if (thid < 8) {
sData[thid] += sData[thid + 8];
if (thid < 4) {
sData[thid] += sData[thid + 4];
if (thid < 2) {
sData[thid] += sData[thid + 2];
if (thid == 0) {
sData[0] += sData[1];
pdBlockSums[blid] = sData[0];
}
}
}
}
}
}
}
__global__ void mult_forces(int nDim, double *pdFx0, double *pdFy0, double *pdFt0, double *pdFx,
double *pdFy, double *pdFt, double *pdMOI, float *pfFF0)
{
int thid = threadIdx.x;
int blid = blockIdx.x;
int nThreads = blockDim.x * gridDim.x / 3;
int arrid = thid + (blid/3) * blockDim.x;
extern __shared__ double sData[];
sData[thid] = 0;
while (arrid < nDim) {
if (blid % 3 == 0)
sData[thid] += pdFx0[arrid] * pdFx[arrid];
else if (blid % 3 == 1)
sData[thid] += pdFy0[arrid] * pdFy[arrid];
else
sData[thid] += pdFt0[arrid] * pdFt[arrid];
arrid += nThreads;
}
__syncthreads();
int stride = blockDim.x / 2;
while (stride > 32) {
if (thid < stride) {
sData[thid] += sData[thid + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 32) {
sData[thid] += sData[thid + 32];
if (thid < 16) {
sData[thid] += sData[thid + 16];
if (thid < 8) {
sData[thid] += sData[thid + 8];
if (thid < 4) {
sData[thid] += sData[thid + 4];
if (thid < 2) {
sData[thid] += sData[thid + 2];
if (thid == 0) {
sData[0] += sData[1];
float tot = atomicAdd(pfFF0, (float)sData[0]);
}
}
}
}
}
}
}
__global__ void new_pr_conj_dir(int nSpherocyls, double *pdFx, double *pdFy, double *pdFt,
double *pdMOI, double *pdDx, double *pdDy, double *pdDt,
float *pfF0Sq, float *pfFSq, float *pfFF0, double dAngleDamping)
{
int thid = threadIdx.x;
int nThreads = blockDim.x * gridDim.x / 3;
//int nThreads = blockDim.x * gridDim.x / 2;
int nPID = thid + (blockIdx.x / 3) * blockDim.x;
//int nPID = thid + (blockIdx.x / 2) * blockDim.x;
float fBeta = (*pfFSq - *pfFF0) / (*pfF0Sq);
if (blockIdx.x % 3 == 0) {
//if (blockIdx.x % 2 == 0) {
while (nPID < nSpherocyls) {
double dNewDx = pdFx[nPID] + fBeta * pdDx[nPID];
pdDx[nPID] = dNewDx;
nPID += nThreads;
}
}
else if (blockIdx.x % 3 == 1) {
//else {
while (nPID < nSpherocyls) {
double dNewDy = pdFy[nPID] + fBeta * pdDy[nPID];
pdDy[nPID] = dNewDy;
nPID += nThreads;
}
}
else {
while (nPID < nSpherocyls) {
double dNewDt = pdFt[nPID] + fBeta * pdDt[nPID];
//double dNewDt = pdFt[nPID] + fBeta * pdDt[nPID];
pdDt[nPID] = dAngleDamping*dNewDt;
nPID += nThreads;
}
}
}
__global__ void new_fr_conj_dir(int nSpherocyls, double *pdFx, double *pdFy, double *pdFt, double *pdMOI,
double *pdDx, double *pdDy, double *pdDt, float *pfF0Sq, float *pfFSq)
{
int thid = threadIdx.x;
int nThreads = blockDim.x * gridDim.x / 3;
//int nThreads = blockDim.x * gridDim.x / 2;
int nPID = thid + (blockIdx.x / 3) * blockDim.x;
//int nPID = thid + (blockIdx.x / 2) * blockDim.x;
float fBeta = (*pfFSq) / (*pfF0Sq);
if (blockIdx.x % 3 == 0) {
//if (blockIdx.x % 2 == 0) {
while (nPID < nSpherocyls) {
double dNewDx = pdFx[nPID] + fBeta * pdDx[nPID];
pdDx[nPID] = dNewDx;
nPID += nThreads;
}
}
else if (blockIdx.x % 3 == 1) {
//else {
while (nPID < nSpherocyls) {
double dNewDy = pdFy[nPID] + fBeta * pdDy[nPID];
pdDy[nPID] = dNewDy;
nPID += nThreads;
}
}
else {
while (nPID < nSpherocyls) {
double dNewDt = pdFt[nPID] + fBeta * pdDt[nPID];
//double dNewDt = pdFt[nPID] + fBeta * pdDt[nPID];
pdDt[nPID] = dNewDt;
nPID += nThreads;
}
}
}
__global__ void temp_move_step(int nSpherocyls, double *pdX, double *pdY, double *pdPhi,
double *pdTempX, double *pdTempY, double *pdTempPhi,
double *pdDx, double *pdDy, double *pdDt, double dStep)
{
int thid = threadIdx.x;
int blid = blockIdx.x;
int nPID = thid + (blid / 3) * blockDim.x;
//int nPID = thid + (blid / 2) * blockDim.x;
int nThreads = blockDim.x * gridDim.x / 3;
//int nThreads = blockDim.x * gridDim.x / 2;
//printf("t: %d, b: %d, p: %d\n", thid, blid, nPID);
if (blid % 3 == 0) {
//if (blid % 2 == 0) {
while (nPID < nSpherocyls) {
pdTempX[nPID] = pdX[nPID] + dStep * pdDx[nPID];
nPID += nThreads;
}
}
else if (blid % 3 == 1) {
//else {
while (nPID < nSpherocyls) {
pdTempY[nPID] = pdY[nPID] + dStep * pdDy[nPID];
nPID += nThreads;
}
}
else {
while (nPID < nSpherocyls) {
pdTempPhi[nPID] = pdPhi[nPID] + dStep * pdDt[nPID];
nPID += nThreads;
}
}
}
__global__ void move_step(int nSpherocyls, double *pdX, double *pdY, double *pdPhi,
double *pdDx, double *pdDy, double *pdDt, double dStep)
{
int thid = threadIdx.x;
int blid = blockIdx.x;
int nPID = thid + (blid / 3) * blockDim.x;
//int nPID = thid + (blid / 2) * blockDim.x;
int nThreads = blockDim.x * gridDim.x / 3;
//int nThreads = blockDim.x * gridDim.x / 2;
if (blid % 3 == 0) {
//if (blid % 2 == 0) {
while (nPID < nSpherocyls) {
pdX[nPID] = pdX[nPID] + dStep * pdDx[nPID];
nPID += nThreads;
}
}
else if (blid % 3 == 1) {
//else {
while (nPID < nSpherocyls) {
pdY[nPID] = pdY[nPID] + dStep * pdDy[nPID];
nPID += nThreads;
}
}
else {
while (nPID < nSpherocyls) {
pdPhi[nPID] = pdPhi[nPID] + dStep * pdDt[nPID];
nPID += nThreads;
}
}
}
int Spherocyl_Box::line_search(bool bFirstStep, bool bSecondStep, double dMinStep, double dMaxStep)
{
bool bFindMin = true;
bool bMinStep = false;
if (bFirstStep) {
cudaMemset((void*) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
//temp_move_step <<<2*m_nGridSize, m_nBlockSize>>>
temp_move_step <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdTempX, d_pdTempY, d_pdTempPhi,
d_pdDx, d_pdDy, d_pdDt, m_dStep);
cudaDeviceSynchronize();
checkCudaError("Moving Step 1");
calc_energy <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdR, d_pdA, d_pfSE+4, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, sizeof(double)*m_nGridSize, cudaMemcpyDeviceToHost);
//cudaMemcpy(h_pfSE+1, d_pfSE+1, sizeof(float), cudaMemcpyDeviceToHost);
h_pdLineEnergy[1] = 0;
cudaDeviceSynchronize();
for(int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[1] += h_pdBlockSums[j];
}
//printf("Step Energy: %.10g\n", dEnergy);
if (h_pdLineEnergy[1] > h_pdLineEnergy[0]) {
//printf("First step %g, line energies: %.10g %.10g\n", m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1]);
if (m_dStep > dMinStep) {
m_dStep /= 2;
h_pdLineEnergy[2] = h_pdLineEnergy[1];
h_pdLineEnergy[1] = 0;
//cudaMemcpyAsync(d_pfSE+1, h_pfSE+1, 2*sizeof(float), cudaMemcpyHostToDevice);
int ret = line_search(1,0, dMinStep, dMaxStep);
if (ret == 1) {
return 1;
}
else if (ret == 2) {
return 2;
}
bFindMin = false;
}
else {
bMinStep = true;
}
}
}
if (bSecondStep) {
cudaMemset((void*) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
//temp_move_step <<<2*m_nGridSize, m_nBlockSize>>>
temp_move_step <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdTempX, d_pdTempY, d_pdTempPhi,
d_pdDx, d_pdDy, d_pdDt, 2*m_dStep);
cudaDeviceSynchronize();
checkCudaError("Moving Step 1");
calc_energy <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdR, d_pdA, d_pfSE+4, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, sizeof(double)*m_nGridSize, cudaMemcpyDeviceToHost);
//cudaMemcpy(h_pfSE+2, d_pfSE+2, sizeof(float), cudaMemcpyDeviceToHost);
h_pdLineEnergy[2] = 0;
cudaDeviceSynchronize();
for(int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[2] += h_pdBlockSums[j];
}
//printf("Step Energy: %.10g\n", dEnergy);
if (h_pdLineEnergy[2] <= h_pdLineEnergy[1]) {
//printf("Second step %g , line energies: %.10g %.10g %.10g\n", m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2]);
if (m_dStep < dMaxStep) {
m_dStep *= 2;
h_pdLineEnergy[1] = h_pdLineEnergy[2];
h_pdLineEnergy[2] = 0;
//cudaMemcpyAsync(d_pfSE+1, h_pfSE+1, 2*sizeof(float), cudaMemcpyHostToDevice);
int ret = line_search(0,1, dMinStep, dMaxStep);
if (ret == 1) {
return 1;
}
else if (ret == 2) {
return 2;
}
bFindMin = false;
}
}
}
if (bFindMin) {
if (h_pdLineEnergy[1] > h_pdLineEnergy[0]) {
printf("Line search result, step %g, line energies %.10g %.10g %.10g\n",
m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2]);
printf("Cannot find lower energy\n");
return 1;
}
else {
double dLineMin = (3*h_pdLineEnergy[0] - 4*h_pdLineEnergy[1] + h_pdLineEnergy[2])/(2*h_pdLineEnergy[0] - 4*h_pdLineEnergy[1] + 2*h_pdLineEnergy[2]);
if (dLineMin > 2) {
dLineMin = 2;
}
else if (h_pdLineEnergy[1] == h_pdLineEnergy[0]) {
dLineMin = 1;
}
printf("Line search result, step %g, line energies %.12g %.12g %.12g, line min %g\n",
m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2], dLineMin);
move_step <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdDx, d_pdDy, d_pdDt, dLineMin*m_dStep);
cudaDeviceSynchronize();
checkCudaError("Moving Spherocyls");
}
}
if (bMinStep)
return 2;
return 0;
}
int Spherocyl_Box::force_line_search(bool bFirstStep, bool bSecondStep, double dMinStep, double dMaxStep)
{
bool bFindMin = true;
bool bMinStep = false;
if (bFirstStep) {
cudaMemset((void*) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
//temp_move_step <<<2*m_nGridSize, m_nBlockSize>>>
temp_move_step <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdTempX, d_pdTempY, d_pdTempPhi,
d_pdDx, d_pdDy, d_pdDt, m_dStep);
cudaDeviceSynchronize();
checkCudaError("Moving Step 1");
calc_fe <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdTempX, d_pdTempY, d_pdTempPhi,
d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pfSE+4, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating energy");
dbl_square_forces <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Summing forces");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, sizeof(double)*m_nGridSize, cudaMemcpyDeviceToHost);
//cudaMemcpy(h_pfSE+1, d_pfSE+1, sizeof(float), cudaMemcpyDeviceToHost);
h_pdLineEnergy[1] = 0;
cudaDeviceSynchronize();
for(int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[1] += h_pdBlockSums[j];
}
//printf("Step Energy: %.10g\n", dEnergy);
if (h_pdLineEnergy[1] > h_pdLineEnergy[0]) {
//printf("First step %g, line energies: %.10g %.10g\n", m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1]);
if (m_dStep > dMinStep) {
m_dStep /= 2;
h_pdLineEnergy[2] = h_pdLineEnergy[1];
h_pdLineEnergy[1] = 0;
//cudaMemcpyAsync(d_pfSE+1, h_pfSE+1, 2*sizeof(float), cudaMemcpyHostToDevice);
int ret = line_search(1,0, dMinStep, dMaxStep);
if (ret == 1) {
return 1;
}
else if (ret == 2) {
return 2;
}
bFindMin = false;
}
else {
bMinStep = true;
}
}
}
if (bSecondStep) {
cudaMemset((void*) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
//temp_move_step <<<2*m_nGridSize, m_nBlockSize>>>
temp_move_step <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdTempX, d_pdTempY, d_pdTempPhi,
d_pdDx, d_pdDy, d_pdDt, 2*m_dStep);
cudaDeviceSynchronize();
checkCudaError("Moving Step 1");
calc_fe <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdTempX, d_pdTempY, d_pdTempPhi,
d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pfSE+4, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating energy");
dbl_square_forces <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Summing forces");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, sizeof(double)*m_nGridSize, cudaMemcpyDeviceToHost);
//cudaMemcpy(h_pfSE+2, d_pfSE+2, sizeof(float), cudaMemcpyDeviceToHost);
h_pdLineEnergy[2] = 0;
cudaDeviceSynchronize();
for(int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[2] += h_pdBlockSums[j];
}
//printf("Step Energy: %.10g\n", dEnergy);
if (h_pdLineEnergy[2] <= h_pdLineEnergy[1]) {
//printf("Second step %g , line energies: %.10g %.10g %.10g\n", m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2]);
if (m_dStep < dMaxStep) {
m_dStep *= 2;
h_pdLineEnergy[1] = h_pdLineEnergy[2];
h_pdLineEnergy[2] = 0;
//cudaMemcpyAsync(d_pfSE+1, h_pfSE+1, 2*sizeof(float), cudaMemcpyHostToDevice);
int ret = line_search(0,1, dMinStep, dMaxStep);
if (ret == 1) {
return 1;
}
else if (ret == 2) {
return 2;
}
bFindMin = false;
}
}
}
if (bFindMin) {
if (h_pdLineEnergy[1] > h_pdLineEnergy[0]) {
printf("Line search result, step %g, line energies %.10g %.10g %.10g\n",
m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2]);
printf("Cannot find lower energy\n");
return 1;
}
else {
double dLineMin = (3*h_pdLineEnergy[0] - 4*h_pdLineEnergy[1] + h_pdLineEnergy[2])/(2*h_pdLineEnergy[0] - 4*h_pdLineEnergy[1] + 2*h_pdLineEnergy[2]);
if (dLineMin > 2) {
dLineMin = 2;
}
else if (h_pdLineEnergy[1] == h_pdLineEnergy[0]) {
dLineMin = 1;
}
//printf("Line search result, step %g, line energies %.12g %.12g %.12g, line min %g\n",
// m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2], dLineMin);
move_step <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdDx, d_pdDy, d_pdDt, dLineMin*m_dStep);
cudaDeviceSynchronize();
checkCudaError("Moving Spherocyls");
}
}
if (bMinStep)
return 2;
return 0;
}
int Spherocyl_Box::cjpr_relax_step(double dMinStep, double dMaxStep, double dAngleDamping)
{
float *d_pfF0Square;
float *d_pfFSquare;
float *d_pfFF0;
cudaMalloc((void **) &d_pfF0Square, sizeof(float));
cudaMalloc((void **) &d_pfFSquare, sizeof(float));
cudaMalloc((void **) &d_pfFF0, sizeof(float));
cudaMemset((void *) d_pfF0Square, 0, sizeof(float));
cudaMemset((void *) d_pfFSquare, 0, sizeof(float));
cudaMemset((void *) d_pfFF0, 0, sizeof(float));
cudaMemset((void *) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
cudaMemset((void *) d_pfSE, 0, 5*sizeof(float));
checkCudaError("Setting memory");
cudaMemcpyAsync(d_pdTempFx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdTempFy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdTempFt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaDeviceSynchronize();
//if (!bAngle) {
// cudaMemset((void *) d_pdTempFt, 0 , m_nSpherocyls*sizeof(double));
//}
calc_fe <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdBlockSums);
square_forces <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdTempFx, d_pdTempFy, d_pdTempFt, d_pdMOI, d_pfF0Square);
cudaDeviceSynchronize();
checkCudaError("Calculating square of forces 1");
//if (!bAngle) {
// cudaMemset((void *) d_pdFt, 0, m_nSpherocyls*sizeof(double));
//}
square_forces <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pfFSquare);
mult_forces <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdTempFx, d_pdTempFy, d_pdTempFt, d_pdMOI, d_pfFF0);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pfSE, d_pfSE, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
float *h_pfF0Square;
float *h_pfFSquare;
//float *h_pfFF0;
h_pfF0Square = (float*) malloc(sizeof(float));
h_pfFSquare = (float*) malloc(sizeof(float));
//h_pfFF0 = (float*) malloc(sizeof(float));
cudaMemcpy(h_pfF0Square, d_pfF0Square, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(h_pfFSquare, d_pfFSquare, sizeof(float), cudaMemcpyDeviceToHost);
//cudaMemcpy(h_pfFF0, d_pfFF0, sizeof(float), cudaMemcpyDeviceToHost);
//printf("F0-square: %g, F-Square: %g, F*F0: %g\n", *h_pfF0Square, *h_pfFSquare, *h_pfFF0);
if (*h_pfFSquare == 0) {
printf("Zero energy found, stopping minimization");
return 1;
}
cudaDeviceSynchronize();
h_pdLineEnergy[4] = h_pdLineEnergy[0];
h_pdLineEnergy[0] = 0;
for (int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[0] += h_pdBlockSums[j];
}
if (h_pdLineEnergy[4] == h_pdLineEnergy[0] && *h_pfFSquare == *h_pfF0Square) {
printf("Minimum Energy Found, stopping minimization");
return 2;
}
//new_conjugate_direction <<<2*m_nGridSize, m_nBlockSize>>>
new_pr_conj_dir <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pdDx, d_pdDy, d_pdDt,
d_pfF0Square, d_pfFSquare, d_pfFF0, dAngleDamping);
cudaDeviceSynchronize();
checkCudaError("Finding new conjugate direction");
//if (!bAngle) {
// cudaMemset((void *) d_pdDt, 0, m_nSpherocyls*sizeof(double));
//}
m_dStep = 0.000001 / sqrt(*h_pfFSquare/(3*m_nSpherocyls));
int ret = line_search(1,1, dMinStep, dMaxStep);
if (ret == 1) {
cudaMemcpyAsync(d_pdDx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
m_dStep = 0.000001 / sqrt(*h_pfFSquare/(3*m_nSpherocyls));
cudaDeviceSynchronize();
ret = line_search(1,1, dMinStep, dMaxStep);
if (ret == 1) {
printf("Stopping due to step size\n");
return 1;
}
}
else if (ret == 2) {
cudaMemcpyAsync(d_pdDx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
m_dStep = 0.000001 / sqrt(*h_pfFSquare/(3*m_nSpherocyls));
cudaDeviceSynchronize();
ret = line_search(1,1, dMinStep, dMaxStep);
if (ret == 1) {
printf("Stopping due to step size\n");
return 1;
}
}
m_dMove += 3*m_dStep*sqrt(*h_pfFSquare/(3*m_nSpherocyls));
if (m_dMove > m_dEpsilon) {
find_neighbors();
m_dMove = 0;
}
free(h_pfF0Square); free(h_pfFSquare);
cudaFree(d_pfF0Square); cudaFree(d_pfFSquare); cudaFree(d_pfFF0);
return 0;
}
int Spherocyl_Box::force_cjpr_relax_step(double dMinStep, double dMaxStep, bool bAngle = true)
{
float *d_pfF0Square;
float *d_pfFSquare;
float *d_pfFF0;
cudaMalloc((void **) &d_pfF0Square, sizeof(float));
cudaMalloc((void **) &d_pfFSquare, sizeof(float));
cudaMalloc((void **) &d_pfFF0, sizeof(float));
cudaMemset((void *) d_pfF0Square, 0, sizeof(float));
cudaMemset((void *) d_pfFSquare, 0, sizeof(float));
cudaMemset((void *) d_pfFF0, 0, sizeof(float));
cudaMemset((void *) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
cudaMemset((void *) d_pfSE, 0, 5*sizeof(float));
checkCudaError("Setting memory");
cudaMemcpyAsync(d_pdTempFx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdTempFy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdTempFt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaDeviceSynchronize();
if (!bAngle) {
cudaMemset((void *) d_pdTempFt, 0 , m_nSpherocyls*sizeof(double));
}
calc_fe <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdBlockSums);
square_forces <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdTempFx, d_pdTempFy, d_pdTempFt, d_pdMOI, d_pfF0Square);
cudaDeviceSynchronize();
checkCudaError("Calculating square of forces 1");
if (!bAngle) {
cudaMemset((void *) d_pdFt, 0, m_nSpherocyls*sizeof(double));
}
dbl_square_forces <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdTempFx, d_pdTempFy, d_pdTempFt, d_pdMOI, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Summing forces");
square_forces <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pfFSquare);
mult_forces <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdTempFx, d_pdTempFy, d_pdTempFt, d_pdMOI, d_pfFF0);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pfSE, d_pfSE, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
float *h_pfF0Square;
float *h_pfFSquare;
//float *h_pfFF0;
h_pfF0Square = (float*) malloc(sizeof(float));
h_pfFSquare = (float*) malloc(sizeof(float));
//h_pfFF0 = (float*) malloc(sizeof(float));
cudaMemcpy(h_pfF0Square, d_pfF0Square, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(h_pfFSquare, d_pfFSquare, sizeof(float), cudaMemcpyDeviceToHost);
//cudaMemcpy(h_pfFF0, d_pfFF0, sizeof(float), cudaMemcpyDeviceToHost);
//printf("F0-square: %g, F-Square: %g, F*F0: %g\n", *h_pfF0Square, *h_pfFSquare, *h_pfFF0);
if (*h_pfFSquare == 0) {
printf("Zero energy found, stopping minimization");
return 1;
}
cudaDeviceSynchronize();
h_pdLineEnergy[4] = h_pdLineEnergy[0];
h_pdLineEnergy[0] = 0;
for (int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[0] += h_pdBlockSums[j];
}
if (h_pdLineEnergy[4] == h_pdLineEnergy[0] && *h_pfFSquare == *h_pfF0Square) {
printf("Minimum Energy Found, stopping minimization");
return 2;
}
//new_conjugate_direction <<<2*m_nGridSize, m_nBlockSize>>>
new_pr_conj_dir <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pdDx, d_pdDy, d_pdDt, d_pfF0Square, d_pfFSquare, d_pfFF0, 1.0);
cudaDeviceSynchronize();
checkCudaError("Finding new conjugate direction");
if (!bAngle) {
cudaMemset((void *) d_pdDt, 0, m_nSpherocyls*sizeof(double));
}
m_dStep = 0.00001 / sqrt(*h_pfFSquare);
int ret = line_search(1,1, dMinStep, dMaxStep);
if (ret == 1) {
cudaMemcpyAsync(d_pdDx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
m_dStep = 0.00001 / sqrt(*h_pfFSquare);
cudaDeviceSynchronize();
ret = line_search(1,1, dMinStep, dMaxStep);
if (ret == 1) {
printf("Stopping due to step size\n");
return 1;
}
}
else if (ret == 2) {
cudaMemcpyAsync(d_pdDx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
m_dStep = 0.00001 / sqrt(*h_pfFSquare);
cudaDeviceSynchronize();
ret = line_search(1,1, dMinStep, dMaxStep);
if (ret == 1) {
printf("Stopping due to step size\n");
return 1;
}
}
m_dMove += m_dStep*(*h_pfFSquare);
if (m_dMove > m_dEpsilon) {
find_neighbors();
m_dMove = 0;
}
free(h_pfF0Square); free(h_pfFSquare);
cudaFree(d_pfF0Square); cudaFree(d_pfFSquare); cudaFree(d_pfFF0);
return 0;
}
int Spherocyl_Box::cjfr_relax_step(double dMinStep, double dMaxStep)
{
float *d_pfF0Square;
float *d_pfFSquare;
cudaMalloc((void **) &d_pfF0Square, sizeof(float));
cudaMalloc((void **) &d_pfFSquare, sizeof(float));
cudaMemset((void *) d_pfF0Square, 0, sizeof(float));
cudaMemset((void *) d_pfFSquare, 0, sizeof(float));
cudaMemset((void *) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
cudaMemset((void *) d_pfSE, 0, 5*sizeof(float));
checkCudaError("Setting memory");
calc_fe <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
square_forces <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pfF0Square);
cudaDeviceSynchronize();
checkCudaError("Calculating square of forces");
calc_fe <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pfSE, d_pfSE, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
square_forces <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pfFSquare);
cudaDeviceSynchronize();
checkCudaError("Calculating square of forces");
float *h_pfF0Square;
float *h_pfFSquare;
h_pfF0Square = (float*) malloc(sizeof(float));
h_pfFSquare = (float*) malloc(sizeof(float));
cudaMemcpy(h_pfF0Square, d_pfF0Square, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(h_pfFSquare, d_pfFSquare, sizeof(float), cudaMemcpyDeviceToHost);
printf("F-square: %g %g\n", *h_pfF0Square, *h_pfFSquare);
if (*h_pfFSquare == 0) {
printf("Stopping due to zero Energy\n");
return 1;
}
h_pdLineEnergy[0] = 0;
for (int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[0] += h_pdBlockSums[j];
}
//printf("Energy: %.10g %.10g\n", h_pfSE[0], dEnergy);
//new_conjugate_direction <<<2*m_nGridSize, m_nBlockSize>>>
new_fr_conj_dir <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pdDx, d_pdDy, d_pdDt, d_pfF0Square, d_pfFSquare);
//cudaMemcpyAsync(d_pdDx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
//cudaMemcpyAsync(d_pdDy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
//cudaMemcpyAsync(d_pdDt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaDeviceSynchronize();
checkCudaError("Finding new conjugate direction");
m_dStep = 0.00001 / sqrt(*h_pfFSquare);
int ret = line_search(1,1, dMinStep, dMaxStep);
if (ret == 1) {
cudaMemcpyAsync(d_pdDx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
m_dStep = 0.00001 / sqrt(*h_pfFSquare);
cudaDeviceSynchronize();
ret = line_search(1,1, dMinStep, dMaxStep);
if (ret == 1) {
printf("Stopping due to step size\n");
return 1;
}
}
//else if (ret == 2) {
free(h_pfF0Square); free(h_pfFSquare);
cudaFree(d_pfF0Square); cudaFree(d_pfFSquare);
return 0;
}
int Spherocyl_Box::gd_relax_step(double dMinStep, double dMaxStep)
{
float *d_pfFSquare;
cudaMalloc((void **) &d_pfFSquare, sizeof(float));
cudaMemset((void *) d_pfFSquare, 0, sizeof(float));
cudaMemset((void *) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
cudaMemset((void *) d_pfSE, 0, 5*sizeof(float));
checkCudaError("Setting memory");
calc_fe <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdDx, d_pdDy, d_pdDt, d_pfSE, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pfSE, d_pfSE, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
square_forces <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdDx, d_pdDy, d_pdDt, d_pdMOI, d_pfFSquare);
cudaDeviceSynchronize();
checkCudaError("Calculating square of forces");
float *h_pfFSquare;
h_pfFSquare = (float*) malloc(sizeof(float));
cudaMemcpy(h_pfFSquare, d_pfFSquare, sizeof(float), cudaMemcpyDeviceToHost);
printf("F-square: %g\n", *h_pfFSquare);
if (*h_pfFSquare == 0) {
printf("Stopping due to zero Energy\n");
return 1;
}
h_pdLineEnergy[0] = 0;
for (int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[0] += h_pdBlockSums[j];
}
m_dStep = 0.00001 / sqrt(*h_pfFSquare);
int ret = line_search(1,1, dMinStep, dMaxStep);
if (ret == 1) {
printf("Stopping due to step size\n");
return 1;
}
//else if (ret == 2) {
free(h_pfFSquare);
cudaFree(d_pfFSquare);
return 0;
}
void Spherocyl_Box::gd_relax(double dMinStep, double dMaxStep)
{
cudaMemset((void*) d_pdDx, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDy, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDt, 0, m_nSpherocyls*sizeof(double));
for (int i = 0; i < 1000000; i++) {
//m_dStep = 0.1;
int ret = gd_relax_step(dMinStep, dMaxStep);
if (ret == 1) {
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
save_positions(i);
break;
}
find_neighbors();
}
}
void Spherocyl_Box::cjfr_relax(double dMinStep, double dMaxStep)
{
cudaMemset((void*) d_pdDx, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDy, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDt, 0, m_nSpherocyls*sizeof(double));
for (int i = 0; i < 1000000; i++) {
//m_dStep = 0.1;
int ret = cjfr_relax_step(dMinStep, dMaxStep);
if (ret == 1) {
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
save_positions(i);
break;
}
find_neighbors();
}
}
void Spherocyl_Box::cjpr_relax(double dMinStep, double dMaxStep, int nMaxSteps = 10000, double dAngleDamping = 1.0)
{
cudaMemset((void*) d_pdDx, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDy, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDt, 0, m_nSpherocyls*sizeof(double));
calc_fe <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
h_pdLineEnergy[0] = 0;
m_dMove = 0;
find_neighbors();
long unsigned int nTime = 0;
while (nTime < nMaxSteps) {
//m_dStep = 0.1;
int ret = cjpr_relax_step(dMinStep, dMaxStep, dAngleDamping);
//printf("Step return: %d\n", ret);
if (ret == 1 || ret == 2) {
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
//save_positions(nTime);
break;
}
//find_neighbors();
nTime += 1;
}
find_neighbors();
calc_fe <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
h_pdLineEnergy[0] = 0;
for (int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[0] += h_pdBlockSums[j];
}
}
void Spherocyl_Box::force_cjpr_relax(double dMinStep, double dMaxStep, int nMaxSteps = 10000)
{
bool bAngle = true;
cudaMemset((void*) d_pdDx, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDy, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDt, 0, m_nSpherocyls*sizeof(double));
calc_fe <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
h_pdLineEnergy[0] = 0;
m_dMove = 0;
find_neighbors();
long unsigned int nTime = 0;
while (nTime < nMaxSteps) {
//m_dStep = 0.1;
int ret = force_cjpr_relax_step(dMinStep, dMaxStep, bAngle);
//printf("Step return: %d\n", ret);
if (ret == 1 || ret == 2) {
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
//save_positions(nTime);
break;
}
//find_neighbors();
nTime += 1;
}
calc_fe <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
h_pdLineEnergy[0] = 0;
for (int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[0] += h_pdBlockSums[j];
}
}
void Spherocyl_Box::quasistatic_compress(double dMaxPack, double dResizeStep, double dMinStep = 1e-10) {
assert(dResizeStep != 0 && dResizeStep != -0);
dResizeStep = fabs(dResizeStep);
calculate_packing();
assert(dMaxPack >= m_dPacking);
int nCompressTime = 0;
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
cjpr_relax(dMinStep, 200);
save_positions(nCompressTime);
calculate_stress_energy();
fprintf(m_pOutfSE, "%d %f %g %g %g %g %g\n", nCompressTime, m_dPacking, h_pfSE[0], h_pfSE[1], h_pfSE[2], h_pfSE[3], h_pfSE[4]);
while(h_pdLineEnergy[0] > 0) {
nCompressTime += 1;
m_dStep = 0.01;
resize_step(nCompressTime, dResizeStep, 0, 0);
cjpr_relax(dMinStep, 200);
calculate_stress_energy();
cudaMemcpy(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
save_positions(nCompressTime);
calculate_packing();
fprintf(m_pOutfSE, "%d %f %g %g %g %g %g\n", nCompressTime, m_dPacking, h_pfSE[0], h_pfSE[1], h_pfSE[2], h_pfSE[3], h_pfSE[4]);
fflush(m_pOutfSE);
}
while (m_dPacking < dMaxPack) {
nCompressTime += 1;
m_dStep = 0.01;
resize_step(nCompressTime, -dResizeStep, 0, 0);
//cjpr_relax(dMinStep, 200, true);
//cjpr_relax(10*dMinStep, 200, false);
cjpr_relax(dMinStep, 200);
calculate_stress_energy();
cudaMemcpy(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
save_positions(nCompressTime);
calculate_packing();
fprintf(m_pOutfSE, "%d %f %g %g %g %g %g\n", nCompressTime, m_dPacking, h_pfSE[0], h_pfSE[1], h_pfSE[2], h_pfSE[3], h_pfSE[4]);
fflush(m_pOutfSE);
}
fclose(m_pOutfSE);
}
int Spherocyl_Box::qs_one_cycle(int nTime, double dMaxE, double dResizeStep, double dMinStep = 1e-10) {
assert(dResizeStep != 0 && dResizeStep != -0);
dResizeStep = fabs(dResizeStep);
calculate_packing();
cjpr_relax(dMinStep, 200);
save_positions(nTime);
calculate_packing();
fprintf(m_pOutfSE, "%d %f %g %g %g %g %g\n", nTime, m_dPacking, h_pfSE[0], h_pfSE[1], h_pfSE[2], h_pfSE[3], h_pfSE[4]);
while(h_pdLineEnergy[0] > 0) {
nTime += 1;
m_dStep = 0.01;
resize_step(nTime, dResizeStep, 0, 0);
cjpr_relax(dMinStep, 200, 10000, 1.0);
cjpr_relax(dMinStep, 20, 5000, 0);
cjpr_relax(dMinStep, 50, 2000, 0.04);
cjpr_relax(dMinStep, 100, 2000, 0.1);
cjpr_relax(dMinStep, 200, 2000, 0.4);
cjpr_relax(dMinStep, 200, 5000, 1.0);
calculate_stress_energy();
cudaMemcpy(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
save_positions(nTime);
calculate_packing();
fprintf(m_pOutfSE, "%d %f %g %g %g %g %g\n", nTime, m_dPacking, h_pfSE[0], h_pfSE[1], h_pfSE[2], h_pfSE[3], h_pfSE[4]);
fflush(m_pOutfSE);
}
while (h_pdLineEnergy[0] < dMaxE) {
nTime += 1;
m_dStep = 0.01;
resize_step(nTime, -dResizeStep, 0, 0);
cjpr_relax(dMinStep, 200, 10000, 1.0);
cjpr_relax(dMinStep, 20, 5000, 0);
cjpr_relax(dMinStep, 50, 2000, 0.04);
cjpr_relax(dMinStep, 100, 2000, 0.1);
cjpr_relax(dMinStep, 200, 2000, 0.4);
cjpr_relax(dMinStep, 200, 5000, 1.0);
calculate_stress_energy();
cudaMemcpy(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
save_positions(nTime);
calculate_packing();
fprintf(m_pOutfSE, "%d %f %g %g %g %g %g\n", nTime, m_dPacking, h_pfSE[0], h_pfSE[1], h_pfSE[2], h_pfSE[3], h_pfSE[4]);
fflush(m_pOutfSE);
}
return nTime;
}
void Spherocyl_Box::quasistatic_cycle(int nCycles, double dMaxE, double dResizeStep, double dMinStep = 1e-10)
{
int nTime = 0;
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
for (int c = 0; c < nCycles; c++) {
nTime = qs_one_cycle(nTime, dMaxE, dResizeStep, dMinStep);
nTime += 1;
}
fclose(m_pOutfSE);
}
void Spherocyl_Box::quasistatic_find_jam(double dMaxE, double dMinE, double dResizeStep, double dMinStep = 1e-10)
{
int nTime = 0;
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
double dMinResizeStep = m_dLx*1e-15;
while (dMaxE > dMinE && dResizeStep > dMinResizeStep) {
nTime = qs_one_cycle(nTime, dMaxE, dResizeStep, dMinStep);
dMaxE *= 0.5;
dResizeStep *= 0.5;
nTime += 1;
}
fclose(m_pOutfSE);
}
int Spherocyl_Box::resize_to_energy_1p(int nTime, double dEnergy, double dStep)
{
dStep = fabs(dStep);
double dCJMinStep = 1e-16;
double dCJMaxStep = 10;
int nCJMaxSteps = 400000;
calc_fe <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
h_pdLineEnergy[0] = 0;
cudaDeviceSynchronize();
for (int i = 0; i < m_nGridSize; i++) {
h_pdLineEnergy[0] += h_pdBlockSums[i];
}
if (h_pdLineEnergy[0] < dEnergy) {
while (h_pdLineEnergy[0] < dEnergy) {
nTime += 1;
m_dStep = 0.01;
resize_step(nTime, -dStep, 0, 0);
cjpr_relax(dCJMinStep, dCJMaxStep, nCJMaxSteps, 1.0);
calculate_stress_energy();
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
calculate_packing();
save_positions(nTime);
cudaDeviceSynchronize();
fprintf(m_pOutfSE, "%d %.9f %g %g %g %g %g\n", nTime, m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, *m_pfPxy, *m_pfPyx);
fflush(m_pOutfSE);
dStep *= 1.1;
}
}
else {
while (h_pdLineEnergy[0] > dEnergy) {
nTime += 1;
m_dStep = 0.01;
resize_step(nTime, dStep, 0, 0);
cjpr_relax(dCJMinStep, dCJMaxStep, nCJMaxSteps, 1.0);
calculate_stress_energy();
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
calculate_packing();
save_positions(nTime);
cudaDeviceSynchronize();
fprintf(m_pOutfSE, "%d %.9f %g %g %g %g %g\n", nTime, m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, *m_pfPxy, *m_pfPyx);
fflush(m_pOutfSE);
dStep *= 1.1;
}
}
return nTime;
}
void Spherocyl_Box::find_jam_1p(double dJamE, double dResizeStep)
{
int nTime = 0;
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
save_positions(0);
double dMinResizeStep = m_dLx*1e-13;
int nOldTime = 0;
while (dResizeStep > dMinResizeStep) {
nTime = resize_to_energy_1p(nTime, dJamE, dResizeStep);
dResizeStep = dResizeStep*pow(1.1, (nTime-nOldTime))/2;
nOldTime = nTime;
}
//save_positions(9999999999);
save_positions_bin(nTime);
fclose(m_pOutfSE);
}
<file_sep>/src/cuda/main_profile.cpp
/*
*
*
*/
#include "spherocyl_box.h"
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <iostream>
#include "file_input.h"
#include <string>
using namespace std;
const double D_PI = 3.14159265358979;
int main()
{
cout << "Setting parameters testing... \n";
int nSpherocyls = 16384;
cout << "Number of particles = " << nSpherocyls << endl;
double dPacking = 0.89;
cout << "Packing fraction = " << dPacking << endl;
double dL = sqrt(0.5 * nSpherocyls * D_PI * (0.5 * 0.5 + 0.7 * 0.7) / dPacking);
cout << "Box dimension = " << dL << endl;
double dStrain = 0.0001;
cout << "Strain rate for shearing = " << dStrain << endl;
double dStep = 0.5;
cout << "Step size for shearing = " << dStep << endl;
double dEpsilon = 0.08;
cout << "Neighbor movement buffer = " << dEpsilon << "\n\n";
double *dX = new double[nSpherocyls];
double *dY = new double[nSpherocyls];
double *dR = new double[nSpherocyls];
srand(time(0));
for (int p = 0; p < nSpherocyls; p++)
{
dX[p] = dL * static_cast<double>(rand()) / RAND_MAX;
dY[p] = dL * static_cast<double>(rand()) / RAND_MAX;
dR[p] = 0.5 + (p % 2) * 0.2;
}
cout << "Testing routines... " << endl;
Spherocyl_Box cTest(nSpherocyls, dL, dX, dY, dR, dEpsilon);
cTest.set_gamma(-0.4999999999);
cTest.set_total_gamma(0.0);
cTest.set_strain(dStrain);
cTest.set_step(dStep);
cout << "Finding neighbors... " << endl;
cTest.find_neighbors();
//cout << "Calculating stresses... " << endl;
//cTest.calculate_stress_energy();
//cout << "Running strain step... " << endl;
//cTest.run_strain(0, dStrain, dStrain*dStep, dStrain);
//cout << "Setting back shear coordinates... " << endl;
//cTest.set_gamma(0.5000000001);
//cTest.set_back_gamma();
cout << "Reordering particles... " << endl;
cTest.reorder_particles();
cTest.reset_IDs();
cout << "Calculating stresses... " << endl;
cTest.calculate_stress_energy();
cout << "Running strain step... " << endl;
cTest.run_strain(0, dStrain, dStrain*dStep, dStrain);
cout << "Setting back shear coordinates... " << endl;
cTest.set_gamma(0.5000000001);
cTest.set_back_gamma();
delete[] dX; delete[] dY; delete[] dR;
return 0;
}
<file_sep>/src/cuda/strain_dynamics.cu
// -*- c++ -*-
/*
* strain_dynamics.cu
*
*
*/
#include <cuda.h>
#include "spherocyl_box.h"
#include "cudaErr.h"
#include <math.h>
#include <sm_20_atomic_functions.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
using namespace std;
const double D_PI = 3.14159265358979;
/*
__global__ void calc_rot_consts(int nSpherocyls, double *pdR, double *pdAs,
double *pdAb, double *pdCOM, double *pdMOI,
double *pdSinCoeff, double *pdCosCoeff)
{
int nPID = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = blockDim.x + gridDim.x;
while (nPID < nSpherocyls) {
double dR = pdR[nPID];
double dAs = pdAs[nPID];
double dA = dAs + 2. * dR;
double dB = pdAb[nPID];
double dC = pdCOM[nPID];
double dIntdS = 2*dA + 4*dB;
double dIntSy2SinCoeff = dA*dA*(2*dA/3 + 4*dB);
double dIntSy2CosCoeff = dB*dB*(16*dB/3 - 8*dC) + 2*(dA + 2*dB)*dC*dC;
double dIntS2 = dIntSy2SinCoeff + dIntSy2CosCoeff;
pdMOI[nPID] = dIntS2 / dIntdS;
pdSinCoeff[nPID] = dIntSy2SinCoeff / dIntS2;
pdCosCoeff[nPID] = dIntSy2CosCoeff / dIntS2;
nPID += nThreads;
}
}
*/
///////////////////////////////////////////////////////////////
//
// Deprecated Method
//
///////////////////////////////////////////////////////////
template<Potential ePot, int bCalcStress>
__global__ void euler_est_sc(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy,
double dGamma, double dStrain, double dStep, double *pdX, double *pdY,
double *pdPhi, double *pdR, double *pdA, double *pdMOI, double *pdFx, double *pdFy,
double *pdFt, float *pfSE, double *pdTempX, double *pdTempY, double *pdTempPhi)
{
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
extern __shared__ double sData[];
int offset = blockDim.x + 8; // +8 should help to avoid a few bank conflict
if (bCalcStress) {
for (int i = 0; i < 5; i++)
sData[i*offset + thid] = 0.0;
__syncthreads(); // synchronizes every thread in the block before going on
}
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dFt = 0.0;
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dDeltaX = dX - pdX[nAdjPID];
double dDeltaY = dY - pdY[nAdjPID];
double dPhiB = pdPhi[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double t;
double s;
if (dA == 0) {
s = 0;
if (dB == 0) {
t = 0;
}
else {
double c = dB*dB;
double e = nxB * dDeltaX + nyB *dDeltaY;
t = fmin(fmax(e/c, -1), 1);
}
}
else {
if (dB == 0) {
t = 0;
double a = dA*dA;
double d = nxA *dDeltaX + nyA * dDeltaY;
s = fmin(fmax(-d/a, -1), 1);
}
else {
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
if (delta == 0) {
double s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
double s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
s = (s1 + s2) / 2;
t = fmin(fmax( -(b*s+e)/c, -1.0), 1.0);
}
else {
t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
}
}
}
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx * dDVij / dDij;
double dPfy = dDy * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
dFt += s*nxA * dPfy - s*nyA * dPfx;
if (bCalcStress)
{
double dCx = 0.5*dDx - s*nxA;
double dCy = 0.5*dDy - s*nyA;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
if (nAdjPID > nPID)
{
sData[thid + 4*offset] += dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
}
pdFx[nPID] = dFx;
pdFy[nPID] = dFy;
pdFt[nPID] = dFt;
pdTempX[nPID] = dX + dStep * (dFx - dGamma * dFy);
pdTempY[nPID] = dY + dStep * dFy;
double dSinPhi = sin(dPhi);
pdTempPhi[nPID] = dPhi + dStep *
(dFt / pdMOI[nPID] - dStrain * dSinPhi * dSinPhi);
nPID += nThreads;
}
if (bCalcStress) {
__syncthreads();
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size, all threads perform two adds
int base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
base += 2*offset;
sData[base] += sData[base + stride];
if (thid < stride) {
base += 2*offset;
sData[base] += sData[base + stride];
}
stride /= 2; // stride is 1/4 block size, all threads perform 1 add
__syncthreads();
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
if (thid < stride) {
base += 4*offset;
sData[base] += sData[base+stride];
}
stride /= 2;
__syncthreads();
while (stride > 4)
{
if (thid < 5 * stride)
{
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 20)
{
base = thid % 4 + offset * (thid / 4);
sData[base] += sData[base + 4];
if (thid < 10)
{
base = thid % 2 + offset * (thid / 2);
sData[base] += sData[base + 2];
if (thid < 5)
{
sData[thid * offset] += sData[thid * offset + 1];
float tot = atomicAdd(pfSE+thid, (float)sData[thid*offset]);
}
}
}
}
}
/////////////////////////////////////////////////////////////////
//
// First step (Netonian estimate) for simple shear
//
//////////////////////////////////////////////////////////////
template<Potential ePot, int bCalcStress>
__global__ void euler_est(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy, double dGamma,
double dStrain, double dStep, double *pdX, double *pdY, double *pdPhi, double *pdR,
double *pdA, double dKd, double *pdArea, double *pdMOI, double *pdIsoC, double *pdFx,
double *pdFy, double *pdFt, float *pfSE, double *pdTempX, double *pdTempY, double *pdTempPhi)
{
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
extern __shared__ double sData[];
int offset = blockDim.x + 8; // +8 should help to avoid a few bank conflict
if (bCalcStress) {
for (int i = 0; i < 5; i++)
sData[i*offset + thid] = 0.0;
__syncthreads(); // synchronizes every thread in the block before going on
}
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dFt = 0.0;
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dAdjX = pdX[nAdjPID];
double dAdjY = pdY[nAdjPID];
double dDeltaX = dX - dAdjX;
double dDeltaY = dY - dAdjY;
double dPhiB = pdPhi[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double t;
double s;
if (dA == 0) {
s = 0;
if (dB == 0) {
t = 0;
}
else {
double c = dB*dB;
double e = nxB * dDeltaX + nyB *dDeltaY;
t = fmin(fmax(e/c, -1), 1);
}
}
else {
if (dB == 0) {
t = 0;
double a = dA*dA;
double d = nxA *dDeltaX + nyA * dDeltaY;
s = fmin(fmax(-d/a, -1), 1);
}
else {
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
if (delta == 0) {
double s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
double s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
s = (s1 + s2) / 2;
t = fmin(fmax( -(b*s+e)/c, -1.0), 1.0);
}
else {
t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
}
}
}
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx * dDVij / dDij;
double dPfy = dDy * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
// Find the point of contact (with respect to the center of the spherocyl)
//double dCx = s*nxA - 0.5*dDx;
//double dCy = s*nyA - 0.5*dDy;
//double dCx = s*nxA;
//double dCy = s*nyA;
dFt += s*nxA * dPfy - s*nyA * dPfx;
if (bCalcStress)
{
double dCx = 0.5*dDx - s*nxA;
double dCy = 0.5*dDy - s*nyA;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
if (nAdjPID > nPID)
{
sData[thid + 4*offset] += dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
}
pdFx[nPID] = dFx;
pdFy[nPID] = dFy;
pdFt[nPID] = dFt;
double dArea = pdArea[nPID];
dFx /= (dKd*dArea);
dFy /= (dKd*dArea);
dFt /= (dKd*dArea*pdMOI[nPID]);
pdTempX[nPID] = dX + dStep * (dFx - dGamma * dFy);
pdTempY[nPID] = dY + dStep * dFy;
double dRIso = 0.5*(1-pdIsoC[nPID]*cos(2*dPhi));
pdTempPhi[nPID] = dPhi + dStep * (dFt - dStrain * dRIso);
nPID += nThreads;
}
if (bCalcStress) {
__syncthreads();
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size, all threads perform two adds
int base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
base += 2*offset;
sData[base] += sData[base + stride];
if (thid < stride) {
base += 2*offset;
sData[base] += sData[base + stride];
}
stride /= 2; // stride is 1/4 block size, all threads perform 1 add
__syncthreads();
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
if (thid < stride) {
base += 4*offset;
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
while (stride > 4)
{
if (thid < 5 * stride)
{
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 20)
{
base = thid % 4 + offset * (thid / 4);
sData[base] += sData[base + 4];
if (thid < 10)
{
base = thid % 2 + offset * (thid / 2);
sData[base] += sData[base + 2];
if (thid < 5)
{
sData[thid * offset] += sData[thid * offset + 1];
float tot = atomicAdd(pfSE+thid, (float)sData[thid*offset]);
}
}
}
}
}
///////////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////////
template<Potential ePot>
__global__ void heun_corr(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy, double dGamma,
double dStrain, double dStep, double *pdX, double *pdY, double *pdPhi, double *pdR,
double *pdA, double dKd, double *pdArea, double *pdMOI, double *pdIsoC,
double *pdFx, double *pdFy, double *pdFt, double *pdTempX, double *pdTempY,
double *pdTempPhi, double *pdXMoved, double *pdYMoved, double dEpsilon, int *bNewNbrs)
{
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dFt = 0.0;
double dX = pdTempX[nPID];
double dY = pdTempY[nPID];
double dPhi = pdTempPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
double dNewGamma = dGamma + dStep * dStrain;
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dAdjX = pdTempX[nAdjPID];
double dAdjY = pdTempY[nAdjPID];
double dDeltaX = dX - dAdjX;
double dDeltaY = dY - dAdjY;
double dPhiB = pdTempPhi[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dNewGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double t;
double s;
if (dA == 0) {
s = 0;
if (dB == 0) {
t = 0;
}
else {
double c = dB*dB;
double e = nxB * dDeltaX + nyB *dDeltaY;
t = fmin(fmax(e/c, -1), 1);
}
}
else {
if (dB == 0) {
t = 0;
double a = dA*dA;
double d = nxA *dDeltaX + nyA * dDeltaY;
s = fmin(fmax(-d/a, -1), 1);
}
else {
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
if (delta == 0) {
double s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
double s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
s = (s1 + s2) / 2;
t = fmin(fmax( -(b*s+e)/c, -1.0), 1.0);
}
else {
t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
}
}
}
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij;
//double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
//dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
//dAlpha = 2.5;
}
double dPfx = dDx * dDVij / dDij;
double dPfy = dDy * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
//double dCx = s*nxA - 0.5*dDx;
//double dCy = s*nyA - 0.5*dDy;
double dCx = s*nxA;
double dCy = s*nyA;
dFt += dCx * dPfy - dCy * dPfx;
}
}
double dMOI = pdMOI[nPID];
double dIsoC = pdIsoC[nPID];
double dArea = pdArea[nPID];
dFx /= (dKd*dArea);
dFy /= (dKd*dArea);
dFt /= (dKd*dArea*dMOI);
dFx -= dNewGamma * dFy;
dFt = dFt - dStrain * 0.5 * (1 - dIsoC*cos(2*dPhi));
double dFy0 = pdFy[nPID] / (dKd*dArea);
double dFx0 = pdFx[nPID] / (dKd*dArea) - dGamma * dFy0;
double dPhi0 = pdPhi[nPID] / (dKd*dArea*dMOI);
double dFt0 = pdFt[nPID] - dStrain * 0.5 * (1 - dIsoC*cos(2*dPhi0));
double dDx = 0.5 * dStep * (dFx0 + dFx);
double dDy = 0.5 * dStep * (dFy0 + dFy);
pdX[nPID] += dDx;
pdY[nPID] += dDy;
pdPhi[nPID] += 0.5 * dStep * (dFt0 + dFt);
pdXMoved[nPID] += dDx;
pdYMoved[nPID] += dDy;
if (fabs(pdXMoved[nPID]) + fabs(pdYMoved[nPID]) > 0.5*dEpsilon)
*bNewNbrs = 1;
nPID += nThreads;
}
}
////////////////////////////////////////////////////////////////////////
//
//
////////////////////////////////////////////////////////////////////
void Spherocyl_Box::strain_step(long unsigned int tTime, bool bSvStress, bool bSvPos)
{
if (bSvStress)
{
cudaMemset((void *) d_pfSE, 0, 5*sizeof(float));
switch (m_ePotential)
{
case HARMONIC:
euler_est <HARMONIC, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC, d_pdFx,
d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est <HERTZIAN, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC, d_pdFx,
d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions, calculating stresses");
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
if (bSvPos)
{
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
}
cudaThreadSynchronize();
}
else
{
switch (m_ePotential)
{
case HARMONIC:
euler_est <HARMONIC, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est <HERTZIAN, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions");
}
switch (m_ePotential)
{
case HARMONIC:
heun_corr <HARMONIC> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdXMoved,
d_pdYMoved, m_dEpsilon, d_bNewNbrs);
break;
case HERTZIAN:
heun_corr <HERTZIAN> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdXMoved,
d_pdYMoved, m_dEpsilon, d_bNewNbrs);
}
if (bSvStress)
{
m_fP = 0.5 * (*m_pfPxx + *m_pfPyy);
fprintf(m_pOutfSE, "%lu %.7g %.7g %.7g %.7g %.7g %.7g\n",
tTime, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy, *m_pfPyx);
if (bSvPos)
save_positions(tTime);
}
cudaThreadSynchronize();
checkCudaError("Updating estimates, moving particles");
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
m_dGamma += m_dStep * m_dStrainRate;
m_dTotalGamma += m_dStep * m_dStrainRate;
cudaThreadSynchronize();
if (m_dGamma > 0.5*m_dLx/m_dLy)
set_back_gamma();
else if (*h_bNewNbrs)
find_neighbors();
else if (m_dGamma - floor(m_dGamma) < 1.1 * m_dStep * m_dStrainRate)
find_neighbors();
}
void Spherocyl_Box::strain_step_ngl(long unsigned int tTime, bool bSvStress, bool bSvPos)
{
if (bSvStress)
{
cudaMemset((void *) d_pfSE, 0, 5*sizeof(float));
switch (m_ePotential)
{
case HARMONIC:
euler_est <HARMONIC, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est <HERTZIAN, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions, calculating stresses");
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
if (bSvPos)
{
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
}
cudaThreadSynchronize();
}
else
{
switch (m_ePotential)
{
case HARMONIC:
euler_est <HARMONIC, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est <HERTZIAN, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions");
}
switch (m_ePotential)
{
case HARMONIC:
heun_corr <HARMONIC> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdXMoved,
d_pdYMoved, m_dEpsilon, d_bNewNbrs);
break;
case HERTZIAN:
heun_corr <HERTZIAN> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdXMoved,
d_pdYMoved, m_dEpsilon, d_bNewNbrs);
}
if (bSvStress)
{
m_fP = 0.5 * (*m_pfPxx + *m_pfPyy);
fprintf(m_pOutfSE, "%lu %.7g %.7g %.7g %.7g %.7g %.7g\n",
tTime, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy, *m_pfPyx);
if (bSvPos)
save_positions(tTime);
}
cudaThreadSynchronize();
checkCudaError("Updating estimates, moving particles");
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
m_dGamma += m_dStep * m_dStrainRate;
m_dTotalGamma += m_dStep * m_dStrainRate;
cudaThreadSynchronize();
if (m_dGamma > 0.5*m_dLx/m_dLy)
find_neighbors();
else if (*h_bNewNbrs)
find_neighbors();
else if (m_dGamma - int(m_dGamma) < 1.1 * m_dStep * m_dStrainRate)
find_neighbors();
}
/////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////
void Spherocyl_Box::save_positions(long unsigned int nTime)
{
char szBuf[150];
sprintf(szBuf, "%s/sd%010lu.dat", m_szDataDir, nTime);
const char *szFilePos = szBuf;
FILE *pOutfPos;
pOutfPos = fopen(szFilePos, "w");
if (pOutfPos == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
int i = h_pnMemID[0];
fprintf(pOutfPos, "%d %.17g %.17g %f %.17g %.14g %g %g\n",
m_nSpherocyls, m_dLx, m_dLy, m_dPacking, m_dGamma, m_dTotalGamma, m_dStrainRate, m_dStep);
for (int p = 0; p < m_nSpherocyls; p++)
{
i = h_pnMemID[p];
fprintf(pOutfPos, "%.17g %.17g %.17g %.2g %.17g\n",
h_pdX[i], h_pdY[i], h_pdPhi[i], h_pdR[i], h_pdA[i]);
}
fclose(pOutfPos);
}
void Spherocyl_Box::save_positions_bin(long unsigned int nTime)
{
char szBuf[150];
sprintf(szBuf, "%s/sd%010lu.bin", m_szDataDir, nTime);
const char *szFilePos = szBuf;
FILE *pOutfPos;
pOutfPos = fopen(szFilePos, "wb");
if (pOutfPos == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
fwrite(&m_nSpherocyls, sizeof(m_nSpherocyls), 1, pOutfPos);
fwrite(&m_dLx, sizeof(m_dLx), 1, pOutfPos);
fwrite(&m_dLy, sizeof(m_dLy), 1, pOutfPos);
fwrite(&m_dPacking, sizeof(m_dPacking), 1, pOutfPos);
fwrite(&m_dGamma, sizeof(m_dGamma), 1, pOutfPos);
fwrite(&m_dTotalGamma, sizeof(m_dTotalGamma), 1, pOutfPos);
fwrite(&m_dStrainRate, sizeof(m_dStrainRate), 1, pOutfPos);
fwrite(&m_dStep, sizeof(m_dStep), 1, pOutfPos);
for (int p = 0; p < m_nSpherocyls; p++) {
int i = h_pnMemID[p];
fwrite(h_pdX+i, sizeof(double), 1, pOutfPos);
fwrite(h_pdY+i, sizeof(double), 1, pOutfPos);
fwrite(h_pdPhi+i, sizeof(double), 1, pOutfPos);
fwrite(h_pdR+i, sizeof(double), 1, pOutfPos);
fwrite(h_pdA+i, sizeof(double), 1, pOutfPos);
}
fclose(pOutfPos);
}
////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////
void Spherocyl_Box::run_strain(double dStartGamma, double dStopGamma, double dSvStressGamma, double dSvPosGamma)
{
if (m_dStrainRate == 0.0)
{
fprintf(stderr, "Cannot strain with zero strain rate\n");
exit(1);
}
printf("Beginnig strain run with strain rate: %g and step %g\n", m_dStrainRate, m_dStep);
fflush(stdout);
if (dSvStressGamma < m_dStrainRate * m_dStep)
dSvStressGamma = m_dStrainRate * m_dStep;
if (dSvPosGamma < m_dStrainRate)
dSvPosGamma = m_dStrainRate;
// +0.5 to cast to nearest integer rather than rounding down
unsigned long int nTime = (unsigned long)(dStartGamma / m_dStrainRate + 0.5);
unsigned long int nStop = (unsigned long)(dStopGamma / m_dStrainRate + 0.5);
unsigned int nIntStep = (unsigned int)(1.0 / m_dStep + 0.5);
unsigned int nSvStressInterval = (unsigned int)(dSvStressGamma / (m_dStrainRate * m_dStep) + 0.5);
unsigned int nSvPosInterval = (unsigned int)(dSvPosGamma / m_dStrainRate + 0.5);
unsigned long int nTotalStep = nTime * nIntStep;
//unsigned int nReorderInterval = (unsigned int)(1.0 / m_dStrainRate + 0.5);
printf("Strain run configured\n");
printf("Start: %lu, Stop: %lu, Int step: %lu\n", nTime, nStop, nIntStep);
printf("Stress save int: %lu, Pos save int: %lu\n", nSvStressInterval, nSvPosInterval);
fflush(stdout);
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
if (nTime == 0)
{
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL)
{
fprintf(stderr, "Could not open file for writing");
exit(1);
}
}
else
{
m_pOutfSE = fopen(szPathSE, "r+");
if (m_pOutfSE == NULL)
{
fprintf(stderr, "Could not open file for writing");
exit(1);
}
unsigned long int nTpos = 0;
while (nTpos != nTime)
{
if (fgets(szBuf, 200, m_pOutfSE) != NULL)
{
int nPos = strcspn(szBuf, " ");
char szTime[20];
strncpy(szTime, szBuf, nPos);
szTime[nPos] = '\0';
nTpos = atol(szTime);
}
else
{
fprintf(stderr, "Reached end of file without finding start position");
exit(1);
}
}
}
// Run strain for specified number of steps
while (nTime < nStop)
{
bool bSvPos = (nTime % nSvPosInterval == 0);
if (bSvPos) {
strain_step(nTime, 1, 1);
fflush(m_pOutfSE);
}
else
{
bool bSvStress = (nTotalStep % nSvStressInterval == 0);
strain_step(nTime, bSvStress, 0);
}
nTotalStep += 1;
for (unsigned int nI = 1; nI < nIntStep; nI++)
{
bool bSvStress = (nTotalStep % nSvStressInterval == 0);
strain_step(nTime, bSvStress, 0);
nTotalStep += 1;
}
nTime += 1;
//if (nTime % nReorderInterval == 0)
//reorder_particles();
}
// Save final configuration
strain_step(nTime, 1, 1);
fflush(m_pOutfSE);
fclose(m_pOutfSE);
}
void Spherocyl_Box::run_strain(unsigned long int nStart, double dRunGamma, double dSvStressGamma, double dSvPosGamma)
{
if (m_dStrainRate == 0.0)
{
fprintf(stderr, "Cannot strain with zero strain rate\n");
exit(1);
}
printf("Beginnig strain run with strain rate: %g and step %g\n", m_dStrainRate, m_dStep);
fflush(stdout);
if (dSvStressGamma < m_dStrainRate * m_dStep)
dSvStressGamma = m_dStrainRate * m_dStep;
if (dSvPosGamma < m_dStrainRate)
dSvPosGamma = m_dStrainRate;
// +0.5 to cast to nearest integer rather than rounding down
unsigned long int nTime = nStart;
unsigned long int nStop = nStart + (unsigned long)(dRunGamma / m_dStrainRate + 0.5);
unsigned int nIntStep = (unsigned int)(1.0 / m_dStep + 0.5);
unsigned int nSvStressInterval = (unsigned int)(dSvStressGamma / (m_dStrainRate * m_dStep) + 0.5);
unsigned int nSvPosInterval = (unsigned int)(dSvPosGamma / m_dStrainRate + 0.5);
unsigned long int nTotalStep = nTime * nIntStep;
//unsigned int nReorderInterval = (unsigned int)(1.0 / m_dStrainRate + 0.5);
printf("Strain run configured\n");
printf("Start: %lu, Stop: %lu, Int step: %lu\n", nTime, nStop, nIntStep);
printf("Stress save int: %lu, Pos save int: %lu\n", nSvStressInterval, nSvPosInterval);
fflush(stdout);
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
if (nTime == 0)
{
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL)
{
fprintf(stderr, "Could not open file for writing");
exit(1);
}
}
else
{
m_pOutfSE = fopen(szPathSE, "r+");
if (m_pOutfSE == NULL)
{
fprintf(stderr, "Could not open file for writing");
exit(1);
}
unsigned long int nTpos = 0;
while (nTpos != nTime)
{
if (fgets(szBuf, 200, m_pOutfSE) != NULL)
{
int nPos = strcspn(szBuf, " ");
char szTime[20];
strncpy(szTime, szBuf, nPos);
szTime[nPos] = '\0';
nTpos = atol(szTime);
}
else
{
fprintf(stderr, "Reached end of file without finding start position");
exit(1);
}
}
}
// Run strain for specified number of steps
while (nTime < nStop)
{
bool bSvPos = (nTime % nSvPosInterval == 0);
if (bSvPos) {
strain_step(nTime, 1, 1);
fflush(m_pOutfSE);
}
else
{
bool bSvStress = (nTotalStep % nSvStressInterval == 0);
strain_step(nTime, bSvStress, 0);
}
nTotalStep += 1;
for (unsigned int nI = 1; nI < nIntStep; nI++)
{
bool bSvStress = (nTotalStep % nSvStressInterval == 0);
strain_step(nTime, bSvStress, 0);
nTotalStep += 1;
}
nTime += 1;
//if (nTime % nReorderInterval == 0)
//reorder_particles();
}
// Save final configuration
strain_step(nTime, 1, 1);
fflush(m_pOutfSE);
fclose(m_pOutfSE);
}
void Spherocyl_Box::run_strain(long unsigned int nSteps)
{
// Run strain for specified number of steps
long unsigned int nTime = 0;
while (nTime < nSteps)
{
strain_step(nTime, 0, 0);
nTime += 1;
}
}
void Spherocyl_Box::run_strain(double dGammaMax)
{
reconfigure_cells(dGammaMax);
find_neighbors();
long unsigned int nTime = 0;
while (m_dGamma < dGammaMax) {
strain_step_ngl(nTime, 0, 0);
nTime += 1;
}
}
__global__ void resize_coords(int nParticles, double dEpsilon, double *pdX, double *pdY)
{
int nPID = threadIdx.x + blockIdx.x*blockDim.x;
int nThreads = blockDim.x*gridDim.x;
while (nPID < nParticles) {
pdX[nPID] += dEpsilon*pdX[nPID];
pdY[nPID] += dEpsilon*pdY[nPID];
nPID += nThreads;
}
}
void Spherocyl_Box::resize_step(long unsigned int tTime, double dEpsilon, bool bSvStress, bool bSvPos)
{
resize_coords <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, dEpsilon, d_pdX, d_pdY);
m_dLx += dEpsilon*m_dLx;
m_dLy += dEpsilon*m_dLy;
m_dPacking = calculate_packing();
cudaThreadSynchronize();
checkCudaError("Resizing box");
if (bSvStress)
{
cudaMemset((void *) d_pfSE, 0, 5*sizeof(float));
switch (m_ePotential)
{
case HARMONIC:
euler_est <HARMONIC, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est <HERTZIAN, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions, calculating stresses");
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
if (bSvPos)
{
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
}
cudaThreadSynchronize();
}
else
{
switch (m_ePotential)
{
case HARMONIC:
euler_est <HARMONIC, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est <HERTZIAN, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions");
}
switch (m_ePotential)
{
case HARMONIC:
heun_corr <HARMONIC> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea,
d_pdMOI, d_pdIsoC, d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY,
d_pdTempPhi, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
break;
case HERTZIAN:
heun_corr <HERTZIAN> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea,
d_pdMOI, d_pdIsoC, d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY,
d_pdTempPhi, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
}
if (bSvStress)
{
m_fP = 0.5 * (*m_pfPxx + *m_pfPyy);
fprintf(m_pOutfSE, "%lu %.7g %.7g %.7g %.7g %.7g %.7g\n",
tTime, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy, *m_pfPyx);
if (bSvPos)
save_positions(tTime);
}
cudaThreadSynchronize();
checkCudaError("Updating estimates, moving particles");
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
reconfigure_cells();
cudaThreadSynchronize();
if (*h_bNewNbrs)
find_neighbors();
}
void Spherocyl_Box::resize_box(long unsigned int nStart, double dEpsilon, double dFinalPacking, double dSvStressRate, double dSvPosRate)
{
assert(dEpsilon != 0);
m_dPacking = calculate_packing();
if (dFinalPacking > m_dPacking && dEpsilon > 0)
dEpsilon = -dEpsilon;
else if (dFinalPacking < m_dPacking && dEpsilon < 0)
dEpsilon = -dEpsilon;
dSvStressRate = int(dEpsilon/fabs(dEpsilon))*fabs(dSvStressRate);
dSvPosRate = int(dEpsilon/fabs(dEpsilon))*fabs(dSvPosRate);
printf("Beginning resize with packing fraction: %f\n", m_dPacking);
unsigned long int nTime = nStart;
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
if (nTime == 0) {
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
}
else {
m_pOutfSE = fopen(szPathSE, "r+");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
long unsigned int nTpos = 0;
while (nTpos != nTime) {
if (fgets(szBuf, 200, m_pOutfSE) != NULL) {
int nPos = strcspn(szBuf, " ");
char szTime[20];
strncpy(szTime, szBuf, nPos);
szTime[nPos] = '\0';
nTpos = atol(szTime);
}
else {
fprintf(stderr, "Reached end of file without finding start position");
exit(1);
}
}
}
sprintf(szBuf, "%s/rs_stress_energy.dat", m_szDataDir);
const char *szRsSE = szBuf;
FILE *pOutfRs;
if (nTime == 0) {
pOutfRs = fopen(szRsSE, "w");
if (pOutfRs == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
}
else {
pOutfRs = fopen(szRsSE, "r+");
if (pOutfRs == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
for (unsigned long int t = 0; t < nTime; t++) {
fgets(szBuf, 200, pOutfRs);
}
fgets(szBuf, 200, pOutfRs);
int nPos = strcspn(szBuf, " ");
char szPack[20];
strncpy(szPack, szBuf, nPos);
szPack[nPos] = '\0';
double dPack = atof(szPack);
/*
if (dPack - (1 + dEpsilon) * m_dPacking || dPack < (1 - dShrinkRate) * m_dPacking) {
fprintf(stderr, "System packing fraction %g does not match with time %lu", dPack, nTime);
exit(1);
}
*/
}
int nSaveStressInt = int(log(1+dSvStressRate)/log(1+dEpsilon));
int nSavePosInt = int(dSvPosRate/dSvStressRate+0.5)*nSaveStressInt;
printf("Starting resize with rate: %g\nStress save rate: %g (%d)\nPosition save rate: %g (%d)\n",
dEpsilon, dSvStressRate, nSaveStressInt, dSvPosRate, nSavePosInt);
while (dEpsilon*(m_dPacking - dFinalPacking) > dEpsilon*dEpsilon) {
bool bSavePos = (nTime % nSavePosInt == 0);
bool bSaveStress = (nTime % nSaveStressInt == 0);
//printf("Step %l\n", nTime);
//fflush(stdout);
resize_step(nTime, dEpsilon, bSaveStress, bSavePos);
if (bSaveStress) {
fprintf(pOutfRs, "%.6g %.7g %.7g %.7g %.7g %.7g %.7g\n",
m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy, *m_pfPyx);
}
if (bSavePos) {
fflush(stdout);
fflush(pOutfRs);
fflush(m_pOutfSE);
}
nTime += 1;
//if (nTime % nReorderInterval == 0)
//reorder_particles();
}
resize_step(nTime, dEpsilon, 1, 1);
fprintf(pOutfRs, "%.6g %.7g %.7g %.7g %.7g %.7g %.7g\n", m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy, *m_pfPyx);
fclose(m_pOutfSE);
fclose(pOutfRs);
}
/////////////////////////////////////////
//
// Relax to minimum
//
///////////////////////////////////////
void Spherocyl_Box::relax_step(long unsigned int tTime, bool bSvStress, bool bSvPos)
{
if (bSvStress)
{
cudaMemset((void *) d_pfSE, 0, 5*sizeof(float));
switch (m_ePotential)
{
case HARMONIC:
euler_est <HARMONIC, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est <HERTZIAN, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions, calculating stresses");
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
if (bSvPos)
{
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
}
cudaThreadSynchronize();
}
else
{
switch (m_ePotential)
{
case HARMONIC:
euler_est <HARMONIC, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est <HERTZIAN, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions");
}
switch (m_ePotential)
{
case HARMONIC:
heun_corr <HARMONIC> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea,
d_pdMOI, d_pdIsoC, d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY,
d_pdTempPhi, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
break;
case HERTZIAN:
heun_corr <HERTZIAN> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea,
d_pdMOI, d_pdIsoC, d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY,
d_pdTempPhi, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
}
if (bSvStress)
{
m_fP = 0.5 * (*m_pfPxx + *m_pfPyy);
fprintf(m_pOutfSE, "%lu %.7g %.7g %.7g %.7g %.7g %.7g\n",
tTime, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy, *m_pfPyx);
if (bSvPos)
save_positions(tTime);
}
cudaThreadSynchronize();
checkCudaError("Updating estimates, moving particles");
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
reconfigure_cells();
cudaThreadSynchronize();
if (*h_bNewNbrs)
find_neighbors();
}
void Spherocyl_Box::relax_box(long unsigned int nSteps, double dMaxStep, double dMinStep, int nSaveStressInt, int nSavePosInt)
{
unsigned long int nTime = 0;
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
if (nTime == 0) {
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
}
else {
m_pOutfSE = fopen(szPathSE, "r+");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
long unsigned int nTpos = 0;
while (nTpos != nTime) {
if (fgets(szBuf, 200, m_pOutfSE) != NULL) {
int nPos = strcspn(szBuf, " ");
char szTime[20];
strncpy(szTime, szBuf, nPos);
szTime[nPos] = '\0';
nTpos = atol(szTime);
}
else {
fprintf(stderr, "Reached end of file without finding start position");
exit(1);
}
}
}
m_dStep = dMaxStep;
printf("Starting relax with step size: %g\nStress save rate: %d\nPosition save rate: %d\n", m_dStep, nSaveStressInt, nSavePosInt);
while (nTime < nSteps) {
bool bSavePos = (nTime % nSavePosInt == 0);
bool bSaveStress = (nTime % nSaveStressInt == 0);
//printf("Step %l\n", nTime);
//fflush(stdout);
relax_step(nTime, bSaveStress, bSavePos);
if (bSavePos) {
fflush(stdout);
fflush(m_pOutfSE);
}
nTime += 1;
//if (nTime % nReorderInterval == 0)
//reorder_particles();
}
relax_step(nTime, 1, 1);
fclose(m_pOutfSE);
}
<file_sep>/src/cuda/calculate_stress_energy.cu
// -*- c++ -*-
/*
* calculate_stress_energy.cu
*
*
*/
#include <cuda.h>
#include "spherocyl_box.h"
#include "cudaErr.h"
#include <math.h>
#include <sm_20_atomic_functions.h>
#include <stdio.h>
using namespace std;
////////////////////////////////////////////////////////
// Calculates energy, stress tensor, forces:
// Returns returns energy, pxx, pyy and pxy to pn
// Returns
//
// The neighbor list pnNbrList has a list of possible contacts
// for each particle and is found in find_neighbors.cu
//
/////////////////////////////////////////////////////////
template<Potential ePot>
__global__ void calc_se(int nSpherocyls, int *pnNPP, int *pnNbrList,
double dLx, double dLy, double dGamma, double *pdX,
double *pdY, double *pdPhi, double *pdR, double *pdA,
double *pdFx, double *pdFy, double *pdFt, float *pfSE)
{
// Declare shared memory pointer, the size is determined at the kernel launch
extern __shared__ double sData[];
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
int offset = blockDim.x;
for (int i = 0; i < 5; i++)
sData[i*offset + thid] = 0.0;
__syncthreads(); // synchronizes every thread in the block before going on
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dFt = 0.0;
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dDeltaX = dX - pdX[nAdjPID];
double dDeltaY = dY - pdY[nAdjPID];
double dPhiB = pdPhi[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
if (dA == 0) {
double s = 0;
double t;
if (dB == 0) {
t = 0;
}
else {
double c = dB*dB;
double e = nxB * dDeltaX + nyB * dDeltaY;
t = fmin(fmax(e/c, -1), 1);
}
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx * dDVij / dDij;
double dPfy = dDy * dDVij / dDij;
double dCx = 0.5 * dDx - s*nxA;
double dCy = 0.5 * dDy - s*nyA;
dFx += dPfx;
dFy += dPfy;
dFt += s*nxA * dPfy - s*nyA * dPfx;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
else {
if (dB == 0) {
double t = 0;
double a = dA*dA;
double d = nxA *dDeltaX + nyA * dDeltaY;
double s = fmin(fmax(-d/a, -1), 1);
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx * dDVij / dDij;
double dPfy = dDy * dDVij / dDij;
double dCx = 0.5 * dDx - s*nxA;
double dCy = 0.5 * dDy - s*nyA;
dFx += dPfx;
dFy += dPfy;
dFt += s*nxA * dPfy - s*nyA * dPfx;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
else {
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double s, t;
if (delta <= dA*dB*1e-14) {
double s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
double s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
if (s1 == s2) {
s = s1;
t = fmin(fmax( -(s*b+e)/c, -1.0), 1.0);
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx * dDVij / dDij;
double dPfy = dDy * dDVij / dDij;
double dCx = 0.5 * dDx - s*nxA;
double dCy = 0.5 * dDy - s*nyA;
dFx += dPfx;
dFy += dPfy;
dFt += s*nxA * dPfy - s*nyA * dPfx;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
else {
double t1,t2;
if (b < 0) {
t1 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
t2 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
}
else {
t1 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
t2 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
}
double dDx1 = dDeltaX + s1*nxA - t1*nxB;
double dDy1 = dDeltaY + s1*nyA - t1*nyB;
double dDSqr1 = dDx1 * dDx1 + dDy1 * dDy1;
if (dDSqr1 < dSigma*dSigma)
{
double dDij = sqrt(dDSqr1);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = 0.5*(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = 0.5*(1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx1 * dDVij / dDij;
double dPfy = dDy1 * dDVij / dDij;
double dCx = 0.5 * dDx1 - s*nxA;
double dCy = 0.5 * dDy1 - s*nyA;
dFx += dPfx;
dFy += dPfy;
dFt += s*nxA * dPfy - s*nyA * dPfx;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
double dDx2 = dDeltaX + s2*nxA - t2*nxB;
double dDy2 = dDeltaY + s2*nyA - t2*nyB;
double dDSqr2 = dDx2 * dDx2 + dDy2 * dDy2;
if (dDSqr2 < dSigma*dSigma)
{
double dDij = sqrt(dDSqr2);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = 0.5*(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = 0.5*(1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx2 * dDVij / dDij;
double dPfy = dDy2 * dDVij / dDij;
double dCx = 0.5 * dDx2 - s*nxA;
double dCy = 0.5 * dDy2 - s*nyA;
dFx += dPfx;
dFy += dPfy;
dFt += s*nxA * dPfy - s*nyA * dPfx;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
else {
t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx * dDVij / dDij;
double dPfy = dDy * dDVij / dDij;
double dCx = 0.5 * dDx - s*nxA;
double dCy = 0.5 * dDy - s*nyA;
dFx += dPfx;
dFy += dPfy;
dFt += s*nxA * dPfy - s*nyA * dPfx;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
}
}
pdFx[nPID] = dFx;
pdFy[nPID] = dFy;
pdFt[nPID] = dFt;
nPID += nThreads;
}
__syncthreads();
// Now we do a parallel reduction sum to find the total number of contacts
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size, all threads perform two adds
int base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
base += 2*offset;
sData[base] += sData[base + stride];
if (thid < stride) {
base += 2*offset;
sData[base] += sData[base + stride];
}
stride /= 2; // stride is 1/4 block size, all threads perform 1 add
__syncthreads();
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
if (thid < stride) {
base += 4*offset;
sData[base] += sData[base+stride];
}
stride /= 2;
__syncthreads();
while (stride > 4)
{
if (thid < 5 * stride)
{
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 20)
{
base = thid % 4 + offset * (thid / 4);
sData[base] += sData[base + 4];
if (thid < 10)
{
base = thid % 2 + offset * (thid / 2);
sData[base] += sData[base + 2];
if (thid < 5)
{
sData[thid * offset] += sData[thid * offset + 1];
float tot = atomicAdd(pfSE+thid, (float)sData[thid*offset]);
}
}
}
}
void Spherocyl_Box::calculate_stress_energy()
{
cudaMemset((void*) d_pfSE, 0, 5*sizeof(float));
//dim3 grid(m_nGridSize);
//dim3 block(m_nBlockSize);
//size_t smem = m_nSM_CalcSE;
//printf("Configuration: %d x %d x %d\n", m_nGridSize, m_nBlockSize, m_nSM_CalcSE);
switch (m_ePotential)
{
case HARMONIC:
calc_se <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, d_pdFx, d_pdFy, d_pdFt, d_pfSE);
break;
case HERTZIAN:
calc_se <HERTZIAN> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, d_pdFx, d_pdFy, d_pdFt, d_pfSE);
}
cudaThreadSynchronize();
checkCudaError("Calculating stresses and energy");
}
__global__ void find_contact(int nSpherocyls, int *pnNPP, int *pnNbrList,
double dLx, double dLy, double dGamma, double *pdX, double *pdY,
double *pdPhi, double *pdR, double *pdA, int *nContacts)
{
// Declare shared memory pointer, the size is determined at the kernel launch
extern __shared__ int sCont[];
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
sCont[thid] = 0;
while (nPID < nSpherocyls)
{
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dDeltaX = dX - pdX[nAdjPID];
double dDeltaY = dY - pdY[nAdjPID];
double dPhiB = pdPhi[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double s, t;
if (delta == 0) {
double s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
double s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
s = (s1 + s2) / 2;
t = fmin(fmax( -(b*s+e)/c, -1.0), 1.0);
}
else {
t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
}
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
sCont[thid] += 1;
}
}
nPID += nThreads;
}
__syncthreads();
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2;
while (stride > 32)
{
if (thid < stride)
{
sCont[thid] += sCont[thid + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 32) //unroll end of loop
{
sCont[thid] += sCont[thid + 32];
if (thid < 16)
{
sCont[thid] += sCont[thid + 16];
if (thid < 8)
{
sCont[thid] += sCont[thid + 8];
if (thid < 4)
{
sCont[thid] += sCont[thid + 4];
if (thid < 2) {
sCont[thid] += sCont[thid + 2];
if (thid == 0) {
sCont[0] += sCont[1];
int nBContacts = atomicAdd(nContacts, sCont[0]);
}
}
}
}
}
}
}
bool Spherocyl_Box::check_for_contacts()
{
int *pnContacts;
cudaMalloc((void**) &pnContacts, sizeof(int));
cudaMemset((void*) pnContacts, 0, sizeof(int));
int nSMSize = m_nBlockSize * sizeof(int);
find_contact <<<m_nGridSize, m_nBlockSize, nSMSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, pnContacts);
cudaThreadSynchronize();
int nContacts;
cudaMemcpy(&nContacts, pnContacts, sizeof(int), cudaMemcpyHostToDevice);
cudaFree(pnContacts);
return (bool)nContacts;
}
////////////////////////////////////////////////////////////////////////////////////
#if GOLD_FUNCS == 1
void calc_se_gold(Potential ePot, int nGridDim, int nBlockDim, int sMemSize,
int nSpherocyls, int *pnNPP, int *pnNbrList, double dL,
double dGamma, double *pdX, double *pdY, double *pdR,
double *pdFx, double *pdFy, float *pfSE)
{
for (int b = 0; b < nGridDim; b++)
{
printf("Entering loop, block %d\n", b);
for (int thid = 0; thid < nBlockDim; thid++)
{
printf("Entering loop, thread %d\n", thid);
// Declare shared memory pointer, the size is determined at the kernel launch
double *sData = new double[sMemSize / sizeof(double)];
int nPID = thid + b * nBlockDim;
int nThreads = nBlockDim * nGridDim;
int offset = nBlockDim + 8; // +8 helps to avoid bank conflicts (I think)
for (int i = 0; i < 5; i++)
sData[thid + i*offset] = 0.0;
double dFx = 0.0;
double dFy = 0.0;
while (nPID < nSpherocyls)
{
double dX = pdX[nPID];
double dY = pdY[nPID];
double dR = pdR[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dDeltaX = dX - pdX[nAdjPID];
double dDeltaY = dY - pdY[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dL * ((dDeltaX < -0.5*dL) - (dDeltaX > 0.5*dL));
dDeltaY += dL * ((dDeltaY < -0.5*dL) - (dDeltaY > 0.5*dL));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
// Check if they overlap
double dRSqr = dDeltaX*dDeltaX + dDeltaY*dDeltaY;
if (dRSqr < dSigma*dSigma)
{
double dDelR = sqrt(dRSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDelR / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDelR / dSigma) * sqrt(1.0 - dDelR / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDeltaX * dDVij / dDelR;
double dPfy = dDeltaY * dDVij / dDelR;
dFx += dPfx;
dFy += dPfy;
if (nAdjPID > nPID)
{
sData[thid] += dDVij * dSigma * (1.0 - dDelR / dSigma) / (dAlpha * dL * dL);
sData[thid + offset] += dPfx * dDeltaX / (dL * dL);
sData[thid + 2*offset] += dPfy * dDeltaY / (dL * dL);
sData[thid + 3*offset] += dPfy * dDeltaX / (dL * dL);
sData[thid + 4*offset] += dPfx * dDeltaY / (dL * dL);
}
}
}
pdFx[nPID] = dFx;
pdFy[nPID] = dFy;
dFx = 0.0;
dFy = 0.0;
nPID += nThreads;
}
// Now we do a parallel reduction sum to find the total number of contacts
for (int s = 0; s < 5; s++)
pfSE[s] += sData[thid + s*offset];
}
}
}
void Spherocyl_Box::calculate_stress_energy_gold()
{
printf("Calculating streeses and energy");
cudaMemcpy(g_pnNPP, d_pnNPP, sizeof(int)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpy(g_pnNbrList, d_pnNbrList, sizeof(int)*m_nSpherocyls*m_nMaxNbrs, cudaMemcpyDeviceToHost);
cudaMemcpy(g_pdX, d_pdX, sizeof(double)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpy(g_pdY, d_pdY, sizeof(double)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpy(g_pdR, d_pdR, sizeof(double)*m_nSpherocyls, cudaMemcpyDeviceToHost);
for (int i = 0; i < 5; i++)
g_pfSE[i] = 0.0;
switch (m_ePotential)
{
case HARMONIC:
calc_se_gold (HARMONIC, m_nGridSize, m_nBlockSize, m_nSM_CalcSE,
m_nSpherocyls, g_pnNPP, g_pnNbrList, m_dL, m_dGamma,
g_pdX, g_pdY, g_pdR, g_pdFx, g_pdFy, g_pfSE);
break;
case HERTZIAN:
calc_se_gold (HERTZIAN, m_nGridSize, m_nBlockSize, m_nSM_CalcSE,
m_nSpherocyls, g_pnNPP, g_pnNbrList, m_dL, m_dGamma,
g_pdX, g_pdY, g_pdR, g_pdFx, g_pdFy, g_pfSE);
}
for (int p = 0; p < m_nSpherocyls; p++)
{
printf("Particle %d: (%g, %g)\n", p, g_pdFx[p], g_pdFy[p]);
}
printf("Energy: %g\n", g_pfSE[0]);
printf("Pxx: %g\n", g_pfSE[1]);
printf("Pyy: %g\n", g_pfSE[2]);
printf("P: %g\n", g_pfSE[1] + g_pfSE[2]);
printf("Pxy: %g\n", g_pfSE[3]);
}
#endif
<file_sep>/src/cuda/strain_dynamics_2.cu
// -*- c++ -*-
/*
* calculate_stress_energy.cu
*
*
*/
#include <cuda.h>
#include "spherocyl_box.h"
#include "cudaErr.h"
#include <math.h>
#include <sm_20_atomic_functions.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
///////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////
template<Potential ePot, bool bCalcStress>
__global__ void euler_est(int nSpherocyls, int *pnBlockNNbrs, int *pnBlockList, int *pnNPP,
int *pnNbrList, double dL, double dGamma, double *pdGlobX,
double *pdGlobY, double *pdGlobR, double *pdFx, double *pdFy,
float *pfSE, double dStep, double *pdTempX, double *pdTempY)
{
int thid = threadIdx.x;
int blid = blockIdx.x;
int nPID = thid + blid * blockDim.x;
int blsz = blockDim.x;
int nThreads = blsz * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
extern __shared__ double sData[];
int offset;
if (bCalcStress) {
offset = blsz + 8; // +8 should help to avoid a few bank conflicts
for (int i = 0; i < 4; i++)
sData[thid + i*offset] = 0.0;
__syncthreads(); // synchronizes every thread in the block before going on
}
else {
offset = 0;
}
double *pdR = &sData[4*offset];
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dX = pdGlobX[nPID];
double dY = pdGlobY[nPID];
double dR = pdGlobR[nPID];
int nBlockNbrs = pnBlockNNbrs[blid];
double *pdX = &pdR[nBlockNbrs];
double *pdY = &pdX[nBlockNbrs];
for (int t = thid; t < nBlockNbrs; t++) {
int nGlobID = pnBlockList[8*blid*blsz + t];
pdR[t] = pdGlobR[nGlobID];
pdX[t] = pdGlobX[nGlobID];
pdY[t] = pdGlobY[nGlobID];
}
__syncthreads();
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dDeltaX = dX - pdX[nAdjPID];
double dDeltaY = dY - pdY[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dL * ((dDeltaX < -0.5*dL) - (dDeltaX > 0.5*dL));
dDeltaY += dL * ((dDeltaY < -0.5*dL) - (dDeltaY > 0.5*dL));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
// Check if they overlap
double dRSqr = dDeltaX*dDeltaX + dDeltaY*dDeltaY;
if (dRSqr < dSigma*dSigma)
{
double dDelR = sqrt(dRSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDelR / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDelR / dSigma) * sqrt(1.0 - dDelR / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDeltaX * dDVij / dDelR;
double dPfy = dDeltaY * dDVij / dDelR;
dFx += dPfx;
dFy += dPfy;
if (bCalcStress)
{
if (nAdjPID > nPID)
{
sData[thid] += dDVij * dSigma * (1.0 - dDelR / dSigma) / (dAlpha * dL * dL);
sData[thid + offset] += dPfx * dDeltaX / (dL * dL);
sData[thid + 2*offset] += dPfy * dDeltaY / (dL * dL);
sData[thid + 3*offset] += dPfx * dDeltaY / (dL * dL);
}
}
}
}
pdFx[nPID] = dFx;
pdFy[nPID] = dFy;
pdTempX[nPID] = dX + dStep * (dFx - dGamma * dFy);
pdTempY[nPID] = dY + dStep * dFy;
blid += gridDim.x;
nPID += nThreads;
}
if (bCalcStress)
{
__syncthreads();
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size, all threads perform two adds
int base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
base += 2*offset;
sData[base] += sData[base + stride];
stride /= 2; // stride is 1/4 block size, all threads perform 1 add
__syncthreads();
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
stride /= 2;
__syncthreads();
while (stride > 8)
{
if (thid < 4 * stride)
{
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 32) //unroll end of loop
{
base = thid % 8 + offset * (thid / 8);
sData[base] += sData[base + 8];
if (thid < 16)
{
base = thid % 4 + offset * (thid / 4);
sData[base] += sData[base + 4];
if (thid < 8)
{
base = thid % 2 + offset * (thid / 2);
sData[base] += sData[base + 2];
if (thid < 4)
{
sData[thid * offset] += sData[thid * offset + 1];
float tot = atomicAdd(pfSE+thid, (float)sData[thid*offset]);
}
}
}
}
}
}
///////////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////////
template<Potential ePot>
__global__ void heun_corr(int nSpherocyls, int *pnBlockNNbrs, int *pnBlockList, int *pnNPP,
int *pnNbrList, double dL, double dGamma, double *pdGlobX, double *pdGlobY,
double *pdGlobR, double *pdFx, double *pdFy, double dStep, double dStrRate,
double *pdTempX, double *pdTempY, double *dLabX, double *dLabY,
double *pdXMoved, double *pdYMoved, double dEpsilon, int *bNewNbrs)
{
extern __shared__ double sData[];
int thid = threadIdx.x;
int blid = blockIdx.x;
int blsz = blockDim.x;
int nPID = thid + blid * blsz;
int nThreads = blsz * gridDim.x;
double *pdR = &sData[0];
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dX = pdTempX[nPID];
double dY = pdTempY[nPID];
double dR = pdGlobR[nPID];
int nBlockNbrs = pnBlockNNbrs[blid];
double *pdX = &pdR[nBlockNbrs];
double *pdY = &pdX[nBlockNbrs];
for (int t = thid; t < nBlockNbrs; t++) {
int nGlobID = pnBlockList[8*blid*blsz + t];
pdR[t] = pdGlobR[nGlobID];
pdX[t] = pdTempX[nGlobID];
pdY[t] = pdTempY[nGlobID];
}
__syncthreads();
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dDeltaX = dX - pdX[nAdjPID];
double dDeltaY = dY - pdY[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dL * ((dDeltaX < -0.5*dL) - (dDeltaX > 0.5*dL));
dDeltaY += dL * ((dDeltaY < -0.5*dL) - (dDeltaY > 0.5*dL));
// Transform from shear coordinates to lab coordinates
dDeltaX += (dGamma + dStep * dStrRate) * dDeltaY;
// Check if they overlap
double dRSqr = dDeltaX*dDeltaX + dDeltaY*dDeltaY;
if (dRSqr < dSigma*dSigma)
{
double dDelR = sqrt(dRSqr);
double dDVij;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDelR / dSigma) / dSigma;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDelR / dSigma) * sqrt(1.0 - dDelR / dSigma) / dSigma;
}
dFx += dDeltaX * dDVij / dDelR;
dFy += dDeltaY * dDVij / dDelR;
}
}
dFx -= (dGamma + dStep * dStrRate) * dFy;
double dFy0 = pdFy[nPID];
double dFx0 = pdFx[nPID] - dGamma * dFy0;
double dDx = 0.5 * dStep * (dFx0 + dFx);
double dDy = 0.5 * dStep * (dFy0 + dFy);
pdGlobX[nPID] += dDx;
pdGlobY[nPID] += dDy;
pdXMoved[nPID] += dDx;
pdYMoved[nPID] += dDy;
if (fabs(pdXMoved[nPID]) > dEpsilon || fabs(pdYMoved[nPID]) > dEpsilon)
*bNewNbrs = 1;
blid += gridDim.x;
nPID += nThreads;
}
}
////////////////////////////////////////////////////////////////////////
//
//
////////////////////////////////////////////////////////////////////
void Spherocyl_Box::strain_step(long unsigned int tTime, bool bSvStress, bool bSvPos)
{
if (bSvStress)
{
cudaMemset((void *) d_pfSE, 0, 4*sizeof(float));
switch (m_ePotential)
{
case HARMONIC:
euler_est <HARMONIC, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnBlockNNbrs, d_pnBlockList, d_pnNPP, d_pnNbrList, m_dL, m_dGamma,
d_pdX, d_pdY, d_pdR, d_pdFx, d_pdFy, d_pfSE, m_dStep, d_pdTempX, d_pdTempY);
break;
case HERTZIAN:
euler_est <HERTZIAN, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnBlockNNbrs, d_pnBlockList, d_pnNPP, d_pnNbrList, m_dL, m_dGamma,
d_pdX, d_pdY, d_pdR, d_pdFx, d_pdFy, d_pfSE, m_dStep, d_pdTempX, d_pdTempY);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions, calculating stresses");
cudaMemcpyAsync(h_pfSE, d_pfSE, 4*sizeof(float), cudaMemcpyDeviceToHost);
if (bSvPos)
{
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdLabX, d_pdLabX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdLabY, d_pdLabY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
}
cudaThreadSynchronize();
}
else
{
switch (m_ePotential)
{
case HARMONIC:
euler_est <HARMONIC, 0> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcF>>>
(m_nSpherocyls, d_pnBlockNNbrs, d_pnBlockList, d_pnNPP, d_pnNbrList, m_dL, m_dGamma,
d_pdX, d_pdY, d_pdR, d_pdFx, d_pdFy, d_pfSE, m_dStep, d_pdTempX, d_pdTempY);
break;
case HERTZIAN:
euler_est <HERTZIAN, 0> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcF>>>
(m_nSpherocyls, d_pnBlockNNbrs, d_pnBlockList, d_pnNPP, d_pnNbrList, m_dL, m_dGamma,
d_pdX, d_pdY, d_pdR, d_pdFx, d_pdFy, d_pfSE, m_dStep, d_pdTempX, d_pdTempY);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions");
}
switch (m_ePotential)
{
case HARMONIC:
heun_corr <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcF>>>
(m_nSpherocyls, d_pnBlockNNbrs, d_pnBlockList, d_pnNPP, d_pnNbrList, m_dL, m_dGamma,
d_pdX, d_pdY, d_pdR, d_pdFx, d_pdFy, m_dStep, m_dStrainRate, d_pdTempX, d_pdTempY,
d_pdLabX, d_pdLabY, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
break;
case HERTZIAN:
heun_corr <HERTZIAN> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcF>>>
(m_nSpherocyls, d_pnBlockNNbrs, d_pnBlockList, d_pnNPP, d_pnNbrList, m_dL, m_dGamma,
d_pdX, d_pdY, d_pdR, d_pdFx, d_pdFy, m_dStep, m_dStrainRate, d_pdTempX, d_pdTempY,
d_pdLabX, d_pdLabY, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
}
if (bSvStress)
{
m_fP = 0.5 * (*m_pfPxx + *m_pfPyy);
fprintf(m_pOutfSE, "%lu %.7g %.7g %.7g %.7g %.7g\n",
tTime, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy);
if (bSvPos)
save_positions(tTime);
}
cudaThreadSynchronize();
checkCudaError("Updating estimates, moving particles");
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
m_dGamma += m_dStep * m_dStrainRate;
m_dTotalGamma += m_dStep * m_dStrainRate;
cudaThreadSynchronize();
if (m_dGamma > 0.5)
set_back_gamma();
else if (*h_bNewNbrs)
find_neighbors();
}
/////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////
void Spherocyl_Box::save_positions(long unsigned int nTime)
{
char szBuf[150];
sprintf(szBuf, "%s/sd%010lu.dat", m_szDataDir, nTime);
const char *szFilePos = szBuf;
FILE *pOutfPos;
pOutfPos = fopen(szFilePos, "w");
if (pOutfPos == NULL)
{
fprintf(stderr, "Could not open file for writing");
exit(1);
}
int i = h_pnMemID[0];
fprintf(pOutfPos, "%d %f %.13f %f %.13g %.13g %.13g %.13g %.13g %.13g\n",
0, m_dPacking, m_dL, h_pdR[i], h_pdLabX[i], h_pdLabY[i], h_pdX[i], h_pdY[i], m_dGamma, m_dTotalGamma);
for (int p = 1; p < m_nSpherocyls; p++)
{
i = h_pnMemID[p];
fprintf(pOutfPos, "%d %f %.13f %f %.13g %.13g %.13g %.13g\n",
p, m_dPacking, m_dL, h_pdR[i], h_pdLabX[i], h_pdLabY[i], h_pdX[i], h_pdY[i]);
}
fclose(pOutfPos);
}
////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////
void Spherocyl_Box::run_strain(double dStartGamma, double dStopGamma, double dSvStressGamma, double dSvPosGamma)
{
if (m_dStrainRate == 0.0)
{
fprintf(stderr, "Cannot strain with zero strain rate\n");
exit(1);
}
printf("Beginnig strain run with strain rate: %g and step %g\n", m_dStrainRate, m_dStep);
fflush(stdout);
if (dSvStressGamma < m_dStrainRate * m_dStep)
dSvStressGamma = m_dStrainRate * m_dStep;
if (dSvPosGamma < m_dStrainRate)
dSvPosGamma = m_dStrainRate;
// +0.5 to cast to nearest integer rather than rounding down
unsigned long int nTime = (unsigned long)(dStartGamma / m_dStrainRate + 0.5);
unsigned long int nStop = (unsigned long)(dStopGamma / m_dStrainRate + 0.5);
unsigned int nIntStep = (unsigned int)(1.0 / m_dStep + 0.5);
unsigned int nSvStressInterval = (unsigned int)(dSvStressGamma / (m_dStrainRate * m_dStep) + 0.5);
unsigned int nSvPosInterval = (unsigned int)(dSvPosGamma / m_dStrainRate + 0.5);
unsigned long int nTotalStep = nTime * nIntStep;
//unsigned int nReorderInterval = (unsigned int)(1.0 / m_dStrainRate + 0.5);
printf("Strain run configured\n");
printf("Start: %lu, Stop: %lu, Int step: %lu\n", nTime, nStop, nIntStep);
printf("Stress save int: %lu, Pos save int: %lu\n", nSvStressInterval, nSvPosInterval);
fflush(stdout);
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
if (nTime == 0)
{
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL)
{
fprintf(stderr, "Could not open file for writing");
exit(1);
}
cudaMemcpy(d_pdLabX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpy(d_pdLabY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
}
else
{
m_pOutfSE = fopen(szPathSE, "r+");
if (m_pOutfSE == NULL)
{
fprintf(stderr, "Could not open file for writing");
exit(1);
}
int nTpos = 0;
while (nTpos != nTime)
{
if (fgets(szBuf, 200, m_pOutfSE) != NULL)
{
int nPos = strcspn(szBuf, " ");
char szTime[20];
strncpy(szTime, szBuf, nPos);
szTime[nPos] = '\0';
nTpos = atoi(szTime);
}
else
{
fprintf(stderr, "Reached end of file without finding start position");
exit(1);
}
}
}
// Run strain for specified number of steps
while (nTime < nStop)
{
bool bSvPos = (nTime % nSvPosInterval == 0);
if (bSvPos)
strain_step(nTime, 1, 1);
else
{
bool bSvStress = (nTotalStep % nSvStressInterval == 0);
strain_step(nTime, bSvStress, 0);
}
nTotalStep += 1;
for (unsigned int nI = 1; nI < nIntStep; nI++)
{
bool bSvStress = (nTotalStep % nSvStressInterval == 0);
strain_step(nTime, bSvStress, 0);
nTotalStep += 1;
}
nTime += 1;
//if (nTime % nReorderInterval == 0)
//reorder_particles();
}
// Save final configuration
calculate_stress_energy();
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdLabX, d_pdLabX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdLabY, d_pdLabY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pfSE, d_pfSE, 4*sizeof(float), cudaMemcpyDeviceToHost);
cudaThreadSynchronize();
m_fP = 0.5 * (*m_pfPxx + *m_pfPyy);
fprintf(m_pOutfSE, "%lu %.7g %.7g %.7g %.7g %.7g\n",
nTime, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy);
save_positions(nTime);
fclose(m_pOutfSE);
}
void Spherocyl_Box::run_strain(long unsigned int nSteps)
{
// Run strain for specified number of steps
long unsigned int nTime = 0;
while (nTime < nSteps)
{
strain_step(nTime, 0, 0);
nTime += 1;
}
}
<file_sep>/src/cuda/data_primitives.h
/* data_primitives.h
*
* exclusive_scan (prefix sum) :
*
*
*
*/
#ifndef DATA_PRIMITIVES_H
#define DATA_PRIMITIVES_H
// Arrays pnIn and pnOut are device arrays
void exclusive_scan(int *pnIn, int *pnOut, int nSize);
void ordered_array(int *pnArray, int nSize, int gridSize = 0, int blockSize = 0);
#endif
<file_sep>/src/cuda/make.sh
#!/bin/bash
export COMPUTE_PROFILE=1
export COMPUTE_PROFILE_LOG=/home/tmarscha/sph_cyl/output/cuda_profile.log
export COMPUTE_PROFILE_CONFIG=/home/tmarscha/sph_cyl/exe/.cuda_profile_config
make<file_sep>/src/cuda/main_2point_ycompress.cpp
/*
*
*
*/
#include "spherocyl_box.h"
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <iostream>
#include "file_input.h"
#include <string>
using namespace std;
const double D_PI = 3.14159265358979;
int int_input(int argc, char* argv[], int argn, char description[] = "")
{
if (argc > argn) {
int input = atoi(argv[argn]);
cout << description << ": " << input << endl;
return input;
}
else {
int input;
cout << description << ": ";
cin >> input;
return input;
}
}
double float_input(int argc, char* argv[], int argn, char description[] = "")
{
if (argc > argn) {
double input = atof(argv[argn]);
cout << description << ": " << input << endl;
return input;
}
else {
double input;
cout << description << ": ";
cin >> input;
return input;
}
}
string string_input(int argc, char* argv[], int argn, char description[] = "")
{
if (argc > argn) {
string input = argv[argn];
cout << description << ": " << input << endl;
return input;
}
else {
string input;
cout << description << ": ";
cin >> input;
return input;
}
}
int main(int argc, char* argv[])
{
int argn = 0;
string strFile = string_input(argc, argv, ++argn, "Data file ('r' for random)");
const char* szFile = strFile.c_str();
cout << strFile << endl;
string strDir = string_input(argc, argv, ++argn, "Output data directory");
const char* szDir = strDir.c_str();
cout << strDir << endl;
int nSpherocyls = int_input(argc, argv, ++argn, "Number of particles");
cout << nSpherocyls << endl;
double dResizeRate = float_input(argc, argv, ++argn, "Resize rate (epsilon)");
cout << dResizeRate << endl;
double dStep = float_input(argc, argv, ++argn, "Integration step size");
cout << dStep << endl;
double dTargetEnergy = float_input(argc, argv, ++argn, "Target Energy");
cout << dTargetEnergy << endl;
double dPosSaveRate = float_input(argc, argv, ++argn, "Position data save rate");
cout << dPosSaveRate << endl;
double dStressSaveRate = float_input(argc, argv, ++argn, "Stress data save rate");
cout << dStressSaveRate << endl;
double dDR = float_input(argc, argv, ++argn, "Cell padding");
cout << dDR << endl;
if (fabs(dStressSaveRate) < fabs(dResizeRate)) {
dStressSaveRate = dResizeRate;
}
if (fabs(dPosSaveRate) < fabs(dStressSaveRate)) {
dPosSaveRate = dStressSaveRate;
}
double dL;
double dLx;
double dLy = 0;
double *dX = new double[nSpherocyls];
double *dY = new double[nSpherocyls];
double *dPhi = new double[nSpherocyls];
double *dRad = new double[nSpherocyls];
double *dA = new double[nSpherocyls];
double dRMax = 0.0;
double dAMax = 0.0;
double dAspect = 4;
double dBidispersity = 1;
double dGamma;
double dTotalGamma;
long unsigned int nTime = 0;
double dPacking;
initialConfig config;
Config sConfig;
if (strFile == "r")
{
double dPacking = float_input(argc, argv, ++argn, "Packing Fraction");
cout << dPacking << endl;
dAspect = float_input(argc, argv, ++argn, "Aspect ratio (i.e. A/R or 2A/D):");
cout << dAspect << endl;
dBidispersity = float_input(argc, argv, ++argn, "Bidispersity ratio: (1 for monodisperse):");
cout << dBidispersity << endl;
if (argc > argn) {
config = (initialConfig)int_input(argc, argv, ++argn, "Initial configuration (0: random, 1: random-uniform, 2: random-aligned, 3: zero-energy, 4: zero-energy-uniform, 5: zero-energy-aligned, 6: grid, 7: grid-uniform, 8: grid-aligned, 9: other-specified)");
if (config == 9) {
sConfig.type = (configType)int_input(argc, argv, ++argn, "Configuration type (0: random, 1: grid)");
sConfig.minAngle = float_input(argc, argv, ++argn, "Minimum angle");
sConfig.maxAngle = float_input(argc, argv, ++argn, "Maximum angle");
sConfig.overlap = float_input(argc, argv, ++argn, "Allowed overlap (min 0, max 1)");
sConfig.angleType = (configType)int_input(argc, argv, ++argn, "Angle Distribution (0: random, 1: uniform");
}
else {
if (config < 6)
sConfig.type = RANDOM;
else
sConfig.type = GRID;
sConfig.minAngle = 0;
if (config % 3 == 2)
sConfig.maxAngle = 0;
else
sConfig.maxAngle = 1;
if (config >= 3 && config < 6)
sConfig.overlap = 0;
else
sConfig.overlap = 1;
if (config %3 == 0)
sConfig.angleType = RANDOM;
else
sConfig.angleType = GRID;
}
}
else {
sConfig.type = RANDOM;
sConfig.minAngle = 0;
sConfig.maxAngle = D_PI;
sConfig.overlap = 1;
}
double dR = 0.5;
double dA = dAspect*dR;
double dArea = 0.5*nSpherocyls*(1+dBidispersity*dBidispersity)*(4*dA + D_PI * dR)*dR;
dL = sqrt(dArea / dPacking);
cout << "Box length L: " << dL << endl;
dRMax = dBidispersity*dR;
dAMax = dBidispersity*dA;
/*
srand(time(0) + static_cast<int>(1000*dPacking));
for (int p = 0; p < nSpherocyls; p++)
{
dX[p] = dL * static_cast<double>(rand() % 1000000000) / 1000000000.;
dY[p] = dL * static_cast<double>(rand() % 1000000000) / 1000000000.;
dPhi[p] = 2.*pi * static_cast<double>(rand() % 1000000000) / 1000000000.;
dRad[p] = dR;
dA[p] = dA.;
}
*/
dGamma = 0.;
dTotalGamma = 0.;
}
else
{
cout << "Loading file: " << strFile << endl;
DatFileInput cData(szFile, 1);
int nHeadLen = cData.getHeadLen();
if (cData.getHeadInt(0) != nSpherocyls) {
cout << "Warning: Number of particles in data file may not match requested number" << endl;
cerr << "Warning: Number of particles in data file may not match requested number" << endl;
}
cData.getColumn(dX, 0);
cData.getColumn(dY, 1);
cData.getColumn(dPhi, 2);
cData.getColumn(dRad, 3);
cData.getColumn(dA, 4);
if (nHeadLen == 8) {
dLx = cData.getHeadFloat(1);
dLy = cData.getHeadFloat(2);
dPacking = cData.getHeadFloat(3);
dGamma = cData.getHeadFloat(4);
dTotalGamma = cData.getHeadFloat(5);
}
else {
dL = cData.getHeadFloat(1);
dPacking = cData.getHeadFloat(2);
dGamma = cData.getHeadFloat(3);
dTotalGamma = cData.getHeadFloat(4);
}
int nFileLen = strFile.length();
string strNum = strFile.substr(nFileLen-14, 10);
nTime = atol(strNum.c_str());
cout << "Time: " << strNum << " " << nTime << endl;
for (int p = 0; p < nSpherocyls; p++) {
if (dA[p] > dAMax) { dAMax = dA[p]; }
if (dRad[p] > dRMax) { dRMax = dRad[p]; }
}
}
int tStart = time(0);
Spherocyl_Box *cSpherocyls;
if (strFile == "r") {
cout << "Initializing box of length " << dL << " with " << nSpherocyls << " particles.";
cSpherocyls = new Spherocyl_Box(nSpherocyls, dL, dAspect, dBidispersity, sConfig, dDR);
}
else {
if (dLy == 0) {
cout << "Initializing box from file of length " << dL << " with " << nSpherocyls << " particles." << endl;
cSpherocyls = new Spherocyl_Box(nSpherocyls, dL, dX, dY, dPhi, dRad, dA, dDR);
}
else {
cout << "Initializing box from file of length " << dLx << " x " << dLy << " with " << nSpherocyls << " particles." << endl;
cSpherocyls = new Spherocyl_Box(nSpherocyls, dLx, dLy, dX, dY, dPhi, dRad, dA, dDR);
}
}
cout << "Spherocyls initialized" << endl;
cSpherocyls->set_gamma(dGamma);
cSpherocyls->set_total_gamma(dTotalGamma);
cSpherocyls->set_strain(0);
cSpherocyls->set_step(dStep);
cSpherocyls->set_data_dir(szDir);
cout << "Configuration set" << endl;
//cSpherocyls.place_random_spherocyls();
//cout << "Random spherocyls placed" << endl;
//cSpherocyls.reorder_particles();
//cSpherocyls.reset_IDs();
//cout << "Spherocyls reordered" << endl;
cSpherocyls->find_neighbors();
cout << "Neighbor lists created" << endl;
cSpherocyls->calculate_stress_energy_2p();
cout << "Stresses calculated" << endl;
cSpherocyls->display(1,1,1,1);
cSpherocyls->y_compress_energy_2p(dTargetEnergy, dResizeRate);
cSpherocyls->calculate_stress_energy_2p();
cSpherocyls->display(1,0,0,1);
//cSpherocyls->save_positions_bin(9999999998);
//cSpherocyls->cjpr_relax(1e-12, 10, 1000000, 1.0);
//cSpherocyls->save_positions(9999999999);
//cSpherocyls->save_positions_bin(9999999999);
//cSpherocyls->calculate_stress_energy();
//cSpherocyls->display(1,0,0,1);
int tStop = time(0);
cout << "\nRun Time: " << tStop - tStart << endl;
delete[] dX; delete[] dY; delete[] dPhi;
delete[] dRad; delete[] dA;
return 0;
}
<file_sep>/src/cpp/spherocyl_box.cpp
#include <vector>
#include <string>
#include <assert.h>
#include "spherocyl_box.h"
#include <iostream>
#include <math.h>
#include <fstream>
#include <cstdlib>
#include <time.h>
#include <limits>
const double D_PI = 3.14159265358979;
using std::cout;
using std::endl;
void SpherocylBox::set_defaults()
{
m_dLx = 0.0;
m_dLy = 0.0;
m_dGamma = 0.0;
m_dGammaTotal = 0.0;
m_dStrainRate = 0.0;
m_dResizeRate = 0.0;
m_dStep = 0.05;
m_dPosSaveStep = 0.01;
m_dSESaveStep = 1e-5;
m_dPacking = 0.0;
m_dAmax = 0.0;
m_dRmax = 0.0;
m_dPadding = 0.0;
m_dMaxMoved = 0.0;
m_dEnergy = 0.0;
m_dPxx = 0.0;
m_dPyy = 0.0;
m_dPxy = 0.0;
m_psParticles = 0;
m_psTempParticles = 0;
m_nParticles = 0;
m_nCellCols = 1;
m_nCellRows = 1;
m_nCells = 1;
m_pvCells = new std::vector<int>[1];
m_dCellWidth = 0;
m_dCellHeight = 0;
m_pnCellNeighbors = 0;
m_pvNeighbors = 0;
m_strOutputDir = ".";
m_strSEOutput = "sp_se.dat";
}
SpherocylBox::SpherocylBox()
{
set_defaults();
}
SpherocylBox::SpherocylBox(double dL, int nParticles)
{
set_defaults();
m_dLx = dL;
m_dLy = dL;
m_nParticles = nParticles;
delete[] m_psParticles;
m_psParticles = new Spherocyl[nParticles];
delete[] m_psTempParticles;
m_psTempParticles = new Spherocyl[nParticles];
delete[] m_pvNeighbors;
m_pvNeighbors = new std::vector<int>[nParticles];
}
SpherocylBox::SpherocylBox(double dL, int nParticles, double dPadding)
{
set_defaults();
m_dLx = dL;
m_dLy = dL;
m_nParticles = nParticles;
m_dPadding = dPadding;
delete[] m_psParticles;
m_psParticles = new Spherocyl[nParticles];
delete[] m_psTempParticles;
m_psTempParticles = new Spherocyl[nParticles];
delete[] m_pvNeighbors;
m_pvNeighbors = new std::vector<int>[nParticles];
}
SpherocylBox::SpherocylBox(double dL, int nParticles, double *pdX, double *pdY, double *pdPhi, double dA, double dR)
{
set_defaults();
m_dLx = dL;
m_dLy = dL;
m_nParticles = nParticles;
delete[] m_psParticles;
m_psParticles = new Spherocyl[nParticles];
delete[] m_psTempParticles;
m_psTempParticles = new Spherocyl[nParticles];
delete[] m_pvNeighbors;
m_pvNeighbors = new std::vector<int>[nParticles];
m_dAmax = dA;
m_dRmax = dR;
for (int p = 0; p < nParticles; p++) {
set_particle(p, pdX[p], pdY[p], pdPhi[p], dA, dR);
}
m_dPacking = calculate_packing_fraction();
m_dPadding = 0.0;
configure_cells();
find_neighbors();
}
SpherocylBox::SpherocylBox(double dL, int nParticles, double *pdX, double *pdY, double *pdPhi, double dA, double dR, double dPadding)
{
set_defaults();
m_dLx = dL;
m_dLy = dL;
m_nParticles = nParticles;
delete[] m_psParticles;
m_psParticles = new Spherocyl[nParticles];
delete[] m_psTempParticles;
m_psTempParticles = new Spherocyl[nParticles];
delete[] m_pvNeighbors;
m_pvNeighbors = new std::vector<int>[nParticles];
m_dAmax = dA;
m_dRmax = dR;
for (int p = 0; p < nParticles; p++) {
set_particle(p, pdX[p], pdY[p], pdPhi[p], dA, dR);
}
m_dPacking = calculate_packing_fraction();
m_dPadding = dPadding;
configure_cells();
find_neighbors();
}
SpherocylBox::SpherocylBox(double dL, int nParticles, double *pdX, double *pdY, double *pdPhi, double *pdA, double *pdR)
{
set_defaults();
m_dLx = dL;
m_dLy = dL;
m_nParticles = nParticles;
delete[] m_psParticles;
m_psParticles = new Spherocyl[nParticles];
delete[] m_psTempParticles;
m_psTempParticles = new Spherocyl[nParticles];
delete[] m_pvNeighbors;
m_pvNeighbors = new std::vector<int>[nParticles];
m_dAmax = 0.0;
m_dRmax = 0.0;
for (int p = 0; p < nParticles; p++) {
set_particle(p, pdX[p], pdY[p], pdPhi[p], pdA[p], pdR[p]);
}
m_dPacking = calculate_packing_fraction();
m_dPadding = 0.0;
configure_cells();
find_neighbors();
}
SpherocylBox::SpherocylBox(double dL, int nParticles, double *pdX, double *pdY, double *pdPhi, double *pdA, double *pdR, double dPadding)
{
set_defaults();
m_dLx = dL;
m_dLy = dL;
m_nParticles = nParticles;
delete[] m_psParticles;
m_psParticles = new Spherocyl[nParticles];
delete[] m_psTempParticles;
m_psTempParticles = new Spherocyl[nParticles];
delete[] m_pvNeighbors;
m_pvNeighbors = new std::vector<int>[nParticles];
m_dAmax = 0.0;
m_dRmax = 0.0;
for (int p = 0; p < nParticles; p++) {
set_particle(p, pdX[p], pdY[p], pdPhi[p], pdA[p], pdR[p]);
}
m_dPacking = calculate_packing_fraction();
m_dPadding = dPadding;
configure_cells();
find_neighbors();
}
SpherocylBox::~SpherocylBox()
{
if (m_nCells > 1) {
for (int c = 0; c < m_nCells; c++) {
delete[] m_pnCellNeighbors[c];
}
}
delete[] m_pnCellNeighbors;
delete[] m_psParticles;
delete[] m_psTempParticles;
delete[] m_pvCells;
delete[] m_pvNeighbors;
}
void SpherocylBox::set_particle(int p, double dX, double dY, double dPhi, double dA, double dR)
{
assert(p < m_nParticles);
assert(dA >= 0.0);
assert(dR > 0.0);
m_psParticles[p].m_dX = dX;
m_psParticles[p].m_dY = dY;
m_psParticles[p].m_dPhi = dPhi;
m_psParticles[p].m_dA = dA;
m_psParticles[p].m_dR = dR;
double dAlpha = dA/dR;
double dC = (3*D_PI + 24*dAlpha + 6*D_PI*dAlpha*dAlpha + 8*dAlpha*dAlpha*dAlpha);
double dArea = dR*(D_PI*dR + 4*dA);
m_psParticles[p].m_dI = dR*dR*dR*dR*dC/(6*dArea);
m_psParticles[p].m_dRC = (8*dAlpha + 6*D_PI*dAlpha*dAlpha + 8*dAlpha*dAlpha*dAlpha)/dC;
while (m_psParticles[p].m_dX > m_dLx)
m_psParticles[p].m_dX -= m_dLx;
while (m_psParticles[p].m_dX < 0.0)
m_psParticles[p].m_dX += m_dLx;
while (m_psParticles[p].m_dY > m_dLy)
m_psParticles[p].m_dY -= m_dLy;
while (m_psParticles[p].m_dY < 0.0)
m_psParticles[p].m_dY += m_dLy;
while (m_psParticles[p].m_dPhi > D_PI)
m_psParticles[p].m_dPhi -= 2*D_PI;
while (m_psParticles[p].m_dPhi < -D_PI)
m_psParticles[p].m_dPhi += 2*D_PI;
if (m_psParticles[p].m_dA > m_dAmax)
m_dAmax = m_psParticles[p].m_dA;
if (m_psParticles[p].m_dR > m_dRmax)
m_dRmax = m_psParticles[p].m_dR;
}
void SpherocylBox::configure_cells()
{
assert(m_dRmax > 0.0);
assert(m_dAmax >= 0.0);
double dWmin = 2.24 * (m_dRmax + m_dAmax) + m_dPadding;
double dHmin = 2 * (m_dRmax + m_dAmax) + m_dPadding;
m_nCellRows = std::max(static_cast<int>(m_dLy / dHmin), 1);
m_nCellCols = std::max(static_cast<int>(m_dLx / dWmin), 1);
m_nCells = m_nCellRows * m_nCellCols;
cout << "Cells: " << m_nCells << ": " << m_nCellRows << " x " << m_nCellCols << endl;
m_dCellWidth = m_dLx / m_nCellCols;
m_dCellHeight = m_dLy / m_nCellRows;
cout << "Cell dimensions: " << m_dCellWidth << " x " << m_dCellHeight << endl;
if (m_dPadding == 0)
m_dPadding = std::max(m_dCellWidth - dWmin, m_dCellHeight - dHmin);
delete[] m_pvCells;
m_pvCells = new std::vector<int>[m_nCells];
delete[] m_pnCellNeighbors;
m_pnCellNeighbors = new int*[m_nCells];
for (int c = 0; c < m_nCells; c++) {
m_pnCellNeighbors[c] = new int[8];
int nRow = c / m_nCellCols;
int nCol = c % m_nCellCols;
int nAdjCol1 = (nCol + 1) % m_nCellCols;
int nAdjCol2 = (m_nCellCols + nCol - 1) % m_nCellCols;
m_pnCellNeighbors[c][0] = nRow * m_nCellCols + nAdjCol1;
m_pnCellNeighbors[c][1] = nRow * m_nCellCols + nAdjCol2;
int nAdjRow = (nRow + 1) % m_nCellRows;
m_pnCellNeighbors[c][2] = nAdjRow * m_nCellCols + nCol;
m_pnCellNeighbors[c][3] = nAdjRow * m_nCellCols + nAdjCol1;
m_pnCellNeighbors[c][4] = nAdjRow * m_nCellCols + nAdjCol2;
nAdjRow = (m_nCellRows + nRow - 1) % m_nCellRows;
m_pnCellNeighbors[c][5] = nAdjRow * m_nCellCols + nCol;
m_pnCellNeighbors[c][6] = nAdjRow * m_nCellCols + nAdjCol1;
m_pnCellNeighbors[c][7] = nAdjRow * m_nCellCols + nAdjCol2;
}
}
void SpherocylBox::find_cells()
{
//cout << "finding cells" << endl;
for (int c = 0; c < m_nCells; c++) {
m_pvCells[c].clear();
}
//cout << "cells cleared" << endl;
for (int p = 0; p < m_nParticles; p++) {
//cout << m_psParticles[p].m_dX << " " << m_psParticles[p].m_dY << endl;
while (m_psParticles[p].m_dX > m_dLx)
m_psParticles[p].m_dX -= m_dLx;
while (m_psParticles[p].m_dX < 0.0)
m_psParticles[p].m_dX += m_dLx;
while (m_psParticles[p].m_dY > m_dLy)
m_psParticles[p].m_dY -= m_dLy;
while (m_psParticles[p].m_dY < 0.0)
m_psParticles[p].m_dY += m_dLy;
while (m_psParticles[p].m_dPhi > D_PI)
m_psParticles[p].m_dPhi -= 2*D_PI;
while (m_psParticles[p].m_dPhi < -D_PI)
m_psParticles[p].m_dPhi += 2*D_PI;
//cout << m_psParticles[p].m_dX << " " << m_psParticles[p].m_dY << endl;
int nCol = (int)(m_psParticles[p].m_dX / m_dCellWidth);
int nRow = (int)(m_psParticles[p].m_dY / m_dCellHeight);
int nCellID = nCol + nRow * m_nCellCols;
//cout << "cell id " << nCellID << " (" << m_nCells << "): " << nRow << " " << nCol << endl;
m_psParticles[p].m_nCell = nCellID;
m_pvCells[nCellID].push_back(p);
}
//cout << " done" << endl;
}
bool SpherocylBox::check_neighbors(int p, int q)
{
double dSigma = m_psParticles[p].m_dR + m_psParticles[p].m_dA + m_psParticles[q].m_dR + m_psParticles[q].m_dA;
double dY = m_psParticles[p].m_dY - m_psParticles[q].m_dY;
dY += m_dLy * ((dY < -0.5 * m_dLy) - (dY > 0.5 * m_dLy));
if (fabs(dY) < dSigma + m_dPadding) {
double dX = m_psParticles[p].m_dX - m_psParticles[q].m_dX;
dX += m_dLx * ((dX < -0.5 * m_dLx) - (dX > 0.5 * m_dLx));
double dXprime = dX + 0.5 * dY; // dX at maximum value of gamma
dX += m_dGamma * dY;
if (fabs(dX) < dSigma + m_dPadding || fabs(dXprime) < dSigma + m_dPadding) {
return true;
}
}
return false;
}
void SpherocylBox::find_neighbors()
{
//cout << " finding neighbors" << endl;
find_cells();
for (int p = 0; p < m_nParticles; p++) {
m_pvNeighbors[p].clear();
m_psParticles[p].m_dXMoved = 0.0;
m_psParticles[p].m_dYMoved = 0.0;
}
for (int p = 0; p < m_nParticles-1; p++) {
int nCellID = m_psParticles[p].m_nCell;
for (int np = 0; np < m_pvCells[nCellID].size(); np++) {
int q = m_pvCells[nCellID][np];
if (q > p) {
if (check_neighbors(p, q)) {
m_pvNeighbors[p].push_back(q);
//m_pvNeighbors[q].puch_back(p);
}
}
}
for (int nc = 0; nc < 8; nc++) {
int nNCellID = m_pnCellNeighbors[nCellID][nc];
for (int np = 0; np < m_pvCells[nNCellID].size(); np++) {
int q = m_pvCells[nNCellID][np];
if (q > p) {
if (check_neighbors(p, q)) {
m_pvNeighbors[p].push_back(q);
//m_pvNeighbors[q].push_back(p);
}
}
}
}
}
//cout << "done" << endl;
}
double SpherocylBox::calculate_packing_fraction()
{
double dArea = m_dLx * m_dLy;
double dFilled = 0.0;
for (int p = 0; p < m_nParticles; p++) {
Spherocyl *s = &m_psParticles[p];
dFilled += (D_PI*(s->m_dR) + 4.0*(s->m_dA))*(s->m_dR);
}
return dFilled / dArea;
}
void SpherocylBox::display(bool bParticles, bool bCells)
{
cout << "Dimensions: " << m_dLx << " x " << m_dLy << endl;
cout << "Particles: " << m_nParticles << endl;
cout << "Packing fraction: " << m_dPacking << endl;
cout << "Gamma: " << m_dGamma << " (" << m_dGammaTotal << ")" << endl;
cout << "Strain rate: " << m_dStrainRate << endl;
cout << "Integration step size: " << m_dStep << endl;
cout << "\nEnergy: " << m_dEnergy << endl;
cout << "Pxx: " << m_dPxx << endl;
cout << "Pyy: " << m_dPyy << endl;
cout << "Pxy: " << m_dPxy << endl;
if (bParticles) {
cout << "\nParticles: (x, y, phi), (A, R), (I, RC) - (Fx, Fy, Tau) - (X_moved, Y_moved)" << endl;
for (int p = 0; p < m_nParticles; p++) {
Spherocyl *s = &m_psParticles[p];
cout << p << ": (" << s->m_dX << ", " << s->m_dY << ", " << s->m_dPhi << "), (" << s->m_dA
<< ", " << s->m_dR << "), (" << s->m_dI << ", " << s->m_dRC << ") - (" << s->m_dFx << ", "
<< s->m_dFy << ", " << s->m_dTau << ") - (" << s->m_dXMoved << ", " << s->m_dYMoved << ")\n";
cout << "Cell: " << s->m_nCell << " Neighbors: ";
for (int np = 0; np < m_pvNeighbors[p].size(); np++) {
cout << m_pvNeighbors[p][np] << " ";
}
cout << endl;
}
}
if (bCells) {
cout << "\nCells:" << endl;
for (int c = 0; c < m_nCells; c++) {
cout << c << ":\t";
for (int cp = 0; cp < m_pvCells[c].size(); cp++) {
cout << m_pvCells[c][cp] << " ";
}
cout << endl << "Neighbors: ";
for (int nc = 0; nc < 8; nc++) {
cout << m_pnCellNeighbors[c][nc] << " ";
}
cout << endl;
}
}
}
void SpherocylBox::save_positions(std::string strFile)
{
std::string strPath = m_strOutputDir + "/" + strFile;
std::ofstream outf(strPath.c_str());
Spherocyl *s = m_psParticles;
outf.precision(14);
outf << m_nParticles << " " << m_dLx << " " << m_dPacking << " " << m_dGamma << " "
<< m_dGammaTotal << " " << m_dStrainRate << " " << m_dStep << endl;
for (int p = 0; p < m_nParticles; p++) {
s = m_psParticles+p;
outf << s->m_dX << " " << s->m_dY << " " << s->m_dPhi << " " << s->m_dR << " " << s->m_dA << endl;
}
outf.close();
}
void SpherocylBox::calc_se_force_pair(int p, int q)
{
double dDeltaX = m_psParticles[p].m_dX - m_psParticles[q].m_dX;
double dDeltaY = m_psParticles[p].m_dY - m_psParticles[q].m_dY;
double dPhiP = m_psParticles[p].m_dPhi;
double dPhiQ = m_psParticles[q].m_dPhi;
double dSigma = m_psParticles[p].m_dR + m_psParticles[q].m_dR;
double dAP = m_psParticles[p].m_dA;
double dAQ = m_psParticles[q].m_dA;
// Make sure we take the closest distance considering boundary conditions
dDeltaX += m_dLx * ((dDeltaX < -0.5*m_dLx) - (dDeltaX > 0.5*m_dLx));
dDeltaY += m_dLy * ((dDeltaY < -0.5*m_dLy) - (dDeltaY > 0.5*m_dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += m_dGamma * dDeltaY;
double nxA = dAP * cos(dPhiP);
double nyA = dAP * sin(dPhiP);
double nxB = dAQ * cos(dPhiQ);
double nyB = dAQ * sin(dPhiQ);
double a = dAP * dAP;
double b = -(nxA * nxB + nyA * nyB);
double c = dAQ * dAQ;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
double s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij = (1.0 - dDij / dSigma) / dSigma;
double dFx = dDx * dDVij / dDij;
double dFy = dDy * dDVij / dDij;
double dTauP = s*nxA * dFy - s*nyA * dFx;
double dTauQ = t*nyB * dFx - t*nxB * dFy;
//double dMoiP = 4.0 * dAP * dAP / 12.0;
//double dMoiQ = 4.0 * dAQ * dAQ / 12.0;
m_psParticles[p].m_dFx += dFx;
m_psParticles[p].m_dFy += dFy;
m_psParticles[p].m_dTau += dTauP;
m_psParticles[q].m_dFx -= dFx;
m_psParticles[q].m_dFy -= dFy;
m_psParticles[q].m_dTau += dTauQ;
double dCxA = s*nxA - 0.5*dDx;
double dCyA = s*nyA - 0.5*dDy;
double dCxB = t*nxB + 0.5*dDx;
double dCyB = t*nxB + 0.5*dDy;
m_dEnergy += dDVij * dSigma * (1.0 - dDij / dSigma) / (2.0 * m_nParticles);
m_dPxx += dFx * dCxA / (m_dLx * m_dLy);
m_dPxx -= dFx * dCxB / (m_dLx * m_dLy);
m_dPyy += dFy * dCyA / (m_dLx * m_dLy);
m_dPyy -= dFy * dCyB / (m_dLx * m_dLy);
m_dPxy += dFy * dCxA / (m_dLx * m_dLy);
m_dPxx -= dFy * dCxB / (m_dLx * m_dLy);
m_dPyx += dFx * dCyA / (m_dLx * m_dLy);
m_dPyx -= dFx * dCyB / (m_dLx * m_dLy);
//cout << "contact between particles " << p << " and " << q << " with forces: ";
//cout << dFx << " " << dFy << " " << dTauP / dMoiP << " " << dTauQ / dMoiQ << endl;
}
}
void SpherocylBox::calc_se()
{
for (int i = 0; i < m_nParticles; i++) {
m_psParticles[i].m_dFx = 0.0;
m_psParticles[i].m_dFy = 0.0;
m_psParticles[i].m_dTau = 0.0;
}
m_dEnergy = 0.0;
m_dPxx = 0.0;
m_dPyy = 0.0;
m_dPxy = 0.0;
for (int p = 0; p < m_nParticles; p++) {
for (int j = 0; j < m_pvNeighbors[p].size(); j++)
{
int q = m_pvNeighbors[p][j];
if (q > p)
calc_se_force_pair(p, q);
}
}
}
void SpherocylBox::set_back_gamma()
{
//cout << "setting back gamma" << endl;
for (int i = 0; i < m_nParticles; i++) //set all paricles to lab frame
{
if (m_psParticles[i].m_dY < 0)
m_psParticles[i].m_dY += m_dLy;
else if (m_psParticles[i].m_dY > m_dLy)
m_psParticles[i].m_dY -= m_dLy;
m_psParticles[i].m_dX += m_psParticles[i].m_dY; //gamma' = gamma - 1
if (m_psParticles[i].m_dX < 0)
m_psParticles[i].m_dX += m_dLx;
else {
while (m_psParticles[i].m_dX > m_dLx) //particles outside the box sent back through periodic BC
m_psParticles[i].m_dX -= m_dLx;
}
}
m_dGamma -= 1.0;
m_dGammaTotal = int(m_dGammaTotal + 1) + m_dGamma;
find_neighbors();
}
bool SpherocylBox::check_particle_contact(int p, int q)
{
//cout << "with: " << q << ": " << m_psParticles[q].m_dX << " " << m_psParticles[q].m_dY << " " << m_psParticles[q].m_dPhi << endl;
double dDeltaX = m_psParticles[p].m_dX - m_psParticles[q].m_dX;
double dDeltaY = m_psParticles[p].m_dY - m_psParticles[q].m_dY;
double dPhiP = m_psParticles[p].m_dPhi;
double dPhiQ = m_psParticles[q].m_dPhi;
double dSigma = m_psParticles[p].m_dR + m_psParticles[q].m_dR;
double dAP = m_psParticles[p].m_dA;
double dAQ = m_psParticles[q].m_dA;
// Make sure we take the closest distance considering boundary conditions
dDeltaX += m_dLx * ((dDeltaX < -0.5*m_dLx) - (dDeltaX > 0.5*m_dLx));
dDeltaY += m_dLy * ((dDeltaY < -0.5*m_dLy) - (dDeltaY > 0.5*m_dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += m_dGamma * dDeltaY;
double nxA = dAP * cos(dPhiP);
double nyA = dAP * sin(dPhiP);
double nxB = dAQ * cos(dPhiQ);
double nyB = dAQ * sin(dPhiQ);
double a = dAP * dAP;
double b = -(nxA * nxB + nyA * nyB);
double c = dAQ * dAQ;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
double s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma || dDSqr != dDSqr) {
//cout << "contact detected" << endl;
return true;
}
else {
//cout << "no contact" << endl;
return false;
}
}
bool SpherocylBox::check_particle_cross(int p, int q)
{
//cout << "with: " << q << ": " << m_psParticles[q].m_dX << " " << m_psParticles[q].m_dY << " " << m_psParticles[q].m_dPhi << endl;
double dDeltaX = m_psParticles[p].m_dX - m_psParticles[q].m_dX;
double dDeltaY = m_psParticles[p].m_dY - m_psParticles[q].m_dY;
double dPhiP = m_psParticles[p].m_dPhi;
double dPhiQ = m_psParticles[q].m_dPhi;
double dSigma = m_psParticles[p].m_dR + m_psParticles[q].m_dR;
double dAP = m_psParticles[p].m_dA;
double dAQ = m_psParticles[q].m_dA;
// Make sure we take the closest distance considering boundary conditions
dDeltaX += m_dLx * ((dDeltaX < -0.5*m_dLx) - (dDeltaX > 0.5*m_dLx));
dDeltaY += m_dLy * ((dDeltaY < -0.5*m_dLy) - (dDeltaY > 0.5*m_dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += m_dGamma * dDeltaY;
double nxA = dAP * cos(dPhiP);
double nyA = dAP * sin(dPhiP);
double nxB = dAQ * cos(dPhiQ);
double nyB = dAQ * sin(dPhiQ);
double a = dAP * dAP;
double b = -(nxA * nxB + nyA * nyB);
double c = dAQ * dAQ;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
double s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < 1e-5*dSigma*dSigma || dDSqr != dDSqr) {
//cout << "contact detected" << endl;
return true;
}
else {
//cout << "no contact" << endl;
return false;
}
}
bool SpherocylBox::check_particle_contact(int p)
{
//cout << "checking contact: " << p << ": " << m_psParticles[p].m_dX << " " << m_psParticles[p].m_dY << " " << m_psParticles[p].m_dPhi << endl;
int nCellID = m_psParticles[p].m_nCell;
for (int ap = 0; ap < m_pvCells[nCellID].size(); ap++) {
int q = m_pvCells[nCellID][ap];
if (check_particle_contact(p,q)) {
return true;
}
}
for (int ac = 0; ac < 8; ac++) {
int nACellID = m_pnCellNeighbors[nCellID][ac];
for (int ap = 0; ap < m_pvCells[nACellID].size(); ap++) {
int q = m_pvCells[nACellID][ap];
if (check_particle_contact(p,q)) {
return true;
}
}
}
//cout << "no contacts detected" << endl;
return false;
}
bool SpherocylBox::check_particle_cross(int p)
{
//cout << "checking contact: " << p << ": " << m_psParticles[p].m_dX << " " << m_psParticles[p].m_dY << " " << m_psParticles[p].m_dPhi << endl;
int nCellID = m_psParticles[p].m_nCell;
for (int ap = 0; ap < m_pvCells[nCellID].size(); ap++) {
int q = m_pvCells[nCellID][ap];
if (check_particle_cross(p,q)) {
return true;
}
}
for (int ac = 0; ac < 8; ac++) {
int nACellID = m_pnCellNeighbors[nCellID][ac];
for (int ap = 0; ap < m_pvCells[nACellID].size(); ap++) {
int q = m_pvCells[nACellID][ap];
if (check_particle_cross(p,q)) {
return true;
}
}
}
//cout << "no contacts detected" << endl;
return false;
}
void SpherocylBox::random_configuration(double dA, double dR, initialConfig config)
{
assert(dA >= 0);
assert(dR > 0);
m_dAmax = dA;
m_dRmax = dR;
double dAlpha = dA/dR;
double dC = (3*D_PI + 24*dAlpha + 6*D_PI*dAlpha*dAlpha + 8*dAlpha*dAlpha*dAlpha);
double dArea = dR*(D_PI*dR + 4*dA);
double dI = dR*dR*dR*dR*dC/(6*dArea);
double dRC = (8*dAlpha + 6*D_PI*dAlpha*dAlpha + 8*dAlpha*dAlpha*dAlpha)/dC;
configure_cells();
for (int p = 0; p < m_nParticles; p++) {
m_pvNeighbors[p].clear();
}
int nRows;
int nCols;
double dWidth;
double dHeight;
double dXOffset = dA + dR;
double dYOffset = dR;
double dRWidth;
double dRHeight;
if (config > 3) {
double dAspect = (dA + dR) / dR;
if (m_dLx == m_dLy) {
double dCols = sqrt(m_nParticles/dAspect);
nRows = int(dAspect*dCols);
nCols = int(dCols);
}
else {
nRows = int(0.5*m_dLx/(dA+dR));
nCols = m_nParticles/nRows + 0 ? m_nParticles % nRows == 0 : 1;
}
dWidth = m_dLx/nCols;
dHeight = m_dLy/nRows;
if (dWidth < 2*(dA+dR) || dHeight < 2*dR) {
std::cerr << "Error: Spherocylinders will not fit into square grid, chang the number or size of box" << endl;
exit(1);
}
dRWidth = dWidth - 2*dXOffset;
dRHeight = dHeight - 2*dYOffset;
}
std::srand(time(0));
for (int p = 0; p < m_nParticles; p++) {
bool bContact = true;
int nTries = 0;
int nR;
int nC;
if (config > 3) {
nR = p / nCols;
nC = p % nCols;
}
while (bContact) {
nTries += 1;
if (config < 4) {
m_psParticles[p].m_dX = m_dLx*double(std::rand())/double(std::numeric_limits<int>::max());
m_psParticles[p].m_dY = m_dLy*double(std::rand())/double(std::numeric_limits<int>::max());
}
else {
m_psParticles[p].m_dX = nC*dWidth + dXOffset + dRWidth*double(std::rand())/double(std::numeric_limits<int>::max());
m_psParticles[p].m_dY = nR*dHeight + dYOffset + dRHeight*double(std::rand())/double(std::numeric_limits<int>::max());
}
if (config % 2 == 1) {
m_psParticles[p].m_dPhi = 0;
}
else {
m_psParticles[p].m_dPhi = 2*D_PI*double(std::rand())/double(std::numeric_limits<int>::max());
}
m_psParticles[p].m_dA = dA;
m_psParticles[p].m_dR = dR;
int nCol = int(m_psParticles[p].m_dX / m_dCellWidth);
int nRow = int(m_psParticles[p].m_dY / m_dCellHeight);
int nCellID = nCol + nRow * m_nCellCols;
m_psParticles[p].m_nCell = nCellID;
if (config < 2) {
bContact = check_particle_cross(p);
}
else {
bContact = check_particle_contact(p);
}
}
m_pvCells[m_psParticles[p].m_nCell].push_back(p);
m_psParticles[p].m_dI = dI;
m_psParticles[p].m_dRC = dRC;
cout << "Particle " << p << " placed in " << nTries << " tries" << endl;
}
m_dPacking = calculate_packing_fraction();
find_neighbors();
}
<file_sep>/src/cuda/spherocyl_box.cpp
/* spherocyl_box.cpp
*
*
*/
#include "spherocyl_box.h"
#include <cuda.h>
#include <cuda_runtime_api.h>
#include <assert.h>
#include <algorithm>
#include "cudaErr.h"
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <random>
using namespace std;
const double D_PI = 3.14159265358979;
void Spherocyl_Box::reconfigure_cells()
{
double dWMin = sqrt(m_dLx*m_dLx/(m_dLy*m_dLy) + 4) * (m_dRMax + m_dAMax) + m_dEpsilon;
double dHMin = 2 * (m_dRMax + m_dAMax) + m_dEpsilon;
int nNewCellRows = max(static_cast<int>(m_dLy / dHMin), 3);
int nNewCellCols = max(static_cast<int>(m_dLx / dWMin), 3);
if (nNewCellRows != m_nCellRows || nNewCellCols != m_nCellCols) {
delete[] h_pnPPC; delete[] h_pnCellList; delete[] h_pnAdjCells;
cudaFree(d_pnPPC); cudaFree(d_pnCellList); cudaFree(d_pnAdjCells);
#if GOLD_FUNCS == 1
delete[] g_pnPPC; delete[] g_pnCellList; delete[] g_pnAdjCells;
#endif
*h_bNewNbrs = 1;
configure_cells();
}
else {
m_dCellW = m_dLx / m_nCellCols;
m_dCellH = m_dLy / m_nCellRows;
}
}
void Spherocyl_Box::reconfigure_cells(double dMaxGamma)
{
double dWMin = 2 * sqrt(dMaxGamma*dMaxGamma + 1) * (m_dRMax + m_dAMax) + m_dEpsilon;
double dHMin = 2 * (m_dRMax + m_dAMax) + m_dEpsilon;
int nNewCellRows = max(static_cast<int>(m_dLy / dHMin), 3);
int nNewCellCols = max(static_cast<int>(m_dLx / dWMin), 3);
if (nNewCellRows != m_nCellRows || nNewCellCols != m_nCellCols) {
cout << "Reconfiguring cells" << endl;
delete[] h_pnPPC; delete[] h_pnCellList; delete[] h_pnAdjCells;
cudaFree(d_pnPPC); cudaFree(d_pnCellList); cudaFree(d_pnAdjCells);
#if GOLD_FUNCS == 1
delete[] g_pnPPC; delete[] g_pnCellList; delete[] g_pnAdjCells;
#endif
*h_bNewNbrs = 1;
configure_cells(dMaxGamma);
}
else {
m_dCellW = m_dLx / m_nCellCols;
m_dCellH = m_dLy / m_nCellRows;
}
}
// Just setting things up here
// configure_cells() decides how the space should be divided into cells
// and which cells are next to each other
void Spherocyl_Box::configure_cells()
{
assert(m_dRMax > 0.0);
assert(m_dAMax >= 0.0);
// Minimum height & width of cells
// Width is set so that it is only possible for particles in
// adjacent cells to interact as long as |gamma| < 0.5
double dWMin = sqrt(m_dLx*m_dLx/(m_dLy*m_dLy) + 4) * (m_dRMax + m_dAMax) + m_dEpsilon;
double dHMin = 2 * (m_dRMax + m_dAMax) + m_dEpsilon;
m_nCellRows = max(static_cast<int>(m_dLy / dHMin), 3);
m_nCellCols = max(static_cast<int>(m_dLx / dWMin), 3);
m_nCells = m_nCellRows * m_nCellCols;
cout << "Cells: " << m_nCells << ": " << m_nCellRows << " x " << m_nCellCols << endl;
m_dCellW = m_dLx / m_nCellCols;
m_dCellH = m_dLy / m_nCellRows;
cout << "Cell dimensions: " << m_dCellW << " x " << m_dCellH << endl;
h_pnPPC = new int[m_nCells];
h_pnCellList = new int[m_nCells * m_nMaxPPC];
h_pnAdjCells = new int[8 * m_nCells];
cudaMalloc((void **) &d_pnPPC, m_nCells * sizeof(int));
cudaMalloc((void **) &d_pnCellList, m_nCells*m_nMaxPPC*sizeof(int));
cudaMalloc((void **) &d_pnAdjCells, 8*m_nCells*sizeof(int));
m_nDeviceMem += m_nCells*(9+m_nMaxPPC)*sizeof(int);
#if GOLD_FUNCS == 1
g_pnPPC = new int[m_nCells];
g_pnCellList = new int[m_nCells * m_nMaxPPC];
g_pnAdjCells = new int[8 * m_nCells];
#endif
// Make a list of which cells are next to each cell
// This is done once for convinience since the boundary conditions
// make this more than trivial
for (int c = 0; c < m_nCells; c++)
{
int nRow = c / m_nCellCols;
int nCol = c % m_nCellCols;
int nAdjCol1 = (nCol + 1) % m_nCellCols;
int nAdjCol2 = (m_nCellCols + nCol - 1) % m_nCellCols;
h_pnAdjCells[8 * c] = nRow * m_nCellCols + nAdjCol1;
h_pnAdjCells[8 * c + 1] = nRow * m_nCellCols + nAdjCol2;
int nAdjRow = (nRow + 1) % m_nCellRows;
h_pnAdjCells[8 * c + 2] = nAdjRow * m_nCellCols + nCol;
h_pnAdjCells[8 * c + 3] = nAdjRow * m_nCellCols + nAdjCol1;
h_pnAdjCells[8 * c + 4] = nAdjRow * m_nCellCols + nAdjCol2;
nAdjRow = (m_nCellRows + nRow - 1) % m_nCellRows;
h_pnAdjCells[8 * c + 5] = nAdjRow * m_nCellCols + nCol;
h_pnAdjCells[8 * c + 6] = nAdjRow * m_nCellCols + nAdjCol1;
h_pnAdjCells[8 * c + 7] = nAdjRow * m_nCellCols + nAdjCol2;
}
cudaMemcpy(d_pnAdjCells, h_pnAdjCells, 8*m_nCells*sizeof(int), cudaMemcpyHostToDevice);
checkCudaError("Configuring cells");
}
void Spherocyl_Box::configure_cells(double dMaxGamma)
{
assert(m_dRMax > 0.0);
assert(m_dAMax >= 0.0);
// Minimum height & width of cells
// Width is set so that it is only possible for particles in
// adjacent cells to interact as long as |gamma| < 0.5
double dWMin = 2 * sqrt(dMaxGamma*dMaxGamma + 1) * (m_dRMax + m_dAMax) + m_dEpsilon;
double dHMin = 2 * (m_dRMax + m_dAMax) + m_dEpsilon;
m_nCellRows = max(static_cast<int>(m_dLy / dHMin), 1);
m_nCellCols = max(static_cast<int>(m_dLx / dWMin), 1);
m_nCells = m_nCellRows * m_nCellCols;
cout << "Cells: " << m_nCells << ": " << m_nCellRows << " x " << m_nCellCols << endl;
m_dCellW = m_dLx / m_nCellCols;
m_dCellH = m_dLy / m_nCellRows;
cout << "Cell dimensions: " << m_dCellW << " x " << m_dCellH << endl;
h_pnPPC = new int[m_nCells];
h_pnCellList = new int[m_nCells * m_nMaxPPC];
h_pnAdjCells = new int[8 * m_nCells];
cudaMalloc((void **) &d_pnPPC, m_nCells * sizeof(int));
cudaMalloc((void **) &d_pnCellList, m_nCells*m_nMaxPPC*sizeof(int));
cudaMalloc((void **) &d_pnAdjCells, 8*m_nCells*sizeof(int));
m_nDeviceMem += m_nCells*(9+m_nMaxPPC)*sizeof(int);
#if GOLD_FUNCS == 1
g_pnPPC = new int[m_nCells];
g_pnCellList = new int[m_nCells * m_nMaxPPC];
g_pnAdjCells = new int[8 * m_nCells];
#endif
// Make a list of which cells are next to each cell
// This is done once for convinience since the boundary conditions
// make this more than trivial
for (int c = 0; c < m_nCells; c++)
{
int nRow = c / m_nCellCols;
int nCol = c % m_nCellCols;
int nAdjCol1 = (nCol + 1) % m_nCellCols;
int nAdjCol2 = (m_nCellCols + nCol - 1) % m_nCellCols;
h_pnAdjCells[8 * c] = nRow * m_nCellCols + nAdjCol1;
h_pnAdjCells[8 * c + 1] = nRow * m_nCellCols + nAdjCol2;
int nAdjRow = (nRow + 1) % m_nCellRows;
h_pnAdjCells[8 * c + 2] = nAdjRow * m_nCellCols + nCol;
h_pnAdjCells[8 * c + 3] = nAdjRow * m_nCellCols + nAdjCol1;
h_pnAdjCells[8 * c + 4] = nAdjRow * m_nCellCols + nAdjCol2;
nAdjRow = (m_nCellRows + nRow - 1) % m_nCellRows;
h_pnAdjCells[8 * c + 5] = nAdjRow * m_nCellCols + nCol;
h_pnAdjCells[8 * c + 6] = nAdjRow * m_nCellCols + nAdjCol1;
h_pnAdjCells[8 * c + 7] = nAdjRow * m_nCellCols + nAdjCol2;
}
cudaMemcpy(d_pnAdjCells, h_pnAdjCells, 8*m_nCells*sizeof(int), cudaMemcpyHostToDevice);
checkCudaError("Configuring cells");
}
// Set the thread configuration for kernel launches
void Spherocyl_Box::set_kernel_configs()
{
switch (m_nSpherocyls)
{
case 512:
m_nGridSize = 4;
m_nBlockSize = 128;
m_nSM_CalcF = 3*128*sizeof(double);
m_nSM_CalcSE = 5*136*sizeof(double);
case 1024:
m_nGridSize = 8; // Grid size (# of thread blocks)
m_nBlockSize = 128; // Block size (# of threads per block)
m_nSM_CalcF = 3*128*sizeof(double);
m_nSM_CalcSE = 5*136*sizeof(double); // Size of shared memory per block
break;
case 1280:
m_nGridSize = 10;
m_nBlockSize = 128;
m_nSM_CalcF = 3*128*sizeof(double);
m_nSM_CalcSE = 5*136*sizeof(double);
break;
case 2048:
m_nGridSize = 16; // Grid size (# of thread blocks)
m_nBlockSize = 128; // Block size (# of threads per block)
m_nSM_CalcF = 3*128*sizeof(double);
m_nSM_CalcSE = 5*136*sizeof(double); // Size of shared memory per block
break;
case 4096:
m_nGridSize = 16;
m_nBlockSize = 256;
m_nSM_CalcF = 3*256*sizeof(double);
m_nSM_CalcSE = 5*264*sizeof(double);
break;
default:
m_nGridSize = m_nSpherocyls / 256 + (0 ? (m_nSpherocyls % 256 == 0) : 1);
m_nBlockSize = 256;
m_nSM_CalcF = 3*256*sizeof(double);
m_nSM_CalcSE = 5*264*sizeof(double);
};
cout << "Kernel config (spherocyls):\n";
cout << m_nGridSize << " x " << m_nBlockSize << endl;
cout << "Shared memory allocation (calculating forces):\n";
cout << (float)m_nSM_CalcF / 1024. << "KB" << endl;
cout << "Shared memory allocation (calculating S-E):\n";
cout << (float)m_nSM_CalcSE / 1024. << " KB" << endl;
}
void Spherocyl_Box::construct_defaults()
{
m_dGamma = 0.0;
m_dTotalGamma = 0.0;
m_dStep = 1;
m_dStrainRate = 1e-3;
m_szDataDir = "./";
m_szFileSE = "sd_stress_energy.dat";
cudaHostAlloc((void**) &h_bNewNbrs, sizeof(int), 0);
*h_bNewNbrs = 1;
cudaMalloc((void**) &d_bNewNbrs, sizeof(int));
cudaMemcpyAsync(d_bNewNbrs, h_bNewNbrs, sizeof(int), cudaMemcpyHostToDevice);
cudaMalloc((void**) &d_pdTempX, sizeof(double)*m_nSpherocyls);
cudaMalloc((void**) &d_pdTempY, sizeof(double)*m_nSpherocyls);
cudaMalloc((void**) &d_pdTempPhi, sizeof(double)*m_nSpherocyls);
cudaMalloc((void**) &d_pdXMoved, sizeof(double)*m_nSpherocyls);
cudaMalloc((void**) &d_pdYMoved, sizeof(double)*m_nSpherocyls);
cudaMalloc((void**) &d_pdDx, sizeof(double)*m_nSpherocyls);
cudaMalloc((void**) &d_pdDy, sizeof(double)*m_nSpherocyls);
cudaMalloc((void**) &d_pdDt, sizeof(double)*m_nSpherocyls);
cudaMalloc((void**) &d_pdMOI, sizeof(double)*m_nSpherocyls);
cudaMalloc((void**) &d_pdIsoC, sizeof(double)*m_nSpherocyls);
m_bMOI = 0;
m_nDeviceMem += 10*m_nSpherocyls*sizeof(double);
#if GOLD_FUNCS == 1
*g_bNewNbrs = 1;
g_pdTempX = new double[3*m_nSpherocyls];
g_pdTempY = new double[3*m_nSpherocyls];
g_pdTempPhi = new double[3*m_nSpherocyls];
g_pdXMoved = new double[3*m_nSpherocyls];
g_pdYMoved = new double[3*m_nSpherocyls];
#endif
// Stress, energy, & force data
h_pdLineEnergy = new double[6];
cudaHostAlloc((void **) &h_pfSE, 5*sizeof(float), 0);
m_pfEnergy = h_pfSE+4;
m_pfPxx = h_pfSE;
m_pfPyy = h_pfSE+1;
m_pfPxy = h_pfSE+2;
m_pfPyx = h_pfSE+3;
m_fP = 0;
h_pdFx = new double[m_nSpherocyls];
h_pdFy = new double[m_nSpherocyls];
h_pdFt = new double[m_nSpherocyls];
h_pdEnergies = new double[m_nSpherocyls];
// GPU
cudaMalloc((void**) &d_pfSE, 5*sizeof(float));
cudaMalloc((void**) &d_pdEnergies, m_nSpherocyls*sizeof(double));
cudaMalloc((void**) &d_pdFx, m_nSpherocyls*sizeof(double));
cudaMalloc((void**) &d_pdFy, m_nSpherocyls*sizeof(double));
cudaMalloc((void**) &d_pdFt, m_nSpherocyls*sizeof(double));
cudaMalloc((void**) &d_pdTempFx, m_nSpherocyls*sizeof(double));
cudaMalloc((void**) &d_pdTempFy, m_nSpherocyls*sizeof(double));
cudaMalloc((void**) &d_pdTempFt, m_nSpherocyls*sizeof(double));
m_nDeviceMem += 5*sizeof(float) + 6*m_nSpherocyls*sizeof(double);
#if GOLD_FUNCS == 1
g_pfSE = new float[5];
g_pdFx = new double[m_nSpherocyls];
g_pdFy = new double[m_nSpherocyls];
g_pdFt = new double[m_nSpherocyls];
#endif
// Cell & neighbor data
h_pnCellID = new int[m_nSpherocyls];
cudaMalloc((void**) &d_pnCellID, sizeof(int)*m_nSpherocyls);
m_nDeviceMem += m_nSpherocyls*sizeof(int);
#if GOLD_FUNCS == 1
g_pnCellID = new int[m_nSpherocyls];
#endif
configure_cells();
h_pnNPP = new int[m_nSpherocyls];
h_pnNbrList = new int[m_nSpherocyls*m_nMaxNbrs];
cudaMalloc((void**) &d_pnNPP, sizeof(int)*m_nSpherocyls);
cudaMalloc((void**) &d_pnNbrList, sizeof(int)*m_nSpherocyls*m_nMaxNbrs);
m_nDeviceMem += m_nSpherocyls*(1+m_nMaxNbrs)*sizeof(int);
#if GOLD_FUNCS == 1
g_pnNPP = new int[m_nSpherocyls];
g_pnNbrList = new int[m_nSpherocyls*m_nMaxNbrs];
#endif
set_kernel_configs();
cudaHostAlloc((void **) &h_pdBlockSums, m_nGridSize*sizeof(double), 0);
cudaMalloc((void **) &d_pdBlockSums, m_nGridSize*sizeof(double));
m_nDeviceMem += m_nGridSize*sizeof(double);
}
double Spherocyl_Box::calculate_packing()
{
double dParticleArea = 0.0;
for (int p = 0; p < m_nSpherocyls; p++)
{
dParticleArea += (4 * h_pdA[p] + D_PI * h_pdR[p]) * h_pdR[p];
}
return dParticleArea / (m_dLx * m_dLy);
}
// Creates the class
// See spherocyl_box.h for default values of parameters
Spherocyl_Box::Spherocyl_Box(int nSpherocyls, double dL, double dAspect, double dBidispersity, Config config, double dEpsilon, double dASig, int nMaxPPC, int nMaxNbrs, Potential ePotential)
{
assert(nSpherocyls > 0);
m_nSpherocyls = nSpherocyls;
assert(dL > 0.0);
m_dLx = dL;
m_dLy = dL;
m_ePotential = ePotential;
m_dEpsilon = dEpsilon;
m_nMaxPPC = nMaxPPC;
m_nMaxNbrs = nMaxNbrs;
m_dASig = dASig;
if (dBidispersity >= 1) {
m_dRMax = 0.5*dBidispersity;
}
else {
m_dRMax = 0.5;
}
m_dAMax = m_dRMax*dAspect;
m_nDeviceMem = 0;
m_dKd = dBidispersity/(D_PI*m_dRMax*m_dRMax + 4*m_dRMax*m_dAMax); // Default dissipative constant: 1/A_s
// This allocates the coordinate data as page-locked memory, which
// transfers faster, since they are likely to be transferred often
cudaHostAlloc((void**)&h_pdX, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdY, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdPhi, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdR, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdA, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pnMemID, nSpherocyls*sizeof(int), 0);
m_dPacking = 0;
// This initializes the arrays on the GPU
cudaMalloc((void**) &d_pdX, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdY, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdPhi, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdR, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdA, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pnInitID, sizeof(int)*nSpherocyls);
cudaMalloc((void**) &d_pnMemID, sizeof(int)*nSpherocyls);
// Spherocylinders
m_nDeviceMem += nSpherocyls*(5*sizeof(double) + 2*sizeof(int));
#if GOLD_FUNCS == 1
g_pdX = new double[nSpherocyls];
g_pdY = new double[nSpherocyls];
g_pdPhi = new double[nSpherocyls];
g_pdR = new double[nSpherocyls];
g_pdA = new double[nSpherocyls];
g_pnInitID = new int[nSpherocyls];
g_pnMemID = new int[nSpherocyls];
#endif
set_shapes(0, dBidispersity);
construct_defaults();
cout << "Memory allocated on device (MB): " << (double)m_nDeviceMem / (1024.*1024.) << endl;
/*
switch (config) {
case RANDOM:
place_random_spherocyls(0,1,dBidispersity);
break;
case RANDOM_ALIGNED:
place_random_spherocyls(0,0,dBidispersity);
break;
case ZERO_E:
place_random_0e_spherocyls(0,1,dBidispersity);
break;
case ZERO_E_ALIGNED:
place_random_0e_spherocyls(0,0,dBidispersity);
break;
case GRID:
place_spherocyl_grid(0,1);
break;
case GRID_ALIGNED:
place_spherocyl_grid(0,0);
break;
}
*/
cudaMemcpy(d_pdR, h_pdR, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdA, h_pdA, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnInitID, h_pnMemID, sizeof(int)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnMemID, h_pnMemID, sizeof(int)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaThreadSynchronize();
place_spherocyls(config,1,dBidispersity);
m_dPacking = calculate_packing();
cout << "Random spherocyls placed" << endl;
//display(0,0,0,0);
}
Spherocyl_Box::Spherocyl_Box(int nSpherocyls, double dLx, double dLy, double dAspect, double dBidispersity, Config config, double dEpsilon, double dASig, int nMaxPPC, int nMaxNbrs, Potential ePotential)
{
assert(nSpherocyls > 0);
m_nSpherocyls = nSpherocyls;
assert(dLx > 0.0 && dLy > 0.0);
m_dLx = dLx;
m_dLy = dLy;
m_ePotential = ePotential;
m_dEpsilon = dEpsilon;
m_nMaxPPC = nMaxPPC;
m_nMaxNbrs = nMaxNbrs;
m_dASig = dASig;
if (dBidispersity >= 1) {
m_dRMax = 0.5*dBidispersity;
}
else {
m_dRMax = 0.5;
}
m_dAMax = m_dRMax*dAspect;
m_dKd = dBidispersity/(D_PI*m_dRMax*m_dRMax + 4*m_dRMax*m_dAMax); // Default dissipative constant: 1/A_s
m_nDeviceMem = 0;
// This allocates the coordinate data as page-locked memory, which
// transfers faster, since they are likely to be transferred often
cudaHostAlloc((void**)&h_pdX, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdY, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdPhi, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdR, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdA, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pnMemID, nSpherocyls*sizeof(int), 0);
m_dPacking = 0;
// This initializes the arrays on the GPU
cudaMalloc((void**) &d_pdX, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdY, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdPhi, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdR, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdA, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pnInitID, sizeof(int)*nSpherocyls);
cudaMalloc((void**) &d_pnMemID, sizeof(int)*nSpherocyls);
// Spherocylinders
m_nDeviceMem += nSpherocyls*(5*sizeof(double) + 2*sizeof(int));
#if GOLD_FUNCS == 1
g_pdX = new double[nSpherocyls];
g_pdY = new double[nSpherocyls];
g_pdPhi = new double[nSpherocyls];
g_pdR = new double[nSpherocyls];
g_pdA = new double[nSpherocyls];
g_pnInitID = new int[nSpherocyls];
g_pnMemID = new int[nSpherocyls];
#endif
cout << "Setting shapes" << endl;
set_shapes(0, dBidispersity);
cout << "Constructing cells etc." << endl;
construct_defaults();
cout << "Memory allocated on device (MB): " << (double)m_nDeviceMem / (1024.*1024.) << endl;
/*
switch (config) {
case RANDOM:
place_random_spherocyls(0,1,dBidispersity);
break;
case RANDOM_ALIGNED:
place_random_spherocyls(0,0,dBidispersity);
break;
case ZERO_E:
place_random_0e_spherocyls(0,1,dBidispersity);
break;
case ZERO_E_ALIGNED:
place_random_0e_spherocyls(0,0,dBidispersity);
break;
case GRID:
place_spherocyl_grid(0,1);
break;
case GRID_ALIGNED:
place_spherocyl_grid(0,0);
break;
}
*/
cudaMemcpy(d_pdR, h_pdR, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdA, h_pdA, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnInitID, h_pnMemID, sizeof(int)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnMemID, h_pnMemID, sizeof(int)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaThreadSynchronize();
place_spherocyls(config,1,dBidispersity);
m_dPacking = calculate_packing();
cout << "Random spherocyls placed" << endl;
//display(0,0,0,0);
}
// Create class with coordinate arrays provided
Spherocyl_Box::Spherocyl_Box(int nSpherocyls, double dLx, double dLy, double *pdX,
double *pdY, double *pdPhi, double *pdR, double *pdA,
double dEpsilon, int nMaxPPC, int nMaxNbrs, Potential ePotential)
{
assert(nSpherocyls > 0);
m_nSpherocyls = nSpherocyls;
assert(dLx > 0 && dLy > 0);
m_dLx = dLx;
m_dLy = dLy;
m_ePotential = ePotential;
m_dEpsilon = dEpsilon;
m_nMaxPPC = nMaxPPC;
m_nMaxNbrs = nMaxNbrs;
// This allocates the coordinate data as page-locked memory, which
// transfers faster, since they are likely to be transferred often
cudaHostAlloc((void**)&h_pdX, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdY, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdPhi, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdR, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdA, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pnMemID, nSpherocyls*sizeof(int), 0);
m_dASig = 0;
m_dRMax = 0.0;
m_dAMax = 0.0;
double dRMin = pdR[0];
double dAMin = pdA[0];
//cout << "Loading positions" << endl;
for (int p = 0; p < nSpherocyls; p++)
{
//cout << "loading p=" << p << endl;
h_pdX[p] = pdX[p];
h_pdY[p] = pdY[p];
h_pdPhi[p] = pdPhi[p];
h_pdR[p] = pdR[p];
h_pdA[p] = pdA[p];
h_pnMemID[p] = p;
if (pdR[p] > m_dRMax)
m_dRMax = pdR[p];
else if (pdR[p] < dRMin)
dRMin = pdR[p];
if (pdA[p] > m_dAMax)
m_dAMax = pdA[p];
else if (pdA[p] > dAMin)
dAMin = pdA[p];
while (h_pdX[p] > dLx)
h_pdX[p] -= dLx;
while (h_pdX[p] < 0)
h_pdX[p] += dLx;
while (h_pdY[p] > dLy)
h_pdY[p] -= dLy;
while (h_pdY[p] < 0)
h_pdY[p] += dLy;
}
m_dKd = 1/(D_PI*dRMin*dRMin+4*dRMin*dAMin);
m_dPacking = calculate_packing();
//cout << "Positions loaded" << endl;
// This initializes the arrays on the GPU
cudaMalloc((void**) &d_pdX, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdY, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdPhi, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdR, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdA, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pnInitID, sizeof(int)*nSpherocyls);
cudaMalloc((void**) &d_pnMemID, sizeof(int)*nSpherocyls);
// This copies the values to the GPU asynchronously, which allows the
// CPU to go on and process further instructions while the GPU copies.
// Only workes on page-locked memory (allocated with cudaHostAlloc)
cudaMemcpyAsync(d_pdX, h_pdX, sizeof(double)*nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdY, h_pdY, sizeof(double)*nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdPhi, h_pdPhi, sizeof(double)*nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdR, h_pdR, sizeof(double)*nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdA, h_pdA, sizeof(double)*nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnMemID, h_pnMemID, sizeof(int)*nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnInitID, d_pnMemID, sizeof(int)*nSpherocyls, cudaMemcpyDeviceToDevice);
m_nDeviceMem += nSpherocyls*(5*sizeof(double)+2*sizeof(int));
#if GOLD_FUNCS == 1
g_pdX = new double[nSpherocyls];
g_pdY = new double[nSpherocyls];
g_pdPhi = new double[nSpherocyls];
g_pdR = new double[nSpherocyls];
g_pdA = new double[nSpherocyls];
g_pnInitID = new int[nSpherocyls];
g_pnMemID = new int[nSpherocyls];
for (int p = 0; p < nSpherocyls; p++)
{
g_pdX[p] = h_pdX[p];
g_pdY[p] = h_pdY[p];
g_pdPhi[p] = h_pdPhi[p];
g_pdR[p] = h_pdR[p];
g_pdA[p] = h_pdA[p];
g_pnMemID[p] = h_pnMemID[p];
g_pnInitID[p] = g_pnMemID[p];
}
#endif
//cout << "Positions transfered to device" << endl;
construct_defaults();
cout << "Memory allocated on device (MB): " << (double)m_nDeviceMem / (1024.*1024.) << endl;
// Get spheocyl coordinates from spherocyls
cudaThreadSynchronize();
//display(0,0,0,0);
}
Spherocyl_Box::Spherocyl_Box(int nSpherocyls, double dL, double *pdX,
double *pdY, double *pdPhi, double *pdR,
double *pdA, double dEpsilon, int nMaxPPC,
int nMaxNbrs, Potential ePotential)
{
assert(nSpherocyls > 0);
m_nSpherocyls = nSpherocyls;
assert(dL > 0);
m_dLx = dL;
m_dLy = dL;
m_ePotential = ePotential;
m_dEpsilon = dEpsilon;
m_nMaxPPC = nMaxPPC;
m_nMaxNbrs = nMaxNbrs;
// This allocates the coordinate data as page-locked memory, which
// transfers faster, since they are likely to be transferred often
cudaHostAlloc((void**)&h_pdX, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdY, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdPhi, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdR, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pdA, nSpherocyls*sizeof(double), 0);
cudaHostAlloc((void**)&h_pnMemID, nSpherocyls*sizeof(int), 0);
m_dASig = 0;
m_dRMax = 0.0;
m_dAMax = 0.0;
double dRMin = pdR[0];
double dAMin = pdA[0];
//cout << "Loading positions" << endl;
for (int p = 0; p < nSpherocyls; p++)
{
//cout << "loading p=" << p << endl;
h_pdX[p] = pdX[p];
h_pdY[p] = pdY[p];
h_pdPhi[p] = pdPhi[p];
h_pdR[p] = pdR[p];
h_pdA[p] = pdA[p];
h_pnMemID[p] = p;
if (pdR[p] > m_dRMax)
m_dRMax = pdR[p];
else if (pdR[p] < dRMin)
dRMin = pdR[p];
if (pdA[p] > m_dAMax)
m_dAMax = pdA[p];
else if (pdA[p] > dAMin)
dAMin = pdA[p];
while (h_pdX[p] > dL)
h_pdX[p] -= dL;
while (h_pdX[p] < 0)
h_pdX[p] += dL;
while (h_pdY[p] > dL)
h_pdY[p] -= dL;
while (h_pdY[p] < 0)
h_pdY[p] += dL;
}
m_dKd = 1/(D_PI*dRMin*dRMin+4*dRMin*dAMin);
m_dPacking = calculate_packing();
// cout << "Positions loaded, particle 0: " << h_pdX[0] << ", " << h_pdY[0] << ", " << h_pdPhi[0] << endl;
// This initializes the arrays on the GPU
cudaMalloc((void**) &d_pdX, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdY, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdPhi, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdR, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pdA, sizeof(double)*nSpherocyls);
cudaMalloc((void**) &d_pnInitID, sizeof(int)*nSpherocyls);
cudaMalloc((void**) &d_pnMemID, sizeof(int)*nSpherocyls);
// This copies the values to the GPU asynchronously, which allows the
// CPU to go on and process further instructions while the GPU copies.
// Only workes on page-locked memory (allocated with cudaHostAlloc)
cudaMemcpyAsync(d_pdX, h_pdX, sizeof(double)*nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdY, h_pdY, sizeof(double)*nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdPhi, h_pdPhi, sizeof(double)*nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdR, h_pdR, sizeof(double)*nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdA, h_pdA, sizeof(double)*nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnMemID, h_pnMemID, sizeof(int)*nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnInitID, d_pnMemID, sizeof(int)*nSpherocyls, cudaMemcpyDeviceToDevice);
m_nDeviceMem += nSpherocyls*(5*sizeof(double)+2*sizeof(int));
#if GOLD_FUNCS == 1
g_pdX = new double[nSpherocyls];
g_pdY = new double[nSpherocyls];
g_pdPhi = new double[nSpherocyls];
g_pdR = new double[nSpherocyls];
g_pdA = new double[nSpherocyls];
g_pnInitID = new int[nSpherocyls];
g_pnMemID = new int[nSpherocyls];
for (int p = 0; p < nSpherocyls; p++)
{
g_pdX[p] = h_pdX[p];
g_pdY[p] = h_pdY[p];
g_pdPhi[p] = h_pdPhi[p];
g_pdR[p] = h_pdR[p];
g_pdA[p] = h_pdA[p];
g_pnMemID[p] = h_pnMemID[p];
g_pnInitID[p] = g_pnMemID[p];
}
#endif
//cout << "Positions transfered to device" << endl;
construct_defaults();
cout << "Memory allocated on device (MB): " << (double)m_nDeviceMem / (1024.*1024.) << endl;
// Get spheocyl coordinates from spherocyls
cudaThreadSynchronize();
//display(0,0,0,0);
}
//Cleans up arrays when class is destroyed
Spherocyl_Box::~Spherocyl_Box()
{
// Host arrays
cudaFreeHost(h_pdX);
cudaFreeHost(h_pdY);
cudaFreeHost(h_pdPhi);
cudaFreeHost(h_pdR);
cudaFreeHost(h_pdA);
cudaFreeHost(h_pnMemID);
cudaFreeHost(h_bNewNbrs);
cudaFreeHost(h_pfSE);
cudaFreeHost(h_pdBlockSums);
delete[] h_pdFx;
delete[] h_pdFy;
delete[] h_pdFt;
delete[] h_pdEnergies;
delete[] h_pnCellID;
delete[] h_pnPPC;
delete[] h_pnCellList;
delete[] h_pnAdjCells;
delete[] h_pnNPP;
delete[] h_pnNbrList;
delete[] h_pdLineEnergy;
// Device arrays
cudaFree(d_pdX);
cudaFree(d_pdY);
cudaFree(d_pdPhi);
cudaFree(d_pdR);
cudaFree(d_pdA);
cudaFree(d_pdTempX);
cudaFree(d_pdTempY);
cudaFree(d_pdTempPhi);
cudaFree(d_pnInitID);
cudaFree(d_pnMemID);
cudaFree(d_pdMOI);
cudaFree(d_pdIsoC);
cudaFree(d_pdXMoved);
cudaFree(d_pdYMoved);
cudaFree(d_bNewNbrs);
cudaFree(d_pfSE);
cudaFree(d_pdBlockSums);
cudaFree(d_pdEnergies);
cudaFree(d_pdFx);
cudaFree(d_pdFy);
cudaFree(d_pdFt);
cudaFree(d_pdTempFx);
cudaFree(d_pdTempFy);
cudaFree(d_pdTempFt);
cudaFree(d_pdDx);
cudaFree(d_pdDy);
cudaFree(d_pdDt);
cudaFree(d_pnCellID);
cudaFree(d_pnPPC);
cudaFree(d_pnCellList);
cudaFree(d_pnAdjCells);
cudaFree(d_pnNPP);
cudaFree(d_pnNbrList);
#if GOLD_FUNCS == 1
delete[] g_pdX;
delete[] g_pdY;
delete[] g_pdPhi;
delete[] g_pdR;
delete[] g_pdA;
delete[] g_pdTempX;
delete[] g_pdTempY;
delete[] g_pdTempPhi;
delete[] g_pdXMoved;
delete[] g_pdYMoved;
delete[] g_pnInitID;
delete[] g_pnMemID;
delete[] g_pfSE;
delete[] g_pdFx;
delete[] g_pdFy;
delete[] g_pdFt;
delete[] g_pnCellID;
delete[] g_pnPPC;
delete[] g_pnCellList;
delete[] g_pnAdjCells;
delete[] g_pnNPP;
delete[] g_pnNbrList;
#endif
}
// Display various info about the configuration which has been calculated
// Mostly used to make sure things are working right
void Spherocyl_Box::display(bool bParticles, bool bCells, bool bNeighbors, bool bStress)
{
cout.precision(9);
if (bParticles)
{
cudaMemcpyAsync(h_pdX, d_pdX, sizeof(double)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, sizeof(double)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, sizeof(double)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdR, d_pdR, sizeof(double)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdA, d_pdA, sizeof(double)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pnMemID, d_pnMemID, sizeof(int)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaThreadSynchronize();
checkCudaError("Display: copying particle data to host");
cout << endl << "Box dimension: " << m_dLx << " x " << m_dLy << endl;;
for (int p = 0; p < m_nSpherocyls; p++)
{
int m = h_pnMemID[p];
cout << "Particle " << p << " (" << m << "): ("
<< h_pdX[m] << ", " << h_pdY[m] << ", " << h_pdPhi[m]
<< ") R = " << h_pdR[m] << " A = " << h_pdA[m] << endl;
}
}
if (bCells)
{
cudaMemcpy(h_pnPPC, d_pnPPC, sizeof(int)*m_nCells, cudaMemcpyDeviceToHost);
cudaMemcpy(h_pnCellList, d_pnCellList, sizeof(int)*m_nCells*m_nMaxPPC, cudaMemcpyDeviceToHost);
checkCudaError("Display: copying cell data to host");
cout << endl;
int nTotal = 0;
int nMaxPPC = 0;
for (int c = 0; c < m_nCells; c++)
{
nTotal += h_pnPPC[c];
nMaxPPC = max(nMaxPPC, h_pnPPC[c]);
cout << "Cell " << c << ": " << h_pnPPC[c] << " particles\n";
for (int p = 0; p < h_pnPPC[c]; p++)
{
cout << h_pnCellList[c*m_nMaxPPC + p] << " ";
}
cout << endl;
}
cout << "Total particles in cells: " << nTotal << endl;
cout << "Maximum particles in any cell: " << nMaxPPC << endl;
}
if (bNeighbors)
{
cudaMemcpy(h_pnNPP, d_pnNPP, sizeof(int)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpy(h_pnNbrList, d_pnNbrList, sizeof(int)*m_nSpherocyls*m_nMaxNbrs, cudaMemcpyDeviceToHost);
checkCudaError("Display: copying neighbor data to host");
cout << endl;
int nMaxNPP = 0;
for (int p = 0; p < m_nSpherocyls; p++)
{
nMaxNPP = max(nMaxNPP, h_pnNPP[p]);
cout << "Particle " << p << ": " << h_pnNPP[p] << " neighbors\n";
for (int n = 0; n < h_pnNPP[p]; n++)
{
cout << h_pnNbrList[n*m_nSpherocyls + p] << " ";
}
cout << endl;
}
cout << "Maximum neighbors of any particle: " << nMaxNPP << endl;
}
if (bStress)
{
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(h_pdFx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpy(h_pdFy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpy(h_pdFt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpy(h_pdEnergies, d_pdEnergies, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaThreadSynchronize();
m_fP = 0.5 * (*m_pfPxx + *m_pfPyy);
cout << endl;
double dEnergyTotal = 0.0;
for (int p = 0; p < m_nSpherocyls; p++)
{
dEnergyTotal += h_pdEnergies[p];
cout << "Particle " << p << ": (" << h_pdFx[p] << ", " << h_pdFy[p] << ", "
<< h_pdFt[p] << ") " << h_pdEnergies[p] << " " << dEnergyTotal << "\n";
}
cout << endl << "Energy: " << *m_pfEnergy << endl;
cout << "Pxx: " << *m_pfPxx << endl;
cout << "Pyy: " << *m_pfPyy << endl;
cout << "Total P: " << m_fP << endl;
cout << "Pxy: " << *m_pfPxy << endl;
cout << "Pyx: " << *m_pfPyx << endl;
}
}
bool Spherocyl_Box::check_for_contacts(int nIndex, double dTol)
{
double dS = 2 * ( m_dAMax + m_dRMax );
double dX = h_pdX[nIndex];
double dY = h_pdY[nIndex];
for (int p = 0; p < nIndex; p++) {
//cout << "Checking: " << nIndex << " vs " << p << endl;
double dXj = h_pdX[p];
double dYj = h_pdY[p];
double dDelX = dX - dXj;
double dDelY = dY - dYj;
dDelX += m_dLx * ((dDelX < -0.5*m_dLx) - (dDelX > 0.5*m_dLx));
dDelY += m_dLy * ((dDelY < -0.5*m_dLy) - (dDelY > 0.5*m_dLy));
dDelX += m_dGamma * dDelY;
double dDelRSqr = dDelX * dDelX + dDelY * dDelY;
if (dDelRSqr < dS*dS) {
double dPhi = h_pdPhi[nIndex];
double dR = h_pdR[nIndex];
double dA = h_pdA[nIndex];
double dDeltaX = dX - dXj;
double dDeltaY = dY - dYj;
double dPhiB = h_pdPhi[p];
double dSigma = dR + h_pdR[p];
double dB = h_pdA[p];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += m_dLx * ((dDeltaX < -0.5*m_dLx) - (dDeltaX > 0.5*m_dLx));
dDeltaY += m_dLy * ((dDeltaY < -0.5*m_dLy) - (dDeltaY > 0.5*m_dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += m_dGamma * dDeltaX;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
double s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < (1-dTol)*dSigma*dSigma || dDSqr != dDSqr)
return 1;
}
}
return 0;
}
bool Spherocyl_Box::check_for_crosses(int nIndex, double dEpsilon)
{
double dX = h_pdX[nIndex];
double dY = h_pdY[nIndex];
for (int p = 0; p < nIndex; p++) {
//cout << "Checking: " << nIndex << " vs " << p << endl;
double dXj = h_pdX[p];
double dYj = h_pdY[p];
double dPhi = h_pdPhi[nIndex];
double dR = h_pdR[nIndex];
double dA = h_pdA[nIndex];
double dDeltaX = dX - dXj;
double dDeltaY = dY - dYj;
double dPhiB = h_pdPhi[p];
double dSigma = dR + h_pdR[p];
double dB = h_pdA[p];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += m_dLx * ((dDeltaX < -0.5*m_dLx) - (dDeltaX > 0.5*m_dLx));
dDeltaY += m_dLy * ((dDeltaY < -0.5*m_dLy) - (dDeltaY > 0.5*m_dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += m_dGamma * dDeltaX;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
double s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dEpsilon*dSigma*dSigma || dDSqr != dDSqr)
return 1;
}
return 0;
}
#if SHEAR_INIT == 1
double Spherocyl_Box::uniformToAngleDist(double dUniform, double dC)
{
double dAngle;
if (dC == 0) {
dAngle = D_PI*dUniform-D_PI/2;
}
else {
dAngle = atan(sqrt(1-dC*dC)*tan(D_PI*(dUniform-0.5))/(1+dC));
}
return dAngle;
}
#else
double Spherocyl_Box::uniformToAngleDist(double dUniform, double dC)
{
double dAngle = D_PI*dUniform-D_PI/2;
return dAngle;
}
#endif
void Spherocyl_Box::place_random_0e_spherocyls(int seed, bool bRandAngle, double dBidispersity)
{
srand(time(0) + seed);
double dAspect = m_dAMax / m_dRMax;
double dC = dAspect*(8/dAspect + 6*D_PI + 8*dAspect)/(3*D_PI/dAspect + 24 + 6*D_PI*dAspect + 8*dAspect*dAspect);
double dR = 0.5;
double dA = dAspect * dR;
double dRDiff = (dBidispersity-1) * dR;
double dADiff = (dBidispersity-1) * dA;
for (int p = 0; p < m_nSpherocyls; p++) {
h_pdR[p] = dR + (1-(p%2))*dRDiff;
h_pdA[p] = dA + (1-(p%2))*dADiff;
h_pnMemID[p] = p;
}
cudaMemcpy(d_pdR, h_pdR, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdA, h_pdA, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnInitID, h_pnMemID, sizeof(int)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnMemID, h_pnMemID, sizeof(int)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaThreadSynchronize();
h_pdX[0] = m_dLx * static_cast<double>(rand())/static_cast<double>(RAND_MAX);
h_pdY[0] = m_dLy * static_cast<double>(rand())/static_cast<double>(RAND_MAX);
if (bRandAngle)
h_pdPhi[0] = uniformToAngleDist( static_cast<double>(rand())/static_cast<double>(RAND_MAX), dC);
else
h_pdPhi[0] = 0;
for (int p = 1; p < m_nSpherocyls; p++) {
bool bContact = 1;
int nTries = 0;
while (bContact) {
h_pdX[p] = m_dLx * static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
h_pdY[p] = m_dLy * static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
if (bRandAngle)
h_pdPhi[p] = uniformToAngleDist( static_cast<double>(rand()) / static_cast<double>(RAND_MAX), dC);
else
h_pdPhi[p] = 0;
bContact = check_for_contacts(p);
nTries += 1;
}
cout << "Spherocyl " << p << " placed in " << nTries << " attempts." << endl;
}
cudaMemcpyAsync(d_pdX, h_pdX, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdY, h_pdY, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdPhi, h_pdPhi, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaThreadSynchronize();
cout << "Data copied to device" << endl;
}
void Spherocyl_Box::place_random_spherocyls(int seed, bool bRandAngle, double dBidispersity)
{
srand(time(0) + seed);
double dAspect = m_dAMax / m_dRMax;
double dC = dAspect*(8/dAspect + 6*D_PI + 8*dAspect)/(3*D_PI/dAspect + 24 + 6*D_PI*dAspect + 8*dAspect*dAspect);
double dR = 0.5;
double dA = dAspect * dR;
double dRDiff = (dBidispersity-1) * dR;
double dADiff = (dBidispersity-1) * dA;
for (int p = 0; p < m_nSpherocyls; p++) {
h_pdR[p] = dR + (1-(p%2))*dRDiff;
h_pdA[p] = dA + (1-(p%2))*dADiff;
h_pnMemID[p] = p;
}
cudaMemcpy(d_pdR, h_pdR, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdA, h_pdA, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnInitID, h_pnMemID, sizeof(int)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnMemID, h_pnMemID, sizeof(int)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaThreadSynchronize();
h_pdX[0] = m_dLx * static_cast<double>(rand())/static_cast<double>(RAND_MAX);
h_pdY[0] = m_dLy * static_cast<double>(rand())/static_cast<double>(RAND_MAX);
if (bRandAngle)
h_pdPhi[0] = uniformToAngleDist( static_cast<double>(rand())/static_cast<double>(RAND_MAX), dC);
else
h_pdPhi[0] = 0;
for (int p = 1; p < m_nSpherocyls; p++) {
bool bContact = 1;
int nTries = 0;
while (bContact) {
h_pdX[p] = m_dLx * static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
h_pdY[p] = m_dLy * static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
if (bRandAngle)
h_pdPhi[p] = uniformToAngleDist( static_cast<double>(rand()) / static_cast<double>(RAND_MAX), dC);
else
h_pdPhi[p] = 0;
bContact = check_for_crosses(p);
nTries += 1;
}
cout << "Spherocylinder " << p << " placed in " << nTries << " attempts." << endl;
}
cudaMemcpyAsync(d_pdX, h_pdX, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdY, h_pdY, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdPhi, h_pdPhi, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaThreadSynchronize();
cout << "Data copied to device" << endl;
}
void Spherocyl_Box::place_spherocyl_grid(int seed, bool bRandAngle)
{
double dAspect = (m_dAMax + m_dRMax) / m_dRMax;
double dA = dAspect - 1.;
double dC = dA*(8 + 6*D_PI*dA + 8*dA*dA)/(3*D_PI + 24*dA + 6*D_PI*dA*dA + 8*dA*dA*dA);
double dCols = sqrt(m_nSpherocyls/dAspect);
int nRows = int(dAspect*dCols);
int nCols = int(dCols);
double dWidth = m_dLx/nCols;
double dHeight = m_dLy/nRows;
if (dWidth < 2*(m_dAMax+m_dRMax) || dHeight < 2*m_dRMax) {
cerr << "Error: Spherocylinders will not fit into square grid, change the number or size of box" << endl;
exit(1);
}
srand(time(0) + seed);
/*
double *pdColOffsets = new double[nCols];
pdColOffsets[0] = 0;
for (int c = 1; c < nCols; c++) {
pdColOffsets[c] = m_dRMax*(1. - 2*static_cast<double>(rand())/static_cast<double>(RAND_MAX));
}
*/
double *pdRowOffsets = new double[nRows];
pdRowOffsets[0] = 0;
for (int r = 1; r < nRows; r++) {
pdRowOffsets[r] = (m_dRMax + m_dAMax)*(1. - 2*static_cast<double>(rand())/static_cast<double>(RAND_MAX));
}
for (int p = 0; p < m_nSpherocyls; p++) {
h_pdR[p] = m_dRMax;
h_pdA[p] = m_dAMax;
h_pnMemID[p] = p;
}
cudaMemcpy(d_pdR, h_pdR, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdA, h_pdA, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnInitID, h_pnMemID, sizeof(int)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnMemID, h_pnMemID, sizeof(int)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaThreadSynchronize();
double dXOffset = m_dAMax + m_dRMax;
double dRWidth = dWidth - 2*dXOffset;
double dYOffset = m_dRMax;
double dRHeight = dHeight - 2*dYOffset;
h_pdX[0] = dXOffset + dRWidth* static_cast<double>(rand())/static_cast<double>(RAND_MAX);
h_pdY[0] = dYOffset + dRHeight * static_cast<double>(rand())/static_cast<double>(RAND_MAX);
if (bRandAngle)
h_pdPhi[0] = uniformToAngleDist( static_cast<double>(rand())/static_cast<double>(RAND_MAX), dC);
else
h_pdPhi[0] = 0;
for (int p = 1; p < m_nSpherocyls; p++) {
bool bContact = 1;
int nTries = 0;
int nR = p / nCols;
int nC = p % nCols;
//double dCOffset = pdColOffsets[nC];
double dROffset = pdRowOffsets[nR];
double dCOffset = 0;
while (bContact) {
h_pdX[p] = nC*dWidth + dXOffset + dROffset + dRWidth * static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
h_pdY[p] = nR*dHeight + dYOffset + dCOffset + dRHeight * static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
if (bRandAngle)
h_pdPhi[p] = uniformToAngleDist( static_cast<double>(rand()) / static_cast<double>(RAND_MAX), dC);
else
h_pdPhi[p] = 0;
bContact = check_for_crosses(p);
nTries += 1;
}
cout << "Spherocylinder " << p << " placed in " << nTries << " attempts." << endl;
}
//flip_group();
cudaMemcpyAsync(d_pdX, h_pdX, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdY, h_pdY, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdPhi, h_pdPhi, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaThreadSynchronize();
cout << "Data copied to device" << endl;
//delete[] pdColOffsets;
delete[] pdRowOffsets;
}
double log_normal(double dNormalRand, double dMu, double dSig) {
return exp(log(dMu) + dSig*dNormalRand);
}
void Spherocyl_Box::set_shapes(int seed, double dBidispersity) {
if (m_dASig > 0) {
cout << "Setting shapes, Aspect sigma = " << m_dASig << endl;
srand(time(0) + seed);
double dAMu = m_dAMax / m_dRMax;
double dASigAbs = dAMu * m_dASig;
double dR = 0.5;
double dRDiff = (dBidispersity-1) * dR;
double dTargetPack = 0.5*(1 + dBidispersity*dBidispersity) * m_nSpherocyls * dR*dR * (4*dAMu + D_PI)/(m_dLx*m_dLy);
double dK = dAMu*dAMu/(dASigAbs*dASigAbs);
double dT = dASigAbs*dASigAbs/dAMu;
default_random_engine generator;
gamma_distribution<double> gamma_dist(dK, dT);
for (int p = 0; p < m_nSpherocyls; p++) {
h_pdR[p] = dR + (1-(p%2))*dRDiff;
double dAlpha = gamma_dist(generator);
h_pdA[p] = h_pdR[p]*dAlpha;
if (h_pdA[p] > m_dAMax)
m_dAMax = h_pdA[p];
h_pnMemID[p] = p;
//cout << "Shape for particle " << p << ": " << h_pdR[p] << " " << h_pdA[p] << endl;
}
cout << "Shape distribution set" << endl;
cout << "Alpha mean: " << dAMu << ", Absolute sigma: " << dASigAbs << ", A max: " << m_dAMax << endl;
double dActualPack = calculate_packing();
cout << "Target pack: " << dTargetPack << ", Actual pack: " << dActualPack << endl;
double dPackDelta = sqrt(dActualPack/dTargetPack);
cout << "Packing adjustment: " << dPackDelta << endl;
m_dLx *= dPackDelta;
m_dLy *= dPackDelta;
m_dPacking = calculate_packing();
cout << "Corrected packing: " << m_dPacking << endl;
}
else {
cout << "Setting shapes, Aspect sigma = " << "None" << endl;
double dAspect = m_dAMax / m_dRMax;
double dR = 0.5;
double dA = dAspect * dR;
double dRDiff = (dBidispersity-1) * dR;
double dADiff = (dBidispersity-1) * dA;
//cout << "Aspect: " << dAspect << " R/A min: " << dR << "/" << dA << " R/A diff: " << dRDiff << "/" << dADiff << endl;
for (int p = 0; p < m_nSpherocyls; p++) {
//cout << p << ": R: " << dR + (1-(p%2))*dRDiff << " A: " << dA + (1-(p%2))*dADiff << endl;
h_pdR[p] = dR + (1-(p%2))*dRDiff;
h_pdA[p] = dA + (1-(p%2))*dADiff;
h_pnMemID[p] = p;
}
}
}
void Spherocyl_Box::place_spherocyls(Config config, int seed, double dBidispersity)
{
//TODO: implement grid placement with bidisperse particles
if (config.type == GRID) {
bool bRandAngle = bool(config.maxAngle - config.minAngle);
place_spherocyl_grid(seed, bRandAngle);
}
else {
srand(time(0) + seed);
double dAspect = m_dAMax / m_dRMax;
double dC = dAspect*(8 + 6*D_PI*dAspect + 8*dAspect*dAspect)/(3*D_PI + 24*dAspect + 6*D_PI*dAspect*dAspect + 8*dAspect*dAspect*dAspect);
/*
double dR = 0.5;
double dA = dAspect * dR;
double dRDiff = (dBidispersity-1) * dR;
double dADiff = (dBidispersity-1) * dA;
for (int p = 0; p < m_nSpherocyls; p++) {
h_pdR[p] = dR + (1-(p%2))*dRDiff;
h_pdA[p] = dA + (1-(p%2))*dADiff;
h_pnMemID[p] = p;
}
cudaMemcpy(d_pdR, h_pdR, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdA, h_pdA, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnInitID, h_pnMemID, sizeof(int)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pnMemID, h_pnMemID, sizeof(int)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaThreadSynchronize();
*/
h_pdX[0] = m_dLx * static_cast<double>(rand())/static_cast<double>(RAND_MAX);
h_pdY[0] = m_dLy * static_cast<double>(rand())/static_cast<double>(RAND_MAX);
if (config.angleType == RANDOM) {
cout << "Finding configuration with random angle from " << config.minAngle << " to " << config.maxAngle << endl;
double dUniformRand = config.minAngle + ((config.maxAngle - config.minAngle) * static_cast<double>(rand())/static_cast<double>(RAND_MAX));
h_pdPhi[0] = uniformToAngleDist(dUniformRand, dC);
cout << "Angle 0: " << h_pdPhi[0] << endl;
}
else {
cout << "Finding configuration with uniform angle from " << config.minAngle << " to " << config.maxAngle << endl;
double dUniformAngle = config.minAngle + ((config.maxAngle - config.minAngle)/(2*m_nSpherocyls));
h_pdPhi[0] = uniformToAngleDist(dUniformAngle, dC);
cout << "Angle 0: " << h_pdPhi[0] << endl;
}
for (int p = 1; p < m_nSpherocyls; p++) {
bool bContact = 1;
int nTries = 0;
while (bContact) {
h_pdX[p] = m_dLx * static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
h_pdY[p] = m_dLy * static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
if (config.angleType == RANDOM) {
double dUniformRand = config.minAngle + ((config.maxAngle - config.minAngle) * static_cast<double>(rand())/static_cast<double>(RAND_MAX));
h_pdPhi[p] = uniformToAngleDist(dUniformRand, dC);
}
else {
double dUniformAngle = config.minAngle + ((2*p+1)*(config.maxAngle - config.minAngle)/(2*m_nSpherocyls));
h_pdPhi[p] = uniformToAngleDist(dUniformAngle, dC);
}
if (config.overlap >= 1)
bContact = check_for_crosses(p);
else
bContact = check_for_contacts(p, config.overlap);
nTries += 1;
}
cout << "Spherocylinder " << p << " placed in " << nTries << " attempts." << endl;
}
cudaMemcpyAsync(d_pdX, h_pdX, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdY, h_pdY, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdPhi, h_pdPhi, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaThreadSynchronize();
cout << "Data copied to device" << endl;
}
}
void Spherocyl_Box::flip_group()
{
int nGroup = int((m_dRMax + m_dAMax)/m_dRMax);
int nCols = int(sqrt(m_nSpherocyls / nGroup));
for (int i = 0; i < nGroup*nCols; i += nCols) {
double dOldX = h_pdX[i];
double dOldY = h_pdY[i];
h_pdX[i] = dOldY;
h_pdY[i] = dOldX;
h_pdPhi[i] += D_PI/2;
}
cudaMemcpyAsync(d_pdX, h_pdX, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdY, h_pdY, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaMemcpyAsync(d_pdPhi, h_pdPhi, sizeof(double)*m_nSpherocyls, cudaMemcpyHostToDevice);
cudaThreadSynchronize();
cout << "Data copied to device" << endl;
}
void Spherocyl_Box::get_0e_configs(int nConfigs, double dBidispersity)
{
for (int i = 0; i < nConfigs; i++) {
place_random_0e_spherocyls(i, 1, dBidispersity);
save_positions(i);
}
}
<file_sep>/src/cpp/spherocyl_box.h
#include <vector>
#include <string>
#include <fstream>
#ifndef SPHEROCYL_BOX_H
#define SPHEROCYL_BOX_H
enum initialConfig {RANDOM, RANDOM_ALIGNED, ZERO_E, ZERO_E_ALIGNED};
struct Spherocyl {
double m_dX; //the x-coordinate
double m_dY; //the y-coordinate
double m_dPhi; //the orientation
double m_dR; //the radius
double m_dA; //the half-shaft length
int m_nCell; //the cell the particle is in
double m_dFx; //The total force on the particle's center of mass in the x direction
double m_dFy; //The total force on the particle's center of mass in the y direction
double m_dTau; //The total torque on the particle
double m_dXMoved;
double m_dYMoved;
double m_dI; // I (moment of inertia for massive particle)
double m_dRC; // Isolated rotation coefficient [ f(phi) = (1-m_dRC*cos(2*phi))/2 ]
};
class SpherocylBox
{
private:
double m_dLx;
double m_dLy;
double m_dGamma;
double m_dGammaTotal;
double m_dStrainRate;
double m_dResizeRate;
double m_dStep;
double m_dPosSaveStep;
double m_dSESaveStep;
double m_dPacking;
double m_dAmax;
double m_dRmax;
double m_dPadding;
double m_dMaxMoved;
double m_dEnergy;
double m_dPxx;
double m_dPyy;
double m_dPxy;
double m_dPyx; // Will probably not be the same as Pxy because there may be a net torque while shearing
Spherocyl *m_psParticles;
Spherocyl *m_psTempParticles;
int m_nParticles;
std::vector<int> *m_pvCells;
int m_nCellCols;
int m_nCellRows;
int m_nCells;
double m_dCellWidth;
double m_dCellHeight;
int **m_pnCellNeighbors;
std::vector<int> *m_pvNeighbors;
std::string m_strOutputDir;
std::string m_strSEOutput;
void set_defaults();
bool check_neighbors(int p, int q);
double calculate_packing_fraction();
void set_back_gamma();
void calc_se_force_pair(int p, int q);
void calc_force_pair(int p, int q);
void calc_temp_force_pair(int p, int q);
void calc_temp_forces();
void strain_step();
void calc_resized_force_pair(int p, int q, bool bShrink);
void calc_resized_forces(bool bShrink);
void resize_step(bool bShrink);
void gradient_relax_step();
void reconfigure_cells();
bool check_particle_contact(int p, int q);
bool check_particle_contact(int p);
bool check_particle_cross(int p, int q);
bool check_particle_cross(int p);
public:
SpherocylBox();
SpherocylBox(double dL, int nParticles);
SpherocylBox(double dL, int nParticles, double dPadding);
SpherocylBox(double dL, int nParticles, double *pdX, double *pdY, double *pdPhi, double dA, double dR);
SpherocylBox(double dL, int nParticles, double *pdX, double *pdY, double *pdPhi, double dA, double dR, double dPadding);
SpherocylBox(double dL, int nParticles, double *pdX, double *pdY, double *pdPhi, double *pdA, double *pdR);
SpherocylBox(double dL, int nParticles, double *pdX, double *pdY, double *pdPhi, double *pdA, double *pdR, double dPadding);
~SpherocylBox();
void set_particle(int nIndex, double dX, double dY, double dPhi, double dA, double dR);
void configure_cells();
void find_cells();
void find_neighbors();
void display(bool bParticles = 0, bool bCells = 0);
void save_positions(std::string strFile);
void calc_se();
void calc_forces();
void random_configuration(double dA, double dR, initialConfig config = RANDOM);
long unsigned int run_strain(double dRunLength);
long unsigned int run_strain(double dRunLength, long unsigned int nTime);
long unsigned int resize_box(double dFinalPacking);
long unsigned int resize_box(double dFinalPacking, long unsigned int nTime);
void gradient_descent_minimize(int nMaxSteps = 1000000, double dMinE = 0);
void set_output_directory(std::string strOutputDir) { m_strOutputDir = strOutputDir; }
void set_se_file(std::string strSEOutput) { m_strSEOutput = strSEOutput; }
void set_strain_rate(double dStrainRate) { m_dStrainRate = dStrainRate; }
void set_resize_rate(double dResizeRate) { m_dResizeRate = dResizeRate; }
void set_step(double dStep) { m_dStep = dStep; }
void set_pos_save_step(double dPosSaveStep) { m_dPosSaveStep = dPosSaveStep; }
void set_se_save_step(double dSESaveStep) { m_dSESaveStep = dSESaveStep; }
void set_cell_padding(double dPadding) { m_dPadding = dPadding; }
void set_gamma(double dGamma) { m_dGamma = dGamma; }
void set_total_gamma(double dTotalGamma) { m_dGammaTotal = dTotalGamma; }
};
#endif
<file_sep>/src/cuda/find_neighbors_2.cu
// -*- c++ -*-
/*
* find_neighbors.cu
*
*
*
*
*/
#include <cuda.h>
#include "spherocyl_box.h"
#include "cudaErr.h"
#include "data_primitives.h"
#include <sm_20_atomic_functions.h>
#include <math.h>
using namespace std;
///////////////////////////////////////////////////////////////
// Find the Cell ID for each particle:
// The list of cell IDs for each particle is returned to pnCellID
// A list of which particles are in each cell is returned to pnCellList
//
// *NOTE* if there are more than nMaxPPC particles in a given cell,
// not all of these particles will get added to the cell list
///////////////////////////////////////////////////////////////
__global__ void find_cells(int nSpherocyls, int nMaxPPC, double dCellW, double dCellH,
int nCellCols, double dL, double *pdX, double *pdY,
int *pnCellID, int *pnPPC, int *pnCellList)
{
// Assign each thread a unique ID accross all thread-blocks, this is its particle ID
int nPID = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
while (nPID < nSpherocyls) {
double dX = pdX[nPID];
double dY = pdY[nPID];
// I often allow the stored coordinates to drift slightly outside the box limits
// until
if (dY > dL)
{
dY -= dL;
pdY[nPID] = dY;
}
else if (dY < 0)
{
dY += dL;
pdY[nPID] = dY;
}
if (dX > dL)
{
dX -= dL;
pdX[nPID] = dX;
}
else if (dX < 0)
{
dX += dL;
pdX[nPID] = dX;
}
//find the cell ID, add a particle to that cell
int nCol = (int)(dX / dCellW);
int nRow = (int)(dY / dCellH);
int nCellID = nCol + nRow * nCellCols;
pnCellID[nPID] = nCellID;
// Add 1 particle to a cell safely (only allows one thread to access the memory
// address at a time). nPPC is the original value, not the result of addition
int nPPC = atomicAdd(pnPPC + nCellID, 1);
// only add particle to cell if there is not already the maximum number in cell
if (nPPC < nMaxPPC)
pnCellList[nCellID * nMaxPPC + nPPC] = nPID;
else
nPPC = atomicAdd(pnPPC + nCellID, -1);
nPID += nThreads;
}
}
////////////////////////////////////////////////////////////////
// Here a list of possible contacts is created for each particle
// The list of neighbors is returned to pnNbrList
//
// This is one function that I may target for optimization in
// the future because I know it is slowed down by branch divergence
////////////////////////////////////////////////////////////////
__global__ void find_nbrs(int nSpherocyls, int nMaxPPC, int *pnCellID, int *pnPPC,
int *pnCellList, int *pnAdjCells, int nMaxNbrs, int *pnNPP,
int *pnNbrList, double *pdX, double *pdY, double *pdR,
double dEpsilon, double dL, double dGamma)
{
extern __shared__ int sData[];
int thid = threadIdx.x;
int blsz = blockDim.x;
int blid = blockIdx.x;
int nPID = thid + blid * blsz;
int nThreads = gridDim.x * blsz;
while (nPID < nSpherocyls)
{
double dX = pdX[nPID];
double dY = pdY[nPID];
double dR = pdR[nPID];
int nNbrs = 0;
// Particles in adjacent cells are added if they are close enough to
// interact without each moving by more than dEpsilon/2
int nCellID = pnCellID[nPID];
int nP = pnPPC[nCellID];
for (int p = 0; p < nP; p++)
{
int nAdjPID = pnCellList[nCellID*nMaxPPC + p];
if (nAdjPID != nPID)
{
double dSigma = dR + pdR[nAdjPID] + dEpsilon;
double dDeltaY = dY - pdY[nAdjPID];
dDeltaY += dL * ((dDeltaY < -0.5 * dL) - (dDeltaY > 0.5 * dL));
if (fabs(dDeltaY) < dSigma)
{
double dDeltaX = dX - pdX[nAdjPID];
dDeltaX += dL * ((dDeltaX < -0.5 * dL) - (dDeltaX > 0.5 * dL));
double dDeltaRx = dDeltaX + dGamma * dDeltaY;
double dDeltaRx2 = dDeltaX + 0.5 * dDeltaY;
if (fabs(dDeltaRx) < dSigma || fabs(dDeltaRx2) < dSigma)
{
// This indexing makes global memory accesses more coalesced
if (nNbrs < nMaxNbrs)
{
//pnNbrList[nSpherocyls * nNbrs + nPID] = nAdjPID;
sData[blsz * nNbrs + thid] = nAdjPID;
nNbrs += 1;
}
}
}
}
}
for (int nc = 0; nc < 8; nc++)
{
int nAdjCID = pnAdjCells[8 * nCellID + nc];
nP = pnPPC[nAdjCID];
for (int p = 0; p < nP; p++)
{
int nAdjPID = pnCellList[nAdjCID*nMaxPPC + p];
// The maximum distance at which two particles could contact
// plus a little bit of moving room - dEpsilon
double dSigma = dR + pdR[nAdjPID] + dEpsilon;
double dDeltaY = dY - pdY[nAdjPID];
// Make sure were finding the closest separation
dDeltaY += dL * ((dDeltaY < -0.5 * dL) - (dDeltaY > 0.5 * dL));
if (fabs(dDeltaY) < dSigma)
{
double dDeltaX = dX - pdX[nAdjPID];
dDeltaX += dL * ((dDeltaX < -0.5 * dL) - (dDeltaX > 0.5 * dL));
// Go to unsheared coordinates
double dDeltaRx = dDeltaX + dGamma * dDeltaY;
// Also look at distance when the strain parameter is at its max (0.5)
double dDeltaRx2 = dDeltaX + 0.5 * dDeltaY;
if (fabs(dDeltaRx) < dSigma || fabs(dDeltaRx2) < dSigma)
{
if (nNbrs < nMaxNbrs)
{
//pnNbrList[nSpherocyls * nNbrs + nPID] = nAdjPID;
sData[blsz * nNbrs + thid] = nAdjPID;
nNbrs += 1;
}
}
}
}
}
pnNPP[nPID] = nNbrs;
for (int n = 0; n < nNbrs; n++) {
pnNbrList[nSpherocyls * n + nPID] = sData[blsz * n + thid];
}
nPID += nThreads;
}
}
__global__ void get_nbr_blocks(int nSpherocyls, int *pnNNbrs, int *pnNbrList, int *pnBlockNbrs, int *pnBlockList)
{
extern __shared__ int sData[];
int thid = threadIdx.x;
int blid = blockIdx.x;
int blsz = blockDim.x;
int nPID = thid + blid * blsz;
while (nPID < nSpherocyls) {
sData[thid] = pnNNbrs[nPID];
int nNbrs = sData[thid];
__syncthreads();
int offset = 1;
for (int d = blsz / 2; d > 0; d /= 2) {
if (thid < d) {
int ai = offset*(2*thid + 1) - 1;
int bi = offset*(2*thid + 2) - 1;
sData[bi] += sData[ai];
}
offset *= 2;
__syncthreads();
}
int nTotNbrs = sData[blsz - 1];
int nSortMax = 256;
int s = nTotNbrs / 256;
while (s > 0) {
nSortMax *= 2;
s /= 2;
}
__syncthreads();
if (thid == 0) {
sData[blsz - 1] = 0;
//pnBlockNbrs[blid] = nTotNbrs;
}
for (int d = 1; d < blsz; d *= 2) {
__syncthreads();
offset /= 2;
if (thid < d) {
int ai = offset*(2*thid + 1) - 1;
int bi = offset*(2*thid + 2) - 1;
int temp = sData[ai];
sData[ai] = sData[bi];
sData[bi] += temp;
}
}
__syncthreads();
//int *pnList = &sData[blsz];
int nID = sData[thid];
for (int n = 0; n < nNbrs; n++) {
sData[blsz + nID + n] = pnNbrList[n * nSpherocyls + nPID];
}
for (int t = nTotNbrs + thid; t < nSortMax; t += blsz) {
sData[blsz + t] = nSpherocyls;
}
__syncthreads();
//for (int t = thid; t < 2048; t += blsz){
//pnBlockList[2048*blid + t] = pnList[t];
//}
for (int oblock = 1; oblock < nSortMax; oblock *= 2) {
int t = thid;
int obid = t / oblock;
while (obid < nSortMax / (2 * oblock)) {
for (int iblock = oblock; iblock > 0; iblock /= 2) {
int s = (t % oblock);
int ibid = s / iblock;
while (ibid < oblock / iblock) {
int ai, bi;
if (obid % 2) {
bi = blsz + 2 * (oblock * obid + iblock * ibid) + s % iblock;
ai = bi + iblock;
}
else {
ai = blsz + 2 * (oblock * obid + iblock * ibid) + s % iblock;
bi = ai + iblock;
}
if (sData[ai] > sData[bi]) {
int temp = sData[ai];
sData[ai] = sData[bi];
sData[bi] = temp;
}
s += blsz;
ibid = s / iblock;
}
if (iblock > 32)
__syncthreads();
}
t += blsz;
obid = t / oblock;
}
__syncthreads();
}
//int *pnCID = &pnList[nSortMax];
for (int t = thid; t < nSortMax - 1; t += blsz) {
if (sData[blsz + t] == sData[blsz + t + 1])
sData[blsz + nSortMax + t] = 0;
else
sData[blsz + nSortMax + t] = 1;
}
if (thid == 0)
sData[blsz + 2 * nSortMax - 1] = 0;
__syncthreads();
offset = 1;
for (int d = nSortMax / 2; d > 0; d /= 2) {
int t = thid;
while (t < d) {
int ai = blsz + nSortMax + offset*(2*t + 1) - 1;
int bi = blsz + nSortMax + offset*(2*t + 2) - 1;
sData[bi] += sData[ai];
t += blsz;
}
offset *= 2;
__syncthreads();
}
nTotNbrs = sData[blsz + 2 * nSortMax - 1];
__syncthreads();
if (thid == 0) {
sData[blsz + 2*nSortMax - 1] = 0;
pnBlockNbrs[blid] = nTotNbrs;
}
for (int d = 1; d < nSortMax; d *= 2) {
__syncthreads();
int t = thid;
offset /= 2;
while (t < d) {
int ai = blsz + nSortMax + offset*(2*t + 1) - 1;
int bi = blsz + nSortMax + offset*(2*t + 2) - 1;
int temp = sData[ai];
sData[ai] = sData[bi];
sData[bi] += temp;
t += blsz;
}
}
__syncthreads();
for (int t = thid; t < nSortMax - 1; t += blsz) {
if (sData[blsz + t] != sData[blsz + t + 1])
pnBlockList[blid*8*blsz + sData[blsz + nSortMax + t]] = sData[blsz + t];
}
__syncthreads();
for (int t = thid; t < nTotNbrs; t += blsz) {
sData[t] = pnBlockList[blid*8*blsz + t];
}
__syncthreads();
for (int n = 0; n < nNbrs; n++) {
int oldID = pnNbrList[nSpherocyls * n + nPID];
int newID = nTotNbrs / 2;
int diff = max(-newID, min(oldID - sData[newID], nTotNbrs - 1 - newID));
int dStep = newID / 2;
newID += diff;
while (dStep > 0) {
diff = max(max(-dStep, -newID), min(oldID - sData[newID], min(dStep, nTotNbrs - 1 - newID)));
newID += diff;
dStep /= 2;
}
pnNbrList[nSpherocyls*n + nPID] = newID;
}
blid += gridDim.x;
nPID += gridDim.x * blsz;
}
}
///////////////////////////////////////////////////////////////
// Finds a list of possible contacts for each particle
//
// Usually when things are moving I keep track of an Xmoved and Ymoved
// and only call this to make a new list of neighbors if some particle
// has moved more than (dEpsilon / 2) in some direction
///////////////////////////////////////////////////////////////
void Spherocyl_Box::find_neighbors()
{
// reset each byte to 0
cudaMemset((void *) d_pnPPC, 0, sizeof(int)*m_nCells);
cudaMemset((void *) d_pdXMoved, 0, sizeof(double)*m_nSpherocyls);
cudaMemset((void *) d_pdYMoved, 0, sizeof(double)*m_nSpherocyls);
cudaMemset((void *) d_bNewNbrs, 0, sizeof(int));
find_cells <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, m_nMaxPPC, m_dCellW, m_dCellH, m_nCellCols,
m_dL, d_pdX, d_pdY, d_pnCellID, d_pnPPC, d_pnCellList);
cudaThreadSynchronize();
checkCudaError("Finding cells");
find_nbrs <<<m_nGridSize, m_nBlockSize, m_nSM_FindCells>>>
(m_nSpherocyls, m_nMaxPPC, d_pnCellID, d_pnPPC, d_pnCellList, d_pnAdjCells,
m_nMaxNbrs, d_pnNPP, d_pnNbrList, d_pdX, d_pdY, d_pdR, m_dEpsilon, m_dL, m_dGamma);
cudaThreadSynchronize();
checkCudaError("Finding neighbors");
get_nbr_blocks <<<m_nGridSize, m_nBlockSize, m_nSM_GetNbrBlks>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, d_pnBlockNNbrs, d_pnBlockList);
cudaThreadSynchronize();
checkCudaError("Getting neighbor blocks");
}
////////////////////////////////////////////////////////////////////////////////////
// Sets gamma back by 1 (used when gamma > 0.5)
// also finds the cells in the process
//
///////////////////////////////////////////////////////////////////////////////////
__global__ void set_back_coords(int nSpherocyls, int nMaxPPC, double dCellW, double dCellH,
int nCellCols, double dL, double *pdX, double *pdY,
int *pnCellID, int *pnPPC, int *pnCellList)
{
// Assign each thread a unique ID accross all thread-blocks, this is its particle ID
int nPID = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
while (nPID < nSpherocyls) {
double dX = pdX[nPID];
double dY = pdY[nPID];
// I often allow the stored coordinates to drift slightly outside the box limits
// until
if (dY > dL)
{
dY -= dL;
pdY[nPID] = dY;
}
else if (dY < 0)
{
dY += dL;
pdY[nPID] = dY;
}
// When gamma -> gamma-1, Xi -> Xi + Yi
dX += dY;
if (dX < 0)
{
dX += dL;
}
while (dX > dL)
{
dX -= dL;
}
pdX[nPID] = dX;
//find the cell ID, add a particle to that cell
int nCol = (int)(dX / dCellW);
int nRow = (int)(dY / dCellH);
int nCellID = nCol + nRow * nCellCols;
pnCellID[nPID] = nCellID;
// Add 1 particle to a cell safely (only allows one thread to access the memory
// address at a time). nPPC is the original value, not the result of addition
int nPPC = atomicAdd(pnPPC + nCellID, 1);
// only add particle to cell if there is not already the maximum number in cell
if (nPPC < nMaxPPC)
pnCellList[nCellID * nMaxPPC + nPPC] = nPID;
else
nPPC = atomicAdd(pnPPC + nCellID, -1);
nPID += nThreads;
}
}
void Spherocyl_Box::set_back_gamma()
{
cudaMemset((void *) d_pnPPC, 0, sizeof(int)*m_nCells);
cudaMemset((void *) d_pdXMoved, 0, sizeof(double)*m_nSpherocyls);
cudaMemset((void *) d_pdYMoved, 0, sizeof(double)*m_nSpherocyls);
cudaMemset((void *) d_bNewNbrs, 0, sizeof(int));
set_back_coords <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, m_nMaxPPC, m_dCellW, m_dCellH, m_nCellCols,
m_dL, d_pdX, d_pdY, d_pnCellID, d_pnPPC, d_pnCellList);
cudaThreadSynchronize();
checkCudaError("Finding new coordinates, cells");
m_dGamma -= 1;
find_nbrs <<<m_nGridSize, m_nBlockSize, m_nSM_FindCells>>>
(m_nSpherocyls, m_nMaxPPC, d_pnCellID, d_pnPPC, d_pnCellList, d_pnAdjCells,
m_nMaxNbrs, d_pnNPP, d_pnNbrList, d_pdX, d_pdY, d_pdR, m_dEpsilon, m_dL, m_dGamma);
cudaThreadSynchronize();
checkCudaError("Finding neighbors");
}
////////////////////////////////////////////////////////////////////////////
// Finds cells for all particles regardless of maximum particle per cell
// used for reordering particles
/////////////////////////////////////////////////////////////////////////
__global__ void find_cells_nomax(int nSpherocyls, double dCellW, double dCellH,
int nCellCols, double dL, double *pdX, double *pdY,
int *pnCellID, int *pnPPC)
{
// Assign each thread a unique ID accross all thread-blocks, this is its particle ID
int nPID = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
while (nPID < nSpherocyls) {
double dX = pdX[nPID];
double dY = pdY[nPID];
// Particles are allowed to drift slightly outside the box limits
// until cells are reassigned due to a particle drift of dEpsilon/2
if (dY > dL) {
dY -= dL;
pdY[nPID] = dY; }
else if (dY < 0) {
dY += dL;
pdY[nPID] = dY; }
if (dX > dL) {
dX -= dL;
pdX[nPID] = dX; }
else if (dX < 0) {
dX += dL;
pdX[nPID] = dX; }
//find the cell ID, add a particle to that cell
int nCol = (int)(dX / dCellW);
int nRow = (int)(dY / dCellH);
int nCellID = nCol + nRow * nCellCols;
pnCellID[nPID] = nCellID;
int nPPC = atomicAdd(pnPPC + nCellID, 1);
nPID += nThreads; }
}
__global__ void reorder_part(int nSpherocyls, double *pdTempX, double *pdTempY,
double *pdTempR, int *pnInitID, double *pdX,
double *pdY, double *pdR, int *pnMemID,
int *pnCellID, int *pnCellSID)
{
int nPID = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
while (nPID < nSpherocyls) {
double dX = pdTempX[nPID];
double dY = pdTempY[nPID];
double dR = pdTempR[nPID];
int nInitID = pnInitID[nPID];
int nCellID = pnCellID[nPID];
int nNewID = atomicAdd(pnCellSID + nCellID, 1);
pdX[nNewID] = dX;
pdY[nNewID] = dY;
pdR[nNewID] = dR;
pnMemID[nNewID] = nInitID;
nPID += nThreads; }
}
__global__ void invert_IDs(int nIDs, int *pnIn, int *pnOut)
{
int thid = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
while (thid < nIDs) {
int i = pnIn[thid];
pnOut[i] = thid;
thid += nThreads; }
}
void Spherocyl_Box::reorder_particles()
{
cudaMemset((void *) d_pnPPC, 0, sizeof(int)*m_nCells);
//find particle cell IDs and number of particles in each cell
find_cells_nomax <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, m_dCellW, m_dCellH, m_nCellCols,
m_dL, d_pdX, d_pdY, d_pnCellID, d_pnPPC);
cudaThreadSynchronize();
checkCudaError("Reordering particles: Finding cells");
int *d_pnCellSID;
double *d_pdTempR;
cudaMalloc((void **) &d_pnCellSID, sizeof(int) * m_nCells);
cudaMalloc((void **) &d_pdTempR, sizeof(double) * m_nSpherocyls);
cudaMemcpy(d_pdTempX, d_pdX, sizeof(double) * m_nSpherocyls, cudaMemcpyDeviceToDevice);
cudaMemcpy(d_pdTempY, d_pdY, sizeof(double) * m_nSpherocyls, cudaMemcpyDeviceToDevice);
cudaMemcpy(d_pdTempR, d_pdR, sizeof(double) * m_nSpherocyls, cudaMemcpyDeviceToDevice);
exclusive_scan(d_pnPPC, d_pnCellSID, m_nCells);
/*
int *h_pnCellSID = (int*) malloc(m_nCells * sizeof(int));
int *h_pnCellNPart = (int*) malloc(m_nCells * sizeof(int));
cudaMemcpy(h_pnCellNPart, d_pnCellNPart, sizeof(int)*m_nCells, cudaMemcpyDeviceToHost);
cudaMemcpy(h_pnCellSID, d_pnCellSID, sizeof(int)*m_nCells, cudaMemcpyDeviceToHost);
for (int c = 0; c < m_nCells; c++)
{
printf("%d %d\n", h_pnCellNPart[c], h_pnCellSID[c]);
}
free(h_pnCellSID);
free(h_pnCellNPart);
*/
//reorder particles based on cell ID (first by Y direction)
reorder_part <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdTempX, d_pdTempY, d_pdTempR, d_pnInitID,
d_pdX, d_pdY, d_pdR, d_pnMemID, d_pnCellID, d_pnCellSID);
cudaThreadSynchronize();
checkCudaError("Reordering particles: changing order");
invert_IDs <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, d_pnMemID, d_pnInitID);
cudaMemcpyAsync(h_pnMemID, d_pnMemID, m_nSpherocyls*sizeof(int), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdR, d_pdR, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaFree(d_pnCellSID);
cudaFree(d_pdTempR);
find_neighbors();
}
////////////////////////////////////////////////////////////////////////
// Sets the particle IDs to their order in memory
// so the current IDs become the initial IDs
/////////////////////////////////////////////////////////////////////
void Spherocyl_Box::reset_IDs()
{
ordered_array(d_pnInitID, m_nSpherocyls, m_nGridSize, m_nBlockSize);
cudaMemcpy(d_pnMemID, d_pnInitID, sizeof(int)*m_nSpherocyls, cudaMemcpyDeviceToDevice);
cudaMemcpy(h_pnMemID, d_pnInitID, sizeof(int)*m_nSpherocyls, cudaMemcpyDeviceToHost);
}
<file_sep>/src/cuda/calculate_stress_energy_2.cu
// -*- c++ -*-
/*
* calculate_stress_energy.cu
*
*
*/
#include <cuda.h>
#include "spherocyl_box.h"
#include "cudaErr.h"
#include <math.h>
#include <sm_20_atomic_functions.h>
#include <stdio.h>
using namespace std;
////////////////////////////////////////////////////////
// Calculates energy, stress tensor, forces:
// Returns returns energy, pxx, pyy and pxy to pn
// Returns
//
// The neighbor list pnNbrList has a list of possible contacts
// for each particle and is found in find_neighbors.cu
//
/////////////////////////////////////////////////////////
template<Potential ePot>
__global__ void calc_se(int nSpherocyls, int *pnBlockNNbrs, int *pnBlockList, int *pnNPP,
int *pnNbrList, double dL, double dGamma, double *pdGlobX, double *pdGlobY,
double *pdGlobR, double *pdFx, double *pdFy, float *pfSE)
{
// Declare shared memory pointer, the size is determined at the kernel launch
extern __shared__ double sData[];
int thid = threadIdx.x;
int blid = blockIdx.x;
int blsz = blockDim.x;
int nPID = thid + blid * blsz;
int nThreads = blsz * gridDim.x;
int offset = blsz + 8; // +8 helps to avoid bank conflicts (I think)
for (int i = 0; i < 4; i++)
sData[thid + i*offset] = 0.0;
double *pdR = &sData[4*offset];
__syncthreads(); // synchronizes every thread in the block before going on
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dX = pdGlobX[nPID];
double dY = pdGlobY[nPID];
double dR = pdGlobR[nPID];
int nBlockNbrs = pnBlockNNbrs[blid];
double *pdX = &pdR[nBlockNbrs];
double *pdY = &pdX[nBlockNbrs];
for (int t = thid; t < nBlockNbrs; t++) {
int nGlobID = pnBlockList[8*blid*blsz + t];
pdR[t] = pdGlobR[nGlobID];
pdX[t] = pdGlobX[nGlobID];
pdY[t] = pdGlobY[nGlobID];
}
__syncthreads();
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dDeltaX = dX - pdX[nAdjPID];
double dDeltaY = dY - pdY[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dL * ((dDeltaX < -0.5*dL) - (dDeltaX > 0.5*dL));
dDeltaY += dL * ((dDeltaY < -0.5*dL) - (dDeltaY > 0.5*dL));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
// Check if they overlap
double dRSqr = dDeltaX*dDeltaX + dDeltaY*dDeltaY;
if (dRSqr < dSigma*dSigma)
{
double dDelR = sqrt(dRSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDelR / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDelR / dSigma) * sqrt(1.0 - dDelR / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDeltaX * dDVij / dDelR;
double dPfy = dDeltaY * dDVij / dDelR;
dFx += dPfx;
dFy += dPfy;
if (nAdjPID > nPID)
{
sData[thid] += dDVij * dSigma * (1.0 - dDelR / dSigma) / (dAlpha * dL * dL);
sData[thid + offset] += dPfx * dDeltaX / (dL * dL);
sData[thid + 2*offset] += dPfy * dDeltaY / (dL * dL);
sData[thid + 3*offset] += dPfx * dDeltaY / (dL * dL);
}
}
}
pdFx[nPID] = dFx;
pdFy[nPID] = dFy;
nPID += nThreads;
blid += gridDim.x;
}
__syncthreads();
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size, all threads perform two adds
int base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
base += 2*offset;
sData[base] += sData[base + stride];
stride /= 2; // stride is 1/4 block size, all threads perform 1 add
__syncthreads();
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
stride /= 2;
__syncthreads();
while (stride > 8)
{
if (thid < 4 * stride)
{
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 32) //unroll end of loop
{
base = thid % 8 + offset * (thid / 8);
sData[base] += sData[base + 8];
if (thid < 16)
{
base = thid % 4 + offset * (thid / 4);
sData[base] += sData[base + 4];
if (thid < 8)
{
base = thid % 2 + offset * (thid / 2);
sData[base] += sData[base + 2];
if (thid < 4)
{
sData[thid * offset] += sData[thid * offset + 1];
float tot = atomicAdd(pfSE+thid, (float)sData[thid*offset]);
}
}
}
}
}
void Spherocyl_Box::calculate_stress_energy()
{
cudaMemset((void*) d_pfSE, 0, 4*sizeof(float));
//dim3 grid(m_nGridSize);
//dim3 block(m_nBlockSize);
//size_t smem = m_nSM_CalcSE;
//printf("Configuration: %d x %d x %d\n", m_nGridSize, m_nBlockSize, m_nSM_CalcSE);
switch (m_ePotential)
{
case HARMONIC:
calc_se <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnBlockNNbrs, d_pnBlockList, d_pnNPP, d_pnNbrList,
m_dL, m_dGamma, d_pdX, d_pdY, d_pdR, d_pdFx, d_pdFy, d_pfSE);
break;
case HERTZIAN:
calc_se <HERTZIAN> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnBlockNNbrs, d_pnBlockList, d_pnNPP, d_pnNbrList,
m_dL, m_dGamma, d_pdX, d_pdY, d_pdR, d_pdFx, d_pdFy, d_pfSE);
}
cudaThreadSynchronize();
checkCudaError("Calculating stresses and energy");
}
////////////////////////////////////////////////////////////////////////////////////
#if GOLD_FUNCS == 1
void calc_se_gold(Potential ePot, int nGridDim, int nBlockDim, int sMemSize,
int nSpherocyls, int *pnNPP, int *pnNbrList, double dL,
double dGamma, double *pdX, double *pdY, double *pdR,
double *pdFx, double *pdFy, float *pfSE)
{
for (int b = 0; b < nGridDim; b++)
{
printf("Entering loop, block %d\n", b);
for (int thid = 0; thid < nBlockDim; thid++)
{
printf("Entering loop, thread %d\n", thid);
// Declare shared memory pointer, the size is determined at the kernel launch
double *sData = new double[sMemSize / sizeof(double)];
int nPID = thid + b * nBlockDim;
int nThreads = nBlockDim * nGridDim;
int offset = nBlockDim + 8; // +8 helps to avoid bank conflicts (I think)
for (int i = 0; i < 4; i++)
sData[thid + i*offset] = 0.0;
double dFx = 0.0;
double dFy = 0.0;
while (nPID < nSpherocyls)
{
double dX = pdX[nPID];
double dY = pdY[nPID];
double dR = pdR[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dDeltaX = dX - pdX[nAdjPID];
double dDeltaY = dY - pdY[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dL * ((dDeltaX < -0.5*dL) - (dDeltaX > 0.5*dL));
dDeltaY += dL * ((dDeltaY < -0.5*dL) - (dDeltaY > 0.5*dL));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
// Check if they overlap
double dRSqr = dDeltaX*dDeltaX + dDeltaY*dDeltaY;
if (dRSqr < dSigma*dSigma)
{
double dDelR = sqrt(dRSqr);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDelR / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDelR / dSigma) * sqrt(1.0 - dDelR / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDeltaX * dDVij / dDelR;
double dPfy = dDeltaY * dDVij / dDelR;
dFx += dPfx;
dFy += dPfy;
if (nAdjPID > nPID)
{
sData[thid] += dDVij * dSigma * (1.0 - dDelR / dSigma) / (dAlpha * dL * dL);
sData[thid + offset] += dPfx * dDeltaX / (dL * dL);
sData[thid + 2*offset] += dPfy * dDeltaY / (dL * dL);
sData[thid + 3*offset] += dPfx * dDeltaY / (dL * dL);
}
}
}
pdFx[nPID] = dFx;
pdFy[nPID] = dFy;
dFx = 0.0;
dFy = 0.0;
nPID += nThreads;
}
// Now we do a parallel reduction sum to find the total number of contacts
for (int s = 0; s < 4; s++)
pfSE[s] += sData[thid + s*offset];
}
}
}
void Spherocyl_Box::calculate_stress_energy_gold()
{
printf("Calculating streeses and energy");
cudaMemcpy(g_pnNPP, d_pnNPP, sizeof(int)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpy(g_pnNbrList, d_pnNbrList, sizeof(int)*m_nSpherocyls*m_nMaxNbrs, cudaMemcpyDeviceToHost);
cudaMemcpy(g_pdX, d_pdX, sizeof(double)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpy(g_pdY, d_pdY, sizeof(double)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpy(g_pdR, d_pdR, sizeof(double)*m_nSpherocyls, cudaMemcpyDeviceToHost);
for (int i = 0; i < 4; i++)
g_pfSE[i] = 0.0;
switch (m_ePotential)
{
case HARMONIC:
calc_se_gold (HARMONIC, m_nGridSize, m_nBlockSize, m_nSM_CalcSE,
m_nSpherocyls, g_pnNPP, g_pnNbrList, m_dL, m_dGamma,
g_pdX, g_pdY, g_pdR, g_pdFx, g_pdFy, g_pfSE);
break;
case HERTZIAN:
calc_se_gold (HERTZIAN, m_nGridSize, m_nBlockSize, m_nSM_CalcSE,
m_nSpherocyls, g_pnNPP, g_pnNbrList, m_dL, m_dGamma,
g_pdX, g_pdY, g_pdR, g_pdFx, g_pdFy, g_pfSE);
}
for (int p = 0; p < m_nSpherocyls; p++)
{
printf("Particle %d: (%g, %g)\n", p, g_pdFx[p], g_pdFy[p]);
}
printf("Energy: %g\n", g_pfSE[0]);
printf("Pxx: %g\n", g_pfSE[1]);
printf("Pyy: %g\n", g_pfSE[2]);
printf("P: %g\n", g_pfSE[1] + g_pfSE[2]);
printf("Pxy: %g\n", g_pfSE[3]);
}
#endif
<file_sep>/src/cpp/Makefile
# compilers
CXX=g++
# includes for header files
CXXINCLUDE=
# compiler flags: include all warnings, optimization level 3
CXXFLAGS=-O3 -Wall
# object files
CXXOBJECTS=spherocyl_box.o dat_file_input.o strain_dynamics.o resize_dynamics.o relaxation_dynamics.o
# final executable
STR_EXE=../../exe/cpp_spherocyl_strain
RESZ_EXE=../../exe/cpp_spherocyl_resize
MIN_EXE=../../exe/cpp_spherocyl_minimize
#rules:
all: $(STR_EXE) $(RESZ_EXE)
strain: $(STR_EXE)
resize: $(RESZ_EXE)
minimize: $(MIN_EXE)
######################
# compile executable #
######################
$(STR_EXE): $(CXXOBJECTS) main.o
$(CXX) -o $(STR_EXE) main.o $(CXXOBJECTS)
$(RESZ_EXE): $(CXXOBJECTS) main_resize.o
$(CXX) -o $(RESZ_EXE) main_resize.o $(CXXOBJECTS)
$(MIN_EXE): $(CXXOBJECTS) main_relax.o
$(CXX) -o $(MIN_EXE) main_relax.o $(CXXOBJECTS)
###################
# compile objects #
###################
#c++ files
main.o: main.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) $(CXXINCLUDE) -c main.cpp
main_resize.o: main_resize.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) $(CXXINCLUDE) -c main_resize.cpp
main_relax.o: main_relax.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) $(CXXINCLUDE) -c main_relax.cpp
spherocyl_box.o: spherocyl_box.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) $(CXXINCLUDE) -c spherocyl_box.cpp
dat_file_input.o: file_input.h dat_file_input.cpp
$(CXX) $(CXXFLAGS) $(CXXINCLUDE) -c dat_file_input.cpp
strain_dynamics.o: spherocyl_box.h strain_dynamics.cpp
$(CXX) $(CXXFLAGS) $(CXXINCLUDE) -c strain_dynamics.cpp
resize_dynamics.o: spherocyl_box.h resize_dynamics.cpp
$(CXX) $(CXXFLAGS) $(CXXINCLUDE) -c resize_dynamics.cpp
relaxation_dynamics.o: spherocyl_box.h relaxation_dynamics.cpp
$(CXX) $(CXXFLAGS) $(CXXINCLUDE) -c relaxation_dynamics.cpp
#clean up object files or other assembly files
clean:
rm -f *.o *.ptx
<file_sep>/src/cuda/test.cpp
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <math.h>
using namespace std;
int main()
{
double a,b;
srand(time(0));
clock_t start = clock();
for (int i = 0; i < 1000000; i++)
{
a = (double)rand()/(double)RAND_MAX;
b = -a;
cout << a << " " << a ^ -0.0 << " " << b << " " << b ^ -0.0 << endl;
/*double c = a - b;
//c += 100.0 * ((c <= -50.0) - (c >= 50.0));
if (c >= 50.0)
c -= 100.0;
else if (c <= -50.0)
c += 100.0;
cout << a << " " << b << " " << c << endl;*/
}
clock_t stop = clock();
cout << "\nRun time: " << stop - start << endl;
return 0;
}
<file_sep>/src/cpp/resize_dynamics.cpp
#include <vector>
#include <string>
#include <assert.h>
#include "spherocyl_box.h"
#include <iostream>
#include <math.h>
#include <fstream>
#include <cstdlib>
using std::cout;
using std::endl;
using std::cerr;
using std::ios;
using std::exit;
void SpherocylBox::calc_resized_force_pair(int p, int q, bool bShrink)
{
double dNewLx;
double dNewLy;
if (bShrink) {
dNewLx = m_dLx * pow(1.0 - m_dResizeRate, m_dStep);
dNewLy = m_dLy * pow(1.0 - m_dResizeRate, m_dStep);
}
else {
dNewLx = m_dLx / pow(1.0 - m_dResizeRate, m_dStep);
dNewLy = m_dLy / pow(1.0 - m_dResizeRate, m_dStep);
}
double dDeltaX = m_psTempParticles[p].m_dX - m_psTempParticles[q].m_dX;
double dDeltaY = m_psTempParticles[p].m_dY - m_psTempParticles[q].m_dY;
double dPhiP = m_psTempParticles[p].m_dPhi;
double dPhiQ = m_psTempParticles[q].m_dPhi;
double dSigma = m_psTempParticles[p].m_dR + m_psTempParticles[q].m_dR;
double dAP = m_psTempParticles[p].m_dA;
double dAQ = m_psTempParticles[q].m_dA;
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dNewLx * ((dDeltaX < -0.5*dNewLx) - (dDeltaX > 0.5*dNewLx));
dDeltaY += dNewLy * ((dDeltaY < -0.5*dNewLy) - (dDeltaY > 0.5*dNewLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += m_dGamma * dDeltaY;
double nxA = dAP * cos(dPhiP);
double nyA = dAP * sin(dPhiP);
double nxB = dAQ * cos(dPhiQ);
double nyB = dAQ * sin(dPhiQ);
double a = dAP * dAP;
double b = -(nxA * nxB + nyA * nyB);
double c = dAQ * dAQ;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
double s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij = (1.0 - dDij / dSigma) / dSigma;
double dFx = dDx * dDVij / dDij;
double dFy = dDy * dDVij / dDij;
double dTauP = s*nxA * dFy - s*nyA * dFx;
double dTauQ = t*nyB * dFx - t*nxB * dFy;
//double dMoiP = 4.0 * dAP * dAP / 12.0;
//double dMoiQ = 4.0 * dAQ * dAQ / 12.0;
m_psTempParticles[p].m_dFx += dFx;
m_psTempParticles[p].m_dFy += dFy;
m_psTempParticles[p].m_dTau += dTauP;
m_psTempParticles[q].m_dFx -= dFx;
m_psTempParticles[q].m_dFy -= dFy;
m_psTempParticles[q].m_dTau += dTauQ;
}
}
void SpherocylBox::calc_resized_forces(bool bShrink)
{
for (int i = 0; i < m_nParticles; i++) {
m_psTempParticles[i].m_dFx = 0.0;
m_psTempParticles[i].m_dFy = 0.0;
m_psTempParticles[i].m_dTau = 0.0;
}
for (int p = 0; p < m_nParticles; p++) {
for (int j = 0; j < m_pvNeighbors[p].size(); j++) {
int q = m_pvNeighbors[p][j];
if (q > p)
calc_temp_force_pair(p, q);
}
}
}
void SpherocylBox::reconfigure_cells()
{
double dWmin = 2.24 * (m_dRmax + m_dAmax) + m_dPadding; //width no less than sqrt(5)*Rmax if gamma = 0.5
double dHmin = 2 * (m_dRmax + m_dAmax) + m_dPadding; //height can be no less than 2*Rmax
int nNewCellRows = std::max(static_cast<int>(m_dLx / dHmin), 1);
int nNewCellCols = std::max(static_cast<int>(m_dLy / dWmin), 1);
if (nNewCellRows != m_nCellRows || nNewCellCols != m_nCellCols) {
configure_cells();
find_neighbors();
}
else {
m_dCellWidth = m_dLx / m_nCellCols;
m_dCellHeight = m_dLy / m_nCellRows;
}
}
/*
void SpherocylBox::resize_step(bool bShrink, int nRelaxSteps)
{
if (bShrink) {
m_psTempParticles[i].m_dX *= pow(1.0 - m_dResizeRate, m_dStep);
m_psTempParticles[i].m_dY *= pow(1.0 - m_dResizeRate, m_dStep);
m_dLx *= pow(1.0 - m_dResizeRate, m_dStep);
m_dLy *= pow(1.0 - m_dResizeRate, m_dStep);
}
else {
m_psParticles[i].m_dX /= pow(1.0 - m_dResizeRate, m_dStep);
m_psParticles[i].m_dY /= pow(1.0 - m_dResizeRate, m_dStep);
m_dLx /= pow(1.0 - m_dResizeRate, m_dStep);
m_dLy /= pow(1.0 - m_dResizeRate, m_dStep);
}
reconfigure_cells();
for (int r = 0; r < nRelaxSteps; r++) {
calc_forces();
for (int i = 0; i < m_nParticles; i++) {
dMoi = m_psParticles[i].m_dA * m_psParticles[i].m_dA / 3.0;
m_psParticles[i].m_dX += m_dStep * m_psParticles[i].m_dFx;
m_psParticles[i].m_dY += m_dStep * m_psParticles[i].m_dFy;
m_psParticles[i].m_dPhi += m_dStep * m_psParticles[i].m_dTau / dMoi;
}
}
for (int i = 0; i < m_nParticles; i++) {
m_psParticles[i].m_dXMoved += m_psTempParticles[i].m_dX - m_psParticles[i].m_dX;
m_psParticles[i].m_dYMoved += m_psTempParticles[i].m_dY - m_psParticles[i].m_dY;
if (m_psParticles[i].m_dXMoved > 0.5 * m_dPadding ||
m_psParticles[i].m_dXMoved < -0.5 * m_dPadding)
find_neighbors();
else if (m_psParticles[i].m_dYMoved > 0.5 * m_dPadding ||
m_psParticles[i].m_dYMoved < -0.5 * m_dPadding)
find_neighbors();
}
}
*/
void SpherocylBox::resize_step(bool bShrink)
{
//calc_forces();
double *dFx0 = new double[m_nParticles];
double *dFy0 = new double[m_nParticles];
double *dTau0 = new double[m_nParticles];
//double *dMoi = new double[m_nParticles];
for (int i = 0; i < m_nParticles; i++)
{
dFx0[i] = m_psParticles[i].m_dFx;
dFy0[i] = m_psParticles[i].m_dFy;
dTau0[i] = m_psParticles[i].m_dTau;
//dMoi[i] = m_psParticles[i].m_dA * m_psParticles[i].m_dA / 3.0;
m_psTempParticles[i] = m_psParticles[i];
m_psTempParticles[i].m_dX += m_dStep * dFx0[i];
m_psTempParticles[i].m_dY += m_dStep * dFy0[i];
m_psTempParticles[i].m_dPhi += m_dStep * dTau0[i] / m_psParticles[i].m_dI;
if (bShrink) {
m_psTempParticles[i].m_dX *= pow(1.0 - m_dResizeRate, m_dStep);
m_psTempParticles[i].m_dY *= pow(1.0 - m_dResizeRate, m_dStep);
}
else {
m_psTempParticles[i].m_dX /= pow(1.0 - m_dResizeRate, m_dStep);
m_psTempParticles[i].m_dY /= pow(1.0 - m_dResizeRate, m_dStep);
}
}
calc_resized_forces(bShrink);
for (int i = 0; i < m_nParticles; i++)
{
double dFx1 = m_psTempParticles[i].m_dFx;
double dFy1 = m_psTempParticles[i].m_dFy;
double dTau1 = m_psTempParticles[i].m_dTau;
double dDx = 0.5 * m_dStep * (dFx0[i] + dFx1);
double dDy = 0.5 * m_dStep * (dFy0[i] + dFy1);
double dDphi = 0.5 * m_dStep * (dTau0[i] + dTau1) / m_psParticles[i].m_dI;
double dX = m_psParticles[i].m_dX;
double dY = m_psParticles[i].m_dY;
m_psParticles[i].m_dX += dDx;
m_psParticles[i].m_dY += dDy;
m_psParticles[i].m_dPhi += dDphi;
if (bShrink) {
m_psParticles[i].m_dX *= pow(1.0 - m_dResizeRate, m_dStep);
m_psParticles[i].m_dY *= pow(1.0 - m_dResizeRate, m_dStep);
}
else {
m_psParticles[i].m_dX /= pow(1.0 - m_dResizeRate, m_dStep);
m_psParticles[i].m_dY /= pow(1.0 - m_dResizeRate, m_dStep);
}
m_psParticles[i].m_dXMoved += m_psParticles[i].m_dX - dX;
m_psParticles[i].m_dYMoved += m_psParticles[i].m_dY - dY;
reconfigure_cells();
if (m_psParticles[i].m_dXMoved > 0.5 * m_dPadding ||
m_psParticles[i].m_dXMoved < -0.5 * m_dPadding)
find_neighbors();
else if (m_psParticles[i].m_dYMoved > 0.5 * m_dPadding ||
m_psParticles[i].m_dYMoved < -0.5 * m_dPadding)
find_neighbors();
}
if (bShrink) {
m_dLx *= pow(1.0 - m_dResizeRate, m_dStep);
m_dLy *= pow(1.0 - m_dResizeRate, m_dStep);
}
else {
m_dLx /= pow(1.0 - m_dResizeRate, m_dStep);
m_dLy /= pow(1.0 - m_dResizeRate, m_dStep);
}
delete[] dTau0;
delete[] dFx0; delete[] dFy0;
}
long unsigned int SpherocylBox::resize_box(double dFinalPacking, long unsigned int nTime)
{
assert(m_dResizeRate != 0.0);
m_dPacking = calculate_packing_fraction();
double dPArea = m_dPacking * (m_dLx * m_dLy);
std::string strSEPath = m_strOutputDir + "/" + m_strSEOutput;
std::fstream outfSE;
if (nTime == 0) {
outfSE.open(strSEPath.c_str(), ios::out);
calc_se();
outfSE << 0 << " " << m_dPacking << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << endl;
save_positions("sp0000000000.dat");
}
else {
outfSE.open(strSEPath.c_str(), ios::out | ios::in);
if (! outfSE) {
cerr << "Output file could not be opened for reading" << endl;
exit(1);
}
bool foundT;
char szBuf[200];
while (! outfSE.eof()) {
outfSE.getline(szBuf, 200);
std::string line = szBuf;
std::size_t spos = line.find_first_of(' ');
std::string strTime = line.substr(0,spos);
if (nTime == std::atoi(strTime.c_str())) {
foundT = true;
break;
}
}
if (!foundT) {
cerr << "Start time not found in output file" << endl;
exit(1);
}
calc_forces();
}
int nIntSteps = int(1.0 / m_dStep + 0.5);
int nPosSaveT = int(m_dPosSaveStep / m_dResizeRate + 0.5);
int nSESaveT = int(m_dSESaveStep / (m_dResizeRate * m_dStep) + 0.5);
bool bShrink;
if (dFinalPacking > m_dPacking) {
bShrink = true;
}
else {
bShrink = false;
}
while (bShrink ? dFinalPacking > m_dPacking : dFinalPacking < m_dPacking) {
nTime += 1;
for (int s = 1; s <= nIntSteps; s++) {
resize_step(bShrink);
if (s % nSESaveT == 0) {
calc_se();
m_dPacking = dPArea / (m_dLx * m_dLy);
outfSE << nTime << " " << m_dPacking << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << "\n";
}
else {
calc_forces();
}
}
m_dPacking = dPArea / (m_dLx * m_dLy);
if (nTime*nIntSteps % nSESaveT == 0) {
outfSE << nTime << " " << m_dPacking << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << "\n";
}
if (nTime % nPosSaveT == 0) {
outfSE.flush();
char szBuf[11];
sprintf(szBuf, "%010lu", nTime);
std::string strSaveFile = std::string("sp") + szBuf + std::string(".dat");
save_positions(strSaveFile);
}
}
outfSE.flush();
outfSE.close();
char szBuf[11];
sprintf(szBuf, "%010lu", nTime);
std::string strSaveFile = std::string("sp") + szBuf + std::string(".dat");
save_positions(strSaveFile);
return nTime;
}
long unsigned int SpherocylBox::resize_box(double dFinalPacking)
{
assert(m_dResizeRate != 0.0);
m_dPacking = calculate_packing_fraction();
double dPArea = m_dPacking * (m_dLx * m_dLy);
std::string strSEPath = m_strOutputDir + "/" + m_strSEOutput;
std::ifstream inf(strSEPath.c_str());
unsigned long int nTime;
if (inf) {
std::string line;
char szBuf[200];
while (! inf.eof()) {
inf.getline(szBuf, 200);
line = szBuf;
}
if (! line.empty()) {
std::size_t spos = line.find_first_of(' ');
std::string strTime = line.substr(0,spos);
nTime = std::atoi(strTime.c_str());
}
else {
nTime = 0;
}
}
std::ofstream outfSE;
outfSE.precision(14);
if (nTime == 0) {
outfSE.open(strSEPath.c_str());
calc_se();
outfSE << 0 << " " << m_dPacking << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << endl;
save_positions("sp0000000000.dat");
}
else {
outfSE.open(strSEPath.c_str(), ios::app);
calc_forces();
}
int nIntSteps = int(1.0 / m_dStep + 0.5);
int nPosSaveT = int(m_dPosSaveStep / m_dResizeRate + 0.5);
int nSESaveT = int(m_dSESaveStep / (m_dResizeRate * m_dStep) + 0.5);
bool bShrink;
if (dFinalPacking > m_dPacking) {
bShrink = true;
}
else {
bShrink = false;
}
while (bShrink ? dFinalPacking > m_dPacking : dFinalPacking < m_dPacking) {
nTime += 1;
for (int s = 1; s <= nIntSteps; s++) {
resize_step(bShrink);
if (s % nSESaveT == 0) {
calc_se();
m_dPacking = dPArea / (m_dLx * m_dLy);
outfSE << nTime << " " << m_dPacking << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << "\n";
}
else {
calc_forces();
}
}
m_dPacking = dPArea / (m_dLx * m_dLy);
if (nTime*nIntSteps % nSESaveT == 0) {
outfSE << nTime << " " << m_dPacking << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << "\n";
}
if (nTime % nPosSaveT == 0) {
outfSE.flush();
char szBuf[11];
sprintf(szBuf, "%010lu", nTime);
std::string strSaveFile = std::string("sp") + szBuf + std::string(".dat");
save_positions(strSaveFile);
}
}
outfSE.flush();
outfSE.close();
char szBuf[11];
sprintf(szBuf, "%010lu", nTime);
std::string strSaveFile = std::string("sp") + szBuf + std::string(".dat");
save_positions(strSaveFile);
return nTime;
}
<file_sep>/src/cpp/strain_dynamics.cpp
#include <vector>
#include <string>
#include <assert.h>
#include "spherocyl_box.h"
#include <iostream>
#include <math.h>
#include <fstream>
#include <cstdlib>
using std::cout;
using std::endl;
using std::cerr;
using std::ios;
using std::exit;
void SpherocylBox::calc_force_pair(int p, int q)
{
double dDeltaX = m_psParticles[p].m_dX - m_psParticles[q].m_dX;
double dDeltaY = m_psParticles[p].m_dY - m_psParticles[q].m_dY;
double dPhiP = m_psParticles[p].m_dPhi;
double dPhiQ = m_psParticles[q].m_dPhi;
double dSigma = m_psParticles[p].m_dR + m_psParticles[q].m_dR;
double dAP = m_psParticles[p].m_dA;
double dAQ = m_psParticles[q].m_dA;
// Make sure we take the closest distance considering boundary conditions
dDeltaX += m_dLx * ((dDeltaX < -0.5*m_dLx) - (dDeltaX > 0.5*m_dLx));
dDeltaY += m_dLy * ((dDeltaY < -0.5*m_dLy) - (dDeltaY > 0.5*m_dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += m_dGamma * dDeltaY;
double nxA = dAP * cos(dPhiP);
double nyA = dAP * sin(dPhiP);
double nxB = dAQ * cos(dPhiQ);
double nyB = dAQ * sin(dPhiQ);
double a = dAP * dAP;
double b = -(nxA * nxB + nyA * nyB);
double c = dAQ * dAQ;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
double s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij = (1.0 - dDij / dSigma) / dSigma;
double dFx = dDx * dDVij / dDij;
double dFy = dDy * dDVij / dDij;
double dTauP = s*nxA * dFy - s*nyA * dFx;
double dTauQ = t*nyB * dFx - t*nxB * dFy;
//double dMoiP = 4.0 * dAP * dAP / 12.0;
//double dMoiQ = 4.0 * dAQ * dAQ / 12.0;
m_psParticles[p].m_dFx += dFx;
m_psParticles[p].m_dFy += dFy;
m_psParticles[p].m_dTau += dTauP;
m_psParticles[q].m_dFx -= dFx;
m_psParticles[q].m_dFy -= dFy;
m_psParticles[q].m_dTau += dTauQ;
}
}
void SpherocylBox::calc_temp_force_pair(int p, int q)
{
double dDeltaX = m_psTempParticles[p].m_dX - m_psTempParticles[q].m_dX;
double dDeltaY = m_psTempParticles[p].m_dY - m_psTempParticles[q].m_dY;
double dPhiP = m_psTempParticles[p].m_dPhi;
double dPhiQ = m_psTempParticles[q].m_dPhi;
double dSigma = m_psTempParticles[p].m_dR + m_psTempParticles[q].m_dR;
double dAP = m_psTempParticles[p].m_dA;
double dAQ = m_psTempParticles[q].m_dA;
// Make sure we take the closest distance considering boundary conditions
dDeltaX += m_dLx * ((dDeltaX < -0.5*m_dLx) - (dDeltaX > 0.5*m_dLx));
dDeltaY += m_dLy * ((dDeltaY < -0.5*m_dLy) - (dDeltaY > 0.5*m_dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += (m_dGamma + m_dStep * m_dStrainRate) * dDeltaY;
double nxA = dAP * cos(dPhiP);
double nyA = dAP * sin(dPhiP);
double nxB = dAQ * cos(dPhiQ);
double nyB = dAQ * sin(dPhiQ);
double a = dAP * dAP;
double b = -(nxA * nxB + nyA * nyB);
double c = dAQ * dAQ;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double t = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
double s = -(b*t+d)/a;
double sarg = fabs(s);
s = fmin( fmax(s,-1.), 1. );
if (sarg > 1)
t = fmin( fmax( -(b*s+e)/c, -1.), 1.);
// Check if they overlap and calculate forces
double dDx = dDeltaX + s*nxA - t*nxB;
double dDy = dDeltaY + s*nyA - t*nyB;
double dDSqr = dDx * dDx + dDy * dDy;
if (dDSqr < dSigma*dSigma)
{
double dDij = sqrt(dDSqr);
double dDVij = (1.0 - dDij / dSigma) / dSigma;
double dFx = dDx * dDVij / dDij;
double dFy = dDy * dDVij / dDij;
double dTauP = s*nxA * dFy - s*nyA * dFx;
double dTauQ = t*nyB * dFx - t*nxB * dFy;
//double dMoiP = 4.0 * dAP * dAP / 12.0;
//double dMoiQ = 4.0 * dAQ * dAQ / 12.0;
m_psTempParticles[p].m_dFx += dFx;
m_psTempParticles[p].m_dFy += dFy;
m_psTempParticles[p].m_dTau += dTauP;
m_psTempParticles[q].m_dFx -= dFx;
m_psTempParticles[q].m_dFy -= dFy;
m_psTempParticles[q].m_dTau += dTauQ;
}
}
void SpherocylBox::calc_forces()
{
for (int i = 0; i < m_nParticles; i++) {
m_psParticles[i].m_dFx = 0.0;
m_psParticles[i].m_dFy = 0.0;
m_psParticles[i].m_dTau = 0.0;
}
for (int p = 0; p < m_nParticles; p++) {
for (int j = 0; j < m_pvNeighbors[p].size(); j++)
{
int q = m_pvNeighbors[p][j];
if (q > p)
calc_force_pair(p, q);
}
}
}
void SpherocylBox::calc_temp_forces()
{
for (int i = 0; i < m_nParticles; i++) {
m_psTempParticles[i].m_dFx = 0.0;
m_psTempParticles[i].m_dFy = 0.0;
m_psTempParticles[i].m_dTau = 0.0;
}
for (int p = 0; p < m_nParticles; p++) {
for (int j = 0; j < m_pvNeighbors[p].size(); j++)
{
int q = m_pvNeighbors[p][j];
if (q > p)
calc_temp_force_pair(p, q);
}
}
}
double isolated_rotation(Spherocyl s)
{
return 0.5*(1 - s.m_dRC*cos(2*s.m_dPhi));
}
void SpherocylBox::strain_step()
{
//calc_forces();
double *dFx0 = new double[m_nParticles];
double *dFy0 = new double[m_nParticles];
double *dTau0 = new double[m_nParticles];
//double *dMoi = new double[m_nParticles];
for (int i = 0; i < m_nParticles; i++)
{
dFx0[i] = m_psParticles[i].m_dFx - m_dGamma * m_psParticles[i].m_dFy;
dFy0[i] = m_psParticles[i].m_dFy;
//double dSinPhi = sin(m_psParticles[i].m_dPhi);
//dMoi[i] = m_psParticles[i].m_dA * m_psParticles[i].m_dA / 3.0;
dTau0[i] = m_psParticles[i].m_dTau / m_psParticles[i].m_dI - m_dStrainRate * isolated_rotation(m_psParticles[i]);
m_psTempParticles[i] = m_psParticles[i];
m_psTempParticles[i].m_dX += m_dStep * dFx0[i];
m_psTempParticles[i].m_dY += m_dStep * dFy0[i];
m_psTempParticles[i].m_dPhi += m_dStep * dTau0[i];
}
calc_temp_forces();
for (int i = 0; i < m_nParticles; i++)
{
double dFx1 = m_psTempParticles[i].m_dFx - (m_dGamma + m_dStep * m_dStrainRate) * m_psTempParticles[i].m_dFy;
double dFy1 = m_psTempParticles[i].m_dFy;
double dSinPhi = sin(m_psTempParticles[i].m_dPhi);
double dTau1 = m_psTempParticles[i].m_dTau / m_psParticles[i].m_dI - m_dStrainRate * isolated_rotation(m_psTempParticles[i]);
double dDx = 0.5 * m_dStep * (dFx0[i] + dFx1);
double dDy = 0.5 * m_dStep * (dFy0[i] + dFy1);
double dDphi = 0.5 * m_dStep * (dTau0[i] + dTau1);
m_psParticles[i].m_dX += dDx;
m_psParticles[i].m_dY += dDy;
m_psParticles[i].m_dPhi += dDphi;
m_psParticles[i].m_dXMoved += dDx;
m_psParticles[i].m_dYMoved += dDy;
if (m_psParticles[i].m_dXMoved > 0.5 * m_dPadding ||
m_psParticles[i].m_dXMoved < -0.5 * m_dPadding)
find_neighbors();
else if (m_psParticles[i].m_dYMoved > 0.5 * m_dPadding ||
m_psParticles[i].m_dYMoved < -0.5 * m_dPadding)
find_neighbors();
}
delete[] dFx0; delete[] dFy0; delete[] dTau0;
m_dGamma += m_dStrainRate * m_dStep;
m_dGammaTotal += m_dStrainRate * m_dStep;
if (m_dGamma >= 0.5)
set_back_gamma();
}
long unsigned int SpherocylBox::run_strain(double dRunLength, long unsigned int nTime)
{
std::string strSEPath = m_strOutputDir + "/" + m_strSEOutput;
std::fstream outfSE;
if (nTime == 0) {
outfSE.open(strSEPath.c_str(), ios::out);
calc_se();
outfSE << 0 << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << endl;
save_positions("sp0000000000.dat");
}
else {
outfSE.open(strSEPath.c_str(), std::fstream::out | std::fstream::in);
if (! outfSE) {
cerr << "Output file could not be opened for reading" << endl;
exit(1);
}
bool foundT;
std::streampos ppos;
char szBuf[500];
while (! outfSE.eof()) {
outfSE.getline(szBuf, 500);
std::string line = szBuf;
std::streampos spos = line.find_first_of(' ');
std::string strTime = line.substr(0,spos);
if (nTime == std::atoi(strTime.c_str())) {
foundT = true;
ppos = outfSE.tellg();
break;
}
}
if (!foundT) {
cerr << "Start time not found in output file" << endl;
exit(1);
}
if (ppos == -1) {
outfSE.seekp(0,std::ios::end);
outfSE << "\n";
}
else
outfSE.seekp(ppos);
calc_forces();
}
int nTSteps = int(dRunLength / m_dStrainRate + 0.5);
int nIntSteps = int(1.0 / m_dStep + 0.5);
int nPosSaveT = int(m_dPosSaveStep / m_dStrainRate + 0.5);
int nSESaveT = int(m_dSESaveStep / (m_dStrainRate * m_dStep) + 0.5);
for (unsigned long int t = nTime+1; t <= nTime + nTSteps; t++)
{
for (int s = 1; s <= nIntSteps; s++) {
strain_step();
if (s % nSESaveT == 0) {
calc_se();
outfSE << t << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << "\n";
}
else {
calc_forces();
}
}
if (t*nIntSteps % nSESaveT == 0) {
outfSE << t << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << "\n";
}
if (t % nPosSaveT == 0) {
outfSE.flush();
char szBuf[11];
sprintf(szBuf, "%010lu", t);
std::string strSaveFile = std::string("sp") + szBuf + std::string(".dat");
save_positions(strSaveFile);
}
}
outfSE.flush();
outfSE.close();
nTime += nTSteps;
char szBuf[11];
sprintf(szBuf, "%010lu", nTime);
std::string strSaveFile = std::string("sp") + szBuf + std::string(".dat");
save_positions(strSaveFile);
return nTime;
}
long unsigned int SpherocylBox::run_strain(double dRunLength)
{
std::string strSEPath = m_strOutputDir + "/" + m_strSEOutput;
std::ifstream inf(strSEPath.c_str());
long unsigned int nTime;
if (inf) {
std::string line;
char szBuf[200];
while (! inf.eof()) {
inf.getline(szBuf, 200);
line = szBuf;
}
if (! line.empty()) {
std::size_t spos = line.find_first_of(' ');
std::string strTime = line.substr(0,spos);
nTime = std::atoi(strTime.c_str());
}
else {
nTime = 0;
}
}
std::ofstream outfSE;
outfSE.precision(14);
if (nTime == 0) {
outfSE.open(strSEPath.c_str());
calc_se();
outfSE << 0 << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << " " << m_dPyx << endl;
save_positions("sp0000000000.dat");
}
else {
outfSE.open(strSEPath.c_str(), ios::app);
calc_forces();
}
int nTSteps = int(dRunLength / m_dStrainRate + 0.5);
int nIntSteps = int(1.0 / m_dStep + 0.5);
int nPosSaveT = int(m_dPosSaveStep / m_dStrainRate + 0.5);
int nSESaveT = int(m_dSESaveStep / (m_dStrainRate * m_dStep) + 0.5);
for (unsigned long int t = nTime+1; t <= nTime + nTSteps; t++)
{
for (int s = 1; s <= nIntSteps; s++) {
strain_step();
if (s % nSESaveT == 0) {
calc_se();
outfSE << t << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << " " << m_dPyx << "\n";
}
else {
calc_forces();
}
}
if (t*nIntSteps % nSESaveT == 0) {
outfSE << t << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << " " << m_dPyx << "\n";
}
if (t % nPosSaveT == 0) {
outfSE.flush();
char szBuf[11];
sprintf(szBuf, "%010lu", t);
std::string strSaveFile = std::string("sp") + szBuf + std::string(".dat");
save_positions(strSaveFile);
}
}
outfSE.flush();
outfSE.close();
nTime += nTSteps;
char szBuf[11];
sprintf(szBuf, "%010lu", nTime);
std::string strSaveFile = std::string("sp") + szBuf + std::string(".dat");
save_positions(strSaveFile);
return nTime;
}
<file_sep>/src/cuda/file_input.h
/*
* file_input.h
*
*
* Created by <NAME> on 7/9/10.
*
* Last Modified 12/17/2013
* Changes:
* -New GzFileInput class for opening gzipped files
* -Better header handling & functions in DatFileInput (also in GzFileInput)
* -getRow() functions to get rows of same data type at once
*
*/
#ifndef FILE_INPUT_H
#define FILE_INPUT_H
#include <string>
#include <fstream>
using namespace std;
//dat files are assumed to contain columns of data with
class DatFileInput
{
private:
const char* m_szFileName;
bool m_bHeader;
int m_nFileLength;
int m_nColumns;
int m_nRows; //the number of rows in the file includes the header row if the file has one
int m_nHeadLen;
string* m_strArray;
string* m_strHeader;
int m_nArrayLine1;
int datGetRows();
int datGetColumns();
int datGetHeadLen();
void datFillHeader();
void datFillArray();
public:
//constructors
DatFileInput(const char* szFile);
DatFileInput(const char* szFile, bool bHeader);
DatFileInput(const char* szFile, int nRows, int nColumns);
DatFileInput(const char* szFile, bool bHeader, int nRows, int nColumns);
//destructor
~DatFileInput() { delete[] m_strArray; delete[] m_strHeader; }
void datDisplayArray();
void getColumn(int anColumn[], int nColumn);
void getColumn(long alColumn[], int nColumn);
void getColumn(double adColumn[], int nColumn);
void getColumn(string astrColumn[], int nColumn);
void getHeader(string strHead[]);
void getRow(int anRow[], int nRow);
void getRow(long alRow[], int nRow);
void getRow(double adRow[], int nRow);
void getRow(string astrRow[], int nRow);
int getInt(int nRow, int nColumn);
long getLong(int nRow, int nColumn);
double getFloat(int nRow, int nColumn);
string getString(int nRow, int nColumn);
int getHeadInt(int nCol);
long getHeadLong(int nCol);
double getHeadFloat(int nCol);
string getHeadString(int nCol);
int getColumns() { return m_nColumns; }
int getRows() { return m_nFileLength - static_cast<int>(m_bHeader); }
int getHeadLen() { return m_nHeadLen; }
};
class GzFileInput
{
private:
const char* m_szFileName;
bool m_bHeader;
int m_nFileLength;
int m_nColumns;
int m_nRows;
int m_nHeadLen;
string *m_strArray;
string *m_strHeader;
int m_nArrayLine1;
int gzGetRows();
int gzGetColumns();
int gzGetHeadLen();
void gzFillArray();
void gzFillHeader();
public:
GzFileInput(const char *szFile);
GzFileInput(const char *szFile, bool bHeader);
GzFileInput(const char *szFile, bool bHeader, int nRows, int nColumns);
~GzFileInput() { delete[] m_strArray; delete[] m_strHeader; }
void getHeader(string strHead[]);
void getRow(int pnRow[], int nRow);
void getRow(long plRow[], int nRow);
void getRow(double pdRow[], int nRow);
void getRow(string pstrRow[], int nRow);
void getColumn(int pnColumn[], int nCol);
void getColumn(long plColumn[], int nCol);
void getColumn(double pdColumn[], int nCol);
void getColumn(string pstrColumn[], int nCol);
int getInt(int nRow, int nCol);
long getLong(int nRow, int nCol);
double getFloat(int nRow, int nCol);
string getString(int nRow, int nCol);
int getHeadInt(int nCol);
long getHeadLong(int nCol);
double getHeadFloat(int nCol);
string getHeadString(int nCol);
int getColumns() { return m_nColumns; }
int getRows() { return m_nFileLength - (int)m_bHeader; }
int getHeadLen() { return m_nHeadLen; }
};
class BinFileInput
{
private:
ifstream m_FileStream;
long int m_nPosition;
long int m_nLength;
int m_nCharSize;
int m_nShortSize;
int m_nIntSize;
int m_nFloatSize;
int m_nLongSize;
int m_nDoubleSize;
char *m_szBuffer;
public:
BinFileInput(const char* szInput);
~BinFileInput();
void set_position(long int nPosition);
void skip_bytes(long int nBytes);
void jump_back_bytes(long int nBytes);
char getChar();
short getShort();
int getInt();
float getFloat();
long getLong();
double getDouble();
long int getFileSize() { return m_nLength; }
};
#endif
<file_sep>/src/cuda/cudaErr.cpp
/* cudaErr.cu
*
* contains simple function for reporting GPU errors
*
*/
#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime_api.h>
#include "cudaErr.h"
void checkCudaError(const char *msg)
{
cudaError_t err = cudaGetLastError();
if( cudaSuccess != err)
{
fprintf(stderr, "Cuda error: %s: %s.\n", msg, cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
}
<file_sep>/src/cpp/main_resize.cpp
/*
*
*
*/
#include "spherocyl_box.h"
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <iostream>
#include "file_input.h"
#include <string>
#include <limits>
using namespace std;
const double D_PI = 3.14159265358979;
int int_input(int argc, char* argv[], int argn, char description[] = "")
{
if (argc > argn) {
int input = atoi(argv[argn]);
cout << description << ": " << input << endl;
return input;
}
else {
int input;
cout << description << ": ";
cin >> input;
return input;
}
}
double float_input(int argc, char* argv[], int argn, char description[] = "")
{
if (argc > argn) {
double input = atof(argv[argn]);
cout << description << ": " << input << endl;
return input;
}
else {
double input;
cout << description << ": ";
cin >> input;
return input;
}
}
string string_input(int argc, char* argv[], int argn, char description[] = "")
{
if (argc > argn) {
string input = argv[argn];
cout << description << ": " << input << endl;
return input;
}
else {
string input;
cout << description << ": ";
cin >> input;
return input;
}
}
int main(int argc, char* argv[])
{
int argn = 0;
string strFile = string_input(argc, argv, ++argn, "Data file ('r' for random)");
const char* szFile = strFile.c_str();
cout << strFile << endl;
string strDir = string_input(argc, argv, ++argn, "Output data directory");
const char* szDir = strDir.c_str();
cout << strDir << endl;
int nParticles = int_input(argc, argv, ++argn, "Number of particles");
cout << nParticles << endl;
double dResizeRate = float_input(argc, argv, ++argn, "Resize rate");
cout << dResizeRate << endl;
double dStep = float_input(argc, argv, ++argn, "Integration step size");
cout << dStep << endl;
double dFinalPacking = float_input(argc, argv, ++argn, "Final packing fraction");
cout << dFinalPacking << endl;
double dPosSaveRate = float_input(argc, argv, ++argn, "Position data save rate");
cout << dPosSaveRate << endl;
double dStressSaveRate = float_input(argc, argv, ++argn, "Stress data save rate");
cout << dStressSaveRate << endl;
double dDR = float_input(argc, argv, ++argn, "Cell padding");
cout << dDR << endl;
if (dStressSaveRate < dResizeRate * dStep)
dStressSaveRate = dResizeRate * dStep;
if (dPosSaveRate < dResizeRate)
dPosSaveRate = dResizeRate;
double dL;
double *pdX = new double[nParticles];
double *pdY = new double[nParticles];
double *pdPhi = new double[nParticles];
double *pdRad = new double[nParticles];
double *pdA = new double[nParticles];
double dRMax = 0.0;
double dAMax = 0.0;
double dGamma;
double dTotalGamma;
long unsigned int nTime = 0;
double dPacking;
initialConfig config;
if (strFile == "r")
{
srand(time(0));
dPacking = float_input(argc, argv, ++argn, "Starting Packing Fraction");
cout << dPacking << endl;
double dA = float_input(argc, argv, ++argn, "Half-shaft length");
cout << dA << endl;
double dR = float_input(argc, argv, ++argn, "Radius");
cout << dR << endl;
if (argc > ++argn) {
config = (initialConfig)int_input(argc, argv, argn, "Initial configuration (0: random, 1: random-aligned, 2: zero-energy, 3: zero-energy-aligned)");
}
else {
config = RANDOM;
}
double dArea = nParticles*(4.0*dA + D_PI * dR)*dR;
dL = sqrt(dArea / dPacking);
cout << "Box length L: " << dL << endl;
dAMax = dA;
dRMax = dR;
for (int p = 0; p < nParticles; p++) {
pdX[p] = dL * double(rand()) / double(numeric_limits<int>::max());
pdY[p] = dL * double(rand()) / double(numeric_limits<int>::max());
pdPhi[p] = 2*D_PI * double(rand()) / double(numeric_limits<int>::max());
pdA[p] = dAMax;
pdRad[p] = dRMax;
}
dGamma = 0.0;
dTotalGamma = 0.0;
nTime = 0;
}
else
{
cout << "Loading file: " << strFile << endl;
DatFileInput cData(szFile, 0);
if (cData.getInt(0, 5) != nParticles) {
cout << "Warning: Number of particles in data file may not match requested number" << endl;
cerr << "Warning: Number of particles in data file may not match requested number" << endl;
}
cData.getColumn(pdX, 0);
cData.getColumn(pdY, 1);
cData.getColumn(pdPhi, 2);
cData.getColumn(pdA, 3);
cData.getColumn(pdRad, 4);
dL = cData.getFloat(0,6);
dPacking = cData.getFloat(0,7);
dGamma = cData.getFloat(0,8);
dTotalGamma = cData.getFloat(0,9);
int nFileLen = strFile.length();
string strNum = strFile.substr(nFileLen-14, 10);
nTime = atoi(strNum.c_str());
cout << "Time: " << strNum << " " << nTime << endl;
for (int p = 0; p < nParticles; p++) {
if (pdA[p] > dAMax) { dAMax = pdA[p]; }
if (pdRad[p] > dRMax) { dRMax = pdRad[p]; }
}
}
int tStart = time(0);
SpherocylBox *cBox;
if (strFile == "r") {
cout << "Initializing box of length " << dL << " with " << nParticles << " particles.";
cBox = new SpherocylBox(dL, nParticles, dDR);
cBox->random_configuration(dAMax, dRMax, config);
}
else {
cout << "Initializing box from file of length " << dL << " with " << nParticles << " particles.";
cBox = new SpherocylBox(dL, nParticles, pdX, pdY, pdPhi, pdA, pdRad, dDR);
}
cBox->calc_se();
cBox->display(1,1);
cBox->set_output_directory(strDir);
cBox->set_se_file("sp_resize_se.dat");
cBox->set_resize_rate(dResizeRate);
cBox->set_step(dStep);
nTime = cBox->resize_box(dFinalPacking, nTime);
int tStop = time(0);
cout << "\nRun Time: " << tStop - tStart << endl;
delete[] pdX; delete[] pdY; delete[] pdPhi;
delete[] pdRad; delete[] pdA;
return 0;
}
<file_sep>/src/cpp/bin_file_input.cpp
/*
* bin_file_input.cpp
*
*
* Created by <NAME> on 3/11/11.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
*/
#include "file_input.h"
#include <fstream>
#include <assert.h>
#include <cstdlib> //for exit, atoi etc
using namespace std;
BinFileInput::BinFileInput(const char* szFile)
{
m_FileStream.open(szFile, ios::in | ios::binary);
m_nPosition = 0;
m_FileStream.seekg(0, ios::end);
m_nLength = m_FileStream.tellg();
m_FileStream.seekg(0, ios::beg);
m_nCharSize = sizeof(char);
m_nShortSize = sizeof(short);
m_nIntSize = sizeof(int);
m_nFloatSize = sizeof(float);
m_nLongSize = sizeof(long);
m_nDoubleSize = sizeof(double);
m_szBuffer = 0;
}
BinFileInput::~BinFileInput()
{
delete[] m_szBuffer;
m_FileStream.close();
}
void BinFileInput::set_position(long int nPosition)
{
assert(nPosition < m_nLength);
m_FileStream.seekg(nPosition);
m_nPosition = nPosition;
}
void BinFileInput::skip_bytes(long int nBytes)
{
m_nPosition = m_FileStream.tellg();
m_nPosition += nBytes;
assert(m_nPosition <= m_nLength);
m_FileStream.seekg(m_nPosition);
}
void BinFileInput::jump_back_bytes(long int nBytes)
{
m_nPosition = m_FileStream.tellg();
m_nPosition -= nBytes;
assert(m_nPosition > 0);
m_FileStream.seekg(m_nPosition);
}
char BinFileInput::getChar()
{
char *cChar;
delete[] m_szBuffer;
m_szBuffer = new char[m_nCharSize];
m_FileStream.read(m_szBuffer, m_nCharSize);
cChar = reinterpret_cast<char*>(m_szBuffer);
m_nPosition = m_FileStream.tellg();
return *cChar;
}
short BinFileInput::getShort()
{
short *snShort;
delete[] m_szBuffer;
m_szBuffer = new char[m_nShortSize];
m_FileStream.read(m_szBuffer, m_nShortSize);
snShort = reinterpret_cast<short*>(m_szBuffer);
m_nPosition = m_FileStream.tellg();
return *snShort;
}
int BinFileInput::getInt()
{
int *nInt;
delete[] m_szBuffer;
m_szBuffer = new char[m_nIntSize];
m_FileStream.read(m_szBuffer, m_nIntSize);
nInt = reinterpret_cast<int*>(m_szBuffer);
m_nPosition = m_FileStream.tellg();
return *nInt;
}
long BinFileInput::getLong()
{
long *lnLong;
delete[] m_szBuffer;
m_szBuffer = new char[m_nLongSize];
m_FileStream.read(m_szBuffer, m_nLongSize);
lnLong = reinterpret_cast<long*>(m_szBuffer);
m_nPosition = m_FileStream.tellg();
return *lnLong;
}
float BinFileInput::getFloat()
{
float *fFloat;
delete[] m_szBuffer;
m_szBuffer = new char[m_nFloatSize];
m_FileStream.read(m_szBuffer, m_nFloatSize);
fFloat = reinterpret_cast<float*>(m_szBuffer);
m_nPosition = m_FileStream.tellg();
return *fFloat;
}
double BinFileInput::getDouble()
{
double *dDouble;
delete[] m_szBuffer;
m_szBuffer = new char[m_nDoubleSize];
m_FileStream.read(m_szBuffer, m_nDoubleSize);
dDouble = reinterpret_cast<double*>(m_szBuffer);
m_nPosition = m_FileStream.tellg();
return *dDouble;
}
<file_sep>/src/cuda/find_neighbors.cu
// -*- c++ -*-
/*
* find_neighbors.cu
*
*
*
*
*/
#include <cuda.h>
#include "spherocyl_box.h"
#include "cudaErr.h"
#include "data_primitives.h"
#include <math.h>
using namespace std;
const double D_PI = 3.14159265358979;
__global__ void find_moi(int nSpherocyls, double *pdMOI, double *pdA)
{
int thid = threadIdx.x + blockIdx.x * blockDim.x;
while (thid < nSpherocyls) {
double dA = pdA[thid];
pdMOI[thid] = dA*dA / 3;
thid += blockDim.x * gridDim.x;
}
}
__global__ void find_rot_consts(int nSpherocyls, double *pdArea, double *pdMOI, double *pdIsoCoeff, double *pdR, double *pdA)
{
int thid = threadIdx.x + blockIdx.x * blockDim.x;
while (thid < nSpherocyls) {
double dR = pdR[thid];
double dA = pdA[thid];
double dAlpha = dA/dR;
double dC = 3*D_PI + 24*dAlpha + 6*D_PI*dAlpha*dAlpha + 8*dAlpha*dAlpha*dAlpha;
double dArea = D_PI*dR*dR + 4*dR*dA;
pdArea[thid] = dArea;
pdMOI[thid] = dR*dR*dR*dR*dC/(6*dArea);
pdIsoCoeff[thid] = (8*dAlpha + 6*D_PI*dAlpha*dAlpha + 8*dAlpha*dAlpha*dAlpha)/dC;
thid += blockDim.x*gridDim.x;
}
}
///////////////////////////////////////////////////////////////
// Find the Cell ID for each particle:
// The list of cell IDs for each particle is returned to pnCellID
// A list of which particles are in each cell is returned to pnCellList
//
// *NOTE* if there are more than nMaxPPC particles in a given cell,
// not all of these particles will get added to the cell list
///////////////////////////////////////////////////////////////
__global__ void find_cells(int nSpherocyls, int nMaxPPC, double dCellW, double dCellH,
int nCellCols, double dLx, double dLy, double *pdX, double *pdY,
double *pdTheta, int *pnCellID, int *pnPPC, int *pnCellList)
{
// Assign each thread a unique ID accross all thread-blocks, this is its particle ID
int nPID = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
while (nPID < nSpherocyls) {
double dX = pdX[nPID];
double dY = pdY[nPID];
double dTheta = pdTheta[nPID];
// I often allow the stored coordinates to drift slightly outside the box limits
// until
if (dTheta < -D_PI) {
dTheta += 2*D_PI;
pdTheta[nPID] = dTheta;
}
else if (dTheta > D_PI) {
dTheta -= 2*D_PI;
pdTheta[nPID] = dTheta;
}
if (dY >= dLy)
{
dY -= dLy;
pdY[nPID] = dY;
}
else if (dY < 0)
{
dY += dLy;
pdY[nPID] = dY;
}
if (dX >= dLx)
{
dX -= dLx;
pdX[nPID] = dX;
}
else if (dX < 0)
{
dX += dLx;
pdX[nPID] = dX;
}
//find the cell ID, add a particle to that cell
int nCol = (int)(dX / dCellW);
int nRow = (int)(dY / dCellH);
int nCellID = nCol + nRow * nCellCols;
pnCellID[nPID] = nCellID;
//printf("Thid: %d, Blid: %d, Pid: %d, Column: %d, Row: %d, Cell: %d\n", threadIdx.x, blockIdx.x, nPID, nCol, nRow, nCellID);
// Add 1 particle to a cell safely (only allows one thread to access the memory
// address at a time). nPPC is the original value, not the result of addition
int nPPC = atomicAdd(pnPPC + nCellID, 1);
// only add particle to cell if there is not already the maximum number in cell
if (nPPC < nMaxPPC)
pnCellList[nCellID * nMaxPPC + nPPC] = nPID;
else
nPPC = atomicAdd(pnPPC + nCellID, -1);
nPID += nThreads;
}
}
////////////////////////////////////////////////////////////////
// Here a list of possible contacts is created for each particle
// The list of neighbors is returned to pnNbrList
//
// This is one function that I may target for optimization in
// the future because I know it is slowed down by "branch divergence"
////////////////////////////////////////////////////////////////
__global__ void find_nbrs(int nSpherocyls, int nMaxPPC, int *pnCellID, int *pnPPC,
int *pnCellList, int *pnAdjCells, int nMaxNbrs, int *pnNPP,
int *pnNbrList, double *pdX, double *pdY, double *pdR,
double *pdA, double dEpsilon, double dLx, double dLy, double dGamma)
{
int nPID = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = gridDim.x * blockDim.x;
while (nPID < nSpherocyls)
{
double dX = pdX[nPID];
double dY = pdY[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = 0;
// Particles in adjacent cells are added if they are close enough to
// interact without each moving by more than dEpsilon/2
int nCellID = pnCellID[nPID];
int nP = pnPPC[nCellID];
for (int p = 0; p < nP; p++)
{
int nAdjPID = pnCellList[nCellID*nMaxPPC + p];
if (nAdjPID != nPID)
{
double dSigma = dR + dA + pdR[nAdjPID] + pdA[nAdjPID] + dEpsilon;
double dDeltaY = dY - pdY[nAdjPID];
dDeltaY += dLy * ((dDeltaY < -0.5 * dLy) - (dDeltaY > 0.5 * dLy));
if (fabs(dDeltaY) < dSigma)
{
double dDeltaX = dX - pdX[nAdjPID];
dDeltaX += dLx * ((dDeltaX < -0.5 * dLx) - (dDeltaX > 0.5 * dLx));
double dDeltaRx = dDeltaX + dGamma * dDeltaY;
double dDeltaRx2 = dDeltaX + ceil(dGamma) * dDeltaY;
if (fabs(dDeltaRx) < dSigma || fabs(dDeltaRx2) < dSigma)
{
// This indexing makes global memory accesses more coalesced
if (nNbrs < nMaxNbrs)
{
pnNbrList[nSpherocyls * nNbrs + nPID] = nAdjPID;
nNbrs += 1;
}
}
}
}
}
for (int nc = 0; nc < 8; nc++)
{
int nAdjCID = pnAdjCells[8 * nCellID + nc];
nP = pnPPC[nAdjCID];
for (int p = 0; p < nP; p++)
{
int nAdjPID = pnCellList[nAdjCID*nMaxPPC + p];
// The maximum distance at which two particles could contact
// plus a little bit of moving room - dEpsilon
double dSigma = dR + dA + pdA[nAdjPID] + pdR[nAdjPID] + dEpsilon;
double dDeltaY = dY - pdY[nAdjPID];
// Make sure were finding the closest separation
dDeltaY += dLy * ((dDeltaY < -0.5 * dLy) - (dDeltaY > 0.5 * dLy));
if (fabs(dDeltaY) < dSigma)
{
double dDeltaX = dX - pdX[nAdjPID];
dDeltaX += dLx * ((dDeltaX < -0.5 * dLx) - (dDeltaX > 0.5 * dLx));
// Go to unsheared coordinates
double dDeltaRx = dDeltaX + dGamma * dDeltaY;
// Also look at distance when the strain parameter is at its max (0.5)
double dDeltaRx2 = dDeltaX + ceil(dGamma) * dDeltaY;
if (fabs(dDeltaRx) < dSigma || fabs(dDeltaRx2) < dSigma)
{
if (nNbrs < nMaxNbrs)
{
pnNbrList[nSpherocyls * nNbrs + nPID] = nAdjPID;
nNbrs += 1;
}
}
}
}
}
pnNPP[nPID] = nNbrs;
nPID += nThreads;
}
}
///////////////////////////////////////////////////////////////
// Finds a list of possible contacts for each particle
//
// Usually when things are moving I keep track of an Xmoved and Ymoved
// and only call this to make a new list of neighbors if some particle
// has moved more than (dEpsilon / 2) in some direction
///////////////////////////////////////////////////////////////
void Spherocyl_Box::find_neighbors()
{
// reset each byte to 0
cudaMemset((void *) d_pnPPC, 0, sizeof(int)*m_nCells);
cudaMemset((void *) d_pdXMoved, 0, sizeof(double)*m_nSpherocyls);
cudaMemset((void *) d_pdYMoved, 0, sizeof(double)*m_nSpherocyls);
cudaMemset((void *) d_bNewNbrs, 0, sizeof(int));
if (!m_bMOI)
find_rot_consts <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, d_pdArea, d_pdMOI, d_pdIsoC, d_pdR, d_pdA);
find_cells <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, m_nMaxPPC, m_dCellW, m_dCellH, m_nCellCols,
m_dLx, m_dLy, d_pdX, d_pdY, d_pdPhi, d_pnCellID, d_pnPPC, d_pnCellList);
cudaThreadSynchronize();
checkCudaError("Finding cells");
find_nbrs <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, m_nMaxPPC, d_pnCellID, d_pnPPC, d_pnCellList, d_pnAdjCells,
m_nMaxNbrs, d_pnNPP, d_pnNbrList, d_pdX, d_pdY, d_pdR, d_pdA,
m_dEpsilon, m_dLx, m_dLy, m_dGamma);
cudaThreadSynchronize();
checkCudaError("Finding neighbors");
/*
int *h_pnCellID = (int*) malloc(sizeof(int)*3*m_nSpherocyls);
int *h_pnNPP = (int*) malloc(sizeof(int)*3*m_nSpherocyls);
int *h_pnNbrList = (int*) malloc(sizeof(int)*3*m_nSpherocyls*m_nMaxNbrs);
cudaMemcpy(h_pnCellID, d_pnCellID, sizeof(int)*3*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpy(h_pnNPP,d_pnNPP, sizeof(int)*3*m_nSpherocyls,cudaMemcpyDeviceToHost);
cudaMemcpy(h_pnNbrList, d_pnNbrList, sizeof(int)*3*m_nSpherocyls*m_nMaxNbrs, cudaMemcpyDeviceToHost);
for (int p = 0; p < 3*m_nSpherocyls; p++) {
printf("Spherocyl: %d, Cell: %d, neighbors: %d\n",
p, h_pnCellID[p], h_pnNPP[p]);
for (int n = 0; n < h_pnNPP[p]; n++) {
printf("%d ", h_pnNbrList[n*3*m_nSpherocyls + p]);
}
printf("\n");
fflush(stdout);
}
free(h_pnCellID); free(h_pnNPP); free(h_pnNbrList);
*/
}
////////////////////////////////////////////////////////////////////////////////////
// Sets gamma back by 1 (used when gamma > 0.5)
// also finds the cells in the process
//
///////////////////////////////////////////////////////////////////////////////////
__global__ void set_back_coords(int nSpherocyls, double dLx, double dLy, double *pdX, double *pdY, double *pdPhi)
{
// Assign each thread a unique ID accross all thread-blocks, this is its particle ID
int nPID = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
while (nPID < nSpherocyls) {
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
// I often allow the stored coordinates to drift slightly outside the box limits
if (dPhi > D_PI)
{
dPhi -= 2*D_PI;
pdPhi[nPID] = dPhi;
}
else if (dPhi < -D_PI)
{
dPhi += 2*D_PI;
pdPhi[nPID] = dPhi;
}
if (dY > dLy)
{
dY -= dLy;
pdY[nPID] = dY;
}
else if (dY < 0)
{
dY += dLy;
pdY[nPID] = dY;
}
// When gamma -> gamma-Lx/Ly, Xi -> Xi + (Lx/Ly)*Yi
dX += dLx*dY/dLy;
if (dX < 0)
{
dX += dLx;
}
while (dX > dLx)
{
dX -= dLx;
}
pdX[nPID] = dX;
nPID += nThreads;
}
}
void Spherocyl_Box::set_back_gamma()
{
cudaMemset((void *) d_pnPPC, 0, sizeof(int)*m_nCells);
cudaMemset((void *) d_pdXMoved, 0, sizeof(double)*m_nSpherocyls);
cudaMemset((void *) d_pdYMoved, 0, sizeof(double)*m_nSpherocyls);
cudaMemset((void *) d_bNewNbrs, 0, sizeof(int));
/*
int *h_pnCellID = (int*) malloc(sizeof(int)*m_nSpherocyls);
int *h_pnNPP = (int*) malloc(sizeof(int)*m_nSpherocyls);
int *h_pnNbrList = (int*) malloc(sizeof(int)*m_nSpherocyls*m_nMaxNbrs);
cudaMemcpy(h_pnCellID, d_pnCellID, sizeof(int)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpy(h_pnNPP,d_pnNPP, sizeof(int)*m_nSpherocyls,cudaMemcpyDeviceToHost);
cudaMemcpy(h_pnNbrList, d_pnNbrList, sizeof(int)*m_nSpherocyls*m_nMaxNbrs, cudaMemcpyDeviceToHost);
printf("\nSetting coordinate system back by gamma\n\nOld neighbors:");
for (int p = 0; p < m_nSpherocyls; p++) {
printf("Spherocyl: %d, Cell: %d, neighbors: %d\n",
p, h_pnCellID[p], h_pnNPP[p]);
for (int n = 0; n < h_pnNPP[p]; n++) {
printf("%d ", h_pnNbrList[n*m_nSpherocyls + p]);
}
printf("\n");
fflush(stdout);
}
*/
set_back_coords <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, m_dLx, m_dLy, d_pdX, d_pdY, d_pdPhi);
cudaThreadSynchronize();
checkCudaError("Finding new coordinates, cells");
m_dGamma -= m_dLx/m_dLy;
//m_dTotalGamma = int(m_dTotalGamma+1) + m_dGamma; // Gamma total will have diverged slightly due to differences in precision with gamma
find_neighbors();
/*
cudaMemcpy(h_pnCellID, d_pnCellID, sizeof(int)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpy(h_pnNPP,d_pnNPP, sizeof(int)*m_nSpherocyls,cudaMemcpyDeviceToHost);
cudaMemcpy(h_pnNbrList, d_pnNbrList, sizeof(int)*m_nSpherocyls*m_nMaxNbrs, cudaMemcpyDeviceToHost);
printf("\nNew Neighbors:\n");
for (int p = 0; p < m_nSpherocyls; p++) {
printf("Spherocyl: %d, Cell: %d, neighbors: %d\n",
p, h_pnCellID[p], h_pnNPP[p]);
for (int n = 0; n < h_pnNPP[p]; n++) {
printf("%d ", h_pnNbrList[n*m_nSpherocyls + p]);
}
printf("\n");
fflush(stdout);
}
free(h_pnCellID); free(h_pnNPP); free(h_pnNbrList);
*/
}
////////////////////////////////////////////////////////////////////////////
// Finds cells for all particles regardless of maximum particle per cell
// used for reordering particles
/////////////////////////////////////////////////////////////////////////
__global__ void find_cells_nomax(int nSpherocyls, double dCellW, double dCellH,
int nCellCols, double dLx, double dLy, double *pdX, double *pdY,
int *pnCellID, int *pnPPC)
{
// Assign each thread a unique ID accross all thread-blocks, this is its particle ID
int nPID = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
while (nPID < nSpherocyls) {
double dX = pdX[nPID];
double dY = pdY[nPID];
// Particles are allowed to drift slightly outside the box limits
// until cells are reassigned due to a particle drift of dEpsilon/2
if (dY > dLy) {
dY -= dLy;
pdY[nPID] = dY; }
else if (dY < 0) {
dY += dLy;
pdY[nPID] = dY; }
if (dX > dLx) {
dX -= dLx;
pdX[nPID] = dX; }
else if (dX < 0) {
dX += dLx;
pdX[nPID] = dX; }
//find the cell ID, add a particle to that cell
int nCol = (int)(dX / dCellW);
int nRow = (int)(dY / dCellH);
int nCellID = nCol + nRow * nCellCols;
pnCellID[nPID] = nCellID;
int nPPC = atomicAdd(pnPPC + nCellID, 1);
nPID += nThreads; }
}
__global__ void reorder_part(int nSpherocyls, double *pdTempX, double *pdTempY,
double *pdTempR, double *pdTempA,
int *pnTempInitID, double *pdX, double *pdY,
double *pdR, double *pdA, int *pnInitID,
int *pnMemID, int *pnCellID, int *pnCellSID)
{
int nPID = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
while (nPID < nSpherocyls) {
double dX = pdTempX[nPID];
double dY = pdTempY[nPID];
double dR = pdTempR[nPID];
double dA = pdTempA[nPID];
int nInitID = pnTempInitID[nPID];
int nCellID = pnCellID[nPID];
int nNewID = atomicAdd(pnCellSID + nCellID, 1);
pdX[nNewID] = dX;
pdY[nNewID] = dY;
pdR[nNewID] = dR;
pdA[nNewID] = dA;
pnMemID[nInitID] = nNewID;
pnInitID[nNewID] = nInitID;
nPID += nThreads;
}
}
__global__ void invert_IDs(int nIDs, int *pnIn, int *pnOut)
{
int thid = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
while (thid < nIDs) {
int i = pnIn[thid];
pnOut[i] = thid;
thid += nThreads; }
}
void Spherocyl_Box::reorder_particles()
{
cudaMemset((void *) d_pnPPC, 0, sizeof(int)*m_nCells);
//find particle cell IDs and number of particles in each cell
find_cells_nomax <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, m_dCellW, m_dCellH, m_nCellCols,
m_dLx, m_dLy, d_pdX, d_pdY, d_pnCellID, d_pnPPC);
cudaThreadSynchronize();
checkCudaError("Reordering particles: Finding cells");
int *d_pnCellSID;
int *d_pnTempInitID;
double *d_pdTempR;
double *d_pdTempA;
cudaMalloc((void **) &d_pnCellSID, sizeof(int) * m_nCells);
cudaMalloc((void **) &d_pdTempR, sizeof(double) * m_nSpherocyls);
cudaMalloc((void **) &d_pdTempA, sizeof(double) * m_nSpherocyls);
cudaMalloc((void **) &d_pnTempInitID, sizeof(int) * m_nSpherocyls);
cudaMemcpy(d_pdTempX, d_pdX, sizeof(double) * m_nSpherocyls, cudaMemcpyDeviceToDevice);
cudaMemcpy(d_pdTempY, d_pdY, sizeof(double) * m_nSpherocyls, cudaMemcpyDeviceToDevice);
cudaMemcpy(d_pdTempR, d_pdR, sizeof(double) * m_nSpherocyls, cudaMemcpyDeviceToDevice);
cudaMemcpy(d_pdTempA, d_pdA, sizeof(double) * m_nSpherocyls, cudaMemcpyDeviceToDevice);
cudaMemcpy(d_pnTempInitID, d_pnInitID, sizeof(int) * m_nSpherocyls, cudaMemcpyDeviceToDevice);
exclusive_scan(d_pnPPC, d_pnCellSID, m_nCells);
/*
int *h_pnCellSID = (int*) malloc(m_nCells * sizeof(int));
int *h_pnCellNPart = (int*) malloc(m_nCells * sizeof(int));
cudaMemcpy(h_pnCellNPart, d_pnCellNPart, sizeof(int)*m_nCells, cudaMemcpyDeviceToHost);
cudaMemcpy(h_pnCellSID, d_pnCellSID, sizeof(int)*m_nCells, cudaMemcpyDeviceToHost);
for (int c = 0; c < m_nCells; c++)
{
printf("%d %d\n", h_pnCellNPart[c], h_pnCellSID[c]);
}
free(h_pnCellSID);
free(h_pnCellNPart);
*/
//reorder particles based on cell ID (first by Y direction)
reorder_part <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdTempX, d_pdTempY, d_pdTempR, d_pdTempA, d_pnTempInitID,
d_pdX, d_pdY, d_pdR, d_pdA, d_pnInitID, d_pnMemID, d_pnCellID, d_pnCellSID);
cudaThreadSynchronize();
checkCudaError("Reordering particles: changing order");
//invert_IDs <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, d_pnMemID, d_pnInitID);
cudaMemcpyAsync(h_pnMemID, d_pnMemID, m_nSpherocyls*sizeof(int), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdR, d_pdR, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdA, d_pdA, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaThreadSynchronize();
cudaFree(d_pnCellSID); cudaFree(d_pnTempInitID);
cudaFree(d_pdTempR); cudaFree(d_pdTempA);
m_bMOI = 0;
find_neighbors();
}
////////////////////////////////////////////////////////////////////////
// Sets the particle IDs to their order in memory
// so the current IDs become the initial IDs
/////////////////////////////////////////////////////////////////////
void Spherocyl_Box::reset_IDs()
{
ordered_array(d_pnInitID, m_nSpherocyls, m_nGridSize, m_nBlockSize);
cudaMemcpyAsync(h_pnMemID, d_pnInitID, sizeof(int)*m_nSpherocyls, cudaMemcpyDeviceToHost);
cudaMemcpy(d_pnMemID, d_pnInitID, sizeof(int)*m_nSpherocyls, cudaMemcpyDeviceToDevice);
}
__global__ void reflect_yaxis(int nParticles, double *pdX, double *pdPhi, double dLx)
{
int nPID = threadIdx.x + blockDim.x*blockIdx.x;
int nThreads = blockDim.x * gridDim.x;
while (nPID < nParticles) {
pdX[nPID] = dLx - pdX[nPID];
pdPhi[nPID] = -pdPhi[nPID];
nPID += nThreads;
}
}
void Spherocyl_Box::flip_shear_direction()
{
cudaMemset((void *) d_pnPPC, 0, sizeof(int)*m_nCells);
cudaMemset((void *) d_pdXMoved, 0, sizeof(double)*m_nSpherocyls);
cudaMemset((void *) d_pdYMoved, 0, sizeof(double)*m_nSpherocyls);
cudaMemset((void *) d_bNewNbrs, 0, sizeof(int));
reflect_yaxis <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdPhi, m_dLx);
cudaThreadSynchronize();
checkCudaError("Finding new coordinates, cells");
m_dGamma = -m_dGamma;
find_neighbors();
}
__global__ void gamma_rotate(int nParticles, double *pdX, double *pdY, double *pdPhi, double dNewLx, double dNewLy, double dGamma)
{
int nPID = threadIdx.x + blockDim.x*blockIdx.x;
int nThreads = blockDim.x * gridDim.x;
while (nPID < nParticles) {
double dY = pdY[nPID];
double dX = pdX[nPID];
double dNewX = (1-2*signbit(dGamma))*dY*sqrt(1+dGamma*dGamma);
double dNewY = (2*signbit(dGamma)-1)*dX/sqrt(1+dGamma*dGamma);
double dNewPhi;
if (dGamma != 0.0)
dNewPhi = pdPhi[nPID] - atan(1/dGamma);
else
dNewPhi = pdPhi[nPID] - D_PI/2;
if (dNewPhi > D_PI) {
dNewPhi -= 2*D_PI;
}
else if (dNewPhi < -D_PI) {
dNewPhi += 2*D_PI;
}
pdPhi[nPID] = dNewPhi;
if (dNewY > dNewLy) {
dNewY -= dNewLy;
}
else if (dNewY < 0) {
dNewY += dNewLy;
}
pdY[nPID] = dNewY;
if (dNewX < 0) {
dNewX += dNewLx;
}
else if (dNewX > dNewLx) {
dNewX -= dNewLx;
}
pdX[nPID] = dNewX;
nPID += nThreads;
}
}
void Spherocyl_Box::rotate_by_gamma()
{
cudaMemset((void *) d_pnPPC, 0, sizeof(int)*m_nCells);
cudaMemset((void *) d_pdXMoved, 0, sizeof(double)*m_nSpherocyls);
cudaMemset((void *) d_pdYMoved, 0, sizeof(double)*m_nSpherocyls);
cudaMemset((void *) d_bNewNbrs, 0, sizeof(int));
double dLx = m_dLx;
double dLy = m_dLy;
m_dLx = dLy*sqrt(1+m_dGamma*m_dGamma);
m_dLy = dLx/sqrt(1+m_dGamma*m_dGamma);
gamma_rotate <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, m_dLx, m_dLy, m_dGamma);
cudaThreadSynchronize();
checkCudaError("Finding new coordinates, cells");
m_dGamma = -m_dGamma;
reconfigure_cells();
find_neighbors();
}
<file_sep>/src/cuda/find_contacts.cu
// -*- c++ -*-
/*
* find_contacts.cu
*
*
*/
#include <cuda.h>
#include "spherocyl_box.h"
#include "cudaErr.h"
#include <math.h>
#include <sm_20_atomic_functions.h>
using namespace std;
////////////////////////////////////////////////////////
// Finds contacts:
// Returns number of contacts of each particle to pnContacts
// Returns 2*(the total numer of contacts) to pnTotContacts
//
// The neighbor list pnNbrList has a list of possible contacts
// for each particle and is found in find_neighbors.cu
//
/////////////////////////////////////////////////////////
__global__ void find_cont(int nSpherocyls, int *pnNPP, int *pnNbrList, double dL,
double dGamma, double *pdX, double *pdY, double *pdR,
double dEpsilon, int *pnContacts, int *pnTotContacts)
{
// Declare shared memory pointer, the size is determined at the kernel launch
extern __shared__ int sData[];
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
sData[thid] = 0;
__syncthreads(); // synchronizes every thread in the block before going on
while (nPID < nSpherocyls)
{
double dX = pdX[nPID];
double dY = pdY[nPID];
double dR = pdR[nPID];
int nContacts = 0;
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dDeltaX = dX - pdX[nAdjPID];
double dDeltaY = dY - pdY[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dL * ((dDeltaX < -0.5*dL) - (dDeltaX > 0.5*dL));
dDeltaY += dL * ((dDeltaY < -0.5*dL) - (dDeltaY > 0.5*dL));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
// Check if they overlap
double dRSqr = dDeltaX*dDeltaX + dDeltaY*dDeltaY;
if (dRSqr < dSigma*dSigma)
nContacts += 1;
}
pnContacts[nPID] = nContacts;
sData[thid] += nContacts;
nPID += nThreads;
}
__syncthreads();
// Now we do a parallel reduction sum to find the total number of contacts
int offset = blockDim.x / 2;
while (offset > 32)
{
if (thid < offset)
sData[thid] += sData[thid + offset];
offset /= 2;
__syncthreads();
}
if (thid < 32) //unroll end of loop (no need to sync since warp size=32
{
sData[thid] += sData[thid + 32];
if (thid < 16)
{
sData[thid] += sData[thid + 16];
if (thid < 8)
{
sData[thid] += sData[thid + 8];
if (thid < 4)
{
sData[thid] += sData[thid + 4];
if (thid < 2)
{
sData[thid] += sData[thid + 2];
if (thid == 0)
{
sData[0] += sData[1];
int tot = atomicAdd(pnTotContacts, sData[0]);
}
}
}
}
}
}
}
void Spherocyl_Box::find_contacts()
{
cudaMemset(d_pnTotContacts, 0, sizeof(int));
find_cont <<<m_nGS_FindContact, m_nBS_FindContact, m_nSM_FindContact>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dL, m_dGamma, d_pdX, d_pdY,
d_pdR, m_dEpsilon, d_pnContacts, d_pnTotContacts);
cudaThreadSynchronize();
}
<file_sep>/src/cuda/2point_dynamics.cu
// -*- c++ -*-
/*
* strain_dynamics.cu
*
*
*/
#include <cuda.h>
#include "spherocyl_box.h"
#include "cudaErr.h"
#include <math.h>
#include <sm_20_atomic_functions.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
using namespace std;
const double D_PI = 3.14159265358979;
/*
__global__ void calc_rot_consts(int nSpherocyls, double *pdR, double *pdAs,
double *pdAb, double *pdCOM, double *pdMOI,
double *pdSinCoeff, double *pdCosCoeff)
{
int nPID = threadIdx.x + blockIdx.x * blockDim.x;
int nThreads = blockDim.x + gridDim.x;
while (nPID < nSpherocyls) {
double dR = pdR[nPID];
double dAs = pdAs[nPID];
double dA = dAs + 2. * dR;
double dB = pdAb[nPID];
double dC = pdCOM[nPID];
double dIntdS = 2*dA + 4*dB;
double dIntSy2SinCoeff = dA*dA*(2*dA/3 + 4*dB);
double dIntSy2CosCoeff = dB*dB*(16*dB/3 - 8*dC) + 2*(dA + 2*dB)*dC*dC;
double dIntS2 = dIntSy2SinCoeff + dIntSy2CosCoeff;
pdMOI[nPID] = dIntS2 / dIntdS;
pdSinCoeff[nPID] = dIntSy2SinCoeff / dIntS2;
pdCosCoeff[nPID] = dIntSy2CosCoeff / dIntS2;
nPID += nThreads;
}
}
*/
///////////////////////////////////////////////////////////////
//
// Deprecated method
//
///////////////////////////////////////////////////////////
template<Potential ePot, int bCalcStress>
__global__ void euler_est_sc_2p(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy,
double dGamma, double dStrain, double dStep, double *pdX, double *pdY,
double *pdPhi, double *pdR, double *pdA, double *pdMOI, double *pdFx, double *pdFy,
double *pdFt, float *pfSE, double *pdTempX, double *pdTempY, double *pdTempPhi)
{
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
extern __shared__ double sData[];
int offset = blockDim.x + 8; // +8 should help to avoid a few bank conflict
if (bCalcStress) {
for (int i = 0; i < 5; i++)
sData[i*offset + thid] = 0.0;
__syncthreads(); // synchronizes every thread in the block before going on
}
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dFt = 0.0;
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dDeltaX = dX - pdX[nAdjPID];
double dDeltaY = dY - pdY[nAdjPID];
double dPhiB = pdPhi[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double s1, t1, s2, t2, s3, t3;
if (delta <= 0) { //delta should never be negative but I'm using <= in case it comes out negative due to precision
s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
if (b < 0)
t1 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
else
t1 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
if (b < 0)
t2 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
else
t2 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
s3 = s2;
t3 = t2;
}
else {
t1 = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s1 = -(b*t1+d)/a;
double sarg = fabs(s1);
s1 = fmin( fmax(s1,-1.), 1. );
if (sarg >= 1) {
t1 = fmin( fmax( -(b*s1+e)/c, -1.), 1.);
s2 = -s1;
t2 = -(b*s2+e)/c;
double targ = fabs(t2);
t2 = fmin( fmax(t2, -1.), 1.);
if (targ >= 1) {
s2 = fmin( fmax( -(b*t2+d)/a, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
t3 = -s1;
else
t3 = s1;
s3 = -(b*t3+d)/a;
sarg = fabs(s3);
s3 = fmin(fmax(s3, -1.0), 1.0);
if (sarg >= 1)
t3 = fmin(fmax(-(b*s3+e)/c, -1.0), 1.0);
}
}
else {
t2 = -t1;
s2 = -(b*t2+d)/a;
sarg = fabs(s2);
s2 = fmin( fmax(s2, -1.), 1.);
if (sarg >= 1) {
t2 = fmin( fmax( -(b*s2+e)/c, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
s3 = -t1;
else
s3 = t1;
t3 = -(b*s3+e)/c;
double targ = fabs(t3);
t3 = fmin(fmax(t3, -1.0), 1.0);
if (targ >= 1)
s3 = min(max(-(b*t3+d)/a, -1.0), 1.0);
}
}
}
// Check if they overlap and calculate forces
double dDx1 = dDeltaX + s1*nxA - t1*nxB;
double dDy1 = dDeltaY + s1*nyA - t1*nyB;
double dDSqr1 = dDx1 * dDx1 + dDy1 * dDy1;
if (dDSqr1 < dSigma*dSigma) {
double dDij = sqrt(dDSqr1);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx1 * dDVij / dDij;
double dPfy = dDy1 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
dFt += s1*nxA * dPfy - s1*nyA * dPfx;
if (bCalcStress)
{
double dCx = 0.5*dDx1 - s1*nxA;
double dCy = 0.5*dDy1 - s1*nyA;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
if (s1 != s2 && t1 != t2) {
double dDx2 = dDeltaX + s2*nxA - t2*nxB;
double dDy2 = dDeltaY + s2*nyA - t2*nyB;
double dDSqr2 = dDx2 * dDx2 + dDy2 * dDy2;
if (s3 != s1 && s3 != s2) {
double dDx3 = dDeltaX + s3*nxA - t3*nxB;
double dDy3 = dDeltaY + s3*nyA - t3*nyB;
double dDSqr3 = dDx3 * dDx3 + dDy3 * dDy3;
if (dDSqr3 < dDSqr2) {
s2 = s3;
t2 = t3;
dDx2 = dDx3;
dDy2 = dDy3;
dDSqr2 = dDSqr3;
}
}
if (dDSqr2 < dSigma*dSigma) {
double dDij = sqrt(dDSqr2);
double dDVij, dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx2 * dDVij / dDij;
double dPfy = dDy2 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
dFt += s2*nxA * dPfy - s2*nyA * dPfx;
if (bCalcStress)
{
double dCx = 0.5*dDx2 - s2*nxA;
double dCy = 0.5*dDy2 - s2*nyA;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
}
pdFx[nPID] = dFx;
pdFy[nPID] = dFy;
pdFt[nPID] = dFt;
pdTempX[nPID] = dX + dStep * (dFx - dGamma * dFy);
pdTempY[nPID] = dY + dStep * dFy;
double dSinPhi = sin(dPhi);
pdTempPhi[nPID] = dPhi + dStep *
(dFt / pdMOI[nPID] - dStrain * dSinPhi * dSinPhi);
nPID += nThreads;
}
if (bCalcStress) {
__syncthreads();
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size, all threads perform two adds
int base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
base += 2*offset;
sData[base] += sData[base + stride];
if (thid < stride) {
base += 2*offset;
sData[base] += sData[base + stride];
}
stride /= 2; // stride is 1/4 block size, all threads perform 1 add
__syncthreads();
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
if (thid < stride) {
base += 4*offset;
sData[base] += sData[base+stride];
}
stride /= 2;
__syncthreads();
while (stride > 4)
{
if (thid < 5 * stride)
{
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 20)
{
base = thid % 4 + offset * (thid / 4);
sData[base] += sData[base + 4];
if (thid < 10)
{
base = thid % 2 + offset * (thid / 2);
sData[base] += sData[base + 2];
if (thid < 5)
{
sData[thid * offset] += sData[thid * offset + 1];
float tot = atomicAdd(pfSE+thid, (float)sData[thid*offset]);
}
}
}
}
}
////////////////////////////////////////////////
//
// First step (Newtonian estimate) for integration of e.o.m.
// Uses two points of contact along flat sides when applicable
//
////////////////////////////////////////////
template<Potential ePot, int bCalcStress>
__global__ void euler_est_2p(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy, double dGamma,
double dStrain, double dStep, double *pdX, double *pdY, double *pdPhi, double *pdR,
double *pdA, double dKd, double *pdArea, double *pdMOI, double *pdIsoC, double *pdFx,
double *pdFy, double *pdFt, float *pfSE, double *pdTempX, double *pdTempY, double *pdTempPhi)
{
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
extern __shared__ double sData[];
int offset = blockDim.x + 8; // +8 should help to avoid a few bank conflict
if (bCalcStress) {
for (int i = 0; i < 5; i++)
sData[i*offset + thid] = 0.0;
__syncthreads(); // synchronizes every thread in the block before going on
}
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dFt = 0.0;
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dAdjX = pdX[nAdjPID];
double dAdjY = pdY[nAdjPID];
double dDeltaX = dX - dAdjX;
double dDeltaY = dY - dAdjY;
double dPhiB = pdPhi[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double s1, t1, s2, t2, s3, t3;
if (delta <= 0) { //delta should never be negative but I'm using <= in case it comes out negative due to precision
s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
if (fabs(s1) == 1)
t1 = fmin(fmax( -(b*s1+e)/c, -1.0), 1.0);
else if (b < 0)
t1 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
else
t1 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
if (fabs(s2) == 1)
t2 = fmin(fmax( -(b*s2+e)/c, -1.0), 1.0);
else if (b < 0)
t2 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
else
t2 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
s3 = s2;
t3 = t2;
}
else {
t1 = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s1 = -(b*t1+d)/a;
double sarg = fabs(s1);
s1 = fmin( fmax(s1,-1.), 1. );
if (sarg >= 1) {
t1 = fmin( fmax( -(b*s1+e)/c, -1.), 1.);
s2 = -s1;
t2 = -(b*s2+e)/c;
double targ = fabs(t2);
t2 = fmin( fmax(t2, -1.), 1.);
if (targ > 1) {
s2 = fmin( fmax( -(b*t2+d)/a, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
t3 = -s1;
else
t3 = s1;
s3 = -(b*t3+d)/a;
sarg = fabs(s3);
s3 = fmin(fmax(s3, -1.0), 1.0);
if (sarg >= 1)
t3 = fmin(fmax(-(b*s3+e)/c, -1.0), 1.0);
}
}
else {
t2 = -t1;
s2 = -(b*t2+d)/a;
sarg = fabs(s2);
s2 = fmin( fmax(s2, -1.), 1.);
if (sarg > 1) {
t2 = fmin( fmax( -(b*s2+e)/c, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
s3 = -t1;
else
s3 = t1;
t3 = -(b*s3+e)/c;
double targ = fabs(t3);
t3 = fmin(fmax(t3, -1.0), 1.0);
if (targ >= 1)
s3 = min(max(-(b*t3+d)/a, -1.0), 1.0);
}
}
}
// Check if they overlap and calculate forces
double dDx1 = dDeltaX + s1*nxA - t1*nxB;
double dDy1 = dDeltaY + s1*nyA - t1*nyB;
double dDSqr1 = dDx1 * dDx1 + dDy1 * dDy1;
if (dDSqr1 < dSigma*dSigma) {
double dDij = sqrt(dDSqr1);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx1 * dDVij / dDij;
double dPfy = dDy1 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
// Find the point of contact (with respect to the center of the spherocyl)
//double dCx = s*nxA - 0.5*dDx;
//double dCy = s*nyA - 0.5*dDy;
//double dCx = s*nxA;
//double dCy = s*nyA;
dFt += s1*nxA * dPfy - s1*nyA * dPfx;
if (bCalcStress)
{
double dCx = 0.5*dDx1 - s1*nxA;
double dCy = 0.5*dDy1 - s1*nyA;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
if (s1 != s2 && t1 != t2) {
double dDx2 = dDeltaX + s2*nxA - t2*nxB;
double dDy2 = dDeltaY + s2*nyA - t2*nyB;
double dDSqr2 = dDx2 * dDx2 + dDy2 * dDy2;
if (s3 != s1 && s3 != s2) {
double dDx3 = dDeltaX + s3*nxA - t3*nxB;
double dDy3 = dDeltaY + s3*nyA - t3*nyB;
double dDSqr3 = dDx3 * dDx3 + dDy3 * dDy3;
if (dDSqr3 < dDSqr2) {
s2 = s3;
t2 = t3;
dDx2 = dDx3;
dDy2 = dDy3;
dDSqr2 = dDSqr3;
}
}
if (dDSqr2 < dSigma*dSigma) {
double dDij = sqrt(dDSqr2);
double dDVij, dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 -dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx2 * dDVij / dDij;
double dPfy = dDy2 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
dFt += s2*nxA * dPfy - s2*nyA * dPfx;
if (bCalcStress) {
double dCx = 0.5*dDx2 - s2*nxA;
double dCy = 0.5*dDy2 - s2*nyA;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
}
pdFx[nPID] = dFx;
pdFy[nPID] = dFy;
pdFt[nPID] = dFt;
double dArea = pdArea[nPID];
dFx /= (dKd*dArea);
dFy /= (dKd*dArea);
dFt /= (dKd*dArea*pdMOI[nPID]);
pdTempX[nPID] = dX + dStep * (dFx - dGamma * dFy);
pdTempY[nPID] = dY + dStep * dFy;
double dRIso = 0.5*(1-pdIsoC[nPID]*cos(2*dPhi));
pdTempPhi[nPID] = dPhi + dStep * (dFt - dStrain * dRIso);
nPID += nThreads;
}
if (bCalcStress) {
__syncthreads();
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size, all threads perform two adds
int base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
base += 2*offset;
sData[base] += sData[base + stride];
if (thid < stride) {
base += 2*offset;
sData[base] += sData[base + stride];
}
stride /= 2; // stride is 1/4 block size, all threads perform 1 add
__syncthreads();
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
if (thid < stride) {
base += 4*offset;
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
while (stride > 4)
{
if (thid < 5 * stride)
{
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 20)
{
base = thid % 4 + offset * (thid / 4);
sData[base] += sData[base + 4];
if (thid < 10)
{
base = thid % 2 + offset * (thid / 2);
sData[base] += sData[base + 2];
if (thid < 5)
{
sData[thid * offset] += sData[thid * offset + 1];
float tot = atomicAdd(pfSE+thid, (float)sData[thid*offset]);
}
}
}
}
}
///////////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////////
template<Potential ePot>
__global__ void heun_corr_2p(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy, double dGamma,
double dStrain, double dStep, double *pdX, double *pdY, double *pdPhi, double *pdR,
double *pdA, double dKd, double *pdArea, double *pdMOI, double *pdIsoC, double *pdFx,
double *pdFy, double *pdFt, double *pdTempX, double *pdTempY, double *pdTempPhi,
double *pdXMoved, double *pdYMoved, double dEpsilon, int *bNewNbrs)
{
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dFt = 0.0;
double dX = pdTempX[nPID];
double dY = pdTempY[nPID];
double dPhi = pdTempPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
double dNewGamma = dGamma + dStep * dStrain;
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dAdjX = pdTempX[nAdjPID];
double dAdjY = pdTempY[nAdjPID];
double dDeltaX = dX - dAdjX;
double dDeltaY = dY - dAdjY;
double dPhiB = pdTempPhi[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dNewGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double s1, t1, s2, t2, s3, t3;
if (delta <= 0) { //delta should never be negative but I'm using <= in case it comes out negative due to precision;
s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
if (fabs(s1) == 1)
t1 = fmin(fmax( -(b*s1+e)/c, -1.0), 1.0);
else if (b < 0)
t1 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
else
t1 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
if (fabs(s2) == 1)
t2 = fmin(fmax( -(b*s2+e)/c, -1.0), 1.0);
else if (b < 0)
t2 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
else
t2 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
s3 = s2;
t3 = t2;
}
else {
t1 = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s1 = -(b*t1+d)/a;
double sarg = fabs(s1);
s1 = fmin( fmax(s1,-1.), 1. );
if (sarg >= 1) {
t1 = fmin( fmax( -(b*s1+e)/c, -1.), 1.);
s2 = -s1;
t2 = -(b*s2+e)/c;
double targ = fabs(t2);
t2 = fmin( fmax(t2, -1.), 1.);
if (targ > 1) {
s2 = fmin( fmax( -(b*t2+d)/a, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
t3 = -s1;
else
t3 = s1;
s3 = -(b*t3+d)/a;
sarg = fabs(s3);
s3 = fmin(fmax(s3, -1.0), 1.0);
if (sarg >= 1)
t3 = fmin(fmax(-(b*s3+e)/c, -1.0), 1.0);
}
}
else {
t2 = -t1;
s2 = -(b*t2+d)/a;
sarg = fabs(s2);
s2 = fmin( fmax(s2, -1.), 1.);
if (sarg > 1) {
t2 = fmin( fmax( -(b*s2+e)/c, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
s3 = -t1;
else
s3 = t1;
t3 = -(b*s3+e)/c;
double targ = fabs(t3);
t3 = fmin(fmax(t3, -1.0), 1.0);
if (targ >= 1)
s3 = min(max(-(b*t3+d)/a, -1.0), 1.0);
}
}
}
// Check if they overlap and calculate forces
double dDx1 = dDeltaX + s1*nxA - t1*nxB;
double dDy1 = dDeltaY + s1*nyA - t1*nyB;
double dDSqr1 = dDx1 * dDx1 + dDy1 * dDy1;
if (dDSqr1 < dSigma*dSigma) {
double dDij = sqrt(dDSqr1);
double dDVij;
//double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
//dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
//dAlpha = 2.5;
}
double dPfx = dDx1 * dDVij / dDij;
double dPfy = dDy1 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
//double dCx = s*nxA - 0.5*dDx;
//double dCy = s*nyA - 0.5*dDy;
double dCx = s1*nxA;
double dCy = s1*nyA;
dFt += dCx * dPfy - dCy * dPfx;
}
if (s1 != s2 && t1 != t2) {
double dDx2 = dDeltaX + s2*nxA - t2*nxB;
double dDy2 = dDeltaY + s2*nyA - t2*nyB;
double dDSqr2 = dDx2 * dDx2 + dDy2 * dDy2;
if (s3 != s1 && s3 != s2) {
double dDx3 = dDeltaX + s3*nxA - t3*nxB;
double dDy3 = dDeltaY + s3*nyA - t3*nyB;
double dDSqr3 = dDx3 * dDx3 + dDy3 * dDy3;
if (dDSqr3 < dDSqr2) {
s2 = s3;
t2 = t3;
dDx2 = dDx3;
dDy2 = dDy3;
dDSqr2 = dDSqr3;
}
}
if (dDSqr2 < dSigma*dSigma) {
double dDij = sqrt(dDSqr2);
double dDVij;
if (ePot == HARMONIC)
{
dDVij = (1.0 -dDij / dSigma) / dSigma;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
}
double dPfx = dDx2 * dDVij / dDij;
double dPfy = dDy2 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
dFt += s2*nxA * dPfy - s2*nyA * dPfx;
}
}
}
double dMOI = pdMOI[nPID];
double dIsoC = pdIsoC[nPID];
double dArea = pdArea[nPID];
dFx /= (dKd*dArea);
dFy /= (dKd*dArea);
dFt /= (dKd*dArea*dMOI);
dFx -= dNewGamma * dFy;
dFt = dFt - dStrain * 0.5 * (1 - dIsoC*cos(2*dPhi));
double dFy0 = pdFy[nPID] / (dKd*dArea);
double dFx0 = pdFx[nPID] / (dKd*dArea) - dGamma * dFy0;
double dPhi0 = pdPhi[nPID] / (dKd*dArea*dMOI);
double dFt0 = pdFt[nPID] - dStrain * 0.5 * (1 - dIsoC*cos(2*dPhi0));
double dDx = 0.5 * dStep * (dFx0 + dFx);
double dDy = 0.5 * dStep * (dFy0 + dFy);
pdX[nPID] += dDx;
pdY[nPID] += dDy;
pdPhi[nPID] += 0.5 * dStep * (dFt0 + dFt);
pdXMoved[nPID] += dDx;
pdYMoved[nPID] += dDy;
if (fabs(pdXMoved[nPID]) + fabs(pdYMoved[nPID]) > 0.5*dEpsilon)
*bNewNbrs = 1;
nPID += nThreads;
}
}
////////////////////////////////////////////////////////////////////////
//
//
////////////////////////////////////////////////////////////////////
void Spherocyl_Box::strain_step_2p(long unsigned int tTime, bool bSvStress, bool bSvPos)
{
if (bSvStress)
{
cudaMemset((void *) d_pfSE, 0, 5*sizeof(float));
switch (m_ePotential)
{
case HARMONIC:
euler_est_2p <HARMONIC, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est_2p <HERTZIAN, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions, calculating stresses");
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
if (bSvPos)
{
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
}
cudaThreadSynchronize();
}
else
{
switch (m_ePotential)
{
case HARMONIC:
euler_est_2p <HARMONIC, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est_2p <HERTZIAN, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions");
}
switch (m_ePotential)
{
case HARMONIC:
heun_corr_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdXMoved,
d_pdYMoved, m_dEpsilon, d_bNewNbrs);
break;
case HERTZIAN:
heun_corr_2p <HERTZIAN> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdXMoved,
d_pdYMoved, m_dEpsilon, d_bNewNbrs);
}
if (bSvStress)
{
m_fP = 0.5 * (*m_pfPxx + *m_pfPyy);
fprintf(m_pOutfSE, "%lu %.7g %.7g %.7g %.7g %.7g %.7g\n",
tTime, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy, *m_pfPyx);
if (bSvPos)
save_positions(tTime);
}
cudaThreadSynchronize();
checkCudaError("Updating estimates, moving particles");
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
m_dGamma += m_dStep * m_dStrainRate;
m_dTotalGamma += m_dStep * m_dStrainRate;
cudaThreadSynchronize();
if (m_dGamma > 0.5*m_dLx/m_dLy)
set_back_gamma();
else if (*h_bNewNbrs)
find_neighbors();
}
////////////////////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////
void Spherocyl_Box::run_strain_2p(double dStartGamma, double dStopGamma, double dSvStressGamma, double dSvPosGamma)
{
if (m_dStrainRate == 0.0)
{
fprintf(stderr, "Cannot strain with zero strain rate\n");
exit(1);
}
printf("Beginnig strain run with strain rate: %g and step %g\n", m_dStrainRate, m_dStep);
fflush(stdout);
if (dSvStressGamma < m_dStrainRate * m_dStep)
dSvStressGamma = m_dStrainRate * m_dStep;
if (dSvPosGamma < m_dStrainRate)
dSvPosGamma = m_dStrainRate;
// +0.5 to cast to nearest integer rather than rounding down
unsigned long int nTime = (unsigned long)(dStartGamma / m_dStrainRate + 0.5);
unsigned long int nStop = (unsigned long)(dStopGamma / m_dStrainRate + 0.5);
unsigned int nIntStep = (unsigned int)(1.0 / m_dStep + 0.5);
unsigned int nSvStressInterval = (unsigned int)(dSvStressGamma / (m_dStrainRate * m_dStep) + 0.5);
unsigned int nSvPosInterval = (unsigned int)(dSvPosGamma / m_dStrainRate + 0.5);
unsigned long int nTotalStep = nTime * nIntStep;
//unsigned int nReorderInterval = (unsigned int)(1.0 / m_dStrainRate + 0.5);
printf("Strain run configured\n");
printf("Start: %lu, Stop: %lu, Int step: %lu\n", nTime, nStop, nIntStep);
printf("Stress save int: %lu, Pos save int: %lu\n", nSvStressInterval, nSvPosInterval);
fflush(stdout);
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
if (nTime == 0)
{
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL)
{
fprintf(stderr, "Could not open file for writing");
exit(1);
}
}
else
{
m_pOutfSE = fopen(szPathSE, "r+");
if (m_pOutfSE == NULL)
{
fprintf(stderr, "Could not open file for writing");
exit(1);
}
unsigned long int nTpos = 0;
while (nTpos != nTime)
{
if (fgets(szBuf, 200, m_pOutfSE) != NULL)
{
int nPos = strcspn(szBuf, " ");
char szTime[20];
strncpy(szTime, szBuf, nPos);
szTime[nPos] = '\0';
nTpos = atol(szTime);
}
else
{
fprintf(stderr, "Reached end of file without finding start position");
exit(1);
}
}
}
// Run strain for specified number of steps
while (nTime < nStop)
{
bool bSvPos = (nTime % nSvPosInterval == 0);
if (bSvPos) {
strain_step_2p(nTime, 1, 1);
fflush(m_pOutfSE);
}
else
{
bool bSvStress = (nTotalStep % nSvStressInterval == 0);
strain_step_2p(nTime, bSvStress, 0);
}
nTotalStep += 1;
for (unsigned int nI = 1; nI < nIntStep; nI++)
{
bool bSvStress = (nTotalStep % nSvStressInterval == 0);
strain_step_2p(nTime, bSvStress, 0);
nTotalStep += 1;
}
nTime += 1;
//if (nTime % nReorderInterval == 0)
//reorder_particles();
}
// Save final configuration
strain_step_2p(nTime, 1, 1);
fflush(m_pOutfSE);
fclose(m_pOutfSE);
}
void Spherocyl_Box::run_strain_2p(unsigned long int nStart, double dRunGamma, double dSvStressGamma, double dSvPosGamma)
{
if (m_dStrainRate == 0.0)
{
fprintf(stderr, "Cannot strain with zero strain rate\n");
exit(1);
}
printf("Beginnig strain run with strain rate: %g and step %g\n", m_dStrainRate, m_dStep);
fflush(stdout);
if (dSvStressGamma < m_dStrainRate * m_dStep)
dSvStressGamma = m_dStrainRate * m_dStep;
if (dSvPosGamma < m_dStrainRate)
dSvPosGamma = m_dStrainRate;
// +0.5 to cast to nearest integer rather than rounding down
unsigned long int nTime = nStart;
unsigned long int nStop = nStart + (unsigned long)(dRunGamma / m_dStrainRate + 0.5);
unsigned int nIntStep = (unsigned int)(1.0 / m_dStep + 0.5);
unsigned int nSvStressInterval = (unsigned int)(dSvStressGamma / (m_dStrainRate * m_dStep) + 0.5);
unsigned int nSvPosInterval = (unsigned int)(dSvPosGamma / m_dStrainRate + 0.5);
unsigned long int nTotalStep = nTime * nIntStep;
//unsigned int nReorderInterval = (unsigned int)(1.0 / m_dStrainRate + 0.5);
printf("Strain run configured\n");
printf("Start: %lu, Stop: %lu, Int step: %lu\n", nTime, nStop, nIntStep);
printf("Stress save int: %lu, Pos save int: %lu\n", nSvStressInterval, nSvPosInterval);
fflush(stdout);
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
if (nTime == 0)
{
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL)
{
fprintf(stderr, "Could not open file for writing");
exit(1);
}
}
else
{
m_pOutfSE = fopen(szPathSE, "r+");
if (m_pOutfSE == NULL)
{
fprintf(stderr, "Could not open file for writing");
exit(1);
}
unsigned long int nTpos = 0;
while (nTpos != nTime)
{
if (fgets(szBuf, 200, m_pOutfSE) != NULL)
{
int nPos = strcspn(szBuf, " ");
char szTime[20];
strncpy(szTime, szBuf, nPos);
szTime[nPos] = '\0';
nTpos = atol(szTime);
}
else
{
fprintf(stderr, "Reached end of file without finding start position");
exit(1);
}
}
}
// Run strain for specified number of steps
while (nTime < nStop)
{
bool bSvPos = (nTime % nSvPosInterval == 0);
if (bSvPos) {
strain_step_2p(nTime, 1, 1);
fflush(m_pOutfSE);
}
else
{
bool bSvStress = (nTotalStep % nSvStressInterval == 0);
strain_step_2p(nTime, bSvStress, 0);
}
nTotalStep += 1;
for (unsigned int nI = 1; nI < nIntStep; nI++)
{
bool bSvStress = (nTotalStep % nSvStressInterval == 0);
strain_step_2p(nTime, bSvStress, 0);
nTotalStep += 1;
}
nTime += 1;
//if (nTime % nReorderInterval == 0)
//reorder_particles();
}
// Save final configuration
strain_step_2p(nTime, 1, 1);
fflush(m_pOutfSE);
fclose(m_pOutfSE);
}
void Spherocyl_Box::run_strain_2p(long unsigned int nSteps)
{
// Run strain for specified number of steps
long unsigned int nTime = 0;
while (nTime < nSteps)
{
strain_step_2p(nTime, 0, 0);
nTime += 1;
}
}
__global__ void resize_coords_2p(int nParticles, double dEpsilon, double *pdX, double *pdY)
{
int nPID = threadIdx.x + blockIdx.x*blockDim.x;
int nThreads = blockDim.x*gridDim.x;
while (nPID < nParticles) {
pdX[nPID] += dEpsilon*pdX[nPID];
pdY[nPID] += dEpsilon*pdY[nPID];
nPID += nThreads;
}
}
__global__ void resize_y_coords_2p(int nParticles, double dEpsilon, double *pdY)
{
int nPID = threadIdx.x + blockIdx.x*blockDim.x;
int nThreads = blockDim.x*gridDim.x;
while (nPID < nParticles) {
pdY[nPID] += dEpsilon*pdY[nPID];
nPID += nThreads;
}
}
void Spherocyl_Box::resize_step_2p(long unsigned int tTime, double dEpsilon, bool bSvStress, bool bSvPos)
{
if (dEpsilon > 0) {
dEpsilon = 1./(1.-dEpsilon) - 1.;
}
resize_coords_2p <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, dEpsilon, d_pdX, d_pdY);
m_dLx += dEpsilon*m_dLx;
m_dLy += dEpsilon*m_dLy;
m_dPacking = calculate_packing();
cudaThreadSynchronize();
checkCudaError("Resizing box");
if (bSvStress)
{
cudaMemset((void *) d_pfSE, 0, 5*sizeof(float));
switch (m_ePotential)
{
case HARMONIC:
euler_est_2p <HARMONIC, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est_2p <HERTZIAN, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions, calculating stresses");
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
if (bSvPos)
{
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
}
cudaThreadSynchronize();
}
else
{
switch (m_ePotential)
{
case HARMONIC:
euler_est_2p <HARMONIC, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est_2p <HERTZIAN, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions");
}
switch (m_ePotential)
{
case HARMONIC:
heun_corr_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea,
d_pdMOI, d_pdIsoC, d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY,
d_pdTempPhi, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
break;
case HERTZIAN:
heun_corr_2p <HERTZIAN> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd,d_pdArea,
d_pdMOI, d_pdIsoC, d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY,
d_pdTempPhi, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
}
if (bSvStress)
{
m_fP = 0.5 * (*m_pfPxx + *m_pfPyy);
fprintf(m_pOutfSE, "%lu %.7g %.7g %.7g %.7g %.7g %.7g\n",
tTime, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy, *m_pfPyx);
if (bSvPos)
save_positions(tTime);
}
cudaThreadSynchronize();
checkCudaError("Updating estimates, moving particles");
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
reconfigure_cells();
cudaThreadSynchronize();
if (*h_bNewNbrs)
find_neighbors();
}
void Spherocyl_Box::y_resize_step_2p(long unsigned int tTime, double dEpsilon, bool bSvStress, bool bSvPos)
{
if (dEpsilon > 0) {
dEpsilon = 1./(1.-dEpsilon) - 1.;
}
resize_y_coords_2p <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, dEpsilon, d_pdY);
m_dLy += dEpsilon*m_dLy;
m_dPacking = calculate_packing();
cudaThreadSynchronize();
checkCudaError("Resizing box");
if (bSvStress)
{
cudaMemset((void *) d_pfSE, 0, 5*sizeof(float));
switch (m_ePotential)
{
case HARMONIC:
euler_est_2p <HARMONIC, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est_2p <HERTZIAN, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions, calculating stresses");
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
if (bSvPos)
{
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
}
cudaThreadSynchronize();
}
else
{
switch (m_ePotential)
{
case HARMONIC:
euler_est_2p <HARMONIC, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est_2p <HERTZIAN, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions");
}
switch (m_ePotential)
{
case HARMONIC:
heun_corr_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea,
d_pdMOI, d_pdIsoC, d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY,
d_pdTempPhi, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
break;
case HERTZIAN:
heun_corr_2p <HERTZIAN> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea,
d_pdMOI, d_pdIsoC, d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY,
d_pdTempPhi, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
}
if (bSvStress)
{
m_fP = 0.5 * (*m_pfPxx + *m_pfPyy);
fprintf(m_pOutfSE, "%lu %.7g %.7g %.7g %.7g %.7g %.7g\n",
tTime, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy, *m_pfPyx);
if (bSvPos)
save_positions(tTime);
}
cudaThreadSynchronize();
checkCudaError("Updating estimates, moving particles");
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
reconfigure_cells();
cudaThreadSynchronize();
if (*h_bNewNbrs)
find_neighbors();
}
void Spherocyl_Box::resize_box_2p(long unsigned int nStart, double dEpsilon, double dFinalPacking, double dSvStressRate, double dSvPosRate)
{
assert(dEpsilon != 0);
m_dPacking = calculate_packing();
if (dFinalPacking > m_dPacking && dEpsilon > 0)
dEpsilon = -dEpsilon;
else if (dFinalPacking < m_dPacking && dEpsilon < 0)
dEpsilon = -dEpsilon;
dSvStressRate = int(dEpsilon/fabs(dEpsilon))*fabs(dSvStressRate);
dSvPosRate = int(dEpsilon/fabs(dEpsilon))*fabs(dSvPosRate);
printf("Beginning resize with packing fraction: %f\n", m_dPacking);
unsigned long int nTime = nStart;
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
if (nTime == 0) {
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
}
else {
m_pOutfSE = fopen(szPathSE, "r+");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
long unsigned int nTpos = 0;
while (nTpos != nTime) {
if (fgets(szBuf, 200, m_pOutfSE) != NULL) {
int nPos = strcspn(szBuf, " ");
char szTime[20];
strncpy(szTime, szBuf, nPos);
szTime[nPos] = '\0';
nTpos = atol(szTime);
}
else {
fprintf(stderr, "Reached end of file without finding start position");
exit(1);
}
}
}
sprintf(szBuf, "%s/rs_stress_energy.dat", m_szDataDir);
const char *szRsSE = szBuf;
FILE *pOutfRs;
if (nTime == 0) {
pOutfRs = fopen(szRsSE, "w");
if (pOutfRs == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
}
else {
pOutfRs = fopen(szRsSE, "r+");
if (pOutfRs == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
for (unsigned long int t = 0; t < nTime; t++) {
fgets(szBuf, 200, pOutfRs);
}
fgets(szBuf, 200, pOutfRs);
int nPos = strcspn(szBuf, " ");
char szPack[20];
strncpy(szPack, szBuf, nPos);
szPack[nPos] = '\0';
double dPack = atof(szPack);
/*
if (dPack - (1 + dEpsilon) * m_dPacking || dPack < (1 - dShrinkRate) * m_dPacking) {
fprintf(stderr, "System packing fraction %g does not match with time %lu", dPack, nTime);
exit(1);
}
*/
}
int nSaveStressInt = int(log(1+dSvStressRate)/log(1+dEpsilon));
int nSavePosInt = int(dSvPosRate/dSvStressRate+0.5)*nSaveStressInt;
printf("Starting resize with rate: %g\nStress save rate: %g (%d)\nPosition save rate: %g (%d)\n",
dEpsilon, dSvStressRate, nSaveStressInt, dSvPosRate, nSavePosInt);
while (dEpsilon*(m_dPacking - dFinalPacking) > dEpsilon*dEpsilon) {
bool bSavePos = (nTime % nSavePosInt == 0);
bool bSaveStress = (nTime % nSaveStressInt == 0);
//printf("Step %l\n", nTime);
//fflush(stdout);
resize_step_2p(nTime, dEpsilon, bSaveStress, bSavePos);
if (bSaveStress) {
fprintf(pOutfRs, "%.6g %.7g %.7g %.7g %.7g %.7g %.7g\n",
m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy, *m_pfPyx);
}
if (bSavePos) {
fflush(stdout);
fflush(pOutfRs);
fflush(m_pOutfSE);
}
nTime += 1;
//if (nTime % nReorderInterval == 0)
//reorder_particles();
}
resize_step_2p(nTime, dEpsilon, 1, 1);
fprintf(pOutfRs, "%.6g %.7g %.7g %.7g %.7g %.7g %.7g\n", m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy, *m_pfPyx);
fclose(m_pOutfSE);
fclose(pOutfRs);
}
/////////////////////////////////////////
//
// Relax to minimum
//
///////////////////////////////////////
void Spherocyl_Box::relax_step_2p(long unsigned int tTime, bool bSvStress, bool bSvPos)
{
if (bSvStress)
{
cudaMemset((void *) d_pfSE, 0, 5*sizeof(float));
switch (m_ePotential)
{
case HARMONIC:
euler_est_2p <HARMONIC, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est_2p <HERTZIAN, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions, calculating stresses");
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
if (bSvPos)
{
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
}
cudaThreadSynchronize();
}
else
{
switch (m_ePotential)
{
case HARMONIC:
euler_est_2p <HARMONIC, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
euler_est_2p <HERTZIAN, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0, m_dStep,
d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions");
}
switch (m_ePotential)
{
case HARMONIC:
heun_corr_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea,
d_pdMOI, d_pdIsoC, d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY,
d_pdTempPhi, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
break;
case HERTZIAN:
heun_corr_2p <HERTZIAN> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, 0,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea,
d_pdMOI, d_pdIsoC, d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY,
d_pdTempPhi, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
}
if (bSvStress)
{
m_fP = 0.5 * (*m_pfPxx + *m_pfPyy);
fprintf(m_pOutfSE, "%lu %.7g %.7g %.7g %.7g %.7g %.7g\n",
tTime, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy, *m_pfPyx);
if (bSvPos)
save_positions(tTime);
}
cudaThreadSynchronize();
checkCudaError("Updating estimates, moving particles");
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
reconfigure_cells();
cudaThreadSynchronize();
if (*h_bNewNbrs)
find_neighbors();
}
void Spherocyl_Box::relax_box_2p(long unsigned int nSteps, double dMaxStep, double dMinStep, int nSaveStressInt, int nSavePosInt)
{
unsigned long int nTime = 0;
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
if (nTime == 0) {
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
}
else {
m_pOutfSE = fopen(szPathSE, "r+");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
long unsigned int nTpos = 0;
while (nTpos != nTime) {
if (fgets(szBuf, 200, m_pOutfSE) != NULL) {
int nPos = strcspn(szBuf, " ");
char szTime[20];
strncpy(szTime, szBuf, nPos);
szTime[nPos] = '\0';
nTpos = atol(szTime);
}
else {
fprintf(stderr, "Reached end of file without finding start position");
exit(1);
}
}
}
m_dStep = dMaxStep;
printf("Starting relax with step size: %g\nStress save rate: %d\nPosition save rate: %d\n", m_dStep, nSaveStressInt, nSavePosInt);
while (nTime < nSteps) {
bool bSavePos = (nTime % nSavePosInt == 0);
bool bSaveStress = (nTime % nSaveStressInt == 0);
//printf("Step %l\n", nTime);
//fflush(stdout);
relax_step_2p(nTime, bSaveStress, bSavePos);
if (bSavePos) {
fflush(stdout);
fflush(m_pOutfSE);
}
nTime += 1;
//if (nTime % nReorderInterval == 0)
//reorder_particles();
}
relax_step_2p(nTime, 1, 1);
fclose(m_pOutfSE);
}
//////////////////////////////////////////////////////////
//
// Pure shear (compression y - expansion x)
//
///////////////////////////////////////////////////
template<Potential ePot, int bCalcStress>
__global__ void pure_euler_est_2p(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy, double dGamma,
double dStrain, double dStep, double *pdX, double *pdY, double *pdPhi, double *pdR,
double *pdA, double dKd, double *pdArea, double *pdMOI, double *pdIsoC, double *pdFx,
double *pdFy, double *pdFt, float *pfSE, double *pdTempX, double *pdTempY, double *pdTempPhi)
{
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
extern __shared__ double sData[];
int offset = blockDim.x + 8; // +8 should help to avoid a few bank conflict
if (bCalcStress) {
for (int i = 0; i < 5; i++)
sData[i*offset + thid] = 0.0;
__syncthreads(); // synchronizes every thread in the block before going on
}
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dFt = 0.0;
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dAdjX = pdX[nAdjPID];
double dAdjY = pdY[nAdjPID];
double dDeltaX = dX - dAdjX;
double dDeltaY = dY - dAdjY;
double dPhiB = pdPhi[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double s1, t1, s2, t2, s3, t3;
if (delta <= 0) { //delta should never be negative but I'm using <= in case it comes out negative due to precision
s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
if (fabs(s1) == 1)
t1 = fmin(fmax( -(b*s1+e)/c, -1.0), 1.0);
else if (b < 0)
t1 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
else
t1 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
if (fabs(s2) == 1)
t2 = fmin(fmax( -(b*s2+e)/c, -1.0), 1.0);
else if (b < 0)
t2 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
else
t2 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
s3 = s2;
t3 = t2;
}
else {
t1 = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s1 = -(b*t1+d)/a;
double sarg = fabs(s1);
s1 = fmin( fmax(s1,-1.), 1. );
if (sarg >= 1) {
t1 = fmin( fmax( -(b*s1+e)/c, -1.), 1.);
s2 = -s1;
t2 = -(b*s2+e)/c;
double targ = fabs(t2);
t2 = fmin( fmax(t2, -1.), 1.);
if (targ > 1) {
s2 = fmin( fmax( -(b*t2+d)/a, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
t3 = -s1;
else
t3 = s1;
s3 = -(b*t3+d)/a;
sarg = fabs(s3);
s3 = fmin(fmax(s3, -1.0), 1.0);
if (sarg >= 1)
t3 = fmin(fmax(-(b*s3+e)/c, -1.0), 1.0);
}
}
else {
t2 = -t1;
s2 = -(b*t2+d)/a;
sarg = fabs(s2);
s2 = fmin( fmax(s2, -1.), 1.);
if (sarg > 1) {
t2 = fmin( fmax( -(b*s2+e)/c, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
s3 = -t1;
else
s3 = t1;
t3 = -(b*s3+e)/c;
double targ = fabs(t3);
t3 = fmin(fmax(t3, -1.0), 1.0);
if (targ >= 1)
s3 = min(max(-(b*t3+d)/a, -1.0), 1.0);
}
}
}
// Check if they overlap and calculate forces
double dDx1 = dDeltaX + s1*nxA - t1*nxB;
double dDy1 = dDeltaY + s1*nyA - t1*nyB;
double dDSqr1 = dDx1 * dDx1 + dDy1 * dDy1;
if (dDSqr1 < dSigma*dSigma) {
double dDij = sqrt(dDSqr1);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx1 * dDVij / dDij;
double dPfy = dDy1 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
// Find the point of contact (with respect to the center of the spherocyl)
//double dCx = s*nxA - 0.5*dDx;
//double dCy = s*nyA - 0.5*dDy;
//double dCx = s*nxA;
//double dCy = s*nyA;
dFt += s1*nxA * dPfy - s1*nyA * dPfx;
if (bCalcStress)
{
double dCx = 0.5*dDx1 - s1*nxA;
double dCy = 0.5*dDy1 - s1*nyA;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
if (s1 != s2 && t1 != t2) {
double dDx2 = dDeltaX + s2*nxA - t2*nxB;
double dDy2 = dDeltaY + s2*nyA - t2*nyB;
double dDSqr2 = dDx2 * dDx2 + dDy2 * dDy2;
if (s3 != s1 && s3 != s2) {
double dDx3 = dDeltaX + s3*nxA - t3*nxB;
double dDy3 = dDeltaY + s3*nyA - t3*nyB;
double dDSqr3 = dDx3 * dDx3 + dDy3 * dDy3;
if (dDSqr3 < dDSqr2) {
s2 = s3;
t2 = t3;
dDx2 = dDx3;
dDy2 = dDy3;
dDSqr2 = dDSqr3;
}
}
if (dDSqr2 < dSigma*dSigma) {
double dDij = sqrt(dDSqr2);
double dDVij, dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 -dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx2 * dDVij / dDij;
double dPfy = dDy2 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
dFt += s2*nxA * dPfy - s2*nyA * dPfx;
if (bCalcStress) {
double dCx = 0.5*dDx2 - s2*nxA;
double dCy = 0.5*dDy2 - s2*nyA;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
}
pdFx[nPID] = dFx;
pdFy[nPID] = dFy;
pdFt[nPID] = dFt;
double dArea = pdArea[nPID];
dFx /= (dKd*dArea);
dFy /= (dKd*dArea);
dFt /= (dKd*dArea*pdMOI[nPID]);
pdTempX[nPID] = dX + dStep * (dFx + 0.5 * dStrain * dX);
pdTempY[nPID] = dY + dStep * (dFy - 0.5 * dStrain * dY);
double dRIso = -0.5 * pdIsoC[nPID] * sin(2*dPhi);
pdTempPhi[nPID] = dPhi + dStep * (dFt + dStrain * dRIso);
nPID += nThreads;
}
if (bCalcStress) {
__syncthreads();
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size, all threads perform two adds
int base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
base += 2*offset;
sData[base] += sData[base + stride];
if (thid < stride) {
base += 2*offset;
sData[base] += sData[base + stride];
}
stride /= 2; // stride is 1/4 block size, all threads perform 1 add
__syncthreads();
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
if (thid < stride) {
base += 4*offset;
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
while (stride > 4)
{
if (thid < 5 * stride)
{
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 20)
{
base = thid % 4 + offset * (thid / 4);
sData[base] += sData[base + 4];
if (thid < 10)
{
base = thid % 2 + offset * (thid / 2);
sData[base] += sData[base + 2];
if (thid < 5)
{
sData[thid * offset] += sData[thid * offset + 1];
float tot = atomicAdd(pfSE+thid, (float)sData[thid*offset]);
}
}
}
}
}
///////////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////////
template<Potential ePot>
__global__ void pure_heun_corr_2p(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy, double dGamma,
double dStrain, double dStep, double *pdX, double *pdY, double *pdPhi, double *pdR,
double *pdA, double dKd, double *pdArea, double *pdMOI, double *pdIsoC, double *pdFx,
double *pdFy, double *pdFt, double *pdTempX, double *pdTempY, double *pdTempPhi,
double *pdXMoved, double *pdYMoved, double dEpsilon, int *bNewNbrs)
{
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dFt = 0.0;
double dX = pdTempX[nPID];
double dY = pdTempY[nPID];
double dPhi = pdTempPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dAdjX = pdTempX[nAdjPID];
double dAdjY = pdTempY[nAdjPID];
double dDeltaX = dX - dAdjX;
double dDeltaY = dY - dAdjY;
double dPhiB = pdTempPhi[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double s1, t1, s2, t2, s3, t3;
if (delta <= 0) { //delta should never be negative but I'm using <= in case it comes out negative due to precision;
s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
if (fabs(s1) == 1)
t1 = fmin(fmax( -(b*s1+e)/c, -1.0), 1.0);
else if (b < 0)
t1 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
else
t1 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
if (fabs(s2) == 1)
t2 = fmin(fmax( -(b*s2+e)/c, -1.0), 1.0);
else if (b < 0)
t2 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
else
t2 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
s3 = s2;
t3 = t2;
}
else {
t1 = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s1 = -(b*t1+d)/a;
double sarg = fabs(s1);
s1 = fmin( fmax(s1,-1.), 1. );
if (sarg >= 1) {
t1 = fmin( fmax( -(b*s1+e)/c, -1.), 1.);
s2 = -s1;
t2 = -(b*s2+e)/c;
double targ = fabs(t2);
t2 = fmin( fmax(t2, -1.), 1.);
if (targ > 1) {
s2 = fmin( fmax( -(b*t2+d)/a, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
t3 = -s1;
else
t3 = s1;
s3 = -(b*t3+d)/a;
sarg = fabs(s3);
s3 = fmin(fmax(s3, -1.0), 1.0);
if (sarg >= 1)
t3 = fmin(fmax(-(b*s3+e)/c, -1.0), 1.0);
}
}
else {
t2 = -t1;
s2 = -(b*t2+d)/a;
sarg = fabs(s2);
s2 = fmin( fmax(s2, -1.), 1.);
if (sarg > 1) {
t2 = fmin( fmax( -(b*s2+e)/c, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
s3 = -t1;
else
s3 = t1;
t3 = -(b*s3+e)/c;
double targ = fabs(t3);
t3 = fmin(fmax(t3, -1.0), 1.0);
if (targ >= 1)
s3 = min(max(-(b*t3+d)/a, -1.0), 1.0);
}
}
}
// Check if they overlap and calculate forces
double dDx1 = dDeltaX + s1*nxA - t1*nxB;
double dDy1 = dDeltaY + s1*nyA - t1*nyB;
double dDSqr1 = dDx1 * dDx1 + dDy1 * dDy1;
if (dDSqr1 < dSigma*dSigma) {
double dDij = sqrt(dDSqr1);
double dDVij;
//double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
//dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
//dAlpha = 2.5;
}
double dPfx = dDx1 * dDVij / dDij;
double dPfy = dDy1 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
//double dCx = s*nxA - 0.5*dDx;
//double dCy = s*nyA - 0.5*dDy;
double dCx = s1*nxA;
double dCy = s1*nyA;
dFt += dCx * dPfy - dCy * dPfx;
}
if (s1 != s2 && t1 != t2) {
double dDx2 = dDeltaX + s2*nxA - t2*nxB;
double dDy2 = dDeltaY + s2*nyA - t2*nyB;
double dDSqr2 = dDx2 * dDx2 + dDy2 * dDy2;
if (s3 != s1 && s3 != s2) {
double dDx3 = dDeltaX + s3*nxA - t3*nxB;
double dDy3 = dDeltaY + s3*nyA - t3*nyB;
double dDSqr3 = dDx3 * dDx3 + dDy3 * dDy3;
if (dDSqr3 < dDSqr2) {
s2 = s3;
t2 = t3;
dDx2 = dDx3;
dDy2 = dDy3;
dDSqr2 = dDSqr3;
}
}
if (dDSqr2 < dSigma*dSigma) {
double dDij = sqrt(dDSqr2);
double dDVij;
if (ePot == HARMONIC)
{
dDVij = (1.0 -dDij / dSigma) / dSigma;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
}
double dPfx = dDx2 * dDVij / dDij;
double dPfy = dDy2 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
dFt += s2*nxA * dPfy - s2*nyA * dPfx;
}
}
}
double dMOI = pdMOI[nPID];
double dArea = pdArea[nPID];
dFx /= (dKd*dArea);
dFy /= (dKd*dArea);
dFt = dFt / (dKd*dArea*dMOI); // - dStrain * 0.5 * dIsoC*sin(2*dPhi);
double dFy0 = pdFy[nPID] / (dKd*dArea);
double dFx0 = pdFx[nPID] / (dKd*dArea);
//double dPhi0 = pdPhi[nPID];
double dFt0 = pdFt[nPID] / (dKd*dArea*dMOI); // - dStrain * 0.5 * dIsoC*sin(2*dPhi0);
double dDx = 0.5 * dStep * (dFx - dFx0);
//double dDsx = 0.5 * dStep * dStrain * (dX + pdX[nPID]);
double dDy = 0.5 * dStep * (dFy - dFy0);
//double dDsy = -0.5 * dStep * dStrain * (dY + pdY[nPID]);
double dDt = 0.5 * dStep * (dFt - dFt0);
pdXMoved[nPID] += dX + dDx - pdX[nPID];
pdYMoved[nPID] += dY + dDy - pdY[nPID];
if (fabs(pdXMoved[nPID]) + fabs(pdYMoved[nPID]) > 0.5*dEpsilon)
*bNewNbrs = 1;
/*
if (thid == 0) {
printf("ID: %d, x0: %g, y0: %g, t0: %g, xt: %g, yt: %g, tt: %g\n", nPID, pdX[nPID], pdY[nPID], pdPhi[nPID], dX, dY, dPhi);
printf("ID: %d, fx0: %g, fy0: %g, ft0: %g, fxt: %g, fyt: %g, ftt: %g\n", nPID, dFx0, dFy0, dFt0, dFx, dFy, dFt);
printf("ID: %d, Dx: %g, Dy: %g, Dt: %g\n", nPID, dDx, dDy, dDt);
}
*/
pdX[nPID] = dX + dDx;
pdY[nPID] = dY + dDy;
pdPhi[nPID] = dPhi + dDt;
nPID += nThreads;
}
}
void Spherocyl_Box::pure_strain_step_2p(long unsigned int tTime, bool bSvStress, bool bSvPos)
{
if (bSvStress)
{
cudaMemset((void *) d_pfSE, 0, 5*sizeof(float));
switch (m_ePotential)
{
case HARMONIC:
pure_euler_est_2p <HARMONIC, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
pure_euler_est_2p <HERTZIAN, 1> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions, calculating stresses");
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
if (bSvPos)
{
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
}
cudaThreadSynchronize();
}
else
{
switch (m_ePotential)
{
case HARMONIC:
pure_euler_est_2p <HARMONIC, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
break;
case HERTZIAN:
pure_euler_est_2p <HERTZIAN, 0> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, m_dStrainRate,
m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pfSE, d_pdTempX, d_pdTempY, d_pdTempPhi);
}
cudaThreadSynchronize();
checkCudaError("Estimating new particle positions");
}
switch (m_ePotential)
{
case HARMONIC:
pure_heun_corr_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx*(1+0.5*m_dStep*m_dStrainRate), m_dLy*(1-0.5*m_dStep*m_dStrainRate),
m_dGamma, m_dStrainRate, m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
break;
case HERTZIAN:
pure_heun_corr_2p <HERTZIAN> <<<m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx*(1+0.5*m_dStep*m_dStrainRate), m_dLy*(1-0.5*m_dStep*m_dStrainRate),
m_dGamma, m_dStrainRate, m_dStep, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, m_dKd, d_pdArea, d_pdMOI, d_pdIsoC,
d_pdFx, d_pdFy, d_pdFt, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdXMoved, d_pdYMoved, m_dEpsilon, d_bNewNbrs);
}
if (bSvStress)
{
m_fP = 0.5 * (*m_pfPxx + *m_pfPyy);
fprintf(m_pOutfSE, "%lu %.7g %.7g %.7g %.7g %.7g %.7g\n",
tTime, *m_pfEnergy, *m_pfPxx, *m_pfPyy, m_fP, *m_pfPxy, *m_pfPyx);
if (bSvPos)
save_positions(tTime);
}
m_dLx += 0.5*m_dStep*m_dStrainRate*m_dLx;
m_dLy -= 0.5*m_dStep*m_dStrainRate*m_dLy;
cudaThreadSynchronize();
checkCudaError("Updating estimates, moving particles");
/*
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaThreadSynchronize();
for (int p=0; p < m_nSpherocyls; p++) {
printf("%d: %g %g %g\n", p, h_pdX[p], h_pdY[p], h_pdPhi[p]);
}
*/
cudaMemcpy(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
if (tTime % 100000 == 0) {
*h_bNewNbrs = 1;
}
cudaThreadSynchronize();
reconfigure_cells(0.0);
m_dTotalGamma += m_dStep*m_dStrainRate;
//cudaThreadSynchronize();
if (*h_bNewNbrs)
find_neighbors();
}
void Spherocyl_Box::run_pure_strain_2p(unsigned long int nStart, double dStopAspect, double dSvStressGamma, double dSvPosGamma)
{
if (m_dStrainRate == 0.0)
{
fprintf(stderr, "Cannot strain with zero strain rate\n");
exit(1);
}
else if (m_dStrainRate < 0.0)
{
m_dStrainRate = -m_dStrainRate;
}
double dAspect = m_dLx / m_dLy;
if (dAspect > dStopAspect) {
fprintf(stderr, "Cannot strain since starting aspect ratio is beyond ending aspect ratio\n");
exit(1);
}
printf("Beginnig strain run with strain rate: %g and step %g\n", m_dStrainRate, m_dStep);
fflush(stdout);
if (dSvStressGamma < m_dStrainRate * m_dStep)
dSvStressGamma = m_dStrainRate * m_dStep;
if (dSvPosGamma < m_dStrainRate)
dSvPosGamma = m_dStrainRate;
// +0.5 to cast to nearest integer rather than rounding down
unsigned long int nTime = nStart;
//unsigned long int nStop = (unsigned long)(dStopGamma / m_dStrainRate + 0.5);
unsigned int nIntStep = (unsigned int)(1.0 / m_dStep + 0.5);
unsigned int nSvStressInterval = (unsigned int)(dSvStressGamma / (m_dStrainRate * m_dStep) + 0.5);
unsigned int nSvPosInterval = (unsigned int)(dSvPosGamma / m_dStrainRate + 0.5);
unsigned long int nTotalStep = nTime * nIntStep;
//unsigned int nReorderInterval = (unsigned int)(1.0 / m_dStrainRate + 0.5);
printf("Strain run configured\n");
printf("Time: %lu, Start: %g, Stop: %g, Int step: %lu\n", nTime, dAspect, dStopAspect, nIntStep);
printf("Stress save int: %lu, Pos save int: %lu\n", nSvStressInterval, nSvPosInterval);
fflush(stdout);
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
if (nTime == 0)
{
m_dTotalGamma = 0;
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL)
{
fprintf(stderr, "Could not open file for writing");
exit(1);
}
}
else
{
m_pOutfSE = fopen(szPathSE, "r+");
if (m_pOutfSE == NULL)
{
fprintf(stderr, "Could not open file for writing");
exit(1);
}
unsigned long int nTpos = 0;
while (nTpos != nTime)
{
if (fgets(szBuf, 200, m_pOutfSE) != NULL)
{
int nPos = strcspn(szBuf, " ");
char szTime[20];
strncpy(szTime, szBuf, nPos);
szTime[nPos] = '\0';
nTpos = atol(szTime);
}
else
{
fprintf(stderr, "Reached end of file without finding start position");
exit(1);
}
}
}
// Run strain for specified number of steps
while (m_dLx / m_dLy < dStopAspect)
{
bool bSvPos = (nTime % nSvPosInterval == 0);
if (bSvPos) {
pure_strain_step_2p(nTime, 1, 1);
fflush(m_pOutfSE);
}
else
{
bool bSvStress = (nTotalStep % nSvStressInterval == 0);
pure_strain_step_2p(nTime, bSvStress, 0);
}
nTotalStep += 1;
for (unsigned int nI = 1; nI < nIntStep; nI++)
{
bool bSvStress = (nTotalStep % nSvStressInterval == 0);
pure_strain_step_2p(nTime, bSvStress, 0);
nTotalStep += 1;
}
nTime += 1;
//printf("Time: %lu, Gamma: %g, Aspect: %g\n", nTime, m_dTotalGamma, m_dLx/m_dLy);
//if (nTime % nReorderInterval == 0)
//reorder_particles();
}
// Save final configuration
strain_step_2p(nTime, 1, 1);
fflush(m_pOutfSE);
fclose(m_pOutfSE);
}
///////////////////////////////////////////////
////////////////////////////////////////////////
// //
// Quasistatic transformations //
// //
////////////////////////////////////////
template<Potential ePot>
__global__ void calc_se_2p(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy,
double dGamma, double *pdX, double *pdY, double *pdPhi, double *pdR, double *pdA,
double *pdFx, double *pdFy, double *pdFt, double *pdEnergies, float *pfSE)
{
// Declare shared memory pointer, the size is determined at the kernel launch
extern __shared__ double sData[];
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
int offset = blockDim.x + 8; // +8 helps to avoid bank conflicts
for (int i = 0; i < 5; i++)
sData[i*offset + thid] = 0.0;
__syncthreads(); // synchronizes every thread in the block before going on
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dFt = 0.0;
double dEnergy = 0.0;
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dDeltaX = dX - pdX[nAdjPID];
double dDeltaY = dY - pdY[nAdjPID];
double dPhiB = pdPhi[nAdjPID];
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double s1, t1, s2, t2, s3, t3;
if (delta <= 0) { //delta should never be negative but I'm using <= in case it comes out negative due to precision
s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
if (b < 0) {
t1 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
t2 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
}
else {
t1 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
t2 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
}
s3 = s2;
t3 = t2;
}
else {
t1 = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s1 = -(b*t1+d)/a;
double sarg = fabs(s1);
s1 = fmin( fmax(s1,-1.), 1. );
if (sarg >= 1) {
t1 = fmin( fmax( -(b*s1+e)/c, -1.), 1.);
s2 = -s1;
t2 = -(b*s2+e)/c;
double targ = fabs(t2);
t2 = fmin( fmax(t2, -1.), 1.);
if (targ > 1) {
s2 = fmin( fmax( -(b*t2+d)/a, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
t3 = -s1;
else
t3 = s1;
s3 = -(b*t3+d)/a;
sarg = fabs(s3);
s3 = fmin(fmax(s3, -1.0), 1.0);
if (sarg >= 1)
t3 = fmin(fmax(-(b*s3+e)/c, -1.0), 1.0);
}
}
else {
t2 = -t1;
s2 = -(b*t2+d)/a;
sarg = fabs(s2);
s2 = fmin( fmax(s2, -1.), 1.);
if (sarg > 1) {
t2 = fmin( fmax( -(b*s2+e)/c, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
s3 = -t1;
else
s3 = t1;
t3 = -(b*s3+e)/c;
double targ = fabs(t3);
t3 = fmin(fmax(t3, -1.0), 1.0);
if (targ >= 1)
s3 = min(max(-(b*t3+d)/a, -1.0), 1.0);
}
}
}
// Check if they overlap and calculate forces
double dDx1 = dDeltaX + s1*nxA - t1*nxB;
double dDy1 = dDeltaY + s1*nyA - t1*nyB;
double dDSqr1 = dDx1 * dDx1 + dDy1 * dDy1;
if (dDSqr1 < dSigma*dSigma)
{
double dDij = sqrt(dDSqr1);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx1 * dDVij / dDij;
double dPfy = dDy1 * dDVij / dDij;
double dCx = 0.5 * dDx1 - s1*nxA;
double dCy = 0.5 * dDy1 - s1*nyA;
dFx += dPfx;
dFy += dPfy;
dFt += s1*nxA * dPfy - s1*nyA * dPfx;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
dEnergy += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
if (s1 != s2 && t1 != t2) {
double dDx2 = dDeltaX + s2*nxA - t2*nxB;
double dDy2 = dDeltaY + s2*nyA - t2*nyB;
double dDSqr2 = dDx2 * dDx2 + dDy2 * dDy2;
if (s3 != s1 && s3 != s2) {
double dDx3 = dDeltaX + s3*nxA - t3*nxB;
double dDy3 = dDeltaY + s3*nyA - t3*nyB;
double dDSqr3 = dDx3 * dDx3 + dDy3 * dDy3;
if (dDSqr3 < dDSqr2) {
s2 = s3;
t2 = t3;
dDx2 = dDx3;
dDy2 = dDy3;
dDSqr2 = dDSqr3;
}
}
if (dDSqr2 < dSigma*dSigma) {
double dDij = sqrt(dDSqr2);
double dAlpha, dDVij;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
//printf("Found second contact: %d %d %f %f %f %f %g %g %.8g %.8g %g %g\n", nPID, nAdjPID, s2, t2, s1, t1, dPhi, dPhiB, dDij1, dDij, dDVij1, dDVij);
double dPfx = dDx2 * dDVij / dDij;
double dPfy = dDy2 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
dFt += s2*nxA * dPfy - s2*nyA * dPfx;
double dCx = 0.5*dDx2 - s2*nxA;
double dCy = 0.5*dDy2 - s2*nyA;
sData[thid] += dCx * dPfx / (dLx * dLy);
sData[thid + offset] += dCy * dPfy / (dLx * dLy);
sData[thid + 2*offset] += dCx * dPfy / (dLx * dLy);
sData[thid + 3*offset] += dCy * dPfx / (dLx * dLy);
sData[thid + 4*offset] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
dEnergy += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
pdFx[nPID] = dFx;
pdFy[nPID] = dFy;
pdFt[nPID] = dFt;
pdEnergies[nPID] = dEnergy;
nPID += nThreads;
}
__syncthreads();
/*
double dEnergyCheck = 0;
if (thid == 0) {
//double dEnergyCheck = 0;
for (int i = 0; i < blockDim.x; i++) {
dEnergyCheck += sData[4*offset + i];
}
}
__syncthreads();
*/
// Now we do a parallel reduction sum to find the total number of contacts
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size, all threads perform two adds
int base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
base += 2*offset;
sData[base] += sData[base + stride];
if (thid < stride) {
base += 2*offset;
sData[base] += sData[base + stride];
}
stride /= 2; // stride is 1/4 block size, all threads perform 1 add
__syncthreads();
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
if (thid < stride) {
base += 4*offset;
sData[base] += sData[base+stride];
}
stride /= 2;
__syncthreads();
while (stride > 4)
{
if (thid < 5 * stride)
{
base = thid % stride + offset * (thid / stride);
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 20)
{
base = thid % 4 + offset * (thid / 4);
sData[base] += sData[base + 4];
if (thid < 10)
{
base = thid % 2 + offset * (thid / 2);
sData[base] += sData[base + 2];
if (thid < 5)
{
sData[thid * offset] += sData[thid * offset + 1];
float tot = atomicAdd(pfSE+thid, (float)sData[thid*offset]);
//if (thid == 0) {
//printf("Energy Check (blid %d): %.8g %.8g\n", blockIdx.x, dEnergyCheck, sData[4*offset]);
//}
}
}
}
}
void Spherocyl_Box::calculate_stress_energy_2p()
{
cudaMemset((void*) d_pfSE, 0, 5*sizeof(float));
//dim3 grid(m_nGridSize);
//dim3 block(m_nBlockSize);
//size_t smem = m_nSM_CalcSE;
//printf("Configuration: %d x %d x %d\n", m_nGridSize, m_nBlockSize, m_nSM_CalcSE);
switch (m_ePotential)
{
case HARMONIC:
calc_se_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdFx, d_pdFy, d_pdFt, d_pdEnergies, d_pfSE);
break;
case HERTZIAN:
calc_se_2p <HERTZIAN> <<<m_nGridSize, m_nBlockSize, m_nSM_CalcSE>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdFx, d_pdFy, d_pdFt, d_pdEnergies, d_pfSE);
}
cudaThreadSynchronize();
checkCudaError("Calculating stresses and energy");
}
template<Potential ePot>
__global__ void calc_fe_2p(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy,
double dGamma, double *pdX, double *pdY, double *pdPhi, double *pdR, double *pdA,
double *pdMOI, double *pdFx, double *pdFy, double *pdFt, double *pdEnergyBlocks)
{
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
extern __shared__ double sData[];
sData[thid] = 0.0;
__syncthreads(); // synchronizes every thread in the block before going on
while (nPID < nSpherocyls)
{
double dFx = 0.0;
double dFy = 0.0;
double dFt = 0.0;
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dAdjX = pdX[nAdjPID];
double dAdjY = pdY[nAdjPID];
double dDeltaX = dX - dAdjX;
double dDeltaY = dY - dAdjY;
double dPhiB = pdPhi[nAdjPID];
//if (dPhi == dPhiB) {
//printf("Spherocyls %d, %d parallel\n", nPID, nAdjPID);
//}
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double s1, t1, s2, t2, s3, t3;
if (delta <= 0) { //delta should never be negative but I'm using <= in case it comes out negative due to precision
s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
if (b < 0) {
t1 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
t2 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
}
else {
t1 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
t2 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
}
s3 = s2;
t3 = t2;
}
else {
t1 = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s1 = -(b*t1+d)/a;
double sarg = fabs(s1);
s1 = fmin( fmax(s1,-1.), 1. );
if (sarg >= 1) {
t1 = fmin( fmax( -(b*s1+e)/c, -1.), 1.);
s2 = -s1;
t2 = -(b*s2+e)/c;
double targ = fabs(t2);
t2 = fmin( fmax(t2, -1.), 1.);
if (targ >= 1) {
s2 = fmin( fmax( -(b*t2+d)/a, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
t3 = -s1;
else
t3 = s1;
s3 = -(b*t3+d)/a;
sarg = fabs(s3);
s3 = fmin(fmax(s3, -1.0), 1.0);
if (sarg >= 1)
t3 = fmin(fmax(-(b*s3+e)/c, -1.0), 1.0);
}
}
else {
t2 = -t1;
s2 = -(b*t2+d)/a;
sarg = fabs(s2);
s2 = fmin( fmax(s2, -1.), 1.);
if (sarg >= 1) {
t2 = fmin( fmax( -(b*s2+e)/c, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
s3 = -t1;
else
s3 = t1;
t3 = -(b*s3+e)/c;
double targ = fabs(t3);
t3 = fmin(fmax(t3, -1.0), 1.0);
if (targ >= 1)
s3 = min(max(-(b*t3+d)/a, -1.0), 1.0);
}
}
}
// Check if they overlap and calculate forces
double dDx1 = dDeltaX + s1*nxA - t1*nxB;
double dDy1 = dDeltaY + s1*nyA - t1*nyB;
double dDSqr1 = dDx1 * dDx1 + dDy1 * dDy1;
if (dDSqr1 < dSigma*dSigma) {
double dDij = sqrt(dDSqr1);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx1 * dDVij / dDij;
double dPfy = dDy1 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
// Find the point of contact (with respect to the center of the spherocyl)
//double dCx = s*nxA - 0.5*dDx;
//double dCy = s*nyA - 0.5*dDy;
//double dCx = s*nxA;
//double dCy = s*nyA;
dFt += s1*nxA * dPfy - s1*nyA * dPfx;
sData[thid] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
if (s1 != s2 && t1 != t2) {
double dDx2 = dDeltaX + s2*nxA - t2*nxB;
double dDy2 = dDeltaY + s2*nyA - t2*nyB;
double dDSqr2 = dDx2 * dDx2 + dDy2 * dDy2;
if (s3 != s1 && s3 != s2) {
double dDx3 = dDeltaX + s3*nxA - t3*nxB;
double dDy3 = dDeltaY + s3*nyA - t3*nyB;
double dDSqr3 = dDx3 * dDx3 + dDy3 * dDy3;
if (dDSqr3 < dDSqr2) {
s2 = s3;
t2 = t3;
dDx2 = dDx3;
dDy2 = dDy3;
dDSqr2 = dDSqr3;
}
}
if (dDSqr2 < dSigma*dSigma) {
double dDij = sqrt(dDSqr2);
double dDVij, dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
double dPfx = dDx2 * dDVij / dDij;
double dPfy = dDy2 * dDVij / dDij;
dFx += dPfx;
dFy += dPfy;
dFt += s2*nxA * dPfy - s2*nyA * dPfx;
sData[thid] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
pdFx[nPID] = dFx;
pdFy[nPID] = dFy;
pdFt[nPID] = dFt;
nPID += nThreads;
}
__syncthreads();
/*
double dEnergyCheck = 0;
if (thid == 0) {
//double dEnergyCheck = 0;
for (int i = 0; i < blockDim.x; i++) {
dEnergyCheck += sData[i];
}
}
__syncthreads();
*/
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size, all threads perform two adds
int base = thid;
while (stride > 32)
{
if (thid < stride)
{
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 32) {
sData[base] += sData[base + 32];
if (thid < 16) {
sData[base] += sData[base + 16];
if (thid < 8) {
sData[base] += sData[base + 8];
if (thid < 4) {
sData[base] += sData[base + 4];
if (thid < 2) {
sData[base] += sData[base + 2];
if (thid == 0) {
sData[0] += sData[1];
pdEnergyBlocks[blockIdx.x] = sData[0];
//printf("Energy Check (blid: %d): %.8g %.8g\n", blockIdx.x, dEnergyCheck, sData[0]);
}
}
}
}
}
}
}
template<Potential ePot>
__global__ void calc_energy_2p(int nSpherocyls, int *pnNPP, int *pnNbrList, double dLx, double dLy, double dGamma,
double *pdX, double *pdY, double *pdPhi, double *pdR, double *pdA, double *pdEnergyBlocks)
{
int thid = threadIdx.x;
int nPID = thid + blockIdx.x * blockDim.x;
int nThreads = blockDim.x * gridDim.x;
// Declare shared memory pointer, the size is passed at the kernel launch
extern __shared__ double sData[];
sData[thid] = 0.0;
__syncthreads(); // synchronizes every thread in the block before going on
while (nPID < nSpherocyls)
{
double dX = pdX[nPID];
double dY = pdY[nPID];
double dPhi = pdPhi[nPID];
double dR = pdR[nPID];
double dA = pdA[nPID];
int nNbrs = pnNPP[nPID];
for (int p = 0; p < nNbrs; p++)
{
int nAdjPID = pnNbrList[nPID + p * nSpherocyls];
double dAdjX = pdX[nAdjPID];
double dAdjY = pdY[nAdjPID];
double dDeltaX = dX - dAdjX;
double dDeltaY = dY - dAdjY;
double dPhiB = pdPhi[nAdjPID];
//if (dPhi == dPhiB) {
//printf("Spherocyls %d, %d parallel\n", nPID, nAdjPID);
//}
double dSigma = dR + pdR[nAdjPID];
double dB = pdA[nAdjPID];
// Make sure we take the closest distance considering boundary conditions
dDeltaX += dLx * ((dDeltaX < -0.5*dLx) - (dDeltaX > 0.5*dLx));
dDeltaY += dLy * ((dDeltaY < -0.5*dLy) - (dDeltaY > 0.5*dLy));
// Transform from shear coordinates to lab coordinates
dDeltaX += dGamma * dDeltaY;
double nxA = dA * cos(dPhi);
double nyA = dA * sin(dPhi);
double nxB = dB * cos(dPhiB);
double nyB = dB * sin(dPhiB);
double a = dA * dA;
double b = -(nxA * nxB + nyA * nyB);
double c = dB * dB;
double d = nxA * dDeltaX + nyA * dDeltaY;
double e = -nxB * dDeltaX - nyB * dDeltaY;
double delta = a * c - b * b;
double s1, t1, s2, t2, s3, t3;
if (delta <= 0) { //delta should never be negative but I'm using <= in case it comes out negative due to precision
s1 = fmin(fmax( -(b+d)/a, -1.0), 1.0);
s2 = fmin(fmax( -(d-b)/a, -1.0), 1.0);
if (b < 0) {
t1 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
t2 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
}
else {
t1 = fmin(fmax( -(e-b)/c, -1.0), 1.0);
t2 = fmin(fmax( -(b+e)/c, -1.0), 1.0);
}
s3 = s2;
t3 = t2;
}
else {
t1 = fmin( fmax( (b*d-a*e)/delta, -1. ), 1. );
s1 = -(b*t1+d)/a;
double sarg = fabs(s1);
s1 = fmin( fmax(s1,-1.), 1. );
if (sarg >= 1) {
t1 = fmin( fmax( -(b*s1+e)/c, -1.), 1.);
s2 = -s1;
t2 = -(b*s2+e)/c;
double targ = fabs(t2);
t2 = fmin( fmax(t2, -1.), 1.);
if (targ >= 1) {
s2 = fmin( fmax( -(b*t2+d)/a, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
t3 = -s1;
else
t3 = s1;
s3 = -(b*t3+d)/a;
sarg = fabs(s3);
s3 = fmin(fmax(s3, -1.0), 1.0);
if (sarg >= 1)
t3 = fmin(fmax(-(b*s3+e)/c, -1.0), 1.0);
}
}
else {
t2 = -t1;
s2 = -(b*t2+d)/a;
sarg = fabs(s2);
s2 = fmin( fmax(s2, -1.), 1.);
if (sarg >= 1) {
t2 = fmin( fmax( -(b*s2+e)/c, -1.), 1.);
s3 = s2;
t3 = t2;
}
else {
if (b < 0)
s3 = -t1;
else
s3 = t1;
t3 = -(b*s3+e)/c;
double targ = fabs(t3);
t3 = fmin(fmax(t3, -1.0), 1.0);
if (targ >= 1)
s3 = min(max(-(b*t3+d)/a, -1.0), 1.0);
}
}
}
// Check if they overlap and calculate forces
double dDx1 = dDeltaX + s1*nxA - t1*nxB;
double dDy1 = dDeltaY + s1*nyA - t1*nyB;
double dDSqr1 = dDx1 * dDx1 + dDy1 * dDy1;
if (dDSqr1 < dSigma*dSigma) {
double dDij = sqrt(dDSqr1);
double dDVij;
double dAlpha;
if (ePot == HARMONIC)
{
dDVij = (1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
sData[thid] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
if (s1 != s2 && t1 != t2) {
double dDx2 = dDeltaX + s2*nxA - t2*nxB;
double dDy2 = dDeltaY + s2*nyA - t2*nyB;
double dDSqr2 = dDx2 * dDx2 + dDy2 * dDy2;
if (s3 != s1 && s3 != s2) {
double dDx3 = dDeltaX + s3*nxA - t3*nxB;
double dDy3 = dDeltaY + s3*nyA - t3*nyB;
double dDSqr3 = dDx3 * dDx3 + dDy3 * dDy3;
if (dDSqr3 < dDSqr2) {
s2 = s3;
t2 = t3;
dDx2 = dDx3;
dDy2 = dDy3;
dDSqr2 = dDSqr3;
}
}
if (dDSqr2 < dSigma*dSigma) {
double dDij = sqrt(dDSqr2);
double dAlpha, dDVij;
if (ePot == HARMONIC)
{
dDVij = (1.0 -dDij / dSigma) / dSigma;
dAlpha = 2.0;
}
else if (ePot == HERTZIAN)
{
dDVij = (1.0 - dDij / dSigma) * sqrt(1.0 - dDij / dSigma) / dSigma;
dAlpha = 2.5;
}
sData[thid] += 0.5 * dDVij * dSigma * (1.0 - dDij / dSigma) / (dAlpha * dLx * dLy);
}
}
}
nPID += nThreads;
}
__syncthreads();
/*
double dEnergyCheck = 0;
if (thid == 0) {
//double dEnergyCheck = 0;
for (int i = 0; i < blockDim.x; i++) {
dEnergyCheck += sData[i];
}
}
__syncthreads();
*/
// Now we do a parallel reduction sum to find the total number of contacts
int stride = blockDim.x / 2; // stride is 1/2 block size, all threads perform two adds
int base = thid;
while (stride > 32)
{
if (thid < stride)
{
sData[base] += sData[base + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 32) {
sData[base] += sData[base + 32];
if (thid < 16) {
sData[base] += sData[base + 16];
if (thid < 8) {
sData[base] += sData[base + 8];
if (thid < 4) {
sData[base] += sData[base + 4];
if (thid < 2) {
sData[base] += sData[base + 2];
if (thid == 0) {
sData[0] += sData[1];
pdEnergyBlocks[blockIdx.x] = sData[0];
//printf("Energy Check (blid: %d): %.8g %.8g\n", blockIdx.x, dEnergyCheck, sData[0]);
}
}
}
}
}
}
}
__global__ void square_forces_2p(int nDim, double *pdFx, double *pdFy, double *pdFt, double *pdMOI, float *pfSquare)
{
int thid = threadIdx.x;
int blid = blockIdx.x;
int nThreads = blockDim.x * gridDim.x / 3;
int arrid = thid + (blid/3) * blockDim.x;
extern __shared__ double sData[];
sData[thid] = 0;
double val;
while (arrid < nDim) {
if (blid % 3 == 0)
val = pdFx[arrid];
else if (blid % 3 == 1)
val = pdFy[arrid];
else
val = pdFt[arrid];
//val = pdFt[arrid] / pdMOI[arrid];
sData[thid] += val*val;
arrid += nThreads;
}
__syncthreads();
int stride = blockDim.x / 2;
while (stride > 32) {
if (thid < stride) {
sData[thid] += sData[thid + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 32) {
sData[thid] += sData[thid + 32];
if (thid < 16) {
sData[thid] += sData[thid + 16];
if (thid < 8) {
sData[thid] += sData[thid + 8];
if (thid < 4) {
sData[thid] += sData[thid + 4];
if (thid < 2) {
sData[thid] += sData[thid + 2];
if (thid == 0) {
sData[0] += sData[1];
float tot = atomicAdd(pfSquare, (float)sData[0]);
}
}
}
}
}
}
}
__global__ void mult_forces_2p(int nDim, double *pdFx0, double *pdFy0, double *pdFt0, double *pdFx,
double *pdFy, double *pdFt, double *pdMOI, float *pfFF0)
{
int thid = threadIdx.x;
int blid = blockIdx.x;
int nThreads = blockDim.x * gridDim.x / 3;
int arrid = thid + (blid/3) * blockDim.x;
extern __shared__ double sData[];
sData[thid] = 0;
while (arrid < nDim) {
if (blid % 3 == 0)
sData[thid] += pdFx0[arrid] * pdFx[arrid];
else if (blid % 3 == 1)
sData[thid] += pdFy0[arrid] * pdFy[arrid];
else
sData[thid] += pdFt0[arrid] * pdFt[arrid];
arrid += nThreads;
}
__syncthreads();
int stride = blockDim.x / 2;
while (stride > 32) {
if (thid < stride) {
sData[thid] += sData[thid + stride];
}
stride /= 2;
__syncthreads();
}
if (thid < 32) {
sData[thid] += sData[thid + 32];
if (thid < 16) {
sData[thid] += sData[thid + 16];
if (thid < 8) {
sData[thid] += sData[thid + 8];
if (thid < 4) {
sData[thid] += sData[thid + 4];
if (thid < 2) {
sData[thid] += sData[thid + 2];
if (thid == 0) {
sData[0] += sData[1];
float tot = atomicAdd(pfFF0, (float)sData[0]);
}
}
}
}
}
}
}
__global__ void sqrt_grad_dir_2p(int nSpherocyls, double *pdFx, double *pdFy, double *pdFt,
double *pdDx, double *pdDy, double *pdDt)
{
int thid = threadIdx.x;
int nThreads = blockDim.x * gridDim.x / 3;
int nPID = thid + (blockIdx.x / 3) * blockDim.x;
if (blockIdx.x % 3 == 0) {
while (nPID < nSpherocyls) {
double dFx = pdFx[nPID];
double dFy = pdFy[nPID];
double dFmag = sqrt(dFx*dFx + dFy*dFy);
if (dFmag == 0) {
pdDx[nPID] = 0;
}
else {
pdDx[nPID] = dFx / sqrt(dFmag);
}
//printf("%d %g %g %g\n", nPID, dFx, dFmag, pdDx[nPID]);
nPID += nThreads;
}
}
else if (blockIdx.x % 3 == 1) {
while (nPID < nSpherocyls) {
double dFx = pdFx[nPID];
double dFy = pdFy[nPID];
double dFmag = sqrt(dFx*dFx + dFy*dFy);
if (dFmag == 0) {
pdDy[nPID] = 0;
}
else {
pdDy[nPID] = dFy / sqrt(dFmag);
}
//printf("%d %g %g %g\n", nPID, dFy, dFmag, pdDy[nPID]);
nPID += nThreads;
}
}
else {
while (nPID < nSpherocyls) {
double dFt = pdFt[nPID];
double dFmag = fabs(dFt);
if (dFmag == 0) {
pdDt[nPID] = 0;
}
else {
pdDt[nPID] = dFt / sqrt(dFmag);
}
//printf("%d %g %g %g\n", nPID, dFt, dFmag, pdDt[nPID]);
nPID += nThreads;
}
}
}
__global__ void new_pr_conj_dir_2p(int nSpherocyls, double *pdFx, double *pdFy, double *pdFt,
double *pdMOI, double *pdDx, double *pdDy, double *pdDt,
float *pfF0Sq, float *pfFSq, float *pfFF0)
{
int thid = threadIdx.x;
int nThreads = blockDim.x * gridDim.x / 3;
int nPID = thid + (blockIdx.x / 3) * blockDim.x;
float fBeta = fmax(0., (*pfFSq - *pfFF0) / (*pfF0Sq));
if (blockIdx.x % 3 == 0) {
while (nPID < nSpherocyls) {
double dNewDx = pdFx[nPID] + fBeta * pdDx[nPID];
pdDx[nPID] = dNewDx;
nPID += nThreads;
}
}
else if (blockIdx.x % 3 == 1) {
//else {
while (nPID < nSpherocyls) {
double dNewDy = pdFy[nPID] + fBeta * pdDy[nPID];
pdDy[nPID] = dNewDy;
nPID += nThreads;
}
}
else {
while (nPID < nSpherocyls) {
double dNewDt = pdFt[nPID] + fBeta * pdDt[nPID];
pdDt[nPID] = dNewDt;
nPID += nThreads;
}
}
}
__global__ void temp_move_step_2p(int nSpherocyls, double *pdX, double *pdY, double *pdPhi,
double *pdTempX, double *pdTempY, double *pdTempPhi,
double *pdDx, double *pdDy, double *pdDt, double dStep)
{
int thid = threadIdx.x;
int blid = blockIdx.x;
int nPID = thid + (blid / 3) * blockDim.x;
int nThreads = blockDim.x * gridDim.x / 3;
if (blid % 3 == 0) {
while (nPID < nSpherocyls) {
pdTempX[nPID] = pdX[nPID] + dStep * pdDx[nPID];
nPID += nThreads;
}
}
else if (blid % 3 == 1) {
while (nPID < nSpherocyls) {
pdTempY[nPID] = pdY[nPID] + dStep * pdDy[nPID];
nPID += nThreads;
}
}
else {
while (nPID < nSpherocyls) {
pdTempPhi[nPID] = pdPhi[nPID] + dStep * pdDt[nPID];
nPID += nThreads;
}
}
}
__global__ void move_step_2p(int nSpherocyls, double *pdX, double *pdY, double *pdPhi,
double *pdDx, double *pdDy, double *pdDt, double dStep,
double *pdXMoved, double *pdYMoved, int *bNewNbrs, double dDR)
{
int thid = threadIdx.x;
int blid = blockIdx.x;
int nPID = thid + (blid / 3) * blockDim.x;
int nThreads = blockDim.x * gridDim.x / 3;
if (blid % 3 == 0) {
while (nPID < nSpherocyls) {
pdX[nPID] = pdX[nPID] + dStep * pdDx[nPID];
pdXMoved[nPID] += dStep * pdDx[nPID];
if (fabs(pdXMoved[nPID]) > 0.5*dDR)
*bNewNbrs = 1;
nPID += nThreads;
}
}
else if (blid % 3 == 1) {
while (nPID < nSpherocyls) {
pdY[nPID] = pdY[nPID] + dStep * pdDy[nPID];
pdYMoved[nPID] += dStep * pdDy[nPID];
if (fabs(pdYMoved[nPID]) > 0.5*dDR)
*bNewNbrs = 1;
nPID += nThreads;
}
}
else {
while (nPID < nSpherocyls) {
pdPhi[nPID] = pdPhi[nPID] + dStep * pdDt[nPID];
nPID += nThreads;
}
}
}
int Spherocyl_Box::new_line_search_2p(double dMinStep, double dMaxStep)
{
cudaMemset((void*) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
temp_move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdTempX, d_pdTempY, d_pdTempPhi,
d_pdDx, d_pdDy, d_pdDt, m_dStep);
cudaDeviceSynchronize();
checkCudaError("Moving Step 1");
calc_energy_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdR, d_pdA, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, sizeof(double)*m_nGridSize, cudaMemcpyDeviceToHost);
h_pdLineEnergy[1] = 0;
cudaDeviceSynchronize();
for(int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[1] += h_pdBlockSums[j];
}
if (h_pdLineEnergy[1] > h_pdLineEnergy[0]) {
while (h_pdLineEnergy[1] >= h_pdLineEnergy[0]) {
m_dStep /= 2;
if (m_dStep < dMinStep) {
printf("Line search stopped due to step size %g %g\n", m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1]);
return 2;
}
h_pdLineEnergy[2] = h_pdLineEnergy[1];
cudaMemset((void*) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
temp_move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdTempX, d_pdTempY, d_pdTempPhi,
d_pdDx, d_pdDy, d_pdDt, m_dStep);
cudaDeviceSynchronize();
checkCudaError("Moving Step 1");
calc_energy_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdR, d_pdA, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, sizeof(double)*m_nGridSize, cudaMemcpyDeviceToHost);
h_pdLineEnergy[1] = 0;
cudaDeviceSynchronize();
for(int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[1] += h_pdBlockSums[j];
}
//printf("Step size %g , line energies: %.10g %.10g %.10g\n", m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2]);
}
}
else {
cudaMemset((void*) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
temp_move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdTempX, d_pdTempY, d_pdTempPhi,
d_pdDx, d_pdDy, d_pdDt, 2*m_dStep);
cudaDeviceSynchronize();
checkCudaError("Moving Step 1");
calc_energy_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdR, d_pdA, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, sizeof(double)*m_nGridSize, cudaMemcpyDeviceToHost);
h_pdLineEnergy[2] = 0;
cudaDeviceSynchronize();
for(int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[2] += h_pdBlockSums[j];
}
//printf("Step size %g , line energies: %.10g %.10g %.10g\n", m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2]);
while (h_pdLineEnergy[2] <= h_pdLineEnergy[1]) {
m_dStep *= 2;
h_pdLineEnergy[1] = h_pdLineEnergy[2];
cudaMemset((void*) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
temp_move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdTempX, d_pdTempY, d_pdTempPhi,
d_pdDx, d_pdDy, d_pdDt, 2*m_dStep);
cudaDeviceSynchronize();
checkCudaError("Moving Step 2");
calc_energy_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdR, d_pdA, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, sizeof(double)*m_nGridSize, cudaMemcpyDeviceToHost);
h_pdLineEnergy[2] = 0;
cudaDeviceSynchronize();
for(int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[2] += h_pdBlockSums[j];
}
//printf("Step size %g , line energies: %.10g %.10g %.10g\n", m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2]);
if (m_dStep > dMaxStep) {
break;
}
}
}
if (h_pdLineEnergy[1] > h_pdLineEnergy[0]) {
printf("Line search result, step %g, line energies %.10g %.10g %.10g\n",
m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2]);
printf("Cannot find lower energy\n");
return 1;
}
else {
double dLineMin = (3*h_pdLineEnergy[0] - 4*h_pdLineEnergy[1] + h_pdLineEnergy[2])/(2*h_pdLineEnergy[0] - 4*h_pdLineEnergy[1] + 2*h_pdLineEnergy[2]);
if (dLineMin > 2) {
dLineMin = 2;
}
else if (h_pdLineEnergy[1] == h_pdLineEnergy[0]) {
dLineMin = 1;
}
move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdDx, d_pdDy, d_pdDt, dLineMin*m_dStep, d_pdXMoved, d_pdYMoved, d_bNewNbrs, m_dEpsilon);
cudaDeviceSynchronize();
checkCudaError("Moving Spherocyls");
calc_energy_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, sizeof(double)*m_nGridSize, cudaMemcpyDeviceToHost);
h_pdLineEnergy[5] = 0;
cudaDeviceSynchronize();
for(int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[5] += h_pdBlockSums[j];
}
if (h_pdLineEnergy[5] > h_pdLineEnergy[1]) {
move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdDx, d_pdDy, d_pdDt, (1.-dLineMin)*m_dStep, d_pdXMoved, d_pdYMoved, d_bNewNbrs, m_dEpsilon);
cudaDeviceSynchronize();
checkCudaError("Moving Spherocyls");
dLineMin = 1;
}
printf("Line search result, step %g, line energies %.12g %.12g %.12g, line min %g\n",
m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2], dLineMin);
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
if (*h_bNewNbrs) {
find_neighbors();
}
}
return 0;
}
int Spherocyl_Box::line_search_2p(bool bFirstStep, bool bSecondStep, double dMinStep, double dMaxStep)
{
bool bFindMin = true;
bool bMinStep = false;
if (bFirstStep) {
cudaMemset((void*) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
temp_move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdTempX, d_pdTempY, d_pdTempPhi,
d_pdDx, d_pdDy, d_pdDt, m_dStep);
cudaDeviceSynchronize();
checkCudaError("Moving Step 1");
calc_energy_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdR, d_pdA, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, sizeof(double)*m_nGridSize, cudaMemcpyDeviceToHost);
h_pdLineEnergy[1] = 0;
cudaDeviceSynchronize();
for(int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[1] += h_pdBlockSums[j];
}
//printf("Step Energy: %.10g\n", dEnergy);
//printf("First step %g, line energies: %.10g %.10g\n", m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1]);
if (h_pdLineEnergy[1] > h_pdLineEnergy[0]) {
if (m_dStep > dMinStep) {
m_dStep /= 2;
h_pdLineEnergy[2] = h_pdLineEnergy[1];
h_pdLineEnergy[1] = 0;
//cudaMemcpyAsync(d_pfSE+1, h_pfSE+1, 2*sizeof(float), cudaMemcpyHostToDevice);
int ret = line_search_2p(1,0, dMinStep, dMaxStep);
if (ret == 1) {
return 1;
}
else if (ret == 2) {
return 2;
}
bFindMin = false;
}
else {
bMinStep = true;
}
}
}
if (bSecondStep) {
cudaMemset((void*) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
temp_move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdTempX, d_pdTempY, d_pdTempPhi,
d_pdDx, d_pdDy, d_pdDt, 2*m_dStep);
cudaDeviceSynchronize();
checkCudaError("Moving Step 1");
calc_energy_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdR, d_pdA, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, sizeof(double)*m_nGridSize, cudaMemcpyDeviceToHost);
//cudaMemcpy(h_pfSE+2, d_pfSE+2, sizeof(float), cudaMemcpyDeviceToHost);
h_pdLineEnergy[2] = 0;
cudaDeviceSynchronize();
for(int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[2] += h_pdBlockSums[j];
}
//printf("Step Energy: %.10g\n", dEnergy);
//printf("Second step %g , line energies: %.10g %.10g %.10g\n", m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2]);
if (h_pdLineEnergy[2] <= h_pdLineEnergy[1]) {
if (m_dStep < dMaxStep) {
m_dStep *= 2;
h_pdLineEnergy[1] = h_pdLineEnergy[2];
h_pdLineEnergy[2] = 0;
//cudaMemcpyAsync(d_pfSE+1, h_pfSE+1, 2*sizeof(float), cudaMemcpyHostToDevice);
int ret = line_search_2p(0,1, dMinStep, dMaxStep);
if (ret == 1) {
return 1;
}
else if (ret == 2) {
return 2;
}
bFindMin = false;
}
}
}
if (bFindMin) {
if (h_pdLineEnergy[1] > h_pdLineEnergy[0]) {
printf("Line search result, step %g, line energies %.10g %.10g %.10g\n",
m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2]);
printf("Cannot find lower energy\n");
return 1;
}
else {
double dLineMin = (3*h_pdLineEnergy[0] - 4*h_pdLineEnergy[1] + h_pdLineEnergy[2])/(2*h_pdLineEnergy[0] - 4*h_pdLineEnergy[1] + 2*h_pdLineEnergy[2]);
if (dLineMin > 2) {
dLineMin = 2;
}
else if (h_pdLineEnergy[1] == h_pdLineEnergy[0]) {
dLineMin = 1;
}
cudaMemset((void*) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
temp_move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdTempX, d_pdTempY, d_pdTempPhi,
d_pdDx, d_pdDy, d_pdDt, dLineMin*m_dStep);
cudaDeviceSynchronize();
checkCudaError("Moving Step 1");
calc_energy_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdTempX, d_pdTempY, d_pdTempPhi, d_pdR, d_pdA, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, sizeof(double)*m_nGridSize, cudaMemcpyDeviceToHost);
//cudaMemcpy(h_pfSE+2, d_pfSE+2, sizeof(float), cudaMemcpyDeviceToHost);
h_pdLineEnergy[2] = 0;
cudaDeviceSynchronize();
for(int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[2] += h_pdBlockSums[j];
}
if (h_pdLineEnergy[2] > h_pdLineEnergy[1]) {
dLineMin = 1;
}
move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdDx, d_pdDy, d_pdDt, dLineMin*m_dStep, d_pdXMoved, d_pdYMoved, d_bNewNbrs, m_dEpsilon);
cudaDeviceSynchronize();
checkCudaError("Moving Spherocyls");
printf("Line search result, step %g, line energies %.14g %.14g %.14g, line min %g\n",
m_dStep, h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[2], dLineMin);
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
if (*h_bNewNbrs) {
find_neighbors();
}
/*
calc_energy_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY, d_pdPhi, d_pdR, d_pdA, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, sizeof(double)*m_nGridSize, cudaMemcpyDeviceToHost);
h_pdLineEnergy[4] = 0;
cudaDeviceSynchronize();
for(int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[4] += h_pdBlockSums[j];
}
if (h_pdLineEnergy[4] > h_pdLineEnergy[2]) {
move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdDx, d_pdDy, d_pdDt, (1.-dLineMin)*m_dStep, d_pdXMoved, d_pdYMoved, d_bNewNbrs, m_dEpsilon);
cudaDeviceSynchronize();
checkCudaError("Moving Spherocyls");
}
*/
}
}
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
if (*h_bNewNbrs) {
find_neighbors();
}
if (m_dStep < dMinStep)
return 2;
return 0;
}
int Spherocyl_Box::gradient_descent_step_2p(double dMinStep, double dMaxStep)
{
//float *d_pfF0Square;
float *d_pfFSquare;
//cudaMalloc((void **) &d_pfF0Square, sizeof(float));
cudaMalloc((void **) &d_pfFSquare, sizeof(float));
//cudaMemset((void *) d_pfF0Square, 0, sizeof(float));
cudaMemset((void *) d_pfFSquare, 0, sizeof(float));
cudaMemset((void *) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
checkCudaError("Setting memory");
//cudaMemcpyAsync(d_pdTempFx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
//cudaMemcpyAsync(d_pdTempFy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
//cudaMemcpyAsync(d_pdTempFt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
//cudaDeviceSynchronize();
calc_fe_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating gradient direction");
//square_forces_2p <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
// (m_nSpherocyls, d_pdTempFx, d_pdTempFy, d_pdTempFt, d_pdMOI, d_pfF0Square);
//cudaDeviceSynchronize();
//checkCudaError("Calculating square of forces 1");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(d_pdDx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
square_forces_2p <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pfFSquare);
cudaDeviceSynchronize();
checkCudaError("Calculating forces squared");
float *h_pfFSquare;
//h_pfF0Square = (float*) malloc(sizeof(float));
h_pfFSquare = (float*) malloc(sizeof(float));
//cudaMemcpy(h_pfF0Square, d_pfF0Square, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(h_pfFSquare, d_pfFSquare, sizeof(float), cudaMemcpyDeviceToHost);
if (*h_pfFSquare == 0) {
printf("Zero energy found, stopping minimization\n");
return 1;
}
double dStepNorm = sqrt(*h_pfFSquare);
m_dStep = 1e-3 / dStepNorm;
dMinStep = 1e-13 / dStepNorm;
dMaxStep = 100 / dStepNorm;
h_pdLineEnergy[5] = h_pdLineEnergy[4];
h_pdLineEnergy[4] = h_pdLineEnergy[3];
h_pdLineEnergy[3] = h_pdLineEnergy[0];
h_pdLineEnergy[0] = 0;
for (int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[0] += h_pdBlockSums[j];
}
if (h_pdLineEnergy[3] <= h_pdLineEnergy[0] && h_pdLineEnergy[4] <= h_pdLineEnergy[3] && h_pdLineEnergy[5] <= h_pdLineEnergy[4]) {
printf("Minimum Energy Found (%g %g %g %g), stopping minimization\n", h_pdLineEnergy[0], h_pdLineEnergy[3], h_pdLineEnergy[4], h_pdLineEnergy[5]);
return 2;
}
int ret = new_line_search_2p(dMinStep, dMaxStep);
printf("Line Search returned %d\n", ret);
if (ret == 2) {
m_dStep = sqrt(h_pdLineEnergy[0]) / dStepNorm;
printf("Moving gradient step: %g %g\n", m_dStep, dStepNorm);
move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdDx, d_pdDy, d_pdDt, m_dStep, d_pdXMoved, d_pdYMoved, d_bNewNbrs, m_dEpsilon);
cudaDeviceSynchronize();
checkCudaError("Moving Spherocyls");
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
if (*h_bNewNbrs) {
find_neighbors();
}
}
else if ((h_pdLineEnergy[0] - h_pdLineEnergy[1]) < (h_pdLineEnergy[0] * 1e-13)) {
m_dStep = sqrt(h_pdLineEnergy[0]) / dStepNorm;
printf("Small delta-E detected: %g %g %g\n", h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[0] - h_pdLineEnergy[1]);
printf("Moving gradient step: %g %g\n", m_dStep, *h_pfFSquare);
move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdDx, d_pdDy, d_pdDt, m_dStep, d_pdXMoved, d_pdYMoved, d_bNewNbrs, m_dEpsilon);
cudaDeviceSynchronize();
checkCudaError("Moving Spherocyls");
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
if (*h_bNewNbrs) {
find_neighbors();
}
}
free(h_pfFSquare);
cudaFree(d_pfFSquare);
return 0;
}
int Spherocyl_Box::cjpr_relax_step_2p(double dMinStep, double dMaxStep)
{
float *d_pfF0Square;
float *d_pfFSquare;
float *d_pfFF0;
cudaMalloc((void **) &d_pfF0Square, sizeof(float));
cudaMalloc((void **) &d_pfFSquare, sizeof(float));
cudaMalloc((void **) &d_pfFF0, sizeof(float));
cudaMemset((void *) d_pfF0Square, 0, sizeof(float));
cudaMemset((void *) d_pfFSquare, 0, sizeof(float));
cudaMemset((void *) d_pfFF0, 0, sizeof(float));
cudaMemset((void *) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
checkCudaError("Setting memory");
cudaMemcpyAsync(d_pdTempFx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdTempFy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdTempFt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaDeviceSynchronize();
calc_fe_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pdBlockSums);
square_forces_2p <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdTempFx, d_pdTempFy, d_pdTempFt, d_pdMOI, d_pfF0Square);
cudaDeviceSynchronize();
checkCudaError("Calculating square of forces 1");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
square_forces_2p <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pfFSquare);
mult_forces_2p <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdTempFx, d_pdTempFy, d_pdTempFt, d_pdMOI, d_pfFF0);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
float *h_pfF0Square;
float *h_pfFSquare;
h_pfF0Square = (float*) malloc(sizeof(float));
h_pfFSquare = (float*) malloc(sizeof(float));
cudaMemcpy(h_pfF0Square, d_pfF0Square, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(h_pfFSquare, d_pfFSquare, sizeof(float), cudaMemcpyDeviceToHost);
if (*h_pfFSquare == 0) {
printf("Zero energy found, stopping minimization\n");
return 1;
}
cudaDeviceSynchronize();
h_pdLineEnergy[4] = h_pdLineEnergy[3];
h_pdLineEnergy[3] = h_pdLineEnergy[0];
h_pdLineEnergy[0] = 0;
for (int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[0] += h_pdBlockSums[j];
}
if (h_pdLineEnergy[3] == h_pdLineEnergy[0] && h_pdLineEnergy[4] == h_pdLineEnergy[3]) {
printf("Minimum Energy Found, stopping minimization\n");
return 2;
}
new_pr_conj_dir_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pdDx, d_pdDy, d_pdDt,
d_pfF0Square, d_pfFSquare, d_pfFF0);
cudaDeviceSynchronize();
checkCudaError("Finding new conjugate direction");
double dStepNorm = sqrt(*h_pfFSquare/(3*m_nSpherocyls));
m_dStep = 2e-6 / dStepNorm;
dMinStep = 1e-18 / dStepNorm;
dMaxStep = 2 / dStepNorm;
printf("Starting Line search with step size: %g %g %g %g\n", m_dStep, *h_pfFSquare, dMinStep, dMaxStep);
int ret = line_search_2p(1,1, dMinStep, dMaxStep);
if (ret == 1) {
cudaMemcpyAsync(d_pdDx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
m_dStep = 1e-6 / dStepNorm;
printf("Starting Line search with step size: %g\n", m_dStep);
cudaDeviceSynchronize();
ret = line_search_2p(1,1, dMinStep, dMaxStep);
if (ret == 1) {
sqrt_grad_dir_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdDx, d_pdDy, d_pdDt);
cudaDeviceSynchronize();
//cudaMemcpy(h_pdFx, d_pdDx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
//cudaMemcpy(h_pdFy, d_pdDy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
//cudaMemcpy(h_pdFt, d_pdDt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
m_dStep = 2e-6 / sqrt(dStepNorm);
dMinStep = 1e-18 / sqrt(dStepNorm);
dMaxStep = 2 / sqrt(dStepNorm);
//printf("Starting Line search with step size: %g\n", m_dStep);
//printf("Step: %g, Dir: %g %g %g, Move: %g %g %g\n",
// m_dStep, h_pdFx[0], h_pdFy[0], h_pdFt[0], m_dStep*h_pdFx[0], m_dStep*h_pdFy[0], m_dStep*h_pdFt[0]);
//printf("Step: %g, Dir: %g %g %g, Move: %g %g %g\n",
// m_dStep, h_pdFx[1], h_pdFy[1], h_pdFt[1], m_dStep*h_pdFx[1], m_dStep*h_pdFy[1], m_dStep*h_pdFt[1]);
ret = line_search_2p(1,1, dMinStep, dMaxStep);
if (ret == 1) {
printf("Stopping due to step size\n");
return 1;
}
}
}
else if (ret == 2) {
cudaMemcpyAsync(d_pdDx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
m_dStep = 1e-6 / dStepNorm;
printf("Starting Line search with step size: %g\n", m_dStep);
cudaDeviceSynchronize();
ret = line_search_2p(1,1, dMinStep, dMaxStep);
if (ret == 1) {
sqrt_grad_dir_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdDx, d_pdDy, d_pdDt);
cudaDeviceSynchronize();
m_dStep = 1e-6 / sqrt(dStepNorm);
dMinStep = 1e-18 / sqrt(dStepNorm);
dMaxStep = 0.01 / sqrt(dStepNorm);
printf("Starting Line search with step size: %g\n", m_dStep);
//printf("Step: %g, Dir: %g %g %g, Move: %g %g %g\n",
// m_dStep, h_pdFx[0], h_pdFy[0], h_pdFt[0], m_dStep*h_pdFx[0], m_dStep*h_pdFy[0], m_dStep*h_pdFt[0]);
//printf("Step: %g, Dir: %g %g %g, Move: %g %g %g\n",
// m_dStep, h_pdFx[1], h_pdFy[1], h_pdFt[1], m_dStep*h_pdFx[1], m_dStep*h_pdFy[1], m_dStep*h_pdFt[1]);
ret = line_search_2p(1,1, dMinStep, dMaxStep);
if (ret == 1) {
printf("Stopping due to step size\n");
return 1;
}
}
}
free(h_pfF0Square); free(h_pfFSquare);
cudaFree(d_pfF0Square); cudaFree(d_pfFSquare); cudaFree(d_pfFF0);
return 0;
}
int Spherocyl_Box::new_cjpr_relax_step_2p(double dMinStep, double dMaxStep)
{
float *d_pfF0Square;
float *d_pfFSquare;
float *d_pfFF0;
float *d_pfDSquare;
cudaMalloc((void **) &d_pfF0Square, sizeof(float));
cudaMalloc((void **) &d_pfFSquare, sizeof(float));
cudaMalloc((void **) &d_pfFF0, sizeof(float));
cudaMalloc((void **) &d_pfDSquare, sizeof(float));
cudaMemset((void *) d_pfF0Square, 0, sizeof(float));
cudaMemset((void *) d_pfFSquare, 0, sizeof(float));
cudaMemset((void *) d_pfFF0, 0, sizeof(float));
cudaMemset((void *) d_pfDSquare, 0, sizeof(float));
cudaMemset((void *) d_pdBlockSums, 0, m_nGridSize*sizeof(double));
checkCudaError("Setting memory");
cudaMemcpyAsync(d_pdTempFx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdTempFy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdTempFt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaDeviceSynchronize();
calc_fe_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pdBlockSums);
square_forces_2p <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdTempFx, d_pdTempFy, d_pdTempFt, d_pdMOI, d_pfF0Square);
cudaDeviceSynchronize();
checkCudaError("Calculating square of forces 1");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
square_forces_2p <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pfFSquare);
mult_forces_2p <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdTempFx, d_pdTempFy, d_pdTempFt, d_pdMOI, d_pfFF0);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
float *h_pfF0Square;
float *h_pfFSquare;
h_pfF0Square = (float*) malloc(sizeof(float));
h_pfFSquare = (float*) malloc(sizeof(float));
cudaMemcpy(h_pfF0Square, d_pfF0Square, sizeof(float), cudaMemcpyDeviceToHost);
cudaMemcpy(h_pfFSquare, d_pfFSquare, sizeof(float), cudaMemcpyDeviceToHost);
if (*h_pfFSquare == 0) {
printf("Zero energy found, stopping minimization\n");
return 1;
}
cudaDeviceSynchronize();
new_pr_conj_dir_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdFx, d_pdFy, d_pdFt, d_pdMOI, d_pdDx, d_pdDy, d_pdDt,
d_pfF0Square, d_pfFSquare, d_pfFF0);
h_pdLineEnergy[5] = h_pdLineEnergy[4];
h_pdLineEnergy[4] = h_pdLineEnergy[3];
h_pdLineEnergy[3] = h_pdLineEnergy[0];
h_pdLineEnergy[0] = 0;
for (int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[0] += h_pdBlockSums[j];
}
cudaDeviceSynchronize();
checkCudaError("Finding new conjugate direction");
square_forces_2p <<<3*m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pdDx, d_pdDy, d_pdDt, d_pdMOI, d_pfDSquare);
float *h_pfDSquare;
h_pfDSquare = (float*) malloc(sizeof(float));
if (h_pdLineEnergy[3] == h_pdLineEnergy[0] && h_pdLineEnergy[4] == h_pdLineEnergy[3] && h_pdLineEnergy[5] <= h_pdLineEnergy[4]) {
printf("Minimum Energy Found, stopping minimization\n");
return 2;
}
cudaDeviceSynchronize();
cudaMemcpy(h_pfDSquare, d_pfDSquare, sizeof(float), cudaMemcpyDeviceToHost);
double dStepNorm = sqrt(*h_pfDSquare);
m_dStep = 1;
dMinStep = 1e-13 / dStepNorm;
dMaxStep = 10 / dStepNorm;
printf("Starting Line search with step size: %g %g %g %g\n", m_dStep, dStepNorm, dMinStep, dMaxStep);
int ret = new_line_search_2p(dMinStep, dMaxStep);
if (ret == 2) {
cudaMemcpyAsync(d_pdDx, d_pdFx, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDy, d_pdFy, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
cudaMemcpyAsync(d_pdDt, d_pdFt, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToDevice);
dStepNorm = sqrt(*h_pfFSquare);
m_dStep = 1;
dMinStep = 1e-13 / dStepNorm;
dMaxStep = 10 / dStepNorm;
printf("Starting Line search with step size: %g %g %g %g\n", m_dStep, dStepNorm, dMinStep, dMaxStep);
cudaDeviceSynchronize();
ret = new_line_search_2p(dMinStep, dMaxStep);
if (ret == 2) {
m_dStep = 0.1;
printf("Moving gradient step: %g %g\n", m_dStep, dStepNorm);
move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdDx, d_pdDy, d_pdDt, m_dStep, d_pdXMoved, d_pdYMoved, d_bNewNbrs, m_dEpsilon);
cudaDeviceSynchronize();
checkCudaError("Moving Spherocyls");
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
if (*h_bNewNbrs) {
find_neighbors();
}
}
else if ((h_pdLineEnergy[0] - h_pdLineEnergy[1]) < (h_pdLineEnergy[0] * 1e-13)) {
m_dStep = 0.1;
printf("Small delta-E detected: %g %g %g\n", h_pdLineEnergy[0], h_pdLineEnergy[1], h_pdLineEnergy[0] - h_pdLineEnergy[1]);
printf("Moving gradient step: %g %g\n", m_dStep, *h_pfFSquare);
move_step_2p <<<3*m_nGridSize, m_nBlockSize>>>
(m_nSpherocyls, d_pdX, d_pdY, d_pdPhi, d_pdDx, d_pdDy, d_pdDt, m_dStep, d_pdXMoved, d_pdYMoved, d_bNewNbrs, m_dEpsilon);
cudaDeviceSynchronize();
checkCudaError("Moving Spherocyls");
cudaMemcpyAsync(h_bNewNbrs, d_bNewNbrs, sizeof(int), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
if (*h_bNewNbrs) {
find_neighbors();
}
}
//cudaMemset((void*) d_pdDx, 0, m_nSpherocyls*sizeof(double));
//cudaMemset((void*) d_pdDy, 0, m_nSpherocyls*sizeof(double));
//cudaMemset((void*) d_pdDt, 0, m_nSpherocyls*sizeof(double));
}
free(h_pfF0Square); free(h_pfFSquare); free(h_pfDSquare);
cudaFree(d_pfF0Square); cudaFree(d_pfFSquare); cudaFree(d_pfFF0); cudaFree(d_pfDSquare);
return 0;
}
void Spherocyl_Box::gradient_relax_2p(double dMinStep, double dMaxStep, int nMaxSteps = 100000)
{
cudaMemset((void*) d_pdDx, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDy, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDt, 0, m_nSpherocyls*sizeof(double));
for (int i = 0; i < 4; i++) {
h_pdLineEnergy[i] = 0;
}
calc_fe_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
for (int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[0] += h_pdBlockSums[j];
}
printf("Relaxation start energy: %g\n", h_pdLineEnergy[0]);
find_neighbors();
h_pdLineEnergy[5] = h_pdLineEnergy[0];
h_pdLineEnergy[3] = h_pdLineEnergy[0];
h_pdLineEnergy[4] = h_pdLineEnergy[0];
h_pdLineEnergy[0] = 0;
long unsigned int nTime = 0;
while (nTime < nMaxSteps) {
printf("Step %lu\n", nTime);
int ret = new_cjpr_relax_step_2p(dMinStep, dMaxStep);
//find_neighbors();
if (ret == 1) {
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
//save_positions(nTime);
break;
}
else if (ret == 2) {
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
//save_positions(nTime);
break;
}
//find_neighbors();
nTime += 1;
}
find_neighbors();
calc_fe_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
h_pdLineEnergy[0] = 0;
for (int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[0] += h_pdBlockSums[j];
}
printf("Relaxation stopped after %lu steps with energy %g\n", nTime, h_pdLineEnergy[0]);
}
void Spherocyl_Box::cjpr_relax_2p(double dMinStep, double dMaxStep, int nMaxSteps = 100000)
{
cudaMemset((void*) d_pdDx, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDy, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDt, 0, m_nSpherocyls*sizeof(double));
for (int i = 0; i < 4; i++) {
h_pdLineEnergy[i] = 0;
}
calc_fe_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
for (int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[0] += h_pdBlockSums[j];
}
printf("Relaxation start energy: %g\n", h_pdLineEnergy[0]);
find_neighbors();
h_pdLineEnergy[0] = 0;
long unsigned int nTime = 0;
while (nTime < nMaxSteps) {
int ret = cjpr_relax_step_2p(dMinStep, dMaxStep);
if (ret == 1 || ret == 2) {
cudaMemcpyAsync(h_pdX, d_pdX, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdY, d_pdY, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaMemcpyAsync(h_pdPhi, d_pdPhi, m_nSpherocyls*sizeof(double), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
//save_positions(nTime);
break;
}
//find_neighbors();
nTime += 1;
if (nTime % (3*m_nSpherocyls) == 0) {
cudaMemset((void*) d_pdDx, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDy, 0, m_nSpherocyls*sizeof(double));
cudaMemset((void*) d_pdDt, 0, m_nSpherocyls*sizeof(double));
}
}
find_neighbors();
calc_fe_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
h_pdLineEnergy[0] = 0;
for (int j = 0; j < m_nGridSize; j++) {
h_pdLineEnergy[0] += h_pdBlockSums[j];
}
printf("Relaxation stopped after %lu steps with energy %g\n", nTime, h_pdLineEnergy[0]);
}
void Spherocyl_Box::compress_qs2p(double dMaxPacking, double dResizeStep)
{
assert(dResizeStep != 0);
dResizeStep = fabs(dResizeStep);
calculate_packing();
assert(dMaxPacking >= m_dPacking);
int nCompressTime = 0;
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
double dCJMinStep = 1e-12;
double dCJMaxStep = 10;
int nCJMaxSteps = 1000000;
cjpr_relax_2p(dCJMinStep, dCJMaxStep, nCJMaxSteps);
calculate_stress_energy_2p();
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
save_positions(nCompressTime);
cudaDeviceSynchronize();
fprintf(m_pOutfSE, "%d %f %g %g %g %g %g\n", nCompressTime, m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, *m_pfPxy, *m_pfPyx);
while (m_dPacking < dMaxPacking) {
nCompressTime += 1;
m_dStep = 0.01;
resize_step_2p(nCompressTime, -dResizeStep, 0, 0);
//resize_coords_2p <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, -dResizeStep, d_pdX, d_pdY);
//m_dLx -= dResizeStep*m_dLx;
//m_dLy -= dResizeStep*m_dLy;
cjpr_relax_2p(dCJMinStep, dCJMaxStep, nCJMaxSteps);
calculate_stress_energy_2p();
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
calculate_packing();
save_positions(nCompressTime);
cudaDeviceSynchronize();
fprintf(m_pOutfSE, "%d %.9f %g %g %g %g %g\n", nCompressTime, m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, *m_pfPxy, *m_pfPyx);
fflush(m_pOutfSE);
}
fclose(m_pOutfSE);
}
void Spherocyl_Box::expand_qs2p(double dMinPacking, double dResizeStep)
{
assert(dResizeStep != 0);
dResizeStep = fabs(dResizeStep);
calculate_packing();
assert(dMinPacking <= m_dPacking);
int nCompressTime = 0;
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
double dCJMinStep = 1e-12;
double dCJMaxStep = 10;
int nCJMaxSteps = 1000000;
cjpr_relax_2p(dCJMinStep, dCJMaxStep, nCJMaxSteps);
calculate_stress_energy_2p();
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
save_positions(nCompressTime);
cudaDeviceSynchronize();
fprintf(m_pOutfSE, "%d %f %g %g %g %g %g\n", nCompressTime, m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, *m_pfPxy, *m_pfPyx);
while (m_dPacking > dMinPacking) {
nCompressTime += 1;
m_dStep = 0.01;
resize_step_2p(nCompressTime, dResizeStep, 0, 0);
//resize_coords_2p <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, -dResizeStep, d_pdX, d_pdY);
//m_dLx -= dResizeStep*m_dLx;
//m_dLy -= dResizeStep*m_dLy;
cjpr_relax_2p(dCJMinStep, dCJMaxStep, nCJMaxSteps);
calculate_stress_energy_2p();
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
calculate_packing();
save_positions(nCompressTime);
cudaDeviceSynchronize();
fprintf(m_pOutfSE, "%d %.9f %g %g %g %g %g\n", nCompressTime, m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, *m_pfPxy, *m_pfPyx);
fflush(m_pOutfSE);
}
fclose(m_pOutfSE);
}
int Spherocyl_Box::resize_to_energy_2p(int nTime, double dEnergy, double dStep)
{
dStep = fabs(dStep);
double dCJMinStep = 1e-15;
double dCJMaxStep = 10;
int nCJMaxSteps = 200000;
find_neighbors();
calc_fe_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
h_pdLineEnergy[0] = 0;
cudaDeviceSynchronize();
for (int i = 0; i < m_nGridSize; i++) {
h_pdLineEnergy[0] += h_pdBlockSums[i];
}
if (h_pdLineEnergy[0] < dEnergy) {
while (h_pdLineEnergy[0] < dEnergy) {
nTime += 1;
m_dStep = 0.01;
resize_step_2p(nTime, -dStep, 0, 0);
//resize_coords_2p <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, -dStep, d_pdX, d_pdY);
//m_dLx -= dStep*m_dLx;
//m_dLy -= dStep*m_dLy;
cjpr_relax_2p(dCJMinStep, dCJMaxStep, nCJMaxSteps);
calculate_stress_energy_2p();
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
calculate_packing();
save_positions(nTime);
cudaDeviceSynchronize();
fprintf(m_pOutfSE, "%d %.10f %.9g %.9g %.9g %.9g %.9g\n", nTime, m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, *m_pfPxy, *m_pfPyx);
fflush(m_pOutfSE);
dStep *= 1.1;
}
}
else {
while (h_pdLineEnergy[0] > dEnergy) {
nTime += 1;
m_dStep = 0.01;
resize_step_2p(nTime, dStep, 0, 0);
//resize_coords_2p <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, dStep, d_pdX, d_pdY);
//m_dLx += dStep*m_dLx;
//m_dLy += dStep*m_dLy;
cjpr_relax_2p(dCJMinStep, dCJMaxStep, nCJMaxSteps);
calculate_stress_energy_2p();
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
calculate_packing();
save_positions(nTime);
cudaDeviceSynchronize();
fprintf(m_pOutfSE, "%d %.10f %.9g %.9g %.9g %.9g %.9g\n", nTime, m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, *m_pfPxy, *m_pfPyx);
fflush(m_pOutfSE);
dStep *= 1.1;
}
}
return nTime;
}
int Spherocyl_Box::y_resize_to_energy_2p(int nTime, double dEnergy, double dStep)
{
dStep = fabs(dStep);
double dCJMinStep = 1e-15;
double dCJMaxStep = 10;
int nCJMaxSteps = 200000;
find_neighbors();
calc_fe_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
h_pdLineEnergy[0] = 0;
cudaDeviceSynchronize();
for (int i = 0; i < m_nGridSize; i++) {
h_pdLineEnergy[0] += h_pdBlockSums[i];
}
if (h_pdLineEnergy[0] < dEnergy) {
while (h_pdLineEnergy[0] < dEnergy) {
nTime += 1;
m_dStep = 0.01;
y_resize_step_2p(nTime, -dStep, 0, 0);
//resize_coords_2p <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, -dStep, d_pdX, d_pdY);
//m_dLx -= dStep*m_dLx;
//m_dLy -= dStep*m_dLy;
cjpr_relax_2p(dCJMinStep, dCJMaxStep, nCJMaxSteps);
calculate_stress_energy_2p();
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
calculate_packing();
save_positions(nTime);
cudaDeviceSynchronize();
fprintf(m_pOutfSE, "%d %.10f %.9g %.9g %.9g %.9g %.9g\n", nTime, m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, *m_pfPxy, *m_pfPyx);
fflush(m_pOutfSE);
dStep *= 1.1;
}
}
else {
while (h_pdLineEnergy[0] > dEnergy) {
nTime += 1;
m_dStep = 0.01;
y_resize_step_2p(nTime, dStep, 0, 0);
//resize_coords_2p <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, dStep, d_pdX, d_pdY);
//m_dLx += dStep*m_dLx;
//m_dLy += dStep*m_dLy;
cjpr_relax_2p(dCJMinStep, dCJMaxStep, nCJMaxSteps);
calculate_stress_energy_2p();
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
calculate_packing();
save_positions(nTime);
cudaDeviceSynchronize();
fprintf(m_pOutfSE, "%d %.10f %.9g %.9g %.9g %.9g %.9g\n", nTime, m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, *m_pfPxy, *m_pfPyx);
fflush(m_pOutfSE);
dStep *= 1.1;
}
}
return nTime;
}
int Spherocyl_Box::resize_relax_step_2p(int nTime, double dStep, int nCJMaxSteps)
{
dStep = fabs(dStep);
double dCJMinStep = 1e-15;
double dCJMaxStep = 100;
//int nCJMaxSteps = 2000000;
find_neighbors();
calc_fe_2p <HARMONIC> <<<m_nGridSize, m_nBlockSize, m_nBlockSize*sizeof(double)>>>
(m_nSpherocyls, d_pnNPP, d_pnNbrList, m_dLx, m_dLy, m_dGamma, d_pdX, d_pdY,
d_pdPhi, d_pdR, d_pdA, d_pdMOI, d_pdFx, d_pdFy, d_pdFt, d_pdBlockSums);
cudaDeviceSynchronize();
checkCudaError("Calculating forces and energy");
cudaMemcpyAsync(h_pdBlockSums, d_pdBlockSums, m_nGridSize*sizeof(double), cudaMemcpyDeviceToHost);
h_pdLineEnergy[0] = 0;
cudaDeviceSynchronize();
for (int i = 0; i < m_nGridSize; i++) {
h_pdLineEnergy[0] += h_pdBlockSums[i];
}
m_dStep = 0.01;
resize_step_2p(nTime, -dStep, 0, 0);
//resize_coords_2p <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, -dStep, d_pdX, d_pdY);
//m_dLx -= dStep*m_dLx;
//m_dLy -= dStep*m_dLy;
cjpr_relax_2p(dCJMinStep, dCJMaxStep, nCJMaxSteps);
nTime += 1;
calculate_stress_energy_2p();
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
calculate_packing();
save_positions(nTime);
cudaDeviceSynchronize();
fprintf(m_pOutfSE, "%d %.10f %.9g %.9g %.9g %.9g %.9g\n", nTime, m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, *m_pfPxy, *m_pfPyx);
fflush(m_pOutfSE);
m_dStep = 0.01;
resize_step_2p(nTime, dStep, 0, 0);
//resize_coords_2p <<<m_nGridSize, m_nBlockSize>>> (m_nSpherocyls, dStep, d_pdX, d_pdY);
//m_dLx += dStep*m_dLx;
//m_dLy += dStep*m_dLy;
cjpr_relax_2p(dCJMinStep, dCJMaxStep, nCJMaxSteps);
nTime += 1;
calculate_stress_energy_2p();
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
calculate_packing();
save_positions(nTime);
cudaDeviceSynchronize();
fprintf(m_pOutfSE, "%d %.10f %.9g %.9g %.9g %.9g %.9g\n", nTime, m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, *m_pfPxy, *m_pfPyx);
fflush(m_pOutfSE);
return nTime;
}
void Spherocyl_Box::find_jam_2p(double dJamE, double dResizeStep)
{
int nTime = 0;
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
save_positions(0);
double dMinResizeStep = 1e-15;
int nOldTime = 0;
while (dResizeStep > dMinResizeStep) {
nTime = resize_to_energy_2p(nTime, dJamE, dResizeStep);
dResizeStep = dResizeStep*pow(1.1, (nTime-nOldTime-1))/2;
nOldTime = nTime;
}
save_positions_bin(nTime);
fclose(m_pOutfSE);
}
void Spherocyl_Box::y_compress_energy_2p(double dTargetE, double dResizeStep)
{
int nTime = 0;
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
save_positions(0);
double dMinResizeStep = 1e-14;
int nOldTime = 0;
while (dResizeStep > dMinResizeStep) {
nTime = y_resize_to_energy_2p(nTime, dTargetE, dResizeStep);
dResizeStep = dResizeStep*pow(1.1, (nTime-nOldTime-1))/2;
nOldTime = nTime;
}
save_positions_bin(nTime);
fclose(m_pOutfSE);
}
void Spherocyl_Box::find_energy_2p(double dResizeStep, double dMinResizeStep, int nMaxSteps)
{
int nTime = 0;
char szBuf[200];
sprintf(szBuf, "%s/%s", m_szDataDir, m_szFileSE);
const char *szPathSE = szBuf;
printf("%s\n", szBuf);
m_pOutfSE = fopen(szPathSE, "w");
if (m_pOutfSE == NULL) {
fprintf(stderr, "Could not open file for writing");
exit(1);
}
save_positions(0);
double L0 = m_dLx;
//double dMinResizeStep = 1e-15;
//nTime = resize_relax_step_2p(nTime, dResizeStep, nMaxSteps);
//dResizeStep *= -0.75;
while (fabs(dResizeStep) > dMinResizeStep) {
printf("Relaxing with step size: %g\n", dResizeStep);
//nTime = resize_relax_step_2p(nTime, dResizeStep, nMaxSteps);
nTime = resize_relax_step_2p(nTime, dResizeStep, nMaxSteps);
dResizeStep /= 2;
}
double dErr = 1 - m_dLx / L0;
if (dErr != 0) {
m_dStep = 0.01;
resize_step_2p(nTime, dErr, 0, 0);
cjpr_relax_2p(1e-15, 100., nMaxSteps);
nTime += 1;
calculate_stress_energy_2p();
cudaMemcpyAsync(h_pfSE, d_pfSE, 5*sizeof(float), cudaMemcpyDeviceToHost);
calculate_packing();
save_positions(nTime);
cudaDeviceSynchronize();
fprintf(m_pOutfSE, "%d %.10f %.9g %.9g %.9g %.9g %.9g\n", nTime, m_dPacking, *m_pfEnergy, *m_pfPxx, *m_pfPyy, *m_pfPxy, *m_pfPyx);
fflush(m_pOutfSE);
}
save_positions_bin(nTime);
fclose(m_pOutfSE);
}
//void Spherocyl_Box::find_energy_2p2(double dResizeStep, double dMinResize
<file_sep>/src/cuda/cudaErr.h
/*
* cudaErr.h
*
*
* Created by <NAME> on 6/15/10.
* Copyright 2010 __MyCompanyName__. All rights reserved.
*
*/
#ifndef CUDAERR_H
#define CUDAERR_H
void checkCudaError(const char *msg);
#endif
<file_sep>/src/cpp/relaxation_dynamics.cpp
#include "spherocyl_box.h"
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
using std::cerr;
using std::exit;
void SpherocylBox::gradient_relax_step()
{
//calc_forces();
for (int i = 0; i < m_nParticles; i++) {
double dDx = m_dStep * m_psParticles[i].m_dFx;
double dDy = m_dStep * m_psParticles[i].m_dFy;
m_psParticles[i].m_dX += dDx;
m_psParticles[i].m_dY += dDy;
m_psParticles[i].m_dPhi += m_dStep * m_psParticles[i].m_dTau / m_psParticles[i].m_dI;
m_psParticles[i].m_dXMoved += dDx;
m_psParticles[i].m_dYMoved += dDy;
if (m_psParticles[i].m_dXMoved > 0.5 * m_dPadding ||
m_psParticles[i].m_dXMoved < -0.5 * m_dPadding)
find_neighbors();
else if (m_psParticles[i].m_dYMoved > 0.5 * m_dPadding ||
m_psParticles[i].m_dYMoved < -0.5 * m_dPadding)
find_neighbors();
}
}
void SpherocylBox::gradient_descent_minimize(int nMaxSteps, double dMinE)
{
//m_dStep = dStep;
std::string strSEPath = m_strOutputDir + "/" + m_strSEOutput;
std::fstream outfSE;
outfSE.open(strSEPath.c_str(), std::ios::out);
int nPosSaveT = int(m_dPosSaveStep + 0.5);
int loop_exit = 0;
for (int s = 0; s < nMaxSteps; s++) {
calc_se();
outfSE << s << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << endl;
if (m_dEnergy <= dMinE) {
outfSE.flush();
char szBuf[11];
sprintf(szBuf, "%010lu", s);
std::string strSaveFile = std::string("sr") + szBuf + std::string(".dat");
save_positions(strSaveFile);
loop_exit = 1;
break;
}
else if (s % nPosSaveT == 0) {
outfSE.flush();
char szBuf[11];
sprintf(szBuf, "%010lu", s);
std::string strSaveFile = std::string("sr") + szBuf + std::string(".dat");
save_positions(strSaveFile);
}
gradient_relax_step();
}
switch (loop_exit)
{
case 0:
{
cout << "\nMaximum relaxation steps reached" << endl;
calc_se();
outfSE << nMaxSteps << " " << m_dEnergy << " " << m_dPxx << " " << m_dPyy << " " << m_dPxy << endl;
char szBuf[11];
sprintf(szBuf, "%010lu", nMaxSteps);
std::string strSaveFile = std::string("sr") + szBuf + std::string(".dat");
save_positions(strSaveFile);
break;
}
case 1:
{
cout << "\nEncountered zero energy" << endl;
break;
}
}
outfSE.close();
}
<file_sep>/src/cpp/gz_file_input.cpp
#include "file_input.h"
#include <fstream>
#include <string>
#include <iostream>
#include <cstdlib> //for exit, atoi etc
#include <cstdio>
using namespace std;
GzFileInput::GzFileInput(const char *szFile)
{
m_szFileName = szFile;
m_bHeader = 0;
m_nHeadLen = 0;
m_strHeader = 0;
m_nColumns = gzGetColumns();
m_nFileLength = gzGetRows();
if (m_nFileLength * m_nColumns < 5000000)
m_nRows = m_nFileLength;
else
m_nRows = 5000000 / m_nColumns;
m_nArrayLine1 = 0;
m_strArray = new string[m_nRows*m_nColumns];
gzFillArray();
}
GzFileInput::GzFileInput(const char *szFile, bool bHeader)
{
m_szFileName = szFile;
m_bHeader = bHeader;
if (bHeader) {
m_nHeadLen = gzGetHeadLen();
m_strHeader = new string[m_nHeadLen];
gzFillHeader();
}
else {
m_nHeadLen = 0;
m_strHeader = 0;
}
m_nColumns = gzGetColumns();
cout << "Getting row count" << endl;
m_nFileLength = gzGetRows();
if (m_nFileLength * m_nColumns < 5000000)
m_nRows = m_nFileLength - (int)m_bHeader;
else
m_nRows = 5000000 / m_nColumns;
m_nArrayLine1 = 0;
m_strArray = new string[m_nRows*m_nColumns];
gzFillArray();
}
GzFileInput::GzFileInput(const char *szFile, bool bHeader, int nRows, int nColumns)
{
m_szFileName = szFile;
m_bHeader = bHeader;
if (bHeader) {
m_nHeadLen = gzGetHeadLen();
m_strHeader = new string[m_nHeadLen];
gzFillHeader();
}
else {
m_nHeadLen = 0;
m_strHeader = 0;
}
m_nColumns = nColumns;
m_nFileLength = nRows + (int)m_bHeader;
if (nRows * nColumns < 5000000)
m_nRows = nRows;
else
m_nRows = 5000000 / m_nColumns;
m_strArray = new string[m_nRows * m_nColumns];
m_nArrayLine1 = 0;
gzFillArray();
}
int GzFileInput::gzGetRows()
{
string strCmd = "zcat ";
strCmd.append(m_szFileName);
FILE *inf = popen(strCmd.c_str(), "r");
if (!inf) {
cerr << "Could not load, check file name and directory" << endl;
exit(1);
}
int nRows = 0;
int ch = getc(inf);
while (ch != EOF) {
if (ch == '\n')
nRows++;
ch = getc(inf);
}
fclose(inf);
return nRows;
}
int GzFileInput::gzGetColumns()
{
string strCmd = "zcat ";
strCmd.append(m_szFileName);
FILE *inf = popen(strCmd.c_str(), "r");
if (!inf) {
cerr << "Could not load, check file name and directory" << endl;
exit(1);
}
if (m_bHeader) {
char szBuf[10000];
fgets(szBuf, 10000, inf);
}
int nCols = 1;
int ch = getc(inf);
while (ch != '\n') {
if (ch == ' ')
nCols++;
ch = getc(inf);
}
fclose(inf);
return nCols;
}
int GzFileInput::gzGetHeadLen()
{
if (!m_bHeader)
return 0;
else {
string strCmd = "zcat ";
strCmd.append(m_szFileName);
FILE *inf = popen(strCmd.c_str(), "r");
if (!inf) {
cerr << "Could not load, check file name and directory" << endl;
exit(1);
}
int nLen = 1;
int ch = getc(inf);
while (ch != '\n') {
if (ch == ' ')
nLen++;
ch = getc(inf);
}
fclose(inf);
return nLen;
}
}
void GzFileInput::gzFillHeader()
{
string strCmd = "zcat ";
strCmd.append(m_szFileName);
FILE *inf = popen(strCmd.c_str(), "r");
if (!inf) {
cerr << "Could not load, check file name and directory" << endl;
exit(1);
}
char szBuf[10000];
fgets(szBuf, 10000, inf);
string strLine(szBuf);
int nColId = 0;
size_t leftSpace = -1;
size_t rightSpace = strLine.find_first_of(" ");
m_strHeader[nColId] = strLine.substr(0, rightSpace);
for (nColId = 1; nColId < m_nHeadLen; nColId++)
{
if (rightSpace == string::npos)
m_strHeader[nColId] = "0";
else
{
leftSpace = rightSpace;
rightSpace = strLine.find_first_of(" ", leftSpace + 1);
m_strHeader[nColId] = strLine.substr(leftSpace + 1, rightSpace - leftSpace - 1);
}
}
fclose(inf);
}
void GzFileInput::gzFillArray()
{
string strCmd = "zcat ";
strCmd.append(m_szFileName);
FILE *inf = popen(strCmd.c_str(), "r");
if (!inf) {
cerr << "Could not load, check file name and directory" << endl;
exit(1);
}
char szBuf[10000];
for (int n = 0; n < m_nArrayLine1 + (int)m_bHeader; n++) {
fgets(szBuf, 10000, inf);
}
for (int rid = 0; rid < m_nRows; rid++) {
if (m_nArrayLine1 + rid + (int)m_bHeader >= m_nFileLength)
break;
int cid = 0;
fgets(szBuf, 10000, inf);
string strLine(szBuf);
size_t leftSpace = -1;
size_t rightSpace = strLine.find_first_of(" ");
m_strArray[rid * m_nColumns + cid] = strLine.substr(0, rightSpace);
for (cid = 1; cid < m_nColumns; cid++)
{
if (rightSpace == string::npos)
m_strArray[rid * m_nColumns + cid] = "0";
else
{
leftSpace = rightSpace;
rightSpace = strLine.find_first_of(" ", leftSpace + 1);
m_strArray[rid * m_nColumns + cid] = strLine.substr(leftSpace + 1, rightSpace - leftSpace - 1);
}
}
}
fclose(inf);
}
void GzFileInput::getHeader(string strHead[])
{
for (int h = 0; h < m_nHeadLen; h++) {
strHead[h] = m_strHeader[h];
}
}
void GzFileInput::getRow(int anRow[], int nRow)
{
for (int nC = 0; nC < m_nColumns; nC++) {
anRow[nC] = getInt(nRow, nC);
}
}
void GzFileInput::getRow(long alRow[], int nRow)
{
for (int nC = 0; nC < m_nColumns; nC++) {
alRow[nC] = getLong(nRow, nC);
}
}
void GzFileInput::getRow(double adRow[], int nRow)
{
for (int nC = 0; nC < m_nColumns; nC++) {
adRow[nC] = getFloat(nRow, nC);
}
}
void GzFileInput::getRow(string astrRow[], int nRow)
{
for (int nC = 0; nC < m_nColumns; nC++) {
astrRow[nC] = getString(nRow, nC);
}
}
void GzFileInput::getColumn(int anColumn[], int nCol)
{
int nR = 0;
while (nR < m_nFileLength - (int)m_bHeader)
{
//cout << "Get column, row: " << nR << endl;
anColumn[nR] = getInt(nR, nCol);
nR++;
}
}
//get column as long
void GzFileInput::getColumn(long alColumn[], int nCol)
{
int nR = 0;
while (nR < m_nFileLength - (int)m_bHeader)
{
alColumn[nR] = getLong(nR, nCol);
nR++;
}
}
//get column as double, (or float through implicit
void GzFileInput::getColumn(double adColumn[], int nCol)
{
int nR = 0;
while (nR < m_nFileLength - (int)m_bHeader)
{
adColumn[nR] = getFloat(nR, nCol);
nR++;
}
}
//get column as string
void GzFileInput::getColumn(string astrColumn[], int nCol)
{
int nR = 0;
while (nR < m_nFileLength - (int)m_bHeader)
{
astrColumn[nR] = getString(nR, nCol);
nR++;
}
}
int GzFileInput::getInt(int nRow, int nCol)
{
int nARow = nRow - m_nArrayLine1;
if (nARow < 0 || nARow >= m_nRows)
{
m_nArrayLine1 = nRow;
gzFillArray();
nARow = 0;
//cout << "Getting row: " << nRow << endl;
}
return atoi(m_strArray[nARow * m_nColumns + nCol].c_str());
}
long GzFileInput::getLong(int nRow, int nCol)
{
int nARow = nRow - m_nArrayLine1;
if (nARow < 0 || nARow >= m_nRows)
{
m_nArrayLine1 = nRow;
gzFillArray();
nARow = 0;
}
return atol(m_strArray[nARow * m_nColumns + nCol].c_str());
}
double GzFileInput::getFloat(int nRow, int nCol)
{
int nARow = nRow - m_nArrayLine1;
if (nARow < 0 || nARow >= m_nRows)
{
m_nArrayLine1 = nRow;
gzFillArray();
nARow = 0;
//cout << "Getting row: " << nRow << endl;
}
return atof(m_strArray[nARow * m_nColumns + nCol].c_str());
}
string GzFileInput::getString(int nRow, int nCol)
{
int nARow = nRow - m_nArrayLine1;
if (nARow < 0 || nARow >= m_nRows)
{
m_nArrayLine1 = nRow;
gzFillArray();
nARow = 0;
}
return m_strArray[nARow * m_nColumns + nCol];
}
int GzFileInput::getHeadInt(int nCol)
{
return atoi(m_strHeader[nCol].c_str());
}
long GzFileInput::getHeadLong(int nCol)
{
return atol(m_strHeader[nCol].c_str());
}
double GzFileInput::getHeadFloat(int nCol)
{
return atof(m_strHeader[nCol].c_str());
}
string GzFileInput::getHeadString(int nCol)
{
return m_strHeader[nCol].c_str();
}
<file_sep>/src/cuda/Makefile
# compilers
CXX=g++
NVCC=nvcc
# paths of cuda libraries
CUDAPATH=/software/cuda/10.0.130/usr/local/cuda-10.0/
# for cudpp:
#CUDASDKPATH=/usr/local/cuda/SDK/NVIDIA_GPU_Computing_SDK/C
# includes for header files
CXXINCLUDE=-I$(CUDAPATH)/include
CUDAINCLUDE=-I$(CUDAPATH)/include
# compiler flags: include all warnings, optimization level 3
CXXFLAGS=-O1 -DGOLD_FUNCS=0 -DSHEAR_INIT=0 -std=c++11
NVCCFLAGS=--ptxas-options=-v -O1 -arch=sm_35 -DGOLD_FUNCS=0
# linker flags: include all warnings, include library files
LDFLAGS=-Wall -lcudart -lcurand
#target_compile_options(strain PRIVATE -DSHEAR_INIT=1)
#target_compile_options(resize PRIVATE -DSHEAR_INIT=0)
# object files
CXXOBJECTS=spherocyl_box.o cudaErr.o dat_file_input.o
NVCCOBJECTS=find_neighbors.o calculate_stress_energy.o data_primitives_2.o strain_dynamics.o energy_minimize.o 2point_dynamics.o
# final executable
EXE=../../exe/spherocyl_box
RESZ=../../exe/spherocyl_resize
RELX=../../exe/spherocyl_relax
CJ=../../exe/spherocyl_cj_relax
QSC=../../exe/spherocyl_qs_compress
JAM=../../exe/spherocyl_findjam
MKCFG=../../exe/spherocyl_configs
TEST=../../exe/test
SRK2P=../../exe/spherocyl2p_compress
RSZ2P=../../exe/spherocyl2p_resize
QS2P=../../exe/spherocyl2p_quasistatic
FJ2P=../../exe/spherocyl2p_findjam
YJ2P=../../exe/spherocyl2p_ycompress
PURE=../../exe/spherocyl2p_pureshear
#PROF_EXE=../../exe/spherocyl_box_profile
#rules:
all: $(EXE) $(RESZ) $(MKCFG)
strain: $(EXE)
resize: $(RESZ)
relax: $(RELX)
cj: $(CJ)
qs: $(QSC)
jam: $(JAM)
mkconfigs: $(MKCFG)
cutest: $(TEST)
resz2p: $(RSZ2P)
qs2p: $(QS2P)
srk2p: $(SRK2P)
jam2p: $(FJ2P)
yjam2p: $(YJ2P)
pure: $(PURE)
#prof: $(PROF_EXE)
######################
# compile executable #
######################
$(EXE): $(CXXOBJECTS) $(NVCCOBJECTS) main.o
$(CXX) -o $(EXE) main.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
$(RESZ): $(CXXOBJECTS) $(NVCCOBJECTS) main_resize.o
$(CXX) -o $(RESZ) main_resize.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
$(RELX): $(CXXOBJECTS) $(NVCCOBJECTS) main_relax.o
$(CXX) -o $(RELX) main_relax.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
$(CJ): $(CXXOBJECTS) $(NVCCOBJECTS) main_cj_relax.o
$(CXX) -o $(CJ) main_cj_relax.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
$(QSC): $(CXXOBJECTS) $(NVCCOBJECTS) main_qs_compress.o
$(CXX) -o $(QSC) main_qs_compress.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
$(JAM): $(CXXOBJECTS) $(NVCCOBJECTS) main_1point_findjam.o
$(CXX) -o $(JAM) main_1point_findjam.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
$(RSZ2P): $(CXXOBJECTS) $(NVCCOBJECTS) main_2point_resize.o
$(CXX) -o $(RSZ2P) main_2point_resize.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
$(SRK2P): $(CXXOBJECTS) $(NVCCOBJECTS) main_2point_qscompress.o
$(CXX) -o $(SRK2P) main_2point_qscompress.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
$(FJ2P): $(CXXOBJECTS) $(NVCCOBJECTS) main_2point_findjam.o
$(CXX) -o $(FJ2P) main_2point_findjam.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
$(YJ2P): $(CXXOBJECTS) $(NVCCOBJECTS) main_2point_ycompress.o
$(CXX) -o $(YJ2P) main_2point_ycompress.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
$(PURE): $(CXXOBJECTS) $(NVCCOBJECTS) main_pure_shear.o
$(CXX) -o $(PURE) main_pure_shear.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
$(QS2P): $(CXXOBJECTS) $(NVCCOBJECTS) main_qs2p.o
$(CXX) -o $(QS2P) main_qs2p.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
$(MKCFG): $(CXXOBJECTS) $(NVCCOBJECTS) main_configmaker.o
$(CXX) -o $(MKCFG) main_configmaker.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
$(TEST): test.o $(CXXOBJECTS) $(NVCCOBJECTS)
$(CXX) -o $(TEST) test.o cudaErr.o $(LDFLAGS)
#$(PROF_EXE): $(CXXOBJECTS) $(NVCCOBJECTS) main_profile.o
# $(CXX) -o $(PROF_EXE) main_profile.o $(CXXOBJECTS) $(NVCCOBJECTS) $(LDFLAGS)
###################
# compile objects #
###################
#c++ files
main.o: main.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) -c main.cpp
main_resize.o: main_resize.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) -c main_resize.cpp
main_relax.o: main_relax.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) -c main_relax.cpp
main_cj_relax.o: main_cj_relax.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) -c main_cj_relax.cpp
main_qs_compress.o: main_qs_compress.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) -c main_qs_compress.cpp
main_1point_findjam.o: main_1point_findjam.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) -c main_1point_findjam.cpp
main_configmaker.o: main_configmaker.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) -c main_configmaker.cpp
main_qs2p.o: main_qs2p.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) -c main_qs2p.cpp
main_2point_resize.o: main_2point_resize.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) -c main_2point_resize.cpp
main_2point_qscompress.o: main_2point_qscompress.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) -c main_2point_qscompress.cpp
main_2point_findjam.o: main_2point_findjam.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) -c main_2point_findjam.cpp
main_2point_ycompress.o: main_2point_ycompress.cpp spherocyl_box.h 2point_dynamics.cu
$(CXX) $(CXXFLAGS) -c main_2point_ycompress.cpp
main_pure_shear.o: main_pure_shear.cpp spherocyl_box.h 2point_dynamics.cu
$(CXX) $(CXXFLAGS) -c main_pure_shear.cpp
test.o: test.cu cudaErr.h
$(NVCC) --ptxas-options=-v -arch=sm_35 -DGOLD_FUNCS=0 -c test.cu
#main_profile.o: main_profile.cpp spherocyl_box.h
# $(CXX) $(CXXFLAGS) $(CXXINCLUDE) -c main_profile.cpp
spherocyl_box.o: spherocyl_box.cpp spherocyl_box.h
$(CXX) $(CXXFLAGS) -c spherocyl_box.cpp
cudaErr.o: cudaErr.h cudaErr.cpp
$(CXX) $(CXXFLAGS) -c cudaErr.cpp
dat_file_input.o: file_input.h dat_file_input.cpp
$(CXX) $(CXXFLAGS) -c dat_file_input.cpp
#cuda files
find_neighbors.o: spherocyl_box.h data_primitives.h cudaErr.h find_neighbors.cu
$(NVCC) $(NVCCFLAGS) -c find_neighbors.cu
calculate_stress_energy.o: spherocyl_box.h cudaErr.h calculate_stress_energy.cu
$(NVCC) $(NVCCFLAGS) -c calculate_stress_energy.cu
strain_dynamics.o: spherocyl_box.h cudaErr.h strain_dynamics.cu
$(NVCC) $(NVCCFLAGS) -c strain_dynamics.cu
energy_minimize.o: spherocyl_box.h cudaErr.h energy_minimize.cu
$(NVCC) $(NVCCFLAGS) -c energy_minimize.cu
2point_dynamics.o: spherocyl_box.h cudaErr.h 2point_dynamics.cu
$(NVCC) $(NVCCFLAGS) -c 2point_dynamics.cu
data_primitives_2.o: data_primitives.h
$(NVCC) $(NVCCFLAGS) -c data_primitives_2.cu
#clean up object files or other assembly files
clean:
rm -f *.o *.ptx
<file_sep>/src/cuda/main_configmaker.cpp
/*
*
*
*/
#include "spherocyl_box.h"
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <iostream>
#include "file_input.h"
#include <string>
using namespace std;
const double D_PI = 3.14159265358979;
int int_input(int argc, char* argv[], int argn, char description[] = "")
{
if (argc > argn) {
int input = atoi(argv[argn]);
cout << description << ": " << input << endl;
return input;
}
else {
int input;
cout << description << ": ";
cin >> input;
return input;
}
}
double float_input(int argc, char* argv[], int argn, char description[] = "")
{
if (argc > argn) {
double input = atof(argv[argn]);
cout << description << ": " << input << endl;
return input;
}
else {
double input;
cout << description << ": ";
cin >> input;
return input;
}
}
string string_input(int argc, char* argv[], int argn, char description[] = "")
{
if (argc > argn) {
string input = argv[argn];
cout << description << ": " << input << endl;
return input;
}
else {
string input;
cout << description << ": ";
cin >> input;
return input;
}
}
int main(int argc, char* argv[])
{
int argn = 0;
string strDir = string_input(argc, argv, ++argn, "Output data directory");
const char* szDir = strDir.c_str();
cout << strDir << endl;
int nSpherocyls = int_input(argc, argv, ++argn, "Number of particles");
cout << nSpherocyls << endl;
int nConfigs = int_input(argc, argv, ++argn, "Number of configurations");
cout << nConfigs << endl;
double dPacking = float_input(argc, argv, ++argn, "Packing Fraction");
cout << dPacking << endl;
double dAspect = float_input(argc, argv, ++argn, "Aspect ratio (i.e. A/R or 2A/D)");
cout << dAspect << endl;
double dBidispersity = float_input(argc, argv, ++argn, "Bidispersity ratio: (1 for monodisperse)");
cout << dBidispersity << endl;
double dDR = 0.1;
double dR = 0.5;
double dA = dAspect*dR;
double dArea = 0.5*nSpherocyls*(1+dBidispersity*dBidispersity)*(4*dA + D_PI * dR)*dR;
double dL = sqrt(dArea / dPacking);
cout << "Box length L: " << dL << endl;
double dRMax = dBidispersity*dR;
double dAMax = dBidispersity*dA;
double dGamma = 0.;
double dTotalGamma = 0.;
Config sConfig = {RANDOM, -D_PI/2, D_PI/2, 0};
int tStart = time(0);
Spherocyl_Box cSpherocyls(nSpherocyls, dL, dAspect, dBidispersity, sConfig, dDR);
cout << "Spherocyls initialized" << endl;
cSpherocyls.set_gamma(dGamma);
cSpherocyls.set_total_gamma(dTotalGamma);
cSpherocyls.set_data_dir(szDir);
cout << "Configuration set" << endl;
cSpherocyls.get_0e_configs(nConfigs, dBidispersity);
int tStop = time(0);
cout << "\nRun Time: " << tStop - tStart << endl;
return 0;
}
<file_sep>/src/cuda/spherocyl_box.h
/* spherocyl_box.h
*
* Arrays with the prefix "h_" are allocated on the host (CPU),
* those with the prefix "d_" are allocated on the device (GPU).
* Anything starting with "g_" is solely used in "gold" functions
* on the cpu (for error checking) and will only be compiled if
* the environmental variable GOLD_FUNCS=1
*
*/
#ifndef GOLD_FUNCS
#define GOLD_FUNCS 0
#endif
#ifndef SHEAR_INIT
#define SHEAR_INIT 0
#endif
#ifndef SPHEROCYL_BOX_H
#define SPHEROCYL_BOX_H
#include <stdio.h>
#include <string.h>
enum Potential {HARMONIC = 2, HERTZIAN = 5};
enum initialConfig {RANDOM_UNALIGNED, RANDOM_UNIFORM, RANDOM_ALIGNED, ZERO_E_UNALIGNED, ZERO_E_UNIFORM, ZERO_E_ALIGNED, GRID_UNALIGNED, GRID_UNIFORM, GRID_ALIGNED, OTHER};
enum configType {RANDOM, GRID};
struct Config {
configType type;
configType angleType;
double minAngle;
double maxAngle;
double overlap;
};
class Spherocyl_Box
{
private:
int m_nSpherocyls;
double m_dLx; // Box side length
double m_dLy;
double m_dPacking; // Packing fraction
double m_dGamma; // Strain parameter
double m_dTotalGamma;
Potential m_ePotential; // Soft core interaction (harmonic or hertzian)
double m_dStrainRate;
double m_dStep;
double m_dMove;
double m_dKd; // Dissipative constant
// file output data
FILE *m_pOutfSE; // output steam
const char *m_szDataDir; // directory to save data (particle configurations)
const char *m_szFileSE; // filename for stress energy data
// Coordinates etc. for spherocyls
double m_dRMax; // Largest radius
double m_dAMax; // Largest spherocylinder half-shaft
double m_dASig; // Relative sigma in width of aspect distribution
// Position and orientation arrays to be allocated on the CPU (host)
double *h_pdX;
double *h_pdY;
double *h_pdPhi;
double *h_pdR; // Radii
double *h_pdA;
int *h_pnMemID; // IDs of particles reordered in memory
int *h_bNewNbrs;
// Position and orientation arrays to be allocated on the GPU (device)
double *d_pdX;
double *d_pdY;
double *d_pdPhi;
double *d_pdR;
double *d_pdA;
double *d_pdArea;
double *d_pdMOI; // Moment of Inertia
double *d_pdIsoC; // Coefficient for isolated rotation function
bool m_bMOI;
double *d_pdTempX; // Temporary positions used in several routines
double *d_pdTempY; // only needed on the device
double *d_pdTempPhi;
double *d_pdXMoved; // Amount each spherocylinder moved since last finding neighbors
double *d_pdYMoved;
double *d_pdDx; // Search directions Dx, Dy, Dt used for minimization routines
double *d_pdDy;
double *d_pdDt;
int *d_pnInitID; // The original ID of the particle
int *d_pnMemID; // ID of the current location of the particle in memory
int *d_bNewNbrs; // Set to 1 when particle moves more than dEpsilon
// Arrays for "gold" routines (for testing)
#if GOLD_FUNCS == 1
double *g_pdX;
double *g_pdY;
double *g_pdPhi;
double *g_pdR;
double *g_pdA;
double *g_pdTempX;
double *g_pdTempY;
double *g_pdTempPhi;
int *g_pnInitID;
int *g_pnMemID;
double *g_pdXMoved;
double *g_pdYMoved;
int *g_bNewNbrs;
#endif
// Stresses and forces
float *m_pfEnergy;
float *m_pfPxx;
float *m_pfPyy;
float *m_pfPxy;
float *m_pfPyx;
float m_fP; // Total pressure
float *h_pfSE; // Array for transfering the stresses and energy
double *h_pdBlockSums;
double *h_pdLineEnergy;
double *h_pdEnergies;
double *h_pdFx;
double *h_pdFy;
double *h_pdFt;
// GPU
float *d_pfSE;
double *d_pdBlockSums;
double *d_pdEnergies;
double *d_pdFx;
double *d_pdFy;
double *d_pdFt;
double *d_pdTempFx;
double *d_pdTempFy;
double *d_pdTempFt;
#if GOLD_FUNCS == 1
float *g_pfSE;
double *g_pdFx;
double *g_pdFy;
double *g_pdFt;
#endif
// These variables are used for spatial subdivision and
// neighbor lists for faster contact detection etc.
int m_nCells;
int m_nCellRows;
int m_nCellCols;
double m_dCellW; // Cell width
double m_dCellH; // Cell height
int *h_pnCellID; // Cell ID for each particle
int *h_pnAdjCells; // Which cells are next to each other
int m_nMaxPPC; // Max particles per cell
int *h_pnPPC; // Number of particles in each cell
int *h_pnCellList; // List of particles in each cell
int m_nMaxNbrs; // Max neighbors a particle can have
int *h_pnNPP; // Number of neighbors (possible contacts) of each particle
int *h_pnNbrList; // List of each particle's neighbors
// GPU arrays
int *d_pnCellID;
int *d_pnAdjCells;
int *d_pnPPC;
int *d_pnCellList;
int *d_pnNPP;
int *d_pnNbrList;
#if GOLD_FUNCS == 1
int *g_pnCellID;
int *g_pnAdjCells;
int *g_pnPPC;
int *g_pnCellList;
int *g_pnNPP;
int *g_pnNbrList;
#endif
// Used to not have to update neighbors every step when things are moving
double m_dEpsilon;
// These variables define configurations for kernel cuda kernel launches
int m_nGridSize; // Grid size (# of thread blocks) for finding cell IDs
int m_nBlockSize; // Block size (# threads per block)
int m_nSM_CalcF;
int m_nSM_CalcSE; // Shared memory per block
int m_nDeviceMem;
void construct_defaults();
void configure_cells();
void configure_cells(double dMaxGamma);
void reconfigure_cells();
void reconfigure_cells(double dMaxGamma);
void set_kernel_configs();
double calculate_packing();
void set_shapes(int seed, double dBidispersity);
void strain_step(long unsigned int nTime, bool bSvStress = 0, bool bSvPos = 0);
void strain_step_2p(long unsigned int nTime, bool bSvStress = 0, bool bSvPos = 0);
void pure_strain_step_2p(long unsigned int nTime, bool bSvStress = 0, bool bSvPos = 0);
void strain_step_ngl(long unsigned int nTime, bool bSvStress = 0, bool bSvPos = 0);
void resize_step(long unsigned int tTime, double dEpsilon, bool bSvStress, bool bSvPos);
void resize_step_2p(long unsigned int tTime, double dEpsilon, bool bSvStress, bool bSvPos);
void y_resize_step_2p(long unsigned int tTime, double dEpsilon, bool bSvStress, bool bSvPos);
void relax_step(unsigned long int nTime, bool bSvStress, bool bSvPos);
void relax_step_2p(unsigned long int nTime, bool bSvStress, bool bSvPos);
int cjfr_relax_step(double dMinStep, double dMaxStep);
int cjpr_relax_step(double dMinStep, double dMaxStep, double dAngleDampling);
int cjpr_relax_step_2p(double dMinStep, double dMaxStep);
int new_cjpr_relax_step_2p(double dMinStep, double dMaxStep);
int gradient_descent_step_2p(double dMinStep, double dMaxStep);
int force_cjpr_relax_step(double dMinStep, double dMaxStep, bool bAngle);
int gd_relax_step(double dMinStep, double dMaxStep);
int force_line_search(bool bFirstStep, bool bSecondStep, double dMinStep, double dMaxStep);
int line_search(bool bFirstStep, bool bSecondStep, double dMinStep, double dMaxStep);
int line_search_2p(bool bFirstStep, bool bSecondStep, double dMinStep, double dMaxStep);
int new_line_search_2p(double dMinStep, double dMaxStep);
int qs_one_cycle(int nTime, double dMaxE, double dResizeStep, double dMinStep);
int resize_to_energy_2p(int nTime, double dEnergy, double dResizeStep);
int y_resize_to_energy_2p(int nTime, double dEnergy, double dResizeStep);
int resize_relax_step_2p(int nTime, double dStep, int nMaxCJSteps = 2000000);
int resize_to_energy_1p(int nTime, double dEnergy, double dResizeStep);
void flip_group();
double uniformToAngleDist(double dUniform, double dAspect);
public:
Spherocyl_Box(int nSpherocyls, double dL, double dAspect, double dBidispersity,
Config config, double dEpsilon = 0.1, double dASig = 0, int nMaxPPC = 18,
int nMaxNbrs = 45, Potential ePotential = HARMONIC);
Spherocyl_Box(int nSpherocyls, double dLx, double dLy, double dAspect,
double dBidispersity, Config config, double dEpsilon = 0.1, double dASig = 0,
int nMaxPPC = 18, int nMaxNbrs = 45, Potential ePotential = HARMONIC);
Spherocyl_Box(int nSpherocyls, double dL, double *pdX, double *pdY, double *pdPhi,
double *pdR, double *pdA, double dEpsilon = 0.1,
int nMaxPPC = 18, int nMaxNbrs = 45, Potential ePotential = HARMONIC);
Spherocyl_Box(int nSpherocyls, double dLx, double dLy, double *pdX, double *pdY,
double *pdPhi, double *pdR, double *pdA, double dEpsilon = 0.1,
int nMaxPPC = 18, int nMaxNbrs = 45, Potential ePotential = HARMONIC);
~Spherocyl_Box();
void save_positions(long unsigned int nTime);
void save_positions_bin(long unsigned int nTime);
void place_random_spherocyls(int seed = 0, bool bRandAngle = 1, double dBidispersity = 1);
void place_random_0e_spherocyls(int seed = 0, bool bRandAngle = 1, double dBidispersity = 1);
void place_spherocyl_grid(int seed = 0, bool bRandAngle = 0);
void place_spherocyls(Config config, int seed = 0, double dBidispersity = 1);
void get_0e_configs(int nConfigs, double dBidispersity);
void find_neighbors();
void set_back_gamma();
void flip_shear_direction();
void rotate_by_gamma();
void reorder_particles();
void reset_IDs();
void calculate_stress_energy();
void calculate_stress_energy_2p();
bool check_for_contacts();
bool check_for_contacts(int nIndex, double dTol = 0);
bool check_for_crosses(int nIndex, double dEpsilon = 1e-5);
void run_strain(double dStartGam, double dStopGam, double dSvStressGam, double dSvPosGam);
void run_strain_2p(double dStartGam, double dStopGam, double dSvStressGam, double dSvPosGam);
void run_pure_strain_2p(long unsigned int nStart, double dAspectStop, double dSvStressGam, double dSvPosGam);
void run_strain(long unsigned int nStart, double dRunGamma, double dSvStressGam, double dSvPosGam);
void run_strain_2p(long unsigned int nStart, double dRunGamma, double dSvStressGam, double dSvPosGam);
void run_strain(long unsigned int nSteps);
void run_strain_2p(long unsigned int nSteps);
void run_strain(double dGammaMax);
void resize_box(long unsigned int nStart, double dEpsilon, double dFinalPacking, double SvStressRate, double dSvPosRate);
void resize_box_2p(long unsigned int nStart, double dEpsilon, double dFinalPacking, double SvStressRate, double dSvPosRate);
void relax_box(unsigned long int nSteps, double dMaxStep, double dMinStep, int nStressSaveInt, int nPosSaveInt);
void relax_box_2p(unsigned long int nSteps, double dMaxStep, double dMinStep, int nStressSaveInt, int nPosSaveInt);
void cjfr_relax(double dMinStep, double dMaxStep);
void cjpr_relax(double dMinStep, double dMaxStep, int nMaxSteps, double dAngleDamping);
void cjpr_relax_2p(double dMinStep, double dMaxStep, int nMaxSteps);
void gradient_relax_2p(double dMinStep, double dMaxStep, int nMaxSteps);
void force_cjpr_relax(double dMinStep, double dMaxStep, int nMaxSteps);
void gd_relax(double dMinStep, double dMaxStep);
void quasistatic_compress(double dMaxPack, double dResizeStep, double dMinStep);
void compress_qs2p(double dMaxPacking, double dResizeStep);
void expand_qs2p(double dMinPacking, double dResizeStep);
void quasistatic_cycle(int nCycles, double dMaxE, double dResizeStep, double dMinStep);
void quasistatic_find_jam(double dMaxE, double dMinE, double dResizeStep, double dMinStep);
void find_jam_2p(double dJamE, double dResizeStep);
void y_compress_energy_2p(double dTargetE, double dResizeStep);
void find_energy_2p(double dResizeStep, double dMinResizeStep, int nMaxSteps);
void find_jam_1p(double dJamE, double dResizeStep);
#if GOLD_FUNCS == 1
void calculate_stress_energy_gold();
#endif
void display(bool bParticles = 1, bool bCells = 1, bool bNbrs = 1, bool bStress = 1);
// Functions for setting parameters after initialization
void set_gamma(double dGamma) { m_dGamma = dGamma; }
void set_total_gamma(double dTotalGamma) { m_dTotalGamma = dTotalGamma; }
void set_step(double dStep) { m_dStep = dStep; }
void set_strain(double dStrain) { m_dStrainRate = dStrain; }
void set_Kd(double dKd) { m_dKd = dKd; } // Set dissipative constant
void set_data_dir(const char *szDataDir) { m_szDataDir = szDataDir; }
void set_se_file(const char *szFileSE) { m_szFileSE = szFileSE; }
};
#endif
|
cc6081206a45639e927d0483fc637e2125e08407
|
[
"C",
"Makefile",
"C++",
"Shell"
] | 32 |
C++
|
tmarschall/spherocyls
|
35b4c6736bb4576d5bd4be880821f192d0e3b506
|
2c5243a64e6fb08079dce21ab3b49f5e6b7c8936
|
refs/heads/master
|
<repo_name>jonmarkprice/McIlroy-parser<file_sep>/tests/parse-string.test.js
const test = require('tape');
const parseString = require('../src/parse-string');
const { Right, Left, fromEither } = require('sanctuary');
test('literal values', assert => {
assert.deepEqual(
parseString('42'),
Right({token: 'Value', type: {name: 'Number'}, value: 42}));
assert.deepEqual(
parseString("'x'"),
Right({token: 'Value', type: {name: 'Char'}, value: 'x'}));
assert.deepEqual(
parseString(""),
Left('No input.'));
assert.end();
})
test('functions', assert => {
const fn = fromEither({}, parseString('+'));
assert.equal(fn.token, 'Value');
assert.equal(fn.type.name, 'Function');
assert.equal(fn.value.display, '+');
assert.equal(fn.value.arity, 2);
assert.end();
});
<file_sep>/src/cli.js
const readline = require('readline');
const parseString = require('./parse-string');
const { parser } = require('./program');
const display = require('./display');
const S = require('sanctuary');
const { Right } = S;
const appendRight = S.lift2(list => elem => S.append(elem, list));
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: '> '
});
rl.prompt();
rl.on('line', (line) => {
const fragments = line.trim().split(' ');
// const tokens = fragments.map(parseString);
const tokens = S.pipe([
// line.trim().split(' '),
S.map(parseString),
S.reduce(appendRight, Right([]))
])(fragments);
// const tokens = S.reduce(appendRight, Right([]), _);
//const result = parseProgram(tokens);
const result = S.map(parser, tokens);
// console.log(fragments);
// console.log(tokens);
// console.log(t2);
// console.log(result);
console.log("----------------------------");
if (S.isLeft(result)) {
console.log(S.fromEither('', result));
console.log(S.either(S.I, S.K(''), result));
}
const steps = S.either(S.K([]), S.prop('steps'), result);
steps.forEach((step, index) => {
const width = 3 - Math.floor(Math.log(index + 1) / Math.log(10));
const padding = ' '.repeat(width);
console.log(`${index + 1}.${padding} ${step.join(' ')}`);
});
rl.prompt();
})
.on('close', () => {
console.log('bye');
process.exit(0);
});
<file_sep>/src/parse-string.js
const { t } = require('./tokens');
const library = require('./library');
const { Right, Left } = require('sanctuary');
// tokenize_
// generator?
function parseString(str) {
if (str === '') {
return Left("No input.");
}
else if (str === ':') {
return Right({value: ':', token: 'Syntax'});
}
else if (str === 'true') {
return Right({value: true, type: t.bool, token: 'Value'});
}
else if (str === 'false') {
return Right({value: false, type: t.bool, token: 'Value'});
}
else if (str === '[]') {
return Right({value: [], type: t.list, token: 'Value'});
}
else if (/'.'/.test(str)) {
return Right({value: str[1], type: t.char, token: 'Value'});
}
// TODO: Maybe add some sugar for strings
//else if (/".*"/.test(str)) {
// return {type: 'string'};
//}
else if (! Number.isNaN(Number(str))) {
return Right({value: Number(str), type: t.num, token: 'Value'});
}
// TODO similarly, scan aliases
else if (library.has(str)) {
return Right({value: library.get(str), type: t.fn, token: 'Value'});
}
else {
//throw new Error('Invalid token');
return Left(`Invalid token: ${str}.`);
}
}
module.exports = parseString;
<file_sep>/tests/steps.test.js
const test = require('tape');
const { parseProgram } = require('../src/program.js');
const { tokenize_ } = require('../src/tokenize');
test('one step', (assert) => {
assert.deepEqual(
parseProgram([1, 2, '+', ':']).steps,
[
["1", "2", "+", ":"], // or similar
["3"]
]
);
assert.end();
});
// multiple step (a la. some integration tests)
// Before implementing createSteps:
// 1. fix / decide on tokenize
// 2. decide on how to handle failure
// 3. decide where 'steps' should go.
/*
Here's my intuition: I needed to have steps in the accumulator to deal with alias expansion.
How did I do it before? I can't remember, but I do know that, before aliases, a program was
guaranteed to take only as many steps as :. How does this change with aliases?
With an alias, one might do:
[14, 23, 45] average :
-> [14, 23, 45] [sum, len] into : / apply :
-> [82, 3] / apply :
-> 27.3
This could have been even worse if we would have expanded sum, but currently we
are not (planning to) expand applicatives.
I might leave each token in a step as a token, or I might map display over them.
--
Technically, a single token on the stack can fail, but the stack itself may not
..., or maybe it could.., depends on how we look at things. If a token faild,
really that would basically just be a null or a Nothing... the thing is, once I
know a computation will fail, as a do as soon as we encounter a bottom (⊥) know
the computation will fail, so there is no reason to add a check to each
function, better to just use an Either or Maybe, and since we pass the function
a *slice* of the stack, it becomes easier to make the whole stack a functor.
On the other hand, I could use sequence (with Sanctuary) to pass the arguments
individually.
The real question here however, is whether the Either should be even "higher"
than that, i.e. over the whole accumulator. If it is not I can pass an object
containing a list of steps and an Either<err, stack> -- alternatively, I can
keep tthe steps somewhere else, or make functions that have side effects.
This does not seem to be the best way to go about it though. A third option
would be to make the steps be overwritten by the error. This is probably fine
for now, as far as I am concerned, ideally (at some later date) we would have
the ability to pinpoint where everything went wrong, by keeping the steps
separate from the Either -- or changing the structure of the either so that
it would save the current information in the Left.
This might be nice anyway, so that we could see a chain of errors, instead of
getting the newest/oldest only.
TODO: See explorations/../sanctuary/maybe-nesting.js for some tests.
CONCLUSIONS: In short flatter is better for access, harder for R.over/R.set because it breaks
the lensProp chain.
*/
|
f95d1bf3bf62f0d9846def79e3da2c3251ed4707
|
[
"JavaScript"
] | 4 |
JavaScript
|
jonmarkprice/McIlroy-parser
|
19d6d2c2bc4c232018e68a73adb4d97e90c9f454
|
6ed006d490a3fee2e3181a6e8a30a089969c281e
|
refs/heads/master
|
<file_sep>package utils;
import base.RestSpecs;
import io.vavr.Lazy;
import org.junit.jupiter.params.aggregator.ArgumentsAccessor;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
public interface TestUtils {
Lazy<String> configSync = Lazy.of(() -> "src/test/resources/sync-get.conf");
Lazy<String> configFile = Lazy.of(() -> "src/test/resources/modelo.conf");
Lazy<String> httpBinBaseURL = Lazy.of(() -> "https://httpbin.org");
Lazy<String> googleBaseURL = Lazy.of(() -> "http://www.google.com");
Lazy<Map<String,Object>> headers = Lazy.of(() -> Map.of("Content-Type", "application/json"));
BiPredicate<List<String>, List<String>> equalsList = (list, list2) ->
list2.containsAll(list);
BiPredicate<String, Map<String, Object>> containsOn = (str, objects) ->
objects.values().stream().allMatch(o -> str.contains(String.valueOf(o)));
BiPredicate<Map<String, Object>, Map<String, Object>> containsOnMap = (map1, map2) ->
map2.values().containsAll(map1.values());
Function<TestSourceTemplate,List<String>> setParams = (data) -> Arrays.asList(data.getQueryParams().replaceAll("[^a-zA-Z0-9,]","").split(","));
BiFunction<ArgumentsAccessor, RestSpecs, RestSpecs> updateRestSpecs = (data, specs) ->
new RestSpecs(specs.getBaseUrl().toString(), data.getString(0), specs.getHeadersMap(), specs.getQueryParams(), specs.getPathParams(),"", data.getString(1));
}
<file_sep><h3>Projeto modelo para teste de API Rest com base funções pré-definidas.</h3>
@Author: <NAME>
@License: Apache 2
[](https://circleci.com/gh/tcanascimento/functional-rest/tree/master)
Foram implementados duas interfaces:
- uma conjunto de Funções para Request Assíncronos com assinatura:
```java
Function<RestSpecs, HttpResponse> asyncRequestGET = (specs) ->
(HttpResponse) Try.of(() ->
specs.getBaseClient().sendAsync(
requestGET.apply(specs),
specs.getResponseBodyHandler()
).get()
).getOrNull();
```
- um conjunto de Funções, uma para cada método, de assinatura similar, porém, Síncronas:
```java
Function<RestSpecs, HttpResponse> syncResquestGET = (specs) ->
Try.of(() ->
specs.getBaseClient().send(requestGET.apply(specs), specs.getResponseBodyHandler())
).getOrNull();
```
Um teste fazendo uso dessa função tem o seguinte formato:
````java
@Tag("Function")
@DisplayName("Aplicando Function")
@Test
void testFunction(){
AtomicReference<HttpResponse> response = new AtomicReference<>();
response.lazySet(Lazy.val(()-> syncRequestPost.apply(restSpecs()), HttpResponse.class));
assertAll("valida dia feliz",
() -> assertNotNull(response.get()),
() -> assertNotNull(response.get().headers().firstValue("x-access-token"))
);
}
````
assertAll("valida dia feliz",
() -> assertNotNull(response.get()),
() -> assertNotNull(response.get().headers().firstValue("x-access-token")));
}
</code></pre>
<p>Para executar testes com uma <i>tag</i> específica, por exemplo 'auth', execute via terminal: <code>gradle clean test -Dtag="auth"</code>. </p>
<p>Consulte a <a href="https://junit.org/junit5/docs/current/user-guide/#writing-tests-tagging-and-filtering">documentação oficial do Junit5</a> para maiores informações.</p>
<p><a href="https://tcanascimento.github.io/functional-rest/">GitHub Page</a></p>
<file_sep>package pojo;
public class Dummy {
private String name;
public Dummy(String name){
this.name = name;
}
public Dummy(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Dummy{" +
"name='" + name + '\'' +
'}';
}
}
<file_sep>package utils;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.params.aggregator.ArgumentsAccessor;
import org.junit.jupiter.params.aggregator.ArgumentsAggregationException;
import org.junit.jupiter.params.aggregator.ArgumentsAggregator;
public class TestTemplateAggregator implements ArgumentsAggregator {
@Override
public Object aggregateArguments(ArgumentsAccessor accessor, ParameterContext context) throws ArgumentsAggregationException {
return new TestSourceTemplate(
accessor.getString(0),
accessor.getString(1),
accessor.getString(2),
accessor.getString(3),
accessor.getString(4),
accessor.getString(5),
accessor.getString(6)
);
}
}
<file_sep>package utils;
import org.junit.jupiter.params.aggregator.AggregateWith;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@AggregateWith(TestTemplateAggregator.class)
public @interface CsvTestTemplate {
}
<file_sep>package base;
/**
* author: <NAME>
* license: Apache2
*/
import functions.BaseUtils;
import java.util.Map;
import java.util.function.Consumer;
/**
* Builder funcional para RestSpecs.
* Exemplo de uso:
* RestSpecs teste = new RestSpecsBuilder().with(
* $ -> {
* $.baseUrl = URI.create(uri);
* $.headers = h;
* $.baseClient = client;
* }).createSpecsOld();
*/
public class RestSpecsBuilder implements BaseUtils {
public Map<String, Object> queryParams;
public Map<String, Object> pathParams;
public Map<String, Object> headersParams;
public String baseUrl2;
public String endpoint2;
public String bodyString;
public String requestMethod;
public RestSpecsBuilder with(Consumer<RestSpecsBuilder> builderFunction) {
builderFunction.accept(this);
return this;
}
public RestSpecs createSpecs(){
return new RestSpecs(baseUrl2, endpoint2, headersParams, queryParams, pathParams, bodyString, requestMethod);
}
}
<file_sep>package functions;
/**
* author: <NAME>
* license: Apache2
*/
import base.RestSpecs;
import io.vavr.API;
import java.net.http.HttpRequest;
import java.util.function.Function;
import static io.vavr.API.$;
import static io.vavr.API.Case;
@Deprecated(forRemoval = true)
public interface HttpFunctions {
Function<RestSpecs, HttpRequest> requestGET = specs ->
HttpRequest
.newBuilder()
.uri(specs.getURI())
.timeout(specs.getTimeout())
.headers(specs.getHeaders())
.GET().build();
Function<RestSpecs, HttpRequest> requestDELETE = specs ->
HttpRequest
.newBuilder()
.uri(specs.getURI())
.timeout(specs.getTimeout())
.headers(specs.getHeaders())
.DELETE().build();
Function<RestSpecs, HttpRequest> requestPOST = specs ->
HttpRequest
.newBuilder()
.uri(specs.getURI())
.timeout(specs.getTimeout())
.headers(specs.getHeaders())
.POST(specs.getBody()).build();
Function<RestSpecs, HttpRequest> requestPUT = specs ->
HttpRequest
.newBuilder()
.uri(specs.getURI())
.timeout(specs.getTimeout())
.headers(specs.getHeaders())
.PUT(specs.getBody()).build();
Function<String, Function<RestSpecs, HttpRequest>> getRequestFunction = requestMethod ->
API.Match(requestMethod.toUpperCase()).of(
Case($("GET"), requestGET),
Case($("POST"), requestPOST),
Case($("PUT"), requestPUT),
Case($("DELETE"), requestDELETE));
}
<file_sep>package pojo.temp;
public class SyncResp{
private Args args;
private Headers headers;
private String data;
private Form form;
private String origin;
private Files files;
private Object json;
private String url;
public void setArgs(Args args){
this.args = args;
}
public Args getArgs(){
return args;
}
public void setHeaders(Headers headers){
this.headers = headers;
}
public Headers getHeaders(){
return headers;
}
public void setData(String data){
this.data = data;
}
public String getData(){
return data;
}
public void setForm(Form form){
this.form = form;
}
public Form getForm(){
return form;
}
public void setOrigin(String origin){
this.origin = origin;
}
public String getOrigin(){
return origin;
}
public void setFiles(Files files){
this.files = files;
}
public Files getFiles(){
return files;
}
public void setJson(Object json){
this.json = json;
}
public Object getJson(){
return json;
}
public void setUrl(String url){
this.url = url;
}
public String getUrl(){
return url;
}
@Override
public String toString(){
return
"SyncResp{" +
"args = '" + args + '\'' +
",headers = '" + headers + '\'' +
",data = '" + data + '\'' +
",form = '" + form + '\'' +
",origin = '" + origin + '\'' +
",files = '" + files + '\'' +
",json = '" + json + '\'' +
",url = '" + url + '\'' +
"}";
}
}
<file_sep>package functions;
import io.vavr.Lazy;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import pojo.Dummy;
import utils.MessageSupplier;
import utils.TestUtils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
@Tag("utils")
class BaseUtilsTest implements BaseUtils, TestUtils, MessageSupplier, Helpers {
private Lazy<String> baseURL = Lazy.of(() -> "https://www.gateway-empresa.com");
private Lazy<String> endpoint = Lazy.of(() -> "/rels/{cnpj}/something/lanc/{conta}");
private Lazy<Map<String, Object>> headers = Lazy.of(() -> Map.of("Content-Type", "application/x-www-form-urlencoded", "client_id", "CLIENTE_ID", "access_token", "<KEY>));
private Lazy<Map<String, Object>> queryPars = Lazy.of(() -> Map.of( "mesInicial", 1, "ano", 2019,"mesFinal", 12 )); //
private Lazy<Map<String, Object>> pathPars = Lazy.of(() -> Map.of("cnpj","12312312312312", "conta", "2.01.01.01.10"));
@Test
@Tag("updates")
void updatesTest(){
var specs = specsFromFile.apply(configFile.get());
Map<String, Object> tempPathPars = new HashMap<>(pathPars.get());
Map<String, Object> tempQuery = new HashMap<>(queryPars.get());
tempPathPars.put("cnpj", "1234567890");
tempQuery.put("mesFinal", 13);
var updatePath = updatePathParams.apply(tempPathPars, specs);
var updateQuery = updateQueryParams.apply(tempQuery, specs);
var tempEndpoint = endpoint.get().concat("/nada");
var updatedEndpoint = updateEndpoint.apply(tempEndpoint, specs);
var tempBody = clazzToJson.apply(new Dummy("new Body"));
var updatedBody = updateBody.apply(tempBody, specs);
assertAll("Updates test",
() -> assertNotNull(updatePath, objectConstructError.get()),
() -> assertNotNull(updateQuery, objectConstructError.get()),
() -> assertNotNull(updatedEndpoint, objectConstructError.get()),
() -> assertNotNull(updatedBody, objectConstructError.get()),
() -> assertNotNull(updatedBody.getBody(), notNull.get()),
() -> assertEquals("1234567890", tempPathPars.get("cnpj"), objectContentEquals.get()),
() -> assertEquals(13, tempQuery.get("mesFinal"), objectContentEquals.get()),
() -> assertEquals(updatePath.getPathParams(), tempPathPars, objectContentEquals.get()),
() -> assertEquals(updateQuery.getQueryParams(), tempQuery, objectContentEquals.get()),
() -> assertEquals("/rels/{cnpj}/something/lanc/{conta}/nada",updatedEndpoint.getRawEndpoint(), objectContentEquals.get())
);
}
//updateQueryParams
@Tag("specs")
@Test
void loadConfigFileTest(){
var specs = specsFromFile.apply(configFile.get());
var formatedEndpoint = queryParametersComposition.apply(setPathParameters.apply(endpoint.get(), pathPars.get()), queryPars.get());
assertAll("Load ConfigFile Test",
() -> assertNotNull(specs, loadFileError.get()),
() -> assertEquals(baseURL.get(), specs.getBaseUrl().toString(), urlMustBeEqual.get()),
() -> assertEquals(headers.get(), specs.getHeadersMap(), matchHeaders.get()),
() -> assertEquals(endpoint.get(), specs.getRawEndpoint(), endpointFormatError.get()),
() -> assertFalse(formatedEndpoint.contains("{cnpj}"), endpointFormatError.get()),
() -> assertEquals(queryPars.get(), specs.getQueryParams(), matchQueryPars.get()),
() -> assertEquals(pathPars.get(), specs.getPathParams(), matchPathPars.get()),
() -> assertNotNull(specs.getURI()));
}
@Tag("path")
@Test
void pathParametersTest(){
var formatedPath = setPathParameters.apply(endpoint.get(), pathPars.get());
var expected = "/rels/12312312312312/something/lanc/2.01.01.01.10";
assertAll(
() -> assertNotNull(formatedPath, objectConstructError.get()),
() -> assertEquals(expected, formatedPath, nonParameters.get()));
}
@Tag("array")
@Test
void mapToStringArrayTest(){
Map<String, Object> basePars = Map.of("par1", "par2", "par3", "par4");
String[] expected = {"par1", "par2", "par3", "par4"};
var res = mapToStringArray.apply(basePars);
assertAll(
() -> assertNotNull(res, notNull.get()),
() -> assertEquals(expected.length, res.length, objectContentEquals.get()),
() -> assertTrue(equalsList.test(Arrays.asList(expected), Arrays.asList(res)), objectContentEquals.get()));
}
@Tag("empty-array")
@Test
void mapToStringEmptyArrayTest(){
Map<String, Object> basePars = Map.of();
String[] expected = {};
var res = mapToStringArray.apply(basePars);
assertAll(
() -> assertNotNull(res, notNull.get()),
() -> assertEquals(expected.length, res.length, objectContentEquals.get()),
() -> assertTrue(equalsList.test(Arrays.asList(expected), Arrays.asList(res)), objectContentEquals.get()));
}
@Tag("query")
@Test
void queryParsCompositionTest(){
var res = queryParametersComposition.apply(endpoint.get(), queryPars.get());
assertAll(
() -> assertNotNull(res, notNull.get()),
() -> assertTrue(res.length() >= endpoint.get().length(), objectContentEquals.get()),
() -> assertTrue(containsOn.test(res, queryPars.get()), objectContentEquals.get()));
}
@Tag("map")
@Test
void mapFromStringTest(){
var str = "{\"ano\": 2019, \"mesInicial\": 1 , \"mesFinal\": 12}";
var res = generateMapFromString.apply(str);
Set<String> keys = Set.of("\"ano\"", "\"mesInicial\"", "\"mesFinal\"");
Set<String> values = Set.of(String.valueOf(2019), String.valueOf(1), String.valueOf(12));
assertAll(
() -> assertNotNull(res, notNull.get()),
() -> assertSame(res.getClass(), HashMap.class, objectMapType.get()),
() -> assertTrue(res.keySet().containsAll(keys)),
() -> assertTrue(res.values().containsAll(values))
);
}
}<file_sep>package base;
import functions.BaseUtils;
import functions.Helpers;
import functions.HttpFunctions;
import functions.RestFunctions;
import io.vavr.Lazy;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Tags;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.aggregator.ArgumentsAccessor;
import org.junit.jupiter.params.provider.CsvFileSource;
import pojo.ResponseObject;
import utils.MessageSupplier;
import utils.TestUtils;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
@Tag("specs")
class RestSpecsTest implements RestFunctions, Helpers, BaseUtils, HttpFunctions, TestUtils, MessageSupplier {
@Tag("builder")
@Test
void specsBuilderWithTwoParametersTest(){
var specs2 = new RestSpecsBuilder().with(
$ -> {
$.baseUrl2 = googleBaseURL.get();
$.headersParams = headers.get();
$.bodyString = "";
$.requestMethod = "get";
}).createSpecs();
assertAll("Just BaseURL and Headers from Builder",
() -> assertNotNull(specs2),
() -> assertTrue(specs2.getURI().toString().equalsIgnoreCase(googleBaseURL.get())),
() -> assertEquals(2, specs2.getHeaders().length));
}
@Tag("specs-from-file")
@Test
void specsConstructorTest(){
var specs = specsFromFile.apply(configFile.get());
assertAll("Load Specs from Config File",
() -> assertNotNull(specs, specsNotNull.get()),
() -> assertNotNull(specs.getBaseUrl(), baseURLNotNull.get()),
() -> assertNotNull(specs.getRawEndpoint(), rawEndpointNotNull.get()),
() -> assertNotNull(specs.getFormatedEndpoint(), formatedEndpointNotNull.get()),
() -> assertNotNull(specs.getHeaders(), headersNotNull.get()),
() -> assertNotNull(specs.getPathParams(), pathParametersNotNull.get()),
() -> assertNotNull(specs.getQueryParams(), queryParametersNotNull.get()),
() -> assertNotNull(specs.getBaseClient(), baseClientNotNull.get()),
() -> assertNotNull(specs.getRawRequestMethod(), requestMethodNotNull.get()),
() -> assertTrue(specs.getRawRequestMethod().equalsIgnoreCase( "PUT"), requestMethodNotNull.get()),
() -> assertNotNull(specs.getURI(), uriNotNull.get())
);
System.out.println("Method: " +specs.getRequestMethod().toString());
}
@Tag("specs-simple")
@Test
void specsConstructorSimpleTest() {
var specs = new RestSpecs(googleBaseURL.get(), headers.get(), "", "get");
assertAll("Just BaseURL, Headers and empty body for Constructor",
() -> assertNotNull(specs, specsNotNull.get()),
() -> assertNotNull(specs.getBaseUrl(), baseURLNotNull.get()),
() -> assertNotNull(specs.getHeaders(), headersNotNull.get()),
() -> assertNotNull(specs.getBaseClient(), baseClientNotNull.get()),
() -> assertNotNull(specs.getURI(), uriNotNull.get()));
}
@Tag("method-exception")
@Test
void specsConstructorExceptionTest() {
var exceptionMsg = "you should specify a request method!"; //"baseURL cannot be empty!";
var exception = assertThrows(AssertionError.class, () -> new RestSpecs(googleBaseURL.get(), headers.get(), "", ""));
var exceptionFullConstructor = assertThrows(AssertionError.class, () -> new RestSpecs(
googleBaseURL.get(), "", headers.get(), Map.of(), Map.of(), "", ""
));
assertAll("Raising exception for request method empty String",
() -> assertEquals(exceptionFullConstructor.getMessage(), exceptionMsg),
() -> assertEquals(exception.getMessage(), exceptionMsg));
}
@Tag("baseURL-exception")
@Test
void specsBaseURLExceptionTest() {
var exceptionMsg = "baseURL cannot be empty!";
var specs = new RestSpecs(googleBaseURL.get(), headers.get(), "", "GET");
var exception = assertThrows(AssertionError.class, () -> specs.setBaseUrl(""));
assertAll("Raising exception for baseURL empty String",
() -> assertEquals(exception.getMessage(), exceptionMsg));
}
@Tags({@Tag("specs")})
@DisplayName(value = "Rest Specs Method")
@ParameterizedTest(name = "Async sample Http test {index} with [{arguments}]")
@CsvFileSource(resources = "/sync-data.csv", numLinesToSkip = 1)
void syncTest(ArgumentsAccessor data) throws ExecutionException, InterruptedException {
var specs = updateRestSpecs.apply(data,specsFromFile.apply(configSync.get()));
var response = asyncRequest.apply(specs);
assumeTrue(response.get().statusCode() >= data.getInteger(2), statusCode200.get());
response.join().request();
var responseObject = (ResponseObject) responseToClass.apply(response.get(), ResponseObject.class);
assertAll(
() -> assertNotNull(response.get().body(), notNull.get()),
() -> assertTrue(specs.getRawRequestMethod().equalsIgnoreCase(data.getString(1)), objectContentEquals.get()),
() -> assertEquals(httpBinBaseURL.get().concat(data.getString(0)), responseObject.getUrl(), objectContentEquals.get()));
}
}<file_sep>package pojo.temp;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Headers{
@JsonProperty("User-Agent")
private String userAgent;
@JsonProperty("Host")
private String host;
@JsonProperty("X-Amzn-Trace-Id")
private String xAmznTraceId;
@JsonProperty("Content-Type")
private String contentType;
public void setUserAgent(String userAgent){
this.userAgent = userAgent;
}
public String getUserAgent(){
return userAgent;
}
public void setHost(String host){
this.host = host;
}
public String getHost(){
return host;
}
public void setXAmznTraceId(String xAmznTraceId){
this.xAmznTraceId = xAmznTraceId;
}
public String getXAmznTraceId(){
return xAmznTraceId;
}
public void setContentType(String contentType){
this.contentType = contentType;
}
public String getContentType(){
return contentType;
}
@Override
public String toString(){
return
"Headers{" +
"user-Agent = '" + userAgent + '\'' +
",host = '" + host + '\'' +
",x-Amzn-Trace-Id = '" + xAmznTraceId + '\'' +
",content-Type = '" + contentType + '\'' +
"}";
}
}
<file_sep>environment=qa
csv=src/test/resources/temp.csv<file_sep>package functions;
import base.RestSpecs;
import io.vavr.control.Either;
import io.vavr.control.Try;
import java.io.IOException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import java.util.function.Function;
import static io.vavr.API.Left;
import static io.vavr.API.Right;
public interface RestFunctions {
BiFunction<RestSpecs, HttpResponse.BodyHandler, CompletableFuture<HttpResponse>> asyncWithBodyHandler = (specs, handler) ->
specs.getBaseClient().sendAsync(specs.getRequestMethod(), handler);
BiFunction<HttpRequest, RestSpecs, Either<String, HttpResponse>> syncHttpRequest = (request, specs) -> {
try {
return Right(specs.getBaseClient().send(request, specs.getResponseBodyHandler()));
} catch (IOException | InterruptedException e) {
return Left(e.getMessage());
}
};
BiFunction<HttpRequest, RestSpecs, CompletableFuture<HttpResponse>> asyncHttpRequest = (request, specs) ->
specs.getBaseClient().sendAsync(request,
specs.getResponseBodyHandler());
Function<RestSpecs, Either<String, HttpResponse>> syncRequest = specs -> {
try {
return Right(specs.getBaseClient().send(specs.getRequestMethod(), specs.getResponseBodyHandler()));
} catch (IOException | InterruptedException e) {
return Left(e.getMessage());
}
};
Function<RestSpecs, CompletableFuture<HttpResponse>> asyncRequest = specs ->
specs.getBaseClient().sendAsync(specs.getRequestMethod(),
specs.getResponseBodyHandler());
}
<file_sep>ext {
alter_version='10.0.0-M7'
cyclops_version = '10.3.3'
}
dependencies {
implementation group: 'com.oath.cyclops', name: 'cyclops-vavr-integration', version: "${alter_version}"
implementation group: 'com.oath.cyclops', name: 'cyclops-reactive-collections', version: "${cyclops_version}"
implementation group: 'com.oath.cyclops', name: 'cyclops-reactor-integration', version: "${cyclops_version}"
implementation group: 'com.oath.cyclops', name: 'cyclops-pure', version: "${cyclops_version}"
implementation group: 'com.oath.cyclops', name: 'cyclops-anym', version: "${cyclops_version}"
testImplementation group: 'com.oath.cyclops', name: 'cyclops-futurestream', version: "${cyclops_version}"
}<file_sep>rootProject.name = 'rest-functions'
<file_sep>package pojo.temp;
public class Files{
@Override
public String toString(){
return
"Files{" +
"}";
}
}
<file_sep>package functions;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vavr.control.Try;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Tags;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.aggregator.ArgumentsAccessor;
import org.junit.jupiter.params.provider.CsvFileSource;
import pojo.ResponseObject;
import pojo.temp.SyncResp;
import utils.MessageSupplier;
import utils.TestUtils;
import java.util.concurrent.ExecutionException;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
@Tags({@Tag("sync"), @Tag("async")})
class FunctionsTest implements Helpers, RestFunctions, BaseUtils, MessageSupplier, TestUtils {
@Tags({@Tag("sync")})
@DisplayName(value = "Async Http")
@ParameterizedTest(name = "Async sample Http test {index} with [{arguments}]")
@CsvFileSource(resources = "/sync-data.csv", numLinesToSkip = 1)
void asyncTest(ArgumentsAccessor data) throws Throwable {
var specs = updateRestSpecs.apply(data,specsFromFile.apply(configSync.get()));
var response = asyncRequest.apply(specs);
assumeTrue(response.get().statusCode() >= data.getInteger(2), statusCode200.get());
var responseObject = Try.of(() -> new ObjectMapper().readValue(response.get().body().toString(), ResponseObject.class)).getOrElseThrow(Throwable::getCause);
assertAll(
() -> assertNotNull(response.get().body(), notNull.get())
,
() -> assertEquals(httpBinBaseURL.get().concat(data.getString(0)), responseObject.getUrl(), objectContentEquals.get()));
}
@Tags({@Tag("sync")})
@DisplayName(value = "Sync Http")
@ParameterizedTest(name = "Sync sample Http test {index} with [{arguments}]")
@CsvFileSource(resources = "/sync-data.csv", numLinesToSkip = 1)
void syncTest(ArgumentsAccessor data) throws Throwable {
var specs = updateRestSpecs.apply(data,specsFromFile.apply(configSync.get()));
var response = syncRequest.apply(specs).get();
assumeTrue(response.statusCode() >= data.getInteger(2), statusCode200.get());
var responseObject = Try.of(() -> new ObjectMapper().readValue(String.valueOf(response.body()), SyncResp.class)).getOrElseThrow(Throwable::getCause);
assertAll(
() -> assertNotNull(response.body(), notNull.get()),
() -> assertEquals(httpBinBaseURL.get().concat(data.getString(0)), responseObject.getUrl(), objectContentEquals.get()));
}
}
<file_sep>package base;
/**
* author: <NAME>
* license: Apache2
*/
import functions.BaseUtils;
import io.vavr.API;
import io.vavr.control.Try;
import java.net.Authenticator;
import java.net.CookieHandler;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Map;
import java.util.function.Supplier;
import java.util.logging.Logger;
import static io.vavr.API.$;
import static io.vavr.API.Case;
public final class RestSpecs implements BaseUtils {
private static final Logger LOG = Logger.getLogger(RestSpecs.class.getName());
private URI baseUrl;
private String endpoint;
private Map<String, Object> headers;
private Map<String, Object> queryParams;
private Map<String, Object> pathParams;
private HttpRequest.BodyPublisher body;
private char responseHandlerType = 's';
private Authenticator authenticator;
private CookieHandler cookieHandler;
private Duration timeout = Duration.ofSeconds(90);
private HttpClient baseClient;
private URI uri;
private String requestMethod;
public RestSpecs(String baseUrl, Map<String, Object> headersParams, String body, String requestMethod){
this.baseUrl = URI.create(baseUrl);
this.uri = URI.create(baseUrl);
this.headers = headersParams;
assert(!requestMethod.isBlank()): "you should specify a request method!";
this.requestMethod = requestMethod;
if(body != null) setBody(body); else setBody("");
}
public RestSpecs(String baseUrl, String endp, Map<String, Object> headersParams, Map<String, Object> queryParams,
Map<String, Object> pathParams, String body, String requestMethod) {
this.baseUrl = URI.create(baseUrl);
this.headers = headersParams;
this.endpoint = endp;
var tempEndpoint = this.endpoint;
this.pathParams = pathParams;
this.queryParams = queryParams;
assert(!requestMethod.isBlank()): "you should specify a request method!";
this.requestMethod = requestMethod;
if(getRawEndpoint() != null && !getRawEndpoint().isBlank()) tempEndpoint = setPathParameters.apply(this.endpoint, pathParams);
if(getRawEndpoint() != null && !getRawEndpoint().isBlank()) tempEndpoint = setQueryParams(tempEndpoint, queryParams);
if(getRawEndpoint() != null) setURI(baseUrl, tempEndpoint); else this.uri = URI.create(baseUrl);
if(body != null) setBody(body); else setBody("");
}
private void setURI(String baseURL, String endpoint){
this.uri = URI.create(baseURL).resolve(endpoint);
}
public HttpResponse.BodyHandler getResponseBodyHandler(){
return API.Match(this.responseHandlerType).of(
Case($('s'), HttpResponse.BodyHandlers.ofString()),
Case($('i'), HttpResponse.BodyHandlers.ofInputStream()),
Case($('b'), HttpResponse.BodyHandlers.ofByteArray()),
// Case($('l'), HttpResponse.BodyHandlers.fromLineSubscriber(Subscriber<String>)),
Case($(), (Supplier<HttpResponse.BodyHandler<String>>) HttpResponse.BodyHandlers::ofString));
}
public char getResponseHandlerType() {
return responseHandlerType;
}
/**
* 's' for String, 'i' for InputStream, 'b' for ByteArray -> String Type is set as default.
* @param responseHandlerType
*/
public void setResponseHandlerType(char responseHandlerType) {
this.responseHandlerType = responseHandlerType;
}
public void setBaseUrl(String url) {
assert(!url.isBlank()): "baseURL cannot be empty!";
this.baseUrl = URI.create(url);
}
public URI getURI() {
return uri;
}
public URI getBaseUrl(){
return baseUrl;
}
public String[] getHeaders() {
return mapToStringArray.apply(headers);
}
public Map<String, Object> getHeadersMap() {return headers;}
public void setHeaders(Map<String, Object> headers) {
this.headers = headers;
}
public Map<String, Object> getQueryParams() {
return queryParams;
}
public HttpRequest.BodyPublisher getBody() {
return body;
}
public void setBody(){
this.body = HttpRequest.BodyPublishers.noBody();
}
public void setRequestMethod(String method){
this.requestMethod = method;
}
private void setBody(String requestBody) {
if (requestBody.endsWith(".json")) setBody(Path.of(requestBody)); else this.body = HttpRequest.BodyPublishers.ofString(requestBody);
}
public void setBody(byte[] body){
this.body = HttpRequest.BodyPublishers.ofByteArray(body);
}
/**
* @param filePathBody
*/
private void setBody(Path filePathBody){
Try.of(()-> this.body = HttpRequest.BodyPublishers.ofFile(filePathBody))
.onFailure(throwable -> LOG.severe(throwable.toString()));
}
public void setBody(HttpRequest.BodyPublisher body){
this.body = body;
}
public Authenticator getAuthenticator() {
return authenticator;
}
public void setAuthenticator(Authenticator authenticator) {
this.authenticator = authenticator;
}
public Duration getTimeout() {
return timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public CookieHandler getCookieHandler() {
return cookieHandler;
}
public void setCookieHandler(CookieHandler cookieHandler) {
this.cookieHandler = cookieHandler;
}
public HttpClient getBaseClient() {
if(null == baseClient) buildBaseClient();
return baseClient;
}
public void setBaseClient(HttpClient client){
this.baseClient = client;
}
public String getRawEndpoint() {
return endpoint;
}
public String getFormatedEndpoint(){
var tempEndpoint = setPathParameters.apply(this.endpoint, pathParams);
tempEndpoint = setQueryParams(tempEndpoint, queryParams);
return tempEndpoint;
}
public Map<String, Object> getPathParams() {
return pathParams;
}
private String setPathParams(Map<String, Object> pathParams, String endpoint) {
this.pathParams = pathParams;
return (pathParams != null && pathParams.size() % 2 == 0) ? setPathParameters.apply(endpoint, pathParams) : endpoint;
}
public void setURI(String uri){
this.uri = URI.create(uri);
}
public HttpRequest getRequestMethod(){
return API.Match(this.getRawRequestMethod().toUpperCase()).of(
Case($("GET"), baseRequestBuilder().GET().build()),
Case($("POST"), baseRequestBuilder().POST(this.getBody()).build()),
Case($("PUT"), baseRequestBuilder().PUT(this.getBody()).build()),
Case($("DELETE"), baseRequestBuilder().DELETE().build()));
}
public String getRawRequestMethod(){
return this.requestMethod;
}
private HttpRequest.Builder baseRequestBuilder(){
return HttpRequest
.newBuilder()
.uri(this.getURI())
.timeout(this.getTimeout())
.headers(this.getHeaders());
}
/**
*
* @param endpoint
* @param queryPars as Map, it does not guarantee order; so, API should how to resolve parameters.
* @return
*/
private String setQueryParams(String endpoint, Map<String, Object> queryPars){
this.queryParams = queryPars;
return (queryPars == null || queryPars.isEmpty()) ? endpoint : queryParametersComposition.apply(endpoint, queryPars);
}
private void buildBaseClient() {
this.baseClient = cookieHandler != null ? HttpClient.newBuilder().cookieHandler(cookieHandler)
.connectTimeout(timeout).build() :
HttpClient.newBuilder().connectTimeout(timeout).build();
}
@Override
public String toString() {
return "RestSpecs{" +
"baseUrl=" + baseUrl +
", endpoint=" + endpoint +
", formated endpoint=" + getFormatedEndpoint() +
", headers=" + headers.values() +
", queryParams=" + queryParams +
", pathParams=" + pathParams +
", body=" + body +
", requestMethod=" + requestMethod +
", responseHandlerType=" + responseHandlerType +
", authenticator=" + authenticator +
", cookieHandler=" + cookieHandler +
", timeout=" + timeout +
", baseClient=" + baseClient +
", uri=" + uri +
'}';
}
}
<file_sep>package functions;
import base.RestSpecs;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vavr.Lazy;
import io.vavr.control.Try;
import java.net.http.HttpResponse;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
public interface Helpers {
Lazy<String> errorMessage = Lazy.of(() -> "ERROR on de-serialization- verify it!");
BiFunction<Map<String,Object>, RestSpecs, RestSpecs> updatePathParams = (pathParams, specs) ->
new RestSpecs(specs.getBaseUrl().toString(),
specs.getRawEndpoint(),
specs.getHeadersMap(),
specs.getQueryParams(),
pathParams, specs.getBody().toString(), specs.getRawRequestMethod());
BiFunction<Map<String,Object>, RestSpecs, RestSpecs> updateQueryParams = (queryParams, specs) ->
new RestSpecs(specs.getBaseUrl().toString(),
specs.getRawEndpoint(),
specs.getHeadersMap(),
queryParams,
specs.getPathParams(), specs.getBody().toString(), specs.getRawRequestMethod());
BiFunction<String, RestSpecs, RestSpecs> updateEndpoint = (endpoint, specs) ->
new RestSpecs(specs.getBaseUrl().toString(), endpoint, specs.getHeadersMap(), specs.getQueryParams(),
specs.getPathParams(), specs.getBody().toString(), specs.getRawRequestMethod());
BiFunction<String, RestSpecs, RestSpecs> updateBody = (body, specs) ->
new RestSpecs(specs.getBaseUrl().toString(), specs.getRawEndpoint(), specs.getHeadersMap(),
specs.getQueryParams(), specs.getPathParams(), body, specs.getRawRequestMethod());
Function<Object, String> clazzToJson = object ->
Try.of(() -> new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(object))
.getOrElse(errorMessage.get());
BiFunction<String, Class, Object> stringToObject = (str, clazz) ->
Try.of(() -> new ObjectMapper().readValue(str, clazz))
.getOrElse(errorMessage.get());
BiFunction<HttpResponse, Class, Object> responseToClass = (response, clazz) ->
Try.of(() -> new ObjectMapper().readValue(response.body().toString(), clazz))
.getOrElse(errorMessage.get());
BiFunction<String, Class, Object> responseBodyToClass = (body, clazz) ->
Try.of(() -> new ObjectMapper().readValue(body, clazz))
.getOrElse(errorMessage.get());
}
<file_sep>package utils;
public enum Scenario {
SUCCESS,
FAIL
}
<file_sep>buildscript {
repositories {
maven { url "https://plugins.gradle.org/m2/" }
jcenter()
}
dependencies {
classpath "eu.davidea:grabver:2.0.1"
// classpath 'com.bmuschko:gradle-clover-plugin:2.2.3'
classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.7.1"
classpath 'com.bmuschko:gradle-nexus-plugin:2.3.1'
}
}
plugins {
id 'java'
id "org.sonarqube" version "2.7"
id 'jacoco'
id 'io.codearte.nexus-staging' version '0.11.0'
}
archivesBaseName = 'functional-rest'
group 'com.github.tcanascimento'
version '1.0-SNAPSHOT'
sourceCompatibility = 11
targetCompatibility = 11
repositories {
mavenLocal()
mavenCentral()
jcenter()
maven { url "https://jitpack.io" }
maven { url "http://dl.bintray.com/davideas/maven" }
maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
maven { url "https://plugins.gradle.org/m2/" }
}
apply from: 'gradle/junit5.gradle'
// apply from: 'gradle/cyclops.gradle'
apply plugin: "eu.davidea.grabver"
apply plugin: 'com.bmuschko.nexus'
//apply plugin: 'com.bmuschko.clover'
configurations {
exclusions {
exclude group: 'org.junit'
}
}
dependencies {
// implementation group: 'com.github.pureconfig', name:'pureconfig-javax_2.12', version: '0.10.2'
// implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.9'
implementation(
'com.github.pureconfig:pureconfig-javax_2.12:0.10.2',
'com.fasterxml.jackson.core:jackson-databind:2.9.9',
'com.github.jitpack:gradle-simple:1.0',
'org.openclover:clover:4.3.1',
'io.vavr:vavr:0.10.2',
'io.vavr:vavr-jackson:0.10.2'
)
}
versioning {
versioning.major
version = versioning.name
major 1
minor 0
patch 7
preRelease "RC1"
// Optional, custom task name to trigger the increase of the version
incrementOn "assemble"
// Optional, custom task name for which you want to save the versioning file
saveOn "assemble"
}
sonarqube {
properties {
property "sonar.sourceEncoding", "UTF-8"
property "sonar.projectName", "${project.name}"
property "sonar.host.url", "https://sonarcloud.io"
property "sonar.login", "${sonar-login}"
property "sonar.projectKey", "tcanascimento_functional-rest"
property "sonar.organization","tcanascimento-github"
property "sonar.junit.reportPaths", "${buildDir}/test-results/test"
property "sonar.coverage.jacoco.xmlReportPaths", "${buildDir}/reports/jacoco/test/jacocoTestReport.xml"
}
}
jacocoTestReport {
reports {
xml.enabled true
csv.enabled true
html.destination file("${buildDir}/jacocoHtml")
}
}
modifyPom {
project {
name 'Functional Rest'
description 'A Small Lib for API Rest Testing'
url 'https://github.com/tcanascimento/functional-rest'
inceptionYear '2019'
scm {
url 'https://github.com/tcanascimento/functional-rest.git'
connection 'scm:https://github.com/tcanascimento/functional-rest.git'
developerConnection 'scm:git://github.com/tcanascimento/functional-rest.git'
}
licenses {
license {
name 'The Apache Software License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
distribution 'repo'
}
}
developers {
developer {
id 'tcanascimento'
name '<NAME>'
email '<EMAIL>'
}
}
}
}
extraArchive {
sources = false
tests = true
javadoc = false
}
nexus {
sign = true
repositoryUrl = 'https://oss.sonatype.org/service/local/staging/deploy/maven2/'
snapshotRepositoryUrl = 'https://oss.sonatype.org/content/repositories/snapshots/'
}
nexusStaging {
packageGroup = "com.github.tcanascimento" //optional if packageGroup == project.getGroup()
stagingProfileId = "cd98c67a221aa" //when not defined will be got from server using "packageGroup"
}
<file_sep>package pojo.temp;
public class Form{
@Override
public String toString(){
return
"Form{" +
"}";
}
}
<file_sep>package pojo.temp;
public class Args{
@Override
public String toString(){
return
"Args{" +
"}";
}
}
<file_sep>ext {
jupiter_version='5.6.1'
alter_version='1.6.1'
}
dependencies {
implementation(
'org.junit.jupiter:junit-jupiter-migrationsupport:'+"${jupiter_version}",
'org.junit.jupiter:junit-jupiter-engine:'+"${jupiter_version}",
'org.junit.jupiter:junit-jupiter-params:'+"${jupiter_version}",
'org.junit.platform:junit-platform-console:'+"${alter_version}",
'org.junit.platform:junit-platform-launcher:'+"${alter_version}",
'org.junit.platform:junit-platform-runner:'+"${alter_version}",
'org.junit.platform:junit-platform-commons:'+"${alter_version}")
}
test {
description = 'Executa testes. Para executar tags específicas, use: gradle clean test -Dtag="tag".'
testLogging.showStandardStreams = true
String tag = System.properties.getProperty("tag")
systemProperties = [
'junit.jupiter.extensions.autodetection.enabled': 'true',
'junit.jupiter.testinstance.lifecycle.default': 'per_class'
]
useJUnitPlatform() {
if(null != tag && !tag.equalsIgnoreCase("")) includeTags String.valueOf(tag)
}
testLogging {
events 'PASSED', 'FAILED', 'SKIPPED'
}
beforeTest { descriptor ->
logger.lifecycle("Running test: ${descriptor}")
}
afterSuite { desc, result ->
if (!desc.parent) {
println "\nTest result: ${result.resultType}"
println "Test summary: ${result.testCount} tests, " +
"${result.successfulTestCount} succeeded, " +
"${result.failedTestCount} failed, " +
"${result.skippedTestCount} skipped"
}
}
/* jacoco {
destinationFile = file("$buildDir/jacoco/jacocoTest.exec")
classDumpDir = file("$buildDir/jacoco/classpathdumps")
} */
}<file_sep>
package pojo;
@SuppressWarnings("unused")
public class Args {
}
<file_sep>//package samples;
//
//import base.BaseRest;
//import base.RestSpecs;
//import base.RestSpecsBuilder;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.typesafe.config.Config;
//import com.typesafe.config.ConfigBeanFactory;
//import com.typesafe.config.ConfigFactory;
//import functions.BaseUtils;
//import functions.Helpers;
//import functions.HttpFunctions;
//import functions.RestFunctions;
//import io.vavr.Lazy;
//import org.junit.jupiter.api.*;
//import org.junit.jupiter.params.ParameterizedTest;
//import org.junit.jupiter.params.aggregator.ArgumentsAccessor;
//import org.junit.jupiter.params.provider.CsvFileSource;
//import pojo.ResponseObject;
//import utils.MessageSupplier;
//import utils.TestUtils;
//
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileNotFoundException;
//import java.io.IOException;
//import java.util.Map;
//import java.util.Properties;
//import java.util.UUID;
//import java.util.concurrent.ExecutionException;
//import java.util.function.Function;
//import java.util.function.Supplier;
//
//import static org.junit.jupiter.api.Assertions.*;
//import static org.junit.jupiter.api.Assumptions.assumeTrue;
//
//class SampleTest implements RestFunctions, Helpers, HttpFunctions, BaseUtils, MessageSupplier, TestUtils {
//
// private Lazy<Map<String, Object>> headers = Lazy.of(() -> Map.of("Content-Type", "application/json"));
//
// @Test
// void asyncSampleTest() {
//
// var specs = new RestSpecs(httpBinBaseURL.get().concat("/get"), headers.get(), "", "get");
// var response = asyncRequest.apply(specs);
//
// assertAll( "Simple validation",
// () -> assertNotNull(response.get().body()),
// () -> assertEquals(200, response.get().statusCode()));
//
// }
//
// @Test
// void syncSampleTest() throws IOException {
//
// var specs = new RestSpecs(httpBinBaseURL.get().concat("/post"), headers.get(), "", "post");
// var response = syncRequest.apply(specs).get();
// var body = new ObjectMapper().readValue(response.body().toString(), ResponseObject.class);
//
// assertAll( "Simple validation",
// () -> assertNotNull(response.body()),
// () -> assertEquals(200, response.statusCode()),
// () -> assertEquals(specs.getBaseUrl().toString(), body.getUrl()));
//
//
//
// System.out.println("body: "+ body);
//
// }
//
// @Tag("specsfromfile")
// @Test
// void specsFromConfSampleTest(){
//
// var specs = specsFromFile.apply(configSync.get());
// var response = asyncRequest.apply(specs);
// assertAll( "Simple validation",
// () -> assertNotNull(response.get().body()),
// () -> assertEquals(200, response.get().statusCode()));
// }
//
// @Tags({@Tag("parameterized"), @Tag("sample")})
// @DisplayName(value = "Async Http")
// @ParameterizedTest(name = "Exemplos de teste Http Assíncrono {index} com [{arguments}]")
// @CsvFileSource(resources = "/sync-data.csv", numLinesToSkip = 1)
// void paramaterizedSampleTest(ArgumentsAccessor data) throws ExecutionException, InterruptedException {
//
// var method = data.getString(0);
//
// var specs = updateRestSpecs.apply(data,specsFromFile.apply(configSync.get()));
//
// var response = asyncRequest.apply(specs);
//
// assumeTrue(response.get().statusCode() >= data.getInteger(2), statusCode200.get());
//
// var responseObject = (ResponseObject) responseToClass.apply(response.get(), ResponseObject.class);
//
// response.join().request();
//
// assertAll("Testing Methods",
// () -> assertNotNull(response.get().body(), notNull.get()),
// () -> assertEquals(httpBinBaseURL.get().concat(data.getString(0)), responseObject.getUrl(), objectContentEquals.get()));
//
// }
//
// protected static String getProp() {
// Properties props = new Properties();
// try {
// props.load(new FileInputStream("src/test/resources/configs.properties"));
// } catch (IOException e) {
// e.printStackTrace();
// }
// return props.getProperty("csv");
// }
//
// private static final String ALGO = getProp();
//
// @Test
// @Tag("props")
// void propsTest(){
// //System.out.println(ALGO);
//
// var rate = 1.50;
// var amount = 100.00;
// var value = 98.50;
//
// assertEquals(0, Double.compare(Math.abs(value) + rate, amount));
// }
//
//
// /*
// {
// Config config = ConfigFactory.parseFile(new File(file)).resolve();
// return new RestSpecsBuilder().with(
// ($) -> {
// $.baseUrl2 = config.getConfig("specs").getString("baseUrl");
// $.endpoint2 = config.getConfig("specs").getString("endpoint");
// $.headersParams = config.getConfig("specs").getObject("headers").unwrapped();
// $.queryParams = config.getConfig("specs").getObject("queryParams").unwrapped();
// $.pathParams = config.getConfig("specs").getObject("pathParams").unwrapped();
// $.bodyString = config.getConfig("specs").getString("body");
// $.requestMethod = config.getConfig("specs").getString("requestMethod");
// }).createSpecs();
// };
// */
//// Function<String, Object> specsToClass = file -> ConfigBeanFactory.create(
//// ConfigFactory.parseFile(new File(file)).resolve().getConfig("specs"),
//// BaseRest.class);
//
//
//}
<file_sep>package functions;
/**
* author: <NAME>
* license: Apache2
*/
import base.RestSpecs;
import base.RestSpecsBuilder;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigBeanFactory;
import com.typesafe.config.ConfigFactory;
import io.vavr.control.Try;
import java.io.File;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
public interface BaseUtils {
/**
* Works good for POJO; it was not intented to work for RestSpecs
*/
BiFunction<String, Class, Object> specsConfigLoaderFromFile = (file, clazz) ->
ConfigBeanFactory.create(
ConfigFactory.parseFile(new File(file)).resolve().getConfig("specs"),
clazz);
Function<String, RestSpecs> specsFromFile = file -> {
Config config = ConfigFactory.parseFile(new File(file)).resolve();
return new RestSpecsBuilder().with(
($) -> {
$.baseUrl2 = config.getConfig("specs").getString("baseUrl");
$.endpoint2 = config.getConfig("specs").getString("endpoint");
$.headersParams = config.getConfig("specs").getObject("headers").unwrapped();
$.queryParams = config.getConfig("specs").getObject("queryParams").unwrapped();
$.pathParams = config.getConfig("specs").getObject("pathParams").unwrapped();
$.bodyString = config.getConfig("specs").getString("body");
$.requestMethod = config.getConfig("specs").getString("requestMethod");
}).createSpecs();
};
//todo: refactor
BiFunction<String,Map<String,Object>, String> setPathParameters = (endpoint, pars) -> {
AtomicReference<String> pathParameter = new AtomicReference<>(endpoint);
pars.keySet()
.forEach(k -> pathParameter.lazySet(pathParameter.get().replaceFirst("\\{".concat(k).concat("\\}"), pars.get(k).toString())));
return pathParameter.get();
};
Function<Map<String,Object>, String[]> mapToStringArray = map -> {
AtomicReference<List<String>> composition = new AtomicReference<>(new ArrayList<>());
map.entrySet().iterator().forEachRemaining(i -> {
composition.get().add(i.getKey());
composition.get().add(String.valueOf(i.getValue())); });
return composition.get().toArray(new String[0]);
};
/**
*
* @param url
* @param queryParams
* @return a String with Query Parameters. Note: the order is not always guaranteed
*/
BiFunction<String, Map<String,Object>, String> queryParametersComposition = (url, queryParams) -> {
AtomicReference<StringBuilder> composition = new AtomicReference<>(new StringBuilder(url.concat("?")));
Iterator<Map.Entry<String,Object>> iter = queryParams.entrySet().iterator();
iter.forEachRemaining(i -> {
composition.get().append(i.getKey()).append("=").append(i.getValue());
if(iter.hasNext()) composition.get().append("&"); });
return composition.get().toString();
};
/**
* Function to generate Map<String, Object> from a json String
*/
Function<String, Map<String, Object>> generateMapFromString = dataVar ->
Arrays.stream(dataVar.replace("{", "").replace("}", "").split(","))
.map(s -> s.split(":"))
.collect(Collectors.toMap(k -> k[0].strip(), k -> k[1].strip()));
}
|
00201e78c2d448ca1b320700b6e72af38e12eef0
|
[
"Markdown",
"Java",
"INI",
"Gradle"
] | 27 |
Java
|
tcanascimento/functional-rest
|
861ac91d80915aec5e7e7bfbd89d996d5b6117ee
|
75182964793b0dd46bb0ca755f931487d426f04b
|
refs/heads/master
|
<repo_name>ayoolaao/CSC374_COMPUTER_SYSTEMS_2<file_sep>/20134_5SumII_csc407_assign4.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head></head><body>
<center>
<h2>CSC 407: Computer Systems II: 2014 Summer II, Assignment #4</h2>
<p>Last Modified 2014 August 18</p>
</center>
<h4>Purpose:</h4>
To practice programming:
<ol type="1">
<li>Linux sockets
</li><li>Linux file and directory I/O
</li><li>cursor control with ncurses (optional)
</li></ol>
<h4>Computing</h4>
<p>
Please <a rel="noopener" href="http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html">ssh</a> into ctilinux1.cstcis.cti.depaul.edu, ctilinux2.cstcis.cti.depaul.edu or ctilinux3.cstcis.cti.depaul.edu.
Please be sure to run the client and server on the <b>same machine!</b>
A client has to know which machine has the server so it can properly connect.
</p>
<h4>Assignment: finish <code>babyFTPServer.cpp</code></h4>
<p>
In this assignment we'll finish a program that acts as a <em>very</em> simple <code>ftp</code> with just three commands:
<ul>
<li>list the files in the current directory</li>
<li>copy a remote file from the server to the client</li>
<li>quit</li>
</ul>
</p>
<p>
When it starts it is told the port to which its server socket should listen, and the password with which clients should authenticate.
It then waits for clients.
When one connects the main process <code>fork()</code>s a child process to handle the new client.
That child process handles the clients requests.
When the client requests to <code>quit</code> the child process ends.
The parent process uses its <code>SIGCHLD</code> handler to reap the child and report on its exit status.
</p>
<p>
All messages from client-to-server and server-to-client should be <code>MAX_LINE</code> characters long.
</p>
<h4>IMPORTANT!</h4>
<p>
<strong>When testing the "get <filename>" command, run the client and server in different directories. Otherwise the client will over-write the file that the server reads!</strong>
</p>
Your job is to:
<ol type="1">
<li>Download from Desire2Learn my file <code>babyFTPClient.zip</code>.
(D2L would not let me upload an executable.)
On Windows, open the zip file and find my executable <code>babyFTPClient</code>
Upload the executable to your CDM Linux machine of your choice.
Now, on that Linux machine, do the following so the OS knows it's an executable:
<pre>
$ <b>chmod u+x babyFTPClient</b>
</pre>
<p></p>
</li><li>Finish <code>main()</code>.
It should install <code>sigchld_handler()</code> as the handler for <code>SIGCHLD</code>.
</li>
<p></p>
<li>Finish <code>createListeningSocket()</code>.
It should create and return a server socket file descriptor that listens to port <code>port</code>.
It should prints an error message and return <code>-1</code> if it encounters a problem.
<p></p>
</li>
<li>Finish <code>obtainPassword()</code>.
It should obtain the password either from the file named <code>passwordFilename</code> or the keyboard.
The code for defining <code>passwordFilename</code> and for obtaining it from the keyboard is already there.
Add to it so that it attempts to read the file <code>passwordFilename</code>.
If it is unsuccessful then it asks the user with the keyboard.
<p></p>
</li>
<li>Finish <code>didLogin()</code>.
<p>
This function <code>read()</code>s <code>MAX_LINE</code> characters from the client into a buffer and sees if it matches the server's password.
<ul>
<li>If it does <em>not</em> match then it puts <code>BAD_PASSWORD_RESPONSE</code> into a buffer, sends <code>MAX_STRING</code> chars back to the client, and returns <code>false</code>.</li>
<li>If it <em>does</em> match then it puts <code>GOOD_PASSWORD_RESPONSE</code> into a buffer, sends <code>MAX_STRING</code> chars back to the client, and returns <code>true</code>.</li>
</ul>
</p>
</li>
<li>Finish <code>listDir()</code>.
<p>
It should iterate over all entries in the directory and send text descriptions of them to the client.
<ul>
<li>For ordinary files it should print out both the filename and size.
Use
<pre>
snprintf(buffer,MAX_LINE,"%30s (%5d)",<i>yourFileNameVar</i>,<i>yourFileSizeVar</i>);
</pre>
to write into <code>buffer</code>.
Then send <code>MAX_LINE</code> bytes of <code>buffer</code> to the client.
</li><li>For directories it should print out the name.
Use
<pre>
snprintf(buffer,MAX_LINE,"%30s ( dir )",<i>yourFileNameVar</i>);
</pre>
to write into <code>buffer</code>.
Then send <code>MAX_LINE</code> bytes of <code>buffer</code> to the client.
</li><li>For anything else it should print out the name.
Use
<pre>
snprintf(buffer,MAX_LINE,"%30s (other)",<i>yourFileNameVar</i>);
</pre>
to write into <code>buffer</code>.
Then send <code>MAX_LINE</code> bytes of <code>buffer</code> to the client.
</li></ul>
</p>
<p>
After sending all entries to the client it should
Then
<ul>
<li>close the directory,</li>
<li>put <code>END_RESPONSE</code> into <code>buffer</code>,
</li><li>send <code>MAX_LINE</code> chars of the buffer to the client,
</li></ul>
</p>
</li>
<li>Finish <code>getFile()</code>.
<p>
This function should:
<ol type="1">
<li>
<code>read()</code> <code>MAX_LINE</code> chars from 'clientFD'.
This string tells the filename that the client wants.
</li>
<li>
Attempt to open the file (for reading).
If it can't be read then put <code>NO_FILE_RESPONSE</code> in a buffer of <code>MAX_LINE</code> chars, send it to the client, and <code>return</code>.
</li>
<li>
Get the size of the file in bytes.
</li>
<li>
Write the size into a buffer of size <code>MAX_LINE</code> chars as a decimal integer, and send the buffer to the client.
</li>
<li>
Read all of the chars of the file and send them to the client.
</li>
<li>
Close the file.
</li>
</ol>
</p>
</li>
<li>Finish <code>sigchld_handler()</code>
<p>
Add this loop:
<pre>
while( (pid = waitpid(-1,&status, WNOHANG)) > 0)
{
<strong>// YOUR CODE</strong>
}
</pre>
<ul>
<li>The <code>-1</code> means <em>"Accept any child process"</em></li>
<li>The <code>&status</code> means <em>"Write the exit status into the address of (integer) variable <code>status</code>"</em></li>
<li>The <code>WNOHANG</code> means <em>"If there are no more child processes for which to <code>wait()</code>, then just return <code>-1</code>"</em></li>
</ul>
If the child process ends successfully do:
<pre>
printf("Process %d finished with return value %d\n",
<childProcessesID>,
<childProcessesExitInteger>
);
</pre>
However, if the child process crashes, do:
<pre>
printf("Process %d crashed.\n",<childProcessesID>);
</pre>
</p>
</li>
</ol>
<p>
<h3>Sample output (server):</h3>
<table border="1">
<tr>
<th>
Server:<br/>
(File <code>.babyFTPrc</code> has password <code>hi</code> in it)
</th>
<th>Client:</th>
</tr>
<tr>
<td>
<pre>
$ <strong>./babyFTPServer </strong>
Desired port number? <strong>20202</strong>
Process 3802 authenticating user . . .
Process 3802 bad password.
Process 3802 finished with return value 1
</pre>
</td>
<td>
<pre>
Server name? <strong>localhost</strong>
Server port? <strong>20202</strong>
Password? ...... (<em>I typed the wrong password: <code>hello</code></em>)
Bad password!
Press enter
(<em>I press <code>enter</code>,
the client ends but the server is still running</em>)
</pre>
</td>
</tr>
<tr>
<td>
<pre>
Process 3805 authenticating user . . .
Process 3805 good password.
Process 3805 starting listing current directory.
Process 3805 finished listing current directory.
Process 3805 attempting to read file.
Process 3805 cannot get file99.txt -- does not exist.
Process 3805 attempting to read file.
Process 3805 getting file0.txt.
Process 3805 read file file0.txt.
Process 3805 quitting.
Process 3805 finished with return value 0
</pre>
</td>
<td>
<pre>
Server name? <strong>localhost</strong>
Server port? <strong>20202</strong>
Password? <strong>...</strong> (<em>I typed the correct password: <code>hi</code></em>)
Login successful.
What would you like to do?
list
get <filename>
put <filename>
quit
Your choice? <strong>list</strong>
file0.txt ( 27)
. ( dir )
file3.txt ( 27)
file1.txt ( 27)
file2.txt ( 27)
.. ( dir )
What would you like to do?
list
get <filename>
put <filename>
quit
Your choice? <strong>get file99.txt</strong>
<no file>
What would you like to do?
list
get <filename>
put <filename>
quit
Your choice? <strong>get file0.txt</strong>
Received file0.txt
What would you like to do?
list
get <filename>
put <filename>
quit
Your choice? <strong>quit</strong>
Press enter
(<em>I press <code>enter</code>,
the client ends but the server is still running</em>)
</pre>
</td>
</tr>
</table>
</p>
<p>
<h3>Sample protocol:</h3>
<pre>
<strong>NOTE:</strong> All strings are of length <code>MAX_LINE</code>
babyFTPClient babyFTPServer
| |
| connect() |
+-------------------------------------->+
| |
| accept() |
+<--------------------------------------+
| |
| "BAD PASSWORD " |
+-------------------------------------->+
| |
| BAD_PASSWORD_RESPONSE |
+<--------------------------------------+
| |
| close() |
| X <-----------------+
| |
X X
end end
babyFTPClient babyFTPServer
| |
| connect() |
+-------------------------------------->+
| |
| accept() |
+<--------------------------------------+
| |
| "CORRECT PASSWORD " |
+-------------------------------------->+
| |
| GOOD_PASSWORD_RESPONSE |
+<--------------------------------------+
| |
| LIST_CMD |
+-------------------------------------->+
| |
| "file0.txt ( 27)" |
+<--------------------------------------+
| |
| ". ( dir )" |
+<--------------------------------------+
| |
| "file3.txt ( 27)" |
+<--------------------------------------+
| |
| "file1.txt ( 27)" |
+<--------------------------------------+
| |
| "file2.txt ( 27)" |
+<--------------------------------------+
| |
| ".. ( dir )" |
+<--------------------------------------+
| |
| END_RESPONSE |
+<--------------------------------------+
| |
| GET_CMD |
+-------------------------------------->+
| |
| "file99.txt " |
+-------------------------------------->+
| |
| NO_FILE_RESPONSE | // This file does not exist
+<--------------------------------------+
| |
| GET_CMD |
+-------------------------------------->+
| |
| "file0.txt " |
+-------------------------------------->+
| |
| "27 " | // Assume file0.txt is 27 chars
+<--------------------------------------+
| |
| "abcdefghijklmnopqrstuvwxyz\n" | // Send EXACTLY 27 chars
+<--------------------------------------+
| |
| QUIT_CMD |
+-------------------------------------->+
| |
X X
end end
</pre>
</p>
<b>5 Points Extra credit!</b> (Lots of work, little glory)
Instead of using <code>fgets()</code> when having the user enter passwords use the <code>ncurses</code> package to let the user type in the name with privacy.
When a letter is between ASCII 32 to ASCII 126 is typed, no matter the letter, the character <code>DUMMY_PASSWORD_VISIBLE_CHAR</code> appears on the screen.
Have the user type in the password twice to verify that they typed it correctly.
If they haven't, make them re-enter twice until they do.
<p>
<b>Sample output (server, extra-credit):</b>
<pre>
[jphillips@cdmlinux Assign4]$ <strong>./babyFTPServer </strong>
Desired port number? <strong>20001</strong>
<em>(Screen clears)</em>
Please enter password: <strong>.....</strong> <em>(I typed "hi".)</em>
Please re-enter password: <strong>.....</strong> <em>(I typed "Hi".)</em>
Passwords don't match!
Please enter password: <strong>.....</strong> <em>(I typed "hi".)</em>
Please re-enter password: <strong>.....</strong> <em>(I typed "hi".)</em>
<em>(Screen clears)</em>
[jphillips@cdmlinux Assign4]$ ./babyFTPServer
Desired port number? 20202
<i>(Program waits for client)</i>
</pre>
</p>
<p>
<strong>babyFTPHeader.h:</strong>
<pre>
/*-------------------------------------------------------------------------*
*--- ---*
*--- babyFTPHeader.h ---*
*--- ---*
*--- This file defines common constants for a very simple remote ---*
*--- file listing server. ---*
*--- ---*
*--- ---- ---- ---- ---- ---- ---- ---- ---- ---*
*--- ---*
*--- Version 1.0 2012 August 9 <NAME> ---*
*--- ---*
*--- Version 1.1 2013 August 15 <NAME> ---*
*--- ---*
*--- Adapted to do more than just list remote files as the ---*
*--- previous remoteFileListingHeader.h. ---*
*--- ---*
*-------------------------------------------------------------------------*/
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <unistd.h> // for close(), read(), write()
#include <arpa/inet.h> // for htons(), bind(), socket()
#include <ncurses.h> // for cursor control
typedef unsigned int uint;
const int MAX_STRING = 80;
const int MAX_PASSWORD_LEN = MAX_STRING;
const int MAX_LINE = 256;
const char DUMMY_PASSWORD_VISIBLE_CHAR = '.';
const char BACKSPACE_CHAR = 127;
#define BAD_PASSWORD_RESPONSE "Bad password!"
#define GOOD_PASSWORD_RESPONSE "Login successful."
#define END_RESPONSE "<end>"
#define NO_FILE_RESPONSE "<no file>"
typedef enum
{
NULL_FTP_ACTION,
LIST_FTP_ACTION,
GET_FTP_ACTION,
PUT_FTP_ACTION,
QUIT_FTP_ACTION
}
ftp_action_t;
#define LIST_CMD "list"
const int LIST_CMD_LEN = sizeof(LIST_CMD) - 1;
#define GET_CMD "get "
const int GET_CMD_LEN = sizeof(GET_CMD) - 1;
#define PUT_CMD "put "
const int PUT_CMD_LEN = sizeof(PUT_CMD) - 1;
#define QUIT_CMD "quit"
const int QUIT_CMD_LEN = sizeof(QUIT_CMD) - 1;</pre>
</p>
<p>
<strong>babyFTPServer.cpp:</strong>
<pre>
/*-------------------------------------------------------------------------*
*--- ---*
*--- babyFTPServer.cpp ---*
*--- ---*
*--- This file defines a very simple file-transfer server ---*
*--- program. ---*
*--- ---*
*--- ---- ---- ---- ---- ---- ---- ---- ---- ---*
*--- ---*
*--- Version 1.0 2012 August 8 <NAME> ---*
*--- ---*
*--- Version 1.1 2013 August 15 <NAME> ---*
*--- ---*
*--- Adapted to do more than just list remote files as the ---*
*--- previous remoteFileListingServer.cpp. ---*
*--- ---*
*-------------------------------------------------------------------------*/
// Compile with:
// $ g++ babyFTPServer.cpp -o babyFTPServer
//
// For extra credit do:
// $ g++ babyFTPServer.cpp -o babyFTPServer -lncurses
#include "babyFTPHeader.h"
#include <sys/types.h> // for open()
#include <sys/stat.h> // for open(), stat()
#include <fcntl.h> // for open()
#include <dirent.h> // for opendir(), readdir(), closedir()
#include <wait.h> // for wait()
#include <signal.h> // for sigaction()
using namespace std;
enum
{
PORT_NUM_CMDLINE_INDEX = 1,
PASSWD_FILENAME_CMDLINE_INDEX
};
const int MAX_NUM_QUEUING_CLIENTS = 5;
#define DIR_NAME "."
#define DEFAULT_PASSWORD_FILENAME ".babyFTPrc"
// PURPOSE: To serve as the SIGCHLD handler. Ignores 'sig'. No return
// value.
void sigchld_handler (int sig
)
{
int status;
pid_t pid;
<strong>// YOUR CODE</strong>
fflush(stdout);
}
// PURPOSE: To replace the first '\n' char appearing in the first 'maxLength'
// chars of 'cPtr' with a '\0'. If neither a '\n' nor a '\0' is found
// in the first 'maxLength' chars then 'cPtr[maxLength-1]' is set to '\0'.
// Returns 'cPtr', or NULL if 'maxLength==0'.
char* removeEndingNewline (char* cPtr,
uint maxLength
)
{
// I. Applicability validity check:
if ( (cPtr == NULL) || (maxLength == 0) )
return(NULL);
// II. Remove ending newline char:
for (uint i = 0; i < maxLength; i++)
{
if (cPtr[i] == '\0')
return(cPtr);
if (cPtr[i] == '\n')
{
cPtr[i] = '\0';
return(cPtr);
}
}
// III. '\n' not found, end string and return:
cPtr[maxLength-1] = '\0';
return(cPtr);
}
// PURPOSE: To get the port number to use either from
// 'argv[PORT_NUM_CMDLINE_INDEX]' (if there are sufficient arguments
// according to 'argc') or by asking the user. Then to attempt to
// open a listening socket on that port. Returns file descriptor of
// listening socket on success or '-1' otherwise.
int createListeningSocket (int argc,
const char* argv[]
)
{
// I. Applicability validity check:
// II. Create listening socket:
// II.A. Get desired port number:
int port;
if (argc > PORT_NUM_CMDLINE_INDEX)
port = strtol(argv[PORT_NUM_CMDLINE_INDEX],NULL,0);
else
{
char text[MAX_STRING];
printf("Desired port number? ");
fgets(text,MAX_STRING,stdin);
port = strtol(text,NULL,0);
}
// II.B. Create listening socket:
int socketDescriptor;
<strong>// YOUR CODE HERE</strong>
// III. Finished:
return(socketDescriptor);
}
// PURPOSE: To get the password, either from the file specified in
// 'argv[PASSWD_FILENAME_CMDLINE_INDEX]' if there are sufficient
// command line arguments according to 'argc', or from file
// 'DEFAULT_PASSWORD_FILENAME', or by asking user. Up to 'maxLength-1'
// chars of password written to 'password'. Returns 'password'.
char* obtainPassword (int argc,
const char* argv[],
char* password,
uint maxLength
)
{
// I. Applicability validity check:
// II. Obtain password:
const char* passwordFilename= (argc > PASSWD_FILENAME_CMDLINE_INDEX)
? argv[PASSWD_FILENAME_CMDLINE_INDEX]
: DEFAULT_PASSWORD_FILENAME;
FILE* passwordFilePtr;
<strong> // YOUR CODE HERE</strong>
if ( true // <strong>CHANGE THIS</strong>
)
{
<strong> // IF YOU DO THE EXTRA-CREDIT REPLACE THESE 2 LINE BELOW:</strong>
printf("Couldn't read %s, password for clients? ",passwordFilename);
fgets(password,maxLength,stdin);
}
else
{
<strong> // DEPENDING ON HOW YOU OPEN YOUR FILE, MAYBE SOMETHING HERE</strong>
}
removeEndingNewline(password,maxLength);
// III. Finished:
return(password);
}
// PURPOSE: To send 'GOOD_PASSWORD_RESPONSE' to the client over socket file
// descriptor 'clientFD' and return 'true' if the password 'read()' from
// 'clientFD' matches 'password', or to send 'BAD_PASSWORD_RESPONSE' to
// the client and return 'false' otherwise.
bool didLogin (int clientFD,
const char* password
)
{
// I. Application validity check:
printf("Process %d authenticating user . . .\n",getpid());
fflush(stdout);
// II. See if user successfully logged-in:
// II.A. Obtain user's password:
char buffer[MAX_LINE];
<strong> // YOUR CODE HERE</strong>
// II.B. Handle when user's password does NOT match:
if ( strncmp(removeEndingNewline(buffer,MAX_LINE),
password,
MAX_PASSWORD_LEN
)
!= 0
)
{
<strong> // YOUR CODE HERE</strong>
printf("Process %d bad password.\n",getpid());
return(false);
}
// II.C. If get here then user's password does match:
<strong> // YOUR CODE HERE</strong>
printf("Process %d good password.\n",getpid());
// III. Finished:
return(true);
}
// PURPOSE: To list the files in the server's current directory to the client
// using file descriptor 'clientFD', followed by 'END_RESPONSE,MAX_LINE'.
// No return value.
void listDir (int clientFD
)
{
// I. Application validity check:
printf("Process %d starting listing current directory.\n",getpid());
fflush(stdout);
// II. List files:
// II.A. Attempt to open the directory:
char buffer[MAX_LINE];
<strong> // YOUR CODE HERE</strong>
// III. Finished:
printf("Process %d finished listing current directory.\n",getpid());
fflush(stdout);
}
// PURPOSE: To send to the client using file descriptor 'clientFD' the file
// whose name is 'read()' from 'clientFD'. No return value.
void getFile (int clientFD
)
{
// I. Applicability validity check:
printf("Process %d attempting to read file.\n",getpid());
fflush(stdout);
// II. Attempt to get the file:
// II.A. Attempt to 'read()' the filename from 'clientFD':
char buffer[MAX_LINE];
char filename[MAX_LINE];
<strong> // YOUR CODE HERE</strong>
// II.B. Attempt to open file:
<strong> // YOUR CODE HERE</strong>
// II.C. Attempt to get file's size:
<strong> // YOUR CODE HERE</strong>
// II.D. Tell client about the file:
printf("Process %d getting %s.\n",getpid(),buffer);
fflush(stdout);
// II.D.1. Tell client how many bytes the file has:
<strong> // YOUR CODE HERE</strong>
// II.D.2. Tell client the chars of the file:
<strong> // YOUR CODE HERE</strong>
// II.E. Close file:
<strong> // YOUR CODE HERE</strong>
// III. Finished:
printf("Process %d read file %s.\n",getpid(),<yourFileNameVar>);
fflush(stdout);
}
// PURPOSE: To handle the client whom talking to over socket file descriptor
// 'clientFD' and that should authenticate with password '<PASSWORD>'.
// Returns 'EXIT_SUCCESS' if session went well or 'EXIT_FAILURE'
// otherwise.
int handleClient (int clientFD,
const char* password
)
{
// I. Application validity check:
if ( !didLogin(clientFD,password) )
{
close(clientFD);
return(EXIT_FAILURE);
}
// II. Handle client:
int status = EXIT_SUCCESS;
char buffer[MAX_LINE];
// II.A. Each iteration attempts to handle another
// command coming from the client:
while (true)
{
// II.A.1. 'read()' command from client:
int numChars = read(clientFD,buffer,MAX_LINE);
if (numChars < 0)
{
status = EXIT_FAILURE;
break;
}
// II.A.2. Handle various commands:
if (strncmp(buffer,QUIT_CMD,QUIT_CMD_LEN) == 0)
{
printf("Process %d quitting.\n",getpid());
fflush(stdout);
break;
}
else
if (strncmp(buffer,LIST_CMD,LIST_CMD_LEN) == 0)
{
listDir(clientFD);
}
else
if (strncmp(buffer,GET_CMD,GET_CMD_LEN) == 0)
{
getFile(clientFD);
}
}
// III. Finished:
return(status);
}
// PURPOSE: To listen on socket 'listeningSocketId' for clients, let them
// attempt to authenticate with password '<PASSWORD>', and to send list
// of current directory entries to those that are successful. No return
// value.
void doServer (int listeningSocketId,
const char* password
)
{
// I. Applicability validity check:
// II. Serve:
// II.A. Each iteration serves one client
bool shouldServe = true;
while (shouldServe)
{
// II.A.1. Open communication with client:
int clientDescriptor = accept(listeningSocketId,NULL,NULL);
// II.A.2. Handle client:
if (fork() == 0)
{
exit(handleClient(clientDescriptor,password));
}
}
// III. Finished:
}
// PURPOSE: To get a port and function as a server on that port that sends
// to clients a listing of the entries in the current directory.
// First command line argument (if present) taken as port to use.
// Second command line argument (if present) taken as filename containing
// password to authenticate users.
int main (int argc,
const char* argv[]
)
{
// I. Applicability validity check:
// II. Do server:
// II.A. Setup for server:
char password[MAX_PASSWORD_LEN];
int listeningSocketId;
if ( (listeningSocketId = createListeningSocket(argc,argv)) < 0 )
return(EXIT_FAILURE);
obtainPassword(argc,argv,password,MAX_PASSWORD_LEN);
<strong>// YOUR CODE HERE to make sigchld_handler() the handler for SIGCHLD</strong>
// II.B. Do server:
doServer(listeningSocketId,password);
// III. Finished:
close(listeningSocketId);
return(EXIT_SUCCESS);
}</pre>
</p>
<script type="text/javascript" src="/d2l/common/math/MathML.js?v=10.7.2.7100-324 "></script><script type="text/javascript">document.addEventListener('DOMContentLoaded', function() { D2LMathML.DesktopInit('https://s.brightspace.com/lib/mathjax/2.6.1/MathJax.js?config=MML_HTMLorMML','https://s.brightspace.com/lib/mathjax/2.6.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML'); });</script></body></html><file_sep>/last.c
// Open a directory
DIR* dirPtr = opendir(".");
if (dirPtr == NULL)
{
fprintf(stderr,"Could not open .\n");
exit(EXIT_FAILURE);
}
struct dirEnt* dirEntryPtr;
dirEntryPtr = readdir(dirPtr);
if (dirEntryPtr == NULL)
{
fprintf(stderr,". is an empty directory\n");
exit(EXIT_FAILURE);
}
int socketFD;
const char* cPtr;
for ( cPtr = dirEntryPtr->d_name
*cPtr != '\0';
cPtr++
)
write(socketFD,cPtr,1);
write(socketFD,cPtr,1);
closedir(dirPtr);
|
4ea00b0e7b51a8a1b53c2de200ce19b806a3fb9c
|
[
"C",
"HTML"
] | 2 |
HTML
|
ayoolaao/CSC374_COMPUTER_SYSTEMS_2
|
e7932c153b887608c6be5d66539bcb373c3c5557
|
246367a257e5a418955db751a334b9b5ebae496d
|
refs/heads/main
|
<file_sep>module github.com/hackformissions/discipulador
go 1.13
require (
github.com/BurntSushi/toml v0.3.1
github.com/PuerkitoBio/goquery v1.6.0
github.com/aymerick/douceur v0.2.0 // indirect
github.com/chris-ramon/douceur v0.2.0
github.com/foolin/goview v0.3.0
github.com/gorilla/css v1.0.0
github.com/jcelliott/lumber v0.0.0-20160324203708-dd349441af25 // indirect
github.com/labstack/echo/v4 v4.1.17
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd
github.com/nanobox-io/golang-scribble v0.0.0-20190309225732-aa3e7c118975
github.com/stretchr/testify v1.4.0
golang.org/x/net v0.0.0-20200822124328-c89045814202
)
<file_sep>package model
type Person struct {
ID string `json:"id,omitempty"`
Firstname string `json:"nome,omitempty"`
Contactinfo `json:"contato,omitempty"`
Birthdate string `json:"aniversario,omitempty"`
}
type Contactinfo struct {
Address string `json:"endereco,omitempty"`
City string `json:"cidade,omitempty"`
Zipcode string `json:"cep,omitempty"`
Phone string `json:"telefone,omitempty"`
Email string `json:"email,omitempty"`
}
<file_sep># Idéia:
Durante a quarentena, a população idosa ficou impedida de ver familiares e de realizar as atividades diárias que possuíam. Com isso, a saúde mental de muitos se viu fragilizada, acometendo-os de medo, estresse e solidão. Muitos não possuíam a habilidade básica de comunicação pelas redes sociais, dificultando, ainda mais, a sua interação com a vida fora de casa. Nosso grupo abraçou este problema, e começamos a pensar quais ações poderiam ser tomadas para que estes efeitos sejam minimizados na vida do idoso? Tivemos a idéia então de criar um sistema para idosos ("preciosos"), que ajuda a acompanhá-los.
# Objetivos:
**Objetivo principal**
- Fornecer uma solução para o discipulado de pessoas da terceira idade (preciosos), com acompanhamento individual
**Objetivos secundários**
- Orientar na saúde mental do precioso
- Oferecer conteúdo bíblico
- Gerar engajamento e interação do precioso
[Apresentação detalhada do projeto](https://docs.google.com/presentation/d/1BXm2HNW1eh9b9wU_JP_d342fmw4iCKRggohnpPkIkwc/edit?usp=sharing)
# Como executar:
O projeto foi desenvolvido utilizando a linguagem de programação [GO](https://golang.org). Uma vez instalado, basta executar:
```go
go run main.go
```
Para visualizar o sistema, acesse o seguinte URL:
```
http://127.0.0.1:9090
```

Devido ao tempo limitado, apenas as funcionalidades básicas foram implementas através de chamadas REST api.
- Criar discipulado:
```
curl -X POST http://127.0.0.1:9090/discipulados -H 'Content-Type: application/json' -d '{"nome":"<NAME>","aniversario": "01/01/1968", "contato": { "endereco":"Rua Mestre Pastinha, n. 147, Edf. Beija-Flor, Apt. 248", "cidade": "Salvador, Bahia", "telefone": "7155556666", "email":"<EMAIL>"}}'
```
- Listar discipulado:
```
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://127.0.0.1:9090/discipulados/3f9cead049d4e688231cb146086b3dea999db6b7af00fc756d68ebc3b83dc65f
```
- Remover discipulado:
```
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X DELETE http://127.0.0.1:9090/discipulados/3f9cead049d4e688231cb146086b3dea999db6b7af00fc756d68ebc3b83dc65f
```

<file_sep>package storage
import (
"github.com/hackformissions/discipulador/model"
"testing"
"time"
)
func TestMain(t *testing.T) {
// storage
db, err := Init("./test_data")
if err != nil {
t.Fatalf("Failure. err=%s", err)
}
p := &model.Person{
ID: time.Now().String(),
Firstname: "T O",
}
db.Write(PERSON_STORE, p.ID, p)
db.Mu.RLock()
pp := db.UnsafeReadAllPersons()
if len(pp) != 1 {
t.FailNow()
}
db.Mu.RUnlock()
db.Delete(PERSON_STORE, p.ID)
pp = db.UnsafeReadAllPersons()
if len(pp) != 0 {
t.FailNow()
}
}
<file_sep>package storage
import (
"encoding/json"
"github.com/nanobox-io/golang-scribble"
"log"
"sync"
"github.com/hackformissions/discipulador/model"
)
const (
PERSON_STORE = "person"
)
type Store struct {
Mu sync.RWMutex
db *scribble.Driver
discipulados map[string]*model.Person
}
func Init(path string) (*Store, error) {
// a new scribble driver, providing the directory where it will be writing to,
// and a qualified logger if desired
db, err := scribble.New(path, nil)
if err != nil {
log.Printf("Unable to initialize storage. err=%s", err)
return nil, err
}
// load existing data
records, err := db.ReadAll(PERSON_STORE)
d := make(map[string]*model.Person)
if err != nil {
log.Printf("No previous data. err=%s", err)
} else {
for _, p := range records {
person := &model.Person{}
if err := json.Unmarshal([]byte(p), person); err != nil {
log.Printf("Unable to unmarshal data. err=%s", err)
}
d[person.ID] = person
}
}
return &Store{
db: db,
discipulados: d,
}, nil
}
func (s *Store) Write(collection string, resource string, v interface{}) error {
err := s.db.Write(collection, resource, v)
if err != nil {
log.Printf("Unable to write to Store. err=%s", err)
} else {
switch v.(type) {
case *model.Person:
s.Mu.Lock()
defer s.Mu.Unlock()
person := v.(*model.Person)
s.discipulados[person.ID] = person
}
}
return err
}
func (s *Store) UnsafeReadAllPersons() map[string]*model.Person {
return s.discipulados
}
func (s *Store) Delete(collection, resource string) error {
err := s.db.Delete(collection, resource)
if err != nil {
log.Printf("Unable to delete from Store. err=%s", err)
} else {
s.Mu.Lock()
defer s.Mu.Unlock()
switch collection {
case PERSON_STORE:
delete(s.discipulados, resource)
}
}
return err
}
<file_sep>package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"github.com/foolin/goview/supports/echoview-v4"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"log"
"net/http"
"time"
"github.com/hackformissions/discipulador/model"
"github.com/hackformissions/discipulador/storage"
)
var db *storage.Store
func main() {
var err error
// Enable line numbers in logging
log.SetFlags(log.LstdFlags | log.Lshortfile)
// storage
db, err = storage.Init("./data")
if err != nil {
log.Panicf("Failure. err=%s", err)
}
// Echo instance
e := echo.New()
e.Static("/", "static")
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
//Set Renderer
e.Renderer = echoview.Default()
// Routes
e.GET("/", func(c echo.Context) error {
//render with master
return c.Render(http.StatusOK, "index", echo.Map{
"title": "Preciosos",
"add": func(a int, b int) int {
return a + b
},
})
})
e.GET("/discipulado", func(c echo.Context) error {
//render with master
db.Mu.RLock()
defer db.Mu.RUnlock()
pp := db.UnsafeReadAllPersons()
return c.Render(http.StatusOK, "discipulado", echo.Map{
"title": "Preciosos: Lista de Discipulados cadastrados",
"persons": pp,
"now": time.Now().Format("Mon Jan _2 15:04:05 2006"),
})
})
// Routes: discipulados (REST API)
e.GET("/discipulados", func(c echo.Context) error {
db.Mu.RLock()
defer db.Mu.RUnlock()
pp := db.UnsafeReadAllPersons()
return c.JSON(http.StatusOK, pp)
})
e.GET("/discipulados/:id", func(c echo.Context) error {
db.Mu.RLock()
defer db.Mu.RUnlock()
pp := db.UnsafeReadAllPersons()
return c.JSON(http.StatusOK, pp[c.Param("id")])
})
e.DELETE("/discipulados/:id", func(c echo.Context) error {
err := db.Delete(storage.PERSON_STORE, c.Param("id"))
if err != nil {
return c.JSON(http.StatusBadRequest, "FAIL")
}
return c.JSON(http.StatusOK, "OK")
})
e.POST("/discipulados", func(c echo.Context) error {
p := new(model.Person)
if err = c.Bind(p); err != nil {
return c.JSON(http.StatusBadRequest, err)
}
jsonString, _ := json.Marshal(p)
hashId := sha256.Sum256([]byte(jsonString))
p.ID = hex.EncodeToString(hashId[:])
if err = db.Write(storage.PERSON_STORE, p.ID, p); err != nil {
return c.JSON(http.StatusBadRequest, err)
}
return c.JSON(http.StatusOK, p)
})
e.GET("/page", func(c echo.Context) error {
//render only file, must have full name with extension
return c.Render(http.StatusOK, "page.html", echo.Map{"title": "Page file title!!"})
})
// Start server
e.Logger.Fatal(e.Start(":9090"))
}
|
a4cf75a0cbd79ea4534aa353ec86f6215dc62862
|
[
"Go",
"Go Module",
"Markdown"
] | 6 |
Go Module
|
hackformissions/discipulador
|
5030530349b982345e7ea297fe6dd29a01423127
|
c68340ec4d02bc13a98ba215ea68f401f61e0605
|
refs/heads/master
|
<file_sep>var description = [
"/images/shizuka/img_1.png",
"/images/shizuka/img_2.png",
"/images/shizuka/img_3.png",
"/images/shizuka/img_4.png",
"/images/shizuka/img_5.png",
"/images/shizuka/img_6.png",
"/images/shizuka/img_7.png",
"/images/shizuka/img_8.png",
"/images/shizuka/img_9.png",
];
var size = description.length
var x = Math.floor(size*Math.random())
document.getElementById('shizuka').src=description[x];
|
8c061b7784c2f22918a27aa0ae0731f84e801a26
|
[
"JavaScript"
] | 1 |
JavaScript
|
chi28050/chi28050.github.io
|
e66633729e9da2ebe8fb52900a098d9eb205eb83
|
1cb510dce183dddf5ce9ff0f6570e369575d954f
|
refs/heads/main
|
<file_sep>from constants import (
SCREEN_WIDTH,
SCREEN_HEIGHT,
GRID_SIZE,
UP,
DOWN,
LEFT,
RIGHT,
WHITE,
GREEN,
)
import random
import pygame
import sys
class Critter:
def __init__(self, id):
self.id = id
self.length = 1
self.positions = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.color = GREEN
def get_head_position(self):
return self.positions[0]
def turn(self, point):
if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction:
return
else:
self.direction = point
def draw(self, surface):
for elem in self.positions:
r = pygame.Rect((elem[0], elem[1]), (GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, WHITE, r, 1)
def reset(self):
self.length = 1
self.positions = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
def move(self):
head = self.get_head_position()
x, y = self.direction
new_pos = (
(head[0] + x * GRID_SIZE) % SCREEN_WIDTH,
(head[1] + y * GRID_SIZE) % SCREEN_HEIGHT,
)
if (len(self.positions) > 2) and (new_pos in self.positions[2:]):
self.reset()
return -1
else:
self.positions.insert(0, new_pos)
if len(self.positions) > self.length:
self.positions.pop()
return 0
def user_input(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.turn(UP)
if event.key == pygame.K_DOWN:
self.turn(DOWN)
if event.key == pygame.K_LEFT:
self.turn(LEFT)
if event.key == pygame.K_RIGHT:
self.turn(RIGHT)
<file_sep>from constants import GRID_SIZE, GRID_WIDTH, GRID_HEIGHT, WHITE
import random
import pygame
class Food:
def __init__(self, id):
self.id = id
self.position = (0, 0)
self.color = WHITE
self.randomize_position()
self.randomize_color()
def draw(self, surface):
r = pygame.Rect((self.position[0], self.position[1]), (GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, WHITE, r, 1)
def reset(self):
pass
def randomize_position(self):
self.position = (
random.randint(0, GRID_WIDTH - 1) * GRID_SIZE,
random.randint(0, GRID_HEIGHT - 1) * GRID_SIZE,
)
def randomize_color(self):
self.color = (
random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255),
)
<file_sep>import pygame
from constants import (
SCREEN_WIDTH,
SCREEN_HEIGHT,
GRID_SIZE,
FRAME_RATE,
GRID_WIDTH,
GRID_HEIGHT,
WHITE,
)
from critter import Critter
from food import Food
def draw_grid(surface):
for y in range(0, int(GRID_HEIGHT)):
for x in range(0, int(GRID_WIDTH)):
r = pygame.Rect(x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE)
pygame.draw.rect(surface, WHITE, r)
def main():
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
surface = pygame.Surface(screen.get_size())
surface = surface.convert()
snake = Critter(0)
food = Food(0)
draw_grid(surface)
myfont = pygame.font.SysFont("monospace", 16)
score = 0
while True:
clock.tick(FRAME_RATE)
snake.user_input()
draw_grid(surface)
result = snake.move()
if result == -1:
score = 0
if snake.get_head_position() == food.position:
snake.length += 1
score += 1
food.randomize_position()
food.randomize_color()
snake.draw(surface)
food.draw(surface)
screen.blit(surface, (0, 0))
text = myfont.render(f"Score: {score}", 1, (0, 0, 0))
screen.blit(text, (5, 10))
pygame.display.update()
main()
<file_sep># pygame-snake
Simple snake recreation using the pygame python library.
## Tools
* Pygame - [pygame](https://www.pygame.org/docs/)
## Installation
Easiest way to install is using Git via the command line.
You can install git here: [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git).
Once installed, run via your terminal:
```
$> git clone https://github.com/MaciejKrzysiak/pygame-snake.git
$> cd pygame-snake
$> pip install pygame
$> python3 pygame-snake.py
```
If you do not have python3 installed, see here: [Python](https://realpython.com/installing-python/).
<file_sep>SCREEN_WIDTH = 480
SCREEN_HEIGHT = 480
GRID_SIZE = 20
GRID_WIDTH = SCREEN_WIDTH / GRID_SIZE
GRID_HEIGHT = SCREEN_HEIGHT / GRID_SIZE
FRAME_RATE = 10
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
WHITE = (255, 255, 255)
GREEN = (0, 128, 0)
|
d1c838310d5020e8604a77220960e85570257de2
|
[
"Markdown",
"Python"
] | 5 |
Python
|
MaciejKrzysiak/pygame-snake
|
3d1f7f7d4fc38c184f5ba6d8af882d6cece40b74
|
284b953d31c6ff6bc2d1598c031f13863d619299
|
refs/heads/master
|
<file_sep>package com.textventure.main;
import java.util.Scanner;
public class Main {
private static boolean running = true;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(running){
String inToLowerCase = scan.nextLine().toLowerCase();
}
scan.close();
}
}
<file_sep>package com.textventure.models.command;
public abstract class Command {
}
<file_sep>package com.textventure.models;
import com.textventure.world.World;
public abstract class Item {
protected String name;
protected String description;
protected long item_id = getCurGlobalID();
protected boolean pickable = false;
protected boolean consumable = false;
protected boolean clickable = false;
protected boolean stateChangeable = false;
protected boolean isKey = false;
//
//global item ID for initializing every item_id
//
private static long globalItemID = 0;
//
//method to get and increase the global item ID
//
private long getCurGlobalID(){
globalItemID++;
return globalItemID;
}
//
//Constructor
//
public Item(String name, String description){
this.name = name;
this.description = description;
}
//
//abstract methods
//
public abstract void processEffects(World world);
//
//Getters and Setters
//
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public long getItem_id() {
return item_id;
}
public void setItem_id(long item_id) {
this.item_id = item_id;
}
public boolean isPickable() {
return pickable;
}
public void setPickable(boolean pickable) {
this.pickable = pickable;
}
public boolean isConsumable() {
return consumable;
}
public void setConsumable(boolean consumable) {
this.consumable = consumable;
}
public boolean isClickable() {
return clickable;
}
public void setClickable(boolean clickable) {
this.clickable = clickable;
}
public boolean isStateChangeable() {
return stateChangeable;
}
public void setStateChangeable(boolean stateChangeable) {
this.stateChangeable = stateChangeable;
}
public boolean isKey() {
return isKey;
}
public void setKey(boolean isKey) {
this.isKey = isKey;
}
}
<file_sep>
# Textventure
A wonderful text adventure taking you through a exciting story
Just try it. If you like it great! If not open an issue :D
<file_sep>package com.textventure.models;
public class Connection {
protected Room room_one, room_two;
protected boolean can_pass = false;
private long connectionId = getCurrGlobalId();
protected String description;
//
// Algorithm for global id assignment
//
private static long globalConnectionId = 0;
protected long getCurrGlobalId() {
globalConnectionId ++;
return globalConnectionId;
}
//
// Constructors
//
public Connection(Room room_one, Room room_two, boolean can_pass, String description) {
super();
this.room_one = room_one;
this.room_two = room_two;
this.can_pass = can_pass;
this.description = description;
}
//
// Getters and Setters
//
public Room getRoom_one() {
return room_one;
}
public void setRoom_one(Room room_one) {
this.room_one = room_one;
}
public Room getRoom_two() {
return room_two;
}
public void setRoom_two(Room room_two) {
this.room_two = room_two;
}
public boolean isCan_pass() {
return can_pass;
}
public void setCan_pass(boolean can_pass) {
this.can_pass = can_pass;
}
public long getConnectionId() {
return connectionId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
<file_sep>package com.textventure.models;
import java.util.ArrayList;
public enum Direction {
North("n","north"),
South("s","south"),
West("w","west"),
East("e","east"),
Northwest("nw","northwest"),
Northeast("ne","northeast"),
Southwest("sw","southwest"),
Southeast("se","southeast"),
Up("u","up"),
Down("d","down"),
This("t","this"),
;
public String abbreviation;
public String full;
public static Direction[] dirs = {North,South,West,East,Northeast,Northwest,Southwest,Southeast,Up,Down,This};
private Direction(String abbreviation, String full){
this.abbreviation = abbreviation;
this.full = full;
}
public Direction getReversedDirection(Direction direction){
if(direction == North){
return South;
}else if(direction == South){
return North;
}else if(direction == West){
return East;
}else if(direction == East){
return West;
}else if(direction == Northwest){
return Southeast;
}else if(direction == Northeast){
return Southwest;
}else if(direction == Southwest){
return Northeast;
}else if(direction == Southeast){
return Northwest;
}else if(direction == Up){
return Down;
}else if(direction == Down){
return Up;
}else if(direction == This){
return This;
}
return null;
}
public Direction getDirection(String direction){
for(int i=0;i<dirs.length;i++){
if(direction.equals(dirs[i].abbreviation) || direction.equals(dirs[i].full)){
return dirs[i];
}
}
return null;
}
}
|
6d72644d5e68049ab19f438c16bdc49d9ff2ba25
|
[
"Markdown",
"Java"
] | 6 |
Java
|
PhilippRo/Textventure
|
ac6687cd0da9f72525130c45253a85b61ce69500
|
0587e92ea474a91e0b4fd639a60d21a6fd9c7198
|
refs/heads/master
|
<file_sep>package yomecolle;
import mainpack.messageFrame;
public class Yomecolle {
public static void main(String[] args) throws Exception {
String _yomeId = "154";
String file = "card/154/1/1.png";
String voiceFile = "voice/154/1/1.wav";
String text = "test1";
String _cardId = "1";
String _voiceId = "1";
String _question = "test2";
String _okAnswer = "test3";
String _ngAnswer = "test4";
String _okChoiceVoice = "test5";
String _ngChoice = "test6";
messageFrame message = new messageFrame(_yomeId, _cardId);
// message.Showmessage(file, "", "");
message.setmessage(_cardId, _voiceId, _question, _okAnswer, _ngAnswer, _okChoiceVoice, _ngChoice);
}
}
<file_sep>import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class encrypt {
private int count;
private static int min = 128;
private static int max = 254;
private static String folder = "";
private static String newfolder = "";
public static void main(String[] args) throws Exception {
String path = "C:\\Documents and Settings\\user\\Desktop\\";
folder = "yomeData";
newfolder = folder+"_out";
getFolder(path+folder);
System.out.println("...all done");
}
public static void getFolder(String outFolder) {
System.out.println("processing folder "+outFolder+"...");
String[] str = {"png","mp3"};
File dir = new File(outFolder);
File[] files = dir.listFiles();
File dirFile = null ;
try {
dirFile = new File(outFolder.replaceFirst(folder, newfolder));
if ( ! (dirFile.exists()) && ! (dirFile.isDirectory())) {
boolean creadok = dirFile.mkdirs();
if (creadok) {
} else {
}
}
} catch (Exception e) {
e.printStackTrace();
// System.out.println(e);
// return false ;
}
for(int i=0;i<files.length;i++){
if (files[i].isDirectory()){
getFolder(files[i].getPath());
}
else{
String fileType = files[i].getName().substring(files[i].getName().lastIndexOf('.')+1,files[i].getName().length());
for(int t=0;t<str.length;t++){
if(str[t].equals(fileType.toLowerCase())){
String name = files[i].getPath();
String name2 = files[i].getPath().replaceFirst(folder, newfolder);
try{
fixPng(name, name2);
}catch (Exception e) {
}
}
}
}
}
}
public static void fixPng(String inputFile, String outputFile) throws IOException{
FileInputStream inputStream=new FileInputStream(inputFile);
DataOutputStream out=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
int input;
input = inputStream.read();
int output = 0;
int i = 0;
int add = i;
int[] Mask = new int[max-min+1];
for (i = min;i<=max; i++){
Mask[i-min]= i;
}
i = 0;
while (input != -1){
String string1 = Integer.toBinaryString(input);
while (string1.length() < 8){
string1 = "0" + string1;
}
String string2 = Integer.toBinaryString(Mask[i]);
while (string2.length() < 8){
string2 = "0" + string2;
}
output = 0;
add = 128;
for (int j = 0; j < 8; j++){
if (string1.charAt(j)!=string2.charAt(j)){ output = output + add;}
add = add / 2;
}
out.writeByte(output);
i += 1;
if (i == Mask.length){
i = 0;
}
input = inputStream.read();
}
inputStream.close();
out.close();
}
}
<file_sep>//http://blog.csdn.net/hjd_love_zzt/article/details/21159153
package com.example.groupactiontest;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
public class MyGame implements ApplicationListener {
TextureAtlas atlas;
Sprite sprite;
Animation alienAnimation;
SpriteBatch batch;
float statetime = 0;
@Override
public void create() {
atlas = new TextureAtlas(Gdx.files.internal("pack.atlas"));
sprite = atlas.createSprite("ALIEN");
sprite.setSize(480, 320);
sprite.setPosition(50, 150);
alienAnimation = new Animation(0.25f, atlas.findRegions("ALIEN"));
batch = new SpriteBatch();
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void render() {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
statetime += Gdx.graphics.getDeltaTime();
batch.begin();
sprite.draw(batch);
batch.draw(alienAnimation.getKeyFrame(statetime, true), 0,0,270,150);
batch.end();
}
@Override
public void resize(int arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
}
|
82e4f116b1c07856229fff5f52f365655f6e7a3f
|
[
"Java"
] | 3 |
Java
|
galaxy18/yomeColleAnalysis
|
332d772e20ae8a3e78e5bda52e205b7a57097880
|
bc22078f89ab7e760e94e5ed99e913f5f5978fb9
|
refs/heads/master
|
<file_sep>__author__ = 'sabin'
## reads the number and tell the number of lines in the file.
import gzip, sys
filename = sys.argv[1]
def reading_txtFile(filename):
txtFile = open(filename, 'r')
line_number = sum(1 for line in txtFile)
print " Determining numbers of lines in the file ..."
print " number of lines in ", filename, " is : \n", line_number
txtFile.close()
def reading_gzfile(filename):
gzFile = gzip.open(filename, 'rb')
line_number = sum(1 for line in gzFile)
print " "
print " rDetermining numbers of lines in the file ..."
print " number of lines in ", filename, " is : \n", line_number
gzFile.close()
if filename.endswith('.txt'):
reading_txtFile(filename)
else:
reading_gzfile(filename)<file_sep>__author__ = 'sabin'
#Print the list of drives attached to the server.
import os
volumes = os.popen("mountvol /").read()
print volumes<file_sep>__author__ = 'sabin'
#Print the list of all users that can log into the computer.
import os, exceptions
no_bin_acc = '/bin/false\n'
bin_acc = '/bin/bash\n'
def readPasswdFile():
try:
fp = open("/etc/passwd")
except exceptions.UserWarning:
print " no permission Amigo!"
return "some default data"
else:
with fp:
print "the username who can login are:"
for n in fp.readlines(1):
#print n
nl = n.split(':')
#print "here", nl
if bin_acc in nl:
print nl[0]
#if nl
#user = nl[0]
#print "username", user
#acc = nl[-1]
#print "bin ", acc
#print acc.strip()
# if acc.strip() != no_bin_acc:
# print (user)
# #print(fp.read())
# userlist = fp.read().split(':')
# #nu = userlist[]
# #print nu
# #print userlist
# return fp.read()
# def readPasswdFile():
# if os.access("/etc/passwd", os.R_OK):
# with open("/etc/passwd") as fp:
# s = fp.read()
# #sl = [fp.read().split(':')]
# ss = s.split(':')
#
#
#
# #print ('here')
# print (ss)
# return fp.read()
# else:
# print " no permission may be"
# #return "some default data"
readPasswdFile()<file_sep>__author__ = 'sabin'
## python class to read files ( txt and .gz)
import gzip, sys
filename = sys.argv[1]
def reading_txtFile(filename):
txtFile = open(filename, 'r')
read_txtFile = txtFile.read()
print " reading the content of the file ..."
print " content of ", filename, " is : \n", read_txtFile
txtFile.close()
def reading_gzfile(filename):
gzFile = gzip.open(filename, 'rb')
read_gzFile = gzFile.read()
print " "
print " reading the content of the gzip file ..."
print " content of ", filename, " is : \n", read_gzFile
gzFile.close()
if filename.endswith('.txt'):
reading_txtFile(filename)
else:
reading_gzfile(filename)
<file_sep>__author__ = 'sabin'
## program to copy the files ( .txt and .gz)
import gzip, sys
filename = sys.argv[1]
newfilename = sys.argv[2]
read_txtFile = ''
def reading_txtFile(filename):
txtFile = open(filename, 'r')
read_txtFile = txtFile.read()
return read_txtFile
def maketxtFile(newfilename, w):
new_txtFile = open(newfilename, 'w+')
writeFile = new_txtFile.write(w)
new_txtFile.close()
print('new copy file named: '), newfilename, ' has been created.'
def reading_gzFile(filename):
gzFile = gzip.open(filename,'r')
read_gzFile = gzFile.read()
return read_gzFile
def makegzFile(newfilename, w):
new_gzFile = gzip.open(newfilename, 'w+')
write = new_gzFile.write(w)
new_gzFile.close()
print('new copy file named: '), newfilename, ' has been created.'
if filename.endswith('.txt') and newfilename.endswith('.txt'):
w = reading_txtFile(filename)
maketxtFile(newfilename, w)
elif filename.endswith('.gz') and newfilename.endswith('.gz'):
w =reading_gzFile(filename)
makegzFile(newfilename,w)
elif filename.endswith('.txt') and newfilename.endswith('.gz'):
w = reading_txtFile(filename)
makegzFile(newfilename,w)
elif filename.endswith('.gz') and newfilename.endswith('.txt'):
w = reading_gzFile(filename)
maketxtFile(newfilename,w)
else:
print('Error: check File extensions to copy and make')
<file_sep>__author__ = 'sabin'
#backup folder without simlinks inside it.
# find -type l -delete
# find /usr/local/lib/ -maxdepth 1 -follow -type l -delete
#openssl enc -aes-256-cbc -e -in filepath -out filepath.enc -pass pass:passkey
import gzip, sys, subprocess, datetime
foldername = sys.argv[1]
replica = sys.argv[2]
passkey = sys.argv[3]
now = datetime.datetime.now()
#print now.strftime("%Y-%m-%d-%H-%M-%S")
dtstamp = now.strftime("-%Y-%m-%d-%H-%M-%S")
compress_replica = replica + dtstamp + ".tar.gz"
#copying the folder along with its child folders and files.
ps_copyfolder = subprocess.Popen(['cp', '-r', foldername, replica], stdout=subprocess.PIPE)
ps_copyfolder.wait()
#find and delete the symlinks in the new replicated folder
ps_deletesymlinks = subprocess.Popen(['find', replica, '-type','l', '-delete'])
ps_deletesymlinks.wait()
# compress zip the new backup folder
ps_zip = subprocess.Popen(['tar', '-azcvf',compress_replica,replica])
ps_zip.wait()
#openssl #openssl enc -aes-256-cbc -e -in filepath -out filepath.enc -pass pass:passkey
encrypted_file = compress_replica + ".enc"
pk = "pass:"+passkey
ps_passprotect = subprocess.Popen(['openssl', 'enc', '-aes-256-cbc', '-e', '-in',compress_replica, '-out', encrypted_file, '-pass', pk])
ps_passprotect.wait()
<file_sep>python_training_scripts
=======================
some python scripts for the sysadmin.
<file_sep>__author__ = 'sabin'
#Print the list of all services started during boot in the same order that they are started by Linux.
import os
test = os.ctermid()
print test
|
234b46d95870f516f8b64dfb22f04d545019a5b7
|
[
"Markdown",
"Python"
] | 8 |
Python
|
thinksabin/python_training_scripts
|
36be9fbcba8849d786faa00883ca5baac8a4d0ea
|
ec2c2bb129daadc4fff6958cbef4803ba1dd9a7e
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.