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/main
<repo_name>Evelynxfl/GugongMuseum.github-io<file_sep>/JS/study_research.js window.onload = function(){ /*获取HTML中的对象*/ var parent = document.getElementById("w5Image"); var img_ul = document.getElementById("img_ul"); var litCir_ul = document.getElementById("litCir_ul"); var buttons = document.getElementById("buttons"); var cLis =litCir_ul.children; var len = img_ul.children.length; //图片张数 var width = parent.offsetWidth; //每张图片的宽度 var rate = 30; //一张图片的切换速度,单位为px var times = 1; //切换速度的倍率 var gap = 7000; //自动切换间隙,单位为毫秒 var timer = null; //初始化一个定时器 var picN = 0; //当前显示的图片下标 var cirN = 0; //当前显示图片的小圆点下标 var now; var then = Date.now(); var temp; /*克隆第一个li到列表末*/ img_ul.appendChild(img_ul.children[0].cloneNode(true)); for (var i=0; i<len; i++){ var a_li = document.createElement("li"); a_li.className = 'quiet'; litCir_ul.appendChild(a_li); } litCir_ul.children[0].className = "active"; function autoRoll(){ now = Date.now(); var t = now - then; if(t >= gap){ if(Roll(-(picN+1)*width)){ picN++; cirN++; then = Date.now(); } for(var i=0; i<len; i++){ cLis[i].className = "quiet"; } if(cirN == len){ cirN = 0; } cLis[cirN].className = "active"; if(picN>=len){ img_ul.style.left = 0; picN = 0; } } timer = requestAnimationFrame(autoRoll); } autoRoll(); parent.onmouseover = function(){ cancelAnimationFrame(timer); buttons.style.display = 'block'; } parent.onmouseout = function(){ timer = requestAnimationFrame(autoRoll); buttons.style.display = 'none'; } for(var i=0; i<len; i++){ cLis[i].index = i; cLis[i].onmouseover = function(){ var flag = 0; var rollN = this.index; for(var j=0; j<len; j++){ cLis[j].className = "quiet"; } this.className = "active"; temp = cirN; //当前active点 picN = cirN = this.index; console.log('this.index:'+this.index); times = Math.abs(this.index - temp); //距离上个小圆点的距离 if(times == 0){ return; } console.log('times:'+times); rate = rate*times; //根据距离改变切换速率 function rollTo(){ cancelAnimationFrame(img_ul.timer); if(Roll(-rollN * width)){ flag++; if(flag == times){ cancelAnimationFrame(img_ul.timer); rate = 15; return; } } img_ul.timer = requestAnimationFrame(rollTo); } rollTo(); } } /*上一张*/ buttons.children[0].onclick = previous; /*下一张*/ buttons.children[1].onclick = next; function next(){ cancelAnimationFrame(img_ul.timer); if(Roll(-(picN+1)*width)){ cancelAnimationFrame(img_ul.timer); picN++; cirN++; for(var i=0; i<len; i++){ cLis[i].className = "quiet"; } if(cirN == len){ cirN = 0; } cLis[cirN].className = "active"; if(picN>=len){ img_ul.style.left = 0; picN = 0; } return; } img_ul.timer = requestAnimationFrame(next); } function previous(){ if(picN<=0){ img_ul.style.left = -len*width + "px"; picN = len; } cancelAnimationFrame(img_ul.timer); if(Roll(-(picN-1)*width)){ cancelAnimationFrame(img_ul.timer); picN--; cirN--; for(var i=0; i<len; i++){ cLis[i].className = "quiet"; } if(cirN < 0){ cirN = len-1; } cLis[cirN].className = "active"; return; } img_ul.timer = requestAnimationFrame(previous); } function Roll(distance){ var speed = img_ul.offsetLeft < distance ? rate:(0-rate); img_ul.style.left = img_ul.offsetLeft + speed + "px"; var leave = distance - img_ul.offsetLeft; if(Math.abs(leave)<=Math.abs(speed)){ img_ul.style.left = distance+"px"; return 1; //切换完一张图片 } return 0; } // 图片蒙版 var boxArr = getEleByCN("box"); var imgArr = getEleByCN("img1"); var maskArr = getEleByCN("mask"); var wArr = getImgWidth(imgArr); var hArr = getImgHeight(imgArr); setSize(boxArr,maskArr,wArr,hArr); for(var i=0;i<boxArr.length;i++){ showMask(boxArr[i],maskArr[i]); hideMask(boxArr[i],maskArr[i]); } function showMask(parent,child){ parent.onmouseover = function(){ child.style.display = "block"; } } function hideMask(parent,child){ parent.onmouseout = function(){ child.style.display = "none"; } } function setSize(bArr,mArr,wArr,hArr){ for(var i=0;i<bArr.length;i++){ bArr[i].style.cssText = "width:" + wArr[i] +"px;height:" + hArr[i] + "px"; mArr[i].style.cssText = "width:" + wArr[i] +"px;height:" + hArr[i] + "px;background:rgba(0,0,0,0.15)"; } } function getEleByCN(classname){ return document.getElementsByClassName(classname); } function getImgWidth(imgArr){ var wArr = []; for(var i=0;i<imgArr.length;i++){ wArr.push(imgArr[i].width); } return wArr; } function getImgHeight(imgArr){ var hArr = []; for(var i=0;i<imgArr.length;i++){ hArr.push(imgArr[i].height); } return hArr; } }<file_sep>/README.md # GugongMuseum.github-io<file_sep>/JS/about_history.js $(document).ready(function() { $(".floaty").mousemove(function(event) { var mouseX = event.pageX; var mouseY = event.pageY; var horzAngle = 0; var vertAngle = 0; var obj = $(this); //Maximum angle 30! var objX = obj.offset().left + obj.innerWidth() / 2; var objY = obj.offset().top + obj.innerHeight() / 2; horzAngle = -((objX - mouseX) / (obj.innerWidth()/2)) * 10; vertAngle = ((objY - mouseY) / (obj.innerHeight()/2)) * 10; obj.attr("style", "transform: rotateY("+horzAngle+"deg) rotateX("+vertAngle+"deg) translateZ(50px);-webkit-transform: rotateY("+horzAngle+"deg) rotateX("+vertAngle+"deg) translateZ(50px);-moz-transform: rotateY("+horzAngle+"deg) rotateX("+vertAngle+"deg) translateZ(50px)"); }); $(".floaty").mouseout(function() { var obj = $(this); obj.css({ '-webkit-transform' : 'rotateY(' + 0 + 'deg)', '-moz-transform' : 'rotateY(' + 0 + 'deg)', '-ms-transform' : 'rotateY(' + 0 + 'deg)', '-o-transform' : 'rotateY(' + 0 + 'deg)', 'transform' : 'rotateY(' + 0 + 'deg)' }); }); //endhoveringeffect by @Bloxore $('.back').click(function(){ $('.container-master').toggleClass('toggled'); }); $('.tile').click(function(){ $('html,body').animate({scrollTop:300},0); $('.container-master').toggleClass('toggled'); $('.lyrics-wrapper').empty(); //get title $('.lyrics-title').html($(this).find('.title').html()); //get lyrics $list = $(this).find('ul li'); $list.each(function(i, li){ console.log(i,li); var lyricsText = '<div class="lyrics-card">'+$(li).html()+'</div>'; $('.lyrics-wrapper').append(lyricsText); setTimeout(function(){ var lis = $('.lyrics-card'); for (var i = 0; i < lis.length; i++) { $(lis[i]).delay(i*500).animate({'top': '0','opacity':1}, 1000); } }, 800); }); }); });<file_sep>/JS/theImperialPalaceWallpaper.js $(function () { gaiBian($('.shouCang1')); gaiBian($('.shouCang2')); gaiBian($('.shouCang3')); gaiBian($('.shouCang4')); gaiBian($('.shouCang5')); gaiBian($('.shouCang6')); gaiBian($('.shouCang7')); gaiBian($('.shouCang8')); gaiBian($('.shouCang9')); gaiBian1($('.faSong1')); gaiBian1($('.faSong2')); gaiBian1($('.faSong3')); gaiBian1($('.faSong4')); gaiBian1($('.faSong5')); gaiBian1($('.faSong6')); gaiBian1($('.faSong7')); gaiBian1($('.faSong8')); gaiBian1($('.faSong9')); gaiBian2($('.xiaZai1')); gaiBian2($('.xiaZai2')); gaiBian2($('.xiaZai3')); gaiBian2($('.xiaZai4')); gaiBian2($('.xiaZai5')); gaiBian2($('.xiaZai6')); gaiBian2($('.xiaZai7')); gaiBian2($('.xiaZai8')); gaiBian2($('.xiaZai9')); function gaiBian(duiXiang) { var toggle=true; duiXiang.click(function () { if (toggle) { duiXiang.attr("src","./images/images1/收藏后.png") alert("收藏成功!"); toggle=false; }else{ duiXiang.attr("src","./images/images1/收藏.png") toggle=true; } }); } function gaiBian1(duiXiang) { var toggle=true; duiXiang.click(function () { if (toggle) { duiXiang.attr("src","./images/images1/收藏后.png") alert("分享成功!"); toggle=false; }else{ duiXiang.attr("src","./images/images1/收藏.png") toggle=true; } }); } function gaiBian2(duiXiang) { var toggle=true; duiXiang.click(function () { if (toggle) { duiXiang.attr("src","./images/images1/收藏后.png") alert("下载成功!"); toggle=false; }else{ duiXiang.attr("src","./images/images1/收藏.png") toggle=true; } }); } var toggle=true; $('.gouXuanTu').click(function (argument) { if (toggle) { $('.gouXuanTu').attr("top","-20px") toggle=false; }else{ $('.gouXuanTu').attr("top","0") toggle=true; } }) window.selectFocus=function (that) { $(that).attr("size",5); }; window.selectClick=function (that) { $(that).parent().removeAttr('size'); $(that).parent().blur(); $(that).parent().children("[selected='selected']").removeAttr('selected'); $(taht).attr("selecter",""); } }) window.onload=function () { var box = document.getElementsByClassName("gouXuanTu")[0]; var flag = true; box.onclick = function(){ if(flag){ box.style.cssText="top:-20px;"; }else{ box.style.cssText="top:0px;"; } flag = !flag; } } <file_sep>/JS/explor_sketch.js $(function(){ var num=0; var btnLeft=$(".prev"); var btnRight=$(".next"); var Id=$(".head"); var oUl=Id.find("ul"); var oLi=oUl.find("li"); var oLiLen=oLi.length; var curHtml="<div class='cur'></div>"; Id.append(curHtml); var oCur=$(".cur"); // 动态添加小圆点 for(var i=0;i<oLiLen;i++){ var curA="<span></span>" oCur.append(curA); } var oCurSpan=oCur.find("span"); var oCurS=oCur.find("span:first"); oCurS.addClass('active') // 自动轮播 var t=setInterval(function(){ num++; lunbo(); },3000); // 左箭头按钮 btnLeft.on("click",function(){ num--; lunbo(); }) //右箭头按钮 btnRight.on("click",function(){ num++; lunbo(); }) function lunbo(){ if(num==oLiLen){ num=0; } oLi.eq(num).fadeIn(1500).siblings(num).fadeOut(1500); oCurSpan.eq(num).addClass('active').siblings(num).removeClass('active'); } lunbo(); }); window.onload=function(){ var lis=document.getElementsByClassName("img1"); var contains=document.getElementsByClassName("contain"); var img=document.getElementsByClassName("img"); var t=document.getElementsByClassName("t"); var daohang=document.getElementsByClassName("header")[0]; var nav=document.getElementById("nav1"); var returnTop=document.getElementById("return"); show1(contains,lis); show2(img,t); show3(nav,daohang,returnTop); } function show1(contains,lis){ for(var i=0;i<contains.length;i++){ lis[i].index = i; lis[i].onmouseover=function(){ lis[this.index].style.opacity="0.95"; } lis[i].onmouseout=function(){ lis[this.index].style.opacity="1"; } lis[i].onclick=function(){ for(var i=0;i<contains.length;i++){ contains[i].style.display="none"; } contains[this.index].style.display="block"; } } } function show2(img,t){ for(var i=0;i<img.length;i++){ img[i].index = i; t[i].index = i; img[i].onmouseenter=function(){ t[this.index].style.marginTop="195px"; } t[i].onmouseleave=function(){ t[this.index].style.marginTop="-185px"; } } } function show3(nav,daohang,returnTop){ var H=daohang.offsetHeight; window.onscroll=function(){ var scrollTop=document.documentElement.scrollTop; // var Y=document.documentElement.scrollTop; if(scrollTop>H){ nav.style.cssText="position:fixed;top=0;display:block;margin:-48px auto;"; } if(scrollTop<H){ nav.style.cssText="display:none;"; } if(scrollTop>0){ returnTop.style.display="block"; } if(scrollTop==0){ returnTop.style.display="none"; } returnTop.onclick=function(){ document.documentElement.scrollTop=0; } } } <file_sep>/JS/guide_map.js $(document).ready(function() { //绑定元素点击事件 $(".map_left_cell2").click(function() { //判断对象是显示还是隐藏 if($(this).children(".map_left_cell3").is(":hidden")){ //表示隐藏 if(!$(this).children(".map_left_cell3").is(":animated")) { // $(this).children(".map_left_nav3").css('color:pink'); //如果当前没有进行动画,则添加新动画 $(this).children(".map_left_cell3").animate({ height: 'show' }, 800) //siblings遍历div1的元素 .end().siblings().find(".map_left_cell3").hide(800); } } else { //表示显示 if(!$(this).children(".map_left_cell3").is(":animated")) { // $(this).children(".btn1").css({'transform':'rotate(360deg)'}); $(this).children(".map_left_cell3").animate({ height: 'hide' }, 800) .end().siblings().find(".map_left_cell3").hide(800); } } }); //阻止事件冒泡,子元素不再继承父元素的点击事件 $('.map_left_cell2').click(function(e){ e.stopPropagation(); }); //点击子菜单为子菜单添加样式,并移除所有其他子菜单样式 $(".map_left_nav3").click(function() { //设置当前菜单为选中状态的样式,并移除同类同级别的其他元素的样式 $(this).addClass("removes").siblings().removeClass("removes"); //遍历获取所有父菜单元素 $(".map_left_nav3").each(function(){ //判断当前的父菜单是否是隐藏状态 if($(this).is(":hidden")){ //如果是隐藏状态则移除其样式 $(this).children(".map_left_nav3").removeClass("removes"); } }); }); }); window.onload=function(){ var imgH, imgW, img = document.getElementById('pic'), big=document.getElementById('big'); big.onclick = function(){ imgH=img.height; imgW=img.width; boxH=box.height; boxW=box.width; img.height = 1188*1.4; img.width = 870*1.2; } small.onclick=function(){ imgH=img.height; imgW=img.width; boxH=box.height; boxW=box.width; img.height = 1188; img.width = 870; } } <file_sep>/JS/show.js $(function() { //代码初始化 var size=$(".img li").size(); for (var i = 1; i <= size; i++) { var li="<li></li>"; $(".num").append(li); }; //手动控制轮播效果 $(".img li").eq(0).show(); $(".num li").eq(0).addClass("active"); $(".num li").mouseover(function() { $(this).addClass("active").siblings().removeClass("active"); var index = $(this).index(); i=index; $(".img li").eq(index).fadeIn(1800).siblings().fadeOut(1800); }) //自动 var i = 0; var t = setInterval(move, 1800); //核心向左的函数 function moveLeft() { i--; if (i == -1) { i = size-1; } $(".num li").eq(i).addClass("active").siblings().removeClass("active"); $(".img li").eq(i).fadeIn(1800).siblings().fadeOut(1800); } //核心向右的函数 function move() { i++; if (i == size) { i = 0; } $(".num li").eq(i).addClass("active").siblings().removeClass("active"); $(".img li").eq(i).fadeIn(1800).siblings().fadeOut(1800); } //定时器的开始与结束 $(".out").hover(function() { clearInterval(t); }, function() { t = setInterval(move, 1800) }) window.onbeforeunload=function(){ document.documentElement.scrollTop=0; document.body.scrollTop=0; } var flag=true; var go_top=document.getElementById('go_top'); $(window).scroll(function(){ var s=$(window).scrollTop(); if(s>620&&s<30000){ if(flag){ go_top.style.display="block"; } } if(s<620){ if(flag){ go_top.style.display="none"; } } }) }) window.onload=function(){ var spe1=document.getElementById('special1'); var spe3=document.getElementById('special3'); var box=document.getElementById('spe_box_all'); spe1.onclick=function(){ box.style.marginLeft='0'; } spe3.onclick=function(){ box.style.marginLeft='-232px'; } var buttomArr=document.getElementsByClassName('out_buttom_cell'); var boxArr=document.getElementsByClassName('out_box_cell'); for(var i=0;i<buttomArr.length;i++){ buttomArr[0].onclick=function(){ for(var j=0;j<boxArr.length;j++){ boxArr[j].style.display='none'; buttomArr[j].style.background='none'; } boxArr[0].style.display='block'; buttomArr[0].style.cssText='background-image: url(images/images2/out_bottom_cell.png)'; } buttomArr[1].onclick=function(){ for(var j=0;j<boxArr.length;j++){ boxArr[j].style.display='none'; buttomArr[j].style.background='none'; } boxArr[1].style.display='block'; buttomArr[1].style.cssText='background-image: url(images/images2/out_bottom_cell.png)'; } buttomArr[2].onclick=function(){ for(var j=0;j<boxArr.length;j++){ boxArr[j].style.display='none'; buttomArr[j].style.background='none'; } boxArr[2].style.display='block'; buttomArr[2].style.cssText='background-image: url(images/images2/out_bottom_cell.png)'; } } }
5ca6613b18660f59a23f643d17f8265f0339c073
[ "JavaScript", "Markdown" ]
7
JavaScript
Evelynxfl/GugongMuseum.github-io
8c8c45a8a434e3b3949fe4814e497b1a89baca7f
d00b8712ada89735f9d0f786c4b71a623ee6ddcb
refs/heads/master
<file_sep>package com.wx.message; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpRetryException; import java.net.HttpURLConnection; import java.net.URLConnection; import java.net.URLDecoder; import java.util.Enumeration; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.Element; import org.omg.CORBA.Request; import com.wx.check.WeixinCheck; import com.wx.util.WeixinXmlElement; /** * 接收微信服务器发送过来的信息、指令等 * * @author Administrator * */ public class WeixinMessage extends HttpServlet { public String acceptMessage(HttpURLConnection httpurlconnection,HttpServletRequest request, HttpServletResponse response) throws IOException { BufferedReader in = null; StringBuffer temp = new StringBuffer(); String msgtype = ""; try { //获取Post数据 in = new BufferedReader(new InputStreamReader( httpurlconnection.getInputStream())); String inputLine = in.readLine(); while (inputLine != null) { temp.append(inputLine); inputLine = in.readLine(); } //获取Get数据 String signature=""; String timestamp=""; String nonce= ""; String echostr=""; Enumeration en = request.getParameterNames(); while (en.hasMoreElements()) { String paramName = (String) en.nextElement(); if("signature".equals(paramName)){ signature = request.getParameter(paramName); } if("timestamp".equals(paramName)){ timestamp = request.getParameter(paramName); } if("nonce".equals(paramName)){ nonce = request.getParameter(paramName); } if("echostr".equals(paramName)){ echostr = request.getParameter(paramName); } } //验证微信真实性 String reback = new WeixinCheck().reBackString(signature, timestamp, nonce, echostr); if("0".equals(reback)){ //验证成功 return new WeixinAcceptMessage().acceptMessage(temp.toString()); }else{ //验证失败 System.out.println(reback); } } catch (IOException e) { e.printStackTrace(); } finally { in.close(); } return temp.toString(); } } <file_sep>package com.wx.message; import java.io.DataOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import org.apache.commons.io.IOUtils; import com.wx.accesstoken.WeixinAccessToken; import com.wx.util.WeixinJson; /** * 发送微信消息 * @author Administrator * */ public class WeixinSendMessage { public String sendMessage(){ String access_token = new WeixinAccessToken().GetAccessToken(); String URL = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+access_token; String jsons = "{\"touser\":\"oTnGruMretQPHreWMMBfTnXxI1Uo\",\"msgtype\":\"text\",\"text\":{\"content\":\"Hello World\"}}"; byte[] xmlData = jsons.getBytes(); InputStream instr = null; java.io.ByteArrayOutputStream out = null; try{ URL url = new URL(URL); URLConnection urlCon = url.openConnection(); urlCon.setDoOutput(true); urlCon.setDoInput(true); urlCon.setUseCaches(false); urlCon.setRequestProperty("Content-Type", "text/xml"); urlCon.setRequestProperty("Content-length",String.valueOf(xmlData.length)); System.out.println(String.valueOf(xmlData.length)); DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream()); printout.write(xmlData); printout.flush(); printout.close(); instr = urlCon.getInputStream(); byte[] bis = IOUtils.toByteArray(instr); String ResponseString = new String(bis, "UTF-8"); if ((ResponseString == null) || ("".equals(ResponseString.trim()))) { System.out.println("返回空"); } System.out.println("返回数据为:" + ResponseString); return ResponseString; }catch(Exception e){ e.printStackTrace(); return "0"; } finally { try { out.close(); instr.close(); }catch (Exception ex) { return "0"; } } } public static void main(String args[]){ WeixinSendMessage wxsm = new WeixinSendMessage(); wxsm.sendMessage(); } } <file_sep>package com.wx.util; import java.util.Iterator; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class WeixinJson { /** * 根据JSON name 获取 JSON value * 一层关系 {name:value} * @param jsons * @param name * @return */ public String getJsonValue(String jsons,String name){ JSONObject jsonobj=JSONObject.fromObject(jsons);//将字符串转化成json对象 String value=jsonobj.getString(name);//获取字符串。 System.out.println(value); return value; } /** * java解析json对象,解析出对象和字符串及数组并遍历出相应的值 */ private static void strJsonObj(){ String json = "{'name': 'helloworlda','array':[{'a':'111','b':'222','c':'333'},{'a':'999'}],'address':'111','people':{'name':'happ','sex':'girl'}}"; JSONObject jsonobj=JSONObject.fromObject(json);//将字符串转化成json对象 String name=jsonobj.getString("name");//获取字符串。 JSONArray array=jsonobj.getJSONArray("array");//获取数组 JSONObject obj=jsonobj.getJSONObject("people");//获取对象 System.out.println("===============strJsonObj=================="); System.out.println("jsonobj : "+jsonobj); System.out.println("array : "+array); System.out.println("obj : "+obj.getString("name")); //遍历json对象 Iterator<?> objkey=obj.keys(); while (objkey.hasNext()) {// 遍历JSONObject String aa2 = (String) objkey.next().toString(); String bb2 = obj.getString(aa2); System.out.println(aa2+":"+bb2); } //遍历数组 for (int i = 0; i < array.size(); i++) { System.out.println("item "+ i + " :" + array.getString(i)); } } public static void main(String args[]){ WeixinJson wxj = new WeixinJson(); //wxj.strJsonObj(); wxj.getJsonValue("{\"token\":\"abc123\"}", "token"); } } <file_sep>package com.wx.util; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; public class WeixinXmlElement { /** * 获取XMLS的元素 * @param xmls * @param column * @return */ public static String getChildColumn(String xmls, String column) { String regBegin = "<" + column + ">"; String regEnd = "</" + column + ">"; String regC = regBegin + "([\\w\\W]*?)" + regEnd; String returnStr = ""; Pattern p = null; Matcher m = null; p = Pattern.compile(regC); m = p.matcher(xmls); if(m.find()) { returnStr = m.group(); returnStr = returnStr.replace(regBegin, ""); returnStr = returnStr.replace(regEnd, ""); try { returnStr = URLDecoder.decode(returnStr, "utf-8"); } catch(IllegalArgumentException ex){ System.out.println("catch=="+ex.getMessage()); } catch(UnsupportedEncodingException e){ System.out.println("CASUtil:"+e.getMessage()); } return returnStr; } else { return returnStr; } } /** * Description:初始化变量 * * @param fileStr * 一段xml的字符串 */ public Element initEle(String fileStr) { Document doc = null; SAXBuilder sb = null; Element element = null; try { sb = new SAXBuilder(); InputStream inputStream = new ByteArrayInputStream(fileStr .getBytes("utf-8")); doc = sb.build(inputStream); element = doc.getRootElement(); } catch (Exception ex) { System.out.println(" XML格式错误: " + ex.getMessage()); } return element; } }
e670101a4cb7d93fe37221b142aee1f03f8091fa
[ "Java" ]
4
Java
yojiwei/weixin
fdc4b3660dd167b8b986c689e0c1d72df06baa51
32bb091d48bf1a022a89bfc20fa303ddf0666669
refs/heads/master
<repo_name>foecum/UserService<file_sep>/README.md [![Build Status](http://jenkins.tangentme.com/buildStatus/icon?job=Build UserService)](http://jenkins.tangentme.com/view/MicroServices/job/Build%20UserService/) [![Documentation Status](https://readthedocs.org/projects/userservice/badge/?version=latest)](https://readthedocs.org/projects/userservice/?badge=latest) # User Service User management service authenticates users for all the other micro services projects. [Documentation] (http://userservice.readthedocs.org/en/latest/) ## Setting Up 1. Start and activate environment virtualenv env source env/bin/activate 1. Run the requirements pip install -r requirements.txt 1. Install the database python manage.py syncdb 1. Run the initial data (if required - this is test data only) python manage.py loaddata data/initial.json 1. Run the tests to ensure the project is up and running correctly python manage.py test ## Build the Docs ### Run the requirements pip install -r requirements-dev.txt ### Manually Build the Docs cd docs make html ### Auto Build the Docs as you Edit cd docs sphinx-autobuild source build/html -p3000 <file_sep>/docs/source/api.rst API === Overview -------- Endpoints --------- Resources ---------<file_sep>/docs/source/quickstart.rst Getting Started with the UserService ===================================== **URLS** * **Production:** http://userservice.tangentme.com * **Staging:** http://staging.userservice.tangentme.com Getting an auth token ---------------------- **Request** **Curl**:: curl -X POST http://staging.userservice.tangentme.com/api-token-auth/ --data "username=admin&password=<PASSWORD>" **Python**:: import requests url = 'http://staging.userservice.tangentme.com/api-token-auth/' r=requests.post(url, data={"username":"admin","password":"<PASSWORD>"}) r.content Out[8]: '{"token": "<PASSWORD>"}' **Response**:: {"token": "<PASSWORD>"} You can use this token to make future authorized requests **Angular** Add constant to settings file:: .constant("SERVICE_BASE_URI", "http://staging.userservice.tangentme.com") Add login to ng-service:: apiService.login = function (username, password) { var deferred = $q.defer(); var url = SERVICE_BASE_URI + "/api-token-auth/"; $http.post(url, { username: username, password: <PASSWORD> }).success(function (response, status, headers, config) { if (response.token) { //Store the token for further calls } deferred.resolve(response, status, headers, config); }).error(function (response, status, headers, config) { deferred.reject(response, status, headers, config); }); return true; //deferred.promise; }; Authorizing with an auth token ------------------------------- To identify yourself in consequent requests, set the `Authorization` header like below **CURL**:: curl GET http://staging.userservice.tangentme.com/users/me/ -H 'Authorization: Token <PASSWORD>' **Python**:: import requests headers = { 'content-type': 'application/json', 'Authorization':'Token <PASSWORD>' } requests.get('http://staging.userservice.tangentme.com/users/me/', headers=headers) **Response**:: { "id": 5, "first_name": "", "last_name": "", "username": "a", "email": "", "is_staff": true, "profile": { "contact_number": "", "status_message": null, "bio": null }, "authentications": [], "roles": [] } **Angular**:: apiService.getMe = function (token) { var deferred = $q.defer(); var url = SERVICE_BASE_URI + "/users/me/"; $http.get(url, { headers: {'Authorization': 'Token ' + token} }).success(function (response, status, headers, config) { if (response) { //Handle the response } deferred.resolve(response, status, headers, config); }).error(function (response, status, headers, config) { deferred.reject(response, status, headers, config); }); return true; //deferred.promise; }; **Possible Responses**: * 200 OK * 401 Authorization failed: * Invalid Token * Authentication credentials were not provided. <file_sep>/requirements.txt django==1.7 gunicorn slumber requests responses mock djangorestframework==2.4.2 django-rest-swagger django-filter django-user-roles django-jenkins django-extensions pylint coverage sphinx sphinx_rtd_theme django-cors-headers <file_sep>/api/permissions.py from rest_framework import permissions class HasRolePermission(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated(): return request.user.has_role(self.required_role) return False class IsDirector(HasRolePermission): required_role = 'Director' class IsAdministrator(HasRolePermission): required_role = 'Administrator' class IsDeveloper(HasRolePermission): required_role = 'Developer' class IsEmployee(HasRolePermission): required_role = 'Employee' class IsSelf(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.user.is_authenticated(): if obj.__class__.__name__ == 'User': return obj.pk == request.user.pk else: user_id = getattr(obj, "user_id", False) if user_id: return user_id == request.user.pk return False class IsSelfOrDirector(IsSelf): def has_object_permission(self, request, view, obj): if request.user.is_authenticated(): if request.user.has_role('Director'): return True return super(IsSelfOrDirector, self).has_object_permission(request, view, obj) return False <file_sep>/api/api.py from django.contrib.auth.models import User from django.http import HttpResponse from rest_framework import routers, serializers, viewsets from rest_framework.authentication import TokenAuthentication from permissions import IsSelfOrDirector from models import Profile, AppAuthorization, Role from rest_framework.decorators import list_route, detail_route import json from rest_framework.permissions import IsAuthenticated class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile exclude = ('user', 'id',) class AppAuthorizationSerializer(serializers.ModelSerializer): class Meta: model = AppAuthorization exclude = ('user',) # Serializers define the API representation. class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(read_only=True) authentications = AppAuthorizationSerializer(read_only=True, many=True) roles = serializers.RelatedField(many=True, read_only=True) class Meta: model = User fields = ('id', 'first_name', 'last_name', 'username', 'email', 'is_staff', 'is_superuser', 'profile', 'authentications', 'roles',) # read_only_fields = ('roles',) depth = 1 # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer #permission_classes = (IsSelfOrDirector,) permission_classes = (IsAuthenticated,) @list_route(methods=['get', 'post']) def me(self, request): # ensure they have permissions to see this user self.check_object_permissions(self.request, request.user) serializer = UserSerializer(request.user) response = json.dumps(serializer.data) return HttpResponse(response, content_type="application/json") class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer class AppAuthorizationViewSet(viewsets.ModelViewSet): queryset = AppAuthorization.objects.all() serializer_class = AppAuthorizationSerializer # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'users', UserViewSet) # router.register(r'profiles', ProfileViewSet) # router.register(r'apps', AuthenticationViewSet)<file_sep>/api/signals.py from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from models import Profile from rest_framework.authtoken.models import Token @receiver(post_save, sender=User) def new_user_created(sender, instance, **kwargs): if kwargs.get("created", False): Token.objects.create(user=instance) Profile.objects.create(user=instance) # create a blank profile # create a token <file_sep>/requirements-dev.txt sphinx ipython sphinx_rtd_theme sphinx-autobuild pytest-pep8 pep8 <file_sep>/api/tests.py # pylint: disable=R0904 from django.test import TestCase, Client from models import Profile from django.contrib.auth.models import User from django.core.urlresolvers import reverse from rest_framework.authtoken.models import Token from permissions import IsDirector, IsSelf from django.http import HttpRequest import json class Pep8TestCase(TestCase): def test_pep8(self): """ Ensure that code is pep8 compliant """ #from subprocess import call # py.test --pep8 # see pytest.ini for config options #result = call(['py.test']) #assert result == 0, "Code is pep8" class TokenAuthTestCase(TestCase): def setUp(self): self.user = User.objects.create_user(username="joe", password="<PASSWORD>") self.c = Client() def test_get_token(self): response = self.c.post( "/api-token-auth/", {"username": "joe", "password": "<PASSWORD>"}) assert 200 == response.status_code, "Response is 200 OK" assert json.loads(response.content).get("token", False) is not False, "Token is set" class PermissionsTestCase(TestCase): def setUp(self): self.user = User.objects.create_user(username="joe", password="<PASSWORD>") def tearDown(self): for role in self.user.roles.all(): role.delete() def test_is_director_passes_if_user_is_director(self): mock_request = HttpRequest() self.user.add_role("Director") mock_request.user = self.user permission_class = IsDirector() authorization_response = permission_class.has_permission( mock_request, None) assert authorization_response is True, "Permission should be granted" def test_is_director_fails_if_user_is_not_a_director(self): mock_request = HttpRequest() mock_request.user = self.user permission_class = IsDirector() authorization_response = permission_class.has_permission( mock_request, None) assert authorization_response is False, "Permission should be denied" def test_is_self_allows_me_to_see_myself(self): mock_request = HttpRequest() mock_request.user = self.user permission_class = IsSelf() authorization_response = permission_class.has_object_permission( mock_request, None, self.user) assert authorization_response is True, "IsSelf passes if I request to see myself" def test_is_self_allows_me_to_see_my_profile(self): mock_request = HttpRequest() mock_request.user = self.user permission_class = IsSelf() authorization_response = permission_class.has_object_permission( mock_request, None, self.user.profile) assert authorization_response is True, "IsSelf passes if I request to see my profile" class ModelsTestCase(TestCase): def test_new_user_signals(self): user = User.objects.create_user(username="joe", password="<PASSWORD>") token = Token.objects.get(user=user) assert type(token) is Token, "Token is 40 characters long" assert Profile.objects.filter( user=user).count() == 1, "Exactly 1 matching profile is created" class EndpointAuthenticationTestCase(TestCase): def setUp(self): self.c = Client() self.user = User.objects.create_user(username="joe", password="<PASSWORD>") def tearDown(self): for role in self.user.roles.all(): role.delete() def test_endpoints_require_token_auth(self): url = reverse('user-me') response = self.c.get(url) assert response.status_code == 401, "401: Authentication required" def test_director_can_see_anyone(self): url = reverse('user-me') self.user.add_role('Director') response = self.c.get( url, HTTP_AUTHORIZATION="Token {0}" . format(self.user.get_token())) assert response.status_code == 200, "Director can view any user" def test_user_can_see_self(self): url = reverse('user-me') response = self.c.get( url, HTTP_AUTHORIZATION="Token {0}" . format(self.user.get_token())) assert response.status_code == 200, "User can see self" class EndpointsTestCase(TestCase): def setUp(self): self.c = Client() def test_enrol_employee(self): """ POST /user/{:id}/enrol/ @requires exec or admin * Give user appropriate roles * Sends a welcome e-mail to staff * Sends an on-boarding e-mail to user * Creates a pivotal account * Creates a hipchat account """ pass def test_retire_employee(self): """ POST /user/{:id}/enrol/ @requires exec or admin * Delete pivotal account * Delete hipchat account * Remove access from Github Organization * Remove access from Tangent microservices """ pass <file_sep>/health/tests.py from django.test import TestCase, Client from django.conf import settings import requests import responses def mock_auth_success(): url = '/health/' responses.add(responses.GET, url, status=200, content_type='application/json') class HealthTestCase(TestCase): def test_health_returns_useful_information(self): response = self.client.get('/') self.assertEqual(response.data, {"version": settings.VERSION, "name": "UserService", "explorer_url": "/api-explorer/"})<file_sep>/pytest.ini [pytest] addopts = --pep8 --ignore=docs --quiet pep8maxlinelength=100 <file_sep>/api/monkey_patching.py # Monkey patching is a way to add additional functionality to the user module # pylint: disable=E1101 # pylint: disable=C0111 from django.contrib.auth.models import User from models import Role from rest_framework.authtoken.models import Token def add_role(self, role_name): if self.is_authenticated(): role, created = Role.objects.get_or_create( role_name=role_name) # pylint: disable=W0612 self.roles.add(role) def has_role(self, role_name): if self.is_authenticated(): return (role_name,) in self.roles.all().values_list("role_name") return False def get_token(self): if self.is_authenticated(): return Token.objects.get(user=self).key return None User.add_to_class("add_role", add_role) User.add_to_class("has_role", has_role) User.add_to_class("get_token", get_token) <file_sep>/userservice/urls.py from django.conf.urls import patterns, include, url from api.api import router from django.contrib import admin from health import api urlpatterns = patterns('', url(r'^api/v1/', include(router.urls)), url(r'^api-token-auth/','rest_framework.authtoken.views.obtain_auth_token'), url(r'^api-explorer/', include('rest_framework_swagger.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^', api.health), ) <file_sep>/api/models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings class Role(models.Model): def __unicode__(self): return self.role_name user = models.ManyToManyField(User, related_name='roles') role_name = models.CharField( max_length=20, help_text='Describes a role that this user has', choices=settings.USER_ROLES) class Profile(models.Model): """ Additional data about a user """ user = models.OneToOneField(User) # token = models.CharField(max_length=36, default=str(uuid.uuid4())) contact_number = models.CharField(max_length=20) status_message = models.CharField( max_length=144, help_text='Twitter style status message', blank=True, null=True) bio = models.TextField(blank=True, null=True) class AppAuthorization(models.Model): """ Collection of authentication tokens/keys for various services """ user = models.ForeignKey(User, related_name='authentications') service_name = models.CharField( max_length=20, help_text='Service such as pivotal, hipchat, .. etc') key = models.CharField(max_length=200, blank=True, null=True, help_text='Optional, typically your API_KEY value') token = models.CharField( max_length=200, blank=True, null=True, help_text='Optional, this is your token or secret') from signals import new_user_created <file_sep>/api/management/commands/generate_tokens.py from django.core.management.base import BaseCommand from rest_framework.authtoken.models import Token from django.contrib.auth.models import User class Command(BaseCommand): args = '<>' help = 'Generals new tokens for all users' def handle(self, *args, **options): users = User.objects.all() for user in users: Token.objects.create(user=user) <file_sep>/api/admin.py from django.contrib import admin from models import Role, Profile, AppAuthorization class RoleAdmin(admin.ModelAdmin): pass class ProfileAdmin(admin.ModelAdmin): pass class AppAuthorizationAdmin(admin.ModelAdmin): pass admin.site.register(Role, RoleAdmin) admin.site.register(Profile, ProfileAdmin) admin.site.register(AppAuthorization, AppAuthorizationAdmin)<file_sep>/health/api.py from rest_framework import routers from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import AllowAny from rest_framework.response import Response from django.conf import settings @api_view(['GET']) @permission_classes((AllowAny,)) def health(request): json = { 'version': settings.VERSION, 'name': "UserService", 'explorer_url': "/api-explorer/" } return Response(json) router = routers.DefaultRouter()
555c293ae109d240fcc045236604d042915e6d3b
[ "reStructuredText", "Markdown", "INI", "Python", "Text" ]
17
Markdown
foecum/UserService
db4dfe61095a1cf8a4d7c6670e8c8c00f6d48847
1abf50e221cd9140cab23f4677104e01de97d04c
refs/heads/master
<repo_name>lukasfialho/senac-bulldog<file_sep>/shared/models/ImageProduto.ts export interface ImageProduto { idimage?: number; path: string; nome: string; idproduto: number; }<file_sep>/pages/api/produtos_old.ts import { NowRequest, NowResponse } from '@vercel/node' import mysql from 'mysql'; import { Produtos } from '../../shared/models/produtos'; const connection = mysql.createConnection({ host: process.env.HOST, user: process.env.DB_USER, password: <PASSWORD>.<PASSWORD>, database: process.env.DATABASE, port: Number(process.env.PORT), insecureAuth: true }); export const queryPromiseGet = (query: any) => { return new Promise((resolve, reject) => { connection.query(query, function(error, results, fields) { if (error) return reject(error); resolve(results); }) }) } export const queryPromiseSave = (query: any, object: any) => { return new Promise((resolve, reject) => { connection.query(query, object, function(error, results, fields) { if (error) return reject(error); resolve(results); }) }) } async function getProducts(request: NowRequest, response: NowResponse) { const query = await queryPromiseGet('SELECT * FROM Produto'); return response.json(query); } async function saveProducts(request: NowRequest, response: NowResponse) { const product: Produtos = request.body; const query = await queryPromiseSave('INSERT INTO Produto SET ?', product); return response.json(query); } async function editProducts(request: NowRequest, response: NowResponse) { console.log(request.body); const product: Produtos = request.body; const query = await queryPromiseSave(`UPDATE Produto SET ? WHERE idproduto=${product.idproduto}`, product); return response.json(query); } async function deleteProduct(request: NowRequest, response: NowResponse) { console.log(request.query); const { idproduto } = request.query; const query = await queryPromiseSave(`UPDATE Produto SET ? WHERE idproduto=${idproduto}`, {status: false}); return response.json(query); } export default async (request: NowRequest, response: NowResponse) => { switch(request.method){ case 'GET': return await getProducts(request, response); case 'POST': return await saveProducts(request, response); case 'PUT': return await editProducts(request, response); case 'DELETE': return await deleteProduct(request, response); default: response.status(405).end(); break; } } <file_sep>/pages/api/users.ts import {NowRequest, NowResponse} from "@vercel/node"; import crypto from 'crypto'; import { User } from "../../shared/models/user"; import { queryPromiseGet } from "./connection"; async function index(request: NowRequest, response: NowResponse) { const query = await queryPromiseGet(`SELECT * FROM Usuario`); return response.json(query); } export default async (request: NowRequest, response: NowResponse) => { switch(request.method){ case 'GET': return await index(request, response); case 'POST': return false; case 'PUT': return false; case 'DELETE': return false; default: response.status(405).end(); break; } } <file_sep>/pages/api/clientes/update.ts import { NowRequest, NowResponse } from "@vercel/node"; import { Cliente } from "../../../shared/models/cliente"; import { Endereco } from "../../../shared/models/endereco"; import {queryPromiseGet, queryPromiseSave} from "../connection"; import { encryptPassword } from "../encryptPassword"; export default async (request: NowRequest, response: NowResponse) => { console.log(request.body); const { idcliente, email, nome, sobrenome, cpf, telefone, status, faturamento, } = request.body; const client: Cliente = { idcliente, email, nome, sobrenome, cpf, telefone, status, }; const query = await queryPromiseSave( `UPDATE Cliente SET ? WHERE idcliente=${idcliente}`, client ) as any; const enderecos: Endereco[] = [faturamento]; const promises = enderecos.map(async endereco => { endereco.idcliente = client.idcliente; await queryPromiseSave( `UPDATE Endereco SET ? WHERE idendereco=${endereco.idendereco}`, endereco ); }); await Promise.all(promises); return response.status(201).json(query); }<file_sep>/pages/api/produtos/findAll.ts import {NowRequest, NowResponse} from '@vercel/node'; import nextConnect from 'next-connect'; import multer from 'multer'; import express from 'express'; import { queryPromiseGet, queryPromiseSave } from '../connection'; import path from 'path'; import uploadConfig from '../../../shared/utils/uploadConfig'; type NowRequestWithFile = NowRequest & { files: Express.Multer.File[] }; const handler = nextConnect(); const upload = multer(uploadConfig); handler.use(upload.array('file')); handler.use('/tmp', express.static(path.join(__dirname, 'tmp'))); handler.get(async (req: NowRequestWithFile, res: NowResponse) => { const query = await queryPromiseGet('SELECT * FROM Produto'); return res.json(query); }); export const config = { api: { bodyParser: false } } export default handler;<file_sep>/pages/api/pergunta.ts import {NowRequest, NowResponse} from "@vercel/node"; import {queryPromiseGet, queryPromiseSave} from "./produtos_old"; import {Pergunta} from "../../shared/models/pergunta"; async function saveQuestions(request: NowRequest, response: NowResponse) { const pergunta: Pergunta = request.body; const query = await queryPromiseSave('INSERT INTO Perguntas SET ?', pergunta); return response.json(query); } async function getQuestions(request: NowRequest, response: NowResponse) { const { idproduto } = request.query; const query = await queryPromiseGet(`SELECT * FROM Perguntas WHERE idproduto=${idproduto}`); return response.json(query); } export default async (request: NowRequest, response: NowResponse) => { switch(request.method){ case 'GET': return await getQuestions(request, response); case 'POST': return await saveQuestions(request, response); case 'PUT': return false; case 'DELETE': return false; default: response.status(405).end(); break; } }<file_sep>/pages/api/produtos/save.ts import {NowRequest, NowResponse} from '@vercel/node'; import nextConnect from 'next-connect'; import multer from 'multer'; import express from 'express'; import { Produtos } from '../../../shared/models/produtos'; import { queryPromiseSave } from '../connection'; import path from 'path'; import uploadConfig from '../../../shared/utils/uploadConfig'; import fs from 'fs'; import {ImageProduto} from '../../../shared/models/ImageProduto'; type NowRequestWithFile = NowRequest & { files: Express.Multer.File[] }; const handler = nextConnect(); const upload = multer(uploadConfig); handler.use(upload.array('file')); handler.use('/tmp', express.static(path.join(__dirname, 'tmp'))); handler.post(async (req: NowRequestWithFile, res: NowResponse) => { const { status, quantidade, nome, descricao, descricao_longa, valor, palavras_chave }: Produtos = req.body; const product = { status: (status as unknown as string) === 'true', quantidade: parseInt((quantidade as unknown as string)), nome, descricao, descricao_longa, valor: parseFloat((valor as unknown as string)), palavras_chave } const query = await queryPromiseSave('INSERT INTO Produto SET ?', product) as any; const promises = req.files.map(async file => { let imageProduto: ImageProduto = { path: file.path, nome: file.filename, idproduto: query.insertId, }; let response = await queryPromiseSave('INSERT INTO ImageProduto SET ?', imageProduto); }); await Promise.all(promises); return res.status(201).json(query); }); export const config = { api: { bodyParser: false } } export default handler;<file_sep>/pages/api/checkout/changeStatus.ts import { NowRequest, NowResponse } from "@vercel/node"; import { Cliente } from "../../../shared/models/cliente"; import { Endereco } from "../../../shared/models/endereco"; import {queryPromiseGet, queryPromiseSave} from "../connection"; import { encryptPassword } from "../encryptPassword"; export default async (request: NowRequest, response: NowResponse) => { const { idcarrinho, produtos, novoStatus } = request.body; const carrinho = { status: novoStatus === 'aprovado' ? 'Pagamento Aprovado' : 'Compra Cancelada', } const q = await queryPromiseSave(`UPDATE Carrinho SET ? WHERE idcarrinho=${idcarrinho}`, carrinho); if (novoStatus === 'aprovado') { const promise = produtos.map(async produto => { const quantidade = produto.quantidade - produto.itens; const query = await queryPromiseSave(`UPDATE Produto SET ? WHERE idproduto=${produto.idproduto}`, {quantidade}); return produto; }); await Promise.all(promise); } return response.status(201).json(true); }<file_sep>/pages/api/login.ts import {NowRequest, NowResponse} from "@vercel/node"; import { User } from "../../shared/models/user"; import jwt from 'jsonwebtoken'; import { queryPromiseGet } from "./connection"; import { encryptPassword } from "./encryptPassword"; async function login(request: NowRequest, response: NowResponse) { let {email, senha} = request.body; console.log('Usuario logando', email); senha = await encryptPassword(senha); const query = await queryPromiseGet( `SELECT * FROM Usuario WHERE (email='${email}' AND senha='${senha}' AND status='ATIVO')` ); console.log(query); if (!query[0]) { //! Preciso fazer um tratamento melhor desse dado query return response.status(404).json({ error: 'No user found' }); } const token = jwt.sign( { email: query[0].email, nome: query[0].nome, sobrenome: query[0].sobrenome, perfil: query[0].perfil, cpf: query[0].cpf, status: query[0].status, idusuario: query[0].idusuario, }, process.env.JWT_SECRET, ); return response.json({token}); } export default async (request: NowRequest, response: NowResponse) => { switch(request.method){ case 'GET': return false; case 'POST': return await login(request, response); case 'PUT': return false; case 'DELETE': return false; default: response.status(405).end(); break; } } <file_sep>/shared/components/BottomNavigation/styles.ts import styled from 'styled-components'; import { Theme, lighten } from '@material-ui/core'; import MaterialFab from '@material-ui/core/Fab'; import MaterialBottomNavigation from '@material-ui/core/BottomNavigation'; import MaterialBottomNavigationAction from '@material-ui/core/BottomNavigationAction'; interface Props { theme: Theme; } export const BottomNavigation = styled(MaterialBottomNavigation)` position: fixed; bottom: 0; left: 0; width: 100%; border-top: 1px solid #cecece; background: #000; `; export const BottomNavigationAction = styled(MaterialBottomNavigationAction)` color: #cecece; &.Mui-selected { color: #cecece; border-bottom: 3px solid #cecece; } `;<file_sep>/pages/api/checkout/store.ts import { NowRequest, NowResponse } from "@vercel/node"; import { Cliente } from "../../../shared/models/cliente"; import { Endereco } from "../../../shared/models/endereco"; import {queryPromiseGet, queryPromiseSave} from "../connection"; import { encryptPassword } from "../encryptPassword"; export default async (request: NowRequest, response: NowResponse) => { const { idcliente, status, pagamento, idendereco, produtos, total } = request.body; let carrinho: any = { idcliente, idendereco, status, pagamento, total, createAt: new Date(), updateAt: new Date() } const carrinhoQuery = await queryPromiseSave( 'INSERT INTO Carrinho SET ? ', carrinho ) as any; if (!carrinhoQuery.insertId) { return response.status(500).json({error: 'Some error has happened.'}); } carrinho = {...carrinho, idcarrinho: carrinhoQuery.insertId, produtos: []}; const promises = produtos.map(async produto => { const item = { idproduto: produto.idproduto, idcarrinho: carrinho.idcarrinho, discount: 0, itens: produto.itens, } const query = await queryPromiseSave( 'INSERT INTO ItemCarrinho SET ?', item ) as any; carrinho.produtos.push({...item, iditemcarrinho: query.insertId}); console.log(query); }); await Promise.all(promises); return response.status(201).json(carrinho); }<file_sep>/shared/models/produtos.ts export interface Produtos { idproduto: number; status: boolean; quantidade: number; nome: string; descricao: string; descricao_longa: string; imagem: string; valor: number; palavras_chave: string; } <file_sep>/pages/api/clientes/deleteEndereco.ts import { NowRequest, NowResponse } from "@vercel/node"; import { queryPromiseGet } from "../connection"; export default async (request: NowRequest, response: NowResponse) => { const { idendereco } = request.query; await queryPromiseGet(`DELETE FROM Endereco WHERE idendereco=${idendereco}`); return response.status(200).json(true); }<file_sep>/pages/api/encryptPassword.ts import crypto from 'crypto'; export async function encryptPassword(password: string) { return crypto.createHmac('sha256', 'senha').update(password).digest('hex'); }<file_sep>/shared/models/pergunta.ts export interface Pergunta { idpergunta: number; idproduto: number; status: boolean; pergunta: string; resposta: string; }<file_sep>/styles/themes/light.ts import { createMuiTheme } from '@material-ui/core'; const LightTheme = createMuiTheme({ overrides: { MuiTextField: { root: { margin: '15px 0', }, }, MuiButton: { label: { textTransform: 'none', fontWeight: 400, }, }, }, palette: { type: 'light', primary: { main: '#FFFFFF', }, secondary: { main: '#ffffff', }, success: { main: '#28B67A', }, error: { main: '#EF3E2D', }, info: { main: '#4995DF', }, warning: { main: '#EFD359', }, background: { default: '#ffffff', }, common: { white: '#ffffff', }, text: { primary: '#000', secondary: '#000', hint: '#fff' } }, }); export default LightTheme; <file_sep>/pages/api/clientes/show.ts import { NowRequest, NowResponse } from "@vercel/node"; import { queryPromiseGet } from "../connection"; export default async (request: NowRequest, response: NowResponse) => { const { idcliente, faturamento, entrega } = request.query; const query1 = await queryPromiseGet(`SELECT * FROM Cliente WHERE idcliente=${idcliente} AND status=1`); console.log(query1); const { email, nome, sobrenome, cpf, telefone, status } = query1[0]; const enderecos = await queryPromiseGet(`SELECT * FROM Endereco WHERE idcliente=${idcliente}`) as any[]; const client = { email, nome, sobrenome, cpf, telefone, status }; console.log(enderecos); return response.json({ idcliente, ...client, faturamento: faturamento ? enderecos.filter(endereco => endereco.tipo === 'Faturamento')[0] : {}, entrega: entrega ? enderecos.filter(endereco => endereco.tipo === 'Entrega') : [] }); }<file_sep>/pages/api/clientes/store.ts import { NowRequest, NowResponse } from "@vercel/node"; import { Cliente } from "../../../shared/models/cliente"; import { Endereco } from "../../../shared/models/endereco"; import {queryPromiseGet, queryPromiseSave} from "../connection"; import { encryptPassword } from "../encryptPassword"; export default async (request: NowRequest, response: NowResponse) => { const { email, senha, nome, sobrenome, cpf, telefone, status, faturamento, entrega } = request.body; const client: Cliente = { email, senha, nome, sobrenome, cpf, telefone, status, }; client.senha = await encryptPassword(client.senha); const query = await queryPromiseSave( 'INSERT INTO Cliente SET ? ', client ) as any; client.idcliente = query.insertId; const enderecos: Endereco[] = [faturamento]; const promises = enderecos.map(async endereco => { endereco.idcliente = client.idcliente; await queryPromiseSave( 'INSERT INTO Endereco SET ?', endereco ); }); await Promise.all(promises); return response.status(201).json(query); }<file_sep>/pages/api/produtos/edit.ts import {NowRequest, NowResponse} from '@vercel/node'; import nextConnect from 'next-connect'; import multer from 'multer'; import express from 'express'; import { Produtos } from '../../../shared/models/produtos'; import { queryPromiseSave } from '../connection'; import path from 'path'; import uploadConfig from '../../../shared/utils/uploadConfig'; import fs from 'fs'; import {ImageProduto} from '../../../shared/models/ImageProduto'; const handler = nextConnect(); handler.post(async (req: NowRequest, res: NowResponse) => { const { idproduto, quantidade, }: Produtos = req.body; const query = await queryPromiseSave(`UPDATE Produto SET ? WHERE idproduto=${idproduto}`, {quantidade}) as any; return res.status(201).json(query); }); export default handler;<file_sep>/shared/components/Header/styles.ts import styled from 'styled-components'; export const Brand = styled.span` color: #fced4b; margin-left: 12px; `; <file_sep>/pages/api/clientes/editBasicInfo.ts import { NowRequest, NowResponse } from "@vercel/node"; import { queryPromiseSave } from "../connection"; export default async (request: NowRequest, response: NowResponse) => { const { nome, sobrenome, telefone, } = request.body; const { idcliente } = request.query; const query = await queryPromiseSave( `UPDATE Cliente SET ? WHERE idcliente=${idcliente}`, { nome, sobrenome, telefone, } ); return response.status(200); }<file_sep>/shared/services/nextroute.ts import Router from "next/router"; export const nextRoute = (route: string) => { Router.push(route) }<file_sep>/shared/layout/PrivateLayout/styles.ts import styled from 'styled-components'; export const Container = styled.section` display: flex; flex-direction: column; flex: 1; `; export const Content = styled.div` display: flex; flex-direction: column; width: 100%; min-height: 70vh; margin-bottom: 32px; padding: 16px; @media screen and (min-width: 992px) { max-width: 600px; } `;<file_sep>/pages/api/clientes/editPassword.ts import { NowRequest, NowResponse } from "@vercel/node"; import { queryPromiseGet, queryPromiseSave } from "../connection"; import { encryptPassword } from "../encryptPassword"; export default async (request: NowRequest, response: NowResponse) => { const { idcliente } = request.query; let { senha, novaSenha, } = request.body; senha = await encryptPassword(senha); novaSenha = await encryptPassword(novaSenha); const cliente = await queryPromiseGet(`SELECT * FROM Cliente WHERE idcliente=${idcliente} AND senha=${senha}`) as any[]; if (cliente.length === 0) { return response.status(404).json({error: 'Cliente não encontrado'}); } await queryPromiseSave( `UPDATE Cliente SET ? WHERE idcliente=${idcliente}`, { senha: novaSenha } ); return response.status(200); }<file_sep>/pages/api/produtos-ativos.ts import {NowRequest, NowResponse} from "@vercel/node"; import { queryPromiseGet } from "./connection"; async function getProducts(request: NowRequest, response: NowResponse) { const query = await queryPromiseGet( 'SELECT * FROM Produto WHERE status=true' ) as any[]; const promises = query.map(async (result) => { let images = await queryPromiseGet(`SELECT * FROM ImageProduto WHERE idproduto=${result.idproduto}`) as any[]; if (images.length > 0) { result.imagem = images[0].nome; } }); await Promise.all(promises); return response.json(query); } export default async (request: NowRequest, response: NowResponse) => { switch(request.method){ case 'GET': return await getProducts(request, response); case 'POST': return false; case 'PUT': return false; case 'DELETE': return false; default: response.status(405).end(); break; } } <file_sep>/pages/api/clientes/editEndereco.ts import { NowRequest, NowResponse } from "@vercel/node"; import { queryPromiseSave } from "../connection"; export default async (request: NowRequest, response: NowResponse) => { const { idendereco } = request.query; const { cep, logradouro, numero, complemento, bairro, cidade, estado, pais } = request.body; await queryPromiseSave( `UPDATE Endereco SET ? WHERE idendereco=${idendereco}`, { cep, logradouro, numero, complemento, bairro, cidade, estado, pais } ); return response.status(200); }<file_sep>/pages/api/user.ts import {NowRequest, NowResponse} from "@vercel/node"; import crypto from 'crypto'; import { User } from "../../shared/models/user"; import { encryptPassword } from "./encryptPassword"; import { queryPromiseGet, queryPromiseSave } from "./produtos_old"; async function show(request: NowRequest, response: NowResponse) { const { idusuario } = request.query; const query = await queryPromiseGet(`SELECT * FROM Usuario WHERE idusuario=${idusuario}`); return response.json(query); } async function store(request: NowRequest, response: NowResponse) { const user: User = request.body; user.senha = await encryptPassword(user.senha); const query = await queryPromiseSave( 'INSERT INTO Usuario SET ?', user ); return response.json(query); } async function update(request: NowRequest, response: NowResponse) { const user: User = request.body; const updateObject: any = { status: user.status, nome: user.nome, sobrenome: user.sobrenome, perfil: user.perfil, cpf: user.cpf }; if (user.senha) { updateObject.senha = await encryptPassword(user.senha); } const query = await queryPromiseSave( `UPDATE Usuario SET ? WHERE idusuario=${user.idusuario}`, updateObject ); return response.json(query); } async function remove(request: NowRequest, response: NowResponse) { const { idusuario } = request.query; const query = await queryPromiseSave( `UPDATE Usuario SET ? WHERE idusuario=${idusuario}`, { status: 'BLOQUEADO' } ); return response.json(query); } export default async (request: NowRequest, response: NowResponse) => { switch(request.method){ case 'GET': return await show(request, response); case 'POST': return await store(request, response); case 'PUT': return await update(request, response); case 'DELETE': return await remove(request, response); default: response.status(405).end(); break; } } <file_sep>/pages/api/clientes/findAll.ts import { NowRequest, NowResponse } from "@vercel/node"; import { queryPromiseGet } from "../connection"; export default async (request: NowRequest, response: NowResponse) => { const clients = await queryPromiseGet('SELECT * FROM Cliente WHERE status=true'); return response.json(clients); }<file_sep>/pages/api/checkout/findAll.ts import { NowRequest, NowResponse } from "@vercel/node"; import { queryPromiseGet } from "../connection"; export const transformarPedido = (pedido: number) => { const str = "" + pedido; const pad = "0000"; return pad.substring(0, pad.length - str.length) + str; } export default async (request: NowRequest, response: NowResponse) => { let carrinhos = await queryPromiseGet(`SELECT Carrinho.*, Cliente.nome, Cliente.sobrenome, Cliente.email FROM Carrinho INNER JOIN Cliente ON Carrinho.idcliente = Cliente.idcliente`) as any[]; carrinhos = carrinhos.map(carrinho => { return {...carrinho, pedido: transformarPedido(carrinho.idcarrinho)}; }) console.log('Carrinhos', carrinhos); return response.json(carrinhos); }<file_sep>/nbproject/project.properties file.reference.senac-bulldog-public=public files.encoding=UTF-8 site.root.folder=${file.reference.senac-bulldog-public} source.folder= <file_sep>/pages/api/clientes/login.ts import { NowRequest, NowResponse } from "@vercel/node"; import jwt from "jsonwebtoken"; import { queryPromiseGet } from "../connection"; import { encryptPassword } from "../encryptPassword"; export default async (request: NowRequest, response: NowResponse) => { console.log(request.body); let { email, senha } = request.body; senha = await encryptPassword(senha); const query = await queryPromiseGet(`SELECT email, nome, sobrenome, cpf, idcliente FROM Cliente WHERE email='${email}' AND senha='${senha}'`); console.log(query); if (!query[0]?.email) { return response.status(404).json({error: 'Cliente não encontrado'}); } console.log(query[0]); const token = jwt.sign( { email: query[0].email, nome: query[0].nome, sobrenome: query[0].sobrenome, cpf: query[0].cpf, status: query[0].status, idcliente: query[0].idcliente, }, process.env.JWT_SECRET, ); return response.json({token}); }<file_sep>/shared/models/user.ts export interface User { idusuario?: number; status: string; nome: string; sobrenome: string; cpf: string; senha: string; email: string; perfil: string; }<file_sep>/pages/api/produto.ts import {NowRequest, NowResponse} from "@vercel/node"; import { queryPromiseGet } from "./produtos_old"; async function getProduct(request: NowRequest, response: NowResponse) { const { idproduto } = request.query; const query = await queryPromiseGet(`SELECT * FROM Produto WHERE status=true AND idproduto=${idproduto}`); const query2 = await queryPromiseGet(`SELECT * FROM ImageProduto WHERE idproduto=${idproduto}`); return response.json({ produto: query, image: query2 }); } export default async (request: NowRequest, response: NowResponse) => { switch(request.method){ case 'GET': return await getProduct(request, response); case 'POST': return false; case 'PUT': return false; case 'DELETE': return false; default: response.status(405).end(); break; } } <file_sep>/pages/api/connection.ts import mysql from 'mysql'; const connection = mysql.createConnection({ host: process.env.HOST, user: process.env.DB_USER, password: <PASSWORD>, database: process.env.DATABASE, port: Number(process.env.PORT), insecureAuth: true }); export const queryPromiseGet = (query: any) => { return new Promise((resolve, reject) => { connection.query(query, function(error, results, fields) { if (error) return reject(error); resolve(results); }) }) } export const queryPromiseSave = (query: any, object: any) => { return new Promise((resolve, reject) => { connection.query(query, object, function(error, results, fields) { if (error) return reject(error); resolve(results); }) }) }<file_sep>/pages/api/checkout/show.ts import { NowRequest, NowResponse } from "@vercel/node"; import { queryPromiseGet } from "../connection"; import { transformarPedido } from "./findAll"; export default async (request: NowRequest, response: NowResponse) => { const {idcarrinho} = request.query; const carrinhos = await queryPromiseGet(`SELECT * FROM Carrinho INNER JOIN Endereco ON Carrinho.idendereco = Endereco.idendereco WHERE idcarrinho=${idcarrinho}`) as any[]; let promises = carrinhos.map(async carrinho => { let itens = await queryPromiseGet(`SELECT * FROM ItemCarrinho INNER JOIN Produto ON ItemCarrinho.idproduto = Produto.idproduto WHERE idcarrinho=${carrinho.idcarrinho}`) as any[]; itens = itens.map(async item => { const query = await queryPromiseGet(`SELECT * FROM ImageProduto WHERE idproduto=${item.idproduto}`); item.imagem = query; return item; }); const promise = await Promise.all(itens); return {...carrinho, itens: promise, pedido: transformarPedido(carrinho.idcarrinho)} }); promises = await Promise.all(promises); return response.json(promises[0]); }<file_sep>/pages/api/produtos/image.ts import {NowRequest, NowResponse} from '@vercel/node'; import nextConnect from 'next-connect'; import multer from 'multer'; import express from 'express'; import { Produtos } from '../../../shared/models/produtos'; import { queryPromiseSave } from '../connection'; import path from 'path'; import uploadConfig from '../../../shared/utils/uploadConfig'; import fs from 'fs'; type NowRequestWithFile = NowRequest & { files: Express.Multer.File[] }; const handler = nextConnect(); const upload = multer(uploadConfig); handler.use(upload.array('file')); handler.get(async (req: NowRequestWithFile, res: NowResponse) => { const file = await fs.readFileSync(`/tmp/${req.query.file}` as string); res.setHeader('Content-Type', 'image/jpg'); return res.send(file); }); export const config = { api: { bodyParser: false } } export default handler;<file_sep>/shared/services/token.ts import jwt from 'jsonwebtoken'; export const decode = (token: string) => { return jwt.decode(token); }<file_sep>/pages/api/clientes/addEndereco.ts import { NowRequest, NowResponse } from "@vercel/node"; import { Cliente } from "../../../shared/models/cliente"; import { Endereco } from "../../../shared/models/endereco"; import {queryPromiseGet, queryPromiseSave} from "../connection"; import { encryptPassword } from "../encryptPassword"; export default async (request: NowRequest, response: NowResponse) => { const { entrega } = request.body; const query = await queryPromiseSave( 'INSERT INTO Endereco SET ?', entrega ); return response.status(201).json(query); }<file_sep>/pages/api/checkout/findAllByClient.ts import { NowRequest, NowResponse } from "@vercel/node"; import { queryPromiseGet } from "../connection"; import { transformarPedido } from "./findAll"; export default async (request: NowRequest, response: NowResponse) => { const {idcliente} = request.query; let carrinhos = await queryPromiseGet(`SELECT * FROM Carrinho WHERE idcliente=${idcliente}`) as any[]; carrinhos = carrinhos.map(carrinho => { return {...carrinho, pedido: transformarPedido(carrinho.idcarrinho)}; }) return response.json(carrinhos); }<file_sep>/pages/api/clientes/delete.ts import { NowRequest, NowResponse } from "@vercel/node"; import { queryPromiseGet } from "../connection"; export default async (request: NowRequest, response: NowResponse) => { const { idcliente } = request.query; await queryPromiseGet(`DELETE FROM Cliente WHERE idcliente=${idcliente}`); return response.status(200); }<file_sep>/shared/models/cliente.ts import { Endereco } from "./endereco"; export interface Cliente { idcliente?: number; email: string; senha?: string; nome: string; sobrenome: string; cpf: string; telefone: string; status: boolean; } export interface ClienteEndereco extends Cliente { faturamento?: Endereco; entrega?: Endereco[]; }
7f10971257ad7bafeb2d71d5b85e41c04ac246e0
[ "TypeScript", "INI" ]
41
TypeScript
lukasfialho/senac-bulldog
5927742a262fac60d2372db743e46584eded2dda
d382298b4a40ac4cf02ee0d371b9cf7bfcef7f57
refs/heads/master
<repo_name>megaBraker01/scrapingAgencia<file_sep>/index.php <!DOCTYPE html> <!-- Copyright 2019 makina. Software protegido por la propiedad intelectual. Queda prohibido copiar, modificar, fusionar, publicar, distribuir, sublicenciar y / o vender copias no autorizadas del software El aviso de copyright anterior y este aviso de permiso se incluirán en todas las copias o porciones sustanciales del software. --> <html> <head> <meta charset="iso-8859-1"> <title>Scraping</title> </head> <body> <h1>Haciendo Scraping</h1> <?php require_once 'simple-html-dom-master/simple_html_dom.php'; $destino = file_get_html("https://www.dominicanatours.com/asp/detalle.asp?destino=12736&r=TI&noches=7&hotel=32&origen=6396&campania=99&habitacion=2&top=&Cal_Mes=11&Cal_Anio=2019&#acal"); // nombre del hotel $title = $destino->find('title',0); $titleContent = $title->innertext; $nombreHotel = substr($titleContent, 0, strpos($titleContent, ",")); echo "<h2>hotel: $nombreHotel</h2>"; // itinerario $itinerario = $destino->find('div[id=panel3]', 0)->children(); foreach ($itinerario as $element) { echo "<pre>$element->innertext<pre>\n"; } // precios en el calendario de salidas for($i = 9; $i <= 12; $i++){ // Create DOM from URL or file $html = file_get_html("https://www.dominicanatours.com/asp/detalle.asp?destino=12736&r=TI&noches=7&hotel=32&origen=6396&campania=99&habitacion=2&top=&Cal_Mes=$i&Cal_Anio=2019&#acal"); // encontrando de forma especifica echo "<h3>del mes $i las fechas son:</h3>"; foreach($html->find('td[class=FechaConOferta]') as $element){ $precio = $element->find('span[class=PrecioFecha]', 0); $dia = $element->find('span[class=diaCalendario]', 0); echo "El precio: $precio, para el dia: $dia <hr>"; } echo "<h3>del mes $i la fecha seleccionada</h3>"; foreach($html->find('td[class=FechaSeleccionada]') as $element){ $precio = $element->find('span[class=PrecioFechaSeleccionada]', 0); $dia = $element->find('span[class=diaCalendario]', 0); echo "El precio: $precio, para el dia: $dia <hr>"; } } ?> </body> </html><file_sep>/simple-html-dom-master/README.md **Note: I don’t intend to maintain this package. [Other copies](https://packagist.org/search/?q=simple-html-dom) of Simple HTML DOM are already available on Packagist, are easier to install and don’t clutter your `composer.json` file.** simple-html-dom =============== A copy of the [PHP Simple HTML DOM Parser project](http://simplehtmldom.sourceforge.net/) usable as a [Composer](http://getcomposer.org/) package. ## Installation First, you need to add this repository at the root of your `composer.json`: ```json "repositories": [ { "type": "vcs", "url": "https://github.com/Youpie/simple-html-dom" } ] ``` Then, require this package in the same way as any other package: ```json "require": { "simple-html-dom/simple-html-dom": "*" } ``` Do a `composer validate`, just to be sure that your file is still valid. And voilà, you’re ready to `composer update`. ## Usage Since this library doesn’t use namespaces, it lives in the global namespace. ```php $instance = new \simple_html_dom(); ``` Check the [official documentation at SourceForge](http://simplehtmldom.sourceforge.net/manual.htm).
3483a07878271bc877a05bceaf656873981578d6
[ "Markdown", "PHP" ]
2
PHP
megaBraker01/scrapingAgencia
389fe97121888714b1b41c12d6480a76db5a2d51
bfa673500e02cbcf83fe91618c65352dd40d0196
refs/heads/master
<repo_name>anusha-copado/git-practice<file_sep>/force-app/main/default/lwc/gitTestFile/gitTestFile.js import { LightningElement } from 'lwc'; export default class GitTestFile extends LightningElement { /*testing new testing*/ }
cfb91c55e1e9a8631d9699ca8fe6fdac44591577
[ "JavaScript" ]
1
JavaScript
anusha-copado/git-practice
2ae8ac008d3199d899a90796c5f9b3086be4651f
30127eda7ffd0b7f6598bfb2cfdfbabb5f885204
refs/heads/master
<file_sep>/** * Created by <NAME> * <NAME> * <NAME> * on 6/19/2017. * * Concepts of Programming Lang XLS Group 94 Summer Semester 2017 * Professor: <NAME> */ public class ValueToken<T> extends SyntaxToken { T value; public ValueToken(TokenConst type, int lineNum, T value) { super(type,lineNum); this.value = value; } public String getLexeme() { return this.value.toString(); } }<file_sep>import java.util.*; /** * Created by <NAME> * <NAME> * <NAME> * on 7/4/2017. * * Concepts of Programming Lang XLS Group 94 Summer Semester 2017 * Professor: <NAME> */ public class Parser { /* Data fields */ private SyntaxToken current; private LinkedList<SyntaxToken> tokenList; private LinkedList<SyntaxToken> parsedTokenList = new LinkedList<>(); private int errors; /* Constructor */ public Parser(List l) { this.tokenList = new LinkedList<>(l); getToken(); } // Returns whether or not a parsing was successful private boolean wasSuccessful() { return errors == 0; } // Returns a number of errors found public int errorCount() { return errors; } // Function that starts the parsing process public void parse() { errors = 0; start(); } // Returns parsed token list // Must be called after parse() public LinkedList<SyntaxToken> getParsedTokenList() { return parsedTokenList; } // Gets next token from the list private void getToken() { if (!tokenList.isEmpty()) { current = tokenList.pop(); parsedTokenList.addLast(current); } else if (current == null) { error("Reached EOF while parsing."); System.exit(0); } else { current = null; } } // Returns true if if the type of the current token // is the same as the given as a parameter token type private boolean check(TokenConst tType) { return current.type == tType; } //Looks for certain tokens to move forward, (optional found) private boolean found(TokenConst tType) { if (check(tType)) { getToken(); return true; } return false; } //Generic error catching for required tokens (required "found") private boolean expect(TokenConst tType) { if (found(tType)) { return true; } else { error("Unexpected Token"); return false; } } private void error(String message) { String err = "Error on Line " + current.lineNum + " at token "; if (current instanceof ValueToken) { err += "'" + ((ValueToken) current).value + "'"; } else { err += "'" + current.type.getLexeme() + " (" + current.type.getDesc() + ")'"; } err += ": " + message; System.out.println(err); errors++; getToken(); } //////////////////////// Recursive Descent Parsers //////////////////// // Parses primary rule void primary() { if (found(TokenConst.LPAREN)) { arithmeticExp(); expect(TokenConst.RPAREN); } else if (found(TokenConst.SUB)) { primary(); } else if (found(TokenConst.INTLIT) || found(TokenConst.STRLIT) || found(TokenConst.ID)) { } else { error("Invalid primary."); } } // Parses mulexp reule void mulExp() { primary(); if (found(TokenConst.MUL) || found(TokenConst.DIV)) { mulExp(); } } // Parses arithmetic_exp rule private void arithmeticExp() { mulExp(); if (found(TokenConst.ADD) || found(TokenConst.SUB)) { arithmeticExp(); } } // Prints out an error if we relative operator not found private void relativeOp() { if (!(found(TokenConst.EQ) || found(TokenConst.NEQ) || found(TokenConst.LT) || found(TokenConst.LTE) || found(TokenConst.GT) || found(TokenConst.GTE))) { error("Missing valid logical operator"); } } // Parses boolean expression rule private void booleanExp() { arithmeticExp(); relativeOp(); arithmeticExp(); } // Parses args rule private void args() { if (!(found(TokenConst.ID) || found(TokenConst.STRLIT) || found(TokenConst.INTLIT))) { error("Invalid argument."); } } //not looped infinitely ( the grammar rules for the non-terminal would intersect if we code it in the order ) private void argsList() { args(); if (found(TokenConst.COMA)) { argsList(); } } // Parses f_body rule private void fBody() { expect(TokenConst.BEGIN); statementList(TokenConst.ENDFUN); } //keep looking for statements in the statements list until we finfd the correct stop token private void statementList(TokenConst stopToken) { while (!found(stopToken) && !tokenList.isEmpty()) { statement(); } } // Parses statement rule private void statement() { if (found(TokenConst.IF)) { ifStatement(); } else if (found(TokenConst.WHILE)) { whileStatement(); } else if (found(TokenConst.SET)) { assignStatement(); } else if (found(TokenConst.REP)) { repeatStatement(); } else if (found(TokenConst.DIS)) { printStatement(); } else { error("Invalid start of statement."); } } // Parses if_statement rule private void ifStatement() { booleanExp(); expect(TokenConst.THEN); statementList(TokenConst.ELSE); statementList(TokenConst.EIF); } // Parses while_statement rule private void whileStatement() { booleanExp(); expect(TokenConst.DO); statementList(TokenConst.EWHILE); } // Parses assignment_statement rule private void assignStatement() { expect(TokenConst.ID); expect(TokenConst.ASSIGN); arithmeticExp(); } // Parses repeat_statement rule private void repeatStatement() { statementList(TokenConst.UNTIL); booleanExp(); expect(TokenConst.EREP); } // parses print_statement rule private void printStatement() { argsList(); } // Parses start rule private void start() { symbols(); forwardRefs(); specifications(); globals(); implement(); } // Parses symbols rule private void symbols() { if (found(TokenConst.SYM)) { symbolDef(); } } // Parses symbol_def rule private void symbolDef() { expect(TokenConst.ID); } // Parses forward_refs private void forwardRefs() { if (found(TokenConst.FORW)) { frefs(); } } // Parses frefs rule private void frefs() { found(TokenConst.REF); forwardList(); } // Parses forward_list rule private void forwardList() { forwards(); } // Parses forwards rule private void forwards() { funcMain(); decParams(); } // parses func_main rule private void funcMain() { if (found(TokenConst.FUN) && found(TokenConst.ID)) { operType(); } else if (found(TokenConst.MAIN)) { } } // Parses dec_parameters rule private void decParams() { } // Parses oper_type rule private void operType() { expect(TokenConst.RTRN); chkPtr(); chkArr(); returnType(); } // Parses chk_pointer rule private void chkPtr() { if (found(TokenConst.POINT)) { } } // Parses chk_array rule private void chkArr() { if (found(TokenConst.ARRAY)) { arrayDimList(); } } // Parses ret_type rule private void returnType() { if (found(TokenConst.TYPE)) { typeName(); } else if (found(TokenConst.STRUCT)) { expect(TokenConst.ID); } else { error("Invalid return type."); } } // Parses array_dim_list rule private void arrayDimList() { expect(TokenConst.LBRACK); do { arrayIndex(); expect(TokenConst.RBRACK); } while (found(TokenConst.LBRACK)); } // Parses type_name rule private void typeName() { if (!(found(TokenConst.MVOID) || found(TokenConst.INTEGER) || found(TokenConst.SHORT))) { error("Invalid type name."); } } // Parses array_index rule (without ICON) private void arrayIndex() { expect(TokenConst.ID); } // Parses specifications rule private void specifications() { } // Parses globals rule private void globals() { if (found(TokenConst.GLOB)) { declarations(); } } // Parses implement rule private void implement() { if (!expect(TokenConst.IMPL)) { error("IMPLEMENTATIONS is required."); } functList(); } // Parses declarations rule private void declarations() { expect(TokenConst.DECL); } // Parses funct_list rule private void functList() { while (!tokenList.isEmpty()) { functDef(); } } // Parses funct_def rule private void functDef() { expect(TokenConst.FUN); mainHead(); parameters(); fBody(); } // Parses main_head rule private void mainHead() { if (!(found(TokenConst.MAIN) || found(TokenConst.ID))) { error("Invalid method name/identifier."); } } // Parses parameters rule private void parameters() { if (found(TokenConst.PARAM)) { paramList(); } } // Parses param_list rule private void paramList() { do { paramDef(); } while (found(TokenConst.COMA)); } // Parses param_def rule private void paramDef() { expect(TokenConst.ID); chkConst(); chkPtr(); chkArr(); expect(TokenConst.TYPE); typeName(); } // Parses chk_const rule private void chkConst() { found(TokenConst.CONST); } } <file_sep>/** * Created by <NAME> * <NAME> * <NAME> * on 6/19/2017. * * Concepts of Programming Lang XLS Group 94 Summer Semester 2017 * Professor: <NAME> */ public class SyntaxToken { TokenConst type; int lineNum; public SyntaxToken(TokenConst type, int lineNum) { this.type = type; this.lineNum = lineNum; } public String getLexeme() { return this.type.getLexeme(); } public void setLexeme (String lexeme) { this.type.setLexeme(lexeme); } public TokenConst getType() { return type; } public int getLineNum() { return lineNum; } public String toString() { return "Line " + lineNum + ": " + type.toString() + "\n"; } }<file_sep>import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.List; /** * Created by <NAME> * <NAME> * <NAME> * on 6/19/2017. * * Concepts of Programming Lang XLS Group 94 Summer Semester 2017 * Professor: <NAME> */ public class Main { /* Entry point of the Scanner*/ public static void main(String[] args) throws IOException{ // Creating an input stream from a source code file InputStream f = Main.class.getResourceAsStream("test.scl"); // Creating a new Scanner using the input stream Scanner sc = new Scanner(f); // Scan the source code to find all possible tokens List<SyntaxToken> m = sc.getTokenList(); // for(SyntaxToken t: m) { // System.out.print(t.toString()); // } // Creating a parser using the list returned from the Scanner Parser parser = new Parser(m); // Parse the list with tokens parser.parse(); LinkedList<SyntaxToken> list = parser.getParsedTokenList(); // Print relevant information whether parsing was successful or not // if(parser.wasSuccessful()) // System.out.println("Parsing successful!"); // else // System.out.println("Parsing failed, " + parser.errorCount() + " errors detected."); Interpreter interpreter = new Interpreter(m); interpreter.run(); } } <file_sep>/** * Created by <NAME> * <NAME> * <NAME> * on 6/19/2017. * * Concepts of Programming Lang XLS Group 94 Summer Semester 2017 * Professor: <NAME> */ public enum TokenConst { // Operators ADD("ADD",1001,"+"), SUB("SUB",1002,"-"), MUL("MUL",1003,"*"), DIV("DIV",1004,"/"), LTE("LTE",1005,"<="), GTE("GTE",1006,">="), LT ("LT",1007,"<"), GT("GT",1008,">"), EQ("EQ",1009,"=="), NEQ("NEQ",1010,"~="), ASSIGN("ASSIGN",1011,"="), LPAREN("LPAREN",1012,"("), RPAREN("RPAREN",1013,")"), LBRACK("LBRACK",1014,"["), RBRACK("RBRACK",1015,"]"), MATPOW("MATHPOW",1016,"^"), COMA("COMA",1017,","), // Reserved Words IMP("IMP",2000,"import"), SPEC("SPEC",2001,"specifications"), SYM("SYM",2002,"symbol"), FORW("FORW",2003,"forward"), REF("REF",2004,"references"), FUN("FUN",2005,"function"), POINT("POINT",2006,"pointer"), ARRAY("ARRAY",2007,"array"), TYPE("TYPE",2008,"type"), STRUCT("STRUCT",2009,"struct"), INT("INT",2010,"integer"), ENUM("ENUM",2011,"enum"), GLOB("GLOB",2012,"global"), DECL("DECL",2013,"declarations"), IMPL("IMPL",20014,"implementations"), MAIN("MAIN",2015,"main"), PARAM("PARAM",2016,"parameters"), CONST("CONST",2017,"constant"), BEGIN("BEGIN",2018,"begin"), ENDFUN("ENDFUN",2019,"endfun"), IF("IF",2020,"if"), THEN("THEN",2021,"then"), ELSE("ELSE",2022,"else"), SET("SET",2023,"set"), EIF("EIF",2024,"endif"), REP("REP",2025,"repeat"), UNTIL("UNTIL",2026,"until"), EREP("EREP",2027,"endrepeat"), DIS("DIS",2028,"display"), WHILE("WHILE",2029,"while"), EWHILE("EWHILE",2030,"endwhile"), OF("OF",2032,"of"), DEF("DEF",2032,"define"), FOR("FOR",2033,"for"), TO("TO",2034,"to"), DO("DO",2035,"do"), IN("IN",2036,"input"), RTRN("RTRN",2037,"return"), MVOID("MVOID",2038,"mvoid"), INTEGER("INTEGER",2039,"integer"), SHORT("SHORT",2040,"short"), // Value type tokens INTLIT("INTLIT",3000,"int_literal"), STRLIT("STRLIT",3001,"string_literal"), ID("ID",3002,"identifier"); // Data Field private String desc; private int tokenCode; private String lexeme; //private int lineNumber = 0; /* Constructors */ private TokenConst(String desc, int code, String lex) { this.desc = desc; this.tokenCode = code; this.lexeme = lex; //this.lineNumber = lineNum; } // Getters and Setters public String getDesc() { return desc; } public int getTokenCode() { return tokenCode; } public String getLexeme() { return lexeme; } public void setLexeme(String lexeme) { this.lexeme = lexeme; } public String toString() { return lexeme + " --> " + desc + ":" + tokenCode; } }
813f6631c0ef4fa0cd230dde77e1456f009a2270
[ "Java" ]
5
Java
georgi-valkov/SCL_Interpreter
e7508f6953a89a09b46a8bf0d8be25fbb5b16d36
fb460a62703ecd747714b8945b39d669c74ba432
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace EventsManager.Application.Dtos { public class TaskDto { public int Id { get; set; } public string Tema { get; set; } public string Local { get; set; } public DateTime Data { get; set; } public int Participants { get; set; } public int Lote { get; set; } } } <file_sep>using EventsManager.Domain.Entity; using System; using System.Collections.Generic; using System.Text; namespace EventsManager.Domain.Interfaces.Services { public interface ITaskService : IBaseService<Task> { } } <file_sep>using Autofac; using AutoMapper; using EventsManager.Application; using EventsManager.Application.Interfaces; using EventsManager.Application.Mappers; using EventsManager.Domain.Interfaces.Repository; using EventsManager.Domain.Interfaces.Services; using EventsManager.Domain.Services; using EventsManager.Infrastructure.Data.Repository; namespace EventsManager.Infrastructure.IOC { public class ConfigurationIOC { public static void Load(ContainerBuilder builder) { #region IOC builder.RegisterType<ApplicationTaskService>().As<IApplicationTaskService>(); builder.RegisterType<TaskService>().As<ITaskService>(); builder.RegisterType<TaskRepository>().As<ITaskRepository>(); builder.Register(ctx => new MapperConfiguration(cfg => { cfg.AddProfile(new DtoToModelMappingTask()); cfg.AddProfile(new ModelToDtoMappingTask()); })); builder.Register(ctx => ctx.Resolve<MapperConfiguration>().CreateMapper()).As<IMapper>().InstancePerLifetimeScope(); #endregion IOC } } }<file_sep>using AutoMapper; using EventsManager.Application.Dtos; using EventsManager.Domain.Entity; using System; using System.Collections.Generic; using System.Text; namespace EventsManager.Application.Mappers { public class ModelToDtoMappingTask : Profile { public ModelToDtoMappingTask() { TaskDtoMap(); } private void TaskDtoMap() { CreateMap<TaskDto, Task>() .ForMember(dest => dest.Id, opt => opt.MapFrom(x => x.Id)) .ForMember(dest => dest.Tema, opt => opt.MapFrom(x => x.Tema)) .ForMember(dest => dest.Local, opt => opt.MapFrom(x => x.Local)) .ForMember(dest => dest.Data, opt => opt.MapFrom(x => x.Data)) .ForMember(dest => dest.Participants, opt => opt.MapFrom(x => x.Participants)) .ForMember(dest => dest.Lote, opt => opt.MapFrom(x => x.Lote)); } } } <file_sep>using EventsManager.Domain.Interfaces.Repository; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; namespace EventsManager.Infrastructure.Data.Repository { public class BaseRepository<T> : IBaseRepository<T> where T : class { private readonly SqlContext sqlContext; public BaseRepository(SqlContext sqlContext) { this.sqlContext = sqlContext; } public void Add(T obj) { try { sqlContext.Set<T>().Add(obj); sqlContext.SaveChanges(); } catch (Exception ex) { throw ex; } } public IEnumerable<T> GetAll() { return sqlContext.Set<T>().ToList(); } public T GetById(int id) { return sqlContext.Set<T>().Find(id); } public void Remove(T obj) { try { sqlContext.Set<T>().Remove(obj); sqlContext.SaveChanges(); } catch (Exception ex) { throw ex; } } public void Update(T obj) { try { sqlContext.Entry(obj).State = EntityState.Modified; sqlContext.SaveChanges(); } catch (Exception ex) { throw ex; } } } }<file_sep>using AutoMapper; using EventsManager.Application.Dtos; using EventsManager.Application.Interfaces; using EventsManager.Domain.Entity; using EventsManager.Domain.Interfaces.Services; using System.Collections.Generic; namespace EventsManager.Application { public class ApplicationTaskService : IApplicationTaskService { private readonly ITaskService taskService; private readonly IMapper mapper; public ApplicationTaskService(ITaskService taskService , IMapper mapper) { this.taskService = taskService; this.mapper = mapper; } public void Add(TaskDto taskDto) { var task = mapper.Map<Task>(taskDto); taskService.Add(task); } public IEnumerable<TaskDto> GetAll() { var tasks = taskService.GetAll(); var tasksDto = mapper.Map<IEnumerable<TaskDto>>(tasks); return tasksDto; } public TaskDto GetById(int id) { var task = taskService.GetById(id); var tasksDto = mapper.Map<TaskDto>(task); return tasksDto; } public void Remove(TaskDto taskDto) { var task = mapper.Map<Task>(taskDto); taskService.Remove(task); } public void Update(TaskDto taskDto) { var task = mapper.Map<Task>(taskDto); taskService.Update(task); } } }<file_sep>using System; using System.ComponentModel.DataAnnotations; namespace EventsManager.Domain.Entity { public class Base { [Key] public int Id { get; set; } } } <file_sep>using AutoMapper; using EventsManager.Application.Dtos; using EventsManager.Domain.Entity; namespace EventsManager.Application.Mappers { public class DtoToModelMappingTask : Profile { public DtoToModelMappingTask() { TaskMap(); } private void TaskMap() { CreateMap<TaskDto, Task>() .ForMember(dest => dest.Id, opt => opt.Ignore()) .ForMember(dest => dest.Tema, opt => opt.MapFrom(x => x.Tema)) .ForMember(dest => dest.Local, opt => opt.MapFrom(x => x.Local)) .ForMember(dest => dest.Data, opt => opt.MapFrom(x => x.Data)) .ForMember(dest => dest.Participants, opt => opt.MapFrom(x => x.Participants)) .ForMember(dest => dest.Lote, opt => opt.MapFrom(x => x.Lote)); } } } <file_sep>using System; namespace EventsManager.Domain.Entity { public class Task : Base { public string Tema { get; set; } public string Local { get; set; } public DateTime Data { get; set; } public int Participants { get; set; } public int Lote { get; set; } } } <file_sep>using EventsManager.Domain.Interfaces.Repository; using EventsManager.Domain.Interfaces.Services; using System.Collections.Generic; namespace EventsManager.Domain.Services { public class BaseService<T> : IBaseService<T> where T : class { private readonly IBaseRepository<T> repository; public BaseService(IBaseRepository<T> repository) { this.repository = repository; } public void Add(T obj) { repository.Add(obj); } public IEnumerable<T> GetAll() { return repository.GetAll(); } public T GetById(int id) { return repository.GetById(id); } public void Remove(T obj) { repository.Remove(obj); } public void Update(T obj) { repository.Update(obj); } } }<file_sep>using EventsManager.Application.Dtos; using System.Collections.Generic; namespace EventsManager.Application.Interfaces { public interface IApplicationTaskService { void Add(TaskDto taskDto); void Update(TaskDto taskDto); void Remove(TaskDto taskDto); IEnumerable<TaskDto> GetAll(); TaskDto GetById(int id); } }<file_sep>using EventsManager.Application.Dtos; using EventsManager.Domain.Entity; using System.Collections.Generic; namespace EventsManager.Application.Interfaces { public interface ITaskMapper { Task MapDtoToEntity(TaskDto taskDto); IEnumerable<TaskDto> MapperTasksListDto(IEnumerable<Task> tasks); TaskDto MapperEntityToDto(Task task); } }<file_sep>using EventsManager.Domain.Entity; namespace EventsManager.Domain.Interfaces.Repository { public interface ITaskRepository : IBaseRepository<Task> { } } <file_sep>using EventsManager.Application.Dtos; using EventsManager.Application.Interfaces; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; namespace EventsManager.API.Controllers { [Route("[controller]")] [ApiController] public class TaskController : ControllerBase { private readonly IApplicationTaskService applicationTaskService; public TaskController(IApplicationTaskService applicationTaskService) { this.applicationTaskService = applicationTaskService; } [HttpGet] public ActionResult<IEnumerable<string>> Get() { return Ok(applicationTaskService.GetAll()); } [HttpGet("{id}")] public ActionResult<string> Get(int id) { return Ok(applicationTaskService.GetById(id)); } [HttpPost] public ActionResult Post([FromBody] TaskDto taskDto) { try { if (taskDto == null) { return NotFound(); } applicationTaskService.Add(taskDto); return Ok("Task criada com sucesso!"); } catch (Exception ex) { throw ex; } } [HttpPut] public ActionResult Put([FromBody] TaskDto taskDto) { try { if (taskDto == null) { return NotFound(); } applicationTaskService.Update(taskDto); return Ok("Task atualizada com sucesso!"); } catch (Exception ex) { throw ex; } } [HttpDelete] public ActionResult Delete([FromBody] TaskDto taskDto) { try { if (taskDto == null) { return NotFound(); } applicationTaskService.Add(taskDto); return Ok("Task removida com sucesso!"); } catch (Exception ex) { throw ex; } } } }<file_sep>using EventsManager.Domain.Entity; using EventsManager.Domain.Interfaces.Repository; namespace EventsManager.Infrastructure.Data.Repository { public class TaskRepository : BaseRepository<Task>, ITaskRepository { private readonly SqlContext sqlContext; public TaskRepository(SqlContext sqlContext) : base(sqlContext) { this.sqlContext = sqlContext; } } }
968a9caea1961a664f40763d6aa9ae5d72a7a8fa
[ "C#" ]
15
C#
joaoazevedo65485/tasksddd
3cadb3ae007aa18ca656c2b833489aefcb4b1773
4d12195f99c11b201198766cfac4875de145bdd5
refs/heads/master
<file_sep>console.log("berhasil bosQ");
70071180db9cfffb2913b3b8e3d99988ae79aa95
[ "JavaScript" ]
1
JavaScript
AdhyWiranto44/rekweb-pertemuan-3
a5f4fbe05f032376c92586fe2b6b3cbe53f91966
5f3dc521fefbae2503115a47ceb177ecfb0afcb8
refs/heads/master
<file_sep># Mobile Sensor Cloud application ## Project Description ► Cloud application which retrieves weather data from sensors deployed at various locations which can be viewed by a customer<br> ► Modules:<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-Admin: Monitors the state of all the sensors, sensor vendors and users<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-Sensor Vendor: Has sensors deployed at various location and enrolls in the application<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-Customer: Views the sensor data by enrolling in a tariff.<br> ## Technology Stack ► BackEnd: Node.js, ExpressJS, RESTful Web Service<br> ► FrontEnd: AngularJS, BootStrap, amCharts, HTML, CSS<br> ► Cloud: AWS<br> ► Load Balancing: HAProxy<br> ► Database: MySQL, MongoDB<br> ## Architecture ![Architecture](screenshots/architecture.png "Architecture:") <br> ### Admin Dashboard ![Admin Dashboard](screenshots/admin%20dashboard.png "Admin Dashboard:") <br> ### Sensor Data ![Sensor Data](screenshots/sensordata.png "Sensor Data:") <br> ### List Users and Sensors ![List Users and Sensors](screenshots/listusersandsensors.png "List Users and Sensors:") <br> ### Sensor Detail ![Sensor Detail](screenshots/sensordetail.png "Sensor Detail:") <br> ### Vendor Dashboard ![Vendor Dashboard](screenshots/vendordashboard.png "Vendor Dashboard:") <file_sep># Mobile Senor Cloud Application Developed a Mobile Sensor Cloud application (Sensor as a Service) hosted on AWS EC2 allows on demand access to real time and historic weather data by simulating sensors deployed at various locations to the user. HA proxy Load Balancer Incorporated Sensor Vendor to add / remove sensors on the cloud and admin to monitor all sensors and their data. <file_sep> /** * Module dependencies. */ var express = require('express') , routes = require('./routes') , signup = require('./routes/signup') , signin = require('./routes/signin') , sensor = require('./routes/sensor') , admin = require('./routes/admin') , user = require('./routes/user') , http = require('http') , path = require('path'); //, session = require('client-sessions'); var app = express(); //all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.cookieParser()); app.use(express.session({ secret: 'keyboard cat', duration: 30 * 60 * 1000})); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); app.configure('development', function(){ app.use(express.errorHandler()); }); app.get('/', routes.index); app.get('/signin', function(req,res){res.render("signin");}); app.get('/signup', function(req,res){res.render("signup");}); app.post('/signin', signin.signin); app.post('/signup', signup.register); app.get('/signupsensorowner', function(req,res){res.render("signupsensorowner");}); app.get('/admin', admin.admin); app.get('/sensorowner', function(req,res){if(req.session.email){res.render("sensorowner");}else{res.render("index");}}); app.get('/user', user.user); app.post('/addsensor', sensor.addsensor); app.post('/editsensor', sensor.editsensor); app.post('/removesensor', sensor.removesensor); app.post('/togglesensor', sensor.togglesensor); app.get('/getsensors', sensor.getsensors); app.get('/getusers', admin.getusers); app.post('/userprofile', function(req,res){req.session.userprofileemail = req.param("useremail");res.end();}); app.get('/userprofile', function(req,res){res.render("adminuserprofile");}); app.get('/getuserprofile', admin.getuserprofile); app.get('/getsensorowners', admin.getsensorowners); app.post('/sensorownerprofile', function(req,res){req.session.sensorownerprofileemail = req.param("sensorowneremail");res.end();}); app.get('/sensorownerprofile', function(req,res){res.render("adminsensorownerprofile");}); app.get('/getsensorownerprofile', admin.getsensorownerprofile); app.get('/getownersensors', admin.getownersensors); app.get('/getallsensors', admin.getallsensors); app.post('/sensorprofile', function(req,res){req.session.sensoridprofile = req.param("sensorid"); res.end();}); app.get('/sensorprofile', function(req,res){res.render("adminsensorprofile");}); app.get('/getsensorprofile', admin.getsensorprofile); app.post('/getusersensors', user.getusersensors); app.post('/addsensortouser', user.addsensortouser); app.get('/getsensordata', user.getsensordata); app.get('/getuserselfprofile', user.getuserselfprofile); app.post('/updatetariff', user.updatetariff); app.post('/updatetariffsensorlocation', user.updatetariffsensorlocation); app.get('/signout', function(req,res){ req.session.destroy(); console.log("Session destroyed"); res.redirect('/'); }); http.createServer(app).listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port')); }); <file_sep> # Simulation of Sensors for Mobile Sensor Cloud Application This is a simulation application which simulates real sensors for mobile sensor cloud application <file_sep>var ejs = require("ejs"); var mysql = require('./mysql'); exports.index = function(req, res){ if(req.session.email){ var email = req.session.email + " via index session"; res.render("home", {emailid: email}); } else{ res.render("index"); } }; exports.signin = function(req,res){ var email = req.body[0].email; var password = req.body[0].password; var usertype = req.body[1]; //1 - admin , 2- owner ,3-user var getUser = "select * from userinfo where email ='" + email + "' and password = '" + <PASSWORD> + "' and usertype = '" + usertype + "'"; console.log("Query is:" + getUser); mysql.fetchData(function(err,results){ console.log("result is" + JSON.stringify(results)); if(err){ throw err; } else { if(results.length > 0){ console.log("valid Login"); req.session.email = email; console.log("session variables : " + req.sessionemail + " " + req.session.tariffplan + " " + req.session.location + " " + req.session.sensorlocation1); if(usertype == "1"){ req.session.usertype = 3; res.end("admin"); } else if(usertype == "2"){ req.session.usertype = 2; res.end("sensorowner"); } else if(usertype == "3"){ req.session.tariffplan = results[0].tariffplan; req.session.tariffsensorlocation = results[0].sensorlocation; req.session.tariffsensorlocation1 = results[0].sensorlocation1; req.session.usertype = 3; res.end("user"); } } else { console.log("WRONG"); res.end("invalid"); } } },getUser); };<file_sep>var mysql = require('./mysql'); var mongo = require("./mongo"); var mongoURL = "mongodb://localhost:27017/simulation"; exports.admin = function(req, res){ if(req.session.email){ var email = req.session.email + " via index session"; res.render("admin"); } else{ res.render("index"); } }; exports.getusers = function(req,res){ var query = "select * from userinfo where usertype = '3'"; mysql.fetchData(function(err, results){ if (err) { throw err; } else { if (results.length > 0) { console.log("getusers in IF"); console.log(JSON.stringify(results)); res.end(JSON.stringify(results)); } } }, query); }; exports.getuserprofile = function(req,res){ var query = "select * from userinfo where email = '" + req.session.userprofileemail + "'"; mysql.fetchData(function(err, results){ if (err) { throw err; } else { console.log("userprofile is " + JSON.stringify(results)); if (results.length > 0) { console.log("getuserprofile in IF"); res.end(JSON.stringify(results)); } } }, query); }; exports.getsensorowners = function(req,res){ var query = "select * from userinfo where usertype = '2'"; mysql.fetchData(function(err, results){ if (err) { throw err; } else { if (results.length > 0) { console.log("getsensorowners in IF"); console.log(JSON.stringify(results)); res.end(JSON.stringify(results)); } } }, query); }; exports.getsensorownerprofile = function(req,res){ var query = "select * from userinfo where email = '" + req.session.sensorownerprofileemail + "'"; mysql.fetchData(function(err, results){ if (err) { throw err; } else { console.log("sensorownerprofile is " + JSON.stringify(results)); if (results.length > 0) { console.log("getsensorownerprofile in IF"); res.end(JSON.stringify(results)); } } }, query); }; exports.getownersensors = function(req,res){ var query = "select * from sensors where email = '" + req.session.sensorownerprofileemail + "'"; mysql.fetchData(function(err, results){ if (err) { throw err; } else { console.log("ownersensors are " + JSON.stringify(results)); if (results.length > 0) { console.log("owner sensors in IF"); res.end(JSON.stringify(results)); } } }, query); }; exports.getsensorprofile = function(req,res){ var query = "select * from sensors where sensorid = '" + req.session.sensoridprofile + "'"; mysql.fetchData(function(err, results){ if (err) { throw err; } else { console.log("sensor are " + JSON.stringify(results)); if (results.length > 0) { console.log("sensors in IF"); res.end(JSON.stringify(results)); } } }, query); }; exports.getallsensors = function(req,res){ var query = "Select * from sensors"; var response = []; var sensorids = []; mysql.fetchData(function(err, results){ console.log("all sensors : " + JSON.stringify(results)); if (err) { throw err; } else{ if (results.length > 0) { response[0] = results //res.end(JSON.stringify(results)); mongo.connect(mongoURL, function(){ for(var i = 0; i< results.length; i++){ sensorids.push(results[i].sensorid.toString()); } console.log(sensorids); console.log('Connected to mongo at: ' + mongoURL); var coll = mongo.collection('sensorsimulation'); coll.find({sensorid: {$in: sensorids}}).toArray(function(err, result){ console.log("In getsensordata : " + JSON.stringify(result)); if (result) { response[1] = result; res.end(JSON.stringify(response)); } else { res.end("empty"); } }); }); } } }, query); }; <file_sep>var mysql = require('./mysql'); var mongo = require("./mongo"); var mongoURL = "mongodb://localhost:27017/simulation"; exports.user = function(req, res){ if(req.session.email){ res.render("user"); } else{ res.render("index"); } }; exports.getusersensors = function(req,res){ var query = "select * from sensors where sensorlocation = '" + req.param("tariffsensorlocation") + "' and status = 'on'"; mysql.fetchData(function(err, results){ console.log("in fetch data"); if (err) { throw err; } else { console.log(JSON.stringify(results)); if (results.length > 0) { console.log("in IF"); res.end(JSON.stringify(results)); } } }, query); }; exports.addsensortouser = function(req,res){ console.log("in add sensor to user"); var query = "insert into user_sensors values ('" + req.session.email + "', '" + req.param('sensorid') + "')"; mysql.fetchData(function(err, results){ console.log("in fetch data addsesnortouser"); if (err) { throw err; } else { console.log("sensor added to user"); res.end(); if (results.length > 0) { console.log("in IF"); res.end(JSON.stringify(results)); } } }, query); }; //exports.getsensordata = function(req,res){ // // var query = "select * from sensors"; // // if(req.session.tariffplan == 1){ // // query = "select * from sensors where sensorlocation = '" + req.session.tariffsensorlocation + "' and status = 'on'"; // console.log("one " + query); // } // else if(req.session.tariffplan == 2){ // // query = "select * from sensors where sensorlocation = '" + req.session.tariffsensorlocation + "' OR sensorlocation = '" + req.session.tariffsensorlocation1 + "' and status = 'on'"; // console.log("one " + query); // } // // // // mysql.fetchData(function(err, results){ // // console.log("getsensor data : " + JSON.stringify(results)); // if (err) { // throw err; // } // else { // // console.log("getsensordata : " + JSON.stringify(results)); // // if (results.length > 0) { // // console.log("in IF"); // res.end(JSON.stringify(results)); // } // } // }, query); //}; exports.updatetariff = function(req,res){ console.log("in updatetariff"); var query; if(req.param("tariffplan") == 1){ query = "update userinfo set tariffplan = '" + req.param("tariffplan") + "', bill = 49.99 where email = '" + req.session.email + "'"; } else if(req.param("tariffplan") == 2){ query = "update userinfo set tariffplan = '" + req.param("tariffplan") + "', bill = 79.99 where email = '" + req.session.email + "'"; } else if(req.param("tariffplan") == 3){ query = "update userinfo set tariffplan = '" + req.param("tariffplan") + "', bill = 99.99 where email = '" + req.session.email + "'"; } console.log("query " + query); mysql.fetchData(function(err, results){ if (err) { throw err; } else { console.log("updated tariffplan"); req.session.tariffplan = req.param("tariffplan"); res.end(); } }, query); }; exports.updatetariffsensorlocation = function(req,res){ console.log("in updatetarifflocation"); if(req.session.tariffplan == 1){ query = "update userinfo set sensorlocation = '" + req.param("tariffsensorlocation") + "' where email = '" + req.session.email + "'"; } else if(req.session.tariffplan == 2){ query = "update userinfo set sensorlocation = '" + req.param("tariffsensorlocation") + "', sensorlocation1 = '" + req.param("tariffsensorlocation1") + "' where email = '" + req.session.email + "'"; } console.log("query " + query); mysql.fetchData(function(err, results){ if (err) { throw err; } else { console.log("updated tariff location"); req.session.tariffsensorlocation = req.param("tariffsensorlocation"); if(req.session.tariffplan == 2){ req.session.tariffsensorlocation1 = req.param("tariffsensorlocation1"); } res.end(); } }, query); }; exports.getuserselfprofile = function(req,res){ mysql.fetchData(function(err, results){ if (err){ throw err; } else { res.end(JSON.stringify(results)); } }, "select * from userinfo where email = '" + req.session.email + "'"); }; exports.getsensordata = function(req,res){ var sensorids = []; var query = "select sensorid from sensors"; if(req.session.tariffplan == 1){ query = "select sensorid from sensors where sensorlocation = '" + req.session.tariffsensorlocation + "' and status = 'on'"; console.log("one " + query); } else if(req.session.tariffplan == 2){ query = "select sensorid from sensors where sensorlocation = '" + req.session.tariffsensorlocation + "' OR sensorlocation = '" + req.session.tariffsensorlocation1 + "' and status = 'on'"; console.log("one " + query); } mysql.fetchData(function(err, results){ if (err) { throw err; } else { console.log("SENSOR ID RETREIVED"); console.log(JSON.stringify(results)); //res.end(); if (results.length > 0) { mongo.connect(mongoURL, function(){ for(var i = 0; i< results.length; i++){ sensorids.push(results[i].sensorid.toString()); } console.log(sensorids); console.log('Connected to mongo at: ' + mongoURL); var coll = mongo.collection('sensorsimulation'); coll.find({sensorid: {$in: sensorids}}).toArray(function(err, response){ console.log("In getsensordata : " + JSON.stringify(response)); if (response) { res.end(JSON.stringify(response)); } else { res.end("empty"); } }); }); } } }, query); };<file_sep> var mysql = require('./mysql'); exports.list = function(req, res){ res.send("respond with a resource"); }; exports.register = function(req,res){ var email = req.body[0].email; var name = req.body[0].name; var password = req.body[0].password; var mobile = req.body[0].mobile; var usertype = req.body[1]; //1 - admin , 2- owner ,3-user var tariffplan = req.body[0].tariffplan; var tariffsensorlocation = req.body[0].tariffsensorlocation; var tariffsensorlocation1 = req.body[0].tariffsensorlocation1; var bill; var query; console.log("req" + JSON.stringify(req.body)); if(tariffplan == 1){bill = 49.99;} else if(tariffplan == 2){bill = 79.99;} else if(tariffplan == 3){bill = 99.99;} if(usertype == 2){ query = "INSERT INTO userinfo (email, name, password, mobile, usertype) VALUES ('" + email + "','" + name + "','" + password + "','" + mobile + "','" + usertype + "')"; } else if(usertype == 3){ query = "INSERT INTO userinfo (email, name, password, mobile, usertype, tariffplan, sensorlocation, sensorlocation1, bill) " + "VALUES ('" + email + "','" + name + "','" + password + "','" + mobile + "','" + usertype + "','" + tariffplan + "','" + tariffsensorlocation + "','" + tariffsensorlocation1 + "','" + bill +"')"; } console.log("signup query " + query); mysql.fetchData(function(err, results){ //console.log("in fetch data"); if (err) { throw err; } else { console.log("data inserted"); req.session.email = email; res.end("registered"); } }, query); };
b8ad8c0c8b09c287dc4c1655ba1687c7ddf17c04
[ "Markdown", "JavaScript" ]
8
Markdown
rajputankit/MobileSensorCloud
fed8054a995e0ff222468cbe8b4e87f37e6ce939
19829d7a2b587e8ab9c92069b78a8450b296a4aa
refs/heads/master
<file_sep>import createElement from './vdom/createElement'; import render from './vdom/render'; import mount from './vdom/mount'; import diff from './vdom/diff'; import manageState from './state/manageState' export default function generateApp(vApp, createVApp, $app, $rootEl,elementAppId, _oldState){ let oldState = _oldState const newState = manageState.getState() render(vApp); mount($app, elementAppId) const vNewApp = createVApp(manageState.getState()) const patch = oldState && newState !== undefined ? diff(vApp, vNewApp, oldState, newState) : diff(vApp, vNewApp); $rootEl = patch($rootEl); vApp = vNewApp; oldState = newState; }<file_sep>import callDirectives from '../directives/index' import bindText from '../bind/bindText' const renderElem = ({ tagName, attrs, children }) => { const $el = document.createElement(tagName); for (const [k, v] of Object.entries(attrs)) { if (k[0] === 't') { callDirectives(k, v) } $el.setAttribute(k, v); } for (const child of children) { const $child = render(child); $el.appendChild($child); } return $el; }; const render = vNode => { if (typeof vNode === "string") { const binded = bindText(vNode) return document.createTextNode(binded); } return renderElem(vNode); }; export default render;<file_sep>let state = {} const createState = (_key, value) => { return state = {...state, [_key]: value} } const getState = () =>{ return state } const setState = (_key, value) =>{ return state = { ...state, [_key]: value } } export default { createState, getState, setState } <file_sep>const tIf = (v, $el) =>{ const _v = v.toString() const conditional = { 'true': () => $el.style.display = "", 'false': () => $el.style.display = "none", 'error': () => console.error("Error test") } return (conditional[_v] || conditional['error'])(); } export default tIf;<file_sep>import manageState from '../state/manageState' const bindText = (textValue) =>{ const text = textValue.split(/(\{\{[^}]+\}\})/g).filter(x => x !== '') const neededBind = text.map((_textValue) => _textValue.match(/^\{\{[^}]+\}\}$/) ? binding(_textValue) : _textValue) function binding(textToBind){ const _textToBind = textToBind.replace(/^\{\{([^}]+)\}\}$/, '$1').trim() const index = _textToBind.split('.')[1] const state = manageState.getState() return state[index] } return neededBind.join('') } export default bindText<file_sep><h2 align="center">Thresh</h2> <p align="center"><img width="100" src="https://gamepedia.cursecdn.com/lolesports_gamepedia_en/7/7b/ThreshSquare.png" alt="Thresh"></p> Experimental UI library ### Run `npm install threshjs thresh-cli` To Install all dependencies and CLI ### Run `cli create-thresh-app` To create a Thresh app More informations: https://www.npmjs.com/package/thresh-cli #### `npm run dev` or `yarn dev` Open: http://localhost:1234/ ##### Examples *** ###### State management ```javascript import manageState from './state/manageState' //Create state manageState.createState('count', 0); //Get state const data = manageState.getState() // Set state manageState.setState('count', 1) ``` *** ###### Hello world - Create element Description: for now children needs to be a array ```javascript //... createElement('h1', { children:["Hello World"] } ``` *** ###### Bind state Description: you need to pass the state as parameter!! ```javascript manageState.createState('name', "Thresh"); createElement('h1', { children:["Hello World {{ state.name }}"] } ``` *** ###### tModel -> get a value from input ```javascript //... attrs:{ value: state.name, tModel: 'name' } ``` *** ###### tClick -> onClick ```javascript //... attrs:{ id: "btn", tClick: { method: test, id: 'btn' } ``` ### Thresh CLI Documentation at https://github.com/HenriqueFutema/CLI-Thresh NPM Link: https://www.npmjs.com/package/thresh-cli ... <file_sep>import manageState from '../state/manageState' const tModel = (el) =>{ window.onload = function(){ let $el = document.getElementById(el) function changeInput(){ manageState.setState(el, $el.value) } $el.addEventListener('input', changeInput) } } export default tModel<file_sep>import tModel from './tModel'; import tClick from './tClick'; import tIf from './tIf'; //All Directives function callDirectives(k, v, $el){ const directive = { 'tModel': () => tModel(v), 'tClick': () => tClick(v), 'tIf': () => tIf(v, $el), 'default': () => console.error('Error directive') } return (directive[k] || directive['default'])(); } export default callDirectives
0c09d4b80dec3f321326659b535eb43b21533248
[ "JavaScript", "Markdown" ]
8
JavaScript
HenriqueFutema/Thresh
3f53ca2279b73a2de1db8aff86619bad014a0024
0391432f9aab4b598714dc02637c1b27ff09b2db
refs/heads/master
<repo_name>zhangyn723777/ting<file_sep>/README.md ## Ting Ting is a material design music social media player app, have music playback, download function. Ting Official website: http://tinger.herokuapp.com/ At present, In the app only access to Ting official website users to share the first 20 songs info and songs comment info. #### [中文文档](https://github.com/Freelander/ting/blob/master/README_ZH.md) ## ScreenShots ![image](https://github.com/Freelander/ting/blob/master/screenshots/1.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/2.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/3.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/4.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/5.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/6.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/7.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/8.png) ##### [DownLoad](http://fir.im/cd7b) ## Thanks **Open source library** Project | Introduction ---- | ---- [Picasso](https://github.com/square/picasso) | A powerful image downloading and caching library for Android [AndroidSlidingUpPanel](https://github.com/umano/AndroidSlidingUpPanel) | This library provides a simple way to add a draggable sliding up panel to your Android application [material-ripple](https://github.com/balysv/material-ripple) | Android L Ripple effect wrapper for Views [numberprogressbar](https://github.com/daimajia/NumberProgressBar) | A beautiful, slim Android ProgressBar [Volley](https://github.com/mcxiaoke/android-volley) | Google network frameworks [Gson](https://github.com/google/gson) | A Java library that can be used to convert Java Objects into their JSON representation [ButterKnife](https://github.com/JakeWharton/butterknife) | Bind Android views and callbacks to fields and methods [SwipeBackLayout](https://github.com/ikew0ng/SwipeBackLayout) | An Android library that help you to build app with swipe back gesture ## License ``` Copyright 2015~2016 Freelander of copyright owner Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` <file_sep>/app/src/main/java/com/music/ting/model/LocalSongs.java package com.music.ting.model; import android.os.Parcel; import android.os.Parcelable; /** * Created by Jun on 2015/5/28. * 本地歌曲信息实体类 */ public class LocalSongs implements Parcelable { /** * 歌曲Id */ private long id; /** * 歌曲标题 */ private String title; /** * 艺术家 */ private String artist; /** * 专辑 */ private String album; /** * 专辑Id */ private long albumId; /** * 时长 */ private long duration; /** * 歌曲大小 */ private long size; /** * 歌曲路径 */ private String url; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getArtist() { return artist; } public void setArtist(String artist) { this.artist = artist; } public long getAlbumId() { return albumId; } public void setAlbumId(long albumId) { this.albumId = albumId; } public String getAlbum() { return album; } public void setAlbum(String album) { this.album = album; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(this.id); dest.writeString(this.title); dest.writeString(this.artist); dest.writeString(this.album); dest.writeLong(this.albumId); dest.writeLong(this.duration); dest.writeLong(this.size); dest.writeString(this.url); } public LocalSongs() { } private LocalSongs(Parcel in) { this.id = in.readLong(); this.title = in.readString(); this.artist = in.readString(); this.album = in.readString(); this.albumId = in.readLong(); this.duration = in.readLong(); this.size = in.readLong(); this.url = in.readString(); } public static final Parcelable.Creator<LocalSongs> CREATOR = new Parcelable.Creator<LocalSongs>() { public LocalSongs createFromParcel(Parcel source) { return new LocalSongs(source); } public LocalSongs[] newArray(int size) { return new LocalSongs[size]; } }; } <file_sep>/README_ZH.md ## Ting-一款音乐社交 App Ting 网址: http://tinger.herokuapp.com/ 目前 App 只获取 Ting 网站上用户分享的前 20 首歌曲信息, 以及歌曲评论信息 ## ScreenShots ![image](https://github.com/Freelander/ting/blob/master/screenshots/1.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/2.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/3.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/4.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/5.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/6.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/7.png) ![image](https://github.com/Freelander/ting/blob/master/screenshots/8.png) ##### [DownLoad](http://fir.im/cd7b) ## Thanks **使用到的一些开源库** 库名 | 简介 ---- | ---- [Picasso](https://github.com/square/picasso) | Square 公司开源的图片缓存库 [AndroidSlidingUpPanel](https://github.com/umano/AndroidSlidingUpPanel) | 向上滑面板 [material-ripple](https://github.com/balysv/material-ripple) | 让 App 在 Android 5.0 以下版本点击任何 View 都带有水波纹效果 [numberprogressbar](https://github.com/daimajia/NumberProgressBar) | 带有百分比显示的进度条 [Volley](https://github.com/mcxiaoke/android-volley) | Google 开发的一个网络请求库 [Gson](https://github.com/google/gson) | Google 开发的一个解析 json 数据库 [ButterKnife](https://github.com/avast/android-butterknife-zelezny) | ButterKnife 生成器, 简写 findViewId 代码 [SwipeBackLayout](https://github.com/ikew0ng/SwipeBackLayout) | 实现向右滑返回功能 ## License ``` Copyright 2015~2016 Freelander of copyright owner Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` <file_sep>/app/src/main/java/com/music/ting/model/OnLineSongs.java package com.music.ting.model; /** * Created by Jun on 2015/5/31. */ public class OnLineSongs { /** * singer : Cascada * lyric : [00:00.00]Everytime We Touch (Yanou&amp;#039;s Candlelight Mix) * id : 1769890006 * pic : http://img.xiami.net/images/album/img22/995422/1290995422_2.jpg * pic2x : http://img.xiami.net/images/album/img22/995422/1290995422.jpg * title : Everytime We Touch (Yanou&#39;s Candlelight Mix) * songurl : http://m5.file.xiami.com/276/37276/413077/1769890006_1793142_l.mp3?auth_key=a6d0acea381c5b2d4fbdf12edf482e16-1433116800-0-null * lyricurl : http://img.xiami.net/lyric/6/1769890006_13830711051717.lrc */ private String singer;//歌手 private String lyric;//歌词 private int id;//歌曲播放Id private String pic;//专辑图片 private String pic2x;//专辑图片大图 private String title;//歌名 private String songurl;//歌曲播放地址 private String lyricurl;//歌词地址 public void setSinger(String singer) { this.singer = singer; } public void setLyric(String lyric) { this.lyric = lyric; } public void setId(int id) { this.id = id; } public void setPic(String pic) { this.pic = pic; } public void setPic2x(String pic2x) { this.pic2x = pic2x; } public void setTitle(String title) { this.title = title; } public void setSongurl(String songurl) { this.songurl = songurl; } public void setLyricurl(String lyricurl) { this.lyricurl = lyricurl; } public String getSinger() { return singer; } public String getLyric() { return lyric; } public int getId() { return id; } public String getPic() { return pic; } public String getPic2x() { return pic2x; } public String getTitle() { return title; } public String getSongurl() { return songurl; } public String getLyricurl() { return lyricurl; } } <file_sep>/app/build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 21 buildToolsVersion "22.0.0" defaultConfig { applicationId "com.music.ting" minSdkVersion 14 targetSdkVersion 21 versionCode 1 versionName "1.1" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { repositories { mavenCentral() } compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:appcompat-v7:21.0.3' compile 'com.android.support:cardview-v7:21.0.+' compile 'com.android.support:recyclerview-v7:21.0.+' compile 'com.android.support:design:22.2.0' compile 'com.squareup.picasso:picasso:2.4.0' compile 'com.sothree.slidinguppanel:library:3.0.0' compile 'com.balysv:material-ripple:1.0.2' compile 'com.daimajia.numberprogressbar:library:1.2@aar' compile 'com.jakewharton:butterknife:6.1.0' compile 'me.imid.swipebacklayout.lib:library:1.0.0' compile files('libs/gson-2.3.1.jar') compile files('libs/volley.jar') } <file_sep>/app/src/main/java/com/music/ting/ui/activity/CommentActivity.java package com.music.ting.ui.activity; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.ShareActionProvider; import android.support.v7.widget.Toolbar; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Response; import com.music.ting.R; import com.music.ting.adapter.CommentAdapter; import com.music.ting.data.GsonRequest; import com.music.ting.data.RequestManager; import com.music.ting.model.Comments; import com.music.ting.model.FileInfo; import com.music.ting.model.OnLineSongs; import com.music.ting.model.Songs; import com.music.ting.service.DownloadService; import com.music.ting.service.MusicService; import com.music.ting.service.MusicService.MusicBinder; import com.music.ting.ui.fragment.DownLoadFragment; import com.music.ting.utils.MediaUtils; import com.music.ting.utils.TingAPI; import com.sothree.slidinguppanel.SlidingUpPanelLayout; import com.squareup.picasso.Picasso; import java.util.List; /** * Created by Jun on 2015/5/20. * */ public class CommentActivity extends BaseActivity { private final static String TAG = "Ting"; public Songs songs = new Songs(); private RecyclerView recyclerView; private SwipeRefreshLayout commentSwipe; private Toolbar toolbar; private ShareActionProvider shareActionProvider; private SlidingUpPanelLayout slidingUpPanelLayout; private ImageView songImage;//歌曲封面 private ImageView songLargeImage;//歌曲封面大图 private TextView songTitle, songArtist;//歌名,歌手 private ImageView playImage;//播放按钮 private ImageView repeatImage;//循环按钮 private ImageView rewImage;//后退按钮 private ImageView playBtnImage;//播放按钮 private ImageView fwdImage;//快进按钮 private ImageView shuffleImage;//随机播放按钮 private TextView tvTimeElapsed;//当前播放位置 private TextView tvDuration;//当前歌曲最大长度 private SeekBar songSeekBar;//歌曲进度条 public String playUrl = ""; private int currentPosition;//当前播放歌曲位置 private int currentMax;//歌曲最大长度 private MusicBinder musicBinder; private ProgressReceiver progressReceiver; private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { musicBinder = (MusicBinder) service; } @Override public void onServiceDisconnected(ComponentName name) { } }; private void connectToMusicService() { Intent intent = new Intent(this, MusicService.class); bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_song_info); initToolbar(); toolbar = (Toolbar) findViewById(R.id.toolbar); //点击返回键 toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); connectToMusicService();//绑定服务 getData(); slidingUpPanelLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout); slidingUpPanelLayout.setPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() { @Override public void onPanelSlide(View panel, float slideOffset) { } @Override public void onPanelExpanded(View panel) { playImage.setVisibility(View.INVISIBLE); } @Override public void onPanelCollapsed(View panel) { playImage.setVisibility(View.VISIBLE); } @Override public void onPanelAnchored(View panel) { } @Override public void onPanelHidden(View panel) { } }); recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (dy < 0) { //当用户向上滑时,隐藏SlidingUpPanelLayout slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED); } else {//当用户向上滑时,显示SlidingUpPanelLayout slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.HIDDEN); } } }); /** * 刷新控件监听 */ commentSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { getSongCommentById(songs.getId()); } }); // 添加来电监听事件 TelephonyManager telManager = (TelephonyManager) getSystemService( Context.TELEPHONY_SERVICE); // 获取系统服务 telManager.listen(new MobliePhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE); } public void onResume() { Log.v(TAG, "OnResume register Progress Receiver"); super.onResume(); registerReceiver(); if (musicBinder != null) { if (musicBinder.isPlaying()) { playImage.setImageResource(R.drawable.ic_pause_black_large); } else { playImage.setImageResource(R.drawable.ic_play_black_round); } musicBinder.notifyActivity(); } } public void onPause() { Log.v(TAG, "OnPause unregister Progress Receiver"); super.onPause(); unregisterReceiver(progressReceiver); } public void onStop() { Log.v(TAG, "OnStop"); super.onStop(); } public void onDestroy() { Log.v(TAG, "OnDestroy"); super.onDestroy(); if (musicBinder != null) { unbindService(serviceConnection); } } public void getData() { recyclerView = (RecyclerView) this.findViewById(R.id.recyclerView); commentSwipe = (SwipeRefreshLayout) this.findViewById(R.id.comment_swipe); songImage = (ImageView) findViewById(R.id.song_image); songLargeImage = (ImageView) findViewById(R.id.song_image_large); songTitle = (TextView) findViewById(R.id.song_title); songArtist = (TextView) findViewById(R.id.song_artist); playImage = (ImageView) findViewById(R.id.play); repeatImage = (ImageView) findViewById(R.id.repeat); playBtnImage = (ImageView) findViewById(R.id.play_btn); fwdImage = (ImageView) findViewById(R.id.fwd); shuffleImage = (ImageView) findViewById(R.id.shuffle); tvTimeElapsed = (TextView) findViewById(R.id.current_position); tvDuration = (TextView) findViewById(R.id.current_max); songSeekBar = (SeekBar) findViewById(R.id.seekBar); songSeekBar.setOnSeekBarChangeListener(new SongSeekBarListener()); //绑定点击事件 ViewOnClickListener viewOnClickListener = new ViewOnClickListener(); playImage.setOnClickListener(viewOnClickListener); playBtnImage.setOnClickListener(viewOnClickListener); commentSwipe.post(new Runnable() { @Override public void run() { commentSwipe.setRefreshing(true); } }); /** * 给RecyclerView线性布局 */ recyclerView.setLayoutManager(new LinearLayoutManager(CommentActivity.this)); Intent intent = getIntent(); songs = intent.getParcelableExtra("Songs"); Picasso.with(CommentActivity.this).load(songs.getUrlPic()).into(songImage); Picasso.with(CommentActivity.this).load(songs.getUrlPic()).into(songLargeImage); songTitle.setText(songs.getTitle()); songArtist.setText(songs.getArtist()); //根据歌曲Id获取歌曲评论信息 getSongCommentById(songs.getId()); getSongPlayUrlBysId(songs.getsId()); } private void play(final String url) { if (musicBinder.isPlaying()) { musicBinder.stopPlay(); playImage.setImageResource(R.drawable.ic_play_black_round); playBtnImage.setImageResource(R.drawable.ic_fab_play_btn_normal); } else { musicBinder.startPlay(url, currentPosition); playImage.setImageResource(R.drawable.ic_pause_black_large); playBtnImage.setImageResource(R.drawable.ic_fab_pause_btn_normal); } } /** * 电话监听类 */ private boolean phoneState = false; //电话状态 private class MobliePhoneStateListener extends PhoneStateListener { @Override public void onCallStateChanged(int state, String incomingNumber) { switch (state) { case TelephonyManager.CALL_STATE_IDLE: // 挂机状态 if(phoneState){ play(playUrl); } break; case TelephonyManager.CALL_STATE_OFFHOOK: //通话状态 case TelephonyManager.CALL_STATE_RINGING: //响铃状态 if(musicBinder.isPlaying()){ //判断歌曲是否在播放 musicBinder.stopPlay(); phoneState = true; } break; default: break; } } } /** * 点击监听器 */ class ViewOnClickListener implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.play: play(playUrl); break; case R.id.play_btn: play(playUrl); break; } } } /** * 进度条监听器 */ private class SongSeekBarListener implements SeekBar.OnSeekBarChangeListener { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { musicBinder.changProgress(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } } /** * 根据歌曲Id获取该歌曲评论 * * @param id */ public void getSongCommentById(int id) { final GsonRequest<List<Comments>> request = TingAPI.getCommentsRequest(id); final Response.Listener<List<Comments>> response = new Response.Listener<List<Comments>>() { @Override public void onResponse(List<Comments> comments) { recyclerView.setAdapter(new CommentAdapter(CommentActivity.this, comments, songs)); commentSwipe.setRefreshing(false); } }; request.setSuccessListener(response); RequestManager.addRequest(request, id); } /** * 根据歌曲播放Id获取歌曲播放地址url * * @param sId * @return */ public void getSongPlayUrlBysId(long sId) { final GsonRequest<OnLineSongs> request = TingAPI.getOnLineSongsRequest(sId); final Response.Listener<OnLineSongs> response = new Response.Listener<OnLineSongs>() { @Override public void onResponse(OnLineSongs onLineSongs) { playUrl = onLineSongs.getSongurl(); } }; request.setSuccessListener(response); RequestManager.addRequest(request, sId); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.song_menu, menu); MenuItem item = menu.findItem(R.id.action_share); shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.action_share: /** * 分享 */ Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, songs.getTitle() + " by " + songs.getArtist() + "\n" + songs.getContent() + " 分享来自 http://tinger.herokuapp.com/ "); shareIntent.setType("text/plain"); startActivity(shareIntent); break; case R.id.action_download: final FileInfo file = new FileInfo(0, playUrl,songs.getArtist() + " - " + songs.getTitle()+".MP3", 0, 0); Intent intent = new Intent(CommentActivity.this, DownloadService.class); intent.setAction(DownloadService.ACTION_START); intent.putExtra("fileInfo", file); startService(intent); DownLoadFragment.isDownLoad = true; Toast.makeText(CommentActivity.this,"加入下载队列",Toast.LENGTH_SHORT).show(); break; } return true; } /** * 注册广播 */ private void registerReceiver() { progressReceiver = new ProgressReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(MusicService.ACTION_UPDATE_PROGRESS); intentFilter.addAction(MusicService.ACTION_UPDATE_DURATION); intentFilter.addAction(MusicService.ACTION_UPDATE_CURRENT_MUSIC); registerReceiver(progressReceiver, intentFilter); } /** * 接收广播类 */ public class ProgressReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (MusicService.ACTION_UPDATE_PROGRESS.equals(action)) { int progress = intent.getIntExtra(MusicService.ACTION_UPDATE_PROGRESS, 0); if (progress > 0) { currentPosition = progress; Log.i(TAG,progress+""); songSeekBar.setProgress(progress / 1000); tvTimeElapsed.setText(MediaUtils.formatDuration(progress)); } } else if (MusicService.ACTION_UPDATE_DURATION.equals(action)) { currentMax = intent.getIntExtra(MusicService.ACTION_UPDATE_DURATION, 0); int max = currentMax / 1000; songSeekBar.setMax(max); tvDuration.setText(MediaUtils.formatDuration(currentMax)); } } } }<file_sep>/app/src/main/java/com/music/ting/model/DrawerListBean.java package com.music.ting.model; /** * Created by Jun on 2015/5/16. */ public class DrawerListBean { private String title; private int titleImageId; public DrawerListBean(String title, int titleImageId){ this.title = title; this.titleImageId = titleImageId; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public void setTitleImageId(int titleImageId){ this.titleImageId = titleImageId; } public int getTitleImageId(){ return titleImageId; } } <file_sep>/app/src/main/java/com/music/ting/model/user/UserShareSongs.java package com.music.ting.model.user; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by Jun on 2015/6/27. */ public class UserShareSongs { private User user; private List<Songs> songs; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public List<Songs> getSongs() { return songs; } public void setSongs(List<Songs> songs) { this.songs = songs; } public class User{ private int id; private Avatar avatar; private String name; private String email; private String bio; public int getId() { return id; } public void setId(int id) { this.id = id; } public Avatar getAvatar() { return avatar; } public void setAvatar(Avatar avatar) { this.avatar = avatar; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBio() { return bio; } public void setBio(String bio) { this.bio = bio; } } public static class Songs implements Parcelable { @SerializedName("user_id") private int userId; private int id; @SerializedName("s_id") private int sId; private String title; private String artist; @SerializedName("pic") private String urlPic; private String content; @SerializedName("comments_count") private int commentsCount; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getsId() { return sId; } public void setsId(int sId) { this.sId = sId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getArtist() { return artist; } public void setArtist(String artist) { this.artist = artist; } public String getUrlPic() { return urlPic; } public void setUrlPic(String urlPic) { this.urlPic = urlPic; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getCommentsCount() { return commentsCount; } public void setCommentsCount(int commentsCount) { this.commentsCount = commentsCount; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.userId); dest.writeInt(this.id); dest.writeInt(this.sId); dest.writeString(this.title); dest.writeString(this.artist); dest.writeString(this.urlPic); dest.writeString(this.content); dest.writeInt(this.commentsCount); } public Songs() { } private Songs(Parcel in) { this.userId = in.readInt(); this.id = in.readInt(); this.sId = in.readInt(); this.title = in.readString(); this.artist = in.readString(); this.urlPic = in.readString(); this.content = in.readString(); this.commentsCount = in.readInt(); } public static final Parcelable.Creator<Songs> CREATOR = new Parcelable.Creator<Songs>() { public Songs createFromParcel(Parcel source) { return new Songs(source); } public Songs[] newArray(int size) { return new Songs[size]; } }; } public class Avatar { /** * small : {"url":"http://7tsy2n.com1.z0.glb.clouddn.com/uploads%2Fuser%2Favatar%2F4%2Fsmall_1623782_586424324782930_323912970_n.png"} * large : {"url":"http://7tsy2n.com1.z0.glb.clouddn.com/uploads%2Fuser%2Favatar%2F4%2Flarge_1623782_586424324782930_323912970_n.png"} * thumb : {"url":"http://7tsy2n.com1.z0.glb.clouddn.com/uploads%2Fuser%2Favatar%2F4%2Fthumb_1623782_586424324782930_323912970_n.png"} * url : http://7tsy2n.com1.z0.glb.clouddn.com/uploads%2Fuser%2Favatar%2F4%2F1623782_586424324782930_323912970_n.png */ private SmallUrl small; private LargeUrl large; private ThumbUrl thumb; private String url; public void setSmall(SmallUrl small) { this.small = small; } public void setLarge(LargeUrl large) { this.large = large; } public void setThumb(ThumbUrl thumb) { this.thumb = thumb; } public void setUrl(String url) { this.url = url; } public SmallUrl getSmall() { return small; } public LargeUrl getLarge() { return large; } public ThumbUrl getThumb() { return thumb; } public String getUrl() { return url; } public class SmallUrl { /** * url : http://7tsy2n.com1.z0.glb.clouddn.com/uploads%2Fuser%2Favatar%2F4%2Fsmall_1623782_586424324782930_323912970_n.png */ private String url; public void setUrl(String url) { this.url = url; } public String getUrl() { return url; } } public class LargeUrl { /** * url : http://7tsy2n.com1.z0.glb.clouddn.com/uploads%2Fuser%2Favatar%2F4%2Flarge_1623782_586424324782930_323912970_n.png */ private String url; public void setUrl(String url) { this.url = url; } public String getUrl() { return url; } } public class ThumbUrl { /** * url : http://7tsy2n.com1.z0.glb.clouddn.com/uploads%2Fuser%2Favatar%2F4%2Fthumb_1623782_586424324782930_323912970_n.png */ private String url; public void setUrl(String url) { this.url = url; } public String getUrl() { return url; } } } } <file_sep>/app/src/main/java/com/music/ting/ui/fragment/SongsListFragment.java package com.music.ting.ui.fragment; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.android.volley.Response; import com.music.ting.R; import com.music.ting.adapter.SongsListAdapter; import com.music.ting.data.GsonRequest; import com.music.ting.data.RequestManager; import com.music.ting.model.Songs; import com.music.ting.ui.activity.CommentActivity; import com.music.ting.utils.TingAPI; import java.util.ArrayList; import java.util.List; /** * Created by Jun on 2015/5/13. */ public class SongsListFragment extends Fragment { private ListView songListView; private SwipeRefreshLayout songSwipe; private View view; private List<Songs> songsList = new ArrayList<Songs>(); @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_songs_list,container,false); songListView = (ListView) view.findViewById(R.id.songs_list); songSwipe = (SwipeRefreshLayout) view.findViewById(R.id.song_swipe); //给刷新控件一个颜色 songSwipe.setColorSchemeColors(R.color.colorPrimary, R.color.colorPrimary, R.color.colorPrimary,R.color.colorPrimary); //刚进入到界面设置刷新控件正在刷新 songSwipe.post(new Runnable() { @Override public void run() { songSwipe.setRefreshing(true); } }); //加载数据 initData(20); /** * 刷新控件监听事件 */ songSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { initData(20); } }); songListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(view.getContext(), CommentActivity.class); intent.putExtra("Songs",songsList.get(position)); startActivity(intent); } }); return view; } /** * 初始化数据 */ public void initData(final int songCount){ final GsonRequest<List<Songs>> request = TingAPI.getSongsRequest(songCount); final Response.Listener<List<Songs>> response = new Response.Listener<List<Songs>>() { @Override public void onResponse(List<Songs> songs) { songsList = songs; songListView.setAdapter(new SongsListAdapter(view.getContext(), R.layout.item_songs_list,songsList)); songSwipe.setRefreshing(false); } }; request.setSuccessListener(response); RequestManager.addRequest(request, null); } } <file_sep>/app/src/main/java/com/music/ting/adapter/CommentAdapter.java package com.music.ting.adapter; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.view.animation.OvershootInterpolator; import android.widget.ImageView; import android.widget.TextView; import com.android.volley.Response; import com.music.ting.R; import com.music.ting.data.GsonRequest; import com.music.ting.data.RequestManager; import com.music.ting.model.Comments; import com.music.ting.model.Songs; import com.music.ting.model.user.UserInfo; import com.music.ting.ui.activity.UserProfileActivity; import com.music.ting.ui.widget.RoundImageView; import com.music.ting.utils.TingAPI; import com.squareup.picasso.Picasso; import java.util.HashMap; import java.util.List; /** * Created by Jun on 2015/5/20. */ public class CommentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private final int SONG = 0; private final int SLOGAN = 1; private final int COMMENT = 2; private List<Comments> commentsList; private HashMap hashMap = new HashMap();//用来存储评论用户信息 private Songs songs; private Context mContext; private boolean isLike = false; private UserInfo mUserInfo; public CommentAdapter(Context mContext, List<Comments> commentsList, Songs songs){ this.mContext = mContext; this.commentsList = commentsList; this.songs = songs; } /** * 获取当前Item(View)是哪种布局类型 * @param position * @return 布局类型 */ @Override public int getItemViewType(int position) { switch (position){ case 0: return SONG; case 1: return SLOGAN; default: return COMMENT; } } /** * 创建不同 Item 的ViewHolder * @param parent * @param viewType View类型 * @return */ @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View song_view = LayoutInflater.from(mContext). inflate(R.layout.item_header_song,parent,false); View slogan_view = LayoutInflater.from(mContext). inflate(R.layout.item_slogan,parent,false); View comment_view = LayoutInflater.from(mContext). inflate(R.layout.item_song_comments,parent,false); View not_comment_view = LayoutInflater.from(mContext). inflate(R.layout.item_not_comment,parent,false); switch (viewType){ case SONG: return new SongViewHolder(song_view); case SLOGAN: return new SloganViewHolder(slogan_view); case COMMENT: if(commentsList.size() == 0){ return new NotCommentViewHolder(not_comment_view); }else{ return new CommentViewHolder(comment_view); } default: return new SongViewHolder(song_view); } } /** * 为不同 Item 的 ViewHolder 绑定数据 * @param viewHolder * @param position */ @Override public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) { if(viewHolder instanceof SongViewHolder){ //为SongViewHolder里面属性绑定值 ((SongViewHolder) viewHolder).songTitle.setText(songs.getTitle()); ((SongViewHolder) viewHolder).songArtist.setText(songs.getArtist()); ((SongViewHolder) viewHolder).songContent.setText(songs.getContent()); Picasso.with(mContext) .load(songs.getUrlPic()) .placeholder(R.drawable.ic_default_pic) .error(R.drawable.ic_default_pic) .resize(50,50) .centerCrop() .into(((SongViewHolder) viewHolder).songPic); /** * 根据用户Id获取用户头像 */ final GsonRequest<UserInfo> request = TingAPI.getUserInfoRequestById(songs.getUserId()); final Response.Listener<UserInfo> response = new Response.Listener<UserInfo>() { @Override public void onResponse(UserInfo userInfo) { mUserInfo = userInfo; Picasso.with(mContext) .load(userInfo.getUser().getAvatar().geturl()) .placeholder(R.drawable.ic_default_pic) .error(R.drawable.ic_default_pic) .resize(50,50) .centerCrop() .into(((SongViewHolder) viewHolder).songShareUserPic); } }; request.setSuccessListener(response); RequestManager.addRequest(request, songs.getUserId()); ((SongViewHolder) viewHolder).songLike.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isLike) { likeAnimator(((SongViewHolder) viewHolder).songLike, R.drawable.ic_like); isLike = false; } else { likeAnimator(((SongViewHolder) viewHolder).songLike, R.drawable.ic_like_selector); isLike = true; } } }); ((SongViewHolder) viewHolder).songShareUserPic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, UserProfileActivity.class); intent.putExtra("UserInfo", mUserInfo); mContext.startActivity(intent); } }); }else if(viewHolder instanceof SloganViewHolder){ //为标识View绑定值 ((SloganViewHolder) viewHolder).slogan.setText("评论"); }else if(viewHolder instanceof CommentViewHolder){ //为评论View绑定值 //获取用户Id final int userId = commentsList.get(position - 2).getUserId(); /** * 根据用户Id获取用户名和用户头像 */ final GsonRequest<UserInfo> request = TingAPI.getUserInfoRequestById(userId); final Response.Listener<UserInfo> response = new Response.Listener<UserInfo>() { @Override public void onResponse(UserInfo userInfo) { hashMap.put(position-2,userInfo); ((CommentViewHolder) viewHolder).commentUser. setText(userInfo.getUser().getName()); Picasso.with(mContext) .load(userInfo.getUser().getAvatar().geturl()) .placeholder(R.drawable.ic_default_pic) .error(R.drawable.ic_default_pic) .resize(50,50) .centerCrop() .into((((CommentViewHolder) viewHolder).commentUserPic)); } }; request.setSuccessListener(response); RequestManager.addRequest(request, userId); ((CommentViewHolder) viewHolder).commentContent. setText(commentsList.get(position - 2).getContent()); ((CommentViewHolder) viewHolder).commentUserPic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, UserProfileActivity.class); intent.putExtra("UserInfo", (UserInfo)hashMap.get(position-2)); mContext.startActivity(intent); } }); }else if(viewHolder instanceof NotCommentViewHolder){ ((NotCommentViewHolder) viewHolder).notComment.setText("没有人评论"); } } /** * 判断有几个View * @return */ @Override public int getItemCount() { return commentsList.size() == 0 ? 3 :commentsList.size() + 2; } /** * 歌曲信息 Song Viewolder类 */ public static class SongViewHolder extends RecyclerView.ViewHolder{ TextView songTitle; TextView songArtist; TextView songContent; ImageView songPic; RoundImageView songShareUserPic; ImageView songLike; public SongViewHolder(View itemView) { super(itemView); songTitle = (TextView) itemView.findViewById(R.id.song_title); songArtist = (TextView) itemView.findViewById(R.id.song_artist); songContent = (TextView) itemView.findViewById(R.id.song_content); songPic = (ImageView) itemView.findViewById(R.id.song_image); songShareUserPic = (RoundImageView) itemView.findViewById(R.id.share_user); songLike = (ImageView) itemView.findViewById(R.id.like); } } /** * Comment 评论 ViewHolder类 */ public static class CommentViewHolder extends RecyclerView.ViewHolder { TextView commentUser; TextView commentContent; RoundImageView commentUserPic; public CommentViewHolder(View itemView) { super(itemView); commentUser = (TextView) itemView.findViewById(R.id.comment_user_name); commentContent = (TextView) itemView.findViewById(R.id.comment_content); commentUserPic = (RoundImageView) itemView.findViewById(R.id.comment_user_pic); } } /** * Slogan 标识ViewHolder类 */ public static class SloganViewHolder extends RecyclerView.ViewHolder { TextView slogan; public SloganViewHolder(View itemView) { super(itemView); slogan = (TextView) itemView.findViewById(R.id.slogan); } } /** * 没有评论 Viewholder类 */ public static class NotCommentViewHolder extends RecyclerView.ViewHolder { TextView notComment; public NotCommentViewHolder(View itemView) { super(itemView); notComment = (TextView) itemView.findViewById(R.id.not_comment); } } /** * 动画 * @param imageView * @param resourceId */ private void likeAnimator(final ImageView imageView, final int resourceId) { AnimatorSet animatorSet = new AnimatorSet(); ObjectAnimator rotationAnim = ObjectAnimator.ofFloat(imageView, "rotation", 0f, 360f); rotationAnim.setDuration(300); rotationAnim.setInterpolator(new AccelerateInterpolator()); ObjectAnimator bounceAnimX = ObjectAnimator.ofFloat(imageView, "scaleX", 0.2f, 1f); bounceAnimX.setDuration(300); bounceAnimX.setInterpolator(new OvershootInterpolator()); bounceAnimX.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { imageView.setImageResource(resourceId); } }); ObjectAnimator bounceAnimY = ObjectAnimator.ofFloat(imageView, "scaleY", 0.2f, 1f); bounceAnimY.setDuration(300); bounceAnimY.setInterpolator(new OvershootInterpolator()); bounceAnimY.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { imageView.setImageResource(resourceId); } }); animatorSet.play(rotationAnim); animatorSet.play(bounceAnimX).with(bounceAnimY).after(rotationAnim); animatorSet.start(); } }
30027b69ba7ef8b225f8d1e28d4c7c0508de2dc5
[ "Markdown", "Java", "Gradle" ]
10
Markdown
zhangyn723777/ting
ad46542f433508eed46fb673a056bbb140854a1e
60b171ac1685156ea41e322031887b57a5fa13ba
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> void zarAt(){ printf(" Random zar atma uygulamsina hosgeldiniz\n"); printf(" -------------------------------------------\n"); printf(" Zarlari atmak icin herhangi bir tusa basin\n\n"); getch(); int sayac=0; int zar; srand(time(NULL)); for(;sayac<3;sayac++){ if(sayac == 0){ printf(" zarlar sirasiyla "); } if(sayac == 1){ zar = (rand() % 7); printf("%d ve ",zar); } if(sayac == 2){ zar = (rand() % 7); printf("%d dir." ,zar); } } getch(" cikmak icin herhangi bir tusa basin"); } void lisans(){ printf("\n\n -----------------------\n"); printf(" MADE BY <NAME>\n"); printf(" -----------------------"); getch(); } int main(){ zarAt(); lisans(); return 0; }
ccfb47a03285dd342ddf127d39113bdcb6a27fae
[ "C" ]
1
C
beginnerstuff/random-roll-dice-with-c
6ee9a27b4496a17d265d8f23a156894767868143
cca47557f1d0294738a118e091166b558ede584c
refs/heads/master
<repo_name>iriusrisk/GoCD-EC2-Elastic-Agent-Plugin<file_sep>/src/main/java/com/continuumsecurity/elasticagent/ec2/executors/PluginStatusReportExecutor.java /* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.executors; import com.continuumsecurity.elasticagent.ec2.AgentInstances; import com.continuumsecurity.elasticagent.ec2.ClusterProfileProperties; import com.continuumsecurity.elasticagent.ec2.Ec2AgentInstances; import com.continuumsecurity.elasticagent.ec2.RequestExecutor; import com.continuumsecurity.elasticagent.ec2.models.StatusReport; import com.continuumsecurity.elasticagent.ec2.requests.PluginStatusReportRequest; import com.continuumsecurity.elasticagent.ec2.views.ViewBuilder; import com.google.gson.JsonObject; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; // Make changes as needed public class PluginStatusReportExecutor implements RequestExecutor { private final PluginStatusReportRequest request; private final Map<String, Ec2AgentInstances> allClusterInstances; private final ViewBuilder viewBuilder; private static final Logger LOG = Logger.getLoggerFor(AgentStatusReportExecutor.class); public PluginStatusReportExecutor(PluginStatusReportRequest request, Map<String, Ec2AgentInstances> allClusterInstances, ViewBuilder viewBuilder) { this.request = request; this.allClusterInstances = allClusterInstances; this.viewBuilder = viewBuilder; } @Override public GoPluginApiResponse execute() throws Exception { LOG.info("[status-report] Generating status report"); List<String> reports = new ArrayList<>(); for (ClusterProfileProperties profile : request.allClusterProfileProperties()) { AgentInstances agentInstances = allClusterInstances.get(profile.uuid()); StatusReport statusReport = agentInstances.getStatusReport(profile); reports.add(viewBuilder.build(viewBuilder.getTemplate("status-report.template.ftlh"), statusReport)); } // aggregate reports for different cluster into one JsonObject responseJSON = new JsonObject(); responseJSON.addProperty("view", reports.stream().collect(Collectors.joining("<hr/>"))); return DefaultGoPluginApiResponse.success(responseJSON.toString()); } } <file_sep>/src/main/java/com/continuumsecurity/elasticagent/ec2/requests/ServerPingRequest.java /* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.requests; import com.continuumsecurity.elasticagent.ec2.ClusterProfileProperties; import com.continuumsecurity.elasticagent.ec2.Ec2AgentInstances; import com.continuumsecurity.elasticagent.ec2.PluginRequest; import com.continuumsecurity.elasticagent.ec2.RequestExecutor; import com.continuumsecurity.elasticagent.ec2.executors.ServerPingRequestExecutor; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import static com.continuumsecurity.elasticagent.ec2.Ec2Plugin.GSON; public class ServerPingRequest { private List<ClusterProfileProperties> allClusterProfileProperties; public ServerPingRequest() { } public ServerPingRequest(List<Map<String, String>> allClusterProfileProperties) { this.allClusterProfileProperties = allClusterProfileProperties.stream() .map(ClusterProfileProperties::fromConfiguration) .collect(Collectors.toList()); } public static ServerPingRequest fromJSON(String json) { return GSON.fromJson(json, ServerPingRequest.class); } public List<ClusterProfileProperties> allClusterProfileProperties() { return allClusterProfileProperties; } @Override public String toString() { return "ServerPingRequest{" + "allClusterProfileProperties=" + allClusterProfileProperties + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ServerPingRequest that = (ServerPingRequest) o; return Objects.equals(allClusterProfileProperties, that.allClusterProfileProperties); } @Override public int hashCode() { return Objects.hash(allClusterProfileProperties); } public RequestExecutor executor(Map<String, Ec2AgentInstances> clusterSpecificAgentInstances, PluginRequest pluginRequest) { return new ServerPingRequestExecutor(this, clusterSpecificAgentInstances, pluginRequest); } } <file_sep>/src/main/java/com/continuumsecurity/elasticagent/ec2/ClusterProfile.java /* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.continuumsecurity.elasticagent.ec2; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.HashMap; import java.util.Objects; import static com.continuumsecurity.elasticagent.ec2.Ec2Plugin.GSON; public class ClusterProfile { @Expose @SerializedName("id") private String id; @Expose @SerializedName("plugin_id") private String pluginId; @Expose @SerializedName("properties") private ClusterProfileProperties clusterProfileProperties; public ClusterProfile() { } public ClusterProfile(String id, String pluginId, PluginSettings pluginSettings) { this.id = id; this.pluginId = pluginId; setClusterProfileProperties(pluginSettings); } public static ClusterProfile fromJSON(String json) { return GSON.fromJson(json, ClusterProfile.class); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClusterProfile that = (ClusterProfile) o; return Objects.equals(id, that.id) && Objects.equals(pluginId, that.pluginId) && Objects.equals(clusterProfileProperties, that.clusterProfileProperties); } @Override public int hashCode() { return Objects.hash(id, pluginId, clusterProfileProperties); } @Override public String toString() { return "ClusterProfile{" + "id='" + id + '\'' + ", pluginId='" + pluginId + '\'' + ", clusterProfileProperties=" + clusterProfileProperties + '}'; } public String getId() { return id; } public String getPluginId() { return pluginId; } public ClusterProfileProperties getClusterProfileProperties() { return clusterProfileProperties; } public void setId(String id) { this.id = id; } public void setPluginId(String pluginId) { this.pluginId = pluginId; } public void setClusterProfileProperties(ClusterProfileProperties clusterProfileProperties) { this.clusterProfileProperties = clusterProfileProperties; } public void setClusterProfileProperties(PluginSettings pluginSettings) { this.clusterProfileProperties = ClusterProfileProperties.fromConfiguration(GSON.fromJson(GSON.toJson(pluginSettings), HashMap.class)); } } <file_sep>/src/test/java/com/continuumsecurity/elasticagent/ec2/executors/GoServerURLFieldTest.java /* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.executors; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; public class GoServerURLFieldTest { private final GoServerURLField goServerURLField = new GoServerURLField("0"); @Test public void shouldCheckBlankInput() { String result = goServerURLField.doValidate(""); assertThat(result, is("Go Server URL must not be blank.")); } @Test public void shouldCheckIfStringIsValidUrl() { String result = goServerURLField.doValidate("foobar"); assertThat(result, is("Go Server URL must be a valid URL (https://example.com:8154/go)")); } @Test public void shouldCheckIfSchemeIsValid() { String result = goServerURLField.doValidate("example.com"); assertThat(result, is("Go Server URL must be a valid URL (https://example.com:8154/go)")); } @Test public void shouldCheckIfSchemeIsHTTPS() { String result = goServerURLField.doValidate("http://example.com"); assertThat(result, is("Go Server URL must be a valid HTTPs URL (https://example.com:8154/go)")); } @Test public void shouldCheckForLocalhost() { String result = goServerURLField.doValidate("https://localhost:8154/go"); assertThat(result, is("Go Server URL must not be localhost, since this gets resolved on the agents")); result = goServerURLField.doValidate("https://127.0.0.1:8154/go"); assertThat(result, is("Go Server URL must not be localhost, since this gets resolved on the agents")); } @Test public void shouldCheckIfUrlEndsWithContextGo() { String result = goServerURLField.doValidate("https://example.com:8154/"); assertThat(result, is("Go Server URL must be a valid URL ending with '/go' (https://example.com:8154/go)")); result = goServerURLField.doValidate("https://example.com:8154/crimemastergogo"); assertThat(result, is("Go Server URL must be a valid URL ending with '/go' (https://example.com:8154/go)")); } @Test public void shouldReturnNullForValidUrls() { String result = goServerURLField.doValidate("https://example.com:8154/go"); assertThat(result, is(nullValue())); result = goServerURLField.doValidate("https://example.com:8154/go/"); assertThat(result, is(nullValue())); result = goServerURLField.doValidate("https://example.com:8154/foo/go/"); assertThat(result, is(nullValue())); } } <file_sep>/src/main/java/com/continuumsecurity/elasticagent/ec2/PluginSettings.java /* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import org.joda.time.Period; import software.amazon.awssdk.regions.Region; import static org.apache.commons.lang3.StringUtils.isBlank; public class PluginSettings { public static final Gson GSON = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .excludeFieldsWithoutExposeAnnotation() .create(); @Expose @SerializedName("go_server_url") private String goServerUrl; @Expose @SerializedName("auto_register_timeout") private String autoRegisterTimeout; @Expose @SerializedName("max_elastic_agents") private String maxElasticAgents; @Expose @SerializedName("aws_access_key_id") private String awsAccessKeyId; @Expose @SerializedName("aws_secret_access_key") private String awsSecretAccessKey; @Expose @SerializedName("aws_region") private String awsRegion; private Period autoRegisterPeriod; public static PluginSettings fromJSON(String json) { return GSON.fromJson(json, PluginSettings.class); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PluginSettings that = (PluginSettings) o; if (goServerUrl != null ? !goServerUrl.equals(that.goServerUrl) : that.goServerUrl != null) return false; if (autoRegisterTimeout != null ? !autoRegisterTimeout.equals(that.autoRegisterTimeout) : that.autoRegisterTimeout != null) return false; if (maxElasticAgents != null ? !maxElasticAgents.equals(that.maxElasticAgents) : that.maxElasticAgents != null) return false; if (awsAccessKeyId != null ? !awsAccessKeyId.equals(that.awsAccessKeyId) : that.awsAccessKeyId != null) return false; if (awsSecretAccessKey != null ? !awsSecretAccessKey.equals(that.awsSecretAccessKey) : that.awsSecretAccessKey != null) return false; if (awsRegion != null ? !awsRegion.equals(that.awsRegion) : that.awsRegion != null) return false; return autoRegisterPeriod != null ? autoRegisterPeriod.equals(that.autoRegisterPeriod) : that.autoRegisterPeriod == null; } @Override public int hashCode() { int result = goServerUrl != null ? goServerUrl.hashCode() : 0; result = 31 * result + (autoRegisterTimeout != null ? autoRegisterTimeout.hashCode() : 0); result = 31 * result + (maxElasticAgents != null ? maxElasticAgents.hashCode() : 0); result = 31 * result + (awsAccessKeyId != null ? awsAccessKeyId.hashCode() : 0); result = 31 * result + (awsSecretAccessKey != null ? awsSecretAccessKey.hashCode() : 0); result = 31 * result + (awsRegion != null ? awsRegion.hashCode() : 0); return result; } @Override public String toString() { String pluginSettingsString = "PluginSettings{" + "goServerUrl='" + goServerUrl + '\'' + ", autoRegisterTimeout='" + autoRegisterTimeout + '\'' + ", maxElasticAgents='" + maxElasticAgents + '\''; if (awsAccessKeyId != null && !awsAccessKeyId.isEmpty()) pluginSettingsString += ", awsAccessKeyId='" + awsAccessKeyId + '\''; if (awsSecretAccessKey != null && !awsSecretAccessKey.isEmpty()) pluginSettingsString += ", awsSecretAccessKey='" + awsSecretAccessKey + '\''; pluginSettingsString += ", awsRegion='" + awsRegion + '\'' + ", autoRegisterPeriod=" + autoRegisterPeriod + '}'; return pluginSettingsString; } public Period getAutoRegisterPeriod() { if (this.autoRegisterPeriod == null) { this.autoRegisterPeriod = new Period().withMinutes(Integer.parseInt(getAutoRegisterTimeout())); } return this.autoRegisterPeriod; } public String getAutoRegisterTimeout() { if (autoRegisterTimeout == null) { autoRegisterTimeout = "10"; } return autoRegisterTimeout; } public String getGoServerUrl() { return goServerUrl; } public Integer getMaxElasticAgents() { return Integer.valueOf(maxElasticAgents); } public String getAwsAccessKeyId() { return awsAccessKeyId; } public String getAwsSecretAccessKey() { return awsSecretAccessKey; } public Region getAwsRegion() throws IllegalArgumentException { return region(awsRegion); } private static Region region(String configuredRegion) { if (isBlank(configuredRegion)) { throw new IllegalArgumentException("Must provide `ec2_region` attribute."); } Region newRegion = Region.of(configuredRegion); if (!Region.regions().contains(newRegion)) { throw new IllegalArgumentException("Region does not exist."); } return newRegion; } public void setGoServerUrl(String goServerUrl) { this.goServerUrl = goServerUrl; } public void setAutoRegisterTimeout(String autoRegisterTimeout) { this.autoRegisterTimeout = autoRegisterTimeout; } public void setMaxElasticAgents(String maxElasticAgents) { this.maxElasticAgents = maxElasticAgents; } public void setAwsAccessKeyId(String awsAccessKeyId) { this.awsAccessKeyId = awsAccessKeyId; } public void setAwsSecretAccessKey(String awsSecretAccessKey) { this.awsSecretAccessKey = awsSecretAccessKey; } public void setAwsRegion(String awsRegion) { this.awsRegion = awsRegion; } } <file_sep>/src/test/java/com/continuumsecurity/elasticagent/ec2/executors/ClusterProfileValidateRequestExecutorTest.java /* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.executors; import com.continuumsecurity.elasticagent.ec2.requests.ClusterProfileValidateRequest; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; import java.util.Collections; public class ClusterProfileValidateRequestExecutorTest { @Test public void shouldBarfWhenUnknownKeysArePassed() throws Exception { ClusterProfileValidateRequestExecutor executor = new ClusterProfileValidateRequestExecutor(new ClusterProfileValidateRequest(Collections.singletonMap("foo", "bar"))); String json = executor.execute().responseBody(); String expectedStr = "[" + "{\"message\":\"Go Server URL must not be blank.\",\"key\":\"go_server_url\"}," + "{\"message\":\"auto_register_timeout must be a positive integer.\",\"key\":\"auto_register_timeout\"}," + "{\"message\":\"max_elastic_agents must be a positive integer.\",\"key\":\"max_elastic_agents\"}," + "{\"message\":\"aws_region must not be blank.\",\"key\":\"aws_region\"}," + "{\"key\":\"foo\",\"message\":\"Is an unknown property\"}" + "]"; JSONAssert.assertEquals(expectedStr, json, JSONCompareMode.NON_EXTENSIBLE); } @Test public void shouldValidateMandatoryKeys() throws Exception { ClusterProfileValidateRequestExecutor executor = new ClusterProfileValidateRequestExecutor(new ClusterProfileValidateRequest(Collections.<String, String>emptyMap())); String json = executor.execute().responseBody(); String expectedStr = "[" + "{\"message\":\"Go Server URL must not be blank.\",\"key\":\"go_server_url\"}," + "{\"message\":\"auto_register_timeout must be a positive integer.\",\"key\":\"auto_register_timeout\"}," + "{\"message\":\"max_elastic_agents must be a positive integer.\",\"key\":\"max_elastic_agents\"}," + "{\"message\":\"aws_region must not be blank.\",\"key\":\"aws_region\"}" + "]\n"; JSONAssert.assertEquals(expectedStr, json, JSONCompareMode.NON_EXTENSIBLE); } } <file_sep>/src/test/java/com/continuumsecurity/elasticagent/ec2/executors/ClusterStatusReportExecutorTest.java /* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.executors; import com.continuumsecurity.elasticagent.ec2.ClusterProfileProperties; import com.continuumsecurity.elasticagent.ec2.Ec2AgentInstances; import com.continuumsecurity.elasticagent.ec2.models.StatusReport; import com.continuumsecurity.elasticagent.ec2.requests.ClusterStatusReportRequest; import com.continuumsecurity.elasticagent.ec2.views.ViewBuilder; import com.google.gson.JsonObject; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import freemarker.template.Template; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.skyscreamer.jsonassert.JSONAssert; import java.util.ArrayList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) public class ClusterStatusReportExecutorTest { @Mock private ClusterStatusReportRequest clusterStatusReportRequest; @Mock private ClusterProfileProperties clusterProfile; @Mock private ViewBuilder viewBuilder; @Mock private Ec2AgentInstances agentInstances; @Mock private Template template; @Test public void shouldGetStatusReport() throws Exception { StatusReport statusReport = aStatusReport(); when(clusterStatusReportRequest.getClusterProfile()).thenReturn(clusterProfile); when(agentInstances.getStatusReport(clusterProfile)).thenReturn(statusReport); when(viewBuilder.getTemplate("status-report.template.ftlh")).thenReturn(template); when(viewBuilder.build(template, statusReport)).thenReturn("statusReportView"); ClusterStatusReportExecutor statusReportExecutor = new ClusterStatusReportExecutor(clusterStatusReportRequest, agentInstances, viewBuilder); GoPluginApiResponse goPluginApiResponse = statusReportExecutor.execute(); JsonObject expectedResponseBody = new JsonObject(); expectedResponseBody.addProperty("view", "statusReportView"); assertThat(goPluginApiResponse.responseCode(), is(200)); JSONAssert.assertEquals(expectedResponseBody.toString(), goPluginApiResponse.responseBody(), true); } private StatusReport aStatusReport() { return new StatusReport(1, new ArrayList<>()); } } <file_sep>/src/test/java/com/continuumsecurity/elasticagent/ec2/executors/CreateAgentRequestExecutorTest.java /* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.executors; import com.continuumsecurity.elasticagent.ec2.*; import com.continuumsecurity.elasticagent.ec2.models.JobIdentifier; import com.continuumsecurity.elasticagent.ec2.requests.CreateAgentRequest; import org.junit.jupiter.api.Test; import java.util.HashMap; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.*; public class CreateAgentRequestExecutorTest { @Test public void shouldAskDockerContainersToCreateAnAgent() throws Exception { final HashMap<String, String> elasticAgentProfileProperties = new HashMap<>(); elasticAgentProfileProperties.put("Image", "image1"); final JobIdentifier jobIdentifier = new JobIdentifier("p1", 1L, "l1", "s1", "1", "j1", 1L); CreateAgentRequest request = new CreateAgentRequest("key1", elasticAgentProfileProperties, jobIdentifier, new HashMap<>()); AgentInstances<Ec2Instance> agentInstances = mock(Ec2AgentInstances.class); PluginRequest pluginRequest = mock(PluginRequest.class); new CreateAgentRequestExecutor(request, agentInstances, pluginRequest).execute(); verify(agentInstances).create(eq(request), eq(pluginRequest), any(ConsoleLogAppender.class)); verify(pluginRequest).appendToConsoleLog(eq(jobIdentifier), contains("Received request to create an instance for")); } @Test public void shouldLogErrorMessageToConsoleIfAgentCreateFails() throws Exception { final HashMap<String, String> elasticAgentProfileProperties = new HashMap<>(); elasticAgentProfileProperties.put("Image", "image1"); final JobIdentifier jobIdentifier = new JobIdentifier("p1", 1L, "l1", "s1", "1", "j1", 1L); CreateAgentRequest request = new CreateAgentRequest("key1", elasticAgentProfileProperties, jobIdentifier, new HashMap<>()); AgentInstances<Ec2Instance> agentInstances = mock(Ec2AgentInstances.class); PluginRequest pluginRequest = mock(PluginRequest.class); when(agentInstances.create(eq(request), eq(pluginRequest), any(ConsoleLogAppender.class))).thenThrow(new RuntimeException("Ouch!")); try { new CreateAgentRequestExecutor(request, agentInstances, pluginRequest).execute(); fail("Should have thrown an exception"); } catch (RuntimeException e) { // expected } verify(pluginRequest).appendToConsoleLog(eq(jobIdentifier), contains("Received request to create an instance for")); verify(pluginRequest).appendToConsoleLog(eq(jobIdentifier), contains("Failed while creating instance: Ouch!")); } } <file_sep>/src/main/java/com/continuumsecurity/elasticagent/ec2/models/ExceptionMessage.java /* * Copyright 2018 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.models; import java.io.Closeable; import java.io.PrintWriter; import java.io.StringWriter; import static org.apache.commons.lang3.StringUtils.isBlank; public class ExceptionMessage { private final Throwable throwable; private String stacktrace; private String message; public ExceptionMessage(Throwable throwable) { this.throwable = throwable; this.stacktrace = initStacktrace(throwable); this.message = initMessage(throwable); } public String getStacktrace() { return stacktrace; } public String getMessage() { return message; } private String initMessage(Throwable throwable) { if (!isBlank(throwable.getMessage())) { return throwable.getMessage(); } if (!isBlank(this.stacktrace)) { return stacktrace.split("\n")[0]; } return null; } private String initStacktrace(Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); try { throwable.printStackTrace(pw); String stacktrace = sw.toString(); return stacktrace; } finally { closeQuietly(sw); closeQuietly(pw); } } private void closeQuietly(Closeable closeable) { try { closeable.close(); } catch (Exception e) { //Ignore } } } <file_sep>/README.md # GoCD Elastic agent plugin for AWS EC2 [GoCD](https://www.gocd.org) server plugin for bringing up Amazon EC2 instances as its agents on demand. Compatible with [version 5.0](https://plugin-api.gocd.org/19.3.0/elastic-agents/) of the elastic agent endpoint (GoCD server versions starting from 19.3.0). Table of Contents ================= * [Installation](#installation) * [Amazon Machine Image](#amazon-machine-image) * [IAM Instance Profile](#iam-instance-profile) * [Security Groups](#security-groups) * [Subnets](#subnets) * [AWS Authentication](#aws-authentication) * [Building the code base](#building-the-code-base) * [Credits](#credits) * [Disclaimer](#disclaimer) ## Installation Copy the file `build/libs/gocd-ec2-elastic-agent-plugin-VERSION.jar` to the GoCD server under `${GO_SERVER_DIR}/plugins/external` and restart the server. Prepare [AMI](#amazon-machine-image), [security groups](#security-groups) and [subnets](#subnets) for the agents. Tested on GoCD server & agent versions 20.6.0. ### Amazon Machine Image This is the most important step, where you will prepare a base image for the agents. Create new clean EC2 instance and install there all the tools and configurations that your agents may need. This plugin in intended to be used with Amazon Linux 2 based agents, but you can also adapt it to run with other operating systems like [Ubuntu](https://github.com/continuumsecurity/GoCD-EC2-Elastic-Agent-Plugin/issues/8#issuecomment-619739056). After that, follow up [the official guide](https://docs.gocd.org/current/installation/install/agent/linux.html) to install Go-Agent. Do not connect it to the server yet, nor enable auto startup of go-agent.service! All this will be done by the plugin itself with the help of the user data scripts. Before stopping this instance perform cleanup with the following commands: ```bash rm -rf /var/lib/cloud/* rm -rf /var/log/cloud-init* rm -rf /usr/share/go-agent/go-agent.pid rm -rf /usr/share/go-agent/config/* rm -rf /var/log/go-agent/* rm -rf /var/lib/go-agent/config/* ``` Finally, create new [Amazon Machine Image](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html) from your instance. Each Elastic Agent Profile can use different AMI to suit your needs. ### IAM Instance Profile AWS allows you to create an [IAM Instance Profile](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html) which assigns an AWS IAM role to the EC2 instance(s), which can be used to authorize the instances to invoke the AWS API. Provide the IAM Instance profile name (not the Role name, or the ARN) to launch instances with the corresponding role associated with them. There is no validation of the IAM Instance Profile and providing an invalid profile name will result in instances not being deployed. Note: in order to be able to assign instance profiles to your agents remember to assign [proper policies](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#permission-to-pass-iam-roles) to your GoCD server. ### Security Groups You will need to setup some connectivity between your GoCD server and elastic agents. You may also want to allow any other inbound/outbound traffic to the agents, like tunnels, version control systems or repositories. The most straightforward way to achieve this is with security groups. Once you have all your security groups defined, put their identifiers into the Elastic Agent Profile and they will be automatically assigned to every newly created EC2 instance. ### Subnets To be able to launch new agents you need to have at least 2 subnets in your VPC where you will put your newly created instances. You can define even more subnets (ideally in different availability zones) in the elastic agent profile and the plugin will choose randomly one of them each time it has to create new instance. If the chosen availability zone has run out of your requested instance type, the plugin will try to bring up instance in the next subnet. Also, remember to enable auto-assign public IP address to the subnets. ### AWS Authentication If an AWS Access Key ID and AWS Secret Access Key is provided for a cluster profile, then those credentials will be used. Otherwise, if left blank, the [Default Provider Credential Chain](https://docs.aws.amazon.com/sdk-for-java/v2/developer-guide/credentials.html) will be used. i.e. The default provider credentials will be resolved from the GoCD server environment (e.g. ~/.credentials file or Ec2 IAM Instance profiles from instance metadata). ## Building the code base To build the jar, run `./gradlew clean assemble` ## Credits This project is fully based on [GoCD Elastic agent plugin skeleton](https://github.com/gocd-contrib/elastic-agent-skeleton-plugin) and [GoCD Elastic agent plugin for Docker](https://github.com/gocd-contrib/docker-elastic-agents). The structure and some parts of code are taken directly from these projects. ## Disclaimer The GoCD Elastic agent plugin for AWS EC2 is supplied "AS IS", use is at your own risk. Author and contributors expressly disclaim all warranties nor support of any kind. <file_sep>/src/main/java/com/continuumsecurity/elasticagent/ec2/MemorySpecification.java package com.continuumsecurity.elasticagent.ec2; import com.google.common.collect.ImmutableSortedMap; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.apache.commons.lang3.StringUtils.isBlank; /** * Parse memory specification. Expected format is: * <ul> * <li>a float number</li> * <li>followed by a letter: M, G, T</li> * </ul> */ public class MemorySpecification { private static final Pattern PATTERN = Pattern.compile("(\\d+(\\.\\d+)?)(\\D)"); private static final Map<String, BigDecimal> SUFFIXES = ImmutableSortedMap.<String, BigDecimal>orderedBy(String.CASE_INSENSITIVE_ORDER) .put("M", BigDecimal.valueOf(1024L * 1024L)) .put("G", BigDecimal.valueOf(1024L * 1024L * 1024L)) .put("T", BigDecimal.valueOf(1024L * 1024L * 1024L * 1024L)) .build(); private List<String> errors = new ArrayList<>(); private Long memory; MemorySpecification(String memory) { this.memory = parse(memory, errors); } Long getMemory() { return memory; } public static Long parse(String memory, List<String> errors) { if (isBlank(memory)) { return null; } final Matcher matcher = PATTERN.matcher(memory); if (!matcher.matches()) { errors.add("Invalid size: " + memory); return null; } final BigDecimal size = new BigDecimal(matcher.group(1)); final BigDecimal unit = SUFFIXES.get(matcher.group(3)); if (unit == null) { errors.add("Invalid size: " + memory + ". Wrong size unit"); return null; } return size.multiply(unit).longValue(); } public List<String> getErrors() { return errors; } } <file_sep>/src/main/java/com/continuumsecurity/elasticagent/ec2/views/ViewBuilder.java /* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.views; import freemarker.cache.ClassTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; public class ViewBuilder { private static ViewBuilder builder; private final Configuration configuration; private ViewBuilder() { configuration = new Configuration(Configuration.VERSION_2_3_23); configuration.setTemplateLoader(new ClassTemplateLoader(getClass(), "/")); configuration.setDefaultEncoding("UTF-8"); configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); configuration.setLogTemplateExceptions(false); configuration.setDateTimeFormat("iso"); } public Template getTemplate(String template) throws IOException { return configuration.getTemplate(template); } public String build(Template template, Object model) throws IOException, TemplateException { Writer writer = new StringWriter(); template.process(model, writer); return writer.toString(); } public static ViewBuilder instance() { if (builder == null) { builder = new ViewBuilder(); } return builder; } } <file_sep>/src/test/java/com/continuumsecurity/elasticagent/ec2/BaseTest.java /* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2; import java.util.HashMap; import java.util.HashSet; import java.util.Map; public abstract class BaseTest { protected static HashSet<String> instances = new HashSet<>(); protected ClusterProfileProperties createClusterProfiles() { ClusterProfileProperties settings = new ClusterProfileProperties(); settings.setGoServerUrl(Properties.SERVER_URL); settings.setAutoRegisterTimeout(Properties.AUTO_REGISTER_TIMEOUT); settings.setMaxElasticAgents(Properties.MAX_ELASTIC_AGENTS); settings.setAwsAccessKeyId(Properties.ACCESS_KEY_ID); settings.setAwsSecretAccessKey(Properties.SECRET_ACCESS_KEY); settings.setAwsRegion(Properties.REGION); return settings; } protected Map<String, String> createProperties() { Map<String, String> properties = new HashMap<>(); properties.put("ec2_ami", Properties.AMI_ID); properties.put("ec2_instance_type", Properties.TYPE); properties.put("ec2_sg", Properties.SG_IDS); properties.put("ec2_subnets", Properties.SUBNETS); properties.put("ec2_key", Properties.KEY); properties.put("ec2_user_data", Properties.USERDATA); properties.put("ec2_instance_profile", Properties.INSTANCE_PROFILE); return properties; } } <file_sep>/src/test/java/com/continuumsecurity/elasticagent/ec2/executors/AgentStatusReportExecutorTest.java /* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.executors; import com.continuumsecurity.elasticagent.ec2.*; import com.continuumsecurity.elasticagent.ec2.models.AgentStatusReport; import com.continuumsecurity.elasticagent.ec2.models.JobIdentifier; import com.continuumsecurity.elasticagent.ec2.models.NotRunningAgentStatusReport; import com.continuumsecurity.elasticagent.ec2.requests.AgentStatusReportRequest; import com.continuumsecurity.elasticagent.ec2.views.ViewBuilder; import com.google.gson.JsonObject; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import freemarker.template.Template; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.skyscreamer.jsonassert.JSONAssert; import software.amazon.awssdk.services.ec2.model.CpuOptions; import software.amazon.awssdk.services.ec2.model.Instance; import software.amazon.awssdk.services.ec2.model.InstanceState; import software.amazon.awssdk.services.ec2.model.Placement; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) public class AgentStatusReportExecutorTest extends BaseTest { @Mock private PluginRequest pluginRequest; @Mock private PluginSettings pluginSettings; @Mock private Ec2AgentInstances agentInstances; @Mock private ViewBuilder viewBuilder; @Mock private Template template; @Mock private Instance instance; @Mock private InstanceState instanceState; @Mock private Placement placement; @Mock private CpuOptions cpuOptions; private Map<String, String> clusterProfileConfigurations; private ClusterProfileProperties clusterProfile; @BeforeEach public void setup() { clusterProfileConfigurations = Collections.singletonMap("go_server_url", "http://go-server-url/go"); clusterProfile = ClusterProfileProperties.fromConfiguration(clusterProfileConfigurations); } private void mockInstance() { when(instance.instanceId()).thenReturn("i-123456test"); when(instanceState.nameAsString()).thenReturn("running"); when(instance.state()).thenReturn(instanceState); when(instance.instanceTypeAsString()).thenReturn(Properties.TYPE); when(instance.imageId()).thenReturn(Properties.AMI_ID); when(placement.availabilityZone()).thenReturn("eu-west-1c"); when(instance.placement()).thenReturn(placement); when(instance.keyName()).thenReturn(Properties.KEY); when(instance.architectureAsString()).thenReturn("x86"); when(instance.hypervisorAsString()).thenReturn("xen"); when(instance.rootDeviceName()).thenReturn("/dev/xvda"); when(instance.rootDeviceTypeAsString()).thenReturn("ebs"); when(instance.virtualizationTypeAsString()).thenReturn("hvm"); when(cpuOptions.coreCount()).thenReturn(1); when(cpuOptions.threadsPerCore()).thenReturn(2); when(instance.cpuOptions()).thenReturn(cpuOptions); when(instance.privateDnsName()).thenReturn("ip-172-31-50-73.eu-west-1.compute.internal"); when(instance.privateIpAddress()).thenReturn("172.31.50.73"); when(instance.publicDnsName()).thenReturn("ec2-test.eu-west-1.compute.amazonaws.com"); when(instance.publicIpAddress()).thenReturn("172.16.17.32"); when(instance.subnetId()).thenReturn("subnet-123456test"); when(instance.vpcId()).thenReturn("vpc-123456test"); } @Test public void shouldGetAgentStatusReportWithElasticAgentId() throws Exception { mockInstance(); String agentId = "elastic-agent-id"; AgentStatusReportRequest agentStatusReportRequest = new AgentStatusReportRequest(agentId, null, clusterProfile); AgentStatusReport agentStatusReport = new AgentStatusReport(null, instance, null); Ec2Instance agentInstance = new Ec2Instance("id", new Date(), new HashMap<>(), new JobIdentifier()); when(agentInstances.find(agentId)).thenReturn(agentInstance); when(agentInstances.getAgentStatusReport(clusterProfile, agentInstance)).thenReturn(agentStatusReport); when(viewBuilder.getTemplate("agent-status-report.template.ftlh")).thenReturn(template); when(viewBuilder.build(template, agentStatusReport)).thenReturn("agentStatusReportView"); GoPluginApiResponse goPluginApiResponse = new AgentStatusReportExecutor(agentStatusReportRequest, pluginRequest, agentInstances, viewBuilder) .execute(); JsonObject expectedResponseBody = new JsonObject(); expectedResponseBody.addProperty("view", "agentStatusReportView"); assertThat(goPluginApiResponse.responseCode(), is(200)); JSONAssert.assertEquals(expectedResponseBody.toString(), goPluginApiResponse.responseBody(), true); } @Test public void shouldGetAgentStatusReportWithJobIdentifier() throws Exception { mockInstance(); JobIdentifier jobIdentifier = new JobIdentifier("up42", 2L, "label", "stage1", "1", "job", 1L); AgentStatusReportRequest agentStatusReportRequest = new AgentStatusReportRequest(null, jobIdentifier, clusterProfile); AgentStatusReport agentStatusReport = new AgentStatusReport(jobIdentifier, instance, null); Ec2Instance instance = new Ec2Instance("id", new Date(), new HashMap<>(), new JobIdentifier()); when(agentInstances.find(jobIdentifier)).thenReturn(instance); when(agentInstances.getAgentStatusReport(clusterProfile, instance)).thenReturn(agentStatusReport); when(viewBuilder.getTemplate("agent-status-report.template.ftlh")).thenReturn(template); when(viewBuilder.build(template, agentStatusReport)).thenReturn("agentStatusReportView"); GoPluginApiResponse goPluginApiResponse = new AgentStatusReportExecutor(agentStatusReportRequest, pluginRequest, agentInstances, viewBuilder) .execute(); JsonObject expectedResponseBody = new JsonObject(); expectedResponseBody.addProperty("view", "agentStatusReportView"); assertThat(goPluginApiResponse.responseCode(), is(200)); JSONAssert.assertEquals(expectedResponseBody.toString(), goPluginApiResponse.responseBody(), true); } @Test public void shouldRenderContainerNotFoundAgentStatusReportViewWhenNoContainerIsRunningForProvidedJobIdentifier() throws Exception { JobIdentifier jobIdentifier = new JobIdentifier("up42", 2L, "label", "stage1", "1", "job", 1L); AgentStatusReportRequest agentStatusReportRequest = new AgentStatusReportRequest(null, jobIdentifier, clusterProfile); when(agentInstances.find(jobIdentifier)).thenReturn(null); when(viewBuilder.getTemplate("not-running-agent-status-report.template.ftlh")).thenReturn(template); when(viewBuilder.build(eq(template), any(NotRunningAgentStatusReport.class))).thenReturn("errorView"); GoPluginApiResponse goPluginApiResponse = new AgentStatusReportExecutor(agentStatusReportRequest, pluginRequest, agentInstances, viewBuilder) .execute(); JsonObject expectedResponseBody = new JsonObject(); expectedResponseBody.addProperty("view", "errorView"); assertThat(goPluginApiResponse.responseCode(), is(200)); JSONAssert.assertEquals(expectedResponseBody.toString(), goPluginApiResponse.responseBody(), true); } @Test public void shouldRenderContainerNotFoundAgentStatusReportViewWhenNoContainerIsRunningForProvidedElasticAgentId() throws Exception { String elasticAgentId = "elastic-agent-id"; AgentStatusReportRequest agentStatusReportRequest = new AgentStatusReportRequest(elasticAgentId, null, clusterProfile); when(agentInstances.find(elasticAgentId)).thenReturn(null); when(viewBuilder.getTemplate("not-running-agent-status-report.template.ftlh")).thenReturn(template); when(viewBuilder.build(eq(template), any(NotRunningAgentStatusReport.class))).thenReturn("errorView"); GoPluginApiResponse goPluginApiResponse = new AgentStatusReportExecutor(agentStatusReportRequest, pluginRequest, agentInstances, viewBuilder) .execute(); JsonObject expectedResponseBody = new JsonObject(); expectedResponseBody.addProperty("view", "errorView"); assertThat(goPluginApiResponse.responseCode(), is(200)); JSONAssert.assertEquals(expectedResponseBody.toString(), goPluginApiResponse.responseBody(), true); } } <file_sep>/src/main/java/com/continuumsecurity/elasticagent/ec2/executors/JobCompletionRequestExecutor.java /* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.executors; import com.continuumsecurity.elasticagent.ec2.*; import com.continuumsecurity.elasticagent.ec2.requests.JobCompletionRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import java.util.Arrays; import java.util.List; import static com.continuumsecurity.elasticagent.ec2.Ec2Plugin.LOG; public class JobCompletionRequestExecutor implements RequestExecutor { private final JobCompletionRequest jobCompletionRequest; private final AgentInstances<Ec2Instance> agentInstances; private final PluginRequest pluginRequest; public JobCompletionRequestExecutor(JobCompletionRequest jobCompletionRequest, AgentInstances<Ec2Instance> agentInstances, PluginRequest pluginRequest) { this.jobCompletionRequest = jobCompletionRequest; this.agentInstances = agentInstances; this.pluginRequest = pluginRequest; } @Override public GoPluginApiResponse execute() throws Exception { ClusterProfileProperties clusterProfileProperties = jobCompletionRequest.getClusterProfileProperties(); String elasticAgentId = jobCompletionRequest.getElasticAgentId(); Agent agent = new Agent(elasticAgentId); LOG.info("[Job Completion] Terminating elastic agent with id {} on job completion {} in cluster {}.", agent.elasticAgentId(), jobCompletionRequest.jobIdentifier(), clusterProfileProperties); List<Agent> agents = Arrays.asList(agent); pluginRequest.disableAgents(agents); agentInstances.terminate(agent.elasticAgentId(), clusterProfileProperties); pluginRequest.deleteAgents(agents); return DefaultGoPluginApiResponse.success(""); } } <file_sep>/src/main/java/com/continuumsecurity/elasticagent/ec2/executors/GetClusterProfileMetadataExecutor.java /* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.executors; import com.continuumsecurity.elasticagent.ec2.RequestExecutor; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import java.util.ArrayList; import java.util.List; import static com.continuumsecurity.elasticagent.ec2.PluginSettings.GSON; public class GetClusterProfileMetadataExecutor implements RequestExecutor { public static final Metadata GO_SERVER_URL = new GoServerURLMetadata(); public static final Metadata AUTO_REGISTER_TIMEOUT = new NumberMetadata("auto_register_timeout", true); public static final Metadata MAX_ELASTIC_AGENTS = new NumberMetadata("max_elastic_agents", true); public static final Metadata AWS_ACCESS_KEY_ID = new Metadata("aws_access_key_id", false, false); public static final Metadata AWS_SECRET_ACCESS_KEY = new Metadata("aws_secret_access_key", false, true); public static final Metadata AWS_REGION = new Metadata("aws_region", true, false); public static final List<Metadata> CLUSTER_PROFILE_FIELDS = new ArrayList<>(); static { CLUSTER_PROFILE_FIELDS.add(GO_SERVER_URL); CLUSTER_PROFILE_FIELDS.add(AUTO_REGISTER_TIMEOUT); CLUSTER_PROFILE_FIELDS.add(MAX_ELASTIC_AGENTS); CLUSTER_PROFILE_FIELDS.add(AWS_ACCESS_KEY_ID); CLUSTER_PROFILE_FIELDS.add(AWS_SECRET_ACCESS_KEY); CLUSTER_PROFILE_FIELDS.add(AWS_REGION); } @Override public GoPluginApiResponse execute() throws Exception { return new DefaultGoPluginApiResponse(200, GSON.toJson(CLUSTER_PROFILE_FIELDS)); } }<file_sep>/src/test/java/com/continuumsecurity/elasticagent/ec2/Properties.java package com.continuumsecurity.elasticagent.ec2; public interface Properties { String SERVER_URL = "https://your.gocd.server/"; String ACCESS_KEY_ID = "ACCES_KEY_ID"; String SECRET_ACCESS_KEY = "SECRET_ACCESS_KEY"; String REGION = "default_aws_region"; String AMI_ID = "ami-id"; String KEY = "key"; String SUBNETS = "subnet-1,subnet-2,subnet-3"; String SG_IDS = "sg-IDS"; String TYPE = "t3.nano"; String USERDATA = "#!/bin/bash\n" + "echo hi"; String INSTANCE_PROFILE = "InstanceProfileName"; String AUTO_REGISTER_TIMEOUT = "5"; String MAX_ELASTIC_AGENTS = "50"; String AUTO_REGISTER_KEY = "AUTO_REGISTER_KEY"; } <file_sep>/src/test/java/com/continuumsecurity/elasticagent/ec2/ClusterProfilePropertiesTest.java /* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2; import com.continuumsecurity.elasticagent.ec2.requests.CreateAgentRequest; import com.continuumsecurity.elasticagent.ec2.requests.JobCompletionRequest; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; public class ClusterProfilePropertiesTest { @Test public void shouldDeserializeFromJSON() throws Exception { ClusterProfileProperties pluginSettings = ClusterProfileProperties.fromJSON("{" + "\"go_server_url\": \"https://cloud.example.com:8154/go\", " + "\"auto_register_timeout\": \"5\", " + "\"max_elastic_agents\": \"50\", " + "\"aws_access_key_id\": \"ACCES_KEY_ID\", " + "\"aws_secret_access_key\": \"SECRET_ACCESS_KEY\", " + "\"aws_region\": \"eu-west-1\"" + "}"); assertThat(pluginSettings.getGoServerUrl(), is("https://cloud.example.com:8154/go")); assertThat(pluginSettings.getAutoRegisterTimeout(), is("5")); assertThat(pluginSettings.getMaxElasticAgents(), is(50)); assertThat(pluginSettings.getAwsAccessKeyId(), is("ACCES_KEY_ID")); assertThat(pluginSettings.getAwsSecretAccessKey(), is("SECRET_ACCESS_KEY")); } @Test public void shouldGenerateSameUUIDForClusterProfileProperties() { Map<String, String> clusterProfileConfigurations = Collections.singletonMap("go_server_url", "http://go-server-url/go"); ClusterProfileProperties clusterProfileProperties = ClusterProfileProperties.fromConfiguration(clusterProfileConfigurations); assertThat(clusterProfileProperties.uuid(), is(clusterProfileProperties.uuid())); } @Test public void shouldGenerateSameUUIDForClusterProfilePropertiesAcrossRequests() { String createAgentRequestJSON = "{\n" + " \"auto_register_key\": \"secret-key\",\n" + " \"elastic_agent_profile_properties\": {\n" + " \"key1\": \"value1\",\n" + " \"key2\": \"value2\"\n" + " },\n" + " \"cluster_profile_properties\": {\n" + " \"go_server_url\": \"https://foo.com/go\",\n" + " \"auto_register_timeout\": \"10\"\n" + " }\n" + "}"; CreateAgentRequest createAgentRequest = CreateAgentRequest.fromJSON(createAgentRequestJSON); String jobCompletionRequestJSON = "{\n" + " \"elastic_agent_id\": \"ea1\",\n" + " \"elastic_agent_profile_properties\": {\n" + " \"ec2_ami\": \"ami-123456\"\n" + " },\n" + " \"cluster_profile_properties\": {\n" + " \"go_server_url\": \"https://foo.com/go\", \n" + " \"auto_register_timeout\": \"10\"\n" + " },\n" + " \"job_identifier\": {\n" + " \"pipeline_name\": \"test-pipeline\",\n" + " \"pipeline_counter\": 1,\n" + " \"pipeline_label\": \"Test Pipeline\",\n" + " \"stage_name\": \"test-stage\",\n" + " \"stage_counter\": \"1\",\n" + " \"job_name\": \"test-job\",\n" + " \"job_id\": 100\n" + " }\n" + "}"; JobCompletionRequest jobCompletionRequest = JobCompletionRequest.fromJSON(jobCompletionRequestJSON); assertThat(jobCompletionRequest.getClusterProfileProperties().uuid(), is(createAgentRequest.getClusterProfileProperties().uuid())); } } <file_sep>/src/main/java/com/continuumsecurity/elasticagent/ec2/SetupSemaphore.java /* * Copyright 2016 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2; import java.util.Map; import java.util.concurrent.Semaphore; class SetupSemaphore implements Runnable { private final Integer maxAllowedInstances; private final Map<?, ?> instances; private final Semaphore semaphore; public SetupSemaphore(Integer maxAllowedInstances, Map<?, ?> instances, Semaphore semaphore) { this.maxAllowedInstances = maxAllowedInstances; this.instances = instances; this.semaphore = semaphore; } @Override public void run() { int currentInstances = instances.size(); int availablePermits = maxAllowedInstances - currentInstances; if (availablePermits <= 0) { // no more capacity available. semaphore.drainPermits(); } else { int semaphoreValueDifference = availablePermits - semaphore.availablePermits(); if (semaphoreValueDifference > 0) { semaphore.release(semaphoreValueDifference); } else if (semaphoreValueDifference < 0) { semaphore.tryAcquire(Math.abs(semaphoreValueDifference)); } } } } <file_sep>/src/test/java/com/continuumsecurity/elasticagent/ec2/executors/JobCompletionRequestExecutorTest.java /* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.executors; import com.continuumsecurity.elasticagent.ec2.*; import com.continuumsecurity.elasticagent.ec2.models.JobIdentifier; import com.continuumsecurity.elasticagent.ec2.requests.JobCompletionRequest; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import java.util.HashMap; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.MockitoAnnotations.initMocks; public class JobCompletionRequestExecutorTest { @Mock private PluginRequest mockPluginRequest; @Mock private AgentInstances<Ec2Instance> mockAgentInstances; @Captor private ArgumentCaptor<List<Agent>> agentsArgumentCaptor; @BeforeEach public void setUp() { initMocks(this); } @Test public void shouldAskDockerContainersToCreateAnAgent() throws Exception { JobIdentifier jobIdentifier = new JobIdentifier(100L); ClusterProfileProperties clusterProfileProperties = new ClusterProfileProperties(); String elasticAgentId = "agent-id"; JobCompletionRequest request = new JobCompletionRequest(elasticAgentId, jobIdentifier, new HashMap<>(), clusterProfileProperties); AgentInstances agentInstances = mock(AgentInstances.class); GoPluginApiResponse response = new JobCompletionRequestExecutor(request, mockAgentInstances, mockPluginRequest).execute(); InOrder inOrder = inOrder(mockPluginRequest, mockAgentInstances); inOrder.verify(mockPluginRequest).disableAgents(agentsArgumentCaptor.capture()); List<Agent> agentsToDisabled = agentsArgumentCaptor.getValue(); assertEquals(1, agentsToDisabled.size()); assertEquals(elasticAgentId, agentsToDisabled.get(0).elasticAgentId()); inOrder.verify(mockAgentInstances).terminate(elasticAgentId, clusterProfileProperties); inOrder.verify(mockPluginRequest).deleteAgents(agentsArgumentCaptor.capture()); List<Agent> agentsToDelete = agentsArgumentCaptor.getValue(); assertEquals(agentsToDisabled, agentsToDelete); assertEquals(200, response.responseCode()); assertTrue(response.responseBody().isEmpty()); } } <file_sep>/src/main/java/com/continuumsecurity/elasticagent/ec2/executors/MigrateConfigurationRequestExecutor.java /* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.continuumsecurity.elasticagent.ec2.executors; import com.continuumsecurity.elasticagent.ec2.*; import com.continuumsecurity.elasticagent.ec2.requests.MigrateConfigurationRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.stream.Collectors; import static com.continuumsecurity.elasticagent.ec2.Ec2Plugin.LOG; public class MigrateConfigurationRequestExecutor implements RequestExecutor { private MigrateConfigurationRequest migrateConfigurationRequest; public MigrateConfigurationRequestExecutor(MigrateConfigurationRequest migrateConfigurationRequest) { this.migrateConfigurationRequest = migrateConfigurationRequest; } @Override public GoPluginApiResponse execute() throws Exception { LOG.info("[Migrate Config] Request for Config Migration Started..."); PluginSettings pluginSettings = migrateConfigurationRequest.getPluginSettings(); List<ClusterProfile> existingClusterProfiles = migrateConfigurationRequest.getClusterProfiles(); List<ElasticAgentProfile> existingElasticAgentProfiles = migrateConfigurationRequest.getElasticAgentProfiles(); if (!arePluginSettingsConfigured(pluginSettings)) { LOG.info("[Migrate Config] No Plugin Settings are configured. Skipping Config Migration..."); return new DefaultGoPluginApiResponse(200, migrateConfigurationRequest.toJSON()); } if (existingClusterProfiles.size() == 0) { LOG.info("[Migrate Config] Did not find any Cluster Profile. Possibly, user just have configured plugin settings and haven't define any elastic agent profiles."); String newClusterId = UUID.randomUUID().toString(); LOG.info("[Migrate Config] Migrating existing plugin settings to new cluster profile '{}'", newClusterId); ClusterProfile clusterProfile = new ClusterProfile(newClusterId, Constants.PLUGIN_ID, pluginSettings); return getGoPluginApiResponse(pluginSettings, Arrays.asList(clusterProfile), existingElasticAgentProfiles); } LOG.info("[Migrate Config] Checking to perform migrations on Cluster Profiles '{}'.", existingClusterProfiles.stream().map(ClusterProfile::getId).collect(Collectors.toList())); for (ClusterProfile clusterProfile : existingClusterProfiles) { List<ElasticAgentProfile> associatedElasticAgentProfiles = findAssociatedElasticAgentProfiles(clusterProfile, existingElasticAgentProfiles); if (associatedElasticAgentProfiles.size() == 0) { LOG.info("[Migrate Config] Skipping migration for the cluster '{}' as no Elastic Agent Profiles are associated with it.", clusterProfile.getId()); continue; } if (!arePluginSettingsConfigured(clusterProfile.getClusterProfileProperties())) { List<String> associatedProfileIds = associatedElasticAgentProfiles.stream().map(ElasticAgentProfile::getId).collect(Collectors.toList()); LOG.info("[Migrate Config] Found an empty cluster profile '{}' associated with '{}' elastic agent profiles.", clusterProfile.getId(), associatedProfileIds); migrateConfigForCluster(pluginSettings, associatedElasticAgentProfiles, clusterProfile); } else { LOG.info("[Migrate Config] Skipping migration for the cluster '{}' as cluster has already been configured.", clusterProfile.getId()); } } return new DefaultGoPluginApiResponse(200, migrateConfigurationRequest.toJSON()); } //this is responsible to copy over plugin settings configurations to cluster profile and if required rename no op cluster private void migrateConfigForCluster(PluginSettings pluginSettings, List<ElasticAgentProfile> associatedElasticAgentProfiles, ClusterProfile clusterProfile) { LOG.info("[Migrate Config] Coping over existing plugin settings configurations to '{}' cluster profile.", clusterProfile.getId()); clusterProfile.setClusterProfileProperties(pluginSettings); if (clusterProfile.getId().equals(String.format("no-op-cluster-for-%s", Constants.PLUGIN_ID))) { String newClusterId = UUID.randomUUID().toString(); LOG.info("[Migrate Config] Renaming dummy cluster profile from '{}' to '{}'.", clusterProfile.getId(), newClusterId); clusterProfile.setId(newClusterId); LOG.info("[Migrate Config] Changing all elastic agent profiles to point to '{}' cluster profile.", clusterProfile.getId()); associatedElasticAgentProfiles.forEach(elasticAgentProfile -> elasticAgentProfile.setClusterProfileId(newClusterId)); } } private List<ElasticAgentProfile> findAssociatedElasticAgentProfiles(ClusterProfile clusterProfile, List<ElasticAgentProfile> elasticAgentProfiles) { return elasticAgentProfiles.stream().filter(profile -> Objects.equals(profile.getClusterProfileId(), clusterProfile.getId())).collect(Collectors.toList()); } private GoPluginApiResponse getGoPluginApiResponse(PluginSettings pluginSettings, List<ClusterProfile> clusterProfiles, List<ElasticAgentProfile> elasticAgentProfiles) { MigrateConfigurationRequest response = new MigrateConfigurationRequest(); response.setPluginSettings(pluginSettings); response.setClusterProfiles(clusterProfiles); response.setElasticAgentProfiles(elasticAgentProfiles); return new DefaultGoPluginApiResponse(200, response.toJSON()); } private boolean arePluginSettingsConfigured(PluginSettings pluginSettings) { return !StringUtils.isBlank(pluginSettings.getGoServerUrl()); } } <file_sep>/src/main/java/com/continuumsecurity/elasticagent/ec2/executors/GoServerURLField.java /* * Copyright 2016 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.continuumsecurity.elasticagent.ec2.executors; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import static com.continuumsecurity.elasticagent.ec2.executors.GetClusterProfileMetadataExecutor.GO_SERVER_URL; import static org.apache.commons.lang3.StringUtils.isBlank; public class GoServerURLField extends Field { public GoServerURLField(String displayOrder) { super(GO_SERVER_URL.getKey(), "Go Server URL", null, true, false, displayOrder); } @Override public String doValidate(String input) { if (isBlank(input)) { return this.displayName + " must not be blank."; } URI uri = null; try { uri = new URL(input).toURI(); } catch (MalformedURLException | URISyntaxException e) { return this.displayName + " must be a valid URL (https://example.com:8154/go)"; } if (isBlank(uri.getScheme())) { return this.displayName + " must be a valid URL (https://example.com:8154/go)"; } if (!uri.getScheme().equalsIgnoreCase("https")) { return this.displayName + " must be a valid HTTPs URL (https://example.com:8154/go)"; } if (uri.getHost().equalsIgnoreCase("localhost") || uri.getHost().equalsIgnoreCase("127.0.0.1")) { return this.displayName + " must not be localhost, since this gets resolved on the agents"; } if (!(uri.getPath().endsWith("/go") || uri.getPath().endsWith("/go/"))) { return this.displayName + " must be a valid URL ending with '/go' (https://example.com:8154/go)"; } return null; } } <file_sep>/src/test/java/com/continuumsecurity/elasticagent/ec2/models/JobIdentifierTest.java /* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.models; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class JobIdentifierTest { @Test public void shouldDeserializeFromJson() { JobIdentifier jobIdentifier = JobIdentifier.fromJson(JobIdentifierMother.getJson().toString()); JobIdentifier expected = JobIdentifierMother.get(); assertThat(jobIdentifier, is(expected)); } @Test public void shouldGetRepresentation() { String representation = JobIdentifierMother.get().getRepresentation(); assertThat(representation, is("up42/1/stage/1/job1")); } } <file_sep>/src/test/java/com/continuumsecurity/elasticagent/ec2/requests/AgentStatusReportRequestTest.java /* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file incorporates changes by @continuumsecurity */ package com.continuumsecurity.elasticagent.ec2.requests; import com.continuumsecurity.elasticagent.ec2.ClusterProfileProperties; import com.continuumsecurity.elasticagent.ec2.models.JobIdentifierMother; import com.google.gson.JsonObject; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class AgentStatusReportRequestTest { @Test public void shouldDeserializeFromJSON() { JsonObject jobIdentifierJson = JobIdentifierMother.getJson(); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("elastic_agent_id", "some-id"); jsonObject.add("job_identifier", jobIdentifierJson); AgentStatusReportRequest agentStatusReportRequest = AgentStatusReportRequest.fromJSON(jsonObject.toString()); AgentStatusReportRequest expected = new AgentStatusReportRequest("some-id", JobIdentifierMother.get(), null); assertThat(agentStatusReportRequest, is(expected)); } @Test public void shouldDeserializeFromJSONWithClusterProfile() { JsonObject jobIdentifierJson = JobIdentifierMother.getJson(); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("elastic_agent_id", "some-id"); jsonObject.add("job_identifier", jobIdentifierJson); JsonObject clusterJSON = new JsonObject(); clusterJSON.addProperty("go_server_url", "https://foo.com/go"); clusterJSON.addProperty("docker_uri", "unix:///var/run/docker.sock"); jsonObject.add("cluster_profile_properties", clusterJSON); AgentStatusReportRequest agentStatusReportRequest = AgentStatusReportRequest.fromJSON(jsonObject.toString()); Map<String, String> expectedClusterProfile = new HashMap<>(); expectedClusterProfile.put("go_server_url", "https://foo.com/go"); expectedClusterProfile.put("docker_uri", "unix:///var/run/docker.sock"); AgentStatusReportRequest expected = new AgentStatusReportRequest("some-id", JobIdentifierMother.get(), ClusterProfileProperties.fromConfiguration(expectedClusterProfile)); assertThat(agentStatusReportRequest, is(expected)); } } <file_sep>/src/test/java/com/continuumsecurity/elasticagent/ec2/Test.java package com.continuumsecurity.elasticagent.ec2; import com.continuumsecurity.elasticagent.ec2.models.JobIdentifier; import com.continuumsecurity.elasticagent.ec2.requests.CreateAgentRequest; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ec2.model.*; import javax.annotation.Nullable; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import static org.mockito.Mockito.mock; public class Test { public static void main(String[] args) { List<String> items = Arrays.asList(Properties.SUBNETS.split("\\s*,\\s*")); System.out.println(items.get(new Random().nextInt(items.size()))); Map<String, String> properties = new HashMap<>(); properties.put("ec2_ami", Properties.AMI_ID); properties.put("ec2_instance_type", Properties.TYPE); properties.put("ec2_sg", Properties.SG_IDS); properties.put("ec2_subnets", Properties.SUBNETS); properties.put("ec2_key", Properties.KEY); properties.put("ec2_user_data", Properties.USERDATA); properties.put("ec2_instance_profile", Properties.INSTANCE_PROFILE); JobIdentifier jobIdentifier = new JobIdentifier( "examplePipeName", 45L, "examplePipeLabel", "exampleStageName", "stage-6", "exampleJobName", 68L ); ClusterProfileProperties settings = new ClusterProfileProperties(); settings.setGoServerUrl(Properties.SERVER_URL); settings.setAutoRegisterTimeout(Properties.AUTO_REGISTER_TIMEOUT); settings.setMaxElasticAgents(Properties.MAX_ELASTIC_AGENTS); settings.setAwsAccessKeyId(Properties.ACCESS_KEY_ID); settings.setAwsSecretAccessKey(Properties.SECRET_ACCESS_KEY); settings.setAwsRegion(Properties.REGION); CreateAgentRequest createAgentRequest = new CreateAgentRequest( Properties.AUTO_REGISTER_KEY, properties, jobIdentifier, settings ); Ec2Instance ec2Instance = Ec2Instance.create(createAgentRequest, settings, mock(ConsoleLogAppender.class)); //*System.out.println(ec2Instance.toString()); ConcurrentHashMap<String, Ec2Instance> instances = new ConcurrentHashMap<>(); instances.put(ec2Instance.id(), ec2Instance); System.out.println(instances.get(ec2Instance.id())); System.out.println(""); try { Thread.sleep(1000); } catch (InterruptedException e) {} AwsBasicCredentials awsCredentials = AwsBasicCredentials.create(Properties.ACCESS_KEY_ID, Properties.SECRET_ACCESS_KEY); Ec2Client ec2 = Ec2Client.builder() .region(Region.EU_WEST_1) .credentialsProvider(StaticCredentialsProvider.create(awsCredentials)) .build(); DescribeInstancesRequest request = DescribeInstancesRequest.builder() .filters( Filter.builder() .name("instance-state-name") .values("running","pending","terminated") .build(), Filter.builder() .name("tag:type") .values(Constants.ELASTIC_AGENT_TAG) .build() ) .build(); DescribeInstancesResponse response = ec2.describeInstances(request); int count = 0; for(Reservation reservation : response.reservations()) { count += reservation.instances().size(); for(Instance instance : reservation.instances()) { System.out.printf( "Found reservation with id %s, " + "AMI %s, " + "type %s, " + "state %s", instance.instanceId(), instance.imageId(), instance.instanceType(), instance.state().name() ); System.out.println("TAGS:"); for (Tag tag : instance.tags()) { System.out.println(tag.toString()); } JobIdentifier ji = JobIdentifier.fromJson(getTag(instance.tags(),"JsonJobIdentifier")); System.out.println(""); } } System.out.println(count+" instances found"); ec2Instance.terminate(settings); } @Nullable private static String getTag(List<Tag> tags, String key) { for (Tag tag : tags) { if (tag.key().equals(key)) { return tag.value(); } } return null; } } <file_sep>/src/main/java/com/continuumsecurity/elasticagent/ec2/requests/MigrateConfigurationRequest.java /* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.continuumsecurity.elasticagent.ec2.requests; import com.continuumsecurity.elasticagent.ec2.ClusterProfile; import com.continuumsecurity.elasticagent.ec2.ElasticAgentProfile; import com.continuumsecurity.elasticagent.ec2.PluginSettings; import com.continuumsecurity.elasticagent.ec2.executors.MigrateConfigurationRequestExecutor; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; import java.util.Objects; import static com.continuumsecurity.elasticagent.ec2.Ec2Plugin.GSON; public class MigrateConfigurationRequest { @Expose @SerializedName("plugin_settings") private PluginSettings pluginSettings; @Expose @SerializedName("elastic_agent_profiles") private List<ElasticAgentProfile> elasticAgentProfiles; @Expose @SerializedName("cluster_profiles") private List<ClusterProfile> clusterProfiles; public MigrateConfigurationRequest() { } public MigrateConfigurationRequest(PluginSettings pluginSettings, List<ClusterProfile> clusterProfiles, List<ElasticAgentProfile> elasticAgentProfiles) { this.pluginSettings = pluginSettings; this.clusterProfiles = clusterProfiles; this.elasticAgentProfiles = elasticAgentProfiles; } public static MigrateConfigurationRequest fromJSON(String json) { return GSON.fromJson(json, MigrateConfigurationRequest.class); } public String toJSON() { return GSON.toJson(this); } public MigrateConfigurationRequestExecutor executor() { return new MigrateConfigurationRequestExecutor(this); } public PluginSettings getPluginSettings() { return pluginSettings; } public void setPluginSettings(PluginSettings pluginSettings) { this.pluginSettings = pluginSettings; } public List<ClusterProfile> getClusterProfiles() { return clusterProfiles; } public void setClusterProfiles(List<ClusterProfile> clusterProfiles) { this.clusterProfiles = clusterProfiles; } public List<ElasticAgentProfile> getElasticAgentProfiles() { return elasticAgentProfiles; } public void setElasticAgentProfiles(List<ElasticAgentProfile> elasticAgentProfiles) { this.elasticAgentProfiles = elasticAgentProfiles; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MigrateConfigurationRequest that = (MigrateConfigurationRequest) o; return Objects.equals(pluginSettings, that.pluginSettings) && Objects.equals(clusterProfiles, that.clusterProfiles) && Objects.equals(elasticAgentProfiles, that.elasticAgentProfiles); } @Override public int hashCode() { return Objects.hash(pluginSettings, clusterProfiles, elasticAgentProfiles); } @Override public String toString() { return "MigrateConfigurationRequest{" + "pluginSettings=" + pluginSettings + ", clusterProfiles=" + clusterProfiles + ", elasticAgentProfiles=" + elasticAgentProfiles + '}'; } }
1d71ec1ff5971bc06660ba6d182bf88b84e03c99
[ "Markdown", "Java" ]
26
Java
iriusrisk/GoCD-EC2-Elastic-Agent-Plugin
0b990699a2f1d6b3fa85a835f27c614d5513c3e2
872b23cfada0646d6a5e2893bb7997640f55d6fe
refs/heads/master
<repo_name>trymnilsen/Fibrous<file_sep>/Fibrous/Fibers/Fiber.cs namespace Fibrous { using System; public enum FiberType { Thread, Pool, Stub } public static class Fiber { private static IFiber GetFromTyoe(FiberType type, IExecutor executor) { switch (type) { case FiberType.Thread: return new ThreadFiber(executor); case FiberType.Pool: return new PoolFiber(executor); case FiberType.Stub: return new StubFiber(executor); default: throw new ArgumentOutOfRangeException("type"); } } /// <summary> /// Helper to create and start an IFiber by type /// </summary> /// <param name="type"></param> /// <param name="executor"></param> /// <returns></returns> public static IFiber StartNew(FiberType type, IExecutor executor = null) //TODO: add Queue { if (executor == null) executor = new Executor(); //if(queue == null) queue = new YieldingQueue(); IFiber fiber = GetFromTyoe(type, executor); fiber.Start(); return fiber; } } }<file_sep>/Fibrous/IRequestPort.cs namespace Fibrous { using System; /// <summary> /// Port for sending requests and receiving repplies. /// </summary> /// <typeparam name="TRequest"></typeparam> /// <typeparam name="TReply"></typeparam> public interface IRequestPort<in TRequest, TReply> { /// <summary> /// Send an asynchronous request, and let the reply be delivered to the fiber when ready /// </summary> /// <param name="request"></param> /// <param name="fiber"></param> /// <param name="onReply"></param> /// <returns></returns> IDisposable SendRequest(TRequest request, IFiber fiber, Action<TReply> onReply); /// <summary> /// Send an asynchronous request and get a reply object for handling the response in the same code block. /// </summary> /// <param name="request"></param> /// <returns></returns> IReply<TReply> SendRequest(TRequest request); } public static class RequestPortExtensions { /// <summary> /// Send a request with infinite timeout /// </summary> /// <typeparam name="TRequest"></typeparam> /// <typeparam name="TReply"></typeparam> /// <param name="port"></param> /// <param name="request"></param> /// <returns></returns> public static TReply SendRequest<TRequest, TReply>(this IRequestPort<TRequest, TReply> port, TRequest request) { return port.SendRequest(request).Receive(TimeSpan.MaxValue).Value; } } /// <summary> /// Future type for receiving a response /// </summary> /// <typeparam name="T"></typeparam> public interface IReply<T> { /// <summary> /// Call to wait for a reply to be delivereed. /// </summary> /// <param name="timeout"></param> /// <returns></returns> IResult<T> Receive(TimeSpan timeout); } /// <summary> /// Reponse to a request /// </summary> /// <typeparam name="T"></typeparam> public interface IResult<T> { /// <summary> /// Did we successfully receive a reply /// </summary> bool IsValid { get; } /// <summary> /// The rpely value /// </summary> T Value { get; } } /// <summary> /// Port for setting up request handling fibers /// </summary> /// <typeparam name="TRequest"></typeparam> /// <typeparam name="TReply"></typeparam> public interface IRequestHandlerPort<out TRequest, in TReply> { /// <summary> /// Set the fiber and handler for responding to requests. /// </summary> /// <param name="fiber"></param> /// <param name="onRequest"></param> /// <returns></returns> IDisposable SetRequestHandler(IFiber fiber, Action<IRequest<TRequest, TReply>> onRequest); } /// <summary> /// Interface for requests where a handler can send a reply /// </summary> /// <typeparam name="TRequest"></typeparam> /// <typeparam name="TReply"></typeparam> public interface IRequest<out TRequest, in TReply> { /// <summary> /// The request /// </summary> TRequest Request { get; } /// <summary> /// Reply to the request /// </summary> /// <param name="reply"></param> void Reply(TReply reply); } }<file_sep>/Fibrous.Tests/ReqReplyTests.cs namespace Fibrous.Tests { using NUnit.Framework; [TestFixture] public class ReqReplyTests { [Test] public void TestName() { IRequestChannel<int, int> channel = new RequestChannel<int, int>(); IFiber fiber1 = PoolFiber.StartNew(); } } }<file_sep>/Fibrous/Fibers/IExecutor.cs namespace Fibrous { using System; using System.Collections.Generic; /// <summary> /// Abstraction of handling drained batch and individual execution. Allows insertion of exception handling, profiling, etc. /// </summary> public interface IExecutor { void Execute(List<Action> toExecute); void Execute(Action toExecute); } /// <summary> /// Default executor that simply /// </summary> public sealed class Executor : IExecutor { public void Execute(List<Action> toExecute) { for (int index = 0; index < toExecute.Count; index++) { Action action = toExecute[index]; Execute(action); } } public void Execute(Action toExecute) { toExecute(); } } /// <summary> /// IExecutor that handles any exceptions thrown with an optional exception callback /// </summary> public sealed class ExceptionHandlingExecutor : IExecutor { private readonly Action<Exception> _callback; public ExceptionHandlingExecutor(Action<Exception> callback = null) { _callback = callback; } public void Execute(List<Action> toExecute) { for (int index = 0; index < toExecute.Count; index++) { Action action = toExecute[index]; Execute(action); } } public void Execute(Action toExecute) { try { toExecute(); } catch (Exception e) { if (_callback != null) _callback(e); } } } }<file_sep>/Fibrous/Fibers/DispatcherFiber.cs namespace Fibrous { using System; using System.Windows.Threading; /// <summary> /// Fiber for use with WPF forms and controls. Provides seamless marshalling to dispatcher thread. /// </summary> public sealed class DispatcherFiber : GuiFiberBase { public DispatcherFiber(Executor executor, Dispatcher dispatcher, DispatcherPriority priority = DispatcherPriority.Normal) : base(executor, new DispatcherAdapter(dispatcher, priority)) { } public DispatcherFiber(Dispatcher dispatcher, DispatcherPriority priority = DispatcherPriority.Normal) : this(new Executor(), dispatcher, priority) { } public DispatcherFiber() : this(Dispatcher.CurrentDispatcher) { } private class DispatcherAdapter : IExecutionContext { private readonly Dispatcher _dispatcher; private readonly DispatcherPriority _priority; public DispatcherAdapter(Dispatcher dispatcher, DispatcherPriority priority) { _dispatcher = dispatcher; _priority = priority; } public void Enqueue(Action action) { _dispatcher.BeginInvoke(action, _priority); } } } }<file_sep>/Fibrous.Tests/FiberBuilderTests.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fibrous.Tests { using System.Threading; using Fibrous; using NUnit.Framework; [TestFixture] public class FiberBuilderTests { [Test] public void BuilderTests() { IFiber threadFiber = FiberBuilder .Create(FiberType.Thread) .WithBlockingQueue(1000) .WithErrorHandlingExecutor() .WithPriority(ThreadPriority.Highest) .Start(); IFiber pool = FiberBuilder .Create(FiberType.Pool) .Start(); } } } <file_sep>/Fibrous.Tests/PerfTests.cs namespace Fibrous.Tests { using System; using System.Collections.Generic; using System.Threading; using Fibrous.Queues; using NUnit.Framework; public class PerfExecutor : IExecutor { public void Execute(List<Action> toExecute) { int count = 0; for (int index = 0; index < toExecute.Count; index++) { Action action = toExecute[index]; action(); count++; } if (count < 10000) Thread.Sleep(1); } public void Execute(Action toExecute) { toExecute(); } } public struct MsgStruct { public int count; } [TestFixture] public class PerfTests { private static void PointToPointPerfTestWithStruct(FiberBase fiber) { using (fiber) { fiber.Start(); IChannel<MsgStruct> channel = new Channel<MsgStruct>(); const int max = 5000000; var reset = new AutoResetEvent(false); var counter = new Counter(reset, max); channel.Subscribe(fiber, counter.OnMsg); Thread.Sleep(100); using (new PerfTimer(max)) { for (int i = 0; i <= max; i++) channel.Publish(new MsgStruct { count = i }); Assert.IsTrue(reset.WaitOne(30000, false)); } } } private class Counter { private readonly int _cutoff; private readonly AutoResetEvent handle; public Counter(AutoResetEvent handle, int cutoff) { this.handle = handle; _cutoff = cutoff; } public int Count { get; set; } public void OnMsg(MsgStruct msg) { Count++; if (Count == _cutoff) handle.Set(); } } private class CounterInt { private readonly int _cutoff; private readonly AutoResetEvent handle; public CounterInt(AutoResetEvent handle, int cutoff) { this.handle = handle; _cutoff = cutoff; } public void OnMsg(int msg) { if (msg == _cutoff) handle.Set(); } } public void PointToPointPerfTestWithInt(FiberBase fiber) { using (fiber) { fiber.Start(); var channel = new Channel<int>(); const int max = 5000000; var reset = new AutoResetEvent(false); var counter = new CounterInt(reset, max); channel.Subscribe(fiber, counter.OnMsg); Thread.Sleep(100); using (new PerfTimer(max)) { for (int i = 0; i <= max; i++) channel.Publish(i); Assert.IsTrue(reset.WaitOne(30000, false)); } } } public void PointToPointPerfTestWithObject(FiberBase fiber) { using (fiber) { fiber.Start(); var channel = new Channel<object>(); const int max = 5000000; var reset = new AutoResetEvent(false); var end = new object(); Action<object> onMsg = delegate(object msg) { if (msg == end) reset.Set(); }; channel.Subscribe(fiber, onMsg); Thread.Sleep(100); using (new PerfTimer(max)) { var msg = new object(); for (int i = 0; i <= max; i++) channel.Publish(msg); channel.Publish(end); Assert.IsTrue(reset.WaitOne(30000, false)); } } } [Test] [Explicit] public void TestBoundedQueue() { PointToPointPerfTestWithStruct(new ThreadFiber(new PerfExecutor(), new TimerScheduler(), new BoundedQueue(1000),"")); PointToPointPerfTestWithInt(new ThreadFiber(new PerfExecutor(), new TimerScheduler(), new BoundedQueue(1000), "")); PointToPointPerfTestWithObject(new ThreadFiber(new PerfExecutor(), new TimerScheduler(), new BoundedQueue(1000), "")); } [Test] [Explicit] public void TestBusyWait() { PointToPointPerfTestWithStruct(new ThreadFiber(new PerfExecutor(), new TimerScheduler(), new BusyWaitQueue(1000,25), "")); PointToPointPerfTestWithInt(new ThreadFiber(new PerfExecutor(), new TimerScheduler(), new BusyWaitQueue(1000, 25), "")); PointToPointPerfTestWithObject(new ThreadFiber(new PerfExecutor(), new TimerScheduler(), new BusyWaitQueue(1000, 25), "")); } [Test] [Explicit] public void TestDefault() { PointToPointPerfTestWithStruct(new ThreadFiber(new PerfExecutor())); PointToPointPerfTestWithInt(new ThreadFiber(new PerfExecutor())); PointToPointPerfTestWithObject(new ThreadFiber(new PerfExecutor())); } [Test] [Explicit] public void TestDefaultSleep() { PointToPointPerfTestWithStruct(new ThreadFiber(new PerfExecutor(), new SleepingQueue())); PointToPointPerfTestWithInt(new ThreadFiber(new PerfExecutor(), new SleepingQueue())); PointToPointPerfTestWithObject(new ThreadFiber(new PerfExecutor(), new SleepingQueue())); } [Test] [Explicit] public void TestDefaultYield() { PointToPointPerfTestWithStruct(new ThreadFiber(new PerfExecutor(), new YieldingQueue())); PointToPointPerfTestWithInt(new ThreadFiber(new PerfExecutor(), new YieldingQueue())); PointToPointPerfTestWithObject(new ThreadFiber(new PerfExecutor(), new YieldingQueue())); } [Test] [Explicit] public void TestPool() { PointToPointPerfTestWithStruct(new PoolFiber(new PerfExecutor())); PointToPointPerfTestWithInt(new PoolFiber(new PerfExecutor())); PointToPointPerfTestWithObject(new PoolFiber(new PerfExecutor())); } [Test] [Explicit] public void TestBlocking() { PointToPointPerfTestWithStruct(new ThreadFiber(new PerfExecutor(), new BlockingQueue())); PointToPointPerfTestWithInt(new ThreadFiber(new PerfExecutor(), new BlockingQueue())); PointToPointPerfTestWithObject(new ThreadFiber(new PerfExecutor(), new BlockingQueue())); } } }<file_sep>/Fibrous/Agents/IAgent.cs namespace Fibrous { using System; /// <summary> /// Actor like abstraction. Recieves a single type of message directly /// </summary> /// <typeparam name="T"></typeparam> public interface IAgent<T> : IPublisherPort<T>, IDisposable { } /// <summary> /// Agent using injected handler function. /// </summary> /// <typeparam name="T"></typeparam> public class Agent<T> : IAgent<T> { private readonly IPublisherPort<T> _channel; protected readonly IFiber Fiber; public Agent(Action<T> handler, FiberType type = FiberType.Pool) { Fiber = Fibrous.Fiber.StartNew(type); _channel = Fiber.NewPublishPort(handler); } public bool Publish(T msg) { return _channel.Publish(msg); } public void Dispose() { Fiber.Dispose(); } } }<file_sep>/Todo.txt - Clean up ctor/factory methods. Allow IQueue to be injected - update Xml docs - Add samples - Update latency tests for queues, use histogram to better see results - better Req/reply tests - re-look at Pool fiber and design/contention <file_sep>/Fibrous.Tests/QueueChannelTests.cs namespace Fibrous.Tests { using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using NUnit.Framework; [TestFixture] public class QueueChannelTests { [Test] public void Multiple() { var queues = new List<IFiber>(); int receiveCount = 0; using (var reset = new AutoResetEvent(false)) { var channel = new QueueChannel<int>(); const int MessageCount = 100; var updateLock = new object(); for (int i = 0; i < 5; i++) { Action<int> onReceive = delegate { Thread.Sleep(15); lock (updateLock) { receiveCount++; if (receiveCount == MessageCount) reset.Set(); } }; IFiber fiber = PoolFiber.StartNew(); queues.Add(fiber); channel.Subscribe(fiber, onReceive); } for (int i = 0; i < MessageCount; i++) channel.Publish(i); Assert.IsTrue(reset.WaitOne(10000, false)); queues.ForEach(q => q.Dispose()); } } [Test] public void SingleConsumer() { int oneConsumed = 0; using (IFiber one = PoolFiber.StartNew()) using (var reset = new AutoResetEvent(false)) { var channel = new QueueChannel<int>(); Action<int> onMsg = obj => { oneConsumed++; if (oneConsumed == 20) reset.Set(); }; channel.Subscribe(one, onMsg); for (int i = 0; i < 20; i++) channel.Publish(i); Assert.IsTrue(reset.WaitOne(10000, false)); } } [Test] public void SingleConsumerWithException() { var failed = new List<Exception>(); var exec = new ExceptionHandlingExecutor(failed.Add); using (IFiber one = PoolFiber.StartNew(exec)) using (var reset = new AutoResetEvent(false)) { var channel = new QueueChannel<int>(); Action<int> onMsg = num => { if (num == 0) throw new Exception(); reset.Set(); }; channel.Subscribe(one, onMsg); channel.Publish(0); channel.Publish(1); Assert.IsTrue(reset.WaitOne(10000, false)); Assert.AreEqual(1, failed.Count); } } [Test] public void MultiConsumer() { var queues = new List<FiberBase>(); IChannel<string> channel = new QueueChannel<string>(); //Init executing Fibers for (int i = 0; i < 5; i++) { Action<string> onReceive = (message) => { var firstChar = message[0]; }; FiberBase threadFiber = new ThreadFiber(new Executor(),new TimerScheduler(),new SleepingQueue() , i.ToString());//new DisruptorQueue(1024*1024) queues.Add(threadFiber); channel.Subscribe(threadFiber, onReceive); } Stopwatch sw = new Stopwatch(); sw.Start(); //Push messages for (int i = 0; i < 1000000; i++) { string msg = "[" + i + "] Push"; channel.Publish(msg); } sw.Stop(); Console.WriteLine("End : " + sw.ElapsedMilliseconds); // Console.ReadLine(); //#Results: //1 ThreadFiber ~= 1sec //2 ThreadFiber ~=> 3sec //3 ThreadFiber ~=> 5sec //4 ThreadFiber ~=> 8sec //5 ThreadFiber ~=> 10sec } [Test] public void MultiConsumerYielding() { var queues = new List<FiberBase>(); IChannel<string> channel = new QueueChannel<string>(); int o = 0; //Init executing Fibers for (int i = 0; i < 5; i++) { Action<string> onReceive = (message) => { var firstChar = message[0]; if (firstChar == firstChar) o++; }; FiberBase threadFiber = new ThreadFiber(new Executor(), new TimerScheduler(), new YieldingQueue(), i.ToString());//new DisruptorQueue(1024*1024) queues.Add(threadFiber); channel.Subscribe(threadFiber, onReceive); } Stopwatch sw = new Stopwatch(); sw.Start(); //Push messages for (int i = 0; i < 1000000; i++) { string msg = "[" + i + "] Push"; channel.Publish(msg); } sw.Stop(); Console.WriteLine("End : " + sw.ElapsedMilliseconds); // Console.ReadLine(); //#Results: //1 ThreadFiber ~= 1sec //2 ThreadFiber ~=> 3sec //3 ThreadFiber ~=> 5sec //4 ThreadFiber ~=> 8sec //5 ThreadFiber ~=> 10sec } [Test] public void MultiConsumerPool() { var queues = new List<IFiber>(); IChannel<string> channel = new QueueChannel<string>(); //Init executing Fibers for (int i = 0; i < 5; i++) { Action<string> onReceive = (message) => { var firstChar = message[0]; //Console.WriteLine("[{0}] {1}", Thread.CurrentThread.ManagedThreadId, message); }; IFiber threadFiber = PoolFiber.StartNew();//new ThreadFiber(new Executor(),new TimerScheduler(),new YieldingQueue() , i.ToString());//new DisruptorQueue(1024*1024) queues.Add(threadFiber); channel.Subscribe(threadFiber, onReceive); } Stopwatch sw = new Stopwatch(); sw.Start(); //Push messages for (int i = 0; i < 1000000; i++) { string msg = "[" + i + "] Push"; channel.Publish(msg); } sw.Stop(); Console.WriteLine("End : " + sw.ElapsedMilliseconds); //#Results: //1 ThreadFiber ~= 1sec //2 ThreadFiber ~=> 3sec //3 ThreadFiber ~=> 5sec //4 ThreadFiber ~=> 8sec //5 ThreadFiber ~=> 10sec } } }<file_sep>/Fibrous/Channels/QueueChannel.cs namespace Fibrous { using System; using System.Collections.Generic; /// <summary> /// Queue channel where a message is consumed by only one consumer. /// </summary> /// <typeparam name="TMsg"></typeparam> public sealed class QueueChannel<TMsg> : IChannel<TMsg> { private readonly object _lock = new object(); private readonly Queue<TMsg> _queue = new Queue<TMsg>(); private int Count { get { lock (_lock) { return _queue.Count; } } } public IDisposable Subscribe(IFiber fiber, Action<TMsg> onMessage) { return new QueueConsumer(fiber, onMessage, this); } public bool Publish(TMsg message) { lock (_lock) { _queue.Enqueue(message); } Action onSignal = SignalEvent; if (onSignal != null) { onSignal(); return true; } return false; } internal event Action SignalEvent; private bool Pop(out TMsg msg) { lock (_lock) { if (_queue.Count > 0) { msg = _queue.Dequeue(); return true; } } msg = default(TMsg); return false; } private sealed class QueueConsumer : IDisposable { private readonly object _lock = new object(); private readonly Action<TMsg> _callback; private readonly QueueChannel<TMsg> _eventChannel; private readonly IExecutionContext _target; private bool _flushPending; public QueueConsumer(IExecutionContext target, Action<TMsg> callback, QueueChannel<TMsg> eventChannel) { _target = target; _callback = callback; _eventChannel = eventChannel; _eventChannel.SignalEvent += Signal; } public void Dispose() { _eventChannel.SignalEvent -= Signal; } private void Signal() { lock (_lock) { if (_flushPending) return; _target.Enqueue(ConsumeNext); _flushPending = true; } } private void ConsumeNext() { try { TMsg msg; if (_eventChannel.Pop(out msg)) _callback(msg); } finally { lock (_lock) { if (_eventChannel.Count == 0) _flushPending = false; else _target.Enqueue(ConsumeNext); } } } } public void Dispose() { _queue.Clear(); } } }<file_sep>/Fibrous/Channels/IChannel.cs namespace Fibrous { using System; /// <summary> /// IChannels are in-memory conduits for messages /// </summary> /// <typeparam name="T"></typeparam> public interface IChannel<T> : IPublisherPort<T>, ISubscriberPort<T> { } public sealed class Channel<T> : IChannel<T> { private readonly Event<T> _internalChannel = new Event<T>(); public bool Publish(T msg) { return _internalChannel.Publish(msg); } public IDisposable Subscribe(IFiber fiber, Action<T> receive) { IDisposable disposable = _internalChannel.Subscribe(Receive(fiber, receive)); return new Unsubscriber(disposable, fiber); } private static Action<T> Receive(IExecutionContext fiber, Action<T> receive) { return msg => fiber.Enqueue(() => receive(msg)); } } }<file_sep>/Fibrous/IFiber.cs namespace Fibrous { using System; /// <summary> /// Fibers are execution contexts that use Threads or ThreadPools for work handlers /// </summary> public interface IFiber : IExecutionContext, IScheduler, IDisposableRegistry { /// <summary> /// Start the fiber's queue /// </summary> /// <returns></returns> void Start(); /// <summary> /// Stop the fiber /// </summary> void Stop(); } public interface IExecutionContext { /// <summary> /// Enqueue an Action to be executed /// </summary> /// <param name="action"></param> void Enqueue(Action action); } public interface IScheduler { /// <summary> /// Schedule an action to be executed once /// </summary> /// <param name="action"></param> /// <param name="dueTime"></param> /// <returns></returns> IDisposable Schedule(Action action, TimeSpan dueTime); /// <summary> /// Schedule an action to be taken repeatedly /// </summary> /// <param name="action"></param> /// <param name="startTime"></param> /// <param name="interval"></param> /// <returns></returns> IDisposable Schedule(Action action, TimeSpan startTime, TimeSpan interval); } public static class SchedulerExtensions { /// <summary> /// Schedule an action at a DateTime /// </summary> /// <param name="scheduler"></param> /// <param name="action"></param> /// <param name="when"></param> /// <returns></returns> public static IDisposable Schedule(this IScheduler scheduler, Action action, DateTime when) { return scheduler.Schedule(action, when - DateTime.Now); } /// <summary> /// Schedule an action at a DateTime with an interval /// </summary> /// <param name="scheduler"></param> /// <param name="action"></param> /// <param name="when"></param> /// <param name="interval"></param> /// <returns></returns> public static IDisposable Schedule(this IScheduler scheduler, Action action, DateTime when, TimeSpan interval) { return scheduler.Schedule(action, when - DateTime.Now, interval); } } /// <summary> /// Collection of disposables, where they can be removed or Disposed together. /// Mostly for internal use, but very convenient for grouping and handling disposables /// </summary> public interface IDisposableRegistry : IDisposable { /// <summary> /// Add an IDisposable to the registry. It will be disposed when the registry is disposed. /// </summary> /// <param name="toAdd"></param> void Add(IDisposable toAdd); /// <summary> /// Remove a disposable from the registry. It will not be disposed when the registry is disposed. /// </summary> /// <param name="toRemove"></param> void Remove(IDisposable toRemove); } }<file_sep>/Fibrous/Channels/Result.cs namespace Fibrous { public struct Result<T> : IResult<T> { public Result(T value) : this() { Value = value; IsValid = true; } public bool IsValid { get; private set; } public T Value { get; private set; } } }
4b1b5ecb097172866715b98269b0cdf548325500
[ "C#", "Text" ]
14
C#
trymnilsen/Fibrous
44055db77bdd737602d0a68c51cbbdead9128274
c34439178750460982ccac4422881b417e4a3b9f
refs/heads/master
<repo_name>tranqui793/Teaching-HEIGVD-RES-2018-Labo-DockerMusic<file_sep>/docker/image-musician/src/musician.js var dgram = require('dgram'); var uuid = require('uuid'); var clientudp = dgram.createSocket('udp4'); function Musician(instrument) { this.instrument = instrument; var data = { uuid: uuid(), instrument: instrument } Musician.prototype.update = function () { data.activeSince = new Date().toISOString(); var payload = JSON.stringify(data,null,'\t'); message = new Buffer(payload); clientudp.send(message, 0, message.length, 12345, '172.16.58.3', function (err, bytes) { console.log("Sending payload: " + payload); }); } setInterval(this.update.bind(this), 1000); } var instrument = process.argv[2]; var m1 = new Musician(instrument);
1fba4b788c5118481cfd5484ed92e67f992f7428
[ "JavaScript" ]
1
JavaScript
tranqui793/Teaching-HEIGVD-RES-2018-Labo-DockerMusic
1494352152b2a7133fd8a2b4e246d4e45e6c0e7e
163c3f76df6bfcb63e1797325563f7f157c8f89d
refs/heads/master
<file_sep>package pe.com.jdmm21.app.model2; import lombok.Data; @Data public class TemporalList { private String idCountry; private String columnaCountry1; } <file_sep>package pe.com.jdmm21.app.model2; import lombok.Data; @Data public class ClaseTemporal { private String columnaTemp1; private String columnaTemp2; } <file_sep>package pe.com.jdmm21.app.model2; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import javax.persistence.Column; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import lombok.Data; @Data public class CountryTemp { private String countryId; private String columna1; private String columna2; @JoinTable( name = "temporalSet", joinColumns = @JoinColumn(name="countryId")) @Column(name = "columnaCountry1") private Set temporalSet = new TreeSet(); } <file_sep>package pe.com.jdmm21.app.service; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import lombok.extern.slf4j.Slf4j; import pe.com.jdmm21.app.dao.CountryDao; import pe.com.jdmm21.app.model.Country; @Service @Slf4j public class CountryService { @Autowired CountryDao countryDao; public Page<Country> findPaginated(Pageable pageable){ int pageSize = pageable.getPageSize(); int currentPage = pageable.getPageNumber(); int startItem = currentPage*pageSize; log.info("pageSize: {}",pageSize); log.info("currentPage: {}",currentPage); log.info("startItem: {}",startItem); List<Country> list; Map<String , Object> params = new HashMap<>(); List<Country> countries = countryDao.getAllCountries(params); if(countries.size()<startItem) { list = Collections.emptyList(); }else { int toIndex = Math.min(startItem+pageSize,countries.size()); list = countries.subList(startItem, toIndex); } Page<Country> countryPage = new PageImpl<Country>(list,PageRequest.of(currentPage, pageSize),countries.size()); return countryPage; } } <file_sep>package pe.com.jdmm21.app.test; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import pe.com.jdmm21.app.AppConfiguration; import pe.com.jdmm21.app.dao.CountryDaoImpl; @RunWith(SpringRunner.class) @SpringJUnitWebConfig(classes = {AppConfiguration.class}) public class CountryControllerTest { @Autowired CountryDaoImpl countryDao; @Autowired NamedParameterJdbcTemplate jdbcTemplate; @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void before() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); countryDao.setJdbcTemplate(jdbcTemplate); } @Test public void testGetCountries() throws Exception { this.mockMvc.perform(get("/api/countries") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } } <file_sep>package pe.com.jdmm21.app.dao; import java.util.List; import java.util.Map; import pe.com.jdmm21.app.model.Country; public interface CountryDao { public List<Country> getAllCountries(Map<String, Object> params); public int getCountriesCount(Map<String, Object> params); } <file_sep>package pe.com.jdmm21.app.dao; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import org.springframework.util.StringUtils; import lombok.extern.slf4j.Slf4j; import pe.com.jdmm21.app.dao.mapper.CountryRowMapper; import pe.com.jdmm21.app.model.Country; @Repository @Slf4j public class CountryDaoImpl implements CountryDao{ @Autowired NamedParameterJdbcTemplate jdbcTemplate; private static final Integer PAGE_SIZE = 10; public void setJdbcTemplate(NamedParameterJdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public List<Country> getAllCountries(Map<String, Object> params) { log.info("Inicio de getAllCountries: {}",params); int pageNo =1; if(params.containsKey("pageNo")) { pageNo = Integer.parseInt(params.get("pageNo").toString()); log.info("paginacion: {}",pageNo); } Integer offset =(pageNo-1)*PAGE_SIZE; log.info("offset: {}",offset); params.put("offset", offset); params.put("size", PAGE_SIZE); String queryString = SELECT_CLAUSE +" WHERE 1=1 " + (!StringUtils.isEmpty(params.get("search"))?SEARCH_WHERE_CLAUSE:"") + (!StringUtils.isEmpty(params.get("continent"))?CONTINENT_WHERE_CLAUSE:"") + (!StringUtils.isEmpty(params.get("region"))?REGION_WHERE_CLAUSE:""); //+ PAGINATION_CLAUSE; return jdbcTemplate.query(queryString, params, new CountryRowMapper()); } public static final String SELECT_CLAUSE = "SELECT" + " c.Code, c.Name, c.Continent,c.region" + ",c.SurfaceArea surface_area, c.IndepYear indep_year,c.population" + ",lifeExpectancy life_expectancy, c.GNP, c.LocalName local_name" + " ,c.GovernmentForm government_form, c.HeadOfState head_of_state" + " ,c.code2, c.capital, cy.name capital_name" + " FROM country c" + " LEFT OUTER JOIN city cy ON cy.id = c.capital"; @Override public int getCountriesCount(Map<String, Object> params) { log.info("params: {}",params); return jdbcTemplate.queryForObject( "SELECT COUNT(*) FROM country c WHERE 1=1 " + (!StringUtils.isEmpty(params.get("search"))?SEARCH_WHERE_CLAUSE:"") + (!StringUtils.isEmpty(params.get("continent"))?CONTINENT_WHERE_CLAUSE:"") + (!StringUtils.isEmpty(params.get("region"))?REGION_WHERE_CLAUSE:"") , params, Integer.class); } public static final String SEARCH_WHERE_CLAUSE= "AND (LOWER(c.name) LIKE CONCAT('%', LOWER(:search),'%' ))"; public static final String CONTINENT_WHERE_CLAUSE= " AND c.continent = :continent"; public static final String REGION_WHERE_CLAUSE= " AND c.region = :region"; public static final String PAGINATION_CLAUSE = "ORDER BY c.code LIMIT :size OFFSET :offset"; } <file_sep>jdbc.url=jdbc:mysql://localhost:3306/worldgdp datasource.user=root datsource.password=<PASSWORD> datasource.classname=com.mysql.jdbc.Driver <file_sep>package pe.com.jdmm21.app.controller.view; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import lombok.extern.slf4j.Slf4j; import pe.com.jdmm21.app.dao.CountryDao; import pe.com.jdmm21.app.model.Country; import pe.com.jdmm21.app.service.CountryService; @Controller @RequestMapping("/") @Slf4j public class ViewController { @Autowired CountryDao countryDao; @Autowired CountryService countrySevice; @GetMapping({"/countries","/"}) public String countries(Model model, @RequestParam Map<String, Object> params, @RequestParam("page") Optional<Integer> page, @RequestParam("size") Optional<Integer> size) { int currentPage = page.orElse(1); int pageSize = size.orElse(20); log.info("currentPage: {}",currentPage); log.info("pageSize: {}",pageSize); Page<Country> countryPage = countrySevice.findPaginated(PageRequest.of(currentPage-1, pageSize)); // model.addAttribute("countries", countryDao.getAllCountries(params)); model.addAttribute("countries", countryPage); int totalPages = countryPage.getTotalPages(); if(totalPages>0) { List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages) .boxed() .collect(Collectors.toList()); model.addAttribute("pageNumbers", pageNumbers); } // int count = countryDao.getCountriesCount(params); // log.info("count: {}",count); // model.addAttribute("count", count); // log.info("fin de ejecucion de metodo"); return "countries"; } }
dfaacc845f53d766dda7424fbca66a42ba59061a
[ "Java", "INI" ]
9
Java
juandiego9221/worldgdpv2
058f0b310b218b0b851a682481166ed301d3063f
45b9e25f865f03af42031995968e2a63fa9347ce
refs/heads/master
<file_sep>package com.baobang.piospa.controller.admin; import java.security.Principal; import java.util.Collections; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.baobang.piospa.entities.Service; import com.baobang.piospa.entities.ServiceTime; import com.baobang.piospa.entities.Staff; import com.baobang.piospa.repositories.ServiceRepository; import com.baobang.piospa.repositories.ServiceTimeRepository; import com.baobang.piospa.repositories.StaffRepository; import com.baobang.piospa.utils.Utils; /** * @author BaoBang * @Created Jul 18, 2018 * */ @Controller public class ServiceAdminController { @Autowired ServiceRepository mServiceRepository; @Autowired ServiceTimeRepository mServiceTimeRepository;; @Autowired StaffRepository mStaffRepository; @Transactional @ResponseBody @RequestMapping(value = "admin/remove-service", method = RequestMethod.GET) public String removeServicePackage(@RequestParam(name = "product_id", required = true) int productId) { System.out.println("## AJAX reomve from csdl: " + productId); Service product = mServiceRepository.findById(productId).get(); if (product != null) { try { mServiceRepository.deleteById(productId); } catch (Exception e) { return "false"; } } else { return "false"; } return "true"; } @RequestMapping(value = "admin/service", method = RequestMethod.GET) public String productList(Model model) { List<Service> liProducts = mServiceRepository.findAll(); Collections.reverse(liProducts); model.addAttribute("result", liProducts); return "service"; } @RequestMapping(value = "admin/edit-service/{id}") public String orderDetail(Model model, HttpServletRequest request, Principal principal, @PathVariable("id") int id, @RequestParam(required = true, name = "productname", defaultValue = "") String productName, @RequestParam(required = true, name = "productimage", defaultValue = "") String productImage, @RequestParam(required = true, name = "timeId", defaultValue = "1") int timeId, @RequestParam(required = true, name = "productdescription", defaultValue = "") String productDescription, @RequestParam(required = true, name = "post_status", defaultValue = "1") int post_status) { Service product = mServiceRepository.findById(id).get(); model.addAttribute("title", "CẬP NHẬT DỊCH VỤ"); String message = ""; if (request.getParameter("submit") != null) { ServiceTime time = mServiceTimeRepository.findById(timeId).get(); product.setServiceName(productName); product.setImage(productImage); product.setDescription(productDescription); product.setIsActive((byte) post_status); product.setServiceTime(time); try { mServiceRepository.save(product); model.addAttribute("result", "update"); } catch (Exception e) { message = e.getMessage(); } } loadAttribute(model, product.getServiceId(), product.getServiceName(), product.getImage(), product.getServiceTime().getServiceTimeId(), product.getDescription(), product.getIsActive()); loadData(model); model.addAttribute("message", message); return "add-service"; } @RequestMapping(value = "admin/add-service") public String addProduct(Model model, HttpServletRequest request,Principal principal, @RequestParam(required = true, name = "productid", defaultValue = "0") int productId, @RequestParam(required = true, name = "productname", defaultValue = "") String productName, @RequestParam(required = true, name = "productimage", defaultValue = "") String productImage, @RequestParam(required = true, name = "timeId", defaultValue = "1") int timeId, @RequestParam(required = true, name = "productdescription", defaultValue = "") String productDescription, @RequestParam(required = true, name = "post_status", defaultValue = "1") int post_status) { String message = ""; model.addAttribute("title", "THÊM DỊCH VỤ"); if (request.getParameter("submit") != null) { if(productImage.trim().length() == 0) { message = "Vui lòng chọn ảnh, và upload ảnh"; loadAttribute(model, productId, productName, productImage, timeId, productDescription, post_status); }else { Service product; product = new Service(); ServiceTime time = mServiceTimeRepository.findById(timeId).get(); product.setServiceName(productName); product.setImage(productImage); product.setDescription(productDescription); product.setIsActive((byte) post_status); product.setServiceTime(time); try { mServiceRepository.save(product); model.addAttribute("result", "create"); loadAttribute(model, 0, "", "", 0, "", 0); } catch (Exception e) { message = e.getMessage(); loadAttribute(model, productId, productName, productImage, timeId, productDescription, post_status); } } } loadData(model); model.addAttribute("message", message); return "add-service"; } private void loadData(Model model) { List<ServiceTime> times = mServiceTimeRepository.findAll(); model.addAttribute("times", times); } private void loadAttribute(Model model, int productId, String productName, String productImage, int timeId, String productDescription, int postStaus) { model.addAttribute("productid", productId); model.addAttribute("productname", productName); model.addAttribute("productimage", productImage); model.addAttribute("productdescription", productDescription); model.addAttribute("timeId", timeId); model.addAttribute("post_status", postStaus); } } <file_sep>package com.baobang.piospa.controller.admin; import java.security.Principal; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.User; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.baobang.piospa.entities.Staff; import com.baobang.piospa.repositories.StaffRepository; import com.baobang.piospa.utils.Utils; import java.util.Optional; /** * @author BaoBang * @Created Jul 16, 2018 * */ @Controller public class StaffAdminController { @Autowired StaffRepository mStaffRepository; @RequestMapping(value = "admin/members", method = RequestMethod.GET) public String productList(Model model) { List<Staff> staffs = mStaffRepository.findAll(); Collections.reverse(staffs); model.addAttribute("result", staffs); return "member-list"; } @RequestMapping(value = "admin/profile/{id}", method = RequestMethod.GET) public String productList(Model model, @PathVariable("id") int id) { Staff staff = mStaffRepository.findById(id).get(); model.addAttribute("account", staff); return "profile"; } @RequestMapping(value = "admin/profile/{id}", method = RequestMethod.POST) public String updateInfo(Model model, @PathVariable("id") int id,Principal principal, @RequestParam(required = true, name = "account_name") String fullName, @RequestParam(required = true, name = "account_phone") String phone, @RequestParam(required = false, name = "account_avatar", defaultValue = "") String avatar, @RequestParam(required = false, name = "account_role") int role) { Optional<Staff> staffOptional = mStaffRepository.findById(id); Staff staff; if(staffOptional == null) { return "redirect:/403"; }else { staff = staffOptional.get(); staff.setFullname(fullName); staff.setPhone(phone); staff.setIsAdmin((byte)role); if(avatar.length() > 0) { staff.setStaffAvatar(avatar); } try { mStaffRepository.save(staff); model.addAttribute("result", true); }catch (Exception e) { model.addAttribute("result", false); } } model.addAttribute("account", staff); return "profile"; } @RequestMapping(value = "admin/profile/{id}/reset-password", method = RequestMethod.POST) public String resetPassword(Model model, @PathVariable("id") int id,Principal principal, @RequestParam(required = true, name = "current_password") String currentPassword, @RequestParam(required = true, name = "new_password") String newPassword, @RequestParam(required = true, name = "confirm_password") String confirmPassword) { Staff staff = mStaffRepository.findById(id).get(); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); if (staff == null) { return "admin/403"; } else { Map<String, String> errors_password = new HashMap<String, String>(); if (currentPassword == null || currentPassword.length() <= 0) errors_password.put("current_password", "<PASSWORD>!"); if (newPassword == null || newPassword.length() <= 0) errors_password.put("new_password", "<PASSWORD>!"); if (confirmPassword == null || confirmPassword.length() <= 0) errors_password.put("confirm_password", "<PASSWORD> không được bỏ trống!"); String passwordHash = encoder.encode(currentPassword); if (passwordHash.equals(staff.getPassword())) { errors_password.put("current_password", "<PASSWORD>!"); } else if (!newPassword.equals(confirmPassword)) { errors_password.put("confirm_password", "<PASSWORD> m<PASSWORD> không chính xác!"); } if (!errors_password.isEmpty()) { model.addAttribute("result_reset_password", false); } else { String hashPassword = encoder.encode(newPassword); staff.setPassword(<PASSWORD>); mStaffRepository.save(staff); model.addAttribute("result_reset_password", true); } model.addAttribute("message", ""); model.addAttribute("account", staff); } return "profile"; } @RequestMapping(value="admin/add-new-account", method=RequestMethod.GET) public String addNewAccount(Model model) { model.addAttribute("account_status", "1"); return "add-new-account"; } @RequestMapping(value="admin/add-new-account", method=RequestMethod.POST) public String doAddNewAccount( Model model,Principal principal, @RequestParam(required=true, name="account_user_name", defaultValue= "") String userName, @RequestParam(required=true, name="account_fullname", defaultValue= "") String fullname, @RequestParam(required=false, name="account_role") int role, @RequestParam(required=true, name="account_password", defaultValue= "") String password, @RequestParam(required=true, name="account_confirm_password", defaultValue= "") String confirmPassword, @RequestParam(required=false, name="post_status") int status, @RequestParam(required=false, name="account_avatar", defaultValue= "") String avatar) { BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); String passwordHash = encoder.encode(password); Staff account = mStaffRepository.findByUsername(userName); if(account != null) { model.addAttribute("message", "Tài khoản đã tồn tại"); model.addAttribute("account", account); return "add-new-account"; } try { account = new Staff(); account.setFullname(fullname); account.setAccount(userName); account.setStaffAvatar(avatar); account.setIsAdmin((byte)role); account.setPassword(<PASSWORD>); if(!password.equals(confirmPassword)) { model.addAttribute("message", "Mật khẩu xác nhận không đúng"); model.addAttribute("account", account); return "add-new-account"; } mStaffRepository.save(account); return "redirect:/admin/members"; }catch(Exception e){ } model.addAttribute("account", account); return "add-new-account"; } @RequestMapping(value = "admin/delete-account", method=RequestMethod.POST) public String deleteAccount(@RequestParam (required = true, name = "id_account") int idAccount) { Optional<Staff> account = mStaffRepository.findById(idAccount); if (account != null) { mStaffRepository.delete(account.get()); } return "redirect:/admin/members"; } } <file_sep>package com.baobang.piospa.entities; import java.io.Serializable; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Date; import java.util.List; /** * The persistent class for the services database table. * */ @Entity @Table(name="services") @NamedQuery(name="Service.findAll", query="SELECT s FROM Service s") public class Service implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="service_id") private int serviceId; private String description; private String image; @Column(name="is_active") private byte isActive; @Column(name="service_name") private String serviceName; //bi-directional many-to-many association to ServicePackage @JsonIgnore @ManyToMany(mappedBy="services") private List<ServicePackage> servicePackages; //bi-directional many-to-one association to ServicePackageDetail @JsonIgnore @OneToMany(mappedBy="service") private List<ServicePackageDetail> servicePackageDetails; //bi-directional many-to-one association to ServicePrice @JsonIgnore @OneToMany(mappedBy="service") private List<ServicePrice> servicePrices; //bi-directional many-to-one association to ServiceTime @ManyToOne @JoinColumn(name="service_time_id") private ServiceTime serviceTime; public Service() { } public int getServiceId() { return this.serviceId; } public void setServiceId(int serviceId) { this.serviceId = serviceId; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getImage() { return this.image; } public void setImage(String image) { this.image = image; } public byte getIsActive() { return this.isActive; } public void setIsActive(byte isActive) { this.isActive = isActive; } public String getServiceName() { return this.serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public List<ServicePackage> getServicePackages() { return this.servicePackages; } public void setServicePackages(List<ServicePackage> servicePackages) { this.servicePackages = servicePackages; } public List<ServicePackageDetail> getServicePackageDetails() { return this.servicePackageDetails; } public void setServicePackageDetails(List<ServicePackageDetail> servicePackageDetails) { this.servicePackageDetails = servicePackageDetails; } public ServicePackageDetail addServicePackageDetail(ServicePackageDetail servicePackageDetail) { getServicePackageDetails().add(servicePackageDetail); servicePackageDetail.setService(this); return servicePackageDetail; } public ServicePackageDetail removeServicePackageDetail(ServicePackageDetail servicePackageDetail) { getServicePackageDetails().remove(servicePackageDetail); servicePackageDetail.setService(null); return servicePackageDetail; } public List<ServicePrice> getServicePrices() { return this.servicePrices; } public void setServicePrices(List<ServicePrice> servicePrices) { this.servicePrices = servicePrices; } public ServicePrice addServicePrice(ServicePrice servicePrice) { getServicePrices().add(servicePrice); servicePrice.setService(this); return servicePrice; } public ServicePrice removeServicePrice(ServicePrice servicePrice) { getServicePrices().remove(servicePrice); servicePrice.setService(null); return servicePrice; } public ServiceTime getServiceTime() { return this.serviceTime; } public void setServiceTime(ServiceTime serviceTime) { this.serviceTime = serviceTime; } }<file_sep>package com.baobang.piospa.entities; import java.io.Serializable; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Date; import java.util.List; /** * The persistent class for the product_label database table. * */ @Entity @Table(name="product_label") @NamedQuery(name="ProductLabel.findAll", query="SELECT p FROM ProductLabel p") public class ProductLabel implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="product_label_id") private int productLabelId; @Column(name="is_active") private byte isActive; @Column(name="product_label_name") private String productLabelName; //bi-directional many-to-one association to Product @JsonIgnore @OneToMany(mappedBy="productLabel") private List<Product> products; public ProductLabel() { } public int getProductLabelId() { return this.productLabelId; } public void setProductLabelId(int productLabelId) { this.productLabelId = productLabelId; } public byte getIsActive() { return this.isActive; } public void setIsActive(byte isActive) { this.isActive = isActive; } public String getProductLabelName() { return this.productLabelName; } public void setProductLabelName(String productLabelName) { this.productLabelName = productLabelName; } public List<Product> getProducts() { return this.products; } public void setProducts(List<Product> products) { this.products = products; } public Product addProduct(Product product) { getProducts().add(product); product.setProductLabel(this); return product; } public Product removeProduct(Product product) { getProducts().remove(product); product.setProductLabel(null); return product; } }<file_sep>package com.baobang.piospa.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.baobang.piospa.entities.ServicePackageDetail; /** * @author BaoBang * @Created Jul 20, 2018 * */ @Repository public interface ServicePackageDetailRepository extends JpaRepository<ServicePackageDetail, Integer>{ } <file_sep>package com.baobang.piospa.controller.api; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.baobang.piospa.entities.OrderStatus; import com.baobang.piospa.model.DataResult; import com.baobang.piospa.repositories.OrderStatusRepository; import com.baobang.piospa.utils.MessageResponse; import com.baobang.piospa.utils.RequestPath; import io.swagger.annotations.ApiOperation; /** * @author BaoBang * @Created Apr 25, 2018 * */ @RestController @RequestMapping(RequestPath.ORDER_STATUS_PATH) public class OrderStatusController { @Autowired OrderStatusRepository mOrderStatusRepository; /** * @api {get} / Request OrderStatus information * @apiName getAll * @apiGroup Order * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {array} the list Order Status * */ @RequestMapping(// method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get all Order Status") public DataResult<List<OrderStatus>> getAll() { List<OrderStatus> OrderStatuss = mOrderStatusRepository.findAll(); return new DataResult<List<OrderStatus>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, OrderStatuss); } /** * @api {get} /{orderStatusId} Request Order Status information * @apiName getOrderStatusById * @apiGroup Order * * @apiParam {orderStatusId} id Order Status unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {OrderStatus} the Order Status was got * */ @RequestMapping(// value = "/{orderStatusId}", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get OrderStatus by id") public DataResult<OrderStatus> getOrderStatusById(@PathVariable(value = "orderStatusId") int orderStatusId) { DataResult<OrderStatus> result = new DataResult<>(); OrderStatus OrderStatus = mOrderStatusRepository.findById(orderStatusId).get(); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(OrderStatus); return result; } /** * @api {post} / Create a new Product OrderStatus * @apiName createOrderStatus * @apiGroup Order * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {OrderStatus} the new Order Status was created * */ @RequestMapping(// value = { "", "/" }, // method = RequestMethod.POST, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Create a new OrderStatus") public DataResult<OrderStatus> createOrderStatus(@RequestBody OrderStatus orderStatus) { DataResult<OrderStatus> result = new DataResult<>(); Date date = new Date(); orderStatus.setOrderStatusId(0); orderStatus = mOrderStatusRepository.save(orderStatus); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(orderStatus); return result; } /** * @api {put}/{orderStatusId} update Order Status by id * @apiName updateOrderStatus * @apiGroup Order * * @apiParam {OrderStatusId} id Product OrderStatus unique ID. * @apiBody {OrderStatus} the info of user need to update * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {OrderStatus} the new Product OrderStatus was updated * */ @RequestMapping(// value = "/{orderStatusId}", // method = RequestMethod.PUT, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Update Order Status by id") public DataResult<OrderStatus> updateOrderStatus(@PathVariable(value = "orderStatusId") int orderStatusId, @RequestBody OrderStatus orderStatus) { DataResult<OrderStatus> result; Optional<OrderStatus> option = mOrderStatusRepository.findById(orderStatusId); OrderStatus newOrderStatus = option.get(); newOrderStatus.setOrderStatusName(orderStatus.getOrderStatusName()); newOrderStatus = mOrderStatusRepository.save(newOrderStatus); result = new DataResult<>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, newOrderStatus); return result; } /** * @api {delete}/{orderStatusId} delete Order Status by id * @apiName deleteOrderStatus * @apiGroup Orders * * @apiParam {orderStatusId} id Product Order Status unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {OrderStatus} the Product Order Status was deleted * * */ @RequestMapping(// value = "/{orderStatusId}", // method = RequestMethod.DELETE, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Delete Order Status by id") public DataResult<OrderStatus> deleteOrderStatus(@PathVariable(value = "orderStatusId") int orderStatusId) { DataResult<OrderStatus> dataResult = new DataResult<>(); OrderStatus orderStatus = mOrderStatusRepository.findById(orderStatusId).get(); mOrderStatusRepository.deleteById(orderStatusId); dataResult.setMessage(MessageResponse.SUCCESSED); dataResult.setStatusCode(HttpStatus.OK.value()); dataResult.setData(orderStatus); return dataResult; } } <file_sep>package com.baobang.piospa.controller.api; import java.util.Date; import java.util.List; import java.util.Optional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.baobang.piospa.entities.BookingDetail; import com.baobang.piospa.model.BookingDetailRequest; import com.baobang.piospa.model.DataResult; import com.baobang.piospa.repositories.BookingDetailRepository; import com.baobang.piospa.utils.MessageResponse; import com.baobang.piospa.utils.RequestPath; import io.swagger.annotations.ApiOperation; /** * @author BaoBang * @Created May 13, 2018 * */ @RestController @RequestMapping(RequestPath.BOOKING_DETAIL_PATH) public class BookingDetailController { @PersistenceContext private EntityManager em; @Autowired BookingDetailRepository mBookingDetailRepository; /** * @api {get} / Request BookingDetail information * @apiName getAll * @apiGroup BookingDetail * * @apiParam none * * @apiSuccess {Integer} the BookingDetail of the response * @apiSuccess {String} the message of the response * @apiSuccess {array} the list BookingDetails * */ @RequestMapping(// method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get all BookingDetails") public DataResult<List<BookingDetail>> getAll() { List<BookingDetail> BookingDetails = mBookingDetailRepository.findAll(); return new DataResult<List<BookingDetail>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, BookingDetails); } /** * @api {post} /date Request BookingDetail information * @apiName getBookingDetailByDateBooking * @apiGroup BookingDetail * * @apiBody {String} the date booking * * @apiSuccess {Integer} the BookingDetail of the response * @apiSuccess {String} the message of the response * @apiSuccess {array} the BookingDetails was got * */ @RequestMapping(// value = "/date", // method = RequestMethod.POST, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get BookingDetail by date booking") public DataResult<List<BookingDetail>> getBookingDetailưById(@RequestBody BookingDetailRequest bookingDetailRequest) { DataResult<List<BookingDetail>> result = new DataResult<>(); List<BookingDetail> details = mBookingDetailRepository.getBookingDetailByDateBooking(bookingDetailRequest.getDate()); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(details); return result; } /** * @api {get} /{BookingDetailId} Request BookingDetail information * @apiName getBookingDetailById * @apiGroup BookingDetail * * @apiParam {BookingDetailId} id BookingDetail DeliveryStatus unique ID. * * @apiSuccess {Integer} the BookingDetail of the response * @apiSuccess {String} the message of the response * @apiSuccess {BookingDetail} the BookingDetail was got * */ @RequestMapping(// value = "/{BookingDetailId}", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get BookingDetail by id") public DataResult<BookingDetail> getBookingDetailưById( @PathVariable(value = "BookingDetailId") int BookingDetailId) { DataResult<BookingDetail> result = new DataResult<>(); BookingDetail BookingDetail = mBookingDetailRepository.findById(BookingDetailId).get(); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(BookingDetail); return result; } /** * @api {post} / Create a new BookingDetail * @apiName createBookingDetail * @apiGroup BookingDetail * * @apiParam none * * @apiSuccess {Integer} the DeliveryStatus of the response * @apiSuccess {String} the message of the response * @apiSuccess {BookingDetail} the new BookingDetail DeliveryStatus was created * */ @RequestMapping(// value = { "", "/" }, // method = RequestMethod.POST, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Create a new BookingDetail") public DataResult<BookingDetail> createBookingDetail(@RequestBody BookingDetail bookingDetail) { DataResult<BookingDetail> result = new DataResult<>(); bookingDetail = mBookingDetailRepository.save(bookingDetail); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(bookingDetail); return result; } /** * @api {put}/{BookingDetailId} update BookingDetail by id * @apiName updateBookingDetail * @apiGroup BookingDetail * * @apiParam {BookingDetailId} id BookingDetail unique ID. * @apiBody {BookingDetail} the info of BookingDetail need to update * * @apiSuccess {Integer} the DeliveryStatus of the response * @apiSuccess {String} the message of the response * @apiSuccess {BookingDetail} the new BookingDetail was updated * */ @RequestMapping(// value = "/{bookingDetailId}", // method = RequestMethod.PUT, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Update BookingDetail by id") public DataResult<BookingDetail> updateBookingDetail(@PathVariable(value = "bookingDetailId") int bookingDetailId, @RequestBody BookingDetail bookingDetail) { DataResult<BookingDetail> result; Optional<BookingDetail> option = mBookingDetailRepository.findById(bookingDetailId); BookingDetail newBookingDetail = option.get(); newBookingDetail.setBooking(bookingDetail.getBooking()); newBookingDetail.setServicePrice(bookingDetail.getServicePrice()); newBookingDetail.setDateBooking(bookingDetail.getDateBooking()); newBookingDetail.setTimeStart(bookingDetail.getTimeStart()); newBookingDetail = mBookingDetailRepository.save(newBookingDetail); result = new DataResult<>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, newBookingDetail); return result; } /** * @api {delete}/{bookingDetailId} delete Booking Detail by id * @apiName deleteBooking * @apiGroup Product * * @apiParam {bookingDetailId} id Booking Detail unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Booking} the Booking Detail was deleted * * */ @RequestMapping(// value = "/{bookingDetailId}", // method = RequestMethod.DELETE, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Delete Booking Detail by id") public DataResult<BookingDetail> deleteBooking(@PathVariable(value = "bookingDetailId") int bookingDetailId) { DataResult<BookingDetail> dataResult = new DataResult<>(); BookingDetail bookingDetail = mBookingDetailRepository.findById(bookingDetailId).get(); mBookingDetailRepository.deleteById(bookingDetailId); dataResult.setMessage(MessageResponse.SUCCESSED); dataResult.setStatusCode(HttpStatus.OK.value()); dataResult.setData(bookingDetail); return dataResult; } } <file_sep>package com.baobang.piospa.entities; import java.io.Serializable; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Date; import java.util.List; /** * The persistent class for the customers database table. * */ @Entity @Table(name = "customers") @NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c") public class Customer implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "customer_id") private int customerId; private String account; private String address; @Temporal(TemporalType.TIMESTAMP) private Date birthday; @Column(name = "customer_avatar") private String customerAvatar; // bi-directional many-to-one association to District @ManyToOne @JoinColumn(name = "district_id") private District district; private String email; private String fullname; private String gender; @Column(name = "is_active") private byte isActive; private String password; private String phone; // bi-directional many-to-one association to Province @ManyToOne @JoinColumn(name = "provinces_id") private Province province; // bi-directional many-to-one association to Ward @ManyToOne @JoinColumn(name = "ward_id") private Ward ward; // bi-directional many-to-one association to Booking @JsonIgnore @OneToMany(mappedBy = "customer") private List<Booking> bookings; // bi-directional many-to-one association to Order @JsonIgnore @OneToMany(mappedBy = "customer") private List<Order> orders; public Customer() { } public int getCustomerId() { return this.customerId; } public void setCustomerId(int customerId) { this.customerId = customerId; } public String getAccount() { return this.account; } public void setAccount(String account) { this.account = account; } public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } public Date getBirthday() { return this.birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getCustomerAvatar() { return this.customerAvatar; } public void setCustomerAvatar(String customerAvatar) { this.customerAvatar = customerAvatar; } public District getDistrict() { return this.district; } public void setDistrict(District district) { this.district = district; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public String getFullname() { return this.fullname; } public void setFullname(String fullname) { this.fullname = fullname; } public String getGender() { return this.gender; } public void setGender(String gender) { this.gender = gender; } public byte getIsActive() { return this.isActive; } public void setIsActive(byte isActive) { this.isActive = isActive; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return this.phone; } public void setPhone(String phone) { this.phone = phone; } public Province getProvince() { return this.province; } public void setProvince(Province province) { this.province = province; } public Ward getWard() { return this.ward; } public void setWard(Ward ward) { this.ward = ward; } public List<Booking> getBookings() { return this.bookings; } public void setBookings(List<Booking> bookings) { this.bookings = bookings; } public Booking addBooking(Booking booking) { getBookings().add(booking); booking.setCustomer(this); return booking; } public Booking removeBooking(Booking booking) { getBookings().remove(booking); booking.setCustomer(null); return booking; } public List<Order> getOrders() { return this.orders; } public void setOrders(List<Order> orders) { this.orders = orders; } public Order addOrder(Order order) { getOrders().add(order); order.setCustomer(this); return order; } public Order removeOrder(Order order) { getOrders().remove(order); order.setCustomer(null); return order; } }<file_sep>package com.baobang.piospa.entities; import java.io.Serializable; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * The persistent class for the orders database table. * */ @Entity @Table(name = "orders") @NamedQuery(name = "Order.findAll", query = "SELECT o FROM Order o ORDER BY o.orderId DESC") public class Order implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "order_id") private int orderId; private String address; @Column(name = "address_delivery") private String addressDelivery; @Temporal(TemporalType.TIMESTAMP) @Column(name = "created_at") private Date createdAt; @Column(name = "delivery_cost") private int deliveryCost; private int discount; private String email; @Column(name = "full_name") private String fullName; private String phone; @Column(name = "sub_total") private int subTotal; private int total; @Temporal(TemporalType.TIMESTAMP) @Column(name = "updated_at") private Date updatedAt; // bi-directional many-to-one association to Booking @OneToOne(mappedBy = "order", cascade = CascadeType.ALL) private Booking booking; // bi-directional many-to-one association to OrderProduct @JsonIgnore @OneToMany(mappedBy = "order", cascade = CascadeType.ALL) private List<OrderProduct> orderProducts = new ArrayList<>(); // bi-directional many-to-one association to Customer @ManyToOne @JoinColumn(name = "customer_id") private Customer customer; // bi-directional many-to-one association to OrderDeliveryStatus @ManyToOne @JoinColumn(name = "order_delivery_status_id") private OrderDeliveryStatus orderDeliveryStatus; // bi-directional many-to-one association to OrderDeliveryType @ManyToOne @JoinColumn(name = "order_delivery_type_id") private OrderDeliveryType orderDeliveryType; // bi-directional many-to-one association to OrderPaymentType @ManyToOne @JoinColumn(name = "order_payment_type_id") private OrderPaymentType orderPaymentType; // bi-directional many-to-one association to OrderStatus @ManyToOne @JoinColumn(name = "order_status_id") private OrderStatus orderStatus; // bi-directional many-to-one association to Tax @ManyToOne @JoinColumn(name = "tax_id") private Tax tax; public Order() { } public int getOrderId() { return this.orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } public String getAddressDelivery() { return this.addressDelivery; } public void setAddressDelivery(String addressDelivery) { this.addressDelivery = addressDelivery; } public Date getCreatedAt() { return this.createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public int getDeliveryCost() { return this.deliveryCost; } public void setDeliveryCost(int deliveryCost) { this.deliveryCost = deliveryCost; } public int getDiscount() { return this.discount; } public void setDiscount(int discount) { this.discount = discount; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public int getSubTotal() { return this.subTotal; } public void setSubTotal(int subTotal) { this.subTotal = subTotal; } public int getTotal() { return this.total; } public void setTotal(int total) { this.total = total; } public Date getUpdatedAt() { return this.updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } public Booking getBooking() { return this.booking; } public void setBooking(Booking booking) { this.booking = booking; } public List<OrderProduct> getOrderProducts() { return this.orderProducts; } public void setOrderProducts(List<OrderProduct> orderProducts) { this.orderProducts = orderProducts; } public OrderProduct addOrderProduct(OrderProduct orderProduct) { getOrderProducts().add(orderProduct); orderProduct.setOrder(this); return orderProduct; } public OrderProduct removeOrderProduct(OrderProduct orderProduct) { getOrderProducts().remove(orderProduct); orderProduct.setOrder(null); return orderProduct; } public Customer getCustomer() { return this.customer; } public void setCustomer(Customer customer) { this.customer = customer; } public OrderDeliveryStatus getOrderDeliveryStatus() { return this.orderDeliveryStatus; } public void setOrderDeliveryStatus(OrderDeliveryStatus orderDeliveryStatus) { this.orderDeliveryStatus = orderDeliveryStatus; } public OrderDeliveryType getOrderDeliveryType() { return this.orderDeliveryType; } public void setOrderDeliveryType(OrderDeliveryType orderDeliveryType) { this.orderDeliveryType = orderDeliveryType; } public OrderPaymentType getOrderPaymentType() { return this.orderPaymentType; } public void setOrderPaymentType(OrderPaymentType orderPaymentType) { this.orderPaymentType = orderPaymentType; } public OrderStatus getOrderStatus() { return this.orderStatus; } public void setOrderStatus(OrderStatus orderStatus) { this.orderStatus = orderStatus; } public void caculate() { total = 0; for (OrderProduct orderProduct : orderProducts) { total += orderProduct.getTotal(); } if (booking != null) { total += booking.getTotal(); } int taxCost = 0; if(tax != null) { if(tax.getType().equals("percent")) { taxCost = total * tax.getValue() / 100; }else if(tax.getType().equals("money")) { taxCost = tax.getValue(); } } subTotal = total + deliveryCost - discount + taxCost; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Tax getTax() { return this.tax; } public void setTax(Tax tax) { this.tax = tax; } } <file_sep>package com.baobang.piospa.repositories; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.baobang.piospa.entities.Product; /** * @author BaoBang * @Created Apr 18, 2018 * */ @Repository public interface ProductRepository extends JpaRepository<Product, Integer> { @Query("select p from Product p where p.productGroup.productGroupId = :groupId and p.isActive = 1") public List<Product> findByGroupId(@Param("groupId") int groupId); @Query(value="SELECT * FROM products WHERE product_group_id = ?1 and is_active = 1 LIMIT 10", nativeQuery = true) public List<Product> findTopTenByGroupId(String groupId); } <file_sep>package com.baobang.piospa.controller.api; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.baobang.piospa.entities.ServiceTime; import com.baobang.piospa.model.DataResult; import com.baobang.piospa.repositories.ServiceTimeRepository; import com.baobang.piospa.utils.MessageResponse; import com.baobang.piospa.utils.RequestPath; import io.swagger.annotations.ApiOperation; /** * @author BaoBang * @Created May 4, 2018 * */ @RestController @RequestMapping(RequestPath.SERVICE_TIME_PATH) public class ServiceTimeController { @Autowired ServiceTimeRepository mServiceTimeRepository; /** * @api {get} / Request Service Time information * @apiName getAll * @apiTime Service * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {array} the list Service Time of the response * */ @RequestMapping(// method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get all Service Times") public DataResult<List<ServiceTime>> getAll() { List<ServiceTime> serviceTimes = mServiceTimeRepository.findAll(); return new DataResult<List<ServiceTime>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, serviceTimes); } /** * * @api {get} /{serviceTimeId} Request Service Time information * @apiName getServiceTimeById * @apiGroup Service * * @param {ServiceTimeId} id Service Time unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {ServiceTime} the Service Time was got * */ @RequestMapping(// value = "/{serviceTimeId}", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get Service Time by id") public DataResult<ServiceTime> getServiceTimeById(@PathVariable(value = "serviceTimeId") int serviceTimeId) { DataResult<ServiceTime> result = new DataResult<>(); Optional<ServiceTime> option = mServiceTimeRepository.findById(serviceTimeId); ServiceTime serviceTime = option.get(); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(serviceTime); return result; } /** * @api {post} / Create a new Service Time * @apiName createServiceTime * @apiTime Service * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {ServiceTime} the new Service Time was created * */ @RequestMapping(// value = { "", "/" }, // method = RequestMethod.POST, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Create a new Service Time") public DataResult<ServiceTime> CreateServiceTime(@RequestBody ServiceTime serviceTime) { DataResult<ServiceTime> result = new DataResult<>(); serviceTime = mServiceTimeRepository.save(serviceTime); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(serviceTime); return result; } /** * @api {put}/{serviceTimeId} update Service Time by id * @apiName updateServiceTime * @apiTime Service * * @apiParam {ServiceTimeId} id Service Time unique ID. * @apiBody {ServiceTime} the info of user need to update * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {ServiceTime} the new Service Time was updated * */ @RequestMapping(// value = "/{serviceTimeId}", // method = RequestMethod.PUT, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Update Service Time by id") public DataResult<ServiceTime> updateServiceTime(@PathVariable(value = "serviceTimeId") int serviceTimeId, @RequestBody ServiceTime serviceTime) { DataResult<ServiceTime> result; Optional<ServiceTime> option = mServiceTimeRepository.findById(serviceTimeId); ServiceTime time = option.get(); time.setTime(serviceTime.getTime()); time = mServiceTimeRepository.save(time); result = new DataResult<>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, time); return result; } /** * @api {delete}/{serviceTimeId} delete Service Time by id * @apiName deleteServiceTime * @apiTime Service * * @apiParam {serviceTimeId} id Service Time unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {ServiceTime} the Service Time was deleted * */ @RequestMapping(// value = "/{serviceTimeId}", // method = RequestMethod.DELETE, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Delete Service Time by id") public DataResult<ServiceTime> deleteServiceTime(@PathVariable(value = "serviceTimeId") int serviceTimeId) { DataResult<ServiceTime> dataResult = new DataResult<>(); ServiceTime serviceTime = mServiceTimeRepository.findById(serviceTimeId).get(); mServiceTimeRepository.deleteById(serviceTimeId); dataResult.setMessage(MessageResponse.SUCCESSED); dataResult.setStatusCode(HttpStatus.OK.value()); dataResult.setData(serviceTime); return dataResult; } } <file_sep>package com.baobang.piospa.entities; import java.io.Serializable; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Date; import java.util.List; /** * The persistent class for the service_package database table. * */ @Entity @Table(name="service_package") @NamedQuery(name="ServicePackage.findAll", query="SELECT s FROM ServicePackage s") public class ServicePackage implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="service_package_id") private int servicePackageId; private String image; private int time; @Column(name="is_active") private int isActive; @Column(name="service_package_name") private String servicePackageName; //bi-directional many-to-many association to Service @JsonIgnore @ManyToMany @JoinTable( name="service_package_detail" , joinColumns={ @JoinColumn(name="service_package_id") } , inverseJoinColumns={ @JoinColumn(name="service_id") } ) private List<Service> services; //bi-directional many-to-one association to ServicePackageDetail @JsonIgnore @OneToMany(mappedBy="servicePackage") private List<ServicePackageDetail> servicePackageDetails; //bi-directional many-to-one association to ServicePrice @JsonIgnore @OneToMany(mappedBy="servicePackage") private List<ServicePrice> servicePrices; public ServicePackage() { } public int getIsActive() { return isActive; } public void setIsActive(int isActive) { this.isActive = isActive; } public int getServicePackageId() { return this.servicePackageId; } public void setServicePackageId(int servicePackageId) { this.servicePackageId = servicePackageId; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } public String getImage() { return this.image; } public void setImage(String image) { this.image = image; } public String getServicePackageName() { return this.servicePackageName; } public void setServicePackageName(String servicePackageName) { this.servicePackageName = servicePackageName; } public List<Service> getServices() { return this.services; } public void setServices(List<Service> services) { this.services = services; } public List<ServicePackageDetail> getServicePackageDetails() { return this.servicePackageDetails; } public void setServicePackageDetails(List<ServicePackageDetail> servicePackageDetails) { this.servicePackageDetails = servicePackageDetails; } public ServicePackageDetail addServicePackageDetail(ServicePackageDetail servicePackageDetail) { getServicePackageDetails().add(servicePackageDetail); servicePackageDetail.setServicePackage(this); return servicePackageDetail; } public ServicePackageDetail removeServicePackageDetail(ServicePackageDetail servicePackageDetail) { getServicePackageDetails().remove(servicePackageDetail); servicePackageDetail.setServicePackage(null); return servicePackageDetail; } public List<ServicePrice> getServicePrices() { return this.servicePrices; } public void setServicePrices(List<ServicePrice> servicePrices) { this.servicePrices = servicePrices; } public ServicePrice addServicePrice(ServicePrice servicePrice) { getServicePrices().add(servicePrice); servicePrice.setServicePackage(this); return servicePrice; } public ServicePrice removeServicePrice(ServicePrice servicePrice) { getServicePrices().remove(servicePrice); servicePrice.setServicePackage(null); return servicePrice; } }<file_sep>package com.baobang.piospa.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.baobang.piospa.entities.ProductLabel; /** * @author BaoBang * @Created Apr 18, 2018 * */ @Repository public interface ProductLabelRepository extends JpaRepository<ProductLabel, Integer> { } <file_sep>package com.baobang.piospa.controller.api; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; 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 com.baobang.piospa.entities.Booking; import com.baobang.piospa.entities.BookingDetail; import com.baobang.piospa.entities.Room; import com.baobang.piospa.entities.ServicePrice; import com.baobang.piospa.model.DataResult; import com.baobang.piospa.model.DateRequest; import com.baobang.piospa.repositories.BookingDetailRepository; import com.baobang.piospa.repositories.RoomRepository; import com.baobang.piospa.utils.DateTimeUtils; import com.baobang.piospa.utils.MessageResponse; import io.swagger.annotations.ApiOperation; /** * @author BaoBang * @Created Aug 16, 2018 * */ @RestController @RequestMapping("/room") public class RoomController { @Autowired BookingDetailRepository mBookingDetailRepository; @Autowired RoomRepository mRoomRepository; @RequestMapping(// method = RequestMethod.POST, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get all room active") public DataResult<List<Room>> getRoomCanBooking(@RequestBody DateRequest dateRequest) { List<Room> allRooms = mRoomRepository.findAll(); Date dateBooking = DateTimeUtils.getDate(dateRequest.getDate(), dateRequest.getTime()); List<Room> rooms = new ArrayList<>(); for(Room room : allRooms) { List<BookingDetail> bookingDetails = mBookingDetailRepository.findByDateAndRoom(room.getRoomId(), dateRequest.getDate()); int count = 0; for(BookingDetail detail : bookingDetails) { Date start = DateTimeUtils.getDate(detail.getDateBooking(), detail.getTimeStart()); Date end = new Date(start.getTime()); int time = getTime(detail.getServicePrice()); end = DateTimeUtils.addMinute(end, time); if(dateBooking.after(start) && dateBooking.before(end)) { count += detail.getNumber(); } } if(count < room.getRoomLimit()) { room.setServing(count); rooms.add(room); } } return new DataResult<List<Room>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, rooms); } private int getTime(ServicePrice servicePrice) { int time = 0; if(servicePrice.getService() != null) { time = Integer.parseInt(servicePrice.getService().getServiceTime().getTime()); }else { time = servicePrice.getServicePackage().getTime(); } return time; } } <file_sep>package com.baobang.piospa.model; import com.baobang.piospa.entities.Room; /** * @author BaoBang * @Created May 27, 2018 * */ public class CartItemService { private int productId; private int number; private String dateBooking; private String timeBooking; private Room room; public CartItemService(int productId, int number, String dateBooking, String timeBooking) { super(); this.productId = productId; this.number = number; this.dateBooking = dateBooking; this.timeBooking = timeBooking; } public CartItemService(int productId, int number, String dateBooking, String timeBooking, Room room) { super(); this.productId = productId; this.number = number; this.dateBooking = dateBooking; this.timeBooking = timeBooking; this.room = room; } public Room getRoom() { return room; } public void setRoom(Room room) { this.room = room; } public CartItemService() { super(); } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getDateBooking() { return dateBooking; } public void setDateBooking(String dateBooking) { this.dateBooking = dateBooking; } public String getTimeBooking() { return timeBooking; } public void setTimeBooking(String timeBooking) { this.timeBooking = timeBooking; } } <file_sep>package com.baobang.piospa.controller.api; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.baobang.piospa.entities.Service; import com.baobang.piospa.entities.ServicePackage; import com.baobang.piospa.model.DataResult; import com.baobang.piospa.repositories.ServicePackageRepository; import com.baobang.piospa.repositories.ServiceRepository; import com.baobang.piospa.utils.MessageResponse; import com.baobang.piospa.utils.RequestPath; import com.baobang.piospa.utils.Utils; import io.swagger.annotations.ApiOperation; /** * @author BaoBang * @Created May 4, 2018 * */ @RestController @RequestMapping(RequestPath.SERVICE_PATH) public class ServiceController { @Autowired ServiceRepository mServiceRepository; @Autowired ServicePackageRepository mServicePackageRepository; /** * @api {get} / Request Service information * @apiName getAll * @apiGroup Service * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {array} the list Service of the response * */ @RequestMapping(// method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get all Service s") public DataResult<List<Service>> getAll() { List<Service> services = mServiceRepository.findAll(); return new DataResult<List<Service>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, services); } /** * @api {get} /{serviceId} Request Service information * @apiName getServiceById * @apiGroup Service * * @apiParam {ServiceId} id Service unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Service} the Service was got * */ @RequestMapping(// value = "/{serviceId}", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get Service by id") public DataResult<Service> getServiceById(@PathVariable(value = "serviceId") int serviceId) { DataResult<Service> result = new DataResult<>(); Optional<Service> option = mServiceRepository.findById(serviceId); Service service = option.get(); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(service); return result; } /** * @api {post} / Create a new Service * @apiName createService * @apiGroup Service * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Service} the new Service was created * */ @RequestMapping(// value = { "", "/" }, // method = RequestMethod.POST, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Create a new Service ") public DataResult<Service> CreateService(@RequestBody Service service) { DataResult<Service> result = new DataResult<>(); service = mServiceRepository.save(service); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(service); return result; } /** * @api {put}/{serviceId} update Service by id * @apiName updateService * @apiGroup Service * * @apiParam {ServiceId} id Service unique ID. * @apiBody {Service} the info of user need to update * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Service} the new Service was updated * */ @RequestMapping(// value = "/{serviceId}", // method = RequestMethod.PUT, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Update Service by id") public DataResult<Service> updateService(@PathVariable(value = "serviceId") int serviceId, @RequestBody Service service) { DataResult<Service> result; Optional<Service> option = mServiceRepository.findById(serviceId); Service temp = option.get(); temp.setServiceName(service.getServiceName()); temp.setServiceTime(service.getServiceTime()); temp.setDescription(service.getDescription()); temp.setImage(service.getImage()); temp.setIsActive(service.getIsActive()); temp = mServiceRepository.save(temp); result = new DataResult<>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, temp); return result; } /** * @api {delete}/{serviceId} delete Service by id * @apiName deleteService * @apiGroup Service * * @apiParam {serviceId} id Service unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Service} the Service was deleted * */ @RequestMapping(// value = "/{serviceId}", // method = RequestMethod.DELETE, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Delete Service by id") public DataResult<Service> deleteService(@PathVariable(value = "serviceId") int serviceId) { DataResult<Service> dataResult = new DataResult<>(); Service service = mServiceRepository.findById(serviceId).get(); mServiceRepository.deleteById(serviceId); dataResult.setMessage(MessageResponse.SUCCESSED); dataResult.setStatusCode(HttpStatus.OK.value()); dataResult.setData(service); return dataResult; } /** * @api {get}/packages/{packageId} get Service by package id * @apiName getServiceByPackageId * @apiGroup Service * * @apiParam {packageId} id Service package unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {array[Service]} the Services was got * */ @RequestMapping(// value = "/packages/{packageId}", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get Service by package id") public DataResult<List<Service>> getServicePackageById(@PathVariable(value = "packageId") int packageId){ ServicePackage servicePackage = mServicePackageRepository.findById(packageId).get(); List<Service> services = servicePackage.getServices(); return new DataResult<List<Service>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, services); } } <file_sep>package com.baobang.piospa.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.baobang.piospa.entities.Province; /** * @author BaoBang * @Created Apr 20, 2018 * */ @Repository public interface ProvinceRepository extends JpaRepository<Province, Integer>{ @Query("select p from Province p where p.provinceid = :provinceid") public Province findById(@Param("provinceid")String provinceid); } <file_sep>package com.baobang.piospa.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.baobang.piospa.entities.Service; /** * @author BaoBang * @Created May 4, 2018 * */ @Repository public interface ServiceRepository extends JpaRepository<Service, Integer>{ } <file_sep>package com.baobang.piospa.entities; import java.io.Serializable; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * The persistent class for the booking database table. * */ @Entity @NamedQuery(name = "Booking.findAll", query = "SELECT b FROM Booking b") public class Booking implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "booking_id") private int bookingId; private int discount; private int number; private int price; private int total; // bi-directional many-to-one association to Customer @ManyToOne @JoinColumn(name = "customer_id") private Customer customer; // bi-directional many-to-one association to BookingDetail @JsonIgnore @OneToMany(mappedBy = "booking", cascade = CascadeType.ALL) private List<BookingDetail> bookingDetails = new ArrayList<>(); // bi-directional many-to-one association to Booking @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name="order_id", referencedColumnName="order_id") private Order order; public void setOrder(Order order) { this.order = order; } public Booking() { } public int getBookingId() { return this.bookingId; } public void setBookingId(int bookingId) { this.bookingId = bookingId; } public int getDiscount() { return this.discount; } public void setDiscount(int discount) { this.discount = discount; } public int getNumber() { return this.number; } public void setNumber(int number) { this.number = number; } public int getPrice() { return this.price; } public void setPrice(int price) { this.price = price; } public int getTotal() { return this.total; } public void setTotal(int total) { this.total = total; } public Customer getCustomer() { return this.customer; } public void setCustomer(Customer customer) { this.customer = customer; } public List<BookingDetail> getBookingDetails() { return this.bookingDetails; } public void setBookingDetails(List<BookingDetail> bookingDetails) { this.bookingDetails = bookingDetails; } public BookingDetail addBookingDetail(BookingDetail bookingDetail) { getBookingDetails().add(bookingDetail); bookingDetail.setBooking(this); return bookingDetail; } public BookingDetail removeBookingDetail(BookingDetail bookingDetail) { getBookingDetails().remove(bookingDetail); bookingDetail.setBooking(null); return bookingDetail; } } <file_sep>package com.baobang.piospa.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.baobang.piospa.entities.Booking; /** * @author BaoBang * @Created May 13, 2018 * */ public interface BookingRepository extends JpaRepository<Booking, Integer>{ } <file_sep>package com.baobang.piospa.model; import java.util.List; import com.baobang.piospa.entities.BookingDetail; import com.baobang.piospa.entities.OrderProduct; /** * @author BaoBang * @Created May 31, 2018 * */ public class OrderResultResponse { private List<OrderProduct> orderProducts; private List<BookingDetail> bookingDetails; public OrderResultResponse(List<OrderProduct> orderProducts, List<BookingDetail> bookingDetails) { super(); this.orderProducts = orderProducts; this.bookingDetails = bookingDetails; } public OrderResultResponse() { super(); } public List<OrderProduct> getOrderProducts() { return orderProducts; } public void setOrderProducts(List<OrderProduct> orderProducts) { this.orderProducts = orderProducts; } public List<BookingDetail> getBookingDetails() { return bookingDetails; } public void setBookingDetails(List<BookingDetail> bookingDetails) { this.bookingDetails = bookingDetails; } } <file_sep>package com.baobang.piospa.utils; /** * @author BaoBang * @Created Apr 14, 2018 * */ public interface MessageResponse { public static final String SUCCESSED = "Thành công"; public static final String NOT_FOUND = "Không tìm thấy"; public static final String NOT_CONTENT = "Không có dữ liệu"; public static final String BAD_REQUEST = "Bad Request"; public static final String EXITS = "Giá trị đã tồn tại"; public static final String ACCOUNT_NOT_EXSIT = "Tài khoản không tồn tại"; public static final String PASSWORD_INCORRECT = "Mật khẩu không đúng"; public static final String ACCOUNT_EXSIT = "Tài khoản đã tồn tại"; } <file_sep>package com.baobang.piospa.controller.api; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.baobang.piospa.entities.District; import com.baobang.piospa.entities.Ward; import com.baobang.piospa.model.DataResult; import com.baobang.piospa.repositories.DistrictRepository; import com.baobang.piospa.utils.MessageResponse; import com.baobang.piospa.utils.RequestPath; import io.swagger.annotations.ApiOperation; /** * @author BaoBang * @Created Apr 20, 2018 * */ @RestController @RequestMapping(RequestPath.DISTRICT_PATH) public class DistrictController { @Autowired DistrictRepository mDistrictRepository; /** * @api {get} / Request District information * @apiName getAll * @apiGroup District * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {array} the list District * */ @RequestMapping(// method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get all Districts") public DataResult<List<District>> getAll() { List<District> districts = mDistrictRepository.findAll(); return new DataResult<List<District>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, districts); } /** * @api {get} /{districtId} Request district information * @apiName getDistrictById * @apiOrigin district * * @apiParam {districtId} id district unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {District} the district was got * */ @RequestMapping(// value = "/{districtId}", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get district by id") public DataResult<District> getDistrictById(@PathVariable(value = "districtId") int districtId) { DataResult<District> result = new DataResult<>(); District district = mDistrictRepository.findById(districtId).get(); if (district == null) { result.setMessage(MessageResponse.NOT_FOUND); result.setStatusCode(HttpStatus.NOT_FOUND.value()); } else { result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); } result.setData(district); return result; } /** * @api {get} /{districtId}/ward Request district information * @apiName getDistrictById * @apiOrigin district * * @apiParam {districtId} id district unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {array[District]} the district was got * */ @RequestMapping(// value = "/{districtId}/ward", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get ward of district by id") public DataResult<List<Ward>> getWardOfDistrictById(@PathVariable(value = "districtId") int districtId) { DataResult<List<Ward>> result = new DataResult<>(); District district = mDistrictRepository.findById(districtId).get(); List<Ward> wards = null; if (district == null) { result.setMessage(MessageResponse.NOT_FOUND); result.setStatusCode(HttpStatus.NOT_FOUND.value()); } else { wards = district.getWards(); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); } result.setData(wards); return result; } } <file_sep>package com.baobang.piospa.controller.api; /** * @author BaoBang * @Created Apr 24, 2018 * */ import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.baobang.piospa.entities.Customer; import com.baobang.piospa.model.DataResult; import com.baobang.piospa.model.LoginForm; import com.baobang.piospa.repositories.CustomerRepository; import com.baobang.piospa.utils.MessageResponse; import com.baobang.piospa.utils.RequestPath; import com.baobang.piospa.utils.Utils; import io.swagger.annotations.ApiOperation; @RestController @RequestMapping(RequestPath.CUSTOMER_PATH) public class CustomerController { @Autowired CustomerRepository mCustomerRepository; /** * @api {get} / Request Customer information * @apiName getAll * @api Customer * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {array} the list Customer * */ @RequestMapping(// method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get all Customers") public DataResult<List<Customer>> getAll() { List<Customer> customers = mCustomerRepository.findAll(); return new DataResult<List<Customer>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, customers); } /** * @api {get} /{CustomerId} Request Customer information * @apiName getCustomerById * @apiOrigin Customer * * @apiParam {CustomerId} id Customer unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {ProductOrigin} the Customer was got * */ @RequestMapping(// value = "/{customerId}", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get Customer by id") public DataResult<Customer> getCustomerById( @PathVariable(value = "customerId") int customerId) { DataResult<Customer> result = new DataResult<>(); Customer customer = mCustomerRepository.findById(customerId).get(); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(customer); return result; } /** * @api {post} / Create a new Customer information * @apiName createCustomer * @api Customer * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Customer} the customer was created * */ @RequestMapping(// value = {"", "/"}, // method = RequestMethod.POST, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Create new Customer") public DataResult<Customer> createCustomer(@RequestBody Customer customer) { DataResult<Customer> result = new DataResult<>(); Customer temp = mCustomerRepository.findByAccount(customer.getAccount()); if (temp == null) { temp = mCustomerRepository.save(customer); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); } else { result.setMessage(MessageResponse.ACCOUNT_EXSIT); result.setStatusCode(HttpStatus.NOT_FOUND.value()); } result.setData(temp); return result; } /** * @api {put} /{customerId} update Customer information * @apiName updateCustomer * @api Customer * * @apiParam {CustomerId} id Customer unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Customer} the customer was created * */ @RequestMapping(// value = "/{customerId}", // method = RequestMethod.PUT, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Update Customer by id") public DataResult<Customer> updateCustomer( @PathVariable(value = "customerId") int customerId, @RequestBody Customer customer) { DataResult<Customer> result = new DataResult<>(); Customer temp = mCustomerRepository.findById(customerId).get(); temp.setFullname(customer.getFullname()); temp.setGender(customer.getGender()); temp.setBirthday(customer.getBirthday()); temp.setPhone(customer.getPhone()); temp.setIsActive(customer.getIsActive()); temp.setProvince(customer.getProvince()); temp.setDistrict(customer.getDistrict()); temp.setWard(customer.getWard()); temp.setEmail(customer.getEmail()); temp.setAddress(customer.getAddress()); temp.setCustomerAvatar(customer.getCustomerAvatar()); temp.setPassword(<PASSWORD>()); temp = mCustomerRepository.save(temp); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(temp); return result; } /** * @api {delete} /{customerId} delete Customer information * @apiName deleteCustomer * @api Customer * * @apiParam {CustomerId} id Customer unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Customer} the customer was created * */ @RequestMapping(// value = "/{customerId}", // method = RequestMethod.DELETE, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Delete Customer by id") public DataResult<Customer> deleteCustomer( @PathVariable(value = "customerId") int customerId) { DataResult<Customer> result = new DataResult<>(); Customer customer = mCustomerRepository.findById(customerId).get(); mCustomerRepository.delete(customer); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(customer); return result; } /** * @api {post} /login request login * @apiName login * @api Customer * * @apiParam none * @apiBody {username, password} account login * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Customer} the customer was logined * */ @RequestMapping(// value = "/login", // method = RequestMethod.POST, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "login") public DataResult<Customer> login( @RequestBody LoginForm loginRequest) { DataResult<Customer> result = new DataResult<>(); Customer customer = mCustomerRepository.findByAccount(loginRequest.getUsername()); if(customer == null) { result.setMessage(MessageResponse.ACCOUNT_NOT_EXSIT); result.setStatusCode(HttpStatus.NOT_FOUND.value()); }else { customer = mCustomerRepository.findByAccountAndPassword(loginRequest.getUsername(), loginRequest.getPassword()); if(customer == null) { result.setMessage(MessageResponse.PASSWORD_INCORRECT); result.setStatusCode(HttpStatus.NOT_FOUND.value()); }else { result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); } } result.setData(customer); return result; } } <file_sep>package com.baobang.piospa.entities; import java.io.Serializable; import javax.persistence.*; import java.util.Date; /** * The persistent class for the service_package_detail database table. * */ @Entity @Table(name="service_package_detail") @NamedQuery(name="ServicePackageDetail.findAll", query="SELECT s FROM ServicePackageDetail s") public class ServicePackageDetail implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="service_package_detail_id") private int servicePackageDetailId; //bi-directional many-to-one association to ServicePackage @ManyToOne @JoinColumn(name="service_package_id") private ServicePackage servicePackage; //bi-directional many-to-one association to Service @ManyToOne @JoinColumn(name="service_id") private Service service; public ServicePackageDetail() { } public int getServicePackageDetailId() { return this.servicePackageDetailId; } public void setServicePackageDetailId(int servicePackageDetailId) { this.servicePackageDetailId = servicePackageDetailId; } public ServicePackage getServicePackage() { return this.servicePackage; } public void setServicePackage(ServicePackage servicePackage) { this.servicePackage = servicePackage; } public Service getService() { return this.service; } public void setService(Service service) { this.service = service; } }<file_sep>package com.baobang.piospa.repositories; import org.springframework.data.jpa.repository.JpaRepository; import com.baobang.piospa.entities.Room; /** * @author BaoBang * @Created Aug 16, 2018 * */ public interface RoomRepository extends JpaRepository<Room, Integer>{ } <file_sep>package com.baobang.piospa.model; import java.util.ArrayList; import java.util.List; import com.baobang.piospa.entities.Order; /** * @author BaoBang * @Created Jul 28, 2018 * */ public class OrderObject { private Order order; private List<OrderProductObject> orderProducts = new ArrayList<>(); private List<BookingDetailObject> bookingDetails = new ArrayList<>(); public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } public List<OrderProductObject> getOrderProducts() { return orderProducts; } public void setOrderProducts(List<OrderProductObject> orderProducts) { this.orderProducts = orderProducts; } public List<BookingDetailObject> getBookingDetails() { return bookingDetails; } public void setBookingDetails(List<BookingDetailObject> bookingDetails) { this.bookingDetails = bookingDetails; } public OrderObject(Order order, List<OrderProductObject> orderProducts, List<BookingDetailObject> bookingDetails) { super(); this.order = order; this.orderProducts = orderProducts; this.bookingDetails = bookingDetails; } public OrderObject() { super(); } } <file_sep>package com.baobang.piospa.entities; import java.io.Serializable; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Date; import java.util.List; /** * The persistent class for the service_group database table. * */ @Entity @Table(name="service_group") @NamedQuery(name="ServiceGroup.findAll", query="SELECT s FROM ServiceGroup s") public class ServiceGroup implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="service_group_id") private int serviceGroupId; @Column(name="service_group_name") private String serviceGroupName; //bi-directional many-to-one association to ServicePrice @JsonIgnore @OneToMany(mappedBy="serviceGroup", fetch = FetchType.EAGER) private List<ServicePrice> servicePrices; public ServiceGroup() { } public int getServiceGroupId() { return this.serviceGroupId; } public void setServiceGroupId(int serviceGroupId) { this.serviceGroupId = serviceGroupId; } public String getServiceGroupName() { return this.serviceGroupName; } public void setServiceGroupName(String serviceGroupName) { this.serviceGroupName = serviceGroupName; } public List<ServicePrice> getServicePrices() { return this.servicePrices; } public void setServicePrices(List<ServicePrice> servicePrices) { this.servicePrices = servicePrices; } public ServicePrice addServicePrice(ServicePrice servicePrice) { getServicePrices().add(servicePrice); servicePrice.setServiceGroup(this); return servicePrice; } public ServicePrice removeServicePrice(ServicePrice servicePrice) { getServicePrices().remove(servicePrice); servicePrice.setServiceGroup(null); return servicePrice; } }<file_sep>package com.baobang.piospa.entities; import java.io.Serializable; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Date; import java.util.List; /** * The persistent class for the service_type database table. * */ @Entity @Table(name="service_type") @NamedQuery(name="ServiceType.findAll", query="SELECT s FROM ServiceType s") public class ServiceType implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="service_type_id") private int serviceTypeId; @Column(name="service_type_name") private String serviceTypeName; //bi-directional many-to-one association to ServicePrice @JsonIgnore @OneToMany(mappedBy="serviceType") private List<ServicePrice> servicePrices; public ServiceType() { } public int getServiceTypeId() { return this.serviceTypeId; } public void setServiceTypeId(int serviceTypeId) { this.serviceTypeId = serviceTypeId; } public String getServiceTypeName() { return this.serviceTypeName; } public void setServiceTypeName(String serviceTypeName) { this.serviceTypeName = serviceTypeName; } public List<ServicePrice> getServicePrices() { return this.servicePrices; } public void setServicePrices(List<ServicePrice> servicePrices) { this.servicePrices = servicePrices; } public ServicePrice addServicePrice(ServicePrice servicePrice) { getServicePrices().add(servicePrice); servicePrice.setServiceType(this); return servicePrice; } public ServicePrice removeServicePrice(ServicePrice servicePrice) { getServicePrices().remove(servicePrice); servicePrice.setServiceType(null); return servicePrice; } }<file_sep>package com.baobang.piospa.entities; import java.io.Serializable; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Date; import java.util.List; /** * The persistent class for the order_payment_type database table. * */ @Entity @Table(name="order_payment_type") @NamedQuery(name="OrderPaymentType.findAll", query="SELECT o FROM OrderPaymentType o") public class OrderPaymentType implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="order_payment_type_id") private int orderPaymentTypeId; @Column(name="order_payment_type_name") private String orderPaymentTypeName; //bi-directional many-to-one association to Order @JsonIgnore @OneToMany(mappedBy="orderPaymentType") private List<Order> orders; public OrderPaymentType() { } public int getOrderPaymentTypeId() { return this.orderPaymentTypeId; } public void setOrderPaymentTypeId(int orderPaymentTypeId) { this.orderPaymentTypeId = orderPaymentTypeId; } public String getOrderPaymentTypeName() { return this.orderPaymentTypeName; } public void setOrderPaymentTypeName(String orderPaymentTypeName) { this.orderPaymentTypeName = orderPaymentTypeName; } public List<Order> getOrders() { return this.orders; } public void setOrders(List<Order> orders) { this.orders = orders; } public Order addOrder(Order order) { getOrders().add(order); order.setOrderPaymentType(this); return order; } public Order removeOrder(Order order) { getOrders().remove(order); order.setOrderPaymentType(null); return order; } }<file_sep>package com.baobang.piospa.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.baobang.piospa.entities.District; /** * @author BaoBang * @Created Apr 20, 2018 * */ @Repository public interface DistrictRepository extends JpaRepository<District, Integer>{ @Query("select d from District d where d.districtid = :districtid") public District findById(@Param("districtid")String districtid); } <file_sep>package com.baobang.piospa.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.baobang.piospa.entities.ServiceGroup; /** * @author BaoBang * @Created May 4, 2018 * */ @Repository public interface ServiceGroupRepository extends JpaRepository<ServiceGroup, Integer>{ @Query("select sg from ServiceGroup sg where sg.serviceGroupName = :serviceGroupName") public ServiceGroup findByName(@Param("serviceGroupName")String serviceGroupName); } <file_sep>package com.baobang.piospa.controller.api; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.baobang.piospa.entities.ServiceType; import com.baobang.piospa.model.DataResult; import com.baobang.piospa.repositories.ServiceTypeRepository; import com.baobang.piospa.utils.MessageResponse; import com.baobang.piospa.utils.RequestPath; import io.swagger.annotations.ApiOperation; /** * @author BaoBang * @Created May 4, 2018 * */ @RestController @RequestMapping(RequestPath.SERVICE_TYPE_PATH) public class ServiceTypeController { @Autowired ServiceTypeRepository mServiceTypeRepository; /** * @api {get} / Request Service Type information * @apiName getAll * @apiType Service * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {array} the list Service Type of the response * */ @RequestMapping(// method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get all Service Types") public DataResult<List<ServiceType>> getAll() { List<ServiceType> serviceTypes = mServiceTypeRepository.findAll(); return new DataResult<List<ServiceType>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, serviceTypes); } /** * @api {get} /{serviceTypeId} Request Service Type information * @apiName getServiceTypeById * @apiType Service * * @apiParam {ServiceTypeId} id Service Type unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {ServiceType} the Service Type was got * */ @RequestMapping(// value = "/{serviceTypeId}", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get Service Type by id") public DataResult<ServiceType> getServiceTypeById(@PathVariable(value = "serviceTypeId") int serviceTypeId) { DataResult<ServiceType> result = new DataResult<>(); Optional<ServiceType> option = mServiceTypeRepository.findById(serviceTypeId); ServiceType Type = option.get(); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(Type); return result; } /** * @api {post} / Create a new Service Type * @apiName createServiceType * @apiType Service * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {ServiceType} the new Service Type was created * */ @RequestMapping(// value = { "", "/" }, // method = RequestMethod.POST, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Create a new Service Type") public DataResult<ServiceType> CreateServiceType(@RequestBody ServiceType serviceType) { DataResult<ServiceType> result = new DataResult<>(); ServiceType sType = mServiceTypeRepository.findByName(serviceType.getServiceTypeName()); if(sType == null) { sType = mServiceTypeRepository.save(serviceType); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); }else { result.setMessage(MessageResponse.EXITS); result.setStatusCode(HttpStatus.NOT_FOUND.value()); } result.setData(sType); return result; } /** * @api {put}/{serviceTypeId} update Service Type by id * @apiName updateServiceType * @apiType Service * * @apiParam {ServiceTypeId} id Service Type unique ID. * @apiBody {ServiceType} the info of user need to update * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {ServiceType} the new Service Type was updated * */ @RequestMapping(// value = "/{serviceTypeId}", // method = RequestMethod.PUT, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Update Service Type by id") public DataResult<ServiceType> updateServiceType(@PathVariable(value = "serviceTypeId") int serviceTypeId, @RequestBody ServiceType serviceType) { DataResult<ServiceType> result; Optional<ServiceType> option = mServiceTypeRepository.findById(serviceTypeId); ServiceType Type = option.get(); Type.setServiceTypeName(serviceType.getServiceTypeName()); Type = mServiceTypeRepository.save(Type); result = new DataResult<>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, Type); return result; } /** * @api {delete}/{serviceTypeId} delete Service Type by id * @apiName deleteServiceType * @apiType Service * * @apiParam {serviceTypeId} id Service Type unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {ServiceType} the Service Type was deleted * */ @RequestMapping(// value = "/{serviceTypeId}", // method = RequestMethod.DELETE, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Delete Service Type by id") public DataResult<ServiceType> deleteServiceType(@PathVariable(value = "serviceTypeId") int serviceTypeId) { DataResult<ServiceType> dataResult = new DataResult<>(); ServiceType serviceType = mServiceTypeRepository.findById(serviceTypeId).get(); mServiceTypeRepository.deleteById(serviceTypeId); dataResult.setMessage(MessageResponse.SUCCESSED); dataResult.setStatusCode(HttpStatus.OK.value()); dataResult.setData(serviceType); return dataResult; } } <file_sep>package com.baobang.piospa.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.baobang.piospa.entities.Ward; /** * @author BaoBang * @Created Apr 20, 2018 * */ @Repository public interface WardRepository extends JpaRepository<Ward, Integer>{ @Query("select w from Ward w where w.wardid = :wardid") public Ward findById(@Param("wardid")String wardId); } <file_sep> package com.baobang.piospa.controller.api; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.baobang.piospa.entities.Product; import com.baobang.piospa.entities.ProductGroup; import com.baobang.piospa.model.DataResult; import com.baobang.piospa.repositories.ProductGroupRepository; import com.baobang.piospa.repositories.ProductRepository; import com.baobang.piospa.utils.MessageResponse; import com.baobang.piospa.utils.RequestPath; import com.baobang.piospa.utils.Utils; import io.swagger.annotations.ApiOperation; /** * @author BaoBang * @Created Apr 18, 2018 * */ @RestController @RequestMapping(RequestPath.PRODUCT_GROUP_PATH) public class ProductGroupController { @Autowired ProductGroupRepository mGroupRepository; @Autowired ProductRepository mProductRepository; /** * @api {get} / Request Product Group information * @apiName getAll * @apiGroup Product * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {array} the list product group of the response * */ @RequestMapping(// method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get all product groups") public DataResult<List<ProductGroup>> getAll() { List<ProductGroup> productGroups = mGroupRepository.findAll(); return new DataResult<List<ProductGroup>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, productGroups); } /** * @api {get} /{productGroupId} Request Product Group information * @apiName getProductGroupById * @apiGroup Product * * @apiParam {productGroupId} id Product Group unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {ProductGroup} the Product Group was got * */ @RequestMapping(// value = "/{productGroupId}", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get product group by id") public DataResult<ProductGroup> getProductGroupById(@PathVariable(value = "productGroupId") int productGroupId) { DataResult<ProductGroup> result = new DataResult<>(); Optional<ProductGroup> option = mGroupRepository.findById(productGroupId); ProductGroup group = option.get(); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(group); return result; } /** * @api {get} /{productGroupId}/products Request Product information * @apiName getProductByGroupId * @apiGroup Product * * @apiParam {productGroupId} id Product Group unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {array[Product]} the Products of Group was got * */ @RequestMapping(// value = "/{productGroupId}/products", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get products by group id") public DataResult<List<Product>> getProductByGroupId(@PathVariable(value = "productGroupId") int productGroupId) { DataResult<List<Product>> result = new DataResult<>(); Optional<ProductGroup> option = mGroupRepository.findById(productGroupId); ProductGroup group = option.get(); List<Product> list = mProductRepository.findByGroupId(group.getProductGroupId()); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(list); return result; } /** * @api {get} / Request Product information * @apiName getAllActive * @api Product * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {array} the list product of the response * */ @RequestMapping(// value = "/{groupId}/products/top-ten", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get all products were actived") public DataResult<List<Product>> getTopTenProductByGroup(@PathVariable(value = "groupId") int groupId) { DataResult<List<Product>> result = new DataResult<>(); Optional<ProductGroup> option = mGroupRepository.findById(groupId); ProductGroup group = option.get(); List<Product> list = mProductRepository.findTopTenByGroupId(group.getProductGroupId()+""); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(list); return new DataResult<List<Product>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, list); } /** * @api {post} / Create a new Product Group * @apiName createProductGroup * @apiGroup Product * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {ProductGroup} the new Product Group was created * */ @RequestMapping(// value = { "", "/" }, // method = RequestMethod.POST, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Create a new product group") public DataResult<ProductGroup> CreateProductGroup(@RequestBody ProductGroup productGroup) { DataResult<ProductGroup> result = new DataResult<>(); productGroup.setProductGroupId(0); productGroup = mGroupRepository.save(productGroup); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(productGroup); return result; } /** * @api {put}/{productGroupId} update Product Group by id * @apiName updateProductGroup * @apiGroup Product * * @apiParam {productGroupId} id Product Group unique ID. * @apiBody {productGroup} the info of user need to update * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {ProductGroup} the new Product Group was updated * */ @RequestMapping(// value = "/{productGroupId}", // method = RequestMethod.PUT, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Update product group by id") public DataResult<ProductGroup> updateProductGroup(@PathVariable(value = "productGroupId") int productGroupId, @RequestBody ProductGroup productGroup) { DataResult<ProductGroup> result; Optional<ProductGroup> option = mGroupRepository.findById(productGroupId); ProductGroup group = option.get(); group.setProductGroupName(productGroup.getProductGroupName()); group.setIsActive(productGroup.getIsActive()); group = mGroupRepository.save(group); result = new DataResult<>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, group); return result; } /** * @api {delete}/{productGroupId} delete Product Group by id * @apiName deleteProductGroup * @apiGroup Product * * @apiParam {productGroupId} id Product Group unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {ProductGroup} the Product Group was deleted * */ @RequestMapping(// value = "/{productGroupId}", // method = RequestMethod.DELETE, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Delete product group by id") public DataResult<ProductGroup> deleteProductGroup(@PathVariable(value = "productGroupId") int productGroupId) { DataResult<ProductGroup> dataResult = new DataResult<>(); ProductGroup productGroup = mGroupRepository.findById(productGroupId).get(); mGroupRepository.deleteById(productGroupId); dataResult.setMessage(MessageResponse.SUCCESSED); dataResult.setStatusCode(HttpStatus.OK.value()); dataResult.setData(productGroup); return dataResult; } } <file_sep>package com.baobang.piospa.controller.admin; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.Calendar; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.baobang.piospa.model.UploadForm; import com.baobang.piospa.utils.ConvertCharacterUtils; @Controller @RequestMapping(value = "/ajax/upload") public class UploadFileWithAjaxController { private static final String UPLOAD_DIRECTORY = "uploads"; // Phương thức này được gọi mỗi lần có Submit. @InitBinder public void initBinder(WebDataBinder dataBinder) { Object target = dataBinder.getTarget(); if (target == null) { return; } System.out.println("Target=" + target); if (target.getClass() == UploadForm.class) { // Đăng ký để chuyển đổi giữa các đối tượng multipart thành byte[] dataBinder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor()); } } // POST: Sử lý Upload @ResponseBody @RequestMapping(value = "/one-file", method = RequestMethod.POST) public String uploadOneFileHandlerPOST(HttpServletRequest request, Model model, @RequestParam("file") MultipartFile file) { return doUpload(request, model, file); } private String doUpload(HttpServletRequest request, Model model, MultipartFile file) { // Thời Gian Upload Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); // Thư mục gốc upload file. String uploadRootPath = request.getServletContext().getRealPath(UPLOAD_DIRECTORY) + File.separator + year; System.out.println("uploadRootPath=" + uploadRootPath); File uploadRootDir = new File(uploadRootPath); // Tạo thư mục gốc upload nếu nó không tồn tại. if (!uploadRootDir.exists()) { uploadRootDir.mkdirs(); } // Tên file gốc tại Client. String name = file.getOriginalFilename(); System.out.println("Client File Name = " + name); String fileName = year + "-" + month + "-" + day + "-" + hour + "-" + minute + "-" + second + "-" + name; String fileSlug = ConvertCharacterUtils.toURLFriendly(fileName); if (name != null && name.length() > 0) { try { // Tạo file tại Server. File serverFile = new File(uploadRootDir.getAbsolutePath() + File.separator + fileSlug); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile)); stream.write(file.getBytes()); stream.close(); return ServletUriComponentsBuilder.fromCurrentContextPath().path("/" + UPLOAD_DIRECTORY + "/") .path(year + "/" + fileSlug).toUriString(); } catch (Exception e) { System.out.println("Error Write file: " + name); } } return ""; } } <file_sep>package com.baobang.piospa.model; import java.util.List; /** * @author BaoBang * @Created Apr 26, 2018 * */ public class CartShopping { private List<CartItemProduct> cartItemProducts; private List<CartItemService> cartItemServices; public List<CartItemProduct> getCartItemProducts() { return cartItemProducts; } public void setCartItemProducts(List<CartItemProduct> cartItemProducts) { this.cartItemProducts = cartItemProducts; } public List<CartItemService> getCartItemServices() { return cartItemServices; } public void setCartItemServices(List<CartItemService> cartItemServices) { this.cartItemServices = cartItemServices; } public CartShopping(List<CartItemProduct> cartItemProducts, List<CartItemService> cartItemServices) { super(); this.cartItemProducts = cartItemProducts; this.cartItemServices = cartItemServices; } public CartShopping() { super(); } } <file_sep>package com.baobang.piospa.model; import com.baobang.piospa.entities.Order; /** * @author BaoBang * @Created Apr 26, 2018 * */ public class OrderBodyRequest { private Order order; private CartShopping cartShopping; public OrderBodyRequest(Order order, CartShopping cartShopping) { super(); this.order = order; this.cartShopping = cartShopping; } public OrderBodyRequest() { super(); } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } public CartShopping getCartShopping() { return cartShopping; } public void setCartShopping(CartShopping cartShopping) { this.cartShopping = cartShopping; } } <file_sep>package com.baobang.piospa.repositories; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.baobang.piospa.entities.BookingDetail; /** * @author BaoBang * @Created May 13, 2018 * */ @Repository public interface BookingDetailRepository extends JpaRepository<BookingDetail, Integer>{ @Query(value = "SELECT * FROM booking_detail WHERE date_booking = :dateBooking", nativeQuery = true) public List<BookingDetail> getBookingDetailByDateBooking(@Param("dateBooking")String dateBooking); @Query(value = "SELECT b from BookingDetail b where b.dateBooking = :date and b.room.roomId = :roomId and b.servedStatus = 0 or b.servedStatus = 1") public List<BookingDetail> findByDateAndRoom(@Param("roomId") int roomId, @Param("date") String date); } <file_sep>package com.baobang.piospa.entities; import java.io.Serializable; import java.util.List; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; /** * The persistent class for the ward database table. * */ @Entity @NamedQuery(name = "Ward.findAll", query = "SELECT w FROM Ward w") public class Ward implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int wardid; private String name; private String type; // bi-directional many-to-one association to District @ManyToOne @JoinColumn(name = "districtid") private District district; // bi-directional many-to-one association to Customer @JsonIgnore @OneToMany(mappedBy = "ward") private List<Customer> customers; public Ward() { } public int getWardid() { return this.wardid; } public void setWardid(int wardid) { this.wardid = wardid; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } public District getDistrict() { return this.district; } public void setDistrict(District district) { this.district = district; } public List<Customer> getCustomers() { return this.customers; } public void setCustomers(List<Customer> customers) { this.customers = customers; } public Customer addCustomer(Customer customer) { getCustomers().add(customer); customer.setWard(this); return customer; } public Customer removeCustomer(Customer customer) { getCustomers().remove(customer); customer.setWard(null); return customer; } }<file_sep>package com.baobang.piospa.controller.api; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.baobang.piospa.entities.Product; import com.baobang.piospa.model.DataResult; import com.baobang.piospa.repositories.ProductRepository; import com.baobang.piospa.utils.MessageResponse; import com.baobang.piospa.utils.RequestPath; import io.swagger.annotations.ApiOperation; /** * @author BaoBang * @Created Apr 18, 2018 * */ @RestController @RequestMapping(RequestPath.PRODUCT_PATH) public class ProductController { @Autowired ProductRepository mProductRepository; /** * @api {get} / Request Product information * @apiName getAll * @api Product * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {array} the list product of the response * */ @RequestMapping(// method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get all products") public DataResult<List<Product>> getAll() { List<Product> products = mProductRepository.findAll(); return new DataResult<List<Product>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, products); } /** * @api {get} /{productId} Request Product information * @apiName getProductById * @api Product * * @apiParam {productId} id Product unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Product} the Product was got * */ @RequestMapping(// value = "/{productId}", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get product by id") public DataResult<Product> getProductById(@PathVariable(value = "productId") int productId) { DataResult<Product> result = new DataResult<>(); Product product = getProduct(productId); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(product); return result; } public Product getProduct(int productId) { Optional<Product> option = mProductRepository.findById(productId); Product product = option.get(); return product; } @RequestMapping(// value = "/code/{productId}", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get product by code") public DataResult<Product> getProductByCode(@PathVariable(value = "productId") int productId) { DataResult<Product> result = new DataResult<>(); Product product = mProductRepository.findById(productId).get(); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(product); return result; } /** * @api {post} / Create a new Product * @apiName createProduct * @api Product * * @apiParam none * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Product} the new Product was created * */ @RequestMapping(// value = { "", "/" }, // method = RequestMethod.POST, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Create a new product ") public DataResult<Product> CreateProduct(@RequestBody Product product) { DataResult<Product> result = new DataResult<>(); Date date = new Date(); product.setProductId(0); product.setCreatedAt(date); product.setUpdatedAt(date); product = mProductRepository.save(product); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(product); return result; } /** * @api {put}/{productId} update Product by id * @apiName updateProduct * @api Product * * @apiParam {productId} id Product unique ID. * @apiBody {product} the info of Product need to update * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Product} the new Product was updated * */ @RequestMapping(// value = "/{productId}", // method = RequestMethod.PUT, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Update product by id") public DataResult<Product> updateProduct(@PathVariable(value = "productId") int productId, @RequestBody Product product) { DataResult<Product> result; Optional<Product> option = mProductRepository.findById(productId); Product oldProduct = option.get(); product.setProductId(oldProduct.getProductId()); product.setUpdatedAt(new Date()); product = mProductRepository.save(product); result = new DataResult<>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, product); return result; } /** * @api {delete}/{productId} delete Product by id * @apiName deleteProduct * @api Product * * @apiParam {productId} id Product unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Product} the Product was deleted * */ @RequestMapping(// value = "/{productId}", // method = RequestMethod.DELETE, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Delete product by id") public DataResult<Product> deleteProduct(@PathVariable(value = "productId") int productId) { DataResult<Product> dataResult = new DataResult<>(); Product product = mProductRepository.findById(productId).get(); mProductRepository.deleteById(productId); dataResult.setMessage(MessageResponse.SUCCESSED); dataResult.setStatusCode(HttpStatus.OK.value()); dataResult.setData(product); return dataResult; } } <file_sep>package com.baobang.piospa.entities; import java.io.Serializable; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.List; /** * The persistent class for the district database table. * */ @Entity @NamedQuery(name = "District.findAll", query = "SELECT d FROM District d") public class District implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int districtid; private String name; private String type; // bi-directional many-to-one association to Customer @JsonIgnore @OneToMany(mappedBy = "district") private List<Customer> customers; // bi-directional many-to-one association to Province @ManyToOne @JoinColumn(name = "provinceid") private Province province; // bi-directional many-to-one association to Ward @JsonIgnore @OneToMany(mappedBy = "district") private List<Ward> wards; public District() { } public int getDistrictid() { return this.districtid; } public void setDistrictid(int districtid) { this.districtid = districtid; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } public Province getProvince() { return this.province; } public void setProvince(Province province) { this.province = province; } public List<Ward> getWards() { return this.wards; } public void setWards(List<Ward> wards) { this.wards = wards; } public Ward addWard(Ward ward) { getWards().add(ward); ward.setDistrict(this); return ward; } public Ward removeWard(Ward ward) { getWards().remove(ward); ward.setDistrict(null); return ward; } public List<Customer> getCustomers() { return this.customers; } public void setCustomers(List<Customer> customers) { this.customers = customers; } public Customer addCustomer(Customer customer) { getCustomers().add(customer); customer.setDistrict(this); return customer; } public Customer removeCustomer(Customer customer) { getCustomers().remove(customer); customer.setDistrict(null); return customer; } }<file_sep>package com.baobang.piospa.entities; import java.io.Serializable; import javax.persistence.*; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Date; import java.util.List; /** * The persistent class for the products database table. * */ @Entity @Table(name="products") @NamedQuery(name="Product.findAll", query="SELECT p FROM Product p ORDER BY p.productId DESC") public class Product implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="product_id") private int productId; @Column(name="cost_price") private int costPrice = 0; @Temporal(TemporalType.TIMESTAMP) @Column(name="created_at") private Date createdAt; private String description = ""; private String image = ""; @Column(name="is_active") private byte isActive = 1; private int price = 0; @Column(name="product_name") private String productName; private int quantity = 0; private int amount = 0; @Column(name="quantity_value") private String quantityValue = "gram"; @Temporal(TemporalType.TIMESTAMP) @Column(name="updated_at") private Date updatedAt; //bi-directional many-to-one association to OrderProduct @JsonIgnore @OneToMany(mappedBy="product") private List<OrderProduct> orderProducts; //bi-directional many-to-one association to ProductGroup @ManyToOne @JoinColumn(name="product_group_id") private ProductGroup productGroup; //bi-directional many-to-one association to ProductLabel @ManyToOne @JoinColumn(name="product_label_id") private ProductLabel productLabel; //bi-directional many-to-one association to ProductOrigin @ManyToOne @JoinColumn(name="product_origin_id") private ProductOrigin productOrigin; public Product() { } public int getProductId() { return this.productId; } public void setProductId(int productId) { this.productId = productId; } public int getCostPrice() { return this.costPrice; } public void setCostPrice(int costPrice) { this.costPrice = costPrice; } public Date getCreatedAt() { return this.createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getImage() { return this.image; } public void setImage(String image) { this.image = image; } public byte getIsActive() { return this.isActive; } public void setIsActive(byte isActive) { this.isActive = isActive; } public int getPrice() { return this.price; } public void setPrice(int price) { this.price = price; } public String getProductName() { return this.productName; } public void setProductName(String productName) { this.productName = productName; } public int getQuantity() { return this.quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public String getQuantityValue() { return this.quantityValue; } public void setQuantityValue(String quantityValue) { this.quantityValue = quantityValue; } public Date getUpdatedAt() { return this.updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } public List<OrderProduct> getOrderProducts() { return this.orderProducts; } public void setOrderProducts(List<OrderProduct> orderProducts) { this.orderProducts = orderProducts; } public OrderProduct addOrderProduct(OrderProduct orderProduct) { getOrderProducts().add(orderProduct); orderProduct.setProduct(this); return orderProduct; } public OrderProduct removeOrderProduct(OrderProduct orderProduct) { getOrderProducts().remove(orderProduct); orderProduct.setProduct(null); return orderProduct; } public ProductGroup getProductGroup() { return this.productGroup; } public void setProductGroup(ProductGroup productGroup) { this.productGroup = productGroup; } public ProductLabel getProductLabel() { return this.productLabel; } public void setProductLabel(ProductLabel productLabel) { this.productLabel = productLabel; } public ProductOrigin getProductOrigin() { return this.productOrigin; } public void setProductOrigin(ProductOrigin productOrigin) { this.productOrigin = productOrigin; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } }<file_sep>$(document) .ready( function() { /** ************slider************ */ $('.product-slider').owlCarousel( { nav : true, loop : true, items : 4, autoHeight : true, navText : [ "<i class='fa fa-chevron-left'></i>", "<i class='fa fa-chevron-right'></i>" ] }); $('#brand-slider').owlCarousel( { nav : true, loop : true, items : 5, navText : [ "<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>" ], autoplay : true, autoplayTimeout : 2000, autostopHoverPause : true, }); $( '.content-shop .row .col-md-12 .product-box .slider .product-slider .owl-height .owl-stage .owl-item') .addClass('product-height'); $( '.content-shop .row .col-md-12 .product-box .slider .product-slider .owl-height') .addClass('product-heightest'); /** ************end ./slider************ */ /** ************GO TO TOP************ */ if ($(".btn-top").length > 0) { $(window).scroll(function() { var e = $(window).scrollTop(); if (e > 300) { $(".btn-top").show() } else { $(".btn-top").hide() } }); $(".btn-top").click(function() { $('body,html').animate({ scrollTop : 0 }) }) } /** ************ end./ GO TO TOP************ */ /** ************thumbnail************ */ $('.thumbnail').on( 'click', function() { var clicked = $(this); var newSelection = clicked.data('big'); var $img = $('.primary-image').attr("src", newSelection); clicked.parent().find('.thumbnail') .removeClass('selected'); clicked.addClass('selected'); $('.primary-image').empty().append( $img.hide().fadeIn('slow')); }); /** ************end./ thumbnail************ */ /** ************* Check register user name ************************ */ /** * ************* End Check register user name * ************************ */ }); /** *************SET HEIGHT FOR CARD PRODUCT*********************** */ function sortNumber(a, b) { return a - b; } var highest = 0; function maxHeight() { var heights = new Array(); $('.product-height').css('height', 'auto'); $('.product-height').each(function() { heights.push($(this).height()); }); heights = heights.sort(sortNumber).reverse(); highest = heights[0]; $('.product-height, .product-heightest').css('height', highest); $('.product').css('height', highest - 20); } $(document).ready(maxHeight); $(window).resize(maxHeight); /** *****************SHOPPING CART********************* */ (function() { $("#navbarDropdownCart").on("click", function() { $(".shopping-cart").fadeToggle("slow/400/fast"); }); })(); /** ***********NAV TAB********************** */ $('#digital a').click(function(e) { e.preventDefault(); $(this).tab('show'); })<file_sep>package com.baobang.piospa.controller.api; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.baobang.piospa.entities.OrderProduct; import com.baobang.piospa.model.DataResult; import com.baobang.piospa.repositories.OrderProductRepository; import com.baobang.piospa.utils.MessageResponse; import com.baobang.piospa.utils.RequestPath; import io.swagger.annotations.ApiOperation; /** * @author BaoBang * @Created Apr 26, 2018 * */ @RestController @RequestMapping(RequestPath.ORDER_PRODUCT_PATH) public class OrderProductController { @Autowired OrderProductRepository mOrderProductRepository; /** * @api {get} / Request OrderProduct information * @apiName getAll * @apiGroup Order * * @apiParam none * * @apiSuccess {Integer} the OrderProduct of the response * @apiSuccess {String} the message of the response * @apiSuccess {array} the list OrderProducts * */ @RequestMapping(// method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Get all OrderProducts") public DataResult<List<OrderProduct>> getAll() { List<OrderProduct> OrderProducts = mOrderProductRepository.findAll(); return new DataResult<List<OrderProduct>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, OrderProducts); } /** * @api {get} /{orderId} Request OrderProduct information * @apiName getOrderProductByOrderId * @apiGroup Order * * @apiParam none * * @apiSuccess {Integer} the OrderProduct of the response * @apiSuccess {String} the message of the response * @apiSuccess {array} the list OrderProducts * */ @RequestMapping(// value = "/{orderId}", // method = RequestMethod.GET, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "get OrderProducts By Order Id") public DataResult<List<OrderProduct>> getOrderProductByOrderId(@PathVariable(value = "orderId") int orderId) { List<OrderProduct> OrderProducts = mOrderProductRepository.findOrderProductByOrderId(orderId); return new DataResult<List<OrderProduct>>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, OrderProducts); } /** * @api {get} /{OrderProductId} Request OrderProduct information * @apiName getOrderProductById * @apiGroup OrderProduct * * @apiParam {OrderProductId} id OrderProduct DeliveryStatus unique ID. * * @apiSuccess {Integer} the OrderProduct of the response * @apiSuccess {String} the message of the response * @apiSuccess {OrderProduct} the OrderProduct was got * */ // @RequestMapping(// // value = "/{orderProductId}", // // method = RequestMethod.GET, // // produces = { MediaType.APPLICATION_JSON_VALUE }) // @ApiOperation(value = "Get OrderProduct by id") // public DataResult<OrderProduct> getOrderProductưById(@PathVariable(value = "orderProductId") int orderProductId) { // DataResult<OrderProduct> result = new DataResult<>(); // OrderProduct OrderProduct = mOrderProductRepository.findById(orderProductId).get(); // result.setMessage(MessageResponse.SUCCESSED); // result.setStatusCode(HttpStatus.OK.value()); // result.setData(OrderProduct); // return result; // } /** * @api {post} / Create a new OrderProduct * @apiName createOrderProductApi * @apiGroup OrderProduct * * @apiParam none * * @apiSuccess {Integer} the DeliveryStatus of the response * @apiSuccess {String} the message of the response * @apiSuccess {OrderProductDeliveryStatus} the new OrderProduct DeliveryStatus * was created * */ @RequestMapping(// value = { "", "/" }, // method = RequestMethod.POST, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Create a new OrderProduct") public DataResult<OrderProduct> createOrderProductApi(@RequestBody OrderProduct orderProduct) { DataResult<OrderProduct> result = new DataResult<>(); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(orderProduct); return result; } public OrderProduct createOrderProduct(OrderProduct orderProduct) { Date date = new Date(); orderProduct.setOrderProductId(0); orderProduct = mOrderProductRepository.save(orderProduct); return orderProduct; } /** * @api {put}/{orderProductId} update OrderProduct by id * @apiName updateOrderProduct * @apiGroup OrderProduct * * @apiParam {OrderProductId} id OrderProduct unique ID. * @apiBody {OrderProduct} the info of OrderProduct need to update * * @apiSuccess {Integer} the DeliveryStatus of the response * @apiSuccess {String} the message of the response * @apiSuccess {OrderProduct} the new OrderProduct was updated * */ @RequestMapping(// value = "/{orderProductId}", // method = RequestMethod.PUT, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Update OrderProduct by id") public DataResult<OrderProduct> updateOrderProduct(@PathVariable(value = "orderProductId") int orderProductId, @RequestBody OrderProduct orderProduct) { DataResult<OrderProduct> result; Optional<OrderProduct> option = mOrderProductRepository.findById(orderProductId); OrderProduct newOrderProduct = option.get(); newOrderProduct.setOrder(orderProduct.getOrder()); newOrderProduct.setProduct(orderProduct.getProduct()); newOrderProduct.setPrice(orderProduct.getPrice()); newOrderProduct.setNumber(orderProduct.getNumber()); newOrderProduct.setDiscount(orderProduct.getDiscount()); newOrderProduct.setTotal(orderProduct.getTotal()); newOrderProduct = mOrderProductRepository.save(newOrderProduct); result = new DataResult<>(HttpStatus.OK.value(), MessageResponse.SUCCESSED, newOrderProduct); return result; } /** * @api {delete} /{orderProductId} delete Order information * @apiName deleteOrderProduct * @apiGroup Order * * @apiParam {orderProductId} id Order unique ID. * * @apiSuccess {Integer} the status of the response * @apiSuccess {String} the message of the response * @apiSuccess {Order} the order was created * */ @RequestMapping(// value = "/{orderProductId}", // method = RequestMethod.DELETE, // produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiOperation(value = "Delete Order product by id") public DataResult<OrderProduct> deleteOrderProduct( @PathVariable(value = "orderProductId") int orderProductId) { DataResult<OrderProduct> result = new DataResult<>(); OrderProduct orderProduct = mOrderProductRepository.findById(orderProductId).get(); mOrderProductRepository.delete(orderProduct); result.setMessage(MessageResponse.SUCCESSED); result.setStatusCode(HttpStatus.OK.value()); result.setData(orderProduct); return result; } }
7d3edb81584004d650b19a261ef67c5c8cea5d36
[ "JavaScript", "Java" ]
45
Java
Practice-Graduation/PiospaWebservice
80d045f73333f9079667980c4ede5823ce1d6478
4c85d4303b66bf25c3b54857c14f065f533e267a
refs/heads/dev
<repo_name>HamedSabri-adsk/maya-usd<file_sep>/plugin/al/usdtransaction/AL/usd/transaction/tests/CMakeLists.txt find_package(GTest REQUIRED) set(USDTRANSACTION_TEST_EXECUTABLE_NAME AL_USDTransactionTests) set(USDTRANSACTION_TEST_NAME GTest:AL_USDTransactionTests) set(USDTRANSACTION_PYTHON_TEST_NAME Python:AL_USDTransactionTests) add_executable(${USDTRANSACTION_TEST_EXECUTABLE_NAME}) # compiler configuration mayaUsd_compile_config(${USDTRANSACTION_TEST_EXECUTABLE_NAME}) target_compile_definitions(${USDTRANSACTION_TEST_EXECUTABLE_NAME} PRIVATE $<$<STREQUAL:${CMAKE_BUILD_TYPE},Debug>:TBB_USE_DEBUG> $<$<STREQUAL:${CMAKE_BUILD_TYPE},Debug>:BOOST_DEBUG_PYTHON> $<$<STREQUAL:${CMAKE_BUILD_TYPE},Debug>:BOOST_LINKING_PYTHON> ) target_sources(${USDTRANSACTION_TEST_EXECUTABLE_NAME} PRIVATE testMain.cpp testTransactionManager.cpp testTransaction.cpp ) if(IS_LINUX) set(PTHREAD_LINK -lpthread -lm) endif() target_link_libraries(${USDTRANSACTION_TEST_EXECUTABLE_NAME} PRIVATE ${GTEST_LIBRARIES} arch usd vt ${boost_python_LIBRARIES} ${USDTRANSACTION_LIBRARY_NAME} ${PTHREAD_LINK} ) target_include_directories(${USDTRANSACTION_TEST_EXECUTABLE_NAME} PRIVATE ${GTEST_INCLUDE_DIRS} PUBLIC ${USDTRANSACTION_INCLUDE_LOCATION} ${USD_INCLUDE_DIR} ) mayaUsd_add_test(${USDTRANSACTION_TEST_NAME} COMMAND ${USDTRANSACTION_TEST_EXECUTABLE_NAME} ENV "LD_LIBRARY_PATH=${ADDITIONAL_LD_LIBRARY_PATH}" ) mayaUsd_add_test(${USDTRANSACTION_PYTHON_TEST_NAME} COMMAND ${MAYA_PY_EXECUTABLE} -m unittest discover -s ${CMAKE_CURRENT_SOURCE_DIR} ENV "LD_LIBRARY_PATH=${ADDITIONAL_LD_LIBRARY_PATH}" ) if (TARGET all_tests) add_dependencies(all_tests ${USDTRANSACTION_TEST_EXECUTABLE_NAME} ${USDTRANSACTION_PYTHON_LIBRARY_NAME}) endif()<file_sep>/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/LockManager.cpp // // Copyright 2017 Animal Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "AL/usdmaya/nodes/proxy/LockManager.h" namespace AL { namespace usdmaya { namespace nodes { namespace proxy { //---------------------------------------------------------------------------------------------------------------------- void LockManager::removeEntries(const SdfPathVector& entries) { auto lockIt = m_lockedPrims.begin(); auto lockEnd = m_lockedPrims.end(); auto unlockIt = m_unlockedPrims.begin(); auto unlockEnd = m_unlockedPrims.end(); for (auto it = entries.begin(), end = entries.end(); lockIt != lockEnd && it != end; ++it) { const SdfPath path = *it; lockIt = std::lower_bound(lockIt, lockEnd, path); if (lockIt != lockEnd && *lockIt == path) { lockIt = m_lockedPrims.erase(lockIt); } } for (auto it = entries.begin(), end = entries.end(); unlockIt != unlockEnd && it != end; ++it) { const SdfPath path = *it; unlockIt = std::lower_bound(unlockIt, unlockEnd, path); if (unlockIt != unlockEnd && *unlockIt == path) { unlockIt = m_unlockedPrims.erase(unlockIt); } } } //---------------------------------------------------------------------------------------------------------------------- void LockManager::removeFromRootPath(const SdfPath& path) { { // find the start of the entries for this path auto lb = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); auto ub = lb; // keep walking forwards until we hit a new branch in the tree while (ub != m_lockedPrims.end()) { if (ub->HasPrefix(path)) { ++ub; } else { break; } } // if we find a valid range, erase the previous entries if (lb != ub) { m_lockedPrims.erase(lb, ub); } } // remove all previous prims from m_lockInheritedPrims that are children of the current prim. { // find the start of the entries for this path auto lb = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); auto ub = lb; // keep walking forwards until we hit a new branch in the tree while (ub != m_unlockedPrims.end()) { if (ub->HasPrefix(path)) { ++ub; } else { break; } } // if we find a valid range, erase the previous entries if (lb != ub) { m_unlockedPrims.erase(lb, ub); } } } //---------------------------------------------------------------------------------------------------------------------- void LockManager::setLocked(const SdfPath& path) { auto lockIter = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); if (lockIter != m_lockedPrims.end()) { // lock already in the locked array, so return if (*lockIter == path) return; } m_lockedPrims.insert(lockIter, path); auto unlockIter = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); if (unlockIter != m_unlockedPrims.end()) { if (*unlockIter == path) { m_unlockedPrims.erase(unlockIter); } } } //---------------------------------------------------------------------------------------------------------------------- void LockManager::setUnlocked(const SdfPath& path) { auto unlockIter = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); if (unlockIter != m_unlockedPrims.end()) { // lock already in the locked array, so return if (*unlockIter == path) return; } m_unlockedPrims.insert(unlockIter, path); auto lockIter = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); if (lockIter != m_lockedPrims.end()) { if (*lockIter == path) { m_lockedPrims.erase(lockIter); } } } //---------------------------------------------------------------------------------------------------------------------- void LockManager::setInherited(const SdfPath& path) { if (!m_unlockedPrims.empty()) { auto unlockIter = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); if (unlockIter != m_unlockedPrims.end()) { // lock already in the locked array, so return if (*unlockIter == path) { m_unlockedPrims.erase(unlockIter); } } } if (!m_lockedPrims.empty()) { auto lockIter = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); if (lockIter != m_lockedPrims.end()) { // lock already in the locked array, so return if (*lockIter == path) { m_lockedPrims.erase(lockIter); } } } } //---------------------------------------------------------------------------------------------------------------------- bool LockManager::isLocked(const SdfPath& path) const { if (m_lockedPrims.empty()) return false; auto lockIter = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); // first check the edge case where this path is in the locked set if (lockIter != m_lockedPrims.end() && *lockIter == path) { return true; } // now attempt to see if a parent of this path is in the locked set bool hasLockedParent = false; if (lockIter != m_lockedPrims.begin()) { --lockIter; { if (path.HasPrefix(*lockIter)) { hasLockedParent = true; } } } // now attempt to see if a parent of this path is in the unlocked set bool hasUnlockedParent = false; auto unlockIter = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); // first check the edge case where this path is in the locked set if (unlockIter != m_unlockedPrims.end() && *unlockIter == path) { return false; } if (unlockIter != m_unlockedPrims.begin()) { --unlockIter; { if (path.HasPrefix(*unlockIter)) { hasUnlockedParent = true; } } } // if we have entries in both the locked and unlocked set..... if (hasLockedParent && hasUnlockedParent) { // if the locked path is longer than the unlocked path, the closest parent to path is // locked. return (lockIter->GetString().size() >= unlockIter->GetString().size()); } else if (hasLockedParent) { return true; } // either the parent is unlocked, or no entry exists at all (treat as unlocked). return false; } //---------------------------------------------------------------------------------------------------------------------- } // namespace proxy } // namespace nodes } // namespace usdmaya } // namespace AL //---------------------------------------------------------------------------------------------------------------------- <file_sep>/test/lib/ufe/testContextOps.py #!/usr/bin/env python # # Copyright 2020 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import fixturesUtils import mayaUtils import usdUtils from pxr import UsdGeom from maya import cmds from maya import standalone from maya.internal.ufeSupport import ufeCmdWrapper as ufeCmd import ufe import os import unittest class TestAddPrimObserver(ufe.Observer): def __init__(self): super(TestAddPrimObserver, self).__init__() self.deleteNotif = 0 self.addNotif = 0 def __call__(self, notification): if isinstance(notification, ufe.ObjectDelete): self.deleteNotif += 1 if isinstance(notification, ufe.ObjectAdd): self.addNotif += 1 def nbDeleteNotif(self): return self.deleteNotif def nbAddNotif(self): return self.addNotif def reset(self): self.addNotif = 0 self.deleteNotif = 0 class ContextOpsTestCase(unittest.TestCase): '''Verify the ContextOps interface for the USD runtime.''' pluginsLoaded = False @classmethod def setUpClass(cls): fixturesUtils.readOnlySetUpClass(__file__, loadPlugin=False) if not cls.pluginsLoaded: cls.pluginsLoaded = mayaUtils.isMayaUsdPluginLoaded() @classmethod def tearDownClass(cls): standalone.uninitialize() def setUp(self): ''' Called initially to set up the maya test environment ''' # Load plugins self.assertTrue(self.pluginsLoaded) # These tests requires no additional setup. if self._testMethodName in ['testAddNewPrim', 'testAddNewPrimWithDelete']: return # Open top_layer.ma scene in testSamples mayaUtils.openTopLayerScene() # Clear selection to start off. ufe.GlobalSelection.get().clear() # Select Ball_35. ball35Path = ufe.Path([ mayaUtils.createUfePathSegment("|transform1|proxyShape1"), usdUtils.createUfePathSegment("/Room_set/Props/Ball_35")]) self.ball35Item = ufe.Hierarchy.createItem(ball35Path) self.ball35Prim = usdUtils.getPrimFromSceneItem(self.ball35Item) ufe.GlobalSelection.get().append(self.ball35Item) # Create a ContextOps interface for it. self.contextOps = ufe.ContextOps.contextOps(self.ball35Item) def testGetItems(self): # The top-level context items are: # - working set management for loadable prims and descendants # - visibility (for all prims with visibility attribute) # - variant sets, for those prims that have them (such as Ball_35) # - add new prim (for all prims) # - prim activate/deactivate contextItems = self.contextOps.getItems([]) contextItemStrings = [c.item for c in contextItems] attrs = ufe.Attributes.attributes(self.contextOps.sceneItem()) self.assertIsNotNone(attrs) hasVisibility = attrs.hasAttribute(UsdGeom.Tokens.visibility) # The proxy shape specifies loading all payloads, so Ball_35 should be # loaded, and since it has a payload, there should be an item for # unloading it. self.assertIn('Unload', contextItemStrings) self.assertIn('Variant Sets', contextItemStrings) if hasVisibility: self.assertIn('Toggle Visibility', contextItemStrings) else: self.assertNotIn('Toggle Visibility', contextItemStrings) self.assertIn('Toggle Active State', contextItemStrings) self.assertIn('Add New Prim', contextItemStrings) # Ball_35 has a single variant set, which has children. contextItems = self.contextOps.getItems(['Variant Sets']) contextItemStrings = [c.item for c in contextItems] self.assertListEqual(['shadingVariant'], contextItemStrings) self.assertTrue(contextItems[0].hasChildren) # Initial shadingVariant is "Ball_8" contextItems = self.contextOps.getItems( ['Variant Sets', 'shadingVariant']) self.assertGreater(len(contextItems), 1) for c in contextItems: self.assertFalse(c.hasChildren) self.assertTrue(c.checkable) if c.checked: self.assertEqual(c.item, 'Ball_8') def testDoOp(self): # Change visibility, undo / redo. cmd = self.contextOps.doOpCmd(['Toggle Visibility']) self.assertIsNotNone(cmd) attrs = ufe.Attributes.attributes(self.ball35Item) self.assertIsNotNone(attrs) visibility = attrs.attribute(UsdGeom.Tokens.visibility) self.assertIsNotNone(visibility) # Initially, Ball_35 has inherited visibility. self.assertEqual(visibility.get(), UsdGeom.Tokens.inherited) ufeCmd.execute(cmd) self.assertEqual(visibility.get(), UsdGeom.Tokens.invisible) cmds.undo() self.assertEqual(visibility.get(), UsdGeom.Tokens.inherited) cmds.redo() self.assertEqual(visibility.get(), UsdGeom.Tokens.invisible) cmds.undo() # Active / Deactivate Prim cmd = self.contextOps.doOpCmd(['Toggle Active State']) self.assertIsNotNone(cmd) # Initially, Ball_35 should be active. self.assertTrue(self.ball35Prim.IsActive()) ufeCmd.execute(cmd) self.assertFalse(self.ball35Prim.IsActive()) cmds.undo() self.assertTrue(self.ball35Prim.IsActive()) cmds.redo() self.assertFalse(self.ball35Prim.IsActive()) # Change variant in variant set. def shadingVariant(): contextItems = self.contextOps.getItems( ['Variant Sets', 'shadingVariant']) for c in contextItems: if c.checked: return c.item self.assertEqual(shadingVariant(), 'Ball_8') cmd = self.contextOps.doOpCmd( ['Variant Sets', 'shadingVariant', 'Cue']) self.assertIsNotNone(cmd) ufeCmd.execute(cmd) self.assertEqual(shadingVariant(), 'Cue') cmds.undo() self.assertEqual(shadingVariant(), 'Ball_8') cmds.redo() self.assertEqual(shadingVariant(), 'Cue') cmds.undo() def testAddNewPrim(self): cmds.file(new=True, force=True) # Create a proxy shape with empty stage to start with. import mayaUsd_createStageWithNewLayer proxyShape = mayaUsd_createStageWithNewLayer.createStageWithNewLayer() # Create our UFE notification observer ufeObs = TestAddPrimObserver() ufe.Scene.addObserver(ufeObs) # Create a ContextOps interface for the proxy shape. proxyShapePath = ufe.Path([mayaUtils.createUfePathSegment(proxyShape)]) proxyShapeItem = ufe.Hierarchy.createItem(proxyShapePath) contextOps = ufe.ContextOps.contextOps(proxyShapeItem) # Add a new prim. cmd = contextOps.doOpCmd(['Add New Prim', 'Xform']) self.assertIsNotNone(cmd) ufeObs.reset() ufeCmd.execute(cmd) # Ensure we got the correct UFE notifs. self.assertEqual(ufeObs.nbAddNotif(), 1) self.assertEqual(ufeObs.nbDeleteNotif(), 0) # The proxy shape should now have a single UFE child item. proxyShapehier = ufe.Hierarchy.hierarchy(proxyShapeItem) self.assertTrue(proxyShapehier.hasChildren()) self.assertEqual(len(proxyShapehier.children()), 1) # Add a new prim to the prim we just added. cmds.pickWalk(d='down') # Get the scene item from the UFE selection. snIter = iter(ufe.GlobalSelection.get()) xformItem = next(snIter) # Create a ContextOps interface for it. contextOps = ufe.ContextOps.contextOps(xformItem) # Add a new prim. cmd = contextOps.doOpCmd(['Add New Prim', 'Xform']) self.assertIsNotNone(cmd) ufeObs.reset() ufeCmd.execute(cmd) # Ensure we got the correct UFE notifs. self.assertEqual(ufeObs.nbAddNotif(), 1) self.assertEqual(ufeObs.nbDeleteNotif(), 0) # The xform prim should now have a single UFE child item. xformHier = ufe.Hierarchy.hierarchy(xformItem) self.assertTrue(xformHier.hasChildren()) self.assertEqual(len(xformHier.children()), 1) # Add another prim cmd = contextOps.doOpCmd(['Add New Prim', 'Capsule']) self.assertIsNotNone(cmd) ufeObs.reset() ufeCmd.execute(cmd) # Ensure we got the correct UFE notifs. self.assertEqual(ufeObs.nbAddNotif(), 1) self.assertEqual(ufeObs.nbDeleteNotif(), 0) # The xform prim should now have two UFE child items. self.assertTrue(xformHier.hasChildren()) self.assertEqual(len(xformHier.children()), 2) # Undo will remove the new prim, meaning one less child. ufeObs.reset() cmds.undo() self.assertTrue(xformHier.hasChildren()) self.assertEqual(len(xformHier.children()), 1) # Ensure we got the correct UFE notifs. self.assertEqual(ufeObs.nbAddNotif(), 0) self.assertEqual(ufeObs.nbDeleteNotif(), 1) # Undo again will remove the first added prim, meaning no children. cmds.undo() self.assertFalse(xformHier.hasChildren()) # Ensure we got the correct UFE notifs. self.assertEqual(ufeObs.nbAddNotif(), 0) self.assertEqual(ufeObs.nbDeleteNotif(), 2) cmds.redo() self.assertTrue(xformHier.hasChildren()) self.assertEqual(len(xformHier.children()), 1) # Ensure we got the correct UFE notifs. self.assertEqual(ufeObs.nbAddNotif(), 1) self.assertEqual(ufeObs.nbDeleteNotif(), 2) cmds.redo() self.assertTrue(xformHier.hasChildren()) self.assertEqual(len(xformHier.children()), 2) # Ensure we got the correct UFE notifs. self.assertEqual(ufeObs.nbAddNotif(), 2) self.assertEqual(ufeObs.nbDeleteNotif(), 2) def testAddNewPrimWithDelete(self): cmds.file(new=True, force=True) # Create a proxy shape with empty stage to start with. import mayaUsd_createStageWithNewLayer proxyShape = mayaUsd_createStageWithNewLayer.createStageWithNewLayer() # Create a ContextOps interface for the proxy shape. proxyShapePath = ufe.Path([mayaUtils.createUfePathSegment(proxyShape)]) proxyShapeItem = ufe.Hierarchy.createItem(proxyShapePath) contextOps = ufe.ContextOps.contextOps(proxyShapeItem) # Add a new Xform prim. cmd = contextOps.doOpCmd(['Add New Prim', 'Xform']) self.assertIsNotNone(cmd) ufeCmd.execute(cmd) # The proxy shape should now have a single UFE child item. proxyShapehier = ufe.Hierarchy.hierarchy(proxyShapeItem) self.assertTrue(proxyShapehier.hasChildren()) self.assertEqual(len(proxyShapehier.children()), 1) # Using UFE, delete this new prim (which doesn't actually delete it but # instead makes it inactive). cmds.pickWalk(d='down') cmds.delete() # The proxy shape should now have no UFE child items (since we skip inactive). self.assertFalse(proxyShapehier.hasChildren()) self.assertEqual(len(proxyShapehier.children()), 0) # Add another Xform prim (which should get a unique name taking into # account the prim we just made inactive). cmd = contextOps.doOpCmd(['Add New Prim', 'Xform']) self.assertIsNotNone(cmd) ufeCmd.execute(cmd) # The proxy shape should now have a single UFE child item. self.assertTrue(proxyShapehier.hasChildren()) self.assertEqual(len(proxyShapehier.children()), 1) def testLoadAndUnload(self): ''' Tests the working set management contextOps "Load", "Load with Descendants", and "Unload". ''' proxyShapePathSegment = mayaUtils.createUfePathSegment( '|transform1|proxyShape1') propsPath = ufe.Path([ proxyShapePathSegment, usdUtils.createUfePathSegment('/Room_set/Props')]) propsItem = ufe.Hierarchy.createItem(propsPath) ball1Path = ufe.Path([ proxyShapePathSegment, usdUtils.createUfePathSegment('/Room_set/Props/Ball_1')]) ball1Item = ufe.Hierarchy.createItem(ball1Path) ball15Path = ufe.Path([ proxyShapePathSegment, usdUtils.createUfePathSegment('/Room_set/Props/Ball_15')]) ball15Item = ufe.Hierarchy.createItem(ball15Path) def _validateLoadAndUnloadItems(hierItem, itemStrings): ALL_ITEM_STRINGS = set([ 'Load', 'Load with Descendants', 'Unload' ]) expectedItemStrings = set(itemStrings or []) expectedAbsentItemStrings = ALL_ITEM_STRINGS - expectedItemStrings contextOps = ufe.ContextOps.contextOps(hierItem) contextItems = contextOps.getItems([]) contextItemStrings = [c.item for c in contextItems] for itemString in expectedItemStrings: self.assertIn(itemString, contextItemStrings) for itemString in expectedAbsentItemStrings: self.assertNotIn(itemString, contextItemStrings) # The stage is fully loaded, so all items should have "Unload" items. _validateLoadAndUnloadItems(propsItem, ['Unload']) _validateLoadAndUnloadItems(ball1Item, ['Unload']) _validateLoadAndUnloadItems(ball15Item, ['Unload']) # The mesh prim path under each Ball asset prim has nothing loadable at # or below it, so it should not have any load or unload items. ball15meshPath = ufe.Path([ proxyShapePathSegment, usdUtils.createUfePathSegment('/Room_set/Props/Ball_15/mesh')]) ball15meshItem = ufe.Hierarchy.createItem(ball15meshPath) _validateLoadAndUnloadItems(ball15meshItem, []) # Unload Ball_1. contextOps = ufe.ContextOps.contextOps(ball1Item) cmd = contextOps.doOpCmd(['Unload']) self.assertIsNotNone(cmd) ufeCmd.execute(cmd) # Only Ball_1 should have been unloaded, and since it has a payload, it # should now have "Load" and "Load with Descendants" context items. # "Props" will now also have "Load with Descendants" because something # loadable below it is unloaded. _validateLoadAndUnloadItems(propsItem, ['Load with Descendants', 'Unload']) _validateLoadAndUnloadItems(ball1Item, ['Load', 'Load with Descendants']) _validateLoadAndUnloadItems(ball15Item, ['Unload']) cmds.undo() _validateLoadAndUnloadItems(propsItem, ['Unload']) _validateLoadAndUnloadItems(ball1Item, ['Unload']) _validateLoadAndUnloadItems(ball15Item, ['Unload']) # Unload Props. contextOps = ufe.ContextOps.contextOps(propsItem) cmd = contextOps.doOpCmd(['Unload']) self.assertIsNotNone(cmd) ufeCmd.execute(cmd) # The "Props" prim does not have a payload of its own, so it should # only have the "Load with Descendants" item. The Ball assets will also # have been unloaded. _validateLoadAndUnloadItems(propsItem, ['Load with Descendants']) _validateLoadAndUnloadItems(ball1Item, ['Load', 'Load with Descendants']) _validateLoadAndUnloadItems(ball15Item, ['Load', 'Load with Descendants']) cmds.undo() _validateLoadAndUnloadItems(propsItem, ['Unload']) _validateLoadAndUnloadItems(ball1Item, ['Unload']) _validateLoadAndUnloadItems(ball15Item, ['Unload']) cmds.redo() _validateLoadAndUnloadItems(propsItem, ['Load with Descendants']) _validateLoadAndUnloadItems(ball1Item, ['Load', 'Load with Descendants']) _validateLoadAndUnloadItems(ball15Item, ['Load', 'Load with Descendants']) # Load Props. contextOps = ufe.ContextOps.contextOps(propsItem) cmd = contextOps.doOpCmd(['Load with Descendants']) self.assertIsNotNone(cmd) ufeCmd.execute(cmd) _validateLoadAndUnloadItems(propsItem, ['Unload']) _validateLoadAndUnloadItems(ball1Item, ['Unload']) _validateLoadAndUnloadItems(ball15Item, ['Unload']) cmds.undo() _validateLoadAndUnloadItems(propsItem, ['Load with Descendants']) _validateLoadAndUnloadItems(ball1Item, ['Load', 'Load with Descendants']) _validateLoadAndUnloadItems(ball15Item, ['Load', 'Load with Descendants']) if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/test/lib/mayaUsd/nodes/testProxyShapeBase.py #!/usr/bin/env mayapy # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from maya import cmds from maya import standalone from pxr import Usd, Sdf import fixturesUtils import os import unittest import tempfile import usdUtils, mayaUtils, ufeUtils import ufe import mayaUsd.ufe class testProxyShapeBase(unittest.TestCase): @classmethod def setUpClass(cls): inputPath = fixturesUtils.setUpClass(__file__) cls.mayaSceneFilePath = os.path.join(inputPath, 'ProxyShapeBaseTest', 'ProxyShapeBase.ma') @classmethod def tearDownClass(cls): standalone.uninitialize() def testBoundingBox(self): cmds.file(self.mayaSceneFilePath, open=True, force=True) # Verify that the proxy shape read something from the USD file. bboxSize = cmds.getAttr('Cube_usd.boundingBoxSize')[0] self.assertEqual(bboxSize, (1.0, 1.0, 1.0)) @unittest.skipUnless(ufeUtils.ufeFeatureSetVersion() >= 2, 'testDuplicateProxyStageAnonymous only available in UFE v2 or greater.') def testDuplicateProxyStageAnonymous(self): ''' Verify stage with new anonymous layer is duplicated properly. ''' cmds.file(new=True, force=True) # create a proxy shape and add a Capsule prim import mayaUsd_createStageWithNewLayer proxyShape = mayaUsd_createStageWithNewLayer.createStageWithNewLayer() proxyShapePath = ufe.PathString.path(proxyShape) proxyShapeItem = ufe.Hierarchy.createItem(proxyShapePath) proxyShapeContextOps = ufe.ContextOps.contextOps(proxyShapeItem) proxyShapeContextOps.doOp(['Add New Prim', 'Capsule']) # proxy shape is expected to have one child proxyShapeHier = ufe.Hierarchy.hierarchy(proxyShapeItem) self.assertEqual(1, len(proxyShapeHier.children())) # child name is expected to be Capsule1 self.assertEqual(str(proxyShapeHier.children()[0].nodeName()), "Capsule1") # validate session name and anonymous tag name stage = mayaUsd.ufe.getStage(str(proxyShapePath)) self.assertEqual(stage.GetLayerStack()[0], stage.GetSessionLayer()) self.assertEqual(stage.GetEditTarget().GetLayer(), stage.GetRootLayer()) self.assertEqual(True, "-session" in stage.GetSessionLayer().identifier) self.assertEqual(True, "anonymousLayer1" in stage.GetRootLayer().identifier) # add proxyShapeItem to selection list ufe.GlobalSelection.get().append(proxyShapeItem) # duplicate the proxyShape. cmds.duplicate() # get the next item in UFE selection list. snIter = iter(ufe.GlobalSelection.get()) duplStageItem = next(snIter) # duplicated stage name is expected to be incremented correctly self.assertEqual(str(duplStageItem.nodeName()), "stage2") # duplicated proxyShape name is expected to be incremented correctly duplProxyShapeHier = ufe.Hierarchy.hierarchy(duplStageItem) duplProxyShapeItem = duplProxyShapeHier.children()[0] self.assertEqual(str(duplProxyShapeItem.nodeName()), "stageShape2") # duplicated ProxyShapeItem should have exactly one child self.assertEqual(1, len(ufe.Hierarchy.hierarchy(duplProxyShapeItem).children())) # child name is expected to be Capsule1 childName = str(ufe.Hierarchy.hierarchy(duplProxyShapeItem).children()[0].nodeName()) self.assertEqual(childName, "Capsule1") # validate session name and anonymous tag name duplStage = mayaUsd.ufe.getStage(str(ufe.PathString.path('|stage2|stageShape2'))) self.assertEqual(duplStage.GetLayerStack()[0], duplStage.GetSessionLayer()) self.assertEqual(duplStage.GetEditTarget().GetLayer(), duplStage.GetRootLayer()) self.assertEqual(True, "-session" in duplStage.GetSessionLayer().identifier) self.assertEqual(True, "anonymousLayer1" in duplStage.GetRootLayer().identifier) # confirm that edits are not shared (a.k.a divorced). cmds.delete('|stage2|stageShape2,/Capsule1') self.assertEqual(0, len(ufe.Hierarchy.hierarchy(duplProxyShapeItem).children())) self.assertEqual(1, len(ufe.Hierarchy.hierarchy(proxyShapeItem).children())) @unittest.skipUnless(ufeUtils.ufeFeatureSetVersion() >= 2, 'testDuplicateProxyStageFileBacked only available in UFE v2 or greater.') def testDuplicateProxyStageFileBacked(self): ''' Verify stage from file is duplicated properly. ''' # open tree.ma scene mayaUtils.openTreeScene() # clear selection to start off cmds.select(clear=True) # select a USD object. mayaPathSegment = mayaUtils.createUfePathSegment('|Tree_usd|Tree_usdShape') usdPathSegment = usdUtils.createUfePathSegment('/TreeBase') treebasePath = ufe.Path([mayaPathSegment]) treebaseItem = ufe.Hierarchy.createItem(treebasePath) # TreeBase has two children self.assertEqual(1, len(ufe.Hierarchy.hierarchy(treebaseItem).children())) # get the USD stage stage = mayaUsd.ufe.getStage(str(mayaPathSegment)) # by default edit target is set to the Rootlayer. self.assertEqual(stage.GetEditTarget().GetLayer(), stage.GetRootLayer()) # add treebaseItem to selection list ufe.GlobalSelection.get().append(treebaseItem) # duplicate cmds.duplicate() # get the next item in UFE selection list. snIter = iter(ufe.GlobalSelection.get()) duplStageItem = next(snIter) # duplicated stage name is expected to be incremented correctly self.assertEqual(str(duplStageItem.nodeName()), "Tree_usd1") # duplicated proxyShape name is expected to be incremented correctly duplProxyShapeHier = ufe.Hierarchy.hierarchy(duplStageItem) duplProxyShapeItem = duplProxyShapeHier.children()[0] self.assertEqual(str(duplProxyShapeItem.nodeName()), "Tree_usd1Shape") # duplicated ProxyShapeItem should have exactly one child self.assertEqual(1, len(ufe.Hierarchy.hierarchy(duplProxyShapeItem).children())) # child name is expected to be Capsule1 childName = str(ufe.Hierarchy.hierarchy(duplProxyShapeItem).children()[0].nodeName()) self.assertEqual(childName, "TreeBase") # validate session name and anonymous tag name duplStage = mayaUsd.ufe.getStage(str(ufe.PathString.path('|Tree_usd1|Tree_usd1Shape'))) self.assertEqual(duplStage.GetLayerStack()[0], duplStage.GetSessionLayer()) self.assertEqual(duplStage.GetEditTarget().GetLayer(), duplStage.GetRootLayer()) self.assertEqual(True, "-session" in duplStage.GetSessionLayer().identifier) self.assertEqual(True, "tree.usd" in duplStage.GetRootLayer().identifier) # delete "/TreeBase" cmds.delete('|Tree_usd1|Tree_usd1Shape,/TreeBase') # confirm that edits are shared. Both source and duplicated proxyShapes have no children now. self.assertEqual(0, len(ufe.Hierarchy.hierarchy(duplProxyShapeItem).children())) self.assertEqual(0, len(ufe.Hierarchy.hierarchy(treebaseItem).children())) def testShareStage(self): ''' Verify share/unshare stage workflow works properly ''' # create new stage cmds.file(new=True, force=True) # Open usdCylinder.ma scene in testSamples mayaUtils.openCylinderScene() # get the stage proxyShapes = cmds.ls(type="mayaUsdProxyShapeBase", long=True) proxyShapePath = proxyShapes[0] stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() rootIdentifier = stage.GetRootLayer().identifier # check that the stage is shared and the root is the right one self.assertTrue(cmds.getAttr('{}.{}'.format(proxyShapePath,"shareStage"))) self.assertEqual(stage.GetRootLayer().GetDisplayName(), "cylinder.usda") # unshare the stage cmds.setAttr('{}.{}'.format(proxyShapePath,"shareStage"), False) stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() rootLayer = stage.GetRootLayer() # check that the stage is now unshared and the root is the anon layer # and the old root is now sublayered under that self.assertFalse(cmds.getAttr('{}.{}'.format(proxyShapePath,"shareStage"))) self.assertEqual(rootLayer.GetDisplayName(), "unshareableLayer") self.assertEqual(rootLayer.subLayerPaths, [rootIdentifier]) # re-share the stage cmds.setAttr('{}.{}'.format(proxyShapePath,"shareStage"), True) stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() # check that the stage is now shared again and the layer is the same self.assertTrue(cmds.getAttr('{}.{}'.format(proxyShapePath,"shareStage"))) self.assertEqual(stage.GetRootLayer().GetDisplayName(), "cylinder.usda") def testSerializationShareStage(self): ''' Verify share/unshare stage works with serialization and complex heirharchies ''' # create new stage cmds.file(new=True, force=True) # Open usdCylinder.ma scene in testSamples mayaUtils.openCylinderScene() # get the stage proxyShapes = cmds.ls(type="mayaUsdProxyShapeBase", long=True) proxyShapePath = proxyShapes[0] stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() originalRootIdentifier = stage.GetRootLayer().identifier # check that the stage is shared and the root is the right one self.assertTrue(cmds.getAttr('{}.{}'.format(proxyShapePath,"shareStage"))) self.assertEqual(stage.GetRootLayer().GetDisplayName(), "cylinder.usda") # unshare the stage cmds.setAttr('{}.{}'.format(proxyShapePath,"shareStage"), False) stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() rootLayer = stage.GetRootLayer() # check that the stage is now unshared and the root is the anon layer # and the old root is now sublayered under that self.assertFalse(cmds.getAttr('{}.{}'.format(proxyShapePath,"shareStage"))) self.assertEqual(rootLayer.GetDisplayName(), "unshareableLayer") self.assertEqual(rootLayer.subLayerPaths, [originalRootIdentifier]) middleLayer = Sdf.Layer.CreateAnonymous("middleLayer") middleLayer.subLayerPaths = [originalRootIdentifier] rootLayer.subLayerPaths = [middleLayer.identifier] # Save and re-open testDir = tempfile.mkdtemp(prefix='ProxyShapeBase') tempMayaFile = os.path.join(testDir, 'ShareStageSerializationTest.ma') cmds.file(rename=tempMayaFile) # make the USD layer absolute otherwise it won't be found cmds.setAttr('{}.{}'.format(proxyShapePath,"filePath"), originalRootIdentifier, type='string') cmds.file(save=True, force=True) cmds.file(new=True, force=True) cmds.file(tempMayaFile, open=True) # get the stage again (since we opened a new file) proxyShapes = cmds.ls(type="mayaUsdProxyShapeBase", long=True) proxyShapePath = proxyShapes[0] stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() rootLayer = stage.GetRootLayer() # make sure the middle layer is back (only one) self.assertEqual(len(rootLayer.subLayerPaths), 1) middleLayer = Sdf.Layer.Find(rootLayer.subLayerPaths[0]) self.assertEqual(middleLayer.GetDisplayName(), "middleLayer") # make sure the middle layer still contains the original root only self.assertEqual(len(middleLayer.subLayerPaths), 1) self.assertEqual(middleLayer.subLayerPaths[0], originalRootIdentifier) # re-share the stage cmds.setAttr('{}.{}'.format(proxyShapePath,"shareStage"), True) stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() # check that the stage is now shared again and the identifier is correct self.assertTrue(cmds.getAttr('{}.{}'.format(proxyShapePath,"shareStage"))) self.assertEqual(stage.GetRootLayer().identifier, originalRootIdentifier) def testShareStageComplexHierarchyToggle(self): ''' Verify share/unshare stage toggle works with complex heirharchies ''' # create new stage cmds.file(new=True, force=True) # Open usdCylinder.ma scene in testSamples mayaUtils.openCylinderScene() # get the stage proxyShapes = cmds.ls(type="mayaUsdProxyShapeBase", long=True) proxyShapePath = proxyShapes[0] stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() originalRootIdentifier = stage.GetRootLayer().identifier # check that the stage is shared and the root is the right one self.assertTrue(cmds.getAttr('{}.{}'.format(proxyShapePath,"shareStage"))) self.assertEqual(stage.GetRootLayer().GetDisplayName(), "cylinder.usda") # unshare the stage cmds.setAttr('{}.{}'.format(proxyShapePath,"shareStage"), False) stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() rootLayer = stage.GetRootLayer() # check that the stage is now unshared and the root is the anon layer # and the old root is now sublayered under that self.assertFalse(cmds.getAttr('{}.{}'.format(proxyShapePath,"shareStage"))) self.assertEqual(rootLayer.GetDisplayName(), "unshareableLayer") self.assertEqual(rootLayer.subLayerPaths, [originalRootIdentifier]) middleLayer = Sdf.Layer.CreateAnonymous("middleLayer") middleLayer.subLayerPaths = [originalRootIdentifier] rootLayer.subLayerPaths = [middleLayer.identifier] # Save and re-open testDir = tempfile.mkdtemp(prefix='ProxyShapeBase') tempMayaFile = os.path.join(testDir, 'ShareStageComplexHierarchyToggle.ma') cmds.file(rename=tempMayaFile) # make the USD layer absolute otherwise it won't be found cmds.setAttr('{}.{}'.format(proxyShapePath,"filePath"), originalRootIdentifier, type='string') cmds.file(save=True, force=True) cmds.file(new=True, force=True) cmds.file(tempMayaFile, open=True) # get the stage again (since we opened a new file) proxyShapes = cmds.ls(type="mayaUsdProxyShapeBase", long=True) proxyShapePath = proxyShapes[0] stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() rootLayer = stage.GetRootLayer() # make sure the middle layer is back (only one) self.assertEqual(len(rootLayer.subLayerPaths), 1) middleLayer = Sdf.Layer.Find(rootLayer.subLayerPaths[0]) self.assertEqual(middleLayer.GetDisplayName(), "middleLayer") # re-share the stage cmds.setAttr('{}.{}'.format(proxyShapePath,"shareStage"), True) stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() # check that the stage is now shared again and the identifier is correct self.assertTrue(cmds.getAttr('{}.{}'.format(proxyShapePath,"shareStage"))) self.assertEqual(stage.GetRootLayer().identifier, originalRootIdentifier) # unshare the stage cmds.setAttr('{}.{}'.format(proxyShapePath,"shareStage"), False) stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() rootLayer = stage.GetRootLayer() # check that the stage is now shared and the root is the anon layer # and the old root is now sublayered under that self.assertFalse(cmds.getAttr('{}.{}'.format(proxyShapePath,"shareStage"))) self.assertEqual(rootLayer.GetDisplayName(), "unshareableLayer") self.assertEqual(rootLayer.subLayerPaths, [middleLayer.identifier]) def testShareStageSourceChange(self): ''' Verify the stage source change maintains the position in the hierarchy ''' # create new stage cmds.file(new=True, force=True) # Open usdCylinder.ma scene in testSamples mayaUtils.openCylinderScene() # get the proxy shape path proxyShapes = cmds.ls(type="mayaUsdProxyShapeBase", long=True) proxyShapeA = proxyShapes[0] # create another proxyshape (B) import mayaUsd_createStageWithNewLayer proxyShapeB = mayaUsd_createStageWithNewLayer.createStageWithNewLayer() proxyShapeB = proxyShapeB.split("|")[-1] # Connect them using stage data cmds.connectAttr('{}.outStageData'.format(proxyShapeA), '{}.inStageData'.format(proxyShapeB)) # get the stage stageB = mayaUsd.lib.GetPrim(proxyShapeB).GetStage() originalRootIdentifierB = stageB.GetRootLayer().identifier # check that the stage is shared and the root is the right one self.assertTrue(cmds.getAttr('{}.{}'.format(proxyShapeB,"shareStage"))) self.assertEqual(stageB.GetRootLayer().GetDisplayName(), "cylinder.usda") # unshare the stage cmds.setAttr('{}.{}'.format(proxyShapeB,"shareStage"), False) stageB = mayaUsd.lib.GetPrim(proxyShapeB).GetStage() rootLayerB = stageB.GetRootLayer() # check that the stage is now unshared and the root is the anon layer # and the old root is now sublayered under that self.assertFalse(cmds.getAttr('{}.{}'.format(proxyShapeB,"shareStage"))) self.assertEqual(rootLayerB.GetDisplayName(), "unshareableLayer") self.assertEqual(rootLayerB.subLayerPaths, [originalRootIdentifierB]) # Add complex hierarchy middleLayerB = Sdf.Layer.CreateAnonymous("middleLayer") middleLayerB.subLayerPaths = [originalRootIdentifierB] rootLayerB.subLayerPaths = [middleLayerB.identifier] # unshare the stage from the first proxy cmds.setAttr('{}.{}'.format(proxyShapeA, "shareStage"), False) stageA = mayaUsd.lib.GetPrim(proxyShapeA).GetStage() rootLayerA = stageA.GetRootLayer() stageB = mayaUsd.lib.GetPrim(proxyShapeB).GetStage() rootLayerB = stageB.GetRootLayer() # check that the stage is now unshared and the entire hierachy is good (A) self.assertFalse(cmds.getAttr('{}.{}'.format(proxyShapeA,"shareStage"))) self.assertEqual(rootLayerA.GetDisplayName(), "unshareableLayer") self.assertEqual(len(rootLayerA.subLayerPaths), 1) self.assertEqual(rootLayerA.subLayerPaths[0], originalRootIdentifierB) # Make sure the hierachy is good (B) self.assertFalse(cmds.getAttr('{}.{}'.format(proxyShapeB,"shareStage"))) self.assertEqual(rootLayerB.GetDisplayName(), "unshareableLayer") self.assertEqual(len(rootLayerB.subLayerPaths), 1) middleLayer = Sdf.Layer.Find(rootLayerB.subLayerPaths[0]) self.assertEqual(middleLayer.GetDisplayName(), "middleLayer") self.assertEqual(len(middleLayer.subLayerPaths), 1) unshareableLayerFromA = Sdf.Layer.Find(middleLayer.subLayerPaths[0]) self.assertEqual(unshareableLayerFromA.GetDisplayName(), "unshareableLayer") self.assertEqual(len(unshareableLayerFromA.subLayerPaths), 1) self.assertEqual(unshareableLayerFromA.subLayerPaths[0], originalRootIdentifierB) if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/lib/mayaUsd/undo/UsdUndoBlock.cpp // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "UsdUndoBlock.h" #include "UsdUndoManager.h" #include <mayaUsd/base/debugCodes.h> #include <pxr/usd/sdf/layer.h> #include <pxr/usd/usd/prim.h> namespace MAYAUSD_NS_DEF { uint32_t UsdUndoBlock::_undoBlockDepth { 0 }; const MString UsdUndoBlockCmd::commandName { "undoBlockCmd" }; UsdUndoableItem UsdUndoBlockCmd::argUndoItem; UsdUndoBlock::UsdUndoBlock() : UsdUndoBlock(nullptr) { } UsdUndoBlock::UsdUndoBlock(UsdUndoableItem* undoItem) : _undoItem(undoItem) { // TfDebug::Enable(USDMAYA_UNDOSTACK); TF_DEBUG_MSG(USDMAYA_UNDOSTACK, "--Opening undo block at depth %i\n", _undoBlockDepth); ++_undoBlockDepth; } UsdUndoBlock::~UsdUndoBlock() { auto& undoManager = UsdUndoManager::instance(); // decrease the depth --_undoBlockDepth; if (_undoBlockDepth == 0) { if (_undoItem == nullptr) { // create an undoable item UsdUndoableItem undoItem; // transfer edits undoManager.transferEdits(undoItem); // execute command UsdUndoBlockCmd::execute(undoItem); } else { // transfer edits undoManager.transferEdits(*_undoItem); } TF_DEBUG_MSG(USDMAYA_UNDOSTACK, "Undoable Item adopted the new edits.\n"); } TF_DEBUG_MSG(USDMAYA_UNDOSTACK, "--Closed undo block at depth %i\n", _undoBlockDepth); } void UsdUndoBlockCmd::execute(const UsdUndoableItem& undoableItem) { argUndoItem = undoableItem; auto status = MGlobal::executeCommand(commandName, true, true); if (!status) { TF_CODING_ERROR("Executing undoBlock command failed!"); } argUndoItem = UsdUndoableItem(); } UsdUndoBlockCmd::UsdUndoBlockCmd(UsdUndoableItem undoableItem) : _undoItem(std::move(undoableItem)) { } bool UsdUndoBlockCmd::isUndoable() const { return true; } void* UsdUndoBlockCmd::creator() { return new UsdUndoBlockCmd(std::move(argUndoItem)); } MStatus UsdUndoBlockCmd::doIt(const MArgList& args) { /* Do nothing */ return MS::kSuccess; } MStatus UsdUndoBlockCmd::redoIt() { _undoItem.redo(); return MS::kSuccess; } MStatus UsdUndoBlockCmd::undoIt() { _undoItem.undo(); return MS::kSuccess; } } // namespace MAYAUSD_NS_DEF<file_sep>/lib/mayaUsd/python/__init__.py from pxr import Tf if hasattr(Tf, 'PreparePythonModule'): Tf.PreparePythonModule('_mayaUsd') else: from . import _mayaUsd Tf.PrepareModule(_mayaUsd, locals()) del _mayaUsd del Tf <file_sep>/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/ProxyShapeMetaData.cpp // // Copyright 2017 Animal Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "AL/usdmaya/Metadata.h" #include "AL/usdmaya/fileio/SchemaPrims.h" #include "AL/usdmaya/fileio/TransformIterator.h" #include "AL/usdmaya/nodes/ProxyShape.h" #include "AL/usdmaya/nodes/Transform.h" namespace AL { namespace usdmaya { namespace nodes { //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::removeMetaData(const SdfPathVector& removedPaths) { TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::removeMetaData"); m_selectabilityDB.removePathsAsUnselectable(removedPaths); m_lockManager.removeEntries(removedPaths); } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::processChangedMetaData( const SdfPathVector& resyncedPaths, const SdfPathVector& changedOnlyPaths) { TF_DEBUG(ALUSDMAYA_EVENTS) .Msg( "ProxyShape::processChangedMetaData - processing changes %lu %lu\n", resyncedPaths.size(), changedOnlyPaths.size()); // if this is just a data change (rather than a variant switch), check for any meta data changes if (m_variantSwitchedPrims.empty()) { // figure out whether selectability has changed. for (const SdfPath& path : changedOnlyPaths) { UsdPrim changedPrim = m_stage->GetPrimAtPath(path); if (!changedPrim) { continue; } TfToken selectabilityPropertyToken; if (changedPrim.GetMetadata<TfToken>( Metadata::selectability, &selectabilityPropertyToken)) { bool hasPath = m_selectabilityDB.containsPath(path); // Check if this prim is unselectable if (selectabilityPropertyToken == Metadata::unselectable) { if (!hasPath) { m_selectabilityDB.addPathAsUnselectable(path); } } if (hasPath) { m_selectabilityDB.removePathAsUnselectable(path); } } // build up new lock-prim list TfToken lockPropertyToken; if (changedPrim.GetMetadata<TfToken>(Metadata::locked, &lockPropertyToken)) { if (lockPropertyToken == Metadata::lockTransform) { m_lockManager.setLocked(path); } else if (lockPropertyToken == Metadata::lockUnlocked) { m_lockManager.setUnlocked(path); } else { m_lockManager.setInherited(path); } } else { m_lockManager.setInherited(path); } } m_lockManager.sort(); } else { auto& unselectablePaths = m_selectabilityDB.m_unselectablePaths; // figure out whether selectability has changed. for (const SdfPath& path : resyncedPaths) { UsdPrim syncPrimRoot = m_stage->GetPrimAtPath(path); if (!syncPrimRoot) { // TODO : Ensure elements have been removed from selectabilityDB, excludeGeom, and // lock prims continue; } // determine range of selectable prims we need to replace in the selectability DB auto lb = std::lower_bound(unselectablePaths.begin(), unselectablePaths.end(), path); auto ub = lb; if (lb != unselectablePaths.end()) { while (ub != unselectablePaths.end() && ub->HasPrefix(*lb)) { ++ub; } } m_lockManager.removeFromRootPath(path); // sort the excluded tagged geom to help searching std::sort(m_excludedTaggedGeometry.begin(), m_excludedTaggedGeometry.end()); // fill these lists as we traverse SdfPathVector newUnselectables; SdfPathVector newExcludeGeom; // keep track of where the last item in the original set of prims is. // As we traverse, lookups will be performed on the first elements in the array, so that // will remain sorted. Items appended to the end of the array will not be sorted. // In order to do this without using a 2nd vector, I'm using the lastTaggedPrim to // denote the boundary between the sorted and unsorted prims size_t lastTaggedPrim = m_excludedTaggedGeometry.size(); // from the resync prim, traverse downwards through the child prims for (fileio::TransformIterator it(syncPrimRoot, parentTransform(), true); !it.done(); it.next()) { auto prim = it.prim(); auto path = prim.GetPath(); // first check to see if the excluded geom has changed { bool excludeGeo = false; if (prim.GetMetadata(Metadata::excludeFromProxyShape, &excludeGeo) && excludeGeo) { auto last = m_excludedTaggedGeometry.begin() + lastTaggedPrim; auto it = std::lower_bound(m_excludedTaggedGeometry.begin(), last, path); if (it != last && *it == path) { // we already have an entry for this prim } else { // add to back of list m_excludedTaggedGeometry.emplace_back(path); } } else { // if we aren't excluding the geom, but have an existing entry, remove it. auto last = m_excludedTaggedGeometry.begin() + lastTaggedPrim; auto it = std::lower_bound(m_excludedTaggedGeometry.begin(), last, path); if (it != last && *it == path) { m_excludedTaggedGeometry.erase(it); --lastTaggedPrim; } } // If prim has exclusion tag or is a descendent of a prim with it, create as // Maya geo if (excludeGeo || primHasExcludedParent(prim)) { VtValue schemaName(fileio::ALExcludedPrimSchema.GetString()); prim.SetCustomDataByKey(fileio::ALSchemaType, schemaName); } } // build up new unselectable list TfToken selectabilityPropertyToken; if (prim.GetMetadata<TfToken>( Metadata::selectability, &selectabilityPropertyToken)) { if (selectabilityPropertyToken == Metadata::unselectable) { newUnselectables.emplace_back(path); } } // build up new lock-prim list TfToken lockPropertyToken; if (prim.GetMetadata<TfToken>(Metadata::locked, &lockPropertyToken)) { if (lockPropertyToken == Metadata::lockTransform) { m_lockManager.addLocked(path); } else if (lockPropertyToken == Metadata::lockUnlocked) { m_lockManager.addUnlocked(path); } } } m_lockManager.sort(); // sort and merge into previous selectable database std::sort(newUnselectables.begin(), newUnselectables.end()); if (lb == unselectablePaths.end()) { if (!newUnselectables.empty()) { unselectablePaths.insert( unselectablePaths.end(), newUnselectables.begin(), newUnselectables.end()); } } else { // TODO: could probably overwrite some of old paths here, and then insert the // remaining new elements. lb = unselectablePaths.erase(lb, ub); if (!newUnselectables.empty()) { unselectablePaths.insert(lb, newUnselectables.begin(), newUnselectables.end()); } } } } // reconstruct the lock prims { constructLockPrims(); } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::constructExcludedPrims() { auto excludedPaths = getExcludePrimPaths(); if (m_excludedGeometry != excludedPaths) { std::swap(m_excludedGeometry, excludedPaths); constructGLImagingEngine(); } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::constructLockPrims() { TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::constructLockPrims\n"); // iterate over the for (auto it : m_requiredPaths) { Scope* s = it.second.getTransformNode(); if (!s) { continue; } const UsdPrim& prim = s->transform()->prim(); if (prim) { bool is_locked = m_lockManager.isLocked(prim.GetPath()); MObject lockObject = s->thisMObject(); MPlug t(lockObject, m_transformTranslate); MPlug r(lockObject, m_transformRotate); MPlug s(lockObject, m_transformScale); t.setLocked(is_locked); r.setLocked(is_locked); s.setLocked(is_locked); if (is_locked) { MFnDependencyNode fn(lockObject); Transform* transformNode = dynamic_cast<Transform*>(fn.userNode()); if (transformNode) { MPlug plug(lockObject, Transform::pushToPrim()); if (plug.asBool()) plug.setBool(false); } } } } } //---------------------------------------------------------------------------------------------------------------------- bool ProxyShape::primHasExcludedParent(UsdPrim prim) { if (prim.IsValid()) { SdfPath primPath = prim.GetPrimPath(); TF_FOR_ALL(excludedPath, m_excludedTaggedGeometry) { if (primPath.HasPrefix(*excludedPath)) { TF_DEBUG(ALUSDMAYA_EVALUATION) .Msg("ProxyShape::primHasExcludedParent %s=true\n", primPath.GetText()); return true; } } } return false; } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::findPrimsWithMetaData() { TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::findPrimsWithMetaData\n"); if (!m_stage) return; if (isLockPrimFeatureActive()) { SdfPathVector newUnselectables; for (fileio::TransformIterator it(m_stage, parentTransform(), true); !it.done(); it.next()) { auto prim = it.prim(); bool excludeGeo = false; if (prim.GetMetadata(Metadata::excludeFromProxyShape, &excludeGeo)) { if (excludeGeo) { m_excludedTaggedGeometry.push_back(prim.GetPrimPath()); } } // If prim has exclusion tag or is a descendent of a prim with it, create as Maya geo if (excludeGeo || primHasExcludedParent(prim)) { VtValue schemaName(fileio::ALExcludedPrimSchema.GetString()); prim.SetCustomDataByKey(fileio::ALSchemaType, schemaName); } TfToken selectabilityPropertyToken; if (prim.GetMetadata<TfToken>(Metadata::selectability, &selectabilityPropertyToken)) { // Check if this prim is unselectable if (selectabilityPropertyToken == Metadata::unselectable) { newUnselectables.push_back(prim.GetPath()); } } // build up new lock-prim list TfToken lockPropertyToken; if (prim.GetMetadata<TfToken>(Metadata::locked, &lockPropertyToken)) { if (lockPropertyToken == Metadata::lockTransform) { m_lockManager.setLocked(prim.GetPath()); } else if (lockPropertyToken == Metadata::lockUnlocked) { m_lockManager.setUnlocked(prim.GetPath()); } else if (lockPropertyToken == Metadata::lockInherited) { m_lockManager.setInherited(prim.GetPath()); } } else { m_lockManager.setInherited(prim.GetPath()); } } constructLockPrims(); constructExcludedPrims(); m_selectabilityDB.setPathsAsUnselectable(newUnselectables); } } //---------------------------------------------------------------------------------------------------------------------- SdfPathVector ProxyShape::getExcludePrimPaths() const { TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::getExcludePrimPaths\n"); SdfPathVector paths = getPrimPathsFromCommaJoinedString(excludePrimPathsPlug().asString()); SdfPathVector temp = getPrimPathsFromCommaJoinedString(excludedTranslatedGeometryPlug().asString()); paths.insert(paths.end(), temp.begin(), temp.end()); return paths; } //---------------------------------------------------------------------------------------------------------------------- } // namespace nodes } // namespace usdmaya } // namespace AL //---------------------------------------------------------------------------------------------------------------------- <file_sep>/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/LockManager.h // // Copyright 2017 Animal Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include <AL/usdmaya/Api.h> #include <pxr/usd/sdf/path.h> PXR_NAMESPACE_USING_DIRECTIVE namespace AL { namespace usdmaya { namespace nodes { namespace proxy { //---------------------------------------------------------------------------------------------------------------------- /// \brief A class that maintains a list of locked and unlocked prims. //---------------------------------------------------------------------------------------------------------------------- struct LockManager { /// \brief removes the specified paths from the locked and unlocked sets /// \param entries the array of entires to remove. AL_USDMAYA_PUBLIC void removeEntries(const SdfPathVector& entries); /// \brief removes all entries from the locked and unlocked sets that are a child of the /// specified path \param path the root path to remove AL_USDMAYA_PUBLIC void removeFromRootPath(const SdfPath& path); /// \brief sets the specified path as locked (and any paths that inherit their state from their /// parent). /// If the path exists within the unlocked set, it will be removed. /// \param path the path to insert into the locked set AL_USDMAYA_PUBLIC void setLocked(const SdfPath& path); /// \brief sets the specified path as unlocked (and any paths that inherit their state from /// their parent). /// If the path exists within the locked set, it will be removed. /// \param path the path to insert into the unlocked set AL_USDMAYA_PUBLIC void setUnlocked(const SdfPath& path); /// \brief adds the specified path to the locked prims list. No checking is done by this method /// to see whether /// the path is part of the locked or unlocked sets. The intention for this method is to /// quickly build up changes in the set of lock prims, and having done that, later sort /// them by calling sort() /// \param path the path to insert into the locked set inline void addLocked(const SdfPath& path) { m_lockedPrims.emplace_back(path); } /// \brief adds the specified path to the unlocked prims list. No checking is done by this /// method to see whether /// the path is part of the locked or unlocked sets. The intention for this method is to /// quickly build up changes in the set of lock prims, and having done that, later sort /// them by calling sort() /// \param path the path to insert into the unlocked set inline void addUnlocked(const SdfPath& path) { m_unlockedPrims.emplace_back(path); } /// \brief sorts the two sets of locked and unlocked prims for fast lookup inline void sort() { std::sort(m_lockedPrims.begin(), m_lockedPrims.end()); std::sort(m_unlockedPrims.begin(), m_unlockedPrims.end()); } /// \brief Will remove the path from both the locked and unlocked sets. The lock status will /// now be inherited. \param path the path to set as inherited AL_USDMAYA_PUBLIC void setInherited(const SdfPath& path); /// \brief a query function to determine whether the specified path is locked or not. /// \param path the path to query the lock status for /// \return true if the prim is locked (either by explicitly being set as locked, or by /// inheriting a lock status) AL_USDMAYA_PUBLIC bool isLocked(const SdfPath& path) const; private: SdfPathVector m_lockedPrims; SdfPathVector m_unlockedPrims; }; //---------------------------------------------------------------------------------------------------------------------- } // namespace proxy } // namespace nodes } // namespace usdmaya } // namespace AL //---------------------------------------------------------------------------------------------------------------------- <file_sep>/doc/CHANGELOG.md # Changelog ## [0.12.0] - 2021-08-23 **Build:** - Implement HdMayaSceneDelegate::GetInstancerPrototypes [#1604](https://github.com/Autodesk/maya-usd/pull/1604) - Fix unit tests to run in Debug builds [#1593](https://github.com/Autodesk/maya-usd/pull/1593) **Translation Framework:** - Export opacity of standardSurface to usdPreviewSurface and back [#1611](https://github.com/Autodesk/maya-usd/pull/1611) - Avoid TF_Verify message when USD attribute is empty [#1599](https://github.com/Autodesk/maya-usd/pull/1599) - Export roots [#1592](https://github.com/Autodesk/maya-usd/pull/1592) - Fix warnings from USDZ texture import [#1589](https://github.com/Autodesk/maya-usd/pull/1589) - Add support for light translators [#1577](https://github.com/Autodesk/maya-usd/pull/1577) - ProxyShape: add pauseUpdate attr to pause evaluation [#1511](https://github.com/Autodesk/maya-usd/pull/1511) **Workflow:** - No USD prompt during crash [#1601](https://github.com/Autodesk/maya-usd/pull/1601) - Add grouping with absolute, relative, world flags [#1600](https://github.com/Autodesk/maya-usd/pull/1600) - Fix crash on scene item creation [#1596](https://github.com/Autodesk/maya-usd/pull/1596) - Matrix op, common API undo/redo [#1586](https://github.com/Autodesk/maya-usd/pull/1586) - Make USD menu tear-off-able [#1575](https://github.com/Autodesk/maya-usd/pull/1575) **Render:** - Revert to using shading with the V1 lighting API [#1626](https://github.com/Autodesk/maya-usd/pull/1626) - Implement UsdTexture2d support in VP2 render delegate [#1617](https://github.com/Autodesk/maya-usd/pull/1617) - Maya 2022.1 has the Light loop API V2 and is compatible with MaterialX [#1609](https://github.com/Autodesk/maya-usd/pull/1609) - Fix rprim state assertions [#1607](https://github.com/Autodesk/maya-usd/pull/1607) - Remove hardcode camera name string [#1598](https://github.com/Autodesk/maya-usd/pull/1598) - Store the correct render item name in HdVP2DrawItem [#1597](https://github.com/Autodesk/maya-usd/pull/1597) **Documentation:** - Fix minor typos in "lock" and "selectability" tutorials [#1574](https://github.com/Autodesk/maya-usd/pull/1574) ## [0.11.0] - 2021-07-27 **Build:** - Remove deprecated UsdRi schemas [#1585](https://github.com/Autodesk/maya-usd/pull/1585) - Bump USD min version to 20.05 [#1568](https://github.com/Autodesk/maya-usd/pull/1568) - Fixed two tests with the same name [#1562](https://github.com/Autodesk/maya-usd/pull/1562) - Pxr tests will use build area for temporary files [#1443](https://github.com/Autodesk/maya-usd/pull/1443) **Translation Framework:** - Review all standard surface default values [#1560](https://github.com/Autodesk/maya-usd/pull/1560) - Remove calls to configure resolver for asset under ar2 [#1530](https://github.com/Autodesk/maya-usd/pull/1530) - UV set renamed to st, st1, st2 [#1528](https://github.com/Autodesk/maya-usd/pull/1528) - Add geomSidedness flag to exporter [#1499](https://github.com/Autodesk/maya-usd/pull/1499) - Fixed bug with visibility determination [#1479](https://github.com/Autodesk/maya-usd/pull/1479) **Workflow:** - Crash when transforming multiple objects with duplicate stage [#1554](https://github.com/Autodesk/maya-usd/pull/1554) - Add restriction for grouping [#1550](https://github.com/Autodesk/maya-usd/pull/1550) - Stage to be created without the proxyShape being capitalized [#1526](https://github.com/Autodesk/maya-usd/pull/1526) - Handle multiple deferred notifs for single path [#1519](https://github.com/Autodesk/maya-usd/pull/1519) - Use SdfComputeAssetPathRelativeToLayer to compute sublayer paths [#1515](https://github.com/Autodesk/maya-usd/pull/1515) - Deleting assembly nodes that contained child assemblies crashes Maya [#1504](https://github.com/Autodesk/maya-usd/pull/1504) - Add support for ungroup command [#1469](https://github.com/Autodesk/maya-usd/pull/1469) - New unshareable stage workflow [#1455](https://github.com/Autodesk/maya-usd/pull/1455) - Disable save for unshared layer root [#1584](https://github.com/Autodesk/maya-usd/pull/1584) - Disable "Revert File" for read-only files [#1579](https://github.com/Autodesk/maya-usd/pull/1579) - On drag and drop of a layer with an editTarget, the edit target moves to the root layer [#1444](https://github.com/Autodesk/maya-usd/pull/1444) **Render:** - MaterialX - Fix MaterialX import errors found by testing [#1553](https://github.com/Autodesk/maya-usd/pull/1553) - Handle UDIM in MaterialX shaders [#1582](https://github.com/Autodesk/maya-usd/pull/1582) - MaterialX UV0 defaultgeomprop to st primvar [#1533](https://github.com/Autodesk/maya-usd/pull/1533) - MaterialX build instructions [#1524](https://github.com/Autodesk/maya-usd/pull/1524) - MaterialX import export [#1478](https://github.com/Autodesk/maya-usd/pull/1478) - Show USD MaterialX in VP2 render delegate [#1433](https://github.com/Autodesk/maya-usd/pull/1433) - Do not crash on invalid materials [#1573](https://github.com/Autodesk/maya-usd/pull/1573) - Show patch curves as wireframe in default material mode [#1570](https://github.com/Autodesk/maya-usd/pull/1570) - Don't normalize point instancer quaternions [#1563](https://github.com/Autodesk/maya-usd/pull/1563) - Pixar fixed render tag issue in v20.08 so only enable env for earlier versions [#1561](https://github.com/Autodesk/maya-usd/pull/1561) - Detect and save a pointer to the cardsUv primvar reader [#1558](https://github.com/Autodesk/maya-usd/pull/1558) - Restore preview purpose material binding [#1555](https://github.com/Autodesk/maya-usd/pull/1555) - Make sure we leave default material mode when the test ends [#1552](https://github.com/Autodesk/maya-usd/pull/1552) - Build a proper index buffer for the default material render item [#1522](https://github.com/Autodesk/maya-usd/pull/1522) - Point snapping to similar instances [#1521](https://github.com/Autodesk/maya-usd/pull/1521) - UsdUVTexture works with Maya color management prefs [#1516](https://github.com/Autodesk/maya-usd/pull/1516) - Handle source color space in Vp2 render delegate [#1508](https://github.com/Autodesk/maya-usd/pull/1508) - Add kSelectPointsForGravity to all selected render items when we should be snapping to active objects [#1502](https://github.com/Autodesk/maya-usd/pull/1502) - Add support to Vp2RenderDelegate for the "cards" drawing mode [#1463](https://github.com/Autodesk/maya-usd/pull/1463) **Documentation:** - Instruction for installing devtoolset-6 on CentOS [#1482](https://github.com/Autodesk/maya-usd/pull/1482) ## [0.10.0] - 2021-06-11 **Build:** - Use new schemaregistry API [#1435](https://github.com/Autodesk/maya-usd/pull/1435) - Update Pixar ProxyShape image tests affected from storm wireframe [#1414](https://github.com/Autodesk/maya-usd/pull/1414) - Use new usdShade/material vector based API for USD versions beyond 21.05 [#1394](https://github.com/Autodesk/maya-usd/pull/1394) - Support building Gulark library locally [#1291](https://github.com/Autodesk/maya-usd/pull/1291) - Center pivot command support test [#1207](https://github.com/Autodesk/maya-usd/pull/1207) **Translation Framework:** - Use Maya matrix decomposition for matrix op TRS accessors [#1428](https://github.com/Autodesk/maya-usd/pull/1428) - Move Transform3d handler creation into core [#1409](https://github.com/Autodesk/maya-usd/pull/1409) - Write correct IOR for metallic shaders [#1388](https://github.com/Autodesk/maya-usd/pull/1388) - Remove namespace on material import [#1344](https://github.com/Autodesk/maya-usd/pull/1344) - Configure resolver to generate resolver context [#1342](https://github.com/Autodesk/maya-usd/pull/1342) - Referenced material non-default attributes not getting exported to USD [#1284](https://github.com/Autodesk/maya-usd/pull/1284) - Don't write fStop when depthOfField is disabled [#1280](https://github.com/Autodesk/maya-usd/pull/1280) - Spurious warning being raised about USDZ texture import [#1279](https://github.com/Autodesk/maya-usd/pull/1279) - Guard against past-end iterator invalidation [#1247](https://github.com/Autodesk/maya-usd/pull/1247) **Workflow:** - Grouping a prim twice will crash Maya [#1453](https://github.com/Autodesk/maya-usd/pull/1453) - AE missing information on materials and texture [#1446](https://github.com/Autodesk/maya-usd/pull/1446) - Implement setMatrixCmd() for common transform API [#1445](https://github.com/Autodesk/maya-usd/pull/1445) - Error messages showing up when opening the "Applied Schema" category [#1434](https://github.com/Autodesk/maya-usd/pull/1434) - Replace callsites into deprecated "Master" API [#1430](https://github.com/Autodesk/maya-usd/pull/1430) - Empty categories appear [#1427](https://github.com/Autodesk/maya-usd/pull/1427) - See mayaUsdProxyShape icon in Node Editor [#1425](https://github.com/Autodesk/maya-usd/pull/1425) - Mute layer doesn't work [#1423](https://github.com/Autodesk/maya-usd/pull/1423) - USD files fail to load on mapped mounted volume [#1422](https://github.com/Autodesk/maya-usd/pull/1422) - Send ufe notifications on undo and redo [#1412](https://github.com/Autodesk/maya-usd/pull/1412) - Remove use of deprecated pxr namespace in favor of PXR_NS [#1411](https://github.com/Autodesk/maya-usd/pull/1411) - On prim AE template, see connected attributes [#1410](https://github.com/Autodesk/maya-usd/pull/1410) - Layer Editor save icon missing when Maya scaling is 125% [#1408](https://github.com/Autodesk/maya-usd/pull/1408) - Title for Shaping API shows up incorrect in Attribute Editor [#1407](https://github.com/Autodesk/maya-usd/pull/1407) - Crash on redo of creation and manipulation of prim [#1406](https://github.com/Autodesk/maya-usd/pull/1406) - On the prim AE template see useful widgets for arrays [#1393](https://github.com/Autodesk/maya-usd/pull/1393) [#1374](https://github.com/Autodesk/maya-usd/pull/1374) [#1367](https://github.com/Autodesk/maya-usd/pull/1367) - Importing USD file with USDZ Texture import option on causes import to fail [#1392](https://github.com/Autodesk/maya-usd/pull/1392) - Check for empty paths [#1387](https://github.com/Autodesk/maya-usd/pull/1387) - Attribute Editor: array attribute does not support nice/long name [#1380](https://github.com/Autodesk/maya-usd/pull/1380) - Prim AE template: categories persist their expand/collapse state [#1372](https://github.com/Autodesk/maya-usd/pull/1372) - Crash when editing layer that has permission to edit false (locked) [#1363](https://github.com/Autodesk/maya-usd/pull/1363) - Clean up runtimeCommands created by the plugin [#1354](https://github.com/Autodesk/maya-usd/pull/1354) - Point instance interactive batched position, orientation and scale changes [#1352](https://github.com/Autodesk/maya-usd/pull/1352) - List all registered prim types for creation [#1350](https://github.com/Autodesk/maya-usd/pull/1350) - On the prim AE template see applied schemas [#1333](https://github.com/Autodesk/maya-usd/pull/1333) - USD load/unload payloads does not update viewport [#1332](https://github.com/Autodesk/maya-usd/pull/1332) - Increase depth priority for point snapping items [#1329](https://github.com/Autodesk/maya-usd/pull/1329) - Point snapping issue on USD instances [#1321](https://github.com/Autodesk/maya-usd/pull/1321) - Send Ufe::CameraChanged when camera attributes are modified [#1315](https://github.com/Autodesk/maya-usd/pull/1315) - Block attribute edits for the remaining transformation stacks [#1308](https://github.com/Autodesk/maya-usd/pull/1308) - Test usd camera animated params and editing params [#1298](https://github.com/Autodesk/maya-usd/pull/1298) - Block attribute authoring in weaker layers in legacy transform3d [#1294](https://github.com/Autodesk/maya-usd/pull/1294) - No tooltip for prim path in Attribute Editor [#1288](https://github.com/Autodesk/maya-usd/pull/1288) - Crash when token for "Info: id" is editied to invalide value [#1287](https://github.com/Autodesk/maya-usd/pull/1287) - Ability to turn off file-backed Save confirmation in Layer Editor [#1277](https://github.com/Autodesk/maya-usd/pull/1277) **Render:** - Invisible prims don't get notifications on _PropagateDirtyBits or Sync [#1432](https://github.com/Autodesk/maya-usd/pull/1432) - Integrate 21.05 UsdPreviewSurface shader into MayaUsd plugin [#1416](https://github.com/Autodesk/maya-usd/pull/1416) - Store render item dirty bits with each render item [#1404](https://github.com/Autodesk/maya-usd/pull/1404) - When the instance count changes we need to update everything related to instancer [#1398](https://github.com/Autodesk/maya-usd/pull/1398) - Add a VP2RenderDelegate test for basis curves to ensure they draw correctly [#1390](https://github.com/Autodesk/maya-usd/pull/1390) - Disable the material consolidation update workaround [#1359](https://github.com/Autodesk/maya-usd/pull/1359) - Metallic IBL Reflection [#1356](https://github.com/Autodesk/maya-usd/pull/1356) - Support default material shading using new SDK APIs [#1339](https://github.com/Autodesk/maya-usd/pull/1339) - Faster point snapping [#1292](https://github.com/Autodesk/maya-usd/pull/1292) - Add camera adapter to support physical camera parameters and configurable motion blur and depth-of-field [#1282](https://github.com/Autodesk/maya-usd/pull/1282) - Hydra prim invalidation for hidden lights [#1281](https://github.com/Autodesk/maya-usd/pull/1281) **Documentation:** - Added getting started docs link to Detailed Documentation section [#1401](https://github.com/Autodesk/maya-usd/pull/1401) - Keep the TF_ERROR message format consistence with TF_WARN and TF_STATUS [#1386](https://github.com/Autodesk/maya-usd/pull/1386) - Update build.md for supported USD v21.05 version [#1365](https://github.com/Autodesk/maya-usd/pull/1365) ## [0.9.0] - 2021-04-01 **Build:** * Added "/permissive-" flag for VS compiler [#1262](https://github.com/Autodesk/maya-usd/pull/1262) * Explicitly case Ar path string to ArResolvedPath [#1261](https://github.com/Autodesk/maya-usd/pull/1261) * Remove/replace all UFE_PREVIEW_VERSION_NUM [#1243](https://github.com/Autodesk/maya-usd/pull/1243) * Namespace cleanup [#1214](https://github.com/Autodesk/maya-usd/pull/1214) [#1223](https://github.com/Autodesk/maya-usd/pull/1223) [#1231](https://github.com/Autodesk/maya-usd/pull/1231) [#1240](https://github.com/Autodesk/maya-usd/pull/1240) * Allow ufeUtils.ufeFeatureSetVersion before Maya standalone initialize [#1237](https://github.com/Autodesk/maya-usd/pull/1237) * Revert pxrUsdMayaGL tests to old color management [#1232](https://github.com/Autodesk/maya-usd/pull/1232) * Fixed Maya 2018 compilation [#1225](https://github.com/Autodesk/maya-usd/pull/1225) * Adapt tests to UsdShade GetInputs() and GetOutputs() API update with USD 21.05 [#1224](https://github.com/Autodesk/maya-usd/pull/1224) * Fixed include order [#1211](https://github.com/Autodesk/maya-usd/pull/1211) * Regression test for scene dirty when editing USD [#1205](https://github.com/Autodesk/maya-usd/pull/1205) * Updates for building with latest post-21.02 dev branch commit of core USD [#1199](https://github.com/Autodesk/maya-usd/pull/1199) * Remove dependency on boost - filesystem/system [#1182](https://github.com/Autodesk/maya-usd/pull/1182) - chrono and date_time [#1184](https://github.com/Autodesk/maya-usd/pull/1184) - hash_combine [#1183](https://github.com/Autodesk/maya-usd/pull/1183) * Replaced usage of USD_VERSION_NUM with PXR_VERSION [#1181](https://github.com/Autodesk/maya-usd/pull/1181) **Translation Framework:** * Added support for indexed normals on import [#1250](https://github.com/Autodesk/maya-usd/pull/1250) * Uvset names not written [#1188](https://github.com/Autodesk/maya-usd/pull/1188) * Support duplicate blendshape target names [#1179](https://github.com/Autodesk/maya-usd/pull/1179) * Maintain UV connectivity across export and re-import round trips [#1175](https://github.com/Autodesk/maya-usd/pull/1175) * Added support import of textures from USDZ archives [#1151](https://github.com/Autodesk/maya-usd/pull/1151) * Support import chaser plugins [#1104](https://github.com/Autodesk/maya-usd/pull/1104) **Workflow:** * Return error code for issues when saving [#1293](https://github.com/Autodesk/maya-usd/pull/1293) * Fixed visibility attribute not blocked via outliner [#1275](https://github.com/Autodesk/maya-usd/pull/1275) * Fixed crash when learing mutiple layers [#1274](https://github.com/Autodesk/maya-usd/pull/1274) * Prim AE template:<br> - option to suppress array attributes [#1267](https://github.com/Autodesk/maya-usd/pull/1267) - show metadata [#1249](https://github.com/Autodesk/maya-usd/pull/1249) * Undoing transform will not update manipulator [#1266](https://github.com/Autodesk/maya-usd/pull/1266) * Don't convert the near and far clipping planes linear units to cm [#1265](https://github.com/Autodesk/maya-usd/pull/1265) * Ability to select usd objects based on kind from the Select menu [#1260](https://github.com/Autodesk/maya-usd/pull/1260) * Better return value (enum) from UI delegate [#1259](https://github.com/Autodesk/maya-usd/pull/1259) * Part 1: Block attribute(s) authoring in weaker layer(s) [#1258](https://github.com/Autodesk/maya-usd/pull/1258) * Added a camera test which relies on unimplemented methods [#1252](https://github.com/Autodesk/maya-usd/pull/1252) * Minimize name-based lookup of proxy shape nodes [#1245](https://github.com/Autodesk/maya-usd/pull/1245) * Added support for manipulating point instances via UFE [#1241](https://github.com/Autodesk/maya-usd/pull/1241) * Stage AE template<br> - load/reload a file as stage source [#1218](https://github.com/Autodesk/maya-usd/pull/1218) - load/unload all payloads [#1203](https://github.com/Autodesk/maya-usd/pull/1203) [#1242](https://github.com/Autodesk/maya-usd/pull/1242) - show PrimPath/Purpose/Exlude Prim Path [#1189](https://github.com/Autodesk/maya-usd/pull/1189) [#1178](https://github.com/Autodesk/maya-usd/pull/1178) [#1176](https://github.com/Autodesk/maya-usd/pull/1176) * No warning icon in USD Save Overwrite section [#1234](https://github.com/Autodesk/maya-usd/pull/1234) * Fixed AE refresh problem when an Xformable is added [#1233](https://github.com/Autodesk/maya-usd/pull/1233) * Undoable command base class [#1227](https://github.com/Autodesk/maya-usd/pull/1227) * Separate callbacks for Save and Export [#1226](https://github.com/Autodesk/maya-usd/pull/1226) * Multiple ProxyShapes with Same Stage [#1228](https://github.com/Autodesk/maya-usd/pull/1228) * Null and anonymous layer checks [#1212](https://github.com/Autodesk/maya-usd/pull/1212) * Multi matrix and fallback parent absolute [#1201](https://github.com/Autodesk/maya-usd/pull/1201) * Fixed bbox computation for purposes [#1170](https://github.com/Autodesk/maya-usd/pull/1170) **Render:** * Added a basic test for Vp2RenderDelegate geom subset material binding support [#1255](https://github.com/Autodesk/maya-usd/pull/1255) * Author a default value for color & opacity if none are present [#1254](https://github.com/Autodesk/maya-usd/pull/1254) * Only assign the fallback material when no material is present [#1253](https://github.com/Autodesk/maya-usd/pull/1253) * Added single-channel half-float EXR support [#1248](https://github.com/Autodesk/maya-usd/pull/1248) * Added per instance inherited data support to Vp2RenderDelegate [#1220](https://github.com/Autodesk/maya-usd/pull/1220) * Added support for 16-bits textures in VP2 renderer delegate [#1219](https://github.com/Autodesk/maya-usd/pull/1219) * Fixed crash on failure to initialize a renderer [#1213](https://github.com/Autodesk/maya-usd/pull/1213) * Use the nurbs curve selection mask for basis curves [#1208](https://github.com/Autodesk/maya-usd/pull/1208) **Documentation:** * Update comment about using universalRenderContext [#1271](https://github.com/Autodesk/maya-usd/pull/1271) * Added namespace section to coding guidelines [#1239](https://github.com/Autodesk/maya-usd/pull/1239) * Identify clang-format version 10.0.0 as the "standard" version [#1229](https://github.com/Autodesk/maya-usd/pull/1229) ## [0.8.0] - 2021-02-18 **Build:** * Fixed UFEv2 test failures with USD 20.02 [#1171](https://github.com/Autodesk/maya-usd/pull/1171) * Set MAYA_APP_DIR for each test, pointing to unique folders. [#1163](https://github.com/Autodesk/maya-usd/pull/1163) * Disabled OCIOv2 in mtoh tests [#1160](https://github.com/Autodesk/maya-usd/pull/1160) * Made tests in test/lib/ufe directly runnable and use fixturesUtils [#1144](https://github.com/Autodesk/maya-usd/pull/1144) * Moved minimum core usd version to v20.02 [#1138](https://github.com/Autodesk/maya-usd/pull/1138) * Made use of PXR_OVERRIDE_PLUGINPATH_NAME everywhere [#1108](https://github.com/Autodesk/maya-usd/pull/1108) * Updates for building with latest post-21.02 dev branch commit of core USD [#1099](https://github.com/Autodesk/maya-usd/pull/1099) **Translation Framework:** * Support empty blendshape targets [#1149](https://github.com/Autodesk/maya-usd/pull/1149) * Fixed load all prims in hierarchy view [#1140](https://github.com/Autodesk/maya-usd/pull/1140) * Improved support for USD leftHanded mesh [#1139](https://github.com/Autodesk/maya-usd/pull/1139) * Fixed export menu after expanding animation option [#1133](https://github.com/Autodesk/maya-usd/pull/1133) * Added support for UV mirroring on UsdUVTexture [#1132](https://github.com/Autodesk/maya-usd/pull/1132) * Imroved export of skeleton rest-xforms [#1130](https://github.com/Autodesk/maya-usd/pull/1130) * Use earliest time when exporting without animation [#1127](https://github.com/Autodesk/maya-usd/pull/1127) * Added error message if unrecognized shadingMode on export [#1110](https://github.com/Autodesk/maya-usd/pull/1110) * Fixed anonymous layer import [#1086](https://github.com/Autodesk/maya-usd/pull/1086) **Workflow:** * Fixed crash when editing prim on a muted layer [#1172](https://github.com/Autodesk/maya-usd/pull/1172) * Added workflows to save in-memory edits [#1152](https://github.com/Autodesk/maya-usd/pull/1152) [#1187](https://github.com/Autodesk/maya-usd/pull/1187) * Removed attributes from AE stage view [#1145](https://github.com/Autodesk/maya-usd/pull/1145) * Added support for duplicating a proxyShape. [#1142](https://github.com/Autodesk/maya-usd/pull/1142) * Adopted data model undo framework for attribute undo [#1134](https://github.com/Autodesk/maya-usd/pull/1134) * Prevent saving layers with anonymous sublayers [#1128](https://github.com/Autodesk/maya-usd/pull/1128) * Added warning when saving layers on disk [#1121](https://github.com/Autodesk/maya-usd/pull/1121) * Fixed crash caused by out of date stage map [#1116](https://github.com/Autodesk/maya-usd/pull/1116) * Fixed crash when fallback stack was having unsupported ops added [#1105](https://github.com/Autodesk/maya-usd/pull/1105) * Fixed parenting with single matrix xform op stacks [#1102](https://github.com/Autodesk/maya-usd/pull/1102) * Author kind=group on the UsdPrim created by the group command when its parent is in the model hierarchy [#1094](https://github.com/Autodesk/maya-usd/pull/1094) * Update edit target when layer removal made it no longer part of the stage [#1156](https://github.com/Autodesk/maya-usd/pull/1156) * Fixed bounding box cache invalidation when editing USD stage [#1153](https://github.com/Autodesk/maya-usd/pull/1153) * Handle selection changes during layer muting and variant switch [#1141](https://github.com/Autodesk/maya-usd/pull/1141) * Fixed crash when removing an invalid layer [#1122](https://github.com/Autodesk/maya-usd/pull/1122) * Added UFE path handling and utilities to support paths that identify point instances of a PointInstancer [#1027](https://github.com/Autodesk/maya-usd/pull/1027) **Render:** * Fixed crash after re-loading the mtoh plugin [#1159](https://github.com/Autodesk/maya-usd/pull/1159) * Added compute extents for modified primitives [#1112](https://github.com/Autodesk/maya-usd/pull/1112) * Fixed drawing of stale data when switching representations [#1100](https://github.com/Autodesk/maya-usd/pull/1100) * Added hilight dirty state propagation [#1091](https://github.com/Autodesk/maya-usd/pull/1091) * Implemented viewport selection highlighting of point instances and point instances pick modes [#1119](https://github.com/Autodesk/maya-usd/pull/1119) [#1161](https://github.com/Autodesk/maya-usd/pull/1161) **Documentation:** * Added import/export cmd documentation [#1146](https://github.com/Autodesk/maya-usd/pull/1146) ## [0.7.0] - 2021-01-20 This release changes to highlight: * Ufe cameras * Blendshape export support * Maya's scene will get modified by changes to USD data model * VP2RenderDelegate is enabled by default and doesn't require env variable flag anymore * Maya-To-Hydra compilation is disabled for Maya 2019 with USD 20.08 or 20.11 **Build:** * Migrated more tests from plugin/pxr to core mayaUsd [#1042](https://github.com/Autodesk/maya-usd/pull/1042) * Cleaned up UI folder [#1037](https://github.com/Autodesk/maya-usd/pull/1037) * Cleaned up test utils [#1034](https://github.com/Autodesk/maya-usd/pull/1034) * Updates for building with latest post-20.11 dev branch of core USD [#1025](https://github.com/Autodesk/maya-usd/pull/1025) * Fixed a build issue on Linux with maya < 2020 [#1013](https://github.com/Autodesk/maya-usd/pull/1013) * Fixed interactive tests to ensure output streams are flushed before quitting [#1009](https://github.com/Autodesk/maya-usd/pull/1009) * Added UsdMayaDiagnosticDelegate to adsk plugin to enable Tf errors reporting using Maya's routines [#1003](https://github.com/Autodesk/maya-usd/pull/1003) * Added basic tests for HdMaya / mtoh [#915](https://github.com/Autodesk/maya-usd/pull/915) [#1006](https://github.com/Autodesk/maya-usd/pull/1006) **Translation Framework:** * Fixed issue where referenced scenes have incorrect UV set attribute name written out. [#1062](https://github.com/Autodesk/maya-usd/pull/1062) * Fixed texture writer path resolver to work relative to final export path [#1028](https://github.com/Autodesk/maya-usd/pull/1028) * Fixed incorrect `bindTransforms` being determined during export [#1024](https://github.com/Autodesk/maya-usd/pull/1024) * Added Blendshape export functionality [#1016](https://github.com/Autodesk/maya-usd/pull/1016) * Added staticSingleSample flag, and optimize mesh attributes by default [#989](https://github.com/Autodesk/maya-usd/pull/989) [#1012](https://github.com/Autodesk/maya-usd/pull/1012) * Added convert for USD timeSamples to Maya FPS [#970](https://github.com/Autodesk/maya-usd/pull/970) [#1010](https://github.com/Autodesk/maya-usd/pull/1010) **Workflow:** * Fixed camera frame for instance proxies. [#1082](https://github.com/Autodesk/maya-usd/pull/1082) * Removed dependency between LayerEditor and HIK image resources [#1072](https://github.com/Autodesk/maya-usd/pull/1072) * Fixed rename for inherits and specializes update [#1071](https://github.com/Autodesk/maya-usd/pull/1071) * Added support for Ufe cameras [#1066](https://github.com/Autodesk/maya-usd/pull/1066) * Editing USD should mark scene as dirty [#1061](https://github.com/Autodesk/maya-usd/pull/1061) * Fixed crash when manipulating certain assets on Linux [#1060](https://github.com/Autodesk/maya-usd/pull/1060) * Made visibility Undo/Redo correct [#1056](https://github.com/Autodesk/maya-usd/pull/1056) * Fixed crash in LayerEditor when removing layer used as edit target [#1015](https://github.com/Autodesk/maya-usd/pull/1015) * Fixed disappearing layer when moved under last layer in LayerEditor [#994](https://github.com/Autodesk/maya-usd/pull/994) **Render:** * Fixed false positive transparency [#1080](https://github.com/Autodesk/maya-usd/pull/1080) * Made VP2RenderDelegate enabled by default [#1065](https://github.com/Autodesk/maya-usd/pull/1065) * Fixed mtoh crash with DirectX [#1059](https://github.com/Autodesk/maya-usd/pull/1059) * Optimized VP2RenderDelegate for many materials [#1043](https://github.com/Autodesk/maya-usd/pull/1043) [#1048](https://github.com/Autodesk/maya-usd/pull/1048) [#1052](https://github.com/Autodesk/maya-usd/pull/1052) * Disabled building of mtoh for Maya 2019 with USD 20.08 and 20.11 [#1023](https://github.com/Autodesk/maya-usd/pull/1023) ## [0.6.0] - 2020-12-14 This release includes many changes, like: * Refactored UFE Manipulation support * New Undo Manager * LayerEditor * Material import/export improvements (displacement, UDIMs, UVs) & bug fixes * AE improvements * Viewport optimization for many duplicated materials * Undo support for UFEv2 selection in viewport * Proxy accessor - handle recursive patterns * Clang-format is applied to the entire repository **Build:** * Fixed compilation on windows if backslash in `Python_EXECUTABLE` [#968](https://github.com/Autodesk/maya-usd/pull/968) * Enable USD version check for components distributed separately [#949](https://github.com/Autodesk/maya-usd/pull/949) [#846](https://github.com/Autodesk/maya-usd/pull/846) * Fixed missing `ARCH_CONSTRUCTOR` code with VS2019 [#937](https://github.com/Autodesk/maya-usd/pull/937) * Fixed current compiler warnings [#930](https://github.com/Autodesk/maya-usd/pull/930) * Fixed compilation errors with latest post-20.11 dev branch of core USD [#929](https://github.com/Autodesk/maya-usd/pull/929) [#889](https://github.com/Autodesk/maya-usd/pull/889) * Added support for `Boost_NO_BOOST_CMAKE=O`N for Boost::python [#912](https://github.com/Autodesk/maya-usd/pull/912) * Organized Gitignore, and add more editor,platform and build specific patterns [#908](https://github.com/Autodesk/maya-usd/pull/908) * Applied clang-format [#890](https://github.com/Autodesk/maya-usd/pull/890) [#918](https://github.com/Autodesk/maya-usd/pull/918) [#895](https://github.com/Autodesk/maya-usd/pull/895) * Enabled initialization order warning on Windows. [#885](https://github.com/Autodesk/maya-usd/pull/885) * Added mayaUtils.openTestScene and mayaUtils.getTestScene [#868](https://github.com/Autodesk/maya-usd/pull/868) * Exposed stage reset notices to python [#861](https://github.com/Autodesk/maya-usd/pull/861) * Clang-format fixes [#842](https://github.com/Autodesk/maya-usd/pull/842) * Devtoolset-9 fixes [#841](https://github.com/Autodesk/maya-usd/pull/841) * Made `WANT_UFE_BUILD` def public. [#793](https://github.com/Autodesk/maya-usd/pull/793) **Translation Framework:** * Fixed `Looks` scopes roundtrip [#985](https://github.com/Autodesk/maya-usd/pull/985) * Added support for UV transform value exports [#954](https://github.com/Autodesk/maya-usd/pull/954) * Allowed loading pure-USD shading mode plugins [#923](https://github.com/Autodesk/maya-usd/pull/923) * Added opacity threshold to USD Preview Surface Shader [#917](https://github.com/Autodesk/maya-usd/pull/917) * Fixed out of bound errors causing segfaults [#914](https://github.com/Autodesk/maya-usd/pull/914) * Added FPS metadata to exported usd files if non static [#913](https://github.com/Autodesk/maya-usd/pull/913) * Added proper support for importing UV set mappings [#902](https://github.com/Autodesk/maya-usd/pull/902) * Fixed `map1` import [#892](https://github.com/Autodesk/maya-usd/pull/892) * Fixed self-specialization bug with textureless materials [#891](https://github.com/Autodesk/maya-usd/pull/891) * Added UDIM Import/Export [#883](https://github.com/Autodesk/maya-usd/pull/883) * Added proper support for UV linkage on material export [#876](https://github.com/Autodesk/maya-usd/pull/876) * Fix to keep USDZ texture paths relative [#865](https://github.com/Autodesk/maya-usd/pull/865) * Added support for handling color space information on file nodes [#862](https://github.com/Autodesk/maya-usd/pull/862) * Added import optimization to merge subsets connected to same material [#860](https://github.com/Autodesk/maya-usd/pull/860) * Renamed InstanceSources to be Maya-specific [#859](https://github.com/Autodesk/maya-usd/pull/859) * Added displacement export & import [#844](https://github.com/Autodesk/maya-usd/pull/844) [#851](https://github.com/Autodesk/maya-usd/pull/851) **Workflow:** * Added save layers dialog [#990](https://github.com/Autodesk/maya-usd/pull/990) * Added Layer Editor [#988](https://github.com/Autodesk/maya-usd/pull/988) * Fixed undo crash when switching between target layers in a stage [#965](https://github.com/Autodesk/maya-usd/pull/965) * Made attributes categorized by schema in AE [#964](https://github.com/Autodesk/maya-usd/pull/964) * Added new transform3d handlers to remove limitations in UFE manipulation support [#962](https://github.com/Autodesk/maya-usd/pull/962) * Added Undo/Redo support for USD data model. [#942](https://github.com/Autodesk/maya-usd/pull/942) [#956](https://github.com/Autodesk/maya-usd/pull/956) * Added connection to time when creating a new empty USD stage [#928](https://github.com/Autodesk/maya-usd/pull/928) * Enabled recursive compute with proxy accessor [#926](https://github.com/Autodesk/maya-usd/pull/926) * Cleaned up Proxy Shape AE template [#922](https://github.com/Autodesk/maya-usd/pull/922) [#944](https://github.com/Autodesk/maya-usd/pull/944) * Made select command UFE aware [#921](https://github.com/Autodesk/maya-usd/pull/921) * Allowed usdPreviewSurface to exist without input connections [#907](https://github.com/Autodesk/maya-usd/pull/907) * Fixed default edit target when root layer is not editable. Added ability to force session layer by default. [#899](https://github.com/Autodesk/maya-usd/pull/899) [#935](https://github.com/Autodesk/maya-usd/pull/935) * Fixed outliner update when duplicating items [#880](https://github.com/Autodesk/maya-usd/pull/880) * Added subtree invalidation support on StageProxy ( a.k.a pseudo-root ). [#864](https://github.com/Autodesk/maya-usd/pull/864) * Added support None-destructive reorder ( move ) of prims relative to their siblings. [#867](https://github.com/Autodesk/maya-usd/pull/867) * Made parenting to a Gprim not allowed [#852](https://github.com/Autodesk/maya-usd/pull/852) * Improved accessor plug name and cleanup tests [#838](https://github.com/Autodesk/maya-usd/pull/838) **Render:** * Enabled color consolidation support for UsdPreviewSurface and UsdPrimvarReader_color [#979](https://github.com/Autodesk/maya-usd/pull/979) * Fixed broken lighting fragment [#963](https://github.com/Autodesk/maya-usd/pull/963) * Removed dependencies on old Hydra texture system from hdMaya for USD releases after 20.11 [#961](https://github.com/Autodesk/maya-usd/pull/961) * Improved draw performance for Rprims without extent [#955](https://github.com/Autodesk/maya-usd/pull/955) * Reuse shader effect for duplicate material networks [#950](https://github.com/Autodesk/maya-usd/pull/950) * Added undo support for viewport selections of USD objects [#940](https://github.com/Autodesk/maya-usd/pull/940) * Fixed transparency issues for pxrUsdPreviewSurface shader node [#903](https://github.com/Autodesk/maya-usd/pull/903) * Fixed fallback shader (a.k.a "blue color") being incorrectly used in some cases [#882](https://github.com/Autodesk/maya-usd/pull/882) * Added CPV support and curveBasis support for basiscurves complexity level 1 [#809](https://github.com/Autodesk/maya-usd/pull/809) ## [0.5.0] - 2020-10-20 **Build:** * Added validation of exported USD in testUsdExportSkeleton for case without bind pose [#839](https://github.com/Autodesk/maya-usd/pull/839) * Added support for core USD release 20.11 [#835](https://github.com/Autodesk/maya-usd/pull/835) [#808](https://github.com/Autodesk/maya-usd/pull/808) [#775](https://github.com/Autodesk/maya-usd/pull/775) * Continue pxr tests migration and fixes [#828](https://github.com/Autodesk/maya-usd/pull/828) [#825](https://github.com/Autodesk/maya-usd/pull/825) [#815](https://github.com/Autodesk/maya-usd/pull/815) [#806](https://github.com/Autodesk/maya-usd/pull/806) [#779](https://github.com/Autodesk/maya-usd/pull/779) * Cleaned up pxr CMake and remove irrelevant build options [#818](https://github.com/Autodesk/maya-usd/pull/818) * Made necessary fixes required before we can apply clang format [#807](https://github.com/Autodesk/maya-usd/pull/807) * Fixed Python 3 warnings [#783](https://github.com/Autodesk/maya-usd/pull/783) * Fixed PROJECT_SOURCE_DIR use for nested projects. [#780](https://github.com/Autodesk/maya-usd/pull/780) * Fixed namespace migration of QStringListModel between Maya 2019 and Maya 2020 in userExportedAttributesUI [#812](https://github.com/Autodesk/maya-usd/pull/812) **Translation Framework:** * Fixed import of "useSpecularWorkflow" input on UsdPreviewSurface shaders [#837](https://github.com/Autodesk/maya-usd/pull/837) * Added translation support between lambert transparency and UsdPreviewSurface opacity * Material import options rework [#822](https://github.com/Autodesk/maya-usd/pull/822) [#831](https://github.com/Autodesk/maya-usd/pull/831) [#832](https://github.com/Autodesk/maya-usd/pull/832) [#833](https://github.com/Autodesk/maya-usd/pull/833) [#836](https://github.com/Autodesk/maya-usd/pull/836) * Ensure UsdShadeMaterialBindingAPI schema is applied when authoring bindings during export [#804](https://github.com/Autodesk/maya-usd/pull/804) * Updated custom converter test plugin to use symmetric writer [#803](https://github.com/Autodesk/maya-usd/pull/803) * Added instance import support [#794](https://github.com/Autodesk/maya-usd/pull/794) * Extracted RenderMan for Maya shading export from "pxrRis" shadingMode for use with "useRegistry" [#787](https://github.com/Autodesk/maya-usd/pull/787) [#799](https://github.com/Autodesk/maya-usd/pull/799) * Fixed registry errors for preview surface readers and writers [#778](https://github.com/Autodesk/maya-usd/pull/778) **Workflow:** * Added prim type icons support in outliner [#782](https://github.com/Autodesk/maya-usd/pull/782) * Made absence of scale pivot support is not an error in transform3d [#834](https://github.com/Autodesk/maya-usd/pull/834) * Adapt to changes in UFE interface to support Maya transform stacks [#827](https://github.com/Autodesk/maya-usd/pull/827) * Added UFE contextOps for working set management (loading and unloading) [#823](https://github.com/Autodesk/maya-usd/pull/823) * Fixed crash after discarding edits on an anon layer [#817](https://github.com/Autodesk/maya-usd/pull/817) * Added display for outliner to show which prims have a composition arc including a variant [#816](https://github.com/Autodesk/maya-usd/pull/816) * Added support for automatic update of internal references when the path they are referencing has changed. [#797](https://github.com/Autodesk/maya-usd/pull/797) * Rewrote the rename restriction algorithm from scratch to cover more edge cases. [#786](https://github.com/Autodesk/maya-usd/pull/786) * Added Cache Id In/Out attributes to the Base Proxy Shape [#785](https://github.com/Autodesk/maya-usd/pull/785) **Render:** * Fixed refresh after change to excluded prims attribute [#821](https://github.com/Autodesk/maya-usd/pull/821) * Fixed snapping to prevent snap to active objects when using point snapping [#819](https://github.com/Autodesk/maya-usd/pull/819) * Always register and de-register the PxrMayaHdImagingShape and its draw override [#810](https://github.com/Autodesk/maya-usd/pull/810) * Added selection and point snapping support for mtoh [#776](https://github.com/Autodesk/maya-usd/pull/776) * Refactored settings / defaultRenderGlobals storage for mtoh [#758](https://github.com/Autodesk/maya-usd/pull/758) ## [0.4.0] - 2020-09-22 This release includes: * Completed materials interop via PreviewSurface * Improved rename and parenting workflows * Improved Outliner support **Build:** * Fixed build script with python 3 where each line starting with 'b and ends with \n' making it hard to read the log. [PR #768](https://github.com/Autodesk/maya-usd/pull/768) * Removed test dependencies on Python future past, and builtin.zip [PR #764](https://github.com/Autodesk/maya-usd/pull/764) * Added test for setting rotate pivot through move command. [PR #763](https://github.com/Autodesk/maya-usd/pull/763) * Migrated pxrUsdMayaGL and relevant pxrUsdTranslators tests from plugin/pxr/... to test/... [PR #762](https://github.com/Autodesk/maya-usd/pull/762) [PR #761](https://github.com/Autodesk/maya-usd/pull/761) [PR #759](https://github.com/Autodesk/maya-usd/pull/759) [PR #756](https://github.com/Autodesk/maya-usd/pull/756) [PR #741](https://github.com/Autodesk/maya-usd/pull/741) [PR #706](https://github.com/Autodesk/maya-usd/pull/706) * Replaced #pragma once with #ifndef include guards [PR #750](https://github.com/Autodesk/maya-usd/pull/750) * Removed old UFE condional compilation blocks [PR #746](https://github.com/Autodesk/maya-usd/pull/746) * Removed code blocks for USD 19.07 [PR #734](https://github.com/Autodesk/maya-usd/pull/734) * Split Maya module file into separate plugins [PR #731](https://github.com/Autodesk/maya-usd/pull/731) **Translation Framework:** * Fixed regression in displayColors shading mode to use the un-linearized lambert transparency to author displayOpacity [PR #751](https://github.com/Autodesk/maya-usd/pull/751) * Renamed pxrUsdPreviewSurface to usdPreviewSurface [PR #744](https://github.com/Autodesk/maya-usd/pull/744) * Fixed empty relative path handling for texture writer [PR #743](https://github.com/Autodesk/maya-usd/pull/743) * Added support for multiple export converters to co-exist in useRegistry export [PR #721](https://github.com/Autodesk/maya-usd/pull/721) * Cleaned-up export material UI [PR #709](https://github.com/Autodesk/maya-usd/pull/709) * Added preview surface to Maya native shaders converstion [PR #707](https://github.com/Autodesk/maya-usd/pull/707) **Workflow:** * Added support in the outliner for displaying activate and deactivate prims [PR #773](https://github.com/Autodesk/maya-usd/pull/773) * Fixed undo/redo re-parenting crash due to accessing a stale prim [PR #772](https://github.com/Autodesk/maya-usd/pull/772) * Fixed matrix converstion when reading/writing to data handles [PR #765](https://github.com/Autodesk/maya-usd/pull/765) * Fixed incorrect exception handling when setting variants in attribute editor for pxrUsdReferenceAssembly [PR #760](https://github.com/Autodesk/maya-usd/pull/760) * Added undo support for multiple parented items in outliner [PR #755](https://github.com/Autodesk/maya-usd/pull/755) * Fixed crash with undo redo in USD Layer Editor [PR #754](https://github.com/Autodesk/maya-usd/pull/754) * Fixed `add new prim` after delete [PR #742](https://github.com/Autodesk/maya-usd/pull/742) * Fixed crash after switching variant [PR #726](https://github.com/Autodesk/maya-usd/pull/726) * Added support in the outliner for prim type icons [PR #712](https://github.com/Autodesk/maya-usd/pull/712) **Render:** * Added mtoh support for standardSurface [PR #749](https://github.com/Autodesk/maya-usd/pull/749) * Fixed refresh with VP2RenderDelegate when the USD stage is cleared [PR #748](https://github.com/Autodesk/maya-usd/pull/748) * Improved draw performance for dense mesh [PR #715](https://github.com/Autodesk/maya-usd/pull/715) ## [0.3.0] - 2020-08-15 ### Build * Fixed build script and test failures with python3 build [PR #700](https://github.com/Autodesk/maya-usd/pull/700) * Fixed unused-but-set-variable on compiling with Maya 2018 earlier than 2018.7 [PR #699](https://github.com/Autodesk/maya-usd/pull/699) * Cleaned up the status report when building USD with Python 3 [PR #688](https://github.com/Autodesk/maya-usd/pull/688) * Removed unused python modules from tests. [PR #670](https://github.com/Autodesk/maya-usd/pull/670) * Added support for core USD release 20.08 [PR #617](https://github.com/Autodesk/maya-usd/pull/617) ### Translation Framework * Fixed import of non displayColors primvars [PR #703](https://github.com/Autodesk/maya-usd/pull/703) * Fixed load Plug libraries when finding and loading in the registry [PR #694](https://github.com/Autodesk/maya-usd/pull/694) * Fixed export of texture file paths [PR #686](https://github.com/Autodesk/maya-usd/pull/686) * Fixed import of UV sets [PR #685](https://github.com/Autodesk/maya-usd/pull/685) * Added UI to display the number of selected prims and changed variants [PR #675](https://github.com/Autodesk/maya-usd/pull/675) ### Workflow * Added Restriction Rules for Parenting [PR #673](https://github.com/Autodesk/maya-usd/pull/673) [PR #680](https://github.com/Autodesk/maya-usd/pull/680) [PR #687](https://github.com/Autodesk/maya-usd/pull/687) [PR #697](https://github.com/Autodesk/maya-usd/pull/697) [PR #682](https://github.com/Autodesk/maya-usd/pull/682) * Fixed Outliner refresh after adding a reference [PR #689](https://github.com/Autodesk/maya-usd/pull/689) * Fixed naming of stage and shape at creation to align with naming in Maya [PR #695](https://github.com/Autodesk/maya-usd/pull/695) * Fixed Outliner refresh after rename [PR #677](https://github.com/Autodesk/maya-usd/pull/677) * Changed default edit target from SessionLayer to RootLayer [PR #661](https://github.com/Autodesk/maya-usd/pull/661) * Fixed the type when creating a new group [PR #672](https://github.com/Autodesk/maya-usd/pull/672) * Added implementation for new UFE unparent interface [PR #665](https://github.com/Autodesk/maya-usd/pull/665) ### Render * Fixed non-UFE selection code path when selecting instances in VP2RenderDelegate [PR #681](https://github.com/Autodesk/maya-usd/pull/681) * Added selection highlight color for lead and active selection in VP2RenderDelegate [PR #671](https://github.com/Autodesk/maya-usd/pull/671) * Fixed stage repopulation in mtoh [PR #650](https://github.com/Autodesk/maya-usd/pull/650) * Added suppor for default material option in mtoh [PR #647](https://github.com/Autodesk/maya-usd/pull/647) * Removed UseVp2 selection highlighting display from mtoh [PR #646](https://github.com/Autodesk/maya-usd/pull/646) ## [0.2.0] - 2020-07-22 This release includes support for Python 3 (requires USD 20.05). The goal of this beta/pre-release version is to validate: * a new Maya 2020 installer * basic import / export of simple Maya materials to UsdShade with PreviewSurface * viewport improvements ### Build * Add python 3 support [PR #622](https://github.com/Autodesk/maya-usd/pull/622) [PR #602](https://github.com/Autodesk/maya-usd/pull/602) [PR #586](https://github.com/Autodesk/maya-usd/pull/586) [PR #573](https://github.com/Autodesk/maya-usd/pull/573) [PR #564](https://github.com/Autodesk/maya-usd/pull/564) [PR #555](https://github.com/Autodesk/maya-usd/pull/555) [PR #502](https://github.com/Autodesk/maya-usd/pull/502) [PR #637](https://github.com/Autodesk/maya-usd/pull/637) * Split MayaUsd mod file into Windows and Linux/MacOS specific [PR #631](https://github.com/Autodesk/maya-usd/pull/631) * Refactored import / export tests to run without dependency on Pixar plugin [PR #595](https://github.com/Autodesk/maya-usd/pull/595) * Enabled GitHub Actions checks for maya-usd branches [PR #434](https://github.com/Autodesk/maya-usd/pull/434) [PR #533](https://github.com/Autodesk/maya-usd/pull/533) [PR #557](https://github.com/Autodesk/maya-usd/pull/557) [PR #565](https://github.com/Autodesk/maya-usd/pull/565) [PR #590](https://github.com/Autodesk/maya-usd/pull/590) * Allowed parallel ctest execution with `ctest-args` build flag [PR #578](https://github.com/Autodesk/maya-usd/pull/578) * Improved mayaUsd_copyDirectory routine to allow more control over copying dir/files. [PR #515](https://github.com/Autodesk/maya-usd/pull/515) * Added override flag for setting WORKING_DIRECTORY. Enabled tests to run from build directory [PR #508](https://github.com/Autodesk/maya-usd/pull/508) [PR #616](https://github.com/Autodesk/maya-usd/pull/616) * Removed support for Maya releases older than 2018 [PR #501](https://github.com/Autodesk/maya-usd/pull/501) * Introduced `compiler_config.cmake` where all the compiler flags/options are applied. [PR #412](https://github.com/Autodesk/maya-usd/pull/412) [PR #443](https://github.com/Autodesk/maya-usd/pull/443) [PR #445](https://github.com/Autodesk/maya-usd/pull/445) * Removed `cmake/defaults/Version.cmake` [PR #440](https://github.com/Autodesk/maya-usd/pull/440) * Updated C++ standard version C++14 [PR #438](https://github.com/Autodesk/maya-usd/pull/438) * Fixed the build when project is not created with Qt [PR #411](https://github.com/Autodesk/maya-usd/pull/411) * Updated mayaUsd_add_test macro calls in AL plugin to add support for additional schema paths [PR #409](https://github.com/Autodesk/maya-usd/pull/409) * Adopted coding guidelines (include directives and cmake) [PR #407](https://github.com/Autodesk/maya-usd/pull/407) [PR #408](https://github.com/Autodesk/maya-usd/pull/408) [PR #585](https://github.com/Autodesk/maya-usd/pull/585) [PR #544](https://github.com/Autodesk/maya-usd/pull/544) [PR #547](https://github.com/Autodesk/maya-usd/pull/547) [PR #653](https://github.com/Autodesk/maya-usd/pull/653) * Various changes to comply with core USD dev branch commits (20.05 support + early 20.08) [PR #402](https://github.com/Autodesk/maya-usd/pull/402) [PR #449](https://github.com/Autodesk/maya-usd/pull/449) [PR #534](https://github.com/Autodesk/maya-usd/pull/534) * Reorganized lib folder [PR #388](https://github.com/Autodesk/maya-usd/pull/388) * Cleanded up build/usage requirements logics for cmake targets [PR #369](https://github.com/Autodesk/maya-usd/pull/369) * Removed hard-coded "pxr" namespace in favor of PXR_NS in baseExportCommand [PR #540](https://github.com/Autodesk/maya-usd/pull/540) * Fixed compilation error on gcc 9.1 [PR #441](https://github.com/Autodesk/maya-usd/pull/441) ### Translation Framework * Added material import via registry [PR #621](https://github.com/Autodesk/maya-usd/pull/621) * Filtered out objects to export by hierarchy [PR #657](https://github.com/Autodesk/maya-usd/pull/657) * Added menu in Hierarchy View to reset the model and variant selections [PR #634](https://github.com/Autodesk/maya-usd/pull/634) * Added option to save .usd files as binary or ascii [PR #630](https://github.com/Autodesk/maya-usd/pull/630) * Fixed opacity vs. transparency issues with UsdPreviewSurface and pxrUsdPreviewSurface [PR #626](https://github.com/Autodesk/maya-usd/pull/626) * Made export UV sets as USD Texture Coordinate value types by default [PR #618](https://github.com/Autodesk/maya-usd/pull/618) * Filtered out wheel events on the variant set combo boxes [PR #600](https://github.com/Autodesk/maya-usd/pull/600) * Added material export via registry [PR #574](https://github.com/Autodesk/maya-usd/pull/574) * Moved mesh translator utilities to core library [PR #420](https://github.com/Autodesk/maya-usd/pull/420) * Moved Pixar import / export commands into core lib library [PR #398](https://github.com/Autodesk/maya-usd/pull/398) * Added .usdz extension to the identifyFile function [PR #396](https://github.com/Autodesk/maya-usd/pull/396) ### Workflow * Fixed anonymous layer default name [PR #660](https://github.com/Autodesk/maya-usd/pull/660) * Improved renaming support [PR #659](https://github.com/Autodesk/maya-usd/pull/659) [PR #639](https://github.com/Autodesk/maya-usd/pull/639) [PR #628](https://github.com/Autodesk/maya-usd/pull/628) [PR #627](https://github.com/Autodesk/maya-usd/pull/627) [PR #625](https://github.com/Autodesk/maya-usd/pull/625) [PR #483](https://github.com/Autodesk/maya-usd/pull/483) [PR #475](https://github.com/Autodesk/maya-usd/pull/475) * Added support for mixed data model compute [PR #594](https://github.com/Autodesk/maya-usd/pull/594) * Updated UFE interface for Create Group [PR #593](https://github.com/Autodesk/maya-usd/pull/593) * Reduced number of transform API conversions [PR #569](https://github.com/Autodesk/maya-usd/pull/569) * Allowed tear-off of Create sub-menu [PR #549](https://github.com/Autodesk/maya-usd/pull/549) * Added UFE interface for parenting [PR #455](https://github.com/Autodesk/maya-usd/pull/455) [PR #545](https://github.com/Autodesk/maya-usd/pull/545) * Improved duplicate command to avoid name collisions [PR #541](https://github.com/Autodesk/maya-usd/pull/541) * Fixed missing notice when newly created proxy shape is dirty [PR #536](https://github.com/Autodesk/maya-usd/pull/536) * Removed all UFE interface data members from UFE handlers [PR #523](https://github.com/Autodesk/maya-usd/pull/523) * Use separate UsdStageCache's for stages that loadAll or loadNone [PR #519](https://github.com/Autodesk/maya-usd/pull/519) * Added add/clear reference menu op's [PR #503](https://github.com/Autodesk/maya-usd/pull/503) [PR #521](https://github.com/Autodesk/maya-usd/pull/521) * Added add prim menu op's [PR #489](https://github.com/Autodesk/maya-usd/pull/489) * Added ability to create proxy shape with new in-memory root layer [PR #478](https://github.com/Autodesk/maya-usd/pull/478) * UFE notification now watches for full xformOpOrder changes [PR #476](https://github.com/Autodesk/maya-usd/pull/476) * Fixed object/sub-tree framing [PR #472](https://github.com/Autodesk/maya-usd/pull/472) * Added clear stage cach on file new/open [PR #437](https://github.com/Autodesk/maya-usd/pull/437) * Renamed 'Create Stage from Existing Layer' [PR #413](https://github.com/Autodesk/maya-usd/pull/413) * Organized transform attributes in UFE AE [PR #383](https://github.com/Autodesk/maya-usd/pull/383) * Updated UFE Attribute interface for USD to read attribute values for current time [PR #381](https://github.com/Autodesk/maya-usd/pull/381) * Added UFE string path support [PR #368](https://github.com/Autodesk/maya-usd/pull/368) * Removed MAYA_WANT_UFE_SELECTION from mod file [PR #367](https://github.com/Autodesk/maya-usd/pull/367) ### Render * Added selection by kind [PR #641](https://github.com/Autodesk/maya-usd/pull/641) * Fixed the regression for selecting single instance objects. [PR #620](https://github.com/Autodesk/maya-usd/pull/620) * Added playblasting support to mtoh [PR #615](https://github.com/Autodesk/maya-usd/pull/615) * Enabled level 1 complexity level for basisCurves [PR #598](https://github.com/Autodesk/maya-usd/pull/598) * Enabled multi connections between shaders on Maya 2018 and 2019 [PR #597](https://github.com/Autodesk/maya-usd/pull/597) * Support rendering purpose [PR #517](https://github.com/Autodesk/maya-usd/pull/517) [PR #558](https://github.com/Autodesk/maya-usd/pull/558) [PR #587](https://github.com/Autodesk/maya-usd/pull/587) * Refactored and improved performance of Pixar batch renderer [PR #577](https://github.com/Autodesk/maya-usd/pull/577) * Improved instance selection performance [PR #575](https://github.com/Autodesk/maya-usd/pull/575) * Hide MRenderItems created for instancers with zero instances [PR #570](https://github.com/Autodesk/maya-usd/pull/570) * Fixed crash with UsdSkel. Skinned mesh is not supported yet, only skeleton will be drawn [PR #559](https://github.com/Autodesk/maya-usd/pull/559) * Added UDIM texture support [PR #538](https://github.com/Autodesk/maya-usd/pull/538) * Fixed selection update on new objects [PR #537](https://github.com/Autodesk/maya-usd/pull/537) * Split pre and post scene passes so camera guides go above Hydra in mtoh. [PR #526](https://github.com/Autodesk/maya-usd/pull/526) * Fixed selection highlight disappears when switching variant [PR #524](https://github.com/Autodesk/maya-usd/pull/524) * Fixing the crash when loading USDSkel [PR #514](https://github.com/Autodesk/maya-usd/pull/514) * Removed UsdMayaGLHdRenderer [PR #482](https://github.com/Autodesk/maya-usd/pull/482) * Fixed viewport refresh after changing the USD stage on proxy [PR #474](https://github.com/Autodesk/maya-usd/pull/474) * Added support for outline selection hilighting and disabling color-quantization in mtoh [PR #469](https://github.com/Autodesk/maya-usd/pull/469) * Added diffuse color multidraw consolidation [PR #468](https://github.com/Autodesk/maya-usd/pull/468) * Removed Pixar batch renderer's support of MAYA_VP2_USE_VP1_SELECTION env var [PR #450](https://github.com/Autodesk/maya-usd/pull/450) * Enabled consolidation for instanced render items [PR #436](https://github.com/Autodesk/maya-usd/pull/436) * Fixed failure to create shader instance when running command-line render [PR #431](https://github.com/Autodesk/maya-usd/pull/431) * Added a script to measure key performance information for MayaUsd Vp2RenderDelegate. [PR #415](https://github.com/Autodesk/maya-usd/pull/415) ### Documentation * Updated build documentation regarding pip install [PR #638](https://github.com/Autodesk/maya-usd/pull/638) * Updated build documentation regarding Catalina [PR #614](https://github.com/Autodesk/maya-usd/pull/614) * Added Python, CMake guidelines and clang-format [PR #484](https://github.com/Autodesk/maya-usd/pull/484) * Added Markdown version of Pixar Maya USD Plugin Doc [PR #384](https://github.com/Autodesk/maya-usd/pull/384) * Added coding guidelines for maya-usd repository [PR #380](https://github.com/Autodesk/maya-usd/pull/380) [PR #400](https://github.com/Autodesk/maya-usd/pull/400) ## [0.1.0] - 2020-03-15 This release adds *all* changes made to refactoring_sandbox branch, including BaseProxyShape, Maya’s Attribute Editor and Outliner support via Ufe-USD runtime plugin, VP2RenderDelegate and Maya To Hydra. Added Autodesk plugin with Import/Export workflows and initial support for stage creation. Made several build improvements, including fixing regression tests execution on all supported platforms. ### Build * Fixed regression tests to run on all supported platforms [PR #198](https://github.com/Autodesk/maya-usd/pull/198) * Improved CMake code and changed minimum version [PR #323](https://github.com/Autodesk/maya-usd/pull/323) * Number several build documentation [PR #208](https://github.com/Autodesk/maya-usd/pull/208) [PR #150](https://github.com/Autodesk/maya-usd/issues/150) [PR #346](https://github.com/Autodesk/maya-usd/pull/346) * Improved configuration of “mayaUSD.mod" with build variables [Issue #21](https://github.com/Autodesk/maya-usd/issues/21) [PR #29](https://github.com/Autodesk/maya-usd/pull/29) * Enabled strict compilation mode for all platforms [PR #222](https://github.com/Autodesk/maya-usd/pull/222) [PR #275](https://github.com/Autodesk/maya-usd/pull/275) [PR #293](https://github.com/Autodesk/maya-usd/pull/293) * Enabled C++11 for GoogleTest external project [#290](https://github.com/Autodesk/maya-usd/pull/290) * Added UFE_PREVIEW_VERSION_NUM pre-processor support. [#289](https://github.com/Autodesk/maya-usd/pull/289) * Qt support for older versions of Maya [PR #318](https://github.com/Autodesk/maya-usd/pull/318) * Added a timer to measure the elapsed time to finish the build. [PR #307](https://github.com/Autodesk/maya-usd/pull/307) * Added HEAD sha/date in the build.log [PR #229](https://github.com/Autodesk/maya-usd/pull/229) * Fixed & closed several build issues ### Translation framework * Refactored Pixar plugin to create one translation framework in mayaUsd core library. Moved Pixar translator plugin to build as a shared module across all studio plugins [PR #154](https://github.com/Autodesk/maya-usd/pull/154) * Refactored AL_USDUtils to create a new shared library under lib. Added support for C++ tests in lib [PR #288](https://github.com/Autodesk/maya-usd/pull/288) ### Workflows * Added bounding box interface to UFE and fixed frame selection [PR #210](https://github.com/Autodesk/maya-usd/pull/210) * Added Attribute Editor support [PR #142](https://github.com/Autodesk/maya-usd/pull/142) * Added base proxy shape and UFE-USD runtime plugin [PR #91](https://github.com/Autodesk/maya-usd/pull/91) * Added attribute observation to UFE and fixed viewport and AE refresh issues [PR #204](https://github.com/Autodesk/maya-usd/pull/204) * Added contextual operations to UFE with basic UFE-USD implementation [PR #303](https://github.com/Autodesk/maya-usd/pull/303) * Added MayaReference schema and reader implementation [#255](https://github.com/Autodesk/maya-usd/pull/255) * Fixed duplicating proxy shape crash [Issue #69](https://github.com/Autodesk/maya-usd/issues/69) * Fixed renaming of prims [Issue #75](https://github.com/Autodesk/maya-usd/issues/75) [PR #237](https://github.com/Autodesk/maya-usd/pull/237) * Fixed duplicate prim [Issue #72](https://github.com/Autodesk/maya-usd/issues/72) *Autodesk plugin* * Added import UI [PR #304](https://github.com/Autodesk/maya-usd/pull/304) [PR #206](https://github.com/Autodesk/maya-usd/pull/206) [PR #276](https://github.com/Autodesk/maya-usd/pull/276) * Clear frameSamples set [#326](https://github.com/Autodesk/maya-usd/pull/326) * Added export UI [PR #216](https://github.com/Autodesk/maya-usd/pull/216) * Enabled import of .usdz files [PR #313](https://github.com/Autodesk/maya-usd/pull/313) * Added “Create USD Stage” to enable proxy shape creation from Maya’s UI [PR #306](https://github.com/Autodesk/maya-usd/pull/306) [PR #317](https://github.com/Autodesk/maya-usd/pull/317) *Animal Logic plugin* * Disabled push to prim to avoid generation of overs while updating the data [PR #295](https://github.com/Autodesk/maya-usd/pull/295) * Added approximate equality checks to determine if new value needs to be saved [PR #294](https://github.com/Autodesk/maya-usd/pull/294) * Fixed colour set export type to be Color3f/Color4f [PR #274](https://github.com/Autodesk/maya-usd/pull/274) * Improved interfaces for BasicTransformationMatrix and TransformationMatrix [PR #251](https://github.com/Autodesk/maya-usd/pull/251) * Improved ColorSet import/export to support USD displayOpacity primvar [PR #250](https://github.com/Autodesk/maya-usd/pull/250) * Fixed crash using TranslatePrim non-recursively on a previously translated transform/scope [PR #249](https://github.com/Autodesk/maya-usd/pull/249) * Added generate unique key method to reduce translator updates to only dirty prims [PR #248](https://github.com/Autodesk/maya-usd/pull/248) * Improved time to select objects in the viewport for ProxyDrawOverride [PR #247](https://github.com/Autodesk/maya-usd/pull/247) * Improved push to prim to avoid generating overs [Issue PR #246](https://github.com/Autodesk/maya-usd/pull/246) * Improved performance when processing prim meta data [PR #245](https://github.com/Autodesk/maya-usd/pull/245) * Improved USDGeomScope import [PR #232](https://github.com/Autodesk/maya-usd/pull/232) * Added USDGeomScope support in Proxy Shape [PR #185](https://github.com/Autodesk/maya-usd/pull/185) * Changed pushToPrim default to On [PR #149](https://github.com/Autodesk/maya-usd/pull/149) *Pixar plugin* * Fixed uniform buffer bindings during batch renderer selection [PR #291](https://github.com/Autodesk/maya-usd/pull/291) * Added profiler & performance tracing when using batch renderer [PR #260](https://github.com/Autodesk/maya-usd/pull/260) ### Render * Added VP2RenderDelegate [PR #91](https://github.com/Autodesk/maya-usd/pull/91) * Added support for wireframe and bounding box display [PR #112](https://github.com/Autodesk/maya-usd/pull/112) * Fixed selection highlight when selecting multiple proxy shapes [Issue #105](https://github.com/Autodesk/maya-usd/issues/105) * Fixed moving proxy shape in VP2RenderDelegate [Issue #71](https://github.com/Autodesk/maya-usd/issues/71) * Fixed hiding proxy shape in VP2RenderDelegate [Issue #70](https://github.com/Autodesk/maya-usd/issues/70) * Added a way for pxrUsdProxyShape to disable subpath selection with the VP2RenderDelegate [PR #315](https://github.com/Autodesk/maya-usd/pull/315) * Added support for USD curves in VP2RenderDelegate [PR #228](https://github.com/Autodesk/maya-usd/pull/228) * Added Maya-to-Hydra (mtoh) plugin and scene delegate [PR #231](https://github.com/Autodesk/maya-usd/pull/231) * Fixed material support in hdMaya with USD 20.2 [Issue #135](https://github.com/Autodesk/maya-usd/issues/135) * Removed MtohGetDefaultRenderer [PR #311](https://github.com/Autodesk/maya-usd/pull/311) * Fixed mtoh initialization to reject invalid delegates. [#292](https://github.com/Autodesk/maya-usd/pull/292) ## [v0.0.2] - 2019-10-30 This release has the last merge from original repositories. Brings AnimalLogic plugin to version 0.34.6 and Pixar plugin to version 19.11. Both plugins now continue to be developed only in maya-usd repository. ## [v0.0.1] - 2019-10-01 This is the first released version containing AnimalLogic (0.31.1) and Pixar (19.05) plugins. <file_sep>/lib/mayaUsd/python/wrapAdaptor.cpp // // Copyright 2018 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <mayaUsd/fileio/registryHelper.h> #include <mayaUsd/fileio/utils/adaptor.h> #include <mayaUsd/utils/undoHelperCommand.h> #include <mayaUsd/utils/util.h> #include <pxr/base/tf/pyResultConversions.h> #include <pxr/pxr.h> #include <pxr/usd/usd/attribute.h> #include <pxr/usd/usd/pyConversions.h> #include <pxr/usd/usdGeom/primvar.h> #include <maya/MObject.h> #include <boost/python.hpp> using namespace boost::python; PXR_NAMESPACE_USING_DIRECTIVE; static UsdMayaAdaptor* _Adaptor__init__(const std::string& dagPath) { MObject object; MStatus status = UsdMayaUtil::GetMObjectByName(dagPath, object); if (!status) { return new UsdMayaAdaptor(MObject::kNullObj); } return new UsdMayaAdaptor(object); } static boost::python::object _Adaptor_GetMetadata(const UsdMayaAdaptor& self, const TfToken& key) { VtValue value; if (self.GetMetadata(key, &value)) { return boost::python::object(value); } return boost::python::object(); } static bool _Adaptor_SetMetadata(UsdMayaAdaptor& self, const TfToken& key, const VtValue& value) { return UsdMayaUndoHelperCommand::ExecuteWithUndo<bool>( [&self, &key, &value](MDGModifier& modifier) { return self.SetMetadata(key, value, modifier); }); } static void _Adaptor_ClearMetadata(UsdMayaAdaptor& self, const TfToken& key) { UsdMayaUndoHelperCommand::ExecuteWithUndo( [&self, &key](MDGModifier& modifier) { self.ClearMetadata(key, modifier); }); } static UsdMayaAdaptor::SchemaAdaptor _Adaptor_ApplySchema(UsdMayaAdaptor& self, const TfType& ty) { typedef UsdMayaAdaptor::SchemaAdaptor Result; return UsdMayaUndoHelperCommand::ExecuteWithUndo<Result>( [&self, &ty](MDGModifier& modifier) { return self.ApplySchema(ty, modifier); }); } static UsdMayaAdaptor::SchemaAdaptor _Adaptor_ApplySchemaByName(UsdMayaAdaptor& self, const TfToken& schemaName) { typedef UsdMayaAdaptor::SchemaAdaptor Result; return UsdMayaUndoHelperCommand::ExecuteWithUndo<Result>( [&self, &schemaName](MDGModifier& modifier) { return self.ApplySchemaByName(schemaName, modifier); }); } static void _Adaptor_UnapplySchema(UsdMayaAdaptor& self, const TfType& ty) { UsdMayaUndoHelperCommand::ExecuteWithUndo( [&self, &ty](MDGModifier& modifier) { self.UnapplySchema(ty, modifier); }); } static void _Adaptor_UnapplySchemaByName(UsdMayaAdaptor& self, const TfToken& schemaName) { UsdMayaUndoHelperCommand::ExecuteWithUndo([&self, &schemaName](MDGModifier& modifier) { self.UnapplySchemaByName(schemaName, modifier); }); } static std::string _Adaptor__repr__(const UsdMayaAdaptor& self) { if (self) { return TfStringPrintf( "%sAdaptor('%s')", TF_PY_REPR_PREFIX.c_str(), self.GetMayaNodeName().c_str()); } else { return "invalid adaptor"; } } static UsdMayaAdaptor::AttributeAdaptor _SchemaAdaptor_CreateAttribute(UsdMayaAdaptor::SchemaAdaptor& self, const TfToken& attrName) { typedef UsdMayaAdaptor::AttributeAdaptor Result; return UsdMayaUndoHelperCommand::ExecuteWithUndo<Result>( [&self, &attrName](MDGModifier& modifier) { return self.CreateAttribute(attrName, modifier); }); } static void _SchemaAdaptor_RemoveAttribute(UsdMayaAdaptor::SchemaAdaptor& self, const TfToken& attrName) { UsdMayaUndoHelperCommand::ExecuteWithUndo([&self, &attrName](MDGModifier& modifier) { return self.RemoveAttribute(attrName, modifier); }); } static std::string _SchemaAdaptor__repr__(const UsdMayaAdaptor::SchemaAdaptor& self) { if (self) { return TfStringPrintf( "%s.GetSchemaByName('%s')", TfPyRepr(self.GetNodeAdaptor()).c_str(), self.GetName().GetText()); } else { return "invalid schema adaptor"; } } static boost::python::object _AttributeAdaptor_Get(const UsdMayaAdaptor::AttributeAdaptor& self) { VtValue value; if (self.Get(&value)) { return boost::python::object(value); } return boost::python::object(); } static bool _AttributeAdaptor_Set(UsdMayaAdaptor::AttributeAdaptor& self, const VtValue& value) { return UsdMayaUndoHelperCommand::ExecuteWithUndo<bool>( [&self, &value](MDGModifier& modifier) { return self.Set(value, modifier); }); } static std::string _AttributeAdaptor__repr__(const UsdMayaAdaptor::AttributeAdaptor& self) { std::string schemaName; const SdfAttributeSpecHandle attrDef = self.GetAttributeDefinition(); if (TF_VERIFY(attrDef)) { const SdfPrimSpecHandle schemaDef = TfDynamic_cast<const SdfPrimSpecHandle>(attrDef->GetOwner()); if (TF_VERIFY(schemaDef)) { schemaName = schemaDef->GetName(); } } if (self) { return TfStringPrintf( "%s.GetSchemaByName('%s').GetAttribute('%s')", TfPyRepr(self.GetNodeAdaptor()).c_str(), schemaName.c_str(), self.GetName().GetText()); } else { return "invalid attribute adaptor"; } } static void RegisterTypedSchemaConversion(const std::string& nodeTypeName, const TfType& usdType) { UsdMayaAdaptor::RegisterTypedSchemaConversion(nodeTypeName, usdType, true); } static void RegisterAttributeAlias(const TfToken& attributeName, const std::string& alias) { UsdMayaAdaptor::RegisterAttributeAlias(attributeName, alias, true); } void wrapAdaptor() { typedef UsdMayaAdaptor This; scope Adaptor = class_<This>("Adaptor", no_init) .def(!self) .def("__init__", make_constructor(_Adaptor__init__)) .def("__repr__", _Adaptor__repr__) .def("GetMayaNodeName", &This::GetMayaNodeName) .def("GetUsdTypeName", &This::GetUsdTypeName) .def("GetUsdType", &This::GetUsdType) .def("GetAppliedSchemas", &This::GetAppliedSchemas) .def("GetSchema", &This::GetSchema) .def( "GetSchemaByName", (This::SchemaAdaptor(This::*)(const TfToken&) const) & This::GetSchemaByName) .def( "GetSchemaOrInheritedSchema", (This::SchemaAdaptor(This::*)(const TfType&) const) & This::GetSchemaOrInheritedSchema) .def("ApplySchema", _Adaptor_ApplySchema) .def("ApplySchemaByName", _Adaptor_ApplySchemaByName) .def("UnapplySchema", _Adaptor_UnapplySchema) .def("UnapplySchemaByName", _Adaptor_UnapplySchemaByName) .def( "GetAllAuthoredMetadata", &This::GetAllAuthoredMetadata, return_value_policy<TfPyMapToDictionary>()) .def("GetMetadata", _Adaptor_GetMetadata) .def("SetMetadata", _Adaptor_SetMetadata) .def("ClearMetadata", _Adaptor_ClearMetadata) .def("GetPrimMetadataFields", &This::GetPrimMetadataFields) .staticmethod("GetPrimMetadataFields") .def( "GetRegisteredAPISchemas", &This::GetRegisteredAPISchemas, return_value_policy<TfPySequenceToList>()) .staticmethod("GetRegisteredAPISchemas") .def( "GetRegisteredTypedSchemas", &This::GetRegisteredTypedSchemas, return_value_policy<TfPySequenceToList>()) .staticmethod("GetRegisteredTypedSchemas") .def("RegisterAttributeAlias", &::RegisterAttributeAlias) .staticmethod("RegisterAttributeAlias") .def("GetAttributeAliases", &This::GetAttributeAliases) .staticmethod("GetAttributeAliases") .def("RegisterTypedSchemaConversion", &::RegisterTypedSchemaConversion) .staticmethod("RegisterTypedSchemaConversion"); class_<This::SchemaAdaptor>("SchemaAdaptor") .def(!self) .def("__repr__", _SchemaAdaptor__repr__) .def("GetNodeAdaptor", &This::SchemaAdaptor::GetNodeAdaptor) .def("GetName", &This::SchemaAdaptor::GetName) .def("GetAttribute", &This::SchemaAdaptor::GetAttribute) .def("CreateAttribute", _SchemaAdaptor_CreateAttribute) .def("RemoveAttribute", _SchemaAdaptor_RemoveAttribute) .def("GetAuthoredAttributeNames", &This::SchemaAdaptor::GetAuthoredAttributeNames) .def("GetAttributeNames", &This::SchemaAdaptor::GetAttributeNames); class_<This::AttributeAdaptor>("AttributeAdaptor") .def(!self) .def("__repr__", _AttributeAdaptor__repr__) .def("GetNodeAdaptor", &This::AttributeAdaptor::GetNodeAdaptor) .def("GetName", &This::AttributeAdaptor::GetName) .def("Get", _AttributeAdaptor_Get) .def("Set", _AttributeAdaptor_Set) .def("GetAttributeDefinition", &This::AttributeAdaptor::GetAttributeDefinition); } <file_sep>/lib/mayaUsd/ufe/UsdCameraHandler.cpp // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "UsdCameraHandler.h" #include "UsdCamera.h" #include "pxr/usd/usdGeom/camera.h" #include <mayaUsd/ufe/UsdSceneItem.h> namespace MAYAUSD_NS_DEF { namespace ufe { UsdCameraHandler::UsdCameraHandler() : Ufe::CameraHandler() { } UsdCameraHandler::~UsdCameraHandler() { } /*static*/ UsdCameraHandler::Ptr UsdCameraHandler::create() { return std::make_shared<UsdCameraHandler>(); } //------------------------------------------------------------------------------ // Ufe::CameraHandler overrides //------------------------------------------------------------------------------ Ufe::Camera::Ptr UsdCameraHandler::camera(const Ufe::SceneItem::Ptr& item) const { UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast<UsdSceneItem>(item); #if !defined(NDEBUG) assert(usdItem); #endif // Test if this item is a camera. If not, then we cannot create a camera // interface for it, which is a valid case (such as for a mesh node type). PXR_NS::UsdGeomCamera primSchema(usdItem->prim()); if (!primSchema) return nullptr; return UsdCamera::create(usdItem); } } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/lib/mayaUsd/ufe/ProxyShapeHierarchy.cpp // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "ProxyShapeHierarchy.h" #include <mayaUsd/ufe/Global.h> #include <mayaUsd/ufe/Utils.h> #include <pxr/usd/usd/stage.h> #include <ufe/log.h> #include <ufe/pathComponent.h> #include <ufe/pathSegment.h> #include <ufe/rtid.h> #include <cassert> #include <stdexcept> #ifdef UFE_V2_FEATURES_AVAILABLE #include <mayaUsd/ufe/UsdUndoCreateGroupCommand.h> #include <mayaUsd/ufe/UsdUndoInsertChildCommand.h> #include <mayaUsd/ufe/UsdUndoReorderCommand.h> #endif PXR_NAMESPACE_USING_DIRECTIVE namespace { UsdPrimSiblingRange getUSDFilteredChildren( const UsdPrim& prim, const Usd_PrimFlagsPredicate pred = UsdPrimDefaultPredicate) { // Since the equivalent of GetChildren is // GetFilteredChildren( UsdPrimDefaultPredicate ), // we will use that as the initial value. // return prim.GetFilteredChildren(pred); } } // namespace namespace MAYAUSD_NS_DEF { namespace ufe { //------------------------------------------------------------------------------ // Global variables //------------------------------------------------------------------------------ extern Ufe::Rtid g_USDRtid; //------------------------------------------------------------------------------ // ProxyShapeHierarchy //------------------------------------------------------------------------------ ProxyShapeHierarchy::ProxyShapeHierarchy(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler) : Ufe::Hierarchy() , fMayaHierarchyHandler(mayaHierarchyHandler) { } ProxyShapeHierarchy::~ProxyShapeHierarchy() { } /*static*/ ProxyShapeHierarchy::Ptr ProxyShapeHierarchy::create(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler) { return std::make_shared<ProxyShapeHierarchy>(mayaHierarchyHandler); } /*static*/ ProxyShapeHierarchy::Ptr ProxyShapeHierarchy::create( const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler, const Ufe::SceneItem::Ptr& item) { auto hierarchy = create(mayaHierarchyHandler); hierarchy->setItem(item); return hierarchy; } void ProxyShapeHierarchy::setItem(const Ufe::SceneItem::Ptr& item) { // Our USD root prim is from the stage, which is from the item. So if we are // changing the item, it's possible that we won't have the same stage (and // thus the same root prim). To be safe, clear our stored root prim. if (fItem != item) { fUsdRootPrim = UsdPrim(); } fItem = item; fMayaHierarchy = fMayaHierarchyHandler->hierarchy(item); } const UsdPrim& ProxyShapeHierarchy::getUsdRootPrim() const { if (!fUsdRootPrim.IsValid()) { // FIXME During AL_usdmaya_ProxyShapeImport, nodes (both Maya // and USD) are being added (e.g. the proxy shape itself), but // there is no stage yet, and there is no way to detect that a // proxy shape import command is under way. PPT, 28-Sep-2018. UsdStageWeakPtr stage = getStage(fItem->path()); if (stage) { fUsdRootPrim = stage->GetPseudoRoot(); } } return fUsdRootPrim; } //------------------------------------------------------------------------------ // Ufe::Hierarchy overrides //------------------------------------------------------------------------------ Ufe::SceneItem::Ptr ProxyShapeHierarchy::sceneItem() const { return fItem; } bool ProxyShapeHierarchy::hasChildren() const { const UsdPrim& rootPrim = getUsdRootPrim(); if (!rootPrim.IsValid()) { UFE_LOG("invalid root prim in ProxyShapeHierarchy::hasChildren()"); return false; } return !getUSDFilteredChildren(rootPrim).empty(); } Ufe::SceneItemList ProxyShapeHierarchy::children() const { // Return children of the USD root. const UsdPrim& rootPrim = getUsdRootPrim(); if (!rootPrim.IsValid()) return Ufe::SceneItemList(); return createUFEChildList(getUSDFilteredChildren(rootPrim)); } #ifdef UFE_V2_FEATURES_AVAILABLE Ufe::SceneItemList ProxyShapeHierarchy::filteredChildren(const ChildFilter& childFilter) const { // Return filtered children of the USD root. const UsdPrim& rootPrim = getUsdRootPrim(); if (!rootPrim.IsValid()) return Ufe::SceneItemList(); // Note: for now the only child filter flag we support is "Inactive Prims". // See UsdHierarchyHandler::childFilter() if ((childFilter.size() == 1) && (childFilter.front().name == "InactivePrims")) { // See uniqueChildName() for explanation of USD filter predicate. Usd_PrimFlagsPredicate flags = childFilter.front().value ? UsdPrimIsDefined && !UsdPrimIsAbstract : UsdPrimDefaultPredicate; return createUFEChildList(getUSDFilteredChildren(rootPrim, flags)); } UFE_LOG("Unknown child filter"); return Ufe::SceneItemList(); } #endif // Return UFE child list from input USD child list. Ufe::SceneItemList ProxyShapeHierarchy::createUFEChildList(const UsdPrimSiblingRange& range) const { // We must create selection items for our children. These will have as // path the path of the proxy shape, with a single path segment of a // single component appended to it. auto parentPath = fItem->path(); Ufe::SceneItemList children; for (const auto& child : range) { children.emplace_back(UsdSceneItem::create( parentPath + Ufe::PathSegment(Ufe::PathComponent(child.GetName().GetString()), g_USDRtid, '/'), child)); } return children; } Ufe::SceneItem::Ptr ProxyShapeHierarchy::parent() const { return fMayaHierarchy->parent(); } #ifndef UFE_V2_FEATURES_AVAILABLE // UFE v1 specific method Ufe::AppendedChild ProxyShapeHierarchy::appendChild(const Ufe::SceneItem::Ptr& child) { throw std::runtime_error("ProxyShapeHierarchy::appendChild() not implemented"); } #endif #ifdef UFE_V2_FEATURES_AVAILABLE Ufe::InsertChildCommand::Ptr ProxyShapeHierarchy::insertChildCmd( const Ufe::SceneItem::Ptr& child, const Ufe::SceneItem::Ptr& pos) { // UsdUndoInsertChildCommand expects a UsdSceneItem which wraps a prim, so // create one using the pseudo-root and our own path. auto usdItem = UsdSceneItem::create(sceneItem()->path(), getUsdRootPrim()); return UsdUndoInsertChildCommand::create(usdItem, downcast(child), downcast(pos)); } Ufe::SceneItem::Ptr ProxyShapeHierarchy::insertChild(const Ufe::SceneItem::Ptr& child, const Ufe::SceneItem::Ptr& pos) { auto insertChildCommand = insertChildCmd(child, pos); return insertChildCommand->insertedChild(); } #if (UFE_PREVIEW_VERSION_NUM >= 3005) Ufe::SceneItem::Ptr ProxyShapeHierarchy::createGroup(const Ufe::PathComponent& name) const { Ufe::SceneItem::Ptr createdItem; auto usdItem = UsdSceneItem::create(sceneItem()->path(), getUsdRootPrim()); UsdUndoCreateGroupCommand::Ptr cmd = UsdUndoCreateGroupCommand::create(usdItem, name.string()); if (cmd) { cmd->execute(); createdItem = cmd->insertedChild(); } return createdItem; } #else Ufe::SceneItem::Ptr ProxyShapeHierarchy::createGroup( const Ufe::Selection& selection, const Ufe::PathComponent& name) const { Ufe::SceneItem::Ptr createdItem; auto usdItem = UsdSceneItem::create(sceneItem()->path(), getUsdRootPrim()); UsdUndoCreateGroupCommand::Ptr cmd = UsdUndoCreateGroupCommand::create(usdItem, selection, name.string()); if (cmd) { cmd->execute(); createdItem = cmd->insertedChild(); } return createdItem; } #endif #if (UFE_PREVIEW_VERSION_NUM >= 3001) Ufe::InsertChildCommand::Ptr #else Ufe::UndoableCommand::Ptr #endif #if (UFE_PREVIEW_VERSION_NUM >= 3005) ProxyShapeHierarchy::createGroupCmd(const Ufe::PathComponent& name) const { auto usdItem = UsdSceneItem::create(sceneItem()->path(), getUsdRootPrim()); return UsdUndoCreateGroupCommand::create(usdItem, name.string()); } #else ProxyShapeHierarchy::createGroupCmd(const Ufe::Selection& selection, const Ufe::PathComponent& name) const { auto usdItem = UsdSceneItem::create(sceneItem()->path(), getUsdRootPrim()); return UsdUndoCreateGroupCommand::create(usdItem, selection, name.string()); } #endif Ufe::UndoableCommand::Ptr ProxyShapeHierarchy::reorderCmd(const Ufe::SceneItemList& orderedList) const { std::vector<TfToken> orderedTokens; for (const auto& item : orderedList) { orderedTokens.emplace_back(downcast(item)->prim().GetPath().GetNameToken()); } // create a reorder command and pass in the parent and its ordered children list return UsdUndoReorderCommand::create(getUsdRootPrim(), orderedTokens); } Ufe::SceneItem::Ptr ProxyShapeHierarchy::defaultParent() const { // Maya shape nodes cannot be unparented. return nullptr; } #endif // UFE_V2_FEATURES_AVAILABLE #ifdef UFE_V3_FEATURES_AVAILABLE Ufe::UndoableCommand::Ptr ProxyShapeHierarchy::ungroupCmd() const { // pseudo root can not be ungrouped. return nullptr; } #endif // UFE_V3_FEATURES_AVAILABLE } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/lib/usd/ui/layerEditor/qtUtils.cpp // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "qtUtils.h" #include <QtGui/QIcon> #include <QtGui/QPixmap> #include <QtWidgets/QtWidgets> namespace UsdLayerEditor { QIcon QtUtils::createIcon(const char* iconName) { return QIcon(iconName); } QPixmap QtUtils::createPNGResPixmap(QString const& in_pixmapName, int width, int height) { QString pixmapName(in_pixmapName); if (pixmapName.indexOf(".png") == -1) { pixmapName += ".png"; } const QString resourcePrefix(":/"); if (pixmapName.left(2) != resourcePrefix) { pixmapName = resourcePrefix + pixmapName; } return createPixmap(pixmapName, width, height); } QPixmap QtUtils::createPixmap(QString const& in_pixmapName, int width, int height) { QPixmap pixmap(in_pixmapName); if (width != 0 && height != 0) { return pixmap.scaled(width, height); } return pixmap; } UsdLayerEditor::QtUtils* utils; void QtUtils::initLayoutMargins(QLayout* layout, int margin) { layout->setContentsMargins(margin, margin, margin, margin); } // returns the widget after setting it fixed-size QWidget* QtUtils::fixedWidget(QWidget* widget) { widget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); return widget; } } // namespace UsdLayerEditor <file_sep>/lib/mayaUsd/fileio/CMakeLists.txt # ----------------------------------------------------------------------------- # sources # ----------------------------------------------------------------------------- target_sources(${PROJECT_NAME} PRIVATE fallbackPrimReader.cpp functorPrimReader.cpp functorPrimWriter.cpp importData.cpp instancedNodeWriter.cpp primReader.cpp primReaderArgs.cpp primReaderContext.cpp primReaderRegistry.cpp primUpdater.cpp primUpdaterContext.cpp primUpdaterRegistry.cpp primWriter.cpp primWriterArgs.cpp primWriterContext.cpp primWriterRegistry.cpp registryHelper.cpp shaderReader.cpp shaderReaderRegistry.cpp shaderWriter.cpp shaderWriterRegistry.cpp transformWriter.cpp writeJobContext.cpp ) set(HEADERS fallbackPrimReader.h functorPrimReader.h functorPrimWriter.h importData.h instancedNodeWriter.h primReader.h primReaderArgs.h primReaderContext.h primReaderRegistry.h primUpdater.h primUpdaterContext.h primUpdaterRegistry.h primWriter.h primWriterArgs.h primWriterContext.h primWriterRegistry.h registryHelper.h shaderReader.h shaderReaderRegistry.h shaderWriter.h shaderWriterRegistry.h transformWriter.h writeJobContext.h ) # ----------------------------------------------------------------------------- # promoted headers # ----------------------------------------------------------------------------- mayaUsd_promoteHeaderList(HEADERS ${HEADERS} SUBDIR fileio) # ----------------------------------------------------------------------------- # install # ----------------------------------------------------------------------------- install(FILES ${HEADERS} DESTINATION ${CMAKE_INSTALL_PREFIX}/include/${PROJECT_NAME}/fileio ) # ----------------------------------------------------------------------------- # subdirectories # ----------------------------------------------------------------------------- add_subdirectory(chaser) add_subdirectory(jobs) add_subdirectory(shading) add_subdirectory(translators) add_subdirectory(utils) <file_sep>/lib/mayaUsd/resources/ae/usdschemabase/ae_template.py # Copyright 2021 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import fnmatch from functools import partial import ufe import maya.mel as mel import maya.cmds as cmds import mayaUsd.ufe as mayaUsdUfe import mayaUsd.lib as mayaUsdLib import maya.internal.common.ufe_ae.template as ufeAeTemplate from maya.common.ui import LayoutManager from maya.common.ui import setClipboardData from maya.OpenMaya import MGlobal # We manually import all the classes which have a 'GetSchemaAttributeNames' # method so we have access to it and the 'pythonClass' method. from pxr import Usd, UsdGeom, UsdLux, UsdRender, UsdRi, UsdShade, UsdSkel, UsdUI, UsdVol, Kind, Tf nameTxt = 'nameTxt' attrValueFld = 'attrValueFld' attrTypeFld = 'attrTypeFld' def getPrettyName(name): # Put a space in the name when preceded by a capital letter. # Exceptions: Number followed by capital # Multiple capital letters together prettyName = str(name[0]) nbChars = len(name) for i in range(1, nbChars): if name[i].isupper() and not name[i-1].isdigit(): if (i < (nbChars-1)) and not name[i+1].isupper(): prettyName += ' ' prettyName += name[i] elif name[i] == '_': continue else: prettyName += name[i] # Make each word start with an uppercase. return prettyName.title() # Helper class to push/pop the Attribute Editor Template. This makes # sure that controls are aligned properly. class AEUITemplate: def __enter__(self): cmds.setUITemplate('attributeEditorTemplate', pst=True) return self def __exit__(self, mytype, value, tb): cmds.setUITemplate(ppt=True) # Custom control, but does not have any UI. Instead we use # this control to be notified from UFE when any attribute has changed # so we can update the AE. This is to fix refresh issue # when transform is added to a prim. class UfeAttributesObserver(ufe.Observer): def __init__(self, item): super(UfeAttributesObserver, self).__init__() self._item = item def __del__(self): ufe.Attributes.removeObserver(self) def __call__(self, notification): if isinstance(notification, ufe.AttributeValueChanged): if notification.name() == UsdGeom.Tokens.xformOpOrder: mel.eval("evalDeferred -low \"refreshEditorTemplates\";") def onCreate(self, *args): ufe.Attributes.addObserver(self._item, self) def onReplace(self, *args): # Nothing needed here since we don't create any UI. pass class MetaDataCustomControl(object): # Custom control for all prim metadata we want to display. def __init__(self, item, prim, useNiceName): # In Maya 2022.1 we need to hold onto the Ufe SceneItem to make # sure it doesn't go stale. This is not needed in latest Maya. mayaVer = '%s.%s' % (cmds.about(majorVersion=True), cmds.about(minorVersion=True)) self.item = item if mayaVer == '2022.1' else None self.prim = prim self.useNiceName = useNiceName # There are four metadata that we always show: primPath, kind, active, instanceable # We use a dictionary to store the various other metadata that this prim contains. self.extraMetadata = dict() def onCreate(self, *args): # Metadata: PrimPath # The prim path is for display purposes only - it is not editable, but we # allow keyboard focus so you copy the value. self.primPath = cmds.textFieldGrp(label='Prim Path', editable=False, enableKeyboardFocus=True) # Metadata: Kind # We add the known Kind types, in a certain order ("model hierarchy") and then any # extra ones that were added by extending the kind registry. # Note: we remove the "model" kind because in the USD docs it states, # "No prim should have the exact kind "model". allKinds = Kind.Registry.GetAllKinds() allKinds.remove(Kind.Tokens.model) knownKinds = [Kind.Tokens.group, Kind.Tokens.assembly, Kind.Tokens.component, Kind.Tokens.subcomponent] temp1 = [ele for ele in allKinds if ele not in knownKinds] knownKinds.extend(temp1) # If this prim's kind is not registered, we need to manually # add it to the list. model = Usd.ModelAPI(self.prim) primKind = model.GetKind() if primKind not in knownKinds: knownKinds.insert(0, primKind) if '' not in knownKinds: knownKinds.insert(0, '') # Set metadata value to "" (or empty). self.kind = cmds.optionMenuGrp(label='Kind', cc=self._onKindChanged, ann='Kind is a type of metadata (a pre-loaded string value) used to classify prims in USD. Set the classification value from the dropdown to assign a kind category to a prim. Set a kind value to activate selection by kind.') for ele in knownKinds: cmds.menuItem(label=ele) # Metadata: Active self.active = cmds.checkBoxGrp(label='Active', ncb=1, cc1=self._onActiveChanged, ann="If selected, the prim is set to active and contributes to the composition of a stage. If a prim is set to inactive, it doesn't contribute to the composition of a stage (it gets striked out in the Outliner and is deactivated from the Viewport).") # Metadata: Instanceable self.instan = cmds.checkBoxGrp(label='Instanceable', ncb=1, cc1=self._onInstanceableChanged, ann='If selected, instanceable is set to true for the prim and the prim is considered a candidate for instancing. If deselected, instanceable is set to false.') # Get all the other Metadata and remove the ones above, as well as a few # we don't ever want to show. allMetadata = self.prim.GetAllMetadata() keysToDelete = ['kind', 'active', 'instanceable', 'typeName', 'documentation'] for key in keysToDelete: allMetadata.pop(key, None) if allMetadata: cmds.separator(h=10, style='single', hr=True) for k in allMetadata: # All extra metadata is for display purposes only - it is not editable, but we # allow keyboard focus so you copy the value. mdLabel = getPrettyName(k) if self.useNiceName else k self.extraMetadata[k] = cmds.textFieldGrp(label=mdLabel, editable=False, enableKeyboardFocus=True) # Update all metadata values. self.refresh() def onReplace(self, *args): # Nothing needed here since USD data is not time varying. Normally this template # is force rebuilt all the time, except in response to time change from Maya. In # that case we don't need to update our controls since none will change. pass def refresh(self): # PrimPath cmds.textFieldGrp(self.primPath, edit=True, text=str(self.prim.GetPath())) # Kind model = Usd.ModelAPI(self.prim) primKind = model.GetKind() if not primKind: # Special case to handle the empty string (for meta data value empty). cmds.optionMenuGrp(self.kind, edit=True, select=1) else: cmds.optionMenuGrp(self.kind, edit=True, value=primKind) # Active cmds.checkBoxGrp(self.active, edit=True, value1=self.prim.IsActive()) # Instanceable cmds.checkBoxGrp(self.instan, edit=True, value1=self.prim.IsInstanceable()) # All other metadata types for k in self.extraMetadata: v = self.prim.GetMetadata(k) if k != 'customData' else self.prim.GetCustomData() cmds.textFieldGrp(self.extraMetadata[k], edit=True, text=str(v)) def _onKindChanged(self, value): with mayaUsdLib.UsdUndoBlock(): model = Usd.ModelAPI(self.prim) model.SetKind(value) def _onActiveChanged(self, value): with mayaUsdLib.UsdUndoBlock(): self.prim.SetActive(value) def _onInstanceableChanged(self, value): with mayaUsdLib.UsdUndoBlock(): self.prim.SetInstanceable(value) # Custom control for all array attribute. class ArrayCustomControl(object): def __init__(self, prim, attrName, useNiceName): self.prim = prim self.attrName = attrName self.useNiceName = useNiceName super(ArrayCustomControl, self).__init__() def onCreate(self, *args): attr = self.prim.GetAttribute(self.attrName) typeName = attr.GetTypeName() if typeName.isArray: values = attr.Get() hasValue = True if values and len(values) > 0 else False # build the array type string # We want something like int[size] or int[] if empty typeNameStr = str(typeName.scalarType) typeNameStr += ("[" + str(len(values)) + "]") if hasValue else "[]" attrLabel = getPrettyName(self.attrName) if self.useNiceName else self.attrName singleWidgetWidth = mel.eval('global int $gAttributeEditorTemplateSingleWidgetWidth; $gAttributeEditorTemplateSingleWidgetWidth += 0') with AEUITemplate(): # See comment in ConnectionsCustomControl below for why nc=5. rl = cmds.rowLayout(nc=5, adj=3) with LayoutManager(rl): cmds.text(nameTxt, al='right', label=attrLabel, annotation=attr.GetDocumentation()) cmds.textField(attrTypeFld, editable=False, text=typeNameStr, font='obliqueLabelFont', width=singleWidgetWidth*1.5) if hasValue: cmds.popupMenu() cmds.menuItem( label="Copy Attribute Value", command=lambda *args: setClipboardData(str(values)) ) cmds.menuItem( label="Print to Script Editor", command=lambda *args: MGlobal.displayInfo(str(values)) ) else: cmds.error(self.attrName + " must be an array!") def onReplace(self, *args): pass def showEditorForUSDPrim(usdPrimPathStr): # Simple helper to open the AE on input prim. mel.eval('evalDeferred "showEditor(\\\"%s\\\")"' % usdPrimPathStr) # Custom control for all attributes that have connections. class ConnectionsCustomControl(object): def __init__(self, ufeItem, prim, attrName, useNiceName): self.path = ufeItem.path() self.prim = prim self.attrName = attrName self.useNiceName = useNiceName super(ConnectionsCustomControl, self).__init__() def onCreate(self, *args): frontPath = self.path.popSegment() attr = self.prim.GetAttribute(self.attrName) attrLabel = getPrettyName(self.attrName) if self.useNiceName else self.attrName attrType = attr.GetMetadata('typeName') singleWidgetWidth = mel.eval('global int $gAttributeEditorTemplateSingleWidgetWidth; $gAttributeEditorTemplateSingleWidgetWidth += 0') with AEUITemplate(): # Because of the way the Maya AE template is defined we use a 5 column setup, even # though we only have two fields. We resize the main field and purposely set the # adjustable column to 3 (one we don't have a field in). We want the textField to # remain at a given width. rl = cmds.rowLayout(nc=5, adj=3) with LayoutManager(rl): cmds.text(nameTxt, al='right', label=attrLabel, annotation=attr.GetDocumentation()) cmds.textField(attrTypeFld, editable=False, text=attrType, backgroundColor=[0.945, 0.945, 0.647], font='obliqueLabelFont', width=singleWidgetWidth*1.5) # Add a menu item for each connection. cmds.popupMenu() for c in attr.GetConnections(): parentPath = c.GetParentPath() primName = parentPath.MakeRelativePath(parentPath.GetParentPath()) mLabel = '%s%s...' % (primName, c.elementString) usdSeg = ufe.PathSegment(str(c.GetPrimPath()), mayaUsdUfe.getUsdRunTimeId(), '/') newPath = (frontPath + usdSeg) newPathStr = ufe.PathString.string(newPath) cmds.menuItem(label=mLabel, command=lambda *args: showEditorForUSDPrim(newPathStr)) def onReplace(self, *args): # We only display the attribute name and type. Neither of these are time # varying, so we don't need to implement the replace. pass class NoticeListener(object): # Inserted as a custom control, but does not have any UI. Instead we use # this control to be notified from USD when any metadata has changed # so we can update the AE fields. def __init__(self, prim, metadataControls): self.prim = prim self.metadataControls = metadataControls def onCreate(self, *args): self.listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.__OnPrimsChanged, self.prim.GetStage()) pname = cmds.setParent(q=True) cmds.scriptJob(uiDeleted=[pname, self.onClose], runOnce=True) def onReplace(self, *args): # Nothing needed here since we don't create any UI. pass def onClose(self): if self.listener: self.listener.Revoke() self.listener = None def __OnPrimsChanged(self, notice, sender): if notice.HasChangedFields(self.prim): # Iterate thru all the metadata controls (we were given when created) and # call the refresh method (if it exists). for ctrl in self.metadataControls: if hasattr(ctrl, 'refresh'): ctrl.refresh() # SchemaBase template class for categorization of the attributes. # We no longer use the base class ufeAeTemplate.Template as we want to control # the placement of the metadata at the bottom (after extra attributes). class AETemplate(object): ''' This system of schema inherits groups attributes per schema helping the user learn how attributes are stored. ''' def __init__(self, ufeSceneItem): self.item = ufeSceneItem self.prim = mayaUsdUfe.ufePathToPrim(ufe.PathString.string(self.item.path())) # Get the UFE Attributes interface for this scene item. self.attrS = ufe.Attributes.attributes(self.item) self.addedAttrs = [] self.suppressedAttrs = [] self.showArrayAttributes = False if cmds.optionVar(exists="mayaUSD_AEShowArrayAttributes"): self.showArrayAttributes = cmds.optionVar(query="mayaUSD_AEShowArrayAttributes") # Should we display nice names in AE? self.useNiceName = True if cmds.optionVar(exists='attrEditorIsLongName'): self.useNiceName = (cmds.optionVar(q='attrEditorIsLongName') ==1) cmds.editorTemplate(beginScrollLayout=True) self.buildUI() self.createAppliedSchemasSection() self.createCustomExtraAttrs() self.createMetadataSection() cmds.editorTemplate(endScrollLayout=True) if ('%s.%s' % (cmds.about(majorVersion=True), cmds.about(minorVersion=True))) > '2022.1': # Because of how we dynamically build the Transform attribute section, # we need this template to rebuild each time it is needed. This will # also restore the collapse/expand state of the sections. # Note: in Maya 2022 all UFE templates were forcefully rebuilt, but # no restore of section states. try: cmds.editorTemplate(forceRebuild=True) except: pass def addControls(self, controls): for c in controls: if c not in self.suppressedAttrs: if self.attributeHasConnections(c): connectionsCustomControl = ConnectionsCustomControl(self.item, self.prim, c, self.useNiceName) self.defineCustom(connectionsCustomControl, c) elif self.isArrayAttribute(c): arrayCustomControl = ArrayCustomControl(self.prim, c, self.useNiceName) self.defineCustom(arrayCustomControl, c) else: cmds.editorTemplate(addControl=[c]) self.addedAttrs.append(c) def suppress(self, control): cmds.editorTemplate(suppress=control) self.suppressedAttrs.append(control) @staticmethod def defineCustom(customObj, attrs=[]): create = lambda *args : customObj.onCreate(args) replace = lambda *args : customObj.onReplace(args) cmds.editorTemplate(attrs, callCustom=[create, replace]) def createSection(self, layoutName, attrList, collapse=False): # We create the section named "layoutName" if at least one # of the attributes from the input list exists. for attr in attrList: if attr in self.suppressedAttrs: continue if self.attrS.hasAttribute(attr): with ufeAeTemplate.Layout(self, layoutName, collapse): # Note: addControls will silently skip any attributes # which do not exist. self.addControls(attrList) return def sectionNameFromSchema(self, schemaTypeName): '''Return a section name from the input schema type name. This section name is a pretty name used in the UI.''' # List of special rules for adjusting the base schema names. prefixToAdjust = { 'UsdAbc' : '', 'UsdGeomGprim' : 'GeometricPrim', 'UsdGeom' : '', 'UsdHydra' : '', 'UsdImagingGL' : '', 'UsdLux' : '', 'UsdMedia' : '', 'UsdRender' : '', 'UsdRi' : '', 'UsdShade' : '', 'UsdSkelAnimation' : 'SkelAnimation', 'UsdSkelBlendShape': 'BlendShape', 'UsdSkelSkeleton': 'Skeleton', 'UsdSkelRoot' : 'SkelRoot', 'UsdUI' : '', 'UsdUtils' : '', 'UsdVol' : '' } for p, r in prefixToAdjust.items(): if schemaTypeName.startswith(p): schemaTypeName = schemaTypeName.replace(p, r, 1) break schemaTypeName = getPrettyName(schemaTypeName) # if the schema name ends with "api", replace it with # "API" and make sure to only replace the last occurence. # Example: "Shaping api" which contains "api" twice most become "Shaping API" if schemaTypeName.endswith("api"): schemaTypeName = " API".join(schemaTypeName.rsplit("api", 1)) return schemaTypeName def createTransformAttributesSection(self, sectionName, attrsToAdd): # Get the xformOp order and add those attributes (in order) # followed by the xformOp order attribute. allAttrs = self.attrS.attributeNames geomX = UsdGeom.Xformable(self.prim) xformOps = geomX.GetOrderedXformOps() xformOpOrderNames = [op.GetOpName() for op in xformOps] xformOpOrderNames.append(UsdGeom.Tokens.xformOpOrder) # Don't use createSection because we want a sub-sections. with ufeAeTemplate.Layout(self, sectionName): with ufeAeTemplate.Layout(self, 'Transform Attributes'): attrsToAdd.remove(UsdGeom.Tokens.xformOpOrder) self.addControls(xformOpOrderNames) # Get the remainder of the xformOps and add them in an Unused section. xformOpUnusedNames = fnmatch.filter(allAttrs, 'xformOp:*') xformOpUnusedNames = [ele for ele in xformOpUnusedNames if ele not in xformOpOrderNames] self.createSection('Unused Transform Attributes', xformOpUnusedNames, collapse=True) # Then add any reamining Xformable attributes self.addControls(attrsToAdd) # Add a custom control for UFE attribute changed. t3dObs = UfeAttributesObserver(self.item) self.defineCustom(t3dObs) def createMetadataSection(self): # We don't use createSection() because these are metadata (not attributes). with ufeAeTemplate.Layout(self, 'Metadata', collapse=True): metaDataControl = MetaDataCustomControl(self.item, self.prim, self.useNiceName) usdNoticeControl = NoticeListener(self.prim, [metaDataControl]) self.defineCustom(metaDataControl) self.defineCustom(usdNoticeControl) def createCustomExtraAttrs(self): # We are not using the maya default "Extra Attributes" section # because we are using custom widget for array type and it's not # possible to inject our widget inside the maya "Extra Attributes" section. # The extraAttrs will contains suppressed attribute but this is not a big deal as # long as the suppressed attributes are suppressed by suppress(self, control). # This function will keep all suppressed attributes into a list which will be use # by addControls(). So any suppressed attributes in extraAttrs will be ignored later. extraAttrs = [attr for attr in self.attrS.attributeNames if attr not in self.addedAttrs] sectionName = mel.eval("uiRes(\"s_TPStemplateStrings.rExtraAttributes\");") self.createSection(sectionName, extraAttrs, True) def createAppliedSchemasSection(self): # USD version 0.21.2 is required because of # Usd.SchemaRegistry().GetPropertyNamespacePrefix() if Usd.GetVersion() < (0, 21, 2): return showAppliedSchemasSection = False # loop on all applied schemas and store all those # schema into a dictionary with the attributes. # Storing the schema into a dictionary allow us to # group all instances of a MultipleApply schema together # so we can later display them into the same UI section. # # By example, if UsdCollectionAPI is applied twice, UsdPrim.GetAppliedSchemas() # will return ["CollectionAPI:instance1","CollectionAPI:instance2"] but we want to group # both instance inside a "CollectionAPI" section. # schemaAttrsDict = {} appliedSchemas = self.prim.GetAppliedSchemas() for schema in appliedSchemas: if Usd.GetVersion() > (0, 21, 5): typeAndInstance = Usd.SchemaRegistry().GetTypeNameAndInstance(schema) else: typeAndInstance = Usd.SchemaRegistry().GetTypeAndInstance(schema) typeName = typeAndInstance[0] schemaType = Usd.SchemaRegistry().GetTypeFromName(typeName) if schemaType.pythonClass: isMultipleApplyAPISchema = Usd.SchemaRegistry().IsMultipleApplyAPISchema(typeName) if isMultipleApplyAPISchema: # get the attributes names. They will not include the namespace and instance name. instanceName = typeAndInstance[1] attrList = schemaType.pythonClass.GetSchemaAttributeNames(False, instanceName) # build the real attr name # By example, collection:lightLink:includeRoot namespace = Usd.SchemaRegistry().GetPropertyNamespacePrefix(typeName) prefix = namespace + ":" + instanceName + ":" attrList = [prefix + i for i in attrList] if typeName in schemaAttrsDict: schemaAttrsDict[typeName] += attrList else: schemaAttrsDict[typeName] = attrList else: attrList = schemaType.pythonClass.GetSchemaAttributeNames(False) schemaAttrsDict[typeName] = attrList # The "Applied Schemas" will be only visible if at least # one applied Schemas has attribute. if not showAppliedSchemasSection: for attr in attrList: if self.attrS.hasAttribute(attr): showAppliedSchemasSection = True break # Create the "Applied Schemas" section # with all the applied schemas if showAppliedSchemasSection: with ufeAeTemplate.Layout(self, 'Applied Schemas', collapse=True): for typeName, attrs in schemaAttrsDict.items(): typeName = self.sectionNameFromSchema(typeName) self.createSection(typeName, attrs, False) def buildUI(self): usdSch = Usd.SchemaRegistry() self.suppressArrayAttribute() # We use UFE for the ancestor node types since it caches the # results by node type. for schemaType in self.item.ancestorNodeTypes(): schemaType = usdSch.GetTypeFromName(schemaType) schemaTypeName = schemaType.typeName sectionName = self.sectionNameFromSchema(schemaTypeName) if schemaType.pythonClass: attrsToAdd = schemaType.pythonClass.GetSchemaAttributeNames(False) # We have a special case when building the Xformable section. if schemaTypeName == 'UsdGeomXformable': self.createTransformAttributesSection(sectionName, attrsToAdd) else: sectionsToCollapse = ['Curves', 'Point Based', 'Geometric Prim', 'Boundable', 'Imageable', 'Field Asset', 'Light'] collapse = sectionName in sectionsToCollapse self.createSection(sectionName, attrsToAdd, collapse) def suppressArrayAttribute(self): # Suppress all array attributes except UsdGeom.Tokens.xformOpOrder if not self.showArrayAttributes: for attrName in self.attrS.attributeNames: if self.isArrayAttribute(attrName): self.suppress(attrName) def isArrayAttribute(self, attrName): # Note: UsdGeom.Tokens.xformOpOrder is a exception, # we are not considering this attribute as an array. if self.attrS.attributeType(attrName) == ufe.Attribute.kGeneric and \ attrName != UsdGeom.Tokens.xformOpOrder: attr = self.prim.GetAttribute(attrName) typeName = attr.GetTypeName() return typeName.isArray return False def attributeHasConnections(self, attrName): # Simple helper to return whether the input attribute (by name) has # any connections. attr = self.prim.GetAttribute(attrName) return attr.HasAuthoredConnections() if attr else False <file_sep>/lib/mayaUsd/ufe/UsdUndoDeleteCommand.cpp // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "UsdUndoDeleteCommand.h" #include "private/UfeNotifGuard.h" #ifdef UFE_V2_FEATURES_AVAILABLE #include <mayaUsd/undo/UsdUndoBlock.h> #endif namespace MAYAUSD_NS_DEF { namespace ufe { UsdUndoDeleteCommand::UsdUndoDeleteCommand(const PXR_NS::UsdPrim& prim) : Ufe::UndoableCommand() , _prim(prim) { } UsdUndoDeleteCommand::~UsdUndoDeleteCommand() { } UsdUndoDeleteCommand::Ptr UsdUndoDeleteCommand::create(const PXR_NS::UsdPrim& prim) { return std::make_shared<UsdUndoDeleteCommand>(prim); } #ifdef UFE_V2_FEATURES_AVAILABLE void UsdUndoDeleteCommand::execute() { MayaUsd::ufe::InAddOrDeleteOperation ad; UsdUndoBlock undoBlock(&_undoableItem); _prim.SetActive(false); } void UsdUndoDeleteCommand::undo() { MayaUsd::ufe::InAddOrDeleteOperation ad; _undoableItem.undo(); } void UsdUndoDeleteCommand::redo() { MayaUsd::ufe::InAddOrDeleteOperation ad; _undoableItem.redo(); } #else void UsdUndoDeleteCommand::perform(bool state) { MayaUsd::ufe::InAddOrDeleteOperation ad; _prim.SetActive(state); } void UsdUndoDeleteCommand::undo() { perform(true); } void UsdUndoDeleteCommand::redo() { perform(false); } #endif } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/plugin/al/translators/CommonTranslatorOptions.cpp #include "CommonTranslatorOptions.h" #include "AL/maya/utils/PluginTranslatorOptions.h" #include <pxr/base/tf/registryManager.h> #include <pxr/base/tf/type.h> namespace AL { namespace usdmaya { namespace fileio { namespace translators { PXR_NAMESPACE_USING_DIRECTIVE AL::maya::utils::PluginTranslatorOptions* g_exportOptions = 0; AL::maya::utils::PluginTranslatorOptions* g_importOptions = 0; //---------------------------------------------------------------------------------------------------------------------- static const char* const g_compactionLevels[] = { "None", "Basic", "Medium", "Extensive", 0 }; //---------------------------------------------------------------------------------------------------------------------- void registerCommonTranslatorOptions() { auto context = AL::maya::utils::PluginTranslatorOptionsContextManager::find("ExportTranslator"); if (context) { g_exportOptions = new AL::maya::utils::PluginTranslatorOptions(*context, "Geometry Export"); g_exportOptions->addBool(GeometryExportOptions::kNurbsCurves, true); g_exportOptions->addBool(GeometryExportOptions::kMeshes, true); g_exportOptions->addBool(GeometryExportOptions::kMeshConnects, true); g_exportOptions->addBool(GeometryExportOptions::kMeshPoints, true); g_exportOptions->addBool(GeometryExportOptions::kMeshExtents, true); g_exportOptions->addBool(GeometryExportOptions::kMeshNormals, true); g_exportOptions->addBool(GeometryExportOptions::kMeshVertexCreases, true); g_exportOptions->addBool(GeometryExportOptions::kMeshEdgeCreases, true); g_exportOptions->addBool(GeometryExportOptions::kMeshUvs, true); g_exportOptions->addBool(GeometryExportOptions::kMeshUvOnly, false); g_exportOptions->addBool(GeometryExportOptions::kMeshPointsAsPref, false); g_exportOptions->addBool(GeometryExportOptions::kMeshColours, true); g_exportOptions->addBool(GeometryExportOptions::kMeshHoles, true); g_exportOptions->addBool(GeometryExportOptions::kNormalsAsPrimvars, false); g_exportOptions->addBool(GeometryExportOptions::kReverseOppositeNormals, false); g_exportOptions->addEnum(GeometryExportOptions::kCompactionLevel, g_compactionLevels, 3); } context = AL::maya::utils::PluginTranslatorOptionsContextManager::find("ImportTranslator"); if (context) { g_importOptions = new AL::maya::utils::PluginTranslatorOptions(*context, "Geometry Import"); g_importOptions->addBool(GeometryImportOptions::kNurbsCurves, true); g_importOptions->addBool(GeometryImportOptions::kMeshes, true); } } //---------------------------------------------------------------------------------------------------------------------- struct RegistrationHack { RegistrationHack() { registerCommonTranslatorOptions(); } }; //---------------------------------------------------------------------------------------------------------------------- RegistrationHack g_registration; //---------------------------------------------------------------------------------------------------------------------- } // namespace translators } // namespace fileio } // namespace usdmaya } // namespace AL //---------------------------------------------------------------------------------------------------------------------- <file_sep>/test/lib/ufe/testAttribute.py #!/usr/bin/env python # # Copyright 2019 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import fixturesUtils import mayaUtils import ufeUtils import testUtils import usdUtils from pxr import UsdGeom, Vt, Gf from maya import cmds from maya import standalone from maya.internal.ufeSupport import ufeCmdWrapper as ufeCmd import mayaUsd from mayaUsd import ufe as mayaUsdUfe import ufe import os import random import unittest class TestObserver(ufe.Observer): def __init__(self): super(TestObserver, self).__init__() self._notifications = 0 def __call__(self, notification): if (ufeUtils.ufeFeatureSetVersion() >= 2): if isinstance(notification, ufe.AttributeValueChanged): self._notifications += 1 else: if isinstance(notification, ufe.AttributeChanged): self._notifications += 1 @property def notifications(self): return self._notifications class AttributeTestCase(unittest.TestCase): '''Verify the Attribute UFE interface, for multiple runtimes. ''' pluginsLoaded = False @classmethod def setUpClass(cls): fixturesUtils.readOnlySetUpClass(__file__, loadPlugin=False) if not cls.pluginsLoaded: cls.pluginsLoaded = mayaUtils.isMayaUsdPluginLoaded() # Open top_layer.ma scene in testSamples mayaUtils.openTopLayerScene() random.seed() @classmethod def tearDownClass(cls): # See comments in MayaUFEPickWalkTesting.tearDownClass cmds.file(new=True, force=True) standalone.uninitialize() def setUp(self): '''Called initially to set up the maya test environment''' self.assertTrue(self.pluginsLoaded) def assertVectorAlmostEqual(self, ufeVector, usdVector): testUtils.assertVectorAlmostEqual( self, ufeVector.vector, usdVector) def assertColorAlmostEqual(self, ufeColor, usdColor): for va, vb in zip(ufeColor.color, usdColor): self.assertAlmostEqual(va, vb, places=6) def runUndoRedo(self, attr, newVal, decimalPlaces=None): oldVal = attr.get() assert oldVal != newVal, "Undo / redo testing requires setting a value different from the current value" ufeCmd.execute(attr.setCmd(newVal)) if decimalPlaces is not None: self.assertAlmostEqual(attr.get(), newVal, decimalPlaces) newVal = attr.get() else: self.assertEqual(attr.get(), newVal) cmds.undo() self.assertEqual(attr.get(), oldVal) cmds.redo() self.assertEqual(attr.get(), newVal) def runTestAttribute(self, path, attrName, ufeAttrClass, ufeAttrType): '''Engine method to run attribute test.''' # Create the UFE/USD attribute for this test from the input path. # Get a UFE scene item the input path in the scene. itemPath = ufe.Path([ mayaUtils.createUfePathSegment("|transform1|proxyShape1"), usdUtils.createUfePathSegment(path)]) ufeItem = ufe.Hierarchy.createItem(itemPath) # Get the USD prim for this item. usdPrim = usdUtils.getPrimFromSceneItem(ufeItem) # Create the attributes interface for the item. ufeAttrs = ufe.Attributes.attributes(ufeItem) self.assertIsNotNone(ufeAttrs) # Get the USDAttribute for the input attribute name so we can use it to # compare to UFE. usdAttr = usdPrim.GetAttribute(attrName) self.assertIsNotNone(usdAttr) # Get the attribute that matches the input name and make sure it matches # the class type of UFE attribute class passed in. self.assertTrue(ufeAttrs.hasAttribute(attrName)) ufeAttr = ufeAttrs.attribute(attrName) self.assertIsInstance(ufeAttr, ufeAttrClass) # Verify that the attribute type matches the input UFE type. self.assertEqual(ufeAttr.type, ufeAttrType) # Verify that the scene item the attribute was created with matches # what is stored in the UFE attribute. self.assertEqual(ufeAttr.sceneItem(), ufeItem) # Verify that this attribute has a value. Note: all the attributes that # are tested by this method are assumed to have a value. self.assertTrue(ufeAttr.hasValue()) # Verify that the name matched what we created the attribute from. self.assertEqual(ufeAttr.name, attrName) # Test that the string representation of the value is not empty. self.assertTrue(str(ufeAttr)) return ufeAttr, usdAttr def testAttributeGeneric(self): '''Test the Generic attribute type.''' # Use our engine method to run the bulk of the test (all the stuff from # the Attribute base class). We use the xformOpOrder attribute which is # an unsupported USD type, so it will be a UFE Generic attribute. ufeAttr, usdAttr = attrDict = self.runTestAttribute( path='/Room_set/Props/Ball_35', attrName=UsdGeom.Tokens.xformOpOrder, ufeAttrClass=ufe.AttributeGeneric, ufeAttrType=ufe.Attribute.kGeneric) # Now we test the Generic specific methods. self.assertEqual(ufeAttr.nativeType(), usdAttr.GetTypeName().type.typeName) def testAttributeEnumString(self): '''Test the EnumString attribute type.''' # Use our engine method to run the bulk of the test (all the stuff from # the Attribute base class). We use the visibility attribute which is # an EnumString type. ufeAttr, usdAttr = attrDict = self.runTestAttribute( path='/Room_set/Props/Ball_35', attrName=UsdGeom.Tokens.visibility, ufeAttrClass=ufe.AttributeEnumString, ufeAttrType=ufe.Attribute.kEnumString) # Now we test the EnumString specific methods. # Compare the initial UFE value to that directly from USD. self.assertEqual(ufeAttr.get(), usdAttr.Get()) # Make sure 'inherited' is in the list of allowed tokens. visEnumValues = ufeAttr.getEnumValues() self.assertIn(UsdGeom.Tokens.inherited, visEnumValues) # Change to 'invisible' and verify the return in UFE. ufeAttr.set(UsdGeom.Tokens.invisible) self.assertEqual(ufeAttr.get(), UsdGeom.Tokens.invisible) # Verify that the new UFE value matches what is directly in USD. self.assertEqual(ufeAttr.get(), usdAttr.Get()) # Change back to 'inherited' using a command. self.runUndoRedo(ufeAttr, UsdGeom.Tokens.inherited) def testAttributeBool(self): '''Test the Bool attribute type.''' # Use our engine method to run the bulk of the test (all the stuff from # the Attribute base class). We use the visibility attribute which is # an bool type. ufeAttr, usdAttr = attrDict = self.runTestAttribute( path='/Room_set/Props/Ball_35/mesh', attrName='doubleSided', ufeAttrClass=ufe.AttributeBool, ufeAttrType=ufe.Attribute.kBool) # Now we test the Bool specific methods. # Compare the initial UFE value to that directly from USD. self.assertEqual(ufeAttr.get(), usdAttr.Get()) # Set the attribute in UFE with the opposite boolean value. ufeAttr.set(not ufeAttr.get()) # Then make sure that new UFE value matches what it in USD. self.assertEqual(ufeAttr.get(), usdAttr.Get()) self.runUndoRedo(ufeAttr, not ufeAttr.get()) def testAttributeInt(self): '''Test the Int attribute type.''' # Use our engine method to run the bulk of the test (all the stuff from # the Attribute base class). We use the visibility attribute which is # an integer type. ufeAttr, usdAttr = attrDict = self.runTestAttribute( path='/Room_set/Props/Ball_35/Looks/BallLook/Base', attrName='inputAOV', ufeAttrClass=ufe.AttributeInt, ufeAttrType=ufe.Attribute.kInt) # Now we test the Int specific methods. # Compare the initial UFE value to that directly from USD. self.assertEqual(ufeAttr.get(), usdAttr.Get()) # Set the attribute in UFE with a different int value. ufeAttr.set(ufeAttr.get() + random.randint(1,5)) # Then make sure that new UFE value matches what it in USD. self.assertEqual(ufeAttr.get(), usdAttr.Get()) self.runUndoRedo(ufeAttr, ufeAttr.get()+1) def testAttributeFloat(self): '''Test the Float attribute type.''' # Use our engine method to run the bulk of the test (all the stuff from # the Attribute base class). We use the visibility attribute which is # an float type. ufeAttr, usdAttr = attrDict = self.runTestAttribute( path='/Room_set/Props/Ball_35/Looks/BallLook/Base', attrName='anisotropic', ufeAttrClass=ufe.AttributeFloat, ufeAttrType=ufe.Attribute.kFloat) # Now we test the Float specific methods. # Compare the initial UFE value to that directly from USD. self.assertEqual(ufeAttr.get(), usdAttr.Get()) # Set the attribute in UFE with a different float value. ufeAttr.set(random.random()) # Then make sure that new UFE value matches what it in USD. self.assertEqual(ufeAttr.get(), usdAttr.Get()) # Python floating-point numbers are doubles. If stored in a float # attribute, the resulting precision will be less than the original # Python value. self.runUndoRedo(ufeAttr, ufeAttr.get() + 1.0, decimalPlaces=6) def _testAttributeDouble(self): '''Test the Double attribute type.''' # I could not find an double attribute to test with pass def testAttributeStringString(self): '''Test the String (String) attribute type.''' # Use our engine method to run the bulk of the test (all the stuff from # the Attribute base class). We use the visibility attribute which is # an string type. ufeAttr, usdAttr = attrDict = self.runTestAttribute( path='/Room_set/Props/Ball_35/Looks/BallLook/BallTexture', attrName='filename', ufeAttrClass=ufe.AttributeString, ufeAttrType=ufe.Attribute.kString) # Now we test the String specific methods. # Compare the initial UFE value to that directly from USD. self.assertEqual(ufeAttr.get(), usdAttr.Get()) # check to see if the attribute edit is allowed # Set the attribute in UFE with a different string value. # Note: this ball uses the ball8.tex ufeAttr.set('./tex/ball7.tex') # Then make sure that new UFE value matches what it in USD. self.assertEqual(ufeAttr.get(), usdAttr.Get()) self.runUndoRedo(ufeAttr, 'potato') def testAttributeStringToken(self): '''Test the String (Token) attribute type.''' # Use our engine method to run the bulk of the test (all the stuff from # the Attribute base class). We use the visibility attribute which is # an string type. ufeAttr, usdAttr = attrDict = self.runTestAttribute( path='/Room_set/Props/Ball_35/Looks/BallLook/BallTexture', attrName='filter', ufeAttrClass=ufe.AttributeString, ufeAttrType=ufe.Attribute.kString) # Now we test the String specific methods. # Compare the initial UFE value to that directly from USD. self.assertEqual(ufeAttr.get(), usdAttr.Get()) # Set the attribute in UFE with a different string value. # Note: this attribute is initially set to token 'Box' ufeAttr.set('Sphere') # Then make sure that new UFE value matches what it in USD. self.assertEqual(ufeAttr.get(), usdAttr.Get()) self.runUndoRedo(ufeAttr, 'Box') def testAttributeColorFloat3(self): '''Test the ColorFloat3 attribute type.''' # Use our engine method to run the bulk of the test (all the stuff from # the Attribute base class). We use the visibility attribute which is # an ColorFloat3 type. ufeAttr, usdAttr = attrDict = self.runTestAttribute( path='/Room_set/Props/Ball_35/Looks/BallLook/Base', attrName='emitColor', ufeAttrClass=ufe.AttributeColorFloat3, ufeAttrType=ufe.Attribute.kColorFloat3) # Now we test the ColorFloat3 specific methods. # Compare the initial UFE value to that directly from USD. self.assertColorAlmostEqual(ufeAttr.get(), usdAttr.Get()) # Set the attribute in UFE with some random color values. vec = ufe.Color3f(random.random(), random.random(), random.random()) ufeAttr.set(vec) # Then make sure that new UFE value matches what it in USD. self.assertColorAlmostEqual(ufeAttr.get(), usdAttr.Get()) # The following causes a segmentation fault on CentOS 7. # self.runUndoRedo(ufeAttr, # ufe.Color3f(vec.r()+1.0, vec.g()+2.0, vec.b()+3.0)) # Entered as MAYA-102168. newVec = ufe.Color3f(vec.color[0]+1.0, vec.color[1]+2.0, vec.color[2]+3.0) self.runUndoRedo(ufeAttr, newVec) def _testAttributeInt3(self): '''Test the Int3 attribute type.''' # I could not find an int3 attribute to test with. pass def testAttributeFloat3(self): '''Test the Float3 attribute type.''' # Use our engine method to run the bulk of the test (all the stuff from # the Attribute base class). We use the visibility attribute which is # an Float3 type. ufeAttr, usdAttr = attrDict = self.runTestAttribute( path='/Room_set/Props/Ball_35/Looks/BallLook/Base', attrName='bumpNormal', ufeAttrClass=ufe.AttributeFloat3, ufeAttrType=ufe.Attribute.kFloat3) # Now we test the Float3 specific methods. # Compare the initial UFE value to that directly from USD. self.assertVectorAlmostEqual(ufeAttr.get(), usdAttr.Get()) # Set the attribute in UFE with some random values. vec = ufe.Vector3f(random.random(), random.random(), random.random()) ufeAttr.set(vec) # Then make sure that new UFE value matches what it in USD. self.assertVectorAlmostEqual(ufeAttr.get(), usdAttr.Get()) self.runUndoRedo(ufeAttr, ufe.Vector3f(vec.x()+1.0, vec.y()+2.0, vec.z()+3.0)) def testAttributeDouble3(self): '''Test the Double3 attribute type.''' # Use our engine method to run the bulk of the test (all the stuff from # the Attribute base class). We use the visibility attribute which is # an Double3 type. ufeAttr, usdAttr = attrDict = self.runTestAttribute( path='/Room_set/Props/Ball_35', attrName='xformOp:translate', ufeAttrClass=ufe.AttributeDouble3, ufeAttrType=ufe.Attribute.kDouble3) # Now we test the Double3 specific methods. # Compare the initial UFE value to that directly from USD. self.assertVectorAlmostEqual(ufeAttr.get(), usdAttr.Get()) # Set the attribute in UFE with some random values. vec = ufe.Vector3d(random.uniform(-100, 100), random.uniform(-100, 100), random.uniform(-100, 100)) ufeAttr.set(vec) # Then make sure that new UFE value matches what it in USD. self.assertVectorAlmostEqual(ufeAttr.get(), usdAttr.Get()) self.runUndoRedo(ufeAttr, ufe.Vector3d(vec.x()-1.0, vec.y()-2.0, vec.z()-3.0)) def testObservation(self): ''' Test Attributes observation interface. Test both global attribute observation and per-node attribute observation. ''' # Start we a clean scene so we can get a consistent number of notifications cmds.file(new=True, force=True) mayaUtils.openTopLayerScene() # Create three observers, one for global attribute observation, and two # on different UFE items. proxyShapePathSegment = mayaUtils.createUfePathSegment( "|transform1|proxyShape1") path = ufe.Path([ proxyShapePathSegment, usdUtils.createUfePathSegment('/Room_set/Props/Ball_34')]) ball34 = ufe.Hierarchy.createItem(path) path = ufe.Path([ proxyShapePathSegment, usdUtils.createUfePathSegment('/Room_set/Props/Ball_35')]) ball35 = ufe.Hierarchy.createItem(path) (ball34Obs, ball35Obs, globalObs) = [TestObserver() for i in range(3)] # Maya registers a single global observer on startup. # Maya-Usd lib registers a single global observer when it is initialized. kNbGlobalObs = 2 self.assertEqual(ufe.Attributes.nbObservers(), kNbGlobalObs) # No item-specific observers. self.assertFalse(ufe.Attributes.hasObservers(ball34.path())) self.assertFalse(ufe.Attributes.hasObservers(ball35.path())) self.assertEqual(ufe.Attributes.nbObservers(ball34), 0) self.assertEqual(ufe.Attributes.nbObservers(ball35), 0) self.assertFalse(ufe.Attributes.hasObserver(ball34, ball34Obs)) self.assertFalse(ufe.Attributes.hasObserver(ball35, ball35Obs)) # No notifications yet. self.assertEqual(ball34Obs.notifications, 0) self.assertEqual(ball35Obs.notifications, 0) self.assertEqual(globalObs.notifications, 0) # Add a global observer. ufe.Attributes.addObserver(globalObs) self.assertEqual(ufe.Attributes.nbObservers(), kNbGlobalObs+1) self.assertFalse(ufe.Attributes.hasObservers(ball34.path())) self.assertFalse(ufe.Attributes.hasObservers(ball35.path())) self.assertEqual(ufe.Attributes.nbObservers(ball34), 0) self.assertEqual(ufe.Attributes.nbObservers(ball35), 0) self.assertFalse(ufe.Attributes.hasObserver(ball34, ball34Obs)) self.assertFalse(ufe.Attributes.hasObserver(ball35, ball35Obs)) # Add item-specific observers. ufe.Attributes.addObserver(ball34, ball34Obs) self.assertEqual(ufe.Attributes.nbObservers(), kNbGlobalObs+1) self.assertTrue(ufe.Attributes.hasObservers(ball34.path())) self.assertFalse(ufe.Attributes.hasObservers(ball35.path())) self.assertEqual(ufe.Attributes.nbObservers(ball34), 1) self.assertEqual(ufe.Attributes.nbObservers(ball35), 0) self.assertTrue(ufe.Attributes.hasObserver(ball34, ball34Obs)) self.assertFalse(ufe.Attributes.hasObserver(ball34, ball35Obs)) self.assertFalse(ufe.Attributes.hasObserver(ball35, ball35Obs)) ufe.Attributes.addObserver(ball35, ball35Obs) self.assertTrue(ufe.Attributes.hasObservers(ball35.path())) self.assertEqual(ufe.Attributes.nbObservers(ball34), 1) self.assertEqual(ufe.Attributes.nbObservers(ball35), 1) self.assertTrue(ufe.Attributes.hasObserver(ball35, ball35Obs)) self.assertFalse(ufe.Attributes.hasObserver(ball35, ball34Obs)) # Make a change to ball34, global and ball34 observers change. ball34Attrs = ufe.Attributes.attributes(ball34) ball34XlateAttr = ball34Attrs.attribute('xformOp:translate') self.assertEqual(ball34Obs.notifications, 0) # The first modification adds a new spec to ball_34 & its ancestors # "Props" and "Room_set". Ufe should be filtering out those notifications # so the global observer should still only see one notification. ufeCmd.execute(ball34XlateAttr.setCmd(ufe.Vector3d(4, 4, 15))) self.assertEqual(ball34Obs.notifications, 1) self.assertEqual(ball35Obs.notifications, 0) self.assertEqual(globalObs.notifications, 1) # The second modification only sends one USD notification for "xformOps:translate" # because all the spec's already exist. Ufe should also see one notification. ufeCmd.execute(ball34XlateAttr.setCmd(ufe.Vector3d(4, 4, 20))) self.assertEqual(ball34Obs.notifications, 2) self.assertEqual(ball35Obs.notifications, 0) self.assertEqual(globalObs.notifications, 2) # Undo, redo cmds.undo() self.assertEqual(ball34Obs.notifications, 3) self.assertEqual(ball35Obs.notifications, 0) self.assertEqual(globalObs.notifications, 3) cmds.redo() self.assertEqual(ball34Obs.notifications, 4) self.assertEqual(ball35Obs.notifications, 0) self.assertEqual(globalObs.notifications, 4) # get ready to undo the first modification cmds.undo() self.assertEqual(ball34Obs.notifications, 5) self.assertEqual(ball35Obs.notifications, 0) self.assertEqual(globalObs.notifications, 5) # Undo-ing the modification which created the USD specs is a little # different in USD, but from Ufe we should just still see one notification. cmds.undo() self.assertEqual(ball34Obs.notifications, 6) self.assertEqual(ball35Obs.notifications, 0) self.assertEqual(globalObs.notifications, 6) cmds.redo() self.assertEqual(ball34Obs.notifications, 7) self.assertEqual(ball35Obs.notifications, 0) self.assertEqual(globalObs.notifications, 7) # Make a change to ball35, global and ball35 observers change. ball35Attrs = ufe.Attributes.attributes(ball35) ball35XlateAttr = ball35Attrs.attribute('xformOp:translate') # "xformOp:translate" ufeCmd.execute(ball35XlateAttr.setCmd(ufe.Vector3d(4, 8, 15))) self.assertEqual(ball34Obs.notifications, 7) self.assertEqual(ball35Obs.notifications, 1) self.assertEqual(globalObs.notifications, 8) # Undo, redo cmds.undo() self.assertEqual(ball34Obs.notifications, 7) self.assertEqual(ball35Obs.notifications, 2) self.assertEqual(globalObs.notifications, 9) cmds.redo() self.assertEqual(ball34Obs.notifications, 7) self.assertEqual(ball35Obs.notifications, 3) self.assertEqual(globalObs.notifications, 10) # Test removeObserver. ufe.Attributes.removeObserver(ball34, ball34Obs) self.assertFalse(ufe.Attributes.hasObservers(ball34.path())) self.assertTrue(ufe.Attributes.hasObservers(ball35.path())) self.assertEqual(ufe.Attributes.nbObservers(ball34), 0) self.assertEqual(ufe.Attributes.nbObservers(ball35), 1) self.assertFalse(ufe.Attributes.hasObserver(ball34, ball34Obs)) ufeCmd.execute(ball34XlateAttr.setCmd(ufe.Vector3d(4, 4, 25))) self.assertEqual(ball34Obs.notifications, 7) self.assertEqual(ball35Obs.notifications, 3) self.assertEqual(globalObs.notifications, 11) ufe.Attributes.removeObserver(globalObs) self.assertEqual(ufe.Attributes.nbObservers(), kNbGlobalObs) ufeCmd.execute(ball34XlateAttr.setCmd(ufe.Vector3d(7, 8, 9))) self.assertEqual(ball34Obs.notifications, 7) self.assertEqual(ball35Obs.notifications, 3) self.assertEqual(globalObs.notifications, 11) # Run last to avoid file new disturbing other tests. def testZAttrChangeRedoAfterPrimCreateRedo(self): '''Redo attribute change after redo of prim creation.''' cmds.file(new=True, force=True) # Create a capsule, change one of its attributes. import mayaUsd_createStageWithNewLayer proxyShape = mayaUsd_createStageWithNewLayer.createStageWithNewLayer() proxyShapePath = ufe.PathString.path(proxyShape) proxyShapeItem = ufe.Hierarchy.createItem(proxyShapePath) proxyShapeContextOps = ufe.ContextOps.contextOps(proxyShapeItem) cmd = proxyShapeContextOps.doOpCmd(['Add New Prim', 'Capsule']) ufeCmd.execute(cmd) capsulePath = ufe.PathString.path('%s,/Capsule1' % proxyShape) capsuleItem = ufe.Hierarchy.createItem(capsulePath) # Create the attributes interface for the item. attrs = ufe.Attributes.attributes(capsuleItem) self.assertIsNotNone(attrs) self.assertTrue(attrs.hasAttribute('radius')) radiusAttr = attrs.attribute('radius') oldRadius = radiusAttr.get() ufeCmd.execute(radiusAttr.setCmd(2)) newRadius = radiusAttr.get() self.assertEqual(newRadius, 2) self.assertNotEqual(oldRadius, newRadius) # Undo 2x: undo attr change and prim creation. cmds.undo() cmds.undo() # Redo 2x: prim creation, attr change. cmds.redo() cmds.redo() # Re-create item, as its underlying prim was re-created. capsuleItem = ufe.Hierarchy.createItem(capsulePath) attrs = ufe.Attributes.attributes(capsuleItem) radiusAttr = attrs.attribute('radius') self.assertEqual(radiusAttr.get(), newRadius) def testSingleAttributeBlocking(self): ''' Authoring attribute(s) in weaker layer(s) are not permitted if there exist opinion(s) in stronger layer(s).''' # create new stage cmds.file(new=True, force=True) import mayaUsd_createStageWithNewLayer mayaUsd_createStageWithNewLayer.createStageWithNewLayer() proxyShapes = cmds.ls(type="mayaUsdProxyShapeBase", long=True) proxyShapePath = proxyShapes[0] proxyShapeItem = ufe.Hierarchy.createItem(ufe.PathString.path(proxyShapePath)) proxyShapeContextOps = ufe.ContextOps.contextOps(proxyShapeItem) stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() # create a prim. This creates the primSpec in the root layer. proxyShapeContextOps.doOp(['Add New Prim', 'Capsule']) # create a USD prim capsulePath = ufe.PathString.path('|stage1|stageShape1,/Capsule1') capsuleItem = ufe.Hierarchy.createItem(capsulePath) capsulePrim = mayaUsd.ufe.ufePathToPrim(ufe.PathString.string(capsulePath)) # author a new radius value self.assertTrue(capsulePrim.HasAttribute('radius')) radiusAttrUsd = capsulePrim.GetAttribute('radius') # authoring new attribute edit is expected to be allowed. self.assertTrue(mayaUsdUfe.isAttributeEditAllowed(radiusAttrUsd)) radiusAttrUsd.Set(10) # author a new axis value self.assertTrue(capsulePrim.HasAttribute('axis')) axisAttrUsd = capsulePrim.GetAttribute('axis') # authoring new attribute edit is expected to be allowed. self.assertTrue(mayaUsdUfe.isAttributeEditAllowed(axisAttrUsd)) axisAttrUsd.Set('Y') # create a sub-layer. rootLayer = stage.GetRootLayer() subLayerA = cmds.mayaUsdLayerEditor(rootLayer.identifier, edit=True, addAnonymous="LayerA")[0] # check to see the if the sublayers was added addedLayers = [subLayerA] self.assertEqual(rootLayer.subLayerPaths, addedLayers) # set the edit target to LayerA. cmds.mayaUsdEditTarget(proxyShapePath, edit=True, editTarget=subLayerA) # radiusAttrUsd is not allowed to change since there is an opinion in a stronger layer self.assertFalse(mayaUsdUfe.isAttributeEditAllowed(radiusAttrUsd)) # axisAttrUsd is not allowed to change since there is an opinion in a stronger layer self.assertFalse(mayaUsdUfe.isAttributeEditAllowed(axisAttrUsd)) def testTransformationAttributeBlocking(self): '''Authoring transformation attribute(s) in weaker layer(s) are not permitted if there exist opinion(s) in stronger layer(s).''' # create new stage cmds.file(new=True, force=True) import mayaUsd_createStageWithNewLayer mayaUsd_createStageWithNewLayer.createStageWithNewLayer() proxyShapes = cmds.ls(type="mayaUsdProxyShapeBase", long=True) proxyShapePath = proxyShapes[0] proxyShapeItem = ufe.Hierarchy.createItem(ufe.PathString.path(proxyShapePath)) proxyShapeContextOps = ufe.ContextOps.contextOps(proxyShapeItem) stage = mayaUsd.lib.GetPrim(proxyShapePath).GetStage() # create 3 sub-layers ( LayerA, LayerB, LayerC ) and set the edit target to LayerB. rootLayer = stage.GetRootLayer() subLayerC = cmds.mayaUsdLayerEditor(rootLayer.identifier, edit=True, addAnonymous="SubLayerC")[0] subLayerB = cmds.mayaUsdLayerEditor(rootLayer.identifier, edit=True, addAnonymous="SubLayerB")[0] subLayerA = cmds.mayaUsdLayerEditor(rootLayer.identifier, edit=True, addAnonymous="SubLayerA")[0] # check to see the sublayers added addedLayers = [subLayerA, subLayerB, subLayerC] self.assertEqual(rootLayer.subLayerPaths, addedLayers) # set the edit target to LayerB cmds.mayaUsdEditTarget(proxyShapePath, edit=True, editTarget=subLayerB) # create a prim. This creates the primSpec in the SubLayerB. proxyShapeContextOps.doOp(['Add New Prim', 'Sphere']) spherePath = ufe.PathString.path('|stage1|stageShape1,/Sphere1') sphereItem = ufe.Hierarchy.createItem(spherePath) spherePrim = mayaUsd.ufe.ufePathToPrim(ufe.PathString.string(spherePath)) # create a transform3d sphereT3d = ufe.Transform3d.transform3d(sphereItem) # create a xformable sphereXformable = UsdGeom.Xformable(spherePrim) # writing to "transform op order" is expected to be allowed. self.assertTrue(mayaUsdUfe.isAttributeEditAllowed(sphereXformable.GetXformOpOrderAttr())) # do any transform editing. sphereT3d = ufe.Transform3d.transform3d(sphereItem) sphereT3d.scale(2.5, 2.5, 2.5) sphereT3d.translate(4.0, 2.0, 3.0) # check the "transform op order" stack. self.assertEqual(sphereXformable.GetXformOpOrderAttr().Get(), Vt.TokenArray(('xformOp:translate', 'xformOp:scale'))) # check if translate attribute is editable translateAttr = spherePrim.GetAttribute('xformOp:translate') self.assertIsNotNone(translateAttr) # authoring new transformation edit is expected to be allowed. self.assertTrue(mayaUsdUfe.isAttributeEditAllowed(translateAttr)) sphereT3d.translate(5.0, 6.0, 7.0) self.assertEqual(translateAttr.Get(), Gf.Vec3d(5.0, 6.0, 7.0)) # set the edit target to a weaker layer (LayerC) cmds.mayaUsdEditTarget(proxyShapePath, edit=True, editTarget=subLayerC) # authoring new transformation edit is not allowed. self.assertFalse(mayaUsdUfe.isAttributeEditAllowed(translateAttr)) # set the edit target to a stronger layer (LayerA) cmds.mayaUsdEditTarget(proxyShapePath, edit=True, editTarget=subLayerA) # authoring new transformation edit is allowed. self.assertTrue(mayaUsdUfe.isAttributeEditAllowed(translateAttr)) sphereT3d.rotate(0.0, 90.0, 0.0) # check the "transform op order" stack. self.assertEqual(sphereXformable.GetXformOpOrderAttr().Get(), Vt.TokenArray(('xformOp:translate','xformOp:rotateXYZ', 'xformOp:scale'))) if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/test/lib/ufe/testAttributes.py #!/usr/bin/env python # # Copyright 2019 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import fixturesUtils import mayaUtils import usdUtils from pxr import UsdGeom from maya import standalone import ufe import unittest class AttributesTestCase(unittest.TestCase): '''Verify the Attributes UFE interface, for multiple runtimes. ''' pluginsLoaded = False @classmethod def setUpClass(cls): fixturesUtils.readOnlySetUpClass(__file__, loadPlugin=False) if not cls.pluginsLoaded: cls.pluginsLoaded = mayaUtils.isMayaUsdPluginLoaded() @classmethod def tearDownClass(cls): standalone.uninitialize() def setUp(self): ''' Called initially to set up the maya test environment ''' self.assertTrue(self.pluginsLoaded) # Open top_layer.ma scene in testSamples mayaUtils.openTopLayerScene() def testAttributes(self): '''Engine method to run attributes test.''' # Get a UFE scene item for one of the balls in the scene. ball35Path = ufe.Path([ mayaUtils.createUfePathSegment("|transform1|proxyShape1"), usdUtils.createUfePathSegment("/Room_set/Props/Ball_35")]) ball35Item = ufe.Hierarchy.createItem(ball35Path) # Then create the attributes interface for that item. ball35Attrs = ufe.Attributes.attributes(ball35Item) self.assertIsNotNone(ball35Attrs) # Test that we get the same scene item back. self.assertEqual(ball35Item, ball35Attrs.sceneItem()) # Verify that ball35 contains the visibility attribute. self.assertTrue(ball35Attrs.hasAttribute(UsdGeom.Tokens.visibility)) # Verify the attribute type of 'visibility' which we know is a enum token. self.assertEqual(ball35Attrs.attributeType(UsdGeom.Tokens.visibility), ufe.Attribute.kEnumString) # Get all the attribute names for this item. ball35AttrNames = ball35Attrs.attributeNames # Visibility should be in this list. self.assertIn(UsdGeom.Tokens.visibility, ball35AttrNames) if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/lib/mayaUsd/ufe/UsdUndoableCommand.h // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include <mayaUsd/base/api.h> #include <mayaUsd/undo/UsdUndoBlock.h> #include <mayaUsd/undo/UsdUndoableItem.h> #include <ufe/path.h> namespace MAYAUSD_NS_DEF { namespace ufe { // Templated helper class to factor out common code for undoable commands. // // Implement the execute, undo and redo of the UFE command interfaces, // declaring the UsdUndoBlock during the execution. // // Sub-classes only need to implement the executeUndoBlock() function. // This function does the real work of modifying values, and these changes // will be captured in the UsdUndoableItem via the UsdUndoBlock declared // in execute(). template <typename Cmd> class UsdUndoableCommand : public Cmd { public: UsdUndoableCommand(const Ufe::Path& path) : Cmd(path) { } // Ufe::UndoableCommand overrides. // Declares a UsdUndoBlock and calls executeUndoBlock() void execute() override { UsdUndoBlock undoBlock(&_undoableItem); executeUndoBlock(); } // Calls undo on the undoable item. void undo() override { _undoableItem.undo(); } // Calls redo on the undoable item. void redo() override { _undoableItem.redo(); } protected: // Actual implementation of the execution of the command, // executed "within" a UsdUndoBlock to capture undo data, // to be implemented by the sub-class. virtual void executeUndoBlock() = 0; private: UsdUndoableItem _undoableItem; }; } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/lib/mayaUsd/fileio/primUpdaterRegistry.cpp // // Copyright 2016 Pixar // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "primUpdaterRegistry.h" #include <mayaUsd/base/debugCodes.h> #include <mayaUsd/fileio/registryHelper.h> #include <pxr/base/plug/registry.h> #include <pxr/base/tf/debug.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/base/tf/registryManager.h> #include <pxr/base/tf/staticTokens.h> #include <pxr/base/tf/stl.h> #include <pxr/base/tf/token.h> #include <pxr/pxr.h> #include <pxr/usd/usd/schemaBase.h> #include <map> #include <string> #include <utility> PXR_NAMESPACE_OPEN_SCOPE // clang-format off TF_DEFINE_PRIVATE_TOKENS( _tokens, (UsdMaya) (PrimUpdater) ); // clang-format on typedef std::map<TfToken, UsdMayaPrimUpdaterRegistry::RegisterItem> _Registry; static _Registry _reg; /* static */ void UsdMayaPrimUpdaterRegistry::Register( const TfType& t, UsdMayaPrimUpdater::Supports sup, UsdMayaPrimUpdaterRegistry::UpdaterFactoryFn fn) { TfToken tfTypeName(t.GetTypeName()); TF_DEBUG(PXRUSDMAYA_REGISTRY) .Msg("Registering UsdMayaPrimWriter for TfType type %s.\n", tfTypeName.GetText()); std::pair<_Registry::iterator, bool> insertStatus = _reg.insert(std::make_pair(tfTypeName, std::make_tuple(sup, fn))); if (insertStatus.second) { UsdMaya_RegistryHelper::AddUnloader([tfTypeName]() { _reg.erase(tfTypeName); }); } else { TF_CODING_ERROR("Multiple updaters for TfType %s", tfTypeName.GetText()); } } /* static */ UsdMayaPrimUpdaterRegistry::RegisterItem UsdMayaPrimUpdaterRegistry::Find(const TfToken& usdTypeName) { TfRegistryManager::GetInstance().SubscribeTo<UsdMayaPrimUpdaterRegistry>(); // unfortunately, usdTypeName is diff from the tfTypeName which we use to // register. do the conversion here. TfType tfType = PlugRegistry::FindDerivedTypeByName<UsdSchemaBase>(usdTypeName); std::string typeNameStr = tfType.GetTypeName(); TfToken typeName(typeNameStr); RegisterItem ret; if (TfMapLookup(_reg, typeName, &ret)) { return ret; } static const TfTokenVector SCOPE = { _tokens->UsdMaya, _tokens->PrimUpdater }; UsdMaya_RegistryHelper::FindAndLoadMayaPlug(SCOPE, typeNameStr); // ideally something just registered itself. if not, we at least put it in // the registry in case we encounter it again. if (!TfMapLookup(_reg, typeName, &ret)) { TF_DEBUG(PXRUSDMAYA_REGISTRY) .Msg( "No usdMaya updater plugin for TfType %s. No maya plugin found.\n", typeName.GetText()); _reg[typeName] = {}; } return ret; } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/lib/usd/translators/nurbsCurveWriter.cpp // // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "nurbsCurveWriter.h" #include <mayaUsd/fileio/primWriter.h> #include <mayaUsd/fileio/primWriterRegistry.h> #include <mayaUsd/fileio/utils/adaptor.h> #include <mayaUsd/fileio/utils/writeUtil.h> #include <mayaUsd/fileio/writeJobContext.h> #include <pxr/base/gf/vec2d.h> #include <pxr/base/gf/vec3f.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usd/timeCode.h> #include <pxr/usd/usdGeom/curves.h> #include <pxr/usd/usdGeom/nurbsCurves.h> #include <maya/MDoubleArray.h> #include <maya/MFnDependencyNode.h> #include <maya/MFnNurbsCurve.h> #include <maya/MPointArray.h> #include <numeric> PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_REGISTER_WRITER(nurbsCurve, PxrUsdTranslators_NurbsCurveWriter); PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(nurbsCurve, UsdGeomNurbsCurves); PxrUsdTranslators_NurbsCurveWriter::PxrUsdTranslators_NurbsCurveWriter( const MFnDependencyNode& depNodeFn, const SdfPath& usdPath, UsdMayaWriteJobContext& jobCtx) : UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) { if (!TF_VERIFY(GetDagPath().isValid())) { return; } UsdGeomNurbsCurves primSchema = UsdGeomNurbsCurves::Define(GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( primSchema, "Could not define UsdGeomNurbsCurves at path '%s'\n", GetUsdPath().GetText())) { return; } _usdPrim = primSchema.GetPrim(); if (!TF_VERIFY( _usdPrim, "Could not get UsdPrim for UsdGeomNurbsCurves at path '%s'\n", primSchema.GetPath().GetText())) { return; } } /* virtual */ void PxrUsdTranslators_NurbsCurveWriter::Write(const UsdTimeCode& usdTime) { UsdMayaPrimWriter::Write(usdTime); UsdGeomNurbsCurves primSchema(_usdPrim); writeNurbsCurveAttrs(usdTime, primSchema); } bool PxrUsdTranslators_NurbsCurveWriter::writeNurbsCurveAttrs( const UsdTimeCode& usdTime, UsdGeomNurbsCurves& primSchema) { MStatus status = MS::kSuccess; // Return if usdTime does not match if shape is animated if (usdTime.IsDefault() == _HasAnimCurves()) { // skip shape as the usdTime does not match if shape isAnimated value return true; } MFnDependencyNode fnDepNode(GetDagPath().node(), &status); MString name = fnDepNode.name(); MFnNurbsCurve curveFn(GetDagPath(), &status); if (!status) { TF_RUNTIME_ERROR( "MFnNurbsCurve() failed for curve at DAG path: %s", GetDagPath().fullPathName().asChar()); return false; } // How to repeat the end knots. bool wrap = false; MFnNurbsCurve::Form form(curveFn.form()); if (form == MFnNurbsCurve::kClosed || form == MFnNurbsCurve::kPeriodic) { wrap = true; } // Get curve attrs ====== unsigned int numCurves = 1; // Assuming only 1 curve for now VtIntArray curveOrder(numCurves); VtIntArray curveVertexCounts(numCurves); VtFloatArray curveWidths(numCurves); VtVec2dArray ranges(numCurves); curveOrder[0] = curveFn.degree() + 1; curveVertexCounts[0] = curveFn.numCVs(); if (!TF_VERIFY(curveOrder[0] <= curveVertexCounts[0])) { return false; } curveWidths[0] = 1.0; // TODO: Retrieve from custom attr double mayaKnotDomainMin; double mayaKnotDomainMax; status = curveFn.getKnotDomain(mayaKnotDomainMin, mayaKnotDomainMax); CHECK_MSTATUS_AND_RETURN(status, false); ranges[0][0] = mayaKnotDomainMin; ranges[0][1] = mayaKnotDomainMax; MPointArray mayaCurveCVs; status = curveFn.getCVs(mayaCurveCVs, MSpace::kObject); CHECK_MSTATUS_AND_RETURN(status, false); VtVec3fArray points(mayaCurveCVs.length()); // all CVs batched together for (unsigned int i = 0; i < mayaCurveCVs.length(); i++) { points[i].Set(mayaCurveCVs[i].x, mayaCurveCVs[i].y, mayaCurveCVs[i].z); } MDoubleArray mayaCurveKnots; status = curveFn.getKnots(mayaCurveKnots); CHECK_MSTATUS_AND_RETURN(status, false); VtDoubleArray curveKnots(mayaCurveKnots.length() + 2); // all knots batched together for (unsigned int i = 0; i < mayaCurveKnots.length(); i++) { curveKnots[i + 1] = mayaCurveKnots[i]; } if (wrap) { curveKnots[0] = curveKnots[1] - (curveKnots[curveKnots.size() - 2] - curveKnots[curveKnots.size() - 3]); curveKnots[curveKnots.size() - 1] = curveKnots[curveKnots.size() - 2] + (curveKnots[2] - curveKnots[1]); } else { curveKnots[0] = curveKnots[1]; curveKnots[curveKnots.size() - 1] = curveKnots[curveKnots.size() - 2]; } // Gprim VtVec3fArray extent(2); UsdGeomCurves::ComputeExtent(points, curveWidths, &extent); UsdMayaWriteUtil::SetAttribute( primSchema.CreateExtentAttr(), &extent, usdTime, _GetSparseValueWriter()); // find the number of segments: (vertexCount - order + 1) per curve // varying interpolation is number of segments + number of curves size_t accumulatedVertexCount = std::accumulate(curveVertexCounts.begin(), curveVertexCounts.end(), 0); size_t accumulatedOrder = std::accumulate(curveOrder.begin(), curveOrder.end(), 0); size_t expectedSegmentCount = accumulatedVertexCount - accumulatedOrder + curveVertexCounts.size(); size_t expectedVaryingSize = expectedSegmentCount + curveVertexCounts.size(); if (curveWidths.size() == 1) primSchema.SetWidthsInterpolation(UsdGeomTokens->constant); else if (curveWidths.size() == points.size()) primSchema.SetWidthsInterpolation(UsdGeomTokens->vertex); else if (curveWidths.size() == curveVertexCounts.size()) primSchema.SetWidthsInterpolation(UsdGeomTokens->uniform); else if (curveWidths.size() == expectedVaryingSize) primSchema.SetWidthsInterpolation(UsdGeomTokens->varying); else { TF_WARN( "MFnNurbsCurve has unsupported width size " "for standard interpolation metadata: %s", GetDagPath().fullPathName().asChar()); } // Curve // not animatable UsdMayaWriteUtil::SetAttribute( primSchema.GetOrderAttr(), curveOrder, UsdTimeCode::Default(), _GetSparseValueWriter()); UsdMayaWriteUtil::SetAttribute( primSchema.GetCurveVertexCountsAttr(), &curveVertexCounts, UsdTimeCode::Default(), _GetSparseValueWriter()); UsdMayaWriteUtil::SetAttribute( primSchema.GetWidthsAttr(), &curveWidths, UsdTimeCode::Default(), _GetSparseValueWriter()); UsdMayaWriteUtil::SetAttribute( primSchema.GetKnotsAttr(), &curveKnots, UsdTimeCode::Default(), _GetSparseValueWriter()); // not animatable UsdMayaWriteUtil::SetAttribute( primSchema.GetRangesAttr(), &ranges, UsdTimeCode::Default(), _GetSparseValueWriter()); // not animatable UsdMayaWriteUtil::SetAttribute( primSchema.GetPointsAttr(), &points, usdTime, _GetSparseValueWriter()); // CVs // TODO: Handle periodic and non-periodic cases return true; } /* virtual */ bool PxrUsdTranslators_NurbsCurveWriter::ExportsGprims() const { return true; } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/lib/mayaUsd/fileio/primUpdater.cpp // // Copyright 2018 Pixar // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "primUpdater.h" #include <maya/MFnDagNode.h> #include <maya/MStatus.h> #include <maya/MString.h> PXR_NAMESPACE_OPEN_SCOPE UsdMayaPrimUpdater::UsdMayaPrimUpdater(const MFnDependencyNode& depNodeFn, const SdfPath& usdPath) : _dagPath(UsdMayaUtil::getDagPath(depNodeFn)) , _mayaObject(depNodeFn.object()) , _usdPath(usdPath) , _baseDagToUsdPaths(UsdMayaUtil::getDagPathMap(depNodeFn, usdPath)) { } bool UsdMayaPrimUpdater::Push(UsdMayaPrimUpdaterContext* context) { return false; } bool UsdMayaPrimUpdater::Pull(UsdMayaPrimUpdaterContext* context) { return false; } void UsdMayaPrimUpdater::Clear(UsdMayaPrimUpdaterContext* context) { } const MDagPath& UsdMayaPrimUpdater::GetDagPath() const { return _dagPath; } const MObject& UsdMayaPrimUpdater::GetMayaObject() const { return _mayaObject; } const SdfPath& UsdMayaPrimUpdater::GetUsdPath() const { return _usdPath; } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/test/lib/usd/translators/testUsdImportSessionLayer.py #!/usr/bin/env mayapy # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import unittest from pxr import Usd from maya import cmds from maya import standalone import fixturesUtils class testUsdImportSessionLayer(unittest.TestCase): @classmethod def tearDownClass(cls): standalone.uninitialize() @classmethod def setUpClass(cls): cls.inputPath = fixturesUtils.readOnlySetUpClass(__file__) def testUsdImport(self): """ This tests that executing a usdImport with variants specified causes those variant selections to be made in a session layer and not affect other open stages. """ usdFile = os.path.join(self.inputPath, "UsdImportSessionLayerTest", "Cubes.usda") # Open the asset USD file and make sure the default variant is what we # expect it to be. stage = Usd.Stage.Open(usdFile) self.assertTrue(stage) modelPrimPath = '/Cubes' modelPrim = stage.GetPrimAtPath(modelPrimPath) self.assertTrue(modelPrim) variantSet = modelPrim.GetVariantSet('modelingVariant') variantSelection = variantSet.GetVariantSelection() # This is the default variant. self.assertEqual(variantSelection, 'OneCube') # Now do a usdImport of a different variant in a clean Maya scene. cmds.file(new=True, force=True) variants = [('modelingVariant', 'ThreeCubes')] cmds.usdImport(file=usdFile, primPath=modelPrimPath, variant=variants) expectedMayaCubeNodesSet = set([ '|Cubes|Geom|CubeOne', '|Cubes|Geom|CubeTwo', '|Cubes|Geom|CubeThree']) mayaCubeNodesSet = set(cmds.ls('|Cubes|Geom|Cube*', long=True)) self.assertEqual(expectedMayaCubeNodesSet, mayaCubeNodesSet) # The import should have made the variant selections in a session layer, # so make sure the selection in our open USD stage was not changed. variantSet = modelPrim.GetVariantSet('modelingVariant') variantSelection = variantSet.GetVariantSelection() self.assertEqual(variantSelection, 'OneCube') if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/lib/mayaUsd/utils/utilSerialization.h // // Copyright 2021 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef MAYAUSD_UTILS_UTILSERIALIZATION_H #define MAYAUSD_UTILS_UTILSERIALIZATION_H #include <mayaUsd/base/api.h> #include <mayaUsd/nodes/proxyShapeBase.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/fileFormat.h> #include <pxr/usd/sdf/layer.h> /// General utility functions used when serializing Usd edits during a save operation namespace MAYAUSD_NS_DEF { namespace utils { /*! \brief Helps suggest a folder to export anonymous layers to. Checks in order: 1. File-backed root layer folder. 2. Current Maya scene folder. 3. Current Maya workspace scenes folder. */ MAYAUSD_CORE_PUBLIC std::string suggestedStartFolder(PXR_NS::UsdStageRefPtr stage); /*! \brief Queries Maya for the current workspace "scenes" folder. */ MAYAUSD_CORE_PUBLIC std::string getSceneFolder(); MAYAUSD_CORE_PUBLIC std::string generateUniqueFileName(const std::string& basename); /*! \brief Queries the Maya optionVar that decides what the internal format of a .usd file should be, either "usdc" or "usda". */ MAYAUSD_CORE_PUBLIC std::string usdFormatArgOption(); enum USDUnsavedEditsOption { kSaveToUSDFiles = 1, kSaveToMayaSceneFile, kIgnoreUSDEdits }; /*! \brief Queries the Maya optionVar that decides which saving option Maya should use for Usd edits. */ MAYAUSD_CORE_PUBLIC USDUnsavedEditsOption serializeUsdEditsLocationOption(); /*! \brief Utility function to update the file path attribute on the proxy shape when an anonymous root layer gets exported to disk. */ MAYAUSD_CORE_PUBLIC void setNewProxyPath(const MString& proxyNodeName, const MString& newValue); struct LayerParent { // Every layer that we are saving should have either a parent layer that // we will need to remap to point to the new path, or the stage if it is an // anonymous root layer. SdfLayerRefPtr _layerParent; std::string _proxyPath; }; struct stageLayersToSave { std::vector<std::pair<SdfLayerRefPtr, LayerParent>> _anonLayers; std::vector<SdfLayerRefPtr> _dirtyFileBackedLayers; }; /*! \brief Save an anonymous layer to disk and update the sublayer path array in the parent layer. */ MAYAUSD_CORE_PUBLIC PXR_NS::SdfLayerRefPtr saveAnonymousLayer( PXR_NS::SdfLayerRefPtr anonLayer, LayerParent parent, const std::string& basename, std::string formatArg = ""); /*! \brief Save an anonymous layer to disk and update the sublayer path array in the parent layer. */ MAYAUSD_CORE_PUBLIC PXR_NS::SdfLayerRefPtr saveAnonymousLayer( PXR_NS::SdfLayerRefPtr anonLayer, const std::string& path, LayerParent parent, std::string formatArg = ""); /*! \brief Check the sublayer stack of the stage looking for any anonymnous layers that will need to be saved. */ MAYAUSD_CORE_PUBLIC void getLayersToSaveFromProxy(const std::string& proxyPath, stageLayersToSave& layersInfo); } // namespace utils } // namespace MAYAUSD_NS_DEF #endif // MAYAUSD_UTILS_UTILSERIALIZATION_H <file_sep>/test/lib/mayaUsd/fileio/CMakeLists.txt set(TARGET_NAME MAYAUSD_FILEIO_TEST) set(TEST_SCRIPT_FILES testPrimReader.py testPrimWriter.py testShaderReader.py testShaderWriter.py testExportChaser.py testImportChaser.py ) add_custom_target(${TARGET_NAME} ALL) foreach(script ${TEST_SCRIPT_FILES}) mayaUsd_get_unittest_target(target ${script}) mayaUsd_add_test(${target} PYTHON_MODULE ${target} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} ENV "PYTHONPATH=${CMAKE_CURRENT_SOURCE_DIR}" ) # Add a ctest label to these tests for easy filtering. set_property(TEST ${target} APPEND PROPERTY LABELS fileio) endforeach() add_subdirectory(utils) <file_sep>/lib/mayaUsd/ufe/UsdAttributes.cpp // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "UsdAttributes.h" #include <pxr/base/tf/token.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/attributeSpec.h> #include <pxr/usd/usd/schemaRegistry.h> #include <ufe/ufeAssert.h> // Note: normally we would use this using directive, but here we cannot because // one of our classes is called UsdAttribute which is exactly the same as // the one in USD. // PXR_NAMESPACE_USING_DIRECTIVE #ifdef UFE_ENABLE_ASSERTS static constexpr char kErrorMsgUnknown[] = "Unknown UFE attribute type encountered"; static constexpr char kErrorMsgInvalidAttribute[] = "Invalid USDAttribute!"; #endif namespace MAYAUSD_NS_DEF { namespace ufe { UsdAttributes::UsdAttributes(const UsdSceneItem::Ptr& item) : Ufe::Attributes() , fItem(item) { fPrim = item->prim(); } UsdAttributes::~UsdAttributes() { } /*static*/ UsdAttributes::Ptr UsdAttributes::create(const UsdSceneItem::Ptr& item) { auto attrs = std::make_shared<UsdAttributes>(item); return attrs; } //------------------------------------------------------------------------------ // Ufe::Attributes overrides //------------------------------------------------------------------------------ Ufe::SceneItem::Ptr UsdAttributes::sceneItem() const { return fItem; } Ufe::Attribute::Type UsdAttributes::attributeType(const std::string& name) { PXR_NS::TfToken tok(name); PXR_NS::UsdAttribute usdAttr = fPrim.GetAttribute(tok); return getUfeTypeForAttribute(usdAttr); } Ufe::Attribute::Ptr UsdAttributes::attribute(const std::string& name) { // early return if name is empty. if (name.empty()) { return nullptr; } // If we've already created an attribute for this name, just return it. auto iter = fAttributes.find(name); if (iter != std::end(fAttributes)) return iter->second; // No attribute for the input name was found -> create one. PXR_NS::TfToken tok(name); PXR_NS::UsdAttribute usdAttr = fPrim.GetAttribute(tok); Ufe::Attribute::Type newAttrType = getUfeTypeForAttribute(usdAttr); Ufe::Attribute::Ptr newAttr; if (newAttrType == Ufe::Attribute::kBool) { newAttr = UsdAttributeBool::create(fItem, usdAttr); } else if (newAttrType == Ufe::Attribute::kInt) { newAttr = UsdAttributeInt::create(fItem, usdAttr); } else if (newAttrType == Ufe::Attribute::kFloat) { newAttr = UsdAttributeFloat::create(fItem, usdAttr); } else if (newAttrType == Ufe::Attribute::kDouble) { newAttr = UsdAttributeDouble::create(fItem, usdAttr); } else if (newAttrType == Ufe::Attribute::kString) { newAttr = UsdAttributeString::create(fItem, usdAttr); } else if (newAttrType == Ufe::Attribute::kColorFloat3) { newAttr = UsdAttributeColorFloat3::create(fItem, usdAttr); } else if (newAttrType == Ufe::Attribute::kEnumString) { newAttr = UsdAttributeEnumString::create(fItem, usdAttr); } else if (newAttrType == Ufe::Attribute::kInt3) { newAttr = UsdAttributeInt3::create(fItem, usdAttr); } else if (newAttrType == Ufe::Attribute::kFloat3) { newAttr = UsdAttributeFloat3::create(fItem, usdAttr); } else if (newAttrType == Ufe::Attribute::kDouble3) { newAttr = UsdAttributeDouble3::create(fItem, usdAttr); } else if (newAttrType == Ufe::Attribute::kGeneric) { newAttr = UsdAttributeGeneric::create(fItem, usdAttr); } else { UFE_ASSERT_MSG(false, kErrorMsgUnknown); } fAttributes[name] = newAttr; return newAttr; } std::vector<std::string> UsdAttributes::attributeNames() const { auto primAttrs = fPrim.GetAttributes(); std::vector<std::string> names; names.reserve(primAttrs.size()); for (const auto& attr : primAttrs) { names.push_back(attr.GetName()); } return names; } bool UsdAttributes::hasAttribute(const std::string& name) const { PXR_NS::TfToken tkName(name); return fPrim.HasAttribute(tkName); } Ufe::Attribute::Type UsdAttributes::getUfeTypeForAttribute(const PXR_NS::UsdAttribute& usdAttr) const { // Map the USD type into UFE type. static const std::unordered_map<size_t, Ufe::Attribute::Type> sUsdTypeToUfe { { PXR_NS::SdfValueTypeNames->Bool.GetHash(), Ufe::Attribute::kBool }, // bool { PXR_NS::SdfValueTypeNames->Int.GetHash(), Ufe::Attribute::kInt }, // int32_t { PXR_NS::SdfValueTypeNames->Float.GetHash(), Ufe::Attribute::kFloat }, // float { PXR_NS::SdfValueTypeNames->Double.GetHash(), Ufe::Attribute::kDouble }, // double { PXR_NS::SdfValueTypeNames->String.GetHash(), Ufe::Attribute::kString }, // std::string { PXR_NS::SdfValueTypeNames->Token.GetHash(), Ufe::Attribute::kEnumString }, // TfToken { PXR_NS::SdfValueTypeNames->Int3.GetHash(), Ufe::Attribute::kInt3 }, // GfVec3i { PXR_NS::SdfValueTypeNames->Float3.GetHash(), Ufe::Attribute::kFloat3 }, // GfVec3f { PXR_NS::SdfValueTypeNames->Double3.GetHash(), Ufe::Attribute::kDouble3 }, // GfVec3d { PXR_NS::SdfValueTypeNames->Color3f.GetHash(), Ufe::Attribute::kColorFloat3 }, // GfVec3f { PXR_NS::SdfValueTypeNames->Color3d.GetHash(), Ufe::Attribute::kColorFloat3 }, // GfVec3d }; if (usdAttr.IsValid()) { const PXR_NS::SdfValueTypeName typeName = usdAttr.GetTypeName(); const auto iter = sUsdTypeToUfe.find(typeName.GetHash()); // ** TEMP - for debugging purposes only // std::string cppName = typeName.GetCPPTypeName(); if (iter != sUsdTypeToUfe.end()) { // Special case for TfToken -> Enum. If it doesn't have any allowed // tokens, then use String instead. if (iter->second == Ufe::Attribute::kEnumString) { auto attrDefn = fPrim.GetPrimDefinition().GetSchemaAttributeSpec(usdAttr.GetName()); if (!attrDefn || !attrDefn->HasAllowedTokens()) return Ufe::Attribute::kString; } return iter->second; } // We use the generic type to show a Usd attribute's value and native type. return Ufe::Attribute::kGeneric; } UFE_ASSERT_MSG(false, kErrorMsgInvalidAttribute); return Ufe::Attribute::kInvalid; } } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/lib/mayaUsd/ufe/UsdAttribute.cpp // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "UsdAttribute.h" #include "private/Utils.h" #include <mayaUsd/ufe/StagesSubject.h> #include <mayaUsd/ufe/Utils.h> #include <mayaUsd/undo/UsdUndoBlock.h> #include <mayaUsd/undo/UsdUndoableItem.h> #include <pxr/base/tf/token.h> #include <pxr/base/vt/value.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/attributeSpec.h> #include <pxr/usd/usd/schemaRegistry.h> #include <sstream> #include <unordered_map> #include <unordered_set> // Note: normally we would use this using directive, but here we cannot because // our class is called UsdAttribute which is exactly the same as the one // in USD. // PXR_NAMESPACE_USING_DIRECTIVE static constexpr char kErrorMsgFailedConvertToString[] = "Could not convert the attribute to a string"; static constexpr char kErrorMsgInvalidType[] = "USD attribute does not match created attribute class type"; //------------------------------------------------------------------------------ // Helper functions //------------------------------------------------------------------------------ namespace { template <typename T> bool setUsdAttr(const PXR_NS::UsdAttribute& attr, const T& value) { // USD Attribute Notification doubling problem: // As of 24-Nov-2019, calling Set() on a UsdAttribute causes two "info only" // change notifications to be sent (see StagesSubject::stageChanged). With // the current USD implementation (USD 19.11), UsdAttribute::Set() ends up // in UsdStage::_SetValueImpl(). This function calls in sequence: // - UsdStage::_CreateAttributeSpecForEditing(), which has an SdfChangeBlock // whose expiry causes a notification to be sent. // - SdfLayer::SetField(), which also has an SdfChangeBlock whose // expiry causes a notification to be sent. // These two calls appear to be made on all calls to UsdAttribute::Set(), // not just on the first call. // // Trying to wrap the call to UsdAttribute::Set() inside an additional // SdfChangeBlock fails: no notifications are sent at all. This is most // likely because of the warning given in the SdfChangeBlock documentation: // // https://graphics.pixar.com/usd/docs/api/class_sdf_change_block.html // // which stages that "it is not safe to use [...] [a] downstream API [such // as Usd] while a changeblock is open [...]". // // Therefore, we have implemented an attribute change block notification of // our own in the StagesSubject, which we invoke here, so that only a // single UFE attribute changed notification is generated. if (!attr.IsValid()) return false; MayaUsd::ufe::AttributeChangedNotificationGuard guard; std::string errMsg; bool isSetAttrAllowed = MayaUsd::ufe::isAttributeEditAllowed(attr, &errMsg); if (!isSetAttrAllowed) { throw std::runtime_error(errMsg); } return attr.Set<T>(value); } PXR_NS::UsdTimeCode getCurrentTime(const Ufe::SceneItem::Ptr& item) { // Attributes with time samples will fail when calling Get with default time code. // So we'll always use the current time when calling Get. If there are no time // samples, it will fall-back to the default time code. return MayaUsd::ufe::getTime(item->path()); } std::string getUsdAttributeValueAsString(const PXR_NS::UsdAttribute& attr, const PXR_NS::UsdTimeCode& time) { if (!attr.IsValid() || !attr.HasValue()) return std::string(); PXR_NS::VtValue v; if (attr.Get(&v, time)) { if (v.CanCast<std::string>()) { PXR_NS::VtValue v_str = v.Cast<std::string>(); return v_str.Get<std::string>(); } std::ostringstream os; os << v; return os.str(); } TF_CODING_ERROR(kErrorMsgFailedConvertToString); return std::string(); } template <typename T, typename U> U getUsdAttributeVectorAsUfe(const PXR_NS::UsdAttribute& attr, const PXR_NS::UsdTimeCode& time) { if (!attr.IsValid() || !attr.HasValue()) return U(); PXR_NS::VtValue vt; if (attr.Get(&vt, time) && vt.IsHolding<T>()) { T gfVec = vt.UncheckedGet<T>(); U ret(gfVec[0], gfVec[1], gfVec[2]); return ret; } return U(); } template <typename T, typename U> void setUsdAttributeVectorFromUfe( PXR_NS::UsdAttribute& attr, const U& value, const PXR_NS::UsdTimeCode& time) { T vec; vec.Set(value.x(), value.y(), value.z()); setUsdAttr<T>(attr, vec); } template <typename T, typename A = MayaUsd::ufe::TypedUsdAttribute<T>> class SetUndoableCommand : public Ufe::UndoableCommand { public: SetUndoableCommand(const typename A::Ptr& attr, const T& newValue) : _attr(attr) , _newValue(newValue) { } void execute() override { MayaUsd::UsdUndoBlock undoBlock(&_undoableItem); _attr->set(_newValue); } void undo() override { _undoableItem.undo(); } void redo() override { _undoableItem.redo(); } private: const typename A::Ptr _attr; const T _newValue; MayaUsd::UsdUndoableItem _undoableItem; }; } // end namespace namespace MAYAUSD_NS_DEF { namespace ufe { //------------------------------------------------------------------------------ // UsdAttribute: //------------------------------------------------------------------------------ UsdAttribute::UsdAttribute(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) : fUsdAttr(usdAttr) { fPrim = item->prim(); } UsdAttribute::~UsdAttribute() { } bool UsdAttribute::hasValue() const { return fUsdAttr.HasValue(); } std::string UsdAttribute::name() const { // Should be the same as the name we were created with. return fUsdAttr.GetName().GetString(); } std::string UsdAttribute::documentation() const { return fUsdAttr.GetDocumentation(); } std::string UsdAttribute::string(const Ufe::SceneItem::Ptr& item) const { return getUsdAttributeValueAsString(fUsdAttr, getCurrentTime(item)); } //------------------------------------------------------------------------------ // UsdAttributeGeneric: //------------------------------------------------------------------------------ UsdAttributeGeneric::UsdAttributeGeneric( const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) : Ufe::AttributeGeneric(item) , UsdAttribute(item, usdAttr) { } /*static*/ UsdAttributeGeneric::Ptr UsdAttributeGeneric::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeGeneric>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeGeneric - Ufe::AttributeGeneric overrides //------------------------------------------------------------------------------ std::string UsdAttributeGeneric::nativeType() const { return fUsdAttr.GetTypeName().GetType().GetTypeName(); } //------------------------------------------------------------------------------ // UsdAttributeEnumString: //------------------------------------------------------------------------------ UsdAttributeEnumString::UsdAttributeEnumString( const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) : Ufe::AttributeEnumString(item) , UsdAttribute(item, usdAttr) { } /*static*/ UsdAttributeEnumString::Ptr UsdAttributeEnumString::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeEnumString>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeEnumString - Ufe::AttributeEnumString overrides //------------------------------------------------------------------------------ std::string UsdAttributeEnumString::get() const { PXR_NS::VtValue vt; if (fUsdAttr.Get(&vt, getCurrentTime(sceneItem())) && vt.IsHolding<TfToken>()) { TfToken tok = vt.UncheckedGet<TfToken>(); return tok.GetString(); } return std::string(); } void UsdAttributeEnumString::set(const std::string& value) { PXR_NS::TfToken tok(value); setUsdAttr<PXR_NS::TfToken>(fUsdAttr, tok); } Ufe::UndoableCommand::Ptr UsdAttributeEnumString::setCmd(const std::string& value) { auto self = std::dynamic_pointer_cast<UsdAttributeEnumString>(shared_from_this()); if (!TF_VERIFY(self, kErrorMsgInvalidType)) return nullptr; std::string errMsg; if (!MayaUsd::ufe::isAttributeEditAllowed(fUsdAttr, &errMsg)) { MGlobal::displayError(errMsg.c_str()); return nullptr; } return std::make_shared<SetUndoableCommand<std::string, UsdAttributeEnumString>>(self, value); } Ufe::AttributeEnumString::EnumValues UsdAttributeEnumString::getEnumValues() const { PXR_NS::TfToken tk(name()); auto attrDefn = fPrim.GetPrimDefinition().GetSchemaAttributeSpec(tk); if (attrDefn && attrDefn->HasAllowedTokens()) { auto tokenArray = attrDefn->GetAllowedTokens(); std::vector<PXR_NS::TfToken> tokenVec(tokenArray.begin(), tokenArray.end()); EnumValues tokens = PXR_NS::TfToStringVector(tokenVec); return tokens; } return EnumValues(); } //------------------------------------------------------------------------------ // TypedUsdAttribute<T>: //------------------------------------------------------------------------------ template <typename T> TypedUsdAttribute<T>::TypedUsdAttribute( const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) : Ufe::TypedAttribute<T>(item) , UsdAttribute(item, usdAttr) { } template <typename T> Ufe::UndoableCommand::Ptr TypedUsdAttribute<T>::setCmd(const T& value) { std::string errMsg; if (!MayaUsd::ufe::isAttributeEditAllowed(fUsdAttr, &errMsg)) { MGlobal::displayError(errMsg.c_str()); return nullptr; } // See // https://stackoverflow.com/questions/17853212/using-shared-from-this-in-templated-classes // for explanation of this->shared_from_this() in templated class. return std::make_shared<SetUndoableCommand<T>>(this->shared_from_this(), value); } //------------------------------------------------------------------------------ // TypedUsdAttribute<T> - Ufe::TypedAttribute overrides //------------------------------------------------------------------------------ template <> std::string TypedUsdAttribute<std::string>::get() const { if (!hasValue()) return std::string(); PXR_NS::VtValue vt; if (fUsdAttr.Get(&vt, getCurrentTime(sceneItem()))) { // The USDAttribute can be holding either TfToken or string. if (vt.IsHolding<TfToken>()) { TfToken tok = vt.UncheckedGet<TfToken>(); return tok.GetString(); } else if (vt.IsHolding<std::string>()) { return vt.UncheckedGet<std::string>(); } } return std::string(); } template <> void TypedUsdAttribute<std::string>::set(const std::string& value) { // We need to figure out if the USDAttribute is holding a TfToken or string. const PXR_NS::SdfValueTypeName typeName = fUsdAttr.GetTypeName(); if (typeName.GetHash() == SdfValueTypeNames->String.GetHash()) { setUsdAttr<std::string>(fUsdAttr, value); return; } else if (typeName.GetHash() == SdfValueTypeNames->Token.GetHash()) { PXR_NS::TfToken tok(value); setUsdAttr<PXR_NS::TfToken>(fUsdAttr, tok); return; } // If we get here it means the USDAttribute type wasn't TfToken or string. TF_CODING_ERROR(kErrorMsgInvalidType); } template <> Ufe::Color3f TypedUsdAttribute<Ufe::Color3f>::get() const { return getUsdAttributeVectorAsUfe<GfVec3f, Ufe::Color3f>(fUsdAttr, getCurrentTime(sceneItem())); } // Note: cannot use setUsdAttributeVectorFromUfe since it relies on x/y/z template <> void TypedUsdAttribute<Ufe::Color3f>::set(const Ufe::Color3f& value) { GfVec3f vec; vec.Set(value.r(), value.g(), value.b()); setUsdAttr<GfVec3f>(fUsdAttr, vec); } template <> Ufe::Vector3i TypedUsdAttribute<Ufe::Vector3i>::get() const { return getUsdAttributeVectorAsUfe<GfVec3i, Ufe::Vector3i>( fUsdAttr, getCurrentTime(sceneItem())); } template <> void TypedUsdAttribute<Ufe::Vector3i>::set(const Ufe::Vector3i& value) { setUsdAttributeVectorFromUfe<GfVec3i, Ufe::Vector3i>( fUsdAttr, value, getCurrentTime(sceneItem())); } template <> Ufe::Vector3f TypedUsdAttribute<Ufe::Vector3f>::get() const { return getUsdAttributeVectorAsUfe<GfVec3f, Ufe::Vector3f>( fUsdAttr, getCurrentTime(sceneItem())); } template <> void TypedUsdAttribute<Ufe::Vector3f>::set(const Ufe::Vector3f& value) { setUsdAttributeVectorFromUfe<GfVec3f, Ufe::Vector3f>( fUsdAttr, value, getCurrentTime(sceneItem())); } template <> Ufe::Vector3d TypedUsdAttribute<Ufe::Vector3d>::get() const { return getUsdAttributeVectorAsUfe<GfVec3d, Ufe::Vector3d>( fUsdAttr, getCurrentTime(sceneItem())); } template <> void TypedUsdAttribute<Ufe::Vector3d>::set(const Ufe::Vector3d& value) { setUsdAttributeVectorFromUfe<GfVec3d, Ufe::Vector3d>( fUsdAttr, value, getCurrentTime(sceneItem())); } template <typename T> T TypedUsdAttribute<T>::get() const { if (!hasValue()) return T(); PXR_NS::VtValue vt; if (fUsdAttr.Get(&vt, getCurrentTime(Ufe::Attribute::sceneItem())) && vt.IsHolding<T>()) { return vt.UncheckedGet<T>(); } return T(); } template <typename T> void TypedUsdAttribute<T>::set(const T& value) { setUsdAttr<T>(fUsdAttr, value); } //------------------------------------------------------------------------------ // UsdAttributeBool: //------------------------------------------------------------------------------ /*static*/ UsdAttributeBool::Ptr UsdAttributeBool::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeBool>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeInt: //------------------------------------------------------------------------------ /*static*/ UsdAttributeInt::Ptr UsdAttributeInt::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeInt>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeFloat: //------------------------------------------------------------------------------ /*static*/ UsdAttributeFloat::Ptr UsdAttributeFloat::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeFloat>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeDouble: //------------------------------------------------------------------------------ /*static*/ UsdAttributeDouble::Ptr UsdAttributeDouble::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeDouble>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeString: //------------------------------------------------------------------------------ /*static*/ UsdAttributeString::Ptr UsdAttributeString::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeString>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeColorFloat3: //------------------------------------------------------------------------------ /*static*/ UsdAttributeColorFloat3::Ptr UsdAttributeColorFloat3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeColorFloat3>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeInt3: //------------------------------------------------------------------------------ /*static*/ UsdAttributeInt3::Ptr UsdAttributeInt3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeInt3>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeFloat3: //------------------------------------------------------------------------------ /*static*/ UsdAttributeFloat3::Ptr UsdAttributeFloat3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeFloat3>(item, usdAttr); return attr; } //------------------------------------------------------------------------------ // UsdAttributeDouble3: //------------------------------------------------------------------------------ /*static*/ UsdAttributeDouble3::Ptr UsdAttributeDouble3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { auto attr = std::make_shared<UsdAttributeDouble3>(item, usdAttr); return attr; } #if 0 // Note: if we were to implement generic attribute setting (via string) this // would be the way it could be done. bool UsdAttribute::setValue(const std::string& value) { // Put the input string into a VtValue so we can cast it to the proper type. PXR_NS::VtValue val(value.c_str()); // Attempt to cast the value to what we want. Get a default value for this // attribute's type name. PXR_NS::VtValue defVal = fUsdAttr.GetTypeName().GetDefaultValue(); // Attempt to cast the given string to the default value's type. // If casting fails, attempt to continue with the given value. PXR_NS::VtValue cast = PXR_NS::VtValue::CastToTypeOf(val, defVal); if (!cast.IsEmpty()) cast.Swap(val); return setUsdAttr<PXR_NS::VtValue>(fUsdAttr, val); } #endif } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/lib/mayaUsd/python/wrapExportChaser.cpp // // Copyright 2021 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <mayaUsd/fileio/chaser/exportChaser.h> #include <mayaUsd/fileio/chaser/exportChaserRegistry.h> #include <mayaUsd/fileio/registryHelper.h> #include <pxr/base/tf/makePyConstructor.h> #include <pxr/base/tf/pyContainerConversions.h> #include <pxr/base/tf/pyEnum.h> #include <pxr/base/tf/pyPolymorphic.h> #include <pxr/base/tf/pyPtrHelpers.h> #include <pxr/base/tf/pyResultConversions.h> #include <pxr/base/tf/refPtr.h> #include <boost/python.hpp> #include <boost/python/args.hpp> #include <boost/python/def.hpp> #include <boost/python/wrapper.hpp> PXR_NAMESPACE_USING_DIRECTIVE //---------------------------------------------------------------------------------------------------------------------- /// \brief boost python binding for the UsdMayaExportChaser //---------------------------------------------------------------------------------------------------------------------- class ExportChaserWrapper : public UsdMayaExportChaser , public TfPyPolymorphic<UsdMayaExportChaser> { public: typedef ExportChaserWrapper This; typedef UsdMayaExportChaser base_t; static ExportChaserWrapper* New(uintptr_t createdWrapper) { return (ExportChaserWrapper*)createdWrapper; } virtual ~ExportChaserWrapper() { } bool default_ExportDefault() { return base_t::ExportDefault(); } bool ExportDefault() override { return this->CallVirtual<>("ExportDefault", &This::default_ExportDefault)(); } bool default_ExportFrame(const UsdTimeCode& time) { return base_t::ExportFrame(time); } bool ExportFrame(const UsdTimeCode& time) override { return this->CallVirtual<>("ExportFrame", &This::default_ExportFrame)(time); } bool default_PostExport() { return base_t::PostExport(); } bool PostExport() override { return this->CallVirtual<>("PostExport", &This::default_PostExport)(); } static void Register(boost::python::object cl, const std::string& mayaTypeName) { UsdMayaExportChaserRegistry::GetInstance().RegisterFactory( mayaTypeName, [=](const UsdMayaExportChaserRegistry::FactoryContext& contextArgName) { auto chaser = new ExportChaserWrapper(); TfPyLock pyLock; boost::python::object instance = cl((uintptr_t)chaser); boost::python::incref(instance.ptr()); initialize_wrapper(instance.ptr(), chaser); return chaser; }, true); } }; //---------------------------------------------------------------------------------------------------------------------- void wrapExportChaser() { typedef ExportChaserWrapper* ExportChaserWrapperPtr; boost::python::class_<ExportChaserWrapper, boost::noncopyable>( "ExportChaser", boost::python::no_init) .def("__init__", make_constructor(&ExportChaserWrapper::New)) .def( "ExportDefault", &ExportChaserWrapper::ExportDefault, &ExportChaserWrapper::default_ExportDefault) .def( "ExportFrame", &ExportChaserWrapper::ExportFrame, &ExportChaserWrapper::default_ExportFrame) .def( "PostExport", &ExportChaserWrapper::PostExport, &ExportChaserWrapper::default_PostExport) .def( "Register", &ExportChaserWrapper::Register, (boost::python::arg("class"), boost::python::arg("mayaTypeName"))) .staticmethod("Register"); } <file_sep>/plugin/al/plugin/AL_USDMayaTestPlugin/py/testProxyShape.py #!/usr/bin/env python # # Copyright 2020 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import json import os import tempfile import shutil import unittest import AL import pxr from pxr import Usd, UsdUtils from maya import cmds from maya.api import OpenMaya as om2 import fixturesUtils class TestProxyShapeGetUsdPrimFromMayaPath(unittest.TestCase): """Test cases for static function: AL.usdmaya.ProxyShape.getUsdPrimFromMayaPath""" def __init__(self, *args, **kwargs): super(TestProxyShapeGetUsdPrimFromMayaPath, self).__init__(*args, **kwargs) self._stage = None self._sphere = None self._proxyName = None def setUp(self): """Export some sphere geometry as .usda, and import into a new Maya scene.""" cmds.file(force=True, new=True) cmds.loadPlugin("AL_USDMayaPlugin", quiet=True) self.assertTrue(cmds.pluginInfo("AL_USDMayaPlugin", query=True, loaded=True)) _tmpfile = tempfile.NamedTemporaryFile(delete=True, suffix=".usda") _tmpfile.close() # Ensure sphere geometry exists self._sphere = cmds.polySphere(constructionHistory=False, name="sphere")[0] cmds.select(self._sphere) # Export, new scene, import cmds.file(_tmpfile.name, exportSelected=True, force=True, type="AL usdmaya export") cmds.file(force=True, new=True) self._proxyName = cmds.AL_usdmaya_ProxyShapeImport(file=_tmpfile.name)[0] # Ensure proxy exists self.assertIsNotNone(self._proxyName) # Store stage proxy = AL.usdmaya.ProxyShape.getByName(self._proxyName) self._stage = proxy.getUsdStage() os.remove(_tmpfile.name) def tearDown(self): """Unload plugin, new Maya scene, reset class member variables.""" cmds.file(force=True, new=True) cmds.unloadPlugin("AL_USDMayaPlugin", force=True) self._stage = None self._sphere = None self._proxyName = None def test_getUsdPrimFromMayaPath_success(self): """Find prim from Maya dag path successfully.""" # Select prim, Maya node(s) created, query path cmds.AL_usdmaya_ProxyShapeSelect(proxy=self._proxyName, primPath="/{}".format(self._sphere)) prim = AL.usdmaya.ProxyShape.getUsdPrimFromMayaPath(self._sphere) self.assertTrue(prim.IsValid()) def test_getUsdPrimFromMayaPath_invalidPrim(self): """Dag paths msut exist and be associated with a prim to return a valid prim.""" # Dag path of sphere is unselected, doesn't exist cmds.select(clear=True) prim = AL.usdmaya.ProxyShape.getUsdPrimFromMayaPath(self._sphere) self.assertFalse(prim.IsValid()) # 'foo' dag path doesn't exist in Maya prim = AL.usdmaya.ProxyShape.getUsdPrimFromMayaPath("foo") self.assertFalse(prim.IsValid()) # Query node unassociated with prim cube = cmds.polyCube(constructionHistory=False, name="foo")[0] self.assertTrue(cmds.objExists(cube)) prim = AL.usdmaya.ProxyShape.getUsdPrimFromMayaPath(cube) self.assertFalse(prim.IsValid()) def test_getUsdPrimFromMayaPath_duplicateNames(self): """Test short name queries return an invalid prim if duplicates exist in the Maya scene.""" # Create a transform with the same name as sphere cmds.createNode("transform", name=self._sphere) # Select prim, Maya node(s) created cmds.AL_usdmaya_ProxyShapeSelect(proxy=self._proxyName, primPath="/{}".format(self._sphere)) # Two nodes exist in Maya named "sphere", short name queries return with invalid prim _sphereShortName = self._sphere prim = AL.usdmaya.ProxyShape.getUsdPrimFromMayaPath(_sphereShortName) self.assertFalse(prim.IsValid()) # Query long name? Success! _sphereLongName = cmds.ls(self._sphere, type="AL_usdmaya_Transform")[0] prim = AL.usdmaya.ProxyShape.getUsdPrimFromMayaPath(_sphereLongName) self.assertTrue(prim.IsValid()) class TestProxyShapeGetMayaPathFromUsdPrim(unittest.TestCase): """Test cases for member function: AL.usdmaya.ProxyShape().getMayaPathFromUsdPrim""" class MayaUsdTestData: """Container that holds links to test data.""" poly = None # Short name path to Maya node, and name of prim in Usd stage proxyName = None # AL_usdmaya_ProxyShape Maya node name proxy = None # AL_usdmaya_ProxyShape instance stage = None # Imported Usd stage that hosts prim prim = None # Usd prim in stage def __init__(self, *args, **kwargs): super(TestProxyShapeGetMayaPathFromUsdPrim, self).__init__(*args, **kwargs) self._stageA = self.MayaUsdTestData() self._stageB = self.MayaUsdTestData() def setUp(self): """A few steps take place here: 1. New scene in Maya, ensure plugin is loaded 2. Create a polySphere and polyCube, export these using to separate Usd stages 3. Import both stages together into a new Maya scene """ cmds.file(force=True, new=True) cmds.loadPlugin("AL_USDMayaPlugin", quiet=True) self.assertTrue(cmds.pluginInfo("AL_USDMayaPlugin", query=True, loaded=True)) stageA_file = tempfile.NamedTemporaryFile(delete=True, suffix=".usda") stageB_file = tempfile.NamedTemporaryFile(delete=True, suffix=".usda") stageA_file.close() stageB_file.close() cube = cmds.polyCube(constructionHistory=False, name="cube")[0] sphere = cmds.polySphere(constructionHistory=False, name="cube")[0] cmds.select(cube, replace=True) cmds.file(stageA_file.name, exportSelected=True, force=True, type="AL usdmaya export") cmds.select(sphere, replace=True) cmds.file(stageB_file.name, exportSelected=True, force=True, type="AL usdmaya export") self._stageA.poly = cube self._stageB.poly = sphere cmds.file(force=True, new=True) self._stageA.proxyName = cmds.AL_usdmaya_ProxyShapeImport(file=stageA_file.name)[0] self._stageB.proxyName = cmds.AL_usdmaya_ProxyShapeImport(file=stageB_file.name)[0] self._stageA.proxy = AL.usdmaya.ProxyShape.getByName(self._stageA.proxyName) self._stageB.proxy = AL.usdmaya.ProxyShape.getByName(self._stageB.proxyName) self._stageA.stage = self._stageA.proxy.getUsdStage() self._stageB.stage = self._stageB.proxy.getUsdStage() self._stageA.prim = self._stageA.stage.GetPrimAtPath("/{}".format(self._stageA.poly)) self._stageB.prim = self._stageB.stage.GetPrimAtPath("/{}".format(self._stageB.poly)) os.remove(stageA_file.name) os.remove(stageB_file.name) def tearDown(self): """New Maya scene, unload plugin, reset data.""" cmds.file(force=True, new=True) cmds.unloadPlugin("AL_USDMayaPlugin", force=True) self._stageA = self.MayaUsdTestData() self._stageB = self.MayaUsdTestData() def test_getMayaPathFromUsdPrim_success(self): """Maya scenes can contain multiple proxies. Query each proxy and test they return the correct Maya nodes.""" # These are dynamic prims, so select them to bring into Maya cmds.select(clear=True) cmds.AL_usdmaya_ProxyShapeSelect(self._stageA.proxyName, replace=True, primPath=str(self._stageA.prim.GetPath())) cmds.AL_usdmaya_ProxyShapeSelect(self._stageB.proxyName, append=True, primPath=str(self._stageB.prim.GetPath())) # Created Maya node names will match the originals self.assertTrue(cmds.objExists(self._stageA.poly)) self.assertTrue(cmds.objExists(self._stageB.poly)) # Fetch the Maya node paths that represent each stage's prims resultA = self._stageA.proxy.getMayaPathFromUsdPrim(self._stageA.prim) resultB = self._stageB.proxy.getMayaPathFromUsdPrim(self._stageB.prim) # Expand to long names expectedA = cmds.ls(self._stageA.poly, long=True)[0] expectedB = cmds.ls(self._stageB.poly, long=True)[0] # The paths should match! self.assertEqual(resultA, expectedA) self.assertEqual(resultB, expectedB) def test_getMayaPathFromUsdPrim_failure(self): """Query a proxy with an invalid prim.""" result = self._stageA.proxy.getMayaPathFromUsdPrim(pxr.Usd.Prim()) expected = "" self.assertEqual(result, expected) def test_getMayaPathFromUsdPrim_unselected(self): """Query a proxy with a valid prim who's Maya node has not been translated (unselected).""" result = self._stageA.proxy.getMayaPathFromUsdPrim(self._stageA.prim) expected = "" self.assertEqual(result, expected) def test_getMayaPathFromUsdPrim_primStageMismatch(self): """Query a proxy with a prim from a different Usd stage.""" result = self._stageA.proxy.getMayaPathFromUsdPrim(self._stageB.prim) expected = "" self.assertEqual(result, expected) def test_getMayaPathFromUsdPrim_staticImport(self): """Force import a prim.""" cmds.AL_usdmaya_ProxyShapeImportPrimPathAsMaya(self._stageA.proxyName, primPath=str(self._stageA.prim.GetPath())) result = self._stageA.proxy.getMayaPathFromUsdPrim(self._stageA.prim) expected = cmds.ls(self._stageA.poly, long=True)[0] self.assertEqual(result, expected) @unittest.skip("Not working") def test_getMayaPathFromUsdPrim_reopenImport(self): """Saving and reopening a Maya scene with dynamic translated prims should work.""" # Save _file = tempfile.NamedTemporaryFile(delete=False, suffix=".ma") with _file: cmds.file(rename=_file.name) cmds.file(save=True, force=True) self.assertFalse(cmds.ls(assemblies=True)) _file.close() # Re-open cmds.file(_file.name, open=True, force=True) # Refresh data, stage wrapper is out of date _stageC = self.MayaUsdTestData() _stageC.poly = self._stageA.poly _stageC.proxyName = self._stageA.proxyName _stageC.proxy = AL.usdmaya.ProxyShape.getByName(_stageC.proxyName) _stageC.stage = _stageC.proxy.getUsdStage() _stageC.prim = _stageC.stage.GetPrimAtPath("/{}".format(_stageC.poly)) # Test cmds.AL_usdmaya_ProxyShapeSelect(_stageC.proxyName, replace=True, primPath=str(_stageC.prim.GetPath())) self.assertTrue(cmds.objExists(_stageC.poly)) result = _stageC.proxy.getMayaPathFromUsdPrim(_stageC.prim) expected = cmds.ls(_stageC.poly, long=True)[0] self.assertEqual(result, expected) # Cleanup os.remove(_file.name) @unittest.skip("Not working") def test_getMayaPathFromUsdPrim_reopenStaticImport(self): """Saving and reopening a Maya scene with static translated prims should work.""" cmds.AL_usdmaya_ProxyShapeImportPrimPathAsMaya(self._stageA.proxyName, primPath=str(self._stageA.prim.GetPath())) # Save _file = tempfile.NamedTemporaryFile(delete=False, suffix=".ma") with _file: cmds.file(rename=_file.name) cmds.file(save=True, force=True) _file.close() # Re-open cmds.file(_file.name, open=True, force=True) # Refresh data, stage wrapper is out of date _stageC = self.MayaUsdTestData() _stageC.poly = self._stageA.poly _stageC.proxyName = self._stageA.proxyName _stageC.proxy = AL.usdmaya.ProxyShape.getByName(_stageC.proxyName) _stageC.stage = _stageC.proxy.getUsdStage() _stageC.prim = _stageC.stage.GetPrimAtPath("/{}".format(_stageC.poly)) # Test cmds.AL_usdmaya_ProxyShapeSelect(_stageC.proxyName, replace=True, primPath=str(_stageC.prim.GetPath())) self.assertTrue(cmds.objExists(_stageC.poly)) result = _stageC.proxy.getMayaPathFromUsdPrim(_stageC.prim) expected = cmds.ls(_stageC.poly, long=True)[0] self.assertEqual(result, expected) # Cleanup os.remove(_file.name) class TestProxyShapeAnonymousLayer(unittest.TestCase): workingDir = None fileName = 'foo.ma' SC = pxr.UsdUtils.StageCache.Get() def setUp(self): unittest.TestCase.setUp(self) self.workingDir = tempfile.mkdtemp() cmds.file(new=True, save=False, force=True) cmds.loadPlugin("AL_USDMayaPlugin", quiet=True) self.assertTrue(cmds.pluginInfo("AL_USDMayaPlugin", query=True, loaded=True)) with pxr.Usd.StageCacheContext(self.SC): stage = pxr.Usd.Stage.CreateInMemory() with pxr.Usd.EditContext(stage, pxr.Usd.EditTarget(stage.GetRootLayer())): pxr.UsdGeom.Xform.Define(stage, '/root/GEO/sphere_hrc').AddTranslateOp().Set((0.0, 1.0, 0.0)) pxr.UsdGeom.Sphere.Define(stage, '/root/GEO/sphere_hrc/sphere').GetRadiusAttr().Set(5.0) cmds.AL_usdmaya_ProxyShapeImport( stageId=self.SC.GetId(stage).ToLongInt(), name='anonymousShape' ) cmds.file(rename=self.serialisationPath()) cmds.file(type='mayaAscii') cmds.file(save=True) cmds.file(new=True, save=False, force=True) self.SC.Clear() def tearDown(self): if os.path.isdir(self.workingDir): shutil.rmtree(self.workingDir) self.SC.Clear() unittest.TestCase.tearDown(self) def serialisationPath(self): return os.path.join(self.workingDir, self.fileName) def test_anonymousLayerRoundTrip(self): cmds.file(self.serialisationPath(), open=True, save=False, force=True) proxyShape = AL.usdmaya.ProxyShape.getByName('anonymousShape') self.assertIsNotNone(proxyShape) stage = proxyShape.getUsdStage() self.assertIsInstance(stage, pxr.Usd.Stage) hrc = stage.GetPrimAtPath('/root/GEO/sphere_hrc') self.assertTrue(hrc.IsValid()) self.assertTrue(hrc.IsDefined()) self.assertTrue(hrc.IsA(pxr.UsdGeom.Xform)) hrcXformableApi = pxr.UsdGeom.XformCommonAPI(hrc) t, r, s, p, _ = hrcXformableApi.GetXformVectors(pxr.Usd.TimeCode.Default()) self.assertEqual(tuple(t), (0.0, 1.0, 0.0)) self.assertEqual(tuple(r), (0.0, 0.0, 0.0)) self.assertEqual(tuple(s), (1.0, 1.0, 1.0)) self.assertEqual(tuple(p), (0.0, 0.0, 0.0)) sphere = stage.GetPrimAtPath('/root/GEO/sphere_hrc/sphere') self.assertTrue(sphere.IsValid()) self.assertTrue(sphere.IsDefined()) self.assertTrue(sphere.IsA(pxr.UsdGeom.Sphere)) self.assertEqual(pxr.UsdGeom.Sphere(sphere).GetRadiusAttr().Get(), 5.0) class TestProxyShapeVariantFallbacks(unittest.TestCase): def setUp(self): cmds.file(new=True, force=True) cmds.loadPlugin("AL_USDMayaPlugin", quiet=True) def tearDown(self): pxr.UsdUtils.StageCache.Get().Clear() cmds.file(force=True, new=True) cmds.unloadPlugin("AL_USDMayaPlugin", force=True) def _prepSessionLayer(self, customVariantFallbacks): defaultGlobalVariantFallbacks = pxr.Usd.Stage.GetGlobalVariantFallbacks() pxr.Usd.Stage.SetGlobalVariantFallbacks(customVariantFallbacks) usdFile = '../test_data/variant_fallbacks.usda' stage = pxr.Usd.Stage.Open(usdFile) stageCacheId = pxr.UsdUtils.StageCache.Get().Insert(stage) sessionLayer = stage.GetSessionLayer() sessionLayer.customLayerData = {'variant_fallbacks': json.dumps(customVariantFallbacks)} # restore default pxr.Usd.Stage.SetGlobalVariantFallbacks(defaultGlobalVariantFallbacks) # create the proxy node with stage cache id proxyName = cmds.AL_usdmaya_ProxyShapeImport(stageId=stageCacheId.ToLongInt())[0] proxyShape = AL.usdmaya.ProxyShape.getByName(proxyName) return proxyShape, proxyName def test_fromSessionLayer(self): # this will create a C++ type of: std::vector<VtValue> custom = {'geo': ['sphere']} proxyShape, proxyName = self._prepSessionLayer(custom) # the "sphere" variant prim should be loaded prim = proxyShape.getUsdStage().GetPrimAtPath('/root/GEO/sphere1/sphereShape1') self.assertTrue(prim.IsValid()) # the custom variant fallback should be saved to the attribute savedAttrValue = cmds.getAttr(proxyName + '.variantFallbacks') self.assertEqual(savedAttrValue, json.dumps(custom)) if __name__ == '__main__': fixturesUtils.runTests(globals()) <file_sep>/lib/mayaUsd/render/vp2RenderDelegate/material.cpp // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "material.h" #include "debugCodes.h" #include "pxr/usd/sdr/registry.h" #include "pxr/usd/sdr/shaderNode.h" #include "render_delegate.h" #include "tokens.h" #include <mayaUsd/render/vp2ShaderFragments/shaderFragments.h> #include <mayaUsd/utils/hash.h> #include <pxr/base/gf/matrix4d.h> #include <pxr/base/gf/matrix4f.h> #include <pxr/base/gf/vec2f.h> #include <pxr/base/gf/vec3f.h> #include <pxr/base/gf/vec4f.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/base/tf/getenv.h> #include <pxr/base/tf/pathUtils.h> #include <pxr/imaging/hd/sceneDelegate.h> #ifdef WANT_MATERIALX_BUILD #include <pxr/imaging/hdMtlx/hdMtlx.h> #endif #include <pxr/pxr.h> #include <pxr/usd/ar/packageUtils.h> #include <pxr/usd/sdf/assetPath.h> #include <pxr/usd/sdr/registry.h> #include <pxr/usd/usdHydra/tokens.h> #include <pxr/usdImaging/usdImaging/textureUtils.h> #include <pxr/usdImaging/usdImaging/tokens.h> #include <maya/MFragmentManager.h> #include <maya/MGlobal.h> #include <maya/MProfiler.h> #include <maya/MShaderManager.h> #include <maya/MStatus.h> #include <maya/MString.h> #include <maya/MStringArray.h> #include <maya/MTextureManager.h> #include <maya/MUintArray.h> #include <maya/MViewport2Renderer.h> #ifdef WANT_MATERIALX_BUILD #include <MaterialXCore/Document.h> #include <MaterialXFormat/File.h> #include <MaterialXFormat/Util.h> #include <MaterialXGenGlsl/GlslShaderGenerator.h> #include <MaterialXGenOgsXml/OgsFragment.h> #include <MaterialXGenOgsXml/OgsXmlGenerator.h> #include <MaterialXGenShader/HwShaderGenerator.h> #include <MaterialXGenShader/ShaderStage.h> #include <MaterialXGenShader/Util.h> #include <MaterialXRender/ImageHandler.h> #endif #if PXR_VERSION <= 2008 // Needed for GL_HALF_FLOAT. #include <GL/glew.h> #endif #include <ghc/filesystem.hpp> #include <tbb/parallel_for.h> #include <iostream> #include <sstream> #include <string> #if PXR_VERSION >= 2102 #include <pxr/imaging/hdSt/udimTextureObject.h> #else #include <pxr/imaging/glf/udimTexture.h> #endif #if PXR_VERSION >= 2102 #include <pxr/imaging/hio/image.h> #else #include <pxr/imaging/glf/image.h> #endif #ifdef WANT_MATERIALX_BUILD namespace mx = MaterialX; #endif PXR_NAMESPACE_OPEN_SCOPE namespace { // clang-format off TF_DEFINE_PRIVATE_TOKENS( _tokens, (file) (opacity) (useSpecularWorkflow) (st) (varname) (result) (cardsUv) (sourceColorSpace) (sRGB) (raw) (glslfx) (fallback) (input) (output) (diffuseColor) (rgb) (r) (g) (b) (a) (xyz) (x) (y) (z) (w) (Float4ToFloatX) (Float4ToFloatY) (Float4ToFloatZ) (Float4ToFloatW) (Float4ToFloat3) (UsdDrawModeCards) (FallbackShader) (mayaIsBackFacing) (isBackfacing) ((DrawMode, "drawMode.glslfx")) (UsdPrimvarReader_color) (UsdPrimvarReader_vector) ); // clang-format on #ifdef WANT_MATERIALX_BUILD // clang-format off TF_DEFINE_PRIVATE_TOKENS( _mtlxTokens, (USD_Mtlx_VP2_Material) (NG_Maya) (image) (tiledimage) (i_geomprop_) (geomprop) (uaddressmode) (vaddressmode) (filtertype) (channels) // Texcoord reader identifiers: (index) (UV0) (geompropvalue) (ST_reader) (vector2) ); const std::set<std::string> _mtlxTopoNodeSet = { // Topo affecting nodes due to object/model/world space parameter "position", "normal", "tangent", "bitangent", // Topo affecting nodes due to channel index. We remap to geomprop in _AddMissingTexcoordReaders "texcoord", // Color at vertices also affect topo, but we have not locked a naming scheme to go from index // based to name based as we did for UV sets. We will mark them as topo-affecting, but there is // nothing we can do to link them correctly to a primvar without specifying a naming scheme. "geomcolor", // Geompropvalue are the best way to reference a primvar by name. The primvar name is // topo-affecting. Note that boolean and string are not supported by the GLSL codegen. "geompropvalue", // Swizzles are inlined into the codegen and affect topology. "swizzle", // Conversion nodes: "convert" }; // clang-format on struct _MaterialXData { _MaterialXData() { _mtlxLibrary = mx::createDocument(); // In the final product, the libraries will be intalled with the plugin and // will be found in a location that is relative to the plugin load path. We // are not ready for the full installer yet, so use the install paths of the // MaterialX used to build the module just like Pixar does in USD. // // Also, since users are able to provide plug-in libraries, we need a fully // extendable mechanism so they can declare where to search for these. // // The MaterialX_DIR location is most likely the cmake folder for a regular // build of MaterialX: mx::FilePath materialXPath(MaterialX_DIR); materialXPath = materialXPath.getParentPath() / mx::FilePath("libraries"); _mtlxSearchPath.append(materialXPath); const std::unordered_set<std::string> uniqueLibraryNames { "targets", "adsklib", "stdlib", "pbrlib", "bxdf", "stdlib/genglsl", "pbrlib/genglsl", "lights", "lights/genglsl" }; mx::loadLibraries( mx::FilePathVec(uniqueLibraryNames.begin(), uniqueLibraryNames.end()), _mtlxSearchPath, _mtlxLibrary); } MaterialX::FileSearchPath _mtlxSearchPath; //!< MaterialX library search path MaterialX::DocumentPtr _mtlxLibrary; //!< MaterialX library }; _MaterialXData& _GetMaterialXData() { static std::unique_ptr<_MaterialXData> materialXData; static std::once_flag once; std::call_once(once, []() { materialXData.reset(new _MaterialXData()); }); return *materialXData; } //! Return true if that node parameter has topological impact on the generated code. // // Swizzle and geompropvalue nodes are known to have an attribute that affects // shader topology. The "channels" and "geomprop" attributes will have effects at the codegen level, // not at runtime. Yes, this is forbidden internal knowledge of the MaterialX shader generator and // we might get other nodes like this one in a future update. // // The index input of the texcoord and geomcolor nodes affect which stream to read and is topo // affecting. // // Any geometric input that can specify model/object/world space is also topo affecting. // // Things to look out for are parameters of type "string" and parameters with the "uniform" // metadata. These need to be reviewed against the code used in their registered // implementations (see registerImplementation calls in the GlslShaderGenerator CTOR). Sadly // we can not make that a rule because the filename of an image node is both a "string" and // has the "uniform" metadata, yet is not affecting topology. bool _IsTopologicalNode(const HdMaterialNode2& inNode) { mx::NodeDefPtr nodeDef = _GetMaterialXData()._mtlxLibrary->getNodeDef(inNode.nodeTypeId.GetString()); if (nodeDef) { return _mtlxTopoNodeSet.find(nodeDef->getNodeString()) != _mtlxTopoNodeSet.cend(); } return false; } bool _IsMaterialX(const HdMaterialNode& node) { SdrRegistry& shaderReg = SdrRegistry::GetInstance(); NdrNodeConstPtr ndrNode = shaderReg.GetNodeByIdentifier(node.identifier); return ndrNode && ndrNode->GetSourceType() == HdVP2Tokens->mtlx; } //! Helper function to generate a topo hash that can be used to detect if two networks share the // same topology. size_t _GenerateNetwork2TopoHash(const HdMaterialNetwork2& materialNetwork) { // The HdMaterialNetwork2 structure is stable. Everything is alphabetically sorted. size_t topoHash = 0; for (const auto& c : materialNetwork.terminals) { MayaUsd::hash_combine(topoHash, hash_value(c.first)); MayaUsd::hash_combine(topoHash, hash_value(c.second.upstreamNode)); MayaUsd::hash_combine(topoHash, hash_value(c.second.upstreamOutputName)); } for (const auto& nodePair : materialNetwork.nodes) { MayaUsd::hash_combine(topoHash, hash_value(nodePair.first)); const auto& node = nodePair.second; MayaUsd::hash_combine(topoHash, hash_value(node.nodeTypeId)); if (_IsTopologicalNode(node)) { // We need to capture values that affect topology: for (auto const& p : node.parameters) { MayaUsd::hash_combine(topoHash, hash_value(p.first)); MayaUsd::hash_combine(topoHash, hash_value(p.second)); } } for (auto const& i : node.inputConnections) { MayaUsd::hash_combine(topoHash, hash_value(i.first)); for (auto const& c : i.second) { MayaUsd::hash_combine(topoHash, hash_value(c.upstreamNode)); MayaUsd::hash_combine(topoHash, hash_value(c.upstreamOutputName)); } } } return topoHash; } //! Helper function to generate a XML string about nodes, relationships and primvars in the //! specified material network. std::string _GenerateXMLString(const HdMaterialNetwork2& materialNetwork) { std::ostringstream result; if (ARCH_LIKELY(!materialNetwork.nodes.empty())) { result << "<terminals>\n"; for (const auto& c : materialNetwork.terminals) { result << " <terminal name=\"" << c.first << "\" dest=\"" << c.second.upstreamNode << "\"/>\n"; } result << "</terminals>\n"; result << "<nodes>\n"; for (const auto& nodePair : materialNetwork.nodes) { const auto& node = nodePair.second; const bool hasChildren = !(node.parameters.empty() && node.inputConnections.empty()); result << " <node path=\"" << nodePair.first << "\" id=\"" << node.nodeTypeId << "\"" << (hasChildren ? ">\n" : "/>\n"); if (!node.parameters.empty()) { result << " <parameters>\n"; for (auto const& p : node.parameters) { result << " <param name=\"" << p.first << "\" value=\"" << p.second << "\"/>\n"; } result << " </parameters>\n"; } if (!node.inputConnections.empty()) { result << " <inputs>\n"; for (auto const& i : node.inputConnections) { if (i.second.size() == 1) { result << " <input name=\"" << i.first << "\" dest=\"" << i.second.back().upstreamNode << "." << i.second.back().upstreamOutputName << "\"/>\n"; } else { // Extremely rare case seen only with array connections. result << " <input name=\"" << i.first << "\">\n"; result << " <connections>\n"; for (auto const& c : i.second) { result << " <cnx dest=\"" << c.upstreamNode << "." << c.upstreamOutputName << "\"/>\n"; } result << " </connections>\n"; } } result << " </inputs>\n"; } if (hasChildren) { result << " </node>\n"; } } result << "</nodes>\n"; // We do not add primvars. They are found later while traversing the actual effect instance. } return result.str(); } // MaterialX FA nodes will "upgrade" the in2 uniform to whatever the vector type it needs for its // arithmetic operation. So we need to "upgrade" the value we want to set as well. // // One example: ND_multiply_vector3FA(vector3 in1, float in2) will generate a float3 in2 uniform. MStatus _SetFAParameter( MHWRender::MShaderInstance* surfaceShader, const HdMaterialNode& node, const MString& paramName, float val) { auto _endsWith = [](const std::string& s, const std::string& suffix) { return s.size() >= suffix.size() && s.compare(s.size() - suffix.size(), std::string::npos, suffix) == 0; }; if (_IsMaterialX(node) && _endsWith(paramName.asChar(), "_in2") && _endsWith(node.identifier.GetString(), "FA")) { // Try as vector float vec[4] { val, val, val, val }; return surfaceShader->setParameter(paramName, &vec[0]); } return MS::kFailure; } // MaterialX has a lot of node definitions that will auto-connect to a zero-index texture coordinate // system. To make these graphs compatible, we will redirect any unconnected input that uses such an // auto-connection scheme to instead read a texcoord geomprop called "st" which is the canonical // name for UV at index zero. void _AddMissingTexcoordReaders(mx::DocumentPtr& mtlxDoc) { // We expect only one node graph, but fixing them all is not an issue: for (mx::NodeGraphPtr nodeGraph : mtlxDoc->getNodeGraphs()) { // This will hold the emergency "ST" reader if one was necessary mx::NodePtr stReader; // Store nodes to delete when loop iteration is complete std::vector<std::string> nodesToDelete; for (mx::NodePtr node : nodeGraph->getNodes()) { // Check the inputs of the node for UV0 default geom properties mx::NodeDefPtr nodeDef = node->getNodeDef(); for (mx::InputPtr input : nodeDef->getInputs()) { if (input->hasDefaultGeomPropString() && input->getDefaultGeomPropString() == _mtlxTokens->UV0.GetString()) { // See if the corresponding input is connected on the node: if (node->getConnectedNodeName(input->getName()).empty()) { // Create emergency ST reader if necessary if (!stReader) { stReader = nodeGraph->addNode( _mtlxTokens->geompropvalue.GetString(), _mtlxTokens->ST_reader.GetString(), _mtlxTokens->vector2.GetString()); mx::ValueElementPtr prpInput = stReader->addInputFromNodeDef(_mtlxTokens->geomprop.GetString()); prpInput->setValueString(_tokens->st.GetString()); } node->addInputFromNodeDef(input->getName()); node->setConnectedNodeName(input->getName(), stReader->getName()); } } } // Check if it is an explicit texcoord reader: if (nodeDef->getCategory() == "texcoord") { // Switch it with a geompropvalue of the same name: std::string nodeName = node->getName(); std::string oldName = nodeName + "_toDelete"; node->setName(oldName); nodesToDelete.push_back(oldName); // Find out if there is an explicit stream index: int streamIndex = 0; mx::InputPtr indexInput = node->getInput(_mtlxTokens->index.GetString()); if (indexInput && indexInput->hasValue()) { mx::ValuePtr indexValue = indexInput->getValue(); if (indexValue->isA<int>()) { streamIndex = indexValue->asA<int>(); } } // Add replacement geompropvalue node: mx::NodePtr doppelNode = nodeGraph->addNode( _mtlxTokens->geompropvalue.GetString(), nodeName, nodeDef->getOutput("out")->getType()); mx::ValueElementPtr prpInput = doppelNode->addInputFromNodeDef(_mtlxTokens->geomprop.GetString()); MString primvar = _tokens->st.GetText(); if (streamIndex) { // If reading at index > 0 we add the index to the primvar name: primvar += streamIndex; } prpInput->setValueString(primvar.asChar()); } } // Delete all obsolete texcoord reader nodes. for (const std::string& deadNode : nodesToDelete) { nodeGraph->removeNode(deadNode); } } } #endif // WANT_MATERIALX_BUILD bool _IsUsdDrawModeId(const TfToken& id) { return id == _tokens->DrawMode || id == _tokens->UsdDrawModeCards; } bool _IsUsdDrawModeNode(const HdMaterialNode& node) { return _IsUsdDrawModeId(node.identifier); } //! Helper utility function to test whether a node is a UsdShade primvar reader. bool _IsUsdPrimvarReader(const HdMaterialNode& node) { const TfToken& id = node.identifier; return ( id == UsdImagingTokens->UsdPrimvarReader_float || id == UsdImagingTokens->UsdPrimvarReader_float2 || id == UsdImagingTokens->UsdPrimvarReader_float3 || id == UsdImagingTokens->UsdPrimvarReader_float4 || id == _tokens->UsdPrimvarReader_vector || id == UsdImagingTokens->UsdPrimvarReader_int); } bool _IsUsdFloat2PrimvarReader(const HdMaterialNode& node) { return (node.identifier == UsdImagingTokens->UsdPrimvarReader_float2); } //! Helper utility function to test whether a node is a UsdShade UV texture. bool _IsUsdUVTexture(const HdMaterialNode& node) { if (node.identifier.GetString().rfind(UsdImagingTokens->UsdUVTexture.GetString(), 0) == 0) { return true; } #ifdef WANT_MATERIALX_BUILD if (_IsMaterialX(node)) { mx::NodeDefPtr nodeDef = _GetMaterialXData()._mtlxLibrary->getNodeDef(node.identifier.GetString()); if (nodeDef && (nodeDef->getNodeString() == _mtlxTokens->image.GetString() || nodeDef->getNodeString() == _mtlxTokens->tiledimage.GetString())) { return true; } } #endif return false; } //! Helper function to generate a XML string about nodes, relationships and primvars in the //! specified material network. std::string _GenerateXMLString(const HdMaterialNetwork& materialNetwork, bool includeParams = true) { std::string result; if (ARCH_LIKELY(!materialNetwork.nodes.empty())) { // Reserve enough memory to avoid memory reallocation. result.reserve(1024); result += "<nodes>\n"; if (includeParams) { for (const HdMaterialNode& node : materialNetwork.nodes) { result += " <node path=\""; result += node.path.GetString(); result += "\" id=\""; result += node.identifier; result += "\">\n"; result += " <params>\n"; for (auto const& parameter : node.parameters) { result += " <param name=\""; result += parameter.first; result += "\" value=\""; result += TfStringify(parameter.second); result += "\"/>\n"; } result += " </params>\n"; result += " </node>\n"; } } else { for (const HdMaterialNode& node : materialNetwork.nodes) { result += " <node path=\""; result += node.path.GetString(); result += "\" id=\""; result += node.identifier; result += "\"/>\n"; } } result += "</nodes>\n"; if (!materialNetwork.relationships.empty()) { result += "<relationships>\n"; for (const HdMaterialRelationship& rel : materialNetwork.relationships) { result += " <rel from=\""; result += rel.inputId.GetString(); result += "."; result += rel.inputName; result += "\" to=\""; result += rel.outputId.GetString(); result += "."; result += rel.outputName; result += "\"/>\n"; } result += "</relationships>\n"; } if (!materialNetwork.primvars.empty()) { result += "<primvars>\n"; for (TfToken const& primvar : materialNetwork.primvars) { result += " <primvar name=\""; result += primvar; result += "\"/>\n"; } result += "</primvars>\n"; } } return result; } //! Return true if the surface shader has its opacity attribute connected to a node which isn't //! a USD primvar reader. bool _IsTransparent(const HdMaterialNetwork& network) { const HdMaterialNode& surfaceShader = network.nodes.back(); for (const HdMaterialRelationship& rel : network.relationships) { if (rel.outputName == _tokens->opacity && rel.outputId == surfaceShader.path) { for (const HdMaterialNode& node : network.nodes) { if (node.path == rel.inputId) { return !_IsUsdPrimvarReader(node); } } } } return false; } //! Helper utility function to convert Hydra texture addressing token to VP2 enum. MHWRender::MSamplerState::TextureAddress _ConvertToTextureSamplerAddressEnum(const TfToken& token) { MHWRender::MSamplerState::TextureAddress address; if (token == UsdHydraTokens->clamp) { address = MHWRender::MSamplerState::kTexClamp; } else if (token == UsdHydraTokens->mirror) { address = MHWRender::MSamplerState::kTexMirror; } else if (token == UsdHydraTokens->black) { address = MHWRender::MSamplerState::kTexBorder; } else { address = MHWRender::MSamplerState::kTexWrap; } return address; } //! Get sampler state description as required by the material node. MHWRender::MSamplerStateDesc _GetSamplerStateDesc(const HdMaterialNode& node) { TF_VERIFY(_IsUsdUVTexture(node)); MHWRender::MSamplerStateDesc desc; desc.filter = MHWRender::MSamplerState::kMinMagMipLinear; #ifdef WANT_MATERIALX_BUILD const bool isMaterialXNode = _IsMaterialX(node); auto it = node.parameters.find(isMaterialXNode ? _mtlxTokens->uaddressmode : UsdHydraTokens->wrapS); #else auto it = node.parameters.find(UsdHydraTokens->wrapS); #endif if (it != node.parameters.end()) { const VtValue& value = it->second; if (value.IsHolding<TfToken>()) { const TfToken& token = value.UncheckedGet<TfToken>(); desc.addressU = _ConvertToTextureSamplerAddressEnum(token); } #ifdef WANT_MATERIALX_BUILD if (value.IsHolding<std::string>()) { TfToken token(value.UncheckedGet<std::string>().c_str()); desc.addressU = _ConvertToTextureSamplerAddressEnum(token); } #endif } #ifdef WANT_MATERIALX_BUILD it = node.parameters.find(isMaterialXNode ? _mtlxTokens->vaddressmode : UsdHydraTokens->wrapT); #else it = node.parameters.find(UsdHydraTokens->wrapT); #endif if (it != node.parameters.end()) { const VtValue& value = it->second; if (value.IsHolding<TfToken>()) { const TfToken& token = value.UncheckedGet<TfToken>(); desc.addressV = _ConvertToTextureSamplerAddressEnum(token); } #ifdef WANT_MATERIALX_BUILD if (value.IsHolding<std::string>()) { TfToken token(value.UncheckedGet<std::string>().c_str()); desc.addressV = _ConvertToTextureSamplerAddressEnum(token); } #endif } it = node.parameters.find(_tokens->fallback); if (it != node.parameters.end()) { const VtValue& value = it->second; if (value.IsHolding<GfVec4f>()) { const GfVec4f& fallbackValue = value.UncheckedGet<GfVec4f>(); float const* value = fallbackValue.data(); std::copy(value, value + 4, desc.borderColor); } } return desc; } MHWRender::MTexture* _LoadUdimTexture(const std::string& path, bool& isColorSpaceSRGB, MFloatArray& uvScaleOffset) { /* For this method to work path needs to be an absolute file path, not an asset path. That means that this function depends on the changes in 4e426565 to materialAdapther.cpp to work. As of my writing this 4e426565 is not in the USD that MayaUSD normally builds against so this code will fail, because UsdImaging_GetUdimTiles won't file the tiles because we don't know where on disk to look for them. https://github.com/PixarAnimationStudios/USD/commit/4e42656543f4e3a313ce31a81c27477d4dcb64b9 */ // test for a UDIM texture #if PXR_VERSION >= 2102 if (!HdStIsSupportedUdimTexture(path)) return nullptr; #else if (!GlfIsSupportedUdimTexture(path)) return nullptr; #endif /* Maya's tiled texture support is implemented quite differently from Usd's UDIM support. In Maya the texture tiles get combined into a single big texture, downscaling each tile if necessary, and filling in empty regions of a non-square tile with the undefined color. In USD the UDIM textures are stored in a texture array that the shader uses to draw. */ MHWRender::MRenderer* const renderer = MHWRender::MRenderer::theRenderer(); MHWRender::MTextureManager* const textureMgr = renderer ? renderer->getTextureManager() : nullptr; if (!TF_VERIFY(textureMgr)) { return nullptr; } // HdSt sets the tile limit to the max number of textures in an array of 2d textures. OpenGL // says the minimum number of layers in 2048 so I'll use that. int tileLimit = 2048; std::vector<std::tuple<int, TfToken>> tiles = UsdImaging_GetUdimTiles(path, tileLimit); if (tiles.size() == 0) { TF_WARN("Unable to find UDIM tiles for %s", path.c_str()); return nullptr; } // I don't think there is a downside to setting a very high limit. // Maya will clamp the texture size to the VP2 texture clamp resolution and the hardware's // max texture size. And Maya doesn't make the tiled texture unnecessarily large. When I // try loading two 1k textures I end up with a tiled texture that is 2k x 1k. unsigned int maxWidth = 0; unsigned int maxHeight = 0; renderer->GPUmaximumOutputTargetSize(maxWidth, maxHeight); // Open the first image and get it's resolution. Assuming that all the tiles have the same // resolution, warn the user if Maya's tiled texture implementation is going to result in // a loss of texture data. { #if PXR_VERSION >= 2102 HioImageSharedPtr image = HioImage::OpenForReading(std::get<1>(tiles[0]).GetString()); #else GlfImageSharedPtr image = GlfImage::OpenForReading(std::get<1>(tiles[0]).GetString()); #endif if (!TF_VERIFY(image)) { return nullptr; } isColorSpaceSRGB = image->IsColorSpaceSRGB(); unsigned int tileWidth = image->GetWidth(); unsigned int tileHeight = image->GetHeight(); int maxTileId = std::get<0>(tiles.back()); int maxU = maxTileId % 10; int maxV = (maxTileId - maxU) / 10; if ((tileWidth * maxU > maxWidth) || (tileHeight * maxV > maxHeight)) TF_WARN( "UDIM texture %s creates a tiled texture larger than the maximum texture size. Some" "resolution will be lost.", path.c_str()); } MString textureName( path.c_str()); // used for caching, using the string with <UDIM> in it is fine MStringArray tilePaths; MFloatArray tilePositions; for (auto& tile : tiles) { tilePaths.append(MString(std::get<1>(tile).GetText())); #if PXR_VERSION >= 2102 HioImageSharedPtr image = HioImage::OpenForReading(std::get<1>(tile).GetString()); #else GlfImageSharedPtr image = GlfImage::OpenForReading(std::get<1>(tile).GetString()); #endif if (!TF_VERIFY(image)) { return nullptr; } if (isColorSpaceSRGB != image->IsColorSpaceSRGB()) { TF_WARN( "UDIM texture %s color space doesn't match %s color space", std::get<1>(tile).GetText(), std::get<1>(tiles[0]).GetText()); } // The image labeled 1001 will have id 0, 1002 will have id 1, 1011 will have id 10. // image 1001 starts with UV (0.0f, 0.0f), 1002 is (1.0f, 0.0f) and 1011 is (0.0f, 1.0f) int tileId = std::get<0>(tile); float u = (float)(tileId % 10); float v = (float)((tileId - u) / 10); tilePositions.append(u); tilePositions.append(v); } MColor undefinedColor(0.0f, 1.0f, 0.0f, 1.0f); MStringArray failedTilePaths; MHWRender::MTexture* texture = textureMgr->acquireTiledTexture( textureName, tilePaths, tilePositions, undefinedColor, maxWidth, maxHeight, failedTilePaths, uvScaleOffset); for (unsigned int i = 0; i < failedTilePaths.length(); i++) { TF_WARN("Failed to load <UDIM> texture tile %s", failedTilePaths[i].asChar()); } return texture; } //! Load texture from the specified path MHWRender::MTexture* _LoadTexture( const std::string& path, bool& isColorSpaceSRGB, MFloatArray& uvScaleOffset, const HdMaterialNode& node) { MProfilingScope profilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L2, "LoadTexture", path.c_str()); // If it is a UDIM texture we need to modify the path before calling OpenForReading #if PXR_VERSION >= 2102 if (HdStIsSupportedUdimTexture(path)) return _LoadUdimTexture(path, isColorSpaceSRGB, uvScaleOffset); #else if (GlfIsSupportedUdimTexture(path)) return _LoadUdimTexture(path, isColorSpaceSRGB, uvScaleOffset); #endif MHWRender::MRenderer* const renderer = MHWRender::MRenderer::theRenderer(); MHWRender::MTextureManager* const textureMgr = renderer ? renderer->getTextureManager() : nullptr; if (!TF_VERIFY(textureMgr)) { return nullptr; } #if PXR_VERSION >= 2102 HioImageSharedPtr image = HioImage::OpenForReading(path); #else GlfImageSharedPtr image = GlfImage::OpenForReading(path); #endif if (!TF_VERIFY(image, "Unable to create an image from %s", path.c_str())) { // Create a 1x1 texture of the fallback color, if it was specified: auto it = node.parameters.find(_tokens->fallback); if (it == node.parameters.end()) { return nullptr; } const VtValue& value = it->second; if (!value.IsHolding<GfVec4f>()) { return nullptr; } MHWRender::MTextureDescription desc; desc.setToDefault2DTexture(); desc.fWidth = 1; desc.fHeight = 1; desc.fFormat = MHWRender::kR8G8B8A8_UNORM; desc.fBytesPerRow = 4; desc.fBytesPerSlice = desc.fBytesPerRow; const GfVec4f& fallbackValue = value.UncheckedGet<GfVec4f>(); std::vector<unsigned char> texels(4); for (size_t i = 0; i < 4; ++i) { float texelValue = std::max(std::min(fallbackValue[i], 1.0f), 0.0f); texels[i] = static_cast<unsigned char>(texelValue * 255.0); } isColorSpaceSRGB = false; return textureMgr->acquireTexture(path.c_str(), desc, texels.data()); } // This image is used for loading pixel data from usdz only and should // not trigger any OpenGL call. VP2RenderDelegate will transfer the // texels to GPU memory with VP2 API which is 3D API agnostic. #if PXR_VERSION >= 2102 HioImage::StorageSpec spec; #else GlfImage::StorageSpec spec; #endif spec.width = image->GetWidth(); spec.height = image->GetHeight(); spec.depth = 1; #if PXR_VERSION >= 2102 spec.format = image->GetFormat(); #elif PXR_VERSION > 2008 spec.hioFormat = image->GetHioFormat(); #else spec.format = image->GetFormat(); spec.type = image->GetType(); #endif spec.flipped = false; const int bpp = image->GetBytesPerPixel(); const int bytesPerRow = spec.width * bpp; const int bytesPerSlice = bytesPerRow * spec.height; std::vector<unsigned char> storage(bytesPerSlice); spec.data = storage.data(); if (!image->Read(spec)) { return nullptr; } MHWRender::MTexture* texture = nullptr; MHWRender::MTextureDescription desc; desc.setToDefault2DTexture(); desc.fWidth = spec.width; desc.fHeight = spec.height; desc.fBytesPerRow = bytesPerRow; desc.fBytesPerSlice = bytesPerSlice; #if PXR_VERSION > 2008 #if PXR_VERSION >= 2102 auto specFormat = spec.format; #else auto specFormat = spec.hioFormat; #endif switch (specFormat) { // Single Channel case HioFormatFloat32: desc.fFormat = MHWRender::kR32_FLOAT; texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); break; case HioFormatFloat16: desc.fFormat = MHWRender::kR16_FLOAT; texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); break; case HioFormatUNorm8: desc.fFormat = MHWRender::kR8_UNORM; texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); break; // Dual channel (quite rare, but seen with mono + alpha files) case HioFormatFloat32Vec2: desc.fFormat = MHWRender::kR32G32_FLOAT; texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); break; case HioFormatFloat16Vec2: { // R16G16 is not supported by VP2. Converted to R16G16B16A16. constexpr int bpp_8 = 8; desc.fFormat = MHWRender::kR16G16B16A16_FLOAT; desc.fBytesPerRow = spec.width * bpp_8; desc.fBytesPerSlice = desc.fBytesPerRow * spec.height; std::vector<unsigned char> texels(desc.fBytesPerSlice); for (int y = 0; y < spec.height; y++) { for (int x = 0; x < spec.width; x++) { const int t = spec.width * y + x; texels[t * bpp_8 + 0] = storage[t * bpp + 0]; texels[t * bpp_8 + 1] = storage[t * bpp + 1]; texels[t * bpp_8 + 2] = storage[t * bpp + 0]; texels[t * bpp_8 + 3] = storage[t * bpp + 1]; texels[t * bpp_8 + 4] = storage[t * bpp + 0]; texels[t * bpp_8 + 5] = storage[t * bpp + 1]; texels[t * bpp_8 + 6] = storage[t * bpp + 2]; texels[t * bpp_8 + 7] = storage[t * bpp + 3]; } } texture = textureMgr->acquireTexture(path.c_str(), desc, texels.data()); break; } case HioFormatUNorm8Vec2: case HioFormatUNorm8Vec2srgb: { // R8G8 is not supported by VP2. Converted to R8G8B8A8. constexpr int bpp_4 = 4; desc.fFormat = MHWRender::kR8G8B8A8_UNORM; desc.fBytesPerRow = spec.width * bpp_4; desc.fBytesPerSlice = desc.fBytesPerRow * spec.height; std::vector<unsigned char> texels(desc.fBytesPerSlice); for (int y = 0; y < spec.height; y++) { for (int x = 0; x < spec.width; x++) { const int t = spec.width * y + x; texels[t * bpp_4] = storage[t * bpp]; texels[t * bpp_4 + 1] = storage[t * bpp]; texels[t * bpp_4 + 2] = storage[t * bpp]; texels[t * bpp_4 + 3] = storage[t * bpp + 1]; } } texture = textureMgr->acquireTexture(path.c_str(), desc, texels.data()); isColorSpaceSRGB = image->IsColorSpaceSRGB(); break; } // 3-Channel case HioFormatFloat32Vec3: desc.fFormat = MHWRender::kR32G32B32_FLOAT; texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); break; case HioFormatFloat16Vec3: { // R16G16B16 is not supported by VP2. Converted to R16G16B16A16. constexpr int bpp_8 = 8; desc.fFormat = MHWRender::kR16G16B16A16_FLOAT; desc.fBytesPerRow = spec.width * bpp_8; desc.fBytesPerSlice = desc.fBytesPerRow * spec.height; GfHalf opaqueAlpha(1.0f); const unsigned short alphaBits = opaqueAlpha.bits(); const unsigned char lowAlpha = reinterpret_cast<const unsigned char*>(&alphaBits)[0]; const unsigned char highAlpha = reinterpret_cast<const unsigned char*>(&alphaBits)[1]; std::vector<unsigned char> texels(desc.fBytesPerSlice); for (int y = 0; y < spec.height; y++) { for (int x = 0; x < spec.width; x++) { const int t = spec.width * y + x; texels[t * bpp_8 + 0] = storage[t * bpp + 0]; texels[t * bpp_8 + 1] = storage[t * bpp + 1]; texels[t * bpp_8 + 2] = storage[t * bpp + 2]; texels[t * bpp_8 + 3] = storage[t * bpp + 3]; texels[t * bpp_8 + 4] = storage[t * bpp + 4]; texels[t * bpp_8 + 5] = storage[t * bpp + 5]; texels[t * bpp_8 + 6] = lowAlpha; texels[t * bpp_8 + 7] = highAlpha; } } texture = textureMgr->acquireTexture(path.c_str(), desc, texels.data()); break; } case HioFormatFloat16Vec4: desc.fFormat = MHWRender::kR16G16B16A16_FLOAT; texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); break; case HioFormatUNorm8Vec3: case HioFormatUNorm8Vec3srgb: { // R8G8B8 is not supported by VP2. Converted to R8G8B8A8. constexpr int bpp_4 = 4; desc.fFormat = MHWRender::kR8G8B8A8_UNORM; desc.fBytesPerRow = spec.width * bpp_4; desc.fBytesPerSlice = desc.fBytesPerRow * spec.height; std::vector<unsigned char> texels(desc.fBytesPerSlice); for (int y = 0; y < spec.height; y++) { for (int x = 0; x < spec.width; x++) { const int t = spec.width * y + x; texels[t * bpp_4] = storage[t * bpp]; texels[t * bpp_4 + 1] = storage[t * bpp + 1]; texels[t * bpp_4 + 2] = storage[t * bpp + 2]; texels[t * bpp_4 + 3] = 255; } } texture = textureMgr->acquireTexture(path.c_str(), desc, texels.data()); isColorSpaceSRGB = image->IsColorSpaceSRGB(); break; } // 4-Channel case HioFormatFloat32Vec4: desc.fFormat = MHWRender::kR32G32B32A32_FLOAT; texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); break; case HioFormatUNorm8Vec4: case HioFormatUNorm8Vec4srgb: desc.fFormat = MHWRender::kR8G8B8A8_UNORM; isColorSpaceSRGB = image->IsColorSpaceSRGB(); texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); break; default: TF_WARN( "VP2 renderer delegate: unsupported pixel format (%d) in texture file %s.", (int)specFormat, path.c_str()); break; } #else switch (spec.format) { case GL_RED: desc.fFormat = MHWRender::kR8_UNORM; if (spec.type == GL_FLOAT) desc.fFormat = MHWRender::kR32_FLOAT; else if (spec.type == GL_HALF_FLOAT) desc.fFormat = MHWRender::kR16_FLOAT; texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); break; case GL_RGB: if (spec.type == GL_FLOAT) { desc.fFormat = MHWRender::kR32G32B32_FLOAT; texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); } else if (spec.type == GL_HALF_FLOAT) { // R16G16B16 is not supported by VP2. Converted to R16G16B16A16. constexpr int bpp_8 = 8; desc.fFormat = MHWRender::kR16G16B16A16_FLOAT; desc.fBytesPerRow = spec.width * bpp_8; desc.fBytesPerSlice = desc.fBytesPerRow * spec.height; GfHalf opaqueAlpha(1.0f); const unsigned short alphaBits = opaqueAlpha.bits(); const unsigned char lowAlpha = reinterpret_cast<const unsigned char*>(&alphaBits)[0]; const unsigned char highAlpha = reinterpret_cast<const unsigned char*>(&alphaBits)[1]; std::vector<unsigned char> texels(desc.fBytesPerSlice); for (int y = 0; y < spec.height; y++) { for (int x = 0; x < spec.width; x++) { const int t = spec.width * y + x; texels[t * bpp_8 + 0] = storage[t * bpp + 0]; texels[t * bpp_8 + 1] = storage[t * bpp + 1]; texels[t * bpp_8 + 2] = storage[t * bpp + 2]; texels[t * bpp_8 + 3] = storage[t * bpp + 3]; texels[t * bpp_8 + 4] = storage[t * bpp + 4]; texels[t * bpp_8 + 5] = storage[t * bpp + 5]; texels[t * bpp_8 + 6] = lowAlpha; texels[t * bpp_8 + 7] = highAlpha; } } texture = textureMgr->acquireTexture(path.c_str(), desc, texels.data()); } else { // R8G8B8 is not supported by VP2. Converted to R8G8B8A8. constexpr int bpp_4 = 4; desc.fFormat = MHWRender::kR8G8B8A8_UNORM; desc.fBytesPerRow = spec.width * bpp_4; desc.fBytesPerSlice = desc.fBytesPerRow * spec.height; std::vector<unsigned char> texels(desc.fBytesPerSlice); for (int y = 0; y < spec.height; y++) { for (int x = 0; x < spec.width; x++) { const int t = spec.width * y + x; texels[t * bpp_4] = storage[t * bpp]; texels[t * bpp_4 + 1] = storage[t * bpp + 1]; texels[t * bpp_4 + 2] = storage[t * bpp + 2]; texels[t * bpp_4 + 3] = 255; } } texture = textureMgr->acquireTexture(path.c_str(), desc, texels.data()); isColorSpaceSRGB = image->IsColorSpaceSRGB(); } break; case GL_RGBA: if (spec.type == GL_FLOAT) { desc.fFormat = MHWRender::kR32G32B32A32_FLOAT; } else if (spec.type == GL_HALF_FLOAT) { desc.fFormat = MHWRender::kR16G16B16A16_FLOAT; } else { desc.fFormat = MHWRender::kR8G8B8A8_UNORM; isColorSpaceSRGB = image->IsColorSpaceSRGB(); } texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); break; default: break; } #endif return texture; } } // anonymous namespace /*! \brief Releases the reference to the texture owned by a smart pointer. */ void HdVP2TextureDeleter::operator()(MHWRender::MTexture* texture) { MRenderer* const renderer = MRenderer::theRenderer(); MHWRender::MTextureManager* const textureMgr = renderer ? renderer->getTextureManager() : nullptr; if (TF_VERIFY(textureMgr)) { textureMgr->releaseTexture(texture); } } /*! \brief Constructor */ HdVP2Material::HdVP2Material(HdVP2RenderDelegate* renderDelegate, const SdfPath& id) : HdMaterial(id) , _renderDelegate(renderDelegate) { } /*! \brief Synchronize VP2 state with scene delegate state based on dirty bits */ void HdVP2Material::Sync( HdSceneDelegate* sceneDelegate, HdRenderParam* /*renderParam*/, HdDirtyBits* dirtyBits) { if (*dirtyBits & (HdMaterial::DirtyResource | HdMaterial::DirtyParams)) { const SdfPath& id = GetId(); MProfilingScope profilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L2, "HdVP2Material::Sync", id.GetText()); VtValue vtMatResource = sceneDelegate->GetMaterialResource(id); if (vtMatResource.IsHolding<HdMaterialNetworkMap>()) { const HdMaterialNetworkMap& networkMap = vtMatResource.UncheckedGet<HdMaterialNetworkMap>(); HdMaterialNetwork bxdfNet, dispNet, vp2BxdfNet; TfMapLookup(networkMap.map, HdMaterialTerminalTokens->surface, &bxdfNet); TfMapLookup(networkMap.map, HdMaterialTerminalTokens->displacement, &dispNet); #ifdef WANT_MATERIALX_BUILD if (!bxdfNet.nodes.empty()) { if (_IsMaterialX(bxdfNet.nodes.back())) { bool isVolume = false; HdMaterialNetwork2 surfaceNetwork; HdMaterialNetwork2ConvertFromHdMaterialNetworkMap( networkMap, &surfaceNetwork, &isVolume); if (isVolume) { // Not supported. return; } size_t topoHash = _GenerateNetwork2TopoHash(surfaceNetwork); if (!_surfaceShader || topoHash != _topoHash) { _surfaceShader.reset( _CreateMaterialXShaderInstance(GetId(), surfaceNetwork)); _topoHash = topoHash; } if (_surfaceShader) { _UpdateShaderInstance(bxdfNet); #ifdef HDVP2_MATERIAL_CONSOLIDATION_UPDATE_WORKAROUND _MaterialChanged(sceneDelegate); #endif *dirtyBits = HdMaterial::Clean; } return; } } #endif _ApplyVP2Fixes(vp2BxdfNet, bxdfNet); if (!vp2BxdfNet.nodes.empty()) { // Generate a XML string from the material network and convert it to a token for // faster hashing and comparison. const TfToken token(_GenerateXMLString(vp2BxdfNet, false)); // Skip creating a new shader instance if the token is unchanged. There is no plan // to implement fine-grain dirty bit in Hydra for the same purpose: // https://groups.google.com/g/usd-interest/c/xytT2azlJec/m/22Tnw4yXAAAJ if (_surfaceNetworkToken != token) { MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L2, "CreateShaderInstance"); // Remember the path of the surface shader for special handling: unlike other // fragments, the parameters of the surface shader fragment can't be renamed. _surfaceShaderId = vp2BxdfNet.nodes.back().path; MHWRender::MShaderInstance* shader; #ifndef HDVP2_DISABLE_SHADER_CACHE // Acquire a shader instance from the shader cache. If a shader instance has // been cached with the same token, a clone of the shader instance will be // returned. Multiple clones of a shader instance will share the same shader // effect, thus reduce compilation overhead and enable material consolidation. shader = _renderDelegate->GetShaderFromCache(token); // If the shader instance is not found in the cache, create one from the // material network and add a clone to the cache for reuse. if (!shader) { shader = _CreateShaderInstance(vp2BxdfNet); if (shader) { _renderDelegate->AddShaderToCache(token, *shader); } } #else shader = _CreateShaderInstance(vp2BxdfNet); #endif // The shader instance is owned by the material solely. _surfaceShader.reset(shader); if (TfDebug::IsEnabled(HDVP2_DEBUG_MATERIAL)) { std::cout << "BXDF material network for " << id << ":\n" << _GenerateXMLString(bxdfNet) << "\n" << "BXDF (with VP2 fixes) material network for " << id << ":\n" << _GenerateXMLString(vp2BxdfNet) << "\n" << "Displacement material network for " << id << ":\n" << _GenerateXMLString(dispNet) << "\n"; if (_surfaceShader) { auto tmpDir = ghc::filesystem::temp_directory_path(); tmpDir /= "HdVP2Material_"; tmpDir += id.GetName(); tmpDir += ".txt"; _surfaceShader->writeEffectSourceToFile(tmpDir.c_str()); std::cout << "BXDF generated shader code for " << id << ":\n"; std::cout << " " << tmpDir << "\n"; } } // Store primvar requirements. _requiredPrimvars = std::move(vp2BxdfNet.primvars); // The token is saved and will be used to determine whether a new shader // instance is needed during the next sync. _surfaceNetworkToken = token; // If the surface shader has its opacity attribute connected to a node which // isn't a primvar reader, it is set as transparent. If the opacity attr is // connected to a primvar reader, the Rprim side will determine the transparency // state according to the primvars:displayOpacity data. If the opacity attr // isn't connected, the transparency state will be set in // _UpdateShaderInstance() according to the opacity value. if (shader) { shader->setIsTransparent(_IsTransparent(bxdfNet)); } } _UpdateShaderInstance(bxdfNet); #ifdef HDVP2_MATERIAL_CONSOLIDATION_UPDATE_WORKAROUND _MaterialChanged(sceneDelegate); #endif } } else { TF_WARN( "Expected material resource for <%s> to hold HdMaterialNetworkMap," "but found %s instead.", id.GetText(), vtMatResource.GetTypeName().c_str()); } } *dirtyBits = HdMaterial::Clean; } /*! \brief Returns the minimal set of dirty bits to place in the change tracker for use in the first sync of this prim. */ HdDirtyBits HdVP2Material::GetInitialDirtyBitsMask() const { return HdMaterial::AllDirty; } /*! \brief Applies VP2-specific fixes to the material network. */ void HdVP2Material::_ApplyVP2Fixes(HdMaterialNetwork& outNet, const HdMaterialNetwork& inNet) { // To avoid relocation, reserve enough space for possible maximal size. The // output network is temporary C++ object that will be released after use. const size_t numNodes = inNet.nodes.size(); const size_t numRelationships = inNet.relationships.size(); size_t nodeCounter = 0; _nodePathMap.clear(); _nodePathMap.reserve(numNodes); HdMaterialNetwork tmpNet; tmpNet.nodes.reserve(numNodes); tmpNet.relationships.reserve(numRelationships); // Some material networks require us to add nodes and connections to the base // HdMaterialNetwork. Keep track of the existence of some key nodes to help // with performance. HdMaterialNode* usdDrawModeCardsNode = nullptr; HdMaterialNode* cardsUvPrimvarReader = nullptr; // Get the shader registry so I can look up the real names of shading nodes. SdrRegistry& shaderReg = SdrRegistry::GetInstance(); // We might need to query the working color space of Maya if we hit texture nodes. Delay // the query until necessary. MString mayaWorkingColorSpace; // Replace the authored node paths with simplified paths in the form of "node#". By doing so // we will be able to reuse shader effects among material networks which have the same node // identifiers and relationships but different node paths, reduce shader compilation overhead // and enable material consolidation for faster rendering. for (const HdMaterialNode& node : inNet.nodes) { tmpNet.nodes.push_back(node); HdMaterialNode& outNode = tmpNet.nodes.back(); // For card draw mode the HdMaterialNode will have an identifier which is the hash of the // file path to drawMode.glslfx on disk. Using that value I can get the SdrShaderNode, and // then get the actual name of the shader "drawMode.glslfx". For other node names the // HdMaterialNode identifier and the SdrShaderNode name seem to be the same, so just convert // everything to use the SdrShaderNode name. SdrShaderNodeConstPtr sdrNode = shaderReg.GetShaderNodeByIdentifierAndType(outNode.identifier, _tokens->glslfx); if (_IsUsdUVTexture(node)) { // We need to rename according to the Maya color working space pref: if (!mayaWorkingColorSpace.length()) { // Query the user pref: mayaWorkingColorSpace = MGlobal::executeCommandStringResult( "colorManagementPrefs -q -renderingSpaceName"); } outNode.identifier = TfToken( HdVP2ShaderFragments::getUsdUVTextureFragmentName(mayaWorkingColorSpace).asChar()); } else { if (!sdrNode) { TF_WARN("Could not find a shader node for <%s>", node.path.GetText()); return; } outNode.identifier = TfToken(sdrNode->GetName()); } if (_IsUsdDrawModeNode(outNode)) { // I can't easily name a Maya fragment something with a '.' in it, so pick a different // fragment name. outNode.identifier = _tokens->UsdDrawModeCards; TF_VERIFY(!usdDrawModeCardsNode); // there should only be one. usdDrawModeCardsNode = &outNode; } if (_IsUsdFloat2PrimvarReader(outNode) && outNode.parameters[_tokens->varname] == _tokens->cardsUv) { TF_VERIFY(!cardsUvPrimvarReader); cardsUvPrimvarReader = &outNode; } outNode.path = SdfPath(outNode.identifier.GetString() + std::to_string(++nodeCounter)); _nodePathMap[node.path] = outNode.path; } // Update the relationships to use the new node paths. for (const HdMaterialRelationship& rel : inNet.relationships) { tmpNet.relationships.push_back(rel); HdMaterialRelationship& outRel = tmpNet.relationships.back(); outRel.inputId = _nodePathMap[outRel.inputId]; outRel.outputId = _nodePathMap[outRel.outputId]; } outNet.nodes.reserve(numNodes + numRelationships); outNet.relationships.reserve(numRelationships * 2); outNet.primvars.reserve(numNodes); // Add additional nodes necessary for Maya's fragment compiler // to work that are logical predecessors of node. auto addPredecessorNodes = [&](const HdMaterialNode& node) { // If the node is a UsdUVTexture node, verify there is a UsdPrimvarReader_float2 connected // to the st input of it. If not, find the basic st reader and/or create it and connect it. // Adding the UV reader only works for cards draw mode. We wouldn't know which UV stream to // read if another material was missing the primvar reader. if (_IsUsdUVTexture(node) && usdDrawModeCardsNode) { // the DrawModeCardsFragment has UsdUVtexture nodes without primvar readers. // Add a primvar reader to each UsdUVTexture which doesn't already have one. if (!cardsUvPrimvarReader) { HdMaterialNode stReader; stReader.identifier = UsdImagingTokens->UsdPrimvarReader_float2; stReader.path = SdfPath(stReader.identifier.GetString() + std::to_string(++nodeCounter)); stReader.parameters[_tokens->varname] = _tokens->cardsUv; outNet.nodes.push_back(stReader); cardsUvPrimvarReader = &outNet.nodes.back(); // Specifically looking for the cardsUv primvar outNet.primvars.push_back(_tokens->cardsUv); } // search for an existing relationship between cardsUvPrimvarReader & node. // TODO: if there are multiple UV sets this can fail, it is looking for // a connection to a specific UsdPrimvarReader_float2. bool hasRelationship = false; for (const HdMaterialRelationship& rel : tmpNet.relationships) { if (rel.inputId == cardsUvPrimvarReader->path && rel.inputName == _tokens->result && rel.outputId == node.path && rel.outputName == _tokens->st) { hasRelationship = true; break; } } if (!hasRelationship) { // The only case I'm currently aware of where we have UsdUVTexture nodes without // a corresponding UsdPrimvarReader_float2 to read the UVs is draw mode cards. // There could be other cases, and it could be find to add the primvar reader // and connection, but we want to know when it is happening. TF_VERIFY(usdDrawModeCardsNode); HdMaterialRelationship newRel = { cardsUvPrimvarReader->path, _tokens->result, node.path, _tokens->st }; outNet.relationships.push_back(newRel); } } // If the node is a DrawModeCardsFragment add a MayaIsBackFacing fragment to cull out // backfaces. if (_IsUsdDrawModeNode(node)) { // Add the MayaIsBackFacing fragment HdMaterialNode mayaIsBackFacingNode; mayaIsBackFacingNode.identifier = _tokens->mayaIsBackFacing; mayaIsBackFacingNode.path = SdfPath( mayaIsBackFacingNode.identifier.GetString() + std::to_string(++nodeCounter)); outNet.nodes.push_back(mayaIsBackFacingNode); // Connect to the isBackfacing input of the DrawModeCards fragment HdMaterialRelationship newRel = { mayaIsBackFacingNode.path, _tokens->mayaIsBackFacing, node.path, _tokens->isBackfacing }; outNet.relationships.push_back(newRel); } }; // Add additional nodes necessary for Maya's fragment compiler // to work that are logical successors of node. auto addSuccessorNodes = [&](const HdMaterialNode& node, const TfToken& primvarToRead) { // If the node is a DrawModeCardsFragment add the fallback material after it to do // the lighting etc. if (_IsUsdDrawModeNode(node)) { // Add the fallback shader node and hook it up. This has to be the last node in // outNet.nodes. HdMaterialNode fallbackShaderNode; fallbackShaderNode.identifier = _tokens->FallbackShader; fallbackShaderNode.path = SdfPath( fallbackShaderNode.identifier.GetString() + std::to_string(++nodeCounter)); outNet.nodes.push_back(fallbackShaderNode); // The DrawModeCards fragment is basically a texture picker. Connect its output to // the diffuseColor input of the fallback shader node. HdMaterialRelationship newRel = { node.path, _tokens->output, fallbackShaderNode.path, _tokens->diffuseColor }; outNet.relationships.push_back(newRel); // Add the required primvars outNet.primvars.push_back(HdTokens->points); outNet.primvars.push_back(HdTokens->normals); // no passthrough nodes necessary between the draw mode cards node & the fallback // shader. return; } // Copy outgoing connections and if needed add passthrough node/connection. for (const HdMaterialRelationship& rel : tmpNet.relationships) { if (rel.inputId != node.path) { continue; } TfToken passThroughId; if (rel.inputName == _tokens->rgb || rel.inputName == _tokens->xyz) { passThroughId = _tokens->Float4ToFloat3; } else if (rel.inputName == _tokens->r || rel.inputName == _tokens->x) { passThroughId = _tokens->Float4ToFloatX; } else if (rel.inputName == _tokens->g || rel.inputName == _tokens->y) { passThroughId = _tokens->Float4ToFloatY; } else if (rel.inputName == _tokens->b || rel.inputName == _tokens->z) { passThroughId = _tokens->Float4ToFloatZ; } else if (rel.inputName == _tokens->a || rel.inputName == _tokens->w) { passThroughId = _tokens->Float4ToFloatW; } else if (primvarToRead == HdTokens->displayColor) { passThroughId = _tokens->Float4ToFloat3; } else if (primvarToRead == HdTokens->displayOpacity) { passThroughId = _tokens->Float4ToFloatW; } else { outNet.relationships.push_back(rel); continue; } const SdfPath passThroughPath( passThroughId.GetString() + std::to_string(++nodeCounter)); const HdMaterialNode passThroughNode = { passThroughPath, passThroughId, {} }; outNet.nodes.push_back(passThroughNode); HdMaterialRelationship newRel = { rel.inputId, _tokens->output, passThroughPath, _tokens->input }; outNet.relationships.push_back(newRel); newRel = { passThroughPath, _tokens->output, rel.outputId, rel.outputName }; outNet.relationships.push_back(newRel); } }; // Add nodes necessary for the fragment compiler to produce a shader that works. for (const HdMaterialNode& node : tmpNet.nodes) { TfToken primvarToRead; const bool isUsdPrimvarReader = _IsUsdPrimvarReader(node); if (isUsdPrimvarReader) { auto it = node.parameters.find(_tokens->varname); if (it != node.parameters.end()) { primvarToRead = TfToken(TfStringify(it->second)); } } addPredecessorNodes(node); outNet.nodes.push_back(node); addSuccessorNodes(node, primvarToRead); // If the primvar reader is reading color or opacity, replace it with // UsdPrimvarReader_color which can create COLOR stream requirement // instead of generic TEXCOORD stream. if (primvarToRead == HdTokens->displayColor || primvarToRead == HdTokens->displayOpacity) { HdMaterialNode& nodeToChange = outNet.nodes.back(); nodeToChange.identifier = _tokens->UsdPrimvarReader_color; } // Normal map is not supported yet. For now primvars:normals is used for // shading, which is also the current behavior of USD/Hydra. // https://groups.google.com/d/msg/usd-interest/7epU16C3eyY/X9mLW9VFEwAJ if (node.identifier == UsdImagingTokens->UsdPreviewSurface) { outNet.primvars.push_back(HdTokens->normals); } // UsdImagingMaterialAdapter doesn't create primvar requirements as // expected. Workaround by manually looking up "varname" parameter. // https://groups.google.com/forum/#!msg/usd-interest/z-14AgJKOcU/1uJJ1thXBgAJ else if (isUsdPrimvarReader) { if (!primvarToRead.IsEmpty()) { outNet.primvars.push_back(primvarToRead); } } } } #ifdef WANT_MATERIALX_BUILD void HdVP2Material::_ApplyMtlxVP2Fixes(HdMaterialNetwork2& outNet, const HdMaterialNetwork2& inNet) { // The goal here is to strip all local names in the network paths in order to reduce the shader // to its topological elements only. // We also strip all local values so that the Maya effect gets created with all values set to // their MaterialX default values. // Once we have that, we can fully re-use any previously encountered effect that has the same // MaterialX topology and only update the values that are found in the material network. size_t nodeCounter = 0; _nodePathMap.clear(); // Paths will go /NG_Maya/N0, /NG_Maya/N1, /NG_Maya/N2... // We need NG_Maya, one level up, as this will be the name assigned to the MaterialX node graph // when run thru HdMtlxCreateMtlxDocumentFromHdNetwork (I know, forbidden knowledge again). SdfPath ngBase(_mtlxTokens->NG_Maya); // We will traverse the network in a depth-first traversal starting at the // terminals. This will allow a stable traversal that will not be affected // by the ordering of the SdfPaths and make sure we assign the same index to // all nodes regardless of the way they are sorted in the network node map. std::vector<const SdfPath*> pathsToTraverse; for (const auto& terminal : inNet.terminals) { const auto& connection = terminal.second; pathsToTraverse.push_back(&(connection.upstreamNode)); } while (!pathsToTraverse.empty()) { const SdfPath* path = pathsToTraverse.back(); pathsToTraverse.pop_back(); if (!_nodePathMap.count(*path)) { const HdMaterialNode2& node = inNet.nodes.find(*path)->second; // We only need to create the anonymized name at this time: _nodePathMap[*path] = ngBase.AppendChild(TfToken("N" + std::to_string(nodeCounter++))); for (const auto& input : node.inputConnections) { for (const auto& connection : input.second) { pathsToTraverse.push_back(&(connection.upstreamNode)); } } } } // Copy the incoming network using only the anonymized names: outNet.primvars = inNet.primvars; for (const auto& terminal : inNet.terminals) { outNet.terminals.emplace( terminal.first, HdMaterialConnection2 { _nodePathMap[terminal.second.upstreamNode], terminal.second.upstreamOutputName }); } for (const auto& nodePair : inNet.nodes) { const HdMaterialNode2& inNode = nodePair.second; HdMaterialNode2 outNode; outNode.nodeTypeId = inNode.nodeTypeId; if (_IsTopologicalNode(inNode)) { // These parameters affect topology: outNode.parameters = inNode.parameters; } for (const auto& cnxPair : inNode.inputConnections) { std::vector<HdMaterialConnection2> outCnx; for (const auto& c : cnxPair.second) { outCnx.emplace_back( HdMaterialConnection2 { _nodePathMap[c.upstreamNode], c.upstreamOutputName }); } outNode.inputConnections.emplace(cnxPair.first, std::move(outCnx)); } outNet.nodes.emplace(_nodePathMap[nodePair.first], std::move(outNode)); } } /*! \brief Detects MaterialX networks and rehydrates them. */ MHWRender::MShaderInstance* HdVP2Material::_CreateMaterialXShaderInstance( SdfPath const& materialId, HdMaterialNetwork2 const& surfaceNetwork) { MHWRender::MShaderInstance* shaderInstance = nullptr; auto const& terminalConnIt = surfaceNetwork.terminals.find(HdMaterialTerminalTokens->surface); if (terminalConnIt == surfaceNetwork.terminals.end()) { // No surface material return shaderInstance; } HdMaterialNetwork2 fixedNetwork; _ApplyMtlxVP2Fixes(fixedNetwork, surfaceNetwork); SdfPath terminalPath = terminalConnIt->second.upstreamNode; const TfToken shaderCacheID(_GenerateXMLString(fixedNetwork)); // Acquire a shader instance from the shader cache. If a shader instance has been cached with // the same token, a clone of the shader instance will be returned. Multiple clones of a shader // instance will share the same shader effect, thus reduce compilation overhead and enable // material consolidation. shaderInstance = _renderDelegate->GetShaderFromCache(shaderCacheID); if (shaderInstance) { _surfaceShaderId = terminalPath; const TfTokenVector* cachedPrimvars = _renderDelegate->GetPrimvarsFromCache(shaderCacheID); if (cachedPrimvars) { _requiredPrimvars = *cachedPrimvars; } return shaderInstance; } SdfPath fixedPath = fixedNetwork.terminals[HdMaterialTerminalTokens->surface].upstreamNode; HdMaterialNode2 const* surfTerminal = &fixedNetwork.nodes[fixedPath]; if (!surfTerminal) { return shaderInstance; } try { // The HdMtlxCreateMtlxDocumentFromHdNetwork function can throw if any MaterialX error is // raised. // Check if the Terminal is a MaterialX Node SdrRegistry& sdrRegistry = SdrRegistry::GetInstance(); const SdrShaderNodeConstPtr mtlxSdrNode = sdrRegistry.GetShaderNodeByIdentifierAndType( surfTerminal->nodeTypeId, HdVP2Tokens->mtlx); mx::DocumentPtr mtlxDoc; const mx::FileSearchPath& crLibrarySearchPath(_GetMaterialXData()._mtlxSearchPath); if (mtlxSdrNode) { // Create the MaterialX Document from the HdMaterialNetwork std::set<SdfPath> hdTextureNodes; mx::StringMap mxHdTextureMap; // Mx-Hd texture name counterparts mtlxDoc = HdMtlxCreateMtlxDocumentFromHdNetwork( fixedNetwork, *surfTerminal, // MaterialX HdNode SdfPath(_mtlxTokens->USD_Mtlx_VP2_Material), _GetMaterialXData()._mtlxLibrary, &hdTextureNodes, &mxHdTextureMap); if (!mtlxDoc) { return shaderInstance; } // Fix any missing texcoord reader. _AddMissingTexcoordReaders(mtlxDoc); _surfaceShaderId = terminalPath; if (TfDebug::IsEnabled(HDVP2_DEBUG_MATERIAL)) { std::cout << "generated shader code for " << materialId.GetText() << ":\n"; std::cout << "Generated graph\n==============================\n"; mx::writeToXmlStream(mtlxDoc, std::cout); std::cout << "\n==============================\n"; } } else { return shaderInstance; } // This function is very recent and might only exist in a PR at this point in time // See https://github.com/autodesk-forks/MaterialX/pull/1197 for current status. mx::OgsXmlGenerator::setUseLightAPIV2(true); mx::NodePtr materialNode; for (const mx::NodePtr& material : mtlxDoc->getMaterialNodes()) { if (material->getName() == _mtlxTokens->USD_Mtlx_VP2_Material.GetText()) { materialNode = material; } } if (!materialNode) { return shaderInstance; } MaterialXMaya::OgsFragment ogsFragment(materialNode, crLibrarySearchPath); // Explore the fragment for primvars: mx::ShaderPtr shader = ogsFragment.getShader(); const mx::VariableBlock& vertexInputs = shader->getStage(mx::Stage::VERTEX).getInputBlock(mx::HW::VERTEX_INPUTS); for (size_t i = 0; i < vertexInputs.size(); ++i) { const mx::ShaderPort* variable = vertexInputs[i]; // Position is always assumed. // Tangent will be generated in the vertex shader using a utility fragment if (variable->getName() == mx::HW::T_IN_NORMAL) { _requiredPrimvars.push_back(HdTokens->normals); } } MHWRender::MRenderer* const renderer = MHWRender::MRenderer::theRenderer(); if (!TF_VERIFY(renderer)) { return shaderInstance; } MHWRender::MFragmentManager* const fragmentManager = renderer->getFragmentManager(); if (!TF_VERIFY(fragmentManager)) { return shaderInstance; } MString fragmentName(ogsFragment.getFragmentName().c_str()); if (!fragmentManager->hasFragment(fragmentName)) { std::string fragSrc = ogsFragment.getFragmentSource(); const MString registeredFragment = fragmentManager->addShadeFragmentFromBuffer(fragSrc.c_str(), false); if (registeredFragment.length() == 0) { TF_WARN("Failed to register shader fragment %s", fragmentName.asChar()); return shaderInstance; } } const MHWRender::MShaderManager* const shaderMgr = renderer->getShaderManager(); if (!TF_VERIFY(shaderMgr)) { return shaderInstance; } shaderInstance = shaderMgr->getFragmentShader(fragmentName, "outColor", true); // Find named primvar readers: MStringArray parameterList; shaderInstance->parameterList(parameterList); for (unsigned int i = 0; i < parameterList.length(); ++i) { static const unsigned int u_geomprop_length = static_cast<unsigned int>(_mtlxTokens->i_geomprop_.GetString().length()); if (parameterList[i].substring(0, u_geomprop_length - 1) == _mtlxTokens->i_geomprop_.GetText()) { MString varname = parameterList[i].substring(u_geomprop_length, parameterList[i].length()); shaderInstance->renameParameter(parameterList[i], varname); _requiredPrimvars.push_back(TfToken(varname.asChar())); } } // Add automatic tangent generation: shaderInstance->addInputFragment("materialXTw", "Tw", "Tw"); shaderInstance->setIsTransparent(ogsFragment.isTransparent()); } catch (mx::Exception& e) { TF_RUNTIME_ERROR( "Caught exception '%s' while processing '%s'", e.what(), materialId.GetText()); return nullptr; } if (TfDebug::IsEnabled(HDVP2_DEBUG_MATERIAL)) { std::cout << "BXDF material network for " << materialId << ":\n" << _GenerateXMLString(surfaceNetwork) << "\n" << "Topology-only network for " << materialId << ":\n" << shaderCacheID << "\n" << "Required primvars:\n"; for (TfToken const& primvar : _requiredPrimvars) { std::cout << "\t" << primvar << std::endl; } auto tmpDir = ghc::filesystem::temp_directory_path(); tmpDir /= "HdVP2Material_"; tmpDir += materialId.GetName(); tmpDir += ".txt"; shaderInstance->writeEffectSourceToFile(tmpDir.c_str()); std::cout << "BXDF generated shader code for " << materialId << ":\n"; std::cout << " " << tmpDir << "\n"; } if (shaderInstance) { _renderDelegate->AddShaderToCache(shaderCacheID, *shaderInstance); _renderDelegate->AddPrimvarsToCache(shaderCacheID, _requiredPrimvars); } return shaderInstance; } #endif /*! \brief Creates a shader instance for the surface shader. */ MHWRender::MShaderInstance* HdVP2Material::_CreateShaderInstance(const HdMaterialNetwork& mat) { MHWRender::MRenderer* const renderer = MHWRender::MRenderer::theRenderer(); if (!TF_VERIFY(renderer)) { return nullptr; } const MHWRender::MShaderManager* const shaderMgr = renderer->getShaderManager(); if (!TF_VERIFY(shaderMgr)) { return nullptr; } MHWRender::MShaderInstance* shaderInstance = nullptr; // MShaderInstance supports multiple connections between shaders on Maya 2018.7, 2019.3, 2020 // and above. #if (MAYA_API_VERSION >= 20190300) \ || ((MAYA_API_VERSION >= 20180700) && (MAYA_API_VERSION < 20190000)) // UsdImagingMaterialAdapter has walked the shader graph and emitted nodes // and relationships in topological order to avoid forward-references, thus // we can run a reverse iteration to avoid connecting a fragment before any // of its downstream fragments. const auto rend = mat.nodes.rend(); for (auto rit = mat.nodes.rbegin(); rit != rend; rit++) { const HdMaterialNode& node = *rit; const MString nodeId = node.identifier.GetText(); const MString nodeName = node.path.GetNameToken().GetText(); if (shaderInstance == nullptr) { shaderInstance = shaderMgr->getFragmentShader(nodeId, "outSurfaceFinal", true); if (shaderInstance == nullptr) { TF_WARN("Failed to create shader instance for %s", nodeId.asChar()); break; } continue; } MStringArray outputNames, inputNames; for (const HdMaterialRelationship& rel : mat.relationships) { if (rel.inputId == node.path) { MString outputName = rel.inputName.GetText(); outputNames.append(outputName); if (rel.outputId != _surfaceShaderId) { std::string str = rel.outputId.GetName(); str += rel.outputName.GetString(); inputNames.append(str.c_str()); } else { inputNames.append(rel.outputName.GetText()); } } } if (outputNames.length() > 0) { MUintArray invalidParamIndices; MStatus status = shaderInstance->addInputFragmentForMultiParams( nodeId, nodeName, outputNames, inputNames, &invalidParamIndices); if (!status && TfDebug::IsEnabled(HDVP2_DEBUG_MATERIAL)) { TF_WARN( "Error %s happened when connecting shader %s", status.errorString().asChar(), node.path.GetText()); const unsigned int len = invalidParamIndices.length(); for (unsigned int i = 0; i < len; i++) { unsigned int index = invalidParamIndices[i]; const MString& outputName = outputNames[index]; const MString& inputName = inputNames[index]; TF_WARN(" %s -> %s", outputName.asChar(), inputName.asChar()); } } if (_IsUsdPrimvarReader(node)) { auto it = node.parameters.find(_tokens->varname); if (it != node.parameters.end()) { const MString paramName = HdTokens->primvar.GetText(); const MString varname = TfStringify(it->second).c_str(); shaderInstance->renameParameter(paramName, varname); } } } else { TF_DEBUG(HDVP2_DEBUG_MATERIAL) .Msg("Failed to connect shader %s\n", node.path.GetText()); } } #elif MAYA_API_VERSION >= 20190000 // UsdImagingMaterialAdapter has walked the shader graph and emitted nodes // and relationships in topological order to avoid forward-references, thus // we can run a reverse iteration to avoid connecting a fragment before any // of its downstream fragments. const auto rend = mat.nodes.rend(); for (auto rit = mat.nodes.rbegin(); rit != rend; rit++) { const HdMaterialNode& node = *rit; const MString nodeId = node.identifier.GetText(); const MString nodeName = node.path.GetNameToken().GetText(); if (shaderInstance == nullptr) { shaderInstance = shaderMgr->getFragmentShader(nodeId, "outSurfaceFinal", true); if (shaderInstance == nullptr) { TF_WARN("Failed to create shader instance for %s", nodeId.asChar()); break; } continue; } MStringArray outputNames, inputNames; std::string primvarname; for (const HdMaterialRelationship& rel : mat.relationships) { if (rel.inputId == node.path) { outputNames.append(rel.inputName.GetText()); inputNames.append(rel.outputName.GetText()); } if (_IsUsdUVTexture(node)) { if (rel.outputId == node.path && rel.outputName == _tokens->st) { for (const HdMaterialNode& n : mat.nodes) { if (n.path == rel.inputId && _IsUsdPrimvarReader(n)) { auto it = n.parameters.find(_tokens->varname); if (it != n.parameters.end()) { primvarname = TfStringify(it->second); } break; } } } } } // Without multi-connection support for MShaderInstance, this code path // can only support common patterns of UsdShade material network, i.e. // a UsdUVTexture is connected to a single input of a USD Preview Surface. // More generic fix is coming. if (outputNames.length() == 1) { MStatus status = shaderInstance->addInputFragment(nodeId, outputNames[0], inputNames[0]); if (!status) { TF_DEBUG(HDVP2_DEBUG_MATERIAL) .Msg( "Error %s happened when connecting shader %s\n", status.errorString().asChar(), node.path.GetText()); } if (_IsUsdUVTexture(node)) { const MString paramNames[] = { "file", "fileSampler", "isColorSpaceSRGB", "fallback", "scale", "bias" }; for (const MString& paramName : paramNames) { const MString resolvedName = nodeName + paramName; shaderInstance->renameParameter(paramName, resolvedName); } const MString paramName = _tokens->st.GetText(); shaderInstance->setSemantic(paramName, "uvCoord"); shaderInstance->setAsVarying(paramName, true); shaderInstance->renameParameter(paramName, primvarname.c_str()); } } else { TF_DEBUG(HDVP2_DEBUG_MATERIAL) .Msg("Failed to connect shader %s\n", node.path.GetText()); if (outputNames.length() > 1) { TF_DEBUG(HDVP2_DEBUG_MATERIAL) .Msg("MShaderInstance doesn't support " "multiple connections between shaders on the current Maya version.\n"); } } } #endif return shaderInstance; } /*! \brief Updates parameters for the surface shader. */ void HdVP2Material::_UpdateShaderInstance(const HdMaterialNetwork& mat) { if (!_surfaceShader) { return; } MProfilingScope profilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L2, "UpdateShaderInstance"); for (const HdMaterialNode& node : mat.nodes) { MString nodeName = ""; #ifdef WANT_MATERIALX_BUILD const bool isMaterialXNode = _IsMaterialX(node); if (isMaterialXNode) { nodeName += _nodePathMap[node.path].GetName().c_str(); if (node.path == _surfaceShaderId) { nodeName = ""; } else { nodeName += "_"; } } else #endif { // Find the simplified path for the authored node path from the map which has been // created when applying VP2-specific fixes. const auto it = _nodePathMap.find(node.path); if (it == _nodePathMap.end()) { continue; } // The simplified path has only one token which is the node name. const SdfPath& nodePath = it->second; if (nodePath != _surfaceShaderId) { nodeName = nodePath.GetText(); } } MStatus samplerStatus = MStatus::kFailure; if (_IsUsdUVTexture(node)) { const MHWRender::MSamplerStateDesc desc = _GetSamplerStateDesc(node); const MHWRender::MSamplerState* sampler = _renderDelegate->GetSamplerState(desc); if (sampler) { #ifdef WANT_MATERIALX_BUILD if (isMaterialXNode) { const MString paramName = "_" + nodeName + "file_sampler"; samplerStatus = _surfaceShader->setParameter(paramName, *sampler); } else #endif { const MString paramName = nodeName + "fileSampler"; samplerStatus = _surfaceShader->setParameter(paramName, *sampler); } } } for (auto const& entry : node.parameters) { const TfToken& token = entry.first; const VtValue& value = entry.second; MString paramName = nodeName + token.GetText(); MStatus status = MStatus::kFailure; if (value.IsHolding<float>()) { const float& val = value.UncheckedGet<float>(); status = _surfaceShader->setParameter(paramName, val); #ifdef WANT_MATERIALX_BUILD if (!status) { status = _SetFAParameter(_surfaceShader.get(), node, paramName, val); } #endif // The opacity parameter can be found and updated only when it // has no connection. In this case, transparency of the shader // is solely determined by the opacity value. if (status && nodeName.length() == 0 && token == _tokens->opacity) { _surfaceShader->setIsTransparent(val < 0.999f); } } else if (value.IsHolding<GfVec2f>()) { const float* val = value.UncheckedGet<GfVec2f>().data(); status = _surfaceShader->setParameter(paramName, val); } else if (value.IsHolding<GfVec3f>()) { const float* val = value.UncheckedGet<GfVec3f>().data(); status = _surfaceShader->setParameter(paramName, val); } else if (value.IsHolding<GfVec4f>()) { const float* val = value.UncheckedGet<GfVec4f>().data(); status = _surfaceShader->setParameter(paramName, val); } else if (value.IsHolding<TfToken>()) { if (_IsUsdUVTexture(node)) { if (token == UsdHydraTokens->wrapS || token == UsdHydraTokens->wrapT) { // The two parameters have been converted to sampler state before entering // this loop. status = samplerStatus; } else if (token == _tokens->sourceColorSpace) { status = MStatus::kSuccess; } } } else if (value.IsHolding<SdfAssetPath>()) { const SdfAssetPath& val = value.UncheckedGet<SdfAssetPath>(); const std::string& resolvedPath = val.GetResolvedPath(); const std::string& assetPath = val.GetAssetPath(); if (_IsUsdUVTexture(node) && token == _tokens->file) { const HdVP2TextureInfo& info = _AcquireTexture(!resolvedPath.empty() ? resolvedPath : assetPath, node); MHWRender::MTextureAssignment assignment; assignment.texture = info._texture.get(); status = _surfaceShader->setParameter(paramName, assignment); #ifdef WANT_MATERIALX_BUILD // TODO: MaterialX image nodes have colorSpace metadata on the file attribute, // and this can be found in the UsdShade version of the MaterialX document. At // this point in time, there is no mechanism in Hydra to transmit metadata so // this information will not reach the render delegate. Follow // https://github.com/PixarAnimationStudios/USD/issues/1523 for future updates // on colorspace handling in MaterialX/Hydra. if (status && !isMaterialXNode) { #else if (status) { #endif paramName = nodeName + "isColorSpaceSRGB"; bool isSRGB = info._isColorSpaceSRGB; auto scsIt = node.parameters.find(_tokens->sourceColorSpace); if (scsIt != node.parameters.end()) { const VtValue& scsValue = scsIt->second; if (scsValue.IsHolding<TfToken>()) { const TfToken& scsToken = scsValue.UncheckedGet<TfToken>(); if (scsToken == _tokens->raw) { isSRGB = false; } else if (scsToken == _tokens->sRGB) { isSRGB = true; } } } status = _surfaceShader->setParameter(paramName, isSRGB); } // These parameters allow scaling texcoords into the proper coordinates of the // Maya UDIM texture atlas: if (status) { #ifdef WANT_MATERIALX_BUILD paramName = nodeName + (isMaterialXNode ? "uv_scale" : "stScale"); #else paramName = nodeName + "stScale"; #endif status = _surfaceShader->setParameter(paramName, info._stScale.data()); } if (status) { #ifdef WANT_MATERIALX_BUILD paramName = nodeName + (isMaterialXNode ? "uv_offset" : "stOffset"); #else paramName = nodeName + "stOffset"; #endif status = _surfaceShader->setParameter(paramName, info._stOffset.data()); } } } else if (value.IsHolding<int>()) { const int& val = value.UncheckedGet<int>(); if (node.identifier == UsdImagingTokens->UsdPreviewSurface && token == _tokens->useSpecularWorkflow) { status = _surfaceShader->setParameter(paramName, val != 0); } else { status = _surfaceShader->setParameter(paramName, val); } } else if (value.IsHolding<bool>()) { const bool& val = value.UncheckedGet<bool>(); status = _surfaceShader->setParameter(paramName, val); } else if (value.IsHolding<GfMatrix4d>()) { MMatrix matrix; value.UncheckedGet<GfMatrix4d>().Get(matrix.matrix); status = _surfaceShader->setParameter(paramName, matrix); } else if (value.IsHolding<GfMatrix4f>()) { MFloatMatrix matrix; value.UncheckedGet<GfMatrix4f>().Get(matrix.matrix); status = _surfaceShader->setParameter(paramName, matrix); #ifdef WANT_MATERIALX_BUILD } else if (value.IsHolding<std::string>()) { // Some MaterialX nodes have a string member that does not translate to a shader // parameter. if (isMaterialXNode && (token == _mtlxTokens->geomprop || token == _mtlxTokens->uaddressmode || token == _mtlxTokens->vaddressmode || token == _mtlxTokens->filtertype || token == _mtlxTokens->channels)) { status = MS::kSuccess; } #endif } if (!status) { TF_DEBUG(HDVP2_DEBUG_MATERIAL) .Msg("Failed to set shader parameter %s\n", paramName.asChar()); } } } } /*! \brief Acquires a texture for the given image path. */ const HdVP2TextureInfo& HdVP2Material::_AcquireTexture(const std::string& path, const HdMaterialNode& node) { const auto it = _textureMap.find(path); if (it != _textureMap.end()) { return it->second; } bool isSRGB = false; MFloatArray uvScaleOffset; MHWRender::MTexture* texture = _LoadTexture(path, isSRGB, uvScaleOffset, node); HdVP2TextureInfo& info = _textureMap[path]; info._texture.reset(texture); info._isColorSpaceSRGB = isSRGB; if (uvScaleOffset.length() > 0) { TF_VERIFY(uvScaleOffset.length() == 4); info._stScale.Set(uvScaleOffset[0], uvScaleOffset[1]); // The first 2 elements are the scale info._stOffset.Set( uvScaleOffset[2], uvScaleOffset[3]); // The next two elements are the offset } return info; } #ifdef HDVP2_MATERIAL_CONSOLIDATION_UPDATE_WORKAROUND void HdVP2Material::SubscribeForMaterialUpdates(const SdfPath& rprimId) { std::lock_guard<std::mutex> lock(_materialSubscriptionsMutex); _materialSubscriptions.insert(rprimId); } void HdVP2Material::UnsubscribeFromMaterialUpdates(const SdfPath& rprimId) { std::lock_guard<std::mutex> lock(_materialSubscriptionsMutex); _materialSubscriptions.erase(rprimId); } void HdVP2Material::_MaterialChanged(HdSceneDelegate* sceneDelegate) { std::lock_guard<std::mutex> lock(_materialSubscriptionsMutex); HdChangeTracker& changeTracker = sceneDelegate->GetRenderIndex().GetChangeTracker(); for (const SdfPath& rprimId : _materialSubscriptions) { changeTracker.MarkRprimDirty(rprimId, HdChangeTracker::DirtyMaterialId); } } #endif PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/lib/mayaUsd/resources/CMakeLists.txt add_subdirectory(ae) add_subdirectory(icons) <file_sep>/lib/mayaUsd/ufe/Utils.cpp // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "Utils.h" #include "private/Utils.h" #include <mayaUsd/nodes/proxyShapeBase.h> #include <mayaUsd/ufe/Global.h> #include <mayaUsd/ufe/ProxyShapeHandler.h> #include <mayaUsd/ufe/UsdStageMap.h> #include <mayaUsd/utils/editability.h> #include <mayaUsd/utils/util.h> #include <pxr/base/tf/hashset.h> #include <pxr/base/tf/stringUtils.h> #include <pxr/usd/pcp/layerStack.h> #include <pxr/usd/pcp/site.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/sdf/tokens.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usdGeom/pointInstancer.h> #include <pxr/usd/usdGeom/tokens.h> #include <pxr/usdImaging/usdImaging/delegate.h> #include <maya/MFnDependencyNode.h> #include <maya/MGlobal.h> #include <maya/MObjectHandle.h> #include <ufe/hierarchy.h> #include <ufe/pathSegment.h> #include <ufe/rtid.h> #include <ufe/selection.h> #include <cassert> #include <cctype> #include <memory> #include <regex> #include <stdexcept> #include <string> #include <unordered_map> PXR_NAMESPACE_USING_DIRECTIVE namespace { constexpr auto kIllegalUSDPath = "Illegal USD run-time path %s."; bool stringBeginsWithDigit(const std::string& inputString) { if (inputString.empty()) { return false; } const char& firstChar = inputString.front(); if (std::isdigit(static_cast<unsigned char>(firstChar))) { return true; } return false; } // This function calculates the position index for a given layer across all // the site's local LayerStacks uint32_t findLayerIndex(const UsdPrim& prim, const PXR_NS::SdfLayerHandle& layer) { uint32_t position { 0 }; const PXR_NS::PcpPrimIndex& primIndex = prim.GetPrimIndex(); // iterate through the expanded primIndex for (PcpNodeRef node : primIndex.GetNodeRange()) { TF_AXIOM(node); const PcpLayerStackSite& site = node.GetSite(); const PcpLayerStackRefPtr& layerStack = site.layerStack; // iterate through the "local" Layer stack for each site // to find the layer for (SdfLayerRefPtr const& l : layerStack->GetLayers()) { if (l == layer) { return position; } ++position; } } return position; } } // anonymous namespace namespace MAYAUSD_NS_DEF { namespace ufe { //------------------------------------------------------------------------------ // Global variables & macros //------------------------------------------------------------------------------ extern UsdStageMap g_StageMap; extern Ufe::Rtid g_MayaRtid; // Cache of Maya node types we've queried before for inheritance from the // gateway node type. std::unordered_map<std::string, bool> g_GatewayType; //------------------------------------------------------------------------------ // Utility Functions //------------------------------------------------------------------------------ UsdStageWeakPtr getStage(const Ufe::Path& path) { return g_StageMap.stage(path); } Ufe::Path stagePath(UsdStageWeakPtr stage) { return g_StageMap.path(stage); } TfHashSet<UsdStageWeakPtr, TfHash> getAllStages() { return g_StageMap.allStages(); } Ufe::PathSegment usdPathToUfePathSegment(const SdfPath& usdPath, int instanceIndex) { const Ufe::Rtid usdRuntimeId = getUsdRunTimeId(); static const char separator = SdfPathTokens->childDelimiter.GetText()[0u]; if (usdPath.IsEmpty()) { // Return an empty segment. return Ufe::PathSegment(Ufe::PathSegment::Components(), usdRuntimeId, separator); } std::string pathString = usdPath.GetString(); if (instanceIndex >= 0) { // Note here that we're taking advantage of the fact that identifiers // in SdfPaths must be C/Python identifiers; that is, they must *not* // begin with a digit. This means that when we see a path component at // the end of a USD path segment that does begin with a digit, we can // be sure that it represents an instance index and not a prim or other // USD entity. pathString += TfStringPrintf("%c%d", separator, instanceIndex); } return Ufe::PathSegment(pathString, usdRuntimeId, separator); } Ufe::Path stripInstanceIndexFromUfePath(const Ufe::Path& path) { if (path.empty()) { return path; } // As with usdPathToUfePathSegment() above, we're taking advantage of the // fact that identifiers in SdfPaths must be C/Python identifiers; that is, // they must *not* begin with a digit. This means that when we see a path // component at the end of a USD path segment that does begin with a digit, // we can be sure that it represents an instance index and not a prim or // other USD entity. if (stringBeginsWithDigit(path.back().string())) { return path.pop(); } return path; } UsdPrim ufePathToPrim(const Ufe::Path& path) { const Ufe::Path ufePrimPath = stripInstanceIndexFromUfePath(path); // Assume that there are only two segments in the path, the first a Maya // Dag path segment to the proxy shape, which identifies the stage, and // the second the USD segment. // When called we do not make any assumption on whether or not the // input path is valid. const Ufe::Path::Segments& segments = ufePrimPath.getSegments(); if (!TF_VERIFY(segments.size() == 2u, kIllegalUSDPath, path.string().c_str())) { return UsdPrim(); } UsdPrim prim; if (auto stage = getStage(Ufe::Path(segments[0]))) { const SdfPath usdPath = SdfPath(segments[1].string()); prim = stage->GetPrimAtPath(usdPath.GetPrimPath()); } return prim; } int ufePathToInstanceIndex(const Ufe::Path& path, PXR_NS::UsdPrim* prim) { int instanceIndex = UsdImagingDelegate::ALL_INSTANCES; const UsdPrim usdPrim = ufePathToPrim(path); if (prim) { *prim = usdPrim; } if (!usdPrim || !usdPrim.IsA<UsdGeomPointInstancer>()) { return instanceIndex; } // Once more as above in usdPathToUfePathSegment() and // stripInstanceIndexFromUfePath(), a path component at the tail of the // path that begins with a digit is assumed to represent an instance index. const std::string& tailComponentString = path.back().string(); if (stringBeginsWithDigit(path.back().string())) { instanceIndex = std::stoi(tailComponentString); } return instanceIndex; } bool isRootChild(const Ufe::Path& path) { // When called we make the assumption that we are given a valid // path and we are only testing whether or not we are a root child. auto segments = path.getSegments(); if (segments.size() != 2) { TF_RUNTIME_ERROR(kIllegalUSDPath, path.string().c_str()); } return (segments[1].size() == 1); } UsdSceneItem::Ptr createSiblingSceneItem(const Ufe::Path& ufeSrcPath, const std::string& siblingName) { auto ufeSiblingPath = ufeSrcPath.sibling(Ufe::PathComponent(siblingName)); return UsdSceneItem::create(ufeSiblingPath, ufePathToPrim(ufeSiblingPath)); } std::string uniqueName(const TfToken::HashSet& existingNames, std::string srcName) { // Compiled regular expression to find a numerical suffix to a path component. // It searches for any number of characters followed by a single non-numeric, // then one or more digits at end of string. std::regex re("(.*)([^0-9])([0-9]+)$"); std::string base { srcName }; int suffix { 1 }; std::smatch match; if (std::regex_match(srcName, match, re)) { base = match[1].str() + match[2].str(); suffix = std::stoi(match[3].str()) + 1; } std::string dstName = base + std::to_string(suffix); while (existingNames.count(TfToken(dstName)) > 0) { dstName = base + std::to_string(++suffix); } return dstName; } std::string uniqueChildName(const UsdPrim& usdParent, const std::string& name) { if (!usdParent.IsValid()) return std::string(); TfToken::HashSet childrenNames; // The prim GetChildren method used the UsdPrimDefaultPredicate which includes // active prims. We also need the inactive ones. // // const Usd_PrimFlagsConjunction UsdPrimDefaultPredicate = // UsdPrimIsActive && UsdPrimIsDefined && // UsdPrimIsLoaded && !UsdPrimIsAbstract; // Note: removed 'UsdPrimIsLoaded' from the predicate. When it is present the // filter doesn't properly return the inactive prims. UsdView doesn't // use loaded either in _computeDisplayPredicate(). // // Note: our UsdHierarchy uses instance proxies, so we also use them here. for (auto child : usdParent.GetFilteredChildren( UsdTraverseInstanceProxies(UsdPrimIsDefined && !UsdPrimIsAbstract))) { childrenNames.insert(child.GetName()); } std::string childName { name }; if (childrenNames.find(TfToken(childName)) != childrenNames.end()) { childName = uniqueName(childrenNames, childName); } return childName; } bool isAGatewayType(const std::string& mayaNodeType) { // If we've seen this node type before, return the cached value. auto iter = g_GatewayType.find(mayaNodeType); if (iter != std::end(g_GatewayType)) { return iter->second; } // Note: we are calling the MEL interpreter to determine the inherited types, // but we are then caching the result. So MEL will only be called once // for each node type. // Not seen before, so ask Maya. // When the inherited flag is used, the command returns a string array containing // the names of all the base node types inherited by the the given node. MString cmd; MStringArray inherited; bool isInherited = false; cmd.format("nodeType -inherited -isTypeName ^1s", mayaNodeType.c_str()); if (MS::kSuccess == MGlobal::executeCommand(cmd, inherited)) { MString gatewayNodeType(ProxyShapeHandler::gatewayNodeType().c_str()); isInherited = inherited.indexOf(gatewayNodeType) != -1; g_GatewayType[mayaNodeType] = isInherited; } return isInherited; } Ufe::Path dagPathToUfe(const MDagPath& dagPath) { // This function can only create UFE Maya scene items with a single // segment, as it is only given a Dag path as input. return Ufe::Path(dagPathToPathSegment(dagPath)); } Ufe::PathSegment dagPathToPathSegment(const MDagPath& dagPath) { MStatus status; // The Ufe path includes a prepended "world" that the dag path doesn't have size_t numUfeComponents = dagPath.length(&status) + 1; Ufe::PathSegment::Components components; components.resize(numUfeComponents); components[0] = Ufe::PathComponent("world"); MDagPath path = dagPath; // make an editable copy // Pop nodes off the path string one by one, adding them to the correct // position in the components vector as we go. Use i>0 as the stopping // condition because we've already written to element 0 of the components // vector. for (int i = numUfeComponents - 1; i > 0; i--) { MObject node = path.node(&status); if (MS::kSuccess != status) return Ufe::PathSegment("", g_MayaRtid, '|'); std::string componentString(MFnDependencyNode(node).name(&status).asChar()); if (MS::kSuccess != status) return Ufe::PathSegment("", g_MayaRtid, '|'); components[i] = componentString; path.pop(1); } return Ufe::PathSegment(std::move(components), g_MayaRtid, '|'); } UsdTimeCode getTime(const Ufe::Path& path) { // Path should not be empty. if (!TF_VERIFY(!path.empty())) { return UsdTimeCode::Default(); } // Proxy shape node should not be null. auto proxyShape = g_StageMap.proxyShapeNode(path); if (!TF_VERIFY(proxyShape)) { return UsdTimeCode::Default(); } return proxyShape->getTime(); } TfTokenVector getProxyShapePurposes(const Ufe::Path& path) { // Path should not be empty. if (!TF_VERIFY(!path.empty())) { return TfTokenVector(); } // Proxy shape node should not be null. auto proxyShape = g_StageMap.proxyShapeNode(path); if (!TF_VERIFY(proxyShape)) { return TfTokenVector(); } bool renderPurpose, proxyPurpose, guidePurpose; proxyShape->getDrawPurposeToggles(&renderPurpose, &proxyPurpose, &guidePurpose); TfTokenVector purposes; if (renderPurpose) { purposes.emplace_back(UsdGeomTokens->render); } if (proxyPurpose) { purposes.emplace_back(UsdGeomTokens->proxy); } if (guidePurpose) { purposes.emplace_back(UsdGeomTokens->guide); } return purposes; } bool isAttributeEditAllowed(const PXR_NS::UsdAttribute& attr, std::string* errMsg) { if (Editability::isLocked(attr)) { if (errMsg) { *errMsg = TfStringPrintf( "Cannot edit [%s] attribute because its lock metadata is [on].", attr.GetBaseName().GetText()); } return false; } // get the property spec in the edit target's layer const auto& prim = attr.GetPrim(); const auto& stage = prim.GetStage(); const auto& editTarget = stage->GetEditTarget(); if (!isEditTargetLayerModifiable(stage, errMsg)) { return false; } // get the index to edit target layer const auto targetLayerIndex = findLayerIndex(prim, editTarget.GetLayer()); // HS March 22th,2021 // TODO: "Value Clips" are UsdStage-level feature, unknown to Pcp.So if the attribute in // question is affected by Value Clips, we would will likely get the wrong answer. See Spiff // comment for more information : // https://groups.google.com/g/usd-interest/c/xTxFYQA_bRs/m/lX_WqNLoBAAJ // Read on Value Clips here: // https://graphics.pixar.com/usd/docs/api/_usd__page__value_clips.html // get the strength-ordered ( strong-to-weak order ) list of property specs that provide // opinions for this property. const auto& propertyStack = attr.GetPropertyStack(); if (!propertyStack.empty()) { // get the strongest layer that has the attr. auto strongestLayer = attr.GetPropertyStack().front()->GetLayer(); // compare the calculated index between the "attr" and "edit target" layers. if (findLayerIndex(prim, strongestLayer) < targetLayerIndex) { if (errMsg) { *errMsg = TfStringPrintf( "Cannot edit [%s] attribute because there is a stronger opinion in [%s].", attr.GetBaseName().GetText(), strongestLayer->GetDisplayName().c_str()); } return false; } } return true; } bool isAttributeEditAllowed(const UsdPrim& prim, const TfToken& attrName) { std::string errMsg; TF_AXIOM(prim); TF_AXIOM(!attrName.IsEmpty()); UsdGeomXformable xformable(prim); if (xformable) { if (UsdGeomXformOp::IsXformOp(attrName)) { // check for the attribute in XformOpOrderAttr first if (!isAttributeEditAllowed(xformable.GetXformOpOrderAttr(), &errMsg)) { MGlobal::displayError(errMsg.c_str()); return false; } } } // check the attribute itself if (!isAttributeEditAllowed(prim.GetAttribute(attrName), &errMsg)) { MGlobal::displayError(errMsg.c_str()); return false; } return true; } bool isEditTargetLayerModifiable(const PXR_NS::UsdStageWeakPtr stage, std::string* errMsg) { const auto editTarget = stage->GetEditTarget(); const auto editLayer = editTarget.GetLayer(); if (editLayer && !editLayer->PermissionToEdit()) { if (errMsg) { std::string err = TfStringPrintf( "Cannot edit [%s] because it is read-only. Set PermissionToEdit = true to proceed.", editLayer->GetDisplayName().c_str()); *errMsg = err; } return false; } if (stage->IsLayerMuted(editLayer->GetIdentifier())) { if (errMsg) { std::string err = TfStringPrintf( "Cannot edit [%s] because it is muted. Unmute [%s] to proceed.", editLayer->GetDisplayName().c_str(), editLayer->GetDisplayName().c_str()); *errMsg = err; } return false; } return true; } Ufe::Selection removeDescendants(const Ufe::Selection& src, const Ufe::Path& filterPath) { // Filter the src selection, removing items below the filterPath Ufe::Selection dst; for (const auto& item : src) { const auto& itemPath = item->path(); // The filterPath itself is still valid. if (!itemPath.startsWith(filterPath) || itemPath == filterPath) { dst.append(item); } } return dst; } Ufe::Selection recreateDescendants(const Ufe::Selection& src, const Ufe::Path& filterPath) { // If a src selection item starts with the filterPath, re-create it. Ufe::Selection dst; for (const auto& item : src) { const auto& itemPath = item->path(); // The filterPath itself is still valid. if (!itemPath.startsWith(filterPath) || itemPath == filterPath) { dst.append(item); } else { auto recreatedItem = Ufe::Hierarchy::createItem(item->path()); TF_AXIOM(recreatedItem); dst.append(recreatedItem); } } return dst; } } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/lib/usd/ui/layerEditor/stageSelectorWidget.cpp // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "stageSelectorWidget.h" #include "qtUtils.h" #include "sessionState.h" #include "stringResources.h" #include <pxr/pxr.h> #include <pxr/usd/usd/common.h> #include <QtCore/QSignalBlocker> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QLabel> Q_DECLARE_METATYPE(UsdLayerEditor::SessionState::StageEntry); namespace { int getEntryIndexById( UsdLayerEditor::SessionState::StageEntry const& entry, std::vector<UsdLayerEditor::SessionState::StageEntry> const& stages) { auto it = std::find_if( stages.begin(), stages.end(), [entry](UsdLayerEditor::SessionState::StageEntry stageEntry) { return (entry._id == stageEntry._id); }); if (it != stages.end()) { return std::distance(stages.begin(), it); } return -1; } } // namespace namespace UsdLayerEditor { StageSelectorWidget::StageSelectorWidget(SessionState* in_sessionState, QWidget* in_parent) : QWidget(in_parent) { auto mainHLayout = new QHBoxLayout(); QtUtils::initLayoutMargins(mainHLayout); mainHLayout->setSpacing(DPIScale(4)); mainHLayout->addWidget(QtUtils::fixedWidget( new QLabel(StringResources::getAsQString(StringResources::kUsdStage)))); _dropDown = new QComboBox(); mainHLayout->addWidget(_dropDown); connect( _dropDown, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &StageSelectorWidget::selectedIndexChanged); setLayout(mainHLayout); setSessionState(in_sessionState); } void StageSelectorWidget::setSessionState(SessionState* in_sessionState) { _sessionState = in_sessionState; connect( _sessionState, &SessionState::stageListChangedSignal, this, &StageSelectorWidget::updateFromSessionState); connect( _sessionState, &SessionState::currentStageChangedSignal, this, &StageSelectorWidget::sessionStageChanged); connect( _sessionState, &SessionState::stageRenamedSignal, this, &StageSelectorWidget::stageRenamed); connect(_sessionState, &SessionState::stageResetSignal, this, &StageSelectorWidget::stageReset); updateFromSessionState(); } SessionState::StageEntry const StageSelectorWidget::selectedStage() { if (_dropDown->currentIndex() != -1) { auto const& data = _dropDown->currentData(); return data.value<SessionState::StageEntry>(); } return SessionState::StageEntry(); } // repopulates the combo based on the session stage list void StageSelectorWidget::updateFromSessionState(SessionState::StageEntry const& entryToSelect) { QSignalBlocker blocker(_dropDown); _dropDown->clear(); auto allStages = _sessionState->allStages(); for (auto const& stageEntry : allStages) { _dropDown->addItem( QString(stageEntry._displayName.c_str()), QVariant::fromValue(stageEntry)); } if (!entryToSelect._stage) { const auto& newEntry = selectedStage(); _sessionState->setStageEntry(newEntry); } else { _sessionState->setStageEntry(entryToSelect); } } // called when combo value is changed by user void StageSelectorWidget::selectedIndexChanged(int index) { _internalChange = true; _sessionState->setStageEntry(selectedStage()); _internalChange = false; } // handles when someone else changes the current stage // but also called when when do it ourselves void StageSelectorWidget::sessionStageChanged() { if (!_internalChange) { auto index = getEntryIndexById(_sessionState->stageEntry(), _sessionState->allStages()); if (index != -1) { QSignalBlocker blocker(_dropDown); _dropDown->setCurrentIndex(index); } } } void StageSelectorWidget::stageRenamed(SessionState::StageEntry const& renamedEntry) { auto index = getEntryIndexById(renamedEntry, _sessionState->allStages()); if (index != -1) { _dropDown->setItemText(index, renamedEntry._displayName.c_str()); _dropDown->setItemData(index, QVariant::fromValue(renamedEntry)); } } void StageSelectorWidget::stageReset(SessionState::StageEntry const& entry) { // Individual combo box entries have a short display name and a reference to a stage, // which is not a unique combination. By construction the combo box indices do line // up with the SessionState StageEntry vector though, so in the case of resetting // a proxy we will find the matching full proxy path in that vector and use its index // to update the combo box. auto count = _dropDown->count(); if (count <= 0) { return; } auto index = getEntryIndexById(entry, _sessionState->allStages()); if (index >= 0 && index < count) { _dropDown->setItemData(index, QVariant::fromValue(entry)); } } } // namespace UsdLayerEditor <file_sep>/plugin/al/plugin/AL_USDMayaTestPlugin/py/testLayerManager.py #!/usr/bin/env python # # Copyright 2020 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import tempfile import unittest from maya import cmds from AL.usdmaya import ProxyShape import fixturesUtils class TestLayerManagerSerialisation(unittest.TestCase): """Test cases for layer manager serialisation and deserialisation""" app = 'maya' def setUp(self): """Export some sphere geometry as .usda, and import into a new Maya scene.""" cmds.file(force=True, new=True) cmds.loadPlugin("AL_USDMayaPlugin", quiet=True) self.assertTrue(cmds.pluginInfo("AL_USDMayaPlugin", query=True, loaded=True)) _tmpfile = tempfile.NamedTemporaryFile(delete=False, suffix=".usda") _tmpfile.close() self._usdaFile = _tmpfile.name # Ensure sphere geometry exists self._sphere = cmds.polySphere(constructionHistory=False, name="sphere")[0] cmds.select(self._sphere) # Export, new scene, import cmds.file(self._usdaFile, exportSelected=True, force=True, type="AL usdmaya export") cmds.file(force=True, new=True) self._proxyName = cmds.AL_usdmaya_ProxyShapeImport(file=self._usdaFile)[0] # Ensure proxy exists self.assertIsNotNone(self._proxyName) # Store stage proxy = ProxyShape.getByName(self._proxyName) self._stage = proxy.getUsdStage() def tearDown(self): """Unload plugin, new Maya scene, reset class member variables.""" cmds.file(force=True, new=True) cmds.unloadPlugin("AL_USDMayaPlugin", force=True) self._stage = None self._sphere = None self._proxyName = None if os.path.isfile(self._usdaFile): os.remove(self._usdaFile) def test_editTargetSerialisation(self): """ As long as we set an editTarget and it ends updirty, it should be serialised when we save Maya scene, and it should be reloadable by SdfLayer::Reload() """ self.assertTrue(self._stage) self._stage.SetEditTarget(self._stage.GetRootLayer()) newPrimPath = "/ChangeInRoot" self._stage.DefinePrim(newPrimPath, "xform") self._stage.SetEditTarget(self._stage.GetSessionLayer()) _tmpMayafile = tempfile.NamedTemporaryFile(delete=True, suffix=".ma") _tmpMayafile.close() cmds.file(rename=_tmpMayafile.name) cmds.file(save=True, force=True) cmds.file(new=True, force=True) cmds.file(_tmpMayafile.name, open=True) self.assertIsNotNone(self._proxyName) ps = ProxyShape.getByName(self._proxyName) self.assertTrue(ps) stage = ps.getUsdStage() self.assertTrue(stage) self.assertTrue(stage.GetPrimAtPath(newPrimPath)) self.assertTrue(stage.GetRootLayer().Reload()) self.assertFalse(stage.GetPrimAtPath(newPrimPath)) os.remove(_tmpMayafile.name) def test_sessionLayerSerialisation(self): """ A clean session layer should not be serialised on Maya scene save, nor we get any complain form usdMaya on Maya scene reopen. A dirty session layer should be serialised correctly on Maya scene save, and we should get it deserialised on Maya scene reopen. We should also be able to reload on session layer to clear it. """ self.assertTrue(self._stage) self._stage.SetEditTarget(self._stage.GetSessionLayer()) # Save the scene with clean session layer: _tmpMayafile = tempfile.NamedTemporaryFile(delete=True, suffix=".ma") _tmpMayafile.close() cmds.file(rename=_tmpMayafile.name) cmds.file(save=True, force=True) cmds.file(new=True, force=True) cmds.file(_tmpMayafile.name, open=True) self.assertFalse(cmds.getAttr('%s.sessionLayerName' % self._proxyName)) os.remove(_tmpMayafile.name) ps = ProxyShape.getByName(self._proxyName) self.assertTrue(ps) stage = ps.getUsdStage() # Make session layer dirty and save the scene: stage.SetEditTarget(stage.GetSessionLayer()) newPrimPath = "/ChangeInSession" stage.DefinePrim(newPrimPath, "xform") _tmpMayafile = tempfile.NamedTemporaryFile(delete=True, suffix=".ma") _tmpMayafile.close() cmds.file(rename=_tmpMayafile.name) cmds.file(save=True, force=True) cmds.file(new=True, force=True) cmds.file(_tmpMayafile.name, open=True) self.assertTrue(cmds.getAttr('%s.sessionLayerName' % self._proxyName)) ps = ProxyShape.getByName(self._proxyName) self.assertTrue(ps) stage = ps.getUsdStage() self.assertTrue(stage) self.assertTrue(stage.GetPrimAtPath(newPrimPath)) self.assertTrue(stage.GetSessionLayer().Reload()) self.assertFalse(stage.GetPrimAtPath(newPrimPath)) os.remove(_tmpMayafile.name) if __name__ == '__main__': fixturesUtils.runTests(globals())<file_sep>/test/lib/mayaUsd/nodes/testLayerManagerSerialization.py #!/usr/bin/env mayapy # # Copyright 2021 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from sys import prefix from maya import cmds from maya import standalone from mayaUsd import lib as mayaUsdLib import fixturesUtils import os import tempfile import unittest from distutils.dir_util import copy_tree import shutil import usdUtils import mayaUtils import ufeUtils from mayaUtils import createProxyAndStage, createProxyFromFile import ufe import mayaUsd.ufe class testLayerManagerSerialization(unittest.TestCase): @classmethod def setUpClass(cls): cls._inputPath = fixturesUtils.setUpClass(__file__) @classmethod def tearDownClass(cls): standalone.uninitialize() def setupEmptyScene(self): self._currentTestDir = tempfile.mkdtemp(prefix='LayerManagerTest') self._tempMayaFile = os.path.join( self._currentTestDir, 'SerializationTest.ma') cmds.file(rename=self._tempMayaFile) def copyTestFilesAndMakeEdits(self): self._currentTestDir = tempfile.mkdtemp(prefix='LayerManagerTest') fromDirectory = os.path.join( self._inputPath, 'LayerManagerSerializationTest') copy_tree(fromDirectory, self._currentTestDir) self._tempMayaFile = os.path.join( self._currentTestDir, 'SerializationTest.ma') self._rootUsdFile = os.path.join( self._currentTestDir, 'SerializationTest.usda') self._test1File = os.path.join( self._currentTestDir, 'SerializationTest_1.usda') self._test1_1File = os.path.join( self._currentTestDir, 'SerializationTest_1_1.usda') self._test2File = os.path.join( self._currentTestDir, 'SerializationTest_2.usda') self._test2_1File = os.path.join( self._currentTestDir, 'SerializationTest_2_1.usda') cmds.file(self._tempMayaFile, open=True, force=True) stage = mayaUsd.ufe.getStage( "|SerializationTest|SerializationTestShape") stack = stage.GetLayerStack() self.assertEqual(6, len(stack)) stage.SetEditTarget(stage.GetRootLayer()) newPrimPath = "/ChangeInRoot" stage.DefinePrim(newPrimPath, "xform") stage.SetEditTarget(stack[2]) newPrimPath = "/ChangeInLayer_1_1" stage.DefinePrim(newPrimPath, "xform") stage.SetEditTarget(stack[0]) newPrimPath = "/ChangeInSessionLayer" stage.DefinePrim(newPrimPath, "xform") stage = mayaUsd.ufe.getStage( "|SerializationTest|SerializationTestShape") stack = stage.GetLayerStack() self.assertEqual(6, len(stack)) cleanCount = 0 dirtyCount = 0 for l in stack: if l.dirty: dirtyCount += 1 else: cleanCount += 1 self.assertEqual(3, dirtyCount) self.assertEqual(3, cleanCount) return stage def confirmEditsSavedStatus(self, fileBackedSavedStatus, sessionSavedStatus): cmds.file(new=True, force=True) proxyNode, stage = createProxyFromFile(self._rootUsdFile) newPrimPath = "/ChangeInRoot" self.assertEqual( fileBackedSavedStatus, stage.GetPrimAtPath(newPrimPath).IsValid()) newPrimPath = "/ChangeInLayer_1_1" self.assertEqual( fileBackedSavedStatus, stage.GetPrimAtPath(newPrimPath).IsValid()) newPrimPath = "/ChangeInSessionLayer" self.assertEqual( sessionSavedStatus, stage.GetPrimAtPath(newPrimPath).IsValid()) @unittest.skipUnless(ufeUtils.ufeFeatureSetVersion() >= 2, 'testSaveAllToMaya is available only in UFE v2 or greater.') def testSaveAllToMaya(self): ''' Verify that all USD edits are save into the Maya file. ''' stage = self.copyTestFilesAndMakeEdits() cmds.optionVar(intValue=('mayaUsd_SerializedUsdEditsLocation', 2)) cmds.file(save=True, force=True) cmds.file(new=True, force=True) cmds.file(self._tempMayaFile, open=True) stage = mayaUsd.ufe.getStage( "|SerializationTest|SerializationTestShape") stack = stage.GetLayerStack() self.assertEqual(6, len(stack)) newPrimPath = "/ChangeInRoot" self.assertTrue(stage.GetPrimAtPath(newPrimPath)) newPrimPath = "/ChangeInLayer_1_1" self.assertTrue(stage.GetPrimAtPath(newPrimPath)) newPrimPath = "/ChangeInSessionLayer" self.assertTrue(stage.GetPrimAtPath(newPrimPath)) self.confirmEditsSavedStatus(False, False) shutil.rmtree(self._currentTestDir) @unittest.skipUnless(ufeUtils.ufeFeatureSetVersion() >= 2, 'testSaveAllToUsd is available only in UFE v2 or greater.') def testSaveAllToUsd(self): ''' Verify that all USD edits are saved back to the original .usd files ''' stage = self.copyTestFilesAndMakeEdits() cmds.optionVar(intValue=('mayaUsd_SerializedUsdEditsLocation', 1)) cmds.file(save=True, force=True) cmds.file(new=True, force=True) cmds.file(self._tempMayaFile, open=True) stage = mayaUsd.ufe.getStage( "|SerializationTest|SerializationTestShape") stack = stage.GetLayerStack() self.assertEqual(6, len(stack)) newPrimPath = "/ChangeInRoot" self.assertTrue(stage.GetPrimAtPath(newPrimPath)) newPrimPath = "/ChangeInLayer_1_1" self.assertTrue(stage.GetPrimAtPath(newPrimPath)) newPrimPath = "/ChangeInSessionLayer" self.assertFalse(stage.GetPrimAtPath(newPrimPath)) self.confirmEditsSavedStatus(True, False) shutil.rmtree(self._currentTestDir) @unittest.skipUnless(ufeUtils.ufeFeatureSetVersion() >= 2, 'testIgnoreAllUsd is available only in UFE v2 or greater.') def testIgnoreAllUsd(self): ''' Verify that all USD edits are ignored ''' stage = self.copyTestFilesAndMakeEdits() cmds.optionVar(intValue=('mayaUsd_SerializedUsdEditsLocation', 3)) cmds.file(save=True, force=True) cmds.file(new=True, force=True) cmds.file(self._tempMayaFile, open=True) stage = mayaUsd.ufe.getStage( "|SerializationTest|SerializationTestShape") stack = stage.GetLayerStack() self.assertEqual(6, len(stack)) newPrimPath = "/ChangeInRoot" self.assertFalse(stage.GetPrimAtPath(newPrimPath)) newPrimPath = "/ChangeInLayer_1_1" self.assertFalse(stage.GetPrimAtPath(newPrimPath)) newPrimPath = "/ChangeInSessionLayer" self.assertFalse(stage.GetPrimAtPath(newPrimPath)) self.confirmEditsSavedStatus(False, False) shutil.rmtree(self._currentTestDir) @unittest.skipUnless(ufeUtils.ufeFeatureSetVersion() >= 2, 'testAnonymousRootToMaya is available only in UFE v2 or greater.') def testAnonymousRootToMaya(self): self.setupEmptyScene() import mayaUsd_createStageWithNewLayer proxyShape = mayaUsd_createStageWithNewLayer.createStageWithNewLayer() proxyShapePath = ufe.PathString.path(proxyShape) stage = mayaUsd.ufe.getStage(str(proxyShapePath)) newPrimPath = "/ChangeInRoot" stage.DefinePrim(newPrimPath, "xform") self.assertTrue(stage.GetPrimAtPath(newPrimPath).IsValid()) stage.SetEditTarget(stage.GetSessionLayer()) newSessionsPrimPath = "/ChangeInSession" stage.DefinePrim(newSessionsPrimPath, "xform") self.assertTrue(stage.GetPrimAtPath(newSessionsPrimPath).IsValid()) cmds.optionVar(intValue=('mayaUsd_SerializedUsdEditsLocation', 2)) cmds.file(save=True, force=True, type='mayaAscii') cmds.file(new=True, force=True) cmds.file(self._tempMayaFile, open=True) stage = mayaUsd.ufe.getStage('|stage1|stageShape1') self.assertTrue(stage.GetPrimAtPath(newPrimPath).IsValid()) self.assertTrue(stage.GetPrimAtPath(newSessionsPrimPath).IsValid()) shutil.rmtree(self._currentTestDir) @unittest.skipUnless(ufeUtils.ufeFeatureSetVersion() >= 2, 'testAnonymousRootToMaya is available only in UFE v2 or greater.') def testAnonymousRootToUsd(self): self.setupEmptyScene() import mayaUsd_createStageWithNewLayer proxyShape = mayaUsd_createStageWithNewLayer.createStageWithNewLayer() proxyShapePath = ufe.PathString.path(proxyShape) stage = mayaUsd.ufe.getStage(str(proxyShapePath)) newPrimPath = "/ChangeInRoot" stage.DefinePrim(newPrimPath, "xform") self.assertTrue(stage.GetPrimAtPath(newPrimPath).IsValid()) stage.SetEditTarget(stage.GetSessionLayer()) newSessionsPrimPath = "/ChangeInSession" stage.DefinePrim(newSessionsPrimPath, "xform") self.assertTrue(stage.GetPrimAtPath(newSessionsPrimPath).IsValid()) cmds.optionVar(intValue=('mayaUsd_SerializedUsdEditsLocation', 1)) msg = ("Session Layer before: " + stage.GetSessionLayer().identifier) stage = None cmds.file(save=True, force=True, type='mayaAscii') cmds.file(new=True, force=True) cmds.file(self._tempMayaFile, open=True) stage = mayaUsdLib.GetPrim('|stage1|stageShape1').GetStage() msg += (" Session Layer after: " + stage.GetSessionLayer().identifier) self.assertTrue(stage.GetPrimAtPath(newPrimPath).IsValid()) # Temporarily disabling this check while investigating why it can fail on certain build combinations # self.assertFalse(stage.GetPrimAtPath( # newSessionsPrimPath).IsValid(), msg) cmds.file(new=True, force=True) shutil.rmtree(self._currentTestDir) if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/lib/usd/ui/layerEditor/saveLayersDialog.cpp #include "saveLayersDialog.h" #include "generatedIconButton.h" #include "layerTreeItem.h" #include "layerTreeModel.h" #include "pathChecker.h" #include "qtUtils.h" #include "sessionState.h" #include "stringResources.h" #include "warningDialogs.h" #include <mayaUsd/base/tokens.h> #include <mayaUsd/fileio/jobs/jobArgs.h> #include <mayaUsd/listeners/notice.h> #include <mayaUsd/utils/utilSerialization.h> #include <pxr/usd/sdf/layer.h> #include <maya/MDagPathArray.h> #include <maya/MGlobal.h> #include <maya/MQtUtil.h> #include <maya/MString.h> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtCore/QString> #include <QtGui/QFontMetrics> #include <QtWidgets/QApplication> #include <QtWidgets/QBoxLayout> #include <string> #if defined(WANT_UFE_BUILD) #include <mayaUsd/ufe/Utils.h> #endif PXR_NAMESPACE_USING_DIRECTIVE namespace { template <typename T> void moveAppendVector(std::vector<T>& src, std::vector<T>& dst) { if (dst.empty()) { dst = std::move(src); } else { dst.reserve(dst.size() + src.size()); std::move(std::begin(src), std::end(src), std::back_inserter(dst)); src.clear(); } } using namespace UsdLayerEditor; void getDialogMessages(const int nbStages, const int nbAnonLayers, QString& msg1, QString& msg2) { MString msg, strNbStages, strNbAnonLayers; strNbStages = nbStages; strNbAnonLayers = nbAnonLayers; msg.format( StringResources::getAsMString(StringResources::kToSaveTheStageSaveAnonym), strNbStages, strNbAnonLayers); msg1 = MQtUtil::toQString(msg); msg.format( StringResources::getAsMString(StringResources::kToSaveTheStageSaveFiles), strNbStages); msg2 = MQtUtil::toQString(msg); } class AnonLayerPathEdit : public QLineEdit { public: AnonLayerPathEdit(QWidget* in_parent) : QLineEdit(in_parent) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); } QSize sizeHint() const override { auto hint = QLineEdit::sizeHint(); if (!text().isEmpty()) { QFontMetrics appFont = QApplication::fontMetrics(); int pathWidth = appFont.boundingRect(text()).width(); hint.setWidth(pathWidth + DPIScale(100)); } return hint; } }; } // namespace namespace UsdLayerEditor { class SaveLayersDialog; } class SaveLayerPathRow : public QWidget { public: SaveLayerPathRow( SaveLayersDialog* in_parent, const std::pair<SdfLayerRefPtr, MayaUsd::utils::LayerParent>& in_layerPair); QString layerDisplayName() const; QString absolutePath() const; QString pathToSaveAs() const; void setAbsolutePath(const std::string& path); protected: void onOpenBrowser(); void onTextChanged(const QString& text); public: QString _absolutePath; SaveLayersDialog* _parent { nullptr }; std::pair<SdfLayerRefPtr, MayaUsd::utils::LayerParent> _layerPair; QLabel* _label { nullptr }; QLineEdit* _pathEdit { nullptr }; QAbstractButton* _openBrowser { nullptr }; }; SaveLayerPathRow::SaveLayerPathRow( SaveLayersDialog* in_parent, const std::pair<SdfLayerRefPtr, MayaUsd::utils::LayerParent>& in_layerPair) : QWidget(in_parent) , _parent(in_parent) , _layerPair(in_layerPair) { auto gridLayout = new QGridLayout(); QtUtils::initLayoutMargins(gridLayout); // Since this is an anonymous layer, it should only be associated with a single stage. std::string stageName; const auto& stageLayers = in_parent->stageLayers(); if (TF_VERIFY(1 == stageLayers.count(_layerPair.first))) { auto search = stageLayers.find(_layerPair.first); stageName = search->second; } QString displayName = _layerPair.first->GetDisplayName().c_str(); _label = new QLabel(displayName); _label->setToolTip(in_parent->buildTooltipForLayer(_layerPair.first)); gridLayout->addWidget(_label, 0, 0); _absolutePath = MayaUsd::utils::generateUniqueFileName(stageName).c_str(); QFileInfo fileInfo(_absolutePath); QString suggestedFullPath = fileInfo.absoluteFilePath(); _pathEdit = new AnonLayerPathEdit(this); _pathEdit->setText(suggestedFullPath); connect(_pathEdit, &QLineEdit::textChanged, this, &SaveLayerPathRow::onTextChanged); gridLayout->addWidget(_pathEdit, 0, 1); QIcon icon = utils->createIcon(":/fileOpen.png"); _openBrowser = new GeneratedIconButton(this, icon); gridLayout->addWidget(_openBrowser, 0, 2); connect(_openBrowser, &QAbstractButton::clicked, this, &SaveLayerPathRow::onOpenBrowser); setLayout(gridLayout); setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum); } QString SaveLayerPathRow::layerDisplayName() const { return _label->text(); } QString SaveLayerPathRow::absolutePath() const { return _absolutePath; } QString SaveLayerPathRow::pathToSaveAs() const { return _absolutePath; } void SaveLayerPathRow::setAbsolutePath(const std::string& path) { _absolutePath = path.c_str(); _pathEdit->setText(_absolutePath); _pathEdit->setEnabled(true); } void SaveLayerPathRow::onOpenBrowser() { std::string fileName; if (SaveLayersDialog::saveLayerFilePathUI(fileName)) { setAbsolutePath(fileName); } } void SaveLayerPathRow::onTextChanged(const QString& text) { _absolutePath = text; } class SaveLayerPathRowArea : public QScrollArea { public: SaveLayerPathRowArea(QWidget* parent = nullptr) : QScrollArea(parent) { setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); } QSize sizeHint() const override { QSize hint; if (widget() && widget()->layout()) { auto l = widget()->layout(); for (int i = 0; i < l->count(); ++i) { QWidget* w = l->itemAt(i)->widget(); QSize rowHint = w->sizeHint(); if (hint.width() < rowHint.width()) { hint.setWidth(rowHint.width()); } if (0 < rowHint.height()) hint.rheight() += rowHint.height(); } // Extra padding (enough for 3.5 lines). hint.rwidth() += 100; if (hint.height() < DPIScale(120)) hint.setHeight(DPIScale(120)); } return hint; } }; // // Main Save All Layers Dialog UI // namespace UsdLayerEditor { #if defined(WANT_UFE_BUILD) SaveLayersDialog::SaveLayersDialog(QWidget* in_parent, const MDagPathArray& proxyShapes) : QDialog(in_parent) , _sessionState(nullptr) { MString msg, nbStages; nbStages = proxyShapes.length(); msg.format(StringResources::getAsMString(StringResources::kSaveXStages), nbStages); setWindowTitle(MQtUtil::toQString(msg)); // For each stage collect the layers to save. for (const auto& shape : proxyShapes) { getLayersToSave(shape.fullPathName().asChar(), shape.partialPathName().asChar()); } QString msg1, msg2; getDialogMessages( static_cast<int>(proxyShapes.length()), static_cast<int>(_anonLayerPairs.size()), msg1, msg2); buildDialog(msg1, msg2); } #endif SaveLayersDialog::SaveLayersDialog(SessionState* in_sessionState, QWidget* in_parent) : QDialog(in_parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint) , _sessionState(in_sessionState) { MString msg; QString dialogTitle = StringResources::getAsQString(StringResources::kSaveStage); if (TF_VERIFY(nullptr != _sessionState)) { auto stageEntry = _sessionState->stageEntry(); std::string stageName = stageEntry._displayName; msg.format(StringResources::getAsMString(StringResources::kSaveName), stageName.c_str()); dialogTitle = MQtUtil::toQString(msg); getLayersToSave(stageEntry._proxyShapePath, stageName); } setWindowTitle(dialogTitle); QString msg1, msg2; getDialogMessages(1, static_cast<int>(_anonLayerPairs.size()), msg1, msg2); buildDialog(msg1, msg2); } SaveLayersDialog ::~SaveLayersDialog() { QApplication::restoreOverrideCursor(); } void SaveLayersDialog::getLayersToSave(const std::string& proxyPath, const std::string& stageName) { // Get the layers to save for this stage. MayaUsd::utils::stageLayersToSave stageLayersToSave; MayaUsd::utils::getLayersToSaveFromProxy(proxyPath, stageLayersToSave); // Keep track of all the layers for this particular stage. for (const auto& layerPairs : stageLayersToSave._anonLayers) { _stageLayerMap.emplace(std::make_pair(layerPairs.first, stageName)); } for (const auto& dirtyLayer : stageLayersToSave._dirtyFileBackedLayers) { _stageLayerMap.emplace(std::make_pair(dirtyLayer, stageName)); } // Add these layers to save to our member var for reference later. // Note: we use a set for the dirty file back layers because they // can come from multiple stages, but we only want them to // appear once in the dialog. moveAppendVector(stageLayersToSave._anonLayers, _anonLayerPairs); _dirtyFileBackedLayers.insert( std::begin(stageLayersToSave._dirtyFileBackedLayers), std::end(stageLayersToSave._dirtyFileBackedLayers)); } void SaveLayersDialog::buildDialog(const QString& msg1, const QString& msg2) { const int mainMargin = DPIScale(20); // Ok/Cancel button area auto buttonsLayout = new QHBoxLayout(); QtUtils::initLayoutMargins(buttonsLayout, 0); buttonsLayout->addStretch(); auto okButton = new QPushButton(StringResources::getAsQString(StringResources::kSaveStages), this); connect(okButton, &QPushButton::clicked, this, &SaveLayersDialog::onSaveAll); okButton->setDefault(true); auto cancelButton = new QPushButton(StringResources::getAsQString(StringResources::kCancel), this); connect(cancelButton, &QPushButton::clicked, this, &SaveLayersDialog::onCancel); buttonsLayout->addWidget(okButton); buttonsLayout->addWidget(cancelButton); const bool haveAnonLayers { !_anonLayerPairs.empty() }; const bool haveFileBackedLayers { !_dirtyFileBackedLayers.empty() }; SaveLayerPathRowArea* anonScrollArea { nullptr }; SaveLayerPathRowArea* fileScrollArea { nullptr }; const int margin { DPIScale(10) }; // Anonymous layers. if (haveAnonLayers) { auto anonLayout = new QVBoxLayout(); anonLayout->setContentsMargins(margin, margin, margin, 0); anonLayout->setSpacing(DPIScale(8)); anonLayout->setAlignment(Qt::AlignTop); for (auto iter = _anonLayerPairs.cbegin(); iter != _anonLayerPairs.cend(); ++iter) { auto row = new SaveLayerPathRow(this, (*iter)); anonLayout->addWidget(row); } _anonLayersWidget = new QWidget(); _anonLayersWidget->setLayout(anonLayout); // Setup the scroll area for anonymous layers. anonScrollArea = new SaveLayerPathRowArea(); anonScrollArea->setFrameShape(QFrame::NoFrame); anonScrollArea->setBackgroundRole(QPalette::Midlight); anonScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); anonScrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); anonScrollArea->setWidget(_anonLayersWidget); anonScrollArea->setWidgetResizable(true); } // File backed layers static const MString kConfirmExistingFileSave = MayaUsdOptionVars->ConfirmExistingFileSave.GetText(); const bool showFileOverrideSection = MGlobal::optionVarExists(kConfirmExistingFileSave) && MGlobal::optionVarIntValue(kConfirmExistingFileSave) != 0; if (showFileOverrideSection && haveFileBackedLayers) { auto fileLayout = new QVBoxLayout(); fileLayout->setContentsMargins(margin, margin, margin, 0); fileLayout->setSpacing(DPIScale(8)); fileLayout->setAlignment(Qt::AlignTop); for (const auto& dirtyLayer : _dirtyFileBackedLayers) { auto row = new QLabel(dirtyLayer->GetRealPath().c_str(), this); row->setToolTip(buildTooltipForLayer(dirtyLayer)); fileLayout->addWidget(row); } _fileLayersWidget = new QWidget(); _fileLayersWidget->setLayout(fileLayout); // Setup the scroll area for dirty file backed layers. fileScrollArea = new SaveLayerPathRowArea(); fileScrollArea->setFrameShape(QFrame::NoFrame); fileScrollArea->setBackgroundRole(QPalette::Midlight); fileScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); fileScrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); fileScrollArea->setWidget(_fileLayersWidget); fileScrollArea->setWidgetResizable(true); } // Create the main layout for the dialog. auto topLayout = new QVBoxLayout(); QtUtils::initLayoutMargins(topLayout, mainMargin); topLayout->setSpacing(DPIScale(8)); if (nullptr != anonScrollArea) { // Add the first message. if (!msg1.isEmpty()) { auto dialogMessage = new QLabel(msg1); topLayout->addWidget(dialogMessage); } // Then add the first scroll area (containing the anonymous layers) topLayout->addWidget(anonScrollArea); // If we also have dirty file backed layers, add a separator. if (showFileOverrideSection && haveFileBackedLayers) { auto lineSep = new QFrame(); lineSep->setFrameShape(QFrame::HLine); lineSep->setLineWidth(DPIScale(1)); QPalette pal(lineSep->palette()); pal.setColor(QPalette::Base, QColor("#575757")); lineSep->setPalette(pal); lineSep->setBackgroundRole(QPalette::Base); topLayout->addWidget(lineSep); } } if (nullptr != fileScrollArea) { // Add the second message. if (!msg2.isEmpty()) { auto dialogMessage = new QLabel(msg2); topLayout->addWidget(dialogMessage); } // Add the second scroll area (containing the file backed layers). topLayout->addWidget(fileScrollArea); } // Finally add the buttons. auto buttonArea = new QWidget(this); buttonArea->setLayout(buttonsLayout); buttonArea->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); topLayout->addWidget(buttonArea); setLayout(topLayout); setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); setSizeGripEnabled(true); QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor)); } QString SaveLayersDialog::buildTooltipForLayer(SdfLayerRefPtr layer) { if (nullptr == layer) return ""; // Disable word wrapping on tooltip. QString tooltip = "<p style='white-space:pre'>"; tooltip += StringResources::getAsQString(StringResources::kUsedInStagesTooltip); auto range = _stageLayerMap.equal_range(layer); bool needComma = false; for (auto it = range.first; it != range.second; ++it) { if (needComma) tooltip.append(", "); tooltip.append(it->second.c_str()); needComma = true; } return tooltip; } void SaveLayersDialog::onSaveAll() { if (!okToSave()) { return; } int i, count; std::string newRoot; _newPaths.clear(); _problemLayers.clear(); _emptyLayers.clear(); // The anonymous layer section in the dialog can be empty. if (nullptr != _anonLayersWidget) { QLayout* anonLayout = _anonLayersWidget->layout(); for (i = 0, count = anonLayout->count(); i < count; ++i) { auto row = dynamic_cast<SaveLayerPathRow*>(anonLayout->itemAt(i)->widget()); if (!row || !row->_layerPair.first) continue; QString path = row->pathToSaveAs(); if (!path.isEmpty()) { auto sdfLayer = row->_layerPair.first; auto parent = row->_layerPair.second; auto qFileName = row->absolutePath(); // If the qFileName is a relative path, compute the absolute path from the scene // folder otherwise, USD will use a path relative the current working directory. if (QDir::isRelativePath(qFileName)) { QDir dir(MayaUsd::utils::getSceneFolder().c_str()); qFileName = dir.absoluteFilePath(qFileName); } auto sFileName = qFileName.toStdString(); auto newLayer = MayaUsd::utils::saveAnonymousLayer(sdfLayer, sFileName, parent); if (newLayer) { _newPaths.append(QString::fromStdString(sdfLayer->GetDisplayName())); _newPaths.append(qFileName); } else { _problemLayers.append(QString::fromStdString(sdfLayer->GetDisplayName())); _problemLayers.append(qFileName); } } else { _emptyLayers.append(row->layerDisplayName()); } } } accept(); } void SaveLayersDialog::onCancel() { reject(); } bool SaveLayersDialog::okToSave() { // Files can have the same file names in complicated ways, with one file having two copies, // another three, so we keep the exact number of copies per file path. QMap<QString, int> alreadySeenPaths; QStringList existingFiles; // The anonymous layer section in the dialog can be empty. if (nullptr != _anonLayersWidget) { QLayout* anonLayout = _anonLayersWidget->layout(); for (int i = 0, count = anonLayout->count(); i < count; ++i) { auto row = dynamic_cast<SaveLayerPathRow*>(anonLayout->itemAt(i)->widget()); if (nullptr == row) continue; QString path = row->pathToSaveAs(); if (!path.isEmpty()) { if (alreadySeenPaths.count(path) > 0) { alreadySeenPaths[path] += 1; } else { alreadySeenPaths[path] = 1; } QFileInfo fInfo(path); if (fInfo.exists()) { existingFiles.append(path); } } } } QStringList identicalFiles; int identicalCount = 0; for (const auto& path : alreadySeenPaths.keys()) { const int count = alreadySeenPaths[path]; if (count > 1) { identicalFiles.append(path); identicalCount += count; } } if (identicalCount > 0) { MString errorMsg; MString count; count = identicalCount; errorMsg.format( StringResources::getAsMString(StringResources::kSaveAnonymousIdenticalFiles), count); warningDialog( StringResources::getAsQString(StringResources::kSaveAnonymousIdenticalFilesTitle), MQtUtil::toQString(errorMsg), &identicalFiles, QMessageBox::Icon::Critical); return false; } if (!existingFiles.isEmpty()) { MString confirmMsg; MString count; count = existingFiles.length(); confirmMsg.format( StringResources::getAsMString(StringResources::kSaveAnonymousConfirmOverwrite), count); return (confirmDialog( StringResources::getAsQString(StringResources::kSaveAnonymousConfirmOverwriteTitle), MQtUtil::toQString(confirmMsg), &existingFiles, nullptr, QMessageBox::Icon::Warning)); } return true; } /*static*/ bool SaveLayersDialog::saveLayerFilePathUI(std::string& out_filePath) { MString fileSelected; MGlobal::executeCommand( MString("UsdLayerEditor_SaveLayerFileDialog"), fileSelected, /*display*/ true, /*undo*/ false); if (fileSelected.length() == 0) return false; out_filePath = fileSelected.asChar(); return true; } } // namespace UsdLayerEditor <file_sep>/lib/usd/translators/jointWriter.cpp // // Copyright 2018 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "jointWriter.h" #include <mayaUsd/base/debugCodes.h> #include <mayaUsd/fileio/primWriter.h> #include <mayaUsd/fileio/primWriterRegistry.h> #include <mayaUsd/fileio/translators/translatorSkel.h> #include <mayaUsd/fileio/translators/translatorUtil.h> #include <mayaUsd/fileio/utils/adaptor.h> #include <mayaUsd/fileio/utils/jointWriteUtils.h> #include <mayaUsd/fileio/utils/writeUtil.h> #include <mayaUsd/fileio/writeJobContext.h> #include <mayaUsd/utils/util.h> #include <pxr/base/gf/matrix4d.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/base/tf/staticTokens.h> #include <pxr/base/tf/token.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/sdf/pathTable.h> #include <pxr/usd/usd/timeCode.h> #include <pxr/usd/usdGeom/xform.h> #include <pxr/usd/usdSkel/animation.h> #include <pxr/usd/usdSkel/bindingAPI.h> #include <pxr/usd/usdSkel/root.h> #include <pxr/usd/usdSkel/skeleton.h> #include <pxr/usd/usdSkel/utils.h> #include <maya/MAnimUtil.h> #include <maya/MDagPath.h> #include <maya/MFnDependencyNode.h> #include <maya/MFnMatrixData.h> #include <maya/MFnTransform.h> #include <maya/MItDag.h> #include <maya/MMatrix.h> #include <maya/MPlug.h> #include <maya/MPlugArray.h> #include <maya/MPxNode.h> #include <maya/MStatus.h> #include <vector> PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_REGISTER_WRITER(joint, PxrUsdTranslators_JointWriter); PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(joint, UsdSkelSkeleton); PxrUsdTranslators_JointWriter::PxrUsdTranslators_JointWriter( const MFnDependencyNode& depNodeFn, const SdfPath& usdPath, UsdMayaWriteJobContext& jobCtx) : UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) , _valid(false) { if (!TF_VERIFY(GetDagPath().isValid())) { return; } const TfToken& exportSkels = _GetExportArgs().exportSkels; if (exportSkels != UsdMayaJobExportArgsTokens->auto_ && exportSkels != UsdMayaJobExportArgsTokens->explicit_) { return; } SdfPath skelPath = UsdMayaJointUtil::getSkeletonPath(GetDagPath(), _GetExportArgs().stripNamespaces); _skel = UsdSkelSkeleton::Define(GetUsdStage(), skelPath); if (!TF_VERIFY(_skel)) { return; } _usdPrim = _skel.GetPrim(); } /// Whether the transform plugs on a transform node are animated. static bool _IsTransformNodeAnimated(const MDagPath& dagPath) { MFnDependencyNode node(dagPath.node()); return UsdMayaUtil::isPlugAnimated(node.findPlug("translateX")) || UsdMayaUtil::isPlugAnimated(node.findPlug("translateY")) || UsdMayaUtil::isPlugAnimated(node.findPlug("translateZ")) || UsdMayaUtil::isPlugAnimated(node.findPlug("rotateX")) || UsdMayaUtil::isPlugAnimated(node.findPlug("rotateY")) || UsdMayaUtil::isPlugAnimated(node.findPlug("rotateZ")) || UsdMayaUtil::isPlugAnimated(node.findPlug("scaleX")) || UsdMayaUtil::isPlugAnimated(node.findPlug("scaleY")) || UsdMayaUtil::isPlugAnimated(node.findPlug("scaleZ")); } /// Gets the world-space rest transform for a single dag path. static GfMatrix4d _GetJointWorldBindTransform(const MDagPath& dagPath) { MFnDagNode dagNode(dagPath); MMatrix restTransformWorld; if (UsdMayaUtil::getPlugMatrix(dagNode, "bindPose", &restTransformWorld)) { return GfMatrix4d(restTransformWorld.matrix); } // NOTE: (yliangsiew) Instead of assuming an identity matrix, we check if the joint is linked to // a corresponding bindPose, and attempt to grab the bind transform matrix there. If it's // _still_ empty, then we assume identity. This catches odd edge cases where a joint is bound, // but its `bindPose` attribute is empty and the `bindPose` node stores the actual bind // transform matrix. MStatus status; MPlug plgMsg = dagNode.findPlug(MPxNode::message, false, &status); if (!status || !plgMsg.isSource()) { return GfMatrix4d(1); } MPlugArray plgsDest; plgMsg.destinations(plgsDest); for (unsigned int i = 0; i < plgsDest.length(); ++i) { MPlug plgDest = plgsDest[i]; MObject curNode = plgDest.node(); if (!curNode.hasFn(MFn::kDagPose)) { continue; } // NOTE: (yliangsiew) We should be connected to a members[x] plug. TF_VERIFY(plgDest.isElement()); unsigned int membersIdx = plgDest.logicalIndex(); MFnDependencyNode fnNode(curNode, &status); CHECK_MSTATUS_AND_RETURN(status, GfMatrix4d(1)); MPlug plgWorldMatrices = fnNode.findPlug("worldMatrix", false, &status); CHECK_MSTATUS_AND_RETURN(status, GfMatrix4d(1)); MPlug plgWorldMatrix = plgWorldMatrices.elementByLogicalIndex(membersIdx); MObject plgWorldMatrixData = plgWorldMatrix.asMObject(); MFnMatrixData fnMatrixData(plgWorldMatrixData, &status); CHECK_MSTATUS_AND_RETURN(status, GfMatrix4d(1)); MMatrix result = fnMatrixData.matrix(); return GfMatrix4d(result.matrix); } return GfMatrix4d(1); } /// Gets world-space bind transforms for all specified dag paths. static VtMatrix4dArray _GetJointWorldBindTransforms( const UsdSkelTopology& topology, const std::vector<MDagPath>& jointDagPaths) { size_t numJoints = jointDagPaths.size(); VtMatrix4dArray worldXforms(numJoints); for (size_t i = 0; i < jointDagPaths.size(); ++i) { worldXforms[i] = _GetJointWorldBindTransform(jointDagPaths[i]); } return worldXforms; } /// Find a dagPose that holds a bind pose for \p dagPath. static MObject _FindBindPose(const MDagPath& dagPath) { MStatus status; MFnDependencyNode depNode(dagPath.node(), &status); CHECK_MSTATUS_AND_RETURN(status, MObject()); MPlug msgPlug = depNode.findPlug("message", &status); MPlugArray outputs; msgPlug.connectedTo(outputs, /*asDst*/ false, /*asSrc*/ true, &status); for (unsigned int i = 0; i < outputs.length(); ++i) { MObject outputNode = outputs[i].node(); if (outputNode.apiType() == MFn::kDagPose) { // dagPose nodes have a 'bindPose' bool that determines whether // or not they represent a bind pose. MFnDependencyNode poseDep(outputNode, &status); MPlug bindPosePlug = poseDep.findPlug("bindPose", &status); if (status) { if (bindPosePlug.asBool()) { return outputNode; } } return outputNode; } } return MObject(); } /// Get the member indices of all objects in \p dagPaths within the /// members array plug of a dagPose. /// Returns true only if all \p dagPaths can be mapped to a dagPose member. static bool _FindDagPoseMembers( const MFnDependencyNode& dagPoseDep, const std::vector<MDagPath>& dagPaths, std::vector<unsigned int>* indices) { MStatus status; MPlug membersPlug = dagPoseDep.findPlug("members", false, &status); CHECK_MSTATUS_AND_RETURN(status, false); // Build a map of dagPath->index. UsdMayaUtil::MObjectHandleUnorderedMap<size_t> pathIndexMap; for (size_t i = 0; i < dagPaths.size(); ++i) { pathIndexMap[MObjectHandle(dagPaths[i].node())] = i; } MPlugArray inputs; size_t numDagPaths = dagPaths.size(); indices->clear(); indices->resize(numDagPaths); std::vector<uint8_t> visitedIndices(numDagPaths, 0); for (unsigned int i = 0; i < membersPlug.numConnectedElements(); ++i) { MPlug memberPlug = membersPlug.connectionByPhysicalIndex(i); memberPlug.connectedTo(inputs, /*asDst*/ true, /*asSrc*/ false); for (unsigned int j = 0; j < inputs.length(); ++j) { MObjectHandle connNode(inputs[j].node()); auto it = pathIndexMap.find(connNode); if (it != pathIndexMap.end()) { (*indices)[it->second] = memberPlug.logicalIndex(); visitedIndices[it->second] = 1; } } } // Validate that all of the input dagPaths are members. for (size_t i = 0; i < visitedIndices.size(); ++i) { uint8_t visited = visitedIndices[i]; if (visited != 1) { TF_WARN( "Node '%s' is not a member of dagPose '%s'.", MFnDependencyNode(dagPaths[i].node()).name().asChar(), dagPoseDep.name().asChar()); return false; } } return true; } bool _GetLocalTransformForDagPoseMember( const MFnDependencyNode& dagPoseDep, unsigned int logicalIndex, GfMatrix4d* xform) { MStatus status; MPlug xformMatrixPlug = dagPoseDep.findPlug("xformMatrix"); #if MAYA_API_VERSION >= 20190000 if (TfDebug::IsEnabled(PXRUSDMAYA_TRANSLATORS)) { // As an extra debug sanity check, make sure that the logicalIndex // already exists MIntArray allIndices; xformMatrixPlug.getExistingArrayAttributeIndices(allIndices); if (std::find(allIndices.cbegin(), allIndices.cend(), logicalIndex) == allIndices.cend()) { TfDebug::Helper().Msg( "Warning - attempting to retrieve %s[%u], but that index did not exist yet", xformMatrixPlug.name().asChar(), logicalIndex); } } #endif MPlug xformPlug = xformMatrixPlug.elementByLogicalIndex(logicalIndex, &status); CHECK_MSTATUS_AND_RETURN(status, false); MObject plugObj = xformPlug.asMObject(MDGContext::fsNormal, &status); CHECK_MSTATUS_AND_RETURN(status, false); MFnMatrixData plugMatrixData(plugObj, &status); CHECK_MSTATUS_AND_RETURN(status, false); *xform = GfMatrix4d(plugMatrixData.matrix().matrix); return true; } /// Get local-space bind transforms to use as rest transforms. /// The dagPose is expected to hold the local transforms. static bool _GetJointLocalRestTransformsFromDagPose( const SdfPath& skelPath, const MDagPath& rootJoint, const std::vector<MDagPath>& jointDagPaths, VtMatrix4dArray* xforms) { // Use whatever bindPose the root joint is a member of. MObject bindPose = _FindBindPose(rootJoint); if (bindPose.isNull()) { TF_DEBUG(PXRUSDMAYA_TRANSLATORS) .Msg( "%s -- Could not find a dagPose node holding a bind pose: " "The Skeleton's 'restTransforms' property will be " "calculated from the 'bindTransforms'.\n", skelPath.GetText()); return false; } MStatus status; MFnDependencyNode bindPoseDep(bindPose, &status); CHECK_MSTATUS_AND_RETURN(status, false); std::vector<unsigned int> memberIndices; if (!_FindDagPoseMembers(bindPoseDep, jointDagPaths, &memberIndices)) { return false; } xforms->resize(jointDagPaths.size()); for (size_t i = 0; i < xforms->size(); ++i) { if (!_GetLocalTransformForDagPoseMember( bindPoseDep, memberIndices[i], xforms->data() + i)) { TF_WARN( "%s -- Failed retrieving the local transform of joint '%s' " "from dagPose '%s': The Skeleton's 'restTransforms' " "property will be calculated from the 'bindTransforms'.", skelPath.GetText(), jointDagPaths[i].fullPathName().asChar(), bindPoseDep.name().asChar()); return false; } } return true; } /// Set local-space rest transform by converting from the world-space bind xforms. static bool _GetJointLocalRestTransformsFromBindTransforms(UsdSkelSkeleton& skel, VtMatrix4dArray& restXforms) { auto bindXformsAttr = skel.GetBindTransformsAttr(); if (!bindXformsAttr) { TF_WARN("skeleton was missing bind transforms attr: %s", skel.GetPath().GetText()); return false; } VtMatrix4dArray bindXforms; if (!bindXformsAttr.Get(&bindXforms)) { TF_WARN("error retrieving bind transforms: %s", skel.GetPath().GetText()); return false; } auto jointsAttr = skel.GetJointsAttr(); if (!jointsAttr) { TF_WARN("skeleton was missing bind joints attr: %s", skel.GetPath().GetText()); return false; } VtTokenArray joints; if (!jointsAttr.Get(&joints)) { TF_WARN("error retrieving bind joints: %s", skel.GetPath().GetText()); return false; } auto restXformsAttr = skel.GetRestTransformsAttr(); if (!restXformsAttr) { restXformsAttr = skel.CreateRestTransformsAttr(); if (!restXformsAttr) { TF_WARN( "skeleton had no rest transforms attr, and was unable to " "create it: %s", skel.GetPath().GetText()); return false; } } UsdSkelTopology topology(joints); restXforms.resize(bindXforms.size()); return UsdSkelComputeJointLocalTransforms(topology, bindXforms, restXforms); } /// Gets the world-space transform of \p dagPath at the current time. static GfMatrix4d _GetJointWorldTransform(const MDagPath& dagPath) { // Don't use Maya's built-in getTranslation(), etc. when extracting the // transform because: // - The rotation won't account for the jointOrient rotation, so // you'd have to query that from MFnIkJoint and combine. // - The scale is special on joints because the scale on a parent // joint isn't inherited by children, due to an implicit // (inverse of parent scale) factor when computing joint // transformation matrices. // In short, no matter what you do, there will be cases where the // Maya joint transform can't be perfectly replicated in UsdSkel; // it's much easier to ensure correctness by letting UsdSkel work // with raw transform data, and perform its own decomposition later // with UsdSkelDecomposeTransforms. MStatus status; MMatrix mx = dagPath.inclusiveMatrix(&status); return status ? GfMatrix4d(mx.matrix) : GfMatrix4d(1); } /// Gets the world-space transform of \p dagPath at the current time. static GfMatrix4d _GetJointLocalTransform(const MDagPath& dagPath) { MStatus status; MFnTransform xform(dagPath, &status); if (status) { MTransformationMatrix mx = xform.transformation(&status); if (status) { return GfMatrix4d(mx.asMatrix().matrix); } } return GfMatrix4d(1); } /// Computes world-space joint transforms for all specified dag paths /// at the current time. static bool _GetJointWorldTransforms(const std::vector<MDagPath>& dagPaths, VtMatrix4dArray* xforms) { xforms->resize(dagPaths.size()); GfMatrix4d* xformsData = xforms->data(); for (size_t i = 0; i < dagPaths.size(); ++i) { xformsData[i] = _GetJointWorldTransform(dagPaths[i]); } return true; } /// Computes joint-local transforms for all specified dag paths /// at the current time. static bool _GetJointLocalTransforms( const UsdSkelTopology& topology, const std::vector<MDagPath>& dagPaths, const GfMatrix4d& rootXf, VtMatrix4dArray* localXforms) { VtMatrix4dArray worldXforms; if (_GetJointWorldTransforms(dagPaths, &worldXforms)) { GfMatrix4d rootInvXf = rootXf.GetInverse(); VtMatrix4dArray worldInvXforms(worldXforms); for (auto& xf : worldInvXforms) xf = xf.GetInverse(); return UsdSkelComputeJointLocalTransforms( topology, worldXforms, worldInvXforms, localXforms, &rootInvXf); } return true; } /// Returns true if the joint's transform definitely matches its rest transform /// over all exported frames. static bool _JointMatchesRestPose( size_t jointIdx, const MDagPath& dagPath, const VtMatrix4dArray& xforms, const VtMatrix4dArray& restXforms, bool exportingAnimation) { if (exportingAnimation && _IsTransformNodeAnimated(dagPath)) return false; else if (jointIdx < xforms.size()) return GfIsClose(xforms[jointIdx], restXforms[jointIdx], 1e-8); return false; } /// Given the list of USD joint names and dag paths, returns the joints that /// (1) are moved from their rest poses or (2) have animation, if we are going /// to export animation. static void _GetAnimatedJoints( const UsdSkelTopology& topology, const VtTokenArray& usdJointNames, const MDagPath& rootDagPath, const std::vector<MDagPath>& jointDagPaths, const VtMatrix4dArray& restXforms, VtTokenArray* animatedJointNames, std::vector<MDagPath>* animatedJointPaths, bool exportingAnimation) { if (!TF_VERIFY(usdJointNames.size() == jointDagPaths.size())) { return; } if (restXforms.size() != usdJointNames.size()) { // Either have invalid restXforms or no restXforms at all // (the latter happens when a user deletes the dagPose). // Must treat all joinst as animated. *animatedJointNames = usdJointNames; *animatedJointPaths = jointDagPaths; return; } VtMatrix4dArray localXforms; if (!exportingAnimation) { // Compute the current local xforms of all joints so we can decide // whether or not they need to have a value encoded on the anim prim. GfMatrix4d rootXform = _GetJointWorldTransform(rootDagPath); _GetJointLocalTransforms(topology, jointDagPaths, rootXform, &localXforms); } // The resulting vector contains only animated joints or joints not // in their rest pose. The order is *not* guaranteed to be the Skeleton // order, because UsdSkel allows arbitrary order on SkelAnimation. for (size_t i = 0; i < jointDagPaths.size(); ++i) { const TfToken& jointName = usdJointNames[i]; const MDagPath& dagPath = jointDagPaths[i]; if (!_JointMatchesRestPose( i, jointDagPaths[i], localXforms, restXforms, exportingAnimation)) { animatedJointNames->push_back(jointName); animatedJointPaths->push_back(dagPath); } } } bool PxrUsdTranslators_JointWriter::_WriteRestState() { // Check if the root joint is the special root joint created // for round-tripping UsdSkel data. bool haveUsdSkelXform = UsdMayaTranslatorSkel::IsUsdSkeleton(GetDagPath()); if (!haveUsdSkelXform) { // We don't have a joint that represents the Skeleton. // This means that the joint hierarchy is originating from Maya. // Mark it, so that the exported results can be reimported in // a structure-preserving way. UsdMayaTranslatorSkel::MarkSkelAsMayaGenerated(_skel); } UsdMayaJointUtil::getJointHierarchyComponents( GetDagPath(), &_skelXformPath, &_jointHierarchyRootPath, &_joints); VtTokenArray skelJointNames = UsdMayaJointUtil::getJointNames(_joints, GetDagPath(), _GetExportArgs().stripNamespaces); _topology = UsdSkelTopology(skelJointNames); std::string whyNotValid; if (!_topology.Validate(&whyNotValid)) { TF_CODING_ERROR("Joint topology is invalid: %s", whyNotValid.c_str()); return false; } // Setup binding relationships on the instance prim, // so that the root xform establishes a skeleton instance // with the right transform. const UsdSkelBindingAPI binding = UsdMayaTranslatorUtil ::GetAPISchemaForAuthoring<UsdSkelBindingAPI>(_skel.GetPrim()); // Mark the bindings for post processing. UsdMayaWriteUtil::SetAttribute( _skel.GetJointsAttr(), skelJointNames, UsdTimeCode::Default(), _GetSparseValueWriter()); SdfPath skelPath = _skel.GetPrim().GetPath(); _writeJobCtx.MarkSkelBindings(skelPath, skelPath, _GetExportArgs().exportSkels); VtMatrix4dArray bindXforms = _GetJointWorldBindTransforms(_topology, _joints); UsdMayaWriteUtil::SetAttribute( _skel.GetBindTransformsAttr(), bindXforms, UsdTimeCode::Default(), _GetSparseValueWriter()); VtMatrix4dArray restXforms; if (_GetJointLocalRestTransformsFromDagPose(skelPath, GetDagPath(), _joints, &restXforms) || _GetJointLocalRestTransformsFromBindTransforms(_skel, restXforms)) { UsdMayaWriteUtil::SetAttribute( _skel.GetRestTransformsAttr(), restXforms, UsdTimeCode::Default(), _GetSparseValueWriter()); } else { TF_WARN("Unable to set rest transforms"); } VtTokenArray animJointNames; _GetAnimatedJoints( _topology, skelJointNames, GetDagPath(), _joints, restXforms, &animJointNames, &_animatedJoints, !_GetExportArgs().timeSamples.empty()); if (haveUsdSkelXform) { _skelXformAttr = _skel.MakeMatrixXform(); if (!_GetExportArgs().timeSamples.empty()) { MObject node = _skelXformPath.node(); _skelXformIsAnimated = UsdMayaUtil::isAnimated(node); } else { _skelXformIsAnimated = false; } } if (!animJointNames.empty()) { SdfPath animPath = UsdMayaJointUtil::getAnimationPath(skelPath); _skelAnim = UsdSkelAnimation::Define(GetUsdStage(), animPath); if (TF_VERIFY(_skelAnim)) { _skelToAnimMapper = UsdSkelAnimMapper(skelJointNames, animJointNames); UsdMayaWriteUtil::SetAttribute( _skelAnim.GetJointsAttr(), animJointNames, UsdTimeCode::Default(), _GetSparseValueWriter()); binding.CreateAnimationSourceRel().SetTargets({ animPath }); } else { return false; } } return true; } /* virtual */ void PxrUsdTranslators_JointWriter::Write(const UsdTimeCode& usdTime) { if (usdTime.IsDefault()) { _valid = _WriteRestState(); } if (!_valid) { return; } if ((usdTime.IsDefault() || _skelXformIsAnimated) && _skelXformAttr) { // We have a joint which provides the transform of the Skeleton, // instead of the transform of a joint in the hierarchy. GfMatrix4d localXf = _GetJointLocalTransform(_skelXformPath); UsdMayaWriteUtil::SetAttribute(_skelXformAttr, localXf, usdTime, _GetSparseValueWriter()); } // Time-varying step: write the packed joint animation transforms once per // time code. We do want to run this @ default time also so that any // deviations from the rest pose are exported as the default values on the // SkelAnimation. if (!_animatedJoints.empty()) { if (!_skelAnim) { SdfPath animPath = UsdMayaJointUtil::getAnimationPath(_skel.GetPrim().GetPath()); TF_CODING_ERROR( "SkelAnimation <%s> doesn't exist but should " "have been created during default-time pass.", animPath.GetText()); return; } GfMatrix4d rootXf = _GetJointWorldTransform(_jointHierarchyRootPath); VtMatrix4dArray localXforms; if (_GetJointLocalTransforms(_topology, _joints, rootXf, &localXforms)) { // Remap local xforms into the (possibly sparse) anim order. VtMatrix4dArray animLocalXforms; if (_skelToAnimMapper.Remap(localXforms, &animLocalXforms)) { VtVec3fArray translations; VtQuatfArray rotations; VtVec3hArray scales; if (UsdSkelDecomposeTransforms( animLocalXforms, &translations, &rotations, &scales)) { // XXX It is difficult for us to tell which components are // actually animated since we rely on decomposition to get // separate anim components. // In the future, we may want to RLE-compress the data in // PostExport to remove redundant time samples. UsdMayaWriteUtil::SetAttribute( _skelAnim.GetTranslationsAttr(), &translations, usdTime, _GetSparseValueWriter()); UsdMayaWriteUtil::SetAttribute( _skelAnim.GetRotationsAttr(), &rotations, usdTime, _GetSparseValueWriter()); UsdMayaWriteUtil::SetAttribute( _skelAnim.GetScalesAttr(), &scales, usdTime, _GetSparseValueWriter()); } } } } } /* virtual */ bool PxrUsdTranslators_JointWriter::ExportsGprims() const { // Nether the Skeleton nor its animation sources are gprims. return false; } /* virtual */ bool PxrUsdTranslators_JointWriter::ShouldPruneChildren() const { return true; } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/lib/mayaUsd/python/wrapPrimWriter.cpp // // Copyright 2021 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <mayaUsd/fileio/primWriter.h> #include <mayaUsd/fileio/primWriterRegistry.h> #include <mayaUsd/fileio/registryHelper.h> #include <mayaUsd/fileio/shaderWriter.h> #include <mayaUsd/fileio/shaderWriterRegistry.h> #include <pxr/base/tf/makePyConstructor.h> #include <pxr/base/tf/pyContainerConversions.h> #include <pxr/base/tf/pyEnum.h> #include <pxr/base/tf/pyPolymorphic.h> #include <pxr/base/tf/pyPtrHelpers.h> #include <pxr/base/tf/pyResultConversions.h> #include <pxr/base/tf/refPtr.h> #include <pxr/usd/usdGeom/camera.h> #include <boost/python.hpp> #include <boost/python/args.hpp> #include <boost/python/def.hpp> #include <boost/python/wrapper.hpp> PXR_NAMESPACE_USING_DIRECTIVE //---------------------------------------------------------------------------------------------------------------------- /// \brief boost python binding for the UsdMayaPrimWriter //---------------------------------------------------------------------------------------------------------------------- template <typename T = UsdMayaPrimWriter> class PrimWriterWrapper : public T , public TfPyPolymorphic<UsdMayaPrimWriter> { public: typedef PrimWriterWrapper This; typedef T base_t; PrimWriterWrapper( const MFnDependencyNode& depNodeFn, const SdfPath& usdPath, UsdMayaWriteJobContext& jobCtx) : T(depNodeFn, usdPath, jobCtx) { } static PrimWriterWrapper* New(uintptr_t createdWrapper) { return (PrimWriterWrapper*)createdWrapper; } virtual ~PrimWriterWrapper() { } const UsdStage& GetUsdStage() const { return *get_pointer(base_t::GetUsdStage()); } // This is the pattern inspired from USD/pxr/base/tf/wrapTestTfPython.cpp // It would have been simpler to call 'this->CallVirtual<>("Write", // &base_t::default_Write)(usdTime);' But it is not allowed Instead of having to create a // function 'default_Write(...)' to call the base class when there is no Python implementation. void default_Write(const UsdTimeCode& usdTime) { base_t::Write(usdTime); } void Write(const UsdTimeCode& usdTime) override { this->template CallVirtual<>("Write", &This::default_Write)(usdTime); } void default_PostExport() { base_t::PostExport(); } void PostExport() override { this->template CallVirtual<>("PostExport", &This::default_PostExport)(); } bool default_ExportsGprims() const { return base_t::ExportsGprims(); } bool ExportsGprims() const override { return this->template CallVirtual<bool>("ExportsGprims", &This::default_ExportsGprims)(); } bool default_ShouldPruneChildren() const { return base_t::ShouldPruneChildren(); }; bool ShouldPruneChildren() const override { return this->template CallVirtual<bool>( "ShouldPruneChildren", &This::default_ShouldPruneChildren)(); } bool default__HasAnimCurves() const { return base_t::_HasAnimCurves(); }; bool _HasAnimCurves() const override { return this->template CallVirtual<bool>("_HasAnimCurves", &This::default__HasAnimCurves)(); } void _SetUsdPrim(const UsdPrim& usdPrim) { base_t::_SetUsdPrim(usdPrim); } const UsdMayaJobExportArgs& _GetExportArgs() const { return base_t::_GetExportArgs(); } boost::python::object _GetSparseValueWriter() { return boost::python::object(base_t::_GetSparseValueWriter()); } const SdfPathVector& default_GetModelPaths() const { return base_t::GetModelPaths(); } const SdfPathVector& GetModelPaths() const override { if (Override o = GetOverride("GetModelPaths")) { auto res = std::function<boost::python::object()>(TfPyCall<boost::python::object>(o))(); if (res) { const_cast<SdfPathVector*>(&_modelPaths)->clear(); TfPyLock pyLock; boost::python::list keys(res); for (int i = 0; i < len(keys); ++i) { boost::python::extract<SdfPath> extractedKey(keys[i]); if (!extractedKey.check()) { TF_CODING_ERROR( "PrimWriterWrapper.GetModelPaths: SdfPath key expected, not " "found!"); return _modelPaths; } SdfPath path = extractedKey; const_cast<SdfPathVector*>(&_modelPaths)->push_back(path); } return _modelPaths; } } return This::default_GetModelPaths(); } const UsdMayaUtil::MDagPathMap<SdfPath>& default_GetDagToUsdPathMapping() const { return base_t::GetDagToUsdPathMapping(); } const UsdMayaUtil::MDagPathMap<SdfPath>& GetDagToUsdPathMapping() const override { if (Override o = GetOverride("GetDagToUsdPathMapping")) { auto res = std::function<boost::python::object()>(TfPyCall<boost::python::object>(o))(); if (res) { const_cast<UsdMayaUtil::MDagPathMap<SdfPath>*>(&_dagPathMap)->clear(); TfPyLock pyLock; boost::python::list tuples(res); for (int i = 0; i < len(tuples); ++i) { boost::python::tuple t(tuples[i]); if (boost::python::len(t) != 2) { TF_CODING_ERROR("PrimWriterWrapper.GetDagToUsdPathMapping: list<tuples> " "key expected, not " "found!"); return _dagPathMap; } boost::python::extract<MDagPath> extractedDagPath(t[0]); if (!extractedDagPath.check()) { TF_CODING_ERROR( "PrimWriterWrapper.GetDagToUsdPathMapping: MDagPath key expected, not " "found!"); return _dagPathMap; } boost::python::extract<SdfPath> extractedSdfPath(t[1]); if (!extractedSdfPath.check()) { TF_CODING_ERROR( "PrimWriterWrapper.GetDagToUsdPathMapping: SdfPath key expected, not " "found!"); return _dagPathMap; } MDagPath dagPath = extractedDagPath; SdfPath path = extractedSdfPath; const_cast<UsdMayaUtil::MDagPathMap<SdfPath>*>(&_dagPathMap) -> operator[](dagPath) = path; } return _dagPathMap; } } return This::default_GetDagToUsdPathMapping(); } static void Register(boost::python::object cl, const std::string& mayaTypeName) { UsdMayaPrimWriterRegistry::Register( mayaTypeName, [=](const MFnDependencyNode& depNodeFn, const SdfPath& usdPath, UsdMayaWriteJobContext& jobCtx) { auto sptr = std::make_shared<PrimWriterWrapper>(depNodeFn, usdPath, jobCtx); TfPyLock pyLock; boost::python::object instance = cl((uintptr_t)(PrimWriterWrapper*)sptr.get()); boost::python::incref(instance.ptr()); initialize_wrapper(instance.ptr(), sptr.get()); return sptr; }, true); } private: SdfPathVector _modelPaths; UsdMayaUtil::MDagPathMap<SdfPath> _dagPathMap; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief boost python binding for the UsdMayaShaderWriter //---------------------------------------------------------------------------------------------------------------------- class ShaderWriterWrapper : public PrimWriterWrapper<UsdMayaShaderWriter> { public: typedef ShaderWriterWrapper This; typedef UsdMayaShaderWriter base_t; ShaderWriterWrapper( const MFnDependencyNode& depNodeFn, const SdfPath& usdPath, UsdMayaWriteJobContext& jobCtx) : PrimWriterWrapper<UsdMayaShaderWriter>(depNodeFn, usdPath, jobCtx) { } static ShaderWriterWrapper* New(uintptr_t createdWrapper) { return (ShaderWriterWrapper*)createdWrapper; } virtual ~ShaderWriterWrapper() { } TfToken default_GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName) { return base_t::GetShadingAttributeNameForMayaAttrName(mayaAttrName); } TfToken GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName) override { return this->CallVirtual<TfToken>( "GetShadingAttributeNameForMayaAttrName", &This::default_GetShadingAttributeNameForMayaAttrName)(mayaAttrName); } UsdAttribute default_GetShadingAttributeForMayaAttrName( const TfToken& mayaAttrName, const SdfValueTypeName& typeName) { return base_t::GetShadingAttributeForMayaAttrName(mayaAttrName, typeName); } UsdAttribute GetShadingAttributeForMayaAttrName( const TfToken& mayaAttrName, const SdfValueTypeName& typeName) override { return this->CallVirtual<UsdAttribute>( "GetShadingAttributeForMayaAttrName", &This::default_GetShadingAttributeForMayaAttrName)(mayaAttrName, typeName); } static void Register(boost::python::object cl, const TfToken& mayaType) { UsdMayaShaderWriterRegistry::Register( mayaType, [=](const UsdMayaJobExportArgs& args) { return UsdMayaShaderWriter::ContextSupport(0); }, [=](const MFnDependencyNode& depNodeFn, const SdfPath& usdPath, UsdMayaWriteJobContext& jobCtx) { auto sptr = std::make_shared<ShaderWriterWrapper>(depNodeFn, usdPath, jobCtx); TfPyLock pyLock; boost::python::object instance = cl((uintptr_t)(ShaderWriterWrapper*)sptr.get()); boost::python::incref(instance.ptr()); initialize_wrapper(instance.ptr(), sptr.get()); return sptr; }, true); } }; //---------------------------------------------------------------------------------------------------------------------- void wrapJobExportArgs() { boost::python::class_<UsdMayaJobExportArgs>("JobExportArgs", boost::python::no_init); } void wrapPrimWriter() { boost::python::class_<PrimWriterWrapper<>, boost::noncopyable>( "PrimWriter", boost::python::no_init) .def("__init__", make_constructor(&PrimWriterWrapper<>::New)) .def( "PostExport", &PrimWriterWrapper<>::PostExport, &PrimWriterWrapper<>::default_PostExport) .def("Write", &PrimWriterWrapper<>::Write, &PrimWriterWrapper<>::default_Write) .def("GetExportVisibility", &PrimWriterWrapper<>::GetExportVisibility) .def("SetExportVisibility", &PrimWriterWrapper<>::SetExportVisibility) .def( "GetMayaObject", &PrimWriterWrapper<>::GetMayaObject, boost::python::return_value_policy<boost::python::return_by_value>()) .def( "GetUsdPrim", &PrimWriterWrapper<>::GetUsdPrim, boost::python::return_internal_reference<>()) .def("_SetUsdPrim", &PrimWriterWrapper<>::_SetUsdPrim) .def( "MakeSingleSamplesStatic", static_cast<void (PrimWriterWrapper<>::*)()>( &PrimWriterWrapper<>::MakeSingleSamplesStatic)) .def( "MakeSingleSamplesStatic", static_cast<void (PrimWriterWrapper<>::*)(UsdAttribute attr)>( &PrimWriterWrapper<>::MakeSingleSamplesStatic)) .def( "_HasAnimCurves", &PrimWriterWrapper<>::_HasAnimCurves, &PrimWriterWrapper<>::default__HasAnimCurves) .def( "_GetExportArgs", &PrimWriterWrapper<>::_GetExportArgs, boost::python::return_internal_reference<>()) .def("_GetSparseValueWriter", &PrimWriterWrapper<>::_GetSparseValueWriter) .def( "GetDagPath", &PrimWriterWrapper<>::GetDagPath, boost::python::return_value_policy<boost::python::return_by_value>()) .def( "GetUsdStage", &UsdMayaPrimWriter::GetUsdStage, boost::python::return_value_policy<boost::python::return_by_value>()) .def( "GetUsdPath", &UsdMayaPrimWriter::GetUsdPath, boost::python::return_value_policy<boost::python::return_by_value>()) .def( "Register", &PrimWriterWrapper<>::Register, (boost::python::arg("class"), boost::python::arg("mayaTypeName"))) .staticmethod("Register"); } TF_REGISTRY_FUNCTION(TfEnum) { TF_ADD_ENUM_NAME(UsdMayaShaderWriter::ContextSupport::Supported, "Supported"); TF_ADD_ENUM_NAME(UsdMayaShaderWriter::ContextSupport::Fallback, "Fallback"); TF_ADD_ENUM_NAME(UsdMayaShaderWriter::ContextSupport::Unsupported, "Unsupported"); } //---------------------------------------------------------------------------------------------------------------------- void wrapShaderWriter() { boost::python:: class_<ShaderWriterWrapper, boost::python::bases<PrimWriterWrapper<>>, boost::noncopyable> c("ShaderWriter", boost::python::no_init); boost::python::scope s(c); TfPyWrapEnum<UsdMayaShaderWriter::ContextSupport>(); c.def("__init__", make_constructor(&ShaderWriterWrapper::New)) .def( "GetShadingAttributeNameForMayaAttrName", &ShaderWriterWrapper::GetShadingAttributeNameForMayaAttrName, &ShaderWriterWrapper::default_GetShadingAttributeNameForMayaAttrName) .def( "GetShadingAttributeForMayaAttrName", &ShaderWriterWrapper::GetShadingAttributeForMayaAttrName, &ShaderWriterWrapper::default_GetShadingAttributeForMayaAttrName) .def( "Register", &ShaderWriterWrapper::Register, (boost::python::arg("class"), boost::python::arg("mayaTypeName"))) .staticmethod("Register"); } <file_sep>/test/testUtils/testUtils.py # # Copyright 2019 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ General test utilities. The functions here should not use Maya, Ufe or Usd. """ import os def stripPrefix(input_str, prefix): if input_str.startswith(prefix): return input_str[len(prefix):] return input_str def assertVectorAlmostEqual(testCase, a, b, places=7): for va, vb in zip(a, b): testCase.assertAlmostEqual(va, vb, places) def assertVectorNotAlmostEqual(testCase, a, b, places=7): for va, vb in zip(a, b): testCase.assertNotAlmostEqual(va, vb, places) def assertVectorEqual(testCase, a, b): for va, vb in zip(a, b): testCase.assertEqual(va, vb) def getTestScene(*args): return os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "testSamples", *args) <file_sep>/lib/mayaUsd/ufe/UsdAttribute.h // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include <mayaUsd/ufe/UsdSceneItem.h> #include <pxr/usd/usd/attribute.h> #include <pxr/usd/usd/prim.h> #include <ufe/attribute.h> // Ufe::Attribute overrides (minus the type method) #define UFE_ATTRIBUTE_OVERRIDES \ bool hasValue() const override { return UsdAttribute::hasValue(); } \ std::string name() const override { return UsdAttribute::name(); } \ std::string documentation() const override { return UsdAttribute::documentation(); } \ std::string string() const override \ { \ return UsdAttribute::string(Ufe::Attribute::sceneItem()); \ } namespace MAYAUSD_NS_DEF { namespace ufe { //! \brief Internal helper class to implement the pure virtual methods from Ufe::Attribute. class UsdAttribute { public: UsdAttribute(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); ~UsdAttribute(); // Ufe::Attribute override methods that we've mimic'd here. bool hasValue() const; std::string name() const; std::string documentation() const; std::string string(const Ufe::SceneItem::Ptr& item) const; protected: PXR_NS::UsdPrim fPrim; PXR_NS::UsdAttribute fUsdAttr; }; // UsdAttribute //! \brief Interface for USD attributes which don't match any defined type. class UsdAttributeGeneric : public Ufe::AttributeGeneric , private UsdAttribute { public: typedef std::shared_ptr<UsdAttributeGeneric> Ptr; UsdAttributeGeneric(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); //! Create a UsdAttributeGeneric. static UsdAttributeGeneric::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); // Ufe::Attribute overrides UFE_ATTRIBUTE_OVERRIDES // Ufe::AttributeGeneric overrides std::string nativeType() const override; }; // UsdAttributeGeneric //! \brief Interface for USD token attributes. class UsdAttributeEnumString : public Ufe::AttributeEnumString , private UsdAttribute { public: typedef std::shared_ptr<UsdAttributeEnumString> Ptr; UsdAttributeEnumString(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); //! Create a UsdAttributeEnumString. static UsdAttributeEnumString::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); // Ufe::Attribute overrides UFE_ATTRIBUTE_OVERRIDES // Ufe::AttributeEnumString overrides std::string get() const override; void set(const std::string& value) override; Ufe::UndoableCommand::Ptr setCmd(const std::string& value) override; EnumValues getEnumValues() const override; }; // UsdAttributeEnumString //! \brief Internal helper template class to implement the get/set methods from Ufe::TypeAttribute. template <typename T> class TypedUsdAttribute : public Ufe::TypedAttribute<T> , private UsdAttribute { public: TypedUsdAttribute(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); // Ufe::Attribute overrides UFE_ATTRIBUTE_OVERRIDES // Ufe::TypedAttribute overrides T get() const override; void set(const T& value) override; Ufe::UndoableCommand::Ptr setCmd(const T& value) override; }; // TypedUsdAttribute //! \brief Interface for USD bool attributes. class UsdAttributeBool : public TypedUsdAttribute<bool> { public: typedef std::shared_ptr<UsdAttributeBool> Ptr; using TypedUsdAttribute<bool>::TypedUsdAttribute; //! Create a UsdAttributeBool. static UsdAttributeBool::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeBool //! \brief Interface for USD int attributes. class UsdAttributeInt : public TypedUsdAttribute<int> { public: typedef std::shared_ptr<UsdAttributeInt> Ptr; using TypedUsdAttribute<int>::TypedUsdAttribute; //! Create a UsdAttributeInt. static UsdAttributeInt::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeInt //! \brief Interface for USD float attributes. class UsdAttributeFloat : public TypedUsdAttribute<float> { public: typedef std::shared_ptr<UsdAttributeFloat> Ptr; using TypedUsdAttribute<float>::TypedUsdAttribute; //! Create a UsdAttributeFloat. static UsdAttributeFloat::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeFloat //! \brief Interface for USD double attributes. class UsdAttributeDouble : public TypedUsdAttribute<double> { public: typedef std::shared_ptr<UsdAttributeDouble> Ptr; using TypedUsdAttribute<double>::TypedUsdAttribute; //! Create a UsdAttributeDouble. static UsdAttributeDouble::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeDouble //! \brief Interface for USD string/token attributes. class UsdAttributeString : public TypedUsdAttribute<std::string> { public: typedef std::shared_ptr<UsdAttributeString> Ptr; using TypedUsdAttribute<std::string>::TypedUsdAttribute; //! Create a UsdAttributeString. static UsdAttributeString::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeString //! \brief Interface for USD RGB color (float) attributes. class UsdAttributeColorFloat3 : public TypedUsdAttribute<Ufe::Color3f> { public: typedef std::shared_ptr<UsdAttributeColorFloat3> Ptr; using TypedUsdAttribute<Ufe::Color3f>::TypedUsdAttribute; //! Create a UsdAttributeColorFloat3. static UsdAttributeColorFloat3::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeColorFloat3 //! \brief Interface for USD Vector3i (int) attributes. class UsdAttributeInt3 : public TypedUsdAttribute<Ufe::Vector3i> { public: typedef std::shared_ptr<UsdAttributeInt3> Ptr; using TypedUsdAttribute<Ufe::Vector3i>::TypedUsdAttribute; //! Create a UsdAttributeInt3. static UsdAttributeInt3::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeInt3 //! \brief Interface for USD Vector3f (float) attributes. class UsdAttributeFloat3 : public TypedUsdAttribute<Ufe::Vector3f> { public: typedef std::shared_ptr<UsdAttributeFloat3> Ptr; using TypedUsdAttribute<Ufe::Vector3f>::TypedUsdAttribute; //! Create a UsdAttributeFloat3. static UsdAttributeFloat3::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeFloat3 //! \brief Interface for USD Vector3d (double) attributes. class UsdAttributeDouble3 : public TypedUsdAttribute<Ufe::Vector3d> { public: typedef std::shared_ptr<UsdAttributeDouble3> Ptr; using TypedUsdAttribute<Ufe::Vector3d>::TypedUsdAttribute; //! Create a UsdAttributeDouble3. static UsdAttributeDouble3::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeDouble3 } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/lib/mayaUsd/render/vp2RenderDelegate/material.h // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef HD_VP2_MATERIAL #define HD_VP2_MATERIAL #include "shader.h" #include <pxr/base/gf/vec2f.h> #include <pxr/imaging/hd/material.h> #include <pxr/pxr.h> #include <maya/MShaderManager.h> #include <mutex> #include <set> #include <unordered_map> // Workaround for a material consolidation update issue in VP2. Before USD 0.20.11, a Rprim will be // recreated if its material has any change, so everything gets refreshed and the update issue gets // masked. Once the update issue is fixed in VP2 we will disable this workaround. #if PXR_VERSION >= 2011 && MAYA_API_VERSION >= 20210000 && MAYA_API_VERSION < 20230000 #define HDVP2_MATERIAL_CONSOLIDATION_UPDATE_WORKAROUND #endif PXR_NAMESPACE_OPEN_SCOPE class HdSceneDelegate; class HdVP2RenderDelegate; /*! \brief A deleter for MTexture, for use with smart pointers. */ struct HdVP2TextureDeleter { void operator()(MHWRender::MTexture*); }; /*! \brief A MTexture owned by a std unique pointer. */ using HdVP2TextureUniquePtr = std::unique_ptr<MHWRender::MTexture, HdVP2TextureDeleter>; /*! \brief Information about the texture. */ struct HdVP2TextureInfo { HdVP2TextureUniquePtr _texture; //!< Unique pointer of the texture GfVec2f _stScale { 1.0f, 1.0f }; //!< UV scale for tiled textures GfVec2f _stOffset { 0.0f, 0.0f }; //!< UV offset for tiled textures bool _isColorSpaceSRGB { false }; //!< Whether sRGB linearization is needed }; /*! \brief An unordered string-indexed map to cache texture information. */ using HdVP2TextureMap = std::unordered_map<std::string, HdVP2TextureInfo>; /*! \brief A VP2-specific implementation for a Hydra material prim. \class HdVP2Material Provides a basic implementation of a Hydra material. */ class HdVP2Material final : public HdMaterial { public: HdVP2Material(HdVP2RenderDelegate*, const SdfPath&); //! Destructor. ~HdVP2Material() override = default; void Sync(HdSceneDelegate*, HdRenderParam*, HdDirtyBits*) override; HdDirtyBits GetInitialDirtyBitsMask() const override; #if PXR_VERSION < 2011 void Reload() override {}; #endif //! Get the surface shader instance. MHWRender::MShaderInstance* GetSurfaceShader() const { return _surfaceShader.get(); } //! Get primvar tokens required by this material. const TfTokenVector& GetRequiredPrimvars() const { return _requiredPrimvars; } #ifdef HDVP2_MATERIAL_CONSOLIDATION_UPDATE_WORKAROUND //! The specified Rprim starts listening to changes on this material. void SubscribeForMaterialUpdates(const SdfPath& rprimId); //! The specified Rprim stops listening to changes on this material. void UnsubscribeFromMaterialUpdates(const SdfPath& rprimId); #endif private: void _ApplyVP2Fixes(HdMaterialNetwork& outNet, const HdMaterialNetwork& inNet); #ifdef WANT_MATERIALX_BUILD void _ApplyMtlxVP2Fixes(HdMaterialNetwork2& outNet, const HdMaterialNetwork2& inNet); MHWRender::MShaderInstance* _CreateMaterialXShaderInstance( SdfPath const& materialId, HdMaterialNetwork2 const& hdNetworkMap); #endif MHWRender::MShaderInstance* _CreateShaderInstance(const HdMaterialNetwork& mat); void _UpdateShaderInstance(const HdMaterialNetwork& mat); const HdVP2TextureInfo& _AcquireTexture(const std::string& path, const HdMaterialNode& node); #ifdef HDVP2_MATERIAL_CONSOLIDATION_UPDATE_WORKAROUND //! Trigger sync on all Rprims which are listening to changes on this material. void _MaterialChanged(HdSceneDelegate* sceneDelegate); #endif HdVP2RenderDelegate* const _renderDelegate; //!< VP2 render delegate for which this material was created std::unordered_map<SdfPath, SdfPath, SdfPath::Hash> _nodePathMap; //!< Mapping from authored node paths to VP2-specific simplified pathes TfToken _surfaceNetworkToken; //!< Generated token to uniquely identify a material network HdVP2ShaderUniquePtr _surfaceShader; //!< VP2 surface shader instance SdfPath _surfaceShaderId; //!< Path of the surface shader HdVP2TextureMap _textureMap; //!< Textures used by this material TfTokenVector _requiredPrimvars; //!< primvars required by this material #ifdef HDVP2_MATERIAL_CONSOLIDATION_UPDATE_WORKAROUND //! Mutex protecting concurrent access to the Rprim set std::mutex _materialSubscriptionsMutex; //! The set of Rprims listening to changes on this material std::set<SdfPath> _materialSubscriptions; #endif #ifdef WANT_MATERIALX_BUILD // MaterialX-only at the moment, but will be used for UsdPreviewSurface when the upgrade to // HdMaterialNetwork2 is complete. size_t _topoHash = 0; #endif }; PXR_NAMESPACE_CLOSE_SCOPE #endif <file_sep>/lib/usd/translators/mayaReferenceUpdater.h // // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef PXRUSDTRANSLATORS_MAYAREFERENCE_UPDATER_H #define PXRUSDTRANSLATORS_MAYAREFERENCE_UPDATER_H #include <mayaUsd/fileio/primUpdater.h> #include <pxr/pxr.h> #include <maya/MFnDependencyNode.h> PXR_NAMESPACE_OPEN_SCOPE class SdfPath; /// Exports Maya cameras to UsdGeomCamera. class PxrUsdTranslators_MayaReferenceUpdater : public UsdMayaPrimUpdater { public: PxrUsdTranslators_MayaReferenceUpdater( const MFnDependencyNode& depNodeFn, const SdfPath& usdPath); bool Pull(UsdMayaPrimUpdaterContext* context) override; void Clear(UsdMayaPrimUpdaterContext* context) override; protected: }; PXR_NAMESPACE_CLOSE_SCOPE #endif <file_sep>/lib/mayaUsd/utils/utilFileSystem.h // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <mayaUsd/base/api.h> #include <pxr/pxr.h> #include <maya/MObject.h> #include <string> PXR_NAMESPACE_OPEN_SCOPE namespace UsdMayaUtilFileSystem { /*! \brief returns the resolved filesystem path for the file identified by the given path */ MAYAUSD_CORE_PUBLIC std::string resolvePath(const std::string& filePath); /*! \brief returns the path to the */ MAYAUSD_CORE_PUBLIC std::string getDir(const std::string& fullFilePath); /*! \brief returns parent directory of a maya scene file opened by reference */ MAYAUSD_CORE_PUBLIC std::string getMayaReferencedFileDir(const MObject& proxyShapeNode); /*! \brief returns parent directory of opened maya scene file */ MAYAUSD_CORE_PUBLIC std::string getMayaSceneFileDir(); /*! \brief returns the Maya workspace file rule entry for scenes */ MAYAUSD_CORE_PUBLIC std::string getMayaWorkspaceScenesDir(); /*! \brief returns a unique file name */ MAYAUSD_CORE_PUBLIC std::string getUniqueFileName(const std::string& dir, const std::string& basename, const std::string& ext); /*! \brief returns the aboluste path relative to the maya file */ MAYAUSD_CORE_PUBLIC std::string resolveRelativePathWithinMayaContext( const MObject& proxyShape, const std::string& relativeFilePath); /** * Appends `b` to the directory path `a` in-place and inserts directory separators as necessary. * * @param a A valid path to a directory on disk. This should be a string * with a buffer large enough to hold the combined contents of itself and the * contents of `b`, including the null-terminator. * @param b A string to append as a directory component to `a`. * * @return ``true`` if the operation succeeded, ``false`` if an error occurred. */ MAYAUSD_CORE_PUBLIC bool pathAppendPath(std::string& a, const std::string& b); /** * Appends `b` to the path `a` and returns a path (by appending two input paths). * * @param a A string that respresents the first path * @param b A string that respresents the second path * * @return the two paths joined by a seperator */ MAYAUSD_CORE_PUBLIC std::string appendPaths(const std::string& a, const std::string& b); /** * Writes data to a file path on disk. * * @param filePath A pointer to the file path to write to on disk. * @param buffer A pointer to the buffer containing the data to write to the file. * @param size The number of bytes to write. * * @return The number of bytes written to disk. */ MAYAUSD_CORE_PUBLIC size_t writeToFilePath(const char* filePath, const void* buffer, const size_t size); /** * Removes the path portion of a fully-qualified path and file, in-place. * * @param filePath A pointer to the null-terminated ANSI file path to remove the path component * for. */ MAYAUSD_CORE_PUBLIC void pathStripPath(std::string& filePath); MAYAUSD_CORE_PUBLIC void pathRemoveExtension(std::string& filePath); MAYAUSD_CORE_PUBLIC std::string pathFindExtension(std::string& filePath); } // namespace UsdMayaUtilFileSystem PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/plugin/adsk/plugin/exportTranslator.cpp // // Copyright 2016 Pixar // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "exportTranslator.h" #include <mayaUsd/fileio/jobs/jobArgs.h> #include <mayaUsd/fileio/jobs/writeJob.h> #include <mayaUsd/fileio/shading/shadingModeRegistry.h> #include <mayaUsd/fileio/utils/writeUtil.h> #include <maya/MFileObject.h> #include <maya/MGlobal.h> #include <maya/MSelectionList.h> #include <maya/MString.h> #include <set> #include <sstream> #include <string> PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { const MString UsdMayaExportTranslator::translatorName("USD Export"); void* UsdMayaExportTranslator::creator() { return new UsdMayaExportTranslator(); } UsdMayaExportTranslator::UsdMayaExportTranslator() : MPxFileTranslator() { } UsdMayaExportTranslator::~UsdMayaExportTranslator() { } MStatus UsdMayaExportTranslator::writer( const MFileObject& file, const MString& optionsString, MPxFileTranslator::FileAccessMode mode) { // If we are in neither of these modes then there won't be anything to do if (mode != MPxFileTranslator::kExportActiveAccessMode && mode != MPxFileTranslator::kExportAccessMode) { return MS::kSuccess; } std::string fileName(file.fullName().asChar(), file.fullName().length()); VtDictionary userArgs; bool exportAnimation = false; GfInterval timeInterval(1.0, 1.0); double frameStride = 1.0; bool append = false; std::set<double> frameSamples; // Get the options if (optionsString.length() > 0) { MStringArray optionList; MStringArray theOption; optionsString.split(';', optionList); for (int i = 0; i < (int)optionList.length(); ++i) { theOption.clear(); optionList[i].split('=', theOption); if (theOption.length() != 2) { // We allow an empty string to be passed to exportRoots. We must process it here. if (theOption.length() == 1 && theOption[0] == UsdMayaJobExportArgsTokens->exportRoots.GetText()) { std::vector<VtValue> userArgVals; userArgVals.push_back(VtValue("")); userArgs[UsdMayaJobExportArgsTokens->exportRoots] = userArgVals; } continue; } std::string argName(theOption[0].asChar()); if (argName == "animation") { exportAnimation = (theOption[1].asInt() != 0); } else if (argName == "startTime") { timeInterval.SetMin(theOption[1].asDouble()); } else if (argName == "endTime") { timeInterval.SetMax(theOption[1].asDouble()); } else if (argName == "frameStride") { frameStride = theOption[1].asDouble(); } else if (argName == "filterTypes") { std::vector<VtValue> userArgVals; MStringArray filteredTypes; theOption[1].split(',', filteredTypes); unsigned int nbTypes = filteredTypes.length(); for (unsigned int idxType = 0; idxType < nbTypes; ++idxType) { const std::string filteredType = filteredTypes[idxType].asChar(); userArgVals.emplace_back(filteredType); } userArgs[UsdMayaJobExportArgsTokens->filterTypes] = userArgVals; } else if (argName == "frameSample") { frameSamples.clear(); MStringArray samplesStrings; theOption[1].split(' ', samplesStrings); unsigned int nbSams = samplesStrings.length(); for (unsigned int sam = 0; sam < nbSams; ++sam) { if (samplesStrings[sam].isDouble()) { frameSamples.insert(samplesStrings[sam].asDouble()); } } } else if (argName == UsdMayaJobExportArgsTokens->exportRoots.GetText()) { MStringArray exportRootStrings; theOption[1].split(',', exportRootStrings); std::vector<VtValue> userArgVals; unsigned int nbRoots = exportRootStrings.length(); for (unsigned int idxRoot = 0; idxRoot < nbRoots; ++idxRoot) { const std::string exportRootPath = exportRootStrings[idxRoot].asChar(); if (!exportRootPath.empty()) { MDagPath rootDagPath; UsdMayaUtil::GetDagPathByName(exportRootPath, rootDagPath); if (!rootDagPath.isValid()) { MGlobal::displayError( MString("Invalid dag path provided for export root: ") + exportRootStrings[idxRoot]); return MS::kFailure; } userArgVals.push_back(VtValue(exportRootPath)); } else { userArgVals.push_back(VtValue("")); } } userArgs[argName] = userArgVals; } else { if (argName == "shadingMode") { TfToken shadingMode(theOption[1].asChar()); if (!shadingMode.IsEmpty() && UsdMayaShadingModeRegistry::GetInstance().GetExporter(shadingMode) == nullptr && shadingMode != UsdMayaShadingModeTokens->none) { MGlobal::displayError( TfStringPrintf("No shadingMode '%s' found.", shadingMode.GetText()) .c_str()); return MS::kFailure; } } userArgs[argName] = UsdMayaUtil::ParseArgumentValue( argName, theOption[1].asChar(), PXR_NS::UsdMayaJobExportArgs::GetDefaultDictionary()); } } } // Now resync start and end frame based on export time interval. if (exportAnimation) { if (timeInterval.IsEmpty()) { // If the user accidentally set start > end, resync to the closed // interval with the single start point. timeInterval = GfInterval(timeInterval.GetMin()); } } else { // No animation, so empty interval. timeInterval = GfInterval(); } MSelectionList objSelList; UsdMayaUtil::MDagPathSet dagPaths; GetFilteredSelectionToExport( (mode == MPxFileTranslator::kExportActiveAccessMode), objSelList, dagPaths); if (dagPaths.empty()) { TF_WARN("No DAG nodes to export. Skipping."); return MS::kSuccess; } const std::vector<double> timeSamples = UsdMayaWriteUtil::GetTimeSamples(timeInterval, frameSamples, frameStride); PXR_NS::UsdMayaJobExportArgs jobArgs = PXR_NS::UsdMayaJobExportArgs::CreateFromDictionary(userArgs, dagPaths, timeSamples); UsdMaya_WriteJob writeJob(jobArgs); if (!writeJob.Write(fileName, append)) { return MS::kFailure; } return MS::kSuccess; } MPxFileTranslator::MFileKind UsdMayaExportTranslator::identifyFile( const MFileObject& file, const char* /*buffer*/, short /*size*/) const { MFileKind retValue = kNotMyFileType; const MString fileName = file.fullName(); const int lastIndex = fileName.length() - 1; const int periodIndex = fileName.rindex('.'); if (periodIndex < 0 || periodIndex >= lastIndex) { return retValue; } const MString fileExtension = fileName.substring(periodIndex + 1, lastIndex); if (fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionDefault.GetText() || fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionASCII.GetText() || fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionCrate.GetText() || fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionPackage.GetText()) { retValue = kIsMyFileType; } return retValue; } /* static */ const std::string& UsdMayaExportTranslator::GetDefaultOptions() { static std::string defaultOptions; static std::once_flag once; std::call_once(once, []() { std::ostringstream optionsStream; for (const std::pair<std::string, VtValue> keyValue : PXR_NS::UsdMayaJobExportArgs::GetDefaultDictionary()) { bool canConvert; std::string valueStr; std::tie(canConvert, valueStr) = UsdMayaUtil::ValueToArgument(keyValue.second); // Options don't handle empty arrays well preventing users from passing actual // values for options with such default value. if (canConvert && valueStr != "[]") { optionsStream << keyValue.first.c_str() << "=" << valueStr.c_str() << ";"; } } optionsStream << "animation=0;"; optionsStream << "startTime=1;"; optionsStream << "endTime=1;"; optionsStream << "frameStride=1.0;"; optionsStream << "frameSample=0.0;"; defaultOptions = optionsStream.str(); }); return defaultOptions; } } // namespace MAYAUSD_NS_DEF <file_sep>/test/lib/ufe/CMakeLists.txt set(TARGET_NAME UFE_TEST) # unit test scripts. Note that testTRSBase.py is not a test case, but rather # a module providing a base class for other tests. set(TEST_SCRIPT_FILES testDeleteCmd.py testMatrices.py testMayaPickwalk.py testPythonWrappers.py testSelection.py testUfePythonImport.py testAttributeBlock.py testBlockedLayerEdit.py ) set(TEST_SUPPORT_FILES testTRSBase.py ) if(CMAKE_UFE_V2_FEATURES_AVAILABLE) list(APPEND TEST_SCRIPT_FILES testAttribute.py testAttributes.py testChildFilter.py testComboCmd.py testContextOps.py testDuplicateCmd.py testGroupCmd.py testMoveCmd.py testObject3d.py testRename.py testParentCmd.py testPointInstances.py testReorderCmd.py testRotateCmd.py testRotatePivot.py testScaleCmd.py testSceneItem.py testTransform3dChainOfResponsibility.py testTransform3dTranslate.py testUIInfoHandler.py testObservableScene.py ) endif() if(CMAKE_UFE_V3_FEATURES_AVAILABLE) list(APPEND TEST_SCRIPT_FILES testUngroupCmd.py ) endif() if (MAYA_API_VERSION VERSION_GREATER_EQUAL 20220100) list(APPEND TEST_SCRIPT_FILES testCamera.py ) endif() if(MAYA_MRENDERITEM_UFE_IDENTIFIER_SUPPORT) list(APPEND TEST_SCRIPT_FILES testSetsCmd.py ) endif() # copy ufe tests to ${CMAKE_CURRENT_BINARY_DIR} and run them from there add_custom_target(${TARGET_NAME} ALL) # copy all the resources and python scripts to build directory mayaUsd_copyDirectory(${TARGET_NAME} SOURCE ${CMAKE_CURRENT_SOURCE_DIR} DESTINATION ${CMAKE_CURRENT_BINARY_DIR} EXCLUDE "*.txt" ) foreach(script ${TEST_SCRIPT_FILES}) mayaUsd_get_unittest_target(target ${script}) mayaUsd_add_test(${target} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} PYTHON_MODULE ${target} ENV "MAYA_PLUG_IN_PATH=${CMAKE_CURRENT_BINARY_DIR}/ufeTestPlugins" "UFE_PREVIEW_VERSION_NUM=${UFE_PREVIEW_VERSION_NUM}" "LD_LIBRARY_PATH=${ADDITIONAL_LD_LIBRARY_PATH}" ) # Add a ctest label to these tests for easy filtering. set_property(TEST ${target} APPEND PROPERTY LABELS ufe) endforeach() <file_sep>/lib/mayaUsd/fileio/jobs/jobArgs.cpp // // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "jobArgs.h" #include <mayaUsd/fileio/registryHelper.h> #include <mayaUsd/fileio/shading/shadingModeRegistry.h> #include <mayaUsd/utils/utilFileSystem.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/base/tf/envSetting.h> #include <pxr/base/tf/fileUtils.h> #include <pxr/base/tf/staticTokens.h> #include <pxr/base/tf/token.h> #include <pxr/base/vt/dictionary.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/sdf/schema.h> #include <pxr/usd/usd/usdaFileFormat.h> #include <pxr/usd/usd/usdcFileFormat.h> #include <pxr/usd/usdGeom/tokens.h> #include <pxr/usd/usdUtils/pipeline.h> #include <pxr/usdImaging/usdImaging/tokens.h> #include <maya/MDagPath.h> #include <maya/MFileObject.h> #include <maya/MGlobal.h> #include <maya/MNodeClass.h> #include <maya/MTypeId.h> #include <ghc/filesystem.hpp> #include <ostream> #include <string> PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_PUBLIC_TOKENS(UsdMayaTranslatorTokens, PXRUSDMAYA_TRANSLATOR_TOKENS); TF_DEFINE_PUBLIC_TOKENS(UsdMayaJobExportArgsTokens, PXRUSDMAYA_JOB_EXPORT_ARGS_TOKENS); TF_DEFINE_PUBLIC_TOKENS(UsdMayaJobImportArgsTokens, PXRUSDMAYA_JOB_IMPORT_ARGS_TOKENS); // clang-format off TF_DEFINE_PRIVATE_TOKENS( _usdExportInfoScope, (UsdMaya) (UsdExport) ); // clang-format on // clang-format off TF_DEFINE_PRIVATE_TOKENS( _usdImportInfoScope, (UsdMaya) (UsdImport) ); // clang-format on /// Extracts a bool at \p key from \p userArgs, or false if it can't extract. static bool _Boolean(const VtDictionary& userArgs, const TfToken& key) { if (!VtDictionaryIsHolding<bool>(userArgs, key)) { TF_CODING_ERROR( "Dictionary is missing required key '%s' or key is " "not bool type", key.GetText()); return false; } return VtDictionaryGet<bool>(userArgs, key); } /// Extracts a string at \p key from \p userArgs, or "" if it can't extract. static std::string _String(const VtDictionary& userArgs, const TfToken& key) { if (!VtDictionaryIsHolding<std::string>(userArgs, key)) { TF_CODING_ERROR( "Dictionary is missing required key '%s' or key is " "not string type", key.GetText()); return std::string(); } return VtDictionaryGet<std::string>(userArgs, key); } /// Extracts a token at \p key from \p userArgs. /// If the token value is not either \p defaultToken or one of the /// \p otherTokens, then returns \p defaultToken instead. static TfToken _Token( const VtDictionary& userArgs, const TfToken& key, const TfToken& defaultToken, const std::vector<TfToken>& otherTokens) { const TfToken tok(_String(userArgs, key)); for (const TfToken& allowedTok : otherTokens) { if (tok == allowedTok) { return tok; } } // Empty token will silently be promoted to default value. // Warning for non-empty tokens that don't match. if (tok != defaultToken && !tok.IsEmpty()) { TF_WARN( "Value '%s' is not allowed for flag '%s'; using fallback '%s' " "instead", tok.GetText(), key.GetText(), defaultToken.GetText()); } return defaultToken; } /// Extracts an absolute path at \p key from \p userArgs, or the empty path if /// it can't extract. static SdfPath _AbsolutePath(const VtDictionary& userArgs, const TfToken& key) { const std::string s = _String(userArgs, key); // Assume that empty strings are empty paths. (This might be an error case.) if (s.empty()) { return SdfPath(); } // Make all relative paths into absolute paths. SdfPath path(s); if (path.IsAbsolutePath()) { return path; } else { return SdfPath::AbsoluteRootPath().AppendPath(path); } } /// Extracts an vector<T> from the vector<VtValue> at \p key in \p userArgs. /// Returns an empty vector if it can't convert the entire value at \p key into /// a vector<T>. template <typename T> static std::vector<T> _Vector(const VtDictionary& userArgs, const TfToken& key) { // Check that vector exists. if (!VtDictionaryIsHolding<std::vector<VtValue>>(userArgs, key)) { TF_CODING_ERROR( "Dictionary is missing required key '%s' or key is " "not vector type", key.GetText()); return std::vector<T>(); } // Check that vector is correctly-typed. std::vector<VtValue> vals = VtDictionaryGet<std::vector<VtValue>>(userArgs, key); if (!std::all_of(vals.begin(), vals.end(), [](const VtValue& v) { return v.IsHolding<T>(); })) { TF_CODING_ERROR( "Vector at dictionary key '%s' contains elements of " "the wrong type", key.GetText()); return std::vector<T>(); } // Extract values. std::vector<T> result; for (const VtValue& v : vals) { result.push_back(v.UncheckedGet<T>()); } return result; } /// Convenience function that takes the result of _Vector and converts it to a /// TfToken::Set. static TfToken::Set _TokenSet(const VtDictionary& userArgs, const TfToken& key) { const std::vector<std::string> vec = _Vector<std::string>(userArgs, key); TfToken::Set result; for (const std::string& s : vec) { result.insert(TfToken(s)); } return result; } // The chaser args are stored as vectors of vectors (since this is how you // would need to pass them in the Maya Python command API). Convert this to a // map of maps. static std::map<std::string, UsdMayaJobExportArgs::ChaserArgs> _ChaserArgs(const VtDictionary& userArgs, const TfToken& key) { const std::vector<std::vector<VtValue>> chaserArgs = _Vector<std::vector<VtValue>>(userArgs, key); std::map<std::string, UsdMayaJobExportArgs::ChaserArgs> result; for (const std::vector<VtValue>& argTriple : chaserArgs) { if (argTriple.size() != 3) { TF_CODING_ERROR("Each chaser arg must be a triple (chaser, arg, value)"); return std::map<std::string, UsdMayaJobExportArgs::ChaserArgs>(); } const std::string& chaser = argTriple[0].Get<std::string>(); const std::string& arg = argTriple[1].Get<std::string>(); const std::string& value = argTriple[2].Get<std::string>(); result[chaser][arg] = value; } return result; } // The shadingMode args are stored as vectors of vectors (since this is how you // would need to pass them in the Maya Python command API). static UsdMayaJobImportArgs::ShadingModes _shadingModesImportArgs(const VtDictionary& userArgs, const TfToken& key) { const std::vector<std::vector<VtValue>> shadingModeArgs = _Vector<std::vector<VtValue>>(userArgs, key); const TfTokenVector modes = UsdMayaShadingModeRegistry::ListImporters(); UsdMayaJobImportArgs::ShadingModes result; for (const std::vector<VtValue>& argTuple : shadingModeArgs) { if (argTuple.size() != 2) { TF_CODING_ERROR( "Each shadingMode arg must be a tuple (shadingMode, convertMaterialFrom)"); return UsdMayaJobImportArgs::ShadingModes(); } TfToken shadingMode = TfToken(argTuple[0].Get<std::string>().c_str()); TfToken convertMaterialFrom = TfToken(argTuple[1].Get<std::string>().c_str()); if (shadingMode == UsdMayaShadingModeTokens->none) { break; } if (std::find(modes.cbegin(), modes.cend(), shadingMode) == modes.cend()) { TF_CODING_ERROR("Unknown shading mode '%s'", shadingMode.GetText()); return UsdMayaJobImportArgs::ShadingModes(); } if (shadingMode == UsdMayaShadingModeTokens->useRegistry) { auto const& info = UsdMayaShadingModeRegistry::GetMaterialConversionInfo(convertMaterialFrom); if (!info.hasImporter) { TF_CODING_ERROR("Unknown material conversion '%s'", convertMaterialFrom.GetText()); return UsdMayaJobImportArgs::ShadingModes(); } // Do not validate second parameter if not in a useRegistry scenario. } result.push_back(UsdMayaJobImportArgs::ShadingMode { shadingMode, convertMaterialFrom }); } return result; } static TfToken _GetMaterialsScopeName(const std::string& materialsScopeName) { const TfToken defaultMaterialsScopeName = UsdUtilsGetMaterialsScopeName(); if (TfGetEnvSetting(USD_FORCE_DEFAULT_MATERIALS_SCOPE_NAME)) { // If the env setting is set, make sure we don't allow the materials // scope name to be overridden by a parameter value. return defaultMaterialsScopeName; } if (SdfPath::IsValidIdentifier(materialsScopeName)) { return TfToken(materialsScopeName); } TF_CODING_ERROR( "'%s' value '%s' is not a valid identifier. Using default " "value of '%s' instead.", UsdMayaJobExportArgsTokens->materialsScopeName.GetText(), materialsScopeName.c_str(), defaultMaterialsScopeName.GetText()); return defaultMaterialsScopeName; } static PcpMapFunction::PathMap _ExportRootsMap( const VtDictionary& userArgs, const TfToken& key, bool stripNamespaces, const UsdMayaUtil::MDagPathSet& dagPaths) { PcpMapFunction::PathMap pathMap; auto addExportRootPathPairFn = [&pathMap, stripNamespaces](const MDagPath& rootDagPath) { if (!rootDagPath.isValid()) return; SdfPath rootSdfPath = UsdMayaUtil::MDagPathToUsdPath(rootDagPath, false, stripNamespaces); if (rootSdfPath.IsEmpty()) return; SdfPath newRootSdfPath = rootSdfPath.ReplacePrefix(rootSdfPath.GetParentPath(), SdfPath::AbsoluteRootPath()); pathMap[rootSdfPath] = newRootSdfPath; }; bool includeEntireSelection = false; const std::vector<std::string> exportRoots = _Vector<std::string>(userArgs, key); for (const std::string& rootPath : exportRoots) { if (!rootPath.empty()) { MDagPath rootDagPath; UsdMayaUtil::GetDagPathByName(rootPath, rootDagPath); addExportRootPathPairFn(rootDagPath); } else { includeEntireSelection = true; } } if (includeEntireSelection) { for (const MDagPath& dagPath : dagPaths) { addExportRootPathPairFn(dagPath); } } return pathMap; } static void _AddFilteredTypeName(const MString& typeName, std::set<unsigned int>& filteredTypeIds) { MNodeClass cls(typeName); unsigned int id = cls.typeId().id(); if (id == 0) { TF_WARN("Given excluded node type '%s' does not exist; ignoring", typeName.asChar()); return; } filteredTypeIds.insert(id); // We also insert all inherited types - only way to query this is through mel, // which is slower, but this should be ok, as these queries are only done // "up front" when the export starts, not per-node MString queryCommand("nodeType -isTypeName -derived "); queryCommand += typeName; MStringArray inheritedTypes; MStatus status = MGlobal::executeCommand(queryCommand, inheritedTypes, false, false); if (!status) { TF_WARN( "Error querying derived types for '%s': %s", typeName.asChar(), status.errorString().asChar()); return; } for (unsigned int i = 0; i < inheritedTypes.length(); ++i) { if (inheritedTypes[i].length() == 0) continue; id = MNodeClass(inheritedTypes[i]).typeId().id(); if (id == 0) { // Unfortunately, the returned list will often include weird garbage, like // "THconstraint" for "constraint", which cannot be converted to a MNodeClass, // so just ignore these... continue; } filteredTypeIds.insert(id); } } static std::set<unsigned int> _FilteredTypeIds(const VtDictionary& userArgs) { const std::vector<std::string> vec = _Vector<std::string>(userArgs, UsdMayaJobExportArgsTokens->filterTypes); std::set<unsigned int> result; for (const std::string& s : vec) { _AddFilteredTypeName(s.c_str(), result); } return result; } UsdMayaJobExportArgs::UsdMayaJobExportArgs( const VtDictionary& userArgs, const UsdMayaUtil::MDagPathSet& dagPaths, const std::vector<double>& timeSamples) : compatibility(_Token( userArgs, UsdMayaJobExportArgsTokens->compatibility, UsdMayaJobExportArgsTokens->none, { UsdMayaJobExportArgsTokens->appleArKit })) , defaultMeshScheme(_Token( userArgs, UsdMayaJobExportArgsTokens->defaultMeshScheme, UsdGeomTokens->catmullClark, { UsdGeomTokens->loop, UsdGeomTokens->bilinear, UsdGeomTokens->none })) , defaultUSDFormat(_Token( userArgs, UsdMayaJobExportArgsTokens->defaultUSDFormat, UsdUsdcFileFormatTokens->Id, { UsdUsdaFileFormatTokens->Id })) , eulerFilter(_Boolean(userArgs, UsdMayaJobExportArgsTokens->eulerFilter)) , excludeInvisible(_Boolean(userArgs, UsdMayaJobExportArgsTokens->renderableOnly)) , exportCollectionBasedBindings( _Boolean(userArgs, UsdMayaJobExportArgsTokens->exportCollectionBasedBindings)) , exportColorSets(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportColorSets)) , exportDefaultCameras(_Boolean(userArgs, UsdMayaJobExportArgsTokens->defaultCameras)) , exportDisplayColor(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportDisplayColor)) , exportInstances(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportInstances)) , exportMaterialCollections( _Boolean(userArgs, UsdMayaJobExportArgsTokens->exportMaterialCollections)) , exportMeshUVs(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportUVs)) , exportNurbsExplicitUV(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportUVs)) , exportReferenceObjects(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportReferenceObjects)) , exportRefsAsInstanceable( _Boolean(userArgs, UsdMayaJobExportArgsTokens->exportRefsAsInstanceable)) , exportSkels(_Token( userArgs, UsdMayaJobExportArgsTokens->exportSkels, UsdMayaJobExportArgsTokens->none, { UsdMayaJobExportArgsTokens->auto_, UsdMayaJobExportArgsTokens->explicit_ })) , exportSkin(_Token( userArgs, UsdMayaJobExportArgsTokens->exportSkin, UsdMayaJobExportArgsTokens->none, { UsdMayaJobExportArgsTokens->auto_, UsdMayaJobExportArgsTokens->explicit_ })) , exportBlendShapes(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportBlendShapes)) , exportVisibility(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportVisibility)) , file(_String(userArgs, UsdMayaJobExportArgsTokens->file)) , ignoreWarnings(_Boolean(userArgs, UsdMayaJobExportArgsTokens->ignoreWarnings)) , materialCollectionsPath( _AbsolutePath(userArgs, UsdMayaJobExportArgsTokens->materialCollectionsPath)) , materialsScopeName( _GetMaterialsScopeName(_String(userArgs, UsdMayaJobExportArgsTokens->materialsScopeName))) , mergeTransformAndShape(_Boolean(userArgs, UsdMayaJobExportArgsTokens->mergeTransformAndShape)) , normalizeNurbs(_Boolean(userArgs, UsdMayaJobExportArgsTokens->normalizeNurbs)) , stripNamespaces(_Boolean(userArgs, UsdMayaJobExportArgsTokens->stripNamespaces)) , parentScope(_AbsolutePath(userArgs, UsdMayaJobExportArgsTokens->parentScope)) , renderLayerMode(_Token( userArgs, UsdMayaJobExportArgsTokens->renderLayerMode, UsdMayaJobExportArgsTokens->defaultLayer, { UsdMayaJobExportArgsTokens->currentLayer, UsdMayaJobExportArgsTokens->modelingVariant })) , rootKind(_String(userArgs, UsdMayaJobExportArgsTokens->kind)) , shadingMode(_Token( userArgs, UsdMayaJobExportArgsTokens->shadingMode, UsdMayaShadingModeTokens->none, UsdMayaShadingModeRegistry::ListExporters())) , convertMaterialsTo(_Token( userArgs, UsdMayaJobExportArgsTokens->convertMaterialsTo, UsdImagingTokens->UsdPreviewSurface, UsdMayaShadingModeRegistry::ListMaterialConversions())) , verbose(_Boolean(userArgs, UsdMayaJobExportArgsTokens->verbose)) , staticSingleSample(_Boolean(userArgs, UsdMayaJobExportArgsTokens->staticSingleSample)) , geomSidedness(_Token( userArgs, UsdMayaJobExportArgsTokens->geomSidedness, UsdMayaJobExportArgsTokens->derived, { UsdMayaJobExportArgsTokens->single, UsdMayaJobExportArgsTokens->double_ })) , chaserNames(_Vector<std::string>(userArgs, UsdMayaJobExportArgsTokens->chaser)) , allChaserArgs(_ChaserArgs(userArgs, UsdMayaJobExportArgsTokens->chaserArgs)) , melPerFrameCallback(_String(userArgs, UsdMayaJobExportArgsTokens->melPerFrameCallback)) , melPostCallback(_String(userArgs, UsdMayaJobExportArgsTokens->melPostCallback)) , pythonPerFrameCallback(_String(userArgs, UsdMayaJobExportArgsTokens->pythonPerFrameCallback)) , pythonPostCallback(_String(userArgs, UsdMayaJobExportArgsTokens->pythonPostCallback)) , dagPaths(dagPaths) , timeSamples(timeSamples) , rootMapFunction(PcpMapFunction::Create( _ExportRootsMap( userArgs, UsdMayaJobExportArgsTokens->exportRoots, stripNamespaces, dagPaths), SdfLayerOffset())) , filteredTypeIds(_FilteredTypeIds(userArgs)) { } std::ostream& operator<<(std::ostream& out, const UsdMayaJobExportArgs& exportArgs) { out << "compatibility: " << exportArgs.compatibility << std::endl << "defaultMeshScheme: " << exportArgs.defaultMeshScheme << std::endl << "defaultUSDFormat: " << exportArgs.defaultUSDFormat << std::endl << "eulerFilter: " << TfStringify(exportArgs.eulerFilter) << std::endl << "excludeInvisible: " << TfStringify(exportArgs.excludeInvisible) << std::endl << "exportCollectionBasedBindings: " << TfStringify(exportArgs.exportCollectionBasedBindings) << std::endl << "exportColorSets: " << TfStringify(exportArgs.exportColorSets) << std::endl << "exportDefaultCameras: " << TfStringify(exportArgs.exportDefaultCameras) << std::endl << "exportDisplayColor: " << TfStringify(exportArgs.exportDisplayColor) << std::endl << "exportInstances: " << TfStringify(exportArgs.exportInstances) << std::endl << "exportMaterialCollections: " << TfStringify(exportArgs.exportMaterialCollections) << std::endl << "exportMeshUVs: " << TfStringify(exportArgs.exportMeshUVs) << std::endl << "exportNurbsExplicitUV: " << TfStringify(exportArgs.exportNurbsExplicitUV) << std::endl << "exportRefsAsInstanceable: " << TfStringify(exportArgs.exportRefsAsInstanceable) << std::endl << "exportSkels: " << TfStringify(exportArgs.exportSkels) << std::endl << "exportSkin: " << TfStringify(exportArgs.exportSkin) << std::endl << "exportBlendShapes: " << TfStringify(exportArgs.exportBlendShapes) << std::endl << "exportVisibility: " << TfStringify(exportArgs.exportVisibility) << std::endl << "file: " << exportArgs.file << std::endl << "ignoreWarnings: " << TfStringify(exportArgs.ignoreWarnings) << std::endl << "materialCollectionsPath: " << exportArgs.materialCollectionsPath << std::endl << "materialsScopeName: " << exportArgs.materialsScopeName << std::endl << "mergeTransformAndShape: " << TfStringify(exportArgs.mergeTransformAndShape) << std::endl << "normalizeNurbs: " << TfStringify(exportArgs.normalizeNurbs) << std::endl << "parentScope: " << exportArgs.parentScope << std::endl << "renderLayerMode: " << exportArgs.renderLayerMode << std::endl << "rootKind: " << exportArgs.rootKind << std::endl << "shadingMode: " << exportArgs.shadingMode << std::endl << "convertMaterialsTo: " << exportArgs.convertMaterialsTo << std::endl << "stripNamespaces: " << TfStringify(exportArgs.stripNamespaces) << std::endl << "timeSamples: " << exportArgs.timeSamples.size() << " sample(s)" << std::endl << "staticSingleSample: " << TfStringify(exportArgs.staticSingleSample) << std::endl << "geomSidedness: " << TfStringify(exportArgs.geomSidedness) << std::endl << "usdModelRootOverridePath: " << exportArgs.usdModelRootOverridePath << std::endl; out << "melPerFrameCallback: " << exportArgs.melPerFrameCallback << std::endl << "melPostCallback: " << exportArgs.melPostCallback << std::endl << "pythonPerFrameCallback: " << exportArgs.pythonPerFrameCallback << std::endl << "pythonPostCallback: " << exportArgs.pythonPostCallback << std::endl; out << "dagPaths (" << exportArgs.dagPaths.size() << ")" << std::endl; for (const MDagPath& dagPath : exportArgs.dagPaths) { out << " " << dagPath.fullPathName().asChar() << std::endl; } out << "filteredTypeIds (" << exportArgs.filteredTypeIds.size() << ")" << std::endl; for (unsigned int id : exportArgs.filteredTypeIds) { out << " " << id << ": " << MNodeClass(MTypeId(id)).typeName() << std::endl; } out << "chaserNames (" << exportArgs.chaserNames.size() << ")" << std::endl; for (const std::string& chaserName : exportArgs.chaserNames) { out << " " << chaserName << std::endl; } out << "allChaserArgs (" << exportArgs.allChaserArgs.size() << ")" << std::endl; for (const auto& chaserIter : exportArgs.allChaserArgs) { // Chaser name. out << " " << chaserIter.first << std::endl; for (const auto& argIter : chaserIter.second) { out << " Arg Name: " << argIter.first << ", Value: " << argIter.second << std::endl; } } out << "exportRootMapFunction (" << exportArgs.rootMapFunction.GetString() << ")" << std::endl; return out; } /* static */ UsdMayaJobExportArgs UsdMayaJobExportArgs::CreateFromDictionary( const VtDictionary& userArgs, const UsdMayaUtil::MDagPathSet& dagPaths, const std::vector<double>& timeSamples) { return UsdMayaJobExportArgs( VtDictionaryOver(userArgs, GetDefaultDictionary()), dagPaths, timeSamples); } /* static */ const VtDictionary& UsdMayaJobExportArgs::GetDefaultDictionary() { static VtDictionary d; static std::once_flag once; std::call_once(once, []() { // Base defaults. d[UsdMayaJobExportArgsTokens->chaser] = std::vector<VtValue>(); d[UsdMayaJobExportArgsTokens->chaserArgs] = std::vector<VtValue>(); d[UsdMayaJobExportArgsTokens->compatibility] = UsdMayaJobExportArgsTokens->none.GetString(); d[UsdMayaJobExportArgsTokens->defaultCameras] = false; d[UsdMayaJobExportArgsTokens->defaultMeshScheme] = UsdGeomTokens->catmullClark.GetString(); d[UsdMayaJobExportArgsTokens->defaultUSDFormat] = UsdUsdcFileFormatTokens->Id.GetString(); d[UsdMayaJobExportArgsTokens->eulerFilter] = false; d[UsdMayaJobExportArgsTokens->exportCollectionBasedBindings] = false; d[UsdMayaJobExportArgsTokens->exportColorSets] = true; d[UsdMayaJobExportArgsTokens->exportDisplayColor] = false; d[UsdMayaJobExportArgsTokens->exportInstances] = true; d[UsdMayaJobExportArgsTokens->exportMaterialCollections] = false; d[UsdMayaJobExportArgsTokens->exportReferenceObjects] = false; d[UsdMayaJobExportArgsTokens->exportRefsAsInstanceable] = false; d[UsdMayaJobExportArgsTokens->exportRoots] = std::vector<VtValue>(); d[UsdMayaJobExportArgsTokens->exportSkin] = UsdMayaJobExportArgsTokens->none.GetString(); d[UsdMayaJobExportArgsTokens->exportSkels] = UsdMayaJobExportArgsTokens->none.GetString(); d[UsdMayaJobExportArgsTokens->exportBlendShapes] = false; d[UsdMayaJobExportArgsTokens->exportUVs] = true; d[UsdMayaJobExportArgsTokens->exportVisibility] = true; d[UsdMayaJobExportArgsTokens->file] = std::string(); d[UsdMayaJobExportArgsTokens->filterTypes] = std::vector<VtValue>(); d[UsdMayaJobExportArgsTokens->ignoreWarnings] = false; d[UsdMayaJobExportArgsTokens->kind] = std::string(); d[UsdMayaJobExportArgsTokens->materialCollectionsPath] = std::string(); d[UsdMayaJobExportArgsTokens->materialsScopeName] = UsdUtilsGetMaterialsScopeName().GetString(); d[UsdMayaJobExportArgsTokens->melPerFrameCallback] = std::string(); d[UsdMayaJobExportArgsTokens->melPostCallback] = std::string(); d[UsdMayaJobExportArgsTokens->mergeTransformAndShape] = true; d[UsdMayaJobExportArgsTokens->normalizeNurbs] = false; d[UsdMayaJobExportArgsTokens->parentScope] = std::string(); d[UsdMayaJobExportArgsTokens->pythonPerFrameCallback] = std::string(); d[UsdMayaJobExportArgsTokens->pythonPostCallback] = std::string(); d[UsdMayaJobExportArgsTokens->renderableOnly] = false; d[UsdMayaJobExportArgsTokens->renderLayerMode] = UsdMayaJobExportArgsTokens->defaultLayer.GetString(); d[UsdMayaJobExportArgsTokens->shadingMode] = UsdMayaShadingModeTokens->useRegistry.GetString(); d[UsdMayaJobExportArgsTokens->convertMaterialsTo] = UsdImagingTokens->UsdPreviewSurface.GetString(); d[UsdMayaJobExportArgsTokens->stripNamespaces] = false; d[UsdMayaJobExportArgsTokens->verbose] = false; d[UsdMayaJobExportArgsTokens->staticSingleSample] = false; d[UsdMayaJobExportArgsTokens->geomSidedness] = UsdMayaJobExportArgsTokens->derived.GetString(); // plugInfo.json site defaults. // The defaults dict should be correctly-typed, so enable // coerceToWeakerOpinionType. const VtDictionary site = UsdMaya_RegistryHelper::GetComposedInfoDictionary(_usdExportInfoScope->allTokens); VtDictionaryOver(site, &d, /*coerceToWeakerOpinionType*/ true); }); return d; } std::string UsdMayaJobExportArgs::GetResolvedFileName() const { MFileObject fileObj; fileObj.setRawFullName(file.c_str()); // Make sure it's an absolute path fileObj.setRawFullName(fileObj.resolvedFullName()); const std::string resolvedFileName = fileObj.resolvedFullName().asChar(); if (!resolvedFileName.empty()) { return resolvedFileName; } return file; } UsdMayaJobImportArgs::UsdMayaJobImportArgs( const VtDictionary& userArgs, const bool importWithProxyShapes, const GfInterval& timeInterval) : assemblyRep(_Token( userArgs, UsdMayaJobImportArgsTokens->assemblyRep, UsdMayaJobImportArgsTokens->Collapsed, { UsdMayaJobImportArgsTokens->Full, UsdMayaJobImportArgsTokens->Import, UsdMayaJobImportArgsTokens->Unloaded })) , excludePrimvarNames(_TokenSet(userArgs, UsdMayaJobImportArgsTokens->excludePrimvar)) , includeAPINames(_TokenSet(userArgs, UsdMayaJobImportArgsTokens->apiSchema)) , includeMetadataKeys(_TokenSet(userArgs, UsdMayaJobImportArgsTokens->metadata)) , shadingModes(_shadingModesImportArgs(userArgs, UsdMayaJobImportArgsTokens->shadingMode)) , preferredMaterial(_Token( userArgs, UsdMayaJobImportArgsTokens->preferredMaterial, UsdMayaPreferredMaterialTokens->none, UsdMayaPreferredMaterialTokens->allTokens)) , importUSDZTexturesFilePath(UsdMayaJobImportArgs::GetImportUSDZTexturesFilePath(userArgs)) , importUSDZTextures(_Boolean(userArgs, UsdMayaJobImportArgsTokens->importUSDZTextures)) , importInstances(_Boolean(userArgs, UsdMayaJobImportArgsTokens->importInstances)) , useAsAnimationCache(_Boolean(userArgs, UsdMayaJobImportArgsTokens->useAsAnimationCache)) , importWithProxyShapes(importWithProxyShapes) , timeInterval(timeInterval) , chaserNames(_Vector<std::string>(userArgs, UsdMayaJobImportArgsTokens->chaser)) , allChaserArgs(_ChaserArgs(userArgs, UsdMayaJobImportArgsTokens->chaserArgs)) { } TfToken UsdMayaJobImportArgs::GetMaterialConversion() const { return shadingModes.empty() ? TfToken() : shadingModes.front().materialConversion; } /* static */ UsdMayaJobImportArgs UsdMayaJobImportArgs::CreateFromDictionary( const VtDictionary& userArgs, const bool importWithProxyShapes, const GfInterval& timeInterval) { return UsdMayaJobImportArgs( VtDictionaryOver(userArgs, GetDefaultDictionary()), importWithProxyShapes, timeInterval); } /* static */ const VtDictionary& UsdMayaJobImportArgs::GetDefaultDictionary() { static VtDictionary d; static std::once_flag once; std::call_once(once, []() { // Base defaults. d[UsdMayaJobImportArgsTokens->assemblyRep] = UsdMayaJobImportArgsTokens->Collapsed.GetString(); d[UsdMayaJobImportArgsTokens->apiSchema] = std::vector<VtValue>(); d[UsdMayaJobImportArgsTokens->excludePrimvar] = std::vector<VtValue>(); d[UsdMayaJobImportArgsTokens->metadata] = std::vector<VtValue>({ VtValue(SdfFieldKeys->Hidden.GetString()), VtValue(SdfFieldKeys->Instanceable.GetString()), VtValue(SdfFieldKeys->Kind.GetString()) }); d[UsdMayaJobImportArgsTokens->shadingMode] = std::vector<VtValue> { VtValue( std::vector<VtValue> { VtValue(UsdMayaShadingModeTokens->useRegistry.GetString()), VtValue(UsdImagingTokens->UsdPreviewSurface.GetString()) }) }; d[UsdMayaJobImportArgsTokens->preferredMaterial] = UsdMayaPreferredMaterialTokens->none.GetString(); d[UsdMayaJobImportArgsTokens->importInstances] = true; d[UsdMayaJobImportArgsTokens->importUSDZTextures] = false; d[UsdMayaJobImportArgsTokens->importUSDZTexturesFilePath] = ""; d[UsdMayaJobImportArgsTokens->useAsAnimationCache] = false; d[UsdMayaJobExportArgsTokens->chaser] = std::vector<VtValue>(); d[UsdMayaJobExportArgsTokens->chaserArgs] = std::vector<VtValue>(); // plugInfo.json site defaults. // The defaults dict should be correctly-typed, so enable // coerceToWeakerOpinionType. const VtDictionary site = UsdMaya_RegistryHelper::GetComposedInfoDictionary(_usdImportInfoScope->allTokens); VtDictionaryOver(site, &d, /*coerceToWeakerOpinionType*/ true); }); return d; } const std::string UsdMayaJobImportArgs::GetImportUSDZTexturesFilePath(const VtDictionary& userArgs) { if (!_Boolean(userArgs, UsdMayaJobImportArgsTokens->importUSDZTextures)) return ""; // Not importing textures. File path stays empty. const std::string pathArg = _String(userArgs, UsdMayaJobImportArgsTokens->importUSDZTexturesFilePath); std::string importTexturesRootDirPath; if (pathArg.size() == 0) { // NOTE: (yliangsiew) If the user gives an empty argument, we'll try // to determine the best directory to write to instead. MString currentMayaWorkspacePath = UsdMayaUtil::GetCurrentMayaWorkspacePath(); MString currentMayaSceneFilePath = UsdMayaUtil::GetCurrentSceneFilePath(); if (currentMayaSceneFilePath.length() != 0 && strstr(currentMayaSceneFilePath.asChar(), currentMayaWorkspacePath.asChar()) == NULL) { TF_RUNTIME_ERROR( "The current scene does not seem to be part of the current Maya project set. " "Could not automatically determine a path to write out USDZ texture imports."); return ""; } if (currentMayaWorkspacePath.length() == 0 || !ghc::filesystem::is_directory(currentMayaWorkspacePath.asChar())) { TF_RUNTIME_ERROR( "Could not automatically determine a path to write out USDZ texture imports. " "Please specify a location using the -importUSDZTexturesFilePath argument, or " "set the Maya project appropriately."); return ""; } else { // NOTE: (yliangsiew) Textures are, by convention, supposed to be located in the // `sourceimages` folder under a Maya project root folder. importTexturesRootDirPath.assign( currentMayaWorkspacePath.asChar(), currentMayaWorkspacePath.length()); MString sourceImagesDirBaseName = MGlobal::executeCommandStringResult("workspace -fre \"sourceImages\""); if (sourceImagesDirBaseName.length() == 0) { TF_RUNTIME_ERROR( "Unable to determine the sourceImages fileRule for the Maya project: %s.", currentMayaWorkspacePath.asChar()); return ""; } bool bStat = UsdMayaUtilFileSystem::pathAppendPath( importTexturesRootDirPath, sourceImagesDirBaseName.asChar()); if (!bStat) { TF_RUNTIME_ERROR( "Unable to determine the texture directory for the Maya project: %s.", currentMayaWorkspacePath.asChar()); return ""; } // Make sure the sourceimage folder is created in the project: TfMakeDirs(importTexturesRootDirPath); } } else { importTexturesRootDirPath.assign(pathArg); } if (!ghc::filesystem::is_directory(importTexturesRootDirPath)) { TF_RUNTIME_ERROR( "The directory specified for USDZ texture imports: %s is not valid.", importTexturesRootDirPath.c_str()); return ""; } return importTexturesRootDirPath; } std::ostream& operator<<(std::ostream& out, const UsdMayaJobImportArgs& importArgs) { out << "shadingModes (" << importArgs.shadingModes.size() << ")" << std::endl; for (const auto& shadingMode : importArgs.shadingModes) { out << " " << TfStringify(shadingMode.mode) << ", " << TfStringify(shadingMode.materialConversion) << std::endl; } out << "preferredMaterial: " << importArgs.preferredMaterial << std::endl << "assemblyRep: " << importArgs.assemblyRep << std::endl << "importInstances: " << TfStringify(importArgs.importInstances) << std::endl << "importUSDZTextures: " << TfStringify(importArgs.importUSDZTextures) << std::endl << "importUSDZTexturesFilePath: " << TfStringify(importArgs.importUSDZTexturesFilePath) << std::endl << "timeInterval: " << importArgs.timeInterval << std::endl << "useAsAnimationCache: " << TfStringify(importArgs.useAsAnimationCache) << std::endl << "importWithProxyShapes: " << TfStringify(importArgs.importWithProxyShapes) << std::endl; out << "chaserNames (" << importArgs.chaserNames.size() << ")" << std::endl; for (const std::string& chaserName : importArgs.chaserNames) { out << " " << chaserName << std::endl; } out << "allChaserArgs (" << importArgs.allChaserArgs.size() << ")" << std::endl; for (const auto& chaserIter : importArgs.allChaserArgs) { // Chaser name. out << " " << chaserIter.first << std::endl; for (const auto& argIter : chaserIter.second) { out << " Arg Name: " << argIter.first << ", Value: " << argIter.second << std::endl; } } return out; } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/lib/mayaUsd/ufe/Global.cpp // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "Global.h" #include "private/UfeNotifGuard.h" #include <mayaUsd/ufe/ProxyShapeHandler.h> #include <mayaUsd/ufe/ProxyShapeHierarchyHandler.h> #include <mayaUsd/ufe/StagesSubject.h> #include <mayaUsd/ufe/UfeVersionCompat.h> #include <mayaUsd/ufe/UsdHierarchyHandler.h> #include <mayaUsd/ufe/UsdSceneItemOpsHandler.h> #include <mayaUsd/ufe/UsdTransform3dHandler.h> #ifdef UFE_V2_FEATURES_AVAILABLE #include <mayaUsd/ufe/ProxyShapeContextOpsHandler.h> #include <mayaUsd/ufe/UsdAttributesHandler.h> #include <mayaUsd/ufe/UsdCameraHandler.h> #include <mayaUsd/ufe/UsdContextOpsHandler.h> #include <mayaUsd/ufe/UsdObject3dHandler.h> #include <mayaUsd/ufe/UsdTransform3dCommonAPI.h> #include <mayaUsd/ufe/UsdTransform3dFallbackMayaXformStack.h> #include <mayaUsd/ufe/UsdTransform3dMatrixOp.h> #include <mayaUsd/ufe/UsdTransform3dMayaXformStack.h> #include <mayaUsd/ufe/UsdTransform3dPointInstance.h> #include <mayaUsd/ufe/UsdUIInfoHandler.h> #include <mayaUsd/ufe/UsdUIUfeObserver.h> #endif #include <ufe/hierarchyHandler.h> #include <ufe/runTimeMgr.h> #ifdef UFE_V2_FEATURES_AVAILABLE #include <ufe/pathString.h> #endif #include <cassert> #include <string> namespace { int gRegistrationCount = 0; } namespace MAYAUSD_NS_DEF { namespace ufe { //------------------------------------------------------------------------------ // Global variables //------------------------------------------------------------------------------ // Maya's UFE run-time name and ID. static const std::string kMayaRunTimeName("Maya-DG"); Ufe::Rtid g_MayaRtid = 0; // Register this run-time with UFE under the following name. static const std::string kUSDRunTimeName("USD"); // Our run-time ID, allocated by UFE at registration time. Initialize it // with illegal 0 value. Ufe::Rtid g_USDRtid = 0; // The normal Maya hierarchy handler, which we decorate for ProxyShape support. // Keep a reference to it to restore on finalization. Ufe::HierarchyHandler::Ptr g_MayaHierarchyHandler; #ifdef UFE_V2_FEATURES_AVAILABLE // The normal Maya context ops handler, which we decorate for ProxyShape support. // Keep a reference to it to restore on finalization. Ufe::ContextOpsHandler::Ptr g_MayaContextOpsHandler; #endif // Subject singleton for observation of all USD stages. StagesSubject::Ptr g_StagesSubject; bool InPathChange::inGuard = false; bool InAddOrDeleteOperation::inGuard = false; //------------------------------------------------------------------------------ // Functions //------------------------------------------------------------------------------ // Only intended to be called by the plugin initialization, to // initialize the stage model. MStatus initialize() { // If we're already registered, do nothing. if (gRegistrationCount++ > 0) return MS::kSuccess; // Replace the Maya hierarchy handler with ours. g_MayaRtid = Ufe::RunTimeMgr::instance().getId(kMayaRunTimeName); #if !defined(NDEBUG) assert(g_MayaRtid != 0); #endif if (g_MayaRtid == 0) return MS::kFailure; g_MayaHierarchyHandler = Ufe::RunTimeMgr::instance().hierarchyHandler(g_MayaRtid); auto proxyShapeHierHandler = ProxyShapeHierarchyHandler::create(g_MayaHierarchyHandler); Ufe::RunTimeMgr::instance().setHierarchyHandler(g_MayaRtid, proxyShapeHierHandler); #ifdef UFE_V2_FEATURES_AVAILABLE g_MayaContextOpsHandler = Ufe::RunTimeMgr::instance().contextOpsHandler(g_MayaRtid); auto proxyShapeContextOpsHandler = ProxyShapeContextOpsHandler::create(g_MayaContextOpsHandler); Ufe::RunTimeMgr::instance().setContextOpsHandler(g_MayaRtid, proxyShapeContextOpsHandler); #endif #ifdef UFE_V2_FEATURES_AVAILABLE Ufe::RunTimeMgr::Handlers handlers; handlers.hierarchyHandler = UsdHierarchyHandler::create(); handlers.sceneItemOpsHandler = UsdSceneItemOpsHandler::create(); handlers.attributesHandler = UsdAttributesHandler::create(); handlers.object3dHandler = UsdObject3dHandler::create(); handlers.contextOpsHandler = UsdContextOpsHandler::create(); handlers.uiInfoHandler = UsdUIInfoHandler::create(); handlers.cameraHandler = UsdCameraHandler::create(); // USD has a very flexible data model to support 3d transformations --- see // https://graphics.pixar.com/usd/docs/api/class_usd_geom_xformable.html // // To map this flexibility into a UFE Transform3d handler, we set up a // chain of responsibility // https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern // for Transform3d interface creation, from least important to most // important: // - Perform operations on a Maya transform stack appended to the existing // transform stack (fallback). // - Perform operations on a 4x4 matrix transform op. // - Perform operations using the USD common transform API. // - Perform operations using a Maya transform stack. // - If the object is a point instance, use the point instance handler. auto fallbackHandler = MayaUsd::ufe::UsdTransform3dFallbackMayaXformStackHandler::create(); auto matrixHandler = MayaUsd::ufe::UsdTransform3dMatrixOpHandler::create(fallbackHandler); auto commonAPIHandler = MayaUsd::ufe::UsdTransform3dCommonAPIHandler::create(matrixHandler); auto mayaStackHandler = MayaUsd::ufe::UsdTransform3dMayaXformStackHandler::create(commonAPIHandler); auto pointInstanceHandler = MayaUsd::ufe::UsdTransform3dPointInstanceHandler::create(mayaStackHandler); handlers.transform3dHandler = pointInstanceHandler; g_USDRtid = Ufe::RunTimeMgr::instance().register_(kUSDRunTimeName, handlers); MayaUsd::ufe::UsdUIUfeObserver::create(); #else auto usdHierHandler = UsdHierarchyHandler::create(); auto usdTrans3dHandler = UsdTransform3dHandler::create(); auto usdSceneItemOpsHandler = UsdSceneItemOpsHandler::create(); g_USDRtid = Ufe::RunTimeMgr::instance().register_( kUSDRunTimeName, usdHierHandler, usdTrans3dHandler, usdSceneItemOpsHandler); #endif #if !defined(NDEBUG) assert(g_USDRtid != 0); #endif if (g_USDRtid == 0) return MS::kFailure; g_StagesSubject = StagesSubject::create(); // Register for UFE string to path service using path component separator '/' UFE_V2(Ufe::PathString::registerPathComponentSeparator(g_USDRtid, '/');) return MS::kSuccess; } MStatus finalize() { // If more than one plugin still has us registered, do nothing. if (gRegistrationCount-- > 1) return MS::kSuccess; // Restore the normal Maya hierarchy handler, and unregister. Ufe::RunTimeMgr::instance().setHierarchyHandler(g_MayaRtid, g_MayaHierarchyHandler); #ifdef UFE_V2_FEATURES_AVAILABLE // Restore the normal Maya context ops handler (can be empty). if (g_MayaContextOpsHandler) Ufe::RunTimeMgr::instance().setContextOpsHandler(g_MayaRtid, g_MayaContextOpsHandler); g_MayaContextOpsHandler.reset(); MayaUsd::ufe::UsdUIUfeObserver::destroy(); #endif Ufe::RunTimeMgr::instance().unregister(g_USDRtid); g_MayaHierarchyHandler.reset(); g_StagesSubject.Reset(); return MS::kSuccess; } Ufe::Rtid getUsdRunTimeId() { return g_USDRtid; } Ufe::Rtid getMayaRunTimeId() { return g_MayaRtid; } } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/lib/usd/translators/shading/mtlxBaseWriter.h // // Copyright 2021 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef MTLXTRANSLATORS_BASE_WRITER_H #define MTLXTRANSLATORS_BASE_WRITER_H /// \file #include <mayaUsd/fileio/shaderWriter.h> #include <pxr/pxr.h> PXR_NAMESPACE_OPEN_SCOPE /// Shader writer for exporting Maya's material shading nodes to MaterialX. class MtlxUsd_BaseWriter : public UsdMayaShaderWriter { public: MtlxUsd_BaseWriter( const MFnDependencyNode& depNodeFn, const SdfPath& usdPath, UsdMayaWriteJobContext& jobCtx); static ContextSupport CanExport(const UsdMayaJobExportArgs&); protected: // Returns the node graph where all ancillary nodes reside UsdPrim GetNodeGraph(); // Add a direct conversion node from one type to another: UsdAttribute AddConversion( const SdfValueTypeName& fromType, const SdfValueTypeName& toType, UsdAttribute nodeOutput); // Add a swizzle node to the current node to extract a channel from a color output: UsdAttribute AddSwizzle(const std::string& channel, int numChannels); // Add a swizzle node to extract a channel from a color output: UsdAttribute AddSwizzle(const std::string& channel, int numChannels, UsdAttribute nodeOutput); // Add a luminance node to the current node to get an alpha value from an RGB texture: UsdAttribute AddLuminance(int numChannels); // Add normal mapping functionnality to a normal input UsdAttribute AddNormalMapping(UsdAttribute normalInput); }; PXR_NAMESPACE_CLOSE_SCOPE #endif <file_sep>/lib/usd/hdMaya/utils.cpp // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "utils.h" #include <pxr/base/tf/token.h> #include <pxr/pxr.h> #include <maya/MFnDependencyNode.h> #include <maya/MObject.h> #include <maya/MPlugArray.h> #include <maya/MStatus.h> #if PXR_VERSION < 2011 #include <pxr/base/tf/fileUtils.h> #include <pxr/imaging/glf/contextCaps.h> #include <pxr/imaging/glf/image.h> #include <pxr/imaging/glf/textureHandle.h> #include <pxr/imaging/glf/textureRegistry.h> #include <pxr/imaging/glf/udimTexture.h> #include <pxr/imaging/hdSt/textureResource.h> #include <pxr/usdImaging/usdImaging/textureUtils.h> #include <tuple> #endif PXR_NAMESPACE_OPEN_SCOPE #if PXR_VERSION < 2011 namespace { class UdimTextureFactory : public GlfTextureFactoryBase { public: virtual GlfTextureRefPtr New(TfToken const& texturePath, GlfImage::ImageOriginLocation originLocation = GlfImage::OriginLowerLeft) const override { const GlfContextCaps& caps = GlfContextCaps::GetInstance(); return GlfUdimTexture::New( texturePath, originLocation, UsdImaging_GetUdimTiles(texturePath, caps.maxArrayTextureLayers)); } virtual GlfTextureRefPtr New(TfTokenVector const& texturePaths, GlfImage::ImageOriginLocation originLocation = GlfImage::OriginLowerLeft) const override { return nullptr; } }; } // namespace #endif // PXR_VERSION < 2011 MObject GetConnectedFileNode(const MObject& obj, const TfToken& paramName) { MStatus status; MFnDependencyNode node(obj, &status); if (ARCH_UNLIKELY(!status)) { return MObject::kNullObj; } return GetConnectedFileNode(node, paramName); } MObject GetConnectedFileNode(const MFnDependencyNode& node, const TfToken& paramName) { MPlugArray conns; node.findPlug(paramName.GetText(), true).connectedTo(conns, true, false); if (conns.length() == 0) { return MObject::kNullObj; } const auto ret = conns[0].node(); if (ret.apiType() == MFn::kFileTexture) { return ret; } return MObject::kNullObj; } TfToken GetFileTexturePath(const MFnDependencyNode& fileNode) { if (fileNode.findPlug(MayaAttrs::file::uvTilingMode, true).asShort() != 0) { const TfToken ret { fileNode.findPlug(MayaAttrs::file::fileTextureNamePattern, true).asString().asChar() }; return ret.IsEmpty() ? TfToken { fileNode.findPlug(MayaAttrs::file::computedFileTextureNamePattern, true) .asString() .asChar() } : ret; } else { const TfToken ret { MRenderUtil::exactFileTextureName(fileNode.object()).asChar() }; return ret.IsEmpty() ? TfToken { fileNode.findPlug(MayaAttrs::file::fileTextureName, true) .asString() .asChar() } : ret; } } #if PXR_VERSION < 2011 std::tuple<HdWrap, HdWrap> GetFileTextureWrappingParams(const MObject& fileObj) { const std::tuple<HdWrap, HdWrap> def { HdWrapClamp, HdWrapClamp }; MStatus status; MFnDependencyNode fileNode(fileObj, &status); if (!status) { return def; } auto getWrap = [&fileNode](MObject& wrapAttr, MObject& mirrorAttr) { if (fileNode.findPlug(wrapAttr, true).asBool()) { if (fileNode.findPlug(mirrorAttr, true).asBool()) { return HdWrapMirror; } else { return HdWrapRepeat; } } else { return HdWrapClamp; } }; return std::tuple<HdWrap, HdWrap> { getWrap(MayaAttrs::file::wrapU, MayaAttrs::file::mirrorU), getWrap(MayaAttrs::file::wrapV, MayaAttrs::file::mirrorV) }; } HdTextureResourceSharedPtr GetFileTextureResource(const MObject& fileObj, const TfToken& filePath, int maxTextureMemory) { if (filePath.IsEmpty()) { return {}; } auto textureType = HdTextureType::Uv; if (GlfIsSupportedUdimTexture(filePath)) { textureType = HdTextureType::Udim; } if (textureType != HdTextureType::Udim && !TfPathExists(filePath)) { return {}; } // TODO: handle origin const auto origin = GlfImage::OriginLowerLeft; GlfTextureHandleRefPtr texture = nullptr; if (textureType == HdTextureType::Udim) { UdimTextureFactory factory; texture = GlfTextureRegistry::GetInstance().GetTextureHandle(filePath, origin, &factory); } else { texture = GlfTextureRegistry::GetInstance().GetTextureHandle(filePath, origin); } const auto wrapping = GetFileTextureWrappingParams(fileObj); // We can't really mimic texture wrapping and mirroring settings // from the uv placement node, so we don't touch those for now. return HdTextureResourceSharedPtr(new HdStSimpleTextureResource( texture, textureType, std::get<0>(wrapping), std::get<1>(wrapping), HdWrapClamp, HdMinFilterLinearMipmapLinear, HdMagFilterLinear, maxTextureMemory)); } #endif // PXR_VERSION < 2011 PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/test/lib/usd/pxrUsdPreviewSurface/CMakeLists.txt set(TARGET_NAME MAYAUSD_PXR_USD_PREVIEW_SURFACE_TEST) # Unit test scripts. set(TEST_SCRIPT_FILES testPxrUsdPreviewSurfaceDraw.py ) if(BUILD_PXR_PLUGIN) # This test uses the file "PxrUsdPreviewSurfaceExportTest.ma" which # requires the plugin "pxrUsdPreviewSurface" that is built by the # Pixar plugin. list(APPEND TEST_SCRIPT_FILES testPxrUsdPreviewSurfaceExport.py ) endif() # copy tests to ${CMAKE_CURRENT_BINARY_DIR} and run them from there add_custom_target(${TARGET_NAME} ALL) # copy test files to build directory mayaUsd_copyDirectory(${TARGET_NAME} SOURCE ${CMAKE_CURRENT_SOURCE_DIR} DESTINATION ${CMAKE_CURRENT_BINARY_DIR} EXCLUDE "CMakeLists.txt" ) foreach(script ${TEST_SCRIPT_FILES}) mayaUsd_get_unittest_target(target ${script}) mayaUsd_add_test(${target} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} PYTHON_MODULE ${target} ) set_property(TEST ${target} APPEND PROPERTY LABELS usdPreviewSurface) endforeach() <file_sep>/test/lib/usd/translators/testUsdExportLayerAttributes.py #!/usr/bin/env mayapy # # Copyright 2020 Apple # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import unittest import fixturesUtils from maya import cmds from maya import standalone from pxr import Usd class testMayaUsdExportLayerAttributes(unittest.TestCase): @classmethod def setUpClass(cls): cls.temp_dir = fixturesUtils.setUpClass(__file__) @classmethod def tearDownClass(cls): standalone.uninitialize() def test_fps(self): fps_map = { "ntsc": 30, "game": 15, "film": 24, "pal": 25, "show": 48, "palf": 50, "ntscf": 60 } for name, fps in fps_map.items(): cmds.currentUnit(time=name) temp_file = os.path.join(self.temp_dir, 'test_{}.usda'.format(name)) cmds.mayaUSDExport(f=temp_file, frameRange=(1, 5)) stage = Usd.Stage.Open(temp_file) self.assertEqual(stage.GetTimeCodesPerSecond(), fps) self.assertEqual(stage.GetFramesPerSecond(), fps) if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/lib/mayaUsd/utils/stageCache.cpp // // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "stageCache.h" #include <mayaUsd/listeners/notice.h> #include <pxr/usd/sdf/attributeSpec.h> #include <pxr/usd/sdf/layer.h> #include <pxr/usd/sdf/primSpec.h> #include <pxr/usd/sdf/relationshipSpec.h> #include <pxr/usd/usd/stageCache.h> #include <pxr/usd/usdGeom/tokens.h> #include <maya/MFileIO.h> #include <maya/MSceneMessage.h> #include <map> #include <memory> #include <mutex> #include <sstream> #include <string> PXR_NAMESPACE_OPEN_SCOPE namespace { static std::map<std::string, SdfLayerRefPtr> _sharedSessionLayers; static std::mutex _sharedSessionLayersMutex; struct _OnSceneResetListener : public TfWeakBase { _OnSceneResetListener() { TfWeakPtr<_OnSceneResetListener> me(this); TfNotice::Register(me, &_OnSceneResetListener::OnSceneReset); } void OnSceneReset(const UsdMayaSceneResetNotice& notice) { UsdMayaStageCache::Clear(); std::lock_guard<std::mutex> lock(_sharedSessionLayersMutex); _sharedSessionLayers.clear(); } }; } // anonymous namespace /* static */ UsdStageCache& UsdMayaStageCache::Get(const bool loadAll) { static UsdStageCache theCacheLoadAll; // used when UsdStage::Open() will be called with // UsdStage::InitialLoadSet::LoadAll static UsdStageCache theCache; // used when UsdStage::Open() will be called with // UsdStage::InitialLoadSet::LoadNode static _OnSceneResetListener onSceneResetListener; return loadAll ? theCacheLoadAll : theCache; } /* static */ void UsdMayaStageCache::Clear() { Get(true).Clear(); Get(false).Clear(); } /* static */ size_t UsdMayaStageCache::EraseAllStagesWithRootLayerPath(const std::string& layerPath) { size_t erasedStages = 0u; const SdfLayerHandle rootLayer = SdfLayer::Find(layerPath); if (!rootLayer) { return erasedStages; } erasedStages += Get(true).EraseAll(rootLayer); erasedStages += Get(false).EraseAll(rootLayer); return erasedStages; } SdfLayerRefPtr UsdMayaStageCache::GetSharedSessionLayer( const SdfPath& rootPath, const std::map<std::string, std::string>& variantSelections, const TfToken& drawMode) { // Example key: "/Root/Path:modelingVariant=round|shadingVariant=red|:cards" std::ostringstream key; key << rootPath; key << ":"; for (const auto& pair : variantSelections) { key << pair.first << "=" << pair.second << "|"; } key << ":"; key << drawMode; std::string keyString = key.str(); std::lock_guard<std::mutex> lock(_sharedSessionLayersMutex); auto iter = _sharedSessionLayers.find(keyString); if (iter == _sharedSessionLayers.end()) { SdfLayerRefPtr newLayer = SdfLayer::CreateAnonymous(); SdfPrimSpecHandle over = SdfCreatePrimInLayer(newLayer, rootPath); for (const auto& pair : variantSelections) { const std::string& variantSet = pair.first; const std::string& variantSelection = pair.second; over->GetVariantSelections()[variantSet] = variantSelection; } if (!drawMode.IsEmpty()) { SdfAttributeSpecHandle drawModeAttr = SdfAttributeSpec::New( over, UsdGeomTokens->modelDrawMode, SdfValueTypeNames->Token, SdfVariabilityUniform); drawModeAttr->SetDefaultValue(VtValue(drawMode)); SdfAttributeSpecHandle applyDrawModeAttr = SdfAttributeSpec::New( over, UsdGeomTokens->modelApplyDrawMode, SdfValueTypeNames->Bool, SdfVariabilityUniform); applyDrawModeAttr->SetDefaultValue(VtValue(true)); } _sharedSessionLayers[keyString] = newLayer; return newLayer; } else { return iter->second; } } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/lib/usd/translators/shading/mtlxImageReader.cpp // // Copyright 2021 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "shadingTokens.h" #include <mayaUsd/fileio/shaderReader.h> #include <mayaUsd/fileio/shaderReaderRegistry.h> #include <mayaUsd/fileio/translators/translatorUtil.h> #include <mayaUsd/fileio/utils/readUtil.h> #include <mayaUsd/fileio/utils/shadingUtil.h> #include <mayaUsd/utils/util.h> #include <mayaUsd/utils/utilFileSystem.h> #include <pxr/base/arch/hash.h> #include <pxr/base/tf/debug.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/base/tf/staticTokens.h> #include <pxr/base/tf/stringUtils.h> #include <pxr/base/tf/token.h> #include <pxr/base/vt/value.h> #include <pxr/pxr.h> #include <pxr/usd/ar/asset.h> #include <pxr/usd/ar/packageUtils.h> #include <pxr/usd/ar/resolver.h> #include <pxr/usd/sdf/layerUtils.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/sdf/types.h> #include <pxr/usd/sdf/valueTypeName.h> #include <pxr/usd/usd/resolver.h> #include <pxr/usd/usdShade/input.h> #include <pxr/usd/usdShade/output.h> #include <pxr/usd/usdShade/shader.h> #include <pxr/usd/usdShade/tokens.h> #include <maya/MFnDependencyNode.h> #include <maya/MGlobal.h> #include <maya/MObject.h> #include <maya/MPlug.h> #include <maya/MStatus.h> #include <ghc/filesystem.hpp> PXR_NAMESPACE_OPEN_SCOPE class MtlxUsd_ImageReader : public UsdMayaShaderReader { public: MtlxUsd_ImageReader(const UsdMayaPrimReaderArgs&); bool Read(UsdMayaPrimReaderContext& context) override; TfToken GetMayaNameForUsdAttrName(const TfToken& usdAttrName) const override; private: TfToken _shaderID; }; PXRUSDMAYA_REGISTER_SHADER_READER(ND_image_float, MtlxUsd_ImageReader) PXRUSDMAYA_REGISTER_SHADER_READER(ND_image_vector2, MtlxUsd_ImageReader) PXRUSDMAYA_REGISTER_SHADER_READER(ND_image_color3, MtlxUsd_ImageReader) PXRUSDMAYA_REGISTER_SHADER_READER(ND_image_color4, MtlxUsd_ImageReader) MtlxUsd_ImageReader::MtlxUsd_ImageReader(const UsdMayaPrimReaderArgs& readArgs) : UsdMayaShaderReader(readArgs) { } /* virtual */ bool MtlxUsd_ImageReader::Read(UsdMayaPrimReaderContext& context) { const auto& prim = _GetArgs().GetUsdPrim(); UsdShadeShader shaderSchema = UsdShadeShader(prim); if (!shaderSchema) { return false; } MStatus status; MObject mayaObject; MFnDependencyNode depFn; if (!(UsdMayaTranslatorUtil::CreateShaderNode( MString(prim.GetName().GetText()), TrMayaTokens->file.GetText(), UsdMayaShadingNodeType::Texture, &status, &mayaObject) && depFn.setObject(mayaObject))) { // we need to make sure assumes those types are loaded.. TF_RUNTIME_ERROR( "Could not create node of type '%s' for shader '%s'.\n", TrMayaTokens->file.GetText(), prim.GetPath().GetText()); return false; } context.RegisterNewMayaNode(prim.GetPath().GetString(), mayaObject); // Create place2dTexture: MObject uvObj = UsdMayaShadingUtil::CreatePlace2dTextureAndConnectTexture(mayaObject); MFnDependencyNode uvDepFn(uvObj); // TODO: Import UV SRT from ND_place2d_vector2 node. // File VtValue val; MPlug mayaAttr = depFn.findPlug(TrMayaTokens->fileTextureName.GetText(), true, &status); UsdShadeInput usdInput = shaderSchema.GetInput(TrMtlxTokens->file); if (status == MS::kSuccess && usdInput && usdInput.Get(&val) && val.IsHolding<SdfAssetPath>()) { std::string filePath = val.UncheckedGet<SdfAssetPath>().GetResolvedPath(); if (!filePath.empty() && !ArIsPackageRelativePath(filePath)) { // Maya has issues with relative paths, especially if deep inside a // nesting of referenced assets. Use absolute path instead if USD was // able to resolve. A better fix will require providing an asset // resolver to Maya that can resolve the file correctly using the // MPxFileResolver API. We also make sure the path is not expressed // as a relationship like texture paths inside USDZ assets. val = SdfAssetPath(filePath); } // NOTE: Will need UDIM support and potentially USDZ support. When that happens, consider // refactoring existing code from usdUVTextureReader.cpp as shared utilities. UsdMayaReadUtil::SetMayaAttr(mayaAttr, val); // colorSpace: if (usdInput.GetAttr().HasColorSpace()) { MString colorSpace = usdInput.GetAttr().GetColorSpace().GetText(); mayaAttr = depFn.findPlug(TrMayaTokens->colorSpace.GetText(), true, &status); if (status == MS::kSuccess) { mayaAttr.setString(colorSpace); } } } // Default color // // The number of channels in the source can vary: shaderSchema.GetIdAttr().Get(&_shaderID); usdInput = shaderSchema.GetInput(TrMtlxTokens->paramDefault); mayaAttr = depFn.findPlug(TrMayaTokens->defaultColor.GetText(), true, &status); if (usdInput && status == MS::kSuccess && usdInput.Get(&val)) { GfVec3f mayaVal(0.0f, 0.0f, 0.0f); if (_shaderID == TrMtlxTokens->ND_image_float && val.IsHolding<float>()) { // Mono: treat as rrr swizzle mayaVal[0] = val.UncheckedGet<float>(); mayaVal[1] = mayaVal[0]; mayaVal[2] = mayaVal[0]; } else if (_shaderID == TrMtlxTokens->ND_image_vector2 && val.IsHolding<GfVec2f>()) { const GfVec2f& vecVal = val.UncheckedGet<GfVec2f>(); // Mono + alpha: treat as rrr swizzle mayaVal[0] = vecVal[0]; mayaVal[1] = vecVal[0]; mayaVal[2] = vecVal[0]; } else if (_shaderID == TrMtlxTokens->ND_image_color3 && val.IsHolding<GfVec3f>()) { mayaVal = val.UncheckedGet<GfVec3f>(); } else if (_shaderID == TrMtlxTokens->ND_image_color4 && val.IsHolding<GfVec4f>()) { const GfVec4f& vecVal = val.UncheckedGet<GfVec4f>(); mayaVal[0] = vecVal[0]; mayaVal[1] = vecVal[1]; mayaVal[2] = vecVal[2]; } UsdMayaReadUtil::SetMayaAttr(mayaAttr, val, /*unlinearizeColors*/ false); } // Wrap U/V const TfToken wrapMirrorTriples[2][3] { { TrMayaTokens->wrapU, TrMayaTokens->mirrorU, TrMtlxTokens->uaddressmode }, { TrMayaTokens->wrapV, TrMayaTokens->mirrorV, TrMtlxTokens->vaddressmode } }; for (auto wrapMirrorTriple : wrapMirrorTriples) { auto wrapUVToken = wrapMirrorTriple[0]; auto mirrorUVToken = wrapMirrorTriple[1]; auto wrapSTToken = wrapMirrorTriple[2]; usdInput = shaderSchema.GetInput(wrapSTToken); if (usdInput) { if (usdInput.Get(&val) && val.IsHolding<std::string>()) { const std::string& wrapVal = val.UncheckedGet<std::string>(); TfToken plugName; if (wrapVal == TrMtlxTokens->periodic.GetString()) { // do nothing - will repeat by default continue; } else if (wrapVal == TrMtlxTokens->mirror.GetString()) { plugName = mirrorUVToken; val = true; } else { plugName = wrapUVToken; val = false; } mayaAttr = uvDepFn.findPlug(plugName.GetText(), true, &status); if (status != MS::kSuccess) { continue; } UsdMayaReadUtil::SetMayaAttr(mayaAttr, val); } } } return true; } /* virtual */ TfToken MtlxUsd_ImageReader::GetMayaNameForUsdAttrName(const TfToken& usdAttrName) const { TfToken usdOutputName; UsdShadeAttributeType attrType; std::tie(usdOutputName, attrType) = UsdShadeUtils::GetBaseNameAndType(usdAttrName); if (attrType == UsdShadeAttributeType::Output && usdOutputName == TrMtlxTokens->out) { if (_shaderID == TrMtlxTokens->ND_image_float) { return TrMayaTokens->outColorR; } return TrMayaTokens->outColor; } return TfToken(); } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/lib/mayaUsd/render/vp2RenderDelegate/mayaPrimCommon.cpp // // Copyright 2021 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "mayaPrimCommon.h" PXR_NAMESPACE_OPEN_SCOPE #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT namespace { MayaUsdCustomData sMayaUsdCustomData; } // namespace /* static */ InstanceIdMap& MayaUsdCustomData::Get(const MHWRender::MRenderItem& renderItem) { return sMayaUsdCustomData._itemData[renderItem.InternalObjectId()]; } /* static */ void MayaUsdCustomData::Remove(const MHWRender::MRenderItem& renderItem) { // not thread safe, so if they are destroyed in parallel this will crash. // consider concurrent_hash_map for locking version that can erase sMayaUsdCustomData._itemData.unsafe_erase(renderItem.InternalObjectId()); } #endif PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/lib/mayaUsd/render/CMakeLists.txt add_subdirectory(px_vp20) add_subdirectory(pxrUsdMayaGL) add_subDirectory(vp2ComputeShaders) add_subdirectory(vp2RenderDelegate) add_subdirectory(vp2ShaderFragments) <file_sep>/lib/mayaUsd/undo/UsdUndoManager.h // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef MAYAUSD_UNDO_UNDOMANAGER_H #define MAYAUSD_UNDO_UNDOMANAGER_H #include "UsdUndoableItem.h" #include <mayaUsd/base/api.h> #include <pxr/usd/sdf/layer.h> #include <functional> #include <vector> PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { //! \brief Singleton class to manage layer states. /*! The UndoManager is responsible for : 1- tracking layer state changes from UsdUndoStateDelegate 2- collecting InvertFunc() in every state change 3- transferring collected edits into an UsdUndoableItem */ class MAYAUSD_CORE_PUBLIC UsdUndoManager { public: using InvertFunc = std::function<void()>; using InvertFuncs = std::vector<InvertFunc>; // returns an instance of the undo manager. static UsdUndoManager& instance(); // delete the copy/move constructors assignment operators. UsdUndoManager(const UsdUndoManager&) = delete; UsdUndoManager& operator=(const UsdUndoManager&) = delete; UsdUndoManager(UsdUndoManager&&) = delete; UsdUndoManager& operator=(UsdUndoManager&&) = delete; // tracks layer states by spawning a new UsdUndoStateDelegate void trackLayerStates(const SdfLayerHandle& layer); private: friend class UsdUndoStateDelegate; friend class UsdUndoBlock; friend class UsdUndoableItem; UsdUndoManager() = default; ~UsdUndoManager() = default; void addInverse(InvertFunc func); void transferEdits(UsdUndoableItem& undoableItem); private: InvertFuncs _invertFuncs; }; } // namespace MAYAUSD_NS_DEF #endif // MAYAUSD_UNDO_UNDOMANAGER_H <file_sep>/lib/mayaUsd/ufe/UsdUndoRenameCommand.cpp // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "UsdUndoRenameCommand.h" #include "private/UfeNotifGuard.h" #include "private/Utils.h" #include <mayaUsd/ufe/Utils.h> #include <mayaUsdUtils/util.h> #include <pxr/base/tf/token.h> #include <pxr/usd/sdf/changeBlock.h> #include <pxr/usd/sdf/copyUtils.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usd/editContext.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usd/stage.h> #include <ufe/log.h> #include <ufe/scene.h> #include <ufe/sceneNotification.h> #ifdef UFE_V2_FEATURES_AVAILABLE #define UFE_ENABLE_ASSERTS #include <ufe/ufeAssert.h> #else #include <cassert> #endif #include <cctype> PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { namespace ufe { /* HS, May 15, 2020 See usd-interest: Question around SdfPrimSepc's SetName routine SdfPrimSpec::SetName() will rename any prim in the layer, but it does not allow you to reparent the prim, nor will it update any relationship or connection targets in the layer that targeted the prim or any of its decendants (they will all break unless you fix them up yourself.Renaming and reparenting prims destructively in composed scenes is pretty tricky stuff that cannot really practically be done with 100% guarantees. */ UsdUndoRenameCommand::UsdUndoRenameCommand( const UsdSceneItem::Ptr& srcItem, const Ufe::PathComponent& newName) : Ufe::UndoableCommand() , _ufeSrcItem(srcItem) , _ufeDstItem(nullptr) , _stage(_ufeSrcItem->prim().GetStage()) { const UsdPrim& prim = _stage->GetPrimAtPath(_ufeSrcItem->prim().GetPath()); ufe::applyCommandRestriction(prim, "rename"); // handle unique name for _newName _newName = uniqueChildName(prim.GetParent(), newName.string()); // names are not allowed to start to digit numbers if (std::isdigit(_newName.at(0))) { _newName = prim.GetName(); } // all special characters are replaced with `_` const std::string specialChars { "~!@#$%^&*()-=+,.?`':{}|<>[]/ " }; std::replace_if( _newName.begin(), _newName.end(), [&](auto c) { return std::string::npos != specialChars.find(c); }, '_'); } UsdUndoRenameCommand::~UsdUndoRenameCommand() { } UsdUndoRenameCommand::Ptr UsdUndoRenameCommand::create(const UsdSceneItem::Ptr& srcItem, const Ufe::PathComponent& newName) { return std::make_shared<UsdUndoRenameCommand>(srcItem, newName); } UsdSceneItem::Ptr UsdUndoRenameCommand::renamedItem() const { return _ufeDstItem; } bool UsdUndoRenameCommand::renameRedo() { // get the stage's default prim path auto defaultPrimPath = _stage->GetDefaultPrim().GetPath(); // 1- open a changeblock to delay sending notifications. // 2- update the Internal References paths (if any) first // 3- set the new name // Note: during the changeBlock scope we are still working with old items/paths/prims. // it's only after the scope ends that we start working with new items/paths/prims { SdfChangeBlock changeBlock; const UsdPrim& prim = _stage->GetPrimAtPath(_ufeSrcItem->prim().GetPath()); auto ufeSiblingPath = _ufeSrcItem->path().sibling(Ufe::PathComponent(_newName)); bool status = MayaUsdUtils::updateReferencedPath( prim, SdfPath(ufeSiblingPath.getSegments()[1].string())); if (!status) { return false; } // set the new name auto primSpec = MayaUsdUtils::getPrimSpecAtEditTarget(prim); status = primSpec->SetName(_newName); if (!status) { return false; } } // the renamed scene item is a "sibling" of its original name. _ufeDstItem = createSiblingSceneItem(_ufeSrcItem->path(), _newName); // update stage's default prim if (_ufeSrcItem->prim().GetPath() == defaultPrimPath) { _stage->SetDefaultPrim(_ufeDstItem->prim()); } // send notification to update UFE data model sendNotification<Ufe::ObjectRename>(_ufeDstItem, _ufeSrcItem->path()); return true; } bool UsdUndoRenameCommand::renameUndo() { // get the stage's default prim path auto defaultPrimPath = _stage->GetDefaultPrim().GetPath(); // 1- open a changeblock to delay sending notifications. // 2- update the Internal References paths (if any) first // 3- set the new name // Note: during the changeBlock scope we are still working with old items/paths/prims. // it's only after the scope ends that we start working with new items/paths/prims { SdfChangeBlock changeBlock; const UsdPrim& prim = _stage->GetPrimAtPath(_ufeDstItem->prim().GetPath()); auto ufeSiblingPath = _ufeSrcItem->path().sibling(Ufe::PathComponent(_ufeSrcItem->prim().GetName())); bool status = MayaUsdUtils::updateReferencedPath( prim, SdfPath(ufeSiblingPath.getSegments()[1].string())); if (!status) { return false; } auto primSpec = MayaUsdUtils::getPrimSpecAtEditTarget(prim); status = primSpec->SetName(_ufeSrcItem->prim().GetName()); if (!status) { return false; } } // the renamed scene item is a "sibling" of its original name. _ufeSrcItem = createSiblingSceneItem(_ufeDstItem->path(), _ufeSrcItem->prim().GetName()); // update stage's default prim if (_ufeDstItem->prim().GetPath() == defaultPrimPath) { _stage->SetDefaultPrim(_ufeSrcItem->prim()); } // send notification to update UFE data model sendNotification<Ufe::ObjectRename>(_ufeSrcItem, _ufeDstItem->path()); return true; } void UsdUndoRenameCommand::undo() { try { InPathChange pc; if (!renameUndo()) { UFE_LOG("rename undo failed"); } } catch (const std::exception& e) { UFE_LOG(e.what()); throw; // re-throw the same exception } } void UsdUndoRenameCommand::redo() { InPathChange pc; if (!renameRedo()) { UFE_LOG("rename redo failed"); } } } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/lib/mayaUsd/fileio/transformWriter.cpp // // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "transformWriter.h" #include <mayaUsd/fileio/primWriterRegistry.h> #include <mayaUsd/fileio/utils/adaptor.h> #include <mayaUsd/fileio/utils/xformStack.h> #include <mayaUsd/fileio/writeJobContext.h> #include <mayaUsd/utils/util.h> #include <pxr/base/gf/matrix4d.h> #include <pxr/base/gf/vec3d.h> #include <pxr/base/gf/vec3f.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/base/tf/token.h> #include <pxr/base/vt/value.h> #include <pxr/pxr.h> #include <pxr/usd/usd/timeCode.h> #include <pxr/usd/usdGeom/xform.h> #include <pxr/usd/usdGeom/xformCommonAPI.h> #include <pxr/usd/usdGeom/xformOp.h> #include <pxr/usd/usdGeom/xformable.h> #include <pxr/usd/usdUtils/sparseValueWriter.h> #include <maya/MFn.h> #include <maya/MFnDependencyNode.h> #include <maya/MFnTransform.h> #include <maya/MString.h> #include <vector> PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_REGISTER_WRITER(transform, UsdMayaTransformWriter); PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(transform, UsdGeomXform); // Given an Op, value and time, set the Op value based on op type and precision static void setXformOp( const UsdGeomXformOp& op, const GfVec3d& value, const UsdTimeCode& usdTime, UsdUtilsSparseValueWriter* valueWriter) { if (!op) { TF_CODING_ERROR("Xform op is not valid"); return; } if (op.GetOpType() == UsdGeomXformOp::TypeTransform) { GfMatrix4d shearXForm(1.0); shearXForm[1][0] = value[0]; // xyVal shearXForm[2][0] = value[1]; // xzVal shearXForm[2][1] = value[2]; // yzVal valueWriter->SetAttribute(op.GetAttr(), shearXForm, usdTime); return; } VtValue vtValue; if (UsdGeomXformOp::GetPrecisionFromValueTypeName(op.GetAttr().GetTypeName()) == UsdGeomXformOp::PrecisionDouble) { vtValue = VtValue(value); } else { // float precision vtValue = VtValue(GfVec3f(value)); } valueWriter->SetAttribute(op.GetAttr(), vtValue, usdTime); } /* static */ void UsdMayaTransformWriter::_ComputeXformOps( const std::vector<_AnimChannel>& animChanList, const UsdTimeCode& usdTime, const bool eulerFilter, UsdMayaTransformWriter::_TokenRotationMap* previousRotates, UsdUtilsSparseValueWriter* valueWriter) { if (!TF_VERIFY(previousRotates)) { return; } // Iterate over each _AnimChannel, retrieve the default value and pull the // Maya data if needed. Then store it on the USD Ops for (const auto& animChannel : animChanList) { if (animChannel.isInverse) { continue; } GfVec3d value = animChannel.defValue; bool hasAnimated = false; bool hasStatic = false; for (unsigned int i = 0u; i < 3u; ++i) { if (animChannel.sampleType[i] == _SampleType::Animated) { value[i] = animChannel.plug[i].asDouble(); hasAnimated = true; } else if (animChannel.sampleType[i] == _SampleType::Static) { hasStatic = true; } } // If the channel is not animated AND has non identity value, we are // computing default time, then set the values. // // If the channel is animated(connected) and we are not setting default // time, then set the values. // // This to make sure static channels are setting their default while // animating ones are actually animating if ((usdTime == UsdTimeCode::Default() && hasStatic && !hasAnimated) || (usdTime != UsdTimeCode::Default() && hasAnimated)) { if (animChannel.opType == _XformType::Rotate) { if (hasAnimated && eulerFilter) { const TfToken& lookupName = animChannel.opName.IsEmpty() ? UsdGeomXformOp::GetOpTypeToken(animChannel.usdOpType) : animChannel.opName; auto findResult = previousRotates->find(lookupName); if (findResult == previousRotates->end()) { MEulerRotation::RotationOrder rotOrder = UsdMayaXformStack::RotateOrderFromOpType( animChannel.usdOpType, MEulerRotation::kXYZ); MEulerRotation currentRotate(value[0], value[1], value[2], rotOrder); (*previousRotates)[lookupName] = currentRotate; } else { MEulerRotation& previousRotate = findResult->second; MEulerRotation::RotationOrder rotOrder = UsdMayaXformStack::RotateOrderFromOpType( animChannel.usdOpType, previousRotate.order); MEulerRotation currentRotate(value[0], value[1], value[2], rotOrder); currentRotate.setToClosestSolution(previousRotate); for (unsigned int i = 0; i < 3; i++) { value[i] = currentRotate[i]; } (*previousRotates)[lookupName] = currentRotate; } } for (unsigned int i = 0; i < 3; i++) { value[i] = GfRadiansToDegrees(value[i]); } } setXformOp(animChannel.op, value, usdTime, valueWriter); } } } /* static */ bool UsdMayaTransformWriter::_GatherAnimChannel( const _XformType opType, const MFnTransform& iTrans, const TfToken& parentName, const MString& xName, const MString& yName, const MString& zName, std::vector<_AnimChannel>* oAnimChanList, const bool isWritingAnimation, const bool setOpName) { _AnimChannel chan; chan.opType = opType; chan.isInverse = false; if (setOpName) { chan.opName = parentName; } MString parentNameMStr = parentName.GetText(); // We default to single precision (later we set the main translate op and // shear to double) chan.precision = UsdGeomXformOp::PrecisionFloat; bool hasValidComponents = false; // this is to handle the case where there is a connection to the parent // plug but not to the child plugs, if the connection is there and you are // not forcing static, then all of the children are considered animated int parentSample = UsdMayaUtil::getSampledType(iTrans.findPlug(parentNameMStr), false); // Determine what plug are needed based on default value & being // connected/animated MStringArray channels; channels.append(parentNameMStr + xName); channels.append(parentNameMStr + yName); channels.append(parentNameMStr + zName); GfVec3d nullValue(opType == _XformType::Scale ? 1.0 : 0.0); for (unsigned int i = 0; i < 3; i++) { // Find the plug and retrieve the data as the channel default value. It // won't be updated if the channel is NOT ANIMATED chan.plug[i] = iTrans.findPlug(channels[i]); double plugValue = chan.plug[i].asDouble(); chan.defValue[i] = plugValue; chan.sampleType[i] = _SampleType::None; // If we allow animation and either the parent sample or local sample is // not 0 then we have an Animated sample else we have a scale and the // value is NOT 1 or if the value is NOT 0 then we have a static xform if ((parentSample != 0 || UsdMayaUtil::getSampledType(chan.plug[i], true) != 0) && isWritingAnimation) { chan.sampleType[i] = _SampleType::Animated; hasValidComponents = true; } else if (!GfIsClose(chan.defValue[i], nullValue[i], 1e-7)) { chan.sampleType[i] = _SampleType::Static; hasValidComponents = true; } } // If there are valid component, then we will add the animation channel. if (hasValidComponents) { if (opType == _XformType::Scale) { chan.usdOpType = UsdGeomXformOp::TypeScale; } else if (opType == _XformType::Translate) { chan.usdOpType = UsdGeomXformOp::TypeTranslate; // The main translate is set to double precision if (parentName == UsdMayaXformStackTokens->translate) { chan.precision = UsdGeomXformOp::PrecisionDouble; } } else if (opType == _XformType::Rotate) { chan.usdOpType = UsdGeomXformOp::TypeRotateXYZ; // Rotation Order ONLY applies to the "rotate" attribute if (parentName == UsdMayaXformStackTokens->rotate) { switch (iTrans.rotationOrder()) { case MTransformationMatrix::kYZX: chan.usdOpType = UsdGeomXformOp::TypeRotateYZX; break; case MTransformationMatrix::kZXY: chan.usdOpType = UsdGeomXformOp::TypeRotateZXY; break; case MTransformationMatrix::kXZY: chan.usdOpType = UsdGeomXformOp::TypeRotateXZY; break; case MTransformationMatrix::kYXZ: chan.usdOpType = UsdGeomXformOp::TypeRotateYXZ; break; case MTransformationMatrix::kZYX: chan.usdOpType = UsdGeomXformOp::TypeRotateZYX; break; default: break; } } } else if (opType == _XformType::Shear) { chan.usdOpType = UsdGeomXformOp::TypeTransform; chan.precision = UsdGeomXformOp::PrecisionDouble; } else { return false; } oAnimChanList->push_back(chan); return true; } return false; } void UsdMayaTransformWriter::_PushTransformStack( const MFnTransform& iTrans, const UsdGeomXformable& usdXformable, const bool writeAnim) { // NOTE: I think this logic and the logic in MayaTransformReader // should be merged so the concept of "CommonAPI" stays centralized. // // By default we assume that the xform conforms to the common API // (xlate,pivot,rotate,scale,pivotINVERTED) As soon as we encounter any // additional xform (compensation translates for pivots, rotateAxis or // shear) we are not conforming anymore bool conformsToCommonAPI = true; // Keep track of where we have rotate and scale Pivots and their inverse so // that we can combine them later if possible unsigned int rotPivotIdx = -1, rotPivotINVIdx = -1, scalePivotIdx = -1, scalePivotINVIdx = -1; // Check if the Maya prim inheritTransform MPlug inheritPlug = iTrans.findPlug("inheritsTransform"); if (!inheritPlug.isNull()) { if (!inheritPlug.asBool()) { usdXformable.SetResetXformStack(true); } } // inspect the translate, no suffix to be closer compatibility with common API _GatherAnimChannel( _XformType::Translate, iTrans, UsdMayaXformStackTokens->translate, "X", "Y", "Z", &_animChannels, writeAnim, false); // inspect the rotate pivot translate if (_GatherAnimChannel( _XformType::Translate, iTrans, UsdMayaXformStackTokens->rotatePivotTranslate, "X", "Y", "Z", &_animChannels, writeAnim, true)) { conformsToCommonAPI = false; } // inspect the rotate pivot bool hasRotatePivot = _GatherAnimChannel( _XformType::Translate, iTrans, UsdMayaXformStackTokens->rotatePivot, "X", "Y", "Z", &_animChannels, writeAnim, true); if (hasRotatePivot) { rotPivotIdx = _animChannels.size() - 1; } // inspect the rotate, no suffix to be closer compatibility with common API _GatherAnimChannel( _XformType::Rotate, iTrans, UsdMayaXformStackTokens->rotate, "X", "Y", "Z", &_animChannels, writeAnim, false); // inspect the rotateAxis/orientation if (_GatherAnimChannel( _XformType::Rotate, iTrans, UsdMayaXformStackTokens->rotateAxis, "X", "Y", "Z", &_animChannels, writeAnim, true)) { conformsToCommonAPI = false; } // invert the rotate pivot if (hasRotatePivot) { _AnimChannel chan; chan.usdOpType = UsdGeomXformOp::TypeTranslate; chan.precision = UsdGeomXformOp::PrecisionFloat; chan.opName = UsdMayaXformStackTokens->rotatePivot; chan.isInverse = true; _animChannels.push_back(chan); rotPivotINVIdx = _animChannels.size() - 1; } // inspect the scale pivot translation if (_GatherAnimChannel( _XformType::Translate, iTrans, UsdMayaXformStackTokens->scalePivotTranslate, "X", "Y", "Z", &_animChannels, writeAnim, true)) { conformsToCommonAPI = false; } // inspect the scale pivot point bool hasScalePivot = _GatherAnimChannel( _XformType::Translate, iTrans, UsdMayaXformStackTokens->scalePivot, "X", "Y", "Z", &_animChannels, writeAnim, true); if (hasScalePivot) { scalePivotIdx = _animChannels.size() - 1; } // inspect the shear. Even if we have one xform on the xform list, it represents a share so we // should name it if (_GatherAnimChannel( _XformType::Shear, iTrans, UsdMayaXformStackTokens->shear, "XY", "XZ", "YZ", &_animChannels, writeAnim, true)) { conformsToCommonAPI = false; } // add the scale. no suffix to be closer compatibility with common API _GatherAnimChannel( _XformType::Scale, iTrans, UsdMayaXformStackTokens->scale, "X", "Y", "Z", &_animChannels, writeAnim, false); // inverse the scale pivot point if (hasScalePivot) { _AnimChannel chan; chan.usdOpType = UsdGeomXformOp::TypeTranslate; chan.precision = UsdGeomXformOp::PrecisionFloat; chan.opName = UsdMayaXformStackTokens->scalePivot; chan.isInverse = true; _animChannels.push_back(chan); scalePivotINVIdx = _animChannels.size() - 1; } // If still potential common API, check if the pivots are the same and NOT animated/connected if (hasRotatePivot != hasScalePivot) { conformsToCommonAPI = false; } if (conformsToCommonAPI && hasRotatePivot && hasScalePivot) { _AnimChannel rotPivChan, scalePivChan; rotPivChan = _animChannels[rotPivotIdx]; scalePivChan = _animChannels[scalePivotIdx]; // If they have different sampleType or are animated, then this does not // conformsToCommonAPI anymore for (unsigned int i = 0; i < 3; i++) { if (rotPivChan.sampleType[i] != scalePivChan.sampleType[i] || rotPivChan.sampleType[i] == _SampleType::Animated) { conformsToCommonAPI = false; } } // If The defaultValue is not the same, does not conformsToCommonAPI anymore if (!GfIsClose(rotPivChan.defValue, scalePivChan.defValue, 1e-9)) { conformsToCommonAPI = false; } // If opType, usdType or precision are not the same, does not conformsToCommonAPI anymore if (rotPivChan.opType != scalePivChan.opType || rotPivChan.usdOpType != scalePivChan.usdOpType || rotPivChan.precision != scalePivChan.precision) { conformsToCommonAPI = false; } if (conformsToCommonAPI) { // To Merge, we first rename rotatePivot and the scalePivot inverse // to pivot. Then we remove the scalePivot and the inverse of the // rotatePivot. // // This means that pivot and its inverse will wrap rotate and scale // since no other ops have been found // // NOTE: scalePivotIdx > rotPivotINVIdx _animChannels[rotPivotIdx].opName = UsdMayaXformStackTokens->pivot; _animChannels[scalePivotINVIdx].opName = UsdMayaXformStackTokens->pivot; _animChannels.erase(_animChannels.begin() + scalePivotIdx); _animChannels.erase(_animChannels.begin() + rotPivotINVIdx); } } // Loop over anim channel vector and create corresponding XFormOps // including the inverse ones if needed TF_FOR_ALL(iter, _animChannels) { _AnimChannel& animChan = *iter; animChan.op = usdXformable.AddXformOp( animChan.usdOpType, animChan.precision, animChan.opName, animChan.isInverse); if (!animChan.op) { TF_CODING_ERROR("Could not add xform op"); animChan.op = UsdGeomXformOp(); } } } UsdMayaTransformWriter::UsdMayaTransformWriter( const MFnDependencyNode& depNodeFn, const SdfPath& usdPath, UsdMayaWriteJobContext& jobCtx) : UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) { // Even though we define an Xform here, it's OK for subclassers to // re-define the prim as another type. UsdGeomXform primSchema = UsdGeomXform::Define(GetUsdStage(), GetUsdPath()); _usdPrim = primSchema.GetPrim(); TF_VERIFY(_usdPrim); // There are special cases where you might subclass UsdMayaTransformWriter // without actually having a transform (e.g. the internal // UsdMaya_FunctorPrimWriter), so accomodate those here. if (GetMayaObject().hasFn(MFn::kTransform)) { const MFnTransform transFn(GetDagPath()); // Create a vector of _AnimChannels based on the Maya transformation // ordering _PushTransformStack(transFn, primSchema, !_GetExportArgs().timeSamples.empty()); } } /* virtual */ void UsdMayaTransformWriter::Write(const UsdTimeCode& usdTime) { UsdMayaPrimWriter::Write(usdTime); // There are special cases where you might subclass UsdMayaTransformWriter // without actually having a transform (e.g. the internal // UsdMaya_FunctorPrimWriter), so accomodate those here. if (GetMayaObject().hasFn(MFn::kTransform)) { // There are valid cases where we have a transform in Maya but not one // in USD, e.g. typeless defs or other container prims in USD. if (UsdGeomXformable xformSchema = UsdGeomXformable(_usdPrim)) { _ComputeXformOps( _animChannels, usdTime, _GetExportArgs().eulerFilter, &_previousRotates, _GetSparseValueWriter()); } } } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/lib/mayaUsd/render/vp2RenderDelegate/proxyRenderDelegate.cpp // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "proxyRenderDelegate.h" #include "mayaPrimCommon.h" #include "render_delegate.h" #include "tokens.h" #include <mayaUsd/base/tokens.h> #include <mayaUsd/nodes/proxyShapeBase.h> #include <mayaUsd/nodes/stageData.h> #include <mayaUsd/utils/selectability.h> #include <mayaUsd/utils/util.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/base/tf/staticTokens.h> #include <pxr/base/tf/stringUtils.h> #include <pxr/base/tf/token.h> #include <pxr/imaging/hd/basisCurves.h> #include <pxr/imaging/hd/enums.h> #include <pxr/imaging/hd/mesh.h> #include <pxr/imaging/hd/primGather.h> #include <pxr/imaging/hd/repr.h> #include <pxr/imaging/hd/rprimCollection.h> #include <pxr/imaging/hd/sceneDelegate.h> #include <pxr/imaging/hdx/renderTask.h> #include <pxr/imaging/hdx/selectionTracker.h> #include <pxr/imaging/hdx/taskController.h> #include <pxr/pxr.h> #include <pxr/usd/kind/registry.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usd/modelAPI.h> #include <pxr/usd/usd/prim.h> #include <pxr/usdImaging/usdImaging/delegate.h> #include <maya/MEventMessage.h> #include <maya/MFileIO.h> #include <maya/MFnPluginData.h> #include <maya/MHWGeometryUtilities.h> #include <maya/MProfiler.h> #include <maya/MSelectionContext.h> #if defined(WANT_UFE_BUILD) #include <mayaUsd/ufe/UsdSceneItem.h> #include <mayaUsd/ufe/Utils.h> #include <ufe/globalSelection.h> #ifdef UFE_V2_FEATURES_AVAILABLE #include <ufe/namedSelection.h> #endif #include <ufe/observableSelection.h> #include <ufe/path.h> #include <ufe/pathSegment.h> #include <ufe/runTimeMgr.h> #include <ufe/scene.h> #include <ufe/sceneItem.h> #include <ufe/sceneNotification.h> #include <ufe/selectionNotification.h> #endif #if defined(BUILD_HDMAYA) #include <mayaUsd/render/mayaToHydra/utils.h> #endif PXR_NAMESPACE_OPEN_SCOPE namespace { //! Representation selector for shaded and textured viewport mode const HdReprSelector kSmoothHullReprSelector(HdReprTokens->smoothHull); #ifdef HAS_DEFAULT_MATERIAL_SUPPORT_API //! Representation selector for default material viewport mode const HdReprSelector kDefaultMaterialReprSelector(HdVP2ReprTokens->defaultMaterial); #endif //! Representation selector for wireframe viewport mode const HdReprSelector kWireReprSelector(TfToken(), HdReprTokens->wire); //! Representation selector for bounding box viewport mode const HdReprSelector kBBoxReprSelector(TfToken(), HdVP2ReprTokens->bbox); //! Representation selector for point snapping const HdReprSelector kPointsReprSelector(TfToken(), TfToken(), HdReprTokens->points); //! Representation selector for selection update const HdReprSelector kSelectionReprSelector(HdVP2ReprTokens->selection); #if defined(WANT_UFE_BUILD) //! \brief Query the global selection list adjustment. MGlobal::ListAdjustment GetListAdjustment() { // Keyboard modifiers can be queried from QApplication::keyboardModifiers() // in case running MEL command leads to performance hit. On the other hand // the advantage of using MEL command is the platform-agnostic state of the // CONTROL key that it provides for aligning to Maya's implementation. int modifiers = 0; MGlobal::executeCommand("getModifiers", modifiers); const bool shiftHeld = (modifiers % 2); const bool ctrlHeld = (modifiers / 4 % 2); MGlobal::ListAdjustment listAdjustment = MGlobal::kReplaceList; if (shiftHeld && ctrlHeld) { listAdjustment = MGlobal::kAddToList; } else if (ctrlHeld) { listAdjustment = MGlobal::kRemoveFromList; } else if (shiftHeld) { listAdjustment = MGlobal::kXORWithList; } return listAdjustment; } //! \brief Query the Kind to be selected from viewport. //! \return A Kind token (https://graphics.pixar.com/usd/docs/api/kind_page_front.html). If the //! token is empty or non-existing in the hierarchy, the exact prim that gets picked //! in the viewport will be selected. TfToken GetSelectionKind() { static const MString kOptionVarName(MayaUsdOptionVars->SelectionKind.GetText()); if (MGlobal::optionVarExists(kOptionVarName)) { MString optionVarValue = MGlobal::optionVarStringValue(kOptionVarName); return TfToken(optionVarValue.asChar()); } return TfToken(); } // clang-format off TF_DEFINE_PRIVATE_TOKENS( _pointInstancesPickModeTokens, (PointInstancer) (Instances) (Prototypes) ); // clang-format on //! \brief Query the pick mode to use when picking point instances in the viewport. //! \return A UsdPointInstancesPickMode enum value indicating the pick mode behavior //! to employ when the picked object is a point instance. //! //! This function retrieves the value for the point instances pick mode optionVar //! and converts it into a UsdPointInstancesPickMode enum value. If the optionVar //! has not been set or otherwise has an invalid value, the default pick mode of //! PointInstancer is returned. UsdPointInstancesPickMode GetPointInstancesPickMode() { static const MString kOptionVarName(MayaUsdOptionVars->PointInstancesPickMode.GetText()); UsdPointInstancesPickMode pickMode = UsdPointInstancesPickMode::PointInstancer; if (MGlobal::optionVarExists(kOptionVarName)) { const MString optionVarValue = MGlobal::optionVarStringValue(kOptionVarName); const TfToken pickModeToken(UsdMayaUtil::convert(optionVarValue)); if (pickModeToken == _pointInstancesPickModeTokens->Instances) { pickMode = UsdPointInstancesPickMode::Instances; } else if (pickModeToken == _pointInstancesPickModeTokens->Prototypes) { pickMode = UsdPointInstancesPickMode::Prototypes; } } return pickMode; } //! \brief Returns the prim or an ancestor of it that is of the given kind. // // If neither the prim itself nor any of its ancestors above it in the // namespace hierarchy have an authored kind that matches, an invalid null // prim is returned. UsdPrim GetPrimOrAncestorWithKind(const UsdPrim& prim, const TfToken& kind) { UsdPrim iterPrim = prim; TfToken primKind; while (iterPrim) { if (UsdModelAPI(iterPrim).GetKind(&primKind) && KindRegistry::IsA(primKind, kind)) { break; } iterPrim = iterPrim.GetParent(); } return iterPrim; } //! \brief Populate Rprims into the Hydra selection from the UFE scene item. void PopulateSelection( const Ufe::SceneItem::Ptr& item, const Ufe::Path& proxyPath, UsdImagingDelegate& sceneDelegate, const HdSelectionSharedPtr& result) { // Filter out items which are not under the current proxy shape. if (!item->path().startsWith(proxyPath)) { return; } // Filter out non-USD items. auto usdItem = std::dynamic_pointer_cast<MayaUsd::ufe::UsdSceneItem>(item); if (!usdItem) { return; } SdfPath usdPath = usdItem->prim().GetPath(); const int instanceIndex = usdItem->instanceIndex(); #if !defined(USD_IMAGING_API_VERSION) || USD_IMAGING_API_VERSION < 11 usdPath = sceneDelegate.ConvertCachePathToIndexPath(usdPath); #endif sceneDelegate.PopulateSelection( HdSelection::HighlightModeSelect, usdPath, instanceIndex, result); } #endif // defined(WANT_UFE_BUILD) //! \brief Append the selected prim paths to the result list. void AppendSelectedPrimPaths(const HdSelectionSharedPtr& selection, SdfPathVector& result) { if (!selection) { return; } SdfPathVector paths = selection->GetSelectedPrimPaths(HdSelection::HighlightModeSelect); if (paths.empty()) { return; } if (result.empty()) { result.swap(paths); } else { result.reserve(result.size() + paths.size()); result.insert(result.end(), paths.begin(), paths.end()); } } //! \brief Configure repr descriptions void _ConfigureReprs() { const HdMeshReprDesc reprDescHull( HdMeshGeomStyleHull, HdCullStyleDontCare, HdMeshReprDescTokens->surfaceShader, /*flatShadingEnabled=*/false, /*blendWireframeColor=*/false); #ifdef HAS_DEFAULT_MATERIAL_SUPPORT_API const HdMeshReprDesc reprDescHullDefaultMaterial( HdMeshGeomStyleHull, HdCullStyleDontCare, HdMeshReprDescTokens->constantColor, /*flatShadingEnabled=*/false, /*blendWireframeColor=*/false); #endif const HdMeshReprDesc reprDescEdge( HdMeshGeomStyleHullEdgeOnly, HdCullStyleDontCare, HdMeshReprDescTokens->surfaceShader, /*flatShadingEnabled=*/false, /*blendWireframeColor=*/false); // Hull desc for shaded display, edge desc for selection highlight. HdMesh::ConfigureRepr(HdReprTokens->smoothHull, reprDescHull, reprDescEdge); #ifdef HAS_DEFAULT_MATERIAL_SUPPORT_API // Hull desc for default material display, edge desc for selection highlight. HdMesh::ConfigureRepr( HdVP2ReprTokens->defaultMaterial, reprDescHullDefaultMaterial, reprDescEdge); #endif // Edge desc for bbox display. HdMesh::ConfigureRepr(HdVP2ReprTokens->bbox, reprDescEdge); // Special token for selection update and no need to create repr. Adding // the empty desc to remove Hydra warning. HdMesh::ConfigureRepr(HdVP2ReprTokens->selection, HdMeshReprDesc()); // Wireframe desc for bbox display. HdBasisCurves::ConfigureRepr(HdVP2ReprTokens->bbox, HdBasisCurvesGeomStyleWire); // Special token for selection update and no need to create repr. Adding // the null desc to remove Hydra warning. HdBasisCurves::ConfigureRepr(HdVP2ReprTokens->selection, HdBasisCurvesGeomStyleInvalid); #ifdef HAS_DEFAULT_MATERIAL_SUPPORT_API // Wire for default material: HdBasisCurves::ConfigureRepr(HdVP2ReprTokens->defaultMaterial, HdBasisCurvesGeomStyleWire); #endif } #if defined(WANT_UFE_BUILD) class UfeObserver : public Ufe::Observer { public: UfeObserver(ProxyRenderDelegate& proxyRenderDelegate) : Ufe::Observer() , _proxyRenderDelegate(proxyRenderDelegate) { } void operator()(const Ufe::Notification& notification) override { // During Maya file read, each node will be selected in turn, so we get // notified for each node in the scene. Prune this out. if (MFileIO::isOpeningFile()) { return; } if (dynamic_cast<const Ufe::SelectionChanged*>(&notification) || dynamic_cast<const Ufe::ObjectAdd*>(&notification)) { _proxyRenderDelegate.SelectionChanged(); } } private: ProxyRenderDelegate& _proxyRenderDelegate; }; #else void SelectionChangedCB(void* data) { ProxyRenderDelegate* prd = static_cast<ProxyRenderDelegate*>(data); if (prd) { prd->SelectionChanged(); } } #endif // Copied from renderIndex.cpp, the code that does HdRenderIndex::GetDrawItems. But I just want the // rprimIds, I don't want to go all the way to draw items. #if defined(HD_API_VERSION) && HD_API_VERSION >= 42 struct _FilterParam { const TfTokenVector& renderTags; const HdRenderIndex* renderIndex; }; bool _DrawItemFilterPredicate(const SdfPath& rprimID, const void* predicateParam) { const _FilterParam* filterParam = static_cast<const _FilterParam*>(predicateParam); const TfTokenVector& renderTags = filterParam->renderTags; const HdRenderIndex* renderIndex = filterParam->renderIndex; // // Render Tag Filter // if (renderTags.empty()) { // An empty render tag set means everything passes the filter // Primary user is tests, but some single task render delegates // that don't support render tags yet also use it. return true; } else { // As the number of tags is expected to be low (<10) // use a simple linear search. TfToken primRenderTag = renderIndex->GetRenderTag(rprimID); size_t numRenderTags = renderTags.size(); size_t tagNum = 0; while (tagNum < numRenderTags) { if (renderTags[tagNum] == primRenderTag) { return true; } ++tagNum; } } return false; } #else struct _FilterParam { const HdRprimCollection& collection; const TfTokenVector& renderTags; const HdRenderIndex* renderIndex; }; bool _DrawItemFilterPredicate(const SdfPath& rprimID, const void* predicateParam) { const _FilterParam* filterParam = static_cast<const _FilterParam*>(predicateParam); const HdRprimCollection& collection = filterParam->collection; const TfTokenVector& renderTags = filterParam->renderTags; const HdRenderIndex* renderIndex = filterParam->renderIndex; // // Render Tag Filter // bool passedRenderTagFilter = false; if (renderTags.empty()) { // An empty render tag set means everything passes the filter // Primary user is tests, but some single task render delegates // that don't support render tags yet also use it. passedRenderTagFilter = true; } else { // As the number of tags is expected to be low (<10) // use a simple linear search. TfToken primRenderTag = renderIndex->GetRenderTag(rprimID); size_t numRenderTags = renderTags.size(); size_t tagNum = 0; while (!passedRenderTagFilter && tagNum < numRenderTags) { if (renderTags[tagNum] == primRenderTag) { passedRenderTagFilter = true; } ++tagNum; } } // // Material Tag Filter // bool passedMaterialTagFilter = false; // Filter out rprims that do not match the collection's materialTag. // E.g. We may want to gather only opaque or translucent prims. // An empty materialTag on collection means: ignore material-tags. // This is important for tasks such as the selection-task which wants // to ignore materialTags and receive all prims in its collection. TfToken const& collectionMatTag = collection.GetMaterialTag(); if (collectionMatTag.IsEmpty() || renderIndex->GetMaterialTag(rprimID) == collectionMatTag) { passedMaterialTagFilter = true; } return (passedRenderTagFilter && passedMaterialTagFilter); } #endif } // namespace //! \brief Draw classification used during plugin load to register in VP2 const MString ProxyRenderDelegate::drawDbClassification( TfStringPrintf( "drawdb/subscene/vp2RenderDelegate/%s", MayaUsdProxyShapeBaseTokens->MayaTypeName.GetText()) .c_str()); //! \brief Factory method registered at plugin load MHWRender::MPxSubSceneOverride* ProxyRenderDelegate::Creator(const MObject& obj) { return new ProxyRenderDelegate(obj); } //! \brief Constructor ProxyRenderDelegate::ProxyRenderDelegate(const MObject& obj) : MHWRender::MPxSubSceneOverride(obj) { MDagPath proxyDagPath; MDagPath::getAPathTo(obj, proxyDagPath); const MFnDependencyNode fnDepNode(obj); _proxyShapeData.reset(new ProxyShapeData( static_cast<MayaUsdProxyShapeBase*>(fnDepNode.userNode()), proxyDagPath)); } //! \brief Destructor ProxyRenderDelegate::~ProxyRenderDelegate() { _ClearRenderDelegate(); #if !defined(WANT_UFE_BUILD) if (_mayaSelectionCallbackId != 0) { MMessage::removeCallback(_mayaSelectionCallbackId); } #endif } //! \brief This drawing routine supports all devices (DirectX and OpenGL) MHWRender::DrawAPI ProxyRenderDelegate::supportedDrawAPIs() const { return MHWRender::kAllDevices; } #if defined(MAYA_ENABLE_UPDATE_FOR_SELECTION) //! \brief Enable subscene update in selection passes for deferred update of selection render //! items. bool ProxyRenderDelegate::enableUpdateForSelection() const { return true; } #endif //! \brief Always requires update since changes are tracked by Hydraw change tracker and it will //! guarantee minimal update; only exception is if rendering through Maya-to-Hydra bool ProxyRenderDelegate::requiresUpdate( const MSubSceneContainer& container, const MFrameContext& frameContext) const { #if defined(BUILD_HDMAYA) // If the current viewport renderer is an mtoh one, skip this update, as // mtoh already has special handling for proxy shapes, and we don't want to // build out a render index we don't need if (IsMtohRenderOverride(frameContext)) { return false; } #endif return true; } void ProxyRenderDelegate::_ClearRenderDelegate() { // The order of deletion matters. Some orders cause crashes. _sceneDelegate.reset(); _taskController.reset(); _renderIndex.reset(); _renderDelegate.reset(); _dummyTasks.clear(); // reset any version ids or dirty information that doesn't make sense if we clear // the render index. _renderTagVersion = 0; #ifdef ENABLE_RENDERTAG_VISIBILITY_WORKAROUND _visibilityVersion = 0; #endif _taskRenderTagsValid = false; _isPopulated = false; } //! \brief Clear data which is now stale because proxy shape attributes have changed void ProxyRenderDelegate::_ClearInvalidData(MSubSceneContainer& container) { TF_VERIFY(_proxyShapeData->ProxyShape()); // We have to clear everything when the stage changes because the new stage doesn't necessarily // have anything in common with the old stage. // When excluded prims changes we don't have a way to know which (if any) prims were removed // from excluded prims & so must be re-added to the render index, so we take the easy way out // and clear everything. If this is a performance problem we can probably store the old value // of excluded prims, compare it to the new value and only add back the difference. if (!_proxyShapeData->IsUsdStageUpToDate() || !_proxyShapeData->IsExcludePrimsUpToDate()) { // delete everything so we can re-initialize with the new stage _ClearRenderDelegate(); container.clear(); } } //! \brief Initialize the render delegate void ProxyRenderDelegate::_InitRenderDelegate() { TF_VERIFY(_proxyShapeData->ProxyShape()); // No need to run all the checks if we got till the end if (_isInitialized()) return; _proxyShapeData->UpdateUsdStage(); _proxyShapeData->UsdStageUpdated(); if (!_renderDelegate) { MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L1, "Allocate VP2RenderDelegate"); _renderDelegate.reset(new HdVP2RenderDelegate(*this)); } if (!_renderIndex) { MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L1, "Allocate RenderIndex"); _renderIndex.reset(HdRenderIndex::New(_renderDelegate.get(), HdDriverVector())); // Set the _renderTagVersion and _visibilityVersion so that we don't trigger a // needlessly large update them on the first frame. HdChangeTracker& changeTracker = _renderIndex->GetChangeTracker(); _renderTagVersion = changeTracker.GetRenderTagVersion(); #ifdef ENABLE_RENDERTAG_VISIBILITY_WORKAROUND _visibilityVersion = changeTracker.GetVisibilityChangeCount(); #endif // Add additional configurations after render index creation. static std::once_flag reprsOnce; std::call_once(reprsOnce, _ConfigureReprs); } if (!_sceneDelegate) { MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L1, "Allocate SceneDelegate"); // Make sure the delegate name is a valid identifier, since it may // include colons if the proxy node is in a Maya namespace. const std::string delegateName = TfMakeValidIdentifier(TfStringPrintf( "Proxy_%s_%p", _proxyShapeData->ProxyShape()->name().asChar(), _proxyShapeData->ProxyShape())); const SdfPath delegateID = SdfPath::AbsoluteRootPath().AppendChild(TfToken(delegateName)); _sceneDelegate.reset(new UsdImagingDelegate(_renderIndex.get(), delegateID)); _taskController.reset(new HdxTaskController( _renderIndex.get(), delegateID.AppendChild(TfToken(TfStringPrintf("_UsdImaging_VP2_%p", this))))); _defaultCollection.reset(new HdRprimCollection()); _defaultCollection->SetName(HdTokens->geometry); #if defined(WANT_UFE_BUILD) if (!_observer) { _observer = std::make_shared<UfeObserver>(*this); auto globalSelection = Ufe::GlobalSelection::get(); if (TF_VERIFY(globalSelection)) { globalSelection->addObserver(_observer); } #ifdef UFE_V2_FEATURES_AVAILABLE Ufe::Scene::instance().addObserver(_observer); #else Ufe::Scene::instance().addObjectAddObserver(_observer); #endif } #else // Without UFE, support basic selection highlight at proxy shape level. if (!_mayaSelectionCallbackId) { _mayaSelectionCallbackId = MEventMessage::addEventCallback("SelectionChanged", SelectionChangedCB, this); } #endif // We don't really need any HdTask because VP2RenderDelegate uses Hydra // engine for data preparation only, but we have to add a dummy render // task to bootstrap data preparation. const HdTaskSharedPtrVector tasks = _taskController->GetRenderingTasks(); for (const HdTaskSharedPtr& task : tasks) { if (dynamic_cast<const HdxRenderTask*>(task.get())) { _dummyTasks.push_back(task); break; } } } } //! \brief Populate render index with prims coming from scene delegate. //! \return True when delegate is ready to draw bool ProxyRenderDelegate::_Populate() { TF_VERIFY(_proxyShapeData->ProxyShape()); if (!_isInitialized()) return false; if (_proxyShapeData->UsdStage() && !_isPopulated) { MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L1, "Populate"); // Remove any excluded prims before populating SdfPathVector excludePrimPaths = _proxyShapeData->ProxyShape()->getExcludePrimPaths(); for (auto& excludePrim : excludePrimPaths) { SdfPath indexPath = _sceneDelegate->ConvertCachePathToIndexPath(excludePrim); if (_renderIndex->HasRprim(indexPath)) { _renderIndex->RemoveRprim(indexPath); } } _proxyShapeData->ExcludePrimsUpdated(); _sceneDelegate->Populate(_proxyShapeData->ProxyShape()->usdPrim(), excludePrimPaths); _isPopulated = true; } return _isPopulated; } //! \brief Synchronize USD scene delegate with Maya's proxy shape. void ProxyRenderDelegate::_UpdateSceneDelegate() { TF_VERIFY(_proxyShapeData->ProxyShape()); if (!_sceneDelegate) return; MProfilingScope profilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "UpdateSceneDelegate"); { MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "SetTime"); const UsdTimeCode timeCode = _proxyShapeData->ProxyShape()->getTime(); _sceneDelegate->SetTime(timeCode); } // Update the root transform used to render by the delagate. // USD considers that the root prim transform is always the Identity matrix so that means // the root transform define the root prim transform. When the real stage root is used to // render this is not a issue because the root transform will be the maya transform. // The problem is when using a primPath as the root prim, we are losing // the prim path world transform. So we need to set the root transform as the world // transform of the prim used for rendering. const MMatrix inclusiveMatrix = _proxyShapeData->ProxyDagPath().inclusiveMatrix(); GfMatrix4d transform(inclusiveMatrix.matrix); if (_proxyShapeData->ProxyShape()->usdPrim().GetPath() != SdfPath::AbsoluteRootPath()) { const UsdTimeCode timeCode = _proxyShapeData->ProxyShape()->getTime(); UsdGeomXformCache xformCache(timeCode); GfMatrix4d m = xformCache.GetLocalToWorldTransform(_proxyShapeData->ProxyShape()->usdPrim()); transform = m * transform; } constexpr double tolerance = 1e-9; if (!GfIsClose(transform, _sceneDelegate->GetRootTransform(), tolerance)) { MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "SetRootTransform"); _sceneDelegate->SetRootTransform(transform); } const bool isVisible = _proxyShapeData->ProxyDagPath().isVisible(); if (isVisible != _sceneDelegate->GetRootVisibility()) { MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "SetRootVisibility"); _sceneDelegate->SetRootVisibility(isVisible); // Trigger selection update when a hidden proxy shape gets shown. if (isVisible) { SelectionChanged(); } } const int refineLevel = _proxyShapeData->ProxyShape()->getComplexity(); if (refineLevel != _sceneDelegate->GetRefineLevelFallback()) { MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "SetRefineLevelFallback"); _sceneDelegate->SetRefineLevelFallback(refineLevel); } } //! \brief Execute Hydra engine to perform minimal VP2 draw data update based on change tracker. void ProxyRenderDelegate::_Execute(const MHWRender::MFrameContext& frameContext) { MProfilingScope profilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "Execute"); _UpdateRenderTags(); // If update for selection is enabled, the draw data for the "points" repr // won't be prepared until point snapping is activated; otherwise the draw // data have to be prepared early for possible activation of point snapping. #if defined(MAYA_ENABLE_UPDATE_FOR_SELECTION) HdReprSelector reprSelector; const bool inSelectionPass = (frameContext.getSelectionInfo() != nullptr); #if !defined(MAYA_NEW_POINT_SNAPPING_SUPPORT) || defined(WANT_UFE_BUILD) const bool inPointSnapping = pointSnappingActive(); #endif #if defined(WANT_UFE_BUILD) // Query selection adjustment and kind only if the update is triggered in a selection pass. if (inSelectionPass && !inPointSnapping) { _globalListAdjustment = GetListAdjustment(); _selectionKind = GetSelectionKind(); _pointInstancesPickMode = GetPointInstancesPickMode(); } else { _globalListAdjustment = MGlobal::kReplaceList; _selectionKind = TfToken(); _pointInstancesPickMode = UsdPointInstancesPickMode::PointInstancer; } #endif // defined(WANT_UFE_BUILD) #else // !defined(MAYA_ENABLE_UPDATE_FOR_SELECTION) HdReprSelector reprSelector = kPointsReprSelector; constexpr bool inSelectionPass = false; #if !defined(MAYA_NEW_POINT_SNAPPING_SUPPORT) constexpr bool inPointSnapping = false; #endif #endif // defined(MAYA_ENABLE_UPDATE_FOR_SELECTION) #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT if (_selectionModeChanged || (_selectionChanged && !inSelectionPass)) { _UpdateSelectionStates(); _selectionChanged = false; _selectionModeChanged = false; } #else if (_selectionChanged && !inSelectionPass) { _UpdateSelectionStates(); _selectionChanged = false; } #endif if (inSelectionPass) { // The new Maya point snapping support doesn't require point snapping items any more. #if !defined(MAYA_NEW_POINT_SNAPPING_SUPPORT) if (inPointSnapping && !reprSelector.Contains(HdReprTokens->points)) { reprSelector = reprSelector.CompositeOver(kPointsReprSelector); } #endif } else { const unsigned int displayStyle = frameContext.getDisplayStyle(); // Query the wireframe color assigned to proxy shape. if (displayStyle & (MHWRender::MFrameContext::kBoundingBox | MHWRender::MFrameContext::kWireFrame)) { _wireframeColor = MHWRender::MGeometryUtilities::wireframeColor(_proxyShapeData->ProxyDagPath()); } // Update repr selector based on display style of the current viewport if (displayStyle & MHWRender::MFrameContext::kBoundingBox) { if (!reprSelector.Contains(HdVP2ReprTokens->bbox)) { reprSelector = reprSelector.CompositeOver(kBBoxReprSelector); } } else { // To support Wireframe on Shaded mode, the two displayStyle checks // should not be mutually excluded. if (displayStyle & MHWRender::MFrameContext::kGouraudShaded) { #ifdef HAS_DEFAULT_MATERIAL_SUPPORT_API if (displayStyle & MHWRender::MFrameContext::kDefaultMaterial) { if (!reprSelector.Contains(HdVP2ReprTokens->defaultMaterial)) { reprSelector = reprSelector.CompositeOver(kDefaultMaterialReprSelector); } } else #endif if (!reprSelector.Contains(HdReprTokens->smoothHull)) { reprSelector = reprSelector.CompositeOver(kSmoothHullReprSelector); } } if (displayStyle & MHWRender::MFrameContext::kWireFrame) { if (!reprSelector.Contains(HdReprTokens->wire)) { reprSelector = reprSelector.CompositeOver(kWireReprSelector); } } } } if (_defaultCollection->GetReprSelector() != reprSelector) { _defaultCollection->SetReprSelector(reprSelector); _taskController->SetCollection(*_defaultCollection); } _engine.Execute(_renderIndex.get(), &_dummyTasks); } //! \brief Main update entry from subscene override. void ProxyRenderDelegate::update(MSubSceneContainer& container, const MFrameContext& frameContext) { MProfilingScope profilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L1, "ProxyRenderDelegate::update"); // Without a proxy shape we can't do anything if (_proxyShapeData->ProxyShape() == nullptr) return; #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT const MSelectionInfo* selectionInfo = frameContext.getSelectionInfo(); if (selectionInfo) { bool oldSnapToPoints = _snapToPoints; #if MAYA_API_VERSION >= 20220000 _snapToPoints = selectionInfo->pointSnapping(); #else _snapToPoints = pointSnappingActive(); #endif if (_snapToPoints != oldSnapToPoints) { _selectionModeChanged = true; } } MStatus status; if (selectionInfo) { bool oldSnapToSelectedObjects = _snapToSelectedObjects; _snapToSelectedObjects = selectionInfo->snapToActive(&status); TF_VERIFY(status == MStatus::kSuccess); if (_snapToSelectedObjects != oldSnapToSelectedObjects) { _selectionModeChanged = true; } } #endif _ClearInvalidData(container); _InitRenderDelegate(); // Give access to current time and subscene container to the rest of render delegate world via // render param's. auto* param = reinterpret_cast<HdVP2RenderParam*>(_renderDelegate->GetRenderParam()); param->BeginUpdate(container, _sceneDelegate->GetTime()); if (_Populate()) { _UpdateSceneDelegate(); _Execute(frameContext); } param->EndUpdate(); } //! \brief Update selection granularity for point snapping. void ProxyRenderDelegate::updateSelectionGranularity( const MDagPath& path, MHWRender::MSelectionContext& selectionContext) { Selectability::prepareForSelection(); // The component level is coarse-grain, causing Maya to produce undesired face/edge selection // hits, as well as vertex selection hits that are required for point snapping. Switch to the // new vertex selection level if available in order to produce vertex selection hits only. if (pointSnappingActive()) { #if MAYA_API_VERSION >= 20220100 selectionContext.setSelectionLevel(MHWRender::MSelectionContext::kVertex); #else selectionContext.setSelectionLevel(MHWRender::MSelectionContext::kComponent); #endif } } // Resolves an rprimId and instanceIndex back to the original USD gprim and instance index. // see UsdImagingDelegate::GetScenePrimPath. // This version works against all the older versions of USD we care about. Once those old // versions go away, and we only support USD_IMAGING_API_VERSION >= 14 then we can remove // this function. #if defined(USD_IMAGING_API_VERSION) && USD_IMAGING_API_VERSION >= 14 SdfPath ProxyRenderDelegate::GetScenePrimPath( const SdfPath& rprimId, int instanceIndex, HdInstancerContext* instancerContext) const #else SdfPath ProxyRenderDelegate::GetScenePrimPath(const SdfPath& rprimId, int instanceIndex) const #endif { #if defined(USD_IMAGING_API_VERSION) && USD_IMAGING_API_VERSION >= 14 SdfPath usdPath = _sceneDelegate->GetScenePrimPath(rprimId, instanceIndex, instancerContext); #elif defined(USD_IMAGING_API_VERSION) && USD_IMAGING_API_VERSION >= 13 SdfPath usdPath = _sceneDelegate->GetScenePrimPath(rprimId, instanceIndex); #else SdfPath indexPath; if (drawInstID > 0) { indexPath = _sceneDelegate->GetPathForInstanceIndex(rprimId, instanceIndex, nullptr); } else { indexPath = rprimId; } SdfPath usdPath = _sceneDelegate->ConvertIndexPathToCachePath(indexPath); // Examine the USD path. If it is not a valid prim path, the selection hit is from a single // instance Rprim and indexPath is actually its instancer Rprim id. In this case we should // call GetPathForInstanceIndex() using 0 as the instance index. if (!usdPath.IsPrimPath()) { indexPath = _sceneDelegate->GetPathForInstanceIndex(rprimId, 0, nullptr); usdPath = _sceneDelegate->ConvertIndexPathToCachePath(indexPath); } // The "Instances" point instances pick mode is not supported for // USD_IMAGING_API_VERSION < 14 (core USD versions earlier than 20.08), so // no using instancerContext here. #endif return usdPath; } //! \brief Selection for both instanced and non-instanced cases. bool ProxyRenderDelegate::getInstancedSelectionPath( const MHWRender::MRenderItem& renderItem, const MHWRender::MIntersection& intersection, MDagPath& dagPath) const { #if defined(WANT_UFE_BUILD) // When point snapping, only the point position matters, so return the DAG path and avoid the // UFE global selection list to be updated. if (pointSnappingActive()) { dagPath = _proxyShapeData->ProxyDagPath(); return true; } if (!_proxyShapeData->ProxyShape() || !_proxyShapeData->ProxyShape()->isUfeSelectionEnabled()) { return false; } auto handler = Ufe::RunTimeMgr::instance().hierarchyHandler(USD_UFE_RUNTIME_ID); if (handler == nullptr) return false; // Extract id of the owner Rprim. A SdfPath directly created from the render // item name could be ill-formed if the render item represents instancing: // "/TreePatch/Tree_1.proto_leaves_id0/DrawItem_xxxxxxxx". Thus std::string // is used instead to extract Rprim id. const std::string renderItemName = renderItem.name().asChar(); const auto pos = renderItemName.find_first_of(VP2_RENDER_DELEGATE_SEPARATOR); const SdfPath rprimId(renderItemName.substr(0, pos)); // If drawInstID is positive, it means the selection hit comes from one instanced render item, // in this case its instance transform matrices have been sorted w.r.t. USD instance index, thus // instanceIndex is drawInstID minus 1 because VP2 instance IDs start from 1. Otherwise the // selection hit is from one regular render item, but the Rprim can be either plain or single // instance, because we don't use instanced draw for single instance render items in order to // improve draw performance in Maya 2020 and before. const int drawInstID = intersection.instanceID(); int instanceIndex = (drawInstID > 0) ? drawInstID - 1 : UsdImagingDelegate::ALL_INSTANCES; #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT // Get the custom data from the MRenderItem and map the instance index to the USD instance index auto mayaToUsd = MayaUsdCustomData::Get(renderItem); if (instanceIndex != UsdImagingDelegate::ALL_INSTANCES && ((int)mayaToUsd.size()) > instanceIndex) { instanceIndex = mayaToUsd[instanceIndex]; } #endif SdfPath topLevelPath; int topLevelInstanceIndex = UsdImagingDelegate::ALL_INSTANCES; #if defined(USD_IMAGING_API_VERSION) && USD_IMAGING_API_VERSION >= 14 HdInstancerContext instancerContext; SdfPath usdPath = GetScenePrimPath(rprimId, instanceIndex, &instancerContext); if (!instancerContext.empty()) { // Store the top-level instancer and instance index if the Rprim is the // result of point instancing. These will be used for the "Instances" // point instances pick mode. topLevelPath = instancerContext.front().first; topLevelInstanceIndex = instancerContext.front().second; } #else SdfPath usdPath = GetScenePrimPath(rprimId, instanceIndex); #endif // If update for selection is enabled, we can query the Maya selection list // adjustment, USD selection kind, and USD point instances pick mode once // per selection update to avoid the cost of executing MEL commands or // searching optionVars for each intersection. #if defined(MAYA_ENABLE_UPDATE_FOR_SELECTION) const TfToken& selectionKind = _selectionKind; const UsdPointInstancesPickMode& pointInstancesPickMode = _pointInstancesPickMode; const MGlobal::ListAdjustment& listAdjustment = _globalListAdjustment; #else const TfToken selectionKind = GetSelectionKind(); const UsdPointInstancesPickMode pointInstancesPickMode = GetPointInstancesPickMode(); const MGlobal::ListAdjustment listAdjustment = GetListAdjustment(); #endif UsdPrim prim = _proxyShapeData->UsdStage()->GetPrimAtPath(usdPath); const UsdPrim topLevelPrim = _proxyShapeData->UsdStage()->GetPrimAtPath(topLevelPath); // Enforce selectability metadata. if (!Selectability::isSelectable(prim)) { dagPath = MDagPath(); return true; } // Resolve the selection based on the point instances pick mode. // Note that in all cases except for "Instances" when the picked // PointInstancer is *not* an instance proxy, we reset the instanceIndex to // ALL_INSTANCES. As a result, the behavior of Viewport 2.0 may differ // slightly for "Prototypes" from that of usdview. Though the pick should // resolve to the same prim as it would in usdview, the selection // highlighting in Viewport 2.0 will highlight all instances rather than // only a single point instancer prototype as it does in usdview. We do // this to ensure that only when in "Instances" point instances pick mode // will we ever construct UFE scene items that represent point instances // and have an instance index component at the end of their Ufe::Path. switch (pointInstancesPickMode) { case UsdPointInstancesPickMode::Instances: { if (topLevelPrim) { prim = topLevelPrim; instanceIndex = topLevelInstanceIndex; } if (prim.IsInstanceProxy()) { while (prim.IsInstanceProxy()) { prim = prim.GetParent(); } instanceIndex = UsdImagingDelegate::ALL_INSTANCES; } usdPath = prim.GetPath(); break; } case UsdPointInstancesPickMode::Prototypes: { // The scene prim path returned by Hydra *is* the prototype prim's // path. We still reset instanceIndex since we're not picking a point // instance. instanceIndex = UsdImagingDelegate::ALL_INSTANCES; break; } case UsdPointInstancesPickMode::PointInstancer: default: { if (topLevelPrim) { prim = topLevelPrim; } while (prim.IsInstanceProxy()) { prim = prim.GetParent(); } usdPath = prim.GetPath(); instanceIndex = UsdImagingDelegate::ALL_INSTANCES; break; } } // If we didn't pick a point instance above, then search up from the picked // prim to satisfy the requested USD selection kind, if specified. If no // selection kind is specified, the exact prim that was picked from the // viewport should be selected, so there is no need to walk the scene // hierarchy. if (instanceIndex == UsdImagingDelegate::ALL_INSTANCES && !selectionKind.IsEmpty()) { prim = GetPrimOrAncestorWithKind(prim, selectionKind); if (prim) { usdPath = prim.GetPath(); } } const Ufe::PathSegment pathSegment = MayaUsd::ufe::usdPathToUfePathSegment(usdPath, instanceIndex); const Ufe::SceneItem::Ptr& si = handler->createItem(_proxyShapeData->ProxyShape()->ufePath() + pathSegment); if (!si) { TF_WARN("Failed to create UFE scene item for Rprim '%s'", rprimId.GetText()); return false; } #ifdef UFE_V2_FEATURES_AVAILABLE TF_UNUSED(listAdjustment); auto ufeSel = Ufe::NamedSelection::get("MayaSelectTool"); ufeSel->append(si); #else auto globalSelection = Ufe::GlobalSelection::get(); switch (listAdjustment) { case MGlobal::kReplaceList: // The list has been cleared before viewport selection runs, so we // can add the new hits directly. UFE selection list is a superset // of Maya selection list, calling clear()/replaceWith() on UFE // selection list would clear Maya selection list. globalSelection->append(si); break; case MGlobal::kAddToList: globalSelection->append(si); break; case MGlobal::kRemoveFromList: globalSelection->remove(si); break; case MGlobal::kXORWithList: if (!globalSelection->remove(si)) { globalSelection->append(si); } break; default: TF_WARN("Unexpected MGlobal::ListAdjustment enum for selection."); break; } #endif #else dagPath = _proxyShapeData->ProxyDagPath(); #endif return true; } //! \brief Notify of selection change. void ProxyRenderDelegate::SelectionChanged() { _selectionChanged = true; } //! \brief Populate lead and active selection for Rprims under the proxy shape. void ProxyRenderDelegate::_PopulateSelection() { #if defined(WANT_UFE_BUILD) if (_proxyShapeData->ProxyShape() == nullptr) { return; } _leadSelection.reset(new HdSelection); _activeSelection.reset(new HdSelection); const auto proxyPath = _proxyShapeData->ProxyShape()->ufePath(); const auto globalSelection = Ufe::GlobalSelection::get(); // Populate lead selection from the last item in UFE global selection. auto it = globalSelection->crbegin(); if (it != globalSelection->crend()) { PopulateSelection(*it, proxyPath, *_sceneDelegate, _leadSelection); // Start reverse iteration from the second last item in UFE global // selection and populate active selection. for (it++; it != globalSelection->crend(); it++) { PopulateSelection(*it, proxyPath, *_sceneDelegate, _activeSelection); } } #endif } /*! \brief Notify selection change to rprims. */ void ProxyRenderDelegate::_UpdateSelectionStates() { const MHWRender::DisplayStatus previousStatus = _displayStatus; _displayStatus = MHWRender::MGeometryUtilities::displayStatus(_proxyShapeData->ProxyDagPath()); SdfPathVector rootPaths; if (_displayStatus == MHWRender::kLead || _displayStatus == MHWRender::kActive) { if (_displayStatus != previousStatus) { rootPaths.push_back(SdfPath::AbsoluteRootPath()); } } else if (previousStatus == MHWRender::kLead || previousStatus == MHWRender::kActive) { rootPaths.push_back(SdfPath::AbsoluteRootPath()); _PopulateSelection(); } else { // Append pre-update lead and active selection. AppendSelectedPrimPaths(_leadSelection, rootPaths); AppendSelectedPrimPaths(_activeSelection, rootPaths); // Update lead and active selection. _PopulateSelection(); // Append post-update lead and active selection. AppendSelectedPrimPaths(_leadSelection, rootPaths); AppendSelectedPrimPaths(_activeSelection, rootPaths); } if (!rootPaths.empty()) { #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT // When the selection mode changes then we have to update all the selected render // items. Set a dirty flag on each of the rprims so they know what to update. // Avoid trying to set dirty the absolute root as it is not a Rprim. if (_selectionModeChanged) { HdChangeTracker& changeTracker = _renderIndex->GetChangeTracker(); const SdfPath& absRoot = SdfPath::AbsoluteRootPath(); for (auto path : rootPaths) { if (path != absRoot) { changeTracker.MarkRprimDirty(path, MayaPrimCommon::DirtySelectionMode); } } } #endif HdRprimCollection collection(HdTokens->geometry, kSelectionReprSelector); collection.SetRootPaths(rootPaths); _taskController->SetCollection(collection); _engine.Execute(_renderIndex.get(), &_dummyTasks); _taskController->SetCollection(*_defaultCollection); } } /*! \brief Trigger rprim update for rprims whose visibility changed because of render tags change */ void ProxyRenderDelegate::_UpdateRenderTags() { // USD pulls the required render tags from the task list passed into execute. // Only rprims which are dirty & which match the current set of render tags // will get a Sync call. // Render tags are harder for us to handle than HdSt because we have our own // cached version of the scene in MPxSubSceneOverride. HdSt draws using // HdRenderIndex::GetDrawItems(), and that returns only items that pass the // render tag filter. There is no need for HdSt to do any update on items that // are being hidden, because the render pass level filtering will prevent // them from drawing. // The Vp2RenderDelegate implements render tags using MRenderItem::Enable(), // which means we do need to update individual MRenderItems when the displayed // render tags change, or when the render tag on an rprim changes. // // To handle an rprim's render tag value changing we need to be sure that // the dummy render task we use to draw includes all render tags. If we // leave any tags out then when an rprim changes from a visible tag to // a hidden one that rprim will get marked dirty, but Sync will not be // called because the rprim doesn't match the current render tags. // // When we change the desired render tags on the proxyShape we'll be adding // and/or removing some tags, so we can have existing MRenderItems that need // to be hidden, or hidden items that need to be shown. To do that we need // to make sure every rprim with a render tag whose visibility changed gets // marked dirty. This will ensure the upcoming execute call will update // the visibility of the MRenderItems in MPxSubSceneOverride. HdChangeTracker& changeTracker = _renderIndex->GetChangeTracker(); // The renderTagsVersion increments when the render tags on an rprim are marked dirty, // or when the global render tags are set. Check to see if the render tags version has // changed since the last time we set the render tags so we know if there is a change // to an individual rprim or not. bool rprimRenderTagChanged = (_renderTagVersion != changeTracker.GetRenderTagVersion()); #ifdef ENABLE_RENDERTAG_VISIBILITY_WORKAROUND rprimRenderTagChanged = rprimRenderTagChanged || (_visibilityVersion != changeTracker.GetVisibilityChangeCount()); #endif bool renderPurposeChanged = false; bool proxyPurposeChanged = false; bool guidePurposeChanged = false; _proxyShapeData->UpdatePurpose( &renderPurposeChanged, &proxyPurposeChanged, &guidePurposeChanged); bool anyPurposeChanged = renderPurposeChanged || proxyPurposeChanged || guidePurposeChanged; if (anyPurposeChanged) { MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L1, "Update Purpose"); TfTokenVector changedRenderTags; // Build the list of render tags which were added or removed (changed) // and the list of render tags which were removed. if (renderPurposeChanged) { changedRenderTags.push_back(HdRenderTagTokens->render); } if (proxyPurposeChanged) { changedRenderTags.push_back(HdRenderTagTokens->proxy); } if (guidePurposeChanged) { changedRenderTags.push_back(HdRenderTagTokens->guide); } // Mark all the rprims which have a render tag which changed dirty SdfPathVector rprimsToDirty = _GetFilteredRprims(*_defaultCollection, changedRenderTags); for (auto& id : rprimsToDirty) { // this call to MarkRprimDirty will increment the change tracker render // tag version. We don't want this to cause rprimRenderTagChanged to be // true when a tag hasn't actually changed. changeTracker.MarkRprimDirty(id, HdChangeTracker::DirtyRenderTag); } } // Vp2RenderDelegate implements render tags as a per-render item setting. // To handle cases when an rprim changes from a displayed tag to a hidden tag // we need to visit all the rprims and set the enable flag correctly on // all their render items. Do visit all the rprims we need to set the // render tags to be all the tags. // When an rprim has it's renderTag changed the global render tag version // id will change. if (rprimRenderTagChanged) { // Sync every rprim, no matter what it's tag is. We don't know the tag(s) of // the rprim that changed, so the only way we can be sure to sync it is by // syncing everything. TfTokenVector renderTags = { HdRenderTagTokens->geometry, HdRenderTagTokens->render, HdRenderTagTokens->proxy, HdRenderTagTokens->guide }; _taskController->SetRenderTags(renderTags); _taskRenderTagsValid = false; } // When the render tag on an rprim changes we do a pass over all rprims to update // their visibility. The frame after we do the pass over all the tags, set the tags back to // the minimum set of tags. else if (anyPurposeChanged || !_taskRenderTagsValid) { TfTokenVector renderTags = { HdRenderTagTokens->geometry }; // always draw geometry render tag purpose. if (_proxyShapeData->DrawRenderPurpose() || renderPurposeChanged) { renderTags.push_back(HdRenderTagTokens->render); } if (_proxyShapeData->DrawProxyPurpose() || proxyPurposeChanged) { renderTags.push_back(HdRenderTagTokens->proxy); } if (_proxyShapeData->DrawGuidePurpose() || guidePurposeChanged) { renderTags.push_back(HdRenderTagTokens->guide); } _taskController->SetRenderTags(renderTags); // if the changedRenderTags is not empty then we could have some tags // in the _taskController just so that we get one sync to hide the render // items. In that case we need to leave _taskRenderTagsValid false, so that // we get a chance to remove that tag next frame. _taskRenderTagsValid = !anyPurposeChanged; } // TODO: UsdImagingDelegate is purpose-aware. There are methods // SetDisplayRender, SetDisplayProxy and SetDisplayGuides which inform the // scene delegate of what is displayed, and changes the behavior of // UsdImagingDelegate::GetRenderTag(). So far I don't see an advantage of // using this feature for MayaUSD, but it may be useful at some point in // the future. _renderTagVersion = changeTracker.GetRenderTagVersion(); #ifdef ENABLE_RENDERTAG_VISIBILITY_WORKAROUND _visibilityVersion = changeTracker.GetVisibilityChangeCount(); #endif } //! \brief List the rprims in collection that match renderTags SdfPathVector ProxyRenderDelegate::_GetFilteredRprims( HdRprimCollection const& collection, TfTokenVector const& renderTags) { SdfPathVector rprimIds; const SdfPathVector& paths = _renderIndex->GetRprimIds(); const SdfPathVector& includePaths = collection.GetRootPaths(); const SdfPathVector& excludePaths = collection.GetExcludePaths(); #if defined(HD_API_VERSION) && HD_API_VERSION >= 42 _FilterParam filterParam = { renderTags, _renderIndex.get() }; #else _FilterParam filterParam = { collection, renderTags, _renderIndex.get() }; #endif HdPrimGather gather; gather.PredicatedFilter( paths, includePaths, excludePaths, _DrawItemFilterPredicate, &filterParam, &rprimIds); return rprimIds; } //! \brief Query the selection state of a given prim from the lead selection. const HdSelection::PrimSelectionState* ProxyRenderDelegate::GetLeadSelectionState(const SdfPath& path) const { return (_leadSelection == nullptr) ? nullptr : _leadSelection->GetPrimSelectionState(HdSelection::HighlightModeSelect, path); } //! \brief Qeury the selection state of a given prim from the active selection. const HdSelection::PrimSelectionState* ProxyRenderDelegate::GetActiveSelectionState(const SdfPath& path) const { return (_activeSelection == nullptr) ? nullptr : _activeSelection->GetPrimSelectionState(HdSelection::HighlightModeSelect, path); } //! \brief Query the selection status of a given prim. HdVP2SelectionStatus ProxyRenderDelegate::GetSelectionStatus(const SdfPath& path) const { if (_displayStatus == MHWRender::kLead) { return kFullyLead; } if (_displayStatus == MHWRender::kActive) { return kFullyActive; } const HdSelection::PrimSelectionState* state = GetLeadSelectionState(path); if (state) { return state->fullySelected ? kFullyLead : kPartiallySelected; } state = GetActiveSelectionState(path); if (state) { return state->fullySelected ? kFullyActive : kPartiallySelected; } return kUnselected; } //! \brief Query the wireframe color assigned to the proxy shape. const MColor& ProxyRenderDelegate::GetWireframeColor() const { return _wireframeColor; } //! \brief const MColor& ProxyRenderDelegate::GetSelectionHighlightColor(bool lead) const { static const MColor kLeadColor(0.056f, 1.0f, 0.366f, 1.0f); static const MColor kActiveColor(1.0f, 1.0f, 1.0f, 1.0f); return lead ? kLeadColor : kActiveColor; } bool ProxyRenderDelegate::DrawRenderTag(const TfToken& renderTag) const { if (renderTag == HdRenderTagTokens->geometry) { return true; } else if (renderTag == HdRenderTagTokens->render) { return _proxyShapeData->DrawRenderPurpose(); } else if (renderTag == HdRenderTagTokens->guide) { return _proxyShapeData->DrawGuidePurpose(); } else if (renderTag == HdRenderTagTokens->proxy) { return _proxyShapeData->DrawProxyPurpose(); } else if (renderTag == HdRenderTagTokens->hidden) { return false; } else { TF_WARN("Unknown render tag"); return true; } } #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT bool ProxyRenderDelegate::SnapToSelectedObjects() const { return _snapToSelectedObjects; } bool ProxyRenderDelegate::SnapToPoints() const { return _snapToPoints; } #endif // ProxyShapeData ProxyRenderDelegate::ProxyShapeData::ProxyShapeData( const MayaUsdProxyShapeBase* proxyShape, const MDagPath& proxyDagPath) : _proxyShape(proxyShape) , _proxyDagPath(proxyDagPath) { assert(_proxyShape); } inline const MayaUsdProxyShapeBase* ProxyRenderDelegate::ProxyShapeData::ProxyShape() const { return _proxyShape; } inline const MDagPath& ProxyRenderDelegate::ProxyShapeData::ProxyDagPath() const { return _proxyDagPath; } inline UsdStageRefPtr ProxyRenderDelegate::ProxyShapeData::UsdStage() const { return _usdStage; } inline void ProxyRenderDelegate::ProxyShapeData::UpdateUsdStage() { _usdStage = _proxyShape->getUsdStage(); } inline bool ProxyRenderDelegate::ProxyShapeData::IsUsdStageUpToDate() const { return _proxyShape->getUsdStageVersion() == _usdStageVersion; } inline void ProxyRenderDelegate::ProxyShapeData::UsdStageUpdated() { _usdStageVersion = _proxyShape->getUsdStageVersion(); } inline bool ProxyRenderDelegate::ProxyShapeData::IsExcludePrimsUpToDate() const { return _proxyShape->getExcludePrimPathsVersion() == _excludePrimsVersion; } inline void ProxyRenderDelegate::ProxyShapeData::ExcludePrimsUpdated() { _excludePrimsVersion = _proxyShape->getExcludePrimPathsVersion(); } inline void ProxyRenderDelegate::ProxyShapeData::UpdatePurpose( bool* drawRenderPurposeChanged, bool* drawProxyPurposeChanged, bool* drawGuidePurposeChanged) { bool drawRenderPurpose, drawProxyPurpose, drawGuidePurpose; ProxyShape()->getDrawPurposeToggles(&drawRenderPurpose, &drawProxyPurpose, &drawGuidePurpose); if (drawRenderPurposeChanged) *drawRenderPurposeChanged = (drawRenderPurpose != _drawRenderPurpose); if (drawProxyPurposeChanged) *drawProxyPurposeChanged = (drawProxyPurpose != _drawProxyPurpose); if (drawGuidePurposeChanged) *drawGuidePurposeChanged = (drawGuidePurpose != _drawGuidePurpose); _drawRenderPurpose = drawRenderPurpose; _drawProxyPurpose = drawProxyPurpose; _drawGuidePurpose = drawGuidePurpose; } inline bool ProxyRenderDelegate::ProxyShapeData::DrawRenderPurpose() const { return _drawRenderPurpose; } inline bool ProxyRenderDelegate::ProxyShapeData::DrawProxyPurpose() const { return _drawProxyPurpose; } inline bool ProxyRenderDelegate::ProxyShapeData::DrawGuidePurpose() const { return _drawGuidePurpose; } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/lib/mayaUsd/fileio/translators/translatorUtil.cpp // // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "translatorUtil.h" #include <mayaUsd/fileio/primReaderArgs.h> #include <mayaUsd/fileio/primReaderContext.h> #include <mayaUsd/fileio/translators/translatorXformable.h> #include <mayaUsd/fileio/utils/adaptor.h> #include <mayaUsd/fileio/utils/xformStack.h> #include <mayaUsd/utils/util.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/schema.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usdGeom/xformable.h> #include <maya/MDagModifier.h> #include <maya/MDagPath.h> #include <maya/MFn.h> #include <maya/MFnDagNode.h> #include <maya/MFnDependencyNode.h> #include <maya/MGlobal.h> #include <maya/MObject.h> #include <maya/MStatus.h> #include <maya/MString.h> PXR_NAMESPACE_OPEN_SCOPE const MString _DEFAULT_TRANSFORM_TYPE("transform"); /* static */ bool UsdMayaTranslatorUtil::CreateTransformNode( const UsdPrim& usdPrim, MObject& parentNode, const UsdMayaPrimReaderArgs& args, UsdMayaPrimReaderContext* context, MStatus* status, MObject* mayaNodeObj) { if (!usdPrim || !usdPrim.IsA<UsdGeomXformable>()) { return false; } if (!CreateNode(usdPrim, _DEFAULT_TRANSFORM_TYPE, parentNode, context, status, mayaNodeObj)) { return false; } // Read xformable attributes from the UsdPrim on to the transform node. UsdGeomXformable xformable(usdPrim); UsdMayaTranslatorXformable::Read(xformable, *mayaNodeObj, args, context); return true; } /* static */ bool UsdMayaTranslatorUtil::CreateDummyTransformNode( const UsdPrim& usdPrim, MObject& parentNode, bool importTypeName, const UsdMayaPrimReaderArgs& args, UsdMayaPrimReaderContext* context, MStatus* status, MObject* mayaNodeObj) { if (!usdPrim) { return false; } if (!CreateNode(usdPrim, _DEFAULT_TRANSFORM_TYPE, parentNode, context, status, mayaNodeObj)) { return false; } MFnDagNode dagNode(*mayaNodeObj); // Set the typeName on the adaptor. if (UsdMayaAdaptor adaptor = UsdMayaAdaptor(*mayaNodeObj)) { VtValue typeName; if (!usdPrim.HasAuthoredTypeName()) { // A regular typeless def. typeName = TfToken(); } else if (importTypeName) { // Preserve type info for round-tripping. typeName = usdPrim.GetTypeName(); } else { // Unknown type name; treat this as though it were a typeless def. typeName = TfToken(); // If there is a typename that we're ignoring, leave a note so that // we know where it came from. const std::string notes = TfStringPrintf( "Imported from @%s@<%s> with type '%s'", usdPrim.GetStage()->GetRootLayer()->GetIdentifier().c_str(), usdPrim.GetPath().GetText(), usdPrim.GetTypeName().GetText()); UsdMayaUtil::SetNotes(dagNode, notes); } adaptor.SetMetadata(SdfFieldKeys->TypeName, typeName); } // Lock all the transform attributes. for (const UsdMayaXformOpClassification& opClass : UsdMayaXformStack::MayaStack().GetOps()) { if (!opClass.IsInvertedTwin()) { MPlug plug = dagNode.findPlug(opClass.GetName().GetText(), true); if (!plug.isNull()) { if (plug.isCompound()) { for (unsigned int i = 0; i < plug.numChildren(); ++i) { MPlug child = plug.child(i); child.setKeyable(false); child.setLocked(true); child.setChannelBox(false); } } else { plug.setKeyable(false); plug.setLocked(true); plug.setChannelBox(false); } } } } return true; } /* static */ bool UsdMayaTranslatorUtil::CreateNode( const UsdPrim& usdPrim, const MString& nodeTypeName, MObject& parentNode, UsdMayaPrimReaderContext* context, MStatus* status, MObject* mayaNodeObj) { return CreateNode(usdPrim.GetPath(), nodeTypeName, parentNode, context, status, mayaNodeObj); } /* static */ bool UsdMayaTranslatorUtil::CreateNode( const SdfPath& path, const MString& nodeTypeName, MObject& parentNode, UsdMayaPrimReaderContext* context, MStatus* status, MObject* mayaNodeObj) { if (!CreateNode( MString(path.GetName().c_str(), path.GetName().size()), nodeTypeName, parentNode, status, mayaNodeObj)) { return false; } if (context) { context->RegisterNewMayaNode(path.GetString(), *mayaNodeObj); } return true; } /* static */ bool UsdMayaTranslatorUtil::CreateNode( const MString& nodeName, const MString& nodeTypeName, MObject& parentNode, MStatus* status, MObject* mayaNodeObj) { // XXX: // Using MFnDagNode::create() results in nodes that are not properly // registered with parent scene assemblies. For now, just massaging the // transform code accordingly so that child scene assemblies properly post // their edits to their parents-- if this is indeed the best pattern for // this, all Maya*Reader node creation needs to be adjusted accordingly (for // much less trivial cases like MFnMesh). MDagModifier dagMod; *mayaNodeObj = dagMod.createNode(nodeTypeName, parentNode, status); CHECK_MSTATUS_AND_RETURN(*status, false); *status = dagMod.renameNode(*mayaNodeObj, nodeName); CHECK_MSTATUS_AND_RETURN(*status, false); *status = dagMod.doIt(); CHECK_MSTATUS_AND_RETURN(*status, false); return TF_VERIFY(!mayaNodeObj->isNull()); } /* static */ bool UsdMayaTranslatorUtil::CreateShaderNode( const MString& nodeName, const MString& nodeTypeName, const UsdMayaShadingNodeType shadingNodeType, MStatus* status, MObject* shaderObj, const MObject parentNode) { MString typeFlag; switch (shadingNodeType) { case UsdMayaShadingNodeType::Light: typeFlag = "-al"; // -asLight break; case UsdMayaShadingNodeType::PostProcess: typeFlag = "-app"; // -asPostProcess break; case UsdMayaShadingNodeType::Rendering: typeFlag = "-ar"; // -asRendering break; case UsdMayaShadingNodeType::Shader: typeFlag = "-as"; // -asShader break; case UsdMayaShadingNodeType::Texture: typeFlag = "-icm -at"; // -isColorManaged -asTexture break; case UsdMayaShadingNodeType::Utility: typeFlag = "-au"; // -asUtility break; default: { MFnDependencyNode depNodeFn; depNodeFn.create(nodeTypeName, nodeName, status); CHECK_MSTATUS_AND_RETURN(*status, false); *shaderObj = depNodeFn.object(status); CHECK_MSTATUS_AND_RETURN(*status, false); return true; } } MString parentFlag; if (!parentNode.isNull()) { const MFnDagNode parentDag(parentNode, status); CHECK_MSTATUS_AND_RETURN(*status, false); *status = parentFlag.format(" -p \"^1s\"", parentDag.fullPathName()); CHECK_MSTATUS_AND_RETURN(*status, false); } MString cmd; // ss = skipSelect *status = cmd.format( "shadingNode ^1s^2s -ss -n \"^3s\" \"^4s\"", typeFlag, parentFlag, nodeName, nodeTypeName); CHECK_MSTATUS_AND_RETURN(*status, false); const MString createdNode = MGlobal::executeCommandStringResult(cmd, false, false, status); CHECK_MSTATUS_AND_RETURN(*status, false); *status = UsdMayaUtil::GetMObjectByName(createdNode.asChar(), *shaderObj); CHECK_MSTATUS_AND_RETURN(*status, false); // Lights are unique in that they're the only DAG nodes we might create in // this function, so they also involve a transform node. The shadingNode // command unfortunately seems to return the transform node for the light // and not the light node itself, so we may need to manually find the light // so we can return that instead. if (shaderObj->hasFn(MFn::kDagNode)) { const MFnDagNode dagNodeFn(*shaderObj, status); CHECK_MSTATUS_AND_RETURN(*status, false); MDagPath dagPath; *status = dagNodeFn.getPath(dagPath); CHECK_MSTATUS_AND_RETURN(*status, false); unsigned int numShapes = 0u; *status = dagPath.numberOfShapesDirectlyBelow(numShapes); CHECK_MSTATUS_AND_RETURN(*status, false); if (numShapes == 1u) { *status = dagPath.extendToShape(); CHECK_MSTATUS_AND_RETURN(*status, false); *shaderObj = dagPath.node(status); CHECK_MSTATUS_AND_RETURN(*status, false); } } return true; } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/test/lib/ufe/testCamera.py #!/usr/bin/env python # # Copyright 2021 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import fixturesUtils import mayaUtils import testUtils import ufeUtils import usdUtils from pxr import Gf from maya import cmds from maya import standalone from maya.api import OpenMaya as om import ufe from functools import partial import unittest def matrix4dTranslation(matrix4d): translation = matrix4d.matrix[-1] return translation[:-1] def transform3dTranslation(transform3d): return matrix4dTranslation(transform3d.inclusiveMatrix()) def addVec(mayaVec, usdVec): return mayaVec + om.MVector(*usdVec) class TestObserver(ufe.Observer): def __init__(self): super(TestObserver, self).__init__() self.changed = 0 def __call__(self, notification): if isinstance(notification, ufe.CameraChanged): self.changed += 1 def notifications(self): return self.changed class CameraTestCase(unittest.TestCase): '''Verify the Camera UFE translate interface, for multiple runtimes. UFE Feature : Camera Maya Feature : camera Action : set & read camera parameters Applied On Selection : No Undo/Redo Test : No Expect Results To Test : - Setting a value through Ufe correctly updates USD - Reading a value through Ufe gets the correct value Edge Cases : - None. ''' pluginsLoaded = False @classmethod def setUpClass(cls): fixturesUtils.readOnlySetUpClass(__file__, loadPlugin=False) if not cls.pluginsLoaded: cls.pluginsLoaded = mayaUtils.isMayaUsdPluginLoaded() @classmethod def tearDownClass(cls): standalone.uninitialize() def setUp(self): ''' Called initially to set up the maya test environment ''' # Load plugins self.assertTrue(self.pluginsLoaded) # value from UsdGeomLinearUnits self.inchesToCm = 2.54 self.mmToCm = 0.1 def _StartTest(self, testName): cmds.file(force=True, new=True) mayaUtils.loadPlugin("mayaUsdPlugin") self._testName = testName testFile = testUtils.getTestScene("camera", self._testName + ".usda") mayaUtils.createProxyFromFile(testFile) globalSelection = ufe.GlobalSelection.get() globalSelection.clear() def _TestCameraAttributes(self, ufeCamera, usdCamera): # Trust that the USD API works correctly, validate that UFE gives us # the same answers self._TestHorizontalAperture(ufeCamera, usdCamera) self._TestVerticalAperture(ufeCamera, usdCamera) self._TestHorizontalApertureOffset(ufeCamera, usdCamera) self._TestVerticalApertureOffset(ufeCamera, usdCamera) self._TestFStop(ufeCamera, usdCamera) self._TestFocalLength(ufeCamera, usdCamera) self._TestFocusDistance(ufeCamera, usdCamera) self._TestClippingRange(ufeCamera, usdCamera) self._TestProjection(ufeCamera, usdCamera) def _TestClippingRange(self, ufeCamera, usdCamera): clippingAttr = usdCamera.GetAttribute('clippingRange') clippingRange = clippingAttr.Get() # read the nearClipPlane and check the value is what we expect. self.assertAlmostEqual(ufeCamera.nearClipPlane(), clippingRange[0]) self.assertAlmostEqual(ufeCamera.farClipPlane(), clippingRange[1]) # setting camera values through Ufe is not yet implemented in MayaUSD # ufeCamera.nearClipPlane(10) # ufeCamera.farClipPlane(20) # clippingRange = clippingAttr.Get() # self.assertAlmostEqual(10, clippingRange[0]) # self.assertAlmostEqual(20, clippingRange[1]) # set the clipping planes using USD clippingAttr.Set(Gf.Vec2f(1, 50)) # read the nearClipPlane and check the value is what we just set. self.assertAlmostEqual(ufeCamera.nearClipPlane(), 1) self.assertAlmostEqual(ufeCamera.farClipPlane(), 50) def _TestHorizontalAperture(self, ufeCamera, usdCamera): usdAttr = usdCamera.GetAttribute('horizontalAperture') horizontalAperture = usdAttr.Get() # the USD schema specifics that horizontal aperture is authored in mm # the ufeCamera gives us inches self.assertAlmostEqual(self.mmToCm * horizontalAperture, self.inchesToCm * ufeCamera.horizontalAperture()) # setting camera values through Ufe is not yet implemented in MayaUSD usdAttr.Set(0.5) self.assertAlmostEqual(self.mmToCm * 0.5, self.inchesToCm * ufeCamera.horizontalAperture()) def _TestVerticalAperture(self, ufeCamera, usdCamera): usdAttr = usdCamera.GetAttribute('verticalAperture') verticalAperture = usdAttr.Get() self.assertAlmostEqual(self.mmToCm * verticalAperture, self.inchesToCm * ufeCamera.verticalAperture()) # setting camera values through Ufe is not yet implemented in MayaUSD usdAttr.Set(0.5) self.assertAlmostEqual(self.mmToCm * 0.5, self.inchesToCm * ufeCamera.verticalAperture()) def _TestHorizontalApertureOffset(self, ufeCamera, usdCamera): usdAttr = usdCamera.GetAttribute('horizontalApertureOffset') horizontalApertureOffset = usdAttr.Get() self.assertAlmostEqual(self.mmToCm * horizontalApertureOffset, self.inchesToCm * ufeCamera.horizontalApertureOffset()) # setting camera values through Ufe is not yet implemented in MayaUSD usdAttr.Set(0.5) self.assertAlmostEqual(self.mmToCm * 0.5, self.inchesToCm * ufeCamera.horizontalApertureOffset()) def _TestVerticalApertureOffset(self, ufeCamera, usdCamera): usdAttr = usdCamera.GetAttribute('verticalApertureOffset') verticalApertureOffset = usdAttr.Get() self.assertAlmostEqual(self.mmToCm * verticalApertureOffset, self.inchesToCm * ufeCamera.verticalApertureOffset()) # setting camera values through Ufe is not yet implemented in MayaUSD usdAttr.Set(0.5) self.assertAlmostEqual(self.mmToCm * 0.5, self.inchesToCm * ufeCamera.verticalApertureOffset()) def _TestFStop(self, ufeCamera, usdCamera): usdAttr = usdCamera.GetAttribute('fStop') fStop = usdAttr.Get() # precision error here from converting units so use a less precise comparison, 6 digits instead of 7 self.assertAlmostEqual(fStop, self.mmToCm * ufeCamera.fStop(), 6) # setting camera values through Ufe is not yet implemented in MayaUSD usdAttr.Set(0.5) self.assertAlmostEqual(0.5, self.mmToCm * ufeCamera.fStop(), 6) def _TestFocalLength(self, ufeCamera, usdCamera): usdAttr = usdCamera.GetAttribute('focalLength') focalLength = usdAttr.Get() self.assertAlmostEqual(self.mmToCm * focalLength, self.mmToCm * ufeCamera.focalLength()) # setting camera values through Ufe is not yet implemented in MayaUSD usdAttr.Set(0.5) self.assertAlmostEqual(self.mmToCm * 0.5, self.mmToCm * ufeCamera.focalLength()) def _TestFocusDistance(self, ufeCamera, usdCamera): usdAttr = usdCamera.GetAttribute('focusDistance') focusDistance = usdAttr.Get() self.assertAlmostEqual(self.mmToCm * focusDistance, self.mmToCm * ufeCamera.focusDistance()) # setting camera values through Ufe is not yet implemented in MayaUSD usdAttr.Set(0.5) self.assertAlmostEqual(self.mmToCm * 0.5, self.mmToCm * ufeCamera.focusDistance()) def _TestProjection(self, ufeCamera, usdCamera): usdAttr = usdCamera.GetAttribute('projection') projection = usdAttr.Get() self.assertEqual(ufe.Camera.Perspective, ufeCamera.projection()) # setting camera values through Ufe is not yet implemented in MayaUSD usdAttr.Set("orthographic") self.assertAlmostEqual(ufe.Camera.Orthographic, ufeCamera.projection()) @unittest.skipIf(mayaUtils.previewReleaseVersion() <= 124, 'Missing Python API for Ufe::Camera before Maya Preview Release 125.') def testUsdCamera(self): self._StartTest('TranslateRotate_vs_xform') mayaPathSegment = mayaUtils.createUfePathSegment('|stage|stageShape') cam2UsdPathSegment = usdUtils.createUfePathSegment('/cameras/cam2/camera2') cam2Path = ufe.Path([mayaPathSegment, cam2UsdPathSegment]) cam2Item = ufe.Hierarchy.createItem(cam2Path) cam2Camera = ufe.Camera.camera(cam2Item) cameraPrim = usdUtils.getPrimFromSceneItem(cam2Item) self._TestCameraAttributes(cam2Camera, cameraPrim) if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/test/lib/usd/translators/testUsdImportUVSetMappings.py #!/usr/bin/env mayapy # # Copyright 2020 Pixar # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from pxr import Usd from pxr import UsdShade from maya import cmds from maya import standalone import os import unittest import fixturesUtils class testUsdImportUVSetMappings(unittest.TestCase): @classmethod def setUpClass(cls): input_path = fixturesUtils.setUpClass(__file__) cls.test_dir = os.path.join(input_path, "UsdImportUVSetMappingsTest") @classmethod def tearDownClass(cls): standalone.uninitialize() def testImportUVSetMappings(self): ''' Tests that importing complex UV set mappings work: ''' usd_path = os.path.join(self.test_dir, "UsdImportUVSetMappings.usda") options = ["shadingMode=[[useRegistry,UsdPreviewSurface]]", "primPath=/"] cmds.file(usd_path, i=True, type="USD Import", ignoreVersion=True, ra=True, mergeNamespacesOnClash=False, namespace="Test", pr=True, importTimeRange="combine", options=";".join(options)) # With merging working, we expect exactly these shading groups (since # two of them were made unmergeable) expected_sg = set(['initialParticleSE', 'initialShadingGroup', 'blinn1SG', 'blinn2SG', 'blinn3SG', 'blinn3SG_uvSet1', 'blinn4SG', 'blinn4SG_uvSet2']) self.assertEqual(set(cmds.ls(type="shadingEngine")), expected_sg) expected_links = [ ("file1", ['pPlane4Shape.uvSet[0].uvSetName', 'pPlane3Shape.uvSet[0].uvSetName', 'pPlane1Shape.uvSet[0].uvSetName', 'pPlane2Shape.uvSet[0].uvSetName']), ("file2", ['pPlane4Shape.uvSet[1].uvSetName', 'pPlane3Shape.uvSet[1].uvSetName', 'pPlane1Shape.uvSet[1].uvSetName', 'pPlane2Shape.uvSet[1].uvSetName']), ("file3", ['pPlane4Shape.uvSet[2].uvSetName', 'pPlane3Shape.uvSet[2].uvSetName', 'pPlane1Shape.uvSet[2].uvSetName', 'pPlane2Shape.uvSet[2].uvSetName']), ("file4", ['pPlane4Shape.uvSet[0].uvSetName', 'pPlane2Shape.uvSet[0].uvSetName']), ("file5", ['pPlane2Shape.uvSet[1].uvSetName',]), ("file6", ['pPlane2Shape.uvSet[2].uvSetName',]), ("file7", ['pPlane4Shape.uvSet[1].uvSetName',]), ("file8", ['pPlane4Shape.uvSet[2].uvSetName',]), ] for file_name, links in expected_links: links = set(links) self.assertEqual(set(cmds.uvLink(texture=file_name)), links) if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/lib/usd/utils/util.h // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef MAYAUSDUTILS_UTIL_H #define MAYAUSDUTILS_UTIL_H #include <mayaUsdUtils/Api.h> #include <mayaUsdUtils/ForwardDeclares.h> PXR_NAMESPACE_USING_DIRECTIVE namespace MayaUsdUtils { //! Return the highest-priority layer where the prim has a def primSpec. MAYA_USD_UTILS_PUBLIC SdfLayerHandle defPrimSpecLayer(const UsdPrim& prim); //! Return a PrimSpec for the argument prim in the layer containing the stage's current edit target. MAYA_USD_UTILS_PUBLIC SdfPrimSpecHandle getPrimSpecAtEditTarget(const UsdPrim& prim); //! Convenience function for printing the list of queried composition arcs in order. MAYA_USD_UTILS_PUBLIC void printCompositionQuery(const UsdPrim& prim, std::ostream& os); //! This function automatically updates the SdfPath for different // composition arcs (internal references, inherits, specializes) when // the path to the concrete prim they refer to has changed. MAYA_USD_UTILS_PUBLIC bool updateReferencedPath(const UsdPrim& oldPrim, const SdfPath& newPath); //! Returns true if reference is internal. MAYA_USD_UTILS_PUBLIC bool isInternalReference(const SdfReference&); } // namespace MayaUsdUtils #endif // MAYAUSDUTILS_UTIL_H <file_sep>/lib/mayaUsd/render/vp2RenderDelegate/mayaPrimCommon.h // // Copyright 2021 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef HD_VP2_MAYA_PRIM_COMMON #define HD_VP2_MAYA_PRIM_COMMON #include "pxr/imaging/hd/changeTracker.h" #include "pxr/imaging/hd/types.h" #include <maya/MHWGeometry.h> #include <tbb/concurrent_unordered_map.h> #include <vector> PXR_NAMESPACE_OPEN_SCOPE #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT // Each instanced render item needs to map from a Maya instance id // back to a usd instance id. using InstanceIdMap = std::vector<unsigned int>; // global singleton rather than MUserData, because consolidated world will // not consolidate render items with different MUserData objects. class MayaUsdCustomData { public: tbb::concurrent_unordered_map<int, InstanceIdMap> _itemData; static InstanceIdMap& Get(const MHWRender::MRenderItem& item); static void Remove(const MHWRender::MRenderItem& item); }; #endif struct MayaPrimCommon { enum DirtyBits : HdDirtyBits { DirtySelection = HdChangeTracker::CustomBitsBegin, DirtySelectionHighlight = (DirtySelection << 1), DirtySelectionMode = (DirtySelectionHighlight << 1), DirtyBitLast = DirtySelectionMode }; }; PXR_NAMESPACE_CLOSE_SCOPE #endif // HD_VP2_MAYA_PRIM_COMMON <file_sep>/lib/mayaUsd/render/vp2RenderDelegate/mesh.cpp // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "mesh.h" #include "bboxGeom.h" #include "debugCodes.h" #include "instancer.h" #include "material.h" #include "render_delegate.h" #include "tokens.h" #include <mayaUsd/render/vp2RenderDelegate/proxyRenderDelegate.h> #include <mayaUsd/utils/colorSpace.h> #include <pxr/base/gf/matrix4d.h> #include <pxr/base/tf/getenv.h> #include <pxr/imaging/hd/meshUtil.h> #include <pxr/imaging/hd/sceneDelegate.h> #include <pxr/imaging/hd/smoothNormals.h> #include <pxr/imaging/hd/version.h> #include <pxr/imaging/hd/vertexAdjacency.h> #include <pxr/pxr.h> #include <pxr/usdImaging/usdImaging/delegate.h> #include <maya/MFrameContext.h> #include <maya/MMatrix.h> #include <maya/MProfiler.h> #include <maya/MSelectionMask.h> #include <numeric> #include <type_traits> PXR_NAMESPACE_OPEN_SCOPE namespace { //! Required primvars when there is no material binding. const TfTokenVector sFallbackShaderPrimvars = { HdTokens->displayColor, HdTokens->displayOpacity, HdTokens->normals }; const MColor kOpaqueBlue(0.0f, 0.0f, 1.0f, 1.0f); //!< Opaque blue const MColor kOpaqueGray(.18f, .18f, .18f, 1.0f); //!< Opaque gray const unsigned int kNumColorChannels = 4; //!< The number of color channels const MString kPositionsStr("positions"); //!< Cached string for efficiency const MString kNormalsStr("normals"); //!< Cached string for efficiency const MString kDiffuseColorStr("diffuseColor"); //!< Cached string for efficiency const MString kSolidColorStr("solidColor"); //!< Cached string for efficiency //! A primvar vertex buffer data map indexed by primvar name. using PrimvarBufferDataMap = std::unordered_map<TfToken, void*, TfToken::HashFunctor>; //! \brief Helper struct used to package all the changes into single commit task //! (such commit task will be executed on main-thread) struct CommitState { HdVP2DrawItem::RenderItemData& _renderItemData; //! If valid, new index buffer data to commit int* _indexBufferData { nullptr }; //! If valid, new primvar buffer data to commit PrimvarBufferDataMap _primvarBufferDataMap; //! If valid, world matrix to set on the render item MMatrix* _worldMatrix { nullptr }; //! If valid, bounding box to set on the render item MBoundingBox* _boundingBox { nullptr }; //! if valid, enable or disable the render item bool* _enabled { nullptr }; //! Instancing doesn't have dirty bits, every time we do update, we must update instance //! transforms MMatrixArray _instanceTransforms; //! Color parameter that _instanceColors should be bound to MString _instanceColorParam; //! Color array to support per-instance color and selection highlight. MFloatArray _instanceColors; MStringArray _ufeIdentifiers; //! If valid, new shader instance to set MHWRender::MShaderInstance* _shader { nullptr }; //! Is this object transparent bool _isTransparent { false }; //! If true, associate geometric buffers to the render item and trigger consolidation/instancing //! update bool _geometryDirty { false }; //! Construct valid commit state CommitState(HdVP2DrawItem::RenderItemData& renderItemData) : _renderItemData(renderItemData) { } //! No default constructor, we need draw item and dirty bits. CommitState() = delete; }; //! Helper utility function to fill primvar data to vertex buffer. template <class DEST_TYPE, class SRC_TYPE> void _FillPrimvarData( DEST_TYPE* vertexBuffer, size_t numVertices, size_t channelOffset, const VtIntArray& renderingToSceneFaceVtxIds, const MString& rprimId, const HdMeshTopology& topology, const TfToken& primvarName, const VtArray<SRC_TYPE>& primvarData, const HdInterpolation& primvarInterp) { switch (primvarInterp) { case HdInterpolationConstant: for (size_t v = 0; v < numVertices; v++) { SRC_TYPE* pointer = reinterpret_cast<SRC_TYPE*>( reinterpret_cast<float*>(&vertexBuffer[v]) + channelOffset); *pointer = primvarData[0]; } break; case HdInterpolationVarying: case HdInterpolationVertex: if (numVertices <= renderingToSceneFaceVtxIds.size()) { const unsigned int dataSize = primvarData.size(); for (size_t v = 0; v < numVertices; v++) { unsigned int index = renderingToSceneFaceVtxIds[v]; if (index < dataSize) { SRC_TYPE* pointer = reinterpret_cast<SRC_TYPE*>( reinterpret_cast<float*>(&vertexBuffer[v]) + channelOffset); *pointer = primvarData[index]; } else { TF_DEBUG(HDVP2_DEBUG_MESH) .Msg( "Invalid Hydra prim '%s': " "primvar %s has %u elements, while its topology " "references face vertex index %u.\n", rprimId.asChar(), primvarName.GetText(), dataSize, index); } } } else { TF_CODING_ERROR( "Invalid Hydra prim '%s': " "requires %zu vertices, while the number of elements in " "renderingToSceneFaceVtxIds is %zu. Skipping primvar update.", rprimId.asChar(), numVertices, renderingToSceneFaceVtxIds.size()); memset(vertexBuffer, 0, sizeof(DEST_TYPE) * numVertices); } break; case HdInterpolationUniform: { const VtIntArray& faceVertexCounts = topology.GetFaceVertexCounts(); const size_t numFaces = faceVertexCounts.size(); if (numFaces <= primvarData.size()) { // The primvar has more data than needed, we issue a warning but // don't skip update. Truncate the buffer to the expected length. if (numFaces < primvarData.size()) { TF_DEBUG(HDVP2_DEBUG_MESH) .Msg( "Invalid Hydra prim '%s': " "primvar %s has %zu elements, while its topology " "references only upto element index %zu.\n", rprimId.asChar(), primvarName.GetText(), primvarData.size(), numFaces); } for (size_t f = 0, v = 0; f < numFaces; f++) { const size_t faceVertexCount = faceVertexCounts[f]; const size_t faceVertexEnd = v + faceVertexCount; for (; v < faceVertexEnd; v++) { SRC_TYPE* pointer = reinterpret_cast<SRC_TYPE*>( reinterpret_cast<float*>(&vertexBuffer[v]) + channelOffset); *pointer = primvarData[f]; } } } else { // The primvar has less data than needed. Issue warning and skip // update like what is done in HdStMesh. TF_DEBUG(HDVP2_DEBUG_MESH) .Msg( "Invalid Hydra prim '%s': " "primvar %s has only %zu elements, while its topology expects " "at least %zu elements. Skipping primvar update.\n", rprimId.asChar(), primvarName.GetText(), primvarData.size(), numFaces); memset(vertexBuffer, 0, sizeof(DEST_TYPE) * numVertices); } break; } case HdInterpolationFaceVarying: // Unshared vertex layout is required for face-varying primvars, in // this case renderingToSceneFaceVtxIds is a natural sequence starting // from 0, thus we can save a lookup into the table. If the assumption // about the natural sequence is changed, we will need the lookup and // remap indices. if (numVertices <= primvarData.size()) { // If the primvar has more data than needed, we issue a warning, // but don't skip the primvar update. Truncate the buffer to the // expected length. if (numVertices < primvarData.size()) { TF_DEBUG(HDVP2_DEBUG_MESH) .Msg( "Invalid Hydra prim '%s': " "primvar %s has %zu elements, while its topology references " "only upto element index %zu.\n", rprimId.asChar(), primvarName.GetText(), primvarData.size(), numVertices); } if (channelOffset == 0 && std::is_same<DEST_TYPE, SRC_TYPE>::value) { const void* source = static_cast<const void*>(primvarData.cdata()); memcpy(vertexBuffer, source, sizeof(DEST_TYPE) * numVertices); } else { for (size_t v = 0; v < numVertices; v++) { SRC_TYPE* pointer = reinterpret_cast<SRC_TYPE*>( reinterpret_cast<float*>(&vertexBuffer[v]) + channelOffset); *pointer = primvarData[v]; } } } else { // It is unexpected to have less data than we index into. Issue // a warning and skip update. TF_DEBUG(HDVP2_DEBUG_MESH) .Msg( "Invalid Hydra prim '%s': " "primvar %s has only %zu elements, while its topology expects " "at least %zu elements. Skipping primvar update.\n", rprimId.asChar(), primvarName.GetText(), primvarData.size(), numVertices); memset(vertexBuffer, 0, sizeof(DEST_TYPE) * numVertices); } break; default: TF_CODING_ERROR( "Invalid Hydra prim '%s': " "unimplemented interpolation %d for primvar %s", rprimId.asChar(), (int)primvarInterp, primvarName.GetText()); break; } } //! If there is uniform or face-varying primvar, we have to create unshared //! vertex layout on CPU because SSBO technique is not widely supported by //! GPUs and 3D APIs. bool _IsUnsharedVertexLayoutRequired(const PrimvarInfoMap& primvarInfo) { for (const auto& it : primvarInfo) { const HdInterpolation interp = it.second->_source.interpolation; if (interp == HdInterpolationUniform || interp == HdInterpolationFaceVarying) { return true; } } return false; } //! Helper utility function to get number of edge indices unsigned int _GetNumOfEdgeIndices(const HdMeshTopology& topology) { const VtIntArray& faceVertexCounts = topology.GetFaceVertexCounts(); unsigned int numIndex = 0; for (std::size_t i = 0; i < faceVertexCounts.size(); i++) { numIndex += faceVertexCounts[i]; } numIndex *= 2; // each edge has two ends. return numIndex; } //! Helper utility function to extract edge indices void _FillEdgeIndices(int* indices, const HdMeshTopology& topology) { const VtIntArray& faceVertexCounts = topology.GetFaceVertexCounts(); const int* currentFaceStart = topology.GetFaceVertexIndices().cdata(); for (std::size_t faceId = 0; faceId < faceVertexCounts.size(); faceId++) { int numVertexIndicesInFace = faceVertexCounts[faceId]; if (numVertexIndicesInFace >= 2) { for (int faceVertexId = 0; faceVertexId < numVertexIndicesInFace; faceVertexId++) { bool isLastVertex = faceVertexId == numVertexIndicesInFace - 1; *(indices++) = *(currentFaceStart + faceVertexId); *(indices++) = isLastVertex ? *currentFaceStart : *(currentFaceStart + faceVertexId + 1); } } currentFaceStart += numVertexIndicesInFace; } } //! Helper utility function to adapt Maya API changes. void setWantConsolidation(MHWRender::MRenderItem& renderItem, bool state) { #if MAYA_API_VERSION >= 20190000 renderItem.setWantConsolidation(state); #else renderItem.setWantSubSceneConsolidation(state); #endif } PrimvarInfo* _getInfo(const PrimvarInfoMap& infoMap, const TfToken& token) { auto it = infoMap.find(token); if (it != infoMap.end()) { return it->second.get(); } return nullptr; } void _getColorData( PrimvarInfoMap& infoMap, VtVec3fArray& colorArray, HdInterpolation& interpolation) { PrimvarInfo* info = _getInfo(infoMap, HdTokens->displayColor); if (info) { const VtValue& value = info->_source.data; if (value.IsHolding<VtVec3fArray>() && value.GetArraySize() > 0) { colorArray = value.UncheckedGet<VtVec3fArray>(); interpolation = info->_source.interpolation; } } if (colorArray.empty()) { // If color/opacity is not found, the 18% gray color will be used // to match the default color of Hydra Storm. colorArray.push_back(GfVec3f(0.18f, 0.18f, 0.18f)); interpolation = HdInterpolationConstant; infoMap[HdTokens->displayColor] = std::make_unique<PrimvarInfo>( PrimvarSource(VtValue(colorArray), interpolation, PrimvarSource::CPUCompute), nullptr); } } void _getOpacityData( PrimvarInfoMap& infoMap, VtFloatArray& opacityArray, HdInterpolation& interpolation) { PrimvarInfo* info = _getInfo(infoMap, HdTokens->displayOpacity); if (info) { const VtValue& value = info->_source.data; if (value.IsHolding<VtFloatArray>() && value.GetArraySize() > 0) { opacityArray = value.UncheckedGet<VtFloatArray>(); interpolation = info->_source.interpolation; } } if (opacityArray.empty()) { opacityArray.push_back(1.0f); interpolation = HdInterpolationConstant; infoMap[HdTokens->displayOpacity] = std::make_unique<PrimvarInfo>( PrimvarSource(VtValue(opacityArray), interpolation, PrimvarSource::CPUCompute), nullptr); } } //! Access the points VtVec3fArray _points(PrimvarInfoMap& infoMap) { if (PrimvarInfo* info = _getInfo(infoMap, HdTokens->points)) { VtValue data = info->_source.data; TF_VERIFY(data.IsHolding<VtVec3fArray>()); return data.UncheckedGet<VtVec3fArray>(); } return VtVec3fArray(); } } // namespace void HdVP2Mesh::_InitGPUCompute() { // check that the viewport is using OpenGL, we need it for the OpenGL normals computation MRenderer* renderer = MRenderer::theRenderer(); // would also be nice to check the openGL version but renderer->drawAPIVersion() returns 4. // Compute was added in 4.3 so I don't have enough information to make the check if (renderer && renderer->drawAPIIsOpenGL() && (TfGetenvInt("HDVP2_USE_GPU_NORMAL_COMPUTATION", 0) > 0)) { int threshold = TfGetenvInt("HDVP2_GPU_NORMAL_COMPUTATION_MINIMUM_THRESHOLD", 8000); _gpuNormalsComputeThreshold = threshold >= 0 ? (size_t)threshold : SIZE_MAX; } else _gpuNormalsComputeThreshold = SIZE_MAX; } size_t HdVP2Mesh::_gpuNormalsComputeThreshold = SIZE_MAX; //! \brief Constructor #if defined(HD_API_VERSION) && HD_API_VERSION >= 36 HdVP2Mesh::HdVP2Mesh(HdVP2RenderDelegate* delegate, const SdfPath& id) : HdMesh(id) #else HdVP2Mesh::HdVP2Mesh(HdVP2RenderDelegate* delegate, const SdfPath& id, const SdfPath& instancerId) : HdMesh(id, instancerId) #endif , _delegate(delegate) , _rprimId(id.GetText()) { _meshSharedData = std::make_shared<HdVP2MeshSharedData>(); // HdChangeTracker::IsVarying() can check dirty bits to tell us if an object is animated or not. // Not sure if it is correct on file load // Store a string version of the Cache Path to be used to tag MRenderItems. The CachePath is // equivalent to the USD segment of the items full Ufe::Path. auto* const param = static_cast<HdVP2RenderParam*>(_delegate->GetRenderParam()); ProxyRenderDelegate& drawScene = param->GetDrawScene(); _PrimSegmentString.append( drawScene.GetScenePrimPath(id, UsdImagingDelegate::ALL_INSTANCES).GetString().c_str()); #ifdef HDVP2_ENABLE_GPU_COMPUTE static std::once_flag initGPUComputeOnce; std::call_once(initGPUComputeOnce, _InitGPUCompute); #endif } void HdVP2Mesh::_CommitMVertexBuffer(MHWRender::MVertexBuffer* const buffer, void* bufferData) const { const MString& rprimId = _rprimId; _delegate->GetVP2ResourceRegistry().EnqueueCommit([buffer, bufferData, rprimId]() { MProfilingScope profilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L2, "CommitBuffer", rprimId.asChar()); // TODO: buffer usage so we know it is positions normals etc buffer->commit(bufferData); }); } void HdVP2Mesh::_PrepareSharedVertexBuffers( HdSceneDelegate* delegate, const HdDirtyBits& rprimDirtyBits, const TfToken& reprToken) { // Normals have two possible sources. They could be authored by the scene delegate, // in which case we should find them in _primvarInfo, or they could be computed // normals. Compute the normal buffer if necessary. PrimvarInfo* normalsInfo = _getInfo(_meshSharedData->_primvarInfo, HdTokens->normals); bool needNormals = _PrimvarIsRequired(HdTokens->normals); bool computeCPUNormals = (!normalsInfo && !_gpuNormalsEnabled) || (normalsInfo && PrimvarSource::CPUCompute == normalsInfo->_source.dataSource); bool computeGPUNormals = (!normalsInfo && _gpuNormalsEnabled) || (normalsInfo && PrimvarSource::GPUCompute == normalsInfo->_source.dataSource); bool hasCleanNormals = normalsInfo && (0 == (rprimDirtyBits & (DirtySmoothNormals | DirtyFlatNormals))); if (needNormals && (computeCPUNormals || computeGPUNormals) && !hasCleanNormals) { _MeshReprConfig::DescArray reprDescs = _GetReprDesc(reprToken); // Iterate through all reprdescs for the current repr to figure out if any // of them requires smooth normals or flat normals. If either (or both) // are required, we will calculate them once and clean the bits. bool requireSmoothNormals = false; bool requireFlatNormals = false; for (size_t descIdx = 0; descIdx < reprDescs.size(); ++descIdx) { const HdMeshReprDesc& desc = reprDescs[descIdx]; if (desc.geomStyle == HdMeshGeomStyleHull) { if (desc.flatShadingEnabled) { requireFlatNormals = true; } else { requireSmoothNormals = true; } } } // If there are authored normals, prepare buffer only when it is dirty. // otherwise, compute smooth normals from points and adjacency and we // have a custom dirty bit to determine whether update is needed. if (requireSmoothNormals && (rprimDirtyBits & DirtySmoothNormals)) { if (computeGPUNormals) { #ifdef HDVP2_ENABLE_GPU_COMPUTE _meshSharedData->_viewportCompute->setNormalVertexBufferGPUDirty(); #endif } if (computeCPUNormals) { // note: normals gets dirty when points are marked as dirty, // at change tracker. Hd_VertexAdjacencySharedPtr adjacency(new Hd_VertexAdjacency()); HdBufferSourceSharedPtr adjacencyComputation = adjacency->GetSharedAdjacencyBuilderComputation(&_meshSharedData->_topology); adjacencyComputation->Resolve(); // Only the points referenced by the topology are used to compute // smooth normals. VtValue normals(Hd_SmoothNormals::ComputeSmoothNormals( adjacency.get(), _points(_meshSharedData->_primvarInfo).size(), _points(_meshSharedData->_primvarInfo).cdata())); if (!normalsInfo) { _meshSharedData->_primvarInfo[HdTokens->normals] = std::make_unique<PrimvarInfo>( PrimvarSource( normals, HdInterpolationVertex, PrimvarSource::CPUCompute), nullptr); } else { normalsInfo->_source.data = normals; normalsInfo->_source.interpolation = HdInterpolationVertex; } } } if (requireFlatNormals && (rprimDirtyBits & DirtyFlatNormals)) { // TODO: } } // Prepare color buffer. if (((rprimDirtyBits & (HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyInstancer | HdChangeTracker::DirtyInstanceIndex)) != 0) && (_PrimvarIsRequired(HdTokens->displayColor) || _PrimvarIsRequired(HdTokens->displayOpacity))) { HdInterpolation colorInterp = HdInterpolationConstant; HdInterpolation alphaInterp = HdInterpolationConstant; VtVec3fArray colorArray; VtFloatArray alphaArray; _getColorData(_meshSharedData->_primvarInfo, colorArray, colorInterp); _getOpacityData(_meshSharedData->_primvarInfo, alphaArray, alphaInterp); PrimvarInfo* colorAndOpacityInfo = _getInfo(_meshSharedData->_primvarInfo, HdVP2Tokens->displayColorAndOpacity); if (!colorAndOpacityInfo) { _meshSharedData->_primvarInfo[HdVP2Tokens->displayColorAndOpacity] = std::make_unique<PrimvarInfo>( PrimvarSource(VtValue(), HdInterpolationConstant, PrimvarSource::CPUCompute), nullptr); colorAndOpacityInfo = _getInfo(_meshSharedData->_primvarInfo, HdVP2Tokens->displayColorAndOpacity); } if (colorInterp == HdInterpolationInstance || alphaInterp == HdInterpolationInstance) { TF_VERIFY(!GetInstancerId().IsEmpty()); VtIntArray instanceIndices = delegate->GetInstanceIndices(GetInstancerId(), GetId()); size_t numInstances = instanceIndices.size(); colorAndOpacityInfo->_extraInstanceData.setLength( numInstances * kNumColorChannels); // the data is a vec4 void* bufferData = &colorAndOpacityInfo->_extraInstanceData[0]; colorAndOpacityInfo->_source.interpolation = HdInterpolationInstance; size_t alphaChannelOffset = 3; for (size_t instance = 0; instance < numInstances; instance++) { int index = instanceIndices[instance]; GfVec3f* color = reinterpret_cast<GfVec3f*>( reinterpret_cast<float*>(&static_cast<GfVec4f*>(bufferData)[instance])); float* alpha = reinterpret_cast<float*>(&static_cast<GfVec4f*>(bufferData)[instance]) + alphaChannelOffset; if (colorInterp == HdInterpolationInstance) { *color = colorArray[index]; } else if (colorInterp == HdInterpolationConstant) { *color = colorArray[0]; } else { TF_WARN("Unsupported combination of display color interpolation and display " "opacity interpolation instance."); } if (alphaInterp == HdInterpolationInstance) { *alpha = alphaArray[index]; } else if (alphaInterp == HdInterpolationConstant) { *alpha = alphaArray[0]; } else { TF_WARN("Unsupported combination of display color interpolation instance and " "display opacity interpolation."); } } } else { if (!colorAndOpacityInfo->_buffer) { const MHWRender::MVertexBufferDescriptor vbDesc( "", MHWRender::MGeometry::kColor, MHWRender::MGeometry::kFloat, 4); colorAndOpacityInfo->_buffer.reset(new MHWRender::MVertexBuffer(vbDesc)); } void* bufferData = _meshSharedData->_numVertices > 0 ? colorAndOpacityInfo->_buffer->acquire(_meshSharedData->_numVertices, true) : nullptr; // Fill color and opacity into the float4 color stream. if (bufferData) { _FillPrimvarData( static_cast<GfVec4f*>(bufferData), _meshSharedData->_numVertices, 0, _meshSharedData->_renderingToSceneFaceVtxIds, _rprimId, _meshSharedData->_topology, HdTokens->displayColor, colorArray, colorInterp); _FillPrimvarData( static_cast<GfVec4f*>(bufferData), _meshSharedData->_numVertices, 3, _meshSharedData->_renderingToSceneFaceVtxIds, _rprimId, _meshSharedData->_topology, HdTokens->displayOpacity, alphaArray, alphaInterp); _CommitMVertexBuffer(colorAndOpacityInfo->_buffer.get(), bufferData); } } } // prepare the other primvar buffers // Prepare primvar buffers. if (rprimDirtyBits & (HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyNormals | HdChangeTracker::DirtyPrimvar)) { for (const auto& it : _meshSharedData->_primvarInfo) { const TfToken& token = it.first; // Color, opacity have been prepared separately. if ((token == HdTokens->displayColor) || (token == HdTokens->displayOpacity) || (token == HdVP2Tokens->displayColorAndOpacity)) continue; MHWRender::MGeometry::Semantic semantic = MHWRender::MGeometry::kTexture; if (token == HdTokens->points) { if ((rprimDirtyBits & HdChangeTracker::DirtyPoints) == 0) continue; semantic = MHWRender::MGeometry::kPosition; } else if (token == HdTokens->normals) { if ((rprimDirtyBits & (HdChangeTracker::DirtyNormals | DirtySmoothNormals)) == 0) continue; semantic = MHWRender::MGeometry::kNormal; } else if ((rprimDirtyBits & HdChangeTracker::DirtyPrimvar) == 0) { continue; } const VtValue& value = it.second->_source.data; const HdInterpolation& interp = it.second->_source.interpolation; if (!value.IsArrayValued() || value.GetArraySize() == 0) continue; MHWRender::MVertexBuffer* buffer = _meshSharedData->_primvarInfo[token]->_buffer.get(); void* bufferData = nullptr; if (value.IsHolding<VtFloatArray>()) { if (!buffer) { const MHWRender::MVertexBufferDescriptor vbDesc( "", semantic, MHWRender::MGeometry::kFloat, 1); buffer = new MHWRender::MVertexBuffer(vbDesc); _meshSharedData->_primvarInfo[token]->_buffer.reset(buffer); } if (buffer) { bufferData = _meshSharedData->_numVertices > 0 ? buffer->acquire(_meshSharedData->_numVertices, true) : nullptr; if (bufferData) { _FillPrimvarData( static_cast<float*>(bufferData), _meshSharedData->_numVertices, 0, _meshSharedData->_renderingToSceneFaceVtxIds, _rprimId, _meshSharedData->_topology, token, value.UncheckedGet<VtFloatArray>(), interp); } } } else if (value.IsHolding<VtVec2fArray>()) { if (!buffer) { const MHWRender::MVertexBufferDescriptor vbDesc( "", semantic, MHWRender::MGeometry::kFloat, 2); buffer = new MHWRender::MVertexBuffer(vbDesc); _meshSharedData->_primvarInfo[token]->_buffer.reset(buffer); } if (buffer) { bufferData = _meshSharedData->_numVertices > 0 ? buffer->acquire(_meshSharedData->_numVertices, true) : nullptr; if (bufferData) { _FillPrimvarData( static_cast<GfVec2f*>(bufferData), _meshSharedData->_numVertices, 0, _meshSharedData->_renderingToSceneFaceVtxIds, _rprimId, _meshSharedData->_topology, token, value.UncheckedGet<VtVec2fArray>(), interp); } } } else if (value.IsHolding<VtVec3fArray>()) { if (!buffer) { const MHWRender::MVertexBufferDescriptor vbDesc( "", semantic, MHWRender::MGeometry::kFloat, 3); buffer = new MHWRender::MVertexBuffer(vbDesc); _meshSharedData->_primvarInfo[token]->_buffer.reset(buffer); } if (buffer) { bufferData = _meshSharedData->_numVertices > 0 ? buffer->acquire(_meshSharedData->_numVertices, true) : nullptr; if (bufferData) { _FillPrimvarData( static_cast<GfVec3f*>(bufferData), _meshSharedData->_numVertices, 0, _meshSharedData->_renderingToSceneFaceVtxIds, _rprimId, _meshSharedData->_topology, token, value.UncheckedGet<VtVec3fArray>(), interp); } } } else if (value.IsHolding<VtVec4fArray>()) { if (!buffer) { const MHWRender::MVertexBufferDescriptor vbDesc( "", semantic, MHWRender::MGeometry::kFloat, 4); buffer = new MHWRender::MVertexBuffer(vbDesc); _meshSharedData->_primvarInfo[token]->_buffer.reset(buffer); } if (buffer) { bufferData = _meshSharedData->_numVertices > 0 ? buffer->acquire(_meshSharedData->_numVertices, true) : nullptr; if (bufferData) { _FillPrimvarData( static_cast<GfVec4f*>(bufferData), _meshSharedData->_numVertices, 0, _meshSharedData->_renderingToSceneFaceVtxIds, _rprimId, _meshSharedData->_topology, token, value.UncheckedGet<VtVec4fArray>(), interp); } } } else if (value.IsHolding<VtIntArray>()) { if (!buffer) { const MHWRender::MVertexBufferDescriptor vbDesc( "", semantic, MHWRender::MGeometry::kFloat, 1); // kInt32 buffer = new MHWRender::MVertexBuffer(vbDesc); _meshSharedData->_primvarInfo[token]->_buffer.reset(buffer); } if (buffer) { bufferData = _meshSharedData->_numVertices > 0 ? buffer->acquire(_meshSharedData->_numVertices, true) : nullptr; if (bufferData) { const VtIntArray& primvarData = value.UncheckedGet<VtIntArray>(); VtFloatArray convertedPrimvarData; convertedPrimvarData.reserve(primvarData.size()); for (auto& source : primvarData) { convertedPrimvarData.push_back(static_cast<float>(source)); } _FillPrimvarData( static_cast<float*>(bufferData), _meshSharedData->_numVertices, 0, _meshSharedData->_renderingToSceneFaceVtxIds, _rprimId, _meshSharedData->_topology, token, convertedPrimvarData, interp); } } } else { TF_WARN("Unsupported primvar array"); } _CommitMVertexBuffer(buffer, bufferData); } } } bool HdVP2Mesh::_PrimvarIsRequired(const TfToken& primvar) const { const TfTokenVector& allRequiredPrimvars = _meshSharedData->_allRequiredPrimvars; TfTokenVector::const_iterator begin = allRequiredPrimvars.cbegin(); TfTokenVector::const_iterator end = allRequiredPrimvars.cend(); return (std::find(begin, end, primvar) != end); } //! \brief Synchronize VP2 state with scene delegate state based on dirty bits and representation void HdVP2Mesh::Sync( HdSceneDelegate* delegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits, const TfToken& reprToken) { // We don't create render items for the selection repr. The selection repr // is used when the Sync call is made during a selection pass. // When the selection mode changes, we DO want the chance to update our // shaded render items (to support things like point snapping to similar instances), so make // another call to Sync but with the smoothHull repr. if (reprToken == HdVP2ReprTokens->selection) { if (*dirtyBits & DirtySelectionMode) { Sync(delegate, renderParam, dirtyBits, HdReprTokens->smoothHull); } return; } const SdfPath& id = GetId(); // We don't update the repr if it is hidden by the render tags (purpose) // of the ProxyRenderDelegate. In additional, we need to hide any already // existing render items because they should not be drawn. auto* const param = static_cast<HdVP2RenderParam*>(_delegate->GetRenderParam()); ProxyRenderDelegate& drawScene = param->GetDrawScene(); HdRenderIndex& renderIndex = delegate->GetRenderIndex(); if (!drawScene.DrawRenderTag(renderIndex.GetRenderTag(id))) { _HideAllDrawItems(reprToken); *dirtyBits &= ~( HdChangeTracker::DirtyRenderTag #ifdef ENABLE_RENDERTAG_VISIBILITY_WORKAROUND | HdChangeTracker::DirtyVisibility #endif ); return; } MProfilingScope profilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L2, _rprimId.asChar(), "HdVP2Mesh::Sync"); // Geom subsets are accessed through the mesh topology. I need to know about // the additional materialIds that get bound by geom subsets before we build the // _primvaInfo. So the very first thing I need to do is grab the topology. if (HdChangeTracker::IsTopologyDirty(*dirtyBits, id)) { // unsubscribe from material updates from the old geom subset materials #ifdef HDVP2_MATERIAL_CONSOLIDATION_UPDATE_WORKAROUND for (const auto& geomSubset : _meshSharedData->_topology.GetGeomSubsets()) { if (!geomSubset.materialId.IsEmpty()) { const SdfPath materialId = dynamic_cast<UsdImagingDelegate*>(delegate)->ConvertCachePathToIndexPath( geomSubset.materialId); HdVP2Material* material = static_cast<HdVP2Material*>( renderIndex.GetSprim(HdPrimTypeTokens->material, materialId)); if (material) { material->UnsubscribeFromMaterialUpdates(id); } } } #endif _meshSharedData->_topology = GetMeshTopology(delegate); // subscribe to material updates from the new geom subset materials #ifdef HDVP2_MATERIAL_CONSOLIDATION_UPDATE_WORKAROUND for (const auto& geomSubset : _meshSharedData->_topology.GetGeomSubsets()) { if (!geomSubset.materialId.IsEmpty()) { const SdfPath materialId = dynamic_cast<UsdImagingDelegate*>(delegate)->ConvertCachePathToIndexPath( geomSubset.materialId); HdVP2Material* material = static_cast<HdVP2Material*>( renderIndex.GetSprim(HdPrimTypeTokens->material, materialId)); if (material) { material->SubscribeForMaterialUpdates(id); } } } #endif } if (*dirtyBits & HdChangeTracker::DirtyMaterialId) { const SdfPath materialId = delegate->GetMaterialId(id); #ifdef HDVP2_MATERIAL_CONSOLIDATION_UPDATE_WORKAROUND const SdfPath& origMaterialId = GetMaterialId(); if (materialId != origMaterialId) { if (!origMaterialId.IsEmpty()) { HdVP2Material* material = static_cast<HdVP2Material*>( renderIndex.GetSprim(HdPrimTypeTokens->material, origMaterialId)); if (material) { material->UnsubscribeFromMaterialUpdates(id); } } if (!materialId.IsEmpty()) { HdVP2Material* material = static_cast<HdVP2Material*>( renderIndex.GetSprim(HdPrimTypeTokens->material, materialId)); if (material) { material->SubscribeForMaterialUpdates(id); } } } #endif #if HD_API_VERSION < 37 _SetMaterialId(renderIndex.GetChangeTracker(), materialId); #else SetMaterialId(materialId); #endif } #if defined(HD_API_VERSION) && HD_API_VERSION >= 36 // Update our instance topology if necessary. _UpdateInstancer(delegate, dirtyBits); #endif // if the instancer is dirty then any streams with instance interpolation need to be updated. // We don't necessarily know if there ARE any streams with instance interpolation, so call // _UpdatePrimvarSources to check. bool instancerDirty = ((*dirtyBits & (HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyInstancer | HdChangeTracker::DirtyInstanceIndex)) != 0); if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->points) || HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->normals) || HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->primvar) || instancerDirty) { auto addRequiredPrimvars = [&](const SdfPath& materialId) { const HdVP2Material* material = static_cast<const HdVP2Material*>( renderIndex.GetSprim(HdPrimTypeTokens->material, materialId)); const TfTokenVector& requiredPrimvars = material && material->GetSurfaceShader() ? material->GetRequiredPrimvars() : sFallbackShaderPrimvars; for (const auto& requiredPrimvar : requiredPrimvars) { if (!_PrimvarIsRequired(requiredPrimvar)) { _meshSharedData->_allRequiredPrimvars.push_back(requiredPrimvar); } } }; // there is a chance that the geom subsets cover all the faces of the // mesh and that the overall material id is unused. I don't figure that // out until much later, so for now just accept that we might pull unnecessary // primvars required by the overall material but not by any of the geom subset // materials. addRequiredPrimvars(GetMaterialId()); for (const auto& geomSubset : _meshSharedData->_topology.GetGeomSubsets()) { addRequiredPrimvars( dynamic_cast<UsdImagingDelegate*>(delegate)->ConvertCachePathToIndexPath( geomSubset.materialId)); } // also, we always require points if (!_PrimvarIsRequired(HdTokens->points)) _meshSharedData->_allRequiredPrimvars.push_back(HdTokens->points); _UpdatePrimvarSources(delegate, *dirtyBits, _meshSharedData->_allRequiredPrimvars); } if (HdChangeTracker::IsTopologyDirty(*dirtyBits, id)) { const HdMeshTopology& topology = _meshSharedData->_topology; const VtIntArray& faceVertexIndices = topology.GetFaceVertexIndices(); const size_t numFaceVertexIndices = faceVertexIndices.size(); VtIntArray newFaceVertexIndices; newFaceVertexIndices.resize(numFaceVertexIndices); if (_IsUnsharedVertexLayoutRequired(_meshSharedData->_primvarInfo)) { _meshSharedData->_numVertices = numFaceVertexIndices; _meshSharedData->_renderingToSceneFaceVtxIds = faceVertexIndices; _meshSharedData->_sceneToRenderingFaceVtxIds.clear(); _meshSharedData->_sceneToRenderingFaceVtxIds.resize(topology.GetNumPoints(), -1); for (size_t i = 0; i < numFaceVertexIndices; i++) { const int sceneFaceVtxId = faceVertexIndices[i]; _meshSharedData->_sceneToRenderingFaceVtxIds[sceneFaceVtxId] = i; // could check if the existing value is -1, but it doesn't matter. // we just need to map to a vertex in the position buffer that has // the correct value. } // Fill with sequentially increasing values, starting from 0. The new // face vertex indices will be used to populate index data for unshared // vertex layout. Note that _FillPrimvarData assumes this sequence to // be used for face-varying primvars and saves lookup and remapping // with _renderingToSceneFaceVtxIds, so in case we change the array we // should update _FillPrimvarData() code to remap indices correctly. std::iota(newFaceVertexIndices.begin(), newFaceVertexIndices.end(), 0); } else { _meshSharedData->_numVertices = topology.GetNumPoints(); _meshSharedData->_renderingToSceneFaceVtxIds.clear(); // Allocate large enough memory with initial value of -1 to indicate // the rendering face vertex index is not determined yet. _meshSharedData->_sceneToRenderingFaceVtxIds.clear(); _meshSharedData->_sceneToRenderingFaceVtxIds.resize(numFaceVertexIndices, -1); unsigned int sceneToRenderingFaceVtxIdsCount = 0; // Sort vertices to avoid drastically jumping indices. Cache efficiency // is important to fast rendering performance for dense mesh. for (size_t i = 0; i < numFaceVertexIndices; i++) { const int sceneFaceVtxId = faceVertexIndices[i]; int renderFaceVtxId = _meshSharedData->_sceneToRenderingFaceVtxIds[sceneFaceVtxId]; if (renderFaceVtxId < 0) { renderFaceVtxId = _meshSharedData->_renderingToSceneFaceVtxIds.size(); _meshSharedData->_renderingToSceneFaceVtxIds.push_back(sceneFaceVtxId); _meshSharedData->_sceneToRenderingFaceVtxIds[sceneFaceVtxId] = renderFaceVtxId; sceneToRenderingFaceVtxIdsCount++; } newFaceVertexIndices[i] = renderFaceVtxId; } _meshSharedData->_sceneToRenderingFaceVtxIds.resize( sceneToRenderingFaceVtxIdsCount); // drop any extra -1 values. } _meshSharedData->_renderingTopology = HdMeshTopology( topology.GetScheme(), topology.GetOrientation(), topology.GetFaceVertexCounts(), newFaceVertexIndices, topology.GetHoleIndices(), topology.GetRefineLevel()); // All the render items to draw the shaded (Hull) style share the topology // calculation HdMeshUtil meshUtil(&_meshSharedData->_renderingTopology, GetId()); _meshSharedData->_trianglesFaceVertexIndices.clear(); _meshSharedData->_primitiveParam.clear(); meshUtil.ComputeTriangleIndices( &_meshSharedData->_trianglesFaceVertexIndices, &_meshSharedData->_primitiveParam, nullptr); // Decide if we should use GPU compute, and set up compute objects for later user #ifdef HDVP2_ENABLE_GPU_COMPUTE _gpuNormalsEnabled = _gpuNormalsEnabled && _meshSharedData->_numVertices >= _gpuNormalsComputeThreshold; if (_gpuNormalsEnabled) { _CreateViewportCompute(); #ifdef HDVP2_ENABLE_GPU_OSD _CreateOSDTables(); #endif } #else _gpuNormalsEnabled = false; #endif } _PrepareSharedVertexBuffers(delegate, *dirtyBits, reprToken); if (HdChangeTracker::IsExtentDirty(*dirtyBits, id)) { _sharedData.bounds.SetRange(delegate->GetExtent(id)); } if (HdChangeTracker::IsTransformDirty(*dirtyBits, id)) { _sharedData.bounds.SetMatrix(delegate->GetTransform(id)); } if (HdChangeTracker::IsVisibilityDirty(*dirtyBits, id)) { _sharedData.visible = delegate->GetVisible(id); // Invisible rprims don't get calls to Sync or _PropagateDirtyBits while // they are invisible. This means that when a prim goes from visible to // invisible that we must update every repr, because if we switch reprs while // invisible we'll get no chance to update! if (!_sharedData.visible) _MakeOtherReprRenderItemsInvisible(delegate, reprToken); } if (*dirtyBits & (HdChangeTracker::DirtyRenderTag #ifdef ENABLE_RENDERTAG_VISIBILITY_WORKAROUND | HdChangeTracker::DirtyVisibility #endif )) { _meshSharedData->_renderTag = delegate->GetRenderTag(id); } *dirtyBits = HdChangeTracker::Clean; // Draw item update is controlled by its own dirty bits. _UpdateRepr(delegate, reprToken); } /*! \brief Returns the minimal set of dirty bits to place in the change tracker for use in the first sync of this prim. */ HdDirtyBits HdVP2Mesh::GetInitialDirtyBitsMask() const { constexpr HdDirtyBits bits = HdChangeTracker::InitRepr | HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyTransform | HdChangeTracker::DirtyMaterialId | HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyVisibility | HdChangeTracker::DirtyInstancer | HdChangeTracker::DirtyInstanceIndex | HdChangeTracker::DirtyRenderTag | DirtySelectionHighlight; return bits; } /*! \brief Add additional dirty bits This callback from Rprim gives the prim an opportunity to set additional dirty bits based on those already set. This is done before the dirty bits are passed to the scene delegate, so can be used to communicate that extra information is needed by the prim to process the changes. The return value is the new set of dirty bits, which replaces the bits passed in. See HdRprim::PropagateRprimDirtyBits() */ HdDirtyBits HdVP2Mesh::_PropagateDirtyBits(HdDirtyBits bits) const { // If subdiv tags are dirty, topology needs to be recomputed. // The latter implies we'll need to recompute all primvar data. // Any data fetched by the scene delegate should be marked dirty here. if (bits & HdChangeTracker::DirtySubdivTags) { bits |= (HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyNormals | HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyDisplayStyle); } else if (bits & HdChangeTracker::DirtyTopology) { // Unlike basis curves, we always request refineLevel when topology is // dirty bits |= HdChangeTracker::DirtySubdivTags | HdChangeTracker::DirtyDisplayStyle; } // A change of material means that the Quadrangulate state may have // changed. if (bits & HdChangeTracker::DirtyMaterialId) { bits |= (HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyNormals | HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyTopology); } // If points, display style, or topology changed, recompute normals. if (bits & (HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyDisplayStyle | HdChangeTracker::DirtyTopology)) { bits |= _customDirtyBitsInUse & (DirtySmoothNormals | DirtyFlatNormals); } // If normals are dirty and we are doing CPU normals // then the normals computation needs the points primvar // so mark points as dirty, so that the scene delegate will provide // the data. if ((bits & (DirtySmoothNormals | DirtyFlatNormals))/* && !HdStGLUtils::IsGpuComputeEnabled()*/) { bits |= HdChangeTracker::DirtyPoints; } // Sometimes we don't get dirty extent notification if (bits & (HdChangeTracker::DirtyPoints)) { bits |= HdChangeTracker::DirtyExtent; } // Visibility and selection result in highlight changes: if ((bits & HdChangeTracker::DirtyVisibility) && (bits & DirtySelection)) { bits |= DirtySelectionHighlight; } if (bits & HdChangeTracker::AllDirty) { // RPrim is dirty, propagate dirty bits to all draw items. for (const std::pair<TfToken, HdReprSharedPtr>& pair : _reprs) { const HdReprSharedPtr& repr = pair.second; const auto& items = repr->GetDrawItems(); #if HD_API_VERSION < 35 for (HdDrawItem* item : items) { if (HdVP2DrawItem* drawItem = static_cast<HdVP2DrawItem*>(item)) { #else for (const HdRepr::DrawItemUniquePtr& item : items) { if (HdVP2DrawItem* const drawItem = static_cast<HdVP2DrawItem*>(item.get())) { #endif for (auto& renderItemData : drawItem->GetRenderItems()) { renderItemData.SetDirtyBits(bits); } } } } } else { // RPrim is clean, find out if any drawItem about to be shown is dirty: for (const std::pair<TfToken, HdReprSharedPtr>& pair : _reprs) { const HdReprSharedPtr& repr = pair.second; const auto& items = repr->GetDrawItems(); #if HD_API_VERSION < 35 for (const HdDrawItem* item : items) { if (const HdVP2DrawItem* drawItem = static_cast<const HdVP2DrawItem*>(item)) { #else for (const HdRepr::DrawItemUniquePtr& item : items) { if (const HdVP2DrawItem* const drawItem = static_cast<HdVP2DrawItem*>(item.get())) { #endif // Is this Repr dirty and in need of a Sync? for (auto& renderItemData : drawItem->GetRenderItems()) { if (renderItemData.GetDirtyBits() & HdChangeTracker::DirtyRepr) { bits |= (renderItemData.GetDirtyBits() & ~HdChangeTracker::DirtyRepr); } } } } } } return bits; } /*! \brief Initialize the given representation of this Rprim. This is called prior to syncing the prim, the first time the repr is used. \param reprToken the name of the repr to initalize. HdRprim has already resolved the reprName to its final value. \param dirtyBits an in/out value. It is initialized to the dirty bits from the change tracker. InitRepr can then set additional dirty bits if additional data is required from the scene delegate when this repr is synced. InitRepr occurs before dirty bit propagation. See HdRprim::InitRepr() */ void HdVP2Mesh::_InitRepr(const TfToken& reprToken, HdDirtyBits* dirtyBits) { auto* const param = static_cast<HdVP2RenderParam*>(_delegate->GetRenderParam()); MSubSceneContainer* subSceneContainer = param->GetContainer(); if (ARCH_UNLIKELY(!subSceneContainer)) return; // Update selection state on demand or when it is a new Rprim. DirtySelection // will be propagated to all draw items, to trigger sync for each repr. if (reprToken == HdVP2ReprTokens->selection || _reprs.empty()) { const HdVP2SelectionStatus selectionStatus = param->GetDrawScene().GetSelectionStatus(GetId()); if (_selectionStatus != selectionStatus) { _selectionStatus = selectionStatus; *dirtyBits |= DirtySelection; } else if (_selectionStatus == kPartiallySelected) { *dirtyBits |= DirtySelection; } // We don't create a repr for the selection token because it serves for // selection state update only. Return from here. if (reprToken == HdVP2ReprTokens->selection) return; } // If the repr has any draw item with the DirtySelection bit, mark the // DirtySelectionHighlight bit to invoke the synchronization call. _ReprVector::const_iterator it = std::find_if(_reprs.begin(), _reprs.end(), _ReprComparator(reprToken)); if (it != _reprs.end()) { const HdReprSharedPtr& repr = it->second; const auto& items = repr->GetDrawItems(); #if HD_API_VERSION < 35 for (HdDrawItem* item : items) { HdVP2DrawItem* drawItem = static_cast<HdVP2DrawItem*>(item); #else for (const HdRepr::DrawItemUniquePtr& item : items) { HdVP2DrawItem* const drawItem = static_cast<HdVP2DrawItem*>(item.get()); #endif if (drawItem) { for (auto& renderItemData : drawItem->GetRenderItems()) { if (renderItemData.GetDirtyBits() & HdChangeTracker::AllDirty) { // About to be drawn, but the Repr is dirty. Add DirtyRepr so we know in // _PropagateDirtyBits that we need to propagate the dirty bits of this draw // items to ensure proper Sync renderItemData.SetDirtyBits(HdChangeTracker::DirtyRepr); } if (renderItemData.GetDirtyBits() & DirtySelection) { *dirtyBits |= DirtySelectionHighlight; } } } } return; } _reprs.emplace_back(reprToken, std::make_shared<HdRepr>()); HdReprSharedPtr repr = _reprs.back().second; // set dirty bit to say we need to sync a new repr *dirtyBits |= HdChangeTracker::NewRepr; _MeshReprConfig::DescArray descs = _GetReprDesc(reprToken); for (size_t descIdx = 0; descIdx < descs.size(); ++descIdx) { const HdMeshReprDesc& desc = descs[descIdx]; if (desc.geomStyle == HdMeshGeomStyleInvalid) { continue; } #if HD_API_VERSION < 35 auto* drawItem = new HdVP2DrawItem(_delegate, &_sharedData); #else std::unique_ptr<HdVP2DrawItem> drawItem = std::make_unique<HdVP2DrawItem>(_delegate, &_sharedData); #endif const MString& renderItemName = drawItem->GetDrawItemName(); MHWRender::MRenderItem* renderItem = nullptr; switch (desc.geomStyle) { case HdMeshGeomStyleHull: // Creating the smoothHull hull render items requires geom subsets from the topology, // and we can't access that here. #ifdef HAS_DEFAULT_MATERIAL_SUPPORT_API if (reprToken == HdVP2ReprTokens->defaultMaterial) { // But default material mode does not use geom subsets, so we create the render item MHWRender::MRenderItem* defaultMaterialItem = _CreateSmoothHullRenderItem( renderItemName, *drawItem.get(), *subSceneContainer, nullptr) ._renderItem; defaultMaterialItem->setDefaultMaterialHandling( MRenderItem::DrawOnlyWhenDefaultMaterialActive); defaultMaterialItem->setShader(_delegate->Get3dDefaultMaterialShader()); #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT if (!GetInstancerId().IsEmpty()) { defaultMaterialItem = _CreateShadedSelectedInstancesItem( renderItemName, *drawItem.get(), *subSceneContainer, nullptr); defaultMaterialItem->setDefaultMaterialHandling( MRenderItem::DrawOnlyWhenDefaultMaterialActive); defaultMaterialItem->setShader(_delegate->Get3dDefaultMaterialShader()); } #endif } #endif break; case HdMeshGeomStyleHullEdgeOnly: // The smoothHull repr uses the wireframe item for selection highlight only. #ifdef HAS_DEFAULT_MATERIAL_SUPPORT_API if (reprToken == HdReprTokens->smoothHull || reprToken == HdVP2ReprTokens->defaultMaterial) { // Share selection highlight render item between smoothHull and defaultMaterial: bool foundShared = false; _ReprVector::const_iterator it = std::find_if( _reprs.begin(), _reprs.end(), _ReprComparator( reprToken == HdReprTokens->smoothHull ? HdVP2ReprTokens->defaultMaterial : HdReprTokens->smoothHull)); if (it != _reprs.end()) { const HdReprSharedPtr& repr = it->second; const auto& items = repr->GetDrawItems(); #if HD_API_VERSION < 35 for (HdDrawItem* item : items) { HdVP2DrawItem* shDrawItem = static_cast<HdVP2DrawItem*>(item); #else for (const HdRepr::DrawItemUniquePtr& item : items) { HdVP2DrawItem* const shDrawItem = static_cast<HdVP2DrawItem*>(item.get()); #endif if (shDrawItem && shDrawItem->MatchesUsage(HdVP2DrawItem::kSelectionHighlight)) { drawItem->SetRenderItem(shDrawItem->GetRenderItem()); foundShared = true; break; } } } if (!foundShared) { renderItem = _CreateSelectionHighlightRenderItem(renderItemName); } drawItem->SetUsage(HdVP2DrawItem::kSelectionHighlight); } #else // The smoothHull repr uses the wireframe item for selection highlight only. if (reprToken == HdReprTokens->smoothHull) { renderItem = _CreateSelectionHighlightRenderItem(renderItemName); drawItem->SetUsage(HdVP2DrawItem::kSelectionHighlight); } #endif // The item is used for wireframe display and selection highlight. else if (reprToken == HdReprTokens->wire) { renderItem = _CreateWireframeRenderItem(renderItemName); drawItem->AddUsage(HdVP2DrawItem::kSelectionHighlight); } // The item is used for bbox display and selection highlight. else if (reprToken == HdVP2ReprTokens->bbox) { renderItem = _CreateBoundingBoxRenderItem(renderItemName); drawItem->AddUsage(HdVP2DrawItem::kSelectionHighlight); } break; #ifndef MAYA_NEW_POINT_SNAPPING_SUPPORT case HdMeshGeomStylePoints: renderItem = _CreatePointsRenderItem(renderItemName); break; #endif default: TF_WARN("Unsupported geomStyle"); break; } if (renderItem) { // Store the render item pointer to avoid expensive lookup in the // subscene container. drawItem->AddRenderItem(renderItem); _delegate->GetVP2ResourceRegistry().EnqueueCommit( [subSceneContainer, renderItem]() { subSceneContainer->add(renderItem); }); } if (desc.geomStyle == HdMeshGeomStyleHull) { if (desc.flatShadingEnabled) { if (!(_customDirtyBitsInUse & DirtyFlatNormals)) { _customDirtyBitsInUse |= DirtyFlatNormals; *dirtyBits |= DirtyFlatNormals; } } else { if (!(_customDirtyBitsInUse & DirtySmoothNormals)) { _customDirtyBitsInUse |= DirtySmoothNormals; *dirtyBits |= DirtySmoothNormals; } } } #if HD_API_VERSION < 35 repr->AddDrawItem(drawItem); #else repr->AddDrawItem(std::move(drawItem)); #endif } } void HdVP2Mesh::_CreateSmoothHullRenderItems( HdVP2DrawItem& drawItem, MSubSceneContainer& subSceneContainer) { // 2021-01-29: Changing topology is not tested TF_VERIFY(drawItem.GetRenderItems().size() == 0); drawItem.GetRenderItems().clear(); // Need to topology to check for geom subsets. const HdMeshTopology& topology = _meshSharedData->_topology; const HdGeomSubsets& geomSubsets = topology.GetGeomSubsets(); // If the geom subsets do not cover all the faces in the mesh we need // to add an additional render item for those faces. int numFacesWithoutRenderItem = topology.GetNumFaces(); // Initialize the face to subset item mapping with an invalid item. _meshSharedData->_faceIdToGeomSubsetId.clear(); _meshSharedData->_faceIdToGeomSubsetId.resize(topology.GetNumFaces(), SdfPath::EmptyPath()); // Create the geom subset render items, and fill in the face to subset item mapping for later // use. for (const auto& geomSubset : geomSubsets) { // Right now geom subsets only support face sets, but edge or vertex sets // are possible in the future. TF_VERIFY(geomSubset.type == HdGeomSubset::TypeFaceSet); if (geomSubset.type != HdGeomSubset::TypeFaceSet) continue; // There can be geom subsets on the object which are not material subsets. I've seen // familyName = "object" in usda files. If there is no materialId on the subset then // don't create a render item for it. if (SdfPath::EmptyPath() == geomSubset.materialId) continue; MString renderItemName = drawItem.GetDrawItemName(); renderItemName += std::string(1, VP2_RENDER_DELEGATE_SEPARATOR).c_str(); renderItemName += geomSubset.id.GetString().c_str(); _CreateSmoothHullRenderItem(renderItemName, drawItem, subSceneContainer, &geomSubset); #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT if (!GetInstancerId().IsEmpty()) { _CreateShadedSelectedInstancesItem( renderItemName, drawItem, subSceneContainer, &geomSubset); } #endif // now fill in _faceIdToGeomSubsetId at geomSubset.indices with the subset item pointer for (auto faceId : geomSubset.indices) { // we expect that material binding geom subsets will not overlap TF_VERIFY(SdfPath::EmptyPath() == _meshSharedData->_faceIdToGeomSubsetId[faceId]); _meshSharedData->_faceIdToGeomSubsetId[faceId] = geomSubset.id; } numFacesWithoutRenderItem -= geomSubset.indices.size(); } TF_VERIFY(numFacesWithoutRenderItem >= 0); if (numFacesWithoutRenderItem > 0) { // create an item for the remaining faces _CreateSmoothHullRenderItem( drawItem.GetDrawItemName(), drawItem, subSceneContainer, nullptr); #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT if (!GetInstancerId().IsEmpty()) { _CreateShadedSelectedInstancesItem( drawItem.GetDrawItemName(), drawItem, subSceneContainer, nullptr); } #endif if (numFacesWithoutRenderItem == topology.GetNumFaces()) { // If there are no geom subsets that are material bind geom subsets, then we don't need // the _faceIdToGeomSubsetId mapping, we'll just create one item and use the full // topology for it. _meshSharedData->_faceIdToGeomSubsetId.clear(); numFacesWithoutRenderItem = 0; } } TF_VERIFY(numFacesWithoutRenderItem == 0); } /*! \brief Hide all of the repr objects for this Rprim except the named repr. Repr objects are created to support specific reprName tokens, and contain a list of HdVP2DrawItems and corresponding RenderItems. */ void HdVP2Mesh::_MakeOtherReprRenderItemsInvisible( HdSceneDelegate* sceneDelegate, const TfToken& reprToken) { for (const std::pair<TfToken, HdReprSharedPtr>& pair : _reprs) { if (pair.first != reprToken) { // For each relevant draw item, update dirty buffer sources. _MeshReprConfig::DescArray reprDescs = _GetReprDesc(pair.first); int drawItemIndex = 0; for (size_t descIdx = 0; descIdx < reprDescs.size(); ++descIdx, drawItemIndex++) { const HdMeshReprDesc& desc = reprDescs[descIdx]; if (desc.geomStyle == HdMeshGeomStyleInvalid) { continue; } auto* drawItem = static_cast<HdVP2DrawItem*>(pair.second->GetDrawItem(drawItemIndex)); if (!drawItem) continue; for (auto& renderItemData : drawItem->GetRenderItems()) { _delegate->GetVP2ResourceRegistry().EnqueueCommit([&renderItemData]() { renderItemData._enabled = false; renderItemData._renderItem->enable(false); }); } } } } } /*! \brief Update the named repr object for this Rprim. Repr objects are created to support specific reprName tokens, and contain a list of HdVP2DrawItems and corresponding RenderItems. */ void HdVP2Mesh::_UpdateRepr(HdSceneDelegate* sceneDelegate, const TfToken& reprToken) { HdReprSharedPtr const& curRepr = _GetRepr(reprToken); if (!curRepr) { return; } auto* const param = static_cast<HdVP2RenderParam*>(_delegate->GetRenderParam()); MSubSceneContainer* subSceneContainer = param->GetContainer(); if (ARCH_UNLIKELY(!subSceneContainer)) return; _MeshReprConfig::DescArray reprDescs = _GetReprDesc(reprToken); // For each relevant draw item, update dirty buffer sources. int drawItemIndex = 0; for (size_t descIdx = 0; descIdx < reprDescs.size(); ++descIdx, drawItemIndex++) { const HdMeshReprDesc& desc = reprDescs[descIdx]; if (desc.geomStyle == HdMeshGeomStyleInvalid) { continue; } auto* drawItem = static_cast<HdVP2DrawItem*>(curRepr->GetDrawItem(drawItemIndex)); if (!drawItem) continue; if (desc.geomStyle == HdMeshGeomStyleHull) { // it is possible we haven't created MRenderItems for this HdDrawItem yet. // if there are no MRenderItems, create them. if (drawItem->GetRenderItems().size() == 0) { _CreateSmoothHullRenderItems(*drawItem, *subSceneContainer); } } for (auto& renderItemData : drawItem->GetRenderItems()) { _UpdateDrawItem(sceneDelegate, drawItem, renderItemData, desc, reprToken); } } } /*! \brief Update the draw item This call happens on worker threads and results of the change are collected in CommitState and enqueued for Commit on main-thread using CommitTasks */ void HdVP2Mesh::_UpdateDrawItem( HdSceneDelegate* sceneDelegate, HdVP2DrawItem* drawItem, HdVP2DrawItem::RenderItemData& renderItemData, const HdMeshReprDesc& desc, const TfToken& reprToken) { HdDirtyBits itemDirtyBits = renderItemData.GetDirtyBits(); auto* const param = static_cast<HdVP2RenderParam*>(_delegate->GetRenderParam()); ProxyRenderDelegate& drawScene = param->GetDrawScene(); #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT // We don't need to update the shaded selected instance item when the selection mode is not // dirty. const bool isShadedSelectedInstanceItem = renderItemData._shadedSelectedInstances; const bool usingShadedSelectedInstanceItem = !GetInstancerId().IsEmpty() && drawScene.SnapToPoints(); const bool updateShadedSelectedInstanceItem = (itemDirtyBits & DirtySelectionMode) != 0; if (isShadedSelectedInstanceItem && !usingShadedSelectedInstanceItem && !updateShadedSelectedInstanceItem) { return; } #else const bool isShadedSelectedInstanceItem = false; const bool usingShadedSelectedInstanceItem = false; #endif // We don't need to update the dedicated selection highlight item when there // is no selection highlight change and the mesh is not selected. Draw item // has its own dirty bits, so update will be done when it shows in viewport. const bool isDedicatedSelectionHighlightItem = drawItem->MatchesUsage(HdVP2DrawItem::kSelectionHighlight); if (isDedicatedSelectionHighlightItem && ((itemDirtyBits & DirtySelectionHighlight) == 0) && (_selectionStatus == kUnselected)) { return; } MHWRender::MRenderItem* renderItem = renderItemData._renderItem; CommitState stateToCommit(renderItemData); HdVP2DrawItem::RenderItemData& drawItemData = stateToCommit._renderItemData; if (ARCH_UNLIKELY(!renderItem)) { return; } const SdfPath& id = GetId(); const HdRenderIndex& renderIndex = sceneDelegate->GetRenderIndex(); // The bounding box item uses a globally-shared geometry data therefore it // doesn't need to extract index data from topology. Points use non-indexed // draw. const bool isBBoxItem = (renderItem->drawMode() == MHWRender::MGeometry::kBoundingBox); #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT constexpr bool isPointSnappingItem = false; #else const bool isPointSnappingItem = (renderItem->primitive() == MHWRender::MGeometry::kPoints); #endif #ifdef HDVP2_ENABLE_GPU_OSD const bool isLineItem = (renderItem->primitive() == MHWRender::MGeometry::kLines); // when we do OSD we don't bother creating indexing until after we have a smooth mesh const bool requiresIndexUpdate = !isBBoxItem && !isPointSnappingItem && isLineItem; #else const bool requiresIndexUpdate = !isBBoxItem && !isPointSnappingItem; #endif // Prepare index buffer. if (requiresIndexUpdate && (itemDirtyBits & HdChangeTracker::DirtyTopology)) { const HdMeshTopology& topologyToUse = _meshSharedData->_renderingTopology; if (desc.geomStyle == HdMeshGeomStyleHull) { // _trianglesFaceVertexIndices has the full triangulation calculated in // _updateRepr. Find the triangles which represent faces in the matching // geom subset and add those triangles to the index buffer for renderItem. VtVec3iArray trianglesFaceVertexIndices; // for this item only! if (_meshSharedData->_faceIdToGeomSubsetId.size() == 0 || reprToken == HdVP2ReprTokens->defaultMaterial) { // If there is no mapping from face to render item or if this is the default // material item then all the faces are on this render item. VtArray has // copy-on-write semantics so this is fast trianglesFaceVertexIndices = _meshSharedData->_trianglesFaceVertexIndices; } else { for (size_t triangleId = 0; triangleId < _meshSharedData->_primitiveParam.size(); triangleId++) { size_t faceId = HdMeshUtil::DecodeFaceIndexFromCoarseFaceParam( _meshSharedData->_primitiveParam[triangleId]); if (_meshSharedData->_faceIdToGeomSubsetId[faceId] == renderItemData._geomSubset.id) { trianglesFaceVertexIndices.push_back( _meshSharedData->_trianglesFaceVertexIndices[triangleId]); } } } // It is possible that all elements in the opacity array are 1. // Due to the performance implications of transparency, we have to // traverse the array and enable transparency only when needed. renderItemData._transparent = false; HdInterpolation alphaInterp = HdInterpolationConstant; VtFloatArray alphaArray; _getOpacityData(_meshSharedData->_primvarInfo, alphaArray, alphaInterp); if (alphaArray.size() > 0) { if (alphaInterp == HdInterpolationConstant) { renderItemData._transparent = (alphaArray[0] < 0.999f); } else { for (const auto& triangle : trianglesFaceVertexIndices) { int x = _meshSharedData->_renderingToSceneFaceVtxIds[triangle[0]]; int y = _meshSharedData->_renderingToSceneFaceVtxIds[triangle[1]]; int z = _meshSharedData->_renderingToSceneFaceVtxIds[triangle[2]]; if (alphaArray[x] < 0.999f || alphaArray[y] < 0.999f || alphaArray[z] < 0.999f) { renderItemData._transparent = true; break; } } } } const int numIndex = trianglesFaceVertexIndices.size() * 3; stateToCommit._indexBufferData = numIndex > 0 ? static_cast<int*>(drawItemData._indexBuffer->acquire(numIndex, true)) : nullptr; if (stateToCommit._indexBufferData) { memcpy( stateToCommit._indexBufferData, trianglesFaceVertexIndices.data(), numIndex * sizeof(int)); } } else if (desc.geomStyle == HdMeshGeomStyleHullEdgeOnly) { unsigned int numIndex = _GetNumOfEdgeIndices(topologyToUse); stateToCommit._indexBufferData = numIndex ? static_cast<int*>(drawItemData._indexBuffer->acquire(numIndex, true)) : nullptr; _FillEdgeIndices(stateToCommit._indexBufferData, topologyToUse); } } #ifdef HDVP2_ENABLE_GPU_COMPUTE if (_gpuNormalsEnabled) { renderItem->addViewportComputeItem(_meshSharedData->_viewportCompute); } #endif if (desc.geomStyle == HdMeshGeomStyleHull && desc.shadingTerminal == HdMeshReprDescTokens->surfaceShader) { bool dirtyMaterialId = (itemDirtyBits & HdChangeTracker::DirtyMaterialId) != 0; if (dirtyMaterialId) { SdfPath materialId = GetMaterialId(); // This is an index path if (drawItemData._geomSubset.id != SdfPath::EmptyPath()) { SdfPath cachePathMaterialId = drawItemData._geomSubset.materialId; // This is annoying! The saved materialId is a cache path, but to look up the // material in the render index we need the index path. materialId = dynamic_cast<UsdImagingDelegate*>(sceneDelegate) ->ConvertCachePathToIndexPath(cachePathMaterialId); } const HdVP2Material* material = static_cast<const HdVP2Material*>( renderIndex.GetSprim(HdPrimTypeTokens->material, materialId)); if (material) { MHWRender::MShaderInstance* shader = material->GetSurfaceShader(); if (shader != nullptr && shader != drawItemData._shader) { drawItemData._shader = shader; drawItemData._shaderIsFallback = false; stateToCommit._shader = shader; stateToCommit._isTransparent = shader->isTransparent() || renderItemData._transparent; } } else { drawItemData._shaderIsFallback = true; } } bool useFallbackMaterial = drawItemData._shaderIsFallback && _PrimvarIsRequired(HdTokens->displayColor); bool updateFallbackMaterial = useFallbackMaterial && drawItemData._fallbackColorDirty; // Use fallback shader if there is no material binding or we failed to create a shader // instance for the material. if (updateFallbackMaterial) { MHWRender::MShaderInstance* shader = nullptr; HdInterpolation colorInterp = HdInterpolationConstant; HdInterpolation alphaInterp = HdInterpolationConstant; VtVec3fArray colorArray; VtFloatArray alphaArray; _getColorData(_meshSharedData->_primvarInfo, colorArray, colorInterp); _getOpacityData(_meshSharedData->_primvarInfo, alphaArray, alphaInterp); if ((colorInterp == HdInterpolationConstant || colorInterp == HdInterpolationInstance) && (alphaInterp == HdInterpolationConstant || alphaInterp == HdInterpolationInstance)) { const GfVec3f& clr3f = MayaUsd::utils::ConvertLinearToMaya(colorArray[0]); const MColor color(clr3f[0], clr3f[1], clr3f[2], alphaArray[0]); shader = _delegate->GetFallbackShader(color); // The color of the fallback shader is ignored when the interpolation is // instance } else { shader = _delegate->GetFallbackCPVShader(); } if (shader != nullptr && shader != drawItemData._shader) { drawItemData._shader = shader; stateToCommit._shader = shader; stateToCommit._isTransparent = renderItemData._transparent; drawItemData._fallbackColorDirty = false; } } } // Local bounds const GfRange3d& range = _sharedData.bounds.GetRange(); // Bounds are updated through MPxSubSceneOverride::setGeometryForRenderItem() // which is expensive, so it is updated only when it gets expanded in order // to reduce calling frequence. if (itemDirtyBits & HdChangeTracker::DirtyExtent) { const GfRange3d& rangeToUse = isBBoxItem ? _delegate->GetSharedBBoxGeom().GetRange() : range; // If the Rprim has empty bounds, we will assign a null bounding box to the render item and // Maya will compute the bounding box from the position data. if (!rangeToUse.IsEmpty()) { const GfVec3d& min = rangeToUse.GetMin(); const GfVec3d& max = rangeToUse.GetMax(); bool boundingBoxExpanded = false; const MPoint pntMin(min[0], min[1], min[2]); if (!drawItemData._boundingBox.contains(pntMin)) { drawItemData._boundingBox.expand(pntMin); boundingBoxExpanded = true; } const MPoint pntMax(max[0], max[1], max[2]); if (!drawItemData._boundingBox.contains(pntMax)) { drawItemData._boundingBox.expand(pntMax); boundingBoxExpanded = true; } if (boundingBoxExpanded) { stateToCommit._boundingBox = &drawItemData._boundingBox; } } } // Local-to-world transformation MMatrix& worldMatrix = drawItemData._worldMatrix; _sharedData.bounds.GetMatrix().Get(worldMatrix.matrix); // The bounding box draw item uses a globally-shared unit wire cube as the // geometry and transfers scale and offset of the bounds to world matrix. if (isBBoxItem) { if ((itemDirtyBits & (HdChangeTracker::DirtyExtent | HdChangeTracker::DirtyTransform)) && !range.IsEmpty()) { const GfVec3d midpoint = range.GetMidpoint(); const GfVec3d size = range.GetSize(); MPoint midp(midpoint[0], midpoint[1], midpoint[2]); midp *= worldMatrix; auto& m = worldMatrix.matrix; m[0][0] *= size[0]; m[0][1] *= size[0]; m[0][2] *= size[0]; m[0][3] *= size[0]; m[1][0] *= size[1]; m[1][1] *= size[1]; m[1][2] *= size[1]; m[1][3] *= size[1]; m[2][0] *= size[2]; m[2][1] *= size[2]; m[2][2] *= size[2]; m[2][3] *= size[2]; m[3][0] = midp[0]; m[3][1] = midp[1]; m[3][2] = midp[2]; m[3][3] = midp[3]; stateToCommit._worldMatrix = &drawItemData._worldMatrix; } } else if (itemDirtyBits & HdChangeTracker::DirtyTransform) { stateToCommit._worldMatrix = &drawItemData._worldMatrix; } // If the mesh is instanced, create one new instance per transform. // The current instancer invalidation tracking makes it hard for // us to tell whether transforms will be dirty, so this code // pulls them every time something changes. // If the mesh is instanced but has 0 instance transforms remember that // so the render item can be hidden. bool instancerWithNoInstances = false; if (!GetInstancerId().IsEmpty()) { // Retrieve instance transforms from the instancer. HdInstancer* instancer = renderIndex.GetInstancer(GetInstancerId()); VtMatrix4dArray transforms = static_cast<HdVP2Instancer*>(instancer)->ComputeInstanceTransforms(id); MMatrix instanceMatrix; const unsigned int instanceCount = transforms.size(); if (0 == instanceCount) { instancerWithNoInstances = true; } else { // The shaded instances are split into two render items: one for the // selected instance and one for the unselected instances. We do this so // that when point snapping we can snap selected instances to unselected // instances, without snapping to selected instances. // This code figures out which instances should be included in the current // render item, and which colors should be used to draw those instances. // Store info per instance const unsigned char dormant = 0; const unsigned char active = 1; const unsigned char lead = 2; const unsigned char invalid = 255; std::vector<unsigned char> instanceInfo; // depending on the type of render item we want to set different values // into instanceInfo; unsigned char modeDormant = invalid; unsigned char modeActive = invalid; unsigned char modeLead = invalid; if (!drawItem->ContainsUsage(HdVP2DrawItem::kSelectionHighlight)) { stateToCommit._instanceColorParam = kDiffuseColorStr; if (!usingShadedSelectedInstanceItem) { if (isShadedSelectedInstanceItem) { modeDormant = invalid; modeActive = invalid; modeLead = invalid; } else { modeDormant = active; modeActive = active; modeLead = active; } } else { if (isShadedSelectedInstanceItem) { modeDormant = invalid; modeActive = active; modeLead = active; } else { modeDormant = active; modeActive = invalid; modeLead = invalid; } } } else if (_selectionStatus == kFullyLead || _selectionStatus == kFullyActive) { modeDormant = _selectionStatus == kFullyLead ? lead : active; stateToCommit._instanceColorParam = kSolidColorStr; } else { modeDormant = isDedicatedSelectionHighlightItem ? invalid : dormant; modeActive = active; modeLead = lead; stateToCommit._instanceColorParam = kSolidColorStr; } // Assign with the dormant info by default. For non-selection // items the default value won't be draw, for wireframe items // this will correspond to drawing with the dormant wireframe color // or not drawing if the item is a selection highlight item. instanceInfo.resize(instanceCount, modeDormant); // Assign with the index to the active selection highlight color. if (const auto state = drawScene.GetActiveSelectionState(id)) { for (const auto& indexArray : state->instanceIndices) { for (const auto index : indexArray) { // This bounds check is necessary because of Pixar USD Issue 1516 // Logged as MAYA-113682 if (index >= 0 && index < (const int)instanceCount) { instanceInfo[index] = modeActive; } } } } // Assign with the index to the lead selection highlight color. if (const auto state = drawScene.GetLeadSelectionState(id)) { for (const auto& indexArray : state->instanceIndices) { for (const auto index : indexArray) { // This bounds check is necessary because of Pixar USD Issue 1516 // Logged as MAYA-113682 if (index >= 0 && index < (const int)instanceCount) { instanceInfo[index] = modeLead; } } } } // Now instanceInfo is set up correctly to tell us which instances are a part of this // render item. // Set up the source color buffers. const MColor wireframeColors[] = { drawScene.GetWireframeColor(), drawScene.GetSelectionHighlightColor(false), drawScene.GetSelectionHighlightColor(true) }; bool useWireframeColors = stateToCommit._instanceColorParam == kSolidColorStr; MFloatArray* shadedColors = nullptr; HdInterpolation colorInterpolation = HdInterpolationConstant; for (auto& entry : _meshSharedData->_primvarInfo) { const TfToken& primvarName = entry.first; if (primvarName == HdVP2Tokens->displayColorAndOpacity) { colorInterpolation = entry.second->_source.interpolation; if (colorInterpolation == HdInterpolationInstance) { shadedColors = &entry.second->_extraInstanceData; TF_VERIFY(shadedColors->length() == instanceCount * kNumColorChannels); } } } #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT // Create & fill the per-instance data buffers: the transform buffer, the color buffer // and the Maya instance id to usd instance id mapping buffer. auto& mayaToUsd = MayaUsdCustomData::Get(*renderItem); mayaToUsd.clear(); #endif for (unsigned int i = 0; i < instanceCount; i++) { unsigned char info = instanceInfo[i]; if (info == invalid) continue; stateToCommit._ufeIdentifiers.append( drawScene.GetScenePrimPath(GetId(), i).GetString().c_str()); transforms[i].Get(instanceMatrix.matrix); stateToCommit._instanceTransforms.append(worldMatrix * instanceMatrix); #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT mayaToUsd.push_back(i); #endif if (useWireframeColors) { const MColor& color = wireframeColors[info]; for (unsigned int j = 0; j < kNumColorChannels; j++) { stateToCommit._instanceColors.append(color[j]); } } else if (shadedColors) { unsigned int offset = i * kNumColorChannels; for (unsigned int j = 0; j < kNumColorChannels; j++) { stateToCommit._instanceColors.append((*shadedColors)[offset + j]); } } } if (stateToCommit._instanceTransforms.length() == 0) instancerWithNoInstances = true; } } else { // Non-instanced Rprims. if ((itemDirtyBits & DirtySelectionHighlight) && drawItem->ContainsUsage(HdVP2DrawItem::kSelectionHighlight)) { const MColor& color = (_selectionStatus != kUnselected ? drawScene.GetSelectionHighlightColor(_selectionStatus == kFullyLead) : drawScene.GetWireframeColor()); MHWRender::MShaderInstance* shader = _delegate->Get3dSolidShader(color); if (shader != nullptr && shader != drawItemData._shader) { drawItemData._shader = shader; stateToCommit._shader = shader; stateToCommit._isTransparent = false; } } } // Determine if the render item should be enabled or not. if (!GetInstancerId().IsEmpty() || (itemDirtyBits & (HdChangeTracker::DirtyVisibility | HdChangeTracker::DirtyRenderTag | HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyExtent | DirtySelectionHighlight))) { bool enable = drawItem->GetVisible() && !_points(_meshSharedData->_primvarInfo).empty() && !instancerWithNoInstances; if (isDedicatedSelectionHighlightItem) { enable = enable && (_selectionStatus != kUnselected); } else if (isPointSnappingItem) { enable = enable && (_selectionStatus == kUnselected); } else if (isBBoxItem) { enable = enable && !range.IsEmpty(); } enable = enable && drawScene.DrawRenderTag(_meshSharedData->_renderTag); if (drawItemData._enabled != enable) { drawItemData._enabled = enable; stateToCommit._enabled = &drawItemData._enabled; } } stateToCommit._geometryDirty = (itemDirtyBits & (HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyNormals | HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyTopology)); #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT if (!isBBoxItem && !isDedicatedSelectionHighlightItem && (itemDirtyBits & (DirtySelectionHighlight | DirtySelectionMode))) { MSelectionMask selectionMask(MSelectionMask::kSelectMeshes); bool shadedUnselectedInstances = !isShadedSelectedInstanceItem && !isDedicatedSelectionHighlightItem && !GetInstancerId().IsEmpty(); if (_selectionStatus == kUnselected || drawScene.SnapToSelectedObjects() || shadedUnselectedInstances) { selectionMask.addMask(MSelectionMask::kSelectPointsForGravity); } // Only unselected Rprims can be used for point snapping. if (_selectionStatus == kUnselected && !shadedUnselectedInstances) { selectionMask.addMask(MSelectionMask::kSelectPointsForGravity); } // The function is thread-safe, thus called in place to keep simple. renderItem->setSelectionMask(selectionMask); } #endif // Capture buffers we need MHWRender::MIndexBuffer* indexBuffer = drawItemData._indexBuffer.get(); PrimvarInfoMap* primvarInfo = &_meshSharedData->_primvarInfo; TfTokenVector* primvars = &_meshSharedData->_allRequiredPrimvars; const HdVP2BBoxGeom& sharedBBoxGeom = _delegate->GetSharedBBoxGeom(); if (isBBoxItem) { indexBuffer = const_cast<MHWRender::MIndexBuffer*>(sharedBBoxGeom.GetIndexBuffer()); } _delegate->GetVP2ResourceRegistry().EnqueueCommit([stateToCommit, param, primvarInfo, primvars, indexBuffer, isBBoxItem, &sharedBBoxGeom]() { const HdVP2DrawItem::RenderItemData& drawItemData = stateToCommit._renderItemData; MHWRender::MRenderItem* renderItem = drawItemData._renderItem; if (ARCH_UNLIKELY(!renderItem)) return; MStatus result; MProfilingScope profilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L2, renderItem->name().asChar(), "Commit"); // If available, something changed if (stateToCommit._indexBufferData) indexBuffer->commit(stateToCommit._indexBufferData); // If available, something changed if (stateToCommit._shader != nullptr) { bool success = renderItem->setShader(stateToCommit._shader); TF_VERIFY(success); renderItem->setTreatAsTransparent(stateToCommit._isTransparent); } // If the enable state is changed, then update it. if (stateToCommit._enabled != nullptr) { renderItem->enable(*stateToCommit._enabled); } ProxyRenderDelegate& drawScene = param->GetDrawScene(); // TODO: this is now including all buffers for the requirements of all // the render items on this rprim. We could filter it down based on the // requirements of the shader. if (stateToCommit._geometryDirty || stateToCommit._boundingBox) { MHWRender::MVertexBufferArray vertexBuffers; std::set<TfToken> addedPrimvars; auto addPrimvar = [primvarInfo, &vertexBuffers, &addedPrimvars, isBBoxItem, &sharedBBoxGeom]( const TfToken& p) { auto entry = primvarInfo->find(p); if (entry == primvarInfo->cend()) { // No primvar by that name. return; } MHWRender::MVertexBuffer* primvarBuffer = nullptr; if (isBBoxItem && p == HdTokens->points) { primvarBuffer = const_cast<MHWRender::MVertexBuffer*>( sharedBBoxGeom.GetPositionBuffer()); } else { primvarBuffer = entry->second->_buffer.get(); } if (primvarBuffer) { // this filters out the separate color & alpha entries MStatus result = vertexBuffers.addBuffer(p.GetText(), primvarBuffer); TF_VERIFY(result == MStatus::kSuccess); } addedPrimvars.insert(p); }; // Points and normals always are at the beginning of vertex requirements: addPrimvar(HdTokens->points); addPrimvar(HdTokens->normals); // Then add required primvars *in order*: if (primvars) { for (const TfToken& primvarName : *primvars) { if (addedPrimvars.find(primvarName) == addedPrimvars.cend()) { addPrimvar(primvarName); } } } // Then add whatever primvar is left that was not in the requirements: for (auto& entry : *primvarInfo) { if (addedPrimvars.find(entry.first) == addedPrimvars.cend()) { addPrimvar(entry.first); } } // The API call does three things: // - Associate geometric buffers with the render item. // - Update bounding box. // - Trigger consolidation/instancing update. result = drawScene.setGeometryForRenderItem( *renderItem, vertexBuffers, *indexBuffer, stateToCommit._boundingBox); TF_VERIFY(result == MStatus::kSuccess); } // Important, update instance transforms after setting geometry on render items! auto& oldInstanceCount = stateToCommit._renderItemData._instanceCount; auto newInstanceCount = stateToCommit._instanceTransforms.length(); // GPU instancing has been enabled. We cannot switch to consolidation // without recreating render item, so we keep using GPU instancing. if (stateToCommit._renderItemData._usingInstancedDraw) { if (oldInstanceCount == newInstanceCount) { for (unsigned int i = 0; i < newInstanceCount; i++) { // VP2 defines instance ID of the first instance to be 1. result = drawScene.updateInstanceTransform( *renderItem, i + 1, stateToCommit._instanceTransforms[i]); TF_VERIFY(result == MStatus::kSuccess); } } else { result = drawScene.setInstanceTransformArray( *renderItem, stateToCommit._instanceTransforms); TF_VERIFY(result == MStatus::kSuccess); } if (newInstanceCount > 0 && stateToCommit._instanceColors.length() == newInstanceCount * kNumColorChannels) { result = drawScene.setExtraInstanceData( *renderItem, stateToCommit._instanceColorParam, stateToCommit._instanceColors); TF_VERIFY(result == MStatus::kSuccess); } } #if MAYA_API_VERSION >= 20210000 else if (newInstanceCount >= 1) { #else // In Maya 2020 and before, GPU instancing and consolidation are two separate systems // that cannot be used by a render item at the same time. In case of single instance, we // keep the original render item to allow consolidation with other prims. In case of // multiple instances, we need to disable consolidation to allow GPU instancing to be // used. else if (newInstanceCount == 1) { bool success = renderItem->setMatrix(&stateToCommit._instanceTransforms[0]); TF_VERIFY(success); } else if (newInstanceCount > 1) { setWantConsolidation(*renderItem, false); #endif result = drawScene.setInstanceTransformArray( *renderItem, stateToCommit._instanceTransforms); TF_VERIFY(result == MStatus::kSuccess); if (stateToCommit._instanceColors.length() == newInstanceCount * kNumColorChannels) { result = drawScene.setExtraInstanceData( *renderItem, stateToCommit._instanceColorParam, stateToCommit._instanceColors); TF_VERIFY(result == MStatus::kSuccess); } stateToCommit._renderItemData._usingInstancedDraw = true; } else if (stateToCommit._worldMatrix != nullptr) { // Regular non-instanced prims. Consolidation has been turned on by // default and will be kept enabled on this case. bool success = renderItem->setMatrix(stateToCommit._worldMatrix); TF_VERIFY(success); } oldInstanceCount = newInstanceCount; #ifdef MAYA_MRENDERITEM_UFE_IDENTIFIER_SUPPORT if (stateToCommit._ufeIdentifiers.length() > 0) { drawScene.setUfeIdentifiers(*renderItem, stateToCommit._ufeIdentifiers); } #endif }); // Reset dirty bits because we've prepared commit state for this render item. renderItemData.ResetDirtyBits(); } void HdVP2Mesh::_HideAllDrawItems(const TfToken& reprToken) { HdReprSharedPtr const& curRepr = _GetRepr(reprToken); if (!curRepr) { return; } _MeshReprConfig::DescArray reprDescs = _GetReprDesc(reprToken); // For each relevant draw item, update dirty buffer sources. int drawItemIndex = 0; for (size_t descIdx = 0; descIdx < reprDescs.size(); ++descIdx) { const HdMeshReprDesc& desc = reprDescs[descIdx]; if (desc.geomStyle == HdMeshGeomStyleInvalid) { continue; } auto* drawItem = static_cast<HdVP2DrawItem*>(curRepr->GetDrawItem(drawItemIndex++)); if (!drawItem) continue; for (auto& renderItemData : drawItem->GetRenderItems()) { renderItemData._enabled = false; _delegate->GetVP2ResourceRegistry().EnqueueCommit( [&]() { renderItemData._renderItem->enable(false); }); } } } #ifdef HDVP2_ENABLE_GPU_COMPUTE /*! \brief Save topology information for later GPGPU evaluation This function pulls topology and UV data from the scene delegate and save that information to be used as an input to the normal calculation later. */ void HdVP2Mesh::_CreateViewportCompute() { if (!_meshSharedData->_viewportCompute) { _meshSharedData->_viewportCompute = MSharedPtr<MeshViewportCompute>::make<>(_meshSharedData); } } #endif #ifdef HDVP2_ENABLE_GPU_OSD void HdVP2Mesh::_CreateOSDTables() { #if defined(DO_CPU_OSD) || defined(DO_OPENGL_OSD) assert(_meshSharedData->_viewportCompute); MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L2, "createOSDTables"); // create topology refiner PxOsdTopologyRefinerSharedPtr refiner; OpenSubdiv::Far::StencilTable const* vertexStencils = nullptr; OpenSubdiv::Far::StencilTable const* varyingStencils = nullptr; OpenSubdiv::Far::PatchTable const* patchTable = nullptr; HdMeshTopology* topology = &_meshSharedData->_renderingTopology; // TODO: something with _topology? // for empty topology, we don't need to refine anything. // but still need to return the typed buffer for codegen if (topology->GetFaceVertexCounts().size() == 0) { // leave refiner empty } else { refiner = PxOsdRefinerFactory::Create( topology->GetPxOsdMeshTopology(), TfToken(_meshSharedData->_renderTag.GetText())); } if (refiner) { OpenSubdiv::Far::PatchTableFactory::Options patchOptions( _meshSharedData->_viewportCompute->level); if (_meshSharedData->_viewportCompute->adaptive) { patchOptions.endCapType = OpenSubdiv::Far::PatchTableFactory::Options::ENDCAP_BSPLINE_BASIS; #if OPENSUBDIV_VERSION_NUMBER >= 30400 // Improve fidelity when refining to limit surface patches // These options supported since v3.1.0 and v3.2.0 respectively. patchOptions.useInfSharpPatch = true; patchOptions.generateLegacySharpCornerPatches = false; #endif } // split trace scopes. { MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L2, "refine"); if (_meshSharedData->_viewportCompute->adaptive) { OpenSubdiv::Far::TopologyRefiner::AdaptiveOptions adaptiveOptions( _meshSharedData->_viewportCompute->level); #if OPENSUBDIV_VERSION_NUMBER >= 30400 adaptiveOptions = patchOptions.GetRefineAdaptiveOptions(); #endif refiner->RefineAdaptive(adaptiveOptions); } else { refiner->RefineUniform(_meshSharedData->_viewportCompute->level); } } #define GENERATE_SOURCE_TABLES #ifdef GENERATE_SOURCE_TABLES { MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L2, "stencilFactory"); OpenSubdiv::Far::StencilTableFactory::Options options; options.generateOffsets = true; options.generateIntermediateLevels = _meshSharedData->_viewportCompute->adaptive; options.interpolationMode = OpenSubdiv::Far::StencilTableFactory::INTERPOLATE_VERTEX; vertexStencils = OpenSubdiv::Far::StencilTableFactory::Create(*refiner, options); options.interpolationMode = OpenSubdiv::Far::StencilTableFactory::INTERPOLATE_VARYING; varyingStencils = OpenSubdiv::Far::StencilTableFactory::Create(*refiner, options); } { MProfilingScope subProfilingScope( HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L2, "patchFactory"); patchTable = OpenSubdiv::Far::PatchTableFactory::Create(*refiner, patchOptions); } #else // grab the values we need from the refiner. const OpenSubdiv::Far::TopologyLevel& refinedLevel = refiner->GetLevel(refiner->GetMaxLevel()); size_t indexLength = refinedLevel.GetNumFaces() * 4; // i know it is quads but not always? can we do this more safely? size_t vertexLength = GetNumVerticesTotal(); // save these values and use them to create the updated geometry index mapping. #endif } #ifdef GENERATE_SOURCE_TABLES // merge endcap if (patchTable && patchTable->GetLocalPointStencilTable()) { // append stencils if (OpenSubdiv::Far::StencilTable const* vertexStencilsWithLocalPoints = OpenSubdiv::Far::StencilTableFactory::AppendLocalPointStencilTable( *refiner, vertexStencils, patchTable->GetLocalPointStencilTable())) { delete vertexStencils; vertexStencils = vertexStencilsWithLocalPoints; } if (OpenSubdiv::Far::StencilTable const* varyingStencilsWithLocalPoints = OpenSubdiv::Far::StencilTableFactory::AppendLocalPointStencilTable( *refiner, varyingStencils, patchTable->GetLocalPointStencilTable())) { delete varyingStencils; varyingStencils = varyingStencilsWithLocalPoints; } } // save values for the next loop _meshSharedData->_viewportCompute->vertexStencils.reset(vertexStencils); _meshSharedData->_viewportCompute->varyingStencils.reset(varyingStencils); _meshSharedData->_viewportCompute->patchTable.reset(patchTable); #endif // if there is a sourceMeshSharedData it should have entries for every vertex in that geometry // source. #endif } #endif /*! \brief Update the _primvarInfo's _source information for all required primvars. This function pulls data from the scene delegate & caches it, but defers processing. While iterating primvars, we skip "points" (vertex positions) because the points primvar is processed separately for direct access later. We only call GetPrimvar on primvars that have been marked dirty. */ void HdVP2Mesh::_UpdatePrimvarSources( HdSceneDelegate* sceneDelegate, HdDirtyBits dirtyBits, const TfTokenVector& requiredPrimvars) { const SdfPath& id = GetId(); auto updatePrimvarInfo = [&](const TfToken& name, const VtValue& value, const HdInterpolation interpolation) { PrimvarInfo* info = _getInfo(_meshSharedData->_primvarInfo, name); if (info) { info->_source.data = value; info->_source.interpolation = interpolation; info->_source.dataSource = PrimvarSource::Primvar; } else { _meshSharedData->_primvarInfo[name] = std::make_unique<PrimvarInfo>( PrimvarSource(value, interpolation, PrimvarSource::Primvar), nullptr); } }; TfTokenVector::const_iterator begin = requiredPrimvars.cbegin(); TfTokenVector::const_iterator end = requiredPrimvars.cend(); // inspired by HdStInstancer::_SyncPrimvars // Get any required instanced primvars from the instancer. Get these before we get // any rprims from the rprim itself. If both are present, the rprim's values override // the instancer's value. const SdfPath& instancerId = GetInstancerId(); if (!instancerId.IsEmpty()) { HdPrimvarDescriptorVector instancerPrimvars = sceneDelegate->GetPrimvarDescriptors(instancerId, HdInterpolationInstance); bool instancerDirty = ((dirtyBits & (HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyInstancer | HdChangeTracker::DirtyInstanceIndex)) != 0); for (const HdPrimvarDescriptor& pv : instancerPrimvars) { if (std::find(begin, end, pv.name) == end) { // erase the unused primvar so we don't hold onto stale data _meshSharedData->_primvarInfo.erase(pv.name); } else { if (HdChangeTracker::IsPrimvarDirty(dirtyBits, instancerId, pv.name) || instancerDirty) { const VtValue value = sceneDelegate->Get(instancerId, pv.name); updatePrimvarInfo(pv.name, value, HdInterpolationInstance); } } } } for (size_t i = 0; i < HdInterpolationCount; i++) { const HdInterpolation interp = static_cast<HdInterpolation>(i); const HdPrimvarDescriptorVector primvars = GetPrimvarDescriptors(sceneDelegate, interp); for (const HdPrimvarDescriptor& pv : primvars) { if (std::find(begin, end, pv.name) == end) { // erase the unused primvar so we don't hold onto stale data _meshSharedData->_primvarInfo.erase(pv.name); } else { if (HdChangeTracker::IsPrimvarDirty(dirtyBits, id, pv.name)) { const VtValue value = GetPrimvar(sceneDelegate, pv.name); updatePrimvarInfo(pv.name, value, interp); // if the primvar color changes then we might need to use a different fallback // material if (interp == HdInterpolationConstant && pv.name == HdTokens->displayColor) { // find all the smooth hull render items and mark their _fallbackColorDirty // true for (const std::pair<TfToken, HdReprSharedPtr>& pair : _reprs) { _MeshReprConfig::DescArray reprDescs = _GetReprDesc(pair.first); // Iterate through all reprdescs for the current repr to figure out if // any of them requires the fallback material for (size_t descIdx = 0; descIdx < reprDescs.size(); ++descIdx) { const HdMeshReprDesc& desc = reprDescs[descIdx]; if (desc.geomStyle == HdMeshGeomStyleHull) { const HdReprSharedPtr& repr = pair.second; const auto& items = repr->GetDrawItems(); #if HD_API_VERSION < 35 for (HdDrawItem* item : items) { if (HdVP2DrawItem* drawItem = static_cast<HdVP2DrawItem*>(item)) { #else for (const HdRepr::DrawItemUniquePtr& item : items) { if (HdVP2DrawItem* const drawItem = static_cast<HdVP2DrawItem*>(item.get())) { #endif for (auto& renderItemData : drawItem->GetRenderItems()) { renderItemData._fallbackColorDirty = true; } } } } } } } } } } } } #ifndef MAYA_NEW_POINT_SNAPPING_SUPPORT /*! \brief Create render item for points repr. */ MHWRender::MRenderItem* HdVP2Mesh::_CreatePointsRenderItem(const MString& name) const { MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( name, MHWRender::MRenderItem::DecorationItem, MHWRender::MGeometry::kPoints); renderItem->setDrawMode(MHWRender::MGeometry::kSelectionOnly); renderItem->depthPriority(MHWRender::MRenderItem::sDormantPointDepthPriority); renderItem->castsShadows(false); renderItem->receivesShadows(false); renderItem->setShader(_delegate->Get3dFatPointShader()); MSelectionMask selectionMask(MSelectionMask::kSelectPointsForGravity); selectionMask.addMask(MSelectionMask::kSelectMeshVerts); renderItem->setSelectionMask(selectionMask); #ifdef MAYA_MRENDERITEM_UFE_IDENTIFIER_SUPPORT auto* const param = static_cast<HdVP2RenderParam*>(_delegate->GetRenderParam()); ProxyRenderDelegate& drawScene = param->GetDrawScene(); drawScene.setUfeIdentifiers(*renderItem, _PrimSegmentString); #endif #if MAYA_API_VERSION >= 20220000 renderItem->setObjectTypeExclusionFlag(MHWRender::MFrameContext::kExcludeMeshes); #endif setWantConsolidation(*renderItem, true); return renderItem; } #endif /*! \brief Create render item for wireframe repr. */ MHWRender::MRenderItem* HdVP2Mesh::_CreateWireframeRenderItem(const MString& name) const { MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( name, MHWRender::MRenderItem::DecorationItem, MHWRender::MGeometry::kLines); renderItem->setDrawMode(MHWRender::MGeometry::kWireframe); renderItem->depthPriority(MHWRender::MRenderItem::sDormantWireDepthPriority); renderItem->castsShadows(false); renderItem->receivesShadows(false); renderItem->setShader(_delegate->Get3dSolidShader(kOpaqueBlue)); #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT MSelectionMask selectionMask(MSelectionMask::kSelectMeshes); selectionMask.addMask(MSelectionMask::kSelectPointsForGravity); renderItem->setSelectionMask(selectionMask); #else renderItem->setSelectionMask(MSelectionMask::kSelectMeshes); #endif #ifdef MAYA_MRENDERITEM_UFE_IDENTIFIER_SUPPORT auto* const param = static_cast<HdVP2RenderParam*>(_delegate->GetRenderParam()); ProxyRenderDelegate& drawScene = param->GetDrawScene(); drawScene.setUfeIdentifiers(*renderItem, _PrimSegmentString); #endif #if MAYA_API_VERSION >= 20220000 renderItem->setObjectTypeExclusionFlag(MHWRender::MFrameContext::kExcludeMeshes); #endif setWantConsolidation(*renderItem, true); return renderItem; } /*! \brief Create render item for bbox repr. */ MHWRender::MRenderItem* HdVP2Mesh::_CreateBoundingBoxRenderItem(const MString& name) const { MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( name, MHWRender::MRenderItem::DecorationItem, MHWRender::MGeometry::kLines); renderItem->setDrawMode(MHWRender::MGeometry::kBoundingBox); renderItem->castsShadows(false); renderItem->receivesShadows(false); renderItem->setShader(_delegate->Get3dSolidShader(kOpaqueBlue)); renderItem->setSelectionMask(MSelectionMask::kSelectMeshes); #ifdef MAYA_MRENDERITEM_UFE_IDENTIFIER_SUPPORT auto* const param = static_cast<HdVP2RenderParam*>(_delegate->GetRenderParam()); ProxyRenderDelegate& drawScene = param->GetDrawScene(); drawScene.setUfeIdentifiers(*renderItem, _PrimSegmentString); #endif #if MAYA_API_VERSION >= 20220000 renderItem->setObjectTypeExclusionFlag(MHWRender::MFrameContext::kExcludeMeshes); #endif setWantConsolidation(*renderItem, true); return renderItem; } #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT MHWRender::MRenderItem* HdVP2Mesh::_CreateShadedSelectedInstancesItem( const MString& name, HdVP2DrawItem& drawItem, MSubSceneContainer& subSceneContainer, const HdGeomSubset* geomSubset) const { MString ssiName = name; ssiName += std::string(1, VP2_RENDER_DELEGATE_SEPARATOR).c_str(); ssiName += "shadedSelectedInstances"; HdVP2DrawItem::RenderItemData& renderItemData = _CreateSmoothHullRenderItem(ssiName, drawItem, subSceneContainer, geomSubset); renderItemData._shadedSelectedInstances = true; return renderItemData._renderItem; } #endif /*! \brief Create render item for smoothHull repr. */ HdVP2DrawItem::RenderItemData& HdVP2Mesh::_CreateSmoothHullRenderItem( const MString& name, HdVP2DrawItem& drawItem, MSubSceneContainer& subSceneContainer, const HdGeomSubset* geomSubset) const { MString itemName = name; if (geomSubset) { itemName += std::string(1, VP2_RENDER_DELEGATE_SEPARATOR).c_str(); itemName += geomSubset->id.GetString().c_str(); } MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( itemName, MHWRender::MRenderItem::MaterialSceneItem, MHWRender::MGeometry::kTriangles); constexpr MHWRender::MGeometry::DrawMode drawMode = static_cast<MHWRender::MGeometry::DrawMode>( MHWRender::MGeometry::kShaded | MHWRender::MGeometry::kTextured); renderItem->setDrawMode(drawMode); renderItem->setExcludedFromPostEffects(false); renderItem->castsShadows(true); renderItem->receivesShadows(true); renderItem->setShader(_delegate->GetFallbackShader(kOpaqueGray)); #ifdef MAYA_MRENDERITEM_UFE_IDENTIFIER_SUPPORT auto* const param = static_cast<HdVP2RenderParam*>(_delegate->GetRenderParam()); ProxyRenderDelegate& drawScene = param->GetDrawScene(); drawScene.setUfeIdentifiers(*renderItem, _PrimSegmentString); #endif #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT MSelectionMask selectionMask(MSelectionMask::kSelectMeshes); selectionMask.addMask(MSelectionMask::kSelectPointsForGravity); renderItem->setSelectionMask(selectionMask); #else renderItem->setSelectionMask(MSelectionMask::kSelectMeshes); #endif #if MAYA_API_VERSION >= 20220000 renderItem->setObjectTypeExclusionFlag(MHWRender::MFrameContext::kExcludeMeshes); #endif #ifdef HAS_DEFAULT_MATERIAL_SUPPORT_API renderItem->setDefaultMaterialHandling(MRenderItem::SkipWhenDefaultMaterialActive); #endif setWantConsolidation(*renderItem, true); _delegate->GetVP2ResourceRegistry().EnqueueCommit( [&subSceneContainer, renderItem]() { subSceneContainer.add(renderItem); }); return drawItem.AddRenderItem(renderItem, geomSubset); } /*! \brief Create render item to support selection highlight for smoothHull repr. */ MHWRender::MRenderItem* HdVP2Mesh::_CreateSelectionHighlightRenderItem(const MString& name) const { MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( name, MHWRender::MRenderItem::DecorationItem, MHWRender::MGeometry::kLines); constexpr MHWRender::MGeometry::DrawMode drawMode = static_cast<MHWRender::MGeometry::DrawMode>( MHWRender::MGeometry::kShaded | MHWRender::MGeometry::kTextured); renderItem->setDrawMode(drawMode); renderItem->depthPriority(MHWRender::MRenderItem::sActiveWireDepthPriority); renderItem->castsShadows(false); renderItem->receivesShadows(false); renderItem->setShader(_delegate->Get3dSolidShader(kOpaqueBlue)); renderItem->setSelectionMask(MSelectionMask()); #ifdef MAYA_MRENDERITEM_UFE_IDENTIFIER_SUPPORT auto* const param = static_cast<HdVP2RenderParam*>(_delegate->GetRenderParam()); ProxyRenderDelegate& drawScene = param->GetDrawScene(); drawScene.setUfeIdentifiers(*renderItem, _PrimSegmentString); #endif #if MAYA_API_VERSION >= 20220000 renderItem->setObjectTypeExclusionFlag(MHWRender::MFrameContext::kExcludeMeshes); #endif setWantConsolidation(*renderItem, true); return renderItem; } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/test/testUtils/CMakeLists.txt set(TARGET_NAME PYTHON_TEST_UTILS) add_custom_target(${TARGET_NAME} ALL) # Copy all of the resources and Python scripts in this directory to a # "test/python" subdirectory under the top-level build directory. This path # will be added to PYTHONPATH for tests so that these utilities are available # to all tests. mayaUsd_copyDirectory(${TARGET_NAME} SOURCE ${CMAKE_CURRENT_SOURCE_DIR} DESTINATION ${CMAKE_BINARY_DIR}/test/python EXCLUDE "*.txt" ) <file_sep>/lib/usd/translators/mayaReferenceUpdater.cpp // // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "mayaReferenceUpdater.h" #include <mayaUsd/fileio/primUpdaterRegistry.h> #include <mayaUsd/fileio/translators/translatorMayaReference.h> #include <mayaUsd/fileio/utils/adaptor.h> #include <mayaUsd/utils/util.h> #include <mayaUsd_Schemas/ALMayaReference.h> #include <mayaUsd_Schemas/MayaReference.h> #include <pxr/base/gf/vec2f.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usd/timeCode.h> #include <pxr/usd/usdGeom/tokens.h> #include <pxr/usd/usdUtils/pipeline.h> PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_REGISTER_UPDATER( MayaUsd_SchemasMayaReference, PxrUsdTranslators_MayaReferenceUpdater, (UsdMayaPrimUpdater::Supports::Push | UsdMayaPrimUpdater::Supports::Clear)); PXRUSDMAYA_REGISTER_UPDATER( MayaUsd_SchemasALMayaReference, PxrUsdTranslators_MayaReferenceUpdater, (UsdMayaPrimUpdater::Supports::Push | UsdMayaPrimUpdater::Supports::Clear)); PxrUsdTranslators_MayaReferenceUpdater::PxrUsdTranslators_MayaReferenceUpdater( const MFnDependencyNode& depNodeFn, const SdfPath& usdPath) : UsdMayaPrimUpdater(depNodeFn, usdPath) { } /* virtual */ bool PxrUsdTranslators_MayaReferenceUpdater::Pull(UsdMayaPrimUpdaterContext* context) { const UsdPrim& usdPrim = GetUsdPrim<MayaUsd_SchemasMayaReference>(*context); const MObject& parentNode = GetMayaObject(); UsdMayaTranslatorMayaReference::update(usdPrim, parentNode); return true; } /* virtual */ void PxrUsdTranslators_MayaReferenceUpdater::Clear(UsdMayaPrimUpdaterContext* context) { const MObject& parentNode = GetMayaObject(); UsdMayaTranslatorMayaReference::UnloadMayaReference(parentNode); } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/doc/MaterialX.md # MaterialX Support for MaterialX in MayaUSD ## Support level Support for MaterialX in Maya USD is based on USD support provided by the usdMtlx and hdMtlx modules. This means we use a UsdShade translation of the MaterialX graph as transport mechanism. ## Export We currently support exporting to MaterialX-compatible UsdShade networks: - Standard surface shader nodes - USD Preview Surface shader nodes - File texture nodes - Connections to color components and alpha/luminance - Normal maps - Custom color spaces ### Not supported: - Lambert, Blinn, and Phong shader nodes - MaterialXSurface shader nodes from MaterialX Maya contrib ### To enable: - Rebuild the MayaUsd plugin for Maya 2022.1 or PR126 using tip of the dev branch or any commit that includes [PR 1478](https://github.com/Autodesk/maya-usd/pull/1478) - Look for a new "MaterialX shading" option in the `Materials` dropdown of the export options ## Import We can import MaterialX networks. - UsdShade networks consisting of MaterialX nodes used for shading in the `mtlx` render context - `.mtlx` files referenced in a USD stage as converted by the `usdMtlx` plugin in USD ### Not supported: - MaterialX networks containing surface shaders other than standard surface or preview surface - MaterialX networks containing unexpected procedural nodes - Importing to MaterialXSurface shader nodes ### To enable: - Rebuild the MayaUsd plugin for Maya 2022.1 or PR126 using tip of the dev branch or any commit that includes [PR 1478](https://github.com/Autodesk/maya-usd/pull/1478) - The import code will discover MaterialX shading networks and attempt to import them automatically ## USD stage support in viewport We support rendering a MaterialX USD asset directly in the VP2 viewport. ### Supported: We are using the hdMtlx translation framework, which is also in use for hdStorm and hdPrman, and using the same GLSL code generator as hdStorm, so valid USD MaterialX material graphs should display correctly. Maya spheres with standard surface shading: ![alt text](./MayaStandardSurfaceSampler.JPG "Standard surface sampler") The same spheres exported with MaterialX shading and loaded as a USD stage: ![alt text](./USDMaterialXStandardSurfaceSampler.JPG "USD MaterialX sampler") ### Not supported: - DirectX 11 viewport - [Issue 1523](https://github.com/PixarAnimationStudios/USD/issues/1523): Color spaces - [Issue 1538](https://github.com/PixarAnimationStudios/USD/issues/1538): MaterialX networks containing surface shaders other than standard surface or preview surface ### To enable: This one is more complex and requires knowledge of how to build USD. **Requires Maya 2022.1 or PR126** 1. Build MaterialX using the [Autodesk fork of MaterialX](https://github.com/autodesk-forks/MaterialX) - Requires a version later than [PR 1285](https://github.com/autodesk-forks/MaterialX/pull/1285) for proper transparency support. - Requires at minimum MATERIALX_BUILD_CONTRIB, MATERIALX_BUILD_GEN_OGSXML, and MATERIALX_BUILD_SHARED_LIBS options to be enabled - We only require the OGS XML shadergen part (and USD requires the GLSL shadergen), so you can turn off all complex options like Viewer, OIIO, OSL, or Python support 2. Install that freshly built MaterialX in the `install` location where you intend to build USD next 3. Build a recent USD from the tip of the dev branch into the `install` location that has the updated MaterialX from step 1 (assuming you will use the build_usd.py script) - There is an API change in the Autodesk branch of MaterialX that requires updating `pxr/imaging/hdSt/materialXFilter.cpp` at line 71 to remove second parameter on the `isTransparentSurface()` function call 4. Rebuild MayaUSD plugin from the tip of the dev branch or any commit that includes both [PR 1478](https://github.com/Autodesk/maya-usd/pull/1478) and [PR 1433](https://github.com/Autodesk/maya-usd/pull/1433) - Requires enabling the CMAKE_WANT_MATERIALX_BUILD option - MaterialX_DIR should point to the one built in step 1 - PXR_USD_LOCATION should point to one built in step 3 Once the updated plugin is in use, the viewport will automatically select MaterialX shading over UsdPreviewSurface shading if the referenced USD stage contains MaterialX shading networks.<file_sep>/lib/mayaUsd/utils/diagnosticDelegate.h // // Copyright 2018 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef PXRUSDMAYA_DIAGNOSTICDELEGATE_H #define PXRUSDMAYA_DIAGNOSTICDELEGATE_H #include <mayaUsd/base/api.h> #include <pxr/base/tf/diagnosticMgr.h> #include <pxr/pxr.h> #include <pxr/usd/usdUtils/coalescingDiagnosticDelegate.h> #include <maya/MGlobal.h> #include <atomic> #include <memory> PXR_NAMESPACE_OPEN_SCOPE class UsdMayaDiagnosticBatchContext; /// Converts Tf diagnostics into native Maya infos, warnings, and errors. /// /// Provides an optional batching mechanism for diagnostics; see /// UsdMayaDiagnosticBatchContext for more information. Note that errors /// are never batched. /// /// The IssueError(), IssueStatus(), etc. functions are thread-safe, since Tf /// may issue diagnostics from secondary threads. Note that, when not batching, /// secondary threads' diagnostic messages are posted to stderr instead of to /// the Maya script window. When batching, secondary threads' diagnostic /// messages will be posted by the main thread to the Maya script window when /// batching ends. /// /// Installing and removing this diagnostic delegate is not thread-safe, and /// must be done only on the main thread. class UsdMayaDiagnosticDelegate : TfDiagnosticMgr::Delegate { public: MAYAUSD_CORE_PUBLIC ~UsdMayaDiagnosticDelegate() override; MAYAUSD_CORE_PUBLIC void IssueError(const TfError& err) override; MAYAUSD_CORE_PUBLIC void IssueStatus(const TfStatus& status) override; MAYAUSD_CORE_PUBLIC void IssueWarning(const TfWarning& warning) override; MAYAUSD_CORE_PUBLIC void IssueFatalError(const TfCallContext& context, const std::string& msg) override; /// Installs a shared delegate globally. /// If this is invoked on a secondary thread, issues a fatal coding error. MAYAUSD_CORE_PUBLIC static void InstallDelegate(); /// Removes the global shared delegate, if it exists. /// If this is invoked on a secondary thread, issues a fatal coding error. MAYAUSD_CORE_PUBLIC static void RemoveDelegate(); /// Returns the number of active batch contexts associated with the global /// delegate. 0 means no batching; 1 or more means diagnostics are batched. /// If there is no delegate installed, issues a runtime error and returns 0. MAYAUSD_CORE_PUBLIC static int GetBatchCount(); private: friend class UsdMayaDiagnosticBatchContext; std::atomic_int _batchCount; std::unique_ptr<UsdUtilsCoalescingDiagnosticDelegate> _batchedStatuses; std::unique_ptr<UsdUtilsCoalescingDiagnosticDelegate> _batchedWarnings; UsdMayaDiagnosticDelegate(); void _StartBatch(); void _EndBatch(); void _FlushBatch(); }; /// As long as a batch context remains alive (process-wide), the /// UsdMayaDiagnosticDelegate will save diagnostic messages, only emitting /// them when the last batch context is destructed. Note that errors are never /// batched. /// /// Batch contexts must only exist on the main thread (though they will apply /// to any diagnostics issued on secondary threads while they're alive). If /// they're constructed on secondary threads, they will issue a fatal coding /// error. /// /// Batch contexts can be constructed and destructed out of "scope" order, e.g., /// this is allowed: /// 1. Context A constructed /// 2. Context B constructed /// 3. Context A destructed /// 4. Context B destructed class UsdMayaDiagnosticBatchContext { public: /// Constructs a batch context, causing all subsequent diagnostic messages /// to be batched on all threads. /// If this is invoked on a secondary thread, issues a fatal coding error. MAYAUSD_CORE_PUBLIC UsdMayaDiagnosticBatchContext(); MAYAUSD_CORE_PUBLIC ~UsdMayaDiagnosticBatchContext(); UsdMayaDiagnosticBatchContext(const UsdMayaDiagnosticBatchContext&) = delete; UsdMayaDiagnosticBatchContext& operator=(const UsdMayaDiagnosticBatchContext&) = delete; private: /// This pointer is used to "bind" this context to a specific delegate in /// case the global delegate is removed (and possibly re-installed) while /// this batch context is alive. std::weak_ptr<UsdMayaDiagnosticDelegate> _delegate; }; PXR_NAMESPACE_CLOSE_SCOPE #endif <file_sep>/test/lib/mayaUsd/fileio/testShaderReader.py #!/usr/bin/env mayapy # # Copyright 2021 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import mayaUsd.lib as mayaUsdLib from pxr import Gf from pxr import Sdf from pxr import Tf from pxr import Vt from pxr import UsdGeom from maya import cmds import maya.api.OpenMaya as OpenMaya from maya import standalone import fixturesUtils, os import unittest class shaderReaderTest(mayaUsdLib.ShaderReader): @classmethod def CanImport(self): print("shaderReaderTest.CanImport called") return self.ContextSupport.Fallback def HasPostReadSubtree(self): print("shaderReaderTest.HasPostReadSubtree called") return False class testShaderReader(unittest.TestCase): @classmethod def setUpClass(cls): fixturesUtils.setUpClass(__file__) @classmethod def tearDownClass(cls): standalone.uninitialize() def setUp(self): cmds.file(new=True, force=True) def testSimpleShaderReader(self): mayaUsdLib.ShaderReader.Register(shaderReaderTest, "test") if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/lib/mayaUsd/utils/diagnosticDelegate.cpp // // Copyright 2018 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "diagnosticDelegate.h" #include <mayaUsd/base/debugCodes.h> #include <pxr/base/arch/threads.h> #include <pxr/base/tf/envSetting.h> #include <pxr/base/tf/stackTrace.h> #include <maya/MGlobal.h> #include <ghc/filesystem.hpp> PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_ENV_SETTING( PIXMAYA_DIAGNOSTICS_BATCH, true, "Whether to batch diagnostics coming from the same call site. " "If batching is off, all secondary threads' diagnostics will be " "printed to stderr."); TF_DEFINE_ENV_SETTING( MAYAUSD_SHOW_FULL_DIAGNOSTICS, false, "This env flag controls the granularity of TF error/warning/status messages " "being displayed in Maya."); // Globally-shared delegate. Uses shared_ptr so we can have weak ptrs. static std::shared_ptr<UsdMayaDiagnosticDelegate> _sharedDelegate; // The delegate can be installed by multiple plugins (e.g. pxrUsd and // mayaUsdPlugin), so keep track of installations to ensure that we only add // the delegate for the first installation call, and that we only remove it for // the last removal call. static int _installationCount = 0; namespace { class _StatusOnlyDelegate : public UsdUtilsCoalescingDiagnosticDelegate { void IssueWarning(const TfWarning&) override { } void IssueFatalError(const TfCallContext&, const std::string&) override { } }; class _WarningOnlyDelegate : public UsdUtilsCoalescingDiagnosticDelegate { void IssueStatus(const TfStatus&) override { } void IssueFatalError(const TfCallContext&, const std::string&) override { } }; } // anonymous namespace static MString _FormatDiagnostic(const TfDiagnosticBase& d) { if (!TfGetEnvSetting(MAYAUSD_SHOW_FULL_DIAGNOSTICS)) { return d.GetCommentary().c_str(); } else { const std::string msg = TfStringPrintf( "%s -- %s in %s at line %zu of %s", d.GetCommentary().c_str(), TfDiagnosticMgr::GetCodeName(d.GetDiagnosticCode()).c_str(), d.GetContext().GetFunction(), d.GetContext().GetLine(), ghc::filesystem::path(d.GetContext().GetFile()).relative_path().string().c_str()); return msg.c_str(); } } static MString _FormatCoalescedDiagnostic(const UsdUtilsCoalescingDiagnosticDelegateItem& item) { const size_t numItems = item.unsharedItems.size(); const std::string suffix = numItems == 1 ? std::string() : TfStringPrintf(" -- and %zu similar", numItems - 1); const std::string message = TfStringPrintf("%s%s", item.unsharedItems[0].commentary.c_str(), suffix.c_str()); return message.c_str(); } static bool _IsDiagnosticBatchingEnabled() { return TfGetEnvSetting(PIXMAYA_DIAGNOSTICS_BATCH); } UsdMayaDiagnosticDelegate::UsdMayaDiagnosticDelegate() : _batchCount(0) { TfDiagnosticMgr::GetInstance().AddDelegate(this); } UsdMayaDiagnosticDelegate::~UsdMayaDiagnosticDelegate() { // If a batch context was open when the delegate is removed, we need to // flush all the batched diagnostics in order to avoid losing any. // The batch context should know how to clean itself up when the delegate // is gone. _FlushBatch(); TfDiagnosticMgr::GetInstance().RemoveDelegate(this); } void UsdMayaDiagnosticDelegate::IssueError(const TfError& err) { // Errors are never batched. They should be rare, and in those cases, we // want to see them separately. const auto diagnosticMessage = _FormatDiagnostic(err); if (ArchIsMainThread()) { MGlobal::displayError(diagnosticMessage); } else { std::cerr << diagnosticMessage << std::endl; } } void UsdMayaDiagnosticDelegate::IssueStatus(const TfStatus& status) { if (_batchCount.load() > 0) { return; // Batched. } const auto diagnosticMessage = _FormatDiagnostic(status); if (ArchIsMainThread()) { MGlobal::displayInfo(diagnosticMessage); } else { std::cerr << diagnosticMessage << std::endl; } } void UsdMayaDiagnosticDelegate::IssueWarning(const TfWarning& warning) { if (_batchCount.load() > 0) { return; // Batched. } const auto diagnosticMessage = _FormatDiagnostic(warning); if (ArchIsMainThread()) { MGlobal::displayWarning(diagnosticMessage); } else { std::cerr << diagnosticMessage << std::endl; } } void UsdMayaDiagnosticDelegate::IssueFatalError( const TfCallContext& context, const std::string& msg) { TfLogCrash( "FATAL ERROR", msg, /*additionalInfo*/ std::string(), context, /*logToDb*/ true); _UnhandledAbort(); } /* static */ void UsdMayaDiagnosticDelegate::InstallDelegate() { if (!ArchIsMainThread()) { TF_FATAL_CODING_ERROR("Cannot install delegate from secondary thread"); } if (_installationCount++ > 0) { return; } _sharedDelegate.reset(new UsdMayaDiagnosticDelegate()); } /* static */ void UsdMayaDiagnosticDelegate::RemoveDelegate() { if (!ArchIsMainThread()) { TF_FATAL_CODING_ERROR("Cannot remove delegate from secondary thread"); } if (_installationCount == 0 || _installationCount-- > 1) { return; } _sharedDelegate.reset(); } /* static */ int UsdMayaDiagnosticDelegate::GetBatchCount() { if (std::shared_ptr<UsdMayaDiagnosticDelegate> ptr = _sharedDelegate) { return ptr->_batchCount.load(); } TF_RUNTIME_ERROR("Delegate is not installed"); return 0; } void UsdMayaDiagnosticDelegate::_StartBatch() { TF_AXIOM(ArchIsMainThread()); if (_batchCount.fetch_add(1) == 0) { // This is the first _StartBatch; add the batching delegates. _batchedStatuses.reset(new _StatusOnlyDelegate()); _batchedWarnings.reset(new _WarningOnlyDelegate()); } } void UsdMayaDiagnosticDelegate::_EndBatch() { TF_AXIOM(ArchIsMainThread()); const int prevValue = _batchCount.fetch_sub(1); if (prevValue <= 0) { TF_FATAL_ERROR("_EndBatch invoked before _StartBatch"); } else if (prevValue == 1) { // This is the last _EndBatch; print the diagnostic messages. // and remove the batching delegates. _FlushBatch(); _batchedStatuses.reset(); _batchedWarnings.reset(); } } void UsdMayaDiagnosticDelegate::_FlushBatch() { TF_AXIOM(ArchIsMainThread()); const UsdUtilsCoalescingDiagnosticDelegateVector statuses = _batchedStatuses ? _batchedStatuses->TakeCoalescedDiagnostics() : UsdUtilsCoalescingDiagnosticDelegateVector(); const UsdUtilsCoalescingDiagnosticDelegateVector warnings = _batchedWarnings ? _batchedWarnings->TakeCoalescedDiagnostics() : UsdUtilsCoalescingDiagnosticDelegateVector(); // Note that we must be in the main thread here, so it's safe to call // displayInfo/displayWarning. for (const UsdUtilsCoalescingDiagnosticDelegateItem& item : statuses) { MGlobal::displayInfo(_FormatCoalescedDiagnostic(item)); } for (const UsdUtilsCoalescingDiagnosticDelegateItem& item : warnings) { MGlobal::displayWarning(_FormatCoalescedDiagnostic(item)); } } UsdMayaDiagnosticBatchContext::UsdMayaDiagnosticBatchContext() : _delegate(_IsDiagnosticBatchingEnabled() ? _sharedDelegate : nullptr) { TF_DEBUG(PXRUSDMAYA_DIAGNOSTICS).Msg(">> Entering batch context\n"); if (!ArchIsMainThread()) { TF_FATAL_CODING_ERROR("Cannot construct context on secondary thread"); } if (std::shared_ptr<UsdMayaDiagnosticDelegate> ptr = _delegate.lock()) { ptr->_StartBatch(); } } UsdMayaDiagnosticBatchContext::~UsdMayaDiagnosticBatchContext() { TF_DEBUG(PXRUSDMAYA_DIAGNOSTICS).Msg("!! Exiting batch context\n"); if (!ArchIsMainThread()) { TF_FATAL_CODING_ERROR("Cannot destruct context on secondary thread"); } if (std::shared_ptr<UsdMayaDiagnosticDelegate> ptr = _delegate.lock()) { ptr->_EndBatch(); } } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/lib/mayaUsd/fileio/primUpdaterContext.h // // Copyright 2016 Pixar // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef PXRUSDMAYA_PRIMUPDATERCONTEXT_H #define PXRUSDMAYA_PRIMUPDATERCONTEXT_H #include <mayaUsd/base/api.h> #include <pxr/pxr.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usd/timeCode.h> PXR_NAMESPACE_OPEN_SCOPE /// \class UsdMayaPrimUpdaterContext /// \brief This class provides an interface for updater plugins to communicate /// state back to the core usd maya logic. class UsdMayaPrimUpdaterContext { public: MAYAUSD_CORE_PUBLIC UsdMayaPrimUpdaterContext(const UsdTimeCode& timeCode, const UsdStageRefPtr& stage); /// \brief returns the time frame where data should be edited. const UsdTimeCode& GetTimeCode() const { return _timeCode; } /// \brief returns the usd stage that is being written to. UsdStageRefPtr GetUsdStage() const { return _stage; } MAYAUSD_CORE_PUBLIC virtual void Clear(const SdfPath&); private: const UsdTimeCode& _timeCode; UsdStageRefPtr _stage; }; PXR_NAMESPACE_CLOSE_SCOPE #endif <file_sep>/lib/mayaUsd/python/wrapImportChaser.cpp // // Copyright 2021 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <mayaUsd/fileio/chaser/importChaser.h> #include <mayaUsd/fileio/chaser/importChaserRegistry.h> #include <mayaUsd/fileio/registryHelper.h> #include <pxr/base/tf/makePyConstructor.h> #include <pxr/base/tf/pyContainerConversions.h> #include <pxr/base/tf/pyEnum.h> #include <pxr/base/tf/pyPolymorphic.h> #include <pxr/base/tf/pyPtrHelpers.h> #include <pxr/base/tf/pyResultConversions.h> #include <pxr/base/tf/refPtr.h> #include <maya/MFnDependencyNode.h> #include <boost/python.hpp> #include <boost/python/args.hpp> #include <boost/python/def.hpp> #include <boost/python/wrapper.hpp> PXR_NAMESPACE_USING_DIRECTIVE //---------------------------------------------------------------------------------------------------------------------- /// \brief boost python binding for the UsdMayaImportChaser //---------------------------------------------------------------------------------------------------------------------- class ImportChaserWrapper : public UsdMayaImportChaser , public TfPyPolymorphic<UsdMayaImportChaser> { public: typedef ImportChaserWrapper This; typedef UsdMayaImportChaser base_t; static ImportChaserWrapper* New(uintptr_t createdWrapper) { return (ImportChaserWrapper*)createdWrapper; } virtual ~ImportChaserWrapper() { } bool default_PostImport( Usd_PrimFlagsPredicate& returnPredicate, const UsdStagePtr& stage, const MDagPathArray& dagPaths, const SdfPathVector& sdfPaths, const UsdMayaJobImportArgs& jobArgs) { return base_t::PostImport(returnPredicate, stage, dagPaths, sdfPaths, jobArgs); } bool PostImport( Usd_PrimFlagsPredicate& returnPredicate, const UsdStagePtr& stage, const MDagPathArray& dagPaths, const SdfPathVector& sdfPaths, const UsdMayaJobImportArgs& jobArgs) override { return this->CallVirtual<bool>("PostImport", &This::default_PostImport)( returnPredicate, stage, dagPaths, sdfPaths, jobArgs); } bool default_Redo() { return base_t::Redo(); } bool Redo() override { return this->CallVirtual<>("Redo", &This::default_Redo)(); } bool default_Undo() { return base_t::Undo(); } bool Undo() override { return this->CallVirtual<>("Undo", &This::default_Undo)(); } static void Register(boost::python::object cl, const char* name) { UsdMayaImportChaserRegistry::GetInstance().RegisterFactory( name, [=](const UsdMayaImportChaserRegistry::FactoryContext& context) { auto chaser = new ImportChaserWrapper(); TfPyLock pyLock; boost::python::object instance = cl((uintptr_t)(ImportChaserWrapper*)chaser); boost::python::incref(instance.ptr()); initialize_wrapper(instance.ptr(), chaser); return chaser; }, true); } }; //---------------------------------------------------------------------------------------------------------------------- void wrapImportChaser() { typedef ImportChaserWrapper* ImportChaserWrapperPtr; boost::python::class_<ImportChaserWrapper, boost::noncopyable>( "ImportChaser", boost::python::no_init) .def("__init__", make_constructor(&ImportChaserWrapper::New)) .def( "PostImport", &ImportChaserWrapper::PostImport, &ImportChaserWrapper::default_PostImport) .def("Redo", &ImportChaserWrapper::Redo, &ImportChaserWrapper::default_Redo) .def("Undo", &ImportChaserWrapper::Undo, &ImportChaserWrapper::default_Undo) .def( "Register", &ImportChaserWrapper::Register, (boost::python::arg("class"), boost::python::arg("type"))) .staticmethod("Register"); } <file_sep>/test/lib/usd/translators/testUsdExportMaterialX.py #!/usr/bin/env mayapy # # Copyright 2021 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from pxr import Usd from pxr import UsdShade from maya import cmds from maya import standalone import mayaUsd.lib as mayaUsdLib import os import unittest import fixturesUtils class testUsdExportMaterialX(unittest.TestCase): @classmethod def setUpClass(cls): inputPath = fixturesUtils.setUpClass(__file__) mayaFile = os.path.join(inputPath, 'UsdExportMaterialXTest', 'StandardSurfaceTextured.ma') cmds.file(mayaFile, force=True, open=True) # Export to USD. usdFilePath = os.path.abspath('UsdExportMaterialXTest.usda') cmds.mayaUSDExport(mergeTransformAndShape=True, file=usdFilePath, shadingMode='useRegistry', convertMaterialsTo='MaterialX', materialsScopeName='Materials') cls._stage = Usd.Stage.Open(usdFilePath) @classmethod def tearDownClass(cls): standalone.uninitialize() def testStageOpens(self): ''' Tests that the USD stage was opened successfully. ''' self.assertTrue(self._stage) def compareValue(self, shader, name, value): """Test that a named attribute has the expected value""" attr = shader.GetInput(name) self.assertTrue(attr) return attr.GetAttr().Get() == value def testExportTexturedMaterialXpPlane1(self): ''' Tests that pPlane1 exported as planned: this plane is a basic RGB texture without any customizations. ''' # Exploring this path: base_path = "/pPlane1/Materials/standardSurface2SG" mesh_prim = self._stage.GetPrimAtPath('/pPlane1') self.assertTrue(mesh_prim) # Validate the Material prim bound to the Mesh prim. self.assertTrue(mesh_prim.HasAPI(UsdShade.MaterialBindingAPI)) mat_binding = UsdShade.MaterialBindingAPI(mesh_prim) mat = mat_binding.ComputeBoundMaterial("mtlx")[0] self.assertTrue(mat) material_path = mat.GetPath().pathString self.assertEqual(material_path, base_path) # Needs a resolved inputs:file1:varname attribute: self.assertEqual(mat.GetInput("file1:varname").GetAttr().Get(), "st") # Needs a MaterialX surface source: shader = mat.ComputeSurfaceSource("mtlx")[0] self.assertTrue(shader) # Which is a standard surface: self.assertEqual(shader.GetIdAttr().Get(), "ND_standard_surface_surfaceshader") # With a connected file texture on base_color going to baseColor on the # nodegraph: attr = shader.GetInput('base_color') self.assertTrue(attr) cnxTuple = attr.GetConnectedSource() self.assertTrue(cnxTuple) ng_path = base_path + '/MayaNG_standardSurface2SG' ng = UsdShade.NodeGraph(cnxTuple[0]) self.assertEqual(ng.GetPath(), ng_path) self.assertEqual(cnxTuple[1], "baseColor") # Should have an outputs connected to a file node: attr = ng.GetOutput('baseColor') self.assertTrue(attr) cnxTuple = attr.GetConnectedSource() self.assertTrue(cnxTuple) # Which is a color3 image: shader = UsdShade.Shader(cnxTuple[0]) self.assertEqual(shader.GetIdAttr().Get(), "ND_image_color3") self.assertEqual(shader.GetPath(), ng_path + "/file1") # Check a few values: self.assertTrue(self.compareValue(shader, "uaddressmode", "periodic")) self.assertTrue(self.compareValue(shader, "default", (0.5, 0.5, 0.5))) # Which is itself connected to a primvar reader: attr = shader.GetInput('texcoord') self.assertTrue(attr) cnxTuple = attr.GetConnectedSource() self.assertTrue(cnxTuple) # Which is a geompropvalue node: shader = UsdShade.Shader(cnxTuple[0]) self.assertEqual(shader.GetIdAttr().Get(), "ND_geompropvalue_vector2") self.assertEqual(shader.GetPath(), ng_path + "/MayaGeomPropValue_file1") def testExportTexturedMaterialXNodeTypes(self): ''' Tests all node ids that are expected: ''' base_path = "/pPlane{0}/Materials/standardSurface{1}SG/MayaNG_standardSurface{1}SG/{2}" to_test = [ (7, 8, "file7", "ND_image_float"), (6, 7, "file6", "ND_image_vector2"), (1, 2, "file1", "ND_image_color3"), (4, 5, "file4", "ND_image_color4"), (1, 2, "MayaGeomPropValue_file1", "ND_geompropvalue_vector2"), (4, 5, "MayaSwizzle_file4_rgb", "ND_swizzle_color4_color3"), (6, 7, "MayaSwizzle_file6_xxx", "ND_swizzle_vector2_color3"), (19, 21, "MayaSwizzle_file20_x", "ND_swizzle_vector2_float"), (7, 8, "MayaSwizzle_file7_rrr", "ND_swizzle_float_color3"), (8, 9, "MayaSwizzle_file8_r", "ND_swizzle_color4_float"), (13, 14, "MayaSwizzle_file13_g", "ND_swizzle_color3_float"), (27, 20, "MayaLuminance_file27", "ND_luminance_color3"), (12, 13, "MayaLuminance_file12", "ND_luminance_color4"), (14, 15, "MayaConvert_file14_color3f_float3", "ND_convert_color3_vector3"), (15, 16, "MayaNormalMap_standardSurface16_normalCamera", "ND_normalmap"), ] for prim_idx, sg_idx, node_name, id_attr in to_test: prim_path = base_path.format(prim_idx, sg_idx, node_name) prim = self._stage.GetPrimAtPath(prim_path) self.assertTrue(prim, prim_path) shader = UsdShade.Shader(prim) self.assertTrue(shader, prim_path) self.assertEqual(shader.GetIdAttr().Get(), id_attr, id_attr) if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/test/lib/ufe/testChildFilter.py #!/usr/bin/env python # # Copyright 2020 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import fixturesUtils import mayaUtils from maya import cmds from maya import standalone import ufe import os import unittest class ChildFilterTestCase(unittest.TestCase): '''Verify the ChildFilter USD implementation. ''' pluginsLoaded = False @classmethod def setUpClass(cls): fixturesUtils.readOnlySetUpClass(__file__, loadPlugin=False) if not cls.pluginsLoaded: cls.pluginsLoaded = mayaUtils.isMayaUsdPluginLoaded() @classmethod def tearDownClass(cls): standalone.uninitialize() def setUp(self): ''' Called initially to set up the Maya test environment ''' # Load plugins self.assertTrue(self.pluginsLoaded) # Open ballset.ma scene in testSamples mayaUtils.openGroupBallsScene() # Clear selection to start off cmds.select(clear=True) def testFilteredChildren(self): # Check that we have six balls propsPath = ufe.PathString.path('|transform1|proxyShape1,/Ball_set/Props') propsItem = ufe.Hierarchy.createItem(propsPath) propsHier = ufe.Hierarchy.hierarchy(propsItem) self.assertEqual(6, len(propsHier.children())) # Deactivate Ball_3 (which will remove it from children) ball3Path = ufe.PathString.path('|transform1|proxyShape1,/Ball_set/Props/Ball_3') ball3Hier = ufe.Hierarchy.createItem(ball3Path) cmds.delete('|transform1|proxyShape1,/Ball_set/Props/Ball_3') # Props should now have 5 children and ball3 should not be one of them. children = propsHier.children() self.assertEqual(5, len(children)) self.assertNotIn(ball3Hier, children) # Ensure we have one USD child filter rid = ufe.RunTimeMgr.instance().getId('USD') usdHierHndlr = ufe.RunTimeMgr.instance().hierarchyHandler(rid) cf = usdHierHndlr.childFilter() self.assertEqual(1, len(cf)) # Make sure the USD hierarchy handler has an inactive prims filter self.assertEqual('InactivePrims', cf[0].name) # Toggle "Inactive Prims" on and get the filtered children # (with inactive prims) and verify ball3 is one of them. cf[0].value = True children = propsHier.filteredChildren(cf) self.assertEqual(6, len(children)) self.assertIn(ball3Hier, children) if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/lib/mayaUsd/ufe/StagesSubject.h // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include <mayaUsd/base/api.h> #include <mayaUsd/listeners/proxyShapeNotice.h> #include <pxr/base/tf/hash.h> #include <pxr/base/tf/notice.h> #include <pxr/base/tf/weakBase.h> #include <pxr/usd/usd/notice.h> #include <pxr/usd/usd/stage.h> #include <maya/MCallbackIdArray.h> #include <ufe/path.h> #include <ufe/ufe.h> // For UFE_V2_FEATURES_AVAILABLE #include <unordered_set> namespace MAYAUSD_NS_DEF { namespace ufe { //! \brief Subject class to observe Maya scene. /*! This class observes Maya file open, to register a USD observer on each stage the Maya scene contains. This USD observer translates USD notifications into UFE notifications. */ class MAYAUSD_CORE_PUBLIC StagesSubject : public PXR_NS::TfWeakBase { public: typedef PXR_NS::TfWeakPtr<StagesSubject> Ptr; //! Constructor StagesSubject(); //! Destructor ~StagesSubject(); //! Create the StagesSubject. static StagesSubject::Ptr create(); // Delete the copy/move constructors assignment operators. StagesSubject(const StagesSubject&) = delete; StagesSubject& operator=(const StagesSubject&) = delete; StagesSubject(StagesSubject&&) = delete; StagesSubject& operator=(StagesSubject&&) = delete; bool beforeNewCallback() const; void beforeNewCallback(bool b); void afterOpen(); private: // Maya scene message callbacks static void beforeNewCallback(void* clientData); static void beforeOpenCallback(void* clientData); static void afterNewCallback(void* clientData); static void afterOpenCallback(void* clientData); //! Call the stageChanged() methods on stage observers. void stageChanged( PXR_NS::UsdNotice::ObjectsChanged const& notice, PXR_NS::UsdStageWeakPtr const& sender); #ifdef UFE_V2_FEATURES_AVAILABLE //! Call the stageEditTargetChanged() methods on stage observers. void stageEditTargetChanged( PXR_NS::UsdNotice::StageEditTargetChanged const& notice, PXR_NS::UsdStageWeakPtr const& sender); #endif private: // Notice listener method for proxy stage set void onStageSet(const PXR_NS::MayaUsdProxyStageSetNotice& notice); // Notice listener method for proxy stage invalidate. void onStageInvalidate(const PXR_NS::MayaUsdProxyStageInvalidateNotice& notice); // Array of Notice::Key for registered listener #ifdef UFE_V2_FEATURES_AVAILABLE using NoticeKeys = std::array<PXR_NS::TfNotice::Key, 2>; #else using NoticeKeys = std::array<PXR_NS::TfNotice::Key, 1>; #endif // Map of per-stage listeners, indexed by stage. typedef PXR_NS::TfHashMap<PXR_NS::UsdStageWeakPtr, NoticeKeys, PXR_NS::TfHash> StageListenerMap; StageListenerMap fStageListeners; /*! \brief Store invalidated ufe paths during dirty propagation. We need to delay notification till stage changes, but at that time it could be too costly to discover what changed in the stage map. Instead, we store all gateway notes that changed during dirty propagation and send invalidation from compute, when the new stage is set. This cache is only useful between onStageInvalidate and onStageSet notifications. */ std::unordered_set<Ufe::Path> fInvalidStages; bool fBeforeNewCallback = false; MCallbackIdArray fCbIds; }; // StagesSubject #ifdef UFE_V2_FEATURES_AVAILABLE //! \brief Guard to delay attribute changed notifications. /*! Instantiating an object of this class allows the attribute changed notifications to be delayed until the guard expires. The guard collapses down notifications for a given UFE path, which is desirable to avoid duplicate notifications. However, it is an error to have notifications for more than one attribute within a single guard. */ class MAYAUSD_CORE_PUBLIC AttributeChangedNotificationGuard { public: AttributeChangedNotificationGuard(); ~AttributeChangedNotificationGuard(); //@{ //! Cannot be copied or assigned. AttributeChangedNotificationGuard(const AttributeChangedNotificationGuard&) = delete; const AttributeChangedNotificationGuard& operator&(const AttributeChangedNotificationGuard&) = delete; //@} }; #endif } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/lib/mayaUsd/ufe/UsdUndoInsertChildCommand.cpp // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "UsdUndoInsertChildCommand.h" #include "Utils.h" #include "private/UfeNotifGuard.h" #include "private/Utils.h" #include <mayaUsdUtils/util.h> #include <pxr/base/tf/token.h> #include <pxr/usd/sdf/copyUtils.h> #include <pxr/usd/usd/editContext.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usdGeom/gprim.h> #include <ufe/log.h> #include <ufe/scene.h> #include <ufe/sceneNotification.h> #define UFE_ENABLE_ASSERTS #include <ufe/ufeAssert.h> namespace { // shared_ptr requires public ctor, dtor, so derive a class for it. template <class T> struct MakeSharedEnabler : public T { MakeSharedEnabler( const MayaUsd::ufe::UsdSceneItem::Ptr& parent, const MayaUsd::ufe::UsdSceneItem::Ptr& child, const MayaUsd::ufe::UsdSceneItem::Ptr& pos) : T(parent, child, pos) { } }; } // namespace namespace MAYAUSD_NS_DEF { namespace ufe { UsdUndoInsertChildCommand::UsdUndoInsertChildCommand( const UsdSceneItem::Ptr& parent, const UsdSceneItem::Ptr& child, const UsdSceneItem::Ptr& /* pos */) : Ufe::InsertChildCommand() , _ufeDstItem(nullptr) , _ufeSrcPath(child->path()) , _usdSrcPath(child->prim().GetPath()) { const auto& childPrim = child->prim(); const auto& parentPrim = parent->prim(); // Don't allow parenting to a Gprim. // USD strongly discourages parenting of one gprim to another. // https://graphics.pixar.com/usd/docs/USD-Glossary.html#USDGlossary-Gprim if (parentPrim.IsA<UsdGeomGprim>()) { std::string err = TfStringPrintf( "Parenting geometric prim [%s] under geometric prim [%s] is not allowed " "Please parent geometric prims under separate XForms and reparent between XForms.", childPrim.GetName().GetString().c_str(), parentPrim.GetName().GetString().c_str()); throw std::runtime_error(err.c_str()); } // Apply restriction rules ufe::applyCommandRestriction(childPrim, "reparent"); ufe::applyCommandRestriction(parentPrim, "reparent"); // First, check if we need to rename the child. const auto childName = uniqueChildName(parent->prim(), child->path().back().string()); // Create a new segment if parent and child are in different run-times. // parenting a USD node to the proxy shape node implies two different run-times auto cRtId = child->path().runTimeId(); if (parent->path().runTimeId() == cRtId) { _ufeDstPath = parent->path() + childName; } else { auto cSep = child->path().getSegments().back().separator(); _ufeDstPath = parent->path() + Ufe::PathSegment(Ufe::PathComponent(childName), cRtId, cSep); } _usdDstPath = parentPrim.GetPath().AppendChild(TfToken(childName)); _childLayer = childPrim.GetStage()->GetEditTarget().GetLayer(); _parentLayer = parentPrim.GetStage()->GetEditTarget().GetLayer(); } UsdUndoInsertChildCommand::~UsdUndoInsertChildCommand() { } /*static*/ UsdUndoInsertChildCommand::Ptr UsdUndoInsertChildCommand::create( const UsdSceneItem::Ptr& parent, const UsdSceneItem::Ptr& child, const UsdSceneItem::Ptr& pos) { if (!parent || !child) { return nullptr; } // Error if requested parent is currently a child of requested child. if (parent->path().startsWith(child->path())) { return nullptr; } return std::make_shared<MakeSharedEnabler<UsdUndoInsertChildCommand>>(parent, child, pos); } bool UsdUndoInsertChildCommand::insertChildRedo() { bool status = SdfCopySpec(_childLayer, _usdSrcPath, _parentLayer, _usdDstPath); if (status) { // remove all scene description for the given path and // its subtree in the current UsdEditTarget { // we shouldn't rely on UsdSceneItem to access the UsdPrim since // it could be stale. Instead we should get the USDPrim from the Ufe::Path const auto& usdSrcPrim = ufePathToPrim(_ufeSrcPath); auto stage = usdSrcPrim.GetStage(); UsdEditContext ctx(stage, _childLayer); status = stage->RemovePrim(_usdSrcPath); } if (status) { _ufeDstItem = UsdSceneItem::create(_ufeDstPath, ufePathToPrim(_ufeDstPath)); sendNotification<Ufe::ObjectReparent>(_ufeDstItem, _ufeSrcPath); } } else { UFE_LOG( std::string("Warning: SdfCopySpec(") + _usdSrcPath.GetString() + std::string(") failed.")); } return status; } bool UsdUndoInsertChildCommand::insertChildUndo() { bool status = SdfCopySpec(_parentLayer, _usdDstPath, _childLayer, _usdSrcPath); if (status) { // remove all scene description for the given path and // its subtree in the current UsdEditTarget { // we shouldn't rely on UsdSceneItem to access the UsdPrim since // it could be stale. Instead we should get the USDPrim from the Ufe::Path const auto& usdDstPrim = ufePathToPrim(_ufeDstPath); auto stage = usdDstPrim.GetStage(); UsdEditContext ctx(stage, _parentLayer); status = stage->RemovePrim(_usdDstPath); } if (status) { auto ufeSrcItem = UsdSceneItem::create(_ufeSrcPath, ufePathToPrim(_ufeSrcPath)); sendNotification<Ufe::ObjectReparent>(ufeSrcItem, _ufeDstPath); } } else { UFE_LOG( std::string("Warning: RemovePrim(") + _usdDstPath.GetString() + std::string(") failed.")); } return status; } void UsdUndoInsertChildCommand::undo() { try { InPathChange pc; if (!insertChildUndo()) { UFE_LOG("insert child undo failed"); } } catch (const std::exception& e) { UFE_LOG(e.what()); throw; // re-throw the same exception } } void UsdUndoInsertChildCommand::redo() { InPathChange pc; if (!insertChildRedo()) { UFE_LOG("insert child redo failed"); } } } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/lib/usd/translators/shading/mtlxFileTextureWriter.cpp // // Copyright 2021 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "mtlxBaseWriter.h" #include "shadingTokens.h" #include <mayaUsd/fileio/shaderWriter.h> #include <mayaUsd/fileio/shaderWriterRegistry.h> #include <mayaUsd/fileio/shading/shadingModeRegistry.h> #include <mayaUsd/fileio/utils/shadingUtil.h> #include <mayaUsd/fileio/writeJobContext.h> #include <mayaUsd/utils/util.h> #include <pxr/base/gf/vec3f.h> #include <pxr/base/gf/vec4f.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/base/tf/pathUtils.h> #include <pxr/base/tf/staticTokens.h> #include <pxr/base/tf/stringUtils.h> #include <pxr/base/tf/token.h> #include <pxr/base/vt/value.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/assetPath.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/sdf/types.h> #include <pxr/usd/usdShade/input.h> #include <pxr/usd/usdShade/material.h> #include <pxr/usd/usdShade/output.h> #include <pxr/usd/usdShade/shader.h> #include <pxr/usd/usdUtils/pipeline.h> #include <pxr/usdImaging/usdImaging/textureUtils.h> #include <pxr/usdImaging/usdImaging/tokens.h> #include <maya/MFnDependencyNode.h> #include <maya/MGlobal.h> #include <maya/MObject.h> #include <maya/MPlug.h> #include <maya/MStatus.h> #include <maya/MString.h> #include <ghc/filesystem.hpp> #include <regex> PXR_NAMESPACE_OPEN_SCOPE class MtlxUsd_FileWriter : public MtlxUsd_BaseWriter { public: MtlxUsd_FileWriter( const MFnDependencyNode& depNodeFn, const SdfPath& usdPath, UsdMayaWriteJobContext& jobCtx); void Write(const UsdTimeCode& usdTime) override; UsdAttribute GetShadingAttributeForMayaAttrName( const TfToken& mayaAttrName, const SdfValueTypeName& typeName) override; private: int _numChannels = 4; }; PXRUSDMAYA_REGISTER_SHADER_WRITER(file, MtlxUsd_FileWriter); // clang-format off TF_DEFINE_PRIVATE_TOKENS( _tokens, // Prefix for helper nodes: ((PrimvarReaderPrefix, "MayaGeomPropValue")) ); // clang-format on MtlxUsd_FileWriter::MtlxUsd_FileWriter( const MFnDependencyNode& depNodeFn, const SdfPath& usdPath, UsdMayaWriteJobContext& jobCtx) : MtlxUsd_BaseWriter(depNodeFn, usdPath, jobCtx) { // Everything must be added in the material node graph: UsdShadeNodeGraph nodegraphSchema(GetNodeGraph()); if (!TF_VERIFY( nodegraphSchema, "Could not get UsdShadeNodeGraph at path '%s'\n", GetUsdPath().GetText())) { return; } SdfPath nodegraphPath = nodegraphSchema.GetPath(); SdfPath texPath = nodegraphPath.AppendChild(TfToken(depNodeFn.name().asChar())); // Create a image shader as the "primary" shader for this writer. UsdShadeShader texSchema = UsdShadeShader::Define(GetUsdStage(), texPath); if (!TF_VERIFY( texSchema, "Could not define UsdShadeShader at path '%s'\n", texPath.GetText())) { return; } _usdPrim = texSchema.GetPrim(); if (!TF_VERIFY( _usdPrim, "Could not get UsdPrim for UsdShadeShader at path '%s'\n", texPath.GetText())) { return; } // We need to know how many channels the texture has: MPlug texNamePlug = depNodeFn.findPlug("fileTextureName"); std::string filename(texNamePlug.asString().asChar()); // Not resolving UDIM tags. We want to actually open one of these files: UsdMayaShadingUtil::ResolveUsdTextureFileName( filename, _GetExportArgs().GetResolvedFileName(), false); _numChannels = UsdMayaShadingUtil::GetNumberOfChannels(filename); switch (_numChannels) { case 1: texSchema.CreateIdAttr(VtValue(TrMtlxTokens->ND_image_float)); texSchema.CreateOutput(TrMtlxTokens->out, SdfValueTypeNames->Float); break; case 2: texSchema.CreateIdAttr(VtValue(TrMtlxTokens->ND_image_vector2)); texSchema.CreateOutput(TrMtlxTokens->out, SdfValueTypeNames->Float2); break; case 3: texSchema.CreateIdAttr(VtValue(TrMtlxTokens->ND_image_color3)); texSchema.CreateOutput(TrMtlxTokens->out, SdfValueTypeNames->Color3f); break; case 4: texSchema.CreateIdAttr(VtValue(TrMtlxTokens->ND_image_color4)); texSchema.CreateOutput(TrMtlxTokens->out, SdfValueTypeNames->Color4f); break; default: TF_CODING_ERROR("Unsupported format"); return; } // Now create a geompropvalue reader that the image shader will use. TfToken primvarReaderName( TfStringPrintf("%s_%s", _tokens->PrimvarReaderPrefix.GetText(), depNodeFn.name().asChar())); const SdfPath primvarReaderPath = nodegraphPath.AppendChild(primvarReaderName); UsdShadeShader primvarReaderSchema = UsdShadeShader::Define(GetUsdStage(), primvarReaderPath); primvarReaderSchema.CreateIdAttr(VtValue(TrMtlxTokens->ND_geompropvalue_vector2)); UsdShadeInput varnameInput = primvarReaderSchema.CreateInput(TrMtlxTokens->geomprop, SdfValueTypeNames->String); // We expose the primvar reader varname attribute to the material to allow // easy specialization based on UV mappings to geometries: SdfPath materialPath = GetUsdPath().GetParentPath(); UsdShadeMaterial materialSchema(GetUsdStage()->GetPrimAtPath(materialPath)); while (!materialSchema && !materialPath.IsEmpty()) { materialPath = materialPath.GetParentPath(); materialSchema = UsdShadeMaterial(GetUsdStage()->GetPrimAtPath(materialPath)); } if (materialSchema) { TfToken inputName( TfStringPrintf("%s:%s", depNodeFn.name().asChar(), TrUsdTokens->varname.GetText())); UsdShadeInput materialInput = materialSchema.CreateInput(inputName, SdfValueTypeNames->String); materialInput.Set(UsdUtilsGetPrimaryUVSetName().GetString()); varnameInput.ConnectToSource(materialInput); } else { varnameInput.Set(UsdUtilsGetPrimaryUVSetName()); } UsdShadeOutput primvarReaderOutput = primvarReaderSchema.CreateOutput(TrMtlxTokens->out, SdfValueTypeNames->Float2); // TODO: Handle UV SRT with a ND_place2d_vector2 node. // Connect the output of the primvar reader to the texture coordinate // input of the UV texture. texSchema.CreateInput(TrMtlxTokens->texcoord, SdfValueTypeNames->Float2) .ConnectToSource(primvarReaderOutput); } /* virtual */ void MtlxUsd_FileWriter::Write(const UsdTimeCode& usdTime) { UsdMayaShaderWriter::Write(usdTime); MStatus status; const MFnDependencyNode depNodeFn(GetMayaObject(), &status); if (status != MS::kSuccess) { return; } UsdShadeShader shaderSchema(_usdPrim); if (!TF_VERIFY( shaderSchema, "Could not get UsdShadeShader schema for UsdPrim at path '%s'\n", _usdPrim.GetPath().GetText())) { return; } // File const MPlug fileTextureNamePlug = depNodeFn.findPlug( TrMayaTokens->fileTextureName.GetText(), /* wantNetworkedPlug = */ true, &status); if (status != MS::kSuccess) { return; } std::string fileTextureName(fileTextureNamePlug.asString(&status).asChar()); if (status != MS::kSuccess) { return; } const MPlug tilingAttr = depNodeFn.findPlug(TrMayaTokens->uvTilingMode.GetText(), true, &status); const bool isUDIM = (status == MS::kSuccess && tilingAttr.asInt() == 3); UsdMayaShadingUtil::ResolveUsdTextureFileName( fileTextureName, _GetExportArgs().GetResolvedFileName(), isUDIM); UsdShadeInput fileInput = shaderSchema.CreateInput(TrMtlxTokens->file, SdfValueTypeNames->Asset); fileInput.Set(SdfAssetPath(fileTextureName.c_str()), usdTime); // Source color space: MPlug colorSpacePlug = depNodeFn.findPlug(TrMayaTokens->colorSpace.GetText(), true, &status); if (status == MS::kSuccess) { MString colorRuleCmd; colorRuleCmd.format( "colorManagementFileRules -evaluate \"^1s\";", fileTextureNamePlug.asString()); const MString colorSpaceByRule(MGlobal::executeCommandStringResult(colorRuleCmd)); const MString colorSpace(colorSpacePlug.asString(&status)); if (status == MS::kSuccess && colorSpace != colorSpaceByRule) { fileInput.GetAttr().SetColorSpace(TfToken(colorSpace.asChar())); } } // Default Color (which needs to have a matching number of channels) const MPlug defaultColorPlug = depNodeFn.findPlug( TrMayaTokens->defaultColor.GetText(), /* wantNetworkedPlug = */ true, &status); if (status != MS::kSuccess) { return; } switch (_numChannels) { case 1: { float fallback = 0.0f; defaultColorPlug.child(0).getValue(fallback); shaderSchema.CreateInput(TrMtlxTokens->paramDefault, SdfValueTypeNames->Float) .Set(fallback, usdTime); } break; case 2: { GfVec2f fallback(0.0f, 0.0f); for (size_t i = 0u; i < GfVec2f::dimension; ++i) { defaultColorPlug.child(i).getValue(fallback[i]); } shaderSchema.CreateInput(TrMtlxTokens->paramDefault, SdfValueTypeNames->Float2) .Set(fallback, usdTime); } break; case 3: { GfVec3f fallback(0.0f, 0.0f, 0.0f); for (size_t i = 0u; i < GfVec3f::dimension; ++i) { defaultColorPlug.child(i).getValue(fallback[i]); } shaderSchema.CreateInput(TrMtlxTokens->paramDefault, SdfValueTypeNames->Color3f) .Set(fallback, usdTime); } break; case 4: { GfVec4f fallback(0.0f, 0.0f, 0.0f, 1.0f); for (size_t i = 0u; i < 3; ++i) { // defaultColor is a 3Float defaultColorPlug.child(i).getValue(fallback[i]); } shaderSchema.CreateInput(TrMtlxTokens->paramDefault, SdfValueTypeNames->Color4f) .Set(fallback, usdTime); } break; default: TF_CODING_ERROR("Unsupported format for default"); return; } // uaddressmode type="string" value="periodic" enum="constant,clamp,periodic,mirror" // vaddressmode type="string" value="periodic" enum="constant,clamp,periodic,mirror" const TfToken wrapMirror[2][3] { { TrMayaTokens->wrapU, TrMayaTokens->mirrorU, TrMtlxTokens->uaddressmode }, { TrMayaTokens->wrapV, TrMayaTokens->mirrorV, TrMtlxTokens->vaddressmode } }; for (auto wrapMirrorTriple : wrapMirror) { auto wrapUVToken = wrapMirrorTriple[0]; auto mirrorUVToken = wrapMirrorTriple[1]; auto addressModeToken = wrapMirrorTriple[2]; const MPlug wrapUVPlug = depNodeFn.findPlug( wrapUVToken.GetText(), /* wantNetworkedPlug = */ true, &status); if (status != MS::kSuccess) { return; } // Don't check if authored const bool wrapVal = wrapUVPlug.asBool(&status); if (status != MS::kSuccess) { return; } std::string outputValue; if (!wrapVal) { outputValue = TrMtlxTokens->clamp.GetString(); } else { const MPlug mirrorUVPlug = depNodeFn.findPlug( mirrorUVToken.GetText(), /* wantNetworkedPlug = */ true, &status); if (status != MS::kSuccess) { return; } const bool mirrorVal = mirrorUVPlug.asBool(&status); if (status != MS::kSuccess) { return; } outputValue = mirrorVal ? TrMtlxTokens->mirror.GetString() : TrMtlxTokens->periodic.GetString(); } shaderSchema.CreateInput(addressModeToken, SdfValueTypeNames->String) .Set(outputValue, usdTime); } // We could try to do filtertype, but the values do not map 1:1 between MaterialX and Maya } /* virtual */ UsdAttribute MtlxUsd_FileWriter::GetShadingAttributeForMayaAttrName( const TfToken& mayaAttrName, const SdfValueTypeName& typeName) { UsdShadeShader nodeSchema(_usdPrim); if (!nodeSchema) { return UsdAttribute(); } if (mayaAttrName == TrMayaTokens->outColor) { switch (_numChannels) { case 1: return AddSwizzle("rrr", _numChannels); case 2: // Monochrome + alpha: use xxx swizzle of ND_image_vector2 return AddSwizzle("xxx", _numChannels); case 3: // Non-swizzled: if (typeName == SdfValueTypeNames->Color3f) { return nodeSchema.GetOutput(TrMtlxTokens->out); } else if (typeName == SdfValueTypeNames->Float3) { return AddConversion( SdfValueTypeNames->Color3f, typeName, nodeSchema.GetOutput(TrMtlxTokens->out)); } case 4: if (typeName == SdfValueTypeNames->Color3f) { return AddSwizzle("rgb", _numChannels); } else if (typeName == SdfValueTypeNames->Float3) { return AddConversion( SdfValueTypeNames->Color3f, typeName, AddSwizzle("rgb", _numChannels)); } default: TF_CODING_ERROR("Unsupported format for outColor"); return UsdAttribute(); } } // Starting here, we handle subcomponent requests: if (_numChannels == 2) { // This will be ND_image_vector2, so requires xyz swizzles: if (mayaAttrName == TrMayaTokens->outColorR || mayaAttrName == TrMayaTokens->outColorG || mayaAttrName == TrMayaTokens->outColorB) { return AddSwizzle("x", _numChannels); } if (mayaAttrName == TrMayaTokens->outAlpha) { return AddSwizzle("y", _numChannels); } } if (mayaAttrName == TrMayaTokens->outColorR) { return AddSwizzle("r", _numChannels); } if (mayaAttrName == TrMayaTokens->outColorG) { return AddSwizzle("g", _numChannels); } if (mayaAttrName == TrMayaTokens->outColorB) { return AddSwizzle("b", _numChannels); } if (mayaAttrName == TrMayaTokens->outAlpha) { bool alphaIsLuminance = false; MStatus status; const MFnDependencyNode depNodeFn(GetMayaObject(), &status); if (status == MS::kSuccess) { MPlug plug = depNodeFn.findPlug(TrMayaTokens->alphaIsLuminance.GetText()); plug.getValue(alphaIsLuminance); } if (alphaIsLuminance || _numChannels == 3) { return AddLuminance(_numChannels); } else { return AddSwizzle("a", _numChannels); } } return UsdAttribute(); } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/plugin/adsk/scripts/mayaUSDRegisterStrings.py # Copyright 2021 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import maya.cmds as cmds import maya.mel as mel def register(key, value): registerPluginResource('mayaUsdPlugin', key, value) def getMayaUsdString(key): return getPluginResource('mayaUsdPlugin', key) def mayaUSDRegisterStrings(): # This function is called from the equivalent MEL proc # with the same name. The strings registered here and all the # ones registered from the MEL proc can be used in either # MEL or python. register("kButtonYes", "Yes") register("kButtonNo", "No") register("kDiscardStageEditsTitle", "Discard Edits on ^1s's Layers") register("kDiscardStageEditsLoadMsg", "Are you sure you want to load in a new file as the stage source?\n\nAll edits on your layers in ^1s will be discarded.") register("kDiscardStageEditsReloadMsg", "Are you sure you want to reload ^1s as the stage source?\n\nAll edits on your layers (except the session layer) in ^2s will be discarded.") register("kLoadUSDFile", "Load USD File") def registerPluginResource(pluginId, stringId, resourceStr): '''See registerPluginResource.mel in Maya. Unfortunately there is no equivalent python version of this MEL proc so we created our own version of it here.''' fullId = 'p_%s.%s' % (pluginId, stringId) if cmds.displayString(fullId, exists=True): # Issue warning if the string is already registered. msgFormat = mel.eval('uiRes("m_registerPluginResource.kNotRegistered")') msg = cmds.format(msgFormat, stringArg=(pluginId, stringId)) cmds.warning(msg) # Replace the string's value cmds.displayString(fullId, replace=True, value=resourceStr) else: # Set the string's default value. cmds.displayString(fullId, value=resourceStr) def getPluginResource(pluginId, stringId): '''See getPluginResource.mel in Maya. Unfortunately there is no equivalent python version of this MEL proc so we created our own version of it here.''' # Form full id string. # Plugin string id's are prefixed with "p_". fullId = 'p_%s.%s' % (pluginId, stringId) if cmds.displayString(fullId, exists=True): dispStr = cmds.displayString(fullId, query=True, value=True) return dispStr else: msgFormat = mel.eval('uiRes("m_getPluginResource.kLookupFailed")') msg = cmds.format(msgFormat, stringArg=(pluginId, stringId)) cmds.error(msg) <file_sep>/test/lib/ufe/testRename.py #!/usr/bin/env python # # Copyright 2019 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import fixturesUtils import mayaUtils import usdUtils import mayaUsd.ufe from pxr import Usd from maya import cmds from maya import standalone import ufe import collections import os import re import unittest # This class is used for composition arcs query. class CompositionQuery(object): def __init__(self, prim): super(CompositionQuery, self).__init__() self._prim = prim def _getDict(self, arc): dic = collections.OrderedDict() dic['ArcType'] = str(arc.GetArcType().displayName) dic['nodePath'] = str(arc.GetTargetNode().path) return dic def getData(self): query = Usd.PrimCompositionQuery(self._prim) arcValueDicList = [self._getDict(arc) for arc in query.GetCompositionArcs()] return arcValueDicList class TestObserver(ufe.Observer): def __init__(self): super(TestObserver, self).__init__() self.unexpectedNotif = 0 self.renameNotif = 0 def __call__(self, notification): if isinstance(notification, (ufe.ObjectAdd, ufe.ObjectDelete)): self.unexpectedNotif += 1 if isinstance(notification, ufe.ObjectRename): self.renameNotif += 1 def notifications(self): return self.renameNotif def receivedUnexpectedNotif(self): return self.unexpectedNotif > 0 class RenameTestCase(unittest.TestCase): '''Test renaming a UFE scene item and its ancestors. Renaming should not affect UFE lookup, including renaming the proxy shape. ''' pluginsLoaded = False @classmethod def setUpClass(cls): fixturesUtils.readOnlySetUpClass(__file__, loadPlugin=False) if not cls.pluginsLoaded: cls.pluginsLoaded = mayaUtils.isMayaUsdPluginLoaded() @classmethod def tearDownClass(cls): cmds.file(new=True, force=True) standalone.uninitialize() def setUp(self): ''' Called initially to set up the Maya test environment ''' # Load plugins self.assertTrue(self.pluginsLoaded) # Open top_layer.ma scene in testSamples mayaUtils.openTopLayerScene() # Clear selection to start off cmds.select(clear=True) def testRenameProxyShape(self): '''Rename proxy shape, UFE lookup should succeed.''' mayaSegment = mayaUtils.createUfePathSegment( "|transform1|proxyShape1") usdSegment = usdUtils.createUfePathSegment("/Room_set/Props/Ball_35") ball35Path = ufe.Path([mayaSegment, usdSegment]) ball35PathStr = ','.join( [str(segment) for segment in ball35Path.segments]) # Because of difference in Python binding systems (pybind11 for UFE, # Boost Python for mayaUsd and USD), need to pass in strings to # mayaUsd functions. Multi-segment UFE paths need to have # comma-separated segments. def assertStageAndPrimAccess( proxyShapeSegment, primUfePathStr, primSegment): proxyShapePathStr = str(proxyShapeSegment) stage = mayaUsd.ufe.getStage(proxyShapePathStr) prim = mayaUsd.ufe.ufePathToPrim(primUfePathStr) stagePath = mayaUsd.ufe.stagePath(stage) self.assertIsNotNone(stage) self.assertEqual(stagePath, proxyShapePathStr) self.assertTrue(prim.IsValid()) self.assertEqual(str(prim.GetPath()), str(primSegment)) assertStageAndPrimAccess(mayaSegment, ball35PathStr, usdSegment) # Rename the proxy shape node itself. Stage and prim access should # still be valid, with the new path. mayaSegment = mayaUtils.createUfePathSegment( "|transform1|potato") cmds.rename('|transform1|proxyShape1', 'potato') self.assertEqual(len(cmds.ls('potato')), 1) ball35Path = ufe.Path([mayaSegment, usdSegment]) ball35PathStr = ','.join( [str(segment) for segment in ball35Path.segments]) assertStageAndPrimAccess(mayaSegment, ball35PathStr, usdSegment) def testRename(self): # open tree.ma scene in testSamples mayaUtils.openTreeScene() # clear selection to start off cmds.select(clear=True) # select a USD object. mayaPathSegment = mayaUtils.createUfePathSegment('|Tree_usd|Tree_usdShape') usdPathSegment = usdUtils.createUfePathSegment('/TreeBase') treebasePath = ufe.Path([mayaPathSegment, usdPathSegment]) treebaseItem = ufe.Hierarchy.createItem(treebasePath) ufe.GlobalSelection.get().append(treebaseItem) # get the USD stage stage = mayaUsd.ufe.getStage(str(mayaPathSegment)) # by default edit target is set to the Rootlayer. self.assertEqual(stage.GetEditTarget().GetLayer(), stage.GetRootLayer()) self.assertTrue(stage.GetRootLayer().GetPrimAtPath("/TreeBase")) # get default prim defaultPrim = stage.GetDefaultPrim() self.assertEqual(defaultPrim.GetName(), 'TreeBase') # TreeBase has two childern: leavesXform, trunk assert len(defaultPrim.GetChildren()) == 2 # get prim spec for defaultPrim primspec = stage.GetEditTarget().GetPrimSpecForScenePath(defaultPrim.GetPath()); # set primspec name primspec.name = "TreeBase_potato" # get the renamed prim renamedPrim = stage.GetPrimAtPath('/TreeBase_potato') # One must use the SdfLayer API for setting the defaultPrim when you rename the prim it identifies. stage.SetDefaultPrim(renamedPrim); # get defaultPrim again defaultPrim = stage.GetDefaultPrim() self.assertEqual(defaultPrim.GetName(), 'TreeBase_potato') # make sure we have a valid prims after the primspec rename assert stage.GetPrimAtPath('/TreeBase_potato') assert stage.GetPrimAtPath('/TreeBase_potato/leavesXform') # prim should be called TreeBase_potato potatoPrim = stage.GetPrimAtPath('/TreeBase_potato') self.assertEqual(potatoPrim.GetName(), 'TreeBase_potato') # prim should be called leaves leavesPrimSpec = stage.GetObjectAtPath('/TreeBase_potato/leavesXform/leaves') self.assertEqual(leavesPrimSpec.GetName(), 'leaves') def testRenameUndo(self): '''Rename USD node.''' # open usdCylinder.ma scene in testSamples mayaUtils.openCylinderScene() # clear selection to start off cmds.select(clear=True) # select a USD object. mayaPathSegment = mayaUtils.createUfePathSegment('|mayaUsdTransform|shape') usdPathSegment = usdUtils.createUfePathSegment('/pCylinder1') cylinderPath = ufe.Path([mayaPathSegment, usdPathSegment]) cylinderItem = ufe.Hierarchy.createItem(cylinderPath) cylinderHierarchy = ufe.Hierarchy.hierarchy(cylinderItem) propsItem = cylinderHierarchy.parent() propsHierarchy = ufe.Hierarchy.hierarchy(propsItem) propsChildrenPre = propsHierarchy.children() ufe.GlobalSelection.get().append(cylinderItem) # get the USD stage stage = mayaUsd.ufe.getStage(str(mayaPathSegment)) # check GetLayerStack behavior self.assertEqual(stage.GetLayerStack()[0], stage.GetSessionLayer()) self.assertEqual(stage.GetEditTarget().GetLayer(), stage.GetRootLayer()) # by default edit target is set to the Rootlayer. self.assertEqual(stage.GetEditTarget().GetLayer(), stage.GetRootLayer()) # rename cylinderItemType = cylinderItem.nodeType() newName = 'pCylinder1_Renamed' cmds.rename(newName) # The renamed item is in the selection. snIter = iter(ufe.GlobalSelection.get()) pCylinder1Item = next(snIter) pCylinder1RenName = str(pCylinder1Item.path().back()) self.assertEqual(pCylinder1RenName, newName) propsChildren = propsHierarchy.children() self.assertEqual(len(propsChildren), len(propsChildrenPre)) self.assertIn(pCylinder1Item, propsChildren) cmds.undo() self.assertEqual(cylinderItemType, ufe.GlobalSelection.get().back().nodeType()) def childrenNames(children): return [str(child.path().back()) for child in children] propsHierarchy = ufe.Hierarchy.hierarchy(propsItem) propsChildren = propsHierarchy.children() propsChildrenNames = childrenNames(propsChildren) self.assertNotIn(pCylinder1RenName, propsChildrenNames) self.assertIn('pCylinder1', propsChildrenNames) self.assertEqual(len(propsChildren), len(propsChildrenPre)) cmds.redo() self.assertEqual(cylinderItemType, ufe.GlobalSelection.get().back().nodeType()) propsHierarchy = ufe.Hierarchy.hierarchy(propsItem) propsChildren = propsHierarchy.children() propsChildrenNames = childrenNames(propsChildren) self.assertIn(pCylinder1RenName, propsChildrenNames) self.assertNotIn('pCylinder1', propsChildrenNames) self.assertEqual(len(propsChildren), len(propsChildrenPre)) def testRenameRestrictionSameLayerDef(self): '''Restrict renaming USD node. Cannot rename a prim defined on another layer.''' # select a USD object. mayaPathSegment = mayaUtils.createUfePathSegment('|transform1|proxyShape1') usdPathSegment = usdUtils.createUfePathSegment('/Room_set/Props/Ball_35') ball35Path = ufe.Path([mayaPathSegment, usdPathSegment]) ball35Item = ufe.Hierarchy.createItem(ball35Path) ufe.GlobalSelection.get().append(ball35Item) # get the USD stage stage = mayaUsd.ufe.getStage(str(mayaPathSegment)) # check GetLayerStack behavior self.assertEqual(stage.GetLayerStack()[0], stage.GetSessionLayer()) self.assertEqual(stage.GetEditTarget().GetLayer(), stage.GetRootLayer()) # expect the exception happens with self.assertRaises(RuntimeError): newName = 'Ball_35_Renamed' cmds.rename(newName) def testRenameRestrictionHasSpecs(self): '''Restrict renaming USD node. Cannot rename a node that doesn't contribute to the final composed prim''' # open appleBite.ma scene in testSamples mayaUtils.openAppleBiteScene() # clear selection to start off cmds.select(clear=True) # select a USD object. mayaPathSegment = mayaUtils.createUfePathSegment('|Asset_flattened_instancing_and_class_removed_usd|Asset_flattened_instancing_and_class_removed_usdShape') usdPathSegment = usdUtils.createUfePathSegment('/apple/payload/geo') geoPath = ufe.Path([mayaPathSegment, usdPathSegment]) geoItem = ufe.Hierarchy.createItem(geoPath) ufe.GlobalSelection.get().append(geoItem) # get the USD stage stage = mayaUsd.ufe.getStage(str(mayaPathSegment)) # rename "/apple/payload/geo" to "/apple/payload/geo_renamed" # expect the exception happens with self.assertRaises(RuntimeError): cmds.rename("geo_renamed") def testRenameUniqueName(self): # open tree.ma scene in testSamples mayaUtils.openTreeScene() # clear selection to start off cmds.select(clear=True) # select a USD object. mayaPathSegment = mayaUtils.createUfePathSegment('|Tree_usd|Tree_usdShape') usdPathSegment = usdUtils.createUfePathSegment('/TreeBase/trunk') trunkPath = ufe.Path([mayaPathSegment, usdPathSegment]) trunkItem = ufe.Hierarchy.createItem(trunkPath) ufe.GlobalSelection.get().append(trunkItem) # get the USD stage stage = mayaUsd.ufe.getStage(str(mayaPathSegment)) # by default edit target is set to the Rootlayer. self.assertEqual(stage.GetEditTarget().GetLayer(), stage.GetRootLayer()) # rename `/TreeBase/trunk` to `/TreeBase/leavesXform` cmds.rename("leavesXform") # get the prim item = ufe.GlobalSelection.get().front() usdPrim = stage.GetPrimAtPath(str(item.path().segments[1])) self.assertTrue(usdPrim) # the new prim name is expected to be "leavesXform1" assert ([x for x in stage.Traverse()] == [stage.GetPrimAtPath("/TreeBase"), stage.GetPrimAtPath("/TreeBase/leavesXform"), stage.GetPrimAtPath("/TreeBase/leavesXform/leaves"), stage.GetPrimAtPath("/TreeBase/leavesXform1"),]) def testRenameSpecialCharacter(self): # open twoSpheres.ma scene in testSamples mayaUtils.openTwoSpheresScene() # clear selection to start off cmds.select(clear=True) # select a USD object. mayaPathSegment = mayaUtils.createUfePathSegment('|usdSphereParent|usdSphereParentShape') usdPathSegment = usdUtils.createUfePathSegment('/sphereXform/sphere') basePath = ufe.Path([mayaPathSegment, usdPathSegment]) usdSphereItem = ufe.Hierarchy.createItem(basePath) ufe.GlobalSelection.get().append(usdSphereItem) # get the USD stage stage = mayaUsd.ufe.getStage(str(mayaPathSegment)) # by default edit target is set to the Rootlayer. self.assertEqual(stage.GetEditTarget().GetLayer(), stage.GetRootLayer()) # rename with special chars newNameWithSpecialChars = '!@#%$@$=sph^e.re_*()<>}021|' cmds.rename(newNameWithSpecialChars) # get the prim pSphereItem = ufe.GlobalSelection.get().front() usdPrim = stage.GetPrimAtPath(str(pSphereItem.path().segments[1])) self.assertTrue(usdPrim) # prim names are not allowed to have special characters except '_' regex = re.compile('[@!#$%^&*()<>?/\|}{~:]') self.assertFalse(regex.search(usdPrim.GetName())) # prim names are not allowed to start with digits newNameStartingWithDigit = '09123Potato' cmds.rename(newNameStartingWithDigit) self.assertFalse(usdPrim.GetName()[0].isdigit()) def testRenameNotifications(self): '''Rename a USD node and test for the UFE notifications.''' # open usdCylinder.ma scene in testSamples mayaUtils.openCylinderScene() # clear selection to start off cmds.select(clear=True) # select a USD object. mayaPathSegment = mayaUtils.createUfePathSegment('|mayaUsdTransform|shape') usdPathSegment = usdUtils.createUfePathSegment('/pCylinder1') cylinderPath = ufe.Path([mayaPathSegment, usdPathSegment]) cylinderItem = ufe.Hierarchy.createItem(cylinderPath) ufe.GlobalSelection.get().append(cylinderItem) # get the USD stage stage = mayaUsd.ufe.getStage(str(mayaPathSegment)) # set the edit target to the root layer stage.SetEditTarget(stage.GetRootLayer()) self.assertEqual(stage.GetEditTarget().GetLayer(), stage.GetRootLayer()) # Create our UFE notification observer ufeObs = TestObserver() # We start off with no observers self.assertFalse(ufe.Scene.hasObserver(ufeObs)) # Add the UFE observer we want to test ufe.Scene.addObserver(ufeObs) # rename newName = 'pCylinder1_Renamed' cmds.rename(newName) # After the rename we should have 1 rename notif and no unexepected notifs. self.assertEqual(ufeObs.notifications(), 1) self.assertFalse(ufeObs.receivedUnexpectedNotif()) def testRenameRestrictionVariant(self): '''Renaming prims inside a variantSet is not allowed.''' cmds.file(new=True, force=True) # open Variant.ma scene in testSamples mayaUtils.openVariantSetScene() # stage mayaPathSegment = mayaUtils.createUfePathSegment('|Variant_usd|Variant_usdShape') stage = mayaUsd.ufe.getStage(str(mayaPathSegment)) # first check that we have a VariantSets objectPrim = stage.GetPrimAtPath('/objects') self.assertTrue(objectPrim.HasVariantSets()) # Geom usdPathSegment = usdUtils.createUfePathSegment('/objects/Geom') geomPath = ufe.Path([mayaPathSegment, usdPathSegment]) geomItem = ufe.Hierarchy.createItem(geomPath) geomPrim = mayaUsd.ufe.ufePathToPrim(ufe.PathString.string(geomPath)) # Small_Potato smallPotatoUsdPathSegment = usdUtils.createUfePathSegment('/objects/Geom/Small_Potato') smallPotatoPath = ufe.Path([mayaPathSegment, smallPotatoUsdPathSegment]) smallPotatoItem = ufe.Hierarchy.createItem(smallPotatoPath) smallPotatoPrim = mayaUsd.ufe.ufePathToPrim(ufe.PathString.string(smallPotatoPath)) # add Geom to selection list ufe.GlobalSelection.get().append(geomItem) # get prim spec for Geom prim primspecGeom = stage.GetEditTarget().GetPrimSpecForScenePath(geomPrim.GetPath()); # primSpec is expected to be None self.assertIsNone(primspecGeom) # rename "/objects/Geom" to "/objects/Geom_something" # expect the exception happens with self.assertRaises(RuntimeError): cmds.rename("Geom_something") # clear selection cmds.select(clear=True) # add Small_Potato to selection list ufe.GlobalSelection.get().append(smallPotatoItem) # get prim spec for Small_Potato prim primspecSmallPotato = stage.GetEditTarget().GetPrimSpecForScenePath(smallPotatoPrim.GetPath()); # primSpec is expected to be None self.assertIsNone(primspecSmallPotato) # rename "/objects/Geom/Small_Potato" to "/objects/Geom/Small_Potato_something" # expect the exception happens with self.assertRaises(RuntimeError): cmds.rename("Small_Potato_something") def testAutomaticRenameCompArcs(self): ''' Verify that SdfPath update happens automatically for "internal reference", "inherit", "specialize" after the rename. ''' cmds.file(new=True, force=True) # open compositionArcs.ma scene in testSamples mayaUtils.openCompositionArcsScene() # stage mayaPathSegment = mayaUtils.createUfePathSegment('|CompositionArcs_usd|CompositionArcs_usdShape') stage = mayaUsd.ufe.getStage(str(mayaPathSegment)) # first check for ArcType, nodePath values. I am only interested in the composition Arc other than "root". compQueryPrimA = CompositionQuery(stage.GetPrimAtPath('/objects/geos/cube_A')) self.assertTrue(list(compQueryPrimA.getData()[1].values()), ['reference', '/objects/geos/cube']) compQueryPrimB = CompositionQuery(stage.GetPrimAtPath('/objects/geos/cube_B')) self.assertTrue(list(compQueryPrimB.getData()[1].values()), ['inherit', '/objects/geos/cube']) compQueryPrimC = CompositionQuery(stage.GetPrimAtPath('/objects/geos/cube_C')) self.assertTrue(list(compQueryPrimC.getData()[1].values()), ['specialize', '/objects/geos/cube']) # rename /objects/geos/cube ---> /objects/geos/cube_banana cubePath = ufe.PathString.path('|CompositionArcs_usd|CompositionArcs_usdShape,/objects/geos/cube') cubeItem = ufe.Hierarchy.createItem(cubePath) ufe.GlobalSelection.get().append(cubeItem) cmds.rename("cube_banana") # check for ArcType, nodePath values again. # expect nodePath to be updated for all the arc compositions compQueryPrimA = CompositionQuery(stage.GetPrimAtPath('/objects/geos/cube_A')) self.assertTrue(list(compQueryPrimA.getData()[1].values()), ['reference', '/objects/geos/cube_banana']) compQueryPrimB = CompositionQuery(stage.GetPrimAtPath('/objects/geos/cube_B')) self.assertTrue(list(compQueryPrimB.getData()[1].values()), ['inherit', '/objects/geos/cube_banana']) compQueryPrimC = CompositionQuery(stage.GetPrimAtPath('/objects/geos/cube_C')) self.assertTrue(list(compQueryPrimC.getData()[1].values()), ['specialize', '/objects/geos/cube_banana']) # rename /objects/geos ---> /objects/geos_cucumber geosPath = ufe.PathString.path('|CompositionArcs_usd|CompositionArcs_usdShape,/objects/geos') geosItem = ufe.Hierarchy.createItem(geosPath) cmds.select(clear=True) ufe.GlobalSelection.get().append(geosItem) cmds.rename("geos_cucumber") # check for ArcType, nodePath values again. # expect nodePath to be updated for all the arc compositions compQueryPrimA = CompositionQuery(stage.GetPrimAtPath('/objects/geos_cucumber/cube_A')) self.assertTrue(list(compQueryPrimA.getData()[1].values()), ['reference', '/objects/geos_cucumber/cube_banana']) compQueryPrimB = CompositionQuery(stage.GetPrimAtPath('/objects/geos_cucumber/cube_B')) self.assertTrue(list(compQueryPrimB.getData()[1].values()), ['inherit', '/objects/geos_cucumber/cube_banana']) compQueryPrimC = CompositionQuery(stage.GetPrimAtPath('/objects/geos_cucumber/cube_C')) self.assertTrue(list(compQueryPrimC.getData()[1].values()), ['specialize', '/objects/geos_cucumber/cube_banana']) # rename /objects ---> /objects_eggplant objectsPath = ufe.PathString.path('|CompositionArcs_usd|CompositionArcs_usdShape,/objects') objectsItem = ufe.Hierarchy.createItem(objectsPath) cmds.select(clear=True) ufe.GlobalSelection.get().append(objectsItem) cmds.rename("objects_eggplant") # check for ArcType, nodePath values again. # expect nodePath to be updated for all the arc compositions compQueryPrimA = CompositionQuery(stage.GetPrimAtPath('/objects_eggplant/geos_cucumber/cube_A')) self.assertTrue(list(compQueryPrimA.getData()[1].values()), ['reference', '/objects_eggplant/geos_cucumber/cube_banana']) compQueryPrimB = CompositionQuery(stage.GetPrimAtPath('/objects_eggplant/geos_cucumber/cube_B')) self.assertTrue(list(compQueryPrimB.getData()[1].values()), ['inherit', '/objects_eggplant/geos_cucumber/cube_banana']) compQueryPrimC = CompositionQuery(stage.GetPrimAtPath('/objects_eggplant/geos_cucumber/cube_C')) self.assertTrue(list(compQueryPrimC.getData()[1].values()), ['specialize', '/objects_eggplant/geos_cucumber/cube_banana']) if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/lib/mayaUsd/listeners/stageNoticeListener.cpp // // Copyright 2018 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "stageNoticeListener.h" #include <pxr/base/tf/notice.h> #include <pxr/base/tf/weakBase.h> #include <pxr/usd/usd/notice.h> #include <pxr/usd/usd/stage.h> PXR_NAMESPACE_OPEN_SCOPE /* virtual */ UsdMayaStageNoticeListener::~UsdMayaStageNoticeListener() { if (_stageContentsChangedKey.IsValid()) { TfNotice::Revoke(_stageContentsChangedKey); } if (_stageObjectsChangedKey.IsValid()) { TfNotice::Revoke(_stageObjectsChangedKey); } } void UsdMayaStageNoticeListener::SetStage(const UsdStageWeakPtr& stage) { _stage = stage; _UpdateStageContentsChangedRegistration(); } void UsdMayaStageNoticeListener::SetStageContentsChangedCallback( const StageContentsChangedCallback& callback) { _stageContentsChangedCallback = callback; _UpdateStageContentsChangedRegistration(); } void UsdMayaStageNoticeListener::SetStageObjectsChangedCallback( const StageObjectsChangedCallback& callback) { _stageObjectsChangedCallback = callback; _UpdateStageContentsChangedRegistration(); } void UsdMayaStageNoticeListener::_UpdateStageContentsChangedRegistration() { if (_stage && _stageContentsChangedCallback) { // Register for notices if we're not already listening. if (!_stageContentsChangedKey.IsValid()) { _stageContentsChangedKey = TfNotice::Register( TfCreateWeakPtr(this), &UsdMayaStageNoticeListener::_OnStageContentsChanged); } } else { // Either the stage or the callback is invalid, so stop listening for // notices. if (_stageContentsChangedKey.IsValid()) { TfNotice::Revoke(_stageContentsChangedKey); } } if (_stage && _stageObjectsChangedCallback) { // Register for notices if we're not already listening. if (!_stageObjectsChangedKey.IsValid()) { _stageObjectsChangedKey = TfNotice::Register( TfCreateWeakPtr(this), &UsdMayaStageNoticeListener::_OnStageObjectsChanged, _stage); } } else { // Either the stage or the callback is invalid, so stop listening for // notices. if (_stageObjectsChangedKey.IsValid()) { TfNotice::Revoke(_stageObjectsChangedKey); } } } void UsdMayaStageNoticeListener::_OnStageContentsChanged( const UsdNotice::StageContentsChanged& notice) const { if (notice.GetStage() == _stage && _stageContentsChangedCallback) { _stageContentsChangedCallback(notice); } } void UsdMayaStageNoticeListener::_OnStageObjectsChanged( const UsdNotice::ObjectsChanged& notice, const UsdStageWeakPtr& sender) const { if (notice.GetStage() == _stage && _stageObjectsChangedCallback) { _stageObjectsChangedCallback(notice); } } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/test/CMakeLists.txt add_subdirectory(lib) add_subdirectory(testSamples) add_subdirectory(testUtils) <file_sep>/plugin/al/schemas/codegenTemplates/api.h // // Copyright 2017 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef{ { Upper(libraryName) } } _API_H #define{ { Upper(libraryName) } } _API_H #include <pxr/base/arch/export.h> #if defined(PXR_STATIC) #define{ { Upper(libraryName) } } _API #define{ { Upper(libraryName) } } _API_TEMPLATE_CLASS(...) #define{ { Upper(libraryName) } } _API_TEMPLATE_STRUCT(...) #define{ { Upper(libraryName) } } _LOCAL #else #if defined({ { Upper(libraryName) } } _EXPORTS) #define{ { Upper(libraryName) } } _API ARCH_EXPORT #define{ { Upper(libraryName) } } _API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__) #define{ { Upper(libraryName) } } _API_TEMPLATE_STRUCT(...) \ ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__) #else #define{ { Upper(libraryName) } } _API ARCH_IMPORT #define{ { Upper(libraryName) } } _API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__) #define{ { Upper(libraryName) } } _API_TEMPLATE_STRUCT(...) \ ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__) #endif #define{ { Upper(libraryName) } } _LOCAL ARCH_HIDDEN #endif #endif <file_sep>/lib/usd/CMakeLists.txt if(BUILD_HDMAYA) add_subdirectory(hdMaya) endif() add_subdirectory(pxrUsdPreviewSurface) add_subdirectory(translators) add_subdirectory(schemas) add_subdirectory(utils) if(Qt5_FOUND) add_subdirectory(ui) endif() #install top level plugInfo.json that includes the configured plugInfo.json set(INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/usd ) install(CODE "file(WRITE \"${CMAKE_CURRENT_BINARY_DIR}/lib/usd/plugInfo.json\" \"{\n \\\"Includes\\\": [ \\\"*/resources/\\\" ]\n}\")" ) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/lib/usd/plugInfo.json DESTINATION ${INSTALL_DESTINATION} ) <file_sep>/lib/CMakeLists.txt add_subdirectory(mayaUsd) add_subdirectory(usd)<file_sep>/test/lib/usd/utils/CMakeLists.txt set(TARGET_NAME DiffCore) add_executable(${TARGET_NAME}) # ----------------------------------------------------------------------------- # sources # ----------------------------------------------------------------------------- target_sources(${TARGET_NAME} PRIVATE main.cpp test_DiffCore.cpp ) # ----------------------------------------------------------------------------- # compiler configuration # ----------------------------------------------------------------------------- mayaUsd_compile_config(${TARGET_NAME}) # ----------------------------------------------------------------------------- # link libraries # ----------------------------------------------------------------------------- target_link_libraries(${TARGET_NAME} PRIVATE GTest::GTest mayaUsdUtils ) # ----------------------------------------------------------------------------- # unit tests # ----------------------------------------------------------------------------- mayaUsd_add_test(${TARGET_NAME} COMMAND $<TARGET_FILE:${TARGET_NAME}> ENV "LD_LIBRARY_PATH=${ADDITIONAL_LD_LIBRARY_PATH}" ) <file_sep>/test/testSamples/CMakeLists.txt set(TARGET_NAME PYTHON_TEST_SAMPLES) add_custom_target(${TARGET_NAME} ALL) # Copy all of the resources in this directory to a # "test/testSamples" subdirectory under the top-level build directory. mayaUsd_copyDirectory(${TARGET_NAME} SOURCE ${CMAKE_CURRENT_SOURCE_DIR} DESTINATION ${CMAKE_BINARY_DIR}/test/testSamples EXCLUDE "*.txt" ) <file_sep>/lib/mayaUsd/ufe/UsdObject3d.h // =========================================================================== // Copyright 2019 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // =========================================================================== #pragma once #include <mayaUsd/base/api.h> #include <mayaUsd/ufe/UsdSceneItem.h> #include <ufe/object3d.h> namespace MAYAUSD_NS_DEF { namespace ufe { //! \brief USD run-time 3D object interface /*! This class implements the Object3d interface for USD prims. */ class MAYAUSD_CORE_PUBLIC UsdObject3d : public Ufe::Object3d { public: using Ptr = std::shared_ptr<UsdObject3d>; UsdObject3d(const UsdSceneItem::Ptr& item); ~UsdObject3d() override; // Delete the copy/move constructors assignment operators. UsdObject3d(const UsdObject3d&) = delete; UsdObject3d& operator=(const UsdObject3d&) = delete; UsdObject3d(UsdObject3d&&) = delete; UsdObject3d& operator=(UsdObject3d&&) = delete; //! Create a UsdObject3d. static UsdObject3d::Ptr create(const UsdSceneItem::Ptr& item); // Ufe::Object3d overrides Ufe::SceneItem::Ptr sceneItem() const override; Ufe::BBox3d boundingBox() const override; bool visibility() const override; void setVisibility(bool vis) override; Ufe::UndoableCommand::Ptr setVisibleCmd(bool vis) override; private: UsdSceneItem::Ptr fItem; PXR_NS::UsdPrim fPrim; }; // UsdObject3d } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/test/lib/usd/translators/testUsdExportRoots.py #!/usr/bin/env mayapy # # Copyright 2021 Luma # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import unittest from maya import cmds from maya import standalone from pxr import Usd from pxr import UsdGeom from pxr import Vt from pxr import Gf import fixturesUtils class testUsdExportRoot(unittest.TestCase): @classmethod def setUpClass(cls): inputPath = fixturesUtils.setUpClass(__file__) filePath = os.path.join(inputPath, "UsdExportRootsTest", "UsdExportRootsTest.ma") cmds.file(filePath, force=True, open=True) @classmethod def tearDownClass(cls): standalone.uninitialize() def doExportImportOneMethod(self, method, shouldError=False, root=None, selection=None): if isinstance(root, str): root = [root] if isinstance(selection, str): selection = [selection] name = 'UsdExportRoot_root-{root}_sel-{sel}'.format(root='-'.join(root or []), sel='-'.join(selection or [])) if method == 'cmd': name += '.usda' elif method == 'translator': # the translator seems to be only able to export .usd - or at least, # I couldn't find an option to do .usda instead... name += '.usd' usdFile = os.path.abspath(name) if method == 'cmd': exportMethod = cmds.mayaUSDExport args = () kwargs = { 'file': usdFile, 'mergeTransformAndShape': True, 'shadingMode': 'useRegistry', } if root: kwargs['exportRoots'] = root if selection: kwargs['selection'] = 1 cmds.select(selection) else: exportMethod = cmds.file args = (usdFile,) kwargs = { 'type': 'USD Export', 'f': 1, } if root: kwargs['options'] = 'exportRoots={}'.format(','.join(root)) if selection: kwargs['exportSelected'] = 1 cmds.select(selection) else: kwargs['exportAll'] = 1 if shouldError: self.assertRaises(RuntimeError, exportMethod, *args, **kwargs) return exportMethod(*args, **kwargs) return Usd.Stage.Open(usdFile) def doExportImportTest(self, validator, shouldError=False, root=None, selection=None): stage = self.doExportImportOneMethod('cmd', shouldError=shouldError, root=root, selection=selection) validator(stage) stage = self.doExportImportOneMethod('translator', shouldError=shouldError, root=root, selection=selection) validator(stage) def assertPrim(self, stage, path, type): prim = stage.GetPrimAtPath(path) self.assertTrue(prim.IsValid()) self.assertEqual(prim.GetTypeName(), type) def assertNotPrim(self, stage, path): self.assertFalse(stage.GetPrimAtPath(path).IsValid()) def testNonOverlappingSelectionRoot(self): # test that the command errors if we give it a root + selection that # have no intersection def validator(stage): pass self.doExportImportTest(validator, shouldError=True, root='Mid', selection='OtherTop') def testExportRoot_rootTop_selNone(self): def validator(stage): self.assertPrim(stage, '/Top/Mid/Cube', 'Mesh') self.assertPrim(stage, '/Top/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/OtherTop') self.assertPrim(stage, '/Top/OtherMid', 'Xform') self.assertPrim(stage, '/Top/Mid/OtherLowest', 'Xform') self.doExportImportTest(validator, root='Top') def testExportRoot_rootTop_selTop(self): def validator(stage): self.assertPrim(stage, '/Top/Mid/Cube', 'Mesh') self.assertPrim(stage, '/Top/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/OtherTop') self.assertPrim(stage, '/Top/OtherMid', 'Xform') self.assertPrim(stage, '/Top/Mid/OtherLowest', 'Xform') self.doExportImportTest(validator, root='Top', selection='Top') def testExportRoot_rootTop_selMid(self): def validator(stage): self.assertPrim(stage, '/Top/Mid/Cube', 'Mesh') self.assertPrim(stage, '/Top/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/Top/OtherMid') self.assertPrim(stage, '/Top/Mid/OtherLowest', 'Xform') self.doExportImportTest(validator, root='Top', selection='Mid') def testExportRoot_rootTop_selCube(self): def validator(stage): self.assertPrim(stage, '/Top/Mid/Cube', 'Mesh') self.assertPrim(stage, '/Top/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/Top/OtherMid') self.assertNotPrim(stage, '/Top/Mid/OtherLowest') self.doExportImportTest(validator, root='Top', selection='Cube') def testExportRoot_rootMid_selNone(self): def validator(stage): self.assertPrim(stage, '/Mid/Cube', 'Mesh') self.assertPrim(stage, '/Mid/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertPrim(stage, '/Mid/OtherLowest', 'Xform') self.doExportImportTest(validator, root='Mid') def testExportRoot_rootMid_selTop(self): def validator(stage): self.assertPrim(stage, '/Mid/Cube', 'Mesh') self.assertPrim(stage, '/Mid/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertPrim(stage, '/Mid/OtherLowest', 'Xform') self.doExportImportTest(validator, root='Mid', selection='Top') def testExportRoot_rootMid_selMid(self): def validator(stage): self.assertPrim(stage, '/Mid/Cube', 'Mesh') self.assertPrim(stage, '/Mid/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertPrim(stage, '/Mid/OtherLowest', 'Xform') self.doExportImportTest(validator, root='Mid', selection='Mid') def testExportRoot_rootMid_selCube(self): def validator(stage): self.assertPrim(stage, '/Mid/Cube', 'Mesh') self.assertPrim(stage, '/Mid/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertNotPrim(stage, '/Mid/OtherLowest') self.doExportImportTest(validator, root='Mid', selection='Cube') def testExportRoot_rootCube_selNone(self): def validator(stage): self.assertPrim(stage, '/Cube', 'Mesh') self.assertPrim(stage, '/Cube/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/Mid') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertNotPrim(stage, '/OtherLowest') self.doExportImportTest(validator, root='Cube') def testExportRoot_rootCube_selTop(self): def validator(stage): self.assertPrim(stage, '/Cube', 'Mesh') self.assertPrim(stage, '/Cube/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/Mid') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertNotPrim(stage, '/OtherLowest') self.doExportImportTest(validator, root='Cube', selection='Top') def testExportRoot_rootCube_selMid(self): def validator(stage): self.assertPrim(stage, '/Cube', 'Mesh') self.assertPrim(stage, '/Cube/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/Mid') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertNotPrim(stage, '/OtherLowest') self.doExportImportTest(validator, root='Cube', selection='Mid') def testExportRoot_rootCube_selCube(self): def validator(stage): self.assertPrim(stage, '/Cube', 'Mesh') self.assertPrim(stage, '/Cube/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/Mid') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertNotPrim(stage, '/OtherLowest') self.doExportImportTest(validator, root='Cube', selection='Cube') def testExportRoot_rootEMPTY_selCube(self): def validator(stage): self.assertPrim(stage, '/Cube', 'Mesh') self.assertPrim(stage, '/Cube/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/Mid') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertNotPrim(stage, '/OtherLowest') self.doExportImportTest(validator, root='', selection='Cube') def testExportRoot_rootEMPTY_selCubeOtherLowest(self): def validator(stage): self.assertPrim(stage, '/Cube', 'Mesh') self.assertPrim(stage, '/Cube/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/Mid') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertPrim(stage, '/OtherLowest', 'Xform') self.doExportImportTest(validator, root='', selection=['Cube','OtherLowest']) def testExportRoot_rootCubeOtherLowest_selNone(self): def validator(stage): self.assertPrim(stage, '/Cube', 'Mesh') self.assertPrim(stage, '/Cube/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/Mid') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertPrim(stage, '/OtherLowest', 'Xform') self.doExportImportTest(validator, root=['Cube','OtherLowest']) def testExportRoot_rootCubeOtherLowest_selCube(self): def validator(stage): self.assertPrim(stage, '/Cube', 'Mesh') self.assertPrim(stage, '/Cube/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/Mid') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertNotPrim(stage, '/OtherLowest') self.doExportImportTest(validator, root=['Cube','OtherLowest'], selection='Cube') def testExportRoot_rootCubeOtherLowest_selCubeOtherLowest(self): def validator(stage): self.assertPrim(stage, '/Mid/Cube', 'Mesh') self.assertPrim(stage, '/Mid/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertPrim(stage, '/OtherLowest', 'Xform') self.doExportImportTest(validator, root=['Mid','OtherLowest'], selection=['Cube','OtherLowest']) def testExportRoot_rootCubeCube1_selCubeCube1(self): # test that two objects from sibling hierarchies export correctly with materials def validator(stage): self.assertPrim(stage, '/Cube', 'Mesh') self.assertPrim(stage, '/Cube/Looks/lambert2SG/lambert2', 'Shader') self.assertNotPrim(stage, '/Top') self.assertNotPrim(stage, '/OtherTop') self.assertNotPrim(stage, '/OtherMid') self.assertNotPrim(stage, '/OtherLowest') self.assertPrim(stage, '/Cube1', 'Mesh') self.assertPrim(stage, '/Cube1/Looks/lambert3SG/lambert3', 'Shader') self.doExportImportTest(validator, root=['Cube','Cube1'], selection=['Cube','Cube1']) def testDagPathValidation(self): # test that the command errors if we give it an invalid dag path def validator(stage): pass self.doExportImportTest(validator, shouldError=True, root='NoneExisting', selection='OtherTop') if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/plugin/al/lib/AL_USDMaya/AL/usdmaya/SelectabilityDB.cpp // // Copyright 2017 Animal Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <AL/usdmaya/SelectabilityDB.h> namespace AL { namespace usdmaya { //---------------------------------------------------------------------------------------------------------------------- bool SelectabilityDB::isPathUnselectable(const SdfPath& path) const { auto begin = m_unselectablePaths.begin(); auto end = m_unselectablePaths.end(); auto foundPathEntry = end; auto root = SdfPath::AbsoluteRootPath(); auto temp(path); while (temp != root) { foundPathEntry = std::lower_bound(begin, foundPathEntry, temp); if (foundPathEntry != end && temp == *foundPathEntry) { return true; } temp = temp.GetParentPath(); } return false; } //---------------------------------------------------------------------------------------------------------------------- void SelectabilityDB::removePathsAsUnselectable(const SdfPathVector& paths) { for (SdfPath path : paths) { removeUnselectablePath(path); } auto end = m_unselectablePaths.end(); auto start = m_unselectablePaths.begin(); for (SdfPath path : paths) { auto temp = std::lower_bound(start, end, path); if (temp != end) { if (*temp == path) { temp = m_unselectablePaths.erase(temp); } start = temp; } } } //---------------------------------------------------------------------------------------------------------------------- void SelectabilityDB::removePathAsUnselectable(const SdfPath& path) { removeUnselectablePath(path); } //---------------------------------------------------------------------------------------------------------------------- void SelectabilityDB::addPathsAsUnselectable(const SdfPathVector& paths) { auto end = m_unselectablePaths.end(); auto start = m_unselectablePaths.begin(); for (auto iter = paths.begin(), last = paths.end(); iter != last; ++iter) { start = std::lower_bound(start, end, *iter); // If we've hit the end, we can simply append the remaining elements in one go. if (start == end) { m_unselectablePaths.insert(end, iter, last); return; } if (*start != *iter) { m_unselectablePaths.insert(start, *iter); } } } //---------------------------------------------------------------------------------------------------------------------- void SelectabilityDB::addPathAsUnselectable(const SdfPath& path) { addUnselectablePath(path); } //---------------------------------------------------------------------------------------------------------------------- bool SelectabilityDB::removeUnselectablePath(const SdfPath& path) { auto end = m_unselectablePaths.end(); auto foundPathEntry = std::lower_bound(m_unselectablePaths.begin(), end, path); if (foundPathEntry != end && *foundPathEntry == path) { m_unselectablePaths.erase(foundPathEntry); return true; } return false; } //---------------------------------------------------------------------------------------------------------------------- bool SelectabilityDB::addUnselectablePath(const SdfPath& path) { auto end = m_unselectablePaths.end(); auto iter = std::lower_bound(m_unselectablePaths.begin(), end, path); if (iter != end) { if (*iter != path) { m_unselectablePaths.insert(iter, path); return true; } } else { m_unselectablePaths.push_back(path); return true; } return false; } //---------------------------------------------------------------------------------------------------------------------- } // namespace usdmaya } // namespace AL //----------------------------------------------------------------------------------------------------------------------<file_sep>/lib/mayaUsd/ufe/UsdContextOps.cpp // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "UsdContextOps.h" #include "private/UfeNotifGuard.h" #include <mayaUsd/ufe/UsdObject3d.h> #include <mayaUsd/ufe/UsdSceneItem.h> #include <mayaUsd/ufe/UsdUndoAddNewPrimCommand.h> #include <mayaUsd/ufe/Utils.h> #include <mayaUsd/utils/util.h> #include <pxr/base/plug/plugin.h> #include <pxr/base/plug/registry.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/sdf/reference.h> #include <pxr/usd/usd/common.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usd/references.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usd/variantSets.h> #include <pxr/usd/usdGeom/tokens.h> #include <maya/MGlobal.h> #include <ufe/attribute.h> #include <ufe/attributes.h> #include <ufe/globalSelection.h> #include <ufe/object3d.h> #include <ufe/observableSelection.h> #include <ufe/path.h> #include <algorithm> #include <cassert> #include <utility> #include <vector> PXR_NAMESPACE_USING_DIRECTIVE namespace { // Ufe::ContextItem strings // - the "Item" describe the operation to be performed. // - the "Label" is used in the context menu (can be localized). // - the "Image" is used for icon in the context menu. Directly used std::string // for these so the emplace_back() will choose the right constructor. With char[] // it would convert that param to a bool and choose the wrong constructor. #ifdef WANT_QT_BUILD static constexpr char kUSDLayerEditorItem[] = "USD Layer Editor"; static constexpr char kUSDLayerEditorLabel[] = "USD Layer Editor..."; #endif static const std::string kUSDLayerEditorImage { "USD_generic.png" }; static constexpr char kUSDLoadItem[] = "Load"; static constexpr char kUSDLoadLabel[] = "Load"; static constexpr char kUSDLoadWithDescendantsItem[] = "Load with Descendants"; static constexpr char kUSDLoadWithDescendantsLabel[] = "Load with Descendants"; static constexpr char kUSDUnloadItem[] = "Unload"; static constexpr char kUSDUnloadLabel[] = "Unload"; static constexpr char kUSDVariantSetsItem[] = "Variant Sets"; static constexpr char kUSDVariantSetsLabel[] = "Variant Sets"; static constexpr char kUSDToggleVisibilityItem[] = "Toggle Visibility"; static constexpr char kUSDMakeVisibleLabel[] = "Make Visible"; static constexpr char kUSDMakeInvisibleLabel[] = "Make Invisible"; static constexpr char kUSDToggleActiveStateItem[] = "Toggle Active State"; static constexpr char kUSDActivatePrimLabel[] = "Activate Prim"; static constexpr char kUSDDeactivatePrimLabel[] = "Deactivate Prim"; static constexpr char kUSDAddNewPrimItem[] = "Add New Prim"; static constexpr char kUSDAddNewPrimLabel[] = "Add New Prim"; static constexpr char kUSDDefPrimItem[] = "Def"; static constexpr char kUSDDefPrimLabel[] = "Def"; static const std::string kUSDDefPrimImage { "out_USD_Def.png" }; static constexpr char kUSDScopePrimItem[] = "Scope"; static constexpr char kUSDScopePrimLabel[] = "Scope"; static const std::string kUSDScopePrimImage { "out_USD_Scope.png" }; static constexpr char kUSDXformPrimItem[] = "Xform"; static constexpr char kUSDXformPrimLabel[] = "Xform"; static const std::string kUSDXformPrimImage { "out_USD_UsdGeomXformable.png" }; static constexpr char kUSDCapsulePrimItem[] = "Capsule"; static constexpr char kUSDCapsulePrimLabel[] = "Capsule"; static const std::string kUSDCapsulePrimImage { "out_USD_Capsule.png" }; static constexpr char kUSDConePrimItem[] = "Cone"; static constexpr char kUSDConePrimLabel[] = "Cone"; static const std::string kUSDConePrimImage { "out_USD_Cone.png" }; static constexpr char kUSDCubePrimItem[] = "Cube"; static constexpr char kUSDCubePrimLabel[] = "Cube"; static const std::string kUSDCubePrimImage { "out_USD_Cube.png" }; static constexpr char kUSDCylinderPrimItem[] = "Cylinder"; static constexpr char kUSDCylinderPrimLabel[] = "Cylinder"; static const std::string kUSDCylinderPrimImage { "out_USD_Cylinder.png" }; static constexpr char kUSDSpherePrimItem[] = "Sphere"; static constexpr char kUSDSpherePrimLabel[] = "Sphere"; static const std::string kUSDSpherePrimImage { "out_USD_Sphere.png" }; #if PXR_VERSION >= 2008 static constexpr char kAllRegisteredTypesItem[] = "All Registered"; static constexpr char kAllRegisteredTypesLabel[] = "All Registered"; // Grouping and name mapping for registered schema plugins static const std::vector<std::string> kSchemaPluginNames = { "usdGeom", "usdLux", "mayaUsd_Schemas", "usdMedia", "usdRender", "usdRi", "usdShade", "usdSkel", "usdUI", "usdVol", "AL_USDMayaSchemasTest", "AL_USDMayaSchemas", }; // clang-format off static const std::vector<std::string> kSchemaNiceNames = { "Geometry", "Lighting", "Maya Reference", "Media", "Render", "RenderMan", "Shading", "Skeleton", "UI", "Volumes", "", // Skip legacy AL schemas "", // Skip legacy AL schemas }; // clang-format on #endif //! \brief Undoable command for loading a USD prim. class LoadUndoableCommand : public Ufe::UndoableCommand { public: LoadUndoableCommand(const UsdPrim& prim, UsdLoadPolicy policy) : _stage(prim.GetStage()) , _primPath(prim.GetPath()) , _oldLoadSet(prim.GetStage()->GetLoadSet()) , _policy(policy) { } void undo() override { if (!_stage) { return; } _stage->LoadAndUnload(_oldLoadSet, SdfPathSet({ _primPath })); } void redo() override { if (!_stage) { return; } _stage->Load(_primPath, _policy); } private: const UsdStageWeakPtr _stage; const SdfPath _primPath; const SdfPathSet _oldLoadSet; const UsdLoadPolicy _policy; }; //! \brief Undoable command for unloading a USD prim. class UnloadUndoableCommand : public Ufe::UndoableCommand { public: UnloadUndoableCommand(const UsdPrim& prim) : _stage(prim.GetStage()) , _primPath({ prim.GetPath() }) , _oldLoadSet(prim.GetStage()->GetLoadSet()) { } void undo() override { if (!_stage) { return; } _stage->LoadAndUnload(_oldLoadSet, SdfPathSet()); } void redo() override { if (!_stage) { return; } _stage->Unload(_primPath); } private: const UsdStageWeakPtr _stage; const SdfPath _primPath; const SdfPathSet _oldLoadSet; }; //! \brief Undoable command for variant selection change class SetVariantSelectionUndoableCommand : public Ufe::UndoableCommand { public: SetVariantSelectionUndoableCommand( const Ufe::Path& path, const UsdPrim& prim, const Ufe::ContextOps::ItemPath& itemPath) : _path(path) , _varSet(prim.GetVariantSets().GetVariantSet(itemPath[1])) , _oldSelection(_varSet.GetVariantSelection()) , _newSelection(itemPath[2]) { } void undo() override { _varSet.SetVariantSelection(_oldSelection); // Restore the saved selection to the global selection. If a saved // selection item started with the prim's path, re-create it. auto globalSn = Ufe::GlobalSelection::get(); globalSn->replaceWith(MayaUsd::ufe::recreateDescendants(_savedSn, _path)); } void redo() override { // Make a copy of the global selection, to restore it on unmute. auto globalSn = Ufe::GlobalSelection::get(); _savedSn.replaceWith(*globalSn); // Filter the global selection, removing items below our prim. globalSn->replaceWith(MayaUsd::ufe::removeDescendants(_savedSn, _path)); _varSet.SetVariantSelection(_newSelection); } private: const Ufe::Path _path; UsdVariantSet _varSet; const std::string _oldSelection; const std::string _newSelection; Ufe::Selection _savedSn; // For global selection save and restore. }; //! \brief Undoable command for prim active state change class ToggleActiveStateCommand : public Ufe::UndoableCommand { public: ToggleActiveStateCommand(const UsdPrim& prim) { _stage = prim.GetStage(); _primPath = prim.GetPath(); _active = prim.IsActive(); } void undo() override { if (_stage) { UsdPrim prim = _stage->GetPrimAtPath(_primPath); if (prim.IsValid()) { MayaUsd::ufe::InAddOrDeleteOperation ad; prim.SetActive(_active); } } } void redo() override { if (_stage) { UsdPrim prim = _stage->GetPrimAtPath(_primPath); if (prim.IsValid()) { MayaUsd::ufe::InAddOrDeleteOperation ad; prim.SetActive(!_active); } } } private: PXR_NS::UsdStageWeakPtr _stage; PXR_NS::SdfPath _primPath; bool _active; }; const char* selectUSDFileScript = R"( global proc string SelectUSDFileForAddReference() { string $result[] = `fileDialog2 -fileMode 1 -caption "Add Reference to USD Prim" -fileFilter "USD Files (*.usd *.usda *.usdc);;*.usd;;*.usda;;*.usdc"`; if (0 == size($result)) return ""; else return $result[0]; } SelectUSDFileForAddReference(); )"; const char* clearAllReferencesConfirmScript = R"( global proc string ClearAllUSDReferencesConfirm() { return `confirmDialog -title "Remove All References" -message "Removing all references from USD prim. Are you sure?" -button "Yes" -button "No" -defaultButton "Yes" -cancelButton "No" -dismissString "No"`; } ClearAllUSDReferencesConfirm(); )"; class AddReferenceUndoableCommand : public Ufe::UndoableCommand { public: static const std::string commandName; AddReferenceUndoableCommand(const UsdPrim& prim, const std::string& filePath) : _prim(prim) , _sdfRef() , _filePath(filePath) { } void undo() override { if (_prim.IsValid()) { UsdReferences primRefs = _prim.GetReferences(); primRefs.RemoveReference(_sdfRef); } } void redo() override { if (_prim.IsValid()) { _sdfRef = SdfReference(_filePath); UsdReferences primRefs = _prim.GetReferences(); primRefs.AddReference(_sdfRef); } } private: UsdPrim _prim; SdfReference _sdfRef; const std::string _filePath; }; const std::string AddReferenceUndoableCommand::commandName("Add Reference..."); class ClearAllReferencesUndoableCommand : public Ufe::UndoableCommand { public: static const std::string commandName; static const MString cancelRemoval; ClearAllReferencesUndoableCommand(const UsdPrim& prim) : _prim(prim) { } void undo() override { } void redo() override { if (_prim.IsValid()) { UsdReferences primRefs = _prim.GetReferences(); primRefs.ClearReferences(); } } private: UsdPrim _prim; }; const std::string ClearAllReferencesUndoableCommand::commandName("Clear All References"); const MString ClearAllReferencesUndoableCommand::cancelRemoval("No"); std::vector<std::pair<const char* const, const char* const>> _computeLoadAndUnloadItems(const UsdPrim& prim) { std::vector<std::pair<const char* const, const char* const>> itemLabelPairs; const bool isInPrototype = #if PXR_VERSION >= 2011 prim.IsInPrototype(); #else prim.IsInMaster(); #endif if (!prim.IsActive() || isInPrototype) { return itemLabelPairs; } UsdStageWeakPtr stage = prim.GetStage(); const SdfPathSet stageLoadSet = stage->GetLoadSet(); const SdfPathSet loadableSet = stage->FindLoadable(prim.GetPath()); // Intersect the set of what *can* be loaded at or below this prim path // with the set of of what *is* loaded on the stage. The resulting set will // contain all paths that are loaded at or below this prim path. SdfPathSet loadedSet; std::set_intersection( loadableSet.cbegin(), loadableSet.cend(), stageLoadSet.cbegin(), stageLoadSet.cend(), std::inserter(loadedSet, loadedSet.end())); // Subtract the set of what *is* loaded on the stage from the set of what // *can* be loaded at or below this prim path. The resulting set will // contain all paths that are loadable, but not currently loaded, at or // below this prim path. SdfPathSet unloadedSet; std::set_difference( loadableSet.cbegin(), loadableSet.cend(), stageLoadSet.cbegin(), stageLoadSet.cend(), std::inserter(unloadedSet, unloadedSet.end())); if (!unloadedSet.empty()) { // Loading without descendants is only meaningful for context ops when // the current prim has an unloaded payload. if (prim.HasPayload() && !prim.IsLoaded()) { itemLabelPairs.emplace_back(std::make_pair(kUSDLoadItem, kUSDLoadLabel)); } // We always add an item for loading with descendants when there are // unloaded paths at or below the current prim, since we may be in one // of the following situations: // - The current prim has a payload that is unloaded, and we don't know // whether loading it will introduce more payloads in descendants, so // we offer the choice to also load those or not. // - The current prim has a payload that is loaded, so there must be // paths below it that are still unloaded. // - The current prim does not have a payload, so there must be paths // below it that are still unloaded. itemLabelPairs.emplace_back( std::make_pair(kUSDLoadWithDescendantsItem, kUSDLoadWithDescendantsLabel)); } // If anything is loaded at this prim path or any of its descendants, add // an item for unload. if (!loadedSet.empty()) { itemLabelPairs.emplace_back(std::make_pair(kUSDUnloadItem, kUSDUnloadLabel)); } return itemLabelPairs; } #if PXR_VERSION >= 2008 //! \brief Get groups of concrete schema prim types to list dynamically in the UI static const std::vector<MayaUsd::ufe::SchemaTypeGroup> getConcretePrimTypes(bool sorted) { std::vector<MayaUsd::ufe::SchemaTypeGroup> groups; // Query all the available types PlugRegistry& plugReg = PlugRegistry::GetInstance(); std::set<TfType> schemaTypes; plugReg.GetAllDerivedTypes<UsdSchemaBase>(&schemaTypes); UsdSchemaRegistry& schemaReg = UsdSchemaRegistry::GetInstance(); for (auto t : schemaTypes) { if (!schemaReg.IsConcrete(t)) { continue; } auto plugin = plugReg.GetPluginForType(t); if (!plugin) { continue; } // For every plugin we check if there's a nice name registered and use that instead auto plugin_name = plugin->GetName(); auto name_itr = std::find(kSchemaPluginNames.begin(), kSchemaPluginNames.end(), plugin_name); if (name_itr != kSchemaPluginNames.end()) { plugin_name = kSchemaNiceNames[name_itr - kSchemaPluginNames.begin()]; } // We don't list empty names. This allows hiding certain plugins too. if (plugin_name.empty()) { continue; } auto type_name = UsdSchemaRegistry::GetConcreteSchemaTypeName(t); // Find or create the schema group and add to it auto group_itr = find(begin(groups), end(groups), plugin_name); if (group_itr == groups.end()) { MayaUsd::ufe::SchemaTypeGroup group { plugin_name }; group._types.emplace_back(type_name); groups.emplace_back(group); } else { groups[group_itr - groups.begin()]._types.emplace_back(type_name); } } if (sorted) { for (size_t i = 0; i < groups.size(); ++i) { auto group = groups[i]; std::sort(group._types.begin(), group._types.end()); groups[i] = group; } std::sort(groups.begin(), groups.end(), [](const auto& lhs, const auto& rhs) { return lhs._name < rhs._name; }); } return groups; } #endif } // namespace namespace MAYAUSD_NS_DEF { namespace ufe { #if PXR_VERSION >= 2008 std::vector<SchemaTypeGroup> UsdContextOps::schemaTypeGroups = {}; #endif UsdContextOps::UsdContextOps(const UsdSceneItem::Ptr& item) : Ufe::ContextOps() , fItem(item) { } UsdContextOps::~UsdContextOps() { } /*static*/ UsdContextOps::Ptr UsdContextOps::create(const UsdSceneItem::Ptr& item) { return std::make_shared<UsdContextOps>(item); } void UsdContextOps::setItem(const UsdSceneItem::Ptr& item) { fItem = item; } const Ufe::Path& UsdContextOps::path() const { return fItem->path(); } //------------------------------------------------------------------------------ // Ufe::ContextOps overrides //------------------------------------------------------------------------------ Ufe::SceneItem::Ptr UsdContextOps::sceneItem() const { return fItem; } Ufe::ContextOps::Items UsdContextOps::getItems(const Ufe::ContextOps::ItemPath& itemPath) const { Ufe::ContextOps::Items items; if (itemPath.empty()) { #ifdef WANT_QT_BUILD // Top-level item - USD Layer editor (for all context op types). // Only available when building with Qt enabled. items.emplace_back(kUSDLayerEditorItem, kUSDLayerEditorLabel, kUSDLayerEditorImage); items.emplace_back(Ufe::ContextItem::kSeparator); #endif // Top-level items (do not add for gateway type node): if (!fIsAGatewayType) { // Working set management (load and unload): const auto itemLabelPairs = _computeLoadAndUnloadItems(prim()); for (const auto& itemLabelPair : itemLabelPairs) { items.emplace_back(itemLabelPair.first, itemLabelPair.second); } // Variant sets: if (prim().HasVariantSets()) { items.emplace_back( kUSDVariantSetsItem, kUSDVariantSetsLabel, Ufe::ContextItem::kHasChildren); } // Visibility: // If the item has a visibility attribute, add menu item to change visibility. // Note: certain prim types such as shaders & materials don't support visibility. auto attributes = Ufe::Attributes::attributes(sceneItem()); if (attributes && attributes->hasAttribute(UsdGeomTokens->visibility)) { auto visibility = std::dynamic_pointer_cast<Ufe::AttributeEnumString>( attributes->attribute(UsdGeomTokens->visibility)); if (visibility) { auto current = visibility->get(); const std::string l = (current == UsdGeomTokens->invisible) ? std::string(kUSDMakeVisibleLabel) : std::string(kUSDMakeInvisibleLabel); items.emplace_back(kUSDToggleVisibilityItem, l); } } // Prim active state: items.emplace_back( kUSDToggleActiveStateItem, prim().IsActive() ? kUSDDeactivatePrimLabel : kUSDActivatePrimLabel); } // Top level item - Add New Prim (for all context op types). items.emplace_back(kUSDAddNewPrimItem, kUSDAddNewPrimLabel, Ufe::ContextItem::kHasChildren); if (!fIsAGatewayType) { items.emplace_back( AddReferenceUndoableCommand::commandName, AddReferenceUndoableCommand::commandName); items.emplace_back( ClearAllReferencesUndoableCommand::commandName, ClearAllReferencesUndoableCommand::commandName); } } else { if (itemPath[0] == kUSDVariantSetsItem) { UsdVariantSets varSets = prim().GetVariantSets(); std::vector<std::string> varSetsNames; varSets.GetNames(&varSetsNames); if (itemPath.size() == 1u) { // Variant sets list. for (auto i = varSetsNames.crbegin(); i != varSetsNames.crend(); ++i) { items.emplace_back(*i, *i, Ufe::ContextItem::kHasChildren); } } else { // Variants of a given variant set. Second item in the path is // the variant set name. assert(itemPath.size() == 2u); UsdVariantSet varSet = varSets.GetVariantSet(itemPath[1]); auto selected = varSet.GetVariantSelection(); const auto varNames = varSet.GetVariantNames(); for (const auto& vn : varNames) { const bool checked(vn == selected); items.emplace_back( vn, vn, Ufe::ContextItem::kNoChildren, Ufe::ContextItem::kCheckable, checked, Ufe::ContextItem::kExclusive); } } // Variants of a variant set } // Variant sets else if (itemPath[0] == kUSDAddNewPrimItem) { if (itemPath.size() == 1u) { // Root setup items.emplace_back( kUSDDefPrimItem, kUSDDefPrimLabel, kUSDDefPrimImage); // typeless prim items.emplace_back(kUSDScopePrimItem, kUSDScopePrimLabel, kUSDScopePrimImage); items.emplace_back(kUSDXformPrimItem, kUSDXformPrimLabel, kUSDXformPrimImage); items.emplace_back(Ufe::ContextItem::kSeparator); items.emplace_back(kUSDCapsulePrimItem, kUSDCapsulePrimLabel, kUSDCapsulePrimImage); items.emplace_back(kUSDConePrimItem, kUSDConePrimLabel, kUSDConePrimImage); items.emplace_back(kUSDCubePrimItem, kUSDCubePrimLabel, kUSDCubePrimImage); items.emplace_back( kUSDCylinderPrimItem, kUSDCylinderPrimLabel, kUSDCylinderPrimImage); items.emplace_back(kUSDSpherePrimItem, kUSDSpherePrimLabel, kUSDSpherePrimImage); #if PXR_VERSION >= 2008 items.emplace_back(Ufe::ContextItem::kSeparator); items.emplace_back( kAllRegisteredTypesItem, kAllRegisteredTypesLabel, Ufe::ContextItem::kHasChildren); } else if (itemPath.size() == 2u) { // Sub Menus if (itemPath[1] == kAllRegisteredTypesItem) { // List the Registered schema plugins // Load this each time the menu is called in case plugins were loaded // in between invocations. // However we cache it so the submenus don't need to re-query schemaTypeGroups = getConcretePrimTypes(true); for (auto schema : schemaTypeGroups) { items.emplace_back( schema._name.c_str(), schema._name.c_str(), Ufe::ContextItem::kHasChildren); } } } else if (itemPath.size() == 3u) { if (itemPath[1] == kAllRegisteredTypesItem) { // List the items that belong to this schema plugin for (auto schema : schemaTypeGroups) { if (schema._name != itemPath[2]) { continue; } for (auto t : schema._types) { items.emplace_back(t, t); } } } #endif } // If USD >= 20.08, submenus end here. Otherwise end of Root Setup } // Add New Prim Item } // Top-level items return items; } Ufe::UndoableCommand::Ptr UsdContextOps::doOpCmd(const ItemPath& itemPath) { // Empty argument means no operation was specified, error. if (itemPath.empty()) { TF_CODING_ERROR("Empty path means no operation was specified"); return nullptr; } if (itemPath[0u] == kUSDLoadItem || itemPath[0u] == kUSDLoadWithDescendantsItem) { const UsdLoadPolicy policy = (itemPath[0u] == kUSDLoadWithDescendantsItem) ? UsdLoadWithDescendants : UsdLoadWithoutDescendants; return std::make_shared<LoadUndoableCommand>(prim(), policy); } else if (itemPath[0u] == kUSDUnloadItem) { return std::make_shared<UnloadUndoableCommand>(prim()); } else if (itemPath[0] == kUSDVariantSetsItem) { // Operation is to set a variant in a variant set. Need both the // variant set and the variant as arguments to the operation. if (itemPath.size() != 3u) { TF_CODING_ERROR("Wrong number of arguments"); return nullptr; } // At this point we know we have enough arguments to execute the // operation. return std::make_shared<SetVariantSelectionUndoableCommand>(path(), prim(), itemPath); } // Variant sets else if (itemPath[0] == kUSDToggleVisibilityItem) { auto object3d = UsdObject3d::create(fItem); TF_AXIOM(object3d); auto current = object3d->visibility(); return object3d->setVisibleCmd(!current); } // Visibility else if (itemPath[0] == kUSDToggleActiveStateItem) { return std::make_shared<ToggleActiveStateCommand>(prim()); } // ActiveState else if (!itemPath.empty() && (itemPath[0] == kUSDAddNewPrimItem)) { // Operation is to create a new prim of the type specified. if (itemPath.size() < 2u) { TF_CODING_ERROR("Wrong number of arguments"); return nullptr; } // At this point we know the last item in the itemPath is the prim type to create auto primType = itemPath[itemPath.size() - 1]; return UsdUndoAddNewPrimCommand::create(fItem, primType, primType); #ifdef WANT_QT_BUILD // When building without Qt there is no LayerEditor } else if (itemPath[0] == kUSDLayerEditorItem) { // Just open the editor directly and return null so we don't have undo. auto ufePath = ufe::stagePath(prim().GetStage()); auto noWorld = ufePath.popHead().string(); auto dagPath = UsdMayaUtil::nameToDagPath(noWorld); auto shapePath = dagPath.fullPathName(); MString script; script.format("mayaUsdLayerEditorWindow -proxyShape ^1s mayaUsdLayerEditor", shapePath); MGlobal::executeCommand(script); return nullptr; #endif } else if (itemPath[0] == AddReferenceUndoableCommand::commandName) { MString fileRef = MGlobal::executeCommandStringResult(selectUSDFileScript); std::string path = UsdMayaUtil::convert(fileRef); if (path.empty()) return nullptr; return std::make_shared<AddReferenceUndoableCommand>(prim(), path); } else if (itemPath[0] == ClearAllReferencesUndoableCommand::commandName) { MString confirmation = MGlobal::executeCommandStringResult(clearAllReferencesConfirmScript); if (ClearAllReferencesUndoableCommand::cancelRemoval == confirmation) return nullptr; return std::make_shared<ClearAllReferencesUndoableCommand>(prim()); } return nullptr; } } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/test/testUtils/usdUtils.py #!/usr/bin/env python # # Copyright 2019 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ Helper functions regarding USD that will be used throughout the test. """ import mayaUsd.ufe import ufe import ufeUtils from pxr import Usd from pxr import UsdGeom usdSeparator = '/' def createUfePathSegment(usdPath): """ Create an UFE path from a given usd path. Args: usdPath (str): The usd path to use Returns : PathSegment of the given usdPath """ return ufe.PathSegment(usdPath, mayaUsd.ufe.getUsdRunTimeId(), usdSeparator) def getPrimFromSceneItem(item): if ufeUtils.ufeFeatureSetVersion() >= 2: rawItem = item.getRawAddress() prim = mayaUsd.ufe.getPrimFromRawItem(rawItem) return prim else: return Usd.Prim() def createAnimatedHierarchy(stage): """ Create simple hierarchy in the stage: /ParentA /Sphere /Cube /ParenB Entire ParentA hierarchy will receive time samples on translate for time 1 and 100 """ parentA = "/ParentA" parentB = "/ParentB" childSphere = "/ParentA/Sphere" childCube = "/ParentA/Cube" parentPrimA = stage.DefinePrim(parentA, 'Xform') parentPrimB = stage.DefinePrim(parentB, 'Xform') childPrimSphere = stage.DefinePrim(childSphere, 'Sphere') childPrimCube = stage.DefinePrim(childCube, 'Cube') UsdGeom.XformCommonAPI(parentPrimA).SetRotate((0,0,0)) UsdGeom.XformCommonAPI(parentPrimB).SetTranslate((1,10,0)) time1 = Usd.TimeCode(1.) UsdGeom.XformCommonAPI(parentPrimA).SetTranslate((0,0,0),time1) UsdGeom.XformCommonAPI(childPrimSphere).SetTranslate((5,0,0),time1) UsdGeom.XformCommonAPI(childPrimCube).SetTranslate((0,0,5),time1) time2 = Usd.TimeCode(100.) UsdGeom.XformCommonAPI(parentPrimA).SetTranslate((0,5,0),time2) UsdGeom.XformCommonAPI(childPrimSphere).SetTranslate((-5,0,0),time2) UsdGeom.XformCommonAPI(childPrimCube).SetTranslate((0,0,-5),time2) <file_sep>/lib/mayaUsd/ufe/UsdAttributes.h // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include <mayaUsd/base/api.h> #include <mayaUsd/ufe/UsdAttribute.h> #include <mayaUsd/ufe/UsdSceneItem.h> #include <pxr/usd/usd/prim.h> #include <ufe/attributes.h> #include <unordered_map> namespace MAYAUSD_NS_DEF { namespace ufe { //! \brief Interface for USD Attributes. class UsdAttributes : public Ufe::Attributes { public: typedef std::shared_ptr<UsdAttributes> Ptr; UsdAttributes(const UsdSceneItem::Ptr& item); ~UsdAttributes() override; // Delete the copy/move constructors assignment operators. UsdAttributes(const UsdAttributes&) = delete; UsdAttributes& operator=(const UsdAttributes&) = delete; UsdAttributes(UsdAttributes&&) = delete; UsdAttributes& operator=(UsdAttributes&&) = delete; //! Create a UsdAttributes. static UsdAttributes::Ptr create(const UsdSceneItem::Ptr& item); // Ufe::Attributes overrides Ufe::SceneItem::Ptr sceneItem() const override; Ufe::Attribute::Type attributeType(const std::string& name) override; Ufe::Attribute::Ptr attribute(const std::string& name) override; std::vector<std::string> attributeNames() const override; bool hasAttribute(const std::string& name) const override; private: Ufe::Attribute::Type getUfeTypeForAttribute(const PXR_NS::UsdAttribute& usdAttr) const; private: UsdSceneItem::Ptr fItem; PXR_NS::UsdPrim fPrim; typedef std::unordered_map<std::string, Ufe::Attribute::Ptr> AttributeMap; AttributeMap fAttributes; }; // UsdAttributes } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/lib/mayaUsd/ufe/wrapUtils.cpp // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <mayaUsd/ufe/Global.h> #include <mayaUsd/ufe/UsdSceneItem.h> #include <mayaUsd/ufe/Utils.h> #include <pxr/base/tf/stringUtils.h> #include <pxr/usd/sdf/path.h> #include <pxr/usdImaging/usdImaging/delegate.h> #include <ufe/path.h> #include <ufe/pathSegment.h> #include <ufe/rtid.h> #include <ufe/runTimeMgr.h> #ifdef UFE_V2_FEATURES_AVAILABLE #include <ufe/pathString.h> #endif #include <boost/python.hpp> #include <string> using namespace MayaUsd; using namespace boost::python; #ifdef UFE_V2_FEATURES_AVAILABLE PXR_NS::UsdPrim getPrimFromRawItem(uint64_t rawItem) { Ufe::SceneItem* item = reinterpret_cast<Ufe::SceneItem*>(rawItem); ufe::UsdSceneItem* usdItem = dynamic_cast<ufe::UsdSceneItem*>(item); if (nullptr != usdItem) { return usdItem->prim(); } return PXR_NS::UsdPrim(); } std::string getNodeNameFromRawItem(uint64_t rawItem) { std::string name; Ufe::SceneItem* item = reinterpret_cast<Ufe::SceneItem*>(rawItem); if (nullptr != item) name = item->nodeName(); return name; } std::string getNodeTypeFromRawItem(uint64_t rawItem) { std::string type; Ufe::SceneItem* item = reinterpret_cast<Ufe::SceneItem*>(rawItem); if (nullptr != item) { // Prepend the name of the runtime manager of this item to the type. type = Ufe::RunTimeMgr::instance().getName(item->runTimeId()) + item->nodeType(); } return type; } #endif PXR_NS::UsdStageWeakPtr getStage(const std::string& ufePathString) { #ifdef UFE_V2_FEATURES_AVAILABLE return ufe::getStage(Ufe::PathString::path(ufePathString)); #else // This function works on a single-segment path, i.e. the Maya Dag path // segment to the proxy shape. We know the Maya run-time ID is 1, // separator is '|'. // The helper function proxyShapeHandle() assumes Maya path starts // with "|world" and will pop it off. So make sure our string has it. // Note: std::string starts_with only added for C++20. So use diff trick. std::string proxyPath; if (ufePathString.rfind("|world", 0) == std::string::npos) { proxyPath = "|world" + ufePathString; } else { proxyPath = ufePathString; } return ufe::getStage(Ufe::Path(Ufe::PathSegment(proxyPath, 1, '|'))); #endif } std::string stagePath(PXR_NS::UsdStageWeakPtr stage) { // Proxy shape node's UFE path is a single segment, so no need to separate // segments with commas. return ufe::stagePath(stage).string(); } std::string usdPathToUfePathSegment( const PXR_NS::SdfPath& usdPath, int instanceIndex = PXR_NS::UsdImagingDelegate::ALL_INSTANCES) { return ufe::usdPathToUfePathSegment(usdPath, instanceIndex).string(); } #ifndef UFE_V2_FEATURES_AVAILABLE // Helper function for UFE versions before version 2 for converting a path // string to a UFE path. static Ufe::Path _UfeV1StringToUsdPath(const std::string& ufePathString) { Ufe::Path path; // The path string is a list of segment strings separated by ',' comma // separator. auto segmentStrings = PXR_NS::TfStringTokenize(ufePathString, ","); // If there are fewer than two segments, there cannot be a USD segment, so // return an invalid path. if (segmentStrings.size() < 2u) { return path; } // We have the path string split into segments. Build up the Ufe::Path one // segment at a time. The path segment separator is the first character // of each segment. We know that USD's separator is '/' and Maya's // separator is '|', so use a map to get the corresponding UFE run-time ID. static std::map<char, Ufe::Rtid> sepToRtid = { { '/', ufe::getUsdRunTimeId() }, { '|', ufe::getMayaRunTimeId() } }; for (size_t i = 0u; i < segmentStrings.size(); ++i) { const auto& segmentString = segmentStrings[i]; char sep = segmentString[0u]; path = path + Ufe::PathSegment(segmentString, sepToRtid.at(sep), sep); } return path; } #endif PXR_NS::UsdTimeCode getTime(const std::string& pathStr) { const Ufe::Path path = #ifdef UFE_V2_FEATURES_AVAILABLE Ufe::PathString::path( #else _UfeV1StringToUsdPath( #endif pathStr); return ufe::getTime(path); } std::string stripInstanceIndexFromUfePath(const std::string& ufePathString) { #ifdef UFE_V2_FEATURES_AVAILABLE const Ufe::Path path = Ufe::PathString::path(ufePathString); return Ufe::PathString::string(ufe::stripInstanceIndexFromUfePath(path)); #else const Ufe::Path path = _UfeV1StringToUsdPath(ufePathString); return ufe::stripInstanceIndexFromUfePath(path).string(); #endif } PXR_NS::UsdPrim ufePathToPrim(const std::string& ufePathString) { #ifdef UFE_V2_FEATURES_AVAILABLE return ufe::ufePathToPrim(Ufe::PathString::path(ufePathString)); #else Ufe::Path path = _UfeV1StringToUsdPath(ufePathString); // If there are fewer than two segments, there cannot be a USD segment, so // return an invalid UsdPrim. if (path.getSegments().size() < 2u) { return PXR_NS::UsdPrim(); } return ufe::ufePathToPrim(path); #endif } int ufePathToInstanceIndex(const std::string& ufePathString) { #ifdef UFE_V2_FEATURES_AVAILABLE return ufe::ufePathToInstanceIndex(Ufe::PathString::path(ufePathString)); #else Ufe::Path path = _UfeV1StringToUsdPath(ufePathString); // If there are fewer than two segments, there cannot be a USD segment, so // return ALL_INSTANCES. if (path.getSegments().size() < 2u) { return PXR_NS::UsdImagingDelegate::ALL_INSTANCES; } return ufe::ufePathToInstanceIndex(path); #endif } bool isAttributeEditAllowed(const PXR_NS::UsdAttribute& attr) { return ufe::isAttributeEditAllowed(attr); } bool isEditTargetLayerModifiable(const PXR_NS::UsdStageWeakPtr stage) { return ufe::isEditTargetLayerModifiable(stage); } PXR_NS::TfTokenVector getProxyShapePurposes(const std::string& ufePathString) { auto path = #ifdef UFE_V2_FEATURES_AVAILABLE Ufe::PathString::path( #else _UfeV1StringToUsdPath( #endif ufePathString); return ufe::getProxyShapePurposes(path); } void wrapUtils() { #ifdef UFE_V2_FEATURES_AVAILABLE def("getPrimFromRawItem", getPrimFromRawItem); def("getNodeNameFromRawItem", getNodeNameFromRawItem); def("getNodeTypeFromRawItem", getNodeTypeFromRawItem); #endif // Because mayaUsd and UFE have incompatible Python bindings that do not // know about each other (provided by Boost Python and pybind11, // respectively), we cannot pass in or return UFE objects such as Ufe::Path // here, and are forced to use strings. Use the tentative string // representation of Ufe::Path as comma-separated segments. We know that // the USD path separator is '/'. PPT, 8-Dec-2019. def("getStage", getStage); def("stagePath", stagePath); def("usdPathToUfePathSegment", usdPathToUfePathSegment, (arg("usdPath"), arg("instanceIndex") = PXR_NS::UsdImagingDelegate::ALL_INSTANCES)); def("getTime", getTime); def("stripInstanceIndexFromUfePath", stripInstanceIndexFromUfePath, (arg("ufePathString"))); def("ufePathToPrim", ufePathToPrim); def("ufePathToInstanceIndex", ufePathToInstanceIndex); def("getProxyShapePurposes", getProxyShapePurposes); def("isAttributeEditAllowed", isAttributeEditAllowed); def("isEditTargetLayerModifiable", isEditTargetLayerModifiable); } <file_sep>/lib/mayaUsd/render/vp2RenderDelegate/proxyRenderDelegate.h // // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef PROXY_RENDER_DELEGATE #define PROXY_RENDER_DELEGATE #include <mayaUsd/base/api.h> #include <pxr/imaging/hd/engine.h> #include <pxr/imaging/hd/selection.h> #include <pxr/imaging/hd/task.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usd/prim.h> #include <pxr/usdImaging/usdImaging/version.h> #include <maya/MDagPath.h> #include <maya/MDrawContext.h> #include <maya/MFrameContext.h> #include <maya/MGlobal.h> #include <maya/MHWGeometryUtilities.h> #include <maya/MMessage.h> #include <maya/MObject.h> #include <maya/MPxSubSceneOverride.h> #include <memory> #if defined(WANT_UFE_BUILD) #include <ufe/observer.h> #endif // Conditional compilation due to Maya API gap. #if MAYA_API_VERSION >= 20200000 #define MAYA_ENABLE_UPDATE_FOR_SELECTION #endif #if PXR_VERSION < 2008 #define ENABLE_RENDERTAG_VISIBILITY_WORKAROUND /* In USD v20.05 and earlier when the purpose of an rprim changes the visibility gets dirtied, and that doesn't update the render tag version. Pixar is in the process of fixing this one as noted in: https://groups.google.com/forum/#!topic/usd-interest/9pzFbtCEY-Y Logged as: https://github.com/PixarAnimationStudios/USD/issues/1243 */ #endif PXR_NAMESPACE_OPEN_SCOPE class HdRenderDelegate; class HdRenderIndex; class HdRprimCollection; class UsdImagingDelegate; class MayaUsdProxyShapeBase; class HdxTaskController; /*! \brief Enumerations for selection status */ enum HdVP2SelectionStatus { kUnselected, //!< A Rprim is not selected kPartiallySelected, //!< A Rprim is partially selected (only applicable for instanced Rprims) kFullyActive, //!< A Rprim is active (meaning fully active for instanced Rprims) kFullyLead //!< A Rprim is lead (meaning fully lead for instanced Rprims) }; //! Pick resolution behavior to use when the picked object is a point instance. enum class UsdPointInstancesPickMode { //! The PointInstancer prim that generated the point instance is picked. If //! multiple nested PointInstancers are involved, the top-level //! PointInstancer is the one picked. If a selection kind is specified, the //! traversal up the hierarchy looking for a kind match will begin at that //! PointInstancer. PointInstancer, //! The specific point instance is picked. These are represented as //! UsdSceneItems with UFE paths to a PointInstancer prim and a non-negative //! instanceIndex for the specific point instance. In this mode, any setting //! for selection kind is ignored. Instances, //! The prototype being instanced by the point instance is picked. If a //! selection kind is specified, the traversal up the hierarchy looking for //! a kind match will begin at the prototype prim. Prototypes }; /*! \brief USD Proxy rendering routine via VP2 MPxSubSceneOverride This drawing routine leverages HdVP2RenderDelegate for synchronization of data between scene delegate and VP2. Final rendering is done by VP2 as part of subscene override mechanism. USD Proxy can be rendered in a number of ways and by default we use VP2RenderDelegate. Use MAYAUSD_DISABLE_VP2_RENDER_DELEGATE env variable before loading USD plugin to switch to the legacy rendering with draw override approach. */ class ProxyRenderDelegate : public MHWRender::MPxSubSceneOverride { ProxyRenderDelegate(const MObject& obj); public: MAYAUSD_CORE_PUBLIC ~ProxyRenderDelegate() override; MAYAUSD_CORE_PUBLIC static const MString drawDbClassification; MAYAUSD_CORE_PUBLIC static MHWRender::MPxSubSceneOverride* Creator(const MObject& obj); MAYAUSD_CORE_PUBLIC MHWRender::DrawAPI supportedDrawAPIs() const override; #if defined(MAYA_ENABLE_UPDATE_FOR_SELECTION) MAYAUSD_CORE_PUBLIC bool enableUpdateForSelection() const override; #endif MAYAUSD_CORE_PUBLIC bool requiresUpdate(const MSubSceneContainer& container, const MFrameContext& frameContext) const override; MAYAUSD_CORE_PUBLIC void update(MSubSceneContainer& container, const MFrameContext& frameContext) override; MAYAUSD_CORE_PUBLIC void updateSelectionGranularity(const MDagPath& path, MSelectionContext& selectionContext) override; MAYAUSD_CORE_PUBLIC bool getInstancedSelectionPath( const MRenderItem& renderItem, const MIntersection& intersection, MDagPath& dagPath) const override; #if defined(USD_IMAGING_API_VERSION) && USD_IMAGING_API_VERSION >= 14 MAYAUSD_CORE_PUBLIC SdfPath GetScenePrimPath( const SdfPath& rprimId, int instanceIndex, HdInstancerContext* instancerContext = nullptr) const; #else MAYAUSD_CORE_PUBLIC SdfPath GetScenePrimPath(const SdfPath& rprimId, int instanceIndex) const; #endif MAYAUSD_CORE_PUBLIC void SelectionChanged(); MAYAUSD_CORE_PUBLIC const MColor& GetWireframeColor() const; MAYAUSD_CORE_PUBLIC const MColor& GetSelectionHighlightColor(bool lead) const; MAYAUSD_CORE_PUBLIC const HdSelection::PrimSelectionState* GetLeadSelectionState(const SdfPath& path) const; MAYAUSD_CORE_PUBLIC const HdSelection::PrimSelectionState* GetActiveSelectionState(const SdfPath& path) const; MAYAUSD_CORE_PUBLIC HdVP2SelectionStatus GetSelectionStatus(const SdfPath& path) const; MAYAUSD_CORE_PUBLIC bool DrawRenderTag(const TfToken& renderTag) const; #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT MAYAUSD_CORE_PUBLIC bool SnapToSelectedObjects() const; MAYAUSD_CORE_PUBLIC bool SnapToPoints() const; #endif private: ProxyRenderDelegate(const ProxyRenderDelegate&) = delete; ProxyRenderDelegate& operator=(const ProxyRenderDelegate&) = delete; //! \brief The main stages of update void _ClearInvalidData(MSubSceneContainer& container); void _InitRenderDelegate(); bool _Populate(); void _UpdateSceneDelegate(); void _Execute(const MHWRender::MFrameContext& frameContext); bool _isInitialized(); void _PopulateSelection(); void _UpdateSelectionStates(); void _UpdateRenderTags(); void _ClearRenderDelegate(); SdfPathVector _GetFilteredRprims(HdRprimCollection const& collection, TfTokenVector const& renderTags); /*! \brief Hold all data related to the proxy shape. In addition to holding data read from the proxy shape, ProxyShapeData tracks when data read from the proxy shape changes. For simple numeric types cache the last value read from _proxyShape & compare to the current value. For complicated types we keep a version number of the last value we read to make fast comparisons. */ class ProxyShapeData { const MayaUsdProxyShapeBase* const _proxyShape { nullptr }; //!< DG proxy shape node const MDagPath _proxyDagPath; //!< DAG path of the proxy shape (assuming no DAG instancing) UsdStageRefPtr _usdStage; //!< USD stage pointer size_t _excludePrimsVersion { 0 }; //!< Last version of exluded prims used during render index populate size_t _usdStageVersion { 0 }; //!< Last version of stage used during render index populate bool _drawRenderPurpose { false }; //!< Should the render delegate draw rprims with the "render" purpose bool _drawProxyPurpose { false }; //!< Should the render delegate draw rprims with the "proxy" purpose bool _drawGuidePurpose { false }; //!< Should the render delegate draw rprims with the "guide" purpose public: ProxyShapeData(const MayaUsdProxyShapeBase* proxyShape, const MDagPath& proxyDagPath); const MayaUsdProxyShapeBase* ProxyShape() const; const MDagPath& ProxyDagPath() const; UsdStageRefPtr UsdStage() const; void UpdateUsdStage(); bool IsUsdStageUpToDate() const; void UsdStageUpdated(); bool IsExcludePrimsUpToDate() const; void ExcludePrimsUpdated(); void UpdatePurpose( bool* drawRenderPurposeChanged, bool* drawProxyPurposeChanged, bool* drawGuidePurposeChanged); bool DrawRenderPurpose() const; bool DrawProxyPurpose() const; bool DrawGuidePurpose() const; }; std::unique_ptr<ProxyShapeData> _proxyShapeData; // USD & Hydra Objects HdEngine _engine; //!< Hydra engine responsible for running synchronization between scene //!< delegate and VP2RenderDelegate HdTaskSharedPtrVector _dummyTasks; //!< Dummy task to bootstrap data preparation inside Hydra engine std::unique_ptr<HdRenderDelegate> _renderDelegate; //!< VP2RenderDelegate std::unique_ptr<HdRenderIndex> _renderIndex; //!< Flattened representation of client scene graph std::unique_ptr<HdxTaskController> _taskController; //!< Task controller necessary for execution with hydra engine (we don't //!< really need it, but there doesn't seem to be a way to get //!< synchronization running without it) std::unique_ptr<UsdImagingDelegate> _sceneDelegate; //!< USD scene delegate bool _isPopulated { false }; //!< If false, scene delegate wasn't populated yet within render index bool _selectionChanged { true }; //!< Whether there is any selection change or not #ifdef MAYA_NEW_POINT_SNAPPING_SUPPORT bool _selectionModeChanged { true }; //!< Whether the global selection mode has changed bool _snapToPoints { false }; //!< Whether point snapping is enabled or not bool _snapToSelectedObjects { false }; //!< Whether point snapping should snap to selected objects #endif MColor _wireframeColor; //!< Wireframe color assigned to the proxy shape //! A collection of Rprims to prepare render data for specified reprs std::unique_ptr<HdRprimCollection> _defaultCollection; //! The render tag version used the last time render tags were updated unsigned int _renderTagVersion { 0 }; // initialized to 1 in HdChangeTracker, so we'll always // have an invalid version the first update. #ifdef ENABLE_RENDERTAG_VISIBILITY_WORKAROUND unsigned int _visibilityVersion { 0 }; // initialized to 1 in HdChangeTracker. #endif bool _taskRenderTagsValid { false }; //!< If false the render tags on the dummy render task are not the minimum set of tags. MHWRender::DisplayStatus _displayStatus { MHWRender::kNoStatus }; //!< The display status of the proxy shape HdSelectionSharedPtr _leadSelection; //!< A collection of Rprims being lead selection HdSelectionSharedPtr _activeSelection; //!< A collection of Rprims being active selection #if defined(WANT_UFE_BUILD) //! Observer to listen to UFE changes Ufe::Observer::Ptr _observer; #else //! Minimum support for proxy selection when UFE is not available. MCallbackId _mayaSelectionCallbackId { 0 }; #endif #if defined(WANT_UFE_BUILD) && defined(MAYA_ENABLE_UPDATE_FOR_SELECTION) //! Adjustment mode for global selection list: ADD, REMOVE, REPLACE, XOR MGlobal::ListAdjustment _globalListAdjustment; //! Token of the Kind to be selected from viewport. If it empty, select the exact prims. TfToken _selectionKind; //! Pick resolution behavior to use when the picked object is a point instance. UsdPointInstancesPickMode _pointInstancesPickMode; #endif }; /*! \brief Is this object properly initialized and can start receiving updates. Once this is done, * render index needs to be populated and then we rely on change tracker. */ inline bool ProxyRenderDelegate::_isInitialized() { return (_sceneDelegate != nullptr); } PXR_NAMESPACE_CLOSE_SCOPE #endif <file_sep>/lib/mayaUsd/ufe/CMakeLists.txt # ----------------------------------------------------------------------------- # sources # ----------------------------------------------------------------------------- target_sources(${PROJECT_NAME} PRIVATE Global.cpp ProxyShapeHandler.cpp ProxyShapeHierarchy.cpp ProxyShapeHierarchyHandler.cpp StagesSubject.cpp UsdHierarchy.cpp UsdHierarchyHandler.cpp UsdPointInstanceOrientationModifier.cpp UsdPointInstancePositionModifier.cpp UsdPointInstanceScaleModifier.cpp UsdRootChildHierarchy.cpp UsdRotatePivotTranslateUndoableCommand.cpp UsdRotateUndoableCommand.cpp UsdScaleUndoableCommand.cpp UsdSceneItem.cpp UsdSceneItemOps.cpp UsdSceneItemOpsHandler.cpp UsdStageMap.cpp UsdTRSUndoableCommandBase.cpp UsdTransform3d.cpp UsdTransform3dHandler.cpp UsdTranslateUndoableCommand.cpp UsdUndoDeleteCommand.cpp UsdUndoDuplicateCommand.cpp UsdUndoRenameCommand.cpp Utils.cpp moduleDeps.cpp ) if(CMAKE_UFE_V2_FEATURES_AVAILABLE) target_sources(${PROJECT_NAME} PRIVATE ProxyShapeContextOpsHandler.cpp RotationUtils.cpp UsdAttribute.cpp UsdAttributes.cpp UsdAttributesHandler.cpp UsdCamera.cpp UsdCameraHandler.cpp UsdContextOps.cpp UsdContextOpsHandler.cpp UsdObject3d.cpp UsdObject3dHandler.cpp UsdSetXformOpUndoableCommandBase.cpp UsdTransform3dBase.cpp UsdTransform3dCommonAPI.cpp UsdTransform3dFallbackMayaXformStack.cpp UsdTransform3dMatrixOp.cpp UsdTransform3dMayaXformStack.cpp UsdTransform3dPointInstance.cpp UsdTransform3dSetObjectMatrix.cpp UsdTransform3dUndoableCommands.cpp UsdUIInfoHandler.cpp UsdUIUfeObserver.cpp UsdUndoAddNewPrimCommand.cpp UsdUndoCreateGroupCommand.cpp UsdUndoInsertChildCommand.cpp UsdUndoReorderCommand.cpp UsdUndoSetKindCommand.cpp UsdUndoVisibleCommand.cpp UsdUndoUngroupCommand.cpp XformOpUtils.cpp ) endif() if(CMAKE_UFE_V3_FEATURES_AVAILABLE) target_sources(${PROJECT_NAME} PRIVATE UsdUndoUngroupCommand.cpp ) endif() set(HEADERS Global.h ProxyShapeHandler.h ProxyShapeHierarchy.h ProxyShapeHierarchyHandler.h StagesSubject.h UsdHierarchy.h UsdHierarchyHandler.h UsdPointInstanceModifierBase.h UsdPointInstanceOrientationModifier.h UsdPointInstancePositionModifier.h UsdPointInstanceScaleModifier.h UsdRootChildHierarchy.h UsdRotatePivotTranslateUndoableCommand.h UsdRotateUndoableCommand.h UsdScaleUndoableCommand.h UsdSceneItem.h UsdSceneItemOps.h UsdSceneItemOpsHandler.h UsdStageMap.h UsdTRSUndoableCommandBase.h UsdTransform3d.h UsdTransform3dHandler.h UsdTranslateUndoableCommand.h UsdUndoDeleteCommand.h UsdUndoDuplicateCommand.h UsdUndoRenameCommand.h Utils.h UfeVersionCompat.h ) if(CMAKE_UFE_V2_FEATURES_AVAILABLE) list(APPEND HEADERS ProxyShapeContextOpsHandler.h RotationUtils.h UsdAttribute.h UsdAttributes.h UsdAttributesHandler.h UsdCamera.h UsdCameraHandler.h UsdContextOps.h UsdContextOpsHandler.h UsdObject3d.h UsdObject3dHandler.h UsdPointInstanceUndoableCommands.h UsdSetXformOpUndoableCommandBase.h UsdTransform3dBase.h UsdTransform3dCommonAPI.h UsdTransform3dFallbackMayaXformStack.h UsdTransform3dMatrixOp.h UsdTransform3dMayaXformStack.h UsdTransform3dPointInstance.h UsdTransform3dSetObjectMatrix.h UsdTransform3dUndoableCommands.h UsdUIInfoHandler.h UsdUIUfeObserver.h UsdUndoableCommand.h UsdUndoAddNewPrimCommand.h UsdUndoCreateGroupCommand.h UsdUndoInsertChildCommand.h UsdUndoReorderCommand.h UsdUndoSetKindCommand.h UsdUndoVisibleCommand.h XformOpUtils.h ) endif() if(CMAKE_UFE_V3_FEATURES_AVAILABLE) list(APPEND HEADERS UsdUndoUngroupCommand.h ) endif() # ----------------------------------------------------------------------------- # promote headers # ----------------------------------------------------------------------------- mayaUsd_promoteHeaderList(HEADERS ${HEADERS} SUBDIR ufe) # ----------------------------------------------------------------------------- # install # ----------------------------------------------------------------------------- install(FILES ${HEADERS} DESTINATION ${CMAKE_INSTALL_PREFIX}/include/${PROJECT_NAME}/ufe ) set(UFE_PYTHON_MODULE_NAME ufe) # ----------------------------------------------------------------------------- # subdirectories # ----------------------------------------------------------------------------- add_subdirectory(private) # ----------------------------------------------------------------------------- # target (UFE Python Bindings) # ----------------------------------------------------------------------------- # UFE Python Bindings if(IS_WINDOWS AND MAYAUSD_DEFINE_BOOST_DEBUG_PYTHON_FLAG) # On Windows when compiling with debug python the library must be named with _d. set(UFE_PYTHON_TARGET_NAME "_${UFE_PYTHON_MODULE_NAME}_d") else() set(UFE_PYTHON_TARGET_NAME "_${UFE_PYTHON_MODULE_NAME}") endif() add_library(${UFE_PYTHON_TARGET_NAME} SHARED) # ----------------------------------------------------------------------------- # sources # ----------------------------------------------------------------------------- target_sources(${UFE_PYTHON_TARGET_NAME} PRIVATE module.cpp wrapGlobal.cpp wrapUtils.cpp wrapNotice.cpp ) # ----------------------------------------------------------------------------- # compiler configuration # ----------------------------------------------------------------------------- target_compile_definitions(${UFE_PYTHON_TARGET_NAME} PRIVATE $<$<BOOL:${IS_MACOSX}>:OSMac_> MFB_PACKAGE_NAME=${UFE_PYTHON_MODULE_NAME} MFB_ALT_PACKAGE_NAME=${UFE_PYTHON_MODULE_NAME} MFB_PACKAGE_MODULE="${PROJECT_NAME}.${UFE_PYTHON_MODULE_NAME}" ) mayaUsd_compile_config(${UFE_PYTHON_TARGET_NAME}) # ----------------------------------------------------------------------------- # link libraries # ----------------------------------------------------------------------------- target_link_libraries(${UFE_PYTHON_TARGET_NAME} PUBLIC ${PROJECT_NAME} ) # ----------------------------------------------------------------------------- # properties # ----------------------------------------------------------------------------- set_python_module_property(${UFE_PYTHON_TARGET_NAME}) # ----------------------------------------------------------------------------- # run-time search paths # ----------------------------------------------------------------------------- if(IS_MACOSX OR IS_LINUX) mayaUsd_init_rpath(rpath "${PROJECT_NAME}") mayaUsd_add_rpath(rpath "../../..") if(IS_MACOSX AND DEFINED MAYAUSD_TO_USD_RELATIVE_PATH) mayaUsd_add_rpath(rpath "../../../../${MAYAUSD_TO_USD_RELATIVE_PATH}/lib") endif() mayaUsd_install_rpath(rpath ${UFE_PYTHON_TARGET_NAME}) endif() # ----------------------------------------------------------------------------- # install # ----------------------------------------------------------------------------- install(TARGETS ${UFE_PYTHON_TARGET_NAME} LIBRARY DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/python/${PROJECT_NAME}/${UFE_PYTHON_MODULE_NAME} RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/python/${PROJECT_NAME}/${UFE_PYTHON_MODULE_NAME} ) install(FILES __init__.py DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/python/${PROJECT_NAME}/${UFE_PYTHON_MODULE_NAME} ) if(IS_WINDOWS) install(FILES $<TARGET_PDB_FILE:${UFE_PYTHON_TARGET_NAME}> DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/python/${PROJECT_NAME}/${UFE_PYTHON_MODULE_NAME} OPTIONAL) endif() <file_sep>/lib/mayaUsd/ufe/Utils.h // // Copyright 2021 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include <mayaUsd/base/api.h> #include <mayaUsd/ufe/UsdSceneItem.h> #include <pxr/base/tf/hashset.h> #include <pxr/base/tf/token.h> #include <pxr/usd/sdf/layer.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usd/timeCode.h> #include <pxr/usdImaging/usdImaging/delegate.h> #include <maya/MDagPath.h> #include <ufe/path.h> #include <ufe/scene.h> #ifdef UFE_V2_FEATURES_AVAILABLE #include <ufe/types.h> #else #include <ufe/transform3d.h> #endif #include <cstring> // memcpy UFE_NS_DEF { class PathSegment; class Selection; } namespace MAYAUSD_NS_DEF { namespace ufe { //------------------------------------------------------------------------------ // Helper functions //------------------------------------------------------------------------------ //! Get USD stage corresponding to argument UFE path. MAYAUSD_CORE_PUBLIC PXR_NS::UsdStageWeakPtr getStage(const Ufe::Path& path); //! Return the ProxyShape node UFE path for the argument stage. MAYAUSD_CORE_PUBLIC Ufe::Path stagePath(PXR_NS::UsdStageWeakPtr stage); //! Return all the USD stages. MAYAUSD_CORE_PUBLIC PXR_NS::TfHashSet<PXR_NS::UsdStageWeakPtr, PXR_NS::TfHash> getAllStages(); //! Get the UFE path segment corresponding to the argument USD path. //! If an instanceIndex is provided, the path segment for a point instance with //! that USD path and index is returned. MAYAUSD_CORE_PUBLIC Ufe::PathSegment usdPathToUfePathSegment( const PXR_NS::SdfPath& usdPath, int instanceIndex = PXR_NS::UsdImagingDelegate::ALL_INSTANCES); //! Get the UFE path representing just the USD prim for the argument UFE path. //! Any instance index component at the tail of the given path is removed from //! the returned path. MAYAUSD_CORE_PUBLIC Ufe::Path stripInstanceIndexFromUfePath(const Ufe::Path& path); //! Return the USD prim corresponding to the argument UFE path. MAYAUSD_CORE_PUBLIC PXR_NS::UsdPrim ufePathToPrim(const Ufe::Path& path); //! Return the instance index corresponding to the argument UFE path if it //! represents a point instance. //! If the given path does not represent a point instance, //! UsdImagingDelegate::ALL_INSTANCES (-1) will be returned. //! If the optional argument prim pointer is non-null, the USD prim //! corresponding to the argument UFE path is returned, as per ufePathToPrim(). MAYAUSD_CORE_PUBLIC int ufePathToInstanceIndex(const Ufe::Path& path, PXR_NS::UsdPrim* prim = nullptr); MAYAUSD_CORE_PUBLIC bool isRootChild(const Ufe::Path& path); MAYAUSD_CORE_PUBLIC UsdSceneItem::Ptr createSiblingSceneItem(const Ufe::Path& ufeSrcPath, const std::string& siblingName); //! Split the source name into a base name and a numerical suffix (set to //! 1 if absent). Increment the numerical suffix until name is unique. MAYAUSD_CORE_PUBLIC std::string uniqueName(const PXR_NS::TfToken::HashSet& existingNames, std::string srcName); //! Return a unique child name. MAYAUSD_CORE_PUBLIC std::string uniqueChildName(const PXR_NS::UsdPrim& parent, const std::string& name); //! Return if a Maya node type is derived from the gateway node type. MAYAUSD_CORE_PUBLIC bool isAGatewayType(const std::string& mayaNodeType); MAYAUSD_CORE_PUBLIC Ufe::Path dagPathToUfe(const MDagPath& dagPath); MAYAUSD_CORE_PUBLIC Ufe::PathSegment dagPathToPathSegment(const MDagPath& dagPath); //! Get the time along the argument path. A gateway node (i.e. proxy shape) //! along the path can transform Maya's time (e.g. with scale and offset). MAYAUSD_CORE_PUBLIC PXR_NS::UsdTimeCode getTime(const Ufe::Path& path); //! Return the non-default purposes of the gateway node (i.e. proxy shape) //! along the argument path. Only those purposes that are true are returned. //! The default purpose is not returned, and is considered implicit. MAYAUSD_CORE_PUBLIC PXR_NS::TfTokenVector getProxyShapePurposes(const Ufe::Path& path); //! Check if an attribute value is allowed to be changed. //! \return True, if the attribute value is allowed to be edited in the stage's local Layer Stack. MAYAUSD_CORE_PUBLIC bool isAttributeEditAllowed(const PXR_NS::UsdAttribute& attr, std::string* errMsg = nullptr); MAYAUSD_CORE_PUBLIC bool isAttributeEditAllowed(const PXR_NS::UsdPrim& prim, const PXR_NS::TfToken& attrName); //! Check if the edit target in the stage is allowed to be changed. //! \return True, if the edit target layer in the stage is allowed to be changed MAYAUSD_CORE_PUBLIC bool isEditTargetLayerModifiable( const PXR_NS::UsdStageWeakPtr stage, std::string* errMsg = nullptr); //! Send notification for data model changes template <class T> void sendNotification(const Ufe::SceneItem::Ptr& item, const Ufe::Path& previousPath) { T notification(item, previousPath); #ifdef UFE_V2_FEATURES_AVAILABLE Ufe::Scene::instance().notify(notification); #else Ufe::Scene::notifyObjectPathChange(notification); #endif } //! Readability function to downcast a SceneItem::Ptr to a UsdSceneItem::Ptr. inline UsdSceneItem::Ptr downcast(const Ufe::SceneItem::Ptr& item) { return std::dynamic_pointer_cast<UsdSceneItem>(item); } //! Copy the argument matrix into the return matrix. inline Ufe::Matrix4d toUfe(const PXR_NS::GfMatrix4d& src) { Ufe::Matrix4d dst; std::memcpy(&dst.matrix[0][0], src.GetArray(), sizeof(double) * 16); return dst; } //! Copy the argument matrix into the return matrix. inline PXR_NS::GfMatrix4d toUsd(const Ufe::Matrix4d& src) { PXR_NS::GfMatrix4d dst; std::memcpy(dst.GetArray(), &src.matrix[0][0], sizeof(double) * 16); return dst; } //! Copy the argument vector into the return vector. inline Ufe::Vector3d toUfe(const PXR_NS::GfVec3d& src) { return Ufe::Vector3d(src[0], src[1], src[2]); } //! Filter a source selection by removing descendants of filterPath. Ufe::Selection removeDescendants(const Ufe::Selection& src, const Ufe::Path& filterPath); //! Re-build a source selection by copying scene items that are not descendants //! of filterPath to the destination, and re-creating the others into the //! destination using the source scene item path. Ufe::Selection recreateDescendants(const Ufe::Selection& src, const Ufe::Path& filterPath); } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/test/lib/ufe/testDuplicateCmd.py #!/usr/bin/env python # # Copyright 2019 Autodesk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import fixturesUtils import mayaUtils import testUtils import ufeUtils import usdUtils from maya import cmds from maya import standalone import ufe import unittest class DuplicateCmdTestCase(unittest.TestCase): '''Verify the Maya delete command, for multiple runtimes. UFE Feature : SceneItemOps Maya Feature : duplicate Action : Duplicate objects in the scene. Applied On Selection : - Multiple Selection [Mixed, Non-Maya]. Maya-only selection tested by Maya. Undo/Redo Test : Yes Expect Results To Test : - Duplicate objects in the scene. Edge Cases : - None. ''' pluginsLoaded = False @classmethod def setUpClass(cls): fixturesUtils.readOnlySetUpClass(__file__, loadPlugin=False) if not cls.pluginsLoaded: cls.pluginsLoaded = mayaUtils.isMayaUsdPluginLoaded() @classmethod def tearDownClass(cls): standalone.uninitialize() def setUp(self): ''' Called initially to set up the Maya test environment ''' # Load plugins self.assertTrue(self.pluginsLoaded) # Open top_layer.ma scene in testSamples mayaUtils.openTopLayerScene() # Create some extra Maya nodes cmds.polySphere() # Clear selection to start off cmds.select(clear=True) def testDuplicate(self): '''Duplicate Maya and USD objects.''' # Select two objects, one Maya, one USD. spherePath = ufe.Path(mayaUtils.createUfePathSegment("|pSphere1")) sphereItem = ufe.Hierarchy.createItem(spherePath) sphereHierarchy = ufe.Hierarchy.hierarchy(sphereItem) worldItem = sphereHierarchy.parent() ball35Path = ufe.Path([ mayaUtils.createUfePathSegment( "|transform1|proxyShape1"), usdUtils.createUfePathSegment("/Room_set/Props/Ball_35")]) ball35Item = ufe.Hierarchy.createItem(ball35Path) ball35Hierarchy = ufe.Hierarchy.hierarchy(ball35Item) propsItem = ball35Hierarchy.parent() worldHierarchy = ufe.Hierarchy.hierarchy(worldItem) worldChildrenPre = worldHierarchy.children() propsHierarchy = ufe.Hierarchy.hierarchy(propsItem) propsChildrenPre = propsHierarchy.children() ufe.GlobalSelection.get().append(sphereItem) ufe.GlobalSelection.get().append(ball35Item) # Set the edit target to the layer in which Ball_35 is defined (has a # primSpec, in USD terminology). Otherwise, duplication will not find # a source primSpec to copy. Layers are the (anonymous) session layer, # the root layer, then the Assembly_room_set sublayer. Trying to find # the layer by name is not practical, as it requires the full path # name, which potentially differs per run-time environment. ball35Prim = usdUtils.getPrimFromSceneItem(ball35Item) stage = ball35Prim.GetStage() layer = stage.GetLayerStack()[2] stage.SetEditTarget(layer) cmds.duplicate() # The duplicate command doesn't return duplicated non-Maya UFE objects. # They are in the selection, in the same order as the sources. snIter = iter(ufe.GlobalSelection.get()) sphereDupItem = next(snIter) sphereDupName = str(sphereDupItem.path().back()) ball35DupItem = next(snIter) ball35DupName = str(ball35DupItem.path().back()) worldChildren = worldHierarchy.children() propsChildren = propsHierarchy.children() self.assertEqual(len(worldChildren)-len(worldChildrenPre), 1) self.assertEqual(len(propsChildren)-len(propsChildrenPre), 1) self.assertIn(sphereDupItem, worldChildren) self.assertIn(ball35DupItem, propsChildren) cmds.undo() # The duplicated items should no longer appear in the child list of # their parents. def childrenNames(children): return [str(child.path().back()) for child in children] worldHierarchy = ufe.Hierarchy.hierarchy(worldItem) worldChildren = worldHierarchy.children() propsHierarchy = ufe.Hierarchy.hierarchy(propsItem) propsChildren = propsHierarchy.children() worldChildrenNames = childrenNames(worldChildren) propsChildrenNames = childrenNames(propsChildren) self.assertNotIn(sphereDupName, worldChildrenNames) self.assertNotIn(ball35DupName, propsChildrenNames) # The duplicated items shoudl reappear after a redo cmds.redo() snIter = iter(ufe.GlobalSelection.get()) sphereDupItem = next(snIter) ball35DupItem = next(snIter) worldChildren = worldHierarchy.children() propsChildren = propsHierarchy.children() self.assertEqual(len(worldChildren)-len(worldChildrenPre), 1) self.assertEqual(len(propsChildren)-len(propsChildrenPre), 1) self.assertIn(sphereDupItem, worldChildren) self.assertIn(ball35DupItem, propsChildren) cmds.undo() # The duplicated items should not be assigned to the name of a # deactivated USD item. cmds.select(clear=True) # Delete the even numbered props: evenPropsChildrenPre = propsChildrenPre[0:35:2] for propChild in evenPropsChildrenPre: ufe.GlobalSelection.get().append(propChild) cmds.delete() worldHierarchy = ufe.Hierarchy.hierarchy(worldItem) worldChildren = worldHierarchy.children() propsHierarchy = ufe.Hierarchy.hierarchy(propsItem) propsChildren = propsHierarchy.children() propsChildrenPostDel = propsHierarchy.children() # Duplicate Ball_1 ufe.GlobalSelection.get().append(propsChildrenPostDel[0]) cmds.duplicate() snIter = iter(ufe.GlobalSelection.get()) ballDupItem = next(snIter) ballDupName = str(ballDupItem.path().back()) self.assertNotIn(ballDupItem, propsChildrenPostDel) self.assertNotIn(ballDupName, propsChildrenNames) self.assertEqual(ballDupName, "Ball_36") cmds.undo() # undo duplication cmds.undo() # undo deletion @unittest.skipUnless(mayaUtils.mayaMajorVersion() >= 2022, 'Requires Maya fixes only available in Maya 2022 or greater.') def testSmartTransformDuplicate(self): '''Test smart transform option of duplicate command.''' torusFile = testUtils.getTestScene("groupCmd", "torus.usda") torusDagPath, torusStage = mayaUtils.createProxyFromFile(torusFile) usdTorusPathString = torusDagPath + ",/pTorus1" cmds.duplicate(usdTorusPathString) cmds.move(10, 0, 0, r=True) smartDup = cmds.duplicate(smartTransform=True) usdTorusItem = ufeUtils.createUfeSceneItem(torusDagPath, '/pTorus3') torusT3d = ufe.Transform3d.transform3d(usdTorusItem) transVector = torusT3d.inclusiveMatrix().matrix[-1] correctResult = [20, 0, 0, 1] self.assertEqual(correctResult, transVector) if __name__ == '__main__': unittest.main(verbosity=2) <file_sep>/test/lib/CMakeLists.txt set(TARGET_NAME MAYAUSD_TEST) # Unit test scripts. set(TEST_SCRIPT_FILES testMayaUsdConverter.py testMayaUsdCreateStageCommands.py testMayaUsdPythonImport.py testMayaUsdLayerEditorCommands.py testMayaUsdCacheId.py ) if (UFE_FOUND AND MAYA_APP_VERSION VERSION_GREATER 2020) list(APPEND TEST_SCRIPT_FILES testMayaUsdDirtyScene.py testMayaUsdProxyAccessor.py ) endif() # Interactive Unit test scripts. set(INTERACTIVE_TEST_SCRIPT_FILES testMayaUsdInteractiveLayerEditorCommands.py ) # copy tests to ${CMAKE_CURRENT_BINARY_DIR} and run them from there add_custom_target(${TARGET_NAME} ALL) mayaUsd_copyFiles(${TARGET_NAME} DESTINATION ${CMAKE_CURRENT_BINARY_DIR} FILES ${TEST_SCRIPT_FILES} ${INTERACTIVE_TEST_SCRIPT_FILES} ) foreach(script ${TEST_SCRIPT_FILES}) mayaUsd_get_unittest_target(target ${script}) mayaUsd_add_test(${target} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} PYTHON_MODULE ${target} ENV "LD_LIBRARY_PATH=${ADDITIONAL_LD_LIBRARY_PATH}" ) # Add a ctest label to these tests for easy filtering. set_property(TEST ${target} APPEND PROPERTY LABELS MayaUsd) endforeach() foreach(script ${INTERACTIVE_TEST_SCRIPT_FILES}) mayaUsd_get_unittest_target(target ${script}) mayaUsd_add_test(${target} INTERACTIVE WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} PYTHON_SCRIPT ${script} ENV "MAYA_PLUG_IN_PATH=${CMAKE_INSTALL_PREFIX}/lib/maya" "LD_LIBRARY_PATH=${ADDITIONAL_LD_LIBRARY_PATH}" ) # Add a ctest label to these tests for easy filtering. set_property(TEST ${target} APPEND PROPERTY LABELS MayaUsd) endforeach() # # ----------------------------------------------------------------------------- # Special case for plug tests # ----------------------------------------------------------------------------- set(TEST_PLUG_FILES testMayaUsdPlugVersionCheck.py ) mayaUsd_copyFiles(${TARGET_NAME} DESTINATION ${CMAKE_CURRENT_BINARY_DIR} FILES ${TEST_PLUG_FILES} ) foreach(script ${TEST_PLUG_FILES}) mayaUsd_get_unittest_target(target ${script}) mayaUsd_add_test(${target} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} PYTHON_MODULE ${target} ENV "LD_LIBRARY_PATH=${ADDITIONAL_LD_LIBRARY_PATH}" "MAYA_PXR_PLUGINPATH_NAME=${CMAKE_CURRENT_BINARY_DIR}/usd/plugin/TestMayaUsdPlug" ) # Add a ctest label to these tests for easy filtering. set_property(TEST ${target} APPEND PROPERTY LABELS MayaUsd) endforeach() # ----------------------------------------------------------------------------- if (UFE_FOUND) add_subdirectory(ufe) add_subdirectory(mayaUsd) endif() add_subdirectory(usd) <file_sep>/lib/mayaUsd/fileio/primUpdater.h // // Copyright 2018 Pixar // Copyright 2019 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef PXRUSDMAYA_MAYAPRIMUPDATER_H #define PXRUSDMAYA_MAYAPRIMUPDATER_H #include <mayaUsd/base/api.h> #include <mayaUsd/fileio/primUpdaterContext.h> #include <mayaUsd/utils/util.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/path.h> #include <maya/MDagPath.h> #include <maya/MFnDependencyNode.h> #include <maya/MObject.h> PXR_NAMESPACE_OPEN_SCOPE class UsdMayaPrimUpdater { public: MAYAUSD_CORE_PUBLIC UsdMayaPrimUpdater(const MFnDependencyNode& depNodeFn, const SdfPath& usdPath); // clang errors if you use "= default" here, due to const SdfPath member // see: http://open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#253 // ...which it seems clang only implements if using newer version + cpp std UsdMayaPrimUpdater() { } virtual ~UsdMayaPrimUpdater() = default; enum class Supports { Invalid = 0, Push = 1 << 0, Pull = 1 << 1, Clear = 1 << 2, All = Push | Pull | Clear }; MAYAUSD_CORE_PUBLIC virtual bool Push(UsdMayaPrimUpdaterContext* context); MAYAUSD_CORE_PUBLIC virtual bool Pull(UsdMayaPrimUpdaterContext* context); MAYAUSD_CORE_PUBLIC virtual void Clear(UsdMayaPrimUpdaterContext* context); /// The source Maya DAG path that we are consuming. /// /// If this prim updater is for a Maya DG node and not a DAG node, this will /// return an invalid MDagPath. MAYAUSD_CORE_PUBLIC const MDagPath& GetDagPath() const; /// The MObject for the Maya node being updated by this updater. MAYAUSD_CORE_PUBLIC const MObject& GetMayaObject() const; /// The path of the destination USD prim which we are updating. MAYAUSD_CORE_PUBLIC const SdfPath& GetUsdPath() const; /// The destination USD prim which we are updating. template <typename T> UsdPrim GetUsdPrim(UsdMayaPrimUpdaterContext& context) const { UsdPrim usdPrim; if (!TF_VERIFY(GetDagPath().isValid())) { return usdPrim; } T primSchema = T::Define(context.GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( primSchema, "Could not define given updater type at path '%s'\n", GetUsdPath().GetText())) { return usdPrim; } usdPrim = primSchema.GetPrim(); if (!TF_VERIFY( usdPrim, "Could not get UsdPrim for given updater type at path '%s'\n", primSchema.GetPath().GetText())) { return usdPrim; } return usdPrim; } private: /// The MDagPath for the Maya node being updated, valid only for DAG node /// prim updaters. const MDagPath _dagPath; /// The MObject for the Maya node being updated, valid for both DAG and DG /// node prim updaters. const MObject _mayaObject; const SdfPath _usdPath; const UsdMayaUtil::MDagPathMap<SdfPath> _baseDagToUsdPaths; }; using UsdMayaPrimUpdaterSharedPtr = std::shared_ptr<UsdMayaPrimUpdater>; inline UsdMayaPrimUpdater::Supports operator|(UsdMayaPrimUpdater::Supports a, UsdMayaPrimUpdater::Supports b) { return static_cast<UsdMayaPrimUpdater::Supports>(static_cast<int>(a) | static_cast<int>(b)); } inline UsdMayaPrimUpdater::Supports operator&(UsdMayaPrimUpdater::Supports a, UsdMayaPrimUpdater::Supports b) { return static_cast<UsdMayaPrimUpdater::Supports>(static_cast<int>(a) & static_cast<int>(b)); } PXR_NAMESPACE_CLOSE_SCOPE #endif <file_sep>/lib/mayaUsd/python/wrapPrimReader.cpp // // Copyright 2021 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <mayaUsd/fileio/primReader.h> #include <mayaUsd/fileio/primReaderRegistry.h> #include <mayaUsd/fileio/registryHelper.h> #include <mayaUsd/fileio/shaderReader.h> #include <mayaUsd/fileio/shaderReaderRegistry.h> #include <mayaUsd/fileio/shading/shadingModeImporter.h> #include <pxr/base/tf/makePyConstructor.h> #include <pxr/base/tf/pyContainerConversions.h> #include <pxr/base/tf/pyEnum.h> #include <pxr/base/tf/pyPolymorphic.h> #include <pxr/base/tf/pyPtrHelpers.h> #include <pxr/base/tf/pyResultConversions.h> #include <pxr/base/tf/refPtr.h> #include <boost/python.hpp> #include <boost/python/args.hpp> #include <boost/python/def.hpp> #include <boost/python/return_internal_reference.hpp> #include <boost/python/wrapper.hpp> PXR_NAMESPACE_USING_DIRECTIVE //---------------------------------------------------------------------------------------------------------------------- /// \brief boost python binding for the UsdMayaPrimReader //---------------------------------------------------------------------------------------------------------------------- template <typename T = UsdMayaPrimReader> class PrimReaderWrapper : public T , public TfPyPolymorphic<UsdMayaPrimReader> { public: typedef PrimReaderWrapper This; typedef T base_t; PrimReaderWrapper(const UsdMayaPrimReaderArgs& args) : T(args) { } static PrimReaderWrapper* New(uintptr_t createdWrapper) { return (PrimReaderWrapper*)createdWrapper; } virtual ~PrimReaderWrapper() { } bool Read(UsdMayaPrimReaderContext& context) override { return this->template CallPureVirtual<bool>("Read")(context); } bool default_HasPostReadSubtree() const { return base_t::HasPostReadSubtree(); } bool HasPostReadSubtree() const override { return this->template CallVirtual<bool>( "HasPostReadSubtree", &This::default_HasPostReadSubtree)(); } void default_PostReadSubtree(UsdMayaPrimReaderContext& context) { base_t::PostReadSubtree(context); } void PostReadSubtree(UsdMayaPrimReaderContext& context) override { this->template CallVirtual<>("PostReadSubtree", &This::default_PostReadSubtree)(context); } // Must be declared for python to be able to call the protected function _GetArgs in // UsdMayaPrimReader const UsdMayaPrimReaderArgs& _GetArgs() { return base_t::_GetArgs(); } static void Register(boost::python::object cl, const std::string& typeName) { auto type = TfType::FindByName(typeName); UsdMayaPrimReaderRegistry::Register( type, [=](const UsdMayaPrimReaderArgs& args) { auto sptr = std::make_shared<PrimReaderWrapper>(args); TfPyLock pyLock; boost::python::object instance = cl((uintptr_t)(PrimReaderWrapper*)sptr.get()); boost::python::incref(instance.ptr()); initialize_wrapper(instance.ptr(), sptr.get()); return sptr; }, true); } }; //---------------------------------------------------------------------------------------------------------------------- /// \brief boost python binding for the UsdMayaShaderReader //---------------------------------------------------------------------------------------------------------------------- class ShaderReaderWrapper : public PrimReaderWrapper<UsdMayaShaderReader> { public: typedef ShaderReaderWrapper This; typedef UsdMayaShaderReader base_t; ShaderReaderWrapper(const UsdMayaPrimReaderArgs& args) : PrimReaderWrapper<UsdMayaShaderReader>(args) { } static ShaderReaderWrapper* New(uintptr_t createdWrapper) { return (ShaderReaderWrapper*)createdWrapper; } virtual ~ShaderReaderWrapper() { } MPlug default_GetMayaPlugForUsdAttrName(const TfToken& usdAttrName, const MObject& mayaObject) const { return base_t::GetMayaPlugForUsdAttrName(usdAttrName, mayaObject); } MPlug GetMayaPlugForUsdAttrName(const TfToken& usdAttrName, const MObject& mayaObject) const override { return this->CallVirtual<MPlug>( "GetMayaPlugForUsdAttrName", &This::default_GetMayaPlugForUsdAttrName)(usdAttrName, mayaObject); } TfToken default_GetMayaNameForUsdAttrName(const TfToken& usdAttrName) const { return base_t::GetMayaNameForUsdAttrName(usdAttrName); } TfToken GetMayaNameForUsdAttrName(const TfToken& usdAttrName) const override { return this->CallVirtual<TfToken>( "GetMayaNameForUsdAttrName", &This::default_GetMayaNameForUsdAttrName)(usdAttrName); } void default_PostConnectSubtree(UsdMayaPrimReaderContext* context) { base_t::PostConnectSubtree(context); } void PostConnectSubtree(UsdMayaPrimReaderContext* context) override { this->CallVirtual<>("PostConnectSubtree", &This::default_PostConnectSubtree)(context); } bool default_IsConverter(UsdShadeShader& downstreamSchema, TfToken& downstreamOutputName) { return base_t::IsConverter(downstreamSchema, downstreamOutputName); } bool IsConverter(UsdShadeShader& downstreamSchema, TfToken& downstreamOutputName) override { return this->CallVirtual<bool>("IsConverter", &This::default_IsConverter)( downstreamSchema, downstreamOutputName); } void default_SetDownstreamReader(std::shared_ptr<UsdMayaShaderReader> downstreamReader) { base_t::SetDownstreamReader(downstreamReader); } void SetDownstreamReader(std::shared_ptr<UsdMayaShaderReader> downstreamReader) override { this->CallVirtual<>("SetDownstreamReader", &This::default_SetDownstreamReader)( downstreamReader); } MObject default_GetCreatedObject( const UsdMayaShadingModeImportContext& context, const UsdPrim& prim) const { return base_t::GetCreatedObject(context, prim); } MObject GetCreatedObject(const UsdMayaShadingModeImportContext& context, const UsdPrim& prim) const override { return this->CallVirtual<MObject>("GetCreatedObject", &This::default_GetCreatedObject)( context, prim); } static void Register(boost::python::object cl, const TfToken& usdInfoId) { UsdMayaShaderReaderRegistry::Register( usdInfoId, [=](const UsdMayaJobImportArgs& args) { return UsdMayaShaderReader::ContextSupport(0); }, [=](const UsdMayaPrimReaderArgs& args) { auto sptr = std::make_shared<ShaderReaderWrapper>(args); TfPyLock pyLock; boost::python::object instance = cl((uintptr_t)(ShaderReaderWrapper*)sptr.get()); boost::python::incref(instance.ptr()); initialize_wrapper(instance.ptr(), sptr.get()); return sptr; }, true); } }; //---------------------------------------------------------------------------------------------------------------------- void wrapPrimReaderContext() { boost::python::class_<UsdMayaPrimReaderContext>("PrimReaderContext", boost::python::no_init) .def( "GetMayaNode", &UsdMayaPrimReaderContext::GetMayaNode, boost::python::return_value_policy<boost::python::return_by_value>()) .def("RegisterNewMayaNode", &UsdMayaPrimReaderContext::RegisterNewMayaNode) .def("GetPruneChildren", &UsdMayaPrimReaderContext::GetPruneChildren) .def("SetPruneChildren", &UsdMayaPrimReaderContext::SetPruneChildren) .def("GetTimeSampleMultiplier", &UsdMayaPrimReaderContext::GetTimeSampleMultiplier) .def("SetTimeSampleMultiplier", &UsdMayaPrimReaderContext::SetTimeSampleMultiplier); } //---------------------------------------------------------------------------------------------------------------------- void wrapJobImportArgs() { boost::python::class_<UsdMayaJobImportArgs>("JobImportArgs", boost::python::no_init); } void wrapPrimReaderArgs() { boost::python::class_<UsdMayaPrimReaderArgs>("PrimReaderArgs", boost::python::no_init) .def( "GetUsdPrim", &UsdMayaPrimReaderArgs::GetUsdPrim, boost::python::return_internal_reference<>()) .def( "GetJobArguments", &UsdMayaPrimReaderArgs::GetJobArguments, boost::python::return_internal_reference<>()) .def("GetTimeInterval", &UsdMayaPrimReaderArgs::GetTimeInterval) .def( "GetIncludeMetadataKeys", &UsdMayaPrimReaderArgs::GetIncludeMetadataKeys, boost::python::return_internal_reference<>()) .def( "GetIncludeAPINames", &UsdMayaPrimReaderArgs::GetIncludeAPINames, boost::python::return_internal_reference<>()) .def( "GetExcludePrimvarNames", &UsdMayaPrimReaderArgs::GetExcludePrimvarNames, boost::python::return_internal_reference<>()) .def("GetUseAsAnimationCache", &UsdMayaPrimReaderArgs::GetUseAsAnimationCache); } void wrapPrimReader() { boost::python::class_<PrimReaderWrapper<>, boost::noncopyable>( "PrimReader", boost::python::no_init) .def("__init__", make_constructor(&PrimReaderWrapper<>::New)) .def("Read", boost::python::pure_virtual(&UsdMayaPrimReader::Read)) .def( "HasPostReadSubtree", &PrimReaderWrapper<>::HasPostReadSubtree, &PrimReaderWrapper<>::default_HasPostReadSubtree) .def( "PostReadSubtree", &PrimReaderWrapper<>::PostReadSubtree, &PrimReaderWrapper<>::default_PostReadSubtree) .def( "_GetArgs", &PrimReaderWrapper<>::_GetArgs, boost::python::return_internal_reference<>()) .def( "Register", &PrimReaderWrapper<>::Register, (boost::python::arg("class"), boost::python::arg("type"))) .staticmethod("Register"); } TF_REGISTRY_FUNCTION(TfEnum) { TF_ADD_ENUM_NAME(UsdMayaShaderReader::ContextSupport::Supported, "Supported"); TF_ADD_ENUM_NAME(UsdMayaShaderReader::ContextSupport::Fallback, "Fallback"); TF_ADD_ENUM_NAME(UsdMayaShaderReader::ContextSupport::Unsupported, "Unsupported"); } //---------------------------------------------------------------------------------------------------------------------- void wrapShaderReader() { boost::python:: class_<ShaderReaderWrapper, boost::python::bases<PrimReaderWrapper<>>, boost::noncopyable> c("ShaderReader", boost::python::no_init); boost::python::scope s(c); TfPyWrapEnum<UsdMayaShaderReader::ContextSupport>(); c.def("__init__", make_constructor(&ShaderReaderWrapper::New)) .def( "GetMayaPlugForUsdAttrName", &ShaderReaderWrapper::GetMayaPlugForUsdAttrName, &ShaderReaderWrapper::default_GetMayaPlugForUsdAttrName) .def( "GetMayaNameForUsdAttrName", &ShaderReaderWrapper::GetMayaNameForUsdAttrName, &ShaderReaderWrapper::default_GetMayaNameForUsdAttrName) .def( "PostConnectSubtree", &ShaderReaderWrapper::PostConnectSubtree, &ShaderReaderWrapper::default_PostConnectSubtree) .def( "IsConverter", &ShaderReaderWrapper::IsConverter, &ShaderReaderWrapper::default_IsConverter) .def( "SetDownstreamReader", &ShaderReaderWrapper::SetDownstreamReader, &ShaderReaderWrapper::default_SetDownstreamReader) .def( "GetCreatedObject", &ShaderReaderWrapper::GetCreatedObject, &ShaderReaderWrapper::default_GetCreatedObject) .def( "Register", &ShaderReaderWrapper::Register, (boost::python::arg("class"), boost::python::arg("mayaTypeName"))) .staticmethod("Register"); } <file_sep>/lib/usd/translators/shading/mtlxBaseWriter.cpp // // Copyright 2021 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "mtlxBaseWriter.h" #include "shadingTokens.h" #include <mayaUsd/fileio/primWriterRegistry.h> #include <mayaUsd/fileio/shaderWriter.h> #include <mayaUsd/fileio/shading/shadingModeRegistry.h> #include <mayaUsd/fileio/utils/writeUtil.h> #include <mayaUsd/fileio/writeJobContext.h> #include <mayaUsd/utils/converter.h> #include <mayaUsd/utils/util.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/base/tf/staticTokens.h> #include <pxr/base/tf/token.h> #include <pxr/base/vt/value.h> #include <pxr/pxr.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/sdf/types.h> #include <pxr/usd/sdf/valueTypeName.h> #include <pxr/usd/usd/timeCode.h> #include <pxr/usd/usdShade/input.h> #include <pxr/usd/usdShade/output.h> #include <pxr/usd/usdShade/shader.h> #include <pxr/usd/usdShade/tokens.h> #include <pxr/usdImaging/usdImaging/tokens.h> #include <maya/MFnDependencyNode.h> #include <maya/MObject.h> #include <maya/MPlug.h> #include <maya/MStatus.h> #include <maya/MString.h> #include <cmath> using namespace MAYAUSD_NS_DEF; PXR_NAMESPACE_OPEN_SCOPE // clang-format off TF_DEFINE_PRIVATE_TOKENS( _tokens, ((nodeGraphPrefix, "MayaNG")) // Prefix for conversion nodes: ((ConverterPrefix, "MayaConvert")) ((SwizzlePrefix, "MayaSwizzle")) ((LuminancePrefix, "MayaLuminance")) ((NormalMapPrefix, "MayaNormalMap")) ); // clang-format on REGISTER_SHADING_MODE_EXPORT_MATERIAL_CONVERSION( TrMtlxTokens->conversionName, TrMtlxTokens->contextName, TrMtlxTokens->niceName, TrMtlxTokens->exportDescription); UsdMayaShaderWriter::ContextSupport MtlxUsd_BaseWriter::CanExport(const UsdMayaJobExportArgs& exportArgs) { return exportArgs.convertMaterialsTo == TrMtlxTokens->conversionName ? ContextSupport::Supported : ContextSupport::Unsupported; } MtlxUsd_BaseWriter::MtlxUsd_BaseWriter( const MFnDependencyNode& depNodeFn, const SdfPath& usdPath, UsdMayaWriteJobContext& jobCtx) : UsdMayaShaderWriter(depNodeFn, usdPath, jobCtx) { } UsdPrim MtlxUsd_BaseWriter::GetNodeGraph() { SdfPath materialPath = GetUsdPath().GetParentPath(); TfToken ngName(TfStringPrintf( "%s_%s", _tokens->nodeGraphPrefix.GetText(), materialPath.GetName().c_str())); SdfPath ngPath = materialPath.AppendChild(ngName); return UsdShadeNodeGraph::Define(GetUsdStage(), ngPath).GetPrim(); } UsdAttribute MtlxUsd_BaseWriter::AddConversion( const SdfValueTypeName& fromType, const SdfValueTypeName& toType, UsdAttribute nodeOutput) { // We currently only support color3f to vector3f for normal maps: if (fromType == SdfValueTypeNames->Color3f && toType == SdfValueTypeNames->Float3) { MStatus status; const MFnDependencyNode depNodeFn(GetMayaObject(), &status); if (status != MS::kSuccess) { return UsdAttribute(); } UsdShadeNodeGraph nodegraphSchema(GetNodeGraph()); SdfPath nodegraphPath = nodegraphSchema.GetPath(); TfToken converterName(TfStringPrintf( "%s_%s_%s_%s", _tokens->ConverterPrefix.GetText(), depNodeFn.name().asChar(), fromType.GetAsToken().GetText(), toType.GetAsToken().GetText())); const SdfPath converterPath = nodegraphPath.AppendChild(converterName); UsdShadeShader converterSchema = UsdShadeShader::Define(GetUsdStage(), converterPath); UsdAttribute converterOutput = converterSchema.GetOutput(TrMtlxTokens->out); if (converterOutput) { // Reusing existing node: return converterOutput; } converterSchema.CreateIdAttr(VtValue(TrMtlxTokens->ND_convert_color3_vector3)); converterSchema.CreateInput(TrMtlxTokens->in, SdfValueTypeNames->Color3f) .ConnectToSource(UsdShadeOutput(nodeOutput)); converterOutput = converterSchema.CreateOutput(TrMtlxTokens->out, SdfValueTypeNames->Float3); return converterOutput; } return UsdAttribute(); } UsdAttribute MtlxUsd_BaseWriter::AddSwizzle(const std::string& channels, int numChannels) { UsdAttribute nodeOutput = UsdShadeShader(_usdPrim).GetOutput(TrMtlxTokens->out); return AddSwizzle(channels, numChannels, nodeOutput); } UsdAttribute MtlxUsd_BaseWriter::AddSwizzle( const std::string& channels, int numChannels, UsdAttribute nodeOutput) { if (numChannels == static_cast<int>(channels.size())) { // No swizzle actually needed: return nodeOutput; } UsdShadeNodeGraph nodegraphSchema(GetNodeGraph()); SdfPath nodegraphPath = nodegraphSchema.GetPath(); SdfPath outputPath = nodeOutput.GetPath().GetParentPath(); TfToken swizzleName(TfStringPrintf( "%s_%s_%s", _tokens->SwizzlePrefix.GetText(), outputPath.GetName().c_str(), channels.c_str())); const SdfPath swizzlePath = nodegraphPath.AppendChild(swizzleName); UsdShadeShader swizzleSchema = UsdShadeShader::Define(GetUsdStage(), swizzlePath); UsdAttribute swizzleOutput = swizzleSchema.GetOutput(TrMtlxTokens->out); if (swizzleOutput) { // Reusing existing node: return swizzleOutput; } // The swizzle name varies according to source and destination channel sizes: std::string srcType, dstType; switch (numChannels) { case 1: srcType = "float"; swizzleSchema.CreateInput(TrMtlxTokens->in, SdfValueTypeNames->Float) .ConnectToSource(UsdShadeOutput(nodeOutput)); break; case 2: srcType = "vector2"; swizzleSchema.CreateInput(TrMtlxTokens->in, SdfValueTypeNames->Float2) .ConnectToSource(UsdShadeOutput(nodeOutput)); break; case 3: srcType = "color3"; swizzleSchema.CreateInput(TrMtlxTokens->in, SdfValueTypeNames->Color3f) .ConnectToSource(UsdShadeOutput(nodeOutput)); break; case 4: srcType = "color4"; swizzleSchema.CreateInput(TrMtlxTokens->in, SdfValueTypeNames->Color4f) .ConnectToSource(UsdShadeOutput(nodeOutput)); break; default: TF_CODING_ERROR("Unsupported format for swizzle"); return UsdAttribute(); } swizzleSchema.CreateInput(TrMtlxTokens->channels, SdfValueTypeNames->String) .Set(channels, UsdTimeCode::Default()); switch (channels.size()) { case 1: dstType = "float"; swizzleOutput = swizzleSchema.CreateOutput(TrMtlxTokens->out, SdfValueTypeNames->Float); break; case 2: dstType = "vector2"; swizzleOutput = swizzleSchema.CreateOutput(TrMtlxTokens->out, SdfValueTypeNames->Float2); break; case 3: dstType = "color3"; swizzleOutput = swizzleSchema.CreateOutput(TrMtlxTokens->out, SdfValueTypeNames->Color3f); break; case 4: dstType = "color4"; swizzleOutput = swizzleSchema.CreateOutput(TrMtlxTokens->out, SdfValueTypeNames->Color4f); break; } TfToken swizzleID(TfStringPrintf("ND_swizzle_%s_%s", srcType.c_str(), dstType.c_str())); swizzleSchema.CreateIdAttr(VtValue(swizzleID)); return swizzleOutput; } UsdAttribute MtlxUsd_BaseWriter::AddLuminance(int numChannels) { UsdAttribute nodeOutput = UsdShadeShader(_usdPrim).GetOutput(TrMtlxTokens->out); if (numChannels < 3) { // Not enough channels: return nodeOutput; } MStatus status; const MFnDependencyNode depNodeFn(GetMayaObject(), &status); if (status != MS::kSuccess) { return UsdAttribute(); } UsdShadeNodeGraph nodegraphSchema(GetNodeGraph()); SdfPath nodegraphPath = nodegraphSchema.GetPath(); TfToken luminanceName( TfStringPrintf("%s_%s", _tokens->LuminancePrefix.GetText(), depNodeFn.name().asChar())); const SdfPath luminancePath = nodegraphPath.AppendChild(luminanceName); UsdShadeShader luminanceSchema = UsdShadeShader::Define(GetUsdStage(), luminancePath); UsdAttribute luminanceOutput = luminanceSchema.GetOutput(TrMtlxTokens->out); if (luminanceOutput) { // Reusing existing node: return luminanceOutput; } switch (numChannels) { case 3: luminanceSchema.CreateIdAttr(VtValue(TrMtlxTokens->ND_luminance_color3)); luminanceSchema.CreateInput(TrMtlxTokens->in, SdfValueTypeNames->Color3f) .ConnectToSource(UsdShadeOutput(nodeOutput)); luminanceOutput = luminanceSchema.CreateOutput(TrMtlxTokens->out, SdfValueTypeNames->Color3f); break; case 4: luminanceSchema.CreateIdAttr(VtValue(TrMtlxTokens->ND_luminance_color4)); luminanceSchema.CreateInput(TrMtlxTokens->in, SdfValueTypeNames->Color4f) .ConnectToSource(UsdShadeOutput(nodeOutput)); luminanceOutput = luminanceSchema.CreateOutput(TrMtlxTokens->out, SdfValueTypeNames->Color4f); break; default: TF_CODING_ERROR("Unsupported format for luminance"); return UsdAttribute(); } return AddSwizzle("r", numChannels, luminanceOutput); } UsdAttribute MtlxUsd_BaseWriter::AddNormalMapping(UsdAttribute normalInput) { // For standard surface (and not preview surface) // We are starting at the NodeGraph boundary and building a chain that will // eventually reach an image node MStatus status; const MFnDependencyNode depNodeFn(GetMayaObject(), &status); if (status != MS::kSuccess) { return UsdAttribute(); } UsdShadeNodeGraph nodegraphSchema(GetNodeGraph()); SdfPath nodegraphPath = nodegraphSchema.GetPath(); // Normal map: TfToken nodeName(TfStringPrintf( "%s_%s_%s", _tokens->NormalMapPrefix.GetText(), depNodeFn.name().asChar(), normalInput.GetBaseName().GetText())); SdfPath nodePath = nodegraphPath.AppendChild(nodeName); UsdShadeShader nodeSchema = UsdShadeShader::Define(GetUsdStage(), nodePath); nodeSchema.CreateIdAttr(VtValue(TrMtlxTokens->ND_normalmap)); UsdShadeInput mapInput = nodeSchema.CreateInput(TrMtlxTokens->in, SdfValueTypeNames->Float3); UsdShadeOutput mapOutput = nodeSchema.CreateOutput(TrMtlxTokens->out, SdfValueTypeNames->Float3); UsdShadeOutput(normalInput).ConnectToSource(UsdShadeOutput(mapOutput)); return mapInput; } PXR_NAMESPACE_CLOSE_SCOPE <file_sep>/lib/mayaUsd/ufe/UsdCamera.cpp // // Copyright 2020 Autodesk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "UsdCamera.h" #include "private/Utils.h" #include "pxr/base/gf/frustum.h" #include "pxr/usd/usdGeom/camera.h" #include "pxr/usd/usdGeom/metrics.h" #include <mayaUsd/ufe/Utils.h> #include <mayaUsd/utils/util.h> #include <pxr/imaging/hd/camera.h> namespace MAYAUSD_NS_DEF { namespace ufe { UsdCamera::UsdCamera() : Camera() { } UsdCamera::UsdCamera(const UsdSceneItem::Ptr& item) : Camera() , fItem(item) { } /* static */ UsdCamera::Ptr UsdCamera::create(const UsdSceneItem::Ptr& item) { return std::make_shared<UsdCamera>(item); } /* static */ bool UsdCamera::isCameraToken(const PXR_NS::TfToken& token) { static std::unordered_set<PXR_NS::TfToken, PXR_NS::TfToken::HashFunctor> cameraTokens { HdCameraTokens->horizontalAperture, HdCameraTokens->verticalAperture, HdCameraTokens->horizontalApertureOffset, HdCameraTokens->verticalApertureOffset, HdCameraTokens->focalLength, HdCameraTokens->clippingRange, HdCameraTokens->fStop }; // There are more HdCameraTokens that Maya ignores: // worldToViewMatrix, projectionMatrix, clipPlanes, windowPolicy, shutterOpen, // shutterClose return cameraTokens.count(token) > 0; } //------------------------------------------------------------------------------ // Ufe::Camera overrides //------------------------------------------------------------------------------ const Ufe::Path& UsdCamera::path() const { return fItem->path(); } Ufe::SceneItem::Ptr UsdCamera::sceneItem() const { return fItem; } Ufe::HorizontalApertureUndoableCommand::Ptr UsdCamera::horizontalApertureCmd(float horizontalAperture) { return nullptr; } float UsdCamera::horizontalAperture() const { // inspired by UsdImagingCameraAdapter::UpdateForTime UsdGeomCamera usdGeomCamera(prim()); GfCamera gfCamera = usdGeomCamera.GetCamera(getTime(sceneItem()->path())); // The USD schema specifies horizontal aperture in tenths of a stage unit. Store // the horizontal aperture in stage units. float horizontalAperture = gfCamera.GetHorizontalAperture() / 10.0f; // Convert the horizontal aperture value to inches, the return unit of this function. // Figure out the stage unit UsdStageWeakPtr stage = prim().GetStage(); double stageUnits = UsdGeomLinearUnits::centimeters; if (UsdGeomStageHasAuthoredMetersPerUnit(stage)) { stageUnits = UsdGeomGetStageMetersPerUnit(stage); } return UsdMayaUtil::ConvertUnit(horizontalAperture, stageUnits, UsdGeomLinearUnits::inches); } Ufe::VerticalApertureUndoableCommand::Ptr UsdCamera::verticalApertureCmd(float verticalAperture) { return nullptr; } float UsdCamera::verticalAperture() const { // inspired by UsdImagingCameraAdapter::UpdateForTime UsdGeomCamera usdGeomCamera(prim()); GfCamera gfCamera = usdGeomCamera.GetCamera(getTime(sceneItem()->path())); // The USD schema specifies vertical aperture in tenths of a stage unit. Store // the vertical aperture in stage units. float verticalAperture = gfCamera.GetVerticalAperture() / 10.0f; // Convert the vertical aperture value to inches, the return unit of this function. // Figure out the stage unit UsdStageWeakPtr stage = prim().GetStage(); double stageUnits = UsdGeomLinearUnits::centimeters; if (UsdGeomStageHasAuthoredMetersPerUnit(stage)) { stageUnits = UsdGeomGetStageMetersPerUnit(stage); } return UsdMayaUtil::ConvertUnit(verticalAperture, stageUnits, UsdGeomLinearUnits::inches); } Ufe::HorizontalApertureOffsetUndoableCommand::Ptr UsdCamera::horizontalApertureOffsetCmd(float) { return nullptr; } float UsdCamera::horizontalApertureOffset() const { // inspired by UsdImagingCameraAdapter::UpdateForTime UsdGeomCamera usdGeomCamera(prim()); GfCamera gfCamera = usdGeomCamera.GetCamera(getTime(sceneItem()->path())); // The USD schema specifies horizontal aperture offset in tenths of a stage unit. Store // the horizontal aperture offset in stage units. float horizontalApertureOffset = gfCamera.GetHorizontalApertureOffset() / 10.0f; // Convert the horizontal aperture offset value to inches, the return unit of this function. // Figure out the stage unit UsdStageWeakPtr stage = prim().GetStage(); double stageUnits = UsdGeomLinearUnits::centimeters; if (UsdGeomStageHasAuthoredMetersPerUnit(stage)) { stageUnits = UsdGeomGetStageMetersPerUnit(stage); } return UsdMayaUtil::ConvertUnit( horizontalApertureOffset, stageUnits, UsdGeomLinearUnits::inches); } Ufe::VerticalApertureOffsetUndoableCommand::Ptr UsdCamera::verticalApertureOffsetCmd(float) { return nullptr; } float UsdCamera::verticalApertureOffset() const { // inspired by UsdImagingCameraAdapter::UpdateForTime UsdGeomCamera usdGeomCamera(prim()); GfCamera gfCamera = usdGeomCamera.GetCamera(getTime(sceneItem()->path())); // The USD schema specifies vertical aperture offset in tenths of a stage unit. Store // the vertical aperture offset in stage units. float verticalApertureOffset = gfCamera.GetVerticalApertureOffset() / 10.0f; // Convert the vertical aperture offset value to inches, the return unit of this function. // Figure out the stage unit UsdStageWeakPtr stage = prim().GetStage(); double stageUnits = UsdGeomLinearUnits::centimeters; if (UsdGeomStageHasAuthoredMetersPerUnit(stage)) { stageUnits = UsdGeomGetStageMetersPerUnit(stage); } return UsdMayaUtil::ConvertUnit(verticalApertureOffset, stageUnits, UsdGeomLinearUnits::inches); } Ufe::FStopUndoableCommand::Ptr UsdCamera::fStopCmd(float) { return nullptr; } float UsdCamera::fStop() const { // inspired by UsdImagingCameraAdapter::UpdateForTime UsdGeomCamera usdGeomCamera(prim()); GfCamera gfCamera = usdGeomCamera.GetCamera(getTime(sceneItem()->path())); // The USD schema specifies fStop in stage units. Store the fStop in stage units. float fStop = gfCamera.GetFStop(); // Convert the fStop value to mm, the return unit of this function. // Figure out the stage unit UsdStageWeakPtr stage = prim().GetStage(); double stageUnits = UsdGeomLinearUnits::centimeters; if (UsdGeomStageHasAuthoredMetersPerUnit(stage)) { stageUnits = UsdGeomGetStageMetersPerUnit(stage); } #if MAYA_API_VERSION >= 20220100 return UsdMayaUtil::ConvertUnit(fStop, stageUnits, UsdGeomLinearUnits::millimeters); #else float retVal = UsdMayaUtil::ConvertUnit(fStop, stageUnits, UsdGeomLinearUnits::millimeters); return retVal < FLT_EPSILON ? FLT_EPSILON : retVal; #endif } Ufe::FocalLengthUndoableCommand::Ptr UsdCamera::focalLengthCmd(float) { return nullptr; } float UsdCamera::focalLength() const { // inspired by UsdImagingCameraAdapter::UpdateForTime UsdGeomCamera usdGeomCamera(prim()); GfCamera gfCamera = usdGeomCamera.GetCamera(getTime(sceneItem()->path())); // The USD schema specifies focal length in tenths of a stage unit. Store the focal length in // stage units. float focalLength = gfCamera.GetFocalLength() / 10.0f; // Convert the focal length value to mm, the return unit of this function. // Figure out the stage unit UsdStageWeakPtr stage = prim().GetStage(); double stageUnits = UsdGeomLinearUnits::centimeters; if (UsdGeomStageHasAuthoredMetersPerUnit(stage)) { stageUnits = UsdGeomGetStageMetersPerUnit(stage); } return UsdMayaUtil::ConvertUnit(focalLength, stageUnits, UsdGeomLinearUnits::millimeters); } Ufe::FocusDistanceUndoableCommand::Ptr UsdCamera::focusDistanceCmd(float) { return nullptr; } float UsdCamera::focusDistance() const { // inspired by UsdImagingCameraAdapter::UpdateForTime UsdGeomCamera usdGeomCamera(prim()); GfCamera gfCamera = usdGeomCamera.GetCamera(getTime(sceneItem()->path())); // The USD schema specifies focus distance in stage units. Store the focus distance in // stage units. float focusDistance = gfCamera.GetFocusDistance(); // Convert the focus distance value to cm, the return unit of this function. // Figure out the stage unit UsdStageWeakPtr stage = prim().GetStage(); double stageUnits = UsdGeomLinearUnits::centimeters; if (UsdGeomStageHasAuthoredMetersPerUnit(stage)) { stageUnits = UsdGeomGetStageMetersPerUnit(stage); } return UsdMayaUtil::ConvertUnit(focusDistance, stageUnits, UsdGeomLinearUnits::centimeters); } Ufe::NearClipPlaneUndoableCommand::Ptr UsdCamera::nearClipPlaneCmd(float) { return nullptr; } float UsdCamera::nearClipPlane() const { // inspired by UsdImagingCameraAdapter::UpdateForTime UsdGeomCamera usdGeomCamera(prim()); GfCamera gfCamera = usdGeomCamera.GetCamera(getTime(sceneItem()->path())); // The USD schema specifies near clip plane in stage units. Store the near clip plane in // stage units. GfRange1f clippingRange = gfCamera.GetClippingRange(); float nearClipPlane = clippingRange.GetMin(); // Ufe doesn't convert linear units for prim size or translation, so don't convert the // clipping plane. return nearClipPlane; } Ufe::FarClipPlaneUndoableCommand::Ptr UsdCamera::farClipPlaneCmd(float) { return nullptr; } float UsdCamera::farClipPlane() const { // inspired by UsdImagingCameraAdapter::UpdateForTime UsdGeomCamera usdGeomCamera(prim()); GfCamera gfCamera = usdGeomCamera.GetCamera(getTime(sceneItem()->path())); // The USD schema specifies far clip plane in stage units. Store the far clip plane in // stage units. GfRange1f clippingRange = gfCamera.GetClippingRange(); float farClipPlane = clippingRange.GetMax(); // Ufe doesn't convert linear units for prim size or translation, so don't convert the // clipping plane. return farClipPlane; } Ufe::ProjectionUndoableCommand::Ptr UsdCamera::projectionCmd(Ufe::Camera::Projection projection) { return nullptr; } Ufe::Camera::Projection UsdCamera::projection() const { // inspired by UsdImagingCameraAdapter::UpdateForTime UsdGeomCamera usdGeomCamera(prim()); GfCamera gfCamera = usdGeomCamera.GetCamera(getTime(sceneItem()->path())); // The USD schema specifics some camera parameters is tenths of a world // unit (e.g., focalLength = 50mm). Convert to world units. if (GfCamera::Orthographic == gfCamera.GetProjection()) { return Ufe::Camera::Orthographic; } return Ufe::Camera::Perspective; } } // namespace ufe } // namespace MAYAUSD_NS_DEF <file_sep>/plugin/al/schemas/codegenTemplates/tokens.h // // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef {{ Upper(tokensPrefix) }}_TOKENS_H #define {{ Upper(tokensPrefix) }}_TOKENS_H /// \file {{ libraryName }}/tokens.h // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // // This is an automatically generated file (by usdGenSchema.py). // Do not hand-edit! // // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX {% if useExportAPI %} #include <pxr/pxr.h> #include "{{ libraryPath }}/api.h" {% endif %} #include <pxr/base/tf/staticTokens.h> {% if useExportAPI %} {{ namespaceOpen }} {% endif %} // clang-format off /// \hideinitializer #define {{ Upper(tokensPrefix) }}_TOKENS \ {% for token in tokens %} {% if token.id == token.value -%}({{ token.id }}) {%- else -%} (({{ token.id }}, "{{ token.value}}")) {%- endif -%}{% if not loop.last %} \{% endif %} // clang-format on {% endfor %} /// \anchor {{ tokensPrefix }}Tokens /// /// <b>{{ tokensPrefix }}Tokens</b> provides static, efficient TfToken's for /// use in all public USD API /// /// These tokens are auto-generated from the module's schema, representing /// property names, for when you need to fetch an attribute or relationship /// directly by name, e.g. UsdPrim::GetAttribute(), in the most efficient /// manner, and allow the compiler to verify that you spelled the name /// correctly. /// /// {{ tokensPrefix }}Tokens also contains all of the \em allowedTokens values declared /// for schema builtin attributes of 'token' scene description type. /// Use {{ tokensPrefix }}Tokens like so: /// /// \code /// gprim.GetVisibilityAttr().Set({{ tokensPrefix }}Tokens->invisible); /// \endcode /// /// The tokens are: {% for token in tokens %} /// \li <b>{{ token.id }}</b> - {{ token.desc }} {% endfor %} TF_DECLARE_PUBLIC_TOKENS({{ tokensPrefix }}Tokens, {% if useExportAPI %}{{ Upper(libraryName) }}_API, {% endif %}{{ Upper(tokensPrefix) }}_TOKENS); {% if useExportAPI %} {{ namespaceClose }} {% endif %} #endif
d9bb8ca564d8bc6844f97dc823a12bcb0ecd8ed7
[ "CMake", "Markdown", "Python", "C", "C++" ]
105
CMake
HamedSabri-adsk/maya-usd
17f30694a08a241ce248d19742f24242b5924aec
2cbd40e046c668a176c608fa76c28d472d1e86e1
refs/heads/master
<file_sep># Reproducible Research: Peer Assessment 1 ## Loading and preprocessing the data ```r file <- unzip("activity.zip") dataset <- read.csv(file,sep = ",", header = TRUE, stringsAsFactors = FALSE) data <- dataset[which(!is.na(dataset$steps)),] ``` ## What is mean total number of steps taken per day? ```r nrsteps <-tapply(data$steps, data$date, sum) #Show histogram hist(nrsteps, main ="Total # of steps per days", xlab = "", col="blue") ``` ![](PA1_template_files/figure-html/unnamed-chunk-2-1.png) ```r # What is the mean total number of steps taken per day? mean(nrsteps) ``` ``` ## [1] 10766.19 ``` ```r # What is the median total number of steps taken per day? median(nrsteps) ``` ``` ## [1] 10765 ``` ## What is the average daily activity pattern? ```r #What is the average daily activity pattern? dailysteps <-tapply(data$steps, data$interval, mean) #Show plot plot(y = dailysteps,x = names(dailysteps), type = "l", xlab = "5-minute interval", main = "Average Daily Activity Pattern", ylab = "Average # of steps") ``` ![](PA1_template_files/figure-html/unnamed-chunk-3-1.png) ```r #What is the maximum amount? max(dailysteps) ``` ``` ## [1] 206.1698 ``` ```r #What is the corresponding interval? dailysteps[dailysteps == max(dailysteps)] ``` ``` ## 835 ## 206.1698 ``` ## Imputing missing values ```r #Inputting missing values data <- dataset data[which(is.na(data$steps)),1] <- dailysteps[as.character(data[which(is.na(data$steps)),3])] dailysteps_new<-tapply(data$steps, data$date, sum) #Show new histogram hist(dailysteps_new, main = "Total # of steps per day", xlab = "",col="red") ``` ![](PA1_template_files/figure-html/unnamed-chunk-4-1.png) ```r #Calculating new mean and median mean(dailysteps_new) ``` ``` ## [1] 10766.19 ``` ```r median(dailysteps_new) ``` ``` ## [1] 10766.19 ``` ```r #Do the values differ from before? What is the impact? mean(nrsteps)-mean(dailysteps_new) ``` ``` ## [1] 0 ``` ```r median(nrsteps)-median(dailysteps_new) ``` ``` ## [1] -1.188679 ``` As can be seen, the impact on the mean and median is relatively small. ```r ## Are there differences in activity patterns between weekdays and weekends? #Convert dates to date format data$date <- as.Date(data$date) #Use weekdays function data$weekday <- weekdays(data$date) #Add typeofday dayType <- function(dates) { f <- function(date) { if (weekdays(date) %in% c("zaterdag", "zondag")) { "weekend" } else { "weekday" } } sapply(dates, f) } data$typeofday <- as.factor(dayType(data$date)) #Creating subsets of data data_weekend <- subset(data, typeofday == "weekend") data_weekday <- subset(data, typeofday == "weekday") #Calculate new daily steps per weekend and weekday dailysteps_weekend <- tapply(data_weekend$steps, data_weekend$interval, mean) dailysteps_weekday <- tapply(data_weekday$steps, data_weekday$interval, mean) #Make plot for weekend plot(y = dailysteps_weekend, x = names(dailysteps_weekend), type = "l", xlab = "5-minute interval", main = "Average Daily Activity Pattern in weekend", ylab = "Average # of steps") ``` ![](PA1_template_files/figure-html/unnamed-chunk-5-1.png) ```r #Make plot for weekday plot(y = dailysteps_weekday,x = names(dailysteps_weekday), type = "l", xlab = "5-minute interval", main = "Average Daily Activity Pattern on weekdays", ylab = "Average # of steps") ``` ![](PA1_template_files/figure-html/unnamed-chunk-5-2.png) As can be seen in the plots, the activity patterns differ quite a bit between the weekdays and weekend. <file_sep>--- title: "Reproducible Research: Peer Assessment 1" output: html_document: keep_md: true --- ## Loading and preprocessing the data ```{r} file <- unzip("activity.zip") dataset <- read.csv(file,sep = ",", header = TRUE, stringsAsFactors = FALSE) data <- dataset[which(!is.na(dataset$steps)),] ``` ## What is mean total number of steps taken per day? ```{r} nrsteps <-tapply(data$steps, data$date, sum) #Show histogram hist(nrsteps, main ="Total # of steps per days", xlab = "", col="blue") # What is the mean total number of steps taken per day? mean(nrsteps) # What is the median total number of steps taken per day? median(nrsteps) ``` ## What is the average daily activity pattern? ```{r} #What is the average daily activity pattern? dailysteps <-tapply(data$steps, data$interval, mean) #Show plot plot(y = dailysteps,x = names(dailysteps), type = "l", xlab = "5-minute interval", main = "Average Daily Activity Pattern", ylab = "Average # of steps") #What is the maximum amount? max(dailysteps) #What is the corresponding interval? dailysteps[dailysteps == max(dailysteps)] ``` ## Imputing missing values ```{r} #Inputting missing values data <- dataset data[which(is.na(data$steps)),1] <- dailysteps[as.character(data[which(is.na(data$steps)),3])] dailysteps_new<-tapply(data$steps, data$date, sum) #Show new histogram hist(dailysteps_new, main = "Total # of steps per day", xlab = "",col="red") #Calculating new mean and median mean(dailysteps_new) median(dailysteps_new) #Do the values differ from before? What is the impact? mean(nrsteps)-mean(dailysteps_new) median(nrsteps)-median(dailysteps_new) ``` As can be seen, the impact on the mean and median is relatively small. ```{r} ## Are there differences in activity patterns between weekdays and weekends? #Convert dates to date format data$date <- as.Date(data$date) #Use weekdays function data$weekday <- weekdays(data$date) #Add typeofday dayType <- function(dates) { f <- function(date) { if (weekdays(date) %in% c("zaterdag", "zondag")) { "weekend" } else { "weekday" } } sapply(dates, f) } data$typeofday <- as.factor(dayType(data$date)) #Creating subsets of data data_weekend <- subset(data, typeofday == "weekend") data_weekday <- subset(data, typeofday == "weekday") #Calculate new daily steps per weekend and weekday dailysteps_weekend <- tapply(data_weekend$steps, data_weekend$interval, mean) dailysteps_weekday <- tapply(data_weekday$steps, data_weekday$interval, mean) #Make plot for weekend plot(y = dailysteps_weekend, x = names(dailysteps_weekend), type = "l", xlab = "5-minute interval", main = "Average Daily Activity Pattern in weekend", ylab = "Average # of steps") #Make plot for weekday plot(y = dailysteps_weekday,x = names(dailysteps_weekday), type = "l", xlab = "5-minute interval", main = "Average Daily Activity Pattern on weekdays", ylab = "Average # of steps") ``` As can be seen in the plots, the activity patterns differ quite a bit between the weekdays and weekend.<file_sep> setwd("C:/Users/Jvandegevel/Documents/Coursera/Reproducible Research") file <- unzip("activity.zip") dataset <- read.csv(file,sep = ",", header = TRUE, stringsAsFactors = FALSE) data <- dataset[which(!is.na(dataset$steps)),] nrsteps <-tapply(data$steps, data$date, sum) #Show histogram hist(nrsteps, main ="Total # of steps per days", xlab = "", col="blue") # What are the mean and median total number of steps taken per day? mean(nrsteps) median(nrsteps) #What is the average daily activity pattern? dailysteps <-tapply(data$steps, data$interval, mean) plot(y = dailysteps,x = names(dailysteps), type = "l", xlab = "5-minute interval", main = "Average Daily Activity Pattern", ylab = "Average # of steps") max(dailysteps) dailysteps[dailysteps == max(dailysteps)] #Inputting missing values data <- dataset data[which(is.na(data$steps)),1] <- dailysteps[as.character(data[which(is.na(data$steps)),3])] dailysteps_new<-tapply(data$steps, data$date, sum) #Show new histogram hist(dailysteps_new, main = "Total # of steps per day", xlab = "",col="red") #Calculating new mean and median mean(dailysteps_new) median(dailysteps_new) #Convert dates to date format data$date <- as.Date(data$date) #Use weekdays function data$weekday <- weekdays(data$date) #Add typeofday dayType <- function(dates) { f <- function(date) { if (weekdays(date) %in% c("zaterdag", "zondag")) { "weekend" } else { "weekday" } } sapply(dates, f) } data$typeofday <- as.factor(dayType(data$date)) #Creating subsets of data data_weekend <- subset(data, typeofday == "weekend") data_weekday <- subset(data, typeofday == "weekday") #Calculate new daily steps per weekend and weekday dailysteps_weekend <- tapply(data_weekend$steps, data_weekend$interval, mean) dailysteps_weekday <- tapply(data_weekday$steps, data_weekday$interval, mean) #Make plot for weekend plot(y = dailysteps_weekend, x = names(dailysteps_weekend), type = "l", xlab = "5-minute interval", main = "Average Daily Activity Pattern in weekend", ylab = "Average # of steps") #Make plot for weekday plot(y = dailysteps_weekday,x = names(dailysteps_weekday), type = "l", xlab = "5-minute interval", main = "Average Daily Activity Pattern on weekdays", ylab = "Average # of steps")
dd6b81582b664731db7d590daf9b9ec278b95d65
[ "Markdown", "R", "RMarkdown" ]
3
Markdown
GdvJ/RepData_PeerAssessment1
a84243bb319c9d77f3d9150762851a64bcb649e0
56221e51e16653a9d20ea432e2378a1add1d8b25
refs/heads/master
<file_sep> <!-- Tab Content !--> <table class="optiontable form-table"> <tbody> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('audio_enable')) ?>"><?php esc_html_e('Enable', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('audio_enable')) ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('audio_enable'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('audio_enable')); ?>"/> <label></label> </div> </td> </tr> <tr valign="top"> <th scope="row"> <label><?php esc_html_e('Audio', 'live-sales-notifications') ?></label> </th> <td> <?php $audios = self::get_audios(); ?> <select name="<?php echo esc_attr(live_sales_notifications_set_field('audio')) ?>" class="mbui fluid dropdown"> <?php foreach ($audios as $audio) { ?> <option <?php selected(live_sales_notifications_get_field('audio', 'cool'), $audio) ?> value="<?php echo esc_attr($audio) ?>"><?php echo esc_html($audio) ?></option> <?php } ?> </select> <p class="description"><?php echo esc_html__('Please select audio. Notification rings when show.', 'live-sales-notifications') ?></p> </td> </tr> </tbody> </table><file_sep><!-- Tab Content !--> <?php /** * * @var $main_instance Live_Sales_Notifications */ ?> <table class="optiontable form-table"> <tbody> <tr valign="top"> <th scope="row"> <label><?php esc_html_e('Show Products', 'live-sales-notifications') ?></label> </th> <td> <select name="<?php echo esc_attr(live_sales_notifications_set_field('show_product_option')); ?>" class="mbui fluid dropdown"> <option <?php selected(live_sales_notifications_get_field('show_product_option'), 0) ?> value="0"><?php esc_attr_e('Get from Billing', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('show_product_option'), 1) ?> value="1"><?php esc_attr_e('Select Products', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('show_product_option'), 2) ?> value="2"><?php esc_attr_e('Latest Products', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('show_product_option'), 3) ?> value="3"><?php esc_attr_e('Select Categories', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('show_product_option'), 4) ?> value="4"><?php esc_attr_e('Recently Viewed Products', 'live-sales-notifications') ?></option> </select> <p class="description"><?php esc_html_e('You can arrange product order or special product which you want to up-sell.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('enable_out_of_stock_product')); ?>"><?php esc_html_e('Out-of-stock products', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('enable_out_of_stock_product')); ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('enable_out_of_stock_product'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('enable_out_of_stock_product')); ?>"/> <label></label> </div> <p class="description"><?php esc_html_e('Turn on to show out-of-stock products on notifications.', 'live-sales-notifications') ?></p> </td> </tr> <!-- Select Categories--> <tr valign="top" class="select-categories hidden"> <th scope="row"> <label><?php esc_html_e('Select Categories', 'live-sales-notifications') ?></label> </th> <td> <?php $cates = live_sales_notifications_get_field('select_categories', array()); ?> <select multiple="multiple" name="<?php echo esc_attr(live_sales_notifications_set_field('select_categories', true)); ?>" class="category-search" placeholder="<?php esc_attr_e('Please select category', 'live-sales-notifications') ?>"> <?php if (count($cates)) { $categories = get_terms( array( 'taxonomy' => 'product_cat', 'include' => $cates, ) ); if (count($categories)) { foreach ($categories as $category) { ?> <option selected="selected" value="<?php echo esc_attr($category->term_id) ?>"><?php echo esc_html($category->name) ?></option> <?php } } } ?> </select> </td> </tr> <tr valign="top" class="hidden select-categories"> <th scope="row"> <label><?php esc_html_e('Exclude Products', 'live-sales-notifications') ?></label> </th> <td> <?php $products = live_sales_notifications_get_field('cate_exclude_products', array()); ?> <select multiple="multiple" name="<?php echo esc_attr(live_sales_notifications_set_field('cate_exclude_products', true)); ?>" class="product-search" placeholder="<?php esc_attr_e('Please select products', 'live-sales-notifications') ?>"> <?php if (count($products)) { $post_type = array('product'); if ($main_instance->store_type == 'edd') { $post_type = array('downlaod'); } $product_data = $main_instance->compatibility()->product_query($products, $post_type); foreach ($product_data as $product_single_item) { ?> <option selected="selected" value="<?php echo esc_attr($product_single_item['product_id']) ?>"><?php echo esc_html($product_single_item['product_name']) ?></option> <?php } // Reset Post Data wp_reset_postdata(); } ?> </select> <p class="description"><?php esc_html_e('These products will not display on notification.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top" class="hidden latest-product-select-categories"> <th scope="row"> <label><?php esc_html_e('Product limit', 'live-sales-notifications') ?></label> </th> <td> <input id="<?php echo esc_attr(live_sales_notifications_set_field('limit_product')) ?>" type="number" tabindex="0" value="<?php echo esc_attr(live_sales_notifications_get_field('limit_product', 50)) ?>" name="<?php echo esc_attr(live_sales_notifications_set_field('limit_product')); ?>"/> <p class="description"><?php esc_html_e('Product quantity will be got in list latest products.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top" class="hidden exclude_products"> <th scope="row"> <label><?php esc_html_e('Exclude Products', 'live-sales-notifications') ?></label> </th> <td> <?php $products = live_sales_notifications_get_field('exclude_products', array()); ?> <select multiple="multiple" name="<?php echo esc_attr(live_sales_notifications_set_field('exclude_products', true)); ?>" class="product-search" placeholder="<?php esc_attr_e('Please select products', 'live-sales-notifications') ?>"> <?php if (count($products)) { $post_type = array('product', 'product_variation'); if ($main_instance->store_type == 'edd') { $post_type = array('download'); } $product_data = $main_instance->compatibility()->product_query($products_ach, $post_type); foreach ($product_data as $product_item) { ?> <option selected="selected" value="<?php echo esc_attr($product_item['product_id']); ?>"><?php echo esc_html($product_item['product_name']); ?></option> <?php } // Reset Post Data wp_reset_postdata(); } ?> </select> <p class="description"><?php esc_html_e('These products will not show on notification.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('product_link')); ?>"><?php esc_html_e('External link', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('product_link')); ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('product_link'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('product_link')); ?>"/> <label></label> </div> <p class="description"><?php esc_html_e('Working with External/Affiliate product. Product link is product URL.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top" class="get_from_billing hidden"> <th scope="row"> <label><?php esc_html_e('Order Time', 'live-sales-notifications') ?></label> </th> <td> <div class="fields"> <div class="twelve wide field"> <input type="number" value="<?php echo esc_attr(live_sales_notifications_get_field('order_threshold_num', 30)); ?>" name="<?php echo esc_attr(live_sales_notifications_set_field('order_threshold_num')); ?>"/> </div> <div class="two wide field"> <select name="<?php echo esc_attr(live_sales_notifications_set_field('order_threshold_time')) ?>" class="mbui fluid dropdown"> <option <?php selected(live_sales_notifications_get_field('order_threshold_time'), 0) ?> value="0"><?php esc_attr_e('Hours', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('order_threshold_time'), 1) ?> value="1"><?php esc_attr_e('Days', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('order_threshold_time'), 2) ?> value="2"><?php esc_attr_e('Minutes', 'live-sales-notifications') ?></option> </select> </div> </div> <p class="description"><?php esc_html_e('Products in this recently time will get from order. ', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top" class="get_from_billing hidden"> <th scope="row"> <label><?php esc_html_e('Order Status', 'live-sales-notifications') ?></label> </th> <td> <?php $order_statuses = live_sales_notifications_get_field('order_statuses'); if (!is_array($order_statuses)) { $order_statuses = array(); } $store_instance = live_sales_notifications_instance()->compatibility(); $statuses = $store_instance->get_all_order_status(); ?> <select multiple="multiple" name="<?php echo esc_attr(live_sales_notifications_set_field('order_statuses', true)); ?>" class="mbui fluid dropdown"> <?php foreach ($statuses as $k => $status) { $selected = ''; if (in_array($k, $order_statuses)) { $selected = 'selected="selected"'; } ?> <option <?php echo $selected; ?> value="<?php echo esc_attr($k) ?>"><?php echo esc_html($status) ?></option> <?php } ?> </select> </td> </tr> <tr valign="top" class="select_only_product hidden"> <th scope="row"> <label><?php esc_html_e('Select Products', 'live-sales-notifications') ?></label> </th> <td> <?php $products_ach = live_sales_notifications_get_field('archive_products', array()); ?> <select multiple="multiple" name="<?php echo esc_attr(live_sales_notifications_set_field('archive_products', true)); ?>" class="product-search" placeholder="<?php esc_attr_e('Please select products', 'live-sales-notifications') ?>"> <?php if (count($products_ach)) { $post_type = array('product', 'product_variation'); if ($main_instance->store_type == 'edd') { $post_type = array('download'); } $product_data = $main_instance->compatibility()->product_query($products_ach, $post_type); foreach ($product_data as $product_item) { ?> <option selected="selected" value="<?php echo esc_attr($product_item['product_id']); ?>"><?php echo esc_html($product_item['product_name']); ?></option> <?php } // Reset Post Data wp_reset_postdata(); } ?> </select> </td> </tr> <tr valign="top" class="select_product hidden"> <th scope="row"> <label><?php esc_html_e('Virtual First Name', 'live-sales-notifications') ?></label> </th> <td> <?php $first_names = live_sales_notifications_get_field('virtual_name') ?> <textarea name="<?php echo esc_attr(live_sales_notifications_set_field('virtual_name')) ?>"><?php echo $first_names ?></textarea> <p class="description"><?php esc_html_e('Virtual first name what will show on notification. Each first name on a line.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top" class="select_product hidden"> <th scope="row"> <label><?php esc_html_e('Virtual Time', 'live-sales-notifications') ?></label></th> <td> <div class="mbui form"> <div class="inline fields"> <input type="number" name="<?php echo esc_attr(live_sales_notifications_set_field('virtual_time')) ?>" value="<?php echo esc_attr(live_sales_notifications_get_field('virtual_time', '10')) ?>"/> <label><?php esc_html_e('hours', 'live-sales-notifications') ?></label> </div> </div> <p class="description"><?php esc_html_e('Time will auto get random in this time threshold ago.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top" class="select_product hidden"> <th scope="row"> <label><?php esc_html_e('Address', 'live-sales-notifications') ?></label></th> <td> <select name="<?php echo esc_attr(live_sales_notifications_set_field('country')) ?>" class="mbui fluid dropdown"> <option <?php selected(live_sales_notifications_get_field('country'), 0) ?> value="0"><?php esc_attr_e('Auto Detect', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('country'), 1) ?> value="1"><?php esc_attr_e('Virtual', 'live-sales-notifications') ?></option> </select> <p class="description"><?php esc_html_e('You can use auto detect address or make virtual address of customer.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top" class="virtual_address hidden"> <th scope="row"> <label><?php esc_html_e('Virtual City', 'live-sales-notifications') ?></label></th> <td> <?php $virtual_city = live_sales_notifications_get_field('virtual_city'); ?> <textarea name="<?php echo esc_attr(live_sales_notifications_set_field('virtual_city')) ?>"><?php echo esc_attr($virtual_city) ?></textarea> <p class="description"><?php esc_html_e('Virtual city name what will show on notification. Each city name on a line.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top" class="virtual_address hidden"> <th scope="row"> <label><?php esc_html_e('Virtual Country', 'live-sales-notifications') ?></label></th> <td> <?php $virtual_country = live_sales_notifications_get_field('virtual_country') ?> <input type="text" name="<?php echo esc_attr(live_sales_notifications_set_field('virtual_country')) ?>" value="<?php echo esc_attr($virtual_country) ?>"/> <p class="description"><?php esc_html_e('Virtual country name what will show on notification.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top"> <th scope="row"> <label><?php esc_html_e('Product image size', 'live-sales-notifications') ?></label> </th> <td> <?php global $_wp_additional_image_sizes; ?> <select name="<?php echo esc_attr(live_sales_notifications_set_field('product_sizes')) ?>" class="mbui fluid dropdown"> <?php foreach ($_wp_additional_image_sizes as $thumb => $thumb_option) { ?> <option <?php selected(live_sales_notifications_get_field('product_sizes'), $thumb) ?> value="<?php echo esc_attr($thumb); ?>"><?php echo esc_html($thumb) ?> - <?php echo isset($_wp_additional_image_sizes[$thumb]) ? $_wp_additional_image_sizes[$thumb]['width'] . 'x' . $_wp_additional_image_sizes[$thumb]['height'] : ''; ?></option> <?php } ?> </select> <p class="description"><?php esc_html_e('Image size will get form your WordPress site.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top" class="get_from_billing hidden"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('non_ajax')) ?>"><?php esc_html_e('Non Ajax', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('non_ajax')) ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('non_ajax'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('non_ajax')) ?>"/> <label></label> </div> <p class="description"><?php esc_html_e('Load popup will not use ajax. Your site will be load faster. It creates cache. It is not working with Get product from Billing feature and options of Product detail tab.', 'live-sales-notifications') ?></p> </td> </tr> </tbody> </table><file_sep> <!-- Tab Content !--> <table class="optiontable form-table"> <tbody> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('loop')) ?>"><?php esc_html_e('Loop', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('loop')) ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('loop'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('loop')) ?>"/> <label></label> </div> </td> </tr> <tr valign="top" class="hidden time_loop"> <th scope="row"> <label><?php esc_html_e('Next time display', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui form"> <div class="inline fields"> <input type="number" name="<?php echo esc_attr(live_sales_notifications_set_field('next_time')) ?>" value="<?php echo esc_attr(live_sales_notifications_get_field('next_time', 60)) ?>"/> <label><?php esc_html_e('seconds', 'live-sales-notifications') ?></label> </div> </div> <p class="description"><?php esc_html_e('Time to show next notification ', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top" class="hidden time_loop"> <th scope="row"> <label><?php esc_html_e('Notification per page', 'live-sales-notifications') ?></label> </th> <td> <input type="number" name="<?php echo esc_attr(live_sales_notifications_set_field('notification_per_page')) ?>" value="<?php echo esc_attr(live_sales_notifications_get_field('notification_per_page', 30)) ?>"/> <p class="description"><?php esc_html_e('Number of notifications on a page.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('initial_delay_random')) ?>"><?php esc_html_e('Initial time random', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('initial_delay_random')) ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('initial_delay_random'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('initial_delay_random')) ?>"/> <label></label> </div> <p class="description"><?php esc_html_e('Initial time will be random from 0 to current value.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top" class="hidden initial_delay_random"> <th scope="row"> <label><?php esc_html_e('Minimum initial delay time', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui form"> <div class="inline fields"> <input type="number" name="<?php echo esc_attr(live_sales_notifications_set_field('initial_delay_min')) ?>" value="<?php echo esc_attr(live_sales_notifications_get_field('initial_delay_min', 0)) ?>"/> <label><?php esc_html_e('seconds', 'live-sales-notifications') ?></label> </div> </div> <p class="description"><?php esc_html_e('Time will be random from Initial delay time min to Initial time.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top"> <th scope="row"> <label><?php esc_html_e('Initial delay', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui form"> <div class="inline fields"> <input type="number" name="<?php echo esc_attr(live_sales_notifications_set_field('initial_delay')) ?>" value="<?php echo esc_attr(live_sales_notifications_get_field('initial_delay', 0)) ?>"/> <label><?php esc_html_e('seconds', 'live-sales-notifications') ?></label> </div> </div> <p class="description"><?php esc_html_e('When your site loads, notifications will show after this amount of time', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top"> <th scope="row"> <label><?php esc_html_e('Display time', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui form"> <div class="inline fields"> <input type="number" name="<?php echo esc_attr(live_sales_notifications_set_field('display_time')) ?>" value="<?php echo esc_attr(live_sales_notifications_get_field('display_time', 5)) ?>"/> <label><?php esc_html_e('seconds', 'live-sales-notifications') ?></label> </div> </div> <p class="description"><?php esc_html_e('Time your notification display.', 'live-sales-notifications') ?></p> </td> </tr> </tbody> </table><file_sep><?php /** * Plugin Name: Live Sales Notifications - WooCommerce & Easy Digital Download Sales Notification * Description: Live sales notifications for WooCommerce and Easy Digital Download products * Version: 1.0.1 * Author: mantrabrain * Author URI: https://mantrabrain.com * Requires at least: 4.4 * Tested up to: 5.1.1 * License: GPLv3 or later */ /* */ if (!defined('ABSPATH')) { exit; } if (!defined('LIVE_SALES_NOTIFICATIONS_VERSION')) { define('LIVE_SALES_NOTIFICATIONS_VERSION', '1.0.1'); } if (!defined('LIVE_SALES_NOTIFICATIONS_PLUGIN_FILE')) { define('LIVE_SALES_NOTIFICATIONS_PLUGIN_FILE', __FILE__); } // Include the main CLASS if (!class_exists('Live_Sales_Notifications')) { include_once dirname(__FILE__) . '/includes/class-live-sales-notifications.php'; } /** * Main instance of live sales notification. * * Returns the main instance to prevent the need to use globals. * * @since 1.0.0 * @return Live_Sales_Notifications */ function live_sales_notifications_instance() { return Live_Sales_Notifications::instance(); } // Global for backwards compatibility. $GLOBALS['live-sales-notifications'] = live_sales_notifications_instance(); <file_sep>'use strict'; jQuery(document).ready(function () { jQuery('.mbui.tabular.menu .item').vi_tab({ history: true, historyType: 'hash' }); /*Setup tab*/ var tabs, tabEvent = false, initialTab = 'general', navSelector = '.mbui.menu', panelSelector = '.mbui.tab', panelFilter = function () { jQuery(panelSelector + ' a').filter(function () { return jQuery(navSelector + ' a[title=' + jQuery(this).attr('title') + ']').size() != 0; }).each(function (event) { jQuery(this).attr('href', '#' + $(this).attr('title').replace(/ /g, '_')); }); }; // Initializes plugin features jQuery.address.strict(false).wrap(true); if (jQuery.address.value() == '') { jQuery.address.history(false).value(initialTab).history(true); } // Address handler jQuery.address.init(function (event) { // Adds the ID in a lazy manner to prevent scrolling jQuery(panelSelector).attr('id', initialTab); panelFilter(); // Tabs setup tabs = jQuery('.mbui.menu') .vi_tab({ history: true, historyType: 'hash' }) }); jQuery('select.mbui.dropdown').dropdown(); /*Search*/ jQuery(".product-search").select2({ placeholder: "Please fill in your product title", ajax: { url: "admin-ajax.php?action=live_sales_notifications_search_product", dataType: 'json', type: "GET", quietMillis: 50, delay: 250, data: function (params) { return { keyword: params.term }; }, processResults: function (data) { return { results: data }; }, cache: true }, escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: 1 }); /*Search*/ jQuery(".category-search").select2({ placeholder: "Please fill in your category title", ajax: { url: "admin-ajax.php?action=live_sales_notifications_search_cate", dataType: 'json', type: "GET", quietMillis: 50, delay: 250, data: function (params) { return { keyword: params.term }; }, processResults: function (data) { return { results: data }; }, cache: true }, escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: 1 }); /*Save Submit button*/ jQuery('.live-sales-notifications-submit').one('click', function () { jQuery(this).addClass('loading'); }); /*Add field depend*/ /*Products*/ if (jQuery('.get_from_billing').length > 0) { jQuery('.get_from_billing').dependsOn({ 'select[name="live_sales_notifications_params[show_product_option]"]': { values: ['0'] } }); } if (jQuery('.show-close-icon').length > 0) { jQuery('.show-close-icon').dependsOn({ 'input[name="live_sales_notifications_params[show_close_icon]"]': { checked: true } }); } if (jQuery('.latest-product-select-categories').length > 0) { jQuery('.latest-product-select-categories').dependsOn({ 'select[name="live_sales_notifications_params[show_product_option]"]': { values: ['2', '3', '4'] } }); } if (jQuery('.select-categories').length > 0) { jQuery('.select-categories').dependsOn({ 'select[name="live_sales_notifications_params[show_product_option]"]': { values: ['3'] } }); } if (jQuery('.select_product').length > 0) { jQuery('.select_product').dependsOn({ 'select[name="live_sales_notifications_params[show_product_option]"]': { values: ['1', '2', '3', '4'] } }); } if (jQuery('.select_only_product').length > 0) { jQuery('.select_only_product').dependsOn({ 'select[name="live_sales_notifications_params[show_product_option]"]': { values: ['1'] } }); } if (jQuery('.exclude_products').length > 0) { jQuery('.exclude_products').dependsOn({ 'select[name="live_sales_notifications_params[show_product_option]"]': { values: ['0'] } }); } if (jQuery('.only_current_product').length > 0) { jQuery('.only_current_product').dependsOn({ 'select[name="live_sales_notifications_params[notification_product_show_type]"]': { values: ['0'] } }); } if (jQuery('.virtual_address').length > 0) { jQuery('.virtual_address').dependsOn({ 'select[name="live_sales_notifications_params[show_product_option]"]': { values: ['1', '2', '3', '4'] }, 'select[name="live_sales_notifications_params[country]"]': { values: ['1'] } }); } if (jQuery('select[name="live_sales_notifications_params[show_product_option]').length > 0) { jQuery('select[name="live_sales_notifications_params[show_product_option]"]').on('change', function () { var data = jQuery(this).val(); if (data == 0) { jQuery('.virtual_address').hide(); } else { var data1 = jQuery('select[name="live_sales_notifications_params[country]"]').val(); if (data1 > 0) { jQuery('.virtual_address').show(); } } }); } if (jQuery('.time_loop').length > 0) { /*Time*/ jQuery('.time_loop').dependsOn({ 'input[name="live_sales_notifications_params[loop]"]': { checked: true } }); } if (jQuery('.initial_delay_random').length > 0) { /*Initial time random*/ jQuery('.initial_delay_random').dependsOn({ 'input[name="live_sales_notifications_params[initial_delay_random]"]': { checked: true } }); } // Color picker jQuery('.color-picker').iris({ change: function (event, ui) { jQuery(this).parent().find('.color-picker').css({backgroundColor: ui.color.toString()}); var ele = jQuery(this).data('ele'); if (ele == 'highlight') { jQuery('#sales-notification').find('a').css({'color': ui.color.toString()}); } else if (ele == 'textcolor') { jQuery('#sales-notification').css({'color': ui.color.toString()}); } else { jQuery('#sales-notification').css({backgroundColor: ui.color.toString()}); } }, hide: true, border: true }).click(function () { jQuery('.iris-picker').hide(); jQuery(this).closest('td').find('.iris-picker').show(); }); jQuery('body').click(function () { jQuery('.iris-picker').hide(); }); jQuery('.color-picker').click(function (event) { event.stopPropagation(); }); var image_picker = { init: function ($wrapper) { this.event($wrapper); }, event: function ($wrapper) { var uploadBtn = $wrapper.find('.upload_image_button'); var removeBtn = $wrapper.find('.remove_image_button'); var file_frame; var wp_media_post_id = $wrapper.attr('data-old-id'); var set_to_post_id = $wrapper.attr('data-new-id'); uploadBtn.on('click', function (event) { var file_frame; event.preventDefault(); // If the media frame already exists, reopen it. if (file_frame) { // Set the post ID to what we want file_frame.uploader.uploader.param('post_id', set_to_post_id); // Open frame file_frame.open(); return; } else { // Set the wp.media post id so the uploader grabs the ID we want when initialised wp.media.model.settings.post.id = set_to_post_id; } // Create the media frame. file_frame = wp.media.frames.file_frame = wp.media({ title: 'Select a image to upload', button: { text: 'Use this image', }, multiple: false // Set to true to allow multiple files to be selected }); // When an image is selected, run a callback. file_frame.on('select', function () { // We set multiple to false so only get one image from the uploader var attachment = file_frame.state().get('selection').first().toJSON(); // Do something with attachment.id and/or attachment.url here $wrapper.find('.image-preview').attr('src', attachment.url).show(); removeBtn.show(); $wrapper.find('.image_attachment_id').val(attachment.id); jQuery('#sales-notification').css('background-image', 'url("' + attachment.url + '")'); // Restore the main post ID wp.media.model.settings.post.id = wp_media_post_id; }); // Finally, open the modal file_frame.open(); }); removeBtn.on('click', function (event) { // Do something with attachment.id and/or attachment.url here $wrapper.find('.image-preview').hide(); $wrapper.find('.image_attachment_id').val(0); jQuery('#sales-notification').css({backgroundImage: 'none'}); removeBtn.hide(); }); } }; image_picker.init(jQuery('.image-picker-wrap')); jQuery('input[name="live_sales_notifications_params[position]"]').on('change', function () { var data = jQuery(this).val(); if (data == 1) { jQuery('#sales-notification').removeClass('top_left top_right').addClass('bottom_right'); } else if (data == 2) { jQuery('#sales-notification').removeClass('bottom_right top_right').addClass('top_left'); } else if (data == 3) { jQuery('#sales-notification').removeClass('bottom_right top_left').addClass('top_right'); } else { jQuery('#sales-notification').removeClass('bottom_right top_left top_right'); } }); jQuery('select[name="live_sales_notifications_params[image_position]"]').on('change', function () { var data = jQuery(this).val(); if (data == 1) { jQuery('#sales-notification').addClass('img-right'); } else { jQuery('#sales-notification').removeClass('img-right'); } }); /*add optgroup to select box semantic*/ jQuery('.mbui.dropdown.selection').has('optgroup').each(function () { var $menu = jQuery('<div/>').addClass('menu'); jQuery(this).find('optgroup').each(function () { $menu.append("<div class=\"header\">" + this.label + "</div><div class=\"divider\"></div>"); return jQuery(this).children().each(function () { return $menu.append("<div class=\"item\" data-value=\"" + this.value + "\">" + this.innerHTML + "</div>"); }); }); return jQuery(this).find('.menu').html($menu.html()); }); jQuery('#sales-notification').attr('data-effect_display', ''); jQuery('#sales-notification').attr('data-effect_hidden', ''); jQuery('select[name="live_sales_notifications_params[message_display_effect]"]').on('change', function () { var data = jQuery(this).val(), message_purchased = jQuery('#sales-notification'); switch (data) { case 'bounceIn': message_purchased.attr('data-effect_display', 'bounceIn'); break; case 'bounceInDown': message_purchased.attr('data-effect_display', 'bounceInDown'); break; case 'bounceInLeft': message_purchased.attr('data-effect_display', 'bounceInLeft'); break; case 'bounceInRight': message_purchased.attr('data-effect_display', 'bounceInRight'); break; case 'bounceInUp': message_purchased.attr('data-effect_display', 'bounceInUp'); break; case 'fade-in': message_purchased.attr('data-effect_display', 'fade-in'); break; case 'fadeInDown': message_purchased.attr('data-effect_display', 'fadeInDown'); break; case 'fadeInDownBig': message_purchased.attr('data-effect_display', 'fadeInDownBig'); break; case 'fadeInLeft': message_purchased.attr('data-effect_display', 'fadeInLeft'); break; case 'fadeInLeftBig': message_purchased.attr('data-effect_display', 'fadeInLeftBig'); break; case 'fadeInRight': message_purchased.attr('data-effect_display', 'fadeInRight'); break; case 'fadeInRightBig': message_purchased.attr('data-effect_display', 'fadeInRightBig'); break; case 'fadeInUp': message_purchased.attr('data-effect_display', 'fadeInUp'); break; case 'fadeInUpBig': message_purchased.attr('data-effect_display', 'fadeInUpBig'); break; case 'flipInX': message_purchased.attr('data-effect_display', 'flipInX'); break; case 'flipInY': message_purchased.attr('data-effect_display', 'flipInY'); break; case 'lightSpeedIn': message_purchased.attr('data-effect_display', 'lightSpeedIn'); break; case 'rotateIn': message_purchased.attr('data-effect_display', 'rotateIn'); break; case 'rotateInDownLeft': message_purchased.attr('data-effect_display', 'rotateInDownLeft'); break; case 'rotateInDownRight': message_purchased.attr('data-effect_display', 'rotateInDownRight'); break; case 'rotateInUpLeft': message_purchased.attr('data-effect_display', 'rotateInUpLeft'); break; case 'rotateInUpRight': message_purchased.attr('data-effect_display', 'rotateInUpRight'); break; case 'slideInUp': message_purchased.attr('data-effect_display', 'slideInUp'); break; case 'slideInDown': message_purchased.attr('data-effect_display', 'slideInDown'); break; case 'slideInLeft': message_purchased.attr('data-effect_display', 'slideInLeft'); break; case 'slideInRight': message_purchased.attr('data-effect_display', 'slideInRight'); break; case 'zoomIn': message_purchased.attr('data-effect_display', 'zoomIn'); break; case 'zoomInDown': message_purchased.attr('data-effect_display', 'zoomInDown'); break; case 'zoomInLeft': message_purchased.attr('data-effect_display', 'zoomInLeft'); break; case 'zoomInRight': message_purchased.attr('data-effect_display', 'zoomInRight'); break; case 'zoomInUp': message_purchased.attr('data-effect_display', 'zoomInUp'); break; case 'rollIn': message_purchased.attr('data-effect_display', 'rollIn'); break; } }); jQuery('select[name="live_sales_notifications_params[message_hidden_effect]"]').on('change', function () { var data = jQuery(this).val(), message_purchased = jQuery('#sales-notification'); switch (data) { case 'bounceOut': message_purchased.attr('data-effect_hidden', 'bounceOut'); break; case 'bounceOutDown': message_purchased.attr('data-effect_hidden', 'bounceOutDown'); break; case 'bounceOutLeft': message_purchased.attr('data-effect_hidden', 'bounceOutLeft'); break; case 'bounceOutRight': message_purchased.attr('data-effect_hidden', 'bounceOutRight'); break; case 'bounceOutUp': message_purchased.attr('data-effect_hidden', 'bounceOutUp'); break; case 'fade-out': message_purchased.attr('data-effect_hidden', 'fade-out'); break; case 'fadeOutDown': message_purchased.attr('data-effect_hidden', 'fadeOutDown'); break; case 'fadeOutDownBig': message_purchased.attr('data-effect_hidden', 'fadeOutDownBig'); break; case 'fadeOutLeft': message_purchased.attr('data-effect_hidden', 'fadeOutLeft'); break; case 'fadeOutLeftBig': message_purchased.attr('data-effect_hidden', 'fadeOutLeftBig'); break; case 'fadeOutRight': message_purchased.attr('data-effect_hidden', 'fadeOutRight'); break; case 'fadeOutRightBig': message_purchased.attr('data-effect_hidden', 'fadeOutRightBig'); break; case 'fadeOutUp': message_purchased.attr('data-effect_hidden', 'fadeOutUp'); break; case 'fadeOutUpBig': message_purchased.attr('data-effect_hidden', 'fadeOutUpBig'); break; case 'flipOutX': message_purchased.attr('data-effect_hidden', 'flipOutX'); break; case 'flipOutY': message_purchased.attr('data-effect_hidden', 'flipOutY'); break; case 'lightSpeedOut': message_purchased.attr('data-effect_hidden', 'lightSpeedOut'); break; case 'rotateOut': message_purchased.attr('data-effect_hidden', 'rotateOut'); break; case 'rotateOutDownLeft': message_purchased.attr('data-effect_hidden', 'rotateOutDownLeft'); break; case 'rotateOutDownRight': message_purchased.attr('data-effect_hidden', 'rotateOutDownRight'); break; case 'rotateOutUpLeft': message_purchased.attr('data-effect_hidden', 'rotateOutUpLeft'); break; case 'rotateOutUpRight': message_purchased.attr('data-effect_hidden', 'rotateOutUpRight'); break; case 'slideOutUp': message_purchased.attr('data-effect_hidden', 'slideOutUp'); break; case 'slideOutDown': message_purchased.attr('data-effect_hidden', 'slideOutDown'); break; case 'slideOutLeft': message_purchased.attr('data-effect_hidden', 'slideOutLeft'); break; case 'slideOutRight': message_purchased.attr('data-effect_hidden', 'slideOutRight'); break; case 'zoomOut': message_purchased.attr('data-effect_hidden', 'zoomOut'); break; case 'zoomOutDown': message_purchased.attr('data-effect_hidden', 'zoomOutDown'); break; case 'zoomOutLeft': message_purchased.attr('data-effect_hidden', 'zoomOutLeft'); break; case 'zoomOutRight': message_purchased.attr('data-effect_hidden', 'zoomOutRight'); break; case 'zoomOutUp': message_purchased.attr('data-effect_hidden', 'zoomOutUp'); break; case 'rollOut': message_purchased.attr('data-effect_hidden', 'rollOut'); break; } }); /*Add new message*/ jQuery('.add-message').on('click', function () { var tr = jQuery('.sales-notification').find('tr').last().clone(); jQuery(tr).appendTo('.sales-notification'); remove_message() }); remove_message(); function remove_message() { jQuery('.remove-message').unbind(); jQuery('.remove-message').on('click', function () { if (confirm("Would you want to remove this message?")) { if (jQuery('.sales-notification tr').length > 1) { var tr = jQuery(this).closest('tr').remove(); } } else { } }); } jQuery('input[name="live_sales_notifications_params[background_image]"]').on('change', function () { var data = jQuery(this).val(); var init_data = { 'spring': { 'hightlight': '#415602', 'text': '#415602', }, 'summer': { 'hightlight': '#164b6d', 'text': '#164b6d', }, 'autumn': { 'hightlight': '#903b28', 'text': '#903b28', }, 'winter': { 'hightlight': '#443e39', 'text': '#443e39', }, 'christmas': { 'hightlight': '#ffffff', 'text': '#ffffff', }, 'christmas_1': { 'hightlight': '#ffffff', 'text': '#ffffff', }, 'black_friday': { 'hightlight': '#ffffff', 'text': '#ffffff', }, 'happy_new_year': { 'hightlight': '#ffffff', 'text': '#ffffff', }, 'valentine': { 'hightlight': '#4e0e2c', 'text': '#4e0e2c', }, 'father': { 'hightlight': '#89152c', 'text': '#89152c', }, 'halloween': { 'hightlight': '#e3a51e', 'text': '#e3a51e', }, 'halloween_1': { 'hightlight': '#ffffff', 'text': '#ffffff', }, 'kids': { 'hightlight': '#401b02', 'text': '#401b02', }, 'kids_1': { 'hightlight': '#2b373e', 'text': '#2b373e', }, 'mother': { 'hightlight': '#ffffff', 'text': '#ffffff', }, 'mother_1': { 'hightlight': '#ffffff', 'text': '#ffffff', } }; if (parseInt(data) == 0) { jQuery('#sales-notification').fadeIn('200'); jQuery('input[name="live_sales_notifications_params[product_color]"]').val('#212121').change(); jQuery('input[name="live_sales_notifications_params[text_color]"]').val('#212121').change(); jQuery('input[name="live_sales_notifications_params[backgroundcolor]"]').val('#ffffff').change(); } else { jQuery('#sales-notification').fadeOut('200'); jQuery('input[name="live_sales_notifications_params[product_color]"]').val(init_data[data]['hightlight']).change(); jQuery('input[name="live_sales_notifications_params[text_color]"]').val(init_data[data]['text']).change(); } }); /** * Start Get download key */ jQuery('.villatheme-get-key-button').one('click', function (e) { var v_button = jQuery(this); v_button.addClass('loading'); var data = v_button.data(); var item_id = data.id; var app_url = data.href; var main_domain = window.location.hostname; main_domain = main_domain.toLowerCase(); var popup_frame; e.preventDefault(); var download_url = v_button.attr('data-download'); popup_frame = window.open(app_url, "myWindow", "width=380,height=600"); window.addEventListener('message', function (event) { /*Callback when data send from child popup*/ var obj = jQuery.parseJSON(event.data); var update_key = ''; var message = obj.message; var support_until = ''; var check_key = ''; if (obj['data'].length > 0) { for (var i = 0; i < obj['data'].length; i++) { if (obj['data'][i].id == item_id && (obj['data'][i].domain == main_domain || obj['data'][i].domain == '' || obj['data'][i].domain == null)) { if (update_key == '') { update_key = obj['data'][i].download_key; support_until = obj['data'][i].support_until; } else if (support_until < obj['data'][i].support_until) { update_key = obj['data'][i].download_key; support_until = obj['data'][i].support_until; } if (obj['data'][i].domain == main_domain) { update_key = obj['data'][i].download_key; break; } } } if (update_key) { check_key = 1; jQuery('.villatheme-autoupdate-key-field').val(update_key); } } v_button.removeClass('loading'); if (check_key) { jQuery('<p><strong>' + message + '</strong></p>').insertAfter(".villatheme-autoupdate-key-field"); jQuery(v_button).closest('form').submit(); } else { jQuery('<p><strong> Your key is not found. Please contact <EMAIL> </strong></p>').insertAfter(".villatheme-autoupdate-key-field"); } }); }); /** * End get download key */ });<file_sep><!-- Tab Content !--> <table class="optiontable form-table"> <tbody> <tr valign="top"> <th scope="row"> <label><?php esc_html_e('Store Type', 'live-sales-notifications') ?></label> </th> <td> <select name="<?php live_sales_notifications_set_field('store_type') ?>" class="mbui fluid dropdown"> <?php $store_types = live_sales_notifications_store_type(); foreach ($store_types as $store => $label) { ?> <option <?php selected(live_sales_notifications_get_field('store_type'), $store) ?> value="<?php echo esc_attr($store); ?>"><?php echo esc_html($label) ?></option> <?php } ?> </select> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo live_sales_notifications_set_field('enable') ?>"> <?php esc_html_e('Enable', 'live-sales-notifications') ?> </label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo live_sales_notifications_set_field('enable') ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('enable'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo live_sales_notifications_set_field('enable') ?>"/> <label></label> </div> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo live_sales_notifications_set_field('enable_mobile') ?>"> <?php esc_html_e('Mobile', 'live-sales-notifications') ?> </label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo live_sales_notifications_set_field('enable_mobile') ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('enable_mobile'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo live_sales_notifications_set_field('enable_mobile') ?>"/> <label></label> </div> <p class="description"><?php esc_html_e('Notification will show on mobile and responsive.', 'live-sales-notifications') ?></p> </td> </tr> </tbody> </table><file_sep><?php if (!defined('ABSPATH')) { exit; } class Live_Sales_Notifications_Admin_Settings { /** * Get files in directory * * @param $dir * * @return array|bool */ static private function get_audios($path = '') { $audio_path = live_sales_notifications_instance()->plugin_path() . '/assets/audios/'; $audio_array = array( 'cool.mp3' => 'cool.mp3', 'iphone.mp3' => 'iphone.mp3', 'unique.mp3' => 'unique.mp3', ); if ($path != '') { $audio_array = is_array($path) ? $path : array($path); } return ($audio_array) ? $audio_array : false; } private function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; } /** * Set Nonce * @return string */ protected static function set_nonce() { return wp_nonce_field('live_sales_notifications_save_email_settings', '_live_sales_notifications_nonce'); } /** * Get list shortcode * @return array */ public static function setting_page() { do_action('live_sales_notifications_before_admin_setting'); wp_enqueue_media(); $main_instance = live_sales_notifications_instance(); $tabs = self::setting_tabs(); ?> <div class="wrap live-sales-notifications"> <h2><?php esc_attr_e('Sales Notification Settings', 'live-sales-notifications') ?></h2> <form method="post" action="" class="mbui form"> <?php echo ent2ncr(self::set_nonce()) ?> <div class="mbui attached tabular menu"> <?php $index = 0; foreach ($tabs as $tab_key => $tab_label) { ?> <div class="item <?php echo $index == 0 ? 'active' : '' ?>" data-tab="<?php echo $tab_key; ?>"> <a href="#<?php echo $tab_key; ?>"><?php echo $tab_label ?></a> </div> <?php $index++; } ?> </div> <div class="live-sales-notifications-admin-tab-content"> <?php $index_content = 0; foreach ($tabs as $tab_index => $label) { ?> <div class="mbui bottom attached tab segment <?php echo $index_content == 0 ? 'active' : '' ?>" data-tab="<?php echo $tab_index; ?>"> <?php $file = 'views/html-settings-tab-' . $tab_index . '.php'; if (file_exists(LIVE_SALES_NOTIFICATIONS_ABSPATH . 'includes/admin/' . $file)) { include_once $file; } else { echo '<h1>File not exists</h1>'; } ?> </div> <?php $index_content++; } ?> </div> <p style="position: relative; z-index: 99999; margin-bottom: 70px; display: inline-block;"> <button class="mbui button labeled icon primary live-sales-notifications-submit "> <i class="icon dashicons dashicons-yes"></i> <?php esc_html_e('Save', 'live-sales-notifications') ?> </button> </p> </form> </div> <?php } private static function setting_tabs() { return apply_filters('live_sales_notifications_setting_tabs', array( 'general' => __('General', 'live-sales-notifications'), 'design' => __('Design', 'live-sales-notifications'), 'notifications' => __('Notifications', 'live-sales-notifications'), 'products' => __('Products', 'live-sales-notifications'), 'product-detail' => __('Product Details', 'live-sales-notifications'), 'time' => __('Time', 'live-sales-notifications'), //'audio' => __('Audio', 'live-sales-notifications'), 'assign' => __('Assign', 'live-sales-notifications'), )); } } new Live_Sales_Notifications_Admin_Settings();<file_sep><!-- Tab Content !--> <table class="optiontable form-table"> <tbody> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('is_home')) ?>"><?php esc_html_e('Home page', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('is_home')) ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('is_home'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('is_home')) ?>"/> <label></label> </div> <p class="description"><?php esc_html_e('Hide notification on Home page', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('is_checkout')) ?>"><?php esc_html_e('Checkout page', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('is_checkout')) ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('is_checkout'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('is_checkout')) ?>"/> <label></label> </div> <p class="description"><?php esc_html_e('Hide notification on Checkout page', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('is_cart')) ?>"><?php esc_html_e('Cart page', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('is_cart')) ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('is_cart'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('is_cart')) ?>"/> <label></label> </div> <p class="description"><?php esc_html_e('Hide notification on Cart page', 'live-sales-notifications') ?></p> </td> </tr> </tbody> </table> <file_sep><?php /** * Live Sales Notification Compatibility WooCommerce. * * @package Live Sales Notification/Classes * @version 1.0.0 */ defined('ABSPATH') || exit; class Live_Sales_Notifications_Compatibility_WooCommerce extends Live_Sales_Notifications_Compatibility { public function __construct() { $this->id = 'woocommerce'; add_action('woocommerce_order_status_completed', array($this, 'order_completed')); add_action('woocommerce_order_status_pending', array($this, 'order_completed')); } public function version_check() { $version = '3.0.0'; global $woocommerce; if (version_compare($woocommerce->version, $version, ">=")) { return true; } return false; } function get_all_order_status() { // TODO: Implement get_all_order_status() method. return wc_get_order_statuses(); } public function order_completed($order_id) { $options = live_sales_notifications_instance()->options; $show_product_option = $options->show_product_option(); if (!$show_product_option) { update_option('_live_sales_notifications_prefix', substr(md5(date("YmdHis")), 0, 10)); } } public function get_product($settings = array()) { // TODO: Implement get_product() method. $enable_single_product = $settings->enable_single_product(); $notification_product_show_type = $settings->get_notification_product_show_type(); $products = array(); $product_link = $settings->product_link(); $product_thumb = $settings->get_product_sizes(); $show_product_option = $settings->show_product_option(); $prefix = live_sales_notifications_prefix(); /*Check Single Product page*/ if ($enable_single_product && is_product()) { $product_id = get_the_ID(); if (!$product_id) { return; } $products = get_transient($prefix . 'live_sales_notifications_product_child' . $product_id); if (is_array($products) && count($products)) { return $products; } $product = wc_get_product($product_id); /* Only show current product*/ if (!$notification_product_show_type) { /*Show variation products*/ $enable_variable = $settings->show_variation(); if ($product->get_type() == 'variable' && $enable_variable) { $temp_p = delete_transient('live_sales_notifications_product_child' . $product->get_id()); if (is_array($temp_p) && count($temp_p)) { return $temp_p; } else { $temp_p = $product->get_children(); if (count($temp_p)) { foreach ($temp_p as $key => $the_product) { $product_variation = wc_get_product($the_product); if (!$product_variation->is_in_stock() && !$settings->enable_out_of_stock_product()) { unset($temp_p[$key]); } else { if ($product_variation->get_catalog_visibility() == 'hidden') { continue; } // do stuff for everything else $link = $product_variation->get_permalink(); $product_tmp = array( 'title' => $product_variation->get_name(), 'url' => $link, 'thumb' => has_post_thumbnail($product->get_id()) ? get_the_post_thumbnail_url($product->get_id(), $product_thumb) : (has_post_thumbnail($product_id) ? get_the_post_thumbnail_url($product_id, $product_thumb) : ''), ); if (!$show_product_option) { $orders = $this->get_orders_by_product($product_id); if (is_array($orders) && count($orders)) { foreach ($orders as $order) { $order_infor = array( 'time' => live_sales_notifications_time_subsctract($order->get_date_created()->date_i18n("Y-m-d H:i:s")), 'time_org' => $order->get_date_created()->date_i18n("Y-m-d H:i:s"), 'first_name' => ucfirst(get_post_meta($order->get_id(), '_billing_first_name', true)), 'last_name' => ucfirst(get_post_meta($order->get_id(), '_billing_last_name', true)), 'city' => ucfirst(get_post_meta($order->get_id(), '_billing_city', true)), 'state' => ucfirst(get_post_meta($order->get_id(), '_billing_state', true)), 'country' => ucfirst(WC()->countries->countries[get_post_meta($order->get_id(), '_billing_country', true)]) ); $products[] = array_merge($product_tmp, $order_infor); } } } else { $products[] = $product_tmp; } } } } } } else { if ($product->is_in_stock() || $settings->enable_out_of_stock_product()) { if ($product->get_catalog_visibility() == 'hidden') { return false; } // do stuff for everything else $link = $product->get_permalink(); $product_tmp = array( 'title' => get_the_title(), 'url' => $link, 'thumb' => has_post_thumbnail($product->get_id()) ? get_the_post_thumbnail_url($product->get_id(), $product_thumb) : '', ); if (!$show_product_option) { $orders = $this->get_orders_by_product($product_id); if (is_array($orders) && count($orders)) { foreach ($orders as $order) { $order_infor = array( 'time' => live_sales_notifications_time_subsctract($order->get_date_created()->date_i18n("Y-m-d H:i:s")), 'time_org' => $order->get_date_created()->date_i18n("Y-m-d H:i:s"), 'first_name' => ucfirst(get_post_meta($order->get_id(), '_billing_first_name', true)), 'last_name' => ucfirst(get_post_meta($order->get_id(), '_billing_last_name', true)), 'city' => ucfirst(get_post_meta($order->get_id(), '_billing_city', true)), 'state' => ucfirst(get_post_meta($order->get_id(), '_billing_state', true)), 'country' => ucfirst(WC()->countries->countries[get_post_meta($order->get_id(), '_billing_country', true)]) ); $products[] = array_merge($product_tmp, $order_infor); } } } else { $products[] = $product_tmp; } } else { return false; } } } else { /* Show products in the same category*/ $cates = $product->get_category_ids(); $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => 50, 'orderby' => 'rand', 'post__not_in' => array($product->get_id()), 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'id', 'terms' => $cates, 'include_children' => false, 'operator' => 'IN' ) ), 'meta_query' => array( array( 'key' => '_stock_status', 'value' => 'instock', 'compare' => '=' ) ) ); if ($settings->enable_out_of_stock_product()) { unset($args['meta_query']); } $the_query = new WP_Query($args); if ($the_query->have_posts()) { while ($the_query->have_posts()) { $the_query->the_post(); $product = wc_get_product(get_the_ID()); if ($product->get_catalog_visibility() == 'hidden') { continue; } if ($product->is_type('external') && $product_link) { // do stuff for simple products $link = get_post_meta($product_id, '_product_url', '#'); if (!$link) { $link = get_the_permalink(); } } else { // do stuff for everything else $link = get_the_permalink(); } $product_tmp = array( 'title' => get_the_title(), 'url' => $link, 'thumb' => has_post_thumbnail() ? get_the_post_thumbnail_url('', $product_thumb) : '', ); $products[] = $product_tmp; } } // Reset Post Data wp_reset_postdata(); } if (is_array($products) && count($products)) { set_transient($prefix . 'live_sales_notifications_product_child' . $product->get_id(), $products, 3600); return $products; } else { return false; } // Reset Post Data } /*Get All page*/ /*Check with Product get from Billing*/ $limit_product = $settings->get_limit_product(); if ($show_product_option > 0) { $products = get_transient($prefix); if (is_array($products) && count($products)) { return $products; } else { $products = array(); } switch ($show_product_option) { case 1: /*Select Products*/ /*Params from Settings*/ $archive_products = $settings->get_products(); $archive_products = is_array($archive_products) ? $archive_products : array(); if (count(array_filter($archive_products)) < 1) { $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => '50', 'orderby' => 'rand', 'meta_query' => array( array( 'key' => '_stock_status', 'value' => 'instock', 'compare' => '=' ), ) ); } else { $args = array( 'post_type' => array('product', 'product_variation'), 'post_status' => 'publish', 'posts_per_page' => '50', 'orderby' => 'rand', 'post__in' => $archive_products, 'meta_query' => array( array( 'key' => '_stock_status', 'value' => 'instock', 'compare' => '=' ), ) ); } break; case 2: /*Latest Products*/ /*Params from Settings*/ $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => $limit_product, 'orderby' => 'date', 'order' => 'DESC', 'meta_query' => array( array( 'key' => '_stock_status', 'value' => 'instock', 'compare' => '=' ) ), ); break; case 4: $viewed_products = !empty($_COOKIE['live_sales_notifications_recently_viewed_product']) ? (array)explode('|', wp_unslash($_COOKIE['live_sales_notifications_recently_viewed_product'])) : array(); // @codingStandardsIgnoreLine $viewed_products = array_reverse(array_filter(array_map('absint', $viewed_products))); if (empty($viewed_products)) { $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => '50', 'orderby' => 'rand', 'meta_query' => array( array( 'key' => '_stock_status', 'value' => 'instock', 'compare' => '=' ), ) ); } else { $args = array( 'posts_per_page' => $limit_product, 'no_found_rows' => 1, 'post_status' => 'publish', 'post_type' => 'product', 'post__in' => $viewed_products, 'orderby' => 'post__in', 'meta_query' => array( array( 'key' => '_stock_status', 'value' => 'instock', 'compare' => '=' ), ) ); // WPCS: slow query ok. } break; default: /*Select Categories*/ $cates = $settings->get_categories(); if (count($cates)) { $categories = get_terms( array( 'taxonomy' => 'product_cat', 'include' => $cates ) ); $categories_checked = array(); if (count($categories)) { foreach ($categories as $category) { $categories_checked[] = $category->term_id; } } else { return false; } /*Params from Settings*/ $cate_exclude_products = $settings->get_cate_exclude_products(); if (!is_array($cate_exclude_products)) { $cate_exclude_products = array(); } $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => $limit_product, 'orderby' => 'rand', 'post__not_in' => $cate_exclude_products, 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'id', 'terms' => $categories_checked, 'include_children' => false, 'operator' => 'IN' ), ), 'meta_query' => array( array( 'key' => '_stock_status', 'value' => 'instock', 'compare' => '=' ), ) ); } else { $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => '50', 'orderby' => 'rand', 'meta_query' => array( array( 'key' => '_stock_status', 'value' => 'instock', 'compare' => '=' ), ) ); } } /*Enable in stock*/ if ($settings->enable_out_of_stock_product()) { unset($args['meta_query']); } $the_query = new WP_Query($args); if ($the_query->have_posts()) { while ($the_query->have_posts()) { $the_query->the_post(); $product = wc_get_product(get_the_ID()); if ($product->get_catalog_visibility() == 'hidden') { continue; } if ($product->is_type('external') && $product_link) { // do stuff for simple products $link = get_post_meta(get_the_ID(), '_product_url', '#'); if (!$link) { $link = get_the_permalink(); } } else { // do stuff for everything else $link = get_the_permalink(); } $product_tmp = array( 'title' => get_the_title(), // 'id' => get_the_ID(), 'url' => $link, 'thumb' => has_post_thumbnail() ? get_the_post_thumbnail_url('', $product_thumb) : '', ); if (!$product_tmp['thumb'] && $product->is_type('variation')) { $parent_id = $product->get_parent_id(); if ($parent_id) { $product_tmp['thumb'] = has_post_thumbnail($parent_id) ? get_the_post_thumbnail_url($parent_id, $product_thumb) : ''; } } $products[] = $product_tmp; } } // Reset Post Data wp_reset_postdata(); if (count($products)) { set_transient($prefix, $products, 3600); return $products; } else { return false; } } else { /*Get from billing*/ /*Parram*/ $order_threshold_num = $settings->get_order_threshold_num(); $order_threshold_time = $settings->get_order_threshold_time(); $exclude_products = $settings->get_exclude_products(); $order_statuses = $settings->get_order_statuses(); if (!is_array($exclude_products)) { $exclude_products = array(); } $current_time = ''; if ($order_threshold_num) { switch ($order_threshold_time) { case 1: $time_type = 'days'; break; case 2: $time_type = 'minutes'; break; default: $time_type = 'hours'; } $current_time = strtotime("-" . $order_threshold_num . " " . $time_type); } $args = array( 'post_type' => 'shop_order', 'post_status' => $order_statuses, 'posts_per_page' => '100', 'orderby' => 'date', 'order' => 'DESC' ); if ($current_time) { $args['date_query'] = array( array( 'after' => array( 'year' => date("Y", $current_time), 'month' => date("m", $current_time), 'day' => date("d", $current_time), 'hour' => date("H", $current_time), 'minute' => date("i", $current_time), 'second' => date("s", $current_time), ), 'inclusive' => true, //(boolean) - For after/before, whether exact value should be matched or not'. 'compare' => '<=', //(string) - Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS' (only in WP >= 3.5), and 'NOT EXISTS' (also only in WP >= 3.5). Default value is '=' 'column' => 'post_date', //(string) - Column to query against. Default: 'post_date'. 'relation' => 'AND', //(string) - OR or AND, how the sub-arrays should be compared. Default: AND. ), ); } $my_query = new WP_Query($args); $products = array(); if ($my_query->have_posts()) { while ($my_query->have_posts()) { $my_query->the_post(); $order = new WC_Order(get_the_ID()); $items = $order->get_items(); foreach ($items as $item) { if (in_array($item['product_id'], $exclude_products)) { continue; } if (isset($item['product_id']) && $item['product_id']) { $p_data = wc_get_product($item['product_id']); if (!$p_data->is_in_stock() && !$settings->enable_out_of_stock_product()) { continue; } if ($p_data->get_status() != 'publish') { continue; } if ($p_data->get_catalog_visibility() == 'hidden') { continue; } // do stuff for everything else $link = $p_data->get_permalink(); $product_tmp = array( 'title' => get_the_title($p_data->get_id()), 'url' => $link, 'thumb' => has_post_thumbnail($p_data->get_id()) ? get_the_post_thumbnail_url($p_data->get_id(), $product_thumb) : '', 'time' => live_sales_notifications_time_subsctract($order->get_date_created()->date_i18n("Y-m-d H:i:s")), 'time_org' => $order->get_date_created()->date_i18n("Y-m-d H:i:s"), 'first_name' => ucfirst(get_post_meta(get_the_ID(), '_billing_first_name', true)), 'last_name' => ucfirst(get_post_meta(get_the_ID(), '_billing_last_name', true)), 'city' => ucfirst(get_post_meta(get_the_ID(), '_billing_city', true)), 'state' => ucfirst(get_post_meta(get_the_ID(), '_billing_state', true)), 'country' => ucfirst(WC()->countries->countries[get_post_meta(get_the_ID(), '_billing_country', true)]) ); if (!$product_tmp['thumb'] && $p_data->is_type('variation')) { $parent_id = $p_data->get_parent_id(); if ($parent_id) { $product_tmp['thumb'] = has_post_thumbnail($parent_id) ? get_the_post_thumbnail_url($parent_id, $product_thumb) : ''; } } $products[] = $product_tmp; } } $products = array_map("unserialize", array_unique(array_map("serialize", $products))); $products = array_values($products); if (count($products) >= 100) { break; } } } // Reset Post Data wp_reset_postdata(); if (count($products)) { return $products; } else { return false; } } } public function is_product() { return is_product(); } public function get_orders_by_product($product_id) { if (is_array($product_id)) { $product_id = implode(',', $product_id); } $order_threshold_num = $this->settings->get_order_threshold_num(); $order_threshold_time = $this->settings->get_order_threshold_time(); if ($order_threshold_num) { switch ($order_threshold_time) { case 1: $time_type = 'days'; break; case 2: $time_type = 'minutes'; break; default: $time_type = 'hours'; } $current_time = strtotime("-" . $order_threshold_num . " " . $time_type); $timestamp = date('Y-m-d G:i:s', $current_time); } global $wpdb; $raw = " SELECT items.order_id, MAX(CASE WHEN itemmeta.meta_key = '_product_id' THEN itemmeta.meta_value END) AS product_id FROM {$wpdb->prefix}woocommerce_order_items AS items INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS itemmeta ON items.order_item_id = itemmeta.order_item_id INNER JOIN {$wpdb->prefix}posts AS post ON post.ID = items.order_id WHERE items.order_item_type IN('line_item') AND itemmeta.meta_key IN('_product_id','_variation_id') AND post.post_date >= '%s' GROUP BY items.order_item_id HAVING product_id IN (%s)"; $sql = $wpdb->prepare($raw, $timestamp, $product_id); return array_map(function ($data) { return wc_get_order($data->order_id); }, $wpdb->get_results($sql)); } public function search_product() { $post_types = array('product'); if (!current_user_can('manage_options')) { return; } ob_start(); $keyword = filter_input(INPUT_GET, 'keyword', FILTER_SANITIZE_STRING); if (empty($keyword)) { die(); } $arg = array( 'post_status' => 'publish', 'post_type' => $post_types, 'posts_per_page' => 50, 's' => $keyword ); $the_query = new WP_Query($arg); $found_products = array(); if ($the_query->have_posts()) { while ($the_query->have_posts()) { $the_query->the_post(); $prd = wc_get_product(get_the_ID()); if ($prd->has_child() && $prd->is_type('variable')) { $product_children = $prd->get_children(); if (count($product_children)) { foreach ($product_children as $product_child) { $product = array( 'id' => $product_child, 'text' => get_the_title($product_child) ); $found_products[] = $product; } } } else { $product_id = get_the_ID(); $product_title = get_the_title(); $the_product = new WC_Product($product_id); if (!$the_product->is_in_stock()) { $product_title .= ' (out-of-stock)'; } $product = array('id' => $product_id, 'text' => $product_title); $found_products[] = $product; } } } wp_send_json($found_products); die; } public function product_query($product_ids = array(), $post_type = array()) { if (count($post_type) < 1) { $post_type = array('product'); } $args_p = array( 'post_type' => $post_type, 'post_status' => 'publish', 'post__in' => $product_ids, 'posts_per_page' => -1, ); $product_data = array(); $the_query_p = new WP_Query($args_p); if ($the_query_p->have_posts()) { $products = $the_query_p->posts; foreach ($products as $product) { $data = wc_get_product($product); if ($data->get_type() == 'variation') { continue; } else { $name_prd = $data->get_title(); } if (!$data->is_in_stock()) { $name_prd .= ' (out-of-stock)'; } $product_id = $data->get_id(); $product_data[] = array( 'product_id' => $product_id, 'product_name' => $name_prd ); } } return $product_data; } public function get_product_by_id($product_id) { $updated_product = new stdClass(); $_product = new EDD_Download($product_id); $updated_product->type = ''; return $updated_product; } }<file_sep><!-- Tab Content !--> <table class="optiontable form-table"> <tbody> <tr valign="top"> <th scope="row"> <label><?php esc_html_e('Product font color', 'live-sales-notifications') ?></label> </th> <td> <input data-ele="highlight" type="text" class="color-picker" name="<?php echo esc_attr(live_sales_notifications_set_field('product_color')) ?>" value="<?php echo esc_attr(live_sales_notifications_get_field('product_color', '#000000')) ?>" style="background-color: <?php echo esc_attr(live_sales_notifications_get_field('product_color', '#000000')) ?>"/> </td> </tr> <tr valign="top"> <th scope="row"> <label><?php esc_html_e('Text color', 'live-sales-notifications') ?></label> </th> <td> <input data-ele="textcolor" style="background-color: <?php echo esc_attr(live_sales_notifications_get_field('text_color', '#000000')) ?>" type="text" class="color-picker" name="<?php echo esc_attr(live_sales_notifications_set_field('text_color')) ?>" value="<?php echo esc_attr(live_sales_notifications_get_field('text_color', '#000000')) ?>"/> </td> </tr> <tr valign="top"> <th scope="row"> <label><?php esc_html_e('Background color', 'live-sales-notifications') ?></label> </th> <td> <input style="background-color: <?php echo esc_attr(live_sales_notifications_get_field('background_color', '#ffffff')) ?>" data-ele="backgroundcolor" type="text" class="color-picker" name="<?php echo esc_attr(live_sales_notifications_set_field('background_color')) ?>" value="<?php echo esc_attr(live_sales_notifications_get_field('background_color', '#ffffff')) ?>"/> </td> </tr> <tr valign="top" class="background-image"> <th scope="row"> <label><?php esc_html_e('Background Image', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui grid"> <?php $attachment_id = (int)live_sales_notifications_get_field('background_image', 0); $attachment_url = wp_get_attachment_url($attachment_id); ?> <div class="four wide column image-picker-wrap"> <img id='image-preview' class="image-preview" src='<?php echo esc_url($attachment_url); ?>' style='height: 96px; width: 320px; <?php echo (empty($attachment_url) || $attachment_id < 1) ? 'display:none;' : ''; ?>'> <input id="upload_image_button" type="button" class="upload_image_button button" value="<?php _e('Upload image'); ?>"/> <input id="remove_image_button" type="button" class="remove_image_button button" value="<?php _e('Remove image'); ?>" style="<?php echo (empty($attachment_url) || $attachment_id < 1) ? 'display:none;' : ''; ?>"/> <input id="<?php echo esc_attr(live_sales_notifications_set_field('background_image')) ?>" type="hidden" <?php checked(live_sales_notifications_get_field('background_image', 0), 0) ?> tabindex="0" class="text image_attachment_id" value="<?php echo $attachment_id; ?>" name="<?php echo esc_attr(live_sales_notifications_set_field('background_image')) ?>"/> </div> </div> </td> </tr> <tr valign="top"> <th scope="row"> <label><?php esc_html_e('Image Position', 'live-sales-notifications') ?></label> </th> <td> <select name="<?php echo esc_attr(live_sales_notifications_set_field('image_position')) ?>" class="mbui fluid dropdown"> <option <?php selected(live_sales_notifications_get_field('image_position'), 0) ?> value="0"><?php esc_attr_e('Left', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('image_position'), 1) ?> value="1"><?php esc_attr_e('Right', 'live-sales-notifications') ?></option> </select> </td> </tr> <tr valign="top"> <th scope="row"> <label><?php esc_html_e('Position', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui form"> <div class="fields"> <div class="four wide field"> <div class="mbui toggle checkbox center aligned segment"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('position')) ?>" type="radio" <?php checked(live_sales_notifications_get_field('position', 0), 0) ?> tabindex="0" class="hidden" value="0" name="<?php echo esc_attr(live_sales_notifications_set_field('position')) ?>"/> <label><?php esc_attr_e('Bottom left', 'live-sales-notifications') ?></label> </div> </div> <div class="four wide field"> <div class="mbui toggle checkbox center aligned segment"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('position')) ?>" type="radio" <?php checked(live_sales_notifications_get_field('position'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('position')) ?>"/> <label><?php esc_attr_e('Bottom right', 'live-sales-notifications') ?></label> </div> </div> <div class="four wide field"> <div class="mbui toggle checkbox center aligned segment"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('position')) ?>" type="radio" <?php checked(live_sales_notifications_get_field('position'), 2) ?> tabindex="0" class="hidden" value="2" name="<?php echo esc_attr(live_sales_notifications_set_field('position')) ?>"/> <label><?php esc_attr_e('Top left', 'live-sales-notifications') ?></label> </div> </div> <div class="four wide field"> <div class="mbui toggle checkbox center aligned segment"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('position')) ?>" type="radio" <?php checked(live_sales_notifications_get_field('position'), 3) ?> tabindex="0" class="hidden" value="3" name="<?php echo esc_attr(live_sales_notifications_set_field('position')) ?>"/> <label><?php esc_attr_e('Top right', 'live-sales-notifications') ?></label> </div> </div> </div> </div> </td> </tr> <tr valign="top"> <th scope="row"> <label><?php esc_html_e('Border radius', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui form"> <div class="inline fields"> <input type="number" name="<?php echo esc_attr(live_sales_notifications_set_field('border_radius')) ?>" value="<?php echo esc_attr(live_sales_notifications_get_field('border_radius', '0')) ?>"/> <label><?php esc_html_e('px', 'live-sales-notifications') ?></label> </div> </div> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('show_close_icon')) ?>"> <?php esc_html_e('Show Close Icon', 'live-sales-notifications') ?> </label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('show_close_icon')) ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('show_close_icon'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('show_close_icon'))?>"/> <label></label> </div> </td> </tr> <tr valign="top" class="show-close-icon hidden"> <th scope="row"> <label><?php esc_html_e('Time close', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui form"> <div class="inline fields"> <input type="number" name="<?php echo esc_attr(live_sales_notifications_set_field('time_close')) ?>" value="<?php echo esc_attr(live_sales_notifications_get_field('time_close', '24')) ?>"/> <label><?php esc_html_e('hours', 'live-sales-notifications') ?></label> </div> </div> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('image_redirect')) ?>"> <?php esc_html_e('Image redirect', 'live-sales-notifications') ?> </label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('image_redirect')) ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('image_redirect'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('image_redirect')) ?>"/> <label></label> </div> <p class="description"><?php echo esc_html__('When click image, you will redirect to product single page.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('image_redirect_target')) ?>"> <?php esc_html_e('Link target', 'live-sales-notifications') ?> </label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('image_redirect_target')) ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('image_redirect_target'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('image_redirect_target')) ?>"/> <label></label> </div> <p class="description"><?php echo esc_html__('Open link on new tab.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('message_display_effect')) ?>"> <?php esc_html_e('Message display effect', 'live-sales-notifications') ?> </label> </th> <td> <select name="<?php echo esc_attr(live_sales_notifications_set_field('message_display_effect')) ?>" class="mbui fluid dropdown" id="<?php echo esc_attr(live_sales_notifications_set_field('message_display_effect')) ?>"> <optgroup label="Bouncing Entrances"> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'bounceIn') ?> value="bounceIn"><?php esc_attr_e('bounceIn', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'bounceInDown') ?> value="bounceInDown"><?php esc_attr_e('bounceInDown', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'bounceInLeft') ?> value="bounceInLeft"><?php esc_attr_e('bounceInLeft', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'bounceInRight') ?> value="bounceInRight"><?php esc_attr_e('bounceInRight', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'bounceInUp') ?> value="bounceInUp"><?php esc_attr_e('bounceInUp', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Fading Entrances"> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'fade-in') ?> value="fade-in"><?php esc_attr_e('fadeIn', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'fadeInDown') ?> value="fadeInDown"><?php esc_attr_e('fadeInDown', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'fadeInDownBig') ?> value="fadeInDownBig"><?php esc_attr_e('fadeInDownBig', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'fadeInLeft') ?> value="fadeInLeft"><?php esc_attr_e('fadeInLeft', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'fadeInLeftBig') ?> value="fadeInLeftBig"><?php esc_attr_e('fadeInLeftBig', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'fadeInRight') ?> value="fadeInRight"><?php esc_attr_e('fadeInRight', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'fadeInRightBig') ?> value="fadeInRightBig"><?php esc_attr_e('fadeInRightBig', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'fadeInUp') ?> value="fadeInUp"><?php esc_attr_e('fadeInUp', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'fadeInUpBig') ?> value="fadeInUpBig"><?php esc_attr_e('fadeInUpBig', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Flippers"> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'flipInX') ?> value="flipInX"><?php esc_attr_e('flipInX', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'flipInY') ?> value="flipInY"><?php esc_attr_e('flipInY', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Lightspeed"> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'lightSpeedIn') ?> value="lightSpeedIn"><?php esc_attr_e('lightSpeedIn', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Rotating Entrances"> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'rotateIn') ?> value="rotateIn"><?php esc_attr_e('rotateIn', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'rotateInDownLeft') ?> value="rotateInDownLeft"><?php esc_attr_e('rotateInDownLeft', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'rotateInDownRight') ?> value="rotateInDownRight"><?php esc_attr_e('rotateInDownRight', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'rotateInUpLeft') ?> value="rotateInUpLeft"><?php esc_attr_e('rotateInUpLeft', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'rotateInUpRight') ?> value="rotateInUpRight"><?php esc_attr_e('rotateInUpRight', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Sliding Entrances"> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'slideInUp') ?> value="slideInUp"><?php esc_attr_e('slideInUp', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'slideInDown') ?> value="slideInDown"><?php esc_attr_e('slideInDown', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'slideInLeft') ?> value="slideInLeft"><?php esc_attr_e('slideInLeft', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'slideInRight') ?> value="slideInRight"><?php esc_attr_e('slideInRight', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Zoom Entrances"> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'zoomIn') ?> value="zoomIn"><?php esc_attr_e('zoomIn', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'zoomInDown') ?> value="zoomInDown"><?php esc_attr_e('zoomInDown', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'zoomInLeft') ?> value="zoomInLeft"><?php esc_attr_e('zoomInLeft', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'zoomInRight') ?> value="zoomInRight"><?php esc_attr_e('zoomInRight', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'zoomInUp') ?> value="zoomInUp"><?php esc_attr_e('zoomInUp', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Special"> <option <?php selected(live_sales_notifications_get_field('message_display_effect'), 'rollIn') ?> value="rollIn"><?php esc_attr_e('rollIn', 'live-sales-notifications') ?></option> </optgroup> </select> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('message_hidden_effect')) ?>"> <?php esc_html_e('Message hidden effect', 'live-sales-notifications') ?> </label> </th> <td> <select name="<?php echo esc_attr(live_sales_notifications_set_field('message_hidden_effect')) ?>" class="mbui fluid dropdown" id="<?php echo esc_attr(live_sales_notifications_set_field('message_hidden_effect')) ?>"> <optgroup label="Bouncing Exits"> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'bounceOut') ?> value="bounceOut"><?php esc_attr_e('bounceOut', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'bounceOutDown') ?> value="bounceOutDown"><?php esc_attr_e('bounceOutDown', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'bounceOutLeft') ?> value="bounceOutLeft"><?php esc_attr_e('bounceOutLeft', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'bounceOutRight') ?> value="bounceOutRight"><?php esc_attr_e('bounceOutRight', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'bounceOutUp') ?> value="bounceOutUp"><?php esc_attr_e('bounceOutUp', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Fading Exits"> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'fade-out') ?> value="fade-out"><?php esc_attr_e('fadeOut', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'fadeOutDown') ?> value="fadeOutDown"><?php esc_attr_e('fadeOutDown', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'fadeOutDownBig') ?> value="fadeOutDownBig"><?php esc_attr_e('fadeOutDownBig', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'fadeOutLeft') ?> value="fadeOutLeft"><?php esc_attr_e('fadeOutLeft', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'fadeOutLeftBig') ?> value="fadeOutLeftBig"><?php esc_attr_e('fadeOutLeftBig', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'fadeOutRight') ?> value="fadeOutRight"><?php esc_attr_e('fadeOutRight', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'fadeOutRightBig') ?> value="fadeOutRightBig"><?php esc_attr_e('fadeOutRightBig', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'fadeOutUp') ?> value="fadeOutUp"><?php esc_attr_e('fadeOutUp', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'fadeOutUpBig') ?> value="fadeOutUpBig"><?php esc_attr_e('fadeOutUpBig', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Flippers"> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'flipOutX') ?> value="flipOutX"><?php esc_attr_e('flipOutX', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'flipOutY') ?> value="flipOutY"><?php esc_attr_e('flipOutY', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Lightspeed"> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'lightSpeedOut') ?> value="lightSpeedOut"><?php esc_attr_e('lightSpeedOut', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Rotating Exits"> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'rotateOut') ?> value="rotateOut"><?php esc_attr_e('rotateOut', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'rotateOutDownLeft') ?> value="rotateOutDownLeft"><?php esc_attr_e('rotateOutDownLeft', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'rotateOutDownRight') ?> value="rotateOutDownRight"><?php esc_attr_e('rotateOutDownRight', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'rotateOutUpLeft') ?> value="rotateOutUpLeft"><?php esc_attr_e('rotateOutUpLeft', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'rotateOutUpRight') ?> value="rotateOutUpRight"><?php esc_attr_e('rotateOutUpRight', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Sliding Exits"> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'slideOutUp') ?> value="slideOutUp"><?php esc_attr_e('slideOutUp', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'slideOutDown') ?> value="slideOutDown"><?php esc_attr_e('slideOutDown', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'slideOutLeft') ?> value="slideOutLeft"><?php esc_attr_e('slideOutLeft', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'slideOutRight') ?> value="slideOutRight"><?php esc_attr_e('slideOutRight', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Zoom Exits"> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'zoomOut') ?> value="zoomOut"><?php esc_attr_e('zoomOut', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'zoomOutDown') ?> value="zoomOutDown"><?php esc_attr_e('zoomOutDown', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'zoomOutLeft') ?> value="zoomOutLeft"><?php esc_attr_e('zoomOutLeft', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'zoomOutRight') ?> value="zoomOutRight"><?php esc_attr_e('zoomOutRight', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'zoomOutUp') ?> value="zoomOutUp"><?php esc_attr_e('zoomOutUp', 'live-sales-notifications') ?></option> </optgroup> <optgroup label="Special"> <option <?php selected(live_sales_notifications_get_field('message_hidden_effect'), 'rollOut') ?> value="rollOut"><?php esc_attr_e('rollOut', 'live-sales-notifications') ?></option> </optgroup> </select> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('custom_css')) ?>"> <?php esc_html_e('Custom CSS', 'live-sales-notifications') ?> </label> </th> <td> <textarea class="" name="<?php echo esc_attr(live_sales_notifications_set_field('custom_css')) ?>"><?php echo esc_html(live_sales_notifications_get_field('custom_css')) ?></textarea> </td> </tr> </tbody> </table> <?php $class = array(); switch (live_sales_notifications_get_field('position')) { case 1: $class[] = 'bottom_right'; break; case 2: $class[] = 'top_left'; break; case 3: $class[] = 'top_right'; break; default: $class[] = ''; } $class[] = live_sales_notifications_get_field('image_position') ? 'img-right' : ''; $attachment_id = live_sales_notifications_get_field('background_image', 0); $attachment_url = wp_get_attachment_url($attachment_id); $custom_css = 'display:block;'; $custom_css .= !empty($attachment_url) && $attachment_id > 0 ? "background-image:url(" . $attachment_url . "); background-size:cover;" : ''; ?> <div style="<?php echo $custom_css; ?>" class=" <?php echo esc_attr(implode(' ', $class)) ?>" id="sales-notification" data-effect_display="<?php echo esc_attr(live_sales_notifications_get_field('message_display_effect')); ?>" data-effect_hidden="<?php echo esc_attr(live_sales_notifications_get_field('message_hidden_effect')); ?>"> <img src="<?php echo esc_url(live_sales_notifications_instance()->plugin_url() . '/assets/images/sample-product.jpg') ?>"> <p><NAME> in New York , United States purchased a <a href="#">Mantranews Pro</a> <small>About 9 hours ago</small> </p> <span id="notify-close"></span> </div> <file_sep>'use strict'; jQuery(document).ready(function () { if (jQuery('#sales-notification').length > 0) { var notify = live_sales_notifications; if (_live_sales_notifications_params.billing == 0 && _live_sales_notifications_params.detect == 0) { notify.detect_address(); } } }); jQuery(window).load(function () { var notify = live_sales_notifications; notify.loop = _live_sales_notifications_params.loop; notify.init_delay = _live_sales_notifications_params.initial_delay; notify.total = _live_sales_notifications_params.notification_per_page; notify.display_time = _live_sales_notifications_params.display_time; notify.next_time = _live_sales_notifications_params.next_time; notify.ajax_url = _live_sales_notifications_params.ajax_url; notify.products = _live_sales_notifications_params.products; notify.messages = _live_sales_notifications_params.messages; notify.image = _live_sales_notifications_params.image; notify.redirect_target = _live_sales_notifications_params.redirect_target; notify.time = _live_sales_notifications_params.time; notify.display_effect = _live_sales_notifications_params.display_effect; notify.hidden_effect = _live_sales_notifications_params.hidden_effect; notify.messages = _live_sales_notifications_params.messages; notify.names = _live_sales_notifications_params.names; notify.detect = _live_sales_notifications_params.detect; notify.billing = _live_sales_notifications_params.billing; notify.in_the_same_cate = _live_sales_notifications_params.in_the_same_cate; notify.message_custom = _live_sales_notifications_params.message_custom; notify.message_number_min = _live_sales_notifications_params.message_number_min; notify.message_number_max = _live_sales_notifications_params.message_number_max; notify.time_close = _live_sales_notifications_params.time_close; notify.show_close = _live_sales_notifications_params.show_close; if (_live_sales_notifications_params.billing == 0 && _live_sales_notifications_params.detect == 0) { notify.cities = [notify.getCookie('live_sales_notifications_city')]; notify.country = [notify.getCookie('live_sales_notifications_country')]; var check_ip = notify.getCookie('live_sales_notifications_client_ip'); if (check_ip && check_ip != 'undefined') { notify.init(); } } else { notify.cities = _live_sales_notifications_params.cities; notify.country = _live_sales_notifications_params.country; notify.init(); } }); var live_sales_notifications = { billing: 0, in_the_same_cate: 0, loop: 0, init_delay: 5, total: 30, display_time: 5, next_time: 60, count: 0, intel: 0, live_sales_notifications_popup: 0, id: 0, messages: '', products: '', ajax_url: '', display_effect: '', hidden_effect: '', time: '', names: '', cities: '', country: '', message_custom: '', message_number_min: '', message_number_max: '', detect: 0, time_close: 0, show_close: 0, shortcodes: ['{first_name}', '{city}', '{state}', '{country}', '{product}', '{product_with_link}', '{time_ago}', '{custom}'], init: function () { if (this.ajax_url) { this.ajax_get_data(); } else { setTimeout(function () { live_sales_notifications.get_product(); }, this.init_delay * 1000); } jQuery('#sales-notification').on('mouseenter', function () { window.clearInterval(live_sales_notifications.live_sales_notifications_popup); }).on('mouseleave', function () { live_sales_notifications.message_show() }); }, detect_address: function () { var ip_address = this.getCookie('live_sales_notifications_client_ip'); if (!ip_address) { jQuery.getJSON('https://extreme-ip-lookup.com/json/', function (data) { if (data.query) { live_sales_notifications.setCookie('live_sales_notifications_client_ip', data.query, 86400); } if (data.city) { live_sales_notifications.setCookie('live_sales_notifications_city', data.city, 86400); } if (data.country) { live_sales_notifications.setCookie('live_sales_notifications_country', data.country, 86400); } }); } }, ajax_get_data: function () { if (this.ajax_url) { var str_data; if (this.id) { str_data = '&id=' + this.id; } else { str_data = ''; } jQuery.ajax({ type: 'POST', data: 'action=live_sales_notifications_get_product' + str_data, url: this.ajax_url, success: function (data) { var products = jQuery.parseJSON(data); if (products && products != 'undefined' && products.length > 0) { live_sales_notifications.products = products; live_sales_notifications.message_show(); setTimeout(function () { live_sales_notifications.get_product(); }, live_sales_notifications.init_delay * 1000); } }, error: function (html) { } }) } }, message_show: function () { var count = this.count++; if (this.total <= count) { return; } window.clearInterval(this.intel); var message_id = jQuery('#sales-notification'); if (message_id.hasClass(this.hidden_effect)) { jQuery(message_id).removeClass(this.hidden_effect); } jQuery(message_id).addClass(this.display_effect).css('display', 'flex'); this.audio(); this.live_sales_notifications_popup = setTimeout(function () { live_sales_notifications.message_hide(); }, this.display_time * 1000); }, message_hide: function () { var message_id = jQuery('#sales-notification'); if (message_id.hasClass(this.display_effect)) { jQuery(message_id).removeClass(this.display_effect); } jQuery('#sales-notification').addClass(this.hidden_effect); jQuery('#sales-notification').fadeOut(1000); window.clearInterval(this.live_sales_notifications_popup); if (this.getCookie('live_sales_notifications_close')) { return; } if (this.loop == true) { this.intel = setInterval(function () { live_sales_notifications.get_product(); }, this.next_time * 1000); } }, get_time_string: function () { var time_cal = this.random(0, this.time * 3600); /*Check day*/ var check_time = parseFloat(time_cal / 86400); if (check_time > 1) { check_time = parseInt(check_time); if (check_time == 1) { return check_time + ' ' + _live_sales_notifications_params.str_day } else { return check_time + ' ' + _live_sales_notifications_params.str_days } } check_time = parseFloat(time_cal / 3600); if (check_time > 1) { check_time = parseInt(check_time); if (check_time == 1) { return check_time + ' ' + _live_sales_notifications_params.str_hour } else { return check_time + ' ' + _live_sales_notifications_params.str_hours } } check_time = parseFloat(time_cal / 60); if (check_time > 1) { check_time = parseInt(check_time); if (check_time == 1) { return check_time + ' ' + _live_sales_notifications_params.str_min } else { return check_time + ' ' + _live_sales_notifications_params.str_mins } } else if (check_time < 10) { return _live_sales_notifications_params.str_few_sec } else { check_time = parseInt(check_time); return check_time + ' ' + _live_sales_notifications_params.str_secs } }, get_product: function () { var products = this.products; var messages = this.messages; var image_redirect = this.image; var redirect_target = this.redirect_target; var data_first_name, data_state, data_country, data_city, time_str, index; if (products == 'undefined' || !products || !messages) { return; } if (products.length > 0 && messages.length > 0) { /*Get message*/ index = live_sales_notifications.random(0, messages.length - 1); var string = messages[index]; /*Get product*/ index = live_sales_notifications.random(0, products.length - 1); var product = products[index]; /*Get name*/ if (parseInt(this.billing) > 0 && parseInt(this.in_the_same_cate) < 1) { data_first_name = product.first_name; data_city = product.city; data_state = product.state; data_country = product.country; time_str = product.time; } else { if (this.names && this.names != 'undefined') { index = live_sales_notifications.random(0, this.names.length - 1); data_first_name = this.names[index]; } else { data_first_name = ''; } if (this.cities && this.cities != 'undefined') { index = live_sales_notifications.random(0, this.cities.length - 1); data_city = this.cities[index]; } else { data_city = ''; } data_state = ''; data_country = this.country; time_str = this.get_time_string(); } var data_product = '<span class="live-sales-notifications-popup-product-title">' + product.title + '</span>'; var data_product_link = '<a '; if (redirect_target) { data_product_link += 'target="_blank"'; } data_product_link += ' href="' + product.url + '">' + product.title + '</a>'; var data_time = '<small>' + _live_sales_notifications_params.str_about + ' ' + time_str + ' ' + _live_sales_notifications_params.str_ago + ' </small>'; var data_custom = this.message_custom; var image_html = ''; if (product.thumb) { if (image_redirect) { image_html = '<a '; if (redirect_target) { image_html += 'target="_blank"'; } image_html += ' href="' + product.url + '"><img src="' + product.thumb + '"></a>' } else { image_html = '<img src="' + product.thumb + '">'; } } /*Replace custom message*/ data_custom = data_custom.replace('{number}', this.random(this.message_number_min, this.message_number_max)); /*Replace message*/ var replaceArray = this.shortcodes; var replaceArrayValue = [data_first_name, data_city, data_state, data_country, data_product, data_product_link, data_time, data_custom]; var finalAns = string; for (var i = replaceArray.length - 1; i >= 0; i--) { finalAns = finalAns.replace(replaceArray[i], replaceArrayValue[i]); } var close_html = ''; if (parseInt(this.show_close) > 0) { close_html = '<div id="notify-close"></div>' } var html = image_html + '<p>' + finalAns + '</p>' + close_html; jQuery('#sales-notification').html(html); this.close_notify(); live_sales_notifications.message_show(); } }, close_notify: function () { jQuery('#notify-close').unbind(); jQuery('#notify-close').bind('click', function () { live_sales_notifications.message_hide(); if (parseInt(live_sales_notifications.time_close) > 0) { jQuery('#sales-notification').unbind(); live_sales_notifications.setCookie('live_sales_notifications_close', 1, 3600 * parseInt(live_sales_notifications.time_close)); } }); }, audio: function () { if (jQuery('#live-sales-notifications-audio').length > 0) { var audio = document.getElementById("live-sales-notifications-audio"); var initAudio = function () { audio.play(); setTimeout(function () { audio.stop(); }, 0); document.removeEventListener('touchstart', initAudio, false); }; document.addEventListener('touchstart', initAudio, false); audio.play(); } }, random: function (min, max) { min = parseInt(min); max = parseInt(max); var rand_number = Math.random() * (max - min); return Math.round(rand_number) + min; }, setCookie: function (cname, cvalue, expire) { var d = new Date(); d.setTime(d.getTime() + (expire * 1000)); var expires = "expires=" + d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; }, getCookie: function (cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } } <file_sep><?php /** * Abstract Compatibility. * * Handles generic compatibility interaction which is implemented by * the different data store classes. * * @class Live_Sales_Notifications_Compatibility * @version 1.0.0 * @package Live_Sales_Notifications/Classes */ if (!defined('ABSPATH')) { exit; } /** * Abstract Live_Sales_Notifications_Compatibility * * Implemented by classes using the same CRUD(s) pattern. * * @version 1.0.0 * @package Live_Sales_Notifications/Abstracts */ abstract class Live_Sales_Notifications_Compatibility { public $store_specific_keys = array( 'order_statuses' ); public $id = 'woocommerce'; public function __construct() { } abstract function version_check(); abstract function get_all_order_status(); abstract function get_product($settings = array()); abstract function is_product(); abstract function search_product(); } <file_sep> <!-- Tab Content !--> <table class="optiontable form-table"> <tbody> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('enable_single_product')) ?>"><?php esc_html_e('Run single product', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('enable_single_product')) ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('enable_single_product'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('enable_single_product')) ?>"/> <label></label> </div> <p class="description"><?php esc_html_e('Notification will only display current product in product detail page that they are viewing.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('notification_product_show_type')) ?>"><?php esc_html_e('Notification show', 'live-sales-notifications') ?></label> </th> <td> <select name="<?php echo esc_attr(live_sales_notifications_set_field('notification_product_show_type')); ?>" class="mbui fluid dropdown"> <option <?php selected(live_sales_notifications_get_field('notification_product_show_type', 0), '0') ?> value="0"><?php echo esc_html__('Current product', 'live-sales-notifications') ?></option> <option <?php selected(live_sales_notifications_get_field('notification_product_show_type')) ?> value="1"><?php echo esc_html__('Products in the same category', 'live-sales-notifications') ?></option> </select> <p class="description"><?php esc_html_e('In product single page, Notification can only display current product or other products in the same category.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top" class="only_current_product hidden"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('show_variation')); ?>"><?php esc_html_e('Show variation', 'live-sales-notifications') ?></label> </th> <td> <div class="mbui toggle checkbox"> <input id="<?php echo esc_attr(live_sales_notifications_set_field('show_variation')) ?>" type="checkbox" <?php checked(live_sales_notifications_get_field('show_variation'), 1) ?> tabindex="0" class="hidden" value="1" name="<?php echo esc_attr(live_sales_notifications_set_field('show_variation')) ?>"/> <label></label> </div> <p class="description"><?php esc_html_e('Show variation instead of product variable.', 'live-sales-notifications') ?></p> </td> </tr> </tbody> </table><file_sep> <!-- Tab Content !--> <table class="optiontable form-table"> <tbody> <tr valign="top"> <th scope="row"> <label><?php esc_html_e('Message purchased', 'live-sales-notifications') ?></label> </th> <td> <table class="mbui sales-notification optiontable form-table"> <?php $messages = live_sales_notifications_get_field('message_purchased'); if (!$messages) { $messages = array('Someone in {city}, {country} purchased a {product_with_link} {time_ago}'); } elseif (!is_array($messages) && $messages) { $messages = array($messages); } if (count($messages)) { foreach ($messages as $k => $message) { ?> <tr> <td width="90%"> <textarea name="<?php echo esc_attr(live_sales_notifications_set_field('message_purchased', 1)) ?>"><?php echo strip_tags($message) ?></textarea> </td> <td> <span class="mbui button remove-message red"><?php esc_html_e('Remove', 'live-sales-notifications') ?></span> </td> </tr> <?php } } ?> </table> <p> <span class="mbui button add-message green"><?php esc_html_e('Add New', 'live-sales-notifications') ?></span> </p> <ul class="description" style="list-style: none"> <li> <span>{first_name}</span> - <?php esc_html_e('Customer\'s first name', 'live-sales-notifications') ?> </li> <li> <span>{city}</span> - <?php esc_html_e('Customer\'s city', 'live-sales-notifications') ?> </li> <li> <span>{state}</span> - <?php esc_html_e('Customer\'s state', 'live-sales-notifications') ?> </li> <li> <span>{country}</span> - <?php esc_html_e('Customer\'s country', 'live-sales-notifications') ?> </li> <li> <span>{product}</span> - <?php esc_html_e('Product title', 'live-sales-notifications') ?> </li> <li> <span>{product_with_link}</span> - <?php esc_html_e('Product title with link', 'live-sales-notifications') ?> </li> <li> <span>{time_ago}</span> - <?php esc_html_e('Time after purchase', 'live-sales-notifications') ?> </li> <li> <span>{custom}</span> - <?php esc_html_e('Use custom shortcode', 'live-sales-notifications') ?> </li> </ul> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('custom_shortcode')) ?>"><?php esc_html_e('Custom', 'live-sales-notifications') ?></label> </th> <td> <?php $custom_shortcode = live_sales_notifications_get_field('custom_shortcode', esc_attr('{number} people seeing this product right now')); ?> <input id="<?php echo esc_attr(live_sales_notifications_set_field('custom_shortcode')) ?>" type="text" tabindex="0" value="<?php echo $custom_shortcode ?>" name="<?php echo esc_attr(live_sales_notifications_set_field('custom_shortcode')) ?>"/> <p class="description"><?php esc_html_e('This is {custom} shortcode content.', 'live-sales-notifications') ?></p> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('min_number')) ?>"><?php esc_html_e('Min Number', 'live-sales-notifications') ?></label> </th> <td> <input id="<?php echo esc_attr(live_sales_notifications_set_field('min_number')) ?>" type="number" tabindex="0" value="<?php echo esc_attr(live_sales_notifications_get_field('min_number', 100)) ?>" name="<?php echo esc_attr(live_sales_notifications_set_field('min_number')) ?>"/> </td> </tr> <tr valign="top"> <th scope="row"> <label for="<?php echo esc_attr(live_sales_notifications_set_field('max_number')) ?>"><?php esc_html_e('Max number', 'live-sales-notifications') ?></label> </th> <td> <input id="<?php echo esc_attr(live_sales_notifications_set_field('max_number')) ?>" type="number" tabindex="0" value="<?php echo esc_attr(live_sales_notifications_get_field('max_number', 200)) ?>" name="<?php echo esc_attr(live_sales_notifications_set_field('max_number')) ?>"/> <p class="description"><?php esc_html_e('Number will random from Min number to Max number', 'live-sales-notifications') ?></p> </td> </tr> </tbody> </table><file_sep><?php /** * Live Sales Notification Compatibility EDD. * * @package Live Sales Notification/Classes * @version 1.0.0 */ defined('ABSPATH') || exit; class Live_Sales_Notifications_Compatibility_EDD extends Live_Sales_Notifications_Compatibility { public function __construct() { $this->id = 'edd'; add_action('woocommerce_order_status_completed', array($this, 'order_completed')); add_action('woocommerce_order_status_pending', array($this, 'order_completed')); } public function version_check() { return true; } public function get_all_order_status() { return array( 'edd-pending' => __('EDD Pending', 'live-sales-notifications'), 'edd-processing' => __('EDD Processing', 'live-sales-notifications'), 'edd-on-hold' => __('EDD on hold', 'live-sales-notifications'), ); } function order_completed($order_id) { // TODO: Implement order_completed() method. } function get_product($settings = array()) { // TODO: Implement get_product() method. $enable_single_product = false;//$settings->enable_single_product(); $notification_product_show_type = true;//$settings->get_notification_product_show_type(); $products = array(); $product_link = $settings->product_link(); $product_thumb = $settings->get_product_sizes(); $show_product_option = $settings->show_product_option(); $prefix = live_sales_notifications_prefix(); /*Check Single Product page*/ if ($enable_single_product && is_edd_product_single_page()) { $product_id = get_the_ID(); if (!$product_id) { return; } $products = get_transient($prefix . 'live_sales_notifications_product_child' . $product_id); if (is_array($products) && count($products)) { return $products; } $product = new EDD_Download($product_id); /* Only show current product*/ if (!$notification_product_show_type) { /*Show variation products*/ $enable_variable = true;//$settings->show_variation(); if ($product->has_variable_prices() && $enable_variable) { $temp_p = delete_transient('live_sales_notifications_product_child' . $product->ID); if (is_array($temp_p) && count($temp_p)) { return $temp_p; } else { //$temp_p = $product->get_children(); /*if (count($temp_p)) { foreach ($temp_p as $key => $the_product) { $product_variation = wc_get_product($the_product); if (!$product_variation->is_in_stock() && !$settings->enable_out_of_stock_product()) { unset($temp_p[$key]); } else { if ($product_variation->get_catalog_visibility() == 'hidden') { continue; } // do stuff for everything else $link = $product_variation->get_permalink(); $product_tmp = array( 'title' => $product_variation->get_name(), 'url' => $link, 'thumb' => has_post_thumbnail($product->get_id()) ? get_the_post_thumbnail_url($product->get_id(), $product_thumb) : (has_post_thumbnail($product_id) ? get_the_post_thumbnail_url($product_id, $product_thumb) : ''), ); if (!$show_product_option) { $orders = $this->get_orders_by_product($product_id); if (is_array($orders) && count($orders)) { foreach ($orders as $order) { $order_infor = array( 'time' => live_sales_notifications_time_subsctract($order->get_date_created()->date_i18n("Y-m-d H:i:s")), 'time_org' => $order->get_date_created()->date_i18n("Y-m-d H:i:s"), 'first_name' => ucfirst(get_post_meta($order->get_id(), '_billing_first_name', true)), 'last_name' => ucfirst(get_post_meta($order->get_id(), '_billing_last_name', true)), 'city' => ucfirst(get_post_meta($order->get_id(), '_billing_city', true)), 'state' => ucfirst(get_post_meta($order->get_id(), '_billing_state', true)), 'country' => ucfirst(WC()->countries->countries[get_post_meta($order->get_id(), '_billing_country', true)]) ); $products[] = array_merge($product_tmp, $order_infor); } } } else { $products[] = $product_tmp; } } } }*/ } } else { return false; } } else { /* Show products in the same category*/ $cates_obj = get_the_terms($product_id, 'download_category'); $cates = wp_list_pluck($cates_obj, 'term_id'); $args = array( 'post_type' => 'download', 'post_status' => 'publish', 'posts_per_page' => 50, 'orderby' => 'rand', 'post__not_in' => array($product_id), 'tax_query' => array( array( 'taxonomy' => 'download_category', 'field' => 'id', 'terms' => $cates, 'include_children' => false, 'operator' => 'IN' ) ) ); $the_query = new WP_Query($args); if ($the_query->have_posts()) { while ($the_query->have_posts()) { $the_query->the_post(); $product = new EDD_Download(get_the_ID()); // do stuff for everything else $link = get_the_permalink(); $product_tmp = array( 'title' => get_the_title(), 'url' => $link, 'thumb' => has_post_thumbnail() ? get_the_post_thumbnail_url('', $product_thumb) : '', ); $products[] = $product_tmp; } } // Reset Post Data wp_reset_postdata(); } if (is_array($products) && count($products)) { set_transient($prefix . 'live_sales_notifications_product_child' . $product->ID, $products, 3600); return $products; } else { return false; } // Reset Post Data } /*Get All page*/ /*Check with Product get from Billing*/ $limit_product = $settings->get_limit_product(); $show_product_option = 0; if ($show_product_option > 0) { $products = array(); /* $products = get_transient($prefix); if (is_array($products) && count($products)) { return $products; } else { $products = array(); }*/ switch ($show_product_option) { case 1: /*Select Products*/ /*Params from Settings*/ $archive_products = $settings->get_products(); $archive_products = is_array($archive_products) ? $archive_products : array(); if (count(array_filter($archive_products)) < 1) { $args = array( 'post_type' => 'download', 'post_status' => 'publish', 'posts_per_page' => 50, 'orderby' => 'rand', ); } else { $args = array( 'post_type' => array('download'), 'post_status' => 'publish', 'posts_per_page' => '50', 'orderby' => 'rand', 'post__in' => $archive_products, ); } break; case 2: /*Latest Products*/ /*Params from Settings*/ $args = array( 'post_type' => 'download', 'post_status' => 'publish', 'posts_per_page' => $limit_product, 'orderby' => 'date', 'order' => 'DESC', ); break; case 4: $viewed_products = !empty($_COOKIE['live_sales_notifications_recently_viewed_product']) ? (array)explode('|', wp_unslash($_COOKIE['live_sales_notifications_recently_viewed_product'])) : array(); // @codingStandardsIgnoreLine $viewed_products = array_reverse(array_filter(array_map('absint', $viewed_products))); if (empty($viewed_products)) { $args = array( 'post_type' => 'download', 'post_status' => 'publish', 'posts_per_page' => '50', 'orderby' => 'rand', ); } else { $args = array( 'posts_per_page' => $limit_product, 'no_found_rows' => 1, 'post_status' => 'publish', 'post_type' => 'download', 'post__in' => $viewed_products, 'orderby' => 'post__in', ); // WPCS: slow query ok. } break; default: /*Select Categories*/ $cates = $settings->get_categories(); if (count($cates)) { $categories = get_terms( array( 'taxonomy' => 'download_category', 'include' => $cates ) ); $categories_checked = array(); if (count($categories)) { foreach ($categories as $category) { $categories_checked[] = $category->term_id; } } else { return false; } /*Params from Settings*/ $cate_exclude_products = $settings->get_cate_exclude_products(); if (!is_array($cate_exclude_products)) { $cate_exclude_products = array(); } $args = array( 'post_type' => 'download', 'post_status' => 'publish', 'posts_per_page' => $limit_product, 'orderby' => 'rand', 'post__not_in' => $cate_exclude_products, 'tax_query' => array( array( 'taxonomy' => 'download_category', 'field' => 'id', 'terms' => $categories_checked, 'include_children' => false, 'operator' => 'IN' ), ) ); } else { $args = array( 'post_type' => 'download', 'post_status' => 'publish', 'posts_per_page' => '50', 'orderby' => 'rand', ); } } $the_query = new WP_Query($args); if ($the_query->have_posts()) { while ($the_query->have_posts()) { $the_query->the_post(); $product = new EDD_Download(get_the_ID()); // do stuff for everything else $link = get_the_permalink(); $product_tmp = array( 'title' => get_the_title(), // 'id' => get_the_ID(), 'url' => $link, 'thumb' => has_post_thumbnail() ? get_the_post_thumbnail_url('', $product_thumb) : '', ); $products[] = $product_tmp; } } // Reset Post Data wp_reset_postdata(); if (count($products)) { set_transient($prefix, $products, 3600); return $products; } else { return false; } } else { /*Get from billing*/ /*Parram*/ $order_threshold_num = $settings->get_order_threshold_num(); $order_threshold_time = $settings->get_order_threshold_time(); $exclude_products = $settings->get_exclude_products(); $order_statuses = $settings->get_order_statuses(); if (!is_array($exclude_products)) { $exclude_products = array(); } $current_time = ''; if ($order_threshold_num) { switch ($order_threshold_time) { case 1: $time_type = 'days'; break; case 2: $time_type = 'minutes'; break; default: $time_type = 'hours'; } $current_time = strtotime("-" . $order_threshold_num . " " . $time_type); } $args = array( 'post_type' => 'edd_payment', 'post_status' => array('pending'),//$order_statuses, 'posts_per_page' => '100', 'orderby' => 'date', 'order' => 'DESC' ); if ($current_time) { $args['date_query'] = array( array( 'after' => array( 'year' => date("Y", $current_time), 'month' => date("m", $current_time), 'day' => date("d", $current_time), 'hour' => date("H", $current_time), 'minute' => date("i", $current_time), 'second' => date("s", $current_time), ), 'inclusive' => true, //(boolean) - For after/before, whether exact value should be matched or not'. 'compare' => '<=', //(string) - Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS' (only in WP >= 3.5), and 'NOT EXISTS' (also only in WP >= 3.5). Default value is '=' 'column' => 'post_date', //(string) - Column to query against. Default: 'post_date'. 'relation' => 'AND', //(string) - OR or AND, how the sub-arrays should be compared. Default: AND. ), ); } $my_query = new WP_Query($args); $products = array(); if ($my_query->have_posts()) { while ($my_query->have_posts()) { $my_query->the_post(); $order = edd_get_payment(get_the_ID()); $order_meta = edd_get_payment_meta_downloads(get_the_ID()); $order_meta_user_info = edd_get_payment_meta_user_info(get_the_ID()); /* echo '<pre>'; print_r($order); print_r($order_meta); print_r($order_meta_user_info);exit;*/ foreach ($order_meta as $item) { if (in_array($item['id'], $exclude_products)) { continue; } if (isset($item['id']) && $item['id']) { $p_data = new EDD_Download($item['id']); if ($p_data->post_status != 'publish') { continue; } // do stuff for everything else $link = get_permalink($item['id']); $item_meta = edd_get_payment_meta($item['id']); $product_tmp = array( 'title' => get_the_title($p_data->ID), 'url' => $link, 'thumb' => has_post_thumbnail($p_data->ID) ? get_the_post_thumbnail_url($p_data->ID, $product_thumb) : '', 'time' => live_sales_notifications_time_subsctract($item_meta['date']), 'time_org' => $item_meta['date'], 'first_name' => ucfirst($order_meta_user_info['first_name']), 'last_name' => ucfirst($order_meta_user_info['last_name']), 'city' => '', 'state' => '', 'country' => '' ); $products[] = $product_tmp; } } $products = array_map("unserialize", array_unique(array_map("serialize", $products))); $products = array_values($products); if (count($products) >= 100) { break; } } } // Reset Post Data wp_reset_postdata(); if (count($products)) { return $products; } else { return false; } } } public function is_product() { return false; } public function search_product() { $post_types = array('download'); if (!current_user_can('manage_options')) { return; } ob_start(); $keyword = filter_input(INPUT_GET, 'keyword', FILTER_SANITIZE_STRING); if (empty($keyword)) { die(); } $arg = array( 'post_status' => 'publish', 'post_type' => $post_types, 'posts_per_page' => 50, 's' => $keyword ); $the_query = new WP_Query($arg); $found_products = array(); if ($the_query->have_posts()) { while ($the_query->have_posts()) { $the_query->the_post(); $product_id = get_the_ID(); $product_title = get_the_title(); $product = array('id' => $product_id, 'text' => $product_title); $found_products[] = $product; } } wp_send_json($found_products); die; } public function product_query($product_ids = array(), $post_type = array()) { if (count($post_type) < 1) { $post_type = array('download'); } $args_p = array( 'post_type' => $post_type, 'post_status' => 'publish', 'post__in' => $product_ids, 'posts_per_page' => -1, ); $product_data = array(); $the_query_p = new WP_Query($args_p); if ($the_query_p->have_posts()) { $products = $the_query_p->posts; foreach ($products as $product) { $product_id = $product->ID; $product_data[] = array( 'product_id' => $product_id, 'product_name' => $product->post_title ); } } return $product_data; } public function get_product_by_id($product_id) { $updated_product = new stdClass(); $_product = wc_get_product($product_id); $updated_product->type = $_product->get_type(); if ($updated_product->type == 'variation') { $updated_product->parent_id = $_product->get_parent_id(); } return $updated_product; } }<file_sep><?php if (!defined('ABSPATH')) { exit; } final class Live_Sales_Notifications { /** * Plugin version. * * @var string */ public $version = LIVE_SALES_NOTIFICATIONS_VERSION; /** * Theme single instance of this class. * * @var object */ protected static $_instance = null; /** * Return an instance of this class. * * @return object A single instance of this class. */ public static function instance() { if (is_null(self::$_instance)) { self::$_instance = new self(); } return self::$_instance; } public $store_type = ''; public $options = array(); public $storewise_options = array(); public $compatibility; /** * Cloning is forbidden. * * @since 1.0.0 */ public function __clone() { _doing_it_wrong(__FUNCTION__, esc_html__('Cheatin&#8217; huh?', 'live-sales-notifications'), '1.0.0'); } /** * Unserializing instances of this class is forbidden. * * @since 1.0.0 */ public function __wakeup() { _doing_it_wrong(__FUNCTION__, esc_html__('Cheatin&#8217; huh?', 'live-sales-notifications'), '1.0.0'); } /** * Initialize the plugin. */ private function __construct() { $this->define_constants(); $this->init_hooks(); do_action('live_sales_notifications_loaded'); } /** * Define Constants. */ private function define_constants() { $this->define('LIVE_SALES_NOTIFICATIONS_ABSPATH', dirname(LIVE_SALES_NOTIFICATIONS_PLUGIN_FILE) . '/'); $this->define('LIVE_SALES_NOTIFICATIONS_PLUGIN_BASENAME', plugin_basename(LIVE_SALES_NOTIFICATIONS_PLUGIN_FILE)); $this->define('LIVE_SALES_NOTIFICATIONS_URI', trailingslashit(plugin_dir_url(LIVE_SALES_NOTIFICATIONS_PLUGIN_FILE))); $this->define('LIVE_SALES_NOTIFICATIONS_DIR', trailingslashit(plugin_dir_path(LIVE_SALES_NOTIFICATIONS_PLUGIN_FILE))); } /** * Define constant if not already set. * * @param string $name Constant name. * @param string|bool $value Constant value. */ private function define($name, $value) { if (!defined($name)) { define($name, $value); } } /** * Hook into actions and filters. */ private function init_hooks() { // Load plugin text domain. add_action('init', array($this, 'load_plugin_textdomain')); add_action('init', array($this, 'load_options'), 11); // Register activation hook. register_activation_hook(LIVE_SALES_NOTIFICATIONS_PLUGIN_FILE, array($this, 'install')); $this->includes(); } public function load_options($is_force = false) { if (!$this->options instanceof Live_Sales_Notifications_Options || $is_force) { $this->options = new Live_Sales_Notifications_Options(); } $this->store_type = $this->options->get_store_type(); $this->storewise_options = $this->options->get_storewise_options(); } /** * Include required core files. */ private function includes() { include_once LIVE_SALES_NOTIFICATIONS_ABSPATH . 'includes/class-live-sales-notifications-autoloader.php'; include_once LIVE_SALES_NOTIFICATIONS_ABSPATH . 'includes/abstracts/abstract-live-sales-notifications-compatibility.php'; include_once LIVE_SALES_NOTIFICATIONS_ABSPATH . 'includes/functions.php'; if ($this->is_request('admin')) { include_once LIVE_SALES_NOTIFICATIONS_ABSPATH . 'includes/admin/class-live-sales-notifications-admin.php'; } if ($this->is_request('frontend')) { $this->frontend_includes(); } } /** * What type of request is this? * * @param string $type admin, ajax, cron or frontend. * @return bool */ private function is_request($type) { switch ($type) { case 'admin': return is_admin(); case 'ajax': return defined('DOING_AJAX'); case 'cron': return defined('DOING_CRON'); case 'frontend': return (!is_admin() || defined('DOING_AJAX')) && !defined('DOING_CRON') && !defined('REST_REQUEST'); } } public function frontend_includes() { include_once LIVE_SALES_NOTIFICATIONS_ABSPATH . 'includes/frontend/class-live-sales-notifications-notify.php'; } /** * Install */ public function install() { // Bypass if filesystem is read-only and/or non-standard upload system is used. if (!is_blog_installed() || apply_filters('live_sales_notifications_install_skip_create_files', false)) { return; } flush_rewrite_rules(); } /** * Load Localisation files. * * Note: the first-loaded translation file overrides any following ones if the same translation is present. * * Locales found in: * - WP_LANG_DIR/live-sales-notifications/live-sales-notifications-LOCALE.mo * - WP_LANG_DIR/plugins/live-sales-notifications-LOCALE.mo */ public function load_plugin_textdomain() { $locale = is_admin() && function_exists('get_user_locale') ? get_user_locale() : get_locale(); $locale = apply_filters('plugin_locale', $locale, 'live-sales-notifications'); unload_textdomain('live-sales-notifications'); load_textdomain('live-sales-notifications', WP_LANG_DIR . '/live-sales-notifications/live-sales-notifications-' . $locale . '.mo'); load_plugin_textdomain('live-sales-notifications', false, plugin_basename(dirname(LIVE_SALES_NOTIFICATIONS_PLUGIN_FILE)) . '/languages'); } /** * Get the plugin url. * * @return string */ public function plugin_url() { return untrailingslashit(plugins_url('/', LIVE_SALES_NOTIFICATIONS_PLUGIN_FILE)); } /** * Get the plugin path. * * @return string */ public function plugin_path() { return untrailingslashit(plugin_dir_path(LIVE_SALES_NOTIFICATIONS_PLUGIN_FILE)); } /** * Display row meta in the Plugins list table. * * @param array $plugin_meta Plugin Row Meta. * @param string $plugin_file Plugin Row Meta. * @return array */ public function plugin_row_meta($plugin_meta, $plugin_file) { if (LIVE_SALES_NOTIFICATIONS_PLUGIN_BASENAME === $plugin_file) { $new_plugin_meta = array( 'docs' => '<a href="' . esc_url(apply_filters('live_sales_notifications_docs_url', 'https://mantrabrain.com/docs/live-sales-notifications/')) . '" title="' . esc_attr(__('View Live Sales Notification Documentation', 'live-sales-notifications')) . '">' . __('Docs', 'live-sales-notifications') . '</a>', 'support' => '<a href="' . esc_url(apply_filters('live_sales_notifications_support_url', 'https://mantrabrain.com/support-forum/')) . '" title="' . esc_attr(__('Visit Free Customer Support Forum', 'live-sales-notifications')) . '">' . __('Free Support', 'live-sales-notifications') . '</a>', ); return array_merge($plugin_meta, $new_plugin_meta); } return (array)$plugin_meta; } public function compatibility($key = '') { if (empty($key)) { $key = $this->store_type; } if (empty($key)) { new Exception("Something wrong, please try again"); } $class = ''; switch ($key) { case "edd": $class = "Live_Sales_Notifications_Compatibility_EDD"; break; case "woocommerce": $class = "Live_Sales_Notifications_Compatibility_WooCommerce"; break; default: new Exception("Wrong compatibility"); break; } if (empty($class)) { throw new Exception("Wrong compatibility, please check your code"); } if (empty($this->compatibility)) { $this->compatibility = new $class; return $this->compatibility; } else if (!$this->compatibility instanceof $class) { $this->compatibility = new $class; return $this->compatibility; } return $this->compatibility; } } <file_sep><?php if (!defined('ABSPATH')) { exit; } class Live_Sales_Notifications_Admin { function __construct() { add_action('admin_menu', array($this, 'menu_page')); add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'), 99999); add_action('init', array($this, 'includes')); } public function includes() { include_once LIVE_SALES_NOTIFICATIONS_ABSPATH . 'includes/admin/class-live-sales-notifications-admin-actions.php'; include_once LIVE_SALES_NOTIFICATIONS_ABSPATH . 'includes/admin/class-live-sales-notifications-admin-settings.php'; } /** * Init Script in Admin */ public function admin_enqueue_scripts() { $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : ''; $page = sanitize_text_field($page); if ($page == 'live-sales-notifications') { global $wp_scripts; $scripts = $wp_scripts->registered; // print_r($scripts); foreach ($scripts as $k => $script) { preg_match('/^\/wp-/i', $script->src, $result); if (count(array_filter($result)) < 1) { wp_dequeue_script($script->handle); } } /*Stylesheet*/ wp_enqueue_style('live-sales-notifications-image', live_sales_notifications_instance()->plugin_url() . '/assets/css/' . 'live-sales-notifications.admin.lib.css'); wp_enqueue_style('live-sales-notifications-transition', live_sales_notifications_instance()->plugin_url() . '/assets/css/' . 'transition.min.css'); wp_enqueue_style('live-sales-notifications-front', live_sales_notifications_instance()->plugin_url() . '/assets/css/' . 'live-sales-notifications.css'); wp_enqueue_style('live-sales-notifications-admin', live_sales_notifications_instance()->plugin_url() . '/assets/css/' . 'live-sales-notifications-admin.css'); wp_enqueue_style('select2', live_sales_notifications_instance()->plugin_url() . '/assets/css/' . 'select2.min.css'); wp_enqueue_script('select2-v4', live_sales_notifications_instance()->plugin_url() . '/assets/js/' . 'select2.js', array('jquery'), '4.0.3'); /*Script*/ wp_enqueue_script('live-sales-notifications-dependsOn', live_sales_notifications_instance()->plugin_url() . '/assets/js/' . 'dependsOn-1.0.2.min.js', array('jquery')); wp_enqueue_script('live-sales-notifications-transition', live_sales_notifications_instance()->plugin_url() . '/assets/js/' . 'transition.min.js', array('jquery')); wp_enqueue_script('live-sales-notifications-dropdown', live_sales_notifications_instance()->plugin_url() . '/assets/js/' . 'dropdown.js', array('jquery')); wp_enqueue_script('live-sales-notifications-tab', live_sales_notifications_instance()->plugin_url() . '/assets/js/' . 'tab.js', array('jquery')); wp_enqueue_script('live-sales-notifications-address', live_sales_notifications_instance()->plugin_url() . '/assets/js/' . 'jquery.address-1.6.min.js', array('jquery')); wp_enqueue_script('live-sales-notifications-admin', live_sales_notifications_instance()->plugin_url() . '/assets/js/' . 'live-sales-notifications-admin.js', array('jquery')); /*Color picker*/ wp_enqueue_script('iris', admin_url('js/iris.min.js'), array( 'jquery-ui-draggable', 'jquery-ui-slider', 'jquery-touch-punch' ), false, 1); /*Custom*/ $product_color = live_sales_notifications_get_field('product_color'); $text_color = live_sales_notifications_get_field('text_color'); $background_color = live_sales_notifications_get_field('background_color'); $custom_css = " #sales-notification{ background-color: {$background_color}; color:{$text_color}; } #sales-notification a{ color:{$product_color}; } "; wp_add_inline_style('live-sales-notifications', $custom_css); } } /** * Register a custom menu page. */ public function menu_page() { add_menu_page( esc_html__('Sales Notification', 'live-sales-notifications'), esc_html__('Sales Notification', 'live-sales-notifications'), 'manage_options', 'live-sales-notifications', array( 'Live_Sales_Notifications_Admin_Settings', 'setting_page' ), 'dashicons-format-status', 25); } } return new Live_Sales_Notifications_Admin();<file_sep><?php if (!defined('ABSPATH')) { exit; } /** * Get Notification Data Setting * Class class Live_Sales_Notifications_Options */ class Live_Sales_Notifications_Options { private $params; public $store_specifc_params; public $store_type = 'woocommerce'; /** * * Init setting */ public function __construct() { global $live_sales_notifications_settings; $live_sales_notifications_settings = get_option('live_sales_notifications_params', array()); $this->params = $live_sales_notifications_settings; $args = array( 'store_type' => 'woocommerce', 'enable' => 0, 'enable_mobile' => 0, 'enable_rtl' => 0, 'product_color' => '#212121', 'text_color' => '#212121', 'background_color' => '#ffffff', 'background_image' => 0, 'image_position' => 0, 'position' => 0, 'border_radius' => 0, 'show_close_icon' => 0, 'time_close' => 0, 'image_redirect' => 0, 'image_redirect_target' => 0, 'message_display_effect' => 'fade-in', 'message_hidden_effect' => 'fade-out', 'custom_css' => '', 'message_purchased' => array(), 'custom_shortcode' => '{number} people seeing this product right now', 'min_number' => '100', 'max_number' => '200', 'show_product_option' => 0, 'select_categories' => array(), 'cate_exclude_products' => array(), 'limit_product' => 50, 'exclude_products' => array(), 'order_threshold_num' => 30, 'order_threshold_time' => 0, 'order_statuses' => array('wc-processing', 'wc-completed'), 'archive_products' => array(), 'virtual_name' => '', 'virtual_time' => 10, 'country' => 0, 'virtual_city' => '', 'virtual_country' => '', 'ipfind_auth_key' => '', 'product_sizes' => 'shop_thumbnail', 'non_ajax' => 0, 'enable_single_product' => 0, 'enable_out_of_stock_product' => 0, 'notification_product_show_type' => 0, 'show_variation' => 0, 'loop' => 0, 'next_time' => 0, 'notification_per_page' => 30, 'initial_delay_random' => 0, 'initial_delay_min' => 0, 'initial_delay' => 0, 'display_time' => 0, 'audio_enable' => 0, 'audio' => 'cool.mp3', 'is_home' => 0, 'is_checkout' => 0, 'is_cart' => 0, 'key' => '', 'product_link' => 0, ); $this->params = apply_filters('live_sales_notifications_settings_args', wp_parse_args($this->params, $args)); if (isset($this->params['store_type'])) { $this->store_type = $this->params['store_type']; } $this->store_specifc_params = $this->get_storewise_options(); } private function get_params($key) { $storewise_params = $this->get_storewise_options($this->params); $store_type = $this->store_type; $return_value = ''; if (isset($storewise_params[$key])) { $return_value = $storewise_params[$key]; } if (isset($storewise_params[$store_type . '_' . $key])) { $return_value = $storewise_params[$store_type . '_' . $key]; } return $return_value; } public function get_storewise_options($datas = array()) { if (count($datas) < 1) { $datas = $this->params; } $storewise_options = array(); $store_type = $this->store_type; $store_instance = live_sales_notifications_instance()->compatibility($store_type); foreach ($datas as $data_key => $data_value) { if ($this->is_store_specific_key($store_instance, $data_key)) { $storewise_options[$store_type . '_' . $data_key] = $data_value; } else { $storewise_options[$data_key] = $data_value; } } return $storewise_options; } public function is_store_specific_key($store_instance, $key) { $store_specific_keys = $store_instance->store_specific_keys; if (!in_array($key, $store_specific_keys)) { return false; } return true; } /** * Get time close cookie * @return mixed|void */ public function get_time_close() { return apply_filters('live_sales_notifications_get_time_close', $this->get_params('time_close')); } /** * Get time close cookie * @return mixed|void */ public function get_store_type() { return apply_filters('live_sales_notifications_get_store_type', $this->store_type); } /** * Enable RTL * @return mixed|void */ public function enable_rtl() { return is_rtl(); } /** * Check External product * @return mixed|void */ public function product_link() { return apply_filters('live_sales_notifications_product_link', $this->get_params('product_link')); } /** * Check enable plugin * @return mixed|void */ public function enable() { return apply_filters('live_sales_notifications_enable', $this->get_params('enable')); } /** * Check enable mobile * @return mixed|void */ public function enable_mobile() { return apply_filters('live_sales_notifications_enable_mobile', $this->get_params('enable_mobile')); } /** * Get Highlight Color * @return mixed|void */ public function get_product_color() { return apply_filters('live_sales_notifications_get_product_color', $this->get_params('product_color')); } /** * Get Text Color * @return mixed|void */ public function get_text_color() { return apply_filters('live_sales_notifications_get_text_color', $this->get_params('text_color')); } /** * Get Background Color * @return mixed|void */ public function get_background_color() { return apply_filters('live_sales_notifications_get_background_color', $this->get_params('background_color')); } /** * Get Background Image * @return mixed|void */ public function get_background_image() { return apply_filters('live_sales_notifications_get_background_image', $this->get_params('background_image')); } /** * Get Image Position * @return mixed|void */ public function get_image_position() { return apply_filters('live_sales_notifications_get_image_position', $this->get_params('image_position')); } /** * Get position * @return mixed|void */ public function get_position() { return apply_filters('live_sales_notifications_get_position', $this->get_params('position')); } /** * Get border radius * @return mixed|void */ public function get_border_radius() { return apply_filters('live_sales_notifications_get_border_radius', $this->get_params('border_radius')); } /** * Check show close icon * @return mixed|void */ public function show_close_icon() { return apply_filters('live_sales_notifications_image_redirect', $this->get_params('show_close_icon')); } /** * Check image clickable * @return mixed|void */ public function image_redirect() { return apply_filters('live_sales_notifications_image_redirect', $this->get_params('image_redirect')); } public function image_redirect_target() { return apply_filters('live_sales_notifications_image_redirect_target', $this->get_params('image_redirect_target')); } /** * Get Display Effect * @return mixed|void */ public function get_display_effect() { return apply_filters('live_sales_notifications_get_message_display_effect', $this->get_params('message_display_effect')); } /** * Get Hidden Effect * @return mixed|void */ public function get_hidden_effect() { return apply_filters('live_sales_notifications_get_message_hidden_effect', $this->get_params('message_hidden_effect')); } /** * Get custom CSS * @return mixed|void */ public function get_custom_css() { return apply_filters('live_sales_notifications_get_custom_css', $this->get_params('custom_css')); } /** * Get message purchased with shortcode * @return mixed|void */ public function get_message_purchased() { return apply_filters('live_sales_notifications_get_message_purchased', $this->get_params('message_purchased')); } /** * Get custom shortcode * @return mixed|void */ public function get_custom_shortcode() { return apply_filters('live_sales_notifications_get_custom_shortcode', $this->get_params('custom_shortcode')); } /** * Get min number in shortcode * @return mixed|void */ public function get_min_number() { return apply_filters('live_sales_notifications_get_min_number', $this->get_params('min_number')); } /** * Get max number in shortcode * @return mixed|void */ public function get_max_number() { return apply_filters('live_sales_notifications_get_max_number', $this->get_params('max_number')); } /** * Check notification data type to get * @return mixed|void */ public function show_product_option() { return apply_filters('live_sales_notifications_get_show_product_option', $this->get_params('show_product_option')); } /** * Get list categories * @return mixed|void */ public function get_categories() { return apply_filters('live_sales_notifications_get_select_categories', $this->get_params('select_categories')); } /** * Get exclude products of Categories * @return mixed|void */ public function get_cate_exclude_products() { return apply_filters('live_sales_notifications_get_cate_exclude_products', $this->get_params('cate_exclude_products')); } /** * Get limit products * @return mixed|void */ public function get_limit_product() { return apply_filters('live_sales_notifications_get_limit_product', $this->get_params('limit_product')); } /** * Get exclude products of get product from billing * @return mixed|void */ public function get_exclude_products() { return apply_filters('live_sales_notifications_get_exclude_products', $this->get_params('exclude_products')); } /** * Get threshold number * @return mixed|void */ public function get_order_threshold_num() { return apply_filters('live_sales_notifications_get_order_threshold_num', $this->get_params('order_threshold_num')); } /** * Get threshold type * @return mixed|void */ public function get_order_threshold_time() { return apply_filters('live_sales_notifications_get_order_threshold_time', $this->get_params('order_threshold_time')); } /** * Get order status * @return mixed|void */ public function get_order_statuses() { return apply_filters('live_sales_notifications_get_order_statuses', $this->get_params('order_statuses')); } /** * Get list products * @return mixed|void */ public function get_products() { return apply_filters('live_sales_notifications_get_archive_products', $this->get_params('archive_products')); } /** * Check address type * @return mixed|void */ public function country() { return apply_filters('live_sales_notifications_country', $this->get_params('country')); } /** * Get Virtual Time * @return mixed|void */ public function get_virtual_name() { return apply_filters('live_sales_notifications_get_virtual_name', $this->get_params('virtual_name')); } /** * Get Virtual Time * @return mixed|void */ public function get_virtual_time() { return apply_filters('live_sales_notifications_get_virtual_time', $this->get_params('virtual_time')); } /** * Get Virtual City * @return mixed|void */ public function get_virtual_city() { return apply_filters('live_sales_notifications_get_virtual_city', $this->get_params('virtual_city')); } /** * Get Virtual Country * @return mixed|void */ public function get_virtual_country() { return apply_filters('live_sales_notifications_get_virtual_country', $this->get_params('virtual_country')); } /** * Get product image size * @return mixed|void */ public function get_product_sizes() { return apply_filters('live_sales_notifications_get_product_sizes', $this->get_params('product_sizes')); } /** * Check turn off Ajax * @return mixed|void */ public function non_ajax() { return apply_filters('live_sales_notifications_non_ajax', $this->get_params('non_ajax')); } /** * Enable notification in single product page * @return mixed|void */ public function enable_single_product() { return apply_filters('live_sales_notifications_enable_single_product', $this->get_params('enable_single_product')); } public function enable_out_of_stock_product() { return apply_filters('live_sales_notifications_enable_out_of_stock_product', $this->get_params('enable_out_of_stock_product')); } /** * Get notification type show in single product * @return mixed|void */ public function get_notification_product_show_type() { return apply_filters('live_sales_notifications_get_notification_product_show_type', $this->get_params('notification_product_show_type')); } /** * Check show variation * @return mixed|void */ public function show_variation() { return apply_filters('live_sales_notifications_show_variation', $this->get_params('show_variation')); } /** * Check loop * @return mixed|void */ public function loop() { return apply_filters('live_sales_notifications_loop', $this->get_params('loop')); } /** * Get next time. * @return mixed|void */ public function get_next_time() { return apply_filters('live_sales_notifications_get_next_time', $this->get_params('next_time')); } /** * Get notification show on page * @return mixed|void */ public function get_notification_per_page() { return apply_filters('live_sales_notifications_get_notification_per_page', $this->get_params('notification_per_page')); } /** * Check random init time * @return mixed|void */ public function initial_delay_random() { return apply_filters('live_sales_notifications_initial_delay_random', $this->get_params('initial_delay_random')); } /** * Get time delay minimum. It will random from initial_delay_min to initial_delay. * @return mixed|void */ public function get_initial_delay_min() { return apply_filters('live_sales_notifications_get_initial_delay_min', $this->get_params('initial_delay_min')); } /** * Get time delay to display notification * @return mixed|void */ public function get_initial_delay() { return apply_filters('live_sales_notifications_get_initial_delay', $this->get_params('initial_delay')); } /** * Get time display of notification * @return mixed|void */ public function get_display_time() { return apply_filters('live_sales_notifications_get_display_time', $this->get_params('display_time')); } /** * Check enable audio * @return mixed|void */ public function audio_enable() { return apply_filters('live_sales_notifications_audio_enable', $this->get_params('audio_enable')); } /** * Get Audio file * @return mixed|void */ public function get_audio() { return apply_filters('live_sales_notifications_get_audio', $this->get_params('audio')); } /** * Check hidden on Homepage * @return mixed|void */ public function is_home() { return apply_filters('live_sales_notifications_is_home', $this->get_params('is_home')); } /** * Check hidden on Checkout page * @return mixed|void */ public function is_checkout() { return apply_filters('live_sales_notifications_is_checkout', $this->get_params('is_checkout')); } /** * Check hidden on Cart page * @return mixed|void */ public function is_cart() { return apply_filters('live_sales_notifications_is_cart', $this->get_params('is_cart')); } /** * Get purchased code * @return mixed|void */ public function get_geo_api() { return apply_filters('live_sales_notifications_get_key', $this->get_params('key')); } }<file_sep><?php if (!defined('ABSPATH')) { exit; } /** * Function include all files in folder * * @param $path Directory address * @param $ext array file extension what will include * @param $prefix string Class prefix */ if (!function_exists('live_sales_notifications_prefix')) { function live_sales_notifications_prefix() { $prefix = get_option('_live_sales_notifications_prefix', date("Ymd")); return $prefix . '_products_' . date("Ymd"); } } if (!function_exists('live_sales_notifications_wpversion')) { function live_sales_notifications_wpversion() { global $wp_version; if (version_compare($wp_version, '4.5.0', '<=')) { return true; } else { false; } } } /** * * @param string $version * * @return bool */ if (!function_exists('live_sales_notifications_store_type')) { function live_sales_notifications_store_type() { $store_type = array( 'woocommerce' => __('WooCommerce', 'live-sales-notifications'), 'edd' => __('Easy Digital Download', 'live-sales-notifications') ); return apply_filters('live_sales_notifications_store_type', $store_type); } } if (!function_exists('live_sales_notifications_get_field')) { function live_sales_notifications_get_field($field, $default = '') { $instance = live_sales_notifications_instance(); $options = $instance->options; $store_type = $instance->store_type; $storewise_params = $instance->storewise_options; $return_value = $default; if (isset($storewise_params[$field])) { $return_value = $storewise_params[$field]; } if (isset($storewise_params[$store_type . '_' . $field])) { $return_value = $storewise_params[$store_type . '_' . $field]; } return $return_value; } } if (!function_exists('live_sales_notifications_set_field')) { function live_sales_notifications_set_field($field, $multi = false) { if ($field) { if ($multi) { return 'live_sales_notifications_params[' . $field . '][]'; } else { return 'live_sales_notifications_params[' . $field . ']'; } } else { return ''; } } } if (!function_exists('live_sales_notifications_get_language')) { function live_sales_notifications_get_language() { $language = ''; // Plugin : sitepress-multilingual-cms/sitepress.php if (function_exists('wpml_get_current_language')) { $language = wpml_get_current_language(); return $language; // Plugin : polylang/polylang.php } elseif (class_exists('Polylang')) { $language = pll_current_language('slug'); return $language; } } } if (!function_exists('live_sales_notifications_time_subsctract')) { function live_sales_notifications_time_subsctract($time, $number = false, $calculate = false) { if (!$number) { if ($time) { $time = strtotime($time); } else { return false; } } if (!$calculate) { $current_time = current_time('timestamp'); // echo "$current_time - $time"; $time_substract = $current_time - $time; } else { $time_substract = $time; } if ($time_substract > 0) { /*Check day*/ $day = $time_substract / (24 * 3600); $day = intval($day); if ($day > 1) { return $day . ' ' . esc_html__('days', 'live-sales-notifications'); } elseif ($day > 0) { return $day . ' ' . esc_html__('day', 'live-sales-notifications'); } /*Check hour*/ $hour = $time_substract / (3600); $hour = intval($hour); if ($hour > 1) { return $hour . ' ' . esc_html__('hours', 'live-sales-notifications'); } elseif ($hour > 0) { return $hour . ' ' . esc_html__('hour', 'live-sales-notifications'); } /*Check min*/ $min = $time_substract / (60); $min = intval($min); if ($min > 1) { return $min . ' ' . esc_html__('minutes', 'live-sales-notifications'); } elseif ($min > 0) { return $min . ' ' . esc_html__('minute', 'live-sales-notifications'); } return intval($time_substract) . ' ' . esc_html__('seconds', 'live-sales-notifications'); } else { return esc_html__('a few seconds', 'live-sales-notifications'); } } }<file_sep><?php /** * Class class Live_Sales_Notifications_Notify */ if (!defined('ABSPATH')) { exit; } class Live_Sales_Notifications_Notify { protected $settings; protected $main_instance; protected $lang; public function __construct() { //$this->settings = new Live_Sales_Notifications_Options(); if (isset($_COOKIE['live_sales_notifications_close']) && $_COOKIE['live_sales_notifications_close'] && $this->settings->show_close_icon()) { return; } add_action('init', array($this, 'init'), 11); add_action('wp_enqueue_scripts', array($this, 'init_scripts')); add_action('wp_footer', array($this, 'wp_footer')); add_action('wp_ajax_nopriv_live_sales_notifications_get_product', array($this, 'product_html')); add_action('wp_ajax_live_sales_notifications_get_product', array($this, 'product_html')); /*Update Recent visited products*/ add_action('template_redirect', array($this, 'track_product_view'), 21); } public function init() { $this->main_instance = live_sales_notifications_instance(); $this->settings = $this->main_instance->options; } /** * Track product views. */ public function track_product_view() { if ($this->settings->show_product_option() != 4) { return; } if (!is_singular('product')) { return; } if (is_active_widget(false, false, 'live_sales_notifications_recently_viewed_product_products', true)) { return; } global $post; if (empty($_COOKIE['live_sales_notifications_recently_viewed_product'])) { // @codingStandardsIgnoreLine. $viewed_products = array(); } else { $viewed_products = wp_parse_id_list((array)explode('|', wp_unslash($_COOKIE['live_sales_notifications_recently_viewed_product']))); // @codingStandardsIgnoreLine. } // Unset if already in viewed products list. $keys = array_flip($viewed_products); if (isset($keys[$post->ID])) { unset($viewed_products[$keys[$post->ID]]); } $viewed_products[] = $post->ID; if (count($viewed_products) > 15) { array_shift($viewed_products); } // Store for session only. setcookie('live_sales_notifications_recently_viewed_product', implode('|', $viewed_products), 0, COOKIEPATH ? COOKIEPATH : '/', COOKIE_DOMAIN, false, false); } /** * Show HTML on front end */ public function product_html() { $enable = $this->settings->enable(); if ($enable) { $products = $this->get_product(); if (is_array($products) && count($products)) { echo json_encode($products); } } die; } /** * Show product * * @param $product_id Product ID * */ protected function show_product() { $image_position = $this->settings->get_image_position(); $position = $this->settings->get_position(); $class = array(); $class[] = $image_position ? 'img-right' : ''; $background_image = $this->settings->get_background_image(); switch ($position) { case 1: $class[] = 'bottom_right'; break; case 2: $class[] = 'top_left'; break; case 3: $class[] = 'top_right'; break; } $attachment_url = esc_url(wp_get_attachment_url($background_image)); $css = 'display:none; '; if (!empty($attachment_url)) { $css .= 'background-image:url(' . $attachment_url . '); background-size:cover; display:none;'; } if ($this->settings->enable_rtl()) { $class[] = 'live-sales-notifications-rtl'; } ob_start(); ?> <div id="sales-notification" class="umeshghimire <?php echo implode(' ', $class) ?>" style="<?php echo esc_attr($css); ?>"> </div> <?php return ob_get_clean(); } /** * Get virtual names * * @param int $limit * * @return array|mixed|void */ public function get_names($limit = 0) { $virtual_name = $this->settings->get_virtual_name(); if ($virtual_name) { $virtual_name = explode("\n", $virtual_name); $virtual_name = array_filter($virtual_name); if ($limit) { if (count($virtual_name) > $limit) { shuffle($virtual_name); return array_slice($virtual_name, 0, $limit); } } } return $virtual_name; } /** * Get virtual cities * * @param int $limit * * @return array|mixed|void */ public function get_cities($limit = 0) { $detect_country = $this->settings->country(); // if ( ! $detect_country ) { // $detect_data = $this->detect_country(); // // $city = isset( $detect_data['city'] ) ? $detect_data['city'] : ''; // } else { $city = $this->settings->get_virtual_city(); if ($city) { $city = explode("\n", $city); $city = array_filter($city); if ($limit) { if (count($city) > $limit) { shuffle($city); return array_slice($city, 0, $limit); } } } // } return $city; } /** * Get all orders given a Product ID. * * @global $wpdb * * @param integer $product_id The product ID. * * @return array An array of WC_Order objects. */ /** * Process product * @return bool */ protected function get_product() { $store = $this->main_instance->compatibility(); $product = $store->get_product($this->settings); return $product; } /** * * @return mixed */ protected function get_custom_shortcode() { $message_shortcode = $this->settings->get_custom_shortcode(); $min_number = $this->settings->get_min_number(); $max_number = $this->settings->get_max_number(); $number = rand($min_number, $max_number); $message = preg_replace('/\{number\}/i', $number, $message_shortcode); return $message; } /** * Message purchased * * @param $product_id */ protected function message_purchased() { $message_purchased = $this->settings->get_message_purchased(); $show_close_icon = $this->settings->show_close_icon(); $show_product_option = $this->settings->show_product_option(); $product_link = $this->settings->product_link(); $image_redirect = $this->settings->image_redirect(); $image_redirect_target = $this->settings->image_redirect_target(); if (is_array($message_purchased)) { $index = rand(0, count($message_purchased) - 1); $message_purchased = $message_purchased[$index]; } $messsage = ''; $keys = array( '{first_name}', '{last_name}', '{city}', '{state}', '{country}', '{product}', '{product_with_link}', '{time_ago}', '{custom}' ); $product = $this->get_product(); if ($product) { $product_id = $product['id']; } else { return false; } $first_name = trim($product['first_name']); $last_name = trim($product['last_name']); $city = trim($product['city']); $state = trim($product['state']); $country = trim($product['country']); $time = trim($product['time']); if (!$show_product_option) { $time = live_sales_notifications_time_subsctract($time); } $_product = $this->main_instance->compatibility()->get_product_by_id($product_id); $product = '<span class="live-sales-notifications-popup-product-title">' . esc_html(strip_tags(get_the_title($product_id))) . '</span>'; if ($_product->type=='external' && $product_link) { // do stuff for simple products $link = get_post_meta($product_id, '_product_url', '#'); if (!$link) { $link = get_permalink($product_id); $link = wp_nonce_url($link, 'wocommerce_notification_click', 'link'); } } else { // do stuff for everything else $link = get_permalink($product_id); $link = wp_nonce_url($link, 'wocommerce_notification_click', 'link'); } ob_start(); ?> <a <?php if ($image_redirect_target) { echo 'target="_blank"'; } ?> href="<?php echo esc_url($link) ?>"><?php echo esc_html($product) ?></a> <?php $product_with_link = ob_get_clean(); ob_start(); ?> <small><?php echo esc_html__('About', 'live-sales-notifications') . ' ' . esc_html($time) . ' ' . esc_html__('ago', 'live-sales-notifications') ?></small> <?php $time_ago = ob_get_clean(); $product_thumb = $this->settings->get_product_sizes(); if (has_post_thumbnail($product_id)) { if ($image_redirect) { $messsage .= '<a ' . ($image_redirect_target ? 'target="_blank"' : '') . ' href="' . esc_url($link) . '">'; } $messsage .= '<img src="' . esc_url(get_the_post_thumbnail_url($product_id, $product_thumb)) . '" class="live-sales-notifications-product-image"/>'; if ($image_redirect) { $messsage .= '</a>'; } } elseif ($_product->type == 'variation') { if (isset($_product->parent_id)) { $parent_id = $_product->parent_id; $messsage .= '<a ' . ($image_redirect_target ? 'target="_blank"' : '') . ' href="' . esc_url($link) . '">'; } $messsage .= '<img src="' . esc_url(get_the_post_thumbnail_url($parent_id, $product_thumb)) . '" class="live-sales-notifications-product-image"/>'; if ($image_redirect) { $messsage .= '</a>'; } } //Get custom shortcode $custom_shortcode = $this->get_custom_shortcode(); $replaced = array( $first_name, $last_name, $city, $state, $country, $product, $product_with_link, $time_ago, $custom_shortcode ); $messsage .= str_replace($keys, $replaced, '<p>' . strip_tags($message_purchased) . '</p>'); ob_start(); if ($show_close_icon) { ?> <span id="notify-close"></span> <?php } $messsage .= ob_get_clean(); return $messsage; } /** * Show HTML code */ public function wp_footer() { $enable = $this->settings->enable(); $audio_enable = $this->settings->audio_enable(); $audio = $this->settings->get_audio(); $enable_mobile = $this->settings->enable_mobile(); $is_home = $this->settings->is_home(); $is_checkout = $this->settings->is_checkout(); $is_cart = $this->settings->is_cart(); // Include and instantiate the class. $detect = new Live_Sales_Notifications_Mobile_Detection; // Any mobile device (phones or tablets). if (!$enable_mobile && $detect->isMobile()) { return false; } /*Assign page*/ if ($is_home && (is_home() || is_front_page())) { return; } if ($is_checkout && is_checkout()) { return; } if ($is_cart && is_cart()) { return; } if ($enable) { echo $this->show_product(); } if ($audio_enable) { ?> <audio id="live-sales-notifications-audio"> <source src="<?php echo esc_url(live_sales_notifications_instance()->plugin_url() . '/assets/audios/' . $audio) ?>"> </audio> <?php } } /** * Add Script and Style */ function init_scripts() { $this->lang = live_sales_notifications_get_language(); $is_home = $this->settings->is_home(); $is_checkout = $this->settings->is_checkout(); $is_cart = $this->settings->is_cart(); $prefix = live_sales_notifications_prefix(); /*Assign page*/ if ($is_home && (is_home() || is_front_page())) { return; } if ($is_checkout && is_checkout()) { return; } if ($is_cart && is_cart()) { return; } wp_enqueue_style('live-sales-notifications', live_sales_notifications_instance()->plugin_url() . '/assets/css/' . 'live-sales-notifications.css', array(), LIVE_SALES_NOTIFICATIONS_VERSION); wp_enqueue_script('live-sales-notifications', live_sales_notifications_instance()->plugin_url() . '/assets/js/' . 'live-sales-notifications.js', array('jquery'), LIVE_SALES_NOTIFICATIONS_VERSION); $options_array = get_transient($prefix . '_head' . $this->lang); $non_ajax = $this->settings->non_ajax(); $archive = $this->settings->show_product_option(); if (!is_array($options_array) || count($options_array) < 1) { $options_array = array( 'str_about' => __('About', 'live-sales-notifications'), 'str_ago' => __('ago', 'live-sales-notifications'), 'str_day' => __('day', 'live-sales-notifications'), 'str_days' => __('days', 'live-sales-notifications'), 'str_hour' => __('hour', 'live-sales-notifications'), 'str_hours' => __('hours', 'live-sales-notifications'), 'str_min' => __('minute', 'live-sales-notifications'), 'str_mins' => __('minutes', 'live-sales-notifications'), 'str_secs' => __('secs', 'live-sales-notifications'), 'str_few_sec' => __('a few seconds', 'live-sales-notifications'), 'time_close' => $this->settings->get_time_close(), 'show_close' => $this->settings->show_close_icon() ); /*Notification options*/ $loop = $this->settings->loop(); $options_array['loop'] = $loop; $initial_delay = $this->settings->get_initial_delay(); $initial_delay_random = $this->settings->initial_delay_random(); if ($initial_delay_random) { $initial_delay_min = $this->settings->get_initial_delay_min(); $initial_delay = rand($initial_delay_min, $initial_delay); } $options_array['initial_delay'] = $initial_delay; $display_time = $this->settings->get_display_time(); $options_array['display_time'] = $display_time; $next_time = $this->settings->get_next_time(); $options_array['next_time'] = $next_time; $notification_per_page = $this->settings->get_notification_per_page(); $options_array['notification_per_page'] = $notification_per_page; $message_display_effect = $this->settings->get_display_effect(); $options_array['display_effect'] = $message_display_effect; $message_hidden_effect = $this->settings->get_hidden_effect(); $options_array['hidden_effect'] = $message_hidden_effect; $target = $this->settings->image_redirect_target(); $options_array['redirect_target '] = $target; $image_redirect = $this->settings->image_redirect(); $options_array['image'] = $image_redirect; $message_purchased = $this->settings->get_message_purchased(); if (!is_array($message_purchased)) { $message_purchased = array($message_purchased); } $options_array['messages'] = $message_purchased; $options_array['message_custom'] = $this->settings->get_custom_shortcode(); $options_array['message_number_min'] = $this->settings->get_min_number(); $options_array['message_number_max'] = $this->settings->get_max_number(); /*Autodetect*/ $detect = $this->settings->country(); $options_array['detect'] = $detect; /*Check get from billing*/ /*Current products*/ $enable_single_product = $this->settings->enable_single_product(); $notification_product_show_type = $this->settings->get_notification_product_show_type(); if ($archive || ($notification_product_show_type && is_product() && $enable_single_product)) { $virtual_time = $this->settings->get_virtual_time(); $options_array['time'] = $virtual_time; $names = $this->get_names(50); if (is_array($names) && count($names)) { $options_array['names'] = $names; } if ($detect) { $cities = $this->get_cities(50); if (is_array($cities) && count($cities)) { $options_array['cities'] = $cities; } $options_array['country'] = $this->settings->get_virtual_country(); } $options_array['billing'] = 0; } else { $options_array['billing'] = 1; if (!$non_ajax && !is_product()) { $options_array['ajax_url'] = admin_url('admin-ajax.php'); } } if ($notification_product_show_type && is_product() && $enable_single_product) { $options_array['in_the_same_cate'] = 1; } else { $options_array['in_the_same_cate'] = 0; } set_transient($prefix . '_head' . $this->lang, $options_array, 86400); } /*Process products, address, time */ /*Load products*/ if ($archive || $non_ajax || is_product()) { $products = $this->get_product(); } else { $products = array(); } if (is_array($products) && count($products)) { $options_array['products'] = $products; } /*echo '<pre>'; //print_r($this->settings); var_dump(!$archive); var_dump(!$non_ajax); var_dump(!is_product()); exit;*/ if ($archive && !$non_ajax && !live_sales_notifications_instance()->compatibility()->is_product()) { $options_array['ajax_url'] = admin_url('admin-ajax.php'); } wp_localize_script('live-sales-notifications', '_live_sales_notifications_params', $options_array); /*Custom*/ $product_color = $this->settings->get_product_color(); $text_color = $this->settings->get_text_color(); $background_color = $this->settings->get_background_color(); $custom_css_setting = $this->settings->get_custom_css(); $background_image = $this->settings->get_background_image(); $border_radius = $this->settings->get_border_radius() . 'px'; $custom_css = " #sales-notification{ background-color: {$background_color}; color:{$text_color} !important; border-radius:{$border_radius} ; } #sales-notification img{ border-radius:{$border_radius} 0 0 {$border_radius}; } #sales-notification a, #sales-notification p{ color:{$text_color} !important; } #sales-notification a, #sales-notification p span{ color:{$product_color} !important; } " . $custom_css_setting; if ($background_image) { $background_image = wp_get_attachment_url($background_image); $custom_css .= "#sales-notification.live-sales-notifications-extended::before{ background-image: url('{$background_image}'); background-size:cover; border-radius:{$border_radius}; }"; } wp_add_inline_style('live-sales-notifications', $custom_css); } } new Live_Sales_Notifications_Notify();<file_sep>=== Live Sales Notifications - WooCommerce & Easy Digital Download Sales Notification === Contributors: mantrabrain Donate link: http://www.mantrabrain.com/ Tags: sales, notification, woocommerce, easy-digital-download, edd Requires at least: 3.3 Requires PHP: 5.2.4 Tested up to: 5.1.1 Stable tag: 1.0.1 License: MIT License License URI: http://opensource.org/licenses/MIT Live sales notification for WooCommerce and Easy Digital Download products. == Description == Live sales notification for WooCommerce and Easy Digital Download products. == Installation == 1. Install Live Sales Notification either via the WordPress.org plugin directory, or by uploading the files to your server 2. Activate the plugin through the 'Plugins' menu in WordPress == Changelog == = 1.0.0 = * Initial Release <file_sep><?php if (!defined('ABSPATH')) { exit; } class Live_Sales_Notifications_Admin_Actions { public function __construct() { add_action('live_sales_notifications_before_admin_setting', array($this, 'save')); add_action('wp_ajax_live_sales_notifications_search_product', array($this, 'search_product')); add_action('wp_ajax_live_sales_notifications_search_cate', array($this, 'search_cate')); } /** * Search product category ajax */ public function search_cate() { if (!current_user_can('manage_options')) { return; } ob_start(); $keyword = filter_input(INPUT_GET, 'keyword', FILTER_SANITIZE_STRING); if (empty($keyword)) { die(); } $categories = get_terms( array( 'taxonomy' => 'product_cat', 'orderby' => 'name', 'order' => 'ASC', 'search' => $keyword, 'number' => 100 ) ); $items = array(); if (count($categories)) { foreach ($categories as $category) { $item = array( 'id' => $category->term_id, 'text' => $category->name ); $items[] = $item; } } wp_send_json($items); die; } /*Ajax Product Search*/ public function search_product($x = '', $post_types = array('product')) { $main_instance = live_sales_notifications_instance(); $main_instance->compatibility()->search_product(); die; } /** * Get files in directory * * @param $dir * * @return array|bool */ private function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; } /** * Save post meta * * @param $post * * @return bool */ public function save() { if (!isset($_POST['_live_sales_notifications_nonce']) || !isset($_POST['live_sales_notifications_params'])) { return false; } if (!wp_verify_nonce($_POST['_live_sales_notifications_nonce'], 'live_sales_notifications_save_email_settings')) { return false; } if (!current_user_can('manage_options')) { return false; } $data = $_POST['live_sales_notifications_params']; $data ['virtual_name'] = sanitize_text_field($this->stripslashes_deep($data['virtual_name'])); $data ['virtual_city'] = sanitize_text_field($this->stripslashes_deep($data['virtual_city'])); $data ['custom_css'] = sanitize_text_field($this->stripslashes_deep($data['custom_css'])); $data ['virtual_country'] = sanitize_text_field($this->stripslashes_deep($data['virtual_country'])); update_option('_live_sales_notifications_prefix', substr(md5(date("YmdHis")), 0, 10)); if (isset($data['check_key'])) { unset($data['check_key']); delete_transient('_site_transient_update_plugins'); } $instance_of_main = live_sales_notifications_instance(); $options = $instance_of_main->options; update_option('live_sales_notifications_params', $options->get_storewise_options($data)); if (is_plugin_active('wp-fastest-cache/wpFastestCache.php')) { $cache = new WpFastestCache(); $cache->deleteCache(true); } $instance_of_main->load_options(true); } } new Live_Sales_Notifications_Admin_Actions();
9cb169c8bb222494fb2842a437ec11cf6c270c99
[ "JavaScript", "Text", "PHP" ]
22
PHP
mantrabrain/live-sales-notifications
7b6fd743bd59b7c7fcdce83360f20f8005dc2935
31a01c8f166788c66f73e5427cf55072e37dadb5
refs/heads/main
<file_sep>class BackgroundColors(): BLUE = '\033[34m' CYAN = '\033[36m' GREEN = '\033[32m' WHITE = '\033[37m' WARNING = '\033[33m' FAIL = '\033[31m' END = '\033[0m' def printColor(value, color, end=END): print(color + value + end) <file_sep>def printOut(string): print(string) printOut('Linting setup!') <file_sep>from .colors import BackgroundColors class DoorMat(): def top(width): BackgroundColors.printColor( value=" Check if TODO or FIXME exist ".center(width, "*"), color=BackgroundColors.CYAN ) def middle(width): BackgroundColors.printColor( value=" End Check & Continu ".center(width, "*"), color=BackgroundColors.CYAN ) def bottom(width): BackgroundColors.printColor( value=" Issues created ".center(width, "*"), color=BackgroundColors.CYAN ) <file_sep>certifi==2020.6.20 chardet==3.0.4 Deprecated==1.2.10 flake8==3.8.4 idna==2.10 mccabe==0.6.1 pycodestyle==2.6.0 pyflakes==2.2.0 PyGithub==1.53 PyJWT==1.7.1 requests==2.24.0 urllib3==1.25.11 wrapt==1.12.1 <file_sep>### Action to scan all files and create issues and todo's Code will scan for `TODO` and `FIXME`. - `TODO` will create a issue with the label `todo` - `FIXME` will create a issue with the label `bug` and `help wanted` Usage: ```yml jobs: welcome: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: RemcoHalman/PythonTodoAction@main with: token: ${{secrets.GITHUB_TOKEN}} assignees: ${{github.actor}} ``` ### TODO - [x] exclude path - [ ] exclude file <file_sep># action will be run in python3 container FROM python:3 WORKDIR /app # copying requirements.txt and install the action dependencies COPY requirements.txt . RUN pip install -r requirements.txt # src folder contains the code that we want to run for this action. COPY ./src . # we will just run our script as our docker entrypoint by calling it python scan.py CMD ["python", "./scan.py"]<file_sep>import json from .colors import BackgroundColors class Writer(): def put(data, filename): try: jsondata = json.dumps(data, indent=4, skipkeys=False, sort_keys=True) fd = open(filename, 'w') fd.write(jsondata) fd.close() except Exception as e: BackgroundColors.printColor( value=f"ERROR writing: {e.filename}", color=BackgroundColors.WARNING ) pass def get(filename): returndata = {} try: fd = open(filename, 'r') text = fd.read() fd.close() returndata = json.loads(text) print(returndata) except IOError as e: BackgroundColors.printColor( value=f"COULD NOT LOAD: {e.filename}", color=BackgroundColors.FAIL )
c119db98d2f49712e3d07bd3b8fd129a34c694a8
[ "Markdown", "Python", "Text", "Dockerfile" ]
7
Python
RemcoHalman/PythonTodoAction
141efd0d795c05305cd93f8a738cf99f5a3334ee
4069ff21fd4ebf84f6ac7f117ca7d7fb27ae774d
refs/heads/master
<file_sep>package btcore.co.kr.ibeacon.Ibeacon; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import android.util.Log; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Timer; import java.util.TimerTask; /** * Created by thenathanjones on 24/01/2014. */ public class IBeaconService implements BluetoothAdapter.LeScanCallback { private static final String TAG = IBeaconService.class.getName(); private final Context mContext; private final Collection<IBeaconListener> mListeners = new ArrayList<IBeaconListener>(); private Map<String, IBeacon> mKnownBeacons = new HashMap<String, IBeacon>(); private Timer mTimer; public IBeaconService(Context context) { mContext = context; } public void registerListener(IBeaconListener listener) { if (mListeners.isEmpty()) { startScanning(); } mListeners.add(listener); } public void unregisterListener(IBeaconListener listener) { mListeners.remove(listener); if (mListeners.isEmpty()) { stopScanning(); } } private void startScanning() { if (bluetoothAdapter().isEnabled()) { bluetoothAdapter().startLeScan(this); startListenerUpdates(); } else { Log.w(TAG, "Bluetooth is disabled, unable to scan."); } } private void startListenerUpdates() { mTimer = new Timer(); TimerTask updateListeners = new TimerTask() { @Override public void run() { updateListenersWith(mKnownBeacons.values()); } }; mTimer.scheduleAtFixedRate(updateListeners, IBeaconConstants.UPDATE_PERIOD, IBeaconConstants.UPDATE_PERIOD); } private void updateListenersWith(Collection<IBeacon> beacons) { cullStaleBeacons(beacons); for (IBeaconListener listener : mListeners) { listener.beaconsFound(mKnownBeacons.values()); } } private void cullStaleBeacons(Collection<IBeacon> beacons) { long now = System.currentTimeMillis(); Collection<IBeacon> toRemove = new HashSet<IBeacon>(); for (IBeacon beacon : beacons) { if ((now - beacon.lastReport()) > IBeaconConstants.CULL_DELAY) { toRemove.add(beacon); } } for (IBeacon beacon : toRemove) { mKnownBeacons.remove(beacon.hash); } } private void stopScanning() { bluetoothAdapter().stopLeScan(this); stopListenerUpdates(); } private void stopListenerUpdates() { mTimer.cancel(); } private BluetoothAdapter mBluetoothAdapter; private BluetoothAdapter bluetoothAdapter() { if (mBluetoothAdapter == null) { final BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); } return mBluetoothAdapter; } @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { parseBeaconFrom(rssi, scanRecord); } private void parseBeaconFrom(int rssi, byte[] scanRecord) { if (IBeacon.isBeacon(scanRecord)) { Log.d(TAG, "Congratulations, you have found an iBeacon!"); IBeacon scannedBeacon = IBeacon.from(scanRecord); IBeacon existingBeacon = mKnownBeacons.get(scannedBeacon.hash); scannedBeacon.calculateDistanceFrom(rssi, existingBeacon); Log.d(TAG + ":distanceVars", scannedBeacon.minor + "," + scannedBeacon.txPower + "," + rssi); mKnownBeacons.put(scannedBeacon.hash, scannedBeacon); Log.d(TAG, "Beacon " + scannedBeacon.hash + " located approx. " + scannedBeacon.distanceInMetres() + "m"); } else { Log.d(TAG, "Record is not an iBeacon"); } } }
fc0b4b37fd045f4822a667fda7cec27e7cc4e944
[ "Java" ]
1
Java
btcoreproject/beacon
2819bf94c274025c64a6d938d21a7a6023fe4a5f
df112b51186005521a0c9562b5639441d3fcc6b2
refs/heads/master
<file_sep>import React from 'react'; class Reviews extends React.Component { constructor(props) { super(props); } render() { return(<li>{this.props.review.description}</li>) } } export default Reviews; <file_sep>#### Setup Fork, clone, run yarn install, yarn start, pull request #### Do * xAdd a new class component for Reviews * xMake sure to use extends and super * xImport and use this component in ProductDetail * xThis component will take a product from props * xIt will show the number of reviews followed by "review" or "reviews" depending on if there is one or more reviews * xIt will create a list of the reviews description which will inititally be hidden * xWhen the word "review" is clicked show the reviews * xWhen clicked again, hide the reviews <file_sep>import React from "react"; import Reviews from './Reviews.js'; class ProductDetail extends React.Component { constructor(props) { super(props); this.state = { visible: false } } buttonClick = () => { this.setState(prevState => ({ visible: !prevState.visible })); console.log(this.state.visible); }; render() { const {name,description,rating,imgUrl} = this.props.product; const stars = []; for (let i = 0; i < rating; i++) { stars.push(<span className="glyphicon glyphicon-star" />); } const reviewIt = this.props.product.reviews.map((r) => { if(this.state.visible) { return <Reviews review={r} /> } return <span></span> }); return ( <div className="col-sm-4 col-lg-4 col-md-4"> <div className="thumbnail"> <img style={{width: "320px",height: "150px"}} src={imgUrl} alt="" /> <div className="caption"> <h4><a href="#">{name}</a> </h4> <p>{description} </p> </div> <div className="ratings"> <div className="pull-right"> <ol onClick={this.buttonClick}> {this.props.product.reviews.length} reviews {reviewIt} </ol> </div> <p> {stars} </p> </div> </div> </div> ); } } export default ProductDetail;
8c35a28c99ed80f1b91dcf5c389de0585c7e40d2
[ "JavaScript", "Markdown" ]
3
JavaScript
gdevany/advanced-state-practice
7c9f3123d6310e78d600001fcd7c7804746e750f
e2fdfdee6e4063c54c3c10b996ceff3324f54839
refs/heads/master
<file_sep>package com.cg.ems.service; import java.util.Collection; import com.cg.ems.dao.EmployeeDAO; import com.cg.ems.dao.EmployeeDAOImpl; import com.cg.ems.pojo.Employee; public class EmployeeServiceImpl implements EmployeeService { private EmployeeDAO dao = new EmployeeDAOImpl(); @Override public void addNewEmployee(Employee employee) { dao.addNewEmployee(employee); @Override public Collection<Employee> viewAllEmployees(){ return dao.viewAllEmployees(); @Override public Employee getemployeeById(int empId) { return dao.getemployeeById(empId); @Override public void deleteEmployee(int empId) { dao.deleteEmployee(empId); } } <file_sep># MVC-EMS-
9e9831c1933f98bb59c1f3fe826102a01f23e7a4
[ "Markdown", "Java" ]
2
Java
drishtihrao/MVC-EMS-
b2217bfc51b5ab98aeba9059711345329d04de37
eef88a301da355e23b5fca7abcb20fb099a8ec46
refs/heads/master
<file_sep>import React from 'react'; import { hashHistory } from 'react-router'; import artists from '../../json/artists.json'; import './artists.scss'; export default class ArtistsPage extends React.Component { onArtistClick(artist) { hashHistory.push(`/shows/${artist.collection}`); } render() { return ( <div> { artists.map(artist => this.renderArtist(artist)) } </div> ); } renderArtist(artist) { return ( <div key={ artist.collection }> <span className="artist-link" onClick={ this.onArtistClick.bind(this, artist) }> { artist.name } </span> </div> ); } }<file_sep>import { take, put, call, fork } from 'redux-saga/effects'; import * as shows from '../api/shows'; import * as actions from '../actions'; function* fetchEntity(entity, apiFn, apiArgs) { try { yield put( entity.request(apiArgs) ); const response = yield call(apiFn, apiArgs); yield put( entity.success(response) ); } catch (error) { yield put( entity.failure(error) ); } } const fetchShows = fetchEntity.bind(null, actions.collectionShows, shows.creamiestByCollectionId); export function* watchGetShowsList() { while (true) { const { collectionId } = yield take(actions.FETCH_COLLECTION_SHOWS); yield fork(fetchShows, collectionId); } } export default function* supervisor() { yield fork(watchGetShowsList); }<file_sep>import 'babel-polyfill'; import React from 'react'; import {render} from 'react-dom'; import {createStore, combineReducers, applyMiddleware} from 'redux'; import {Provider} from 'react-redux'; import {Router, Route, IndexRedirect, hashHistory} from 'react-router'; import {syncHistoryWithStore, routerReducer} from 'react-router-redux' import Layout from './Layout.jsx'; import ArtistsPage from './pages/artists/ArtistsPage.jsx'; import ShowsPage from './pages/shows/ShowsPage.jsx'; import createSagaMiddleware from 'redux-saga'; import createLogger from 'redux-logger'; import sagas from './sagas'; const div = document.createElement('div'); document.body.appendChild(div); const sagaMiddleware = createSagaMiddleware(); const store = createStore( combineReducers({ routing: routerReducer }), applyMiddleware(sagaMiddleware, createLogger()) ); sagaMiddleware.run(sagas); const history = syncHistoryWithStore(hashHistory, store); const router = <Provider store={ store }> <Router history={ history }> <Route path="/" component={ Layout }> <IndexRedirect to="/artists" /> <Route path="artists" component={ ArtistsPage }/> <Route path="shows/:collectionId" component={ ShowsPage }/> </Route> </Router> </Provider>; render(router, div); <file_sep>React client for Live Music Archive <file_sep> export default (url, options) => { return window.fetch(url, options); }; <file_sep>import doFetch from 'fetch-jsonp'; const ROW_COUNT = 20; const FORMAT = 'VBR+MP3+OR+Ogg+Vorbis'; const CREAM_SORT_BY = 'downloads'; const FRESH_SORT_BY = 'publicdate'; const getSearchUrl = (collectionId, sortBy) => `http://archive.org/advancedsearch.php?q=%28collection%3A${collectionId}+OR+mediatype%3A${collectionId}%29+AND+format%3A(${FORMAT})+AND+-mediatype%3Acollection&fl%5B%5D=date&fl%5B%5D=downloads&fl%5B%5D=format&fl%5B%5D=identifier&fl%5B%5D=mediatype&fl%5B%5D=title&sort%5B%5D=${sortBy}+desc&sort%5B%5D=&sort%5B%5D=&rows=${ROW_COUNT}&page=1&output=json`; const getBrowseUrl = (collectionId, year) => `http://archive.org/advancedsearch.php?q=collection%3Aetree+AND+date%3A%5B${year}-01-01+TO+${year}-12-31%5D+AND+collection%3A${collectionId}+AND+format%3A(${FORMAT})&fl%5B%5D=avg_rating&fl%5B%5D=collection&fl%5B%5D=date&fl%5B%5D=downloads&fl%5B%5D=format&fl%5B%5D=identifier&fl%5B%5D=mediatype&fl%5B%5D=num_reviews&fl%5B%5D=title&sort%5B%5D=date+desc&sort%5B%5D=&sort%5B%5D=&rows=${ROW_COUNT}&page=&output=json`; export const creamiestByCollectionId = collectionId => doFetch(getSearchUrl(collectionId, CREAM_SORT_BY)).then(r => r.json()); export const freshestByCollectionId = collectionId => doFetch(getSearchUrl(collectionId, FRESH_SORT_BY)).then(r => r.json()); export const browseByYearAndCollectionId = (collectionId, year) => doFetch(getBrowseUrl(collectionId, year)).then(r => r.json());<file_sep>const REQUEST = 'REQUEST'; const SUCCESS = 'SUCCESS'; const FAILURE = 'FAILURE'; function createRequestTypes(base) { const res = {}; [REQUEST, SUCCESS, FAILURE].forEach(type => res[type] = `${base}_${type}`); return res; } export const COLLECTION_SHOWS = createRequestTypes('COLLECTION_SHOWS'); export const collectionShows = { request: collectionId => action(COLLECTION_SHOWS.REQUEST, {collectionId}), success: response => action(COLLECTION_SHOWS.SUCCESS, {response}), failure: error => action(COLLECTION_SHOWS.FAILURE, {error}) }; const action = (type, payload = {}) => ({type, ...payload}); export const FETCH_COLLECTION_SHOWS = 'FETCH_COLLECTION_SHOWS'; export const fetchCollectionShows = collectionId => action(FETCH_COLLECTION_SHOWS, {collectionId}); <file_sep>import React from 'react'; import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import {fetchCollectionShows} from '../../actions'; export const mapDispatchToProps = dispatch => { return bindActionCreators({ fetchCollectionShows }, dispatch); }; @connect(state => state, mapDispatchToProps) export default class ShowsPage extends React.Component { componentDidMount() { this.props.fetchCollectionShows(this.props.params.collectionId); } render() { return ( <div> Shows! </div> ); } }<file_sep>jest.unmock('../artistsApi'); import artistsApi from '../shows'; import doFetch from '../fetch'; describe('artistsApi', () => { it('returns loading promise', () => { expect(doFetch).toBeCalledWith(); }); });
a438f3271b7ffc19c04d295625d51de20634869e
[ "JavaScript", "Markdown" ]
9
JavaScript
ab712/lp
a35fa8bc797ee761b2ef59fae936291b25d6a02d
962c05b709f31eb6b061084c8cfe8317820d8ef3
refs/heads/master
<repo_name>superstrings/about-fun<file_sep>/golang/gobyexample/env.go package main import ( "os" "fmt" ) func main() { fmt.Printf("%+v", os.Environ()) }<file_sep>/README.md # about-fun <file_sep>/golang/gobyexample/init.go package main import "fmt" // 包内首先被执行 func init() { fmt.Println("init...") } func main() { fmt.Println("main..") }<file_sep>/golang/exercise-learning-go/c2.go package main import "fmt" func q9(arg ... int) { for i, v := range arg { println(i, v) } } func main() { q9(1, 2, 3, 4, 5) type Vertex struct { x, y int } v := Vertex{1, 2} fmt.Printf("%T %#v", v, v) }<file_sep>/golang/exercise-learning-go/c1/q1_for_loop.go package main import "fmt" func main() { for i := 0; i < 10; i++ { fmt.Println(i) } i := 0 LOOP: fmt.Println(i) i++ if i < 10 { goto LOOP } arr := [...]int{2, 3, 5, 7, 11, 13} for _, v := range arr { fmt.Println(v) } } <file_sep>/golang/exercise-learning-go/even/even.go package even func Even(a int) bool { return a % 2 == 0 } func Edd(a int) bool { return a % 2 == 1 }<file_sep>/golang/gobyexample/panic.go package main import "os" func main() { //panic("panic ...") _, err := os.Create("/tmp/tmp/tmp/1") if err != nil { panic(err) } }<file_sep>/golang/exercise-learning-go/c1.go package main import ( "fmt" "unicode/utf8" ) func fizz_buzz() { for i := 1; i <= 100; i++ { if (i % 3 == 0) && (i % 5 == 0) { fmt.Println("FizzBuzz") } else if i % 3 == 0 { fmt.Println("Fizz") } else if i % 5 == 0 { fmt.Println("Buzz") } else { fmt.Println(i) } } } func q3() { const max = 7 for i := 0; i < max; i++ { for j := 0; j <= i; j++ { fmt.Print("A") } fmt.Println() } } func q3_2(str string) { //utf8.RuneCount() cnt := 0 for i, w := 0, 0; i < len(str); i += w { runeValue, width := utf8.DecodeRuneInString(str[i:]) fmt.Println(runeValue, width) w = width cnt++ } fmt.Printf("rune count: %d\n", cnt) fmt.Printf("str bytes: %d\n", len(str)) fmt.Println(str) r := []rune(str) text := string(r[0:4]) + "abc" + string(r[7:]) fmt.Println(text) } func q3_3(str string) { r := []rune(str) for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } fmt.Println(string(r)) } func q4() { //if len(s) == 0 // print 0 s := []float64{1.1, 2.2, 3.3, 4.4} sum := float64(0) for _, v := range s { sum += v } fmt.Println(sum / float64(len(s))) } func main() { //fizz_buzz() //q3() //q3_2("foo bar 中文 鸭子") q3_3("foobar") q4() }
9cf84301852b634131d532806df40f0621337da7
[ "Markdown", "Go" ]
8
Go
superstrings/about-fun
286a685e289f6fdde92be5a4145e171aaed48a79
109a5bdea98736cdf93aee1a29eb767b1ae47f15
refs/heads/master
<repo_name>levithomason/canibrowse<file_sep>/test/fixtures/userAgents.js module.exports = { chrome51Mac: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', chrome58Mac: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_0) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/10.2 Safari/604.1.23 Chrome/58.0.3029.110', chrome60Mac: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36', chrome51Win: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', firefox46Mac: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:46.0) Gecko/20100101 Firefox/46.0', firefox46Win: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:46.0) Gecko/20100101 Firefox/46.0', msedge13: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/13.10586', msie8: 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)', msie9: 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)', msie11: 'Mozilla/5.0 (Windows NT 6.3; Win64, x64; Trident/7.0; rv:11.0) like Gecko', safari10Mac: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4', safari10iOS: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/10.0 Mobile/14A300 Safari/602.1', safari10iPad: 'Mozilla/5.0 (iPad; CPU OS 10_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/10.0 Mobile/14A300 Safari/602.1', } <file_sep>/src/index.js const express = require('express') const cors = require('cors') const app = express() const handlers = require('./handlers') // // Middleware // app.use(cors()) // // Routes // app.get('/', handlers.getRoot) app.get('/detect', handlers.getDetect) // // Error handler // app.use((err, req, res, next) => { if (res.headersSent) return next(err) res.status(err.status || 400) res.json({ error: err.message }) }) // // Start // const { PORT = 3000 } = process.env app.listen(PORT, () => { console.log(`Server listening on ${PORT}`) }) <file_sep>/test/specs/handlers.spec.js const _ = require('lodash') const HTTPError = require('node-http-error') const { getRoot, requestToArguments } = require('../../src/handlers') const DEFAULT_REQ = { header: () => {}, query: {} } const DEFAULT_RES = { json: () => {} } const req = (req = {}) => _.merge({}, DEFAULT_REQ, req) const res = (res = {}) => _.merge({}, DEFAULT_RES, res) describe('handlers', () => { describe('requestToArguments', () => { test('coerces boolean query params', () => { const input = req({ query: { debug: 'true', mobile: 'false', strict: '', tablet: 'false' } }) const expected = { debug: true, mobile: false, strict: true, tablet: false } expect(requestToArguments(input)).toMatchObject(expected) }) test('defaults ua to the User-Agent header', () => { const mockRequest = req({ header: name => name }) const { ua } = requestToArguments(mockRequest) expect(ua).toEqual('User-Agent') }) test('returns top level keys: debug, mobile, strict, tablet', () => { const args = requestToArguments( req({ query: { debug: '', mobile: '', strict: '', tablet: '', ua: 'foo' } }), ) expect(args).toMatchObject({ debug: true, mobile: true, strict: true, tablet: true }) }) test('does not return undefined keys', () => { const args = requestToArguments(req()) Object.keys(args).forEach(key => { // assert the object doesn't have the property for better failure messages if (args[key] === undefined) expect(args).not.toHaveProperty(key) }) }) describe('browser specifications', () => { test('considers extra query params to be browser specifications', () => { const args = requestToArguments(req({ query: { aBrowser: '0.1' } })) expect(args).toHaveProperty('browsers.aBrowser') }) test('handles whitelisting with "true"', () => { const args = requestToArguments(req({ query: { chrome: 'true' } })) expect(args).toHaveProperty('browsers.chrome', { blacklisted: false, minVersions: [], whitelisted: true, }) }) test("handles whitelisting with ''", () => { const args = requestToArguments(req({ query: { firefox: '' } })) expect(args).toHaveProperty('browsers.firefox', { blacklisted: false, minVersions: [], whitelisted: true, }) }) test('handles blacklisting', () => { const args = requestToArguments(req({ query: { msie: 'false' } })) expect(args).toHaveProperty('browsers', { msie: { blacklisted: true, minVersions: [], whitelisted: false, }, }) }) test('handles single versions', () => { const args = requestToArguments(req({ query: { chrome: '60' } })) expect(args).toHaveProperty('browsers.chrome', { blacklisted: false, minVersions: ['60'], whitelisted: false, }) }) test('handles multiple versions', () => { const args = requestToArguments(req({ query: { msie: ['10', '11'] } })) expect(args).toHaveProperty('browsers.msie', { blacklisted: false, minVersions: ['10', '11'], whitelisted: false, }) }) }) }) describe('getRoot', () => { test('throws if browsers and mobile and tablet were not specified', () => { expect(() => getRoot(req(), res())).toThrow( new HTTPError(400, 'Request has no requirements. Docs https://goo.gl/RJGJgf.'), ) }) test('does not throw when excluding mobile and tablet', () => { expect(() => getRoot(req({ query: { mobile: false, tablet: false } }), res())).not.toThrow() }) }) }) <file_sep>/README.md Can I Browse [![CircleCI](https://img.shields.io/circleci/project/github/levithomason/canibrowse/master.svg?style=flat-square)]() [![David](https://img.shields.io/david/levithomason/canibrowse.svg?style=flat-square)]() ============ Determine if your user's are using a supported browser. <!-- toc --> - [Why?](#why) - [Usage](#usage) - [Examples](#examples) * [IE >= 9](#ie--9) * [Only Chrome and Firefox](#only-chrome-and-firefox) * [Blacklist specific browsers](#blacklist-specific-browsers) * [Whitelist specific browsers](#whitelist-specific-browsers) * [Specify mobile or tablet](#specify-mobile-or-tablet) * [Debug what is going on](#debug-what-is-going-on) * [Just get detection info](#just-get-detection-info) * [Send a custom user agent](#send-a-custom-user-agent) - [Features I'd :heart: to see](#features-id-heart-to-see) * [Query browser versions](#query-browser-versions) - [Credits](#credits) <!-- tocstop --> ## Why? - You want to display a message to your users to upgrade or change browsers. - You don't want to ship and update browser lists and detection code with your client code. ## Usage Hit the API with the browsers you support as query params: [`https://canibrowse.now.sh?chrome=60`](https://canibrowse.now.sh?chrome=60) Response in Chrome >= 60: ```js { canBrowse: true // did the user agent meet the requirements? detected: { // user agent detection results name: 'Chrome', chrome: true, version: '60.0', blink: true, mac: true, osversion: '10.12.5', a: true, }, } ``` ## Examples 💡Detection is done with [bowser][1]. All of its [browser flags][2] are supported. ### IE >= 9 By default, browsers you do not specify are considered supported. [`https://canibrowse.now.sh?msie=9`](https://canibrowse.now.sh?msie=9) |Chrome |Firefox |IE8 |IE9 | |--------|--------|--------|--------| |✓ |✓ |✖ |✓ | ### Only Chrome and Firefox Use `strict` if you support only the specified browsers and no others. [`https://canibrowse.now.sh?strict&chrome&firefox`](https://canibrowse.now.sh?strict&chrome&firefox) |Chrome |Firefox |IE |Safari | |--------|--------|--------|--------| |✓ |✓ |✖ |✖ | ### Blacklist specific browsers Pass a browser as `false` to exclude all versions. [`https://canibrowse.now.sh?msie=false`](https://canibrowse.now.sh?msie=false) |Chrome |Firefox |IE |Safari | |--------|--------|--------|--------| |✓ |✓ |✖ |✓ | ### Whitelist specific browsers Pass a browser as `true` or without a value to include all versions. [`https://canibrowse.now.sh?strict&chrome=true`](https://canibrowse.now.sh?strict&chrome=true) [`https://canibrowse.now.sh?strict&chrome`](https://canibrowse.now.sh?strict&chrome) |Chrome 1 |Chrome ∞ |Other browsers| |----------|----------|--------------| |✓ |✓ |✖ | ### Specify mobile or tablet You can specify `mobile` or `tablet`. [`https://canibrowse.now.sh?mobile=false&tablet=false`](https://canibrowse.now.sh?mobile=false&tablet=false) |Mobile |Tablet |Desktop | |--------|--------|--------| |✖ |✖ |✓ | ### Debug what is going on Pass `debug` to see more info on the `detection` and `requirements`. [`https://canibrowse.now.sh?debug&chrome=60`](https://canibrowse.now.sh?debug&chrome=60) ```js { canBrowse: true // did the user agent meet the requirements? detected: { // user agent detection results name: 'Chrome', chrome: true, version: '60.0', blink: true, mac: true, osversion: '10.12.5', a: true, }, strict: false, // was strict enabled mobile: false, // was mobile enabled tablet: false, // was tablet enabled browsers: { // browser requirements generated form the request chrome: { minVersions: ['60'], whitelisted: false, blacklisted: false, }, }, } ``` ### Just get detection info Only returns the user agent detection results, perhaps to do your own checks against. [`https://canibrowse.now.sh/detect`](https://canibrowse.now.sh/detect) ```js { name: 'Chrome', chrome: true, version: '60.0', blink: true, mac: true, osversion: '10.12.5', a: true, } ``` ### Send a custom user agent You can pass a `ua` query param or override the `User-Agent` header. ## Features I'd :heart: to see These are possible with the current libraries we use, they just to be implemented. PRs welcome. >### Query browser versions > >Specify supported browsers by a [Browserslist][3] `query` like `last 2 versions` or `> 5%`. > >[`https://canibrowse.now.sh?query=last 2 versions`](https://canibrowse.now.sh?query=last%202%20versions) > >|Older |2 version old |Current | >|--------|--------------|--------| >|✖ |✓ |✓ | > ## Credits Can I Browse is uses [bowser][1] for user agent parsing and compatibility checks and [Browserslist][3] for browser list queries. Browser detection and browser list query issues should be opened on the main repos. [1]: https://github.com/lancedikson/bowser [2]: https://github.com/lancedikson/bowser#browser-flags [3]: https://github.com/ai/browserslist <file_sep>/src/handlers.js const bowser = require('bowser') const HTTPError = require('node-http-error') const { isBrowserSupported } = require('./controller') const requestToArguments = req => { const reqQuery = Object.assign({}, req.query) // coerce boolean query params Object.keys(reqQuery).forEach(key => { if (reqQuery[key] === '' || reqQuery[key] === 'true') reqQuery[key] = true if (reqQuery[key] === 'false') reqQuery[key] = false }) const { debug, mobile, strict, tablet, ua = req.header('User-Agent'), query } = reqQuery delete reqQuery.debug delete reqQuery.mobile delete reqQuery.strict delete reqQuery.tablet delete reqQuery.ua delete reqQuery.query // all other query params are browser specifications const browserParams = reqQuery const browsers = {} // Browserslist has a default query // Only add browsers if there is a user query if (query) { // browserslist(query).forEach(result => { // const [browser, version] = result.split(' ') // // TODO convert Browserslist results to bowser arguments before adding to requirements // // requirements[browser] = requirements[browser] || {} // requirements[browser].minVersions = requirements[browser].minVersions || [] // requirements[browser].minVersions.concat(version) // }) } Object.keys(browserParams).forEach(browser => { const specs = [].concat(browserParams[browser]) browsers[browser] = browsers[browser] || {} browsers[browser].minVersions = browsers[browser].minVersions || [] specs.forEach(value => { // Coerce boolean values const blacklisted = value === false const whitelisted = value === true browsers[browser].blacklisted = blacklisted browsers[browser].whitelisted = whitelisted // if it is not a boolean, it is a browser version (i.e. '59') if (typeof value !== 'boolean') { browsers[browser].minVersions.push(value) } }) }) const args = { browsers, debug, mobile, strict, tablet, ua } // remove undefined values Object.keys(args).forEach(key => args[key] === undefined && delete args[key]) return args } const getRoot = (req, res) => { const { browsers, debug, mobile, strict, tablet, ua } = requestToArguments(req) if (mobile === undefined && tablet === undefined && !Object.keys(browsers).length) { throw new HTTPError(400, 'Request has no requirements. Docs https://goo.gl/RJGJgf.') } const result = isBrowserSupported(ua, { browsers, debug, mobile, strict, tablet }) res.json(result) } const getDetect = (req, res) => { const { ua } = requestToArguments(req) res.json(bowser._detect(ua)) } module.exports = { requestToArguments, getRoot, getDetect, } <file_sep>/src/controller.js const bowser = require('bowser') // TODO support browser list queries // const browserslist = require('browserslist') const isBrowserSupported = (ua = '', opts = {}) => { const { debug, mobile, strict, tablet, browsers } = opts const detected = bowser._detect(ua) let canBrowse if (strict) { // When strict, a passing browser: // - must match defined mobile/tablet opts // - AND // - must be specified in the browsers // - must not be blacklisted // - must either be whitelisted or pass the minVersions check const passesMobile = mobile === undefined || !!detected.mobile === mobile const passesTablet = tablet === undefined || !!detected.tablet === tablet const isValidVersion = !browsers || Object.keys(browsers).some(browser => { const { minVersions, whitelisted, blacklisted } = browsers[browser] if (!detected[browser]) return false if (blacklisted) return false if (whitelisted) return true return minVersions.some(version => bowser.check({ [browser]: version }, strict, ua)) }) canBrowse = passesMobile && passesTablet && isValidVersion } else { // When not strict, a passing browser: // - can have no requirements // - OR // - must not fail mobile/tablet opts // - must not be blacklisted // - must be whitelisted or must pass the minVersions check const passesMobile = !(mobile === false && detected.mobile) const passesTablet = !(tablet === false && detected.tablet) const isValidVersion = !browsers || Object.keys(browsers).every(browser => { const { minVersions, whitelisted, blacklisted } = browsers[browser] if (!detected[browser]) return true if (blacklisted) return false if (whitelisted) return true return minVersions.some(version => bowser.check({ [browser]: version }, strict, ua)) }) canBrowse = passesMobile && passesTablet && isValidVersion } // // Result // const result = { canBrowse, detected } if (debug) { Object.assign(result, { strict: !!strict, mobile: !!mobile, tablet: !!tablet, browsers, }) } // remove undefined values Object.keys(result).forEach(key => result[key] === undefined && delete result[key]) return result } module.exports = { isBrowserSupported, }
4706891ae009d56cdc48c636e63ed4c9ac8e5e15
[ "JavaScript", "Markdown" ]
6
JavaScript
levithomason/canibrowse
df6093dd8b7b40109f1815f179f829b025711616
fd714d9274c2b421a6ee2b97ccd19f77cffaec6b
refs/heads/master
<repo_name>nishp77/thenewboston-python-client<file_sep>/tests/banks.py from tnb.banks import Bank def test_success_fetch_accounts(requests_mock): accounts = [ { "id": "5a8c7990-393a-4299-ae92-2f096a2c7f43", "created_date": "2020-10-08T02:18:07.346849Z", "modified_date": "2020-10-08T02:18:07.346914Z", "account_number": "<KEY>", "trust": "0.00", }, { "id": "2682963f-06b1-47d7-a2e1-1f8ec6ae98dc", "created_date": "2020-10-08T02:39:44.071810Z", "modified_date": "2020-10-08T02:39:44.071853Z", "account_number": "<KEY>", "trust": "0.00", }, ] result = { "count": 2, "next": None, "previous": None, "results": accounts, } requests_mock.get( "http://10.2.3.4:80/accounts", json=result, ) bank = Bank(address="10.2.3.4") response = bank.fetch_accounts() assert response == result def test_success_fetch_accounts_on_page_2(requests_mock): results = [ { "id": "5a8c7990-393a-4299-ae92-2f096a2c7f43", "created_date": "2020-10-08T02:18:07.346849Z", "modified_date": "2020-10-08T02:18:07.346914Z", "account_number": "<KEY>", "trust": "0.00", }, { "id": "2682963f-06b1-47d7-a2e1-1f8ec6ae98dc", "created_date": "2020-10-08T02:39:44.071810Z", "modified_date": "2020-10-08T02:39:44.071853Z", "account_number": "<KEY>", "trust": "0.00", }, ] address = "10.2.3.4" url = f"http://{address}:80/accounts" payload = { "count": 6, "next": f"{url}?limit=2&offset=4", "previous": f"{url}?limit=2", "results": results, } requests_mock.get(f"{url}?limit=2&offset=2", json=payload) bank = Bank(address=address) response = bank.fetch_accounts(offset=2, limit=2) assert response == payload def test_success_fetch_bank_transactions(requests_mock): bank_transactions = [ { "id": "8d422974-7ca2-4386-a2aa-26ac0cab00b8", "block": { "id": "370b5e8c-03ed-4d72-b649-940e1ec82fca", "created_date": "2020-11-19T17:55:22.188130Z", "modified_date": "2020-11-19T17:55:22.188176Z", "balance_key": "<KEY>", "sender": "<KEY>", "signature": "743bc0bfcc8db0cd0b736e5cbaf0c5fd1866fd73e805e58cdb2afd3a19" "8d53636a5d9d4560ec047a8c8e221da29a0f7b1b20f3bf879e7bb7c281f0890b413e02", }, "amount": 1, "recipient": "2e86f48216567302527b69eae6c6a188097ed3a9741f43cc3723e570cf47644c", }, { "id": "e98c8ce2-d89e-4b72-8e90-61f431a83dd1", "block": { "id": "370b5e8c-03ed-4d72-b649-940e1ec82fca", "created_date": "2020-11-19T17:55:22.188130Z", "modified_date": "2020-11-19T17:55:22.188176Z", "balance_key": "<KEY>", "sender": "0d304450eae6b5094240cc58b008066316d9f641878d9af9dd70885f065913a0", "signature": "743bc0bfcc8db0cd0b736e5cbaf0c5fd1866fd73e805e58cdb2afd3a19" "8d53636a5d9d4560ec047a8c8e221da29a0f7b1b20f3bf879e7bb7c281f0890b413e02", }, "amount": 19600, "recipient": "82ad4b185c2ac04440c8f1c54854819ac2ea374255e8fecc54a6f28d4fcc4814", }, ] result = { "count": 2, "next": None, "previous": None, "results": bank_transactions, } requests_mock.get( "http://10.2.3.4:80/bank_transactions", json=result, ) bank = Bank(address="10.2.3.4") response = bank.fetch_bank_transactions() assert response == result def test_success_fetch_bank_transactions_on_page_2(requests_mock): results = [ { "id": "8d422974-7ca2-4386-a2aa-26ac0cab00b8", "block": { "id": "370b5e8c-03ed-4d72-b649-940e1ec82fca", "created_date": "2020-11-19T17:55:22.188130Z", "modified_date": "2020-11-19T17:55:22.188176Z", "balance_key": "<KEY>", "sender": "0d304450eae6b5094240cc58b008066316d9f641878d9af9dd70885f065913a0", "signature": "743bc0bfcc8db0cd0b736e5cbaf0c5fd1866fd73e805e58cdb2afd3a19" "8d53636a5d9d4560ec047a8c8e221da29a0f7b1b20f3bf879e7bb7c281f0890b413e02", }, "amount": 1, "recipient": "2e86f48216567302527b69eae6c6a188097ed3a9741f43cc3723e570cf47644c", }, { "id": "e98c8ce2-d89e-4b72-8e90-61f431a83dd1", "block": { "id": "370b5e8c-03ed-4d72-b649-940e1ec82fca", "created_date": "2020-11-19T17:55:22.188130Z", "modified_date": "2020-11-19T17:55:22.188176Z", "balance_key": "<KEY>", "sender": "0d304450eae6b5094240cc58b008066316d9f641878d9af9dd70885f065913a0", "signature": "743bc0bfcc8db0cd0b736e5cbaf0c5fd1866fd73e805e58cdb2afd3a19" "8d53636a5d9d4560ec047a8c8e221da29a0f7b1b20f3bf879e7bb7c281f0890b413e02", }, "amount": 19600, "recipient": "82ad4b185c2ac04440c8f1c54854819ac2ea374255e8fecc54a6f28d4fcc4814", }, ] address = "10.2.3.4" url = f"http://{address}:80/bank_transactions" payload = { "count": 6, "next": f"{url}?limit=2&offset=4", "previous": f"{url}?limit=2", "results": results, } requests_mock.get(f"{url}?limit=2&offset=2", json=payload) bank = Bank(address=address) response = bank.fetch_bank_transactions(offset=2, limit=2) assert response == payload def test_success_fetch_invalid_blocks(requests_mock): result = [ { "id": "2bcd53c5-19f9-4226-ab04-3dfb17c3a1fe", "created_date": "2020-07-11T18:44:16.518695Z", "modified_date": "2020-07-11T18:44:16.518719Z", "block_identifier": "65ae26192dfb9ec41f88c6d582b374a9b42ab58833e", "block": "3ff4ebb0-2b3d-429b-ba90-08133fcdee4e", "confirmation_validator": "fcd2dce8-9e4f-4bf1-8dac-cdbaf64e5ce8", "primary_validator": "51461a75-dd8d-4133-81f4-543a3b054149", } ] requests_mock.get( "http://10.2.3.4:80/invalid_blocks", json=result, ) bank = Bank(address="10.2.3.4") response = bank.fetch_invalid_blocks() assert response == result def test_success_fetch_invalid_blocks_on_page_2(requests_mock): results = [ { "id": "2bcd53c5-19f9-4226-ab04-3dfb17c3a1fe", "created_date": "2020-07-11T18:44:16.518695Z", "modified_date": "2020-07-11T18:44:16.518719Z", "block_identifier": "65ae26192dfb9ec41f88c6d582b374a9b42ab58833e", "block": "3ff4ebb0-2b3d-429b-ba90-08133fcdee4e", "confirmation_validator": "fcd2dce8-9e4f-4bf1-8dac-cdbaf64e5ce8", "primary_validator": "51461a75-dd8d-4133-81f4-543a3b054149", } ] address = "10.2.3.4" url = f"http://{address}:80/invalid_blocks" payload = { "count": 3, "next": None, "previous": f"{url}?limit=2", "results": results, } requests_mock.get(f"{url}?limit=2&offset=2", json=payload) bank = Bank(address=address) response = bank.fetch_invalid_blocks(offset=2, limit=2) assert response == payload def test_success_fetch_confirmations_blocks(requests_mock): blocks = [ { "id": "e7c5c2e0-8ed1-4eb3-abd8-97fa2e5ca8db", "created_date": "2020-10-08T02:18:07.908635Z", "modified_date": "2020-10-08T02:18:07.908702Z", "block_identifier": "824614aa97edb391784b17ce6956b70aed31edf741c1858d43ae4d566b2a13ed", "block": "c6fc11cf-8948-4d32-96c9-d56caa6d5b24", "validator": "e2a138b0-ebe9-47d2-a146-fb4d9d9ca378", }, { "id": "78babf4b-74ed-442e-b5ab-7b23345c18f8", "created_date": "2020-10-08T02:18:07.998146Z", "modified_date": "2020-10-08T02:18:07.998206Z", "block_identifier": "824614aa97edb391784b17ce6956b70aed31edf741c1858d43ae4d566b2a13ed", "block": "c6fc11cf-8948-4d32-96c9-d56caa6d5b24", "validator": "97a878ac-328a-47b6-ac93-be6deee75d94", }, ] result = { "count": 2, "next": None, "previous": None, "results": blocks, } requests_mock.get( "http://10.2.3.4:80/confirmation_blocks", json=result, ) bank = Bank(address="10.2.3.4") response = bank.fetch_confirmation_blocks() assert response == result def test_success_fetch_confirmations_blocks_on_page_2(requests_mock): results = [ { "id": "e7c5c2e0-8ed1-4eb3-abd8-97fa2e5ca8db", "created_date": "2020-10-08T02:18:07.908635Z", "modified_date": "2020-10-08T02:18:07.908702Z", "block_identifier": "824614aa97edb391784b17ce6956b70aed31edf741c1858d43ae4d566b2a13ed", "block": "c6fc11cf-8948-4d32-96c9-d56caa6d5b24", "validator": "e2a138b0-ebe9-47d2-a146-fb4d9d9ca378", }, { "id": "78babf4b-74ed-442e-b5ab-7b23345c18f8", "created_date": "2020-10-08T02:18:07.998146Z", "modified_date": "2020-10-08T02:18:07.998206Z", "block_identifier": "824614aa97edb391784b17ce6956b70aed31edf741c1858d43ae4d566b2a13ed", "block": "c6fc11cf-8948-4d32-96c9-d56caa6d5b24", "validator": "97a878ac-328a-47b6-ac93-be6deee75d94", }, ] address = "10.2.3.4" url = f"http://{address}:80/confirmation_blocks" payload = { "count": 6, "next": f"{url}?limit=2&offset=4", "previous": f"{url}?limit=2", "results": results, } requests_mock.get(url, json=payload) bank = Bank(address=address) response = bank.fetch_confirmation_blocks(offset=2, limit=2) assert response == payload def test_success_fetch_validator_confirmation_services(requests_mock): confirmation_services = [ { "id": "5634f7d5-fa93-40c4-8e53-472055f1aa1c", "created_date": "2020-09-24T22:15:09.375150Z", "modified_date": "2020-09-24T22:15:09.375197Z", "end": "2021-01-27T22:15:09.343282Z", "start": "2020-09-24T22:15:09.343282Z", "validator": "e2a138b0-ebe9-47d2-a146-fb4d9d9ca378", }, { "id": "817a91bc-9dca-44d2-92ea-55547660e60e", "created_date": "2020-09-24T22:15:30.057923Z", "modified_date": "2020-09-24T22:15:30.057980Z", "end": "2020-11-30T14:15:29.982900Z", "start": "2020-09-24T22:15:29.982900Z", "validator": "97a878ac-328a-47b6-ac93-be6deee75d94", }, ] result = { "count": 2, "next": None, "previous": None, "results": confirmation_services, } requests_mock.get( "http://10.2.3.4:80/validator_confirmation_services", json=result, ) bank = Bank(address="10.2.3.4") response = bank.fetch_validator_confirmation_services() assert response == result def test_success_fetch_validator_confirmation_services_on_page_2(requests_mock): results = [ { "id": "5634f7d5-fa93-40c4-8e53-472055f1aa1c", "created_date": "2020-09-24T22:15:09.375150Z", "modified_date": "2020-09-24T22:15:09.375197Z", "end": "2021-01-27T22:15:09.343282Z", "start": "2020-09-24T22:15:09.343282Z", "validator": "e2a138b0-ebe9-47d2-a146-fb4d9d9ca378", }, { "id": "817a91bc-9dca-44d2-92ea-55547660e60e", "created_date": "2020-09-24T22:15:30.057923Z", "modified_date": "2020-09-24T22:15:30.057980Z", "end": "2020-11-30T14:15:29.982900Z", "start": "2020-09-24T22:15:29.982900Z", "validator": "97a878ac-328a-47b6-ac93-be6deee75d94", }, ] address = "10.2.3.4" url = f"http://{address}:80/validator_confirmation_services" payload = { "count": 6, "next": f"{url}?limit=2&offset=4", "previous": f"{url}?limit=2", "results": results, } requests_mock.get(url, json=payload) bank = Bank(address=address) response = bank.fetch_validator_confirmation_services(offset=2, limit=2) assert response == payload def test_success_create_validator_confirmation_service(requests_mock): result = { "id": "2558fd55-e132-4667-8d39-d3b5e8eb9c4d", "created_date": "2020-07-10T02:38:44.917554Z", "modified_date": "2020-07-10T02:38:44.917601Z", "end": "2020-07-09T22:10:25Z", "start": "2020-08-09T22:10:25Z", "validator": "fcd2dce8-9e4f-4bf1-8dac-cdbaf64e5ce8", } requests_mock.post( "http://10.2.3.4:80/validator_confirmation_services", json=result, ) bank = Bank(address="10.2.3.4") response = bank.create_validator_confirmation_service( msg_start="2020-07-09T22:10:25Z", msg_end="2020-07-09T22:10:25Z", node_id="d5356888dc9303e44ce52b1e06c3165a7759b9df1e6a6dfbd33ee1c3df1a", signature="f41788fe19690a67abe3336d4ca84565c090691efae0e5cdd8bf02e126", ) assert response == result def test_success_fetch_validators(requests_mock): validators = [ { "account_number": "2e86f48216567302527b69eae6c6a188097ed3a9741f43cc3723e570cf47644c", "ip_address": "192.168.3.11", "node_identifier": "2262026a562b0274163158e92e8fbc4d28e519bc5ba8c1cf403703292be84a51", "port": None, "protocol": "http", "version": "v1.0", "default_transaction_fee": 1, "root_account_file": "https://gist.githubusercontent.com/" "buckyroberts/0688f136b6c1332be472a8baf10f78c5/raw/323fcd29672e392be2b934b82ab9eac8d15e840f/alpha-00.json", "root_account_file_hash": "0f775023bee79884fbd9a90a76c5eacfee38a8ca52735f7ab59dab63a75cbee1", "seed_block_identifier": "", "daily_confirmation_rate": None, "trust": "100.00", }, { "account_number": "4699a423c455a40feb1d6b90b167584a880659e1bf9adf9954a727d534ff0c16", "ip_address": "192.168.3.11", "node_identifier": "b1b232503b3db3975524faf98674f22c83f4357c3d946431b8a8568715d7e1d9", "port": None, "protocol": "http", "version": "v1.0", "default_transaction_fee": 1, "root_account_file": "http://5172.16.17.32/media/root_account_file.json", "root_account_file_hash": "cc9390cc579dc8a99a1f34c1bea5d54a0f45b27ecee7e38662f0cd853f76744d", "seed_block_identifier": "", "daily_confirmation_rate": 1, "trust": "98.00", }, ] result = {"count": 2, "next": None, "previous": None, "results": validators} requests_mock.get( "http://10.2.3.4:80/validators", json=result, ) bank = Bank(address="10.2.3.4") response = bank.fetch_validators() assert response == result def test_success_fetch_validators_on_page_2(requests_mock): results = [ { "account_number": "2e86f48216567302527b69eae6c6a188097ed3a9741f43cc3723e570cf47644c", "ip_address": "192.168.3.11", "node_identifier": "2262026a562b0274163158e92e8fbc4d28e519bc5ba8c1cf403703292be84a51", "port": None, "protocol": "http", "version": "v1.0", "default_transaction_fee": 1, "root_account_file": "https://gist.githubusercontent.com/" "buckyroberts/0688f136b6c1332be472a8baf10f78c5/raw/323fcd29672e392be2b934b82ab9eac8d15e840f/alpha-00.json", "root_account_file_hash": "0f775023bee79884fbd9a90a76c5eacfee38a8ca52735f7ab59dab63a75cbee1", "seed_block_identifier": "", "daily_confirmation_rate": None, "trust": "100.00", }, { "account_number": "4699a423c455a40feb1d6b90b167584a880659e1bf9adf9954a727d534ff0c16", "ip_address": "192.168.3.11", "node_identifier": "b1b232503b3db3975524faf98674f22c83f4357c3d946431b8a8568715d7e1d9", "port": None, "protocol": "http", "version": "v1.0", "default_transaction_fee": 1, "root_account_file": "http://54.219.178.46/media/root_account_file.json", "root_account_file_hash": "cc9390cc579dc8a99a1f34c1bea5d54a0f45b27ecee7e38662f0cd853f76744d", "seed_block_identifier": "", "daily_confirmation_rate": 1, "trust": "98.00", }, ] address = "10.2.3.4" url = f"http://{address}:80/validators" payload = { "count": 6, "next": f"{url}?limit=2&offset=4", "previous": f"{url}?limit=2", "results": results, } requests_mock.get(url, json=payload) bank = Bank(address=address) response = bank.fetch_validators(offset=2, limit=2) assert response == payload def test_success_fetch_banks(requests_mock): banks = [ { "account_number": "dfddf07ec15cbf363ecb52eedd7133b70b3ec896b488460bcecaba63e8e36be5", "ip_address": "192.168.3.11", "node_identifier": "6dbaff44058e630cb375955c82b0d3bd7bc7e20cad93e74909a8951f747fb8a4", "port": None, "protocol": "http", "version": "v1.0", "default_transaction_fee": 1, "trust": "100.00", }, { "account_number": "<KEY>", "ip_address": "172.16.58.3", "node_identifier": "735bfc11f802dbb8365998703539823d751ac5f5f82905143fba8a84d967f29b", "port": None, "protocol": "http", "version": "v1.0", "default_transaction_fee": 2, "trust": "0.00", }, ] result = {"count": 2, "next": None, "previous": None, "results": banks} requests_mock.get( "http://10.2.3.4:80/banks", json=result, ) bank = Bank(address="10.2.3.4") response = bank.fetch_banks() assert response == result def test_success_fetch_banks_with_page_2(requests_mock): results = [ { "account_number": "dfddf07ec15cbf363ecb52eedd7133b70b3ec896b488460bcecaba63e8e36be5", "ip_address": "192.168.3.11", "node_identifier": "6dbaff44058e630cb375955c82b0d3bd7bc7e20cad93e74909a8951f747fb8a4", "port": None, "protocol": "http", "version": "v1.0", "default_transaction_fee": 1, "trust": "100.00", }, { "account_number": "<KEY>", "ip_address": "172.16.58.3", "node_identifier": "735bfc11f802dbb8365998703539823d751ac5f5f82905143fba8a84d967f29b", "port": None, "protocol": "http", "version": "v1.0", "default_transaction_fee": 2, "trust": "0.00", }, ] address = "10.2.3.4" url = f"http://{address}:80/banks" payload = { "count": 6, "next": f"{url}?limit=2&offset=4", "previous": f"{url}?limit=2", "results": results, } requests_mock.get(url, json=payload) bank = Bank(address=address) response = bank.fetch_banks(offset=2, limit=2) assert response == payload def test_success_fetch_config(requests_mock): result = { "primary_validator": { "account_number": "1a105575c681c5c4bbd9e88a90346f356051646dcee254afd5fdc67782cc6e56", "ip_address": "192.168.3.11", "node_identifier": "4a02e9e03ca6f2e64fe8dc675da73e31b8112e435439189012944f0b7adebf50", "port": None, "protocol": "http", "version": "v1.0", "default_transaction_fee": 1, "root_account_file": "http://20.188.33.93/media/root_account_file.json", "root_account_file_hash": "b2885f94cd099a8c5ba5355ff9cdd69252b4cad2541e32d20152702397722cf5", "seed_block_identifier": "", "daily_confirmation_rate": 100, "trust": "100.00", }, "account_number": "5878f25f576eb9d398ab1b6dd8b2e831ad74a58e6d6b8c8bea1c48f69a9db42d", "ip_address": "172.16.31.10", "node_identifier": "d1f994720d89c9d3b300367fdb85a452fd1fbb7d60c2e2707ff059e8df48e081", "port": None, "protocol": "http", "version": "v1.0", "default_transaction_fee": 1, "node_type": "BANK", } requests_mock.get( "http://10.2.3.4:80/config", json=result, ) bank = Bank(address="10.2.3.4") response = bank.fetch_config() assert response == result def test_success_patch_trust_level(requests_mock): result = { "account_number": "5e12967707909e62b2bb2036c209085a784fabbc3deccefee70052b6181c8ed8", "ip_address": "192.168.1.232", "node_identifier": "d5356888dc9303e44ce52b1e06c3165a7759b9df1e6a6dfbd33ee1c3df1ab4d1", "port": "80", "protocol": "http", "version": "v1.0", "default_transaction_fee": "1.0000000000000000", "trust": "76.26", } requests_mock.patch( "http://10.2.3.4:80/banks/d5356888dc9303e44ce52b1e06c3165a7759b9df1e6a6dfbd33ee1c3df1ab4d1", json=result, ) bank = Bank(address="10.2.3.4") response = bank.patch_trust_level( trust=99.98, signature="d11c5f7fcc5f541a94ceee7c73972b21c73912e41f06cc22989863fa22529" "f55d0b81bc9f95a203191be0259518bdfe073de77d87a7230d37bb14f21666ee40a", node_identifier="d5356888dc9303e44ce52b1e06c3165a7759b9df1e6a6dfbd33ee1c3df1ab4d1", ) assert response == result def test_success_patch_account(requests_mock): result = { "id": "64426fc5-b3ac-42fb-b75b-d5ccfcdc6872", "created_date": "2020-07-14T02:59:22.204580Z", "modified_date": "2020-07-21T00:58:01.013685Z", "account_number": "0cdd4ba04456ca169baca3d66eace869520c62fe84421329", "trust": "99.98", } requests_mock.patch( "http://10.2.3.4:80/accounts/0cdd4ba04456ca169baca3d66eace869520c62", json=result, ) bank = Bank(address="10.2.3.4") response = bank.patch_account( account_number="0cdd4ba04456ca169baca3d66eace869520c62", node_id="d5356888dc9303e44ce52b1e06c3165a7759b9df1e6a6dfbd33ee1c3df1a", trust=99.98, signature="f41788fe19690a67abe3336d4ca84565c090691efae0e5cdd8bf02e126", ) assert response == result def test_success_patch_validator(requests_mock): result = { "account_number": "<KEY>314", "ip_address": "192.168.1.75", "node_identifier": "3afdf37573f1a511def0bd85553404b7091a76bcd79cdcebba1310527b167521", "port": None, "protocol": "http", "version": "v1.0", "default_transaction_fee": "4.0000000000000000", "root_account_file": "https://gist.githubusercontent.com/buckyroberts/519b5cb82a0a5b5d4ae8a2175b722520" "/raw/9237deb449e27cab93cb89ea3346ecdfc61fe9ea/0.json", "root_account_file_hash": "4694e1ee1dcfd8ee5f989e59ae40a9f751812bf5ca52aca2766b322c4060672b", "seed_block_identifier": "", "daily_confirmation_rate": None, "trust": "76.28", } requests_mock.patch( "http://10.2.3.4:80/validators/d5356888dc9303e44ce52b1e06c3165a7759b9df1e6a6dfbd33ee1c3df1ab4d1", json=result, ) bank = Bank(address="10.2.3.4") response = bank.patch_validator( node_id="d5356888dc9303e44ce52b1e06c3165a7759b9df1e6a6dfbd33ee1c3df1ab4d1", trust=76.28, signature="b9106148b9c6d445f6a5fe7bb54b552ac2ff639cb72e2af70f75659" "04120dbb2040987c6cad559d7aa3b507c8d475af9291e4faee4930b" "324996c7a3c0696805", ) assert response == result def test_success_send_confirmation_block(requests_mock): result = [] requests_mock.post( "http://10.2.3.4:80/confirmation_blocks", json=result, ) bank = Bank(address="10.2.3.4") response = bank.send_confirmation_block( message={"block": None}, node_id="d5356888dc9303e44ce52b1e06c3165a7759b9df1e6a6dfbd33ee1c3df1", signature="f41788fe19690a67abe3336d4ca84565c090691efae0e5cdd8bf02e12", ) assert response == result def test_success_connection_requests(requests_mock): result = [] requests_mock.post( "http://10.2.3.4:80/connection_requests", json=result, ) bank = Bank(address="10.2.3.4") response = bank.connection_requests( node_id="d5356888dc9303e44ce52b1e06c3165a7759b9df1e6a6dfbd33ee1c3df1", signature="f41788fe19690a67abe3336d4ca84565c090691efae0e5cdd8bf02e12", ) assert response == result def test_success_fetch_blocks(requests_mock): result = [ { "id": "2bcd53c5-19f9-4226-ab04-3dfb17c3a1fe", "created_date": "2020-07-11T18:44:16.518695Z", "modified_date": "2020-07-11T18:44:16.518719Z", "block_identifier": "65ae26192dfb9ec41f88c6d582b374a9b42ab58833e1612452d7a8f685dcd4d5", "block": "3ff4ebb0-2b3d-429b-ba90-08133fcdee4e", "confirmation_validator": "fcd2dce8-9e4f-4bf1-8dac-cdbaf64e5ce8", "primary_validator": "51461a75-dd8d-4133-81f4-543a3b054149", } ] requests_mock.get("http://10.2.3.4:80/blocks", json=result) bank = Bank(address="10.2.3.4") response = bank.fetch_blocks() assert response == result def test_success_fetch_blocks_on_page_2(requests_mock): results = [ { "id": "2bcd53c5-19f9-4226-ab04-3dfb17c3a1fe", "created_date": "2020-07-11T18:44:16.518695Z", "modified_date": "2020-07-11T18:44:16.518719Z", "block_identifier": "65ae26192dfb9ec41f88c6d582b374a9b42ab58833e1612452d7a8f685dcd4d5", "block": "3ff4ebb0-2b3d-429b-ba90-08133fcdee4e", "confirmation_validator": "fcd2dce8-9e4f-4bf1-8dac-cdbaf64e5ce8", "primary_validator": "51461a75-dd8d-4133-81f4-543a3b054149", } ] address = "10.2.3.4" url = f"http://{address}:80/blocks" payload = { "count": 3, "next": None, "previous": f"{url}?limit=2", "results": results, } requests_mock.get(url, json=payload) bank = Bank(address=address) response = bank.fetch_blocks() assert response == payload def test_success_post_block(requests_mock): result = { "id": "3ff4ebb0-2b3d-429b-ba90-08133fcdee4e", "created_date": "2020-07-09T21:45:25.909512Z", "modified_date": "2020-07-09T21:45:25.909557Z", "balance_key": "ce51f0d9facaa7d3e69657429dd3f961ce70077a8efb53dcda508c7c0a19d2e3", "sender": "0cdd4ba04456ca169baca3d66eace869520c62fe84421329086e03d91a68acdb", "signature": "ee5a2f2a2f5261c1b633e08dd61182fd0db5604c853ebd8498f6f28ce8e2ccbbc38093918610ea88a7ad47c7f3192ed95" "5d9d1529e7e390013e43f25a5915c0f", } requests_mock.post("http://10.2.3.4:80/blocks", json=result) bank = Bank(address="10.2.3.4") response = bank.post_block( account_number="0cdd4ba04456ca169baca3d66eace869520c62fe84421329086e03d91a68acdb", balance_key="ce51f0d9facaa7d3e69657429dd3f961ce70077a8efb53dcda508c7c0a19d2e3", transactions=[ { "amount": 12.5, "recipient": "<KEY>", }, { "amount": 1, "recipient": "5e12967707909e62b2bb2036c209085a784fabbc3deccefee70052b6181c8ed8", }, { "amount": 4, "recipient": "ad1f8845c6a1abb6011a2a434a079a087c460657aad54329a84b406dce8bf314", }, ], signature="ee5a2f2a2f5261c1b633e08dd61182fd0db5604c853ebd8498f6f28ce8e2ccbbc38093918610ea88a7ad47c7f3192ed955d9" "d1529e7e390013e43f25a5915c0f", ) assert response == result def test_success_post_invalid_block(requests_mock): result = { "id": "2bcd53c5-19f9-4226-ab04-3dfb17c3a1fe", "created_date": "2020-07-11T18:44:16.518695Z", "modified_date": "2020-07-11T18:44:16.518719Z", "block_identifier": "65ae26192dfb9ec41f88c6d582b374a9b42ab58833e1612452d7a8f685dcd4d5", "block": "3ff4ebb0-2b3d-429b-ba90-08133fcdee4e", "confirmation_validator": "fcd2dce8-9e4f-4bf1-8dac-cdbaf64e5ce8", "primary_validator": "51461a75-dd8d-4133-81f4-543a3b054149", } requests_mock.post( "http://10.2.3.4:80/invalid_blocks", json=result, ) bank = Bank(address="10.2.3.4") response = bank.post_invalid_block( block={ "account_number": "0cdd4ba04456ca169baca3d66eace869520c62fe84421329086e03d91a68acdb", "message": { "balance_key": "ce51f0d9facaa7d3e69657429dd3f961ce70077a8efb53dcda508c7c0a19d2e3", "txs": [ { "amount": 12, "recipient": "<KEY>", }, { "amount": 1, "recipient": "5e12967707909e62b2bb2036c209085a784fabbc3deccefee70052b6181c8ed8", }, { "amount": 4, "recipient": "<KEY>", }, ], }, "signature": "ee5a2f2a2f5261c1b633e08dd61182fd0db5604c853ebd8498f6f28ce8e2ccbbc" "38093918610ea88a7ad47c7f3192ed955d9d1529e7e390013e43f25a5915c0f", }, block_identifier="65ae26192dfb9ec41f88c6d582b374a9b42ab58833e1612452d7a8f685dcd4d5", primary_validator_node_identifier="3afdf37573f1a511def0bd85553404b7091a76bcd79cdcebba1310527b167521", node_identifier="59479a31c3b91d96bb7a0b3e07f18d4bf301f1bb0bde05f8d36d9611dcbe7cbf", signature="c61ef8067307f8a48979a656699709e415692eb7b7b0083e3cd41da4ff6cb388e7347896b5cacb0a74200390d" "228b30547f73a72029ebd4ed10482db5e925b0c", ) assert response == result def test_success_post_upgrade_notice(requests_mock): result = [200, {}] requests_mock.post( "http://10.2.3.4:80/upgrade_notice", json=result, status_code=200, ) bank = Bank(address="10.2.3.4") bank_nid = "banknodeidentifier1234" node_id = "validatoridentifier1234" signature = "signature" response = bank.post_upgrade_notice(bank_nid, node_id, signature) assert response == result <file_sep>/tnb/validators.py from tnb.base_client import BaseClient class Validator(BaseClient): def fetch_accounts(self, offset: int = 0, limit: int = 50) -> dict: """ Fetch accounts from validator :param offset: The offset to start at. Default: 0 :param limit: The limit of results to retrieve. Default: 50 Return response as a Python object """ params = {"offset": offset, "limit": limit} return self.fetch("/accounts", params=params) def fetch_account_balance(self, account_number: str) -> dict: """ Fetch account balance from account :param account_number: The account number of the account Return response as a Python object """ return self.fetch(f"/accounts/{account_number}/balance") def fetch_account_balance_lock(self, account_number: str) -> dict: """ Fetch balance lock for account with number account_number :param account_number: The account number of the account Return response as a Python object """ return self.fetch(f"/accounts/{account_number}/balance_lock") def fetch_confirmation_block(self, block_identifier: str) -> dict: """ Fetch confirmation block by block_identifier :param block_identifier: ID for the block Return response as Python object """ return self.fetch(f"/confirmation_blocks/{block_identifier}/valid") <file_sep>/tests/validators.py from tnb.validators import Validator def test_success_fetch_accounts(requests_mock): accounts = [ { "id": "<KEY>", "account_number": "9bfa37627e2dba0ae48165b219e76ceaba036b3db8e84108af73a1cce01fad35", "balance": 6, "balance_lock": "749f6faa4eeeda50f51334e903a1eaae084435d53d2a85fb0993a518fef27273", }, { "id": "9c6dd61a-438c-4a95-b1d2-33f90bd7f6ad", "account_number": "2e86f48216567302527b69eae6c6a188097ed3a9741f43cc3723e570cf47644c", "balance": 380, "balance_lock": "aca94f4d2f472c6b9b662f60aab247b9c6aef2079d63b870e2cc02308a7c822b", }, ] result = { "count": 2, "next": None, "previous": None, "results": accounts, } requests_mock.get("http://42.0.6.9:80/accounts", json=result) validator = Validator(address="192.168.3.11") response = validator.fetch_accounts() assert response == result def test_success_fetch_accounts_on_page_2(requests_mock): results = [ { "id": "4cb1cdbe-ebbf-43c8-9<KEY>", "account_number": "9bfa37627e2dba0ae48165b219e76ceaba036b3db8e84108af73a1cce01fad35", "balance": 6, "balance_lock": "749f6faa4eeeda50f51334e903a1eaae084435d53d2a85fb0993a518fef27273", }, { "id": "9c6dd61a-438c-4a95-b1d2-33f90bd7f6ad", "account_number": "2e86f48216567302527b69eae6c6a188097ed3a9741f43cc3723e570cf47644c", "balance": 380, "balance_lock": "aca94f4d2f472c6b9b662f60aab247b9c6aef2079d63b870e2cc02308a7c822b", }, ] address = "42.0.6.9" url = f"http://{address}:80/accounts" payload = { "count": 6, "next": f"{url}?limit=2&offset=4", "previous": f"{url}?limit=2", "results": results, } requests_mock.get(f"{url}?limit=2&offset=2", json=payload) validator = Validator(address=address) response = validator.fetch_accounts(offset=2, limit=2) assert response == payload def test_success_fetch_account_balance(requests_mock): result = {"balance": 50546} requests_mock.get( "http://42.0.6.9:80/accounts/<KEY>/balance", json=result, ) validator = Validator(address="42.0.6.9") response = validator.fetch_account_balance( "a3<KEY>" ) assert response == result def test_success_fetch_account_balance_lock(requests_mock): result = { "balance_lock": "e9a91c4aed7593fd08bae4daac411e3a6bd1e01dc56cd2f5f060f8c790414f35" } requests_mock.get( "http://42.0.6.9:80/accounts/<KEY>/balance_lock", json=result, ) validator = Validator(address="42.0.6.9") response = validator.fetch_account_balance_lock( "a37e283680597<KEY>bd<KEY>" ) assert response == result def test_success_fetch_confirmation_blocks(requests_mock): result = { "message": { "block": { "account_number": "0cdd4ba04456ca169baca3d66eace869520c62fe84421329086e03d91a68acdb", "message": { "balance_key": "<KEY>", "txs": [ { "amount": 60, "recipient": "<KEY>", }, { "amount": 1, "recipient": "5e12967707909e62b2bb2036c209085a784fabbc3deccefee70052b6181c8ed8", }, { "amount": 4, "recipient": "<KEY>", }, ], }, "signature": "d857184b7d3121a8f9dccab09062fafc82dd0fb30a5d53e19ab25a587171bb9c6b33858353cd3ff7ddc1ad2bf\ c59a885e85827799bcfc082fd048f9bf34bd404", } } } requests_mock.get( "http://42.0.6.9:80/confirmation_blocks/4c9595b2b661a23e665256d6826ae940bd4ea82bef0c1ba7b3104e40a4c42b91/valid", json=result, ) validator = Validator(address="192.168.3.11") response = validator.fetch_confirmation_block( "4c9595b2b661a23e665256d6826ae940bd4ea82bef0c1ba7b3104e40a4c42b91" ) assert response == result
a6eab625ffc7e6201d511c4484b9c5d086ccb5b2
[ "Python" ]
3
Python
nishp77/thenewboston-python-client
da234b4fee354a9d7ccf993a2205f5baf54a969e
bfb78f2e65c0216b1a7ed54bad7c10c28ce300d0
refs/heads/master
<file_sep>FROM python:3 WORKDIR /app/ ADD ./requirements.txt /app/ RUN pip install -r requirements.txt<file_sep>from flask import Flask def create_app(): app = Flask(__name__) @app.route('/') def index_page(): return 'index page' return app <file_sep>version: '3.3' services: data-db: image: machbase/machbase volumes: - machdata:/home/machbase/machbase/dbs stdin_open: true tty: true expose: - "5001" - "5656" web-db: image: postgres:11 environment: - POSTGRES_DB=uyeg - POSTGRES_USER=its - POSTGRES_PASSWORD=<PASSWORD> - POSTGRES_INITDB_ARGS=--encoding=UTF-8 ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data web: build: context: . dockerfile: ./app/Dockerfile environment: - FLASK_APP=app - FLASK_ENV=development ports: - "5000:5000" links: - data-db - web-db depends_on: - data-db - web-db working_dir: / command: flask run -h 0.0.0.0 volumes: - ./app/:/app/ volumes: pgdata: {} machdata: {}
3f594177a5b325072c6f1897791a781ee4a3c28f
[ "Python", "Dockerfile", "YAML" ]
3
Dockerfile
clianor/Simple_Flask_docker_compose
febb8f0e3c4fdec5d05129acaf867e17630b7670
fafc88e877efc95ce307451d8f8b4ff044145698
refs/heads/master
<repo_name>FluffyFoxUwU/ext2-boot<file_sep>/stage2/elf.c /* elf.c =============================================================================== MIT License Copyright (c) 2007-2016 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================== */ #include "defs.h" #include "ext2.h" #include "elf.h" #include "crunch.h" void elf_objdump(void* data) { elf32_ehdr *ehdr = (elf32_ehdr*) data; /* Make sure the file ain't fucked */ assert(ehdr->e_ident[0] == ELF_MAGIC); assert(ehdr->e_machine == EM_386); assert(ehdr->e_type == ET_EXEC); printx("ELF ident ",ehdr->e_ident[0]); printx("Entry ",ehdr->e_entry); /* Parse the program headers */ elf32_phdr* phdr = (uint32_t) data + ehdr->e_phoff; elf32_phdr* last_phdr = (uint32_t) phdr + (ehdr->e_phentsize * ehdr->e_phnum); vga_pretty("Offset \tVirt Addr\tPhys Addr\tFile Sz\tMem sz \tAlign \n", VGA_LIGHTMAGENTA); while(phdr < last_phdr) { vga_puts(" "); vga_puts(itoa(phdr->p_offset, 16)); vga_puts("\t"); vga_puts(itoa(phdr->p_vaddr, 16)); vga_putc('\t'); vga_puts(itoa(phdr->p_paddr, 16)); vga_putc('\t'); vga_puts(itoa(phdr->p_filesz, 10)); vga_putc('\t'); vga_puts(itoa(phdr->p_memsz, 16)); vga_putc('\t'); // vga_puts(itoa(phdr->p_align, 16)); vga_putc('\n'); // printf("LOAD:\toff 0x%x\tvaddr\t0x%x\tpaddr\t0x%x\n\t\tfilesz\t%d\tmemsz\t%d\talign\t%d\t\n", // phdr->p_offset, phdr->p_vaddr, phdr->p_paddr, phdr->p_filesz, phdr->p_memsz, phdr->p_align); phdr++; } /* Parse the section headers */ elf32_shdr* shdr = (uint32_t) data + ehdr->e_shoff; elf32_shdr* sh_str = (uint32_t) shdr + (ehdr->e_shentsize * ehdr->e_shstrndx); elf32_shdr* last_shdr = (uint32_t) shdr + (ehdr->e_shentsize * ehdr->e_shnum); char* string_table = (uint32_t) data + sh_str->sh_offset; shdr++; // Skip null entry int q = 0; vga_pretty("Sections:\nIdx Name\tSize\t\tAddress \tOffset\tAlign\n", VGA_LIGHTMAGENTA); while (shdr < last_shdr) { vga_puts(itoa(++q, 10)); vga_puts(" "); vga_puts(string_table + shdr->sh_name); if (strlen(string_table + shdr->sh_name) < 6) vga_puts("\t"); vga_putc('\t'); vga_puts(itoa(shdr->sh_size, 16)); vga_putc('\t'); vga_puts(itoa(shdr->sh_addr, 16)); vga_putc('\t'); vga_puts(itoa(shdr->sh_offset, 10)); vga_putc('\t'); vga_puts(itoa(shdr->sh_addralign, 16)); vga_putc('\n'); shdr++; } } void elf_load(mmap* one, gfx_context* two) { inode* ki = ext2_inode(1,12); uint32_t* data = ext2_read_file(ki); //uint32_t* data = ext2_file_seek(ext2_inode(1,12), 1024, 0); elf32_ehdr * ehdr = (elf32_ehdr*) data; assert(ehdr->e_ident[0] == ELF_MAGIC); elf_objdump(data); printx("data at: ", data); printx("heap at: ", malloc(0)); free(data); elf32_phdr* phdr = (uint32_t) data + ehdr->e_phoff; elf32_phdr* last_phdr = (uint32_t) phdr + (ehdr->e_phentsize * ehdr->e_phnum); uint32_t off = (phdr->p_vaddr - phdr->p_paddr); while(phdr < last_phdr) { printx("header: ", phdr->p_paddr); memcpy(phdr->p_paddr, (uint32_t)data + phdr->p_offset, phdr->p_filesz); phdr++; } void (*entry)(mmap*, gfx_context*); entry = (void(*)(void))(ehdr->e_entry - off); // CLEAR OUT THE ENTIRE HEAP uint32_t END_OF_HEAP = malloc(0); memset(HEAP_START, 0, (END_OF_HEAP - HEAP_START)); printx("entry: ", entry); asm volatile("cli"); entry(one, two); } <file_sep>/stage2/lib.c /* string.c =============================================================================== MIT License Copyright (c) 2007-2016 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================== Implementation of string library for baremetal project */ #include "defs.h" #include <stdint.h> // Returns length of a null-terminated string size_t strlen( char* s ) { char* p = s; uint32_t i = 0; while (*p++ != 0 ) i++; return i; } // Appends a copy of the source string to the destination string char* strncat( char* destination, const char* source, size_t n ) { size_t length = strlen(destination); int i; for (i = 0; i < n && source[i] != '\0'; i++) destination[length+i] = source[i]; destination[length+i] = '\0'; return destination; } // wrapper for strncat char* strcat(char *destination, const char* source) { return strncat(destination, source, strlen(source)); } // Copy first n characters of src to destination char* strncpy(char *dest, const char *src, uint16_t n) { uint16_t i; for (i = 0; i < n && src[i] != '\0'; i++) dest[i] = src[i]; for ( ; i < n; i++) dest[i] = '\0'; return dest; } // Copy all of str to dest char* strcpy(char *dest, const char *src) { return strncpy(dest, src, strlen(src)); } int strncmp(char* s1, char* s2, size_t n) { for (size_t i = 0; i < n && *s1 == *s2; s1++, s2++, i++) if (*s1 == '\0') return 0; return ( *(unsigned char*)s1 - *(unsigned char*)s2 ); } int strcmp(char *s1, char* s2) { return strncmp(s1, s2, strlen(s1)); } char* strchr(const char* s, int c) { while (*s != '\0') if (*s++ == c) return (char*) s; return NULL; } char* strdup(const char* s) { return strcpy((char*) malloc(strlen(s)), s); } /* In place string reverse */ char* strrev(char* s) { int length = strlen(s) - 1; for (int i = 0; i <= length/2; i++) { char temp = s[i]; s[i] = s[length-i]; s[length-i] = temp; } return s; } void* memcpy(void *s1, const void *s2, uint32_t n) { uint8_t* src = (uint8_t*) s2; uint8_t* dest = (uint8_t*) s1; for (int i = 0; i < n; i++) dest[i] = src[i]; return s1; } void* memset(void *s, int c, size_t n) { uint8_t* dest = (uint8_t*) s; for (size_t i = 0; i < n; i++) dest[i] = c; return s; } void* memsetw(void *s, int c, size_t n) { uint16_t* dest = (uint16_t*) s; for (size_t i = 0; i < n; i++) *dest++ = c; } void* memmove(void *s1, const void* s2, size_t n) { char* dest = (char*) s1; char* src = (char*) s2; char* temp = (char*) malloc(n); for (int i = 0; i < n; i++) temp[i] = src[i]; for (int i = 0; i < n; i++) dest[i] = temp[i]; free(temp); return s1; } void* memchr(const void* s, int c, size_t n) { uint8_t* b = s; while (n--) if (*b++ == c) return b; return NULL; } void* memrchr(const void* s, int c, size_t n) { return strrev(memchr(strrev(s), c, n)); } int memcmp(const uint8_t* s1, const uint8_t* s2, size_t n) { while (*s1 == *s2 && n--) { s1++; s2++; } return ( *(uint8_t*)s1 - *(uint8_t*)s2 ); } char* strtok(char* s, const char* delim) { char* b = NULL; static char* ptr, d = NULL; if (s) ptr = s; if (!ptr && !s) return NULL; for (int i = 0; i < strlen(delim); i++) { b = ptr; ptr = strchr(ptr, delim[i]); if (!ptr) return b; *--ptr = '\0'; ptr++; return b; } return NULL; } inline uint8_t inb(uint16_t port) { // "=a" (result) means: put AL register in variable result when finished // "d" (_port) means: load EDX with _port unsigned char result; asm volatile("inb %1, %0" : "=a" (result) : "dN" (port)); return result; } inline void outb(uint16_t port, uint16_t data) { asm volatile ("outb %1, %0" : : "dN" (port), "a" (data)); } inline void insl(int port, void *addr, int cnt) { asm volatile("cld; rep insl" : "=D" (addr), "=c" (cnt) : "d" (port), "0" (addr), "1" (cnt) : "memory", "cc"); } char* itoa(uint32_t num, int base) { int i = 0; //num = abs(num); int len = 8; char* buffer = malloc(32); if (base == 2) len = 32; if (num == 0 && base == 2) { while(i < len) buffer[i++] = '0'; buffer[i] = '\0'; return buffer; } /* if (num == 0 && base == 0) { buffer[0] = '0'; buffer[1] = '\0'; return buffer; }*/ // go in reverse order while (num != 0 && len--) { int remainder = num % base; // case for hexadecimal buffer[i++] = (remainder > 9)? (remainder - 10) + 'A' : remainder + '0'; num = num / base; } while(len-- && base != 10) buffer[i++] = '0'; buffer[i] = '\0'; return strrev(buffer); } <file_sep>/Makefile COBJS = stage2/main.o \ stage2/ext2.o \ stage2/lib.o \ stage2/vga.o \ stage2/elf.o CC = /home/lazear/opt/cross/bin/i686-elf-gcc LD = /home/lazear/opt/cross/bin/i686-elf-ld AS = nasm CCFLAGS = -w -fno-pic -fno-builtin -nostdlib -ffreestanding -std=gnu99 -m32 -c EXT2UTIL= ../ext2util/ext2util DISK = boot.img all: compile clean run: kernel compile clean emu nok: compile clean emu %.o : %.c $(CC) $(CCFLAGS) $< -o $@ stage2: $(COBJS) kernel: make -C ../crunchy compile: stage2 $(AS) -f bin bootstrap.asm -o stage1.bin $(LD) -N -e stage2_main -Ttext 0x00050000 -o stage2.bin $(COBJS) --oformat binary cp boot.img.bak boot.img dd if=stage1.bin of=$(DISK) conv=notrunc #cp ../crunchy/bin/kernel.bin ./kernel $(EXT2UTIL) -x $(DISK) -wf stage2.bin -i 5 $(EXT2UTIL) -x $(DISK) -wf kernel $(EXT2UTIL) -x $(DISK) -wf boot.conf new: dd if=/dev/zero of=boot.img bs=1k count=16k sudo mke2fs boot.img emu: qemu-system-i386 -hdb boot.img -curses clean: rm stage2/*.o <file_sep>/stage2/main.c #include "defs.h" #include "crunch.h" uint32_t HEAP = 0x00200000; uint32_t HEAP_START; static void putpixel(unsigned char* screen, int x,int y, int color); void parse_config(char* config); void stage2_main(uint32_t* mem_info, vid_info* v) { //clear the screen HEAP_START = HEAP; vga_clear(); vga_pretty("Stage2 loaded...\n", VGA_LIGHTGREEN); lsroot(); mmap* m = (mmap*) *mem_info; mmap* max = (mmap*) *++mem_info; printx("Video Mode:", v->mode); vga_puts("framebuffer@ 0x"); vga_puts(itoa(v->info->framebuffer, 16)); vga_putc('\n'); /* Don't use the heap, because it's going to be wiped */ gfx_context *c = (gfx_context*) 0x000F0000; c->pitch = v->info->pitch; c->width = v->info->width; c->height = v->info->height; c->bpp = v->info->bpp; c->framebuffer = v->info->framebuffer; memcpy(0x000F1000, m, (uint32_t) max - (uint32_t) m); vga_pretty("Memory map:\n", VGA_LIGHTGREEN); while (m < max) { vga_puts(itoa(m->base, 16)); vga_putc('-'); vga_puts(itoa(m->len + m->base, 16)); vga_putc('\t'); //vga_puts(itoa(m->type, 10)); switch((char)m->type) { case 1: { vga_puts("Usable Ram\t"); break; } case 2: { vga_puts("Reserved\t"); break; } default: vga_putc('\n'); } vga_puts(itoa(m->len/0x400, 10)); vga_puts(" KB\n"); m++; } int boot_conf_inode = ext2_find_child("boot.conf", 2); char* config = ext2_read_file(ext2_inode(1, boot_conf_inode)); parse_config(config); /* We should never reach this point */ for(;;); } void parse_config(char* config) { vga_puts(config); } static void putpixel(unsigned char* screen, int x,int y, int color) { unsigned where = x*3 + y*768*4; screen[where] = color & 255; // BLUE screen[where + 1] = (color >> 8) & 255; // GREEN screen[where + 2] = (color >> 16) & 255; // RED } <file_sep>/README.md # ext2-boot ### x86 bootloader for ext2 filesystems and elf32 kernels ext2-boot aims to be a configurable bootloader utilizing the reserved bootloader block from the ext2 specification to load and run 32 bit ELF executables. Stage2 is essentially a minimal kernel, with only print-to-screen, ext2 file reading, and ELF execution capabilities. ext2-boot currently supports BIOS memory mapping, and passes along the information. Goals of this project are to provide easy-to-read, minimal yet functional code that can be used on native ext2 partitions, and be easier to set up than GRUB for people running Windows. ![alt tag](https://raw.githubusercontent.com/lazear/ext2-boot/master/bootloader.png) #### To-Do: * Add in configuration file * Finish video mode selection code * Add support for multiboot #### Requirements: * [ext2util](https://github.com/lazear/ext2util), or some other way to write the second stage loader to inode #5 * elf32 executable #### Build Simply run ```sh $ make ``` And all necessary files will be compiled and moved onto the ext2 image. If you need a fresh ext2 disk image: ```sh $ dd if=/dev/zero of=disk.img bs=1k count=16k $ mke2fs disk.img ``` ext2util can be used to write files (such as a kernel) to the ext2 image. <file_sep>/stage2/defs.h #ifndef __defs__ #define __defs__ #include <stdint.h> #define NULL ((void*) 0) #define malloc(n) ((void*)((HEAP += n) - n)) #define free(x) #define size_t uint32_t #define assert(e) ((e) ? (void) 0 : vga_pretty(#e, VGA_RED)) extern void lsroot(); extern char* itoa(uint32_t num, int base); extern void putx(char* msg, uint32_t i); extern size_t strlen( char* s ); extern char* strncat( char* destination, const char* source, size_t n ); extern char* strcat(char *destination, const char* source); extern char* strncpy(char *dest, const char *src, uint16_t n); extern char* strcpy(char *dest, const char *src) ; extern int strncmp(char* s1, char* s2, size_t n); extern int strcmp(char *s1, char* s2); extern char* strchr(const char* s, int c); extern char* strdup(const char* s) ; extern char* strrev(char* s); extern void* memcpy(void *s1, const void *s2, uint32_t n); extern void* memset(void *s, int c, size_t n) ; extern void* memsetw(void *s, int c, size_t n); extern void* memmove(void *s1, const void* s2, size_t n); extern void* memchr(const void* s, int c, size_t n); extern void* memrchr(const void* s, int c, size_t n) ; extern int memcmp(const uint8_t* s1, const uint8_t* s2, size_t n); extern char* strtok(char* s, const char* delim); extern inline uint8_t inb(uint16_t port); extern inline void outb(uint16_t port, uint16_t data); extern inline void insl(int port, void *addr, int cnt); extern uint32_t HEAP; extern uint32_t HEAP_START; #define VGA_BLACK 0x00 #define VGA_BLUE 0x01 #define VGA_GREEN 0x02 #define VGA_CYAN 0x03 #define VGA_RED 0x04 #define VGA_MAGENTA 0x05 #define VGA_BROWN 0x06 #define VGA_LIGHTGREY 0x07 #define VGA_DARKGREY 0x08 #define VGA_LIGHTBLUE 0x09 #define VGA_LIGHTGREEN 0x0A #define VGA_LIGHTCYAN 0x0B #define VGA_LIGHTRED 0x0C #define VGA_LIGHTMAGENTA 0x0D #define VGA_LIGHTBROWN 0x0E #define VGA_WHITE 0x0F #define VGA_COLOR(f, b) ((b << 4) | (f & 0xF)) #define RGB(r,g,b) (((r&0xFF)<<16) | ((g&0xFF)<<8) | (b & 0xFF)) #define isascii(c) (c >= 0 && c <= 127) #define isdigit(c) (c >= '0' && c <= '9') #define islower(c) (c >= 'a' && c <= 'z') #define isupper(c) (c >= 'A' && c <= 'Z') #define tolower(c) (isdigit(c) ? c : (islower(c) ? c : ((c - 'A') + 'a'))) #define toupper(c) (isdigit(c) ? c : (isupper(c) ? c : ((c - 'a') + 'A'))) typedef struct vbe { uint16_t attributes; // deprecated, only bit 7 should be of interest to you, and it indicates the mode supports a linear frame buffer. uint8_t window_a; // deprecated uint8_t window_b; // deprecated uint16_t granularity; // deprecated; used while calculating bank numbers uint16_t window_size; uint16_t segment_a; uint16_t segment_b; uint32_t win_func_ptr; // deprecated; used to switch banks from protected mode without returning to real mode uint16_t pitch; // number of bytes per horizontal line uint16_t width; // width in pixels uint16_t height; // height in pixels uint8_t w_char; // unused... uint8_t y_char; // ... uint8_t planes; uint8_t bpp; // bits per pixel in this mode uint8_t banks; // deprecated; total number of banks in this mode uint8_t memory_model; uint8_t bank_size; // deprecated; size of a bank, almost always 64 KB but may be 16 KB... uint8_t image_pages; uint8_t reserved0; uint8_t red_mask; uint8_t red_position; uint8_t green_mask; uint8_t green_position; uint8_t blue_mask; uint8_t blue_position; uint8_t reserved_mask; uint8_t reserved_position; uint8_t direct_color_attributes; uint32_t framebuffer; // physical address of the linear frame buffer; write here to draw to the screen uint32_t off_screen_mem_off; uint16_t off_screen_mem_size; // size of memory in the framebuffer but not being displayed on the screen } vbe; typedef struct _vid_info { uint32_t mode; vbe* info; } vid_info; #endif<file_sep>/stage2/ext2.h /* ext2.h ================================================================================ MIT License Copyright (c) 2007-2016 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================================================ */ /* Block groups are found at the address (group number - 1) * blocks_per_group. Each block group has a backup superblock as it's first block */ #include <stdint.h> #ifndef __baremetal_ext2__ #define __baremetal_ext2__ #define BLOCK_SIZE 1024 #define SECTOR_SIZE 512 #define EXT2_BOOT 0 // Block 0 is bootblock #define EXT2_SUPER 1 // Block 1 is superblock #define EXT2_MAGIC 0x0000EF53 typedef struct superblock_s { uint32_t inodes_count; // Total # of inodes uint32_t blocks_count; // Total # of blocks uint32_t r_blocks_count; // # of reserved blocks for superuser uint32_t free_blocks_count; uint32_t free_inodes_count; uint32_t first_data_block; uint32_t log_block_size; // 1024 << Log2 block size = block size uint32_t log_frag_size; uint32_t blocks_per_group; uint32_t frags_per_group; uint32_t inodes_per_group; uint32_t mtime; // Last mount time, in POSIX time uint32_t wtime; // Last write time, in POSIX time uint16_t mnt_count; // # of mounts since last check uint16_t max_mnt_count; // # of mounts before fsck must be done uint16_t magic; // 0xEF53 uint16_t state; uint16_t errors; uint16_t minor_rev_level; uint32_t lastcheck; uint32_t checkinterval; uint32_t creator_os; uint32_t rev_level; uint16_t def_resuid; uint16_t def_resgid; } __attribute__((packed)) superblock; /* Inode bitmap size = (inodes_per_group / 8) / BLOCK_SIZE block_group = (block_number - 1)/ (blocks_per_group) + 1 */ typedef struct block_group_descriptor_s { uint32_t block_bitmap; uint32_t inode_bitmap; uint32_t inode_table; uint16_t free_blocks_count; uint16_t free_inodes_count; uint16_t used_dirs_count; uint16_t pad[7]; } block_group_descriptor; /* maximum value of inode.block[index] is inode.blocks / (2 << log_block_size) Locating an inode: block group = (inode - 1) / s_inodes_per_group inside block: local inode index = (inode - 1) % s_inodes_per_group containing block = (index * INODE_SIZE) / BLOCK_SIZE */ typedef struct inode_s { uint16_t mode; // Format of the file, and access rights uint16_t uid; // User id associated with file uint32_t size; // Size of file in bytes uint32_t atime; // Last access time, POSIX uint32_t ctime; // Creation time uint32_t mtime; // Last modified time uint32_t dtime; // Deletion time uint16_t gid; // POSIX group access uint16_t links_count; // How many links uint32_t blocks; // # of 512-bytes blocks reserved to contain the data uint32_t flags; // EXT2 behavior uint32_t osdl; // OS dependent value uint32_t block[15]; // Block pointers. Last 3 are indirect uint32_t generation; // File version uint32_t file_acl; // Block # containing extended attributes uint32_t dir_acl; uint32_t faddr; // Location of file fragment uint32_t osd2[3]; } inode; #define INODE_SIZE (sizeof(inode)) /* Directories must be 4byte aligned, and cannot extend between multiple blocks on the disk */ typedef struct dirent_s { uint32_t inode; // Inode uint16_t rec_len; // Total size of entry, including all fields uint8_t name_len; // Name length, least significant 8 bits uint8_t file_type; // Type indicator uint8_t name[]; } __attribute__((packed)) dirent; /* IMPORTANT: Inode addresses start at 1 */ typedef struct ide_buffer { uint32_t block; // block number uint8_t data[BLOCK_SIZE]; // 1 disk sector of data } buffer; #define B_BUSY 0x1 // buffer is locked by a process #define B_VALID 0x2 // buffer has been read from disk #define B_DIRTY 0x4 // buffer has been written to /* Define IDE status bits */ #define IDE_BSY (1<<7) // Drive is preparing to send/receive data #define IDE_RDY (1<<6) // Clear when drive is spun down, or after error #define IDE_DF (1<<5) // Drive Fault error #define IDE_ERR (1<<0) // Error has occured #define IDE_IO 0x1F0 // Main IO port #define IDE_DATA 0x0 // R/W PIO data bytes #define IDE_FEAT 0x1 // ATAPI devices #define IDE_SECN 0x2 // # of sectors to R/W #define IDE_LOW 0x3 // CHS/LBA28/LBA48 specific #define IDE_MID 0x4 #define IDE_HIGH 0x5 #define IDE_HEAD 0x6 // Select drive/heaad #define IDE_CMD 0x7 // Command/status port #define IDE_ALT 0x3F6 // alternate status #define LBA_LOW(c) ((uint8_t) (c & 0xFF)) #define LBA_MID(c) ((uint8_t) (c >> 8) & 0xFF) #define LBA_HIGH(c) ((uint8_t) (c >> 16) & 0xFF) #define LBA_LAST(c) ((uint8_t) (c >> 24) & 0xF) #define IDE_CMD_READ (BLOCK_SIZE/SECTOR_SIZE == 1) ? 0x20 : 0xC4 #define IDE_CMD_WRITE (BLOCK_SIZE/SECTOR_SIZE == 1) ? 0x30 : 0xC5 #define IDE_CMD_READ_MUL 0xC4 #define IDE_CMD_WRITE_MUL 0xC5 extern block_group_descriptor* ext2_blockdesc(); extern superblock* ext2_superblock(); extern void* ext2_read_file(inode* in); extern void vga_puts(char* s); #endif<file_sep>/stage2/ext2.c /* ext2_bootloader.c =============================================================================== MIT License Copyright (c) 2007-2016 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================== This is intended to be used as a Stage2 bootloader. As such, only Read functionality. This loader will be located at inode 5 so that Stage1 bootloader can easily find it. */ #include "ext2.h" #include "defs.h" // void stage2_main() { // //clear the screen // vga_clear(); // vga_puts("Stage2 loaded...\n"); // lsroot(); // for(;;); // } /* Wait for IDE device to become ready check = 0, do not check for errors check != 0, return -1 if error bit set */ int ide_wait(int check) { char r; // Wait while drive is busy. Once just ready is set, exit the loop while (((r = (char)inb(IDE_IO | IDE_CMD)) & (IDE_BSY | IDE_RDY)) != IDE_RDY); // Check for errors if (check && (r & (IDE_DF | IDE_ERR)) != 0) return 0xF; return 0; } static void* ide_read(void* b, uint32_t block) { int sector_per_block = BLOCK_SIZE / SECTOR_SIZE; // 2 int sector = block * sector_per_block; ide_wait(0); outb(IDE_IO | IDE_SECN, sector_per_block); // # of sectors outb(IDE_IO | IDE_LOW, LBA_LOW(sector)); outb(IDE_IO | IDE_MID, LBA_MID(sector)); outb(IDE_IO | IDE_HIGH, LBA_HIGH(sector)); // Slave/Master << 4 and last 4 bits outb(IDE_IO | IDE_HEAD, 0xE0 | (1 << 4) | LBA_LAST(sector)); outb(IDE_IO | IDE_CMD, IDE_CMD_READ); ide_wait(0); // Read only insl(IDE_IO, b, BLOCK_SIZE/4); return b; } /* Buffer_read and write are used as glue functions for code compatibility with hard disk ext2 driver, which has buffer caching functions. Those will not be included here. */ void* buffer_read(int block) { return ide_read(malloc(BLOCK_SIZE), block); } /* Read superblock from device dev, and check the magic flag. Return NULL if not a valid EXT2 partition */ superblock* ext2_superblock() { superblock* sb = buffer_read(EXT2_SUPER); if (sb->magic != EXT2_MAGIC) return NULL; return sb; } block_group_descriptor* ext2_blockdesc() { return buffer_read(EXT2_SUPER + 1); } inode* ext2_inode(int dev, int i) { superblock* s = ext2_superblock(); block_group_descriptor* bgd = ext2_blockdesc(); int block_group = (i - 1) / s->inodes_per_group; // block group # int index = (i - 1) % s->inodes_per_group; // index into block group int block = (index * INODE_SIZE) / BLOCK_SIZE; bgd += block_group; // Not using the inode table was the issue... uint32_t* data = buffer_read(bgd->inode_table+block); inode* in = (inode*)((uint32_t) data + (index % (BLOCK_SIZE/INODE_SIZE))*INODE_SIZE); return in; } uint32_t ext2_read_indirect(uint32_t indirect, size_t block_num) { char* data = buffer_read(indirect); return *(uint32_t*) ((uint32_t) data + block_num*4); } void* ext2_read_file(inode* in) { assert(in); if(!in) return NULL; int num_blocks = in->blocks / (BLOCK_SIZE/SECTOR_SIZE); assert(num_blocks != 0); if (!num_blocks) return NULL; size_t sz = BLOCK_SIZE*num_blocks; void* buf = malloc(sz); assert(buf != NULL); int indirect = 0; /* Singly-indirect block pointer */ if (num_blocks > 12) { indirect = in->block[12]; } int blocknum = 0; char* data; for (int i = 0; i < num_blocks; i++) { if (i < 12) { blocknum = in->block[i]; char* data = buffer_read(blocknum); memcpy((uint32_t) buf + (i * BLOCK_SIZE), data, BLOCK_SIZE); } if (i > 12) { blocknum = ext2_read_indirect(indirect, i-13); char* data = buffer_read(blocknum); memcpy((uint32_t) buf + ((i-1) * BLOCK_SIZE), data, BLOCK_SIZE); } } return buf; } void* ext2_file_seek(inode* in, size_t n, size_t offset) { int nblocks = ((n-1 + BLOCK_SIZE & ~(BLOCK_SIZE-1)) / BLOCK_SIZE); int off_block = (offset / BLOCK_SIZE); // which block int off = offset % BLOCK_SIZE; // offset in block void* buf = malloc(nblocks*BLOCK_SIZE); // round up to whole block size assert(nblocks <= in->blocks/2); assert(off_block <= in->blocks/2); for (int i = 0; i < nblocks; i++) { buffer* b = buffer_read(in->block[off_block+i]); memcpy(buf + (i*BLOCK_SIZE), b->data + off, BLOCK_SIZE); //printf("Read @ block %d (%d)\n",in->block[off_block+i], off_block); off = 0; // Eliminate offset after first block } return buf; } /* Finds an inode by name in dir_inode */ int ext2_find_child(const char* name, int dir_inode) { if (!dir_inode) return -1; inode* i = ext2_inode(1, dir_inode); // Root directory char* buf = malloc(BLOCK_SIZE*i->blocks/2); memset(buf, 0, BLOCK_SIZE*i->blocks/2); for (int q = 0; q < i->blocks / 2; q++) { char* data = buffer_read(i->block[q]); memcpy((uint32_t)buf+(q * BLOCK_SIZE), data, BLOCK_SIZE); } dirent* d = (dirent*) buf; int sum = 0; int calc = 0; do { // Calculate the 4byte aligned size of each entry calc = (sizeof(dirent) + d->name_len + 4) & ~0x3; sum += d->rec_len; //printf("%2d %10s\t%2d %3d\n", (int)d->inode, d->name, d->name_len, d->rec_len); if (strncmp(d->name, name, d->name_len)== 0) { free(buf); return d->inode; } d = (dirent*)((uint32_t) d + d->rec_len); } while(sum < (1024 * i->blocks/2)); free(buf); return -1; } void lsroot() { // vga_puts("lsroot"); inode* i = ext2_inode(1, 2); // Root directory char* buf = malloc(BLOCK_SIZE*i->blocks/2); // printx("Inode@: ", i); for (int q = 0; q < i->blocks / 2; q++) { // printx("Block: ", i->block[q]); char* data = buffer_read(i->block[q]); memcpy((uint32_t)buf+(q * BLOCK_SIZE), data, BLOCK_SIZE); } dirent* d = (dirent*) buf; int sum = 0; int calc = 0; vga_puts("Root directory:\n"); do { // Calculate the 4byte aligned size of each entry calc = (sizeof(dirent) + d->name_len + 4) & ~0x3; sum += d->rec_len; vga_puts("/"); vga_puts(d->name); vga_putc('\n'); if (d->rec_len != calc && sum == 1024) { /* if the calculated value doesn't match the given value, then we've reached the final entry on the block */ //sum -= d->rec_len; d->rec_len = calc; // Resize this entry to it's real size // d = (dirent*)((uint32_t) d + d->rec_len); } d = (dirent*)((uint32_t) d + d->rec_len); } while(sum < 1024); return NULL; }
bdffc4402f6a4843f29f7f0ee060ddcbd58b2623
[ "Markdown", "C", "Makefile" ]
8
C
FluffyFoxUwU/ext2-boot
d6698890ac9b832c8ad2f5d4548f327c7747396d
c0b085fb02bcc5a4adf6f38437e8cbda4db34634
refs/heads/master
<file_sep>list1=[12,-7,5,64,-14] for i in list1: if i>0: print(i, end=" ") //OUTPUT => 12 5 64
1651befe53813e1b58b0901c783a231a6746bb13
[ "Python" ]
1
Python
indraprasath/python_basics
5149cd83af03c2d2b4dbee9d1cc7301a32d0f315
292a4de8d36d97b98534c359a984632db31788a4
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using EnergyApp.Data; namespace EnergyApp.Data { /// <summary> /// /// </summary> public class ApplicationDbContext : IdentityDbContext { /// <summary> /// /// </summary> /// <param name="options"></param> public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } /// <summary> /// /// </summary> /// <value></value> public DbSet<Configuration> Configuration { get; set; } /// <summary> /// /// </summary> /// <value></value> public DbSet<Meter> Meters { get; set; } /// <summary> /// /// </summary> /// <value></value> public DbSet<Charger> Chargers { get; set; } /// <summary> /// /// </summary> /// <value></value> public DbSet<Outlet> Outlets { get; set; } /// <summary> /// /// </summary> /// <value></value> public DbSet<Partner> Partners { get; set; } /// <summary> /// /// </summary> /// <value></value> public DbSet<CMPAssignment> CMPAssignments { get; set; } /// <summary> /// /// </summary> /// <param name="builder"></param> public DbSet<ChargeSession> ChargeSession { get; set; } /// <summary> /// /// </summary> /// <param name="builder"></param> protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<CMPAssignment>() .HasKey(k => new {k.ChargerID, k.PartnerID,k.MeterID}); builder.Entity<Configuration>(entity => { entity.Property(e => e.Key) .IsRequired() .HasMaxLength(50); }); base.OnModelCreating(builder); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using EnergyApp.Data; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using powerconcern.mqtt.services; using Microsoft.Extensions.Hosting; using Microsoft.AspNetCore.Mvc.Authorization; namespace EnergyApp { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); //string test=Configuration.GetValue<string>("BrokerURL"); services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity<IdentityUser>() .AddRoles<IdentityRole>() .AddDefaultUI(UIFramework.Bootstrap4) .AddEntityFrameworkStores<ApplicationDbContext>(); services.AddSingleton<IHostedService, MQTTService>(); services.AddAuthorization(options => { options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin")); options.AddPolicy("RequireInstallerRole", policy => policy.RequireRole("Installer")); options.AddPolicy("RequireCustomerRole", policy => policy.RequireRole("Customer")); }); services.AddMvc(config => { // using Microsoft.AspNetCore.Mvc.Authorization; // using Microsoft.AspNetCore.Authorization; var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }) .AddRazorPagesOptions(options => { options.Conventions.AuthorizePage("/Configuration", "RequireAdminRole"); options.Conventions.AuthorizePage("/Configuration/Index", "RequireAdminRole"); options.Conventions.AuthorizePage("/Customer", "RequireCustomerRole"); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, IServiceProvider serviceProvider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseMvc(); CreateRoles(serviceProvider).Wait(); } private async Task CreateRoles(IServiceProvider serviceProvider) { //initializing custom roles var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>(); var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>(); string[] roleNames = { "Admin", "Installer", "Customer" }; IdentityResult roleResult; IdentityUser user; foreach (var roleName in roleNames) { var roleExist = await RoleManager.RoleExistsAsync(roleName); if (!roleExist) { //create the roles and seed them to the database: Question 1 roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName)); } } List<string> AdmUsers=new List<string>{"<EMAIL>","<EMAIL>","<EMAIL>"}; foreach (var admUser in AdmUsers) { user = await UserManager.FindByEmailAsync(admUser); if (user == null) { user = new IdentityUser() { UserName = "test<EMAIL>", Email = "<EMAIL>", }; await UserManager.CreateAsync(user, "Test@123"); } await UserManager.AddToRoleAsync(user, "Admin"); } /* user = await UserManager.FindByEmailAsync("<EMAIL>"); var token = await UserManager.GeneratePasswordResetTokenAsync(user); var result = await UserManager.ResetPasswordAsync(user, token, ""); Console.WriteLine(result); */ } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using EnergyApp.Data; namespace EnergyApp.Data { public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Customer> Customers { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<CMCAssign>() .HasKey(k => new {k.ChargerID, k.CustomerID,k.MeterID}); base.OnModelCreating(builder); } public DbSet<EnergyApp.Data.Meter> Meter { get; set; } public DbSet<EnergyApp.Data.Charger> Charger { get; set; } public DbSet<EnergyApp.Data.CMCAssign> CMCAssign { get; set; } } } <file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace EnergyApp.Data { public class Configuration { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ID { get; set; } public string Key { get; set; } public string Value { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Hosting; using System.Security.Claims; using powerconcern.mqtt.services; using EnergyApp.Data; namespace EnergyApp.Pages { // [AllowAnonymous] public class IndexModel : PageModel { private IHostedService _mqttsvc; private EnergyApp.Data.ApplicationDbContext _context; public IndexModel(IHostedService mqttsvc, EnergyApp.Data.ApplicationDbContext context) { _mqttsvc=mqttsvc; _context=context; } [BindProperty] public Charger Charger { get; set; } [BindProperty] public Partner Partner { get; set; } [BindProperty] public string userId {get;set;} [BindProperty] public float fMeanCurrent {get;set;} [BindProperty] public List<MeterCache> meterCacheList {get;set;} public async void OnGet() { //Init cache meterCacheList=new List<MeterCache>(); //Get user id userId = User.FindFirst(ClaimTypes.NameIdentifier).Value; var customer=await _context.Partners .Include(cmp => cmp.CMPAssignments) .ThenInclude(m => m.Meter) .Include(cmp => cmp.CMPAssignments) .ThenInclude(c => c.Charger) .AsNoTracking() .FirstOrDefaultAsync(p => p.UserReference == userId && p.Type == PartnerType.Kund); Partner=customer; foreach (var meter in customer.CMPAssignments) { //find metercache based on name MeterCache mc=(MeterCache)((MQTTService)_mqttsvc).GetBaseCache(meter.Meter.Name); meterCacheList.Add(mc); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using EnergyApp.Data; namespace EnergyApp.Pages_Partners { public class DeleteModel : PageModel { private readonly EnergyApp.Data.ApplicationDbContext _context; public DeleteModel(EnergyApp.Data.ApplicationDbContext context) { _context = context; } [BindProperty] public Partner Partner { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } Partner = await _context.Partners.FirstOrDefaultAsync(m => m.ID == id); if (Partner == null) { return NotFound(); } return Page(); } public async Task<IActionResult> OnPostAsync(int? id) { if (id == null) { return NotFound(); } Partner = await _context.Partners.FindAsync(id); if (Partner != null) { _context.Partners.Remove(Partner); await _context.SaveChangesAsync(); } return RedirectToPage("./Index"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using EnergyApp.Data; namespace EnergyApp.Pages_CMPAssignments { public class CreateModel : PageModel { private readonly EnergyApp.Data.ApplicationDbContext _context; public CreateModel(EnergyApp.Data.ApplicationDbContext context) { _context = context; } public IActionResult OnGet() { ViewData["ChargerID"] = new SelectList(_context.Chargers, "ID", "ID"); ViewData["MeterID"] = new SelectList(_context.Meters, "ID", "ID"); ViewData["PartnerID"] = new SelectList(_context.Partners, "ID", "ID"); return Page(); } [BindProperty] public CMPAssignment CMPAssignment { get; set; } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } _context.CMPAssignments.Add(CMPAssignment); await _context.SaveChangesAsync(); return RedirectToPage("./Index"); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using EnergyApp.Data; namespace RelationTest.Pages_CMCAssigns { public class IndexModel : PageModel { private readonly EnergyApp.Data.ApplicationDbContext _context; public IndexModel(EnergyApp.Data.ApplicationDbContext context) { _context = context; } public IList<CMCAssign> CMCAssign { get;set; } public async Task OnGetAsync() { CMCAssign = await _context.CMCAssign .Include(c => c.Charger) .Include(c => c.Customer) .Include(c => c.Meter).ToListAsync(); } } } <file_sep>PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" ( "MigrationId" TEXT NOT NULL CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY, "ProductVersion" TEXT NOT NULL ); INSERT INTO __EFMigrationsHistory VALUES('00000000000000_CreateIdentitySchema','2.2.4-servicing-10062'); INSERT INTO __EFMigrationsHistory VALUES('20190721213752_InitialCreate','2.2.4-servicing-10062'); INSERT INTO __EFMigrationsHistory VALUES('20190722151026_Meters','2.2.4-servicing-10062'); CREATE TABLE IF NOT EXISTS "AspNetRoles" ( "Id" TEXT NOT NULL CONSTRAINT "PK_AspNetRoles" PRIMARY KEY, "Name" TEXT NULL, "NormalizedName" TEXT NULL, "ConcurrencyStamp" TEXT NULL ); CREATE TABLE IF NOT EXISTS "AspNetUsers" ( "Id" TEXT NOT NULL CONSTRAINT "PK_AspNetUsers" PRIMARY KEY, "UserName" TEXT NULL, "NormalizedUserName" TEXT NULL, "Email" TEXT NULL, "NormalizedEmail" TEXT NULL, "EmailConfirmed" INTEGER NOT NULL, "PasswordHash" TEXT NULL, "SecurityStamp" TEXT NULL, "ConcurrencyStamp" TEXT NULL, "PhoneNumber" TEXT NULL, "PhoneNumberConfirmed" INTEGER NOT NULL, "TwoFactorEnabled" INTEGER NOT NULL, "LockoutEnd" TEXT NULL, "LockoutEnabled" INTEGER NOT NULL, "AccessFailedCount" INTEGER NOT NULL ); INSERT INTO AspNetUsers VALUES('7688c7a6-1a6d-4ad7-8fb5-e551d0c3ce48','<EMAIL>','<EMAIL>','<EMAIL>','<EMAIL>',0,'AQAAAAEAACcQAAAAEBMH6Fa6giqte/1T+kCeEjtbP3u55HBDhXOC5I7Tv/J7DGxf58oV9siQoU9E3+MILg==','WM7L57427S2G75NMIYZ6BMXRE3PAKZCG','4c64c53c-ff76-457b-864c-41227e23e700',NULL,0,0,NULL,1,0); CREATE TABLE IF NOT EXISTS "AspNetRoleClaims" ( "Id" INTEGER NOT NULL CONSTRAINT "PK_AspNetRoleClaims" PRIMARY KEY AUTOINCREMENT, "RoleId" TEXT NOT NULL, "ClaimType" TEXT NULL, "ClaimValue" TEXT NULL, CONSTRAINT "FK_AspNetRoleClaims_AspNetRoles_RoleId" FOREIGN KEY ("RoleId") REFERENCES "AspNetRoles" ("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetUserClaims" ( "Id" INTEGER NOT NULL CONSTRAINT "PK_AspNetUserClaims" PRIMARY KEY AUTOINCREMENT, "UserId" TEXT NOT NULL, "ClaimType" TEXT NULL, "ClaimValue" TEXT NULL, CONSTRAINT "FK_AspNetUserClaims_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetUserLogins" ( "LoginProvider" TEXT NOT NULL, "ProviderKey" TEXT NOT NULL, "ProviderDisplayName" TEXT NULL, "UserId" TEXT NOT NULL, CONSTRAINT "PK_AspNetUserLogins" PRIMARY KEY ("LoginProvider", "ProviderKey"), CONSTRAINT "FK_AspNetUserLogins_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetUserRoles" ( "UserId" TEXT NOT NULL, "RoleId" TEXT NOT NULL, CONSTRAINT "PK_AspNetUserRoles" PRIMARY KEY ("UserId", "RoleId"), CONSTRAINT "FK_AspNetUserRoles_AspNetRoles_RoleId" FOREIGN KEY ("RoleId") REFERENCES "AspNetRoles" ("Id") ON DELETE CASCADE, CONSTRAINT "FK_AspNetUserRoles_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetUserTokens" ( "UserId" TEXT NOT NULL, "LoginProvider" TEXT NOT NULL, "Name" TEXT NOT NULL, "Value" TEXT NULL, CONSTRAINT "PK_AspNetUserTokens" PRIMARY KEY ("UserId", "LoginProvider", "Name"), CONSTRAINT "FK_AspNetUserTokens_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "Configurations" ( "ConfigurationID" INTEGER NOT NULL CONSTRAINT "PK_Configurations" PRIMARY KEY, "Key" TEXT NOT NULL, "Value" INTEGER NOT NULL ); INSERT INTO Configurations VALUES(1,'BrokerURL','192.168.222.20'); CREATE TABLE IF NOT EXISTS "Meters" ( "ID" INTEGER NOT NULL CONSTRAINT "PK_Meters" PRIMARY KEY AUTOINCREMENT, "Name" TEXT NULL, "MaxCurrent" REAL NOT NULL, "Type" INTEGER NULL, "ChargerID" INTEGER NOT NULL ); INSERT INTO Meters VALUES(1,'FredriksMätare',16.0,0,1); DELETE FROM sqlite_sequence; INSERT INTO sqlite_sequence VALUES('Meters',1); CREATE INDEX "IX_AspNetRoleClaims_RoleId" ON "AspNetRoleClaims" ("RoleId"); CREATE UNIQUE INDEX "RoleNameIndex" ON "AspNetRoles" ("NormalizedName"); CREATE INDEX "IX_AspNetUserClaims_UserId" ON "AspNetUserClaims" ("UserId"); CREATE INDEX "IX_AspNetUserLogins_UserId" ON "AspNetUserLogins" ("UserId"); CREATE INDEX "IX_AspNetUserRoles_RoleId" ON "AspNetUserRoles" ("RoleId"); CREATE INDEX "EmailIndex" ON "AspNetUsers" ("NormalizedEmail"); CREATE UNIQUE INDEX "UserNameIndex" ON "AspNetUsers" ("NormalizedUserName"); COMMIT; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using EnergyApp.Data; namespace EnergyApp.Pages_CMPAssignments { public class EditModel : PageModel { private readonly EnergyApp.Data.ApplicationDbContext _context; public EditModel(EnergyApp.Data.ApplicationDbContext context) { _context = context; } [BindProperty] public CMPAssignment CMPAssignment { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } CMPAssignment = await _context.CMPAssignments .Include(c => c.Charger) .Include(c => c.Meter) .Include(c => c.Partner).FirstOrDefaultAsync(m => m.ChargerID == id); if (CMPAssignment == null) { return NotFound(); } ViewData["ChargerID"] = new SelectList(_context.Chargers, "ID", "ID"); ViewData["MeterID"] = new SelectList(_context.Meters, "ID", "ID"); ViewData["PartnerID"] = new SelectList(_context.Partners, "ID", "ID"); return Page(); } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } _context.Attach(CMPAssignment).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CMPAssignmentExists(CMPAssignment.ChargerID)) { return NotFound(); } else { throw; } } return RedirectToPage("./Index"); } private bool CMPAssignmentExists(int id) { return _context.CMPAssignments.Any(e => e.ChargerID == id); } } } <file_sep>using System; using System.Collections.Generic; namespace EnergyApp.Data { public class ChargeSession { public int ID { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } public int Kwh { get; set; } public int OutletID { get; set; } public int ChargerID { get; set; } public Charger Charger { get; set; } } }<file_sep>using System; using System.Collections.Generic; namespace EnergyApp.Data { public class Adjustment { public int ID { get; set; } public DateTime TimeStamp { get; set; } public int Current { get; set; } public int iPhase { get; set; } } }<file_sep>using System; using System.Text; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Globalization; using MQTTnet; using MQTTnet.Client; using MQTTnet.Client.Options; using MQTTnet.Protocol; namespace Energy { class Replay { static void Main(string[] args) { bool IsConnected=false; bool isDebug=false; int msPause=5000; //Find replay file string sFile="Replay0909.txt"; if(args.Length>0&&args[0] != null) { sFile=args[0]; Console.WriteLine($"Reading from {sFile}"); } string sQualifier="2019-"; if(args.Length>1&&args[1] != null) { sQualifier=args[1]; Console.WriteLine($"Qualifier {sQualifier}"); } if(args.Length>2&&args[2] != null) { if(args[2].Equals("0")) { isDebug=false; Console.WriteLine($"Pausing between sections until keypress"); } else { isDebug=true; msPause=int.Parse(args[2]); Console.WriteLine($"Debugging, pause {msPause} ms"); } } // string sBrokerURL="mqtt.symlink.se"; // string sBrokerUser="johsim:johsim"; // string sBrokerPasswd="<PASSWORD>"; string sBrokerURL="192.168.222.20"; // string sBrokerUser="johsim:johsim"; //string sBrokerPasswd="<PASSWORD>"; MqttFactory Factory=new MqttFactory(); IMqttClient MqttClnt=Factory.CreateMqttClient(); IMqttClientOptions options = new MqttClientOptionsBuilder() .WithClientId("EnergyAppTester") .WithTcpServer(sBrokerURL) //.WithCredentials(sBrokerUser, sBrokerPasswd) //.WithCleanSession() .Build(); //var result = MqttClnt.ConnectAsync(options); #region UseConnectedHandler MqttClnt.UseConnectedHandler(e => { Console.WriteLine("### CONNECTED TO SERVER ###"); IsConnected=true; // Subscribe to topics // foreach(string Name in bcLookup.Keys) { // await MqttClnt.SubscribeAsync(new TopicFilterBuilder().WithTopic($"{Name}/#").Build()); // } //await MqttClnt.SubscribeAsync(new TopicFilterBuilder().WithTopic("+/status/#").Build()); //await MqttClnt.SubscribeAsync(new TopicFilterBuilder().WithTopic("+/set/#").Build()); Console.WriteLine("### SUBSCRIBED to ###"); }); #endregion MqttClnt.UseDisconnectedHandler(async e => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); IsConnected=false; await Task.Delay(TimeSpan.FromSeconds(5)); try { await MqttClnt.ConnectAsync(options); IsConnected=true; } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } }); var result = MqttClnt.ConnectAsync(options); Console.WriteLine($"Replaying from {sFile}"); MessageHandler msgHandler=new MessageHandler(sQualifier); foreach (string line in File.ReadLines(sFile, Encoding.UTF8)) { if(msgHandler.HandleRow(line)) { if(msgHandler.NextSection()) { if(isDebug) { Thread.Sleep(msPause); } else { Console.WriteLine("Press key for next topic post"); Console.ReadLine(); } } string sNewTopic="Test"+msgHandler.Topic; //Check if connected while (!IsConnected) { Console.WriteLine("Waiting for connection"); //Task.Delay(TimeSpan.FromSeconds(5)); Thread.Sleep(5000); } MqttClnt.PublishAsync(sNewTopic, msgHandler.Value, MqttQualityOfServiceLevel.AtLeastOnce, false); Console.WriteLine($"Sent {msgHandler.Value} to {sNewTopic} (time {msgHandler.PostDTM})"); } } } } //Class to handle messages for MQTT topics in replayfile public class MessageHandler { private DateTime LastPostDTM {get;set;} public DateTime PostDTM {get;set;} private string[] sTopicParts; private string LastClient {get;set;} private string Client {get;set;} public string Topic {get;set;} /* Not needed as long as we only prefix Test public string NewTopic { get { StringBuilder stringBuilder=new StringBuilder(sPrefix); for (int i = 0; i < sTopicParts.Length; i++) { stringBuilder.Append(sTopicParts[i]); } return stringBuilder.ToString(); } set { } } */ public string Value {get;set;} private string Qualifier {get;set;} public MessageHandler(string qualf) { Qualifier=qualf; } public bool HandleRow(string line) { bool bHandled=false; if(line.Contains(Qualifier)) { //Set Topic and Value if(line.Contains("Test")) { Console.WriteLine($"Filtering out {line}"); bHandled=false; } else { string[] tmpLine=line.Trim().Split(" "); LastClient=Client; LastPostDTM=PostDTM; if(tmpLine[0].Contains('/')) { //US dateformat PostDTM=DateTime.Parse($"{tmpLine[0]} {tmpLine[1]} {tmpLine[2].Substring(0,2)}", CultureInfo.InvariantCulture); Topic=tmpLine[3]; } else { PostDTM=DateTime.Parse($"{tmpLine[0]} {tmpLine[1].Substring(0,8)}", CultureInfo.InvariantCulture); Topic=tmpLine[2]; } sTopicParts=Topic.Split("/"); Client=sTopicParts[0]; Value=tmpLine[tmpLine.Length-1]; if(LastClient is null) { LastClient=Client; LastPostDTM=PostDTM; } bHandled=true; } } return bHandled; } public bool NextSection() { bool bNextSection=false; if(LastClient is null) { bNextSection=true; } else { bNextSection=!Client.Equals(LastClient); } //Calculate time since last topic post if(bNextSection || SecondsSinceLastPost()>3) { return true; } else { return false; } } public double SecondsSinceLastPost() { return (PostDTM - LastPostDTM).TotalSeconds; } } } <file_sep>using System; using Microsoft.EntityFrameworkCore.Migrations; namespace EnergyApp.Data.Migrations { public partial class BaseModel : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Chargers", columns: table => new { ID = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Name = table.Column<string>(nullable: true), MaxCurrent = table.Column<float>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Chargers", x => x.ID); }); migrationBuilder.CreateTable( name: "Configuration", columns: table => new { ID = table.Column<int>(nullable: false), Key = table.Column<string>(maxLength: 50, nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Configuration", x => x.ID); }); migrationBuilder.CreateTable( name: "Meters", columns: table => new { ID = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Name = table.Column<string>(nullable: true), MaxCurrent = table.Column<float>(nullable: false), Type = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Meters", x => x.ID); }); migrationBuilder.CreateTable( name: "Partners", columns: table => new { ID = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Name = table.Column<string>(nullable: true), UserReference = table.Column<string>(nullable: true), Type = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Partners", x => x.ID); }); migrationBuilder.CreateTable( name: "ChargeSession", columns: table => new { ID = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Start = table.Column<DateTime>(nullable: false), End = table.Column<DateTime>(nullable: false), Kwh = table.Column<int>(nullable: false), OutletID = table.Column<int>(nullable: false), ChargerID = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ChargeSession", x => x.ID); table.ForeignKey( name: "FK_ChargeSession_Chargers_ChargerID", column: x => x.ChargerID, principalTable: "Chargers", principalColumn: "ID", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Outlets", columns: table => new { ID = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Name = table.Column<string>(nullable: true), ChargerID = table.Column<int>(nullable: false), MaxCurrent = table.Column<float>(nullable: false), Type = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Outlets", x => x.ID); table.ForeignKey( name: "FK_Outlets_Chargers_ChargerID", column: x => x.ChargerID, principalTable: "Chargers", principalColumn: "ID", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "CMPAssignments", columns: table => new { MeterID = table.Column<int>(nullable: false), ChargerID = table.Column<int>(nullable: false), PartnerID = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_CMPAssignments", x => new { x.ChargerID, x.PartnerID, x.MeterID }); table.ForeignKey( name: "FK_CMPAssignments_Chargers_ChargerID", column: x => x.ChargerID, principalTable: "Chargers", principalColumn: "ID", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_CMPAssignments_Meters_MeterID", column: x => x.MeterID, principalTable: "Meters", principalColumn: "ID", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_CMPAssignments_Partners_PartnerID", column: x => x.PartnerID, principalTable: "Partners", principalColumn: "ID", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Adjustment", columns: table => new { ID = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), TimeStamp = table.Column<DateTime>(nullable: false), Current = table.Column<int>(nullable: false), iPhase = table.Column<int>(nullable: false), CMPAssignmentChargerID = table.Column<int>(nullable: true), CMPAssignmentMeterID = table.Column<int>(nullable: true), CMPAssignmentPartnerID = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Adjustment", x => x.ID); table.ForeignKey( name: "FK_Adjustment_CMPAssignments_CMPAssignmentChargerID_CMPAssignmentPartnerID_CMPAssignmentMeterID", columns: x => new { x.CMPAssignmentChargerID, x.CMPAssignmentPartnerID, x.CMPAssignmentMeterID }, principalTable: "CMPAssignments", principalColumns: new[] { "ChargerID", "PartnerID", "MeterID" }, onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Adjustment_CMPAssignmentChargerID_CMPAssignmentPartnerID_CMPAssignmentMeterID", table: "Adjustment", columns: new[] { "CMPAssignmentChargerID", "CMPAssignmentPartnerID", "CMPAssignmentMeterID" }); migrationBuilder.CreateIndex( name: "IX_ChargeSession_ChargerID", table: "ChargeSession", column: "ChargerID"); migrationBuilder.CreateIndex( name: "IX_CMPAssignments_MeterID", table: "CMPAssignments", column: "MeterID"); migrationBuilder.CreateIndex( name: "IX_CMPAssignments_PartnerID", table: "CMPAssignments", column: "PartnerID"); migrationBuilder.CreateIndex( name: "IX_Outlets_ChargerID", table: "Outlets", column: "ChargerID"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Adjustment"); migrationBuilder.DropTable( name: "ChargeSession"); migrationBuilder.DropTable( name: "Configuration"); migrationBuilder.DropTable( name: "Outlets"); migrationBuilder.DropTable( name: "CMPAssignments"); migrationBuilder.DropTable( name: "Chargers"); migrationBuilder.DropTable( name: "Meters"); migrationBuilder.DropTable( name: "Partners"); } } } <file_sep>using System; namespace EnergyApp.Data { public class CMCAssign { public DateTime AddedDate { get; set; } public int MeterID { get; set; } public int ChargerID { get; set; } public int CustomerID { get; set; } public Meter Meter { get; set; } public Charger Charger { get; set; } public Customer Customer { get; set; } } }<file_sep>using System.Collections.Generic; namespace EnergyApp.Data { public class CMPAssignment { public int MeterID { get; set; } public int ChargerID { get; set; } public int PartnerID { get; set; } public Meter Meter { get; set; } public Charger Charger { get; set; } public Partner Partner { get; set; } public ICollection<Adjustment> Adjustments { get; set; } } }<file_sep>-- SQLite INSERT INTO `Customers` (ID, Name, CustomerNumber, MeterID, ChargerID, Type) VALUES (1, '<NAME>', 'TODO', 1, 1, 0 );<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using EnergyApp.Data; namespace RelationTest.Pages_CMCAssigns { public class EditModel : PageModel { private readonly EnergyApp.Data.ApplicationDbContext _context; public EditModel(EnergyApp.Data.ApplicationDbContext context) { _context = context; } [BindProperty] public CMCAssign CMCAssign { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } CMCAssign = await _context.CMCAssign .Include(c => c.Charger) .Include(c => c.Customer) .Include(c => c.Meter).FirstOrDefaultAsync(m => m.ChargerID == id); if (CMCAssign == null) { return NotFound(); } ViewData["ChargerID"] = new SelectList(_context.Charger, "ID", "ID"); ViewData["CustomerID"] = new SelectList(_context.Customers, "ID", "ID"); ViewData["MeterID"] = new SelectList(_context.Meter, "ID", "ID"); return Page(); } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } _context.Attach(CMCAssign).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CMCAssignExists(CMCAssign.ChargerID)) { return NotFound(); } else { throw; } } return RedirectToPage("./Index"); } private bool CMCAssignExists(int id) { return _context.CMCAssign.Any(e => e.ChargerID == id); } } } <file_sep>using System.Collections.Generic; namespace EnergyApp.Data { public class Charger { public int ID { get; set; } public string Name { get; set; } public float MaxCurrent { get; set; } public ICollection<Outlet> Outlets { get; set; } public ICollection<ChargeSession> ChargeSessions { get; set; } public ICollection<CMPAssignment> CMPAssignments { get; set; } } }<file_sep>using System.Collections.Generic; namespace EnergyApp.Data { public class Partner { public int ID { get; set; } public string Name { get; set; } public string UserReference { get; set; } public ICollection<CMPAssignment> CMPAssignments { get; set; } public PartnerType? Type { get; set; } } public enum PartnerType { None, Kund, Förening, Företag } }<file_sep>BEGIN TRANSACTION; CREATE TABLE IF NOT EXISTS "Customers" ( "ID" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "Name" TEXT, "CustomerNumber" TEXT, "MeterID" INTEGER NOT NULL, "ChargerID" INTEGER NOT NULL, "Type" INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS "Outlets" ( "ID" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "Name" TEXT, "MaxCurrent" REAL NOT NULL, "Type" INTEGER, "ChargerID" INTEGER, CONSTRAINT "FK_Outlets_Chargers_ChargerID" FOREIGN KEY("ChargerID") REFERENCES "Chargers"("ID") ON DELETE RESTRICT ); CREATE TABLE IF NOT EXISTS "Chargers" ( "ID" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "OutletID" INTEGER NOT NULL, "Name" TEXT, "MaxCurrent" REAL NOT NULL, "CustomerID" INTEGER ); CREATE TABLE IF NOT EXISTS "Meters" ( "ID" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "Name" TEXT, "MaxCurrent" REAL NOT NULL, "Type" INTEGER, "ChargerID" INTEGER NOT NULL, "CustomerID" INTEGER ); CREATE TABLE IF NOT EXISTS "Configurations" ( "ID" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "Key" TEXT NOT NULL, "Value" TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS "AspNetUserTokens" ( "UserId" TEXT NOT NULL, "LoginProvider" TEXT NOT NULL, "Name" TEXT NOT NULL, "Value" TEXT, CONSTRAINT "PK_AspNetUserTokens" PRIMARY KEY("UserId","LoginProvider","Name"), CONSTRAINT "FK_AspNetUserTokens_AspNetUsers_UserId" FOREIGN KEY("UserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetUserRoles" ( "UserId" TEXT NOT NULL, "RoleId" TEXT NOT NULL, CONSTRAINT "PK_AspNetUserRoles" PRIMARY KEY("UserId","RoleId"), CONSTRAINT "FK_AspNetUserRoles_AspNetRoles_RoleId" FOREIGN KEY("RoleId") REFERENCES "AspNetRoles"("Id") ON DELETE CASCADE, CONSTRAINT "FK_AspNetUserRoles_AspNetUsers_UserId" FOREIGN KEY("UserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetUserLogins" ( "LoginProvider" TEXT NOT NULL, "ProviderKey" TEXT NOT NULL, "ProviderDisplayName" TEXT, "UserId" TEXT NOT NULL, CONSTRAINT "PK_AspNetUserLogins" PRIMARY KEY("LoginProvider","ProviderKey"), CONSTRAINT "FK_AspNetUserLogins_AspNetUsers_UserId" FOREIGN KEY("UserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetUserClaims" ( "Id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "UserId" TEXT NOT NULL, "ClaimType" TEXT, "ClaimValue" TEXT, CONSTRAINT "FK_AspNetUserClaims_AspNetUsers_UserId" FOREIGN KEY("UserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetRoleClaims" ( "Id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "RoleId" TEXT NOT NULL, "ClaimType" TEXT, "ClaimValue" TEXT, CONSTRAINT "FK_AspNetRoleClaims_AspNetRoles_RoleId" FOREIGN KEY("RoleId") REFERENCES "AspNetRoles"("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetUsers" ( "Id" TEXT NOT NULL, "UserName" TEXT, "NormalizedUserName" TEXT, "Email" TEXT, "NormalizedEmail" TEXT, "EmailConfirmed" INTEGER NOT NULL, "PasswordHash" TEXT, "SecurityStamp" TEXT, "ConcurrencyStamp" TEXT, "PhoneNumber" TEXT, "PhoneNumberConfirmed" INTEGER NOT NULL, "TwoFactorEnabled" INTEGER NOT NULL, "LockoutEnd" TEXT, "LockoutEnabled" INTEGER NOT NULL, "AccessFailedCount" INTEGER NOT NULL, CONSTRAINT "PK_AspNetUsers" PRIMARY KEY("Id") ); CREATE TABLE IF NOT EXISTS "AspNetRoles" ( "Id" TEXT NOT NULL, "Name" TEXT, "NormalizedName" TEXT, "ConcurrencyStamp" TEXT, CONSTRAINT "PK_AspNetRoles" PRIMARY KEY("Id") ); INSERT INTO "Customers" VALUES (1,'<NAME>','74621ca4-a029-4c78-9387-17db8f0ab2bd',1,1,1); INSERT INTO "Customers" VALUES (2,'<NAME>','7688c7a6-1a6d-4ad7-8fb5-e551d0c3ce48',1,1,1); INSERT INTO "Outlets" VALUES (1,'TEVCharger',16.0,0,NULL); INSERT INTO "Chargers" VALUES (1,1,'EVCS',16.0,1); INSERT INTO "Chargers" VALUES (2,1,'TestEVCS',16.0,2); INSERT INTO "Meters" VALUES (1,'CMS',20.0,0,1,1); INSERT INTO "Meters" VALUES (2,'TestCMS',20.0,0,2,2); INSERT INTO "Configurations" VALUES (1,'BrokerURL','mqtt.symlink.se'); INSERT INTO "Configurations" VALUES (2,'BrokerUser','johsim:johsim'); INSERT INTO "Configurations" VALUES (3,'BrokerPasswd','<PASSWORD>'); INSERT INTO "AspNetUserRoles" VALUES ('74621ca4-a029-4c78-9387-17db8f0ab2bd','4db1b8f8-37b8-4243-9d97-99c376b10fde'); INSERT INTO "AspNetUserRoles" VALUES ('b7459bb9-0c0a-43dd-aba3-a41c74859726','4db1b8f8-37b8-4243-9d97-99c376b10fde'); INSERT INTO "AspNetUserRoles" VALUES ('7688c7a6-1a6d-4ad7-8fb5-e551d0c3ce48','4db1b8f8-37b8-4243-9d97-99c376b10fde'); INSERT INTO "AspNetUsers" VALUES ('7688c7a6-1a6d-4ad7-8fb5-e551d0c3ce48','<EMAIL>','<EMAIL>','<EMAIL>','<EMAIL>',0,'AQAAAAEAACcQAAAAEBMH6Fa6giqte/1T+kCeEjtbP3u55HBDhXOC5I7Tv/J7DGxf58oV9siQoU9E3+MILg==','WM7L57427S2G75NMIYZ6BMXRE3PAKZCG','56c0837b-6ecc-4c30-a139-a5e0fcad8184',NULL,0,0,NULL,1,0); INSERT INTO "AspNetUsers" VALUES ('74621ca4-a029-4c78-9387-17db8f0ab2bd','<EMAIL>','<EMAIL>','<EMAIL>','<EMAIL>',0,'AQAAAAEAACcQAAAAENhNQH7dNv1v5FklrbLBpUjG32x2o3gBs7OJxoCRUacV/GwLF2XSFA2+EBEYPKByew==','N6GSBLEEMPKJ4CPUHTJECE3SA6KP76MM','1b37455b-a454-4e22-ad16-a57825377af9',NULL,0,0,NULL,1,0); INSERT INTO "AspNetUsers" VALUES ('b7459bb9-0c0a-43dd-aba3-a41c74859726','<EMAIL>','<EMAIL>','<EMAIL>','<EMAIL>',0,'AQAAAAEAACcQAAAAEFYlelnlBPNqLI751mZgRDUJ4HvOqcTs1R8IF56uWaiGDouETf5Q9bNpVE/NbqIcaw==','DCXOZWB6TSK5FX6THHMWNWYAWZTL5SKV','038263e9-19a9-4506-8fbf-0b2012056ec2',NULL,0,0,NULL,1,0); INSERT INTO "AspNetRoles" VALUES ('4db1b8f8-37b8-4243-9d97-99c376b10fde','Admin','ADMIN','94e86504-bb4e-4626-95de-2f5df6f7e174'); INSERT INTO "AspNetRoles" VALUES ('3364159d-a82d-4bac-bf05-063322c7f79b','Manager','MANAGER','1192a0e9-151a-4a81-986a-4be774fc504a'); INSERT INTO "AspNetRoles" VALUES ('c8e8c036-cedd-4682-8334-43596078ebc0','Member','MEMBER','831a43da-138d-48e7-a7f1-b0408784b2d0'); INSERT INTO "AspNetRoles" VALUES ('6c34ddef-1d45-47e6-bc95-8b9689c93151','Installer','INSTALLER','c36def2a-03f4-458a-ae13-0abe0574ddd0'); INSERT INTO "AspNetRoles" VALUES ('35419737-7c13-44ee-938d-f347f5739b67','Customer','CUSTOMER','472d7e7f-c4de-45f0-b93f-802b95382cd4'); CREATE INDEX IF NOT EXISTS "IX_Chargers_CustomerID" ON "Chargers" ( "CustomerID" ); CREATE INDEX IF NOT EXISTS "IX_Meters_CustomerID" ON "Meters" ( "CustomerID" ); CREATE INDEX IF NOT EXISTS "IX_Outlets_ChargerID" ON "Outlets" ( "ChargerID" ); CREATE UNIQUE INDEX IF NOT EXISTS "UserNameIndex" ON "AspNetUsers" ( "NormalizedUserName" ); CREATE INDEX IF NOT EXISTS "EmailIndex" ON "AspNetUsers" ( "NormalizedEmail" ); CREATE INDEX IF NOT EXISTS "IX_AspNetUserRoles_RoleId" ON "AspNetUserRoles" ( "RoleId" ); CREATE INDEX IF NOT EXISTS "IX_AspNetUserLogins_UserId" ON "AspNetUserLogins" ( "UserId" ); CREATE INDEX IF NOT EXISTS "IX_AspNetUserClaims_UserId" ON "AspNetUserClaims" ( "UserId" ); CREATE UNIQUE INDEX IF NOT EXISTS "RoleNameIndex" ON "AspNetRoles" ( "NormalizedName" ); CREATE INDEX IF NOT EXISTS "IX_AspNetRoleClaims_RoleId" ON "AspNetRoleClaims" ( "RoleId" ); COMMIT; <file_sep>-- SQLite PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE IF NOT EXISTS "Configurations" ( "ConfigurationID" INTEGER NOT NULL CONSTRAINT "PK_Configurations" PRIMARY KEY, "Key" TEXT NOT NULL, "Value" INTEGER NOT NULL ); INSERT INTO Configurations VALUES(1,'BrokerURL','192.168.222.20'); COMMIT;<file_sep>using System.Collections.Generic; namespace EnergyApp.Data { public class Charger { public int ID { get; set; } public string Name { get; set; } public float MaxCurrent { get; set; } public ICollection<CMCAssign> CMCAssigns { get; set; } } }<file_sep>using System; using Xunit; namespace EnergyApp.Test { public class UnitTest1 { [Fact] public void Test1() { System.Console.Out.WriteLineAsync("Hi 1"); } [Fact] public void Test2() { System.Console.Out.WriteLineAsync("Hi Test2"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using EnergyApp.Data; namespace RelationTest.Pages_CMCAssigns { public class DetailsModel : PageModel { private readonly EnergyApp.Data.ApplicationDbContext _context; public DetailsModel(EnergyApp.Data.ApplicationDbContext context) { _context = context; } public CMCAssign CMCAssign { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } CMCAssign = await _context.CMCAssign .Include(c => c.Charger) .Include(c => c.Customer) .Include(c => c.Meter).FirstOrDefaultAsync(m => m.ChargerID == id); if (CMCAssign == null) { return NotFound(); } return Page(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using EnergyApp.Data; namespace EnergyApp.Pages_Outlet { public class IndexModel : PageModel { private readonly EnergyApp.Data.ApplicationDbContext _context; public IndexModel(EnergyApp.Data.ApplicationDbContext context) { _context = context; } public IList<Outlet> Outlet { get;set; } public async Task OnGetAsync() { Outlet = await _context.Outlets.ToListAsync(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using EnergyApp.Data; namespace EnergyApp.Pages_Outlet { public class EditModel : PageModel { private readonly EnergyApp.Data.ApplicationDbContext _context; public EditModel(EnergyApp.Data.ApplicationDbContext context) { _context = context; } [BindProperty] public Outlet Outlet { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } Outlet = await _context.Outlets.FirstOrDefaultAsync(m => m.ID == id); if (Outlet == null) { return NotFound(); } return Page(); } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } _context.Attach(Outlet).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!OutletExists(Outlet.ID)) { return NotFound(); } else { throw; } } return RedirectToPage("./Index"); } private bool OutletExists(int id) { return _context.Outlets.Any(e => e.ID == id); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using EnergyApp.Data; namespace EnergyApp.Pages_CMPAssignments { public class IndexModel : PageModel { private readonly EnergyApp.Data.ApplicationDbContext _context; public IndexModel(EnergyApp.Data.ApplicationDbContext context) { _context = context; } public IList<CMPAssignment> CMPAssignment { get;set; } public async Task OnGetAsync() { CMPAssignment = await _context.CMPAssignments .Include(c => c.Charger) .Include(c => c.Meter) .Include(c => c.Partner).ToListAsync(); } } } <file_sep>using System; using System.Diagnostics; using System.Collections.Generic; using System.Globalization; using System.IO; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using EnergyApp.Data; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using MQTTnet; using MQTTnet.Client; using MQTTnet.Client.Options; using MQTTnet.Diagnostics; using MQTTnet.Protocol; namespace powerconcern.mqtt.services { public class MQTTService: BackgroundService { //private readonly DbContextOptions<ApplicationDbContext> _dbContextOptions; private readonly IServiceProvider _serviceProvider; private readonly ILogger _log; private ApplicationDbContext dbContext; private List<Configuration> appConfig; public MqttFactory Factory { get; } public IMqttClient MqttClnt {get; } public IMqttClientOptions options; public CultureInfo culture; private string sTestPrefix {get;set;} //Automatically passes the logger factory in to the constructor via dependency injection public MQTTService(ILogger<MQTTService> log, IServiceProvider serviceProvider) { //Get serviceprovider so we later can connect to databasemodel from it. _serviceProvider=serviceProvider; _log=log; //log=_serviceProvider.GetRequiredService() culture=CultureInfo.CreateSpecificCulture("sv-SE"); //fMeanCurrent=new float[4]; bcLookup=new Dictionary<string, BaseCache>(); string sBrokerURL, sBrokerUser, sBrokerPasswd=""; Factory=new MqttFactory(); MqttClnt=Factory.CreateMqttClient(); /* log = loggerFactory?.CreateLogger("MQTTSvc"); if(log == null) { throw new ArgumentNullException(nameof(loggerFactory)); } */ using(var scope = _serviceProvider.CreateScope()) { dbContext = scope.ServiceProvider.GetService<ApplicationDbContext>(); //Read all of the config appConfig=dbContext.Configuration.ToList(); sBrokerURL=GetConfigString("BrokerURL"); sBrokerUser=GetConfigString("BrokerUser"); sBrokerPasswd=GetConfigString("BrokerPasswd"); sTestPrefix=GetConfigString("TestPrefix"); try { var assignments=dbContext.CMPAssignments .Include(m=>m.Meter) .Include(p=>p.Partner) .Include(c=>c.Charger) .AsNoTracking(); foreach (var assignItem in assignments) { var meitem=assignItem.Meter; var paitem=assignItem.Partner; var chitem=assignItem.Charger; try { MeterCache meterCache=new MeterCache(); meterCache.sName=meitem.Name; meterCache.sCustomerID=paitem.UserReference; meterCache.fMaxCurrent=meitem.MaxCurrent; bcLookup.Add(meitem.Name, meterCache); ChargerCache chargerCache=new ChargerCache(); chargerCache.sCustomerID=paitem.UserReference; chargerCache.fMaxCurrent=chitem.MaxCurrent; chargerCache.bcParent=meterCache; chargerCache.sName=chitem.Name; chargerCache.iPhases=7; meterCache.cChildren.Add(chargerCache); bcLookup.Add(chitem.Name, chargerCache); } catch (System.Exception e) { _log.LogError(e.Message); } } } catch(Exception e) { _log.LogWarning(e.Message); //fMaxCurrent=-1; LogInformation($"MaxCurrent error: {e.Message}"); } LogInformation($"BrokerURL:{sBrokerURL}"); } //MqttNetGlobalLogger.LogMessagePublished += OnTraceMessagePublished; options = new MqttClientOptionsBuilder() .WithClientId("EnergyApp") .WithTcpServer(sBrokerURL) .WithCredentials(sBrokerUser, sBrokerPasswd) .Build(); //var result = MqttClnt.ConnectAsync(options); #region UseConnectedHandler MqttClnt.UseConnectedHandler(async e => { Console.WriteLine("### CONNECTED TO SERVER ###"); // Subscribe to topics foreach(string Name in bcLookup.Keys) { if(Name.Contains("EVC")) { await MqttClnt.SubscribeAsync(new TopicFilterBuilder().WithTopic($"{Name}/#").Build()); } } for (int i = 1; i < 4; i++) { await MqttClnt.SubscribeAsync(new TopicFilterBuilder().WithTopic($"+/status/current_l{i}/#").Build()); } Console.WriteLine("### SUBSCRIBED ###"); }); #endregion MqttClnt.UseDisconnectedHandler(async e => { Console.WriteLine("### DISCONNECTED FROM SERVER ###"); await Task.Delay(TimeSpan.FromSeconds(5)); try { await MqttClnt.ConnectAsync(options); } catch { Console.WriteLine("### RECONNECTING FAILED ###"); } }); MqttClnt.UseApplicationMessageReceivedHandler(e => { LogInformation($"IncomingMsg;{e.ApplicationMessage.Topic};{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); //Find charger from chargername or meter from metername string[] topic = e.ApplicationMessage.Topic.Split('/'); BaseCache mc; try { mc = bcLookup[topic[0]]; } catch (System.Exception) { LogInformation($"Cannot find {topic[0]}"); mc = null; } //TODO What happens if not found //Check current from the highest meter to the charger if (mc is MeterCache) { MeterCache mCache = (MeterCache)mc; if (e.ApplicationMessage.Topic.Contains("current_l")) { //Get info in temp vars var fCurrent = ToFloat(e.ApplicationMessage.Payload); int iPhase = Int16.Parse(e.ApplicationMessage.Topic.Substring(e.ApplicationMessage.Topic.Length - 1)); //Store in cache mCache.fMeterCurrent[iPhase] = fCurrent; mCache.fMeanCurrent[iPhase] = (2 * mCache.fMeanCurrent[iPhase] + fCurrent) / 3; LogInformation($"Phase: {iPhase}; Current: {fCurrent}; Mean Current: {mCache.fMeanCurrent[iPhase]}"); float fSuggestedCurrentChange; //Calculate new value if (fCurrent > mCache.fMaxCurrent) { //What's the overcurrent? float fOverCurrent = fCurrent - mCache.fMaxCurrent; LogInformation($"Holy Moses, {fCurrent} is {fOverCurrent}A too much!"); //Check all chargers that is connected var connChargers = mCache.cChildren.Where(m => m.bConnected); //Set new current //Number of chargers to even out on int iChargers = connChargers.Count(); fSuggestedCurrentChange = (-fOverCurrent) / iChargers; foreach (ChargerCache cc in connChargers) { //TODO Handle the case where one charger uses less current than given. //TODO Distribute to the others. float fNewCurrent = cc.AdjustNewChargeCurrent(fSuggestedCurrentChange); //TODO Might hang with await PostAdjustedCurrent(fNewCurrent, cc); } LogInformation($"New charging current for {mCache.sName}"); } else { //Loop through chargers and outlets /* foreach (var charger in mCache.cChildren) { if(fCurrent>charger.fMaxCurrent) { float fOverCurrent=fCurrent-mCache.fMaxCurrent; _logger.LogInformation($"Holy Charger, {fCurrent} is {fOverCurrent}A too much!"); fNewChargeCurrent=(charger.fMaxCurrent-fOverCurrent); await AdjustCurrent(fNewChargeCurrent, charger); } } */ } } } else if (mc is ChargerCache) { var cCache = (ChargerCache)mc; if (e.ApplicationMessage.Topic.Contains("/status/current")) { cCache.fCurrentSet = ToFloat(e.ApplicationMessage.Payload); LogInformation($"Got charger current:{cCache.fCurrentSet}"); } else if (e.ApplicationMessage.Topic.Contains("/status/max_current")) { cCache.fMaxCurrent = ToFloat(e.ApplicationMessage.Payload); LogInformation($"Got charger maxcurrent:{cCache.fMaxCurrent}"); } else if (e.ApplicationMessage.Topic.Contains("/status/charging")) { cCache.bConnected = ToBool(e.ApplicationMessage.Payload); LogInformation($"Got charger charging:{cCache.bConnected}"); using(var scope = _serviceProvider.CreateScope()) { dbContext = scope.ServiceProvider.GetService<ApplicationDbContext>(); var chSession=new ChargeSession(); chSession.ChargerID=1; chSession.ID=1; chSession.OutletID=1; chSession.Kwh=10; dbContext.ChargeSession.Add(chSession); dbContext.SaveChanges(); } } } if (e.ApplicationMessage.Topic.Contains("current1d")) { //Save PNG to file Stream s = new FileStream("1d.png", FileMode.Create); var bw = new BinaryWriter(s); bw.Write(e.ApplicationMessage.Payload); //bw.Flush(); bw.Close(); } LogInformation($"Receive end"); }); LogInformation("MQTTService created"); } private static Stopwatch NewMethod() { return new Stopwatch(); } private void LogInformation(string sLogInfo) { _log.LogInformation($"{DateTime.Now.ToString("MM-ddTHH:mm:ss.FFF",culture)};{sLogInfo}"); } private async Task PostAdjustedCurrent(float fNewChargeCurrent, ChargerCache cCache) { string sNewChargeCurrent=fNewChargeCurrent.ToString(); if(cCache.fCurrentSet!=fNewChargeCurrent) { LogInformation($"Adjusting {sTestPrefix}{cCache.sName} to {sNewChargeCurrent}A"); await MqttClnt.PublishAsync($"{sTestPrefix}{cCache.sName}/set/current", sNewChargeCurrent, MqttQualityOfServiceLevel.AtLeastOnce, false); LogInformation($"Adjusted {sTestPrefix}{cCache.sName} to {sNewChargeCurrent}A"); } else { LogInformation($"{sTestPrefix}{cCache.sName} already at {sNewChargeCurrent}A"); } //TODO Store in database } private string GetConfigString(string sKey) { try { var result=appConfig.First(c=>c.Key.Equals(sKey)); return result.Value; } catch (Exception e) { return e.Message; } } private bool ToBool(byte[] bArray) { string s=System.Text.Encoding.UTF8.GetString(bArray); return s.Equals("1"); } private float ToFloat(byte[] bArray) { float f=0; string s=System.Text.Encoding.UTF8.GetString(bArray); //Adjust to sv-SE Culture? Or Invariant try { f=float.Parse(s,System.Globalization.NumberStyles.Float,CultureInfo.InvariantCulture); } catch (System.Exception) { _log.LogError($"Unable to parse {s}"); } return f; } private void OnTraceMessagePublished(object sender, MqttNetLogMessagePublishedEventArgs e) { //Logger.LogTrace(e.TraceMessage.Message); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using(var scope = _serviceProvider.CreateScope()) { dbContext = scope.ServiceProvider.GetService<ApplicationDbContext>(); var test=dbContext.Meters.AsQueryable(); } LogInformation("Background thread started"); var result = await MqttClnt.ConnectAsync(options); LogInformation($"Connection result: {result.ResultCode}"); while (!stoppingToken.IsCancellationRequested) { await Task.Delay(30000, stoppingToken); //Check if we can increase the charge current //Loop through meters foreach(BaseCache cCache in bcLookup.Values) { if(cCache is MeterCache) { MeterCache mc = (MeterCache)cCache; //Get max current we can increase with //Checks all phases LogInformation($"{mc.sName}, checking possible currentChange"); //TODO Check one phase at a time float fSuggestedCurrentChange=mc.GetMaxPhaseAddCurrent(7); //Check all chargers that is connected var connChargers=mc.cChildren.Where(m => m.bConnected); //Set new current //Number of chargers to even out on int iChargers=connChargers.Count(); LogInformation($"{mc.sName}, possible currentChange for {iChargers} chargers: {fSuggestedCurrentChange}A"); fSuggestedCurrentChange=fSuggestedCurrentChange/iChargers; foreach(ChargerCache cc in connChargers) { //TODO Handle the case where one charger uses less current than given. //TODO Distribute to the others. float fNewCurrent=cc.AdjustNewChargeCurrent(fSuggestedCurrentChange); await PostAdjustedCurrent(fNewCurrent, cc); } } } LogInformation($"Background svc loop end"); } stoppingToken.Register(() => LogInformation($" MQTTSvc background task is stopping.")); /* Python rules client.subscribe("EVCharger/#") client.subscribe("CurrentMeter/#") if msg.topic == "EVCharger/status/current": charge_current = float(msg.payload) print("Charge current %.1f A" % charge_current) if msg.topic == "CurrentMeter/status/current": current = float(msg.payload) mean_current = (9*mean_current + current) / 10 print("Current %.1f (mean %.1f)" % (current, mean_current)) if mean_current > max_current: new_charge_current = charge_current - (mean_current-max_current) client.publish("EVCharger/set/current", payload=str(int(new_charge_current)), qos=0, retain=False) if new_charge_current < 2: client.publish("EVCharger/set/enable", payload=str(0), qos=0, retain=False) else: client.publish("EVCharger/set/current", payload=str(int(max_current)), qos=0, retain=False) client.publish("EVCharger/set/enable", payload=str(1), qos=0, retain=False) */ //MqttClient client=(MqttClient)MqttClnt; //result = await MqttClnt.ConnectAsync(options); /* async Task Handler1(MqttApplicationMessageReceivedEventArgs e) { // await client1.PublishAsync($"reply/{eventArgs.ApplicationMessage.Topic}"); string _logstr=$"{DateTime.Now} {e.ApplicationMessage.Topic} \t {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"; //Logger.LogInformation(logstr); Console.WriteLine(logstr); } client.UseApplicationMessageReceivedHandler(Handler1); while (!stoppingToken.IsCancellationRequested) { await Task.Delay(1000, stoppingToken); Console.WriteLine("Background svc looping"); } */ Console.WriteLine("Background svc is stopping."); //return Task.CompletedTask; } private Dictionary<string, BaseCache> bcLookup {get; set;} public BaseCache GetBaseCache(string sKey) { return bcLookup[sKey]; //TODO reread structure if not found } } public class BaseCache { public BaseCache() { cChildren=new List<ChargerCache>(); } public string sName; public string sCustomerID; public float fMaxCurrent; public BaseCache bcParent; public ICollection<ChargerCache> cChildren; public ICollection<MeterCache> mChildren; } public enum CacheType {ChargerType, MeterType}; public class MeterCache :BaseCache { public MeterCache() { fMeanCurrent=new float[4]; fMeterCurrent=new float[4]; } public float[] fMeanCurrent; public float[] fMeterCurrent; //public int iPhase; public bool bCurrentAdd; /**Return max meancurrent for the incoming phases iPhases = phases in binary form */ public float GetMaxPhaseAddCurrent(int iPhases) { float fMax=0; int iPhase=3; for (int iPowTwo = 4; iPowTwo > 0 ; iPowTwo/=2) { if(iPhases>=iPowTwo) { //Valid phase - use in calculation if(fMeanCurrent[iPhase]>fMax) { fMax=fMeanCurrent[iPhase]; } iPhase--; iPhases-=iPowTwo; } } return fMaxCurrent-fMax; } } public class ChargerCache :BaseCache { public float fCurrentSet; public bool bConnected; public int iPhases=0; /// <summary> /// Calculates new chargercurrent /// </summary> /// <returns></returns> public string GetNewChargeCurrent() { //Get max current that meter could handle float fCurrentMaxAdd=((MeterCache)bcParent).GetMaxPhaseAddCurrent(iPhases); //Can the charger handle that too? //TODO Get this from Outlet instead. Or don't - maybe not necessary //Current to increase with float fSuggestedCurrentChange=fCurrentMaxAdd-fCurrentSet; float fNewChargeCurrent=AdjustNewChargeCurrent(fSuggestedCurrentChange); //Max current to increase with return fNewChargeCurrent.ToString("0"); } /// <summary> /// Adjusts for max and min current /// </summary> /// <param name="fSuggestedCurrentChange"></param> /// <returns></returns> public float AdjustNewChargeCurrent(float fSuggestedCurrentChange) { float fNewIncomingCurrent=fCurrentSet+fSuggestedCurrentChange; if(fNewIncomingCurrent>fMaxCurrent) { fNewIncomingCurrent=fMaxCurrent; } if(fNewIncomingCurrent<2) { fNewIncomingCurrent=0; } //Round down return (int)fNewIncomingCurrent; } } }<file_sep>BEGIN TRANSACTION; CREATE TABLE IF NOT EXISTS "Customers" ( "ID" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "Name" TEXT, "CustomerNumber" TEXT, "MeterID" INTEGER NOT NULL, "ChargerID" INTEGER NOT NULL, "Type" INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS "Outlets" ( "ID" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "Name" TEXT, "MaxCurrent" REAL NOT NULL, "Type" INTEGER, "ChargerID" INTEGER, CONSTRAINT "FK_Outlets_Chargers_ChargerID" FOREIGN KEY("ChargerID") REFERENCES "Chargers"("ID") ON DELETE RESTRICT ); CREATE TABLE IF NOT EXISTS "Chargers" ( "ID" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "OutletID" INTEGER NOT NULL, "Name" TEXT, "MaxCurrent" REAL NOT NULL, "CustomerID" INTEGER ); CREATE TABLE IF NOT EXISTS "Meters" ( "ID" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "Name" TEXT, "MaxCurrent" REAL NOT NULL, "Type" INTEGER, "ChargerID" INTEGER NOT NULL, "CustomerID" INTEGER ); CREATE TABLE IF NOT EXISTS "Configurations" ( "ID" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "Key" TEXT NOT NULL, "Value" TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS "AspNetUserTokens" ( "UserId" TEXT NOT NULL, "LoginProvider" TEXT NOT NULL, "Name" TEXT NOT NULL, "Value" TEXT, CONSTRAINT "PK_AspNetUserTokens" PRIMARY KEY("UserId","LoginProvider","Name"), CONSTRAINT "FK_AspNetUserTokens_AspNetUsers_UserId" FOREIGN KEY("UserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetUserRoles" ( "UserId" TEXT NOT NULL, "RoleId" TEXT NOT NULL, CONSTRAINT "PK_AspNetUserRoles" PRIMARY KEY("UserId","RoleId"), CONSTRAINT "FK_AspNetUserRoles_AspNetRoles_RoleId" FOREIGN KEY("RoleId") REFERENCES "AspNetRoles"("Id") ON DELETE CASCADE, CONSTRAINT "FK_AspNetUserRoles_AspNetUsers_UserId" FOREIGN KEY("UserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetUserLogins" ( "LoginProvider" TEXT NOT NULL, "ProviderKey" TEXT NOT NULL, "ProviderDisplayName" TEXT, "UserId" TEXT NOT NULL, CONSTRAINT "PK_AspNetUserLogins" PRIMARY KEY("LoginProvider","ProviderKey"), CONSTRAINT "FK_AspNetUserLogins_AspNetUsers_UserId" FOREIGN KEY("UserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetUserClaims" ( "Id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "UserId" TEXT NOT NULL, "ClaimType" TEXT, "ClaimValue" TEXT, CONSTRAINT "FK_AspNetUserClaims_AspNetUsers_UserId" FOREIGN KEY("UserId") REFERENCES "AspNetUsers"("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetRoleClaims" ( "Id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "RoleId" TEXT NOT NULL, "ClaimType" TEXT, "ClaimValue" TEXT, CONSTRAINT "FK_AspNetRoleClaims_AspNetRoles_RoleId" FOREIGN KEY("RoleId") REFERENCES "AspNetRoles"("Id") ON DELETE CASCADE ); CREATE TABLE IF NOT EXISTS "AspNetUsers" ( "Id" TEXT NOT NULL, "UserName" TEXT, "NormalizedUserName" TEXT, "Email" TEXT, "NormalizedEmail" TEXT, "EmailConfirmed" INTEGER NOT NULL, "PasswordHash" TEXT, "SecurityStamp" TEXT, "ConcurrencyStamp" TEXT, "PhoneNumber" TEXT, "PhoneNumberConfirmed" INTEGER NOT NULL, "TwoFactorEnabled" INTEGER NOT NULL, "LockoutEnd" TEXT, "LockoutEnabled" INTEGER NOT NULL, "AccessFailedCount" INTEGER NOT NULL, CONSTRAINT "PK_AspNetUsers" PRIMARY KEY("Id") ); CREATE TABLE IF NOT EXISTS "AspNetRoles" ( "Id" TEXT NOT NULL, "Name" TEXT, "NormalizedName" TEXT, "ConcurrencyStamp" TEXT, CONSTRAINT "PK_AspNetRoles" PRIMARY KEY("Id") ); CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" ( "MigrationId" TEXT NOT NULL, "ProductVersion" TEXT NOT NULL, CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY("MigrationId") ); INSERT INTO "Customers" ("ID","Name","CustomerNumber","MeterID","ChargerID","Type") VALUES (1,'<NAME>','74621ca4-a029-4c78-9387-17db8f0ab2bd',1,1,1), (2,'Tommys Test','7688c7a6-1a6d-4ad7-8fb5-e551d0c3ce48',1,1,1); INSERT INTO "Outlets" ("ID","Name","MaxCurrent","Type","ChargerID") VALUES (1,'TEVCharger',16.0,0,NULL); INSERT INTO "Chargers" ("ID","OutletID","Name","MaxCurrent","CustomerID") VALUES (1,1,'EVCS',16.0,1), (2,1,'TestEVCS',16.0,2); INSERT INTO "Meters" ("ID","Name","MaxCurrent","Type","ChargerID","CustomerID") VALUES (1,'CMS',20.0,0,1,1), (2,'TestCMS',20.0,0,2,2); INSERT INTO "Configurations" ("ID","Key","Value") VALUES (1,'BrokerURL','mqtt.symlink.se'), (2,'BrokerUser','johsim:johsim'), (3,'BrokerPasswd','<PASSWORD>'); INSERT INTO "AspNetUserRoles" ("UserId","RoleId") VALUES ('74621ca4-a029-4c78-9387-17db8f0ab2bd','4db1b8f8-37b8-4243-9d97-99c376b10fde'), ('b7459bb9-0c0a-43dd-aba3-a41c74859726','4db1b8f8-37b8-4243-9d97-99c376b10fde'), ('7688c7a6-1a6d-4ad7-8fb5-e551d0c3ce48','4db1b8f8-37b8-4243-9d97-99c376b10fde'); INSERT INTO "AspNetUsers" ("Id","UserName","NormalizedUserName","Email","NormalizedEmail","EmailConfirmed","PasswordHash","SecurityStamp","ConcurrencyStamp","PhoneNumber","PhoneNumberConfirmed","TwoFactorEnabled","LockoutEnd","LockoutEnabled","AccessFailedCount") VALUES ('7688c7a6-1a6d-4ad7-8fb5-e551d0c3ce48','<EMAIL>','<EMAIL>','<EMAIL>','<EMAIL>',0,'AQAAAAEAACcQAAAAEBMH6Fa6giqte/1T+kCeEjtbP3u55HBDhXOC5I7Tv/J7DGxf58oV9siQoU9E3+MILg==','WM7L57427S2G75NMIYZ6BMXRE3PAKZCG','56c0837b-6ecc-4c30-a139-a5e0fcad8184',NULL,0,0,NULL,1,0), ('74621ca4-a029-4c78-9387-17db8f0ab2bd','<EMAIL>','<EMAIL>','<EMAIL>','<EMAIL>',0,'AQAAAAEAACcQAAAAENhNQH7dNv1v5FklrbLBpUjG32x2o3gBs7OJxoCRUacV/GwLF2XSFA2+EBEYPKByew==','N6GSBLEEMPKJ4CPUHTJECE3SA6KP76MM','1b37455b-a454-4e22-ad16-a57825377af9',NULL,0,0,NULL,1,0), ('b7459bb9-0c0a-43dd-aba3-a41c74859726','<EMAIL>','<EMAIL>','<EMAIL>','<EMAIL>',0,'AQAAAAEAACcQAAAAEFYlelnlBPNqLI751mZgRDUJ4HvOqcTs1R8IF56uWaiGDouETf5Q9bNpVE/NbqIcaw==','DCXOZWB6TSK5FX6THHMWNWYAWZTL5SKV','038263e9-19a9-4506-8fbf-0b2012056ec2',NULL,0,0,NULL,1,0); INSERT INTO "AspNetRoles" ("Id","Name","NormalizedName","ConcurrencyStamp") VALUES ('4db1b8f8-37b8-4243-9d97-99c376b10fde','Admin','ADMIN','94e86504-bb4e-4626-95de-2f5df6f7e174'), ('3364159d-a82d-4bac-bf05-063322c7f79b','Manager','MANAGER','1192a0e9-151a-4a81-986a-4be774fc504a'), ('c8e8c036-cedd-4682-8334-43596078ebc0','Member','MEMBER','831a43da-138d-48e7-a7f1-b0408784b2d0'), ('6c34ddef-1d45-47e6-bc95-8b9689c93151','Installer','INSTALLER','c36def2a-03f4-458a-ae13-0abe0574ddd0'), ('35419737-7c13-44ee-938d-f347f5739b67','Customer','CUSTOMER','472d7e7f-c4de-45f0-b93f-802b95382cd4'); INSERT INTO "__EFMigrationsHistory" ("MigrationId","ProductVersion") VALUES ('00000000000000_CreateIdentitySchema','2.2.4-servicing-10062'), ('20190721213752_InitialCreate','2.2.4-servicing-10062'), ('20190722151026_Meters','2.2.4-servicing-10062'), ('20190724212142_ChargerOutlet','2.2.4-servicing-10062'), ('20190808091717_Customer','2.2.4-servicing-10062'); CREATE INDEX IF NOT EXISTS "IX_Chargers_CustomerID" ON "Chargers" ( "CustomerID" ); CREATE INDEX IF NOT EXISTS "IX_Meters_CustomerID" ON "Meters" ( "CustomerID" ); CREATE INDEX IF NOT EXISTS "IX_Outlets_ChargerID" ON "Outlets" ( "ChargerID" ); CREATE UNIQUE INDEX IF NOT EXISTS "UserNameIndex" ON "AspNetUsers" ( "NormalizedUserName" ); CREATE INDEX IF NOT EXISTS "EmailIndex" ON "AspNetUsers" ( "NormalizedEmail" ); CREATE INDEX IF NOT EXISTS "IX_AspNetUserRoles_RoleId" ON "AspNetUserRoles" ( "RoleId" ); CREATE INDEX IF NOT EXISTS "IX_AspNetUserLogins_UserId" ON "AspNetUserLogins" ( "UserId" ); CREATE INDEX IF NOT EXISTS "IX_AspNetUserClaims_UserId" ON "AspNetUserClaims" ( "UserId" ); CREATE UNIQUE INDEX IF NOT EXISTS "RoleNameIndex" ON "AspNetRoles" ( "NormalizedName" ); CREATE INDEX IF NOT EXISTS "IX_AspNetRoleClaims_RoleId" ON "AspNetRoleClaims" ( "RoleId" ); COMMIT; <file_sep>namespace EnergyApp.Data { public enum OutletType { Type2, Schuko } public class Outlet { public int ID { get; set; } public string Name { get; set; } public int ChargerID { get; set; } public float MaxCurrent { get; set; } public OutletType? Type { get; set; } public Charger Charger { get; set; } } }
53fdcb6dddc4d72adf44dcf3c491f4c119bc9fef
[ "C#", "SQL" ]
31
C#
powerconcern/EnergyApp
f3cbbed7c0ca544a1a5e20a33d1299463c8fa1fc
b73f373f14902fefa5c7f0028dbf559db6929d2e
refs/heads/master
<repo_name>kurai021/ECSL2016-JS-Arduino<file_sep>/ejemplos/led_example/public/javascripts/led.js $(document).ready(function() { var socket = io.connect('http://localhost:3000'); $('#red').click(function(e){ socket.emit('red'); e.preventDefault(); }); $('#yellow').click(function(e){ socket.emit('yellow'); e.preventDefault(); }); $('#green').click(function(e){ socket.emit('green'); e.preventDefault(); }); }); <file_sep>/presentacion/slides/slide2.html <h3 class="bold">¡Hablemos de NodeBots!</h3> <br> <p class="fragment fade-in">Eventos creados por entusiastas de Javascript y hardware</p> <br> <strong class="fragment fade-in">¡Si estás interesado, aquí verás como empezar!</strong>
fe54631a4da804c454e8ba9532ea27011f906819
[ "JavaScript", "HTML" ]
2
JavaScript
kurai021/ECSL2016-JS-Arduino
28043b3a9cac85624b86a5470900bfe06689c89b
3e9af4366a1f4fc14bd4ddb982ada92db5da2607
refs/heads/master
<repo_name>msjones3/requests<file_sep>/post.py from flask import * import requests app = Flask(__name__) @app.route("/", methods=["GET", "POST"]) def main(): if request.method=="POST": username = request.form['username'] print(username) return render_template('destination.html') return render_template('forms.html') @app.route("/get") def get(): username = request.args.get('username') print(username) return render_template('destination.html') app.run(debug=True) <file_sep>/README.md # requests comparison of get and post requests with Flask # Description: Both GET and POST methods are applied when transferring data from the client to the server; however, the way the data is presented to the server is different In Flask, we often want to retrieve arguments that were passed to a form via a user. This demo shows how these arguments can be retrieved. Pay attention to the address bar in each of these examples. What is the difference? Which of these methods would be appropriate for - a password - a search bar - very long paragraph
4ea8e96d87daef3f7bb3cabf1588202bfa942856
[ "Markdown", "Python" ]
2
Python
msjones3/requests
5dfbe81da0993f4303b5ba90f98776b5773b8fa8
4047d8272cb6bcfb4c78c167cf27aab76a43aef7
refs/heads/master
<file_sep>var app = angular.module('angularPlayground'); app.controller('ExpressionsController', ExpressionsController); function ExpressionsController(){ this.expressionsStatus = 'Working'; this.test = 'Yipee! It works!' } app.controller('MyOwnFrikinController', MyOwnFrikinController); function MyOwnFrikinController(){ this.isTheBomb = "This is my own frikin property!"; }
6a31ebd457388de2544fee6ac2a6cd2a9bd81780
[ "JavaScript" ]
1
JavaScript
jonnyporter/angular-playground
8981a0f86695f7554d9610d98d4d88e56f982acc
f84cb683f07245fb310e818352325eb0239247b7
refs/heads/main
<repo_name>patrickgr-ghub/data_engineering<file_sep>/README.md # data_engineering Core Data Engineering Knowledge for Delivering Other Projects <p>This repository represents fundamental processes to deliver other Data Engineering projects. 1. Establish Authentication Credentials using Config Parser 2. Create & Launch an Amazon Redshift Cluster for Analytics 3. Upload Tables to Redshift Cluster 4. Copy and Insert Records from S3 Buckets 5. Delete Redshift Cluster after use </p> Last Update - December 2020 <file_sep>/etl/connection.py import pandas as pd import boto3 import json import configparser from pprint import pprint from time import time # Created December 2020 # Load all config parameters from the config file "dwh.cfg" config = configparser.ConfigParser() config.read_file(open('dwh.cfg')) KEY = config.get('AWS','KEY') SECRET = config.get('AWS','SECRET') DWH_CLUSTER_TYPE = config.get("DWH","DWH_CLUSTER_TYPE") DWH_NUM_NODES = config.get("DWH","DWH_NUM_NODES") DWH_NODE_TYPE = config.get("DWH","DWH_NODE_TYPE") DWH_IAM_ROLE_NAME = config.get("DWH", "DWH_IAM_ROLE_NAME") DWH_CLUSTER_IDENTIFIER = config.get("DWH","DWH_CLUSTER_IDENTIFIER") DB_NAME=config.get("CLUSTER","DB_NAME") DB_USER=config.get("CLUSTER","DB_USER") DB_PASSWORD=config.get("CLUSTER","DB_PASSWORD") DB_PORT=config.get("CLUSTER","DB_PORT") DWH_ENDPOINT = config.get("CLUSTER","HOST") DWH_ROLE_ARN = config.get("IAM_ROLE","DWH_ROLE_ARN") SONG_DATA = config.get("S3","SONG_DATA") LOG_DATA = config.get("S3","LOG_DATA") LOG_JSONPATH = config.get("S3","LOG_JSONPATH") pd.DataFrame({"Param": ["DWH_CLUSTER_TYPE", "DWH_NUM_NODES", "DWH_NODE_TYPE", "DWH_CLUSTER_IDENTIFIER", "DWH_IAM_ROLE_NAME", "DWH_ENDPOINT", "DWH_ROLE_ARN", "SONG_DATA", "LOG_DATA", "LOG_JSONPATH", "DB_NAME", "DB_USER", "DB_PASSWORD", "DB_PORT"], "Value": [DWH_CLUSTER_TYPE, DWH_NUM_NODES, DWH_NODE_TYPE, DWH_CLUSTER_IDENTIFIER, DWH_IAM_ROLE_NAME, DWH_ENDPOINT, DWH_ROLE_ARN, SONG_DATA, LOG_DATA, LOG_JSONPATH, DB_NAME, DB_USER, DB_PASSWORD, DB_PORT] }) # Create the needed AWS Clients ec2 = boto3.resource('ec2', region_name="us-west-2", aws_access_key_id=KEY, aws_secret_access_key=SECRET ) s3 = boto3.resource('s3', region_name="us-west-2", aws_access_key_id=KEY, aws_secret_access_key=SECRET ) iam = boto3.client('iam', region_name="us-west-2", aws_access_key_id=KEY, aws_secret_access_key=SECRET ) redshift = boto3.client('redshift', region_name="us-west-2", aws_access_key_id=KEY, aws_secret_access_key=SECRET ) # Create the IAM Role to have Redshift Access the S3 Bucket (ReadOnly) def create_role(DWH_IAM_ROLE_NAME): try: print("1.1 Creating a new IAM Role") dwhRole = iam.create_role( Path='/', RoleName=DWH_IAM_ROLE_NAME, Description = "Allows Redshift clusters to call AWS services on your behalf.", AssumeRolePolicyDocument=json.dumps( {'Statement': [{'Action': 'sts:AssumeRole', 'Effect': 'Allow', 'Principal': {'Service': 'redshift.amazonaws.com'}}], 'Version': '2012-10-17'}) ) except Exception as e: print(e) # Attach Policy def attach_policy(DWH_IAM_ROLE_NAME): print("1.2 Attaching Policy") iam.attach_role_policy(RoleName=DWH_IAM_ROLE_NAME, PolicyArn="arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess" )['ResponseMetadata']['HTTPStatusCode'] # Get & Print the IAM Role ARN def get_role(DWH_IAM_ROLE_NAME): print("1.3 Get the IAM role ARN") roleArn = iam.get_role(RoleName=DWH_IAM_ROLE_NAME)['Role']['Arn'] print(roleArn) return roleArn # Create the Redshift Cluster def create_cluster(DWH_CLUSTER_TYPE, DWH_NODE_TYPE, DWH_NUM_NODES, DB_NAME, DWH_CLUSTER_IDENTIFIER, DB_USER, DB_PASSWORD, roleArn): try: response = redshift.create_cluster( #HW ClusterType=DWH_CLUSTER_TYPE, NodeType=DWH_NODE_TYPE, NumberOfNodes=int(DWH_NUM_NODES), #Identifiers & Credentials DBName=DB_NAME, ClusterIdentifier=DWH_CLUSTER_IDENTIFIER, MasterUsername=DB_USER, MasterUserPassword=<PASSWORD>, #Roles (for s3 access) IamRoles=[roleArn] ) except Exception as e: print(e) # Run "connection.py" functions to create role, attach policy, set roleArn, and create the cluster. def main(): create_role(DWH_IAM_ROLE_NAME) attach_policy(DWH_IAM_ROLE_NAME) roleArn = get_role(DWH_IAM_ROLE_NAME) create_cluster(DWH_CLUSTER_TYPE, DWH_NODE_TYPE, DWH_NUM_NODES, DB_NAME, DWH_CLUSTER_IDENTIFIER, DB_USER, DB_PASSWORD, roleArn) if __name__ == "__main__": main() <file_sep>/etl/etl.py import psycopg2 from connection import * from sql_queries import copy_table_queries, insert_table_queries # Load Tables, Insert, Connect and Launch Functions def load_staging_tables(cur, conn): for query in copy_table_queries: cur.execute(query) conn.commit() def insert_tables(cur, conn): for query in insert_table_queries: cur.execute(query) conn.commit() def main(): conn = psycopg2.connect("host={} dbname={} user={} password={} port={}".format(DWH_ENDPOINT, DB_NAME, DB_USER, DB_PASSWORD, DB_PORT)) cur = conn.cursor() load_staging_tables(cur, conn) insert_tables(cur, conn) conn.close() # Make Connection and Execute Functions if __name__ == "__main__": main() <file_sep>/etl/AWS_Datawarehouse.md # Project: Data Warehouse on AWS ### Authored by: <NAME> ### Authored on: October 2020 #### Sources Include: Personal Project Work, Answers Provided within the "Mentor Help" Responses for this project within the Udacity Learning Portal, and Code Mentoring Sessions. ## Project Description <p>This project simulates the Extraction, Transformation, and Loading (ETL) of "songs" and "user activity" on the new music streaming app for Sparkify. The analytics team would like to understand what songs users are currently listening to. The current data resides in a S3 bucket of user activity JSON logs and a directory of song metadata. The analytics team wants to move their processes and data onto the cloud to take advantage of the latest updates to database technologies and the ability to scale processes elasticly.</p> <p>In order to optimize queries, the Data Engineer has created a database schema and ETL pipeline for loading information into data warehouses on AWS to be used within Redshift Analyses.</p> ### Visual Schema of the Project Tables: <p> ![See Project Workspace File:'Schema_Data_Modeling_Postgres.png](http://na-sjdemo1.marketo.com/rs/786-GZR-035/images/Schema_Data_Modeling_Postgres.png "Visual of the Project Schema - Available in Project Workspace Files - 'Schema_Data_Modeling_Postgres.png' ") </p> <p>The Database Schema for the AWS Redshift ETL Pipeline reflects the final Fact and Dimension Tables that can be used to query information by the Analytics Team. It is important to note that staging tables were used to extract information from the "Songs" and "User Activity" Logs.</p> ### Staging Tables: <p>"events_staging" Table <ul> <li>"artist", type: varchar</li> <li>"auth", type: varchar</li> <li>"firstName", type: varchar</li> <li>"gender", type: varchar</li> <li>"itemInSession", type: integer</li> <li>"lastName", type: varchar</li> <li>"length", type: float</li> <li>"level", type: varchar</li> <li>"location", type: varchar</li> <li>"method", type: varchar</li> <li>"page", type: varchar</li> <li>"registration", type: float</li> <li>"sessionId", type: integer</li> <li>"song", type: varchar</li> <li>"status", type: integer</li> <li>"ts", type: numeric</li> <li>"userAgent", type: varchar</li> <li>"userId", type: integer</li> </ul> </p> <p>"songs_staging" Table <ul> <li>"num_songs", type: integer</li> <li>"artist_id", type: varchar</li> <li>"artist_latitude", type: float</li> <li>"artist_longitude", type: float</li> <li>"artist_location", type: varchar</li> <li>"artist_name", type: varchar</li> <li>"song_id", type: varchar</li> <li>"title", type: varchar</li> <li>"duration", type: float</li> <li>"year", type: integer</li> </ul> </p> ### Database Schema: <p>"songplays" Fact Table <ul> <li>"sps_songplay_id", type: integer identity(1,1) NOT NULL</li> <li>"sps_ts", type: numeric NOT NULL</li> <li>"sps_user_id", type: integer NOT NULL</li> <li>"sps_level", type: varchar</li> <li>"sps_song_id", type: varchar distkey</li> <li>"sps_artist_id", type: varchar sortkey</li> <li>"sps_session_id", type: integer</li> <li>"sps_artist_location", type: varchar</li> <li>"sps_user_agent", type: varchar</li> </ul> </p> <p>"songs" Dimension Table <ul> <li>"song_id", type: varchar sortkey distkey</li> <li>"title", type: varchar</li> <li>"artist_id", type: varchar</li> <li>"year", type: integer</li> <li>"duration", type: numeric</li> </ul> </p> <p>"artists" Dimension Table <ul> <li>"artist_id", type: varchar NOT NULL sortkey</li> <li>"artist_name", type: varchar</li> <li>"artist_location", type: varchar</li> <li>"artist_latitude", type: numeric</li> <li>"artist_longitude", type: numeric</li> </ul> </p> <p>"users" Dimension Table <ul> <li>"user_id", type: integer sortkey</li> <li>"first_name", type: varchar</li> <li>"last_name", type: varchar</li> <li>"gender", type: varchar</li> <li>"level", type: varchar</li> </ul> </p> <p>"time" Dimension Table <ul> <li>"ts", type: timestamp NOT NULL sortkey</li> <li>"hour", type: integer</li> <li>"day", type: integer</li> <li>"week", type: integer</li> <li>"month", type: integer</li> <li>"year", type: integer</li> <li>"dayofweek", type: integer</li> </ul> </p> ### Explanation of Sort & Dist Keys: <p>To maintain data integrity and identify any inconsistencies that arise as table creation occurs, NOT NULL has been added to Primary Keys for each of the CREATE TABLE queries within "sql_queries.py". Distkeys and Sortkeys have been applied to fields and tables to optimize data processing times.</p> > The "identity(1,1)" clause is use to create a unique identifier for each record within AWS Redshift. ### ETL Schema: <p>To create the "songplays" Fact Table, the following ETL Schema was developed:</p> <ul> <li>File: "connection.py", Purpose: IaC framework to create the Redshift Cluster and Access Roles.</li> <li>File: "create_tables.py", Purpose: Drops & Creates Tables within the Redshift Database</li> <li>File: "sql_queries.py", Purpose: Queries to Drop, Create, and Insert Stagging & Songplays Data.</li> <li>File: "etl.py", Purpose: Executes the Finalized ETL Processes, Production Code.</li> <li>File: "ETL_Build.ipynb", Purpose: Jupyter Notebooks file used to build & validate Draft ETL Production Code.</li> <li>File: "delete_cluster.py", Purpose: Deletes Redshift Cluster & Roles.</li> </ul> ## Description of Data Handling & Functions <p>Leverging Infrastructure as Code (IaC), the "connection.py" file will establish the AWS Role and Arn needed to make appropriate connections to Redshift. The "crate_tables.py" file will Drop existing tables if needed, then setup the listed tables that include the staging tables, dimension tables, and final "songplays" Fact Table. Finally, the "etl.py" file will be used to upload data from SONGS_DATA and LOG_DATA according the following extractions, transformations, and loads based on the process described below.</p> <p>The "delete_cluster" table can be used at any time to eliminate the project cluster to restart, refine, and clean up the project.</p> ### 1. Establish the AWS IAM Role for Redshift Access & Create the Redshift Cluster <p>The first step in delivering analytics capabilities through the Cloud will be to setup the Redshift Services via IaC using the "connection.py" file.</p> <p>Begin by loading the "dwh.cfg" file and variables into local memory through the "configparser" library.</p> > import configparser > create local project variables <p> <ul> <li>KEY = Secret Key for AWS Authentication</li> <li>SECRET = Secret Password for AWS Authentication</li> <li>DWH_CLUSTER_TYPE = Defines Cluster Type for IaC</li> <li>DWH_NUM_NODES = Defines Number of Nodes within Cluster Type for IaC</li> <li>DWH_NODE_TYPE = Defines Node Type for IaC</li> <li>DWH_IAM_ROLE_NAME = Sets the IAM Role Name for IaC</li> <li>DWH_CLUSTER_IDENTIFIER = Provides Cluster Identifier for IaC</li> <li>DWH_ROLE_ARN = Establishes roleArn for IaC and Redshift Connections</li> <li>SONG_DATA = Song Data S3 Bucket Path</li> <li>LOG_DATA = Log Data S3 Bucket Path</li> <li>LOG_JSONPATH = JSON Path to Interpret Log Data</li> <li>HOST = Path to Connect with Redshift Cluster</li> <li>DB_NAME = Cluster Name in Redshift</li> <li>DB_USER = User Name in Redshift</li> <li>DB_PASSWORD = Password to Connect with Redshift Cluster</li> <li>DB_PORT = Redshift Connection Port</li> </ul> </p> > create AWS Clients using boto3 Library <p> <ul> <li>ec2 Client</li> <li>s3 Client</li> <li>iam Client</li> <li>redshift Client</li> </ul> </p> <p>Launch Functions to Create Role, Attach Policy, Get Role, and Create Cluster - Created the following functions in line with accessibility and scalability of IaC.</p> > function "create_role" :: to create the IAM Role through IaC > function "attach_policy" :: to attach IAM Role Policy > function "get_role" :: to get & print the IAM Role > function "create_cluster" :: to create the Redshift Cluster through IaC ### 2. Establish staging, dimension, and "songplays" tables using "create_tables.py" <p>The first step in delivering the ETL schema is to CREATE the staging tables to import the SONG_DATA and LOG_DATA from the "udacity-dend" S3 bucket.</p> <p>Load the appropriate python libraries</p> > import psycopg2 :: postgreSQL Library > from connection import * :: bring over local variables from "connection.py" > from sql_queries import create_table_queries, drop_table_queries :: imports queries from "sql_queries.py" <p>Drop Tables if they Exist:</p> > def drop_tables(cur, conn): <p> <ul> <li>Drops each table using the queries in `drop_table_queries` list.</li> </ul> </p> <p>Create staging, dimension, and "songplays" fact tables:</p> > def create_tables(cur, conn): <p> <ul> <li>Creates each table using the queries in `create_table_queries` list.</li> </ul> </p> <p>**It is important to note that the etl process is designed to load data into the "songs_staging" and "events_staging" tables in Redshift that will then be used to populate the dimension and fact tables.</p> <p>Create Connection & Execute functions:</p> > def main(): <p> <ul> <li>conn = creates connection</li> <li>cur = creates the cursor</li> <li>drop_tables(cur,conn) = execute drop_tables function</li> <li>create_tables(cur,conn) = execute create_tables function</li> </ul> </p> <p>Launch Connection & Functions</p> > if__name__ == "__main__": main() ### 3. Access DROP, CREATE and INSERT queries within "sql_queries.py" <p>The "create_tables.py" and "etl.py" files reference the "sql_queries.py" file through associated functions to deliver the supporting sql_queries that will DROP, CREATE and INSERT data into the appropriate tables, including the associated Fact and Dimension VALUES.</p> <p>CREATE Queries Include: <ul> <li>songs_staging_table_create</li> <li>events_staging_table_create</li> <li>songplays_table_create</li> <li>songs_table_create</li> <li>artists_table_create</li> <li>users_table_create</li> <li>time_table_crate</li> </ul> </p> <p>The "artists" and "users" dimensions tables have the potential for duplicate records coming from the staging tables. To remove duplicates, "SELECT DISTINCT" has been used to de-duplicate the identity keys - resulting in unique records within each table.</p> <p>COPY Queries Include: <ul> <li>events_staging_copy</li> <li>songs_staging_copy</li> </ul> </p> <p>The copy queries leverage the Local Variables of SONG_DATA, LOG_DATA, LOG_JSONPATH, and DWH_ROLE_ARN to connect to the appropriate "udacity-dend" S3 buckets and COPY the data into the staging tables.</p> <p>INSERT Queries Include: <ul> <li>songplays_table_insert</li> <li>songs_table_insert</li> <li>artists_table_insert</li> <li>users_table_insert</li> <li>time_table_insert</li> </ul> </p> <p>The "songplays_table_insert statement uses INSERT INTO with JOINS on "artist_name", "title", and "duration" WHERE "page"="NextSong".</p> #### Explanation of NOT NULL, sortkey and distkey by table: <p>The Songs, Artists, Users, and Time Tables are large files and could take large amounts of time to process if ingested evenly across all Redshift Nodes. To optimize the ingestion of information to the dimension and "songplays" fact tables sortkeys and distkeys have been added to the following fields: <ul> <li>songs_table_create: sortkey and distkey for "sgs_song_id"</li> <li>artists_table_create: sortkey for "a_artist_id"</li> <li>users_table_create: sortkey for "u_user_id"</li> <li>time_table_create: sortkey for "t_ts"</li> <li>songsplays_table_create: sortkey for "sps_artist_id" and distkey for "sps_song_id"</li> </ul> </p> ### 4. Load data to dimension tables & "songplays" fact table through "etl.py" <p>The final step in delivering the ETL schema is to setup the dimension and fact tables will be to INSERT data from the staging tables into "songs", "artists", "users", "time", and "songplays".</p> <p>Load the appropriate python libraries</p> > import psycopg2 :: postgreSQL Library > from connection import * :: bring over local variables from "connection.py" > from sql_queries import copy_table_queries, insert_table_queries :: imports queries from "sql_queries.py" <p>Load Staging Tables</p> > def load_staging_tables(cur, conn): <p> <ul> <li>Uses the COPY function to bring over data from "udacity-dend" S3 buckets.</li> </ul> </p> <p>INSERT data into dimension tables and "songplays" fact table:</p> > def insert_tables(cur, conn): <p> <ul> <li>Inserts data from staging tables into dimension tables & "songplays" fact table.</li> </ul> </p> <p>**It is important to note that the etl process is designed to load data into the "songs_staging" and "events_staging" tables in Redshift - these tables are then be used to populate the dimension and fact tables.</p> <p>Create Connection & Execute functions:</p> > def main(): <p> <ul> <li>conn = creates connection</li> <li>cur = creates the cursor</li> <li>drop_tables(cur,conn) = execute drop_tables function</li> <li>create_tables(cur,conn) = execute create_tables function</li> </ul> </p> <p>Launch Connection & Functions</p> > if__name__ == "__main__": main() ### 5. Test the "songplays" ETL Schema <p>To test the success of the ETL Schema, log into Redshift and attempt the following queries through the Redshift Query Editor: <ul> <li>SELECT * FROM users LIMIT 10</li> <li>SELECT * FROM artists LIMIT 10</li> <li>SELECT * FROM songs LIMIT 10</li> <li>SELECT * FROM time LIMIT 10</li> <li>SELECT * FROM songplays LIMIT 10</li> </ul> </p> ### DATABASE CLEANUP file "delete_cluster.py" <p>To reduce the cost of running servers and systems through AWS, data engineers can access the "delete_cluster.py" file. This file has the following design and functions:</p> <p>Load the appropriate python libraries</p> > import pandas as pd :: pandas Library > import psycopg2 :: postgreSQL Library > from connection import * :: bring over local variables from "connection.py" <p>Retreive Cluster Properties</p> > def prettyRedshiftProps(props): <p> <ul> <li>Loads the Project Redshift Cluster Properties into the Dataframe.</li> </ul> </p> <p>Delete the Project Cluster and IAM Role</p> > def deleteCluster(cur, conn): <p>Create Connection & Execute functions:</p> > def main(): <p> <ul> <li>conn = creates connection</li> <li>cur = creates the cursor</li> <li>drop_tables(cur,conn) = execute drop_tables function</li> <li>create_tables(cur,conn) = execute create_tables function</li> </ul> </p> <p>Launch Connection & Functions</p> > if__name__ == "__main__": main() <file_sep>/etl/delete_cluster.py import pandas as pd import psycopg2 from connection import * # Define cluster properties def prettyRedshiftProps(props): pd.set_option('display.max_colwidth', -1) keysToShow = ["ClusterIdentifier", "NodeType", "ClusterStatus", "MasterUsername", "DBName", "Endpoint", "NumberOfNodes", 'VpcId'] x = [(k, v) for k,v in props.items() if k in keysToShow] return pd.DataFrame(data=x, columns=["Key", "Value"]) # Function to Delete Project Cluster def deleteCluster(cur,conn): redshift.delete_cluster( ClusterIdentifier=DWH_CLUSTER_IDENTIFIER, SkipFinalClusterSnapshot=True) myClusterProps = redshift.describe_clusters(ClusterIdentifier=DWH_CLUSTER_IDENTIFIER)['Clusters'][0] prettyRedshiftProps(myClusterProps) iam.detach_role_policy(RoleName=DWH_IAM_ROLE_NAME, PolicyArn="arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess") iam.delete_role(RoleName=DWH_IAM_ROLE_NAME) # Function to Launch Connection and Execute "deleteCluster" def main(): conn = psycopg2.connect("host={} dbname={} user={} password={} port={}".format(DWH_ENDPOINT, DB_NAME, DB_USER, DB_PASSWORD, DB_PORT)) cur = conn.cursor() deleteCluster(cur,conn) conn.close() # Execute Functions if __name__ == "__main__": main() <file_sep>/etl/sql_queries.py from connection import * # DROP TABLES events_staging_table_drop = ("DROP TABLE IF EXISTS events_staging") songs_staging_table_drop = ("DROP TABLE IF EXISTS songs_staging") songplays_table_drop = ("DROP TABLE IF EXISTS songplays") users_table_drop = ("DROP TABLE IF EXISTS users") songs_table_drop = ("DROP TABLE IF EXISTS songs") artists_table_drop = ("DROP TABLE IF EXISTS artists") time_table_drop = ("DROP TABLE IF EXISTS time") # CREATE TABLES events_staging_table_create= (""" CREATE TABLE "events_staging" ( "artist" varchar, "auth" varchar, "firstName" varchar, "gender" varchar, "itemInSession" integer, "lastName" varchar, "length" float, "level" varchar, "location" varchar, "method" varchar, "page" varchar, "registration" float, "sessionId" integer, "song" varchar, "status" integer, "ts" numeric, "userAgent" varchar, "userId" integer ); """) songs_staging_table_create = (""" CREATE TABLE "songs_staging" ( "num_songs" integer, "artist_id" varchar, "artist_latitude" float, "artist_longitude" float, "artist_location" varchar, "artist_name" varchar, "song_id" varchar, "title" varchar, "duration" float, "year" integer ); """) users_table_create = (""" CREATE TABLE "users" ( "u_user_id" integer sortkey, "u_first_name" varchar, "u_last_name" varchar, "u_gender" varchar, "u_level" varchar) diststyle all; """) songs_table_create = (""" CREATE TABLE "songs" ( "sgs_song_id" varchar sortkey distkey, "sgs_title" varchar, "sgs_artist_id" varchar, "sgs_year" integer, "sgs_duration" float ); """) artists_table_create = (""" CREATE TABLE "artists" ( "a_artist_id" varchar not null sortkey, "a_artist_name" varchar, "a_artist_location" varchar, "a_artist_latitude" float, "a_artist_longitude" float) diststyle all; """) time_table_create = (""" CREATE TABLE "time" ( "t_ts" numeric not null sortkey, "t_hour" integer, "t_day" integer, "t_week" integer, "t_month" integer, "t_year" integer, "t_dayofweek" integer) diststyle all; """) songplays_table_create = (""" CREATE TABLE "songplays" ( "sps_songplay_id" integer identity(1,1) not null, "sps_ts" numeric not null, "sps_user_id" integer not null, "sps_level" varchar, "sps_song_id" varchar distkey, "sps_artist_id" varchar sortkey, "sps_session_id" integer, "sps_artist_location" varchar, "sps_user_agent" varchar ); """) # STAGING TABLES events_staging_copy = (""" COPY songs_staging FROM {} CREDENTIALS 'aws_iam_role={}' REGION 'us-west-2' JSON 'auto' """).format(SONG_DATA, DWH_ROLE_ARN) songs_staging_copy = (""" COPY events_staging FROM {} CREDENTIALS 'aws_iam_role={}' REGION 'us-west-2' COMPUPDATE OFF FORMAT AS JSON {} TIMEFORMAT 'epochmillisecs' """).format(LOG_DATA, DWH_ROLE_ARN, LOG_JSONPATH) # FINAL TABLES time_table_insert = (""" INSERT INTO time ( t_ts, t_hour, t_day, t_week, t_month, t_year, t_dayofweek ) SELECT distinct ts, EXTRACT(HOUR FROM t_start_time) AS t_hour, EXTRACT(DAY FROM t_start_time) AS t_day, EXTRACT(WEEK FROM t_start_time) AS t_week, EXTRACT(MONTH FROM t_start_time) AS t_month, EXTRACT(YEAR FROM t_start_time) AS t_year, EXTRACT(DOW FROM t_start_time) AS t_weekday FROM (SELECT distinct ts,'1970-01-01'::date + ts/1000 * interval '1 second' as t_start_time FROM events_staging); """) songs_table_insert = (""" INSERT INTO songs ( sgs_song_id, sgs_title, sgs_artist_id, sgs_year, sgs_duration ) SELECT song_id, title, artist_id, year, duration FROM songs_staging; """) artists_table_insert = (""" INSERT INTO artists ( a_artist_id, a_artist_name, a_artist_location, a_artist_latitude, a_artist_longitude ) SELECT DISTINCT artist_id, artist_name, artist_location, artist_latitude, artist_longitude FROM songs_staging WHERE artist_id IS NOT null; """) users_table_insert = (""" INSERT INTO users ( u_user_id, u_first_name, u_last_name, u_gender, u_level ) SELECT DISTINCT userId, firstName, lastName, gender, level FROM events_staging es1 WHERE userId IS NOT null AND ts = (SELECT max(ts) FROM events_staging es2 WHERE es1.userId = es2.userId) ORDER BY userId DESC; """) songplays_table_insert = (""" INSERT INTO songplays ( sps_ts, sps_user_id, sps_level, sps_song_id, sps_artist_id, sps_session_id, sps_artist_location, sps_user_agent ) SELECT es.ts, es.userId, es.level, ss.song_id, ss.artist_id, es.sessionId, es.location, es.userAgent FROM events_staging es JOIN songs_staging ss ON (es.artist = ss.artist_name) AND (es.song = ss.title) AND (es.length = ss.duration) WHERE es.page = 'NextSong'; """) # QUERY LISTS create_table_queries = [events_staging_table_create, songs_staging_table_create, songplays_table_create, users_table_create, songs_table_create, artists_table_create, time_table_create] drop_table_queries = [events_staging_table_drop, songs_staging_table_drop, songplays_table_drop, users_table_drop, songs_table_drop, artists_table_drop, time_table_drop] copy_table_queries = [events_staging_copy, songs_staging_copy] insert_table_queries = [songplays_table_insert, users_table_insert, songs_table_insert, artists_table_insert, time_table_insert]
6f10ea9c57b55a7743b89aad59f3189e4fd02f44
[ "Markdown", "Python" ]
6
Markdown
patrickgr-ghub/data_engineering
620220bcbf5cf9861b4a80a1e26d238f37984108
8388d942d8d38dd42ab4c037cab5b42f1a441b4c
refs/heads/master
<file_sep>import React from 'react'; import PropTypes from 'prop-types'; import styles from '../../../styles/DescriptionExtended.css'; const DescriptionExtended = ({ descriptionExtended, hideDescription, showDescriptionExtended, }) => { const bullets = Object.keys(descriptionExtended); const fade = showDescriptionExtended ? styles.fadeIn : styles.fadeOut; return ( <div className={`${styles.container} ${fade}`}> {bullets.map(bullet => ( <div> <span>{bullet}</span> {descriptionExtended[bullet].map(paragraph => ( <p>{paragraph}</p> ))} </div> ))} <button type="button" onClick={() => hideDescription()} >Hide </button> </div> ); }; DescriptionExtended.propTypes = { descriptionExtended: PropTypes.objectOf(PropTypes.string), hideDescription: PropTypes.func, showDescriptionExtended: PropTypes.bool, }; DescriptionExtended.defaultProps = { descriptionExtended: { 'THE SPACE': 'IT\'S LARGE', 'VERY IMPORTANT:': 'DON\'T TOUCH THINGS', 'GUEST ACCESS': 'USE THE DOOR', }, hideDescription: () => {}, showDescriptionExtended: false, }; export default DescriptionExtended; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import styles from '../../../styles/Owner.css'; const Owner = ({ ownerName, ownerPicture }) => ( <div className={styles.container}> <img className={styles.imgCircle} src={ownerPicture} alt="" /> <div className={styles.name}>{ownerName.split(' ')[0]}</div> </div> ); Owner.propTypes = { ownerName: PropTypes.string, ownerPicture: PropTypes.string, }; Owner.defaultProps = { ownerName: '<NAME>', ownerPicture: 'https://s3-us-west-1.amazonaws.com/airbnb-owner-photos/airbnb1.jpg', }; export default Owner; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import DescriptionExtended from './DescriptionExtended.jsx'; import styles from '../../../styles/Description.css'; const Description = ({ description, descriptionExtended, showDescription, showDescriptionExtended, hideDescription, }) => { let expandDescriptionButton; if (showDescriptionExtended) { expandDescriptionButton = ( <div /> ); } else { expandDescriptionButton = ( <button className={styles.button} type="button" onClick={() => showDescription()} >Read more about the space </button> ); } return ( <div className={styles.container}> <p> {description} </p> <DescriptionExtended hideDescription={hideDescription} descriptionExtended={descriptionExtended} showDescriptionExtended={showDescriptionExtended} /> {expandDescriptionButton} </div> ); }; Description.propTypes = { description: PropTypes.string, descriptionExtended: PropTypes.objectOf(PropTypes.string), showDescription: PropTypes.func, hideDescription: PropTypes.func, showDescriptionExtended: PropTypes.bool, }; Description.defaultProps = { description: '', descriptionExtended: { 'THE SPACE': 'IT\'S LARGE', 'VERY IMPORTANT:': 'DON\'T TOUCH THINGS', 'GUEST ACCESS': 'USE THE DOOR', }, showDescription: () => {}, hideDescription: () => {}, showDescriptionExtended: false, }; export default Description; <file_sep>import { shallow } from 'enzyme'; import React from 'react'; import toJson from 'enzyme-to-json'; import Amenities from '../../client/src/components/Amenities'; describe('<Amenities />', () => { it('should render properly', () => { const wrapper = shallow(<Amenities amenities={{}} />); expect(toJson(wrapper)).toMatchSnapshot(); }); it('should run hideAmenities if the backdrop is clicked', () => { const baseProps = { amenities: {}, hideAmenities: jest.fn(), }; const wrapper = shallow( <Amenities {...baseProps} />, ); wrapper.find('div').first().simulate('click'); expect(baseProps.hideAmenities).toHaveBeenCalledTimes(1); }); }); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import Header from './Header.jsx'; import ListingStats from './ListingStats.jsx'; import Owner from './Owner.jsx'; import styles from '../../../styles/HeaderContainer.css'; const HeaderContainer = ({ guests, bedrooms, beds, baths, name, ownerName, ownerPicture, location, livingSpace, }) => ( <div className={styles.wrapper}> <Header livingSpace={livingSpace} name={name} location={location} /> <ListingStats guests={guests} bedrooms={bedrooms} beds={beds} baths={baths} /> <Owner ownerName={ownerName} ownerPicture={ownerPicture} /> </div> ); HeaderContainer.propTypes = { guests: PropTypes.number, bedrooms: PropTypes.number, beds: PropTypes.number, baths: PropTypes.number, ownerName: PropTypes.string, ownerPicture: PropTypes.string, name: PropTypes.string, location: PropTypes.string, livingSpace: PropTypes.string, }; HeaderContainer.defaultProps = { guests: 0, bedrooms: 0, beds: 0, baths: 0, ownerName: '<NAME>', ownerPicture: 'https://s3-us-west-1.amazonaws.com/airbnb-owner-photos/airbnb1.jpg', name: '<NAME>', location: 'San Francisco', livingSpace: 'Apartment', }; export default HeaderContainer; <file_sep>import { shallow } from 'enzyme'; import React from 'react'; import toJson from 'enzyme-to-json'; import Header from '../../client/src/components/Header'; describe('<Header />', () => { it('should render properly', () => { const wrapper = shallow(<Header />); expect(toJson(wrapper)).toMatchSnapshot(); }); }); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import styles from '../../../styles/HomeHighlight.css'; const Highlight = ({ highlight }) => ( <div> <span className={styles.highlight} >{highlight.highlight} </span> <span className={styles.interpunct}>·</span> <span className={styles.details} >{highlight.details} </span> </div> ); Highlight.propTypes = { highlight: PropTypes.objectOf(PropTypes.string), }; Highlight.defaultProps = { highlight: { highlight: 'Self Check-in', details: 'Easily check yourself in with the lockbox.', }, }; export default Highlight; <file_sep>const getRandomInt = (min, max) => { const newMin = Math.ceil(min); const newMax = Math.floor(max); return Math.floor(Math.random() * (newMax - newMin)) + min; }; const generateProperties = (data, property, min) => { const range = getRandomInt(min, data.length); for (let i = 0; i < range; i += 1) { const randomBasics = getRandomInt(0, data.length); if (!property.includes(data[randomBasics])) { property.push(data[randomBasics]); } } }; const descriptionIpsum = () => `Escape civilization to this incredible and peaceful getaway! Reconnect with nature and disconnect from technology on your own private deck surrounded by pristine and untouched nature just a short drive away from LA.`; const iconMap = { Gym: 'https://s3.amazonaws.com/airbnb-icons/gym.png', Kitchen: 'https://s3.amazonaws.com/airbnb-icons/kitcher.png', Wifi: 'https://s3.amazonaws.com/airbnb-icons/wifi.png', 'Laptop friendly workspace': 'https://s3.amazonaws.com/airbnb-icons/laptop.png', Hangers: 'https://s3.amazonaws.com/airbnb-icons/hanger.png', Iron: 'https://s3.amazonaws.com/airbnb-icons/iron.png', }; const descriptionExtendedIpsum = { 'THE SPACE': ['This is the personal Airstream of a nature-loving Malibu designer who built it as his personal getaway from his busy hectic schedule. Stripped down to its bare aluminum studs, the airstream has been redesigned into a large studio with three large frameless glass panels that slide open to a huge cantilevered deck with unrivaled views of the pristine Santa Monica mountains rolling down to the Pacific ocean below.', 'Lounge in our luxury extra thick wool rugs and cotton poufs, drive down to surf one of Malibu\'s best breaks or go hike Sandstone Peak (Santa Monica\'s highest mountain). But whatever you do, make sure not to miss the incredible sunsets off our deck. At night, watch the milky way appear and count the constellations above or the moon reflect on the ocean below. And if the wind is right, listen to the sounds of the crashing waves travel up the canyon or even the seals barking down below.', 'And then at dawn, if you\'re lucky with the morning fog, wake up above the clouds like you are the only person in this planet.'], 'VERY IMPORTANT:': ['DO NOT CLICK ON THE AIRBNB LINK FOR DIRECTIONS as it might take you to the wrong location. Only use the accurate directions provided on our itinerary. If you don\'t you might get lost and we are not responsible if you do not follow our easy and foolproof directions.', 'PLEASE DO NOT BOOK THIS LISTING if you are afraid of nature or its creatures. Understand you are surrounded by thousands of completely untouched nature. You are very likely to hear (or see) coyotes, owls, seals, roadrunners and bunnies. There is a bobcat in the area but these are usually very skittish. There are a mice in the Santa Monica mountains. About once a month, a guest will complain that they saw a mouse. Said mouse might come into the airstream if food is left outside the fridge. We do not offer refunds if a mouse comes into the airstream but we do have 4 traps around the airstream so the odds are heavily stacked against the mice.', 'In three years we have yet to ever see a rattle snake near the airstream so the area is definitely not prone to them.', 'This listing is weather dependent. If there is a high chance of rain scheduled during your stay we reserve the right to cancel the reservation due to potential slippery road conditions and the fact that we have to store all the expensive furniture inside the airstream.', 'The beauty of this experience lies in seeing infinite views and yet no trace of humankind. Sleeping with the doors open, under the milky-way while hearing the ocean waves crashing below and the occasional seal barking in the distance or coyote howling for its pack. Our guests have the most special nights here.', 'Reconnect with nature and disconnect from technology :-)'], 'Guest access': ['There\'s a queen sized bed and another pull out sofa that can fit another person - bring your own sleeping bag for the 3rd wheel. Kitchenette, fridge and separate bathroom with complete privacy and stunning views.'], 'Interaction with guests': ['There is a house 400 yards below the airstream where a lovely family with kids live. If you peak over the edge of the deck you might see the kids playing outside. Frank and Heidi the parents are super friendly and can help you with serious issues once you are there.'], 'Other things to note': ['There is no reception at the airstream. 1/2 mile down below, where the paved road end (upper camp area) there is perfect reception in case you need to make a call.', 'This off the grid airstream means there is no AC power for electrical devices. The 12V DC system powers the LED lights and stereo / speakers. You can charge your iphone off the stereo but bring your own cable as guests take ours often :(', 'We provide a solar battery that charges outside on the deck and does indeed have AC power. Usually it will have a decent charge, but if the prior guests drain it with electronics, then it will take a while to re-charge.', 'There are two routes up to the airstream. The short one (not paved, you\'ll need an SUV) takes 7 minutes to the beach, the longer one (paved and gentle dirt road, all non lowered cars make it ok as long as you are a decent driver and know how to navigate ruts) takes about 11 minutes but is very scenic and beautiful.'], }; const countAmenities = (amenities) => { let count = 0; const keys = Object.keys(amenities); for (let i = 0; i < keys.length; i += 1) { if (Array.isArray(amenities[keys[i]])) { count += amenities[keys[i]].length; } } return count; }; const generateAmenitiesArray = (amenities) => { const amenitiesArray = []; const keys = Object.keys(amenities); if (keys.length > 0) { for (let i = 0; i < keys.length; i += 1) { if (keys[i] !== 'notIncluded' && keys[i] !== 'id' && keys[i] !== '_id') { amenitiesArray.push({ amenity: keys[i], amenities: amenities[keys[i]], }); } } amenitiesArray.push({ amenity: 'notIncluded', amenities: amenities.notIncluded, }); } return amenitiesArray; }; module.exports = { getRandomInt, generateProperties, descriptionIpsum, descriptionExtendedIpsum, countAmenities, generateAmenitiesArray, iconMap, }; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import Thumbs from './Thumbs.jsx'; import Highlight from './Highlight.jsx'; import styles from '../../../styles/HomeHighlight.css'; class HomeHighlight extends React.Component { constructor(props) { super(props); this.state = { showThumbs: true, }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState({ showThumbs: false, }); } render() { const { highlight } = this.props; const { showThumbs } = this.state; let buttonOrFeedback; if (showThumbs) { buttonOrFeedback = ( <Thumbs handleClick={this.handleClick} /> ); } else { buttonOrFeedback = ( <div className={styles.helpful}> Thanks for your feedback. </div> ); } return ( <div className={styles.container}> <Highlight highlight={highlight} /> {buttonOrFeedback} </div> ); } } HomeHighlight.propTypes = { highlight: PropTypes.objectOf(PropTypes.string), }; HomeHighlight.defaultProps = { highlight: { highlight: 'Self Check-in', details: 'Easily check yourself in with the lockbox.', }, }; export default HomeHighlight; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import styles from '../../../styles/HomeHighlight.css'; const Thumbs = ({ handleClick }) => ( <div className={styles.helpful}> <button className={styles.button} type="button" onClick={() => handleClick()} >Helpful <i className={`${styles.i} far fa-thumbs-up`} /> </button> <span className={styles.interpunct}>·</span> <button className={styles.button} type="button" onClick={() => handleClick()} >Not Helpful </button> </div> ); Thumbs.propTypes = { handleClick: PropTypes.func, }; Thumbs.defaultProps = { handleClick: () => {}, }; export default Thumbs; <file_sep>const { getRandomInt } = require('./helpers.js'); const adjectives = [ 'Charming', 'Quiet', 'Tiny', 'Stunning', 'Awe-inspring', 'Modern', 'Urban', 'Bright', 'Beautiful', ]; const places = [ 'Home', 'Penthouse', 'Garden', 'Condo', 'Apartment', 'Studio', 'Townhouse', ]; const additions = [ 'Pool', 'View', 'Balcony', 'Courtyard', 'Common Space', 'Nightlife Scene', 'Night Market Nearby', 'Dog Park', ]; const homeHighlights = [ { highlight: 'Self Check-in', details: 'Easily check yourself in with the lockbox.', }, { highlight: 'Great check-in experience', details: ' 100% of recent guests gave this home’s check-in process a 5-star rating.', }, { highlight: 'Great location', details: '95% of recent guests gave this home’s location a 5-star rating.', }, { highlight: 'Superhost', details: 'Superhosts are experienced, highly rated hosts who are committed to providing great stays for guests.', }, { highlight: 'Outstanding hospitality', details: '98% of recent guests said this host offered outstanding hospitality.', }, { highlight: 'Sparkling clean', details: '94% of recent guests have said that this home was sparkling clean.', }, { highlight: 'Quick responses', details: '98% of recent guests said this host responded quickly.', }, { highlight: 'Great value', details: '100% of recent guests gave this home’s value a 5-star rating.', }, ]; const homeHighlightsRange = getRandomInt(3, homeHighlights.length); const displayAmenities = [ 'Gym', 'Kitchen', 'Wifi', 'Laptop friendly workspace', 'Hangers', 'Iron', 'TV', 'Hot tub', 'Indoor Fireplace', 'Free Parking', ]; module.exports = { adjectives, places, additions, homeHighlights, homeHighlightsRange, displayAmenities, }; <file_sep>import { shallow, mount } from 'enzyme'; import React from 'react'; import toJson from 'enzyme-to-json'; import HomeHighlight from '../../client/src/components/HomeHighlight'; describe('<HomeHighlight />', () => { it('should render properly', () => { const wrapper = shallow(<HomeHighlight />); expect(toJson(wrapper)).toMatchSnapshot(); }); it('should render a div that says \'Thanks for your feedback\' when the first button is clicked', () => { const wrapper = mount( <HomeHighlight />, ); wrapper.find('button').first().simulate('click'); const renderedDiv = wrapper.find('div div').last(); expect(renderedDiv.text()).toEqual('Thanks for your feedback.'); }); it('should render a div that says \'Thanks for your feedback\' when the second button is clicked', () => { const wrapper = mount( <HomeHighlight />, ); wrapper.find('button').last().simulate('click'); const renderedDiv = wrapper.find('div div').last(); expect(renderedDiv.text()).toEqual('Thanks for your feedback.'); }); }); <file_sep>const path = require('path'); const express = require('express'); const cors = require('cors'); const app = express(); const { getListing } = require('../database/model.js'); app.use(cors()); app.use('/:id', express.static(path.resolve(__dirname, '../public'))); app.get('/descriptions/:id', (req, res) => { getListing(req.params.id, (listing) => { res.send(listing); }); }); module.exports = app; <file_sep>const basics = [ { name: 'Wifi', details: 'continuous access in the listing' }, { name: 'Cable TV', details: '' }, { name: 'Indoor fireplace', details: '' }, { name: 'Laptop friendly workspace', details: 'A table or desk with space for a laptop and a chair that’s comfortable to work in', }, { name: 'Washer', details: 'In the building, or free' }, { name: 'Dryer', details: 'In the building, or free' }, { name: 'Air Conditioning', details: '' }, { name: 'Heating', details: '' }, { name: 'Stove', details: '' }, ]; const dining = [ { name: 'Kitchen', details: 'Space where guests can cook their own meals' }, { name: 'Coffee Maker', details: '' }, { name: 'Cooking Basics', deatails: 'Pots and pans, oil, salt and pepper' }, { name: 'Microwave', details: '' }, { name: 'Refrigerator', details: '' }, { name: 'Dishes and silverware', details: '' }, ]; const guestAccess = [ { name: 'Host greets you', details: '' }, { name: 'Keypad', details: 'Check yourself into the home with a door code' }, { name: 'Private entrance', details: 'Separate street or building entrance' }, { name: 'Building staff', details: 'Someone is available 24 hours a day to let guests in' }, { name: 'Lockbox', details: '' }, ]; const bedAndBath = [ { name: 'Hangers', details: '' }, { name: 'Shampoo', details: '' }, { name: '<NAME>', details: '' }, { name: '<NAME>', details: '' }, { name: '<NAME>', details: '' }, { name: 'Extra Pillows and Blankets', details: '' }, { name: 'Lock on bedroom door', details: 'Private room can be locked for safety and privacy', }]; const safetyFeatures = [ { name: 'Fire extinguisher', details: '' }, { name: 'Smoke detector', details: '' }, { name: 'Carbon Monoxide Detector', details: '' }, { name: 'Security guard', details: 'They\'re a cool person' }]; const notIncluded = [ { name: 'Private entrance' }, { name: 'Washer' }, { name: 'Dryer' }, { name: 'TV' }, { name: 'Bathroom' }, { name: 'Bedroom' }, { name: 'Dogs' }, ]; module.exports = { basics, dining, guestAccess, bedAndBath, safetyFeatures, notIncluded, }; <file_sep>import { shallow } from 'enzyme'; import React from 'react'; import toJson from 'enzyme-to-json'; import Description from '../../client/src/components/Description'; describe('<Description />', () => { it('should render properly', () => { const wrapper = shallow(<Description />); expect(toJson(wrapper)).toMatchSnapshot(); }); it('should render an expand button if showDescriptionExtended is false', () => { const wrapper = shallow(<Description showDescriptionExtended={false} />); expect(wrapper.find('button')).toHaveLength(1); }); it('should not render an expand button if showDescriptionExtended is true', () => { const wrapper = shallow(<Description showDescriptionExtended />); expect(wrapper.find('button')).toHaveLength(0); }); }); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import styles from '../../../styles/ListingStats.css'; const ListingStats = ({ guests, bedrooms, beds, baths, }) => ( <div className={styles.container}> <div className={styles.statOne}> <img alt="" className={styles.img} src="https://s3-us-west-1.amazonaws.com/airbnb-owner-photos/guests.png" /> <div>{guests} guests</div> </div> <div className={styles.statTwo}> <img alt="" className={styles.img} src="https://s3-us-west-1.amazonaws.com/airbnb-owner-photos/living.png" /> <div>{bedrooms} bedrooms</div> </div> <div className={styles.statThree}> <img className={styles.img3} alt="" src="https://s3-us-west-1.amazonaws.com/airbnb-owner-photos/beds.png" /> <div>{beds} beds</div> </div> <div className={styles.statFour}> <img className={styles.img} alt="" src="https://s3-us-west-1.amazonaws.com/airbnb-owner-photos/bath.png" /> <div>{baths} baths</div> </div> </div> ); ListingStats.propTypes = { guests: PropTypes.number, bedrooms: PropTypes.number, beds: PropTypes.number, baths: PropTypes.number, }; ListingStats.defaultProps = { guests: 0, bedrooms: 0, beds: 0, baths: 0, }; export default ListingStats; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import Amenities from './Amenities.jsx'; import styles from '../../../styles/AmenitiesDisplay.css'; import { countAmenities, iconMap } from '../../../seedDatabase/helpers'; const AmenitiesDisplay = ({ displayAmenities, amenities, showModal, showAmenities, hideAmenities, hideAmenitiesPress, }) => { const column1 = displayAmenities.slice(0, 3); const column2 = displayAmenities.slice(3, 6); const amenitiesCount = countAmenities(amenities); return ( <div className={styles.container}> <hr className={styles.pageBreak} /> <div className={styles.title}> Amenities </div> <div className={styles.columns}> <div> {column1.map((amenity, i) => ( <div className={`${styles.displayAmenity} ${styles.amenity}`}> <div> <img className={styles.img} alt="" src={iconMap[amenity]} /> </div> <div key={amenity.id} className={styles.amenity} >{amenity} </div> </div> ))} </div> <div className={styles.rightColumn}> {column2.map(amenity => ( <div className={styles.displayAmenity}> <img alt="" src={iconMap[amenity]} className={styles.img} /> <div key={amenity.id} className={styles.amenity} >{amenity} </div> </div> ))} </div> </div> <button className={styles.button} type="button" onClick={() => showAmenities()} >Show all {amenitiesCount} amenities </button> <Amenities amenities={amenities} hideAmenities={hideAmenities} hideAmenitiesPress={hideAmenitiesPress} showModal={showModal} /> </div> ); }; AmenitiesDisplay.propTypes = { displayAmenities: PropTypes.arrayOf(PropTypes.string), showModal: PropTypes.bool, showAmenities: PropTypes.func, hideAmenities: PropTypes.func, hideAmenitiesPress: PropTypes.func, amenities: PropTypes.shape({ id: PropTypes.number, _id: PropTypes.string, basics: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string, details: PropTypes.string, }), ), bedAndBath: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string, details: PropTypes.string, }), ), dining: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string, details: PropTypes.string, }), ), guestAccess: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string, details: PropTypes.string, }), ), safetyFeautes: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string, details: PropTypes.string, }), ), notIncluded: PropTypes.arrayOf(PropTypes.string), }), }; AmenitiesDisplay.defaultProps = { displayAmenities: [], showModal: false, showAmenities: () => {}, hideAmenities: () => {}, hideAmenitiesPress: () => {}, amenities: {}, }; export default AmenitiesDisplay; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import HomeHighlight from './HomeHighlight.jsx'; import styles from '../../../styles/HomeHighlights.css'; const HomeHighlights = ({ homehighlights }) => ( <div className={styles.container}> <div className={styles.title}>HOME HIGHLIGHTS</div> {homehighlights.map((highlight, i) => <HomeHighlight key={i} highlight={highlight} />)} </div> ); HomeHighlights.propTypes = { homehighlights: PropTypes.arrayOf(PropTypes.object), }; HomeHighlights.defaultProps = { homehighlights: [], }; export default HomeHighlights; <file_sep>const request = require('supertest'); const app = require('../../server/app'); describe('Server', () => { it('should respond to get to rooturl', () => { return request(app).get('/1/').then((response) => { expect(response.statusCode).toBe(200); }); }); it('should respond to a GET method to listings', () => { return request(app).get('/descriptions/1').then((response) => { expect(response.statusCode).toBe(200); }); }); it('respond with json', (done) => { request(app) .get('/descriptions/1') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200, done); }); }); <file_sep>import { shallow } from 'enzyme'; import React from 'react'; import toJson from 'enzyme-to-json'; import Thumbs from '../../client/src/components/Thumbs'; describe('<Thumbs />', () => { it('should render properly', () => { const wrapper = shallow(<Thumbs />); expect(toJson(wrapper)).toMatchSnapshot(); }); }); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import styles from '../../../styles/Amenity.css'; const Amenity = ({ availableAmenity }) => { const amenityFormatMap = { basics: 'Basics', guestAccess: 'Guest Access', bedAndBath: 'Bed and Bath', safetyFeatures: 'Safety Features', notIncluded: 'Not Included', }; return ( <div className={styles.amenity}> <h3 className={styles.title}> {amenityFormatMap[availableAmenity.amenity]} </h3> <div className={styles.border} /> {availableAmenity.amenities.map((amenity => ( <p>{amenity.name}</p> )))} </div> ); }; Amenity.propTypes = { availableAmenity: PropTypes.shape({ name: PropTypes.string, details: PropTypes.string, }), }; Amenity.defaultProps = { availableAmenity: { amenity: 'basics', amenities: [{ name: 'Heating', details: '' }], }, }; export default Amenity; <file_sep>import { shallow } from 'enzyme'; import React from 'react'; import toJson from 'enzyme-to-json'; import HomeHighlights from '../../client/src/components/HomeHighlights'; describe('<HomeHighlights />', () => { it('should render properly', () => { const wrapper = shallow(<HomeHighlights />); expect(toJson(wrapper)).toMatchSnapshot(); }); }); <file_sep>import { shallow } from 'enzyme'; import React from 'react'; import toJson from 'enzyme-to-json'; import Amenity from '../../client/src/components/Amenity'; describe('<Amenity />', () => { it('should render properly', () => { const wrapper = shallow(<Amenity />); expect(toJson(wrapper)).toMatchSnapshot(); }); });
bb2d6bccedc3a9c257cc66e3c1932f0fd7ee9cb9
[ "JavaScript" ]
23
JavaScript
Bearbnb/hrsf102-description-service
6a66d19194c9173c3c64efaaae62b2bc35686bf9
17b86af859f671e1c76720d0cf0b0aae6b9dd6c5
refs/heads/master
<file_sep>{% extends 'base_dashboard.html' %} {% load static %} {% block title %} <title>Direccionamiento | Fecha</title> {% endblock %} {% block link %} <link rel="stylesheet" href="{% static 'css/table_dashboard.css' %}"> {% endblock %} {% block content %} <br/> <br/> <br/> <main role="main" class="container"> <!-- render table Addressing--> <div class="table-responsive"> <table class="table"> <thead> <tr > <th scopr="col">Programacion</th> <th scopr="col">Id</th> <th scopr="col">NoPrescripcion</th> <th scopr="col">TipoTec</th> <th scopr="col">ConTec</th> <th scopr="col">NoIdPaciente</th> <th scopr="col">NoEntrega</th> <th scopr="col">NoSubEntrega</th> <th scopr="col">TipoIDProv</th> <th scopr="col">NoIDProv</th> <th scopr="col">CodMunEnt</th> <th scopr="col">FecMaxEnt</th> <th scopr="col">CantTotAEntregar</th> <th scopr="col">DirPaciente</th> <th scopr="col">CodTecAEntregar</th> </tr> </thead> <h1 id="demo"></h1> <tbody id='repos'> {% for result in results %} <tr> <!-- <td> <a href="{{ object.get_absolute_url }}">{{ object|upper }}</a> </td> --> <td class="col-xs-2" > <span style="font-size: 30px; color: green;"> <a type="button"> <i class="far fa-calendar-check" data-toggle="modal" data-target="#addressingProgramModal" onclick="return loadAddressings('{{forloop.counter}}')"></i> </a> </span> </td> <td class="col-xs-2" id="ID_{{forloop.counter}}"> {{ result.id }} </td> <td class="col-xs-2" id="NoPrescripcion_{{forloop.counter}}"> {{ result.NoPrescripcion }} </td> <td class="col-xs-2" id="TipoTec_{{forloop.counter}}"> {{ result.TipoTec }} </td> <td class="col-xs-2" id="ConTec_{{forloop.counter}}"> {{ result.ConTec }} </td> <td class="col-xs-2" id="NoIdPaciente_{{forloop.counter}}"> {{ result.NoIdPaciente }} </td> <td class="col-xs-2" id="NoEntrega_{{forloop.counter}}"> {{ result.NoEntrega }} </td> <td class="col-xs-2" id="NoSubEntrega_{{forloop.counter}}"> {{ result.NoSubEntrega }} </td> <td class="col-xs-2" id="TipoIDProv_{{forloop.counter}}"> {{ result.TipoIDProv }} </td> <td class="col-xs-2" id="NoIDProv_{{forloop.counter}}"> {{ result.NoIDProv }} </td> <td class="col-xs-2" id="CodMunEnt_{{forloop.counter}}"> {{ result.CodMunEnt }} </td> <td class="col-xs-2" id="FecMaxEnt_{{forloop.counter}}"> {{ result.FecMaxEnt }} </td> <td class="col-xs-2" id="CantTotAEntregar_{{forloop.counter}}"> {{ result.CantTotAEntregar }} </td> <td class="col-xs-2" id="DirPaciente_{{forloop.counter}}"> {{ result.DirPaciente }} </td> <td class="col-xs-2" id="CodTecAEntregar_{{forloop.counter}}"> {{ result.CodSerTecAEntregar }} </td> </tr> {% endfor %} </tbody> </table> <!-- end render table Addressing--> </div> </main> <!-- Modal Addressing Date--> <div class="modal fade" id="addressingDateModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Selecciona una fecha para consultar.</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="{% url 'addressing-date' %}" method="post"> {% csrf_token %} <input class="form-control" type="date" name="date" value="YYYY/mm/dd" id="date-start"> <hr> <input type="submit" value="Consulta" id="button-consult" class="btn btn-success btn-lg"> </form> </div> </div> </div> </div> <!-- End Modal Addressing Date--> <!-- Modal Programming--> <div class="modal fade" id="addressingProgramModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Programar</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="{% url 'addressing-program' %}" method="post"> {% csrf_token %} <h6 id="numAddressing2"></h6> <input type="text" name="numAddressing" value="" id="numAddressing" style="display:none"> <input type="text" name="ID" value="" id="ID" style="display:none"> <input type="text" name="TipoTec" value="" id="TipoTec" style="display:none"> <input type="text" name="ConTec" value="" id="ConTec" style="display:none"> <input type="text" name="NoIdPaciente" value="" id="NoIdPaciente" style="display:none"> <input type="text" name="NoEntrega" value="" id="NoEntrega" style="display:none"> <input type="text" name="NoSubEntrega" value="" id="NoSubEntrega" style="display:none"> <input type="text" name="TipoIDProv" value="" id="TipoIDProv" style="display:none"> <input type="text" name="NoIDProv" value="" id="NoIDProv" style="display:none"> <input type="text" name="CodMunEnt" value="" id="CodMunEnt" style="display:none"> <input type="text" name="FecMaxEnt" value="" id="FecMaxEnt" style="display:none"> <input type="text" name="CantTotAEntregar" value="" id="CantTotAEntregar" style="display:none"> <input type="text" name="DirPaciente" value="" id="DirPaciente" style="display:none"> <input type="text" name="CodTecAEntregar" value="" id="CodTecAEntregar" style="display:none"> <input type="text" name="ConTec" value="" id="ConTec" style="display:none"> <hr> <input type="submit" value="Programar" id="button-program" class="btn btn-success btn-lg"> </form> </div> </div> </div> </div> {% endblock %} {% block scripts %} <script src="{% static 'js/program_addressing.js' %}"></script> {% endblock %}<file_sep>aniso8601==7.0.0 Django==2.2.2 djangorestframework==3.9.4 graphene==2.1.8 graphql-core==2.2.1 graphql-relay==2.0.0 gunicorn==19.9.0 Markdown==3.1.1 pep8==1.7.1 promise==2.2.1 psycopg2==2.8.3 pytz==2019.1 Rx==1.6.1 six==1.12.0 sqlparse==0.3.0 <file_sep>document.getElementById("date-start").addEventListener("change", activateButton); // document.getElementById("form-control").addEventListener("change", myFunction); // document.getElementsByClassName("program-btn").addEventListener("click", myFunction); function activateButton() { var x = document.getElementById("date-start"); // document.getElementById("demo").innerHTML = "Fecha a Consultar: " + x.value; document.getElementById("button-consult").className = "btn btn-success btn-lg"; // document.getElementById("button-consult").href = "{% url 'addressing-date' '" + x.value + "' %}"; } <file_sep>from django.urls import path, re_path # from . import views from .views import AddressingDateView, AddressingProgramView # app_name = 'jtest' urlpatterns = [ path('date/', AddressingDateView.as_view(), name='addressing-date'), path('program/', AddressingProgramView.as_view(), name='addressing-program'), # re_path(r'^fecha/(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})/$', views.addressing_date, name='addressing-date') ]<file_sep>from django.shortcuts import render from django.views.generic import TemplateView from . mixins import DashboardLoginRequiredMixin # Create your views here. class index(TemplateView): template_name = 'home/index.html' class DashboardView(DashboardLoginRequiredMixin, TemplateView): template_name = 'home/dashboard.html' # def get_context_data(self, *args, **kwargs): # context = super(DashboardView, self).get_context_data(*args, **kwargs) # context["titulo"]= Copropiedad.objects.get(pk = self.object.pk) # print(context) # return context<file_sep>import json import requests from django.http import HttpResponseRedirect from django.shortcuts import render from django.views import View from apps.core import choices # Create your views here. class AddressingDateView(View): template_name = 'addressing/addressing_date.html' def get(self, request, *args, **kwargs): return render(request, self.template_name, context={}) def post(self, request, *args, **kwargs): date = self.request.POST.get('date', None) response = requests.get(choices.addressing_date, headers={'date': date, 'token': '<KEY>', 'nit': '87654321', }, ) results = response.json() context = { 'results': results['results'], } return render(request, self.template_name, context=context) class AddressingProgramView(View): template_name = 'addressing/addressing_program.html' def get(self, request, *args, **kwargs): print('REQUEST OF PROGRAMMING>>>>', request) return render(request, self.template_name, context={}) def post(self, request, *args, **kwargs): print('ID User', self.request.POST.get('ID', None)) ID = self.request.POST.get('ID', None) numAddressing = self.request.POST.get('numAddressing', None) TipoTec = self.request.POST.get('TipoTec', None) ConTec = self.request.POST.get('ConTec', None) NoIdPaciente = self.request.POST.get('NoIdPaciente', None) NoEntrega = self.request.POST.get('NoEntrega', None) NoSubEntrega = self.request.POST.get('NoSubEntrega', None) TipoIDProv = self.request.POST.get('TipoIDProv', None) NoIDProv = self.request.POST.get('NoIDProv', None) CodMunEnt = self.request.POST.get('CodMunEnt', None) FecMaxEnt = self.request.POST.get('FecMaxEnt', None) CantTotAEntregar = self.request.POST.get('CantTotAEntregar', None) DirPaciente = self.request.POST.get('DirPaciente', None) CodTecAEntregar = self.request.POST.get('CodTecAEntregar', None) response = requests.put( choices.programming, data = { "id": ID, "FecMaxEnt": FecMaxEnt, "TipoIDSedeProv": TipoIDProv, "NoIDSedeProv": NoIDProv, "CodSedeProv": CodMunEnt, "CodTecAEntregar": CodTecAEntregar, "CantTotAEntregar": CantTotAEntregar, }, headers = { 'token': '<KEY>', 'nit': '87654321', }, ) print('\n\n\n') print('!!!!!!!!!!!!::::::::::::::::', response) results = response.json() context = { 'results': results, 'numAddressing': numAddressing, 'TipoTec': TipoTec, 'ConTec': ConTec, 'NoIdPaciente': NoIdPaciente, 'NoEntrega': NoEntrega, 'NoSubEntrega': NoSubEntrega, 'TipoIDProv': TipoIDProv, 'NoIDProv': NoIDProv, 'CodMunEnt': CodMunEnt, 'FecMaxEnt': FecMaxEnt, 'CantTotAEntregar': CantTotAEntregar, 'DirPaciente': DirPaciente, 'CodTecAEntregar': CodTecAEntregar } return render(request, self.template_name, context=context) <file_sep>from django.shortcuts import render, redirect, render_to_response from django.urls import reverse from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse from django.contrib.auth.models import User from django.views.generic import ListView, DetailView from apps.users.models import Profile from apps.home.mixins import DashboardLoginRequiredMixin # Exections from django.db.utils import IntegrityError # class UserDetailView(DashboardLoginRequiredMixin, DetailView): # model = User # template_name = 'usuarios/user_detail.html' # def get_success_url(self): # return reverse("dashboard") def loginView(request): nit = name_company = '' if request.method == 'POST': email = request.POST['email'] password = request.POST['<PASSWORD>'] username = User.objects.get(email=email.lower()).username user = authenticate(request, username=username, password=<PASSWORD>) profile_obj = Profile.objects.get(user=user.id) nit = profile_obj.nit if profile_obj else nit name_company = profile_obj.name_company if profile_obj else name_company if user: login(request, user) return redirect('dashboard') else: return render(request, 'users/login.html', {'error':'Usuario o Password incorrectos'}) return render(request, 'users/login.html') def logoutView(request): logout(request) return redirect('login') # def signupView(request): # if request.method == 'POST': # email = request.POST['email'] # password = request.POST['<PASSWORD>'] # password_confirmation = request.POST['password_confirmation'] # if password != password_confirmation: # return render(request, 'users/signup.html', {'error':'Password no coinciden'}) # try: # user = User.objects.create_user(email=email, password=<PASSWORD>) # except IntegrityError: # return render(request, 'users/signup.html', {'error':'Usuario ya existe'}) # user.first_name = request.POST['first_name'] # user.last_name = request.POST['last_name'] # user.email = request.POST['email'] # user.save() # perfil = Perfil(usuraio=user) # perfil.save() # return redirect('login') # return render(request, 'users/signup.html') <file_sep>from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin class DashboardLoginRequiredMixin(LoginRequiredMixin): login_url = reverse_lazy('login')<file_sep># -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals ROL_USER = ( ('medico','Medico'), ('dispensador','Dispensador'), ) # addressing_date = "https://tablas.sispro.gov.co/WSSUMMIPRESNOPBS/api/DireccionamientoXFecha/" addressing_date = "https://apimipres.herokuapp.com/api/addressdate/" # programming = "https://apimipres.herokuapp.com/api/programming/" programming = "http://127.0.0.1:5500/api/programming/" # addressing_date = "https://apimipres.herokuapp.com/api/addressprescription/" # addressing_date = "https://apimipres.herokuapp.com/api/addressdocument/"<file_sep>"""Modelo Usuarios""" # Django from django.db import models from django.contrib.auth.models import User from apps.core import choices class Profile(models.Model): """Modelo Perfil""" user = models.OneToOneField(User, on_delete=models.PROTECT) name_company = models.CharField(max_length=80, default='') nit = models.CharField(max_length=20, default='') token = models.CharField(max_length=32, default='') address = models.CharField(blank=True, max_length=100) phone = models.CharField(blank=True, max_length=20) rol = models.CharField(max_length=20, blank=False, choices=choices.ROL_USER) date_create = models.DateTimeField(auto_now_add=True) date_modify = models.DateField(auto_now=True) def __str__(self): return self.name_company <file_sep>from django.contrib import admin from apps.users.models import Profile admin.site.register(Profile)
d89249bbea81f789b51df4eea142befbae142300
[ "JavaScript", "Python", "Text", "HTML" ]
11
HTML
jairnet/iris_project
2d155a997959b973ecdee2d084571f2328c3f5ab
e764a2ef27f86c8393921d1164184c9729f2aa52
refs/heads/master
<repo_name>gracl/ProgrammingAssignment2<file_sep>/cachematrix.R ## Put comments here that give an overall description of what your ## functions do ## This function creates a special "matrix" object that can cache its inverse makeCacheMatrix <- function(x = matrix()) { # Create matrix object, initialize to NULL i <- NULL # Define functions that to operate on the cache matrix: # Set matrix value set <- function(y) { x <<- y i <<- NULL } # Get matrix value get <- function() x # Set inverse value setinverse <- function(inverse) i <<- inverse # Get inverse value getinverse <- function() i # List containing all functions list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } ## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. ## If the inverse has already been calculated (and the matrix has not changed), then the cachesolve should retrieve the inverse from the cache cacheSolve <- function(x, ...) { # Retrieve inverse i i <- x$getinverse() # If i is not null, print that it was cached and return value if(!is.null(i)) { message("Retrieving from cache") return(i) } # Get the matrix and compute the inverse data <- x$get() i <- solve(data, ...) # Cache the inverse for the matrix x$setinverse(i) # Return a matrix that is the inverse of 'x' i }
e7f19db9a732ac3709021b1674f7aacedb44fe2a
[ "R" ]
1
R
gracl/ProgrammingAssignment2
9cef954d8c714ffce4aa4e5f58f91a6835c4c352
45775cb2907fa8b9618b39add59362c05d0388ae
refs/heads/master
<repo_name>cadyherron/assignment_crud<file_sep>/app/controllers/cruds_controller.rb class CrudsController < ApplicationController def index @cruds = Crud.all end def new @crud = Crud.new end def create @crud = Crud.new(crud_params) @crud.save flash[:success] = "New CRUD #{@crud.title} has been crud-ed!" redirect_to crud_path(@crud) end def show @crud = Crud.find(params[:id]) end def edit @crud = Crud.find(params[:id]) end def update @crud = Crud.find(params[:id]) @crud.update(crud_params) flash[:success] = "New CRUD #{@crud.title} has been saved!" redirect_to crud_path(@crud) end def destroy @crud = Crud.find(params[:id]) @crud.destroy flash[:success] = "CRUD #{@crud.title} has been deleted!" redirect_to cruds_path end private def crud_params params.require(:crud).permit(:title,:body) end end
073ee2c9e73bb1063a302cd84df879b1a9db540d
[ "Ruby" ]
1
Ruby
cadyherron/assignment_crud
325f8f610d2aca019fdc6b045c9cc9187a2ce243
c8b873ef1f4509f59158d5c2c210655da5b22518
refs/heads/main
<repo_name>dave-ready/A-OneEmployeeDirectory<file_sep>/src/components/DataTable/index.js import React, { useState, useEffect } from "react"; import "./style.css"; import App from "../../App"; //import API from "../../utils/API"; <App />; function DataTable(props) { return ( <> {props.employees .filter((response) => { if (!props.searchTerm) { return response; }else if (response.name.first.toLowerCase().includes(props.searchTerm.toLowerCase())) { return response } }) .map((response) => ( <div className="dataTable"> <div className="img-container"> <img id="pic" alt={response.name.first} src={response.picture.large} /> <p id="info"> {" "} {response.name.first} {response.name.last}{" "} </p> <p id="email">{response.email}</p> </div> </div> ))} </> ); } export default DataTable;<file_sep>/src/utils/API.js import axios from "axios"; export default { employeeSearch: function() { console.log("Queried the API!") return axios.get("https://randomuser.me/api/?exc=gender,dob,cell,nat&results=30"); } }; // function employeeSearch() { // console.log("Queried the API!") // return axios.get("https://randomuser.me/api/?exc=gender,dob,cell,nat&results=30"); // }; //export default { //if doesn't work wrap in here //}; //export default employeeSearch(); <file_sep>/src/App.js import React, { useEffect, useState } from "react"; import DataTable from "./components/DataTable"; import Container from "./components/Container"; import Header from "./components/Header"; import Navbar from "./components/Navbar"; import API from "./utils/API"; function App (){ const [employeeState, setEmployeeState] = useState([]); useEffect(function () { API.employeeSearch().then((result) => { console.log(result.data.results); setEmployeeState(result.data.results); console.log(employeeState) }); }, []); const [ searchTerm, setSearchTerm ] = useState(""); const [ sorted, setSorted] = useState(false); const [ data, setEmployees ] = useState([]); function handleSearchTerm(event) { setSearchTerm(event.target.value) } function handleSortByName() { if (!sorted) { setEmployees(employeeState.sort((a, b) => (a.name.first > b.name.first) ? 1 : -1)); setSorted(true); } else { setEmployees(employeeState.sort((a, b) => (a.name.first > b.name.first) ? -1 : 1)); setSorted(false); } } return ( <Container> <Navbar handleSearchTerm={handleSearchTerm} searchTerm={searchTerm} handleSortByName={handleSortByName} /> <Header /> <DataTable searchTerm={searchTerm} employees={employeeState}/> </Container> ); } export default App; //import logo from './logo.svg'; //import './App.css'; //function App() { // return ( // <div className="App"> // <header className="App-header"> // <img src={logo} className="App-logo" alt="logo" /> // <p> // Edit <code>src/App.js</code> and save to reload. // </p> // <a // className="App-link" // href="https://reactjs.org" // target="_blank" // rel="noopener noreferrer" // > // Learn React // </a> // </header> // </div> // ); //} // //export default App; <file_sep>/README.md ## Apache 2.0<img scr="https://opensource.org/licenses/Apache-2.0"> [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)] # **A-ONE EMPLOYEE DIRECTORY** ## Table of Contents - [Description](#description) - [User Story](#usage) - [Technologies](#technologies) - [Installation](#installation) - [Deployed App](#deployedApp) ## Description For this assignment, I created an Employee Directory using React ## User Story As a user, I want to be able to view my entire employee directory at once so that I have quick access to their information. ## Technologies Javascript, CSS, React, ESlint, Axios ## Installation npm install ## Deployed App https://dave-ready.github.io/A-OneEmployeeDirectory/ ## Github Repository https://github.com/dave-ready/A-OneEmployeeDirectory ## Contact - Github Username: https://github.com/dave-ready - E-mail: <EMAIL>
e3dc3f66396596099f6d2ca167aecfec21e123e3
[ "JavaScript", "Markdown" ]
4
JavaScript
dave-ready/A-OneEmployeeDirectory
9f780585f95edc0cf4bafa3e2476662efec640d1
0dd77b6f49eeba733da85add4599776383e0d739
refs/heads/master
<repo_name>rasterradio/GGJ2020<file_sep>/Assets/Scripts/flashSprite.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class flashSprite : MonoBehaviour { SpriteRenderer spriteRenderer; void Start() { spriteRenderer = GetComponent<SpriteRenderer>(); } public void flash() { StartCoroutine("showHitFlash"); } IEnumerator showHitFlash() { spriteRenderer.material.shader = Shader.Find("PaintWhite"); yield return new WaitForSeconds(0.15f); spriteRenderer.material.shader = Shader.Find("Sprites/Default"); } } <file_sep>/README.md # GGJ2020 GameJam Goals ============= The goals: 1. Learn from the experience 2. Build a prototype game GameJam Prep List ================= Decide on your tools -------------------- When you have to build a game in <3 days, it is very hard to make a prototype game while learning new tools. Build your own tools -------------------- Game Engines have come a long way in the past 20 years. Software builds on software. Take your knowledge of game technologies, and look for gaps in your game engine's toolset. Implement what you think would be most useful for speeding or simplifying the game development process. Example: Unity Engine doesn't come with Steering behaviours built in. Perhaps build your own Steering AI for use in Unity. Be Prepared for Paper Prototyping --------------------------------- Bring the Following 1. Scissors 2. Colored Markers 3. Lots of Paper 4. Pencil 5. Eraser GameJam Group Prep ================== Agree on a Game Engine ---------------------- A game engine is where all the resources come together to produce your game. Almost all participants will want to have the same version of the game engine to encourage easy merging of resources. Share your Tools ---------------- Share what tools you intend to use with the group to avoid incompatabilities. This also serves as a way for group members to learn about new and useful technologies that they are not using. *Note: Do not let new tools distract you from the making of your game <file_sep>/Assets/Scripts/player/playerKeyMovement.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class playerKeyMovement : MonoBehaviour { Rigidbody2D rb2d; float horizDir; float vertDir; float diagonalLimiter = 0.7f; public float runSpeed = 20.0f; void Start() { rb2d = GetComponent<Rigidbody2D>(); } void Update() { getInput(); } void FixedUpdate() { calcSpeed(); } void getInput() { horizDir = Input.GetAxisRaw("Horizontal"); vertDir = Input.GetAxisRaw("Vertical"); } void calcSpeed() { if (horizDir != 0 && vertDir != 0) // Diagonal movement { horizDir *= diagonalLimiter; vertDir *= diagonalLimiter; } rb2d.velocity = new Vector2(horizDir * runSpeed, vertDir * runSpeed); } }
25dc05aafe29ac61dad5ad895a4fa890c8b58050
[ "Markdown", "C#" ]
3
C#
rasterradio/GGJ2020
24cb66706b99c9658dd73ff3b6b0df8c73e01a5d
3e28aaa44fde6ad82fdeeee20cdc5998d6553266
refs/heads/master
<repo_name>tttthemanCorp/designmart<file_sep>/themes/customsite/template.php <?php /** * @file * This file is empty by default because the base theme chain (Alpha & Omega) provides * all the basic functionality. However, in case you wish to customize the output that Drupal * generates through Alpha & Omega this file is a good place to do so. * * Alpha comes with a neat solution for keeping this file as clean as possible while the code * for your subtheme grows. Please read the README.txt in the /preprocess and /process subfolders * for more information on this topic. */ function customsite_form_alter(&$form, &$form_state, $form_id) { switch($form_id) { /** * Make some adjustments to the login form to use HTML5 Placeholder values. * They can be easily changed as they are wrapped in the t() function * or you can simply copy this function to your sub theme and change the values */ case 'user_login_block': $form['name']['#attributes']['placeholder'] = t('Username…'); $form['pass']['#attributes']['placeholder'] = t('Password...'); break; case 'search_block_form': $form['search_block_form']['#attributes']['placeholder'] = t('Search…'); break; } } function customsite_preprocess_node(&$vars) { /** * if user pictures are enabled on nodes, inject them with the body field */ if(isset($vars['user_picture']) && isset($vars['content']['body'][0]['#markup']) && !$vars['teaser']) { $vars['content']['body'][0]['#markup'] = $vars['user_picture'] . $vars['content']['body'][0]['#markup']; } }<file_sep>/themes/customsite/js/customsite.js /** * @todo */ (function($) { /** * This is needed for a little extra flexibility in defining our default active menu item * if Drupal isn't by default. If nothing is labeled as active, then we'll make the first link * active (which is usually the home link */ Drupal.behaviors.customsiteActiveMenu = { attach: function (context) { var activeMenu = $('nav ul.main-menu li.active, nav ul.main-menu li.active-trail').size(); console.log(activeMenu); if (activeMenu == '0') { $('nav ul.main-menu li:first-child').addClass('active').children('a:first-child').addClass('active'); } } }; })(jQuery);<file_sep>/README.md designmart ========== designmart site in Drupal
a197b4e651ef4b25ee6daa450b53fa9171f8195b
[ "JavaScript", "Markdown", "PHP" ]
3
PHP
tttthemanCorp/designmart
7a8ebf52024a1884fc5a1f0085a30a046e56cc6a
1345038290dd6d6b3f7572e50c10ee6d37951185
refs/heads/master
<repo_name>susenfeng/workDemo<file_sep>/nginfinitiesScroll/app.js angular.module('app',['infinite-scroll','$scope']) .controller('MainCtrl', MainCtrl); function MainCtrl(infinite-scroll,$scope){ console.log($scope) console.log(111111111111) }<file_sep>/README.md # workDemo ## 1:二维码生成标签 ``` <qrcode data="{{url}}" style="height: 100%;width: 100%" size="80" version="10"></qrcode> ``` ----------------------------------------------------------------------------------------- ## 2:移动端1px分割线制作 <pre> .line { //横线 width: 1px; -webkit-transform: scaleY(0.5); -webkit-transform-origin: 0 0; overflow: hidden; } .line { //竖线 width: 1px; height: 100px; background: #d5d5d5; -webkit-transform: scaleX(0.5); -webkit-transform-origin: 0 0; overflow: hidden; } </pre> -------------------------------------------------------------------------------------- ## 3:img与外层div之间缝隙问题 ### 解决方法基本是四种: 1.将img设置为block; 这个基本可以解决img和div下方的缝隙问题。 2.设置img的竖直对齐方式 img{vertical-align:bottom;} 3.设置父div的font-size:0 4.设置外层的div的line-height:0 #### 推荐使用第一种方式。 --------------------------------------------------------------------------------------- ## 4:多行溢出显示省略号 ``` .comment_inner{ width: 200px; word-break: break-all; text-overflow: ellipsis; display: -webkit-box; /** 对象作为伸缩盒子模型显示 **/ -webkit-box-orient: vertical; /** 设置或检索伸缩盒对象的子元素的排列方式 **/ -webkit-line-clamp: 3; /** 显示的行数 **/ overflow: hidden; /** 隐藏超出的内容 **/ } ``` ### 单行 ``` overflow: hidden; text-overflow:ellipsis; white-space: nowrap; 多行 display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; ``` ## 5:IOS中使用网页时input去除默认样式的两个属性   参考 : [http://blog.csdn.net/zhang_red/article/details/44594395](http://blog.csdn.net/zhang_red/article/details/44594395) [http://www.w3cplus.com/css3/changing-appearance-of-element-with-css3.html](http://www.w3cplus.com/css3/changing-appearance-of-element-with-css3.html) [http://www.w3cplus.com/content/css3-box-shadow](http://www.w3cplus.com/content/css3-box-shadow) ``` -webkit-appearance :none ; -webkit-box-shadow:none; ``` ## 6:不定宽制作等高盒子(div) ``` &:before{ content: ''; display: inline-block;          // display: inline-table; padding-top: 100%; } ``` ## 7:正则 ``` 提取信息中的网络链接:(h|H)(r|R)(e|E)(f|F) *= *('|")?(\w|\\|\/|\.)+('|"| *|>)? 提取信息中的邮件地址:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* 提取信息中的图片链接:(s|S)(r|R)(c|C) *= *('|")?(\w|\\|\/|\.)+('|"| *|>)? 提取信息中的IP地址:(\d+)\.(\d+)\.(\d+)\.(\d+) 提取信息中的中国电话号码(包括移动和固定电话):(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14} 提取信息中的中国邮政编码:[1-9]{1}(\d+){5} 提取信息中的中国身份证号码:\d{18}|\d{15} 提取信息中的整数:\d+ 提取信息中的浮点数(即小数):(-?\d*)\.?\d+ 提取信息中的任何数字 :(-?\d*)(\.\d+)? 提取信息中的中文字符串:[\u4e00-\u9fa5]* 提取信息中的双字节字符串 (汉字):[^\x00-\xff]* //身份证正则表达式(15位) isIDCard1=/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/; //身份证正则表达式(18位) isIDCard2=/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/; 身份证正则合并:(^\d{15}$)|(^\d{17}([0-9]|X)$) 一、校验数字的表达式 1 数字:^[0-9]*$ 2 n位的数字:^\d{n}$ 3 至少n位的数字:^\d{n,}$ 4 m-n位的数字:^\d{m,n}$ 5 零和非零开头的数字:^(0|[1-9][0-9]*)$ 6 非零开头的最多带两位小数的数字:^([1-9][0-9]*)+(.[0-9]{1,2})?$ 7 带1-2位小数的正数或负数:^(\-)?\d+(\.\d{1,2})?$ 8 正数、负数、和小数:^(\-|\+)?\d+(\.\d+)?$ 9 有两位小数的正实数:^[0-9]+(.[0-9]{2})?$ 10 有1~3位小数的正实数:^[0-9]+(.[0-9]{1,3})?$ 11 非零的正整数:^[1-9]\d*$ 或 ^([1-9][0-9]*){1,3}$ 或 ^\+?[1-9][0-9]*$ 12 非零的负整数:^\-[1-9][]0-9"*$ 或 ^-[1-9]\d*$ 13 非负整数:^\d+$ 或 ^[1-9]\d*|0$ 14 非正整数:^-[1-9]\d*|0$ 或 ^((-\d+)|(0+))$ 15 非负浮点数:^\d+(\.\d+)?$ 或 ^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$ 16 非正浮点数:^((-\d+(\.\d+)?)|(0+(\.0+)?))$ 或 ^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$ 17 正浮点数:^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$ 或 ^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$ 18 负浮点数:^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$ 或 ^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$ 19 浮点数:^(-?\d+)(\.\d+)?$ 或 ^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$ 二、校验字符的表达式 1 汉字:^[\u4e00-\u9fa5]{0,}$ 2 英文和数字:^[A-Za-z0-9]+$ 或 ^[A-Za-z0-9]{4,40}$ 3 长度为3-20的所有字符:^.{3,20}$ 4 由26个英文字母组成的字符串:^[A-Za-z]+$ 5 由26个大写英文字母组成的字符串:^[A-Z]+$ 6 由26个小写英文字母组成的字符串:^[a-z]+$ 7 由数字和26个英文字母组成的字符串:^[A-Za-z0-9]+$ 8 由数字、26个英文字母或者下划线组成的字符串:^\w+$ 或 ^\w{3,20}$ 9 中文、英文、数字包括下划线:^[\u4E00-\u9FA5A-Za-z0-9_]+$ 10 中文、英文、数字但不包括下划线等符号:^[\u4E00-\u9FA5A-Za-z0-9]+$ 或 ^[\u4E00-\u9FA5A-Za-z0-9]{2,20}$ 11 可以输入含有^%&',;=?$\"等字符:[^%&',;=?$\x22]+ 12 禁止输入含有~的字符:[^~\x22]+ 三、特殊需求表达式 1 Email地址:^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ 2 域名:[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.? 3 InternetURL:[a-zA-z]+://[^\s]* 或 ^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$ 4 手机号码:^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$ 5 电话号码("XXX-XXXXXXX"、"XXXX-XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX"和"XXXXXXXX):^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$ 6 国内电话号码(0511-4405222、021-87888822):\d{3}-\d{8}|\d{4}-\d{7} 7 身份证号(15位、18位数字):^\d{15}|\d{18}$ 8 短身份证号码(数字、字母x结尾):^([0-9]){7,18}(x|X)?$ 或 ^\d{8,18}|[0-9x]{8,18}|[0-9X]{8,18}?$ 9 帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$ 10 密码(以字母开头,长度在6~18之间,只能包含字母、数字和下划线):^[a-zA-Z]\w{5,17}$ 11 强密码(必须包含大小写字母和数字的组合,不能使用特殊字符,长度在8-10之间):^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$ 12 日期格式:^\d{4}-\d{1,2}-\d{1,2} 13 一年的12个月(01~09和1~12):^(0?[1-9]|1[0-2])$ 14 一个月的31天(01~09和1~31):^((0?[1-9])|((1|2)[0-9])|30|31)$ 15 钱的输入格式: 16 1.有四种钱的表示形式我们可以接受:"10000.00" 和 "10,000.00", 和没有 "分" 的 "10000" 和 "10,000":^[1-9][0-9]*$ 17 2.这表示任意一个不以0开头的数字,但是,这也意味着一个字符"0"不通过,所以我们采用下面的形式:^(0|[1-9][0-9]*)$ 18 3.一个0或者一个不以0开头的数字.我们还可以允许开头有一个负号:^(0|-?[1-9][0-9]*)$ 19 4.这表示一个0或者一个可能为负的开头不为0的数字.让用户以0开头好了.把负号的也去掉,因为钱总不能是负的吧.下面我们要加的是说明可能的小数部分:^[0-9]+(.[0-9]+)?$ 20 5.必须说明的是,小数点后面至少应该有1位数,所以"10."是不通过的,但是 "10" 和 "10.2" 是通过的:^[0-9]+(.[0-9]{2})?$ 21 6.这样我们规定小数点后面必须有两位,如果你认为太苛刻了,可以这样:^[0-9]+(.[0-9]{1,2})?$ 22 7.这样就允许用户只写一位小数.下面我们该考虑数字中的逗号了,我们可以这样:^[0-9]{1,3}(,[0-9]{3})*(.[0-9]{1,2})?$ 23 8.1到3个数字,后面跟着任意个 逗号+3个数字,逗号成为可选,而不是必须:^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,2})?$ 24 备注:这就是最终结果了,别忘了"+"可以用"*"替代如果你觉得空字符串也可以接受的话(奇怪,为什么?)最后,别忘了在用函数时去掉去掉那个反斜杠,一般的错误都在这里 25 xml文件:^([a-zA-Z]+-?)+[a-zA-Z0-9]+\\.[x|X][m|M][l|L]$ 26 中文字符的正则表达式:[\u4e00-\u9fa5] 27 双字节字符:[^\x00-\xff] (包括汉字在内,可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)) 28 空白行的正则表达式:\n\s*\r (可以用来删除空白行) 29 HTML标记的正则表达式:<(\S*?)[^>]*>.*?</\1>|<.*? /> (网上流传的版本太糟糕,上面这个也仅仅能部分,对于复杂的嵌套标记依旧无能为力) 30 首尾空白字符的正则表达式:^\s*|\s*$或(^\s*)|(\s*$) (可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式) 31 腾讯QQ号:[1-9][0-9]{4,} (腾讯QQ号从10000开始) 32 中国邮政编码:[1-9]\d{5}(?!\d) (中国邮政编码为6位数字) 33 IP地址:\d+\.\d+\.\d+\.\d+ (提取IP地址时有用) 34 IP地址:((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)) //手机号正则 function checkPhone(){ var phone = document.getElementById('phone').value; if(!(/^1[34578]\d{9}$/.test(phone))){ alert("手机号码有误,请重填"); return false; } } ``` ## 8:行高,字体大小,盒子高度 [详解line-height](http://www.jianshu.com/p/15dcaa64554f) [字体大小,行高,高度](http://blog.csdn.net/qq8427003/article/details/18980849) 1,font-size 没有设置值时,各浏览器的默认值基本都为16px。 如果设置font-family:"宋体",那么都为16px,如果不设置font-family,IE下中文为16px 英文为17px。主要受了字体的影响。 2,如果font-size:12px,line-height不设置,height不设置。 则有:line-height = font-size + 2px = 14px height = line-height = 14px; 3,如果font-size:12px,line-height:12px,会出现上面所述IE6bug。 4,如果font-size:14px,line-height:12px,height不设置 则有:font-size:14px,line-height:12px;,height:12px。 总结:1,字体大小会影响行高,及行高=字体大小+2px(前提是行高不设置值,如果设置值,则为设置的值)。 2,但是行高不能影响字体大小。高度也不能影响字体大小(见下面例子,很重要)。 3,行高会影响高度,行高等于高度(如果高度不设置)。 ## 9:G2 G6 F2 [https://antv.alipay.com/zh-cn/index.html](https://antv.alipay.com/zh-cn/index.html) ----------------------------------------------------------------------------------------------------- # 小问题 ## 问题1 * 此问题与数组相关 * 1:了解素组相关方法 * 此问题针对那些会返回一个新数组不改变原数组的数组方法 * 此问题用来说明数组元素是字符串和数字 与 数组对象是对象的区别 例如:[1,2,3] 与 [{num:1},{num:2},{num:3}] * 本例子使用了slice()方法做示例 * slice()方法:可从已有的数组中返回选定的元素。返回值:返回一个新的数组,包含从 start 到 end (不包括该元素)的 arrayObject 中的元素。 * 说明:请注意,该方法并不会修改数组,而是返回一个子数组。如果想删除数组中的一段元素,应该使用方法 Array.splice()。 * (数组说明来自W3C标准 http://www.w3school.com.cn/jsref/jsref_slice_array.asp) ``` var arr1 = [1,2,3,4]; var arr2 = [{num:1},{num:2},{num:3},{num:4}]; var arrSlice = function(arr){ var newArr = arr.slice(1,3) console.log('newArr===',newArr); console.log('oldArr===',arr); newArr[0] = 55555; console.log('newArr-last===',newArr); console.log('oldArr-last===',arr); } arrSlice(arr1); var arrSlice2 = function(arr){ var newArr = arr.slice(1,3) console.log('newArr2===',newArr); console.log('oldArr2===',arr); newArr[0].num = 55555; console.log('newArr2-last===',newArr); console.log('oldArr2-last===',arr); } arrSlice2(arr2); ``` 问题所在: 从slice()定义上看出获取的新数组newArr是一个新数组不会修改老数组 从两个方法输出对比;都是通过slice()方法获取的新数组newArr然后对newArr进行操作,为什么操作后 arr1的原数组未发生改变( console.log('oldArr-last===',arr)处看出) 而arr2的原数组发生了改变(console.log('oldArr2-last===',arr)处看出) 涉及主要知识点js数组,对象,对象克隆,slice()方法 (注:本人认为此处可以用后台语言中的对象指针和对象地址来解释更容易理解) ## 问题2 ``` i=i++;这句代码不会改变i的值 //相当与var temp = i;i=i+1;i=temp; ``` <file_sep>/DataTime/app.js angular.module('ui.bootstrap.demo', []); angular.module('ui.bootstrap.demo').controller('PaginationDemoCtrl', function ($scope, $log) { // 时间控件 $('.dateTime').datepicker({ format: "yyyy-mm-dd", todayBtn: "linked", language: "zh-CN", orientation: "auto", autoclose: true }); });
43f6803b783faa2f6d92b19c3843d287515beb8e
[ "JavaScript", "Markdown" ]
3
JavaScript
susenfeng/workDemo
64ee97d3ab987c4e590a3f6f92c2778193eda6e1
5596d871dc09e4fbf9e512dab8ff4eb1993b98af
refs/heads/main
<file_sep>import fetch from 'node-fetch'; // import * as fs from 'fs'; async function main() { let traitsData = {} for (let i = 3585; i < 3586; i++) { const result = await fetch(`https://ipfs.io/ipfs/QmQMNdQS1UZkerbM429knJPTCNLV5zTfpmiEunKd4rYsZ3/${i}`, { "credentials": "omit", "headers": { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0", "Accept": "application/json, text/plain, */*", "Accept-Language": "en-US,en;q=0.5", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "cross-site" }, "referrer": "https://moonninjas.com/", "method": "GET", "mode": "cors" }); const data = await result.text(); console.log(data); traitsData[i] = data } // fs.writeFile ("output.json", JSON.stringify(traitsData), 'utf8', function(err) { // if (err) throw err; // console.log('complete'); // } // ); console.log(traitsData) } main().catch(console.error); <file_sep>import './App.css'; import React from 'react'; const listing = require('./rarity-data.json'); function Rarity(data){ data= data.data; return ( <div className='grid-flow'> {listing && listing.map(((item, index) => ( <div key={index} className="post"> <a><img src={ data[item].image? `https://ipfs.io/ipfs/${data[item].image.split('//').pop()}` : null } className="App-logo" alt="logo" /></a> <h3>{`${data[item].name}`}</h3> {data[item].number == '1273' || data[item].number == '1274' ? <h4>Rarity: {data[item].rarity}</h4> : <h4>Rarity: : {data[item].rarity.toFixed(5)}</h4>} <h4>Rank: {data[item].rank? data[item].rank : null}</h4> </div> ))) } </div> ); } export default Rarity;<file_sep>Check Rarity at https://rajdeep7singh.github.io/MoonNinja-Rarity/<file_sep>const stats = require('./stats.json'); function rarityCalculation(ninja){ let attributes = ninja.attributes; let i = 0; let rarity = 1; let trait_count = null; for (i = 0; i < attributes.length; i++){ trait_count = stats[attributes[i].trait_type][attributes[i].value] rarity *= trait_count } return rarity*1000000 } export default rarityCalculation;<file_sep>import './App.css'; import React, { useState } from 'react'; import Rarity from './rarity' const data = require('./output.json'); function App() { const id = window.location.href.split('id=').pop(); const ninja = data[id]; const [show, setShow] = useState(false); const rarity = () => { setShow(!show) } if (!ninja) { return ( <div className="App"> <header className="App-header"> <a rel="noreferrer" target="_blank" href='https://moonninjas.com/nft/1834'><img src="https://ipfs.io/ipfs/QmSeBuEUScRgvGWCPpQbC8KyddujLkLXsM7BgapiSoZbwP/1834.png" className="App-logo" alt="logo" /></a> <p>Check Rarity of Moonninja</p> <form className='form' method='get'> <input name='id' type='text' placeholder='123' /> <input type='submit' value='Search'/> <button type='button' onClick={rarity}>Rarity wise list</button> </form><br/> <div>Buy me a coffee: <span className='address'>0x255885BD80B534e72Fc4ac9989C2351249EC5f89</span></div><br/> <div>I am not associated with the <a rel="noreferrer" target="_blank" href="https://moonninja.com/">MOONNINJA</a> team.</div><br/> <div>Made with &#9829; by <a rel="noreferrer" target="_blank" href='https://twitter.com/sklul7'>@sklul7</a></div> {show? <Rarity data={data}></Rarity> : null} </header> </div> ); } const imageUrl = `https://ipfs.io/ipfs/${ninja.image.split('//').pop()}` console.log(imageUrl); return ( <div className="App"> <header className="App-header"> <img src={imageUrl} className="App-logo" alt="nft" /><br /> <div>{ninja.name}</div><br/> <div>Traits: {ninja.attributes.length}</div><br/> <div className='attributes'> {ninja.attributes.map(attribute => <div className='attribute' key={attribute.value}> <span className='percentage'>{attribute.trait_type}:{attribute.value}</span> </div>)} </div><br/> {ninja.number == '1273' || ninja.number == '1274'? <div>Rarity: {ninja.rarity}</div> : <div>Rarity: {ninja.rarity.toFixed(5)} (Lower the rarer)</div> } <div class='bold'>Rank: {ninja.rank}/4269</div> <div>Check another <a href="/">MOONNINJA</a></div><br/> <div>Buy me a coffee: <span className='address'>0x255885BD80B534e72Fc4ac9989C2351249EC5f89</span></div><br/> <div>I am not associated with the <a rel="noreferrer" target="_blank" href="https://moonninja.com/">MOONNINJA</a> team.</div><br/> <div>Made with &#9829; by <a rel="noreferrer" target="_blank" href='https://twitter.com/sklul7'>@sklul7</a></div> </header> </div> ); } export default App;
3e034dbb78b522d333640ff44fd4eb319dbe498d
[ "JavaScript", "Markdown" ]
5
JavaScript
rajdeep7Singh/moonninja-rarity
cebc9968ea7d96312dc9c84dbff51cce03efc1b1
d74df12b1ad6ecfd87939da6d1e99376b581bf79
refs/heads/master
<file_sep>package ee.itcollege.taltechcars.repository.custom; import ee.itcollege.taltechcars.repository.CarRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CarCustomRepositoryImplTest { @Autowired private CarRepository carRepository; @Test public void findCarByModelNrAndYearOlder() { carRepository.findCarByParams("123", 123, null); } }<file_sep>spring.datasource.url=jdbc:h2:~/test;AUTO_SERVER=TRUE spring.datasource.username=test spring.datasource.password=<PASSWORD> spring.jpa.database-platform=org.hibernate.dialect.H2Dialect<file_sep>package ee.itcollege.taltechcars.controller; import ee.itcollege.taltechcars.model.Car; import ee.itcollege.taltechcars.service.CarService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.List; @RestController @RequestMapping("/car") public class CarController { public static final String URL = "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22"; @Autowired private CarService carService; @Autowired private RestTemplate restTemplate; @GetMapping public List<Car> findAll( @RequestParam(value = "modelNr", required = false) String modelNr, @RequestParam(value = "yearOlder", required = false) Integer yearOlder, @RequestParam(value = "available", required = false) Boolean available ) { ResponseEntity<Obj> forEntity = restTemplate.getForEntity(URL, Obj.class); return carService.findAll(modelNr, yearOlder, available); } @GetMapping("{id}") public Car findOne(@PathVariable Long id) { return carService.findOne(id); } @PostMapping public Car save(@RequestBody Car car) { return carService.save(car); } @PutMapping("{id}") public Car update(@RequestBody Car car, @PathVariable Long id) { return carService.update(car, id); } @DeleteMapping("{id}") public void delete(@PathVariable Long id) { carService.delete(id); } } <file_sep>package ee.itcollege.taltechcars.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class NotificationManager { @Autowired private LeaseService leaseService; @Scheduled(fixedDelay = 1000) public void scheduleFixedDelayTask() { //List<Lease> leases = leaseService.findAllCarsOverdue(); //TalTechNotification notification = new TalTechNotification(); //notification.message("lala"); //notification.car(car) System.out.println( "Fixed delay task - " + System.currentTimeMillis() / 1000); } } <file_sep>package ee.itcollege.taltechcars.repository.custom; import ee.itcollege.taltechcars.model.Car; import org.apache.commons.lang3.StringUtils; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import java.util.List; import static org.apache.commons.lang3.StringUtils.*; public class CarCustomRepositoryImpl implements CarCustomRepository { @PersistenceContext private EntityManager entityManager; @Override public List<Car> findCarByParams(String modelNr, Integer yearOlder, Boolean available) { Query query = entityManager.createNativeQuery("" + "SELECT *\n" + "FROM CAR \n" + "WHERE true \n" + (isNotBlank(modelNr) ? "and lower(MODEL_NR) LIKE :modelNr \n" : "") + (yearOlder != null ? "and year > :year \n" : "") + (available != null ? "and leased = :leased \n" : "") , Car.class); if (isNotBlank(modelNr)) { query = query.setParameter("modelNr", "%" + modelNr.toLowerCase() + "%"); } if (yearOlder != null) { query = query.setParameter("year", yearOlder); } if (available != null) { query = query.setParameter("leased", !available); } return (List<Car>) query.getResultList(); } } <file_sep>package ee.itcollege.taltechcars.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.validation.constraints.NotNull; import java.time.LocalDate; @Entity public class Lease { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull @ManyToOne @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) private Car car; @ManyToOne @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) private User user; @NotNull private LocalDate startDate; @NotNull private LocalDate endDate; private LocalDate returnDate; public Lease() { } public Lease(Car car, User user, LocalDate startDate) { this.car = car; this.user = user; this.startDate = startDate; this.endDate = startDate.plusDays(7); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public LocalDate getStartDate() { return startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public LocalDate getEndDate() { return endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } public LocalDate getReturnDate() { return returnDate; } public void setReturnDate(LocalDate returnDate) { this.returnDate = returnDate; } }<file_sep>package ee.itcollege.taltechcars.service; import ee.itcollege.taltechcars.model.Car; import ee.itcollege.taltechcars.model.User; import java.time.LocalDate; public class LeaseDto { private Long id; private Car car; private User user; private LocalDate returnDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public LocalDate getReturnDate() { return returnDate; } public void setReturnDate(LocalDate returnDate) { this.returnDate = returnDate; } } <file_sep>package ee.itcollege.taltechcars.repository; import ee.itcollege.taltechcars.model.Car; import ee.itcollege.taltechcars.repository.custom.CarCustomRepository; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface CarRepository extends JpaRepository<Car, Long>, CarCustomRepository { List<Car> findByModelNrContainingIgnoreCase(String modelNr); } <file_sep>package ee.itcollege.taltechcars; import com.opencsv.CSVReader; import ee.itcollege.taltechcars.model.Car; import ee.itcollege.taltechcars.model.Lease; import ee.itcollege.taltechcars.model.User; import ee.itcollege.taltechcars.repository.CarRepository; import ee.itcollege.taltechcars.repository.LeaseRepository; import ee.itcollege.taltechcars.repository.UserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; import java.io.FileReader; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @SpringBootApplication public class TaltechCarsApplication { private static Logger logger = LoggerFactory.getLogger(TaltechCarsApplication.class); public static void main(String[] args) { SpringApplication.run(TaltechCarsApplication.class, args); } @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } @Bean public CommandLineRunner initCars(CarRepository carRepository, UserRepository userRepository, LeaseRepository leaseRepository) { return (args) -> { // save a couple of cars Car vwGolf = new Car("111111111", 1999, "VW Golf"); vwGolf.setLeased(true); Car savedVwGolf = carRepository.save(vwGolf); carRepository.save(new Car("222222222", 2008, "Audi A6")); carRepository.save(new Car("333333333", 2014, "BMW 318d")); carRepository.save(new Car("444444444", 2016, "Volvo V50")); carRepository.save(new Car("555555555", 2018, "Audi A6")); //import csv file for users logger.info("Started reading records from csv file"); List<List<String>> records = new ArrayList<>(); try (CSVReader csvReader = new CSVReader(new FileReader("./files/users.csv"))) { String[] values = null; while ((values = csvReader.readNext()) != null) { records.add(Arrays.asList(values)); } } logger.info(records.toString()); logger.info("Finished reading records"); // save a couple of students User jill = userRepository.save(new User("SweetJill14", "ICS0011")); userRepository.save(new User("Chloe123", "ICS0012")); userRepository.save(new User("KimTheDragon", "ICS0013")); userRepository.save(new User("DavidDavid", "ICS0014")); userRepository.save(new User("Mich3ll3", "ICS0015")); leaseRepository.save(new Lease(savedVwGolf, jill, LocalDate.now())); }; } } <file_sep>package ee.itcollege.taltechcars.service; import ee.itcollege.taltechcars.model.Car; import ee.itcollege.taltechcars.repository.CarRepository; import ee.itcollege.taltechcars.repository.LeaseRepository; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; import java.time.LocalDateTime; import java.util.List; import static org.springframework.http.HttpStatus.BAD_REQUEST; @Service public class CarService { @Autowired private CarRepository carRepository; @Autowired private LeaseRepository leaseRepository; @Autowired private CarValidator carValidator; public List<Car> findAll(String modelNr, Integer yearOlder, Boolean available) { if (StringUtils.isNotBlank(modelNr) || yearOlder != null || available != null) { return carRepository.findCarByParams(modelNr, yearOlder, available); } return carRepository.findAll(); } public Car findOne(Long id) { Car car = carRepository.findById(id) .orElseThrow(this::badRequest); //List<Lease> leases = leaseRepository.findByCar(car); //car.setLeases(leases); return car; } public Car save(Car car) { carValidator.validate(car); car.setCreatedAt(LocalDateTime.now()); return carRepository.save(car); } public Car update(Car car, Long id) { carValidator.validate(car); Car dbCar = findOne(id); dbCar.setModelNr(car.getModelNr()); dbCar.setRegistrationNr(car.getRegistrationNr()); dbCar.setYear(car.getYear()); dbCar.setUpdatedAt(LocalDateTime.now()); return carRepository.save(dbCar); } public void delete(Long id) { Car dbCar = findOne(id); carRepository.delete(dbCar); } private ResponseStatusException badRequest() { return new ResponseStatusException(BAD_REQUEST, "id doesnt exist"); } }
fd6166c42105c512c2aaf3be94961f096e239098
[ "Java", "INI" ]
10
Java
OlegPahhomov/taltech-cars
c5f98e43ec18a3241c76229ba7e436ccefa38b99
e536ef40df62b893783a8242cdd10b660a08ea58
refs/heads/master
<repo_name>shishir-roy/competitive-programming-master<file_sep>/Codechef/Contests/August Long Challenge 2017/P - Parity Gamev2.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string a,b; cin >> a >> b; int oa=0; for(auto i:a) if(i=='1') oa++; int ob=0; for(auto i:b) if(i=='1') ob++; if(oa>=ob) { cout << "YES"; } else if(oa%2==1) { if(oa+1>=ob) { cout << "YES"; } else { cout << "NO"; } } else { cout << "NO"; } return 0; }<file_sep>/Contest/SPC Individual Contest 04 [21-03-2017]/E - k-th divisor.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); // const clock_t begin_time = clock(); long long int n,k; cin >> n >> k; int sq=sqrt(n); vector<long long int>vt; for(int i=1;i<=sq;i++) { if(n%i==0) { vt.push_back(i); if(i!=(n/i)) vt.push_back(n/i); } } sort(vt.begin(),vt.end()); //cout << vt.size() << endl; if(vt.size()<k) cout << -1 ; else cout << vt[k-1]; // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/Marathon/Weekly Marathon #2 by DJ/A2.cpp #include<bits/stdc++.h> #define ll long long int #define pair<ll,ll> #define fs first #define sc second bool cmp(const pair<ll,pair<ll,ll> & a,const pair<ll,pair<ll,ll> & b) { return a.fs<b.fs; } int main() { int n; while(cin>>n) { ll ara[n+7]; vector< pair<ll,pair<ll,ll> > >add,sub; for(int i=0;i<n;i++) { cin >> ara[i]; } sort(ara,ara+n); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { add.push_back( { ara[i]+ara[j] , {ara[i],ara[j]} }); } } for(int i=n-1;i>=0;i--) { for(int j=0;j<n;j++) { if(ara[i]-ara[j]<0)break; sub.push_back( { ara[i]-ara[j] , {ara[i],ara[j]} }); } } sort(sub.begin(),sub.end(),cmp); for(int i=0;i<add.size();i++) { if(binary_search(sub.begin(),sun.end(),add[i].fs) ) { auto l=lower_bound(sub.begin(),sub.end(),add[i].fs)-sub.begin(); auto h=upper_bound(sub.begin(),sub.end(),add[i].fs)-sub.begin(); } } } return 0; } <file_sep>/LightOJ/1241 - Pinocchio.cpp #include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n; cin >> n; vector<int>vt; vt.push_back(2); for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back(t); } int ans=0; for(int i=1;i<=n;i++) { double t=vt[i]-vt[i-1]; if(t>0.5) ans+=ceil(t/5.0); } cout << "Case " << qq << ": " << ans << '\n'; } return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #404 (Div. 2)/b.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int n; cin >> n; vector<int>nl,nr; for(int i=0; i<n; i++) { int l,r; cin >> l >> r; nl.push_back(l); nr.push_back(r); } sort(nl.begin(),nl.end()); sort(nr.begin(),nr.end()); // DB; int m; cin >> m; vector<int>ml,mr; for(int i=0; i<m; i++) { int l,r; cin >> l >> r; ml.push_back(l); mr.push_back(r); } sort(ml.begin(),ml.end()); sort(mr.begin(),mr.end()); // cout << ml[n-1] << nr[0] << endl; int d=max(ml[m-1]-nr[0],nl[n-1]-mr[0]); if(d<=0) cout <<0; else cout << d; return 0; } /* */ <file_sep>/Marathon/Mathematics/580 Critical Mass.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int n; ll dp[100007][5]; ll rec(int ps,int cnt) { if(ps>=n) return 1; ll& ret=dp[ps][cnt]; if(cnt==2) { ret=rec(ps+1,0); } else { ret=rec(ps+1,0); ret+=rec(ps+1,cnt+1); } return ret; } int main() { while(cin >> n) { if(n==0) return 0; memset(dp,-1,sizeof dp); ll t=rec(0,0); cout << (1LL<<n) - t << endl; } return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #461 (Div. 2)/D. Robot Vacuum Cleanerv2.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 500007 ll hh[maxn]; bool cmp(string a,string b) { ll as=0,ah=0; for(char x : a) { if(x=='s')as++; else ah++; } ll bs=0,bh=0; for(char x : b) { if(x=='s')bs++; else bh++; } if(as*bh>bs*ah) return 1; else return 0; } int main() { // cout << ("s"<"h") << endl; ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); int n; cin >>n; vector<string>vt; for(int i=0;i<n;i++) { string t; cin >> t; vt.push_back(t); } sort(vt.begin(),vt.end(),cmp); string t; for(int i=0;i<n;i++) { t+=vt[i]; } // cout << t << endl; memset(hh,0,sizeof hh); ll cnt=0; for(int i=t.size()-1; i>=0; i--) { if(t[i]=='h')cnt++; hh[i]=cnt; } ll ans=0; for(int i=0;i<t.size();i++) { if(t[i]=='s') { ans+=hh[i+1]; // cout << i << " er jonno " << ans << endl; } } cout << ans; return 0; } /* 4 s ssh hs hhhs */ <file_sep>/Codeforces/Contests/Codeforces Round #427 (Div. 2)/test.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); return 0; }<file_sep>/Marathon/Weekly Marathon #3 by DJ/f.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 ll convert(int ara[],int n,int b) { ll ans=0; ll base=1; while(n--) { ans+=ara[n]*base; base*=b; } // ans+=ara[n]*base; return ans; } int main() { /* freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); */ // const clock_t begin_time = clock(); int n,a; cin >> n >> a; int aa[n+7]; for(int i=0;i<n;i++) { cin >> aa[i]; } ll ca=convert(aa,n,a); int m,b; cin >> m >> b; int bb[m+7]; for(int i=0;i<m;i++) { cin >> bb[i]; } ll cb=convert(bb,m,b); //cout << "**** " << endl; // cout << ca << " " << cb << endl; if(ca==cb)cout << "=" << endl; else if(ca<cb) cout << "<" << endl; else cout << ">" << endl; //cout << ca << " " << cb << endl; // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/Contest/Team Forming Contest 3 (08-09-2017) (2015)/C - Little Elephant and Magic Square.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int ara[5][5],sum[5]; memset(sum,0,sizeof sum); int mx=0; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { cin >> ara[i][j]; sum[i]+=ara[i][j]; } mx=max(mx,sum[i]); } while(1) { mx++; // cout << mx << endl; int t1=mx-sum[0]; int t2=mx-sum[1]; int t3=mx-sum[2]; if(t1+t2+t3==ara[0][2]+t2+ara[2][0]) { ara[0][0]=t1; ara[1][1]=t2; ara[2][2]=t3; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { cout << ara[i][j] << " "; } cout << endl; } return 0; } // if(mx==15) // break; } return 0; } <file_sep>/Codeforces/B numbers/A. ACM.cpp #include<bits/stdc++.h> using namespace std; int main() { int ara[10]; int sum=0; for(int i=0;i<6;i++) { cin >> ara[i]; sum+=ara[i]; } for(int i=0;i<6;i++) { for(int j=i+1;j<6;j++) { for(int k=j+1;k<6;k++) { if(ara[i]+ara[j]+ara[k]==sum/2 and sum%2==0) { cout << "YES" << endl; return 0; } } } } cout << "NO"; return 0; } <file_sep>/LightOJ/1235 - Coin Change (IV).cpp #include<bits/stdc++.h> using namespace std; vector<int>bam,dan; vector<int>leftall,rightall; void recl(int ps,int sum) { if(ps>=bam.size()) { leftall.push_back(sum); return; } for(int i=0;i<3;i++) { recl(ps+1,sum+bam[ps]*i); } } void recr(int ps,int sum) { if(ps>=dan.size()) { rightall.push_back(sum); return; } for(int i=0;i<3;i++) { recr(ps+1,sum+dan[ps]*i); } } int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n,k; cin >> n >> k; bam.clear(); leftall.clear(); for(int i=0;i<n/2;i++) { int t; cin >> t; bam.push_back(t); } recl(0,0); dan.clear(); rightall.clear(); for(int i=n/2;i<n;i++) { int t; cin >> t; dan.push_back(t); } recr(0,0); sort(leftall.begin(),leftall.end()); int f=0; for(int i=0;i<rightall.size();i++) { if(binary_search(leftall.begin(),leftall.end(),k-rightall[i])) { f=1; } } if(f) { cout << "Case " << qq << ": Yes" << '\n'; } else { cout << "Case " << qq << ": No" << '\n'; } } return 0; } <file_sep>/USACO/Section 1.1/Bear and Species.cpp #include<bits/stdc++.h> using namespace std; int fx[]={-1,1,0,0}; int fy[]={0,0,-1,1}; int cnt=0; int ff=1; char str[70][70]; int flag[70][70]; int n; void dfs(pair<int,int>u,char ch) { flag[u.first][u.second]=1; cnt++; for(int i=0;i<4 and ff;i++) { int tx=u.first+fx[i]; int ty=u.second+fy[i]; if(tx>=0 and tx<n and ty>=0 and ty<n and flag[tx][ty]==-1 ) { if(str[tx][ty]=='?') { dfs({tx,ty}); } else if(str[tx][ty]==ch) { ff=0; } } } } int main() { int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { cin >> n; for(int i=0;i<n;i++) { sf("%s",str[i]); } memset(flag,-1,sizeof flag); for(int i=0;i<n and ff;i++) { for(int j=0;j<n and ff;j++) { if(str[i][j]=='G') { for(int k=0;k<4;k++) { int tx=i+fx[i]; int ty=j+fy[i]; if(tx>=0 and tx<n and ty>=0 and ty<n and str[tx][ty]=='G') { ff=0; } } } } } long long ans=0; for(int i=0;i<n and ff;i++) { for(int j=0;j<n and ff;j++) { if(str[i][j]=='B') { ans=1; dfs({i,j},'P'); } else if(str[i][j]=='P') { ans=1; dfs({i,j},'B'); } } } if(!ff) { cout << 0 << '\n'; continue; } long long int one=0; long long int tr=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(str[i][j]=='B') { cnt=0; tr++; dfs({i,j},'*'); if(cnt==1) { one++; } } } } int pt[3000]; pt[0]=1; for(int i=0;i<3000;i++) { ll temp=pt[i-1]*2; temp%=1000000007; pt[i]=temp; } ans+=pt[tr]; ans%=1000000007; for(int i=1;i<=one;i++) { ans+=pt[tr-i]; ans%=1000000007; } cout << ans << '\n'; } return 0; } <file_sep>/Codeforces/Contests/Educational Codeforces Round 26/test.cpp /*#include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp>*/ #include <bits/stdc++.h> using namespace std; //using namespace __gnu_pbds; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pii; //typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ordered_set; #define FOR(i, a, b) for (int i=a; i<b; i++) #define F0R(i, a) for (int i=0; i<a; i++) #define FORd(i,a,b) for (int i = (b)-1; i >= a; i--) #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) #define mp make_pair #define pb push_back #define f first #define s second #define lb lower_bound #define ub upper_bound const int MOD = 1000000007; double PI = 4*atan(1); ll x,y; vector<ll> prim; void fill() { ll x1 = x; for (ll i = 2; i*i <= x; ++i) if (x % i == 0) { while (x % i == 0) x /= i; prim.pb(i); } if (x > 1) prim.pb(x); x = x1; } ll get(ll x, ll y) { ll ans = 0; while (y > 0) { ll g = __gcd(x,y); x /= g, y /= g; ll mx = 0; for (ll a: prim) if (x % a == 0) mx = max(mx,a*(y/a)); ans += (y-mx); y = mx; } return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> x >> y; fill(); cout << get(x,y); } <file_sep>/LightOJ/Distinct Palindromes.cpp #include <iostream> #include <vector> #include <cstdio> #include <math.h> #include <map> #include <algorithm> #define MAXL 1111 #define MODD 1000000007 #define ll long long using namespace std; int npos[27][MAXL+1]; int ppos[27][MAXL+1]; int dp[1111][1111]; int Count(int st,int en) { if (dp[st][en]!=-1) return dp[st][en]; int ans=1; for(int c=0; c<26; c++) { int p1 = npos[c][st]; int p2 = ppos[c][en]; if (p1 == -1 || p2 == -1) continue; if (p1 > p2) continue; if (p1 == p2) { ans++; continue; } ans += 1+Count(p1+1,p2-1); if (ans >= MODD) ans-=MODD; } return dp[st][en]=ans; } int main() { string S; cin>>S; int L=S.size(); for(int c=0; c<26; c++) { npos[c][L]=-1; } for(int j=L-1; j>=0; j--) { for(int c=0; c<26; c++) { if (S[j]==c+'a') npos[c][j]=j; else npos[c][j]=npos[c][j+1]; } } for(int c=0; c<26; c++) { ppos[c][0]=-1; } ppos[S[0]-'a'][0]=0; for(int j=1; j<L; j++) { for(int c=0; c<26; c++) { if (S[j]==c+'a') ppos[c][j]=j; else ppos[c][j]=ppos[c][j-1]; } } for(int i=0; i<1111; i++) for(int j=0; j<1111; j++) dp[i][j]=-1; cout << (Count(0,L-1)+MODD-1)%MODD <<endl; } <file_sep>/USACO/Section 1.2/Dual Palindromes.cpp /* ID:shishir10 LANG:C++ TASK:dualpal */ #include<bits/stdc++.h> using namespace std; string con(int num,int b) { char ara[]={'0','1','2','3','4','5','6','7','8','9','A','B'}; string str; while(num>0) { str+=ara[num%b]; num/=b; } return str; } int main() { freopen("dualpal.in","r",stdin); freopen("dualpal.out","w",stdout); int n,s; cin >> n >> s ; int cnt=0; while(1) { ++s; int c=0; for(int i=2;i<=10;i++) { string str=con(s,i); string t=str; reverse(str.begin(),str.end()); if(str==t) { c++; } if(c>=2) { cnt++; cout << s << '\n'; break; } } if(cnt==n) break; } return 0; } <file_sep>/LightOJ/1283 - Shelving Books.cpp #include<bits/stdc++.h> using namespace std; int ara[107],n; int dp[107][107][107]; int rec(int ps,int l,int r) { if(ps>n) return 0; int& ret=dp[ps][l][r]; if(ret!=-1) return ret; ret=INT_MIN; if(ara[ps]>=ara[l] && ara[ps]<=ara[r]) { ret=max(ret,1+rec(ps+1,ps,r)); ret=max(ret,1+rec(ps+1,l,ps)); } ret=max(ret,rec(ps+1,l,r)); return ret; } int main() { int tc; cin >> tc; for(int qq=1; qq<=tc; qq++) { cin >> n; for(int i=1; i<=n; i++) { cin >> ara[i]; } memset(dp,-1,sizeof dp); ara[0]=-1,ara[n+1]=1<<30; int t=rec(1,0,n+1); cout << "Case " << qq << ": " << t << endl; } return 0; } <file_sep>/Marathon/Weekly Marathon #2 by DJ/b.cpp #include<bits/stdc++.h> using namespace std; int main() { string str; vector<string>vt; while(getline(cin,str)) { vt.push_back(str); } sort(vt.begin(),vt.end()); //cout << "input sesh " << endl; for(int i=0;i<vt.size();i++) { string temp=vt[i]; for(int i=0;i<temp.size();i++) { string a=temp.substr(0,i); string b=temp.substr(i,temp.size()-1); // cout << a << " " << b << endl; if(binary_search(vt.begin(),vt.end(),a) && binary_search(vt.begin(),vt.end(),b) ) { cout << temp << '\n'; break; } } } return 0; } <file_sep>/Codeforces/Contests/8VC Venture Cup 2017 - Elimination Round/C. PolandBall and Forest.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 10007 int ara[maxn]; int id(int r) { // cout << ara[r] << ' ' << r << endl; if(ara[r]==r) return r; ara[r]=id(ara[r]); return ara[r]; } int main() { int n; cin >> n; for(int i=1 ;i<=n ;i++ ) { ara[i]=i; } int t; for(int i=1 ;i<=n ;i++ ) { sf("%d",&t); int x=id(i),y=id(t); if(x!=y) { ara[x]=y; } } // id(1); // DB; for(int i=1 ;i<=n ;i++ ) { id(i); } set<int>st; for(int i=1 ;i<=n ;i++ ) { st.insert(ara[i]); } cout << st.size() ; return 0; } /* */ <file_sep>/Codeforces/Contests/Codeforces Round 225/C. Propagating tree.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 300000 int n,m; int val[maxn]; class data { public: int ara[maxn]; int tree[maxn*5],lazy[maxn*5]; void clr() { memset(tree,0,sizeof tree); memset(lazy,0,sizeof lazy); memset(ara,0,sizeof ara); } void build(int id,int l,int r) { if(l==r) { tree[id] = val[l]; return; } int mid = (l+r)/2; build(id*2,l,mid); build(id*2+1,mid+1,r); tree[id] = tree[id*2] + tree[id*2+1]; } void shift(int id,int l,int r) { if(l != r) { tree[id*2]+=lazy[id]; tree[id*2+1]+=lazy[id]; lazy[id*2]+=lazy[id]; lazy[id*2+1]+=lazy[id]; lazy[id] = 0 ; } } void updt(int id,int l,int r,int ql,int qr,int v) { if(lazy[id]) { shift(id,l,r); } if(l>qr || r<ql) { return ; } if(l>=ql and r<=qr) { tree[id]+= v; lazy[id]+=v; return ; } int mid = (l+r)/2; updt(id*2,l,mid,ql,qr,v); updt(id*2+1,mid+1,r,ql,qr,v); tree[id] = tree[id*2] + tree[id*2+1]; } int query(int id,int l,int r,int ql,int qr) { if(lazy[id]) { shift(id,l,r); } if(l>qr || r<ql) { return 0; } if(l>=ql and r<=qr) { return tree[id]; } int mid = (l+r)/2; int a1 = query(id*2,l,mid,ql,qr); int a2 = query(id*2+1,mid+1,r,ql,qr); tree[id]= tree[id*2] + tree[id*2+1]; return a1 + a2 ; } }; data odd,even; vector<int>gr[maxn]; int lvl[maxn],bgn[maxn],ed[maxn],tim=0; void dfs(int u,int p) { tim++; lvl[u] = lvl[p] + 1; if(lvl[u]%2 == 1) { odd.ara[tim] = val[u]; } else { even.ara[tim] = val[u]; } bgn[u] = tim; for(int v : gr[u]) { if(v != p) { dfs(v,u); } } ed[u] = tim; } int main() { odd.clr(); even.clr(); sf2(n,m); for(int i=1; i<=n; i++) { sf1(val[i]); } for(int i=0; i<n-1; i++) { int u,v; sf2(u,v); gr[u].push_back(v); gr[v].push_back(u); } dfs(1,0); // for(int i=1; i<=10; i++) // { // cout << i << " --> " << odd.ara[i] << " " << even.ara[i] << endl; // } // cout << endl << endl; odd.build(1,1,tim); // cout << endl; even.build(1,1,tim); while(m--) { int typ; sf1(typ); if(typ==1) { int x,v; sf2(x,v); if(lvl[x]%2 ==1) { odd.updt(1,1,tim,bgn[x],ed[x],v); even.updt(1,1,tim,bgn[x],ed[x],-1*v); } else { odd.updt(1,1,tim,bgn[x],ed[x],-1*v); even.updt(1,1,tim,bgn[x],ed[x],v); } } else { int x; sf1(x); if(lvl[x]%2 == 1) { int ans = odd.query(1,1,tim,bgn[x],bgn[x]); pf1(ans); } else { int ans = even.query(1,1,tim,bgn[x],bgn[x]); pf1(ans); } } } return 0; } /* */ <file_sep>/Codeforces/Contests/Codeforces Round #332 (Div. 2)/A. Patrick and Shopping.cpp #include<bits/stdc++.h> using namespace std; int main() { long long int a,b,c; cin >> a >> b >> c; cout << min(min(a,b)*2+c*2,min(2*a+2*b,a+b+c)); return 0; } <file_sep>/Codeforces/B numbers/B. Average Sleep Time.cpp #include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); int n,k; cin >> n >> k; vector<int>vt(n+7); for(int i=0;i<n;i++) cin >> vt[i]; unsigned long long int t=0,cur=0; for(int x=0,y=0;y<n;y++) { if(y-x+1<k) { t+=vt[y]; } else { if(cur==0) { t+=vt[y]; cur=t; continue; } cur=cur+vt[y]-vt[x]; t+=cur; x++; } } double ans=(double)t/(double)(n-k+1); cout << setprecision(10) << ans << endl; return 0; } <file_sep>/Marathon/Mathematics/1635 Irrelevant Elements.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define MAX 1000000 ///joto porjonto sieve korte cai #define LMT 1007 /// sqrt(MAX) #define LEN 100000 ///appx number of primes #define RNG 100032 ///range for segmentflaged sieve #define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31))) #define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31))) unsigned primeflag[MAX/64+7], segmentflag[RNG/64+7], primes[LEN+7]; /* Generates all the necessary prime numbers and marks them in primeflag[]*/ void sieve() { unsigned long long int i, j, k; for(i=3; i<LMT; i+=2) if(!chkC(primeflag, i)) for(j=i*i, k=i<<1; j<MAX; j+=k) setC(primeflag, j); j=0; primes[j++]=2; for(i=3; i<MAX; i+=2) if(!chkC(primeflag, i)) primes[j++] = i; } vector< pair<int,int> > prime_factorize_of_m(ll n) { vector< pair<int,int> >factors; int sqrtn = sqrt ( n ); for ( int i = 0; i < LEN && primes[i] <= sqrtn; i++ ) { if ( n % primes[i] == 0 ) { int cnt=0; while ( n % primes[i] == 0 ) { n /= primes[i]; cnt++; } factors.push_back({primes[i],cnt}); sqrtn = sqrt ( n ); } } if ( n != 1 ) { factors.push_back({n,1}); } return factors; } int go(int n,int p) { if(n==0) return 0; int cnt=0; while(n%p==0) { n/=p; cnt++; } return cnt; } int main() { sieve(); ll n,m; while(cin >> n >> m) { map<int,int>mp; vector<int>ans; vector< pair<int,int> > pm = prime_factorize_of_m(m); for(auto it:pm) { cout << it.first << " " << it.second << endl; } cout << endl << endl; ll now=1,prev=1; for(ll r=0;r<n;r++) { int ok=1; for(int i=0;i<pm.size() and ok==1;i++) { int p=pm[i].first; int cnt=pm[i].second; int a=go(n-r,p); cout << n-r << " er moddeh " << p << " ache " << a << endl; int b=go(r,p); cout << r << " er moddeh " << p << " ache " << b << endl << endl; int t=mp[p]+a-b; /*cout << "pri " << p << " " << t << endl;*/ if(t<cnt) { ok=0; } if(t<0)t=0; mp[p]=t; } /*cout << endl;*/ if(ok) { ans.push_back(r+1); } } cout << ans.size() << endl; if(!ans.empty()) cout << ans[0]; for(int i=1;i<ans.size();i++) { cout << " " << ans[i]; } cout << endl; } return 0; } <file_sep>/Contest/ACM ICPC Dhaka Regional 2017 Online Preliminary Round Hosted by University of Asia Pacific/jv2.cpp /* author : <NAME> CSE'15 SUST */ #include<bits/stdc++.h> #define pii pair<int,int> #define tii pair<int,pair<int,int> > #define mkp make_pair #define fs first #define sc second #define pb push_back #define ppb pop_back() #define pcase(x) printf("Case %d: ",x) #define hi cout<<"hi"<<endl; #define mod 1000000007 #define inf 1000000007 #define pi acos(-1.0) #define mem(arr,x) memset((arr), (x), sizeof((arr))); #define FOR(i,x) for(int i=0;i<(x); i++) #define FOR1(i,x) for(int i = 1; i<=(x) ; i++) #define jora(a,b) make_pair(a,b) #define tora(a,b,c) jora(a,jora(b,c)) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define N 100005 #define level 26 // #define noya vector< vector<int> >(6,vector<int>(6,0)) // #define mat vector<vector<int> > // #define m 6 using namespace std; typedef long long int lint; typedef double dbl; struct PT{ double x,y; PT(){} PT(double x,double y) : x(x), y(y){} }; PT RotateCCW(PT p, double t){ return PT(p.x*cos(t) - p.y*sin(t),p.x*sin(t)+p.y*cos(t)); } inline double dis(double a,double b,double c,double d) { double x=(a-c); double y=(b-d); return x*x+y*y; } int main() { int test,case_no=1; // sf1(test); cin>>test; while(test--) { double bx,by,ax,t,w; cin>>bx>>by>>ax>>w>>t; double m = ax; PT B = RotateCCW(PT(bx,by),t*w); double a=1.0; double b=-2.0*B.x; double c=B.x*B.x+B.y*B.y-dis(bx,by,ax,0.0); double x= (-b+sqrt(b*b-4*a*c))/2.0; double x2 = (-b-sqrt(b*b-4*a*c))/2.0; if(m<0.0) x*=(-1.0); cout<<"Case "<<case_no++<<": "<<setprecision(14)<<fixed<<x<<endl; } return 0; } <file_sep>/LightOJ/1013 - Love Calculator.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 string a,b; int dp[35][35]; int l,m,siz; int lcs(int i,int j) { if(i>=l|| j>=m) return 0; int &ret=dp[i][j]; if(ret!=-1) return ret; if(a[i]==b[j]) ret=1+lcs(i+1,j+1); else { ret=max(lcs(i+1,j),lcs(i,j+1)); } return ret; } ll dpp[65][65][65]; ll rec(int i,int j,int cnt) { if(i==l && j==m) { if(cnt==siz) return 1; return 0; } else if(i==l) { if(siz==cnt+m-j) return 1; return 0; } else if(j==m) { if(siz==cnt+l-i) return 1; return 0; } ll &ret=dpp[i][j][cnt]; if(ret!=-1) return ret; if(a[i]==b[j]) ret=rec(i+1,j+1,cnt+1); else { ret=rec(i+1,j,cnt+1)+rec(i,j+1,cnt+1); } return ret; } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { cin >> a >>b; l=a.size(),m=b.size(); memset(dp,-1,sizeof dp); siz=l+m-lcs(0,0); memset(dpp,-1,sizeof dpp); ll ans=rec(0,0,0); pf("Case %d: %d %lld\n",qq,siz,ans); } return 0; } /* */ <file_sep>/Contest/2016-2017 CTU Open Contest/C - Password Hacking.cpp #include<bits/stdc++.h> using namespace std; int main() { int n; while(cin >>n) { vector<double>vt; for(int i=0;i<n;i++) { string s; double t; cin >> s >> t; vt.push_back(t); } double ans=0.0; sort(vt.rbegin(),vt.rend()); for(int i=0;i<vt.size();i++) { ans+=(vt[i]*(i+1.0)); // cout << vt[i] << " " << ans << endl; } cout << setprecision(10) << ans << endl; } return 0; } <file_sep>/Contest/Individual Practice Contest 7/H - Killing everything.c #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 int main() { int tc; cin >> tc; return 0; } /* */ <file_sep>/Novice/Marathon Week - 9 ArticulationBridgeSCC/H - Ant Hills.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 10007 int n,m,root,ti; vector<int>gh[maxn]; set<int>st; int d[maxn],parent[maxn],low[maxn]; bool visit[maxn]; void art(int u) { d[u]=ti; low[u]=ti; ti++; visit[u]=1; int child=0; for(int i=0 ;i<gh[u].size() ; i++ ) { int v=gh[u][i]; if(v==parent[u]) continue; if(visit[v]) { low[u]=min(low[u],d[v]); } else { parent[v]=u; // cout << u << " --> " << v << endl; art(v); // cout << "after call " << u << endl; child++; low[u]=min(low[u],low[v]); if(d[u]<=low[v] && u!=root) { st.insert(u); } } } if(child>1 && u==root) { st.insert(u); } } void make() { sf("%d %d",&n,&m); for(int i=0 ;i<=n ;i++ ) { gh[i].clear(); } st.clear(); int u,v; for(int i=0 ;i<m ;i++ ) { sf("%d%d",&u,&v); gh[u].push_back(v); gh[v].push_back(u); } } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { make(); // cout << gh[3][0] << gh[3][1] << gh[3][2] << endl; // DB; ti=1; root=1; memset(visit,0,sizeof visit); for(int i=1 ;i<=n ;i++ ) { if(!visit[i]) { art(i); } } // for(int i=1 ;i<=n ;i++ ) // { // cout << i << ' ' << low[i] << endl; // } // cout << *st.begin() << endl; pf("Case %d: %d\n",qq,st.size()); } return 0; } /* 2 5 4 2 1 1 3 5 4 4 1 */ <file_sep>/Contest/SPC Individual Contest 02 [18-03-2017]/H - Little Girl and Maximum XOR.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 ll func(ll n) { ll ans=1; while(n) { n>>=1; ans<<=1; } return ans; } int main() { // freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); // const clock_t begin_time = clock(); ll l,r; cin >> l >> r; ll temp=l^r; ll ans=func(temp); cout << ans-1 ; // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/Contest/Team Forming Contest 3 (08-09-2017) (2015)/H - LCM Challenge.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll unsigned long long int ll lcm(ll a,ll b) { return a/__gcd(a,b)*b; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll n,mx=0; cin >> n; ll o=1; if(n>100) { o=n-100; } // cout << o << endl; for(ll a=o;a<=n;a++) { for(ll b=o;b<=n;b++) { for(ll c=o;c<=n;c++) { ll t=lcm(a,lcm(b,c)); mx=max(mx,t); } } } // mx=max(mx,n*(n-1)*(n-2)); cout << mx << endl; return 0; } <file_sep>/Codeforces/B numbers/A. Fox and Box Accumulation.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int n,t; cin >> n; int ara[150]; memset(ara,0,sizeof ara); for(int i=0 ;i<n ;i++ ) { sf("%d",&t); ara[t]++; } int f=1; int cnt=0; // DB; while(f) { f=0; for(int i=102 ;i>=0 ;i-- ) { if(ara[i]!=0 && f==0) { f=1; } if(ara[i]>0) ara[i]--; } cnt++; } cout << cnt-1 << '\n'; // main(); return 0; } /* */ <file_sep>/LightOJ/1105 - Fi Binary Number.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 ll dp[50]; int rec(int ps) { if(ps==1) return 1; ll& ret =dp[ps]; if(ret != -1) return ret; ret=1; for(int i=1;i<=ps-2;i++) { ret+=rec(i); } return ret; } void solve(int n) { string str; int l=-1; for(int i=0;i<46;i++) { // cout << n << " *** " << dp[i] << endl; if(dp[i]>=n) { l=i; break; } } cout << "expected length of the string " << l << endl; for(int i=0;i<l and str.size()<=l ;i++) { for(int j=0;j<46;j++) { if(dp[j]>=n) { str+="10"; break; } else { n-=dp[i]; } } } cout << str << endl; } int main() { memset(dp,-1,sizeof dp); // cout << rec(45) << endl; dp[0]=0; for(int i=1;i<46;i++) { dp[i]=rec(i); } for(int i=1;i<46;i++) { dp[i]+=dp[i-1]; } cout << dp[2] << endl; ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n; cin >> n; solve(n); } return 0; } <file_sep>/Codechef/Contests/November Lunchtime 2017/L-R queries.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 int ara[maxn]; multiset<int>tree[4*maxn]; void build(int id,int l,int r) { if(l==r) { tree[id].insert(ara[l]); return; } int mid = (l+r)/2; build(id*2,l,mid); build(id*2+1,mid+1,r); tree[id].insert( tree[id*2].begin(), tree[id*2].end() ); tree[id].insert( tree[id*2+1].begin(), tree[id*2+1].end() ); } void updt(int id,int l,int r,int ql,int qr,int pval,int cval) { if(r<ql || l>qr) return ; auto it=tree[id].find(pval); tree[id].erase(it); tree[id].insert(cval); if(l==r) { return ; } int mid = (l+r)/2; updt(id*2,l,mid,ql,qr,pval,cval); updt(id*2+1,mid+1,r,ql,qr,pval,cval); } ll query(int id,int l,int r,int ql,int qr,int val) { if(r<ql || l>qr) return INT_MIN; if(l>=ql and r<=qr) { ll a=INT_MIN, b=INT_MIN; auto it=tree[id].upper_bound(val); if(it!=tree[id].end()) a= 1LL*(*it-ara[ql])*(ara[qr]-*it); if(it!=tree[id].begin()) --it, b =1LL*(*it-ara[ql])*(ara[qr]-*it); return max(a,b); } int mid= (l+r)/2; return max ( query(id*2,l,mid,ql,qr,val), query(id*2+1,mid+1,r,ql,qr,val) ); } int main() { int tc; sf1(tc); while(tc--) { for(int i=0;i<4*maxn;i++) tree[i].clear(); int n,q; sf2(n,q); for(int i=1;i<=n;i++) sf1(ara[i]); build(1,1,n); while(q--) { int type,x,y; cin >> type >> x >> y; if( type == 1) { cout << query(1,1,n,x,y,(ara[x]+ara[y])/2 ) << endl; } else { updt(1,1,n,x,x,ara[x],y); ara[x]=y; } } } return 0; } /* 1 4 3 2 1 4 3 1 1 4 2 2 3 1 1 3 */ <file_sep>/LightOJ/1079 - Just another Robbery2.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int tak[1007],sum=0,n; double dp[10007],cau[1007]; void pre() { for(int i=1;i<=sum;i++) { dp[i]=1.0; } dp[0]=0.0; for(int i=0;i<n;i++) { for(int j=sum;j>=tak[i];j--) { dp[j]=min(dp[j], dp[j-tak[i]] + (1.0-dp[j-tak[i]])*cau[i]); } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { double gp; cin >> gp >> n; sum=0; for(int i=0;i<n;i++) { cin >> tak[i] >> cau[i]; sum+=tak[i]; } pre(); int ans=0; for(int i=sum;i>=0;i--) { if(dp[i]<gp) { ans=i; break; } } cout << "Case " << qq << ": " << ans << endl; } return 0; } <file_sep>/Print/kmp.cpp #include<bits/stdc++.h> using namespace std; void compute_lps(string pat,int lps[]) { int j=0,i=1; lps[0]=0; while(i<pat.size()) { if(pat[i]==pat[j]) { lps[i]=j+1; i++,j++; } else { if(j!=0) { j=lps[j-1]; } else { lps[i]=0; i++; } } } } void KMP(string txt,string pat) { int lps[pat.size()+7]; compute_lps(pat,lps); int i=0,j=0; while(i<txt.size()) { if(txt[i]==pat[j]) { i++,j++; } if(j==pat.size()) { cout << "found " << i-j << endl; j=lps[j-1]; } else if(i<txt.size() and txt[i]!=pat[j]) { if(j!=0) { j=lps[j-1]; } else i++; } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); KMP("abcabcabcabc","abc"); return 0; } <file_sep>/Contest/Individual Practice Contest 4/I - Blue and Red.cpp #include <cstdio> #include <sstream> #include <cstdlib> #include <cctype> #include <cmath> #include <algorithm> #include <set> #include <queue> #include <stack> #include <list> #include <iostream> #include <fstream> #include <numeric> #include <string> #include <vector> #include <cstring> #include <map> #include <iterator> #include<complex> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define DB cout<<" **** "<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 207 vector<int>gr[maxn]; bool mat[maxn][maxn]; bool cmp(pii a, pii b) { if(a.fs != b.fs) { return a.sc < b.sc; } return a.fs > b.fs; } int main() { int tc; sf1(tc); for(int qq=1;qq<=tc;qq++) { for(int i=0;i<maxn;i++) { gr[i].clear(); } int n,m; sf2(n,m); int col[maxn]; for(int i=0;i<n;i++) { sf1(col[i]); } memset(mat,0,sizeof mat); for(int i=0;i<m;i++) { int x,y; sf2(x,y); if(mat[x][y]==0) { mat[x][y] = 1; mat[y][x] = 1; gr[x].push_back(y); gr[y].push_back(x); } } /// degree set kortechi vector< pii > vt; for(int i=0;i<n;i++) { vt.push_back(make_pair(gr[i].size(),i) ); } sort(vt.begin(),vt.end() ,cmp); int cnt=0; vector<int>ans; for(int i=0;i<vt.size();i++) { int u = vt[i].sc; for(int i=0;i<gr[u].size();i++) { int v = gr[u][i]; if(mat[u][v] and col[u]!=col[v]) { mat[u][v]=0; mat[v][u]=0; cnt++; ans.push_back(u); } } } sort(ans.begin(), ans.end() ); pf1(cnt); for(int i=0;i<ans.size();i++) { pf(" %d",ans[i]); } pf("\n"); } return 0; } /* */ <file_sep>/Marathon/Sack (dsu on tree)/D. Tree Requests.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 500000+7 vector<int>gr[maxn]; string s; int sz[maxn],st[maxn],ft[maxn],ver[maxn],level[maxn],timer=0; vector< pair<int,int> > query[maxn]; int ans[maxn]; int cnt[maxn][27]; void getsz(int u,int p) { st[u]=timer; ver[timer]=u; sz[u]=1; timer++; for(auto v : gr[u]) { if(v!=p) { level[v]=level[u]+1; getsz(v,u); sz[u]+=sz[v]; } } ft[u]=timer; } void dfs(int u,int p,int keep) { int mx=-1,bigchild=-1; for(auto v : gr[u]) { if(v!=p and sz[v]>mx) { mx=sz[v]; bigchild=v; } } for(int v : gr[u]) { if(v !=p and v!=bigchild) { dfs(v,u,0); } } if(bigchild!=-1) { dfs(bigchild,u,1); } for(int v : gr[u]) { if(v!=p and v!=bigchild) { for(int p=st[v];p<ft[v];p++) { cnt[level[ver[p]]][s[ver[p]-1]-'a']++; } } } cnt[level[u]][s[u-1]-'a']++; for(auto q : query[u]) { bool f=1; int odd=0; for(int i=0;i<26;i++) { if(cnt[q.first][i]&1)odd++; } if(odd>1) { f=0; } ans[q.second]=f; } if(keep==0) { for(int p=st[u];p<ft[u];p++) { cnt[level[ver[p]]][s[ver[p]-1]-'a']--; } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n,m; cin >> n >> m; for(int i=2; i<=n; i++) { int t; cin >> t; gr[t].push_back(i); } cin >> s; for(int i=0; i<m; i++) { int h,v; cin >> v >> h; query[v].push_back({h,i}); } level[1]=1; getsz(1,-1); dfs(1,-1,1); for(int i=0; i<m; i++) { if(ans[i]) { cout << "Yes" << endl; } else { cout << "No" << endl; } } return 0; }<file_sep>/LightOJ/1140 - How Many Zeroes.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 char str[12]; ll dp[12][3][3][300],l; ll rec(int ps,int isst,int issmall,ll val) { if(ps>=l) { return val; } ll &ret=dp[ps][isst][issmall][val]; if(ret!=-1) return ret; ret=0; int d= issmall==1 ? str[ps]-'0' : 9; if(isst) ret+=rec(ps+1,isst,d>0?0:issmall,val+1); else ret+=rec(ps+1,isst,0,val); for(int i=1 ; i<=d ; i++ ) { ret+=rec(ps+1,1,i<d?0:issmall,val); } return ret; } int main() { int tc; sf("%d",&tc); for(int qq=1 ; qq<=tc ; qq++ ) { ll a,b,aa; sf("%lld %lld",&a,&b); if(a==0) { aa=0; } else { l=sprintf(str,"%lld",a-1); memset(dp,-1,sizeof dp); aa=rec(0,0,1,0)+1; } l=sprintf(str,"%lld",b); memset(dp,-1,sizeof dp); ll bb=rec(0,0,1,0)+1; pf("Case %d: %lld\n",qq,bb-aa); } return 0; } /* 5 100 200 */ <file_sep>/Codeforces/Contests/Codeforces Round #404 (Div. 2)/a.cpp #include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; long long int sum=0; while(n--) { string str; cin >> str; // cout << str; if(str=="Tetrahedron") sum+=4; else if(str=="Cube") sum+=6; else if(str=="Octahedron")sum+=8; else if(str=="Dodecahedron") sum+=12; else if(str=="Icosahedron")sum+=20; // cout << sum << endl; } cout << sum << '\n'; return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #299 (Div. 2)/E. Information Graph.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 vector<int>gr[maxn]; bool cmp(const pair<int,pii>a,const pair<int,pii>b) { return a.sc.sc < b.sc.sc; } int par[maxn]; int root(int u) { if(par[u]==u) return u; return par[u]=root(par[u]); } void add(int u,int v) { int ru = root(u); int rv = root(v); par[ru]=rv; } bool fin(int u,int v) { int ru = root(u); int rv = root(v); return ru==rv; } int flag[maxn],st[maxn],ed[maxn],tim=1,dd[maxn]; void dfs(int u) { dd[u] = 1; st[u]=tim++; for(int v : gr[u]) { if(dd[v]==0) dfs(v); } ed[u]=tim++; } int main() { vector< pair<int,pii> >edge,q; int n,m; sf2(n,m); int pack=1,qn=1; for(int i=1;i<=m;i++) { int typ; sf1(typ); if(typ==1) { int u,v; sf2(u,v); gr[v].push_back(u); flag[v] = 1; edge.push_back( {1,{u,v}} ); } else if(typ==2) { int d; sf1(d);///d ke pack no document dawya hoiche edge.push_back( {2,{d,pack++}} ); } else { int x,d; sf2(x,d);/// x ke d pack ta dawya hoiche kina q.push_back( {qn++,{x,d}} ); } } sort(q.begin(),q.end(),cmp); for(int i=1;i<=n;i++) { if(flag[i]==1 and dd[i]==0) { dfs(i); } par[i] = i; } // for(int i=1;i<=4;i++) // { // cout << i << " er " << st[i] << " " << ed[i] << endl; // } int ans[maxn]; memset(ans,-1,sizeof ans); int j=0; for(int i=0;i<edge.size();i++) { int typ=edge[i].fs; if(typ==1) { // cout << edge[i].sc.fs << " of type 1 " << edge[i].sc.sc << endl; add(edge[i].sc.fs,edge[i].sc.sc); } else { int p = edge[i].sc.fs; int pack = edge[i].sc.sc; int rp = root(p); for(;j<q.size();j++) { if(q[j].sc.sc != pack) break; int t = q[j].sc.fs; // cout << rp << " " << t << " connection " << fin(rp,t) << endl; if(fin(rp,t)==0) { // cout << "first no" << endl; ans[q[j].fs] = 0; } else { if(st[t]<=st[p] and ed[t]>=ed[p]) { ans[q[j].fs] = 1; } else { // cout << "second no " << endl; ans[q[j].fs] = 0; } } } } } for(int i=1;i<qn;i++) { if(ans[i]==0) { cout << "NO" << endl; } else { cout << "YES" << endl; } } return 0; } /* */ <file_sep>/USACO/Section 1.3/Wormholes.cpp /* ID:shishir10 TASK:wormhole LANG:C++11 */ #include<bits/stdc++.h> using namespace std; int x[17],y[17]; int part[17]; int n; int nex[17]; bool ok() { for(int s=1;s<=n;s++) { int ps=s; // cout << ps << " theke cycle start hoiteche " << endl; for(int i=1;i<=n;i++) { ps=nex[part[ps]]; // cout << ps << " " ; } // cout << endl; if(ps!=0) return 1; } return 0; } int solve() { int i,j; for( i=1; i<=n; i++) { if(part[i]==0) { break; } } if(i>n) { if(ok()) return 1; return 0; } int temp=0; for( j=i+1; j<=n; j++) { if(part[j]==0) { part[i]=j; part[j]=i; temp+=solve(); part[i]=part[j]=0; } } return temp; } int main() { ifstream fin("wormhole.in"); ofstream fout("wormhole.out"); fin >> n; for(int i=1; i<=n; i++) { fin >> x[i] >> y[i]; } fin.close(); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if( x[j]>x[i] and y[i]==y[j]) { if(nex[i]==0 || (x[j]-x[i]) < (x[nex[i]]-x[i]) ) { // cout << i << " er nex " << j << endl; nex[i]=j; } } } } // cout << solve() << endl; fout << solve() << endl; fout.close(); return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #427 (Div. 2)/A. Key races.cpp #include<bits/stdc++.h> using namespace std; int main() { int s,v1,v2,t1,t2; cin >> s >> v1 >> v2 >> t1 >> t2; int a=s*v1+t1*2; int b=s*v2+t2*2; if(a<b) { cout << "First"; } else if(a>b) { cout << "Second"; } else { cout << "Friendship"; } return 0; } <file_sep>/USACO/Section 1.3/Ski Course Design.cpp /* ID:shishir10 TASK:skidesign LANG:C++11 */ #include<bits/stdc++.h> using namespace std; int main() { ifstream fin("skidesign.in"); ofstream fout("skidesign.out"); int n; vector<int>vt; fin >> n; for(int i=0;i<n;i++) { int t; fin >> t; vt.push_back(t); } sort(vt.begin(),vt.end()); int mn=INT_MAX; for(int st=0;st<vt[n-1];st++) { int low=st; int hi=low+17; int ans=0; for(int j=0;j<n;j++) { if(vt[j]<low) { ans+=( (low-vt[j]) * (low-vt[j]) ); } else if(vt[j]>hi) { ans+=( (vt[j]-hi) * (vt[j]-hi) ); } } mn=min(mn,ans); } // cout << mn << endl; fout << mn << '\n'; return 0; } <file_sep>/Marathon/Weekly Marathon #3 by DJ/L - Anatoly and Cockroaches.cpp #include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; string str; cin >> str; int r=0,b=0; for(int i=0;i<n;i++) { if( (i&1) and str[i]!='r') r++; else if( (!(i&1)) and str[i]!='b') b++; } int mx=max(r,b); r=0,b=0; for(int i=0;i<n;i++) { if( (i&1) and str[i]!='b') r++; else if( (!(i&1)) and str[i]!='r') b++; } int x=max(r,b); cout << min(mx,x) << '\n'; return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #332 (Div. 2)/C. Day at the Beach.cpp #include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); int n; vector<int>vt; cin >> n; for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back(t); } vector<int>mn=vt; mn.push_back(2000000000); for(int i=n-1;i>=0;i--) { mn[i]=min(mn[i],mn[i+1]); } int mx=-1,step=0; for(int i=0;i<n;i++) { mx=max(mx,vt[i]); if(mx<=mn[i+1]) { step++; mx=-1; } } cout << step << endl; return 0; } <file_sep>/Marathon/Weekly Marathon #7 by DJ/C. Marina and Vasyav2.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,t; string a,b; cin >> n >> t >> a >> b; sort(a.begin(),a.end()); sort(b.begin(),b.end()); string ans; int w=0; for(int ) return 0; }<file_sep>/Contest/Team Forming Contest 3 (08-09-2017) (2015)/I - Lap.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int x,y; while(cin >> x >> y) { int d=y-x; int a=(y+d-1)/d; cout << a << endl; } return 0; }<file_sep>/Marathon/Weekly Marathon #2 by DJ/e.cpp #include<bits/stdc++.h> using namespace std; int small(int ara[],int n,int sum) { map<int,int>mp; int mx=n+7; for(int i=0;i<n;i++) { int cur=cur+ara[i]; if(cur==sum) { mx=min(mx,i+1); } if(mp.find(cur-sum)!=mp.end()) { mx=min(mx,i-mp[cur-sum]); } mp[cur]=i; } return mx; } int smallv2(int ara[],int n,int sum) { int cur=0,st=0,mx=INT_MAX; for(int i=0;i<=n;i++) { while(cur>=sum and st<i) { mx=min(mx,i-st); // cout <<cur << " " << st << " " << i << endl; cur-=ara[st]; st++; } cur+=ara[i]; } return mx; } int main() { //ios_base::sync_with_stdio(0); int n,sum; while(cin >> n >> sum) { int ara[n+2]; for(int i=0;i<n;i++) { cin >> ara[i]; } int ans=smallv2(ara,n,sum); if(ans==INT_MAX) cout << "0" << '\n'; else cout << ans << '\n'; } return 0; } <file_sep>/Marathon/Weekly Marathon #2 by DJ/test.cpp #include <bits/stdc++.h> #define FAST ios_base::sync_with_stdio(0) #define dbug(x) cout<<x<<" " using namespace std; int main() { FAST; int n, s; while(cin>>n>>s) { long long a[n],sum = 0,low=0, ans = n+2; for(int i = 0; i < n; i++) { cin>>a[i]; sum+=a[i]; while(sum>=s) { ans=min(ans,i-low+1); sum-=a[low]; low++; } } if(ans == n+2)ans = 0; cout<<ans<<'\n'; } return 0; } <file_sep>/Codeforces/1500 = Codeforces Rating = 1599/C. Dima and Staircase.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 ll tree[4*maxn]; int ara[maxn]; void build(int id,int l,int r) { if(l==r) { tree[id] = ara[l]; return ; } int mid = (l+r) / 2 ; build(id*2,l,mid); build(id*2+1,mid+1,r); tree[id] = max(tree[id*2],tree[id*2+1]); } ll lazy[4*maxn]; void shift(int id,int l,int r) { if(l != r) { tree[id*2] = tree[id*2+1] = lazy[id]; lazy[id*2] = lazy[id*2+1] = lazy[id]; lazy[id] = 0 ; } } void updt(int id,int l,int r,int ql,int qr,ll val) { if(l>qr || r<ql) return; if(lazy[id]) { shift(id,l,r); } if(l>=ql && r<=qr) { lazy[id] = tree[id] = val; return ; } int mid = (l+r) / 2; updt(id*2,l,mid,ql,qr,val); updt(id*2+1,mid+1,r,ql,qr,val); tree[id] = max(tree[id*2],tree[id*2+1]); } ll query(int id,int l,int r,int ql,int qr) { if(l>qr || r<ql) { return -1LL; } if(lazy[id]) { shift(id,l,r); } if(l>=ql and r<=qr) { // cout << l << " --> " << r << endl; return tree[id]; } int mid = (l+r) / 2; return max( query(id*2,l,mid,ql,qr), query(id*2+1,mid+1,r,ql,qr) ); } int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); int n; sf1(n); for(int i=1; i<=n; i++) { sf1(ara[i]); } build(1,1,n); // cout << tree[1] << " " << tree[2] << " " << tree[1*2+1] << endl; int q; sf1(q); while(q--) { ll w,h; sf2ll(w,h); ll val = query(1,1,n,1,w); pf1ll(val); updt(1,1,n,1,w,val+h); } return 0; } /* */ <file_sep>/Marathon/Mathematics/10820 - Send a Table.cpp #include<bits/stdc++.h> using namespace std; long long int phi[500000]; long long int cum[500000]; // Computes and prints totien of all numbers // smaller than or equal to n. void computeTotient(int n) { // Create and initialize an array to store // phi or totient values for (int i=1; i<=n; i++) phi[i] = i; // indicates not evaluated yet // and initializes for product // formula. // Compute other Phi values for (int p=2; p<=n; p++) { // If phi[p] is not computed already, // then number p is prime if (phi[p] == p) { // Phi of a prime number p is // always equal to p-1. phi[p] = p-1; // Update phi values of all // multiples of p for (int i = 2*p; i<=n; i += p) { // Add contribution of p to its // multiple i by multiplying with // (1 - 1/p) phi[i] = (phi[i]/p) * (p-1); } } } // Print precomputed phi values /*for (int i=1; i<=10; i++) cout << "Totient of " << i << " is " << phi[i] << endl; */ } int main() { computeTotient(500000-7); for(int i=1;i<500000-7;i++) { cum[i]=cum[i-1]+phi[i]*2; } int n; while(cin >> n) { if(n==0) return 0; cout << cum[n]-1 << endl; } return 0; } <file_sep>/Codeforces/Contests/191/dv2.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int n,m; string grid[507]; int fx[] = {-1,1,0,0}; int fy[] = {0,0,-1,1}; vector< pair<char,pair<int,int> > >vt; bool ok(int x,int y) { if(x>=0 and x<n and y>=0 and y<m) return 1; return 0; } int flag[507][507]; void dfs(int ux,int uy) { for(int i=0;i<4;i++) { int vx = fx[i] + ux , vy = fy[i] + uy; if( ok(vx,vy) and flag[vx][vy]==-1 and grid[vx][vy]=='.') { vt.push_back( {'B', {vx,vy} } ); flag[vx][vy]=1; dfs(vx,vy); } } vt.push_back( {'D', {ux,uy} } ); vt.push_back( {'R', {ux,uy} } ); } int main() { cin >> n >> m; for(int i=0;i<n;i++) { cin >> grid[i]; } memset(flag,-1,sizeof flag); int cnt=0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if( flag[i][j]==-1 && grid[i][j]=='.' ) { vt.push_back( {'B', {i,j} } ); flag[i][j]=1; dfs(i,j); vt.pop_back(); vt.pop_back(); cnt++; } } } cout <<vt.size() << endl; for(int i=0;i<vt.size();i++) { // printf("%c %d %d\n",vt[i].first,vt[i].second.first+1 , vt[i].second.second+1); cout << vt[i].first << " " << vt[i].second.first+1 << " " << vt[i].second.second+1 << '\n'; // cout << vt[i].first << " " << vt[i].second.first+1 << " " << vt[i].second.second+1 << endl; } // cout << cnt << endl; return 0; } <file_sep>/LightOJ/1060 - nth Permutation.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int ll fac[22]; ll ways(vector<int>& vt) { int t=0; ll den=1; for(int i=0; i<vt.size(); i++) { den*=fac[vt[i]]; t+=vt[i]; } return fac[t]/den; } void solve() { string str; int n; cin >> str >> n; vector<int>vt(30); for(int i=0; i<str.size(); i++) vt[str[i]-'a']++; if(ways(vt)<n) { cout << "Impossible" << endl; return ; } // cout << ways(vt) << "fine" << endl; string ans; for(int i=0; i<str.size(); i++) { for(int j=0;j<vt.size();j++) { if(vt[j]) { vt[j]--; if(ways(vt)>=n) { ans+=('a'+j); break; } else { n-=ways(vt); vt[j]++; } } } } cout << ans << endl; } int main() { fac[1]=1,fac[0]=1; for(ll i=2; i<22; i++) fac[i]=i*fac[i-1]; ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1; qq<=tc; qq++) { cout << "Case " << qq << ": "; solve(); } return 0; } <file_sep>/Marathon/BPM Marathon/C - Marriage Media.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 57 struct data { int h,age,c; }; vector<int>gr[maxn]; int Left[maxn], Right[maxn]; bool vist[maxn]; bool dfs(int u) { if(vist[u]) return 0; vist[u] = 1; for(int i=0;i<gr[u].size();i++) { int v = gr[u][i]; if(Right[v] == -1) { Right[v] = u; Left[u] = v; return 1; } } for(int i=0;i<gr[u].size();i++) { int v = gr[u][i]; if( dfs(Right[v]) ) { Right[v] = u; Left[u] = v; return 1; } } return 0; } int matching() { memset(Left,-1,sizeof Left); memset(Right,-1,sizeof Right); bool done ; do{ done = 1; memset(vist,0,sizeof vist); for(int i=0;i<maxn;i++) { if(Left[i] == -1 && dfs(i) ) { done = 0; } } }while(!done); int ret = 0; for(int i=0;i<maxn;i++) { ret += (Left[i] != -1); } return ret; } int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); int tc; sf1(tc); for(int qq=1;qq<=tc;qq++) { for(int i=0;i<maxn;i++) { gr[i].clear(); } int m,w; sf2(m,w); data ara[m+7]; for(int i=0;i<m;i++) { sf3(ara[i].h, ara[i].age, ara[i].c ); } data ara2[w+7]; for(int i=0;i<w;i++) { sf3(ara2[i].h, ara2[i].age, ara2[i].c); } for(int i=0;i<m;i++) { for(int j=0;j<w;j++) { if( abs(ara[i].h-ara2[j].h)<=12 and abs(ara[i].age-ara2[j].age)<=5 and ara[i].c==ara2[j].c) { gr[i].push_back(j); } } } int ans = matching(); pcase(qq); pf1(ans); } return 0; } /* */ <file_sep>/LightOJ/1020 - A Childhood Game.cpp #include<bits/stdc++.h> using namespace std; int main() { int tc; scanf("%d",&tc); for(int qq=1;qq<=tc;qq++) { long long int n; char str[10]; scanf("%lld",&n); scanf("% s",str); cin >> str; printf("Case %d: ",qq); if(str[0]=='A') { if(n%3==1) { cout << "Bob"; } else { cout << "Alice"; } } else { if(n%3==0) { cout << "Alice"; } else { cout << "Bob"; } } printf("\n"); } return 0; } <file_sep>/Contest/Individual Practice Contest 8/B - Number of Waysv2.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 1000007 ll ara[maxn],sum=0; int main() { ios_base::sync_with_stdio(0); int n; cin >> n ; for(int i=1;i<=n;i++) { cin >> ara[i]; sum+=ara[i]; } if(sum%3) { cout << 0 << endl; return 0; } ll t=0,i; for(i=1;i<=n;i++) { t+=ara[i]; if(t==sum/3) { i++; break; } } int j; t=0; for(j=n;j>=0;j--) { t+=ara[j]; if(t==sum/3) { j--; break; } } cout << i << " " << j << endl; vector<int>vt; for(;i<=j;i++) { vt.push_back(ara[i]); } for(int i=0;i<vt.size();i++) { cout << vt[i] << " "; } for(int x : vt) { cout << x << " "; } return 0; } /* */ <file_sep>/Marathon/SQRT decomposition/test.cpp #include <bits/stdc++.h> using namespace std; const int SQRT = 320; const int N = 1e5 + 10; struct query { int id, l, r; bool operator < (const query &q) const { return l/SQRT == q.l/SQRT ? r < q.r : l/SQRT < q.l/SQRT; } }; query q[N]; int n, m, a[N], cnt[N], res[N], cur; void add (int p) { if (a[p] <= n) { if (cnt[a[p]] == a[p]) --cur; ++cnt[a[p]]; if (cnt[a[p]] == a[p]) ++cur; } } void del (int p) { if (a[p] <= n) { if (cnt[a[p]] == a[p]) --cur; --cnt[a[p]]; if (cnt[a[p]] == a[p]) ++cur; } } int main (int argc, char const *argv[]) { scanf("%d %d", &n, &m); for (int i = 1; i <= n; ++i) { scanf("%d", a + i); } for (int i = 1; i <= m; ++i) { q[i].id = i; scanf("%d %d", &q[i].l, &q[i].r); } sort(q + 1, q + m + 1); int l = 1, r = 0; for (int i = 1; i <= m; ++i) { while (r < q[i].r) add(++r); while (l > q[i].l) add(--l); while (l < q[i].l) del(l++); while (r > q[i].r) del(r--); res[q[i].id] = cur; } for (int i = 1; i <= m; ++i) { printf("%d\n", res[i]); } return 0; } <file_sep>/Codeforces/Contests/AIM Tech Round 4 (Div. 2)/C. Sorting by Subsequences.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; vector<int>vt; for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back(t); } vector<int>temp; sort(temp.begin(),temp.end()); vector<int>ans[100007]; int a=0; int j=0; for(int i=0;i<n;i++) { int t=vt[i],cnt=0; int pos=lower_bound(vt.begin(),vt.end(),t)-vt.begin()+1; for(;j<n;j++) { ans[a++].push_back() } } return 0; }<file_sep>/Contest/Battle of Brains, 2017 (Replay)/A Girl's Story.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll x,y; cin >> x >> y; cout << (y-x+x*2)/2 << endl; return 0; }<file_sep>/Marathon/Weekly Marathon #5 by DJ/I - Igor In the Museum.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int vector<string>grid; map< pair<int,int> , int >mp; int fx[]={1,-1,0,0}; int fy[]={0,0,-1,1}; int cnt=0; int flag[1007][1007]; vector< pair<int,int> > vt; void dfs(int ux,int uy) { flag[ux][uy]=1; for(int i=0;i<4;i++) { int vx=ux+fx[i]; int vy=uy+fy[i]; if(flag[vx][vy]==0) { if(grid[vx][vy]=='*') { cnt++; } else { vt.push_back({vx,vy}); dfs(vx,vy); } } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,m,k; cin >> n >> m >> k; for(int i=0;i<n;i++) { string t; cin >> t; grid.push_back(t); } while(k--) { int r,c; cin >> r >> c; r--; c--; auto it=mp.find({r,c}); if(it!=mp.end()) { cout << it->second << endl; } else { cnt=0; vt.clear(); memset(flag,0,sizeof flag); dfs(r,c); cout << cnt << endl; vt.push_back({r,c}); for(auto it:vt) { mp[it]=cnt; } } } return 0; }<file_sep>/Codeforces/Contests/Codeforces Round #404 (Div. 2)/c.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); ll n,m; cin >> n >> m; const clock_t begin_time = clock(); if(m>=n) { cout << n << endl; return 0; } else { ll a=2*(n-m); ll p=sqrt(a); while(p*p+p<a) p++; cout << p+m << endl; } // cout << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* 1000000000000000000 1 */ <file_sep>/Contest/CUET NCPC 2017 Preliminary Contest/F. Grundy and K-Nim.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; sf("%d",&tc); for(int qq=1 ; qq<=tc ; qq++ ) { int n,q; sf("%d",&n); ll ara[n+7]; for(int i=0 ; i<n ; i++ ) { sf("%lld",&ara[i]); } // DB; pf("Case %d:\n",qq); sf("%d",&q); for(int ii=1 ; ii<=q ; ii++ ) { ll t; sf("%lld",&t); ll x=0; for(int i=0 ; i<n ; i++ ) { x=x^(ara[i]%(t+1)); } if(x==0) { pf("Query %d: Lose\n",ii); } else { pf("Query %d: Win\n",ii); } } } return 0; } /* 1 3 3 5 5 2 2 4 */ <file_sep>/Contest/ACM ICPC Dhaka Regional 2017 Online Preliminary Round Hosted by University of Asia Pacific/iibys.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int ll bigmod(ll a,ll b,ll m) { /// a^b%m ll ans=1; while(b>0) { if(b&1LL) ans=(a*ans)%m; b>>=1; a=(a*a)%m; } return ans; } int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { string a,b; cin >> a >> b; cout << "Case " << qq << ": "; int f=1; for(int i=0;i<a.size();i++) { if(a[i]!='0') { f=0; break; } } if(f) { cout << 0 << endl; continue; } ll r=0; for(int i=0;i<a.size();i++) { r+=(1LL*(a[i]-'0') ); r%=9LL; } if(r==0) r=9LL; // cout << "r " << r << endl; ll t=bigmod(r,10LL,9LL)%9LL; ll temp[b.size()+7]; temp[b.size()-1]=r; for(int i=b.size()-2;i>=0;i--) { temp[i]=bigmod(temp[i+1],10LL,9LL)%9LL; } ll ans=1LL; for(int i=0;i<b.size();i++) { ans*=(bigmod(temp[i],(b[i]-'0')*1LL,9LL)); ans%=9LL; } if(ans==0) ans=9LL; cout << ans << endl; } return 0; } <file_sep>/Codechef/Contests/November Lunchtime 2017/Smart Strategy.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; while(tc--) { int n,q; cin >> n >> q; vector<int>vt; for(int i=0;i<n;i++) { int t; cin >> t; if(t!=1) { vt.push_back(t); } } sort(vt.rbegin(), vt.rend() ); while(q--) { int ans; cin >> ans; for(int i : vt) { ans/=i; if(ans<1) { break; } } cout << ans << " "; } cout << endl; } return 0; } <file_sep>/Marathon/Weekly Marathon #7 by DJ/D - Modulo Sum.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int vector<int>vt; int n,m,f=0; int dp[1007][1007][2]; int rec(int ps,int sum,int cnt) { /*cout << "sum " << sum << endl;*/ if(sum%m==0 and cnt>0) { f=1; return 1; } if(f) return 1; if(ps>=n) { return 0; } int &ret=dp[ps][sum][cnt]; if(ret!=-1) return ret; ret=rec(ps+1,(sum+vt[ps])%m,cnt|1) | rec(ps+1,sum,cnt); return ret; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back(t); } if(n>=m) { cout << "YES"; return 0; } memset(dp,-1,sizeof dp); rec(0,0,0); if(f) { cout << "YES" ; } else { cout << "NO"; } return 0; }<file_sep>/Codeforces/Contests/Codeforces Round #444 (Div. 2)/C. Solution for Cube.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int vector< vector<int,int> >vt[10]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int pre=-1,t; for(int i=0;i<24;i++) { cin >> t; if(pre!=t) { cnt=0; t=pre; } else { cnt++; } if(cnt) } return 0; } <file_sep>/Codeforces/B numbers/shishir.cpp #include<bits/stdc++.h> using namespace std; int lps[800]; void LPS(string str) { memset(lps,0,sizeof lps); int j=0; lps[0]=0; int i=1; while(i<str.size()) { if(str[j]==str[i]) { lps[i]=j+1; i++; j++; } else { if(j==0) { lps[i]=0; i++; } else { j=lps[j-1]; } } } } in int main() { string str; cin >> str; LPS(str); for(int i=0;i<str.size();i++) { cout << lps[i] << " " ; } cout << '\n'; return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #299 (Div. 2)/B. Tavas and SaDDas version2.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { int n; cin >> n; int digit=0; int ans=0; while(n>0) { if(n%10==7) { ans|=(1<<digit); } n/=10; digit++; } for(int i=1 ;i<digit ;i++ ) { ans+=(1<<i); } cout << ans+1 << endl; // main(); return 0; } /* */ <file_sep>/Codeforces/Contests/Codeforces Round 225/E. Prime Gift.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 1000000000000000000 vector<ll>xs,ys; void rec(const vector<ll>&in, vector<ll>&out,ll cur,int ps) { if(cur>maxn) { return ; } out.push_back(cur); for(int i=ps; i<in.size(); i++) { if(cur<=maxn/in[i]) { rec(in,out,cur*in[i],i); } } } ll f(ll t) { ll res = 0; ll yidx = 0; for(ll x : xs) { while(yidx<ys.size() && ys[yidx]<=t/x) { yidx++; } res+=yidx; } return res; } int main() { ios_base::sync_with_stdio(0); int n; cin >> n; vector<ll>vt[3]; for(int i=0; i<n; i++) { ll t; cin >> t; vt[i%2].push_back(t); } rec(vt[0],xs,1LL,0); rec(vt[1],ys,1LL,0); sort(xs.rbegin(),xs.rend()); sort(ys.begin(),ys.end()); ll l=1,r=maxn+7; // for(int x : xs) // { // cout << x << " "; // } // cout << endl; // for(int x : ys) // { // cout << x << " "; // } // cout << endl << endl; ll k; cin >> k; while(l<r) { ll mid = (l+r)/2; ll t = f(mid); if(t<k) { l = mid+1; } else { r = mid; } } cout << l << endl; return 0; } /* */ <file_sep>/Implementation/temporary/sparse.cpp /*input */ #include<bits/stdc++.h> #define ll long long int #define maxn 100007 int table[maxn][20]; int vt[maxn]; int n; // AC code void prepocess() { for(int i=0;i<n;i++) { table[i][0]=i; } for(int j=1;(1<<j)<=n;j++) { for(int i=0;(i+(1<<j)-1)<n;i++) { if(vt[table[i][j-1]]<vt[table[i+(1<<(j-1))][j-1]]) { table[i][j]=table[i][j-1]; } else { table[i][j]=table[i+(1<<(j-1))][j-1]; } } } } int query(int l,int r) { int e=r-l+1; int t=log2(e); return std::min( vt[table[l][t]], vt[table[r-(1<<t)+1][t]] ); } int main() { int tc; scanf("%d",&tc); for(int qq=1;qq<=tc;qq++) { int q; scanf("%d %d",&n,&q); for(int i=0;i<n;i++) { scanf("%d",&vt[i]); } prepocess(); printf("Case %d:\n",qq); while(q--) { int l,r; scanf("%d %d",&l,&r); l--,r--; printf("%d\n",query(l,r)); } } return 0; } <file_sep>/Contest/SPC Individual Contest 03 [19-03-2017]/Play with dates.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 bool leap(int y) { if(y%4) return 0; if(y%100==0 and y%400==0) return 1; if(y%100==0) return 0; return 1; } int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); // const clock_t begin_time = clock(); int tc; string days[]={"Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"}; int nd[]={0,31,28,31,30,31,30,31,31,30,31,30,31}; cin >> tc; while(tc--) { int date,mon,year; cin >> date >> mon >> year ; int cnt=4; int md=0; //cout << "INPUT NEWYA SESH" << endl; int flag=1; for(int y=2012;y<=year;y++) { for(int m=1;m<=12 and flag;m++) { //if(y==2012 and m<=11) m=11; if(leap(y) and m==2) { md=29; } else md=nd[m]; for(int d=1;d<=md and flag;d++) { if(y==2012 and m==1 and d<=11) d=11; //cout << "HI" << endl; //cout << d << " " << m << " " << y << endl; if(d==date and m==mon and y==year) { cout << days[cnt] << endl; flag=0; } cnt++; cnt%=7; } } } } // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/LightOJ/1087 - Diablo.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); // const clock_t begin_time = clock(); int tc; sf("%d",&tc); for(int qq=1;qq<=tc;qq++) { int n,q; sf("%d %d",&n,&q); vector<int>vt; for(int i=0;i<n;i++) { int t; sf("%d",&t); vt.push_back(t); } pf("Case %d:\n",qq); while(q--) { char ch; int id; sf(" %c %d",&ch,&id); if(ch=='a') { vt.push_back(id); } else { if(id>vt.size()) { pf("none\n"); continue; } pf("%d\n",vt[id-1]); vt.erase(vt.begin()+id-1); } } } // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/Codeforces/Contests/Codeforces Round #427 (Div. 2)/D. Palindromic characteristicsv2.cpp /*input abacaba */ #include<bits/stdc++.h> using namespace std; #define ll long long int string str; int palin[5007][5007],dp[5007][5007]; int ispalin(int i,int j) { if(palin[i][j]!=-1) return palin[i][j]; if(i==j || i>j) return 1; if(str[i]==str[j]) return palin[i][j]=ispalin(i+1,j-1); else return palin[i][j]=0; } int rec(int i,int j) { if(i==j) return dp[i][j]=1; int& ret=dp[i][j]; if(ret!=-1) { return ret; } if(ispalin(i,j)) { return ret=1+rec(i,(i+j-1)/2); } else return ret=0; } int ara[5007]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> str; memset(palin,-1,sizeof palin); memset(dp,-1,sizeof dp); for(int i=0;i<str.size();i++) { for(int j=i;j<str.size();j++) { ara[rec(i,j)]++; } } // cout << palin[1][2] << endl; for(int i=str.size()-1;i>=0;i--) { ara[i]+=ara[i+1]; } for(int i=1;i<=str.size();i++) { cout << ara[i] << " "; } return 0; } <file_sep>/Novice/Marathon Week - 9 ArticulationBridgeSCC/G - Come and Go.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 2009 vector<int>gh[maxn],tgh[maxn]; int n,m,u,v,w; int visit[maxn],marking[maxn]; stack<int>st; void dfs(int u) { visit[u]=1; for(int i=0 ;i<gh[u].size() ;i++ ) { int v=gh[u][i]; if(!visit[v]) { dfs(v); } } st.push(u); } void dfss(int u,int mark) { visit[u]=1; marking[u]=mark; for(int i=0 ;i<tgh[u].size() ;i++ ) { int v=tgh[u][i]; if(!visit[v]) { dfss(v,mark); } } } void scc() { memset(visit,0,sizeof visit); while(!st.empty())st.pop(); for(int i=1 ;i<=n ;i++ ) { if(!visit[i]) { dfs(i); } } memset(visit,0,sizeof visit); memset(marking,0,sizeof marking); int mark=0; // stack<int>::iterator it; // it=st.begin() // for( ; it!=st.end():it++ ) // { // cout << it << endl; // } // DB; while(!st.empty()) { int u=st.top(); st.pop(); if(!visit[u]) { dfss(u,mark++); } } if(mark>1) cout << "0" << '\n'; else cout << "1" << '\n'; } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); while(sf("%d %d",&n,&m)==2) { if(n==0 && m==0) break; for(int i=0 ;i<=n ;i++ ) { gh[i].clear(); tgh[i].clear(); } for(int i=0 ; i<m ; i++ ) { // DB; sf("%d %d %d",&u,&v,&w); if(w==1) { gh[u].push_back(v); tgh[v].push_back(u); } else { gh[u].push_back(v); gh[v].push_back(u); tgh[u].push_back(v); tgh[v].push_back(u); } } // DB; scc(); } return 0; } /* */ <file_sep>/Codeforces/1500 = Codeforces Rating = 1599/B. Mashmokh and ACM.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 2007 int n,k; vector<int>vt[maxn]; ll dp[maxn][maxn]; ll rec(int cnt,int prev) { if(cnt==k) { return 1; } ll &ret = dp[cnt][prev]; if(ret != -1) return ret; ret =0 ; for(int i=0; i<vt[prev].size() && vt[prev][i]<=n; i++) { ret+=rec(cnt+1,vt[prev][i]); ret%=mod; } return ret; } int main() { for(int i=1; i<maxn; i++) { for(int j=i; j<maxn; j++) { if(j%i==0) { vt[i].push_back(j); } } } ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); cin >> n >> k; memset(dp,-1,sizeof dp); ll ans = 0; for(int i=1; i<=n; i++) { ans+=rec(1,i); ans%=mod; } cout << ans << endl; return 0; } /* */ <file_sep>/Contest/Individual Practice Contest 6/A - Nested Segments.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 bool cmp(pii a,pii b) { if(a.fs == b.fs) { return a.sc>b.sc; } return a.fs<b.fs; } int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); map<pii,int>mp; vector<pii>vt; int n; sf1(n); for(int i=1; i<=n; i++) { int x,y; sf2(x,y); vt.push_back(make_pair(x,y)); mp[make_pair(x,y)] = i; } map<pii,int>qmp; int q; sf1(q); for(int i=0; i<q; i++) { int t; sf1(t); vt.push_back(make_pair(t,0)); qmp[make_pair(t,0)] = i; } sort(vt.begin(),vt.end(),cmp); int ans[q+7]; stack<pii>st; for(int i=0; i<vt.size(); i++) { pii temp = vt[i]; if(temp.sc==0) { if(st.empty()) { ans[qmp[temp]] = -1; // cout << ans[qmp[temp]] << " print " << endl; continue; } while( !st.empty() and (st.top().fs>temp.fs || st.top().sc<temp.fs) ) { st.pop(); } if(st.empty()) { ans[qmp[temp]] = -1; // cout << ans[qmp[temp]] << " print " << endl; continue; } ans[qmp[temp]] = mp[st.top()]; // cout << ans[qmp[temp]] << " print " << endl; } else { st.push(temp); } } for(int i=0; i<q; i++) { pf1(ans[i]); } return 0; } /* 3 2 10 2 3 5 7 11 1 2 3 4 5 6 7 8 9 10 11 */ <file_sep>/LightOJ/1042 - Secret Origins.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { int n; vector<int>vt; sf("%d",&n); while(n>0) { vt.push_back(n%2); n/=2; } vt.push_back(0); reverse(vt.begin(),vt.end()); next_permutation(vt.begin(),vt.end()); ll ans=0,ps=0; for(int i=vt.size()-1 ;i>=0 ;i-- ) { if(vt[i]) { ans|=(1<<ps); } ps++; } pf("Case %d: %lld\n",qq,ans); } return 0; } /* */ <file_sep>/Codeforces/B numbers/N - Average Numbers.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; vector<int>vt; ll sum=0; for(int i=1;i<=n;i++) { int t; cin >> t; vt.push_back(t); sum+=t; } vector<int>ans; for(int i=0;i<vt.size();i++) { ll t=sum-vt[i]; ll avg=t/(n-1); if(vt[i]==avg and t%(n-1)==0 ) { ans.push_back(i+1); } } if(ans.empty()) cout << 0 ; else { cout << ans.size() << endl; for(int i : ans) cout << i << " "; } return 0; }<file_sep>/Contest/SPC Individual Contest 02 [18-03-2017]/Stripe.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int n; cin >> n; int ara[n+7]; int sums[n+7]; ara[0]=0; sums[0]=0; for(int i=1;i<=n;i++) { cin >> ara[i]; sums[i]=sums[i-1]+ara[i]; } int cnt=0; for(int i=1;i<n;i++) { if(sums[i]==sums[n]-sums[i]) { // cout << sums[i] << endl; // cout << i << endl; // DB; cnt++; } } cout << cnt ; return 0; } /* */ <file_sep>/Codeforces/Contests/Educational Codeforces Round 18/A. New Bus Route.cpp #include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; vector<int>vt; for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back(t); } sort(vt.begin(),vt.end()); int mn=INT_MAX; for(int i=1;i<vt.size();i++) { mn=min(mn,abs(vt[i]-vt[i-1])); } int cnt=0; for(int i=1;i<vt.size();i++) { if(abs(vt[i]-vt[i-1])==mn) { cnt++; } } cout << mn << " " << cnt << '\n'; return 0; } /* for(int j=i+1; j<vt.size(); j++) { if(abs(vt[i]-vt[j])==mn) { cnt++; } } */ <file_sep>/USACO/Section 1.2/Name That Numbe.cpp /* ID:shishir10 LANG:C++ TASK:namenum */ #include<bits/stdc++.h> #include<fstream> using namespace std; vector<char>vt; vector<string>col; vector<string>dd; string gn; int n; int flag=1; ofstream fout("namenum.out") ; ifstream fin("namenum.in") ,fdict("dict.txt"); void name(int ps) { if(ps>=n) { string str; for(int i=0;i<vt.size();i++) { str+=vt[i]; } if(binary_search(col.begin(),col.end(),str)) { flag=0; fout << str << '\n'; } return; } for(int i=0;i<3;i++) { vt.push_back(dd[gn[ps]-'0'-2][i]); name(ps+1); vt.pop_back(); } } int main() { dd.push_back("ABC"); dd.push_back("DEF"); dd.push_back("GHI"); dd.push_back("JKL"); dd.push_back("MNO"); dd.push_back("PRS"); dd.push_back("TUV"); dd.push_back("WXY"); string t; while(fdict>>t) { //cout << t << endl; col.push_back(t); } fin>>gn; n=gn.size(); name(0); if(flag) fout << "NONE" << '\n'; return 0; } <file_sep>/Marathon/Weekly Marathon #5 by DJ/test.cpp #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; class LongMansionDiv2 { public: long long minimalTime(int, vector <int>); }; long long LongMansionDiv2::minimalTime(int M, vector <int> t) { sort(t.begin(),t.end()); long long int sum=0; for(int i=0;i<t.size();i++) sum+=(long long int)t[i]; cout << sum << endl; cout << t[0] << endl; cout << M-1 << endl; cout << t[0]*M-1 << endl; sum+=((long long int)t[0]*(long long int)(M-1) ); return sum; } int main() { int m=4; vector<int>vt={3, 2, 4, 2}; LongMansionDiv2 t; long long int f=t.minimalTime(4,vt); cout << f << endl; return 0; } <file_sep>/LightOJ/1089 - Points in Segments (II)2.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 50007 int tree[10000000]; void updt(int id,int l,int r,int i,int j) { if(l>j || r<i) return; if(l>=i && r<=j) { tree[id]++; return; } int mid=(l+r)/2; updt(id*2,l,mid,i,j); updt(id*2+1,mid+1,r,i,j); } int query(int id,int l,int r,int ps) { if(l==r && l==ps) return tree[id]; int mid=(l+r)/2; if(ps<=mid) return query(id*2,l,mid,ps)+tree[id]; else return query(id*2+1,mid+1,r,ps)+tree[id]; } int main() { int tc; sf("%d",&tc); for(int qq=1;qq<=tc;qq++) { int n,q; sf("%d %d",&n,&q); map<ll,int>mp; int hv=1; vector< pair<ll,ll> >seg; vector<ll>all; for(int i=0;i<n;i++) { ll x,y; sf("%lld %lld",&x,&y); seg.push_back({x,y}); all.push_back(x); all.push_back(y); } vector<ll>points; for(int i=0;i<q;i++) { ll t; sf("%lld",&t); points.push_back(t); all.push_back(t); } sort(all.begin(),all.end()); for(int i=0;i<all.size();i++) { if(mp.find(all[i])==mp.end()) { mp[all[i]]=hv++; } } memset(tree,0,sizeof tree); for(int i=0;i<n;i++) { updt(1,1,hv,mp[seg[i].fs],mp[seg[i].sc]); } pf("Case %d:\n",qq); for(int i=0;i<q;i++) { pf("%d\n",query(1,1,hv,mp[points[i]])); } } return 0; } /* */ <file_sep>/Codeforces/B numbers/B. Valued Keys.cpp #include<bits/stdc++.h> using namespace std; int main() { string x,z,y; cin >> x >> y; for(int i=0;i<x.size();i++) { if(y[i]>x[i]) { cout << -1 << '\n'; return 0; } } cout << y << '\n'; return 0; } <file_sep>/Contest/Individual Practice Contest 1/Fliptile.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define DB cout<<" **** "<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 int tog(int num,int ps) { return ( num^=(1<<ps) ) ; } bool chk(int num,int ps) { return (bool)( num& (1<<ps) ); } int seti(int num,int ps) { return ( num|=(1<<ps) ); } int m,n; int ara[17][17]; vector<int>bits; void toggle(int r,int c) { tog(bits[r],c); if(r-1>=0) tog( bits[r-1], c); if(r+1<m) tog(bits[r+1], c); if(c-1>=0) tog(r,c-1); if(c+1<n) tog(r,c+1); } void int main() { sf2(m,n); for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { sf1(ara[i][j]); } } return 0; } /* */ <file_sep>/Contest/SPC Individual Contest 03 [19-03-2017]/Luggage .cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 vector<int>vt; int d=0; int f=0; void rec(int ps,int sum) { // cout << sum << endl; if(ps>=vt.size()) { if(sum==d) f=1; return ; } if(f) return ; rec(ps+1,sum+vt[ps]); rec(ps+1,sum); } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); // const clock_t begin_time = clock(); int tc; cin >> tc; getchar(); while(tc--) { vt.clear(); string str; getline(cin,str); int t=0; int ii=0; int ara[300]; for(int i=0;i<str.size();i++) { if(str[i]==' ') { ara[ii++]=t; t=0; } else { t=t*10+str[i]-'0'; } } ara[ii++]=t; int flag[308]; memset(flag,0,sizeof flag); // for(int i=0;i<ii;i++) // { // cout << ara[i] << endl; // } for(int i=0;i<ii;i++) { flag[ara[i]]++; } // DB; // cout << flag[1] << endl; for(int i=0;i<300;i++) { if(flag[i]%2==1) { vt.push_back(i); } } int sum=0; for(int i=0;i<vt.size();i++) { sum+=vt[i]; } // for(int i=0;i<vt.size();i++) // { // cout << vt[i] << endl; // } if(sum%2==1) { cout << "NO" << endl; } else { if(sum==0) { // DB; cout << "YES" << endl; } else { f=0; d=sum/2; // cout << "d " << d << endl; // DB; // DB; rec(0,0); if(f) { cout << "YES" << endl; } else { cout << "NO" << endl; } } } } // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* 3 2 3 4 1 2 5 10 50 3 50 */ <file_sep>/Contest/Individual Practice Contest 4/test.cpp #include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <cstdlib> #include <queue> #include <climits> #define ll long long #define MOD 1000000007 #define mx 3005 #define mkp make_pair #define MAXN 3000005 using namespace std; int tree[MAXN][2], ptr = 0, cnt[MAXN]; int fun(int n, int i) { return bool(n & (1<<i)); } long long ans = 0; const int deb = 0; void insert(int n) { int tmp = 0; for(int i = 23 - deb; i>=0; i--) { int d = fun(n, i); cnt[tmp]++; if(tree[tmp][d] == -1) tree[tmp][d] = ++ptr; tmp = tree[tmp][d]; } cnt[tmp]++; } void search(int n, int k) { int tmp = 0; for(int i = 23 - deb; i>=0; i--) { int d = fun(n, i), dk = fun(k, i); if(tree[tmp][d^dk^1] != -1 && dk == 1) { ans += cnt[tree[tmp][d^dk^1]]; } if(tree[tmp][d^dk] != -1) { tmp = tree[tmp][d^dk]; } else break; } } void clear() { for(int i = 0; i<=ptr; i++) { tree[i][0] = tree[i][1] = -1; cnt[i] = 0; } ptr = 0; ans = 0; } int main() { memset(tree, -1, sizeof tree); int t; scanf("%d", &t); while(t--) { int n, k; scanf("%d %d", &n, &k); int ara[n]; clear(); insert(0); for(int i = 0; i<n; i++) { scanf("%d", &ara[i]); if(i) ara[i] ^= ara[i-1]; search(ara[i], k); insert(ara[i]); } printf("%lld\n", ans); } return 0; } <file_sep>/Contest/CUET NCPC 2017 Preliminary Contest/D. Sum of Two Sequences.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { ll a1,d1,k1,a2,d2,k2; sf("%lld%lld%lld %lld%lld%lld",&a1,&d1,&k1,&a2,&d2,&k2); ll s1=k1*(2*a1+(k1-1)*d1)/2; // cout << s1 << endl; ll s2=k2*(2*a2+(k2-1)*d2)/2; pf("Case %d: %lld\n",qq,s1+s2); } return 0; } /* 5 100000 100000 100000 100000 100000 100000 */ <file_sep>/Codeforces/Contests/198/B. Maximal Area Quadrilateral.cpp #include<bits/stdc++.h> #define pii pair<int,int> #define tii pair<int,pair<int,int> > #define fs first #define sc second #define DB cout<<"*****"<<endl; #define mod 1000000007 #define inf 1000000007 #define pi acos(-1.0) #define sf scanf #define pf printf #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define pcase(x) printf("Case %d: ",x) #define ll long long int #define maxn 100007 using namespace std; struct PT{ int x,y; PT() {} PT(double x, double y) : x(x), y(y) {} PT(const PT &p) : x(p.x), y(p.y) {} PT operator + (const PT &p) const { return PT(x+p.x, y+p.y); } PT operator - (const PT &p) const { return PT(x-p.x, y-p.y); } PT operator * (double c) const { return PT(x*c, y*c); } PT operator / (double c) const { return PT(x/c,y/c); } }; int cross(PT &p, PT &q) { return p.x*q.y-p.y*q.x; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; PT points[n+7]; for(int i=0;i<n;i++) { cin >> points[i].x >> points[i].y ; } vector < PT > dia; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { dia.push_back( PT(points[i]+points[j]) ); } } for(int i=0;i<dia.size();i++) { for(int i) } return 0; } /* */ <file_sep>/LightOJ/1224 - DNA Prefix.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 50001*51 int nex[4][maxn]; int mark[maxn],sz=0; int mx = -1; void insert(string str) { int v = 0; for(int i=0; i<str.size(); i++) { int ch; if(str[i] == 'A') { ch = 0; } else if(str[i] == 'C') { ch = 1; } else if(str[i] == 'G') { ch = 2; } else { ch = 3 ; } if(nex[ch][v] == -1) { nex[ch][v] = ++sz; } v = nex[ch][v]; mark[v]++; mx = max(mx,mark[v]*(i+1) ); } } void clr() { memset(mark,0,sizeof mark); memset(nex,-1,sizeof nex); sz = 0; mx = 0; } int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; for(int qq=1; qq<=tc; qq++) { int n; cin >> n; vector<string>vt; for(int i=0; i<n; i++) { string t; cin >> t; vt.push_back(t); } clr(); for(int i=0; i<n; i++) { insert(vt[i]); } cout << "Case " << qq << ": " << mx << endl; } return 0; } /* 3 4 CGCGCCGCGCGCGC GCGCGC CGCGCCGCGCGCGC TC */ <file_sep>/LightOJ/1089 - Points in Segments (II).cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 50007 int n,q; int l[maxn],r[maxn]; int main() { int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { sf("%d %d",&n,&q); for(int i=0 ;i<n ;i++ ) { sf("%d %d",&l[i],&r[i]); } sort(l,l+n); sort(r,r+n); for(int i=0;i<n;i++) cout << l[i] << " "; cout << '\n'; for(int i=0;i<n;i++) cout << r[i] <<" "; cout << '\n'; int t; pf("Case %d:\n",qq); while(q--) { sf("%d",&t); int ps1=upper_bound(l,l+n,t)-l; int ps2=lower_bound(r,r+n,t)-r; cout << ps1 << ' ' << n-ps2 << endl; // cout << ps1 << ' ' << ps2 << endl; int ans=min(n-ps2,ps1); pf("%d\n",ans); } } return 0; } /* 1 10 5 6334 26500 15724 19169 11478 29358 24464 26962 5705 28145 16827 23281 491 9961 2995 11942 4827 5436 14604 32391 12382 17421 */ <file_sep>/Marathon/Suffix Array/C - Distinct Substringsv2.cpp #include <cstdio> #include <sstream> #include <cstdlib> #include <cctype> #include <cmath> #include <algorithm> #include <set> #include <queue> #include <stack> #include <list> #include <iostream> #include <fstream> #include <numeric> #include <string> #include <vector> #include <cstring> #include <map> #include <iterator> #include <stdio.h> /* printf */ #include <math.h> /* log2 */ //#include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 int n; string str; struct entry{ int nr[3],p; }L[maxn]; int lcp[maxn],P[20][maxn]; bool cmp(entry a,entry b) { return (a.nr[0] == b.nr[0]) ? (a.nr[1] < b.nr[1] ? 1 : 0) : (a.nr[0] < b.nr[0] ? 1 : 0); } inline void SA() { n = str.size(); memset(P,-1,sizeof P); for(int i=0;i<n;i++) { P[0][i] = str[i]-'A'; } int stp,cnt; for(stp = 1,cnt=1; cnt < n; stp++,cnt<<=1) { for(int i=0;i<n;i++) { L[i].nr[0] = P[stp-1][i]; L[i].nr[1] = i+cnt<n ? P[stp-1][i+cnt] : -1; L[i].p = i; } sort(L,L+n,cmp); for(int i=0;i<n;i++) { P[stp][L[i].p] = i>0 && L[i-1].nr[0] == L[i].nr[0] && L[i-1].nr[1] == L[i].nr[1] ? P[stp][L[i-1].p] : i ; } } // for(int i=0;i<n;i++) // { // cout << L[i].p << " "; // } // cout << endl << endl; lcp[0] = 0; ll sum = 0; for(int i=1;i<n;i++) { int x = L[i-1].p; int y = L[i].p; lcp[i] = 0; for(int k=stp-1;k>=0;k--) { if( (P[k][x] == P[k][y])) { lcp[i] += (1<<k); x+=(1<<k); y+=(1<<k); } } sum+=lcp[i]; } ll ans = 1LL*n*(n+1)/2LL; cout << ans-sum << endl; } ///Got AC int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; while(tc--) { cin >> str; SA(); } return 0; } /* */ <file_sep>/Marathon/Weekly Marathon #2 by DJ/A.cpp #include<bits/stdc++.h> using namespace std; int main() { int n; while(cin>>n) { if(n==0) return 0; int ara[n+8]; for(int i=0;i<n;i++) { cin >> ara[i]; } sort(ara,ara+n); int flag=1; for(int i=n-1;i>=0 and flag;i--) { for(int j=0;j<i and flag;j++) { // if(j==i) continue; for(int k=j+1;k<i and flag;k++) { // if(k==i) continue; for(int l=k+1;l<i and flag;l++) { // if(l==i) continue; if(ara[i]==ara[j]+ara[k]+ara[l]) { flag=0; cout << ara[i] << '\n'; } } } } } if(flag) { cout << "no solution" << '\n'; } } return 0; } //#include<bits/stdc++.h> //using namespace std; //int main() //{ // int n; // while(cin>>n) // { // if(n==0) // return 0; // int ara[n+8]; // for(int i=0;i<n;i++) // { // cin >> ara[i]; // } // sort(ara,ara+n); // int flag=1; // for(int i=n-1;i>=0 and flag;i--) // { // for(int j=0;j<=i and flag;j++) // { // for(int k=j+1;k<=i and flag;k++) // { // for(int l=k+1;l<=i and flag;l++) // { // if(ara[i]==ara[j]+ara[k]+ara[l]) // { // flag=0; // cout << ara[i] << '\n'; // } // } // } // } // } // if(flag) // { // cout << "no solution" << '\n'; // } // } // return 0; //} <file_sep>/Codeforces/Contests/Codeforces Round #429 (Div. 2)/A. Generous Kefa.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { int n,k; cin >> n >>k; int ara[50]; memset(ara,0,sizeof ara); char ch; while(scanf("%c",&ch)==1) { if(ch>='a' and ch<='z') { ara[ch-'a']++; } if(ch>='a' and ch<='z' and ara[ch-'a']>k) { cout << "NO"; return 0; } } cout << "YES"; return 0; }<file_sep>/Codeforces/Contests/191/D. Block Tower.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int n,m; string grid[507]; int fx[] = {-1,1,0,0}; int fy[] = {0,0,-1,1}; int cnt=0; vector< pair<char,pair<int,int> > >vt; bool ok(int x,int y) { if(x>=0 and x<n and y>=0 and y<m) return 1; return 0; } int flag[507][507]; void dfs(int ux,int uy,int p=1) { cnt++; for(int i=0; i<4; i++) { int vx = fx[i] + ux, vy = fy[i] + uy; if( ok(vx,vy) and flag[vx][vy]==-1 and grid[vx][vy]=='.') { flag[vx][vy]=1; dfs(vx,vy,1); } } if(p) { cnt+=2; } } void dfs_print(int ux,int uy,int p=1) { cout << "B " << ux+1 << " " << uy+1 << endl; for(int i=0; i<4; i++) { int vx = fx[i] + ux, vy = fy[i] + uy; if( ok(vx,vy) and flag[vx][vy]==-1 and grid[vx][vy]=='.') { flag[vx][vy]=1; dfs_print(vx,vy,1); } } if(p) { cout << "D " << ux+1 << " " << uy+1 << endl; cout << "R " << ux+1 << " " << uy+1 << endl; } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; for(int i=0; i<n; i++) { cin >> grid[i]; } memset(flag,-1,sizeof flag); for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { if( flag[i][j]==-1 && grid[i][j]=='.' ) { flag[i][j]=1; dfs(i,j,0); } } } cout << cnt << endl; memset(flag,-1,sizeof flag); for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { if( flag[i][j]==-1 && grid[i][j]=='.' ) { flag[i][j]=1; dfs_print(i,j,0); } } } return 0; } <file_sep>/Codeforces/B numbers/B. Crossword solving.cpp #include<bits/stdc++.h> using namespace std; int main() { int a,b; cin >> a >> b; string x,y; cin >> x >> y; set<int>vt,ans; for(int i=0;i<y.size();i++) { vt.clear(); int j,p; for(j=0,p=i;j<x.size() and p<y.size();j++,p++) { if(x[j]!=y[p] ) { // cout << " " << p << endl; vt.insert(j); } } if( (ans.size()==0 or vt.size()<ans.size() ) and j==x.size()) { ans.clear(); ans=vt; } } cout << ans.size() << '\n'; for(int i : ans) cout << i+1 << " "; return 0; } <file_sep>/LightOJ/1011 - Marriage Ceremonies.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int on(int n,int ps) { return (n|=(1<<ps)); } int off(int n,int ps) { return n=n&~(1<<ps); } bool check(int n,int ps) { return (bool) (n&(1<<ps)); } int n; int ara[20][20]; int dp[(1<<17)+7][17]; int rec(int mask,int men) { if(mask==(1<<n)-1 and men>=n) return 0; int &ret=dp[mask][men]; if(ret!=-1) return ret; ret=0; for(int i=0 ;i<n ;i++ ) { if(check(mask,i)==0) { int mn=ara[i][men]+rec(on(mask,i),men+1); ret=max(mn,ret); } } return ret; } int main() { int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { sf("%d",&n); for(int i=0 ;i<n ;i++ ) { for(int j=0 ;j<n ;j++ ) { sf("%d",&ara[i][j]); } } memset(dp,-1,sizeof dp); int ans=rec(0,0); pf("Case %d: %d\n",qq,ans); } return 0; } /* */ <file_sep>/Codeforces/Contests/VK Cup 2016 - Round 1 (Div. 2 Edition)/B. Bear and Displayed Friends.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 bool cmp(int a,int b) { return a>b; } int main() { int n,k,q; cin >> n >> k >> q; int t[n+7]; for(int i=0 ;i<n ;i++ ) { sf("%d",&t[i]); } int typ,a; vector<int>vt; while(q--) { sf("%d %d",&typ,&a); if(typ==1) { vt.push_back(t[a-1]); sort(vt.begin(),vt.end(),cmp); if(vt.size()>k) vt.resize(k); for(auto& it :vt ) { cout << it << endl; } } else if(binary_search(vt.begin(),vt.end(),t[a-1])) { cout << "YES" << '\n'; } else cout << "NO" << '\n'; } return 0; } /* */ <file_sep>/Contest/SPC Individual Contest 02 [18-03-2017]/C - Dominos.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 100007 stack<int>st; vector<int>graph[maxn]; void dfs(int u) { flag[u]=1; for(int i=0;i<graph[u].size();i++) { int v=graph[u][i]; if(flag[v]==-1) { dfs(v); st.push(v); } } } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; cin >> tc; while(tc--) { int n,m; cin >> n >> m; for(int i=0;i<m;i++) { int x,y; cin >> x >> y; graph[x].push_back(y); } st.clear(); memset(flag,-1,sizeof flag); for(int i=1;i<=n;i++) { if(flag[i]==-1) { dfs(i); } } while() } return 0; } /* */ <file_sep>/Codechef/Contests/August Long Challenge 2017/K - New Year Table.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define pi acos(-1.0) int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; double R,r; cin >> R >> r; int t=pi/asin(r/(R-r))+0.000000000001; /*cout << fixed << setprecision(10) << pi/asin(r/(R-r)) << endl; cout << t << endl;*/ if(r<=R and n==1) { cout << "YES" << endl; } else if(R==r and n>1) { cout << "NO" << endl; } else if(n<=t) { cout << "YES" << endl; } else { cout << "NO" << endl; } return 0; }<file_sep>/Codeforces/Contests/Codeforces Round #427 (Div. 2)/B. The number on the board.cpp #include<bits/stdc++.h> using namespace std; int main() { int k; string n; cin >> k >> n; int t=0; for(int i=0; i<n.size(); i++) { t+=(n[i]-'0'); } if(k<=t) { cout << 0; } else { // cout << "###" << endl; sort(n.begin(),n.end()); int i; // cout << t << endl; for(i=0; i<n.size(); i++) { t+=(9-n[i]+'0'); if(t>=k) { cout << i+1; return 0; } // cout << t << endl; } // cout << t << endl; if(t>=k) { cout << i+1; return 0; } } return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #428 (Div. 2/A. Arya and Bran.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,k; cin >> n >> k; int t=0,day=0,prev=0; for(int i=0;i<n;i++) { int tt; cin >> tt; tt+=prev; if(tt>8) { t+=8; prev=tt-8; } else { t+=tt; prev=0; } day++; if(t>=k) { break; } } if(t>=k) { cout << day << endl; } else { cout << -1 << endl; } return 0; }<file_sep>/LightOJ/1016 - Brush (II).cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n,w; cin >> n >> w; std::vector<int>vt; for(int i=0;i<n;i++) { int a,b; cin >> a >> b; vt.push_back(b); } sort(vt.begin(),vt.end()); int d=vt[0]+w, cnt=1; for(int i=0;i<n;i++) { if(vt[i]>d) { cnt++; d=vt[i]+w; } } cout << "Case " << qq << ": " << cnt << endl; } return 0; }<file_sep>/Contest/Team Forming Contest 4 (09-09-2017) (2015)/D - No Ball.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { vector<string>vt; for(int i=0;i<5;i++) { string t; cin >> t; vt.push_back(t); } int f=0,c=0; for(int i=0;i<5;i++) { f=0; for(int j=0;j<5;j++) { if( (vt[i][j]=='|' or vt[i][j]=='<') and f==0 ) { /*cout << i << " " << j << endl;*/ f=1; } else if( (vt[i][j]=='>' or vt[i][j]=='|') and f==1) { /*cout << i << " " << j << endl;*/ f=2; c=1; } } } if(c==1) { cout << "Case " << qq << ": " << "No Ball" << endl; } else { cout << "Case " << qq << ": " << "Thik Ball" << endl; } } return 0; }<file_sep>/LightOJ/1319 - Monkey Tradition.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 ll egcd (ll a,ll b,ll &x,ll &y) { /// ax+by=1 finding x and y where a<b if (a == 0) { x = 0; y = 1; return b; } ll x1, y1; ll d = egcd (b%a,a,x1,y1); x = y1 - (b/a) * x1; y = x1; return d; } ll CRT(const vector< pair<ll, ll> > &equations) { if (equations.size() == 0) return -1; /// No equations to solve ll a1 = equations[0].first; ll m1 = equations[0].second; a1 %= m1; /** Initially x = a_0 (mod m_0)*/ /** Merge the solution with remaining equations */ for ( int i = 1; i < equations.size(); i++ ) { ll a2 = equations[i].first; ll m2 = equations[i].second; ll g = __gcd(m1, m2); if ( a1 % g != a2 % g ) return -1; /// Conflict in equations /** Merge the two equations*/ ll p, q; egcd(m1/g, m2/g, p, q); ll M = m1 / g * m2; ll x = ( a1 * (m2/g) % M *q % M + a2 * (m1/g) % M * p % M ) % M; /** Merged equation*/ a1 = x; cout << a1 << " " << M << endl; if ( a1 < 0 ) a1 += M; m1 = M; } return a1; } int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); int tc; sf1(tc); for(int qq=1; qq<=tc; qq++) { int n; sf1(n); vector< pair<ll,ll> > vt; for(int i=0; i<n; i++) { ll p,r; sf2ll(p,r); vt.push_back( {r,p} ); } ll ans = CRT( vt ); pcase(qq); if(ans == -1) { pf("Impossible\n"); } else { pf1ll(ans); } } return 0; } /* */ <file_sep>/LightOJ/1307 - Counting Triangles.cpp #include<bits/stdc++.h> using namespace std; int main() { int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { long long int n; cin >> n; vector<int>vt; for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back(t); } sort(vt.begin(),vt.end()); long long int ans=0; long long int nc=(n*(n-1)*(n-2))/(6); for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { int t=vt.size()-( upper_bound(vt.begin(),vt.end(),vt[i]+vt[j]-1)-vt.begin() ); ans+=t; } } cout << "Case " << qq << ": " << nc-ans << '\n'; } return 0; } <file_sep>/LightOJ/1038 - Race to 1 Again.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 double dp[maxn]; double rec(int n) { if(n==1) return 0; double& ret=dp[n]; if(ret > -1.0) return ret; // cout << "ites fine " << endl; int sq=sqrt(n)-2; while(sq*sq<n) sq++; int cnt=2; for(int i=2;i<sq;i++) { if(n%i==0) { cnt+=2; } } if(sq*sq==n)cnt++; ret=0; for(int i=2;i<sq;i++) { if(n%i==0) { ret+=( 1+rec(i) )/(double)cnt; ret+=( 1+rec(n/i) )/(double)cnt; } } if(sq*sq==n)ret+=( 1+rec(sq) )/(double)cnt; ret+=( 1+rec(1) )/(double)cnt; ret+=1.0/cnt; ret=(ret*cnt)/(double)(cnt-1); return ret; } int main() { for(int i=0;i<maxn;i++) dp[i]=-100.0; ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int t; cin >> t; cout << "Case " << qq << ": " << setprecision(10) << fixed << rec(t) << endl; } return 0; } <file_sep>/Marathon/Sack (dsu on tree)/D. Tree Requestsv2.cpp #include<bits/stdc++.h> using namespace std; #define int long long #define maxn 500010 #define X first #define Y second vector <int> gr[maxn]; string s; vector < pair<int,int> > query[maxn]; int sz[maxn], level[maxn], cnt[maxn][27], ans[maxn], st[maxn], ft[maxn], ver[maxn], timer = 0; void getsz(int u, int p) { st[u] = timer; ver[timer] = u; timer++; sz[u] = 1; for(auto v : gr[u]) { if(v == p)continue; level[v] = level[u]+1; getsz(v, u); sz[u] += sz[v]; } ft[u] = timer; } void dfs(int u, int p, bool keep) { int mx = -1, bigchild = -1; for(auto v : gr[u]) { if(v != p) { if(sz[v] > mx) mx = sz[v], bigchild = v; } } for(auto v : gr[u]) { if(v != p && v != bigchild) { dfs(v, u, 0); } } if(bigchild != -1) dfs(bigchild, u, 1); cnt[level[u]][s[u-1] - 'a']++; for(auto v : gr[u]) { if(v != p && v != bigchild) { for(int t = st[v]; t < ft[v]; t++) { int vv = ver[t]; cnt[level[vv]][s[vv-1] - 'a']++; } } } for(auto q : query[u]) { bool f = true; int bejor = 0; for(int i = 0; i < 26; i++) { int temp = cnt[q.first][i]; if(temp&1) bejor++; } if(bejor > 1) f = false; ans[q.second] = f; } if(!keep) { for(int t = st[u]; t < ft[u]; t++) { int vv = ver[t]; cnt[level[vv]][s[vv-1] - 'a']--; } } } main() { ios::sync_with_stdio(0), cin.tie(0); int n, m; cin>>n>>m; for(int i = 2; i<=n; i++) { int j; cin>>j; //gr[i].push_back(j); gr[j].push_back(i); } cin>>s; for(int i = 1; i <= m; i++) { int u, l; cin>>u>>l; query[u].push_back({l, i}); } level[1]=1; getsz(1, -1); dfs(1, -1, 1); for(int i = 1; i<=m ; i++) { if(ans[i]) cout<<"Yes\n"; else cout<<"No\n"; } return 0; } <file_sep>/LightOJ/1071 - Baker Vaiv2.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 #define D(x) cout << #x " = " << (x) << endl int ara[107][107],r,c; int dp[107][107][107]; int rec(int row,int c1,int c2) { // cout << row << " " << c1 << " " << c2 << endl; if(c1>=c2 || c2 > c || c1>c || row>r) return 0; if(row==r and c1==c-1 and c2==c) return ara[row][c1]+ara[row][c2]; // if(row==r and c1==c-1 ) // return ara[row][c-1]; // if(row==r and c2==c) // return ara[row][c2]; int& ret=dp[row][c1][c2]; if(ret!=-1) return ret; ret=INT_MIN; if(row==r) { // ret=max(ret, rec(row,c1+1,c2)+ara[row][c1] ); // ret=max(ret, rec(row,c1,c2+1)+ara[row][c2] ); if(c1<c2 and c2<c) { ret=max(ret, rec(row,c1,c2+1)+ara[row][c2] ); } if(c1<c2-1 and c1<c-1) { ret=max(ret, rec(row,c1+1,c2)+ara[row][c1] ); } return ret; } if(c1<c2 and c2<c) { ret=max(ret, rec(row,c1,c2+1)+ara[row][c2] ); } if(c1<c2-1 and c1<c-1) { ret=max(ret, rec(row,c1+1,c2)+ara[row][c1] ); } if(row<=r) { ret=max(ret, rec(row+1,c1,c2)+ara[row][c1]+ara[row][c2] ); } // ret=max(ret, rec(row+1,c1,c2)+ara[row][c1]+ara[row][c2] ); // ret=max(ret, rec(row,c1,c2+1)+ara[row][c2] ); // ret=max(ret, rec(row,c1+1,c2)+ara[row][c1] ); // cout << "row " << row << " *** " << c1 << " " << c2 << " er jonno " << ret << endl; return ret; } int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); int tc; cin >> tc; for(int qq=1; qq<=tc; qq++) { cin >> r >> c; for(int i=1; i<=r; i++) { for(int j=1; j<=c; j++) { cin >> ara[i][j]; } } memset(dp,-1,sizeof dp); // cout << "******" << endl << endl; int ans=rec(1,1,2); cout << "Case " << qq << ": " << ans << endl; } return 0; } <file_sep>/LightOJ/1131 - Just Two Functions.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int ll mod; struct matrix { int row=0,col=0; ll mat[17][17]; }; matrix matmult(const matrix &a, const matrix &b) { /// depending on the problem statement mod sum assert(a.col==b.row); matrix ans; ans.row=a.row, ans.col=b.col; for(int i=0; i<a.row; i++) { for(int j=0; j<b.col; j++) { ll sum=0; for(int k=0; k<a.col; k++) { sum+=(a.mat[i][k]*b.mat[k][j]); sum%=mod; } ans.mat[i][j]=sum; } } return ans; } matrix matexpo(matrix base,int p) { /// a matrix is only exponenable when its row==col that means it must have to be a square matrix. matrix ans; ans.row=ans.col=base.row; for(int i=0; i<base.col; i++) { for(int j=0; j<base.col; j++) { ans.mat[i][j]=(i==j); } } while(p) { if(p&1) ans=matmult(ans,base); base=matmult(base,base); p>>=1; } return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int a1,b1,c1; cin >> a1 >> b1 >> c1 ; int a2,b2,c2; cin >> a2 >> b2 >> c2; int f0,f1,f2; cin >> f0 >> f1 >> f2; int g0,g1,g2; cin >> g0 >> g1 >> g2; cin >> mod; cout << "Case " << qq << ":" << endl; int q; cin >> q; matrix M,A,B; M.row=6,M.col=6; M.mat[0][0]=a1 , M.mat[0][1]=b1 , M.mat[0][2]=M.mat[0][3]=M.mat[0][4]=0 , M.mat[0][5]=c1; M.mat[1][0]=1, M.mat[1][1]=M.mat[1][2]=M.mat[1][3]=M.mat[1][4]=M.mat[1][5]=0; M.mat[2][1]=1, M.mat[2][0]=M.mat[2][2]=M.mat[2][3]=M.mat[2][4]=M.mat[2][5]=0; M.mat[3][0]=M.mat[3][1]=0 , M.mat[3][2]=c2, M.mat[3][3]=a2, M.mat[3][4]=b2, M.mat[3][5]=0; M.mat[4][3]=1, M.mat[4][1]=M.mat[4][2]=M.mat[4][0]=M.mat[4][4]=M.mat[4][5]=0; M.mat[5][4]=1, M.mat[5][0]=M.mat[5][2]=M.mat[5][3]=M.mat[5][1]=M.mat[5][5]=0; /*for(int i=0;i<6;i++) { for(int j=0;j<6;j++) { cout << M.mat[i][j] << " "; } cout << endl; }*/ A.row=6,A.col=1; A.mat[0][0]=f2, A.mat[1][0]=f1, A.mat[2][0]=f0, A.mat[3][0]=g2, A.mat[4][0]=g1, A.mat[5][0]=g0; /*for(int i=0;i<6;i++) { cout << A.mat[i][0] << endl; }*/ while(q--) { int n; cin >> n; if(n==0) { cout << f0%mod << " " << g0%mod << endl; continue; } else if(n==1) { cout << f1%mod << " " << g1%mod << endl; continue; } else if(n==2) { cout << f2%mod << " " << g2%mod << endl; continue; } matrix t=matexpo(M,n-2); B=matmult(t,A); cout << B.mat[0][0]%mod << " " << B.mat[3][0]%mod << endl; } } return 0; } <file_sep>/Codechef/Contests/August Cook-Off 2017/Matrix and Chef.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,q; cin >> n >> q; int ara[n+7][n+7]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cin >> ara[i][j]; } } cout << ara[0][0] << endl; for(int i=1;i<n;i++) cout << " " << ara[0][i]; while(q--) { int p; cin >> p; p--; for(int i=0;i<n;i++) { int t; cin >> t; ara[p][i]=t; ara[i][p]=t; } for(int i=0;i<n;i++) { } } return 0; }<file_sep>/Codeforces/C numbers/C. k-Tree.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define mod 1000000007 int k,d; ll dp[600][43]; ll rec(int n,int f) { if(n==0 and f==1) { return 1; } else if(n<0) { return 0; } ll& ret=dp[n][f]; if(ret!=-1)return ret; ret=0; for(int i=1;i<=k;i++) { ret+=rec(n-i,i>=d?1:f); ret%=mod; } ret%=mod; return ret; } int main() { int n; cin >> n >> k >> d; memset(dp,-1,sizeof dp); ll t=rec(n,0)%mod; cout << t << endl; return 0; } <file_sep>/Marathon/Weekly Marathon #3 by DJ/Complete the Word.cpp #include<bits/stdc++.h> using namespace std; queue<char>vt; bool func(string str,int u,int v) { int flag[29]={}; int cnt=0; for(int i=u;i<=v;i++) { if(str[i]!='?') { flag[str[i]-'A']++; } else cnt++; } int c=0; while(!vt.empty()) vt.pop(); for(int i=0;i<26;i++) { if(flag[i]==0) { vt.push(i+'A'); c++; } } //cout << "cnt " << cnt << " c " << c << endl; if(c==cnt) { return 1; } else { return 0; } } int main() { string str; cin >> str; //cout << "*** " << endl; int ans=0; if(str.size()<26) { cout << -1 << '\n'; } else { int x=0,y=25; for(;y<str.size();x++,y++) { // cout << "loop run " << endl; if(func(str,x,y)) { ans=1; while(x<=y) { if(str[x]=='?') { // cout << vt.front() << endl; str[x]=vt.front(); vt.pop(); } x++; } break; } } for(int i=0;i<str.size();i++) { if(str[i]=='?') { str[i]='A'; } } //cout << "ei " << endl; if(ans) cout << str << '\n'; else cout << -1 << '\n'; } return 0; } <file_sep>/Contest/SPC Individual Contest 02 [18-03-2017]/Little Girl and Maximum Sum.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { int return 0; } /* */ <file_sep>/Codeforces/C numbers/C. Marco and GCD Sequence.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; vector<int>vt; for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back(t); } if(vt.size()==1) { cout << 1 << endl; cout << vt[0] << endl; return 0; } int t=__gcd(vt[0],vt[1]); for(int i=3;i<n;i++) { t=__gcd(t,vt[i]); } if(binary_search(vt.begin(),vt.end(),t)==0) { cout << -1 ; return 0; } vector<int>ans; for(int i=0;i<n;i++) { ans.push_back(vt[i]); ans.push_back(vt[0]); } cout << ans.size() << endl; for(int i=0;i<ans.size();i++) cout << ans[i] << " "; return 0; } <file_sep>/Marathon/Weekly Marathon #5 by DJ/A - Vasya and Basketball.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; vector<ll>a,b; vector< pair<int,int> > all; for(int i=0;i<n;i++) { int t; cin >> t; a.push_back(t); all.push_back({t,-1}); } int m; cin >> m; for(int i=0;i<m;i++) { int t; cin >> t; b.push_back(t); all.push_back({t,-2}); } sort(a.begin(),a.end()); sort(b.begin(),b.end()); sort(all.begin(),all.end()); ll mx=INT_MIN,ansa=0,ansb=0; for(int i=0;i<all.size();i++) { if(all[i].second==-1) { int d=all[i].first-1; int t=upper_bound(a.begin(),a.end(),d)-a.begin(); /*cout << t << endl;*/ int ta=t*2+(n-t)*3; t=upper_bound(b.begin(),b.end(),d)-b.begin(); int tb=t*2+(m-t)*3; int dif=ta-tb; /*cout << d << " d er jonno " << ta << " " << tb << " " << mx << endl;*/ if(dif>mx) { /*cout << "###" << endl;*/ mx=dif; /*cout << "d " << d << endl;*/ ansa=ta,ansb=tb; } else if(dif==mx) { if(ta>ansa) { ansa=ta; ansb=tb; } } } else { int d=all[i].first+1; int t=upper_bound(a.begin(),a.end(),d)-a.begin(); int ta=t*2+(n-t)*3; t=upper_bound(b.begin(),b.end(),d)-b.begin(); int tb=t*2+(m-t)*3; int dif=ta-tb; if(dif>mx) { mx=dif; /*cout << "d " << d << endl;*/ ansa=ta,ansb=tb; } else if(dif==mx) { if(ta>ansa) { ansa=ta; ansb=tb; } } } int d=all[i].first; int t=upper_bound(a.begin(),a.end(),d)-a.begin(); int ta=t*2+(n-t)*3; t=upper_bound(b.begin(),b.end(),d)-b.begin(); int tb=t*2+(m-t)*3; int dif=ta-tb; /*cout << d << " d er jonno " << ta << " " << tb << " " << mx << endl;*/ if(dif>mx) { mx=dif; /*cout << "d " << d << endl;*/ ansa=ta,ansb=tb; } else if(dif==mx) { if(ta>ansa) { ansa=ta; ansb=tb; } } } cout << ansa << ":" << ansb << endl; return 0; }<file_sep>/Contest/SPC Day 1 [Basic] [23-03-2017]/b.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); // const clock_t begin_time = clock(); string str; cin >> str; int n; if(str.size()==1) { n=str[0]-'0'; } else { n=(str[str.size()-2]-'0')*10+(str[str.size()-1]-'0'); } n%=4; if(n==0) cout << 4 ; else cout << 0; // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/Print/Phi sieve and Phi(n).cpp #include<bits/stdc++.h> using namespace std; // Computes and prints totien of all numbers // smaller than or equal to n. void computeTotient(int n) { // Create and initialize an array to store // phi or totient values long long phi[n+1]; for (int i=1; i<=n; i++) phi[i] = i; // indicates not evaluated yet // and initializes for product // formula. // Compute other Phi values for (int p=2; p<=n; p++) { // If phi[p] is not computed already, // then number p is prime if (phi[p] == p) { // Phi of a prime number p is // always equal to p-1. phi[p] = p-1; // Update phi values of all // multiples of p for (int i = 2*p; i<=n; i += p) { // Add contribution of p to its // multiple i by multiplying with // (1 - 1/p) phi[i] = (phi[i]/p) * (p-1); } } } // Print precomputed phi values for (int i=1; i<=n; i++) cout << "Totient of " << i << " is " << phi[i] << endl; } int phi(int n) { int result = n; // Initialize result as n // Consider all prime factors of n and subtract their // multiples from result for (int p=2; p*p<=n; ++p) { // Check if p is a prime factor. if (n % p == 0) { // If yes, then update n and result while (n % p == 0) n /= p; result -= result / p; } } // If n has a prime factor greater than sqrt(n) // (There can be at-most one such prime factor) if (n > 1) result -= result / n; return result; } int main() { int n; for (n=1; n<=10; n++) printf("phi(%d) = %d\n", n, phi(n)); computeTotient(12); return 0; }<file_sep>/Codeforces/Contests/Codeforces Round #429 (Div. 2)/B. Godsend.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; ll sum=0; int f=1; for(int i=0;i<n;i++) { int t; cin >> t; sum+=t; if(t&1) f=0; } if(f) { cout << "Second" ; } else { cout << "First"; } return 0; }<file_sep>/Contest/Individual Practice Contest 4/E - Silver Cow Party.cpp #include <cstdio> #include <sstream> #include <cstdlib> #include <cctype> #include <cmath> #include <algorithm> #include <set> #include <queue> #include <stack> #include <list> #include <iostream> #include <fstream> #include <numeric> #include <string> #include <vector> #include <cstring> #include <map> #include <iterator> #include<complex> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define DB cout<<" **** "<<endl; #define mod 1000000007 #define inf 1000000007 #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 1007 vector<pii>gr[maxn],rev[maxn]; int dist[maxn]; struct cmp { bool operator () (const pii &a, const pii &b) { return a.second > b.second; } }; void dijkstra(int src) { int vist[maxn]; for(int i=0; i<maxn; i++) { dist[i] = inf; vist[i] = 0; } priority_queue< pii, vector<pii>, cmp > Q; Q.push( make_pair(src,0) ); dist[src] = 0; while(!Q.empty()) { pii u = Q.top(); Q.pop(); if(vist[u.fs]) { continue; } for(int i=0; i<gr[u.fs].size(); i++) { int v = gr[u.fs][i].fs; int w = gr[u.fs][i].sc; if(dist[u.fs]+w < dist[v]) { dist[v] = dist[u.fs] + w; Q.push( make_pair(v,dist[v]) ); } } vist[u.fs]=1; } } int revd[maxn]; void dijkstra2(int src) { int vist[maxn]; for(int i=0; i<maxn; i++) { revd[i] = inf; vist[i] = 0; } priority_queue< pii, vector<pii>, cmp > Q; Q.push(make_pair(src,0)); revd[src] = 0; while(!Q.empty()) { int u = Q.top().fs; Q.pop(); if(vist[u]) { continue; } for(int i=0; i<rev[u].size(); i++) { int v = rev[u][i].fs; int w = rev[u][i].sc; if(revd[u]+w < revd[v]) { revd[v] = revd[u] + w; Q.push(make_pair(v,dist[v])); } } } } //struct comp //{ // bool operator ()(pii &a ,pii &b) // { // return a.second>b.second; // } //}; //void dijkstra(int src) //{ // int distance[maxn]; // for (int i=1;i<=n ;i++ ) // { // distance[i]=inf; // visit[i]=false; // } // priority_queue<pii,vector<pii>,comp>Q; // Q.push(pii(src,0)); // distance[src]=0; // while(!Q.empty()) // { // int u=Q.top().first; // Q.pop(); // if(visit[u])continue; // for (int i=0;i<vt[u].size() ;i++ ) // { // int v=vt[u][i].first; // int w=vt[u][i].second; // if(distance[u]+w<distance[v]) // { // distance[v]=distance[u]+w; // Q.push(pii(v,distance[v])); // } // } // visit[u]=true; // } // if(distance[n]!=inf) pf("%d\n",distance[n]); // else pf("Impossible\n"); //} int main() { int n,m,x; sf3(n,m,x); for(int i=0; i<m; i++) { int u,v,w; sf3(u,v,w); gr[u].push_back( make_pair(v,w) ); rev[v].push_back( make_pair(u,w) ); } dijkstra(x); // cout << "fine " << endl; // for(int i=1; i<=n; i++) // { // cout << i << " --> " << dist[i] << endl; // } // cout << "first dijkstra sesh " << endl; dijkstra2(x); // for(int i=1; i<=n; i++) // { // cout << i << " --> " << revd[i] << endl; // } // cout << "first dijkstra sesh " << endl; int mn=0; for(int i=1; i<=n; i++) { if(i!=x) mn=max(mn,dist[i]+revd[i]); } pf1(mn); return 0; } /* */ <file_sep>/Spoj/QTREE2 - Query on a tree IIv2.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 10000+7 #define level 20 vector< pair<int,int> >gr[maxn]; int depth[maxn],dis[maxn],par[maxn][level+7]; void dfs(int u,int p) { depth[u]=depth[p]+1; par[u][0]=p; for(auto v:gr[u]) { if(v.first!=p) { dis[v.first]=dis[u]+v.second; dfs(v.first,u); } } } void preprocess(int n) { for(int j=1;j<level;j++) { for(int node=1;node<=n;node++) { if(par[node][j-1]!=-1) { par[node][j]=par[par[node][j-1]][j-1]; } } } } int lca(int u,int v) { if(depth[u]<depth[v]) { swap(u,v); } int diff=depth[u]-depth[v]; for(int i=0;i<level;i++) { if((diff>>i)&1) { u=par[u][i]; } } if(u==v) return u; for(int i=level-1;i>=0;i--) { if(par[u][i]!=par[v][i]) { u=par[u][i]; v=par[v][i]; } } return par[u][0]; } int jump(int u,int k) { for(int i=0;i<level;i++) { if((k>>i)&1) { u=par[u][i]; } } return u; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; while(tc--) { int n; cin >> n; for(int i=0;i<=n;i++) gr[i].clear(); for(int i=1;i<n;i++) { int u,v,c; cin >> u >> v >> c; gr[u].push_back({v,c}); gr[v].push_back({u,c}); } memset(par,-1,sizeof par); depth[0]=0; dfs(1,0); preprocess(n); /*cout << lca(4,6) << endl;*/ string str; while(cin >> str) { if(str=="DIST") { int u,v; cin >> u >> v; int t=lca(u,v); cout << dis[u]+dis[v]-2*dis[t] << endl; } else if(str=="KTH") { int u,v,k; cin >> u >> v >> k; int t=lca(u,v); int du=depth[u]-depth[t]+1; /*cout << t << " " << du << endl;*/ if(k<=du) { /*cout << "yes " << endl; cout << u << " theke " << k << endl;*/ cout << jump(u,k-1) << endl; } else { int dv=depth[v]-depth[t]; /*cout << "du " << du << endl; cout << "dv " << dv << endl;*/ k-=du; /*cout << "k " << k << endl;*/ int aa=dv-k; /*cout << "aa " << aa << endl;*/ cout << jump(v,aa) << endl; } } else if(str=="DONE") { break; } } } return 0; }<file_sep>/Contest/Team Forming Contest 4 (09-09-2017) (2015)/I - High School Assembly.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n; cin >> n; vector<int>ara,temp; for(int i=0;i<n;i++) { int t; cin >> t; ara.push_back(t); } temp=ara; sort(temp.begin(),temp.end()); int cnt=0; for(int x=0,y=0;y<n;) { if(temp[x]==ara[y]) { x++,y++; } else { y++; cnt++; } } /*cout << cnt << endl;*/ cout << "Case " << qq << ": " << cnt << endl; } return 0; }<file_sep>/Marathon/Mathematics/E - GCD XOR UVA - 12716.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); for(int i=1;i<=100;i++) { for(int j=i+1;j<=100;j++) { if(__gcd(i,j) == (i^j) ) { cout << i << " " << j << endl; } } } return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #427 (Div. 2)/C. Star sky.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); int n,q,c; cin >> n >> q >> c; int ara[15][107][107]; memset(ara,0,sizeof ara); for(int i=0;i<n;i++) { int x,y,s; cin >> x >> y >> s; ara[s][x][y]++; } for(int p=0;p<=c;p++) { for(int i=1;i<=101;i++) { for(int j=1;j<=101;j++) { ara[p][i][j]+=(ara[p][i-1][j]+ara[p][i][j-1]-ara[p][i-1][j-1]); } } } while(q--) { int t,x1,y1,x2,y2; cin >> t >> x1 >> y1 >> x2 >> y2; ll ans=0; for(int p=0;p<=c;p++) { int temp=(p+t)%(c+1); int amt=ara[p][x2][y2]-ara[p][x1-1][y2]-ara[p][x2][y1-1]+ara[p][x1-1][y1-1]; ans+=(temp*amt); } cout << ans << endl; } return 0; } <file_sep>/Novice/Marathon Week - 9 ArticulationBridgeSCC/Network.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 107 vector<int>gh[maxn]; int root,ti; int n; set<int>st; int d[maxn],low[maxn],parent[maxn]; bool visit[maxn]; void art(int u) { d[u]=ti; low[u]=ti; ti++; visit[u]=1; int child=0; for(int i=0 ; i<gh[u].size() ; i++ ) { int v=gh[u][i]; if(v==parent[u]) continue; if(visit[v]) { low[u]=min(low[u],d[v]); } else { parent[v]=u; art(v); child++; low[u]=min(low[u],low[v]); if(d[u]<=low[v] && u!=root) { st.insert(u); } } } if(child>1 && u==root) { st.insert(u); } } void make() { for(int i=0 ; i<=n ; i++ ) { gh[i].clear(); } st.clear(); while(1) { string s; getline(cin,s); stringstream ss(s); int u,v; ss>>u; // cout << "u " << u << endl; if(u==0) return; while(ss>>v) { // cout << v << ' '; gh[u].push_back(v); gh[v].push_back(u); } // cout << '\n'; } } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); while(sf("%d",&n)==1) { if(n==0) { // pf("\n"); return 0; } getchar(); make(); root=1; ti=1; memset(visit,0,sizeof visit); art(1); cout << (int)st.size() << '\n'; } return 0; } /* 5 1 2 3 4 5 2 5 3 5 0 4 1 2 3 3 4 0 4 1 2 3 3 4 0 4 1 2 3 3 4 2 4 0 4 1 2 3 3 4 0 5 1 3 4 2 3 4 3 4 4 5 0 */ <file_sep>/Codeforces/Contests/VK Cup 2016 - Round 1 (Div. 2 Edition)/A. Bear and Reverse Radewoosh.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { int n,c; sf("%d %d",&n,&c); int p[n+7],t[n+7]; for(int i=0 ; i<n ; i++ ) { sf("%d",&p[i]); } for(int i=0 ; i<n ; i++ ) { sf("%d",&t[i]); } ll l=0,r=0,tt=0; for(int i=0; i<n ; i++ ) { tt+=t[i]; l+=max(0LL,p[i]-c*tt); } tt=0; for(int i=n-1; i>=0 ; i-- ) { tt+=t[i]; r+=max(0LL,p[i]-c*tt); } // cout << l << ' ' << r << endl; if(l==r) cout << "Tie"; else if(l>r) cout << "Limak"; else cout << "Radewoosh"; return 0; } /* */ <file_sep>/Marathon/Weekly Marathon #7 by DJ/C. Marina and Vasya.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,t; cin >> n >> t; string s1,s2; cin >> s1 >> s2; int a[50],b[50]; memset(a,0,sizeof a); memset(b,0,sizeof b); for(int i=0;i<n;i++) { a[s1[i]-'a']++; b[s2[i]-'a']++; } string w; int d=n-t; int x=0; for(int i=0;i<26;i++) { int t=min(a[i],b[i]); if(w.size()+t<=d) { for(int j=0;j<t;j++) { char ch=i+'a'; w+=ch; } } else { int tt=d-w.size(); for(int j=0;j<tt;j++) { char ch=i+'a'; w+=ch; } } } /* for(int i=0;i<n;i++) { if(w.size()<d) { w+= } }*/ for(int i=0;i<n;i++) { if(w.size()<d) { char ch=i+'a'; } } char c; for(int i=0;i<n;i++) { if(a[i]==0 and b[i]==0 and w.size()<n) { c=i+'a'; } } while(w.size()<n) { w+=c; } cout << w << endl; return 0; }<file_sep>/Codeforces/B numbers/KQUERYO - K-Query Online.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 vector<int>vt[4*maxn]; int ara[maxn]; int k; void merge2(vector<int>& left,vector<int>&right,vector<int>& s) { //vector<int>s; int i=0,j=0; int l=left.size(),r=right.size(); int k=0; while(k<l+r) { if(right.empty()) { s.push_back(left.front()); left.erase(left.begin()); } else if(left.empty()) { s.push_back(right.front()); right.erase(right.begin()); } else if(right.front()<left.front()) { s.push_back(right.front()); right.erase(right.begin()); } else { s.push_back(left.front()); left.erase(left.begin()); } //cout << "***** " << s[k] << endl; k++; } cout << "s er size" << s.size() << endl; //return s; } void build(int id,int l,int r) { if(l==r) { vt[id].push_back(ara[l]); return ; } int mid=(l+r)/2; build(id*2,l,mid); build(id*2+1,mid+1,r); merge2(vt[id*2],vt[id*2+1],vt[id]); cout << "vt er size" << vt[id].size() << endl; // vt[id].resize(vt[id*2].size()+vt[id*2+1].size()); // merge(vt[id*2].begin(),vt[id*2].end(),vt[id*2+1].begin(),vt[id*2+1].end(),vt[id].begin()); } int query(int id,int l,int r,int i,int j) { if(l>j or r<i) return 0; if(l>=i and r<=j) { // cout << id << " " << vt[id].size() << " " << vt[id].size()-(upper_bound(vt[id].begin(),vt[id].end(),k)-vt[id].begin()) << endl; return vt[id].size()-(upper_bound(vt[id].begin(),vt[id].end(),k)-vt[id].begin()); } int mid=(l+r)/2; return query(id*2,l,mid,i,j)+query(id*2+1,mid+1,r,i,j); } int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); // const clock_t begin_time = clock(); int n; sf("%d",&n); for(int i=1;i<=n;i++) { sf("%d",ara+i); } int q; build(1,1,n); //cout << vt[2].size() << endl; sf("%d",&q); //cout << "query suru " << endl; int last=0; while(q--) { int a,b,c; sf("%d%d%d",&a,&b,&c); int i=a^last; int j=b^last; k=c^last; //cout << i << " " << j << " " << k << endl; last=query(1,1,n,i,j); pf("%d\n",last); } // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/Codeforces/Contests/Codeforces Round #299 (Div. 2)/C. Tavas and Karafs.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int a,b,n,m,t,l=1; inline ll h(ll i) { return a+(i-1)*b; } inline ll sum(int r) { if(h(r)>t) return false; int n=r-l+1; ll ans=(ll) 2LL*h(l)+(n-1)*b; ans=ans*n/2; if(ans>(ll)m*t) return false; return true; } int main() { cin >> a >> b >> n; while(n--) { sf("%d %d %d",&l,&t,&m); if(h(l)>t) { cout << "-1" << '\n'; continue; } int r=max(t,m)+l,res; int left=l; while(left<=r) { int mid=(left+r)/2; if(sum(mid)){ left=mid+1; res=mid; } else r=mid-1; } cout << res << endl; } return 0; } /* 2 3 100000 148990 913922 18257 2 1 4 7 10 2 */ <file_sep>/Novice/Marathon Week - 9 ArticulationBridgeSCC/F - Dominos.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 100007 vector<int>gh[maxn]; int visit[maxn]; stack<int>s; void dfs(int u) { visit[u]=0; for(int i=0 ;i<gh[u].size() ;i++ ) { int v=gh[u][i]; if(visit[v]==-1) { dfs(v); } } s.push(u); } void Dfs(int u) { visit[u]=0; for(int i=0 ;i<gh[u].size() ;i++ ) { int v=gh[u][i]; if(visit[v]==-1) { dfs(v); } } } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { int n,m,u,v; sf("%d %d",&n,&m); // DB; // cout << n <<' ' << m << endl; for(int i=0 ;i<=n ;i++ ) { gh[i].clear(); } for(int i=0 ;i<m ;i++ ) { sf("%d %d",&u,&v); gh[u].push_back(v); // gh[v].push_back(u); } memset(visit,-1,sizeof visit); int cnt=0; for(int i=1 ;i<=n ;i++ ) { if(visit[i]==-1) { dfs(i); } } memset(visit,-1,sizeof visit); while(!s.empty()) { int u=s.top(); s.pop(); if(visit[u]==-1) { Dfs(u); cnt++; } } pf("%d\n",cnt); } return 0; } /* 8 10 3 3 10 9 10 7 2 */ <file_sep>/USACO/Section 1.3/Mixing Milk.cpp /* ID:shishir10 LANG:C++11 TASK:milk */ #include<bits/stdc++.h> using namespace std; int main() { freopen("milk.in","r",stdin); freopen("milk.out","w",stdout); long long int total; cin >> total; int n; cin >> n; vector< pair<int,int> >vt; for(int i=0;i<n;i++) { int pu,am; cin >> pu >> am; vt.push_back(make_pair(pu,am)); } sort(vt.begin(),vt.end());; long long int cost=0LL; for(int i=0;i<vt.size() and total>0;i++) { long long int temp=vt[i].second; if(total>=temp) { cost+=(vt[i].first*temp); total-=temp; } else { cost+=(vt[i].first*total ); total=0; } } cout << cost << '\n'; //cout << total << endl; return 0; } <file_sep>/LightOJ/team/mm.cpp /*input 6 1 2 3 4 5 6 6 5 4 3 2 1 */ /* author : <NAME> CSE'15 SUST */ #include <iostream> #include <string> #include <vector> #include <algorithm> #include <sstream> #include <queue> #include <deque> #include <bitset> #include <iterator> #include <list> #include <stack> #include <map> #include <set> #include <functional> #include <numeric> #include <utility> #include <limits> #include <time.h> #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #define pii pair<int,int> #define tii pair<int,pair<int,int> > #define mkp make_pair #define fs first #define sc second #define pb push_back #define ppb pop_back() #define pcase(x) printf("Case %d: ",x) #define hi cout<<"hi"<<endl; #define mod 1000000007 #define inf 1000000007 // #define n 10000007 #define pi acos(-1.0) #define mem(arr,x) memset((arr), (x), sizeof((arr))); #define FOR(i,x) for(int i=0;i<(x); i++) #define FOR1(i,x) for(int i = 1; i<=(x) ; i++) #define jora(a,b) make_pair(a,b) #define tora(a,b,c) jora(a,jora(b,c)) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) // #define noya vector< vector<int> >(6,vector<int>(6,0)) // #define mat vector<vector<int> > // #define m 6 using namespace std; typedef long long int lint; int sum[205][205]; int a[205][205]; inline void pre(int n,int m) { for(int i=1;i<=m;i++) sum[1][i]=a[1][i]; for(int i=1;i<=n;i++) for(int j=2;j<=m;j++) sum[i][j]=sum[i-1][j]+sum[i][j]; for(int j=1;j<=m;j++) for(int i=1;i<=n;i++) sum[i][j]+=sum[i][j-1]; return ; } inline int hudai(int x1,int y1,int x2,int y2) { return sum[x2][y2]+sum[x1-1][y1-1]-sum[x1-1][y2]-sum[x2][y1-1]; } int main() { int n,m,r,c; while(scanf("%d",&n)) { if(n==0) break; scanf("%d %d %d",&m,&r,&c); mem(sum,0); for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) scanf("%d",&a[i][j]); pre(n,m); int x1,x2;int y1,y2; int ans=-inf; for(int k=1;k<=min(n,m);k++) { if(i+r-k) for(int i=1;i<=n-r+1;i++) for(int j=1;j<=m-c+1;j++) { int s=hudai(i,j,i+r-1,j+c-1); } } printf("%d %d %d %d\n",x,y,x+r-1,y+c-1); } return 0; }<file_sep>/Codeforces/D numbers/test.cpp #include<iostream> #include<cmath> using namespace std; int main() { long long t,n,sqrt_n; long long mod = 1000000007; cin>>t; while(t--) { for(int i=1;i<=25;i++) { cout << i << " " << 25/i << endl; } cin>>n; sqrt_n = sqrt(n); long long sum = 0; //finding summation of N/i *i from i=1 to sqrt(N) for(long long i=1; i<=sqrt_n; i++) sum = sum + (n/i)*i; // after i=sqrt(N), there is no need to iterate further bcoz value of N/i will either decrease by 1 or remain same for(long long i=n/sqrt_n-1; i>=1; i--) { long long lower_limit = n/(i+1); long long upper_limit = n/i; long long tmp = ((upper_limit*(upper_limit+1))/2 - (lower_limit*(lower_limit+1))/2); sum = sum + tmp*i; } cout<<sum%mod<<endl; } return 0; } <file_sep>/Contest/Team Forming Contest 2 (26-8-2017) (2015)/E - Primes on Intervalv2.cpp ///*input // //*/ //#include<bits/stdc++.h> //using namespace std; //#define ll long long int //int a,b,k; //#define MAX 1000007 //#define LMT sqrt(MAX) // //unsigned base[MAX/64],nprimes[MAX]; // //#define chkS(x,n) (x[n>>6]&(1<<((n>>1)&31))) //#define setS(x,n) (x[n>>6]|=(1<<((n>>1)&31))) // //void sieve() //{ // unsigned i, j, k; // for(i=3; i<LMT; i+=2) // if(!chkS(base, i)) // for(j=i*i, k=i<<1; j<MAX; j+=k) // setS(base, j); // nprimes[1]=0,nprimes[2]=1; // ll sum=1; // for(j=3;j<MAX;j++) // { // if(j%2==0) // { // nprimes[j]=nprimes[j-1]; // } // else if(!chkS(base,j)) // { // nprimes[j]=nprimes[j-1]+1; // } // else // { // nprimes[j]=nprimes[j-1]; // } // } //} //inline bool ok(int l) //{ // for(int x=a;x<=b-l+1;x++) // { // int y=x+l-1; // if(nprimes[y]-nprimes[x-1]<k) // return 0; // } // return 1; //} //int bs(int l,int r) //{ // int ans=-1; // while(l<=r) // { // int mid=(l+r)/2; // /*cout << mid << " " << ok(mid) << endl;*/ // if(ok(mid)) // { // ans=mid; // r=mid-1; // } // else // { // l=mid+1; // } // } // return ans; //} //int main() //{ // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); // sieve(); // cin >> a >> b >> k; // /*cout << nprimes[10] << " " << nprimes[6] << endl; // cout << ok(4) << endl;*/ // int ans=bs(1,b-a+1); // cout << ans << endl; // return 0; //} int lca(int u, int v) { if(depth[v]<depth[u]) swap(u,v); int diff=depth[v]-depth[u]; for(int i=0;i<level;i++) if((diff>>i)&1) v=par[v][i]; if(v==u) return v; for(int i=level;i>=0;i--) if(par[u][i]!=par[v][i]) { u=par[u][i]; v=par[v][i]; } return par[u][0]; } <file_sep>/Codeforces/B numbers/Critical Links.cpp #include<bits/stdc++.h> using namespace std; vector<int>gh[10007]; vector< pair<int,int> >bridges; int dis[10007],low[10007]; int ti=0; void art(int u,int p) { dis[u]=low[u]=ti++; for(int i=0;i<gh[u].size();i++) { int v=gh[u][i]; if(v==p) continue; if(dis[v]==-1) { art(v,u); low[u]=min(low[u],low[v]); if(dis[u]<low[v]) { bridges.push_back({min(u,v),max(u,v)}); } } else low[u]=min(low[u],dis[v]); } } int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); int tc; cin >> tc; for(int qq=1; qq<=tc; qq++) { int n; cin >> n; getchar(); for(int i=0; i<=n; i++) { gh[i].clear(); } for(int i=0; i<n; i++) { string str; getline(cin,str); for(int i=0; i<str.size(); i++) { if(str[i]=='(' or str[i]==')')str[i]=' '; } stringstream ss; ss<<str; int u,nv; ss>>u,ss>>nv; int v; while(nv--) { ss>>v; gh[u].push_back(v); } } memset(dis,-1,sizeof dis); ti=0; bridges.clear(); for(int i=0;i<n;i++) { if(dis[i]==-1) { art(i,-1); } } sort(bridges.begin(),bridges.end()); cout << "Case " << qq << ":" << '\n'; cout << bridges.size() << " critical links" << '\n'; // cout << "kaaj sesh " << endl; for(int i=0;i<bridges.size();i++) { cout << bridges[i].first << " - " << bridges[i].second << '\n'; } } return 0; } /* 3 8 0 (1) 1 1 (3) 2 0 3 2 (2) 1 3 3 (3) 1 2 4 4 (1) 3 7 (1) 6 6 (1) 7 5 (0) 0 2 0 (1) 1 1 (1) 0 */ <file_sep>/USACO/Section 1.3/Combination Lock.cpp /* ID:shishir10 LANG:C++11 TASK:combo */ #include<bits/stdc++.h> using namespace std; int n; bool f(int a,int b) { if(abs(a-b)<=2) return 1; if(abs(a-b)>=n-2) return 1; return 0; } bool check(int i,int j,int k,int a,int b,int c) { return ( f(i,a) and f(j,b) and f(k,c) ); } int main() { freopen("combo.in","r",stdin); freopen("combo.out","w",stdout); int a,b,c,d,e,f; cin >> n; cin >> a >> b >> c >> d >> e >> f ; int cnt=0; for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { for(int k=1;k<=n;k++) { if( check(i,j,k,a,b,c) or check(i,j,k,d,e,f) ) { cnt++; // cout << i << " " << j << " " << k << endl; } } } } cout << cnt << endl; return 0; } <file_sep>/Codeforces/B numbers/A. Lucky Year.cpp #include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); string str; cin >> str; long long int g=0; for(int i=0;i<str.size();i++) { g*=10; g+=(str[i]-'0'); } // cout << "its g " << g << endl; int t=(str[0]-'0'+1); int tt=0; for(int i=1;i<str.size();i++) { if(str[i]!='0') { tt=1; } t*=10; } // cout << " its t " << t << endl; cout << t-g << '\n'; return 0; } <file_sep>/Codeforces/Contests/191/E. Axis Walking.cpp #include<bits/stdc++.h> #define pii pair<int,int> #define tii pair<int,pair<int,int> > #define fs first #define sc second #define DB cout<<"*****"<<endl; #define mod 1000000007 #define inf 1000000007 #define pi acos(-1.0) #define sf scanf #define pf printf #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define pcase(x) printf("Case %d: ",x) #define ll long long int #define maxn 100007 using namespace std; bool chk(int n,int ps) { return (bool)(n&(1<<ps)); } int ara[27],sp[5]; vector<pii> subset_gen( vector<int>& vt ) { vector< pii > ans; int n=vt.size(); int num=1<<n; for(int i=1;i<num;i++) { int cnt=0,sum=0; for(int j=0;j<7;j++) { if(chk(i,j)) { cnt++; sum+=vt[j]; } } ans.push_back( {sum,cnt} ); } return ans; } map< int , int >mp; void subset_map( vector<int>& vt ) { int n=vt.size(); int num=1<<n; for(int i=1;i<num;i++) { int cnt=0,sum=0; for(int j=0;j<7;j++) { if(chk(i,j)) { cnt++; sum+=vt[j]; } } mp[sum]=cnt; } } ll fac[27]; void fact() { fac[1]=1; for(ll i=2;i<25;i++) { fac[i]=(fac[i-1]*i)%mod; } } int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); vector<int>temp={1,2,3}; subset_gen( temp ); fact(); int n; sf1(n); int sum=0 for(int i=0;i<n;i++) { sf1(ara[i]); sum+=ara[i]; } int k; sf1(k); if(k==0) { pf1ll(fac[n]); } else if(k==1) { ll myans = fac[n]; int mid=n/2; vector<int>f; for(int i=0;i<mid;i++) { f.push_back(ara[i]); } vector<pii>subf = subset_gen(f); vector<int>s; for(int i=mid;i<n;i++) { s.push_back(ara[i]); } subset_map(s); for(int i=0;i<subf.size();i++) { int b=sum-subf[i].first; int a=n-subf[i].second; if(mp[b]==a) { a*=subf[i].second; ans-=a; } } } return 0; } /* */ <file_sep>/Codechef/Contests/August Long Challenge 2017/P - Parity.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int void compute_lps(string pat,int *lps) { lps[0]=0; int len=0,i=1; while(i<pat.size()) { if(pat[i]==pat[len]) { lps[i]=len+1; len++,i++; } else { if(len!=0) { len=lps[len-1]; } else { lps[i]=0; i++; } } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string a,b; cin >> a >> b; string t; t+=b; t+='#'; t+=a; int lps[1007]; compute_lps(t,lps); int tt=lps[t.size()-1]; int id=t.size()-1; string c,d; for(int i=0;i<a.size()-tt;i++) { c+=a[i]; } for(int i=a.size()-tt;i<a.size();i++) { d+=a[i]; } /*cout << c << " " << d << endl;*/ int od=0; for(auto i:d) { if(i=='1') od++; } int oc=0; for(auto i:c) { if(i=='1') oc++; } int ob=0; for(auto i:b) { if(i=='1') ob++; } int nd=ob-od; if(nd<=oc) { cout << "YES" ; } /*else if(nd==1 and oc%2==1) { cout << "YES"; }*/ else { cout << "NO"; } return 0; }<file_sep>/Contest/Individual Practice Contest 4/C. Array.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 200007 ll fac[maxn],inv[maxn]; ll bigmod(ll b,ll p) { ll ans=1; while(p) { if(p&1) ans = (ans*b) % mod ; p>>=1; b = (b*b) % mod; } return ans%mod; } void pre() { fac[0] = 1; inv[0] = 1; for(ll i=1;i<maxn;i++) { fac[i] = (fac[i-1]*i) % mod; inv[i] = ( inv[i-1] * bigmod(i,mod-2) ) % mod; } } ll ncr(ll n,ll r) { ll nu = ( fac[n] * inv[r] ) % mod; ll t = ( nu*inv[n-r] ) % mod; return t; } int main() { pre(); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll n; cin >> n; ll ans = ncr(2LL*n-1,n-1) % mod; ans*=2LL; ans-=n; cout << (ans+mod) % mod << endl; return 0; } /* */ <file_sep>/LightOJ/1017 - Brush (III).cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int n,w,k,x[107],y[107]; ll dp[107][107]; ll rec(int ps,int t) { if(ps>=n || t<=0) return 0; ll &ret=dp[ps][t]; if(ret!=-1) return ret; int i; for(i=ps ;y[i]-y[ps]<=w && i<n ;i++ ); ret=max(i-ps+rec(i,t-1),rec(ps+1,t)); return ret; } int main() { int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { sf("%d %d %d",&n,&w,&k); for(int i=0 ;i<n ;i++ ) { sf("%d %d",&x[i],&y[i]); } sort(y,y+n); memset(dp,-1,sizeof dp); ll ans=rec(0,k); pf("Case %d: %lld\n",qq,ans); } return 0; } /* */ <file_sep>/Contest/ACM ICPC Dhaka Regional 2017 Online Preliminary Round Hosted by University of Asia Pacific/II.cpp #include <algorithm> #include <cassert> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <fstream> #include <iomanip> #include <iostream> #include <iterator> #include <list> #include <map> #include <numeric> #include <queue> #include <stack> #include <set> #include <string> #include <vector> #define LL long long #define FF first #define SS second #define PB push_back #define MP make_pair #define all(cont) cont.begin(), cont.end() #define rall(cont) cont.end(), cont.begin() #define D(x) cout << #x " is " << x << endl using namespace std; typedef vector<int> VI; typedef vector<VI> VVI; typedef pair<int, int> PII; typedef vector<PII> VII; typedef vector<string> VS; const int INF = 2000000009; const int MX = 100005; const double EPS = 1e-9; const int MOD = 1000000007; /*******************************************************/ int power(int b,int p) { if (b==0) return b; int ret = 1; for (int i = 0;i<p;i++) ret*=b; return ret; } int main() { //std::ios_base:ync_with_stdio(false); int tc,cn = 0; scanf("%d",&tc); while (tc--) { char a[MX],b[MX]; scanf("%s%s",a,b); int r = 0; int la = strlen(a); if (a[0]=='0'){ printf("0\n"); continue; } for (int i = 0;i<la;i++) { r+=a[i]-'0'; r%=9; } if (r==0) r = 9; int lb = strlen(b); int temp = 1; int ans = 1; for (int i = lb-1;i>=0;i--) { ans*=(power(temp,b[i]-'0')); ans%=9; temp= power(temp,10)%9; } if(ans==0) ans = 9; printf("%d\n",ans); } return 0; } <file_sep>/Codeforces/Contests/Educational Codeforces Round 26/B. Flag of Berland.cpp #include<bits/stdc++.h> using namespace std; vector<string>vt; int n,m; int chk_row() { if(n%3!=0) return 0; int a=n/3; char ch=vt[0][0]; for(int i=0; i<a; i++) { for(int j=0; j<m; j++) { if(vt[i][j]!=ch) { return 0; } } } ch=vt[a][0]; for(int i=a; i<a+a; i++) { for(int j=0; j<m; j++) { if(vt[i][j]!=ch) { return 0; } } } ch=vt[a+a][0]; for(int i=a+a; i<n; i++) { for(int j=0; j<m; j++) { if(vt[i][j]!=ch) { return 0; } } } return 1; } int chk_col() { if(m%3!=0) return 0; int a=m/3; char ch=vt[0][0]; for(int i=0; i<n; i++) { for(int j=0; j<a; j++) { if(vt[i][j]!=ch) { return 0; } } } ch=vt[0][a]; for(int i=0; i<n; i++) { for(int j=a; j<a+a; j++) { if(vt[i][j]!=ch) { return 0; } } } ch=vt[0][a+a]; for(int i=0; i<n; i++) { for(int j=a+a; j<m; j++) { if(vt[i][j]!=ch) { return 0; } } } return 1; } int main() { cin >> n >> m; for(int i=0; i<n; i++) { string t; cin >> t; vt.push_back(t); } if(chk_row()||chk_col()) { cout << "YES"; } else { cout << "NO"; } return 0; } <file_sep>/Contest/SPC Individual Contest 02 [18-03-2017]/B - Heavy Cargo.cpp #include<bits/stdc++.h> using namespace std; #define DB printf("*****\n") #define sf scanf #define pf printf #define ll long long int #define maxn 207 #define pii pair<int,int> #define inf 2147483645 vector<pii>vt[maxn]; int n,r; struct comp { bool operator ()(pii &a,pii &b) { return a.second>b.second; } }; int dijkstra(int src,int des) { int dist[maxn]; for (int i=1; i<=n ; i++ ) { dist[i]=-inf; } priority_queue<pii,vector<pii>,comp>Q; Q.push(pii(src,inf)); dist[src]=inf; while(!Q.empty()) { int u=Q.top().first; Q.pop(); for (int i=0; i<vt[u].size() ; i++ ) { int v=vt[u][i].first; int w=vt[u][i].second; if(min(dist[u],w)>dist[v]) { dist[v]=max(dist[v],min(dist[u],w) ); Q.push(pii(v,dist[v])); } } } return dist[des]; } int main() { int tc=1; while(sf("%d %d",&n,&r)==2) { if(n==0 and r==0) return 0; for(int i=0; i<=n; i++) { vt[i].clear(); } map<string,int>mp; int mpv=1; for(int i=0; i<r; i++) { string u,v; int w; cin >> u >> v >> w; if(mp.find(u)==mp.end()) { mp[u]=mpv++; } if(mp.find(v)==mp.end()) { mp[v]=mpv++; } vt[mp[u]].push_back({mp[v],w}); vt[mp[v]].push_back({mp[u],w}); } string u,v; cin >> u >> v; int ans=dijkstra(mp[u],mp[v]); pf("Scenario #%d\n",tc++); pf("%d tons\n\n",ans); } return 0; } /* 2 3 2 1 2 50 2 3 10 */ <file_sep>/Codeforces/Contests/Codeforces Round #405(Div. 1)/test.cpp #include <bits/stdc++.h> using namespace std; const int nax = 2e5 + 5; vector<int> edges[nax]; int count_subtree[nax][5]; int total_subtree[nax]; long long answer; int n, k; int subtract(int a, int b) { return ((a - b) % k + k) % k; } void dfs(int a, int par, int depth) { count_subtree[a][depth % k] = total_subtree[a] = 1; for(int b : edges[a]) if(b != par) { dfs(b, a, depth + 1); for(int i = 0; i < k; ++i) for(int j = 0; j < k; ++j) { // compute distance modulo k int remainder = subtract(i + j, 2 * depth); // compute x such that (distance + x) is divisible by k int needs = subtract(k, remainder); answer += (long long) needs * count_subtree[a][i] * count_subtree[b][j]; } for(int i = 0; i < k; ++i) count_subtree[a][i] += count_subtree[b][i]; total_subtree[a] += total_subtree[b]; } // in how many pairs we will count the edge from 'a' to its parent? answer += (long long) total_subtree[a] * (n - total_subtree[a]); } int main() { scanf("%d%d", &n, &k); for(int i = 0; i < n - 1; ++i) { int a, b; scanf("%d%d", &a, &b); edges[a].push_back(b); edges[b].push_back(a); } dfs(1, -1, 0); assert(answer % k == 0); printf("%lld\n", answer / k); }<file_sep>/Codeforces/Contests/8VC Venture Cup 2017 - Elimination Round/B. PolandBall and Game.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { int p,e; cin >> p >> e; string pw[p+7],ew[e+7]; for(int i=0 ;i<p ;i++ ) { cin >> pw[i]; } int cnt=0; for(int i=0 ;i<e ;i++ ) { cin >> ew[i]; for(int j=0 ;j<p ;j++ ) { if(pw[j]==ew[i]) { cnt++; } } } if(cnt%2==1) { p++; } if(p>e) { cout << "YES"; } else cout << "NO"; return 0; } /* */ <file_sep>/Marathon/Weekly Marathon #3 by DJ/b.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int bool is_prime(ll t) { if(t==1) return 0; else if(t==2) return 1; else if(t%2==0) return 0; ll sq=sqrt(t); for(ll i=3;i<=sq;i+=2) { if(t%i==0) return 0; } return 1; } int main() { int n; cin >> n; while(n--) { ll t; cin >> t; ll sq=sqrt(t); if(sq*sq==t and is_prime(sq) ) { cout << "YES\n"; } else { cout << "NO\n"; } } return 0; } <file_sep>/Codeforces/B numbers/sum of sub.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 struct data { int val=0,ps=0; }; bool cmp(data a,data b) { if(a.val!=b.val) { return a.val<b.val; } return a.ps>b.ps; } data ara[maxn]; ll res[maxn]; int tree[maxn]; void shift(int id,int l,int r) { if(l==r) { res[l]+=lazy[id]; } else { lazy[id*2]=lazy[id]; lazy[id*2+1]=lazy[id]; } lazy[id]=0; } void updt(int id,int l,int r,int ps) { if(l>ps || r<ps) return; if(l>=ps && r<=ps) { tree[id]=1; return; } } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int n; sf("%d",&n); for(int i=1 ;i<=n ;i++ ) { sf("%d",&ara[i].val); ara[i].ps=i; } return 0; } /* */ <file_sep>/Python/a.py print(3+6) player =[1,2,3,4,34,54]; print(player) player.append(32); print(player); temp = player[2:5]; print("temp"); print(temp); a=8 print(a) <file_sep>/LightOJ/1282 - Leading and Trailingv2.cpp #include<bits/stdc++.h> using namespace std; long long int bgmd(long long int b,long long int p) { long long int ans=1; while(p>0) { if(p&1) { ans%=1000; ans*=b; ans%=1000; } b=(b*b)%1000; p>>=1; } return ans; } int main() { int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { double n,k; cin >> n >> k; int trail=bgmd(n,k); double t=k*log(n)/log(10); int tt=floor(t); double a=pow(10,t-tt); // cout << setprecision(10) << a << endl; int b=(a+.00001)*100; int c=(a-.00001)*100; if(b>=1000) b/=10; // cout << b << " " << c << endl; printf("Case %d: %02d %03d\n",qq,b,trail); } return 0; } <file_sep>/Contest/SPC Individual Contest 02 [18-03-2017]/PICK UP DROP ESCAPE.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int ara[78]; int n,k; int mx=0; void rec(int ps,int rem,int x) { // cout << x << endl; if(ps>=n) { if(rem==0) { mx=max(mx,x); } return ; } rec(ps+1,rem-1,x^ara[ps]); rec(ps+1,rem,x); } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); // const clock_t begin_time = clock(); int tc; cin >> tc; while(tc--){ cin >> n >> k ; for(int i=0;i<n;i++) cin >> ara[i]; mx=0; rec(0,k,0); cout << mx << '\n'; } // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/Contest/Battle of Brains, 2017 (Replay)/Counting Murgis.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int n,k; ll dp[30][30]; ll rec(int ps,int prev) { if(ps>=k) return 1; ll &ret=dp[ps][prev]; if(ret!=-1) return ret; ret=0; int i=prev+1; for(;i<n;i++) { ret+=rec(ps+1,i); } return ret; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; while(tc--) { cin >> n >> k; memset(dp,-1,sizeof dp); ll ans=rec(0,0); cout << ans << endl; } return 0; }<file_sep>/LightOJ/test.cpp #include <stdio.h> #include <string.h> #include <stdlib.h> #define rep(i,n) for(i=0;i<(n);i++) #define max(a,b) (((a)>(b))?(a):(b)) #define MAXN 105 int n, m; int a[MAXN][MAXN]; int dp[MAXN][MAXN][MAXN][3]; int go(int row, int c1, int c2, int nextMove) { if(row == n-1 && c2 == m-1 && c1 == m-2 && nextMove == 0) return 0; if(dp[row][c1][c2][nextMove] != -1) return dp[row][c1][c2][nextMove]; int &res = dp[row][c1][c2][nextMove]; res = 0; if(nextMove == 0) //move the left one to the right { if(c1+1 < c2) res = max(res, go(row, c1+1, c2, 0) + a[row][c1+1]); res = max(res, go(row, c1, c2, 1)); //finished moving } else if(nextMove == 1) //move the right one to the right { if(c2+1 < m) res = max(res, go(row, c1, c2+1, 1) + a[row][c2+1]); if(c2 > c1) res = max(res, go(row, c1, c2, 2)); //finished moving } else //move both to the immediate bottom row { if(c1 < c2 && row+1 < n) res = max(res, go(row+1, c1, c2, 0) + a[row+1][c1] + a[row+1][c2]); } return res; } int main() { int T, kase=1, i, j; int res; scanf(" %d",&T); while(T--) { scanf(" %d %d",&n,&m); rep(i,n) rep(j,m) scanf(" %d",&a[i][j]); printf("Case %d: ",kase++); memset(dp, -1, sizeof(dp)); res = go(0, 0, 0) + a[0][0]; printf("%d\n",res); } return 0; } <file_sep>/Contest/SPC Individual Contest 03 [19-03-2017]/C - Square.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int d; vector<int>vt; vector<int>ara; vector< vector<int> > all; int flag[100000]; int temp[100000]; int n; void rec(int ps) { if(ps>=n) { int s=0; for(int i=0;i<vt.size();i++) { s+=vt[i]; } if(s==d) { all.push_back(vt); } return; } vt.push_back(ara[ps]); rec(ps+1); vt.pop(); rec(ps+1); } int main() { // freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); // const clock_t begin_time = clock(); int tc; cin >> tc; while(tc--) { cin >> n; int sum=0; for(int i=0;i<n;i++) { int t; cin >> t; push_back(t) sum+=t; } // sort(ara,ara+n); if(!(sum%4)) { cout << "no" << '\n'; continue; } else if(ara[n-1]>=sum/4) { cout << "no" << '\n'; continue; } rec(0); if(all.size()<4) { cout << "no" << '\n'; else { for(int i=0;i<all.size();i++) { for(int j=i+1;j<all.size();j++) { for(int k=j+1;j<all.size();j++) { for(int l=k+1;k<all.size();k++) { if(all[i]+all[j]+all[k]+all[l]==ara) { cout << "yes" << endl; } } } } } } } // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/Codeforces/Contests/Codeforces Round 389 (Div.2)/B. Santa Claus and Keyboard Check.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { string pat,text; cin >> pat >> text; map<char,char>mp; map<char,char>::iterator it,it1; map<char,char>mpp; for(int i=0 ;i<pat.size() ;i++ ) { it=mp.find(pat[i]); it1=mpp.find(text[i]); if(it==mp.end()) { mp[pat[i]]=text[i]; } else { if(it->second!=text[i]) { cout << "-1" << '\n'; return 0; } } if(it1==mpp.end()) { mpp[text[i]]=pat[i]; } else { if(it1->second!=pat[i]) { cout << "-1" << '\n'; return 0; } } } vector<char>vt; for(it=mp.begin() ;it!=mp.end() ;it++ ) { if(it->fs!=it->sc) { if(find(vt.begin(),vt.end(),it->fs)!=vt.end() and find(vt.begin(),vt.end(),it->sc)!=vt.end()) continue; vt.push_back(it->fs); vt.push_back(it->sc); } } for(int i=0 ;i<vt.size() ;i++ ) { int cnt=0; for(int j=0 ;j<vt.size() ;j++ ) { if(vt[i]==vt[j]) cnt++; } if(cnt>1) { cout << "-1" << '\n'; return 0; } } cout << vt.size()/2 << endl; for(int i=0 ;i<vt.size() ;i+=2 ) { cout << vt[i] << ' ' << vt[i+1] << '\n'; } return 0; } /* */ <file_sep>/Marathon/Weekly Marathon #5 by DJ/I - Igor In the Museumv2.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int vector<string>grid; int ans=0; int vis[1007][1007]; int fx[]={1,-1,0,0}; int fy[]={0,0,-1,1}; void dfs(int ux,int uy,int flag) { if(flag==1) { vis[ux][uy]=ans; } if(flag==0) { vis[ux][uy]=1; } for(int i=0;i<4;i++) { int vx=ux+fx[i]; int vy=uy+fy[i]; if(flag==0 and grid[vx][vy]=='*') { ans++; } if(grid[vx][vy]=='.' and vis[vx][vy]==flag) { dfs(vx,vy,flag); } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,m,k; cin >> n >> m >> k; for(int i=0;i<n;i++) { string t; cin >> t; grid.push_back(t); } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(grid[i][j]=='.' and vis[i][j]==0) { ans=0; dfs(i,j,0); dfs(i,j,1); } } } while(k--) { int r,c; cin >> r >> c; r--,c--; cout << vis[r][c] << endl; } return 0; }<file_sep>/Codeforces/Contests/Codeforces Round #459/B. Radio Station.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 int ara[6000],flag[6000]; int main() { ios_base::sync_with_stdio(0); int n,m; cin >> n >> m; map<string,string>mp; for(int i=0;i<n;i++) { string name,ip; cin >> name >> ip; mp[ip]=name; } for(int i=0;i<m;i++) { string a,b; cin >> a >> b; int sz=b.size(); string c = b.substr(0,sz-1); cout << a << " " << b << " #" << mp[c] << endl; // cout << c << endl; } return 0; } /* */ <file_sep>/LightOJ/1211 - Intersection of Cubes.cpp #include<bits/stdc++.h> using namespace std; int main() { int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n; cin >> n; int x1[n+7],y1[n+7],z1[n+7],x2[n+7],y2[n+7],z2[n+7]; for(int i=0;i<n;i++) { cin >> x1[i] >> y1[i] >> z1[i] >> x2[i] >> y2[i] >> z2[i]; } int xh=0,xl=2000,yh=0,yl=2000,zh=0,zl=2000; for(int i=0;i<n;i++) { xl=min(xl,x2[i]); xh=max(xh,x1[i]); yl=min(yl,y2[i]); yh=max(yh,y1[i]); zl=min(zl,z2[i]); zh=max(zh,z1[i]); } // cout << xl << " " << xh << endl; long long int ans= (xl-xh) * (yl-yh) * (zl-zh); if(ans<0) ans=0; cout << "Case " << qq << ": " << ans << '\n'; } return 0; } <file_sep>/USACO/Section 1.4/Arithmetic Progressions.cpp /* ID:shishir10 LANG:C++11 TASK:ariprog */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { freopen("ariprog.in","r",stdin); freopen("ariprog.out","w",stdout); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,m; cin >> n >> m; bool vis[m*m+m*m+7]; memset(vis,0,sizeof vis); vector<int>vt; int mx=INT_MIN; for(int i=0;i<=m;i++) { for(int j=0;j<=m;j++) { int t=i*i+j*j; if(!vis[t]) { vis[t]=1; vt.push_back(t); mx=max(mx,t); } } } sort(vt.begin(),vt.end()); vector< pair<int,int> >ans; for(int i=0;i<vt.size();i++) { for(int j=i+1;j<vt.size();j++) { int f=1; if(vt[i]+(vt[j]-vt[i])*(n-1)>mx) break; for(int cnt=0;cnt<n;cnt++) { ll t=vt[i]+(vt[j]-vt[i])*cnt; if(!vis[t]) { f=0; } if(t>mx) break; } if(f) { ans.push_back({vt[j]-vt[i],vt[i]}); } } } sort(ans.begin(),ans.end()); if(ans.empty()) { cout << "NONE" << endl; } else { for(int i=0;i<ans.size();i++) { cout << ans[i].second << " " << ans[i].first << endl; } } return 0; } <file_sep>/Spoj/DQUERY - D-query.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 200000+7 int block; struct data { int l,r,idx; bool operator < (const data &a) const { if(l/block!=a.l/block) return l/block < a.l/block; return r < a.r; } }Q[maxn]; // the size of the cnt should be equal to largest element of the array int ara[maxn],cnt[1000000+7],ans[maxn],counti=0; inline void add(int ps) { cnt[ara[ps]]++; if(cnt[ara[ps]]==1) counti++; } inline void remove(int ps) { cnt[ara[ps]]--; if(cnt[ara[ps]]==0) counti--; } int main() { int n; cin >> n; block=sqrt(n); for(int i=1;i<=n;i++) { scanf("%d", &ara[i]); /*cin >> ara[i];*/ } int m; cin >> m; for(int i=0;i<m;i++) { scanf("%d %d",&Q[i].l, &Q[i].r); /*cin >> Q[i].l >> Q[i].r;*/ Q[i].idx=i; } int curL=0,curR=0; sort(Q,Q+m); for(int i=0;i<m;i++) { while(curL < Q[i].l) remove(curL++); while(curL > Q[i].l) add(--curL); while(curR < Q[i].r) add(++curR); while(curR > Q[i].r) remove(curR--); ans[Q[i].idx]=counti; } for(int i=0;i<m;i++) printf("%d\n",ans[i]); return 0; }<file_sep>/Contest/Individual Practice Contest 8/e.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 1000007 ll bigmod(ll a,ll b,ll m) { /// a^b%m ll ans=1; while(b>0LL) { if(b&1LL) ans=(a*ans)%m; b>>=1LL; a=(a*a)%m; } return ans; } vector<int>vt; void div(int b) { int sq=sqrt(b)+5; for(int i=1;i<sq;i++) { if(b%i==0) { vt.push_back(i); vt.push_back(b/i); } } sort(vt.begin(),vt.end()); } int main() { ios_base::sync_with_stdio(0); ll a,b,p,x; cin >> a >> b >> p >> x ; div(b); int cnt=0; for(int i=0;i<vt.size()&&vt[i]<=x;i++) { ll x = bigmod(a,vt[i],p); ll y = (x*vt[i])%p; if(y==b) { cnt++; } } cout << cnt << endl; return 0; } /* */ <file_sep>/LightOJ/1205 - Palindromic Numbers.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 #define sf scanf #define pf printf char str[20]; ll dp[20][3]; int l; ll rec(int ps,int flag) { cout << ps << " " << l/2 << endl; if(ps>=l/2) { return 1; } ll &ret = dp[ps][flag] ; int d = flag==1 ? str[ps]-'0' : 9 ; ret=0; for(int i=0; i<=d; i++) { ret+= rec(ps+1,i<d ? 0 : flag ); } return ret; } int main() { l=sprintf(str,"%lld",33LL); memset(dp,-1,sizeof dp); if(l&1)l++; cout << l << "**" << endl; ll bb= rec(0,1); cout << bb << " final " << endl; int tc; sf("%lld", & tc); for(int qq=1; qq<=tc; qq++) { ll a,b; sf("%lld %lld", &a, &b); l=sprintf(str,"%lld",b); memset(dp,-1,sizeof dp); reverse(str,str+l); if(l&1)l++; cout << l << endl; ll bb= rec(0,1); cout << bb << endl; l = sprintf(str,"%lld",a-1); if(l&1)l++; cout << l << endl; ll aa= rec(0,0); cout << bb-aa << endl; } return 0; } <file_sep>/Marathon/Weekly Marathon #7 by DJ/J - The Meaningless Game.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; while(n--) { ll a,b; cin >> a >> b; ll mult=a*b; ll t=pow(mult,1.0/3.0)-2; while(t*t*t<mult) { t++; } if(t*t*t==mult and a%t==0 and b%t==0) { cout << "YES" << endl; } else { cout << "NO" << endl; } } return 0; }<file_sep>/LightOJ/1058 - Parallelogram Counting.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { int tc; scanf("%d",&tc); for(int qq=1;qq<=tc;qq++) { int n; scanf("%d",&n); ll x[n+7],y[n+7]; for(int i=0;i<n;i++) { scanf("%lld %lld",&x[i],&y[i]); } vector< pair<ll,ll> > vt; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { ll mx=x[i]+x[j], my=y[i]+y[j]; vt.push_back(make_pair(mx,my)); } } sort(vt.begin(),vt.end()); ll ans=0,cnt=1; // cout << "vt size " << vt.size() << endl; for(int i=1;i<vt.size();i++) { // cout << vt[i].first << " " << vt[i].second << " --->> " << vt[i-1].first << " " << vt[i-1].second << endl; if(vt[i]==vt[i-1]) { cnt++; } else { ans+=( cnt*(cnt-1)/2 ); cnt=1; } } ans+=cnt*(cnt-1)/2; cout << "Case " << qq << ": " << ans << endl; } return 0; } <file_sep>/Contest/Team Forming Contest 2 (26-8-2017) (2015)/B - Books.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,k; cin >> n >> k; vector<int>vt; for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back(t); } ll sum=0; int mx=INT_MIN,st=0; for(int i=0;i<vt.size();i++) { sum+=vt[i]; while(sum>k) { sum-=vt[st]; st++; } mx=max(mx,i-st+1); } cout << mx << endl; return 0; }<file_sep>/Contest/SPC Individual Contest 04 [21-03-2017]/B - Queue.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); // const clock_t begin_time = clock(); int n; cin >> n; vector< pair<int,int> > vt; for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back(pair<int,int>(t,i) ); } sort(vt.begin(),vt.end()); int ps=-1; for(int i=0;i<n;i++) { if(vt[i].sc>ps) ps=vt[i].sc; vt[i].fs=vt[i].sc; vt[i].sc=ps-vt[i].sc-1; } sort(vt.begin(),vt.end()); for(int i=0;i<n;i++) { cout << vt[i].sc << " " ; } // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/Marathon/Weekly Marathon #7 by DJ/H - Little Girl and Maximum XOR.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { const clock_t begin_time = clock(); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll a,b; cin >> a >> b; ll temp=a^b; ll ans=1; while(temp) { ans<<=1; temp>>=1; } cout << ans-1 ; /*cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC;*/ return 0; }<file_sep>/Contest/Individual Practice Contest 7/C.cpp #include<bits/stdc++.h> using namespace std; int n,m,ara[100][100],flag[100][100]; int fx[] = {1,-1,0,0,1,-1,1,-1}; int fy[] = {0,0,1,-1,1,1,-1,-1}; bool ok(int x,int y) { if(x>=0 and x<n and y>=0 and y<m) { return 1; } else return 0; } int cnt=0; void dfs(int x,int y) { cnt++; flag[x][y] = 1; for(int i=0;i<8;i++) { int tx = x + fx[i]; int ty = y + fy[i]; if(ok(tx,ty) and flag[tx][ty] == -1 and ara[tx][ty]==1) { dfs(tx,ty); } } } int main() { ios_base::sync_with_stdio(0); cin >> n >> m; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cin >> ara[i][j]; } } memset(flag,-1,sizeof flag); int ans =0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(flag[i][j] == -1) { cnt=1; dfs(i,j); ans = max(ans,cnt); } } } cout << ans << endl; return 0; } <file_sep>/LightOJ/1050 - Marbles.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 double dp[607][607][7]; double rec(int r,int b,int p) { if(r+b==1) { if(b==1) return 1.0; if(r==1) return 0.0; } double& ret=dp[r][b][p]; if(ret > -0.1) return ret; ret=0.0; if(p==1) { if(r>0) { ret+=( rec(r-1,b,2)*(double)r )/(double)(r+b); } if(b>0) { ret+=( rec(r,b-1,2)*(double)b )/(double)(r+b); } return ret; } if(b>0) ret+= rec(r,b-1,1); return ret; } inline void seti() { for(int i=0; i<507; i++) { for(int j=0; j<507; j++) { for(int k=0; k<5; k++) { dp[i][j][k]=-1.0; } } } } int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; seti(); for(int qq=1; qq<=tc; qq++) { int r,b; cin >> r >> b; double ans=rec(r,b,1); cout << "Case " << qq << ": " << setprecision(10) << fixed << ans << '\n'; } return 0; } <file_sep>/LightOJ/1018 - Brush (IV).cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int n,x[20],y[20]; int same_slope[20][20]; inline bool co_linier(int i,int j,int k) { return (x[j]-x[k]) * (y[i]-y[j]) - (x[i]-x[j]) * (y[j]-y[k]) == 0; } void go() { memset(same_slope,0,sizeof same_slope); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { for(int k=0;k<n;k++) { if(i!=j and co_linier(i,j,k) ) { same_slope[i][j]|=(1<<k); } } } } } int dp[(1<<16)+7]; int rec(int mask) { if(mask==(1<<n)-1) { return 0; } if (__builtin_popcount(mask) == (n - 1)) return dp[mask] = 1; int &ret=dp[mask]; if(ret!=-1) return ret; ret=INT_MAX; int i=0; for (i = 0; ((mask >> i) & 1); ++i); for (int j = 0; j < n; ++j) if ((i != j) && !((mask >> j) & 1)) ret = min(ret, rec(mask | same_slope[i][j]) + 1); return ret; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { cin >> n; for(int i=0;i<n;i++) { cin >> x[i] >> y[i]; } go(); memset(dp,-1,sizeof dp); int ans=rec(0); cout << "Case " << qq << ": " << ans << endl; } return 0; }<file_sep>/Codeforces/Contests/Codeforces Round #459/B. MADMAX.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 vector<int>gr[500],wt[500]; int dp[500][500][50][5]; int rec(int u,int v,int pre,int mv) { int &ret=dp[u][v][pre][mv]; if(ret != -1) { return ret; } ret=0; if(mv==1) { for(int i=0;i<gr[u].size();i++) { int x = gr[u][i]; int y = wt[u][i]; if(y>=pre) { ret |= ( 1-rec(x,v,y,2) ); } } } else { for(int i=0;i<gr[v].size();i++) { int x = gr[v][i]; int y = wt[v][i]; if(y>=pre) { ret |= ( 1-rec(u,x,y,1) ); } } } return ret; } int main() { int n,m; sf2(n,m); for(int i=0;i<m;i++) { int a,b; char ch; sf2(a,b); sf(" %c",&ch); int t = ch-'a'+1; gr[a].push_back(b); wt[a].push_back(t); } memset(dp,-1,sizeof dp); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(rec(i,j,0,1)) { pf("A"); } else { pf("B"); } } pf("\n"); } return 0; } /* */ <file_sep>/Contest/Individual Practice Contest 1/H - Wedding of Sultan.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 vector<int>gr[100]; string str; void mak() { for(int i=0;i<100;i++) gr[i].clear(); stack<char>st; st.push(str[0]); for(int i=1;i<str.size();i++) { char ch=st.top(); if(ch==str[i]) { st.pop(); } else { // cout << ch << " --> " << str[i] << endl; st.push(str[i]); gr[ch-'A'].push_back(str[i]); gr[str[i]-'A'].push_back(ch-'A'); } } for(int i=0;i<27;i++) { if(!gr[i].empty()) { char ch=i+'A'; cout << ch << " = " << gr[i].size() << endl; } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { cin >> str; cout << "Case " << qq << endl; mak(); } return 0; } <file_sep>/Codeforces/Contests/Educational Codeforces Round 26/D. Round Subset.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int pair<int,int>vt[207]; pair<int,pair<int,int> > dp[207][207]; pair<int,int> five_two(ll a) { ll cnt=0; while(a%2==0) { cnt++; a/=2; } ll cntt=0; while(a%5==0) { cntt++; a/=5; } return {cnt,cntt}; } ll ans=0; ll n,k; void rec(int ps,int cnt) { if(cnt==k) { ans=max(ans,min(dp[ps][cnt].first,dp[ps][cnt].second)); } if(ps>=n) { return {0,{0,0}}; } pair<int,pair<int,int> >& ret=dp[ps][cnt]; if(ret!={0,{0,0}}) return ret; pair<int,pair<int,int> > temp1=rec(ps+1,cnt+1) } int main() { cin >> n >> k; for(int i=0;i<n;i++) { ll t; cin >> t; vt.push_back(five_two(t)); } } <file_sep>/Contest/Team Forming Contest 4 (09-09-2017) (2015)/E - Mobile SMS.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string ara[]={" ",".,\?\"","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { string ans; int n; cin >> n; int key[n+7],no[n+7]; for(int i=0;i<n;i++) { cin >> key[i]; } for(int i=0;i<n;i++) { int t; cin >> t; ans+=ara[key[i]][t-1]; } cout << ans << endl; } return 0; }<file_sep>/Print/digit dp.cpp ///the number of integers in the range [A, B] which //are divisible by K and the sum of its digits is also divisible by K #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int dp[12][93][93][3]; ll a,b,k; int l; char vt[12]; int rec(int ps,int dgt_sum,int num,int flag) { if(ps==l) { if(dgt_sum%k==0 and num%k==0) return 1; return 0; } int &ret=dp[ps][dgt_sum][num][flag]; if(ret!=-1) return ret; ret=0; int d= flag==1 ? vt[ps]-'0' : 9; for(int i=0 ;i<=d ;i++ ) { ret+=rec(ps+1,(dgt_sum+i)%k,(num*10+i)%k,i<d?0:flag); } return ret; } int main() { int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { sf("%lld %lld %lld",&a,&b,&k); if(k>90) pf("Case %d: 0\n",qq); else if(k==1) pf("Case %d: %lld\n",qq,b-a+1); else { /// sprintf returns koi ta character newya hoice l=sprintf(vt,"%lld",a-1); memset(dp,-1,sizeof dp); int aa=rec(0,0,0,1); l=sprintf(vt,"%lld",b); memset(dp,-1,sizeof dp); int bb=rec(0,0,0,1); pf("Case %d: %d\n",qq,bb-aa); } } return 0; } /* */ <file_sep>/Contest/Team Forming Contest 1 (25-8-2017) (2015)/H - Smallest Sub-Array.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n,m,k; cin >> n >> m >> k; int ara[n+7]; ara[1]=1,ara[2]=2,ara[3]=3; for(int i=4;i<=n;i++) { ara[i]=(ara[i-1]+ara[i-2]+ara[i-3])%m+1; } if(mn!=INT_MAX) { cout << "Case " << qq << ": " << mn << endl; } else { cout << "Case " << qq << ": " << "sequence nai" << endl; } } return 0; } <file_sep>/Codeforces/Contests/Educational Codeforces Round 33 (Rated for Div. 2)/C. Rumor.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 vector<int>gr[maxn]; ll gold[maxn]; ll mn; int flag[maxn]; void dfs(int u) { flag[u]=1; mn=min(mn,gold[u]); for(int i=0;i<gr[u].size();i++) { int v=gr[u][i]; if(flag[v]==-1) { dfs(v); } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,m; cin >> n >> m; for(int i=1;i<=n;i++) { cin >> gold[i]; } while(m--) { int x,y; cin >> x >> y; gr[x].push_back(y); gr[y].push_back(x); } ll ans=0; memset(flag,-1,sizeof flag); for(int i=1;i<=n;i++) { if(flag[i]==-1) { mn=INT_MAX; dfs(i); ans+=mn; } } cout << ans << endl; return 0; } <file_sep>/Contest/Individual Practice Contest 1/F - st-Spanning Tree.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 vector<int>gr[maxn]; vector< pair<int,int> > edge; int vist[maxn]; int cl=0; void dfs(int u) { vist[u]=cl; for(int v : gr[u]) { if(vist[v]==-1) { // cout << u << " ---> " << v << endl; edge.push_back({u,v}); dfs(v); } } } int dfs2(int u,int nisi) { vist[u]=-5; set<int>st; for(int v : gr[u]) { if(v==nisi) continue; st.insert(vist[v]); } for(int v : gr[u]) { auto it = st.find(vist[v]); if( it!=st.end()) { if(v==nisi) continue; edge.push_back({u,v}); st.erase(it); } } return st.size(); } int main() { int n,m; sf2(n,m); for(int i=0; i<m; i++) { int u,v; sf2(u,v); gr[u].push_back(v); gr[v].push_back(u); } int s,t,ds,dt; sf2(s,t); sf2(ds,dt); memset(vist,-1,sizeof vist); vist[s]=0; vist[t]=0; for(int i=1; i<=n; i++) { if(vist[i]==-1) { cl++; dfs(i); } } int a= dfs2(s,t); int b= dfs2(t,s); if(a>ds || b>dt) { pf("No\n"); return 0; } for(int i=1; i<=n; i++) { if(vist[i]==-1) { pf("No\n"); return 0; } } pf("Yes\n"); for(int i=0; i<edge.size(); i++) { pf("%d %d\n",edge[i].fs, edge[i].sc); } return 0; } /* */ <file_sep>/Marathon/[15] Weekly Marathon #8 by DJ/A - Not Equal on a Segment.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 200007 int ara[maxn],cnt[1000007]; int block; struct data { int l,r,idx; bool operator < (const data &a)const { if(l/block!=a.l/block) { return l/block < a.l/block; } return r < a.r; } }Q[maxn]; int id[maxn]; inline void add(int ps) { cnt[ara[ps]]++; if(cnt[ara[ps]]==1) { id[ara[ps]]=ps; } } inline void remove(int ps) { cnt[ara[ps]]--; if(cnt[ara[ps]]==0) { id[ara[ps]]=-1; } } int main() { int n,m; scanf("%d %d",&n,&m); for(int i=1;i<=n;i++) scanf("%d",&ara[i]); for(int i=0;i<m;i++) { scanf("%d %d %d",Q[i].l,Q[i].r,Q[i].x); Q[i].idx=i; } sort(Q,Q+m); int curL=0,curR=0; add(0); for(int i=0;i<m;i++) { while(curL<Q.l) remove(curL++); while(culL>Q.l) add(--curL); } return 0; }<file_sep>/Marathon/[15] Weekly Marathon #8 by DJ/J - Judging Moose.cpp #include <algorithm> #include <cassert> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <fstream> #include <iomanip> #include <iostream> #include <iterator> #include <list> #include <map> #include <numeric> #include <queue> #include <stack> #include <set> #include <string> #include <vector> #define LL long long #define FF first #define SS second #define PB push_back #define MP make_pair #define all(cont) cont.begin(), cont.end() #define rall(cont) cont.end(), cont.begin() #define D(x) cout << #x " is " << x << endl using namespace std; typedef vector<int> VI; typedef vector<VI> VVI; typedef pair<int, int> PII; typedef vector<PII> VII; typedef vector<string> VS; const int INF = 2000000009; const int MX = 100005; const double EPS = 1e-9; const int MOD = 1000000007; /*******************************************************/ int main() { std::ios_base::sync_with_stdio(false); return 0; }<file_sep>/Contest/Team Forming Contest 3 (08-09-2017) (2015)/J - TEX Quotes.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { char ch; int f=0; string ss,tt; ss+='\`'; ss+='\`'; tt+='\''; tt+='\''; // cout << ss << " " << tt << endl; while(scanf("%c",&ch)==1) { if(ch==34) { if(f==0) { cout << ss; f=1; } else if(f==1) { cout << tt; f=0; } } else cout << ch ; // printf("%d",ch); } return 0; } <file_sep>/Marathon/SQRT decomposition/A - Little Elephant and Array.cpp /*input */ // d-query problem ac solution #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 2000000+7 ll block; struct data { ll l,r,idx; bool operator < (const data &a) const { if(l/block!=a.l/block) return l/block < a.l/block; return r < a.r; } }Q[maxn]; ll n,m; // the size of the cnt should be equal to largest element of the array ll ara[maxn],ans[maxn],counti=0; int cnt[maxn]; inline void add(ll ps) { if(ara[ps]>n) return; cnt[ara[ps]]++; if(cnt[ara[ps]]==ara[ps]) { counti++; } else if(cnt[ara[ps]] > ara[ps]) { counti--; } } inline void remove(ll ps) { if(ara[ps]>n) return; cnt[ara[ps]]--; if(cnt[ara[ps]]==ara[ps]-1) counti--; if(cnt[ara[ps]]==ara[ps]) { counti++; } } int main() { scanf("%lld %lld",&n, &m); block=sqrt(n); for(ll i=1;i<=n;i++) { scanf("%lld", &ara[i]); cnt[ara[i]]=0; } for(ll i=0;i<m;i++) { scanf("%lld %lld",&Q[i].l, &Q[i].r); Q[i].idx=i; } ll curL=1,curR=1; cnt[ara[1]]++; if(cnt[ara[1]]==ara[1])counti++; sort(Q,Q+m); for(ll i=0;i<m;i++) { while(curL < Q[i].l) remove(curL++); while(curL > Q[i].l) add(--curL); while(curR < Q[i].r) add(++curR); while(curR > Q[i].r) remove(curR--); ans[Q[i].idx]=counti; } for(ll i=0;i<m;i++) printf("%lld\n",ans[i]); return 0; } <file_sep>/Codechef/Contests/August Long Challenge 2017/Chef and Moverv2.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n,d; cin >> n >> d; int ara[n+7]; ll sum=0; for(int i=0;i<n;i++) { cin >> ara[i]; sum+=ara[i]; } if(sum%n!=0) { cout << -1 << endl; } else { ll avg=sum/n,ans=0,f=1; for(int i=0;i<d;i++) { /*cout << "inf " << endl;*/ ll s=0,a=0,prev=0,cnt=0; for(int j=i;j<n;j+=d) { /* cout << ara[j] << " ";*/ s+=ara[j]; ll t=ara[j]+prev; prev=0; if(t>avg) { ll com=t-avg; ans+=com; prev=com; } else if(t<avg) { ll com=avg-t; ans+=com; prev=-com; }/* cout << ara[j] << " " << prev << endl; cout << "ans " << ans << endl;*/ cnt++; } /* cout << endl; cout << "s " << s << endl;*/ if(s%cnt!=0) { f=0; break; } a=s/cnt; if(a!=avg) { f=0; break; } } if(f) { /*cout << "final " << ans << endl;*/ cout << ans << endl; } else { cout << -1 << endl; } } } return 0; } <file_sep>/LightOJ/1137 - Expanding Rods.cpp #include<bits/stdc++.h> using namespace std; #define Pi 2*acos(0.0) double bs(double l,double lprime) { double lo=0,hi=10000,t=-1.0; while(fabs(lo-hi)>0.00000001) { double r=(lo+hi)/2.0; double angle=lprime/r; double temp=2.0*r*sin(angle/2.0); if(fabs(temp-l)<0.00000001) { t=angle; break; } else if(temp<l) { lo=r; } else hi=r; } cout << "angle " << t << endl; return t; } int main() { int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { double l,n,c; cin >> l >> n >> c; double lprime= (1+n*c)*l; cout << lprime << endl; double centerr_angle=bs(l,lprime); double center_angle_degree=180.0*centerr_angle/Pi; double alph=(360.0-center_angle_degree)/2.0; cout << (l/2.0)/(tan(alph)) << endl; } } <file_sep>/Contest/Team Forming Contest 2 (26-8-2017) (2015)/D - Lucky Sum of Digits.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; if(n%7==0) { for(int i=0;i<n/7;i++) { cout << 7; } return 0; } int s=0; int anf=-1,ans=-1; if(n%4==0) { anf=n/4; ans=0; } while(n>=7) { n-=7; s++; if(n%4==0) { anf=n/4; ans=s; } } if(anf==-1 and ans==-1) cout << -1 ; for(int i=0;i<anf;i++) cout << 4 ; for(int i=0;i<ans;i++) cout << 7; return 0; }<file_sep>/Contest/Team Forming Contest 1 (25-8-2017) (2015)/B - Let's Watch Football.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll a,b,c; cin >> a >> b >> c; ll t=a*c-b*c; cout << (t+b-1)/b << endl; return 0; }<file_sep>/Python/first.py print("I hope that it will work") plyer = [45, 343, 43 ] ''' for x in range(1,3,1): print(x) print(plyer[x]) ''' print("<NAME>") for x in plyer: print(x) def func(a,b): return a+b print(func(6,3)) print(5**3) print(25/2)<file_sep>/USACO/Section 1.5/Number Triangles.cpp /* ID:shishir10 LANG:C++11 TASK:numtri */ #include<bits/stdc++.h> using namespace std; #define ll long long int int n; int ara[1000+7][1000+7]; int flag[1000+7][1000+7]; int fx[]={1,1}; int fy[]={0,1}; /*int bfs() { queue< pair<int,pair<int,int> > >Q; Q.push({0,{0,1}}); while(!Q.empty()) { pair<int,pair<int,int> > u=Q.front(); Q.pop(); for(int i=0;i<2;i++) { int vx=u.first+fx[i]; int vy=u.second.first+fy[i]; if(vx>=0 and vx<n and vy>=0 and vy<n and vx<u.second.second+1) { flag[vx][vy]=max(flag[vx][vy],flag[u.first][u.second.second]+ara[vx][vy]); Q.push({vx,{vy,u.second.second+1}}); } } } }*/ void dfs(pair<int,pair<int,int> >u) { for(int i=0;i<2;i++) { int vx=u.first+fx[i]; int vy=u.second.first+fy[i]; if(vx>=0 and vx<n and vy>=0 and vy<n and vx<u.second.second+1) { flag[vx][vy]=max(flag[vx][vy],flag[u.first][u.second.second]+ara[vx][vy]); dfs({vx,{vy,u.second.second+1}}); } } } int main() { /* freopen("numtri.in","r",stdin); freopen("numtri.out","w",stdout);*/ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; memset(ara,0,sizeof ara); for(int i=0;i<n;i++) { for(int j=0;j<i+1;j++) { cin >> ara[i][j]; } } /*for(int i=0;i<n;i++) { for(int j=0;j<n;j++) cout << ara[i][j] << " "; cout << endl; } cout << "#####" << endl;*/ /*bfs();*/ for(int i=0;i<n+7;i++) { for(int j=0;j<n+7;j++) { flag[i][j]=INT_MIN; } } flag[0][0]=ara[0][0]; dfs({0,{0,1}}); int mx=0; for(int i=0;i<n;i++) mx=max(mx,flag[n-1][i]); cout << mx << endl; return 0; }<file_sep>/Codeforces/Contests/AIM Tech Round 4 (Div. 2)/B. Rectangles.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,m; cin >> n >> m; int ara[100][100]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cin >> ara[i][j]; } } ll pw[70]; pw[0]=1; for(int i=1;i<70;i++) { pw[i]=pw[i-1]*2LL; } ll ans=0; for(int i=0;i<n;i++) { int o=0,z=0; for(int j=0;j<m;j++) { if(ara[i][j]==1) { o++; } else z++; } ans+=(pw[o]+pw[z]-2); } for(int i=0;i<m;i++) { int o=0,z=0; for(int j=0;j<n;j++) { if(ara[j][i]==1) { o++; } else z++; } ans+=(pw[o]+pw[z]-2); } cout << ans-(n*m); return 0; }<file_sep>/Marathon/Weekly Marathon #2 by DJ/i.cpp #include<bits/stdc++.h> using namespace std; long long int cnt=0; void merge(int ara[],int p,int q,int r) { queue<int>left,right; for(int i=p;i<=q;i++) left.push(ara[i]); for(int i=q+1;i<=r;i++) right.push(ara[i]); int k=p; //cout << "while loop er age " << endl; while(k<=r) { if(right.empty()) { ara[k]=left.front(); left.pop(); } else if(left.empty()) { ara[k]=right.front(); right.pop(); } else { if(left.front()>right.front()) { ara[k]=right.front(); cnt+=left.size(); right.pop(); } else { ara[k]=left.front(); left.pop(); } } k++; } //cout << "merging sesh hoilo " << endl; } void merge_sort(int ara[],int p,int r) { if(p<r) { int q=(p+r)/2; // cout << "calling " << endl; merge_sort(ara,p,q); merge_sort(ara,q+1,r); // cout << "merging suru " << endl; merge(ara,p,q,r); } } int main() { while(1) { int n; cin >> n; if(n==0)return 0; int ara[n+7]; for(int i=0;i<n;i++) cin >> ara[i]; cnt=0; merge_sort(ara,0,n-1); cout << cnt << '\n'; } return 0; } <file_sep>/Marathon/SQRT decomposition/B. Little Elephant and Array2.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 #define sf scanf #define pf printf int block; struct data { int l,r,idx; bool operator < (const data& a) const { if( l/block != a.l/block) { return l/block < a.l/block; } return r < a.r ; } }; int ara[maxn],cnt[2000000],counti=0,n,m; inline void add(int ps) { if(ara[ps]<=n) { cnt[ara[ps]]++; // cout << "add " << ara[ps] << " " << cnt[ara[ps]] << endl; if(cnt[ara[ps]]==ara[ps]) { counti++; } if(cnt[ara[ps]]==ara[ps]+1) { counti--; } } } inline void rmv(int ps) { if(ara[ps]<=n) { cnt[ara[ps]]--; if(cnt[ara[ps]]==ara[ps]-1) { counti--; } if(cnt[ara[ps]]==ara[ps]) { counti++; } } } int main() { sf("%d %d",&n, &m); block=sqrt(n)+1; for(int i=1;i<=n;i++) sf("%d ",&ara[i]); data Q[m+7]; for(int i=0;i<m;i++) { sf("%d %d",&Q[i].l, &Q[i].r ); Q[i].idx=i; } sort(Q,Q+m); int curL=1,curR=1; int ans[m+7]; memset(cnt,0,sizeof cnt); add(1); for(int i=0;i<m;i++) { while(curL < Q[i].l) rmv(curL++); while(curL > Q[i].l) add(--curL); while(curR < Q[i].r) add(++curR); while(curR > Q[i].r) rmv(curR--); ans[Q[i].idx]=counti; } for(int i=0;i<m;i++) cout << ans[i] << endl; return 0; } <file_sep>/Marathon/Sack (dsu on tree)/test.cpp #include<bits/stdc++.h> using namespace std; //#define int long long #define maxn 100010 #define X first #define Y second vector <int> edge[maxn]; string s; vector < pair<int,int> > query[maxn]; int sz[maxn], level[maxn], cnt[maxn], ans[maxn], st[maxn], ft[maxn], ver[maxn], timer = 0; int t[maxn], p[maxn][20]; void getsz(int u, int p) { t[u] = p; st[u] = timer; ver[timer] = u; timer++; sz[u] = 1; for(auto v : edge[u]) { if(v == p)continue; level[v] = level[u]+1; getsz(v, u); sz[u] += sz[v]; } ft[u] = timer; } void dfs(int u,int p,int keep) { int mx=-1,bigchild=-1; for(int v : gr[u]) { if(v!=p and sz[v]>mx) { mx=sz[v]; bigchild=v; } } for(int v : gr[u]) { if(v!=p and v!=bigchild) { dfs(v,u,0); } } if(bigchild!=-1) { dfs(bigchild,u,1); } cnt[col[u]]++; } void dfs(int u, int p, bool keep) { int mx = -1, big = -1; for(auto v : edge[u]) { if(v != p) { if(sz[v] > mx) mx = sz[v], big = v; } } for(auto v : edge[u]) { if(v != p && v != big) { dfs(v, u, 0); } } if(big != -1) dfs(big, u, 1); cnt[level[u]]++; for(auto v : edge[u]) { if(v != p && v != big) { for(int t = st[v]; t < ft[v]; t++) { int vv = ver[t]; cnt[level[vv]]++; } } } for(auto q : query[u]) { //cout<<u<<' '<<level[u]+q.X<<' '<<cnt[level[u]+q.X]<<endl; ans[q.Y] = cnt[level[u] + q.X] - 1; } if(!keep) { for(int t = st[u]; t < ft[u]; t++) { int vv = ver[t]; cnt[level[vv]]--; } } } void lcainit(int n) { memset(p, -1, sizeof(p)); {for(int i = 0; i <= n; i++) { p[i][0] = t[i];}} for(int j = 1; (1<<j) <= n && j < 19; j++) for(int i = 0; i <= n; i++) { if(p[i][j-1] != -1) p[i][j] = p[p[i][j-1]][j-1]; } } int parent(int u, int l, int n) { if(l+1 >= level[u] ) return -1; for(int j = 19; j >= 0; j--) { if(l & (1<<j)) u = p[u][j]; } int p = t[u]; if(p) return p; return -1; } main() { ios::sync_with_stdio(0), cin.tie(0); int n, m; cin>>n; for(int i = 1; i<=n; i++) { int j; cin>>j; edge[i].push_back(j); edge[j].push_back(i); } getsz(0, -1); lcainit(n); cin>>m; for(int i = 1; i <= m; i++) { int u, l; cin>>u>>l; int p = parent(u, l-1,n ); if(p == -1) ans[i] = 0 ; else query[p].push_back({l, i}); } dfs(0, -1, 1); for(int i = 1; i<=m ; i++) { cout<<ans[i]<<' '; } }<file_sep>/Codeforces/B numbers/O - K-th Number.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int vector<int>tree[4*100000+7]; vector<int>vt(100000); void build(int id,int l,int r) { if(l==r) { tree[id].push_back(vt[l]); return; } int mid=(l+r)/2; build(id*2,l,mid); build(id*2+1,mid+1,r); merge(tree[id*2].begin(),tree[id*2].end(),tree[id*2+1].begin(),tree[id*2+1].end(),back_inserter(tree[id])); } int query(int id,int l,int r,int i,int j,int val) { if(r<i || l>j) return 0; if(l>=i and r<=j) return upper_bound(tree[id].begin(),tree[id].end(),val)-tree[id].begin() ; int mid=(l+r)/2; return query(id*2,l,mid,i,j,val) + query(id*2+1,mid+1,r,i,j,val); } int main() { ios_base::sync_with_stdio(0); int n,m; cin >> n >> m; for(int i=1; i<=n; i++) cin >> vt[i]; build(1,1,n); for(int q=0; q<m; q++) { int i,j,k; cin >> i >> j >> k; ll l=-1000000007,r=1000000007; int t=-1; while(l<=r) { ll mid=(l+r)/2; int tt=query(1,1,n,i,j,mid); if(tt>=k) { t=mid; r=mid-1; } else l=mid+1; } cout << t << endl; } return 0; } <file_sep>/Codeforces/Contests/Educational Codeforces Round 18/E. Connected Components.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d ",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 200007 set<int>gr[maxn],st; int flag[maxn],cnt=0,n; map<int,int>mp; void dfs(int u) { flag[u]=1; cnt++; cout << "ok " << endl; for(int x : st) { cout << x << " * "; } cout << endl; for(int x : st) { cout << x << " x" << endl; if(x>5 || x<0) continue; auto it = gr[u].find(x); if(it!=gr[u].end()) { continue; } if(flag[x]==0) { cout << u << " --> " << x << endl; st.erase(x); dfs(x); } } } int main() { int m; sf2(n,m); for(int i=1;i<=n;i++) { st.insert(i); } for(int i=0;i<m;i++) { int u,v; sf2(u,v); gr[u].insert(v); gr[v].insert(u); } vector<int>vt; for(int i=1;i<=n;i++) { if(flag[i]==0) { cnt=0; dfs(i); vt.push_back(cnt); cout << "ok" << endl; } } sort(vt.begin(),vt.end()); cout << vt.size() << endl; for(int x : vt) { pf1(x); } return 0; } /* */ <file_sep>/Codechef/Contests/November Long Challenge 2017/Villages and Tribes.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; while(tc--) { string str; cin >> str; int fa,la,fb,lb; for(int i=0;i<str.size();i++) { if() } } return 0; } <file_sep>/Codechef/Contests/August Long Challenge 2017/Palindromic Game.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { string s,t; cin >> s >> t; sort(s.begin(),s.end()); sort(t.begin(),t.end()); int ara[34]; memset(ara,0,sizeof ara); int f=0,tt=0; for(int i=0;i<s.size();i++) { ara[s[i]-'a']++; } int temp[34]; memset(temp,0,sizeof temp); for(int i=0;i<s.size();i++) { temp[t[i]-'a']++; } for(int i=0;i<min(s.size(),t.size());i++) { if(ara[i]>=2 and temp[i]==0) { f=1; } } int in=0; if(s.size()-1==t.size()) { for(int i=0,j=0;i<s.size() and j<t.size();i++) { if(s[i]!=t[j] and in==0) { in=1; } else if(s[i]!=t[j] and in==1) { in=2; } else { j++; } } } /*cout << "in " << in << endl;*/ if(f==1 or in==1) { cout << "A" << endl; } else { cout << "B" << endl; } } return 0; }<file_sep>/Contest/ACM ICPC Dhaka Regional 2017 Online Preliminary Round Hosted by University of Asia Pacific/test.cpp /* <NAME> */ /* UVA 10791 - Minimum Sum LCM /* Time limit: 3.000s /********************************/ #include <algorithm> #include <bitset> #include <cctype> #include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <map> #include <queue> #include <stack> #include <string> #include <vector> #define FileIn(file) freopen(file".inp", "r", stdin) #define FileOut(file) freopen(file".out", "w", stdout) #define FOR(i, a, b) for (int i=a; i<=b; i++) #define REP(i, n) for (int i=0; i<n; i++) #define Fill(ar, val) memset(ar, val, sizeof(ar)) #define PI 3.1415926535897932385 #define uint64 unsigned long long #define int64 long long #define all(ar) ar.begin(), ar.end() #define pb push_back #define bit(n) (1<<(n)) #define Last(i) ( i & -i ) #define INF 500000000 #define maxN 46350 using namespace std; bitset<maxN> isP; vector<int> prime; void sieve() { isP.set(); isP.reset(0); isP.reset(1); for (int i = 4; i < maxN; i += 2) isP.reset(i); for (int i = 3; i * i < maxN; i += 2) if (isP[i]) for (int j = i * i; j < maxN; j += i + i) isP.reset(j); prime.pb(2); for (int i = 3; i < maxN; i += 2) if (isP[i]) prime.pb(i); } int64 solve(int n) { if (n == 1) return 2; if (n < maxN && isP[n]) return n + 1; int nn = n, p = 0, fact = 0; int64 sum = 0; while (p < prime.size() && nn != 1) { if (nn % prime[p] == 0) { int64 tmp = 1; while (nn % prime[p] == 0) { tmp *= prime[p]; nn /= prime[p]; } sum += tmp; fact++; } p++; } if (nn != 1) { sum += nn; fact++; } if (fact == 1) sum++; return sum; } main() { // FileIn("test"); FileOut("test"); sieve(); int Case = 0, n; while (scanf("%d", &n) && n) { printf("Case %d: %lld\n", ++Case, solve(n)); } } <file_sep>/Contest/Team Forming Contest 2 (26-8-2017) (2015)/E - Primes on Interval.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define MAX 10000050 ll base[MAX/64],primes[MAX]; #define sq(x) ((x)*(x)) #define mset(x,v) memset(x,v,sizeof(x)) #define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31))) #define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31))) /* Generates all the necessary prime numbers and marks them in base[]*/ int no=0; void sieve() { unsigned i, j, k; int LMT=sqrt(MAX); for(i=3; i<LMT; i+=2) if(!chkC(base, i)) for(j=i*i, k=i<<1; j<MAX; j+=k) setC(base, j); j=0; primes[j++]=2; for(i=3; i<MAX; i+=2) if(!chkC(base, i)) primes[j++] = i; no=j-1; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); sieve(); /*cout << no << " " << primes[no] << endl;*/ ll a,b,k; cin >> a >> b >> k; /*int id=upper_bound(primes,primes+no,a)-primes; if(primes[id-1]==a) { id=id-1; int t=id+k; if(t>b) { cout << -1; } else { cout << primes[t]-a; } } else { int t=id+k; if(t>b) { cout << -1; } else { cout << primes[t]-a; } }*/ int cnt=0; int i=0; for(i=0;i<no;i++) { if(primes[i]>=a and primes[i]<=b) { cnt++; } if(primes[i]>b) break; if(cnt==k+1) { if(primes[i]-a-1 > b-a+1) { cout << -1 ; return 0; } cout << primes[i]-a-1 << endl; return 0; } } if(primes[i]-a > b-a+1) { cout << -1 ; return 0; } if(cnt==k) { cout << primes[i]-a << endl; return 0; } cout << -1; return 0; }<file_sep>/LightOJ/1255 - Substring Frequency.cpp #include<bits/stdc++.h> using namespace std; void compute_lps(string pat,int *lps) { int len=0,i=1; lps[0]=0; while(i<pat.size()) { if(pat[i]==pat[len]) { lps[i]=len+1; len++,i++; } else { if(len!=0) { len=lps[len-1]; } else { lps[i]=0; i++; } } } } int KMP(string txt,string pat) { int lps[pat.size()+7]; compute_lps(pat,lps); int i=0,j=0,ans=0; while(i<txt.size()) { if(txt[i]==pat[j]) { i++,j++; } if(j==pat.size()) { ans++; j=lps[j-1]; } else if(txt[i]!=pat[j]) { if(j!=0) { j=lps[j-1]; } else i++; } } return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { string txt,pat; cin >> txt >> pat; int t=KMP(txt,pat); cout << "Case " << qq << ": " << t << '\n'; } return 0; } <file_sep>/Codeforces/B numbers/B. Ilya and tic-tac-toe game.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 char str[7][7]; int fx[]= {-1,1,0,0,1,1,-1,-1}; int fy[]= {0,0,-1,1,1,-1,1,-1}; bool valid(int x,int y) { if(x>=0 && x<4 && y>=0 && y<4) return 1; return 0; } int main() { for(int i=0 ; i<4 ; i++ ) { sf("%s",str[i]); } string cmp[]= {"xx.", "x.x",".xx"}; for(int i=0 ; i<4 ; i++ ) { for(int j=0 ; j<4 ; j++ ) { if(str[i][j]=='x') { for(int k=0 ;k<8 ;k++ ) { if(valid(i+fx[k]*2,j+fy[k]*2)) { int x=i,y=j; string s; for(int qq=0 ;qq<3 ;qq++ ) { s+=str[x][y]; x+=fx[k]; y+=fy[k]; } if(s==cmp[0] || s==cmp[1] || s==cmp[2]) { cout << "YES"; return 0; } } } } } } cout << "NO"; return 0; } /* .oxx x... .o.. o... */ <file_sep>/LightOJ/1161 - Extreme GCD.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int cnt[maxn],ara[maxn]; void divi(int n) { for(int i=1; i*i<=n; i++) { if(n%i==0) { cnt[i]++; if(i*i != n) cnt[n/i]++; } } } ll nc4(ll n) { return n*(n-1)*(n-2)*(n-3)/24LL ; } ll solve() { ll ans[maxn]; for(int i=10007; i>=1; i--) { ans[i]=nc4(cnt[i]); for(int j=2*i; j<=10000; j+=i) { ans[i]-=ans[j]; } } return ans[1]; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1; qq<=tc; qq++) { memset(cnt,0,sizeof cnt); int n; cin >> n; for(int i=0; i<n; i++) { cin >> ara[i]; divi(ara[i]); } solve(); cout << "Case " << qq << ": " << solve() << endl; } return 0; } <file_sep>/LightOJ/1125 - Divisible Group Sums.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int ll n,q,d,m,ara[207]; long long int dp[207][17][27]; long long int rec(int ps,int cnt,ll sum) { if(ps>=n) { if(cnt==m && ( (sum%d)+d )%d==0) return 1ll; return 0ll; } long long int &ret=dp[ps][cnt][sum]; if(ret!=-1) return ret; ret=0ll; ret+=rec(ps+1,cnt+1,( (sum+ara[ps])%d +d )%d ); ret+=rec(ps+1,cnt,sum%d ); return ret; } int main() { int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { cin >> n >> q; for(int i=0;i<n;i++) cin >> ara[i]; cout << "Case " << qq << ":" << endl; while(q--) { cin >> d >> m; memset(dp,-1,sizeof dp); cout << rec(0,0,0) << endl; } } return 0; }<file_sep>/Codeforces/C numbers/C. On Changing Tree.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); int return 0; } /* */ <file_sep>/Codeforces/B numbers/B. Vlad and Cafes.cpp #include<bits/stdc++.h> using namespace std; int main() { int n; scanf("%d",&n); int ara[n+7]; set<int>st,t; for(int i=0;i<n;i++) { scanf("%d",&ara[i]); st.insert(ara[i]); } // cout << st.size() << endl; for(int i=n-1;i>=0;i--) { if(t.size()==st.size()-1 and t.find(ara[i])==t.end()) { cout << ara[i] << endl; return 0; } t.insert(ara[i]); } return 0; } <file_sep>/Codeforces/B numbers/B. Beautiful Paintings.cpp #include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int ara[1009]; memset(ara,0,sizeof ara); for(int i=0;i<n;i++) { int t; cin >> t; ara[t]++; } int mx=0; for(int i=0;i<1007;i++) { mx=max(mx,ara[i]); } cout << n-mx; return 0; } <file_sep>/Contest/Individual Practice Contest 8/B. Perfect Number.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 1000007 bool ok(int n) { int d=0; while(n) { d+=(n%10); n/=10; } return d==10; } int main() { vector<int>vt; int i=10; while(vt.size()<10007) { if(ok(i)) { vt.push_back(i); } i++; } sort(vt.begin(),vt.end()); // for(int i=0;i<=40;i++) // { // cout << vt[i] << " "; // } int n; cin >> n; cout << vt[n-1] << endl; return 0; } /* C. Seat Arrangements */ <file_sep>/Marathon/Sack (dsu on tree)/a.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 vector<int>gr[maxn]; int col[maxn],sz[maxn],ver[maxn],st[maxn],cnt[maxn],ft[maxn],timer=0,ans[maxn],koi_bar[maxn]; void getsz(int u,int p) { sz[u]=1; ver[timer]=u; st[u]=timer; timer++; for(int v : gr[u]) { if(v!=p) { getsz(v,u); sz[u]+=sz[v]; } } ft[u]=timer; } void dfs(int u,int p,int keep) { int mx=-1,bigchild=-1; for(int v : gr[u]) { if(v!=p and sz[v]) { mx=sz[v]; bigchild=v; } } for(int v : gr[u]) { if(v!=p and v!=bigchild) { dfs(v,u,0); } } if(bigchild!=-1) { dfs(bigchild,u,1); } cnt[col[u]]++; int mxx=cnt[col[u]]; for(int v : gr[u]) { if(v!=bigchild) { for(int p=st[v];p<ft[v];p++) { cnt[col[ver[p]]]++; mxx=max(mxx,cnt[col[ver[p]]]); koi_bar[cnt[col[ver[p]]]]++; } } } ans[u]=koi_bar[mxx]*mxx; if(keep==0) { for(int p=st[u];p<ft[u];p++) { cnt[col[ver[p]]]--; koi_bar[cnt[col[ver[p]]]]--; } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; for(int i=1;i<=n;i++) { cin >> col[i]; } for(int i=0;i<n-1;i++) { int u,v; cin >> u >> v; gr[u].push_back(v); gr[v].push_back(u); } getsz(1,-1); dfs(1,-1,1); for(int i=1;i<=n;i++) cout << ans[i] << " "; return 0; }<file_sep>/LightOJ/1037 - Agent 47.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 bool check(int n,int ps) { return (bool)(n&(1<<ps)); } int seti(int n,int ps) { return ( n|=(1<<ps) ); } int dp[1<<16]; int health[18]; char str[18][18]; int n; int cnt=0; int rec(int mask) { int t = __builtin_popcount(mask); if(t == n) return 0; if(dp[mask]!=-1) return dp[mask]; int ans=inf; for(int i=0; i<n; i++) { if(!((mask>>i)&1)) { ans=min(ans,health[i]+rec(mask|(1<<i))); for(int j=0; j<n; j++) { if(((mask>>j)&1)) { int d=str[j][i]-'0'; if(d==0) continue; ans=min(ans,(health[i]+d-1)/d+rec(mask|(1<<i))); } } } } return dp[mask]=ans; } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); // const clock_t begin_time = clock(); int tc; cin >> tc; for(int qq=1; qq<=tc; qq++) { cin >> n; for(int i=0; i<n; i++) { cin >> health[i]; } for(int i=0; i<n; i++) { sf("%s",str[i]); } memset(dp,-1,sizeof dp); int ans=rec(0); cout << "Case " << qq << ": " << ans << '\n'; } // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/LightOJ/1030 - Discovering Gold.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int n; double ara[107]; double dp[107]; double rec(int ps) { if(ps==n-1) { return ara[n-1]; } double& ret=dp[ps]; if(ret>-1.0) return ret; ret=0.0; int i=1; int f=0; for(i=1;i<=6;i++) { if(i+ps<n) { ret+=( (ara[ps]+rec(ps+i))/6.0 ); } else { f=1; break; } } if(f) { int t=max(0,6-i+1); ret=( 6.0*ret )/ (6-t); } return ret; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { cin >> n; for(int i=0;i<n;i++) cin >> ara[i]; for(int i=0;i<105;i++) dp[i]=-100.0; double temp=rec(0); cout << "Case " << qq << ": " << setprecision(10) << fixed << temp << endl; } return 0; } <file_sep>/Implementation/The Ultimate Riddle.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int ll bigmod(ll a,ll b,ll m) { /// a^b%m ll ans=1; while(b>0) { if(b&1) ans=(a*ans)%m; b>>=1; a=(a*a)%m; } return ans; } ll egcd (ll a,ll b,ll &x,ll &y) { /// ax+by=1 finding x and y where a<b if (a == 0) { x = 0; y = 1; return b; } ll x1, y1; ll d = egcd (b%a,a,x1,y1); x = y1 - (b/a) * x1; y = x1; return d; } ll modInv(ll a,ll m) { /// works only when (a,m)=1; /// ax=1 (mod m) finding x ll x,y; if(a<=m) egcd(a,m,x,y); else egcd(m,a,y,x); x%=m; if(x<0) x+=m; /// if x can be very large nand m is prime then use big mod // x=bigmod(a,m-2,m)%m; return x; } ll ncr(ll n,ll r,ll p) { if(n<r) return 0; r=min(r,n-r); ll nu=1,de=1; for(ll i=n; i>=n-r+1; i--) { nu=(nu*i)%p; } for(int i=1; i<=r; i++) { de=(de*i)%p; } ll mide=modInv(de,p)%p; ll t=(nu*mide)%p; return t; } ll Lucas(ll n, ll r, ll p) { /// works only when p is prime if (n==0 && r==0) return 1; int ni = n % p; int mi = r % p; if (mi>ni) return 0; return Lucas(n/p, r/p, p) * ncr(ni, mi, p); } ll CRT(const vector< pair<int, int> > &vt) { /// pair<ai(residues),pi(primes)> ll M = 1; for(int i = 0; i<vt.size(); i++) M *= vt[i].second; ll ret = 0; for(int i = 0; i<vt.size(); i++) { ll ai = vt[i].first; ll Mi = (M/vt[i].second); ret += ai * Mi * modInv(Mi % vt[i].second, vt[i].second); ret %= M; } return ret; } int main() { int tc; cin >> tc; for(int qq=1; qq<=tc; qq++) { int n,r,m; cin >> n >> r >> m; vector< pair<int,int> > vt; for(int i=2;i<=50;i++) { if(m%i==0) { m/=i; ll t=Lucas(n,r,i); vt.push_back({t,i}); } } ll ans=CRT(vt); cout << ans << endl; } return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #299 (Div. 2)/B. Tavas and SaDDas.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647 #define eps 1e -10 #define maxn 1000000007 #define mod 100000007 vector<ll>vt; void init(ll num) { if(num>maxn) return; vt.push_back(num); init(num*10+4); init(num*10+7); } int main() { init(0); sort(vt.begin(),vt.end()); ll n; cin >>n; for(int i=1;i<vt.size();i++) { if(vt[i]==n){ cout << i << endl; return 0; } } return 0; } /* */ <file_sep>/Codeforces/Contests/Codeforces Round 225/text.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; typedef long long ll; const ll MAX_VALUE = 1LL * 100; void precalc(const vector<ll> &in, vector<ll> &out, ll cur = 1, int k = 0, ll bound = MAX_VALUE) { if (k >= in.size()) { out.push_back(cur); return; } while (bound > 0) { precalc(in, out, cur, k + 1, bound); cur *= in[k]; bound /= in[k]; } } vector<ll> xs, ys; ll count_le(ll t) { ll res = 0; int yidx = 0; cout << "******" << endl<< endl; for (ll x : xs) { while (yidx < ys.size() && ys[yidx] <= t / x) { yidx++; } // cout << x << " er jonno " << yidx << endl; res += yidx; } return res; } int main() { ll n; cin >> n; vector<ll> a[2]; for (int i = 0; i < n; i++) { int x; cin >> x; a[i % 2].push_back(x); } ll k; cin >> k; precalc(a[0], xs); precalc(a[1], ys); sort(xs.rbegin(), xs.rend()); sort(ys.begin(), ys.end()); for(int x : xs) { cout << x << " "; } cout << endl; for(int x : ys) { cout << x << " "; } cout << endl << endl; ll l = 0, r = MAX_VALUE + 1; while (l != r) { ll m = (l + r) / 2; if (count_le(m) < k) { l = m + 1; } else { r = m; } } if (l != MAX_VALUE + 1) { cout << l << endl; } else { cout << -1 << endl; } return 0; } <file_sep>/Codeforces/C numbers/Skiing.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 #define sf scanf #define pf printf int r,c; int fx[]={-1,1,0,0}; int fy[]={0,0,-1,1}; int flag[1007][1007], ara[1007][1007]; void dfs(int ux,int uy) { flag[ux][uy]=1; for(int i=0;i<4;i++) { int vx=ux+fx[i],vy=uy+fy[i]; if( vx>=0 and vx<r and vy>=0 and vy<c and flag[vx][vy]==-1 and ara[vx][vy]<=ara[ux][uy] ) { flag[vx][vy]=1; dfs(vx,vy); } } } int main() { int tc; sf("%d",&tc); for(int qq=1;qq<=tc;qq++) { sf("%d %d",&r,&c); vector< pair<int,pair<int,int>> >vt; for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { sf("%d",&ara[i][j]); vt.push_back( { ara[i][j],{i,j} } ); } } sort(vt.rbegin(),vt.rend()); memset(flag,-1,sizeof flag); int cnt=0; for(int i=0;i<vt.size();i++) { int x=vt[i].second.first, y=vt[i].second.second; if(flag[x][y]==-1) { // cout << x << " " << y << endl; cnt++; dfs(x,y); } } cout << cnt << endl; } return 0; } <file_sep>/Contest/Individual Practice Contest 3/F - Zhenya moves from parents.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 581827 struct data { ll tk,loan; }; data tree[5*maxn]; void updt(int id,int l,int r,int ps,int val) { if(l==r) { if(val>0) { tree[id].tk = val; } else { tree[id].loan = - val; } return ; } int mid = (l+r)/2; if(ps<=mid) { updt(id*2,l,mid,ps,val); } else { updt(id*2+1,mid+1,r,ps,val); } tree[id].tk = tree[id*2].tk + tree[id*2+1].tk; if(tree[id*2+1].loan <= tree[id*2].tk) { tree[id].tk -= tree[id*2+1].loan; tree[id].loan = 0; } else { tree[id*2+1].loan -= tree[id].tk; tree[id].tk = 0; } tree[id].loan = tree[id*2+1].loan ; } int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); int n; sf1(n); int c,date,month,hour,minute; while(n--) { sf("%d %d.%d %d:%d", &c, &date, &month, &hour, &minute); ll mp = ( ( month*31 + date )*24 + hour) * 60 + minute; updt(1,1,maxn-3,mp,c); int t = tree[1].loan*-1; cout << t << endl; } return 0; } /* */ <file_sep>/Marathon/Sack (dsu on tree)/A - Lomsat gelral.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 vector<int>gr[maxn]; int sz[maxn],st[maxn],ft[maxn],ver[maxn],timer=0,col[maxn]; void getsz(int u,int p) { sz[u]=1; st[u]=timer; ver[timer]=u; timer++; for(int v : gr[u]) { if(v!=p) { getsz(v,u); sz[u]+=sz[v]; } } ft[u]=timer; } int cnt[maxn],dom[maxn]; ll ans[maxn]; void dfs(int u,int p,int keep) { int mx=-1,bigchild=-1; for(int v : gr[u]) { if(v!=p and sz[v]>mx) { mx=sz[v]; bigchild=v; } } for(int v : gr[u]) { if(v!=p and v!=bigchild) { dfs(v,u,0); } } if(bigchild!=-1) { dfs(bigchild,u,1); } cnt[col[u]]++; int mxc=cnt[col[u]]; for(int v : gr[u]) { if(v!=p and v!=bigchild) { for(int p=st[v];p<ft[v];p++) { cnt[col[ver[p]]]++; mxc=max(mxc,cnt[col[ver[p]]]); } } } if(bigchild!=-1 and dom[bigchild]==mxc) { ll t=ans[bigchild]; unordered_set<int>sat; if(mxc==cnt[col[u]]) { sat.insert(col[u]); } for(int v : gr[u]) { if(v!=p and v!=bigchild) { for(int p=st[v];p<ft[v];p++) { if(mxc==cnt[col[ver[p]]]) { sat.insert(col[ver[p]]); } } } } for(int it : sat) { t+=it; } ans[u]=t; dom[u]=mxc; } else if(bigchild!=-1 and dom[bigchild]>mxc) { ans[u]=ans[bigchild]; dom[u]=dom[bigchild]; } else { ll t=0; unordered_set<int>sat; if(mxc==cnt[col[u]]) { sat.insert(col[u]); } for(int v : gr[u]) { if(v!=p and v!=bigchild) { for(int p=st[v];p<ft[v];p++) { if(mxc==cnt[col[ver[p]]]) { sat.insert(col[ver[p]]); } } } } for(int it : sat) { t+=it; } ans[u]=t; dom[u]=mxc; } if(keep==0) { for(int p=st[u];p<ft[u];p++) { cnt[col[ver[p]]]--; } dom[u]=0; } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; for(int i=1;i<=n;i++) { cin >> col[i]; } for(int i=0;i<n-1;i++) { int u,v; cin >> u >> v; gr[u].push_back(v); gr[v].push_back(u); } getsz(1,-1); /*cout << " ok " << endl;*/ dfs(1,-1,1); for(int i=1;i<=n;i++) cout << ans[i] << " "; return 0; }<file_sep>/Contest/Battle of Brains, 2017 (Replay)/Meena Has Three Wishes.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; while(tc--) { double d; cin >> d; cout << fixed << setprecision(2) << .5*d*d << endl; } return 0; }<file_sep>/Codeforces/B numbers/Untitled1.cpp #include<bits/stdc++.h> using namespace std; #define DB printf("*****\n") #define sf scanf #define pf printf #define ll long long int #define pii pair<int,int> #define inf 2147483647 #define maxn 100004 int ara[maxn]; int tree[3*maxn]; void init(int node,int l,int r) { if(l==r) { tree[node]=ara[l]; return; } int left=node*2; int right=node*2+1; int mid=(l+r)/2; init(left,l,mid); init(right,mid+1,r); tree[node]=min(tree[left],tree[right]); } int query(int node,int l,int r,int i,int j) { if(l>=i and r<=j) return tree[node]; if(j<l or i>r) return inf; int left=node*2; int right=node*2+1; int mid=(l+r)/2; int p1=query(left,l,mid,i,j); int p2=query(right,mid+1,r,i,j); return min(p1,p2); } void update(int node,int l,int r,int i,int value) { if(l>i or r<i) return; if(l==r) { tree[node]=value; return; } int left=node*2; int right=node*2+1; int mid=(l+r)/2; update(left,l,mid,i,value); update(right,mid+1,r,i,value); tree[node]=min(tree[left],tree[right]); } int main() { int tc; sf("%d",&tc); int n,q; for (int qq=1;qq<=tc ;qq++ ) { sf("%d %d",&n,&q); for (int i=1;i<=n ;i++ ) { sf("%d",&ara[i]); } init(1,1,n); pf("Case %d:\n",qq); int i,j; while(q--) { sf("%d %d",&i,&j); pf("%d\n",query(1,1,n,i,j)); } } return 0; } /* 78 1 22 12 3 */ <file_sep>/Codeforces/Contests/191/Contiguous Segments.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; vector< pair<int,int> > vt; for(int i=0; i<n; i++) { int x,y; cin >> x >> y; vt.push_back({x,y}); } sort(vt.begin(),vt.end()); if(n%2==1) { int l,r; l=r=n/2; l--; r++; int ans=0; while(l>=0) { int d=vt[l+1].first-vt[l].second; ans+=d; vt[l].first+=d; vt[l].second+=d; d=vt[r].first-vt[r-1].second; ans+=d; vt[r].first-=d; vt[r].second-=d; l--,r++; } cout << ans << endl; } else { vector< pair<int,int> >temp(vt.begin(),vt.end()); int l,r; l=r=n/2; l--; r++; // cout << l << " " << r << endl; int ans1=0; while(l>0) { int d=vt[l+1].first-vt[l].second; ans1+=d; vt[l].first+=d; vt[l].second+=d; d=vt[r].first-vt[r-1].second; ans1+=d; vt[r].first-=d; vt[r].second-=d; l--,r++; } int d=vt[l+1].first-vt[l].second; ans1+=d; vt[l].first+=d; vt[l].second+=d; // cout << "ans1 " << ans1 << endl; l=r=n/2 - 1; l--; r++; // cout << l << " " << r << endl; int ans2=0; while(l>=0) { int d=temp[l+1].first-temp[l].second; ans2+=d; temp[l].first+=d; temp[l].second+=d; d=temp[r].first-temp[r-1].second; ans2+=d; temp[r].first-=d; temp[r].second-=d; l--,r++; } d=temp[r].first-temp[r-1].second; ans2+=d; temp[r].first-=d; temp[r].second-=d; // cout << "ans2 " << ans2 << endl; cout << min(ans1,ans2) << endl; } return 0; } <file_sep>/Marathon/Weekly Marathon #3 by DJ/a.cpp #include<bits/stdc++.h> using namespace std; int main() { vector<long long int>vt; vt.push_back(1); for(int i=0;i<=32;i++) { vt.push_back(vt.back()*2); } int tc; cin >> tc; while(tc--) { long long int sum=0; long long int n; cin >> n; sum+=(n*(n+1)/2); for(int i=0;i<vt.size();i++) { if(vt[i]<=n) sum-=(vt[i]*2); } cout << sum << '\n'; } return 0; } <file_sep>/Codeforces/Contests/191/A. Flipping Game.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; vector<int>ara(n+7); // int ara[n+7]; for(int i=0; i<n; i++) cin >> ara[i]; int ans=0; // for(int i=0; i<n; i++) // { // if(ara[i]==1) // { // ans++; // } // } for(int l=0; l<n; l++) { for(int r=l; r<n; r++) { vector<int>vt; vt=ara; for(int i=l; i<=r; i++) { if(vt[i]==1) { vt[i]=0; } else vt[i]=1; } int cnt=0; for(int i=0; i<n; i++) { if(vt[i]==1) { cnt++; } } ans=max(ans,cnt); } } cout << ans << endl; return 0; } <file_sep>/LightOJ/Looking for a Subsequence.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define pcase(x) printf("Case %d:\n",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 struct data { int val, ps; }; bool cmp(const data &a,const data &b) { if(a.val != b.val) return a.val > b.val; return a.ps < b.ps; } data ara[maxn]; int temp[maxn]; int tree[4*maxn]; void updt(int id,int l,int r,int ql,int val) { if(l==r) { tree[id] = val; return; } int mid = (l+r)/2; if(ql <= mid) { updt(id*2,l,mid,ql,val); } else { updt(id*2+1,mid+1,r,ql,val); } tree[id] = max( tree[id*2], tree[id*2+1] ); } int query(int id,int l,int r,int ql,int qr) { if(l>qr || r<ql) { return 0; } if(l>=ql and r<=qr) { return tree[id]; } int mid = (l+r)/2; return max( query(id*2,l,mid,ql,qr), query(id*2+1,mid+1,r,ql,qr) ); } int main() { int tc; sf1(tc); for(int qq=1;qq<=tc;qq++) { int n, q; sf2(n,q); for(int i=0;i<n;i++) { sf1(ara[i].val); ara[i].ps = i; temp[i] = ara[i].val; } sort(ara,ara+n,cmp); for(int i=0;i<4*maxn;i++) { tree[i] = 0; } int lis[maxn]; for(int i=0;i<n;i++) { int temp = query(1,0,n-1,ara[i].ps,n-1); temp++; lis[ara[i].ps] = temp; updt(1,0,n-1,ara[i].ps,temp); } pcase(qq); while(q--) { int m; sf1(m); int prev = -1000000000, f=0; for(int i=0;i<n;i++) { if(lis[i]>=m and prev < temp[i]) { if(f) { pf(" %d",temp[i]); } else { pf("%d",temp[i]); } f=1; prev = temp[i]; m--; if(m==0) { break; } } } if(m>0) { pf("Impossible"); } pf("\n"); } } return 0; } /* */ <file_sep>/Codeforces/Contests/Educational Codeforces Round 26/A. Text Volume.cpp #include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int mx=0; string str; while(cin >> str) { int t=0; for(int i=0;i<str.size();i++) { if(str[i]>='A' and str[i]<='Z') { t++; } } mx=max(mx,t); } cout << mx; return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #461 (Div. 2)/B. Magic Forest.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 1000007 int vis[2507][2507]; bool ok(int a,int b,int c) { vector<int>vt; vt.push_back(a); vt.push_back(b); vt.push_back(c); sort(vt.begin(),vt.end()); if(vt[2]<vt[1]+vt[0]) return 1; else return 0; } int main() { int cnt=0; int n; cin >> n; for(int a=1;a<=n;a++) { for(int b=a+1;b<=n;b++) { int c = a^b ; if(vis[a][b] || vis[a][c] || vis[b][c])continue; if(c<=n and ok(a,b,c)) { vis[a][b] = 1; vis[a][c] = 1; vis[b][c] = 1; // cout << a << " " << b << " " << c << endl; cnt++; } } } cout << cnt << endl; return 0; } /* */ <file_sep>/Codeforces/C numbers/Concatenated Array.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,k; cin >> n >> k; string str; cin >> str; string t; for(int i=0;i<10;i++) { t+=str; } int f=1,ans=0,id=0; for(int i=0;i<t.size();i++) { if(t[i]=='1') { f=0; break; } } if(f) { cout << n*k << endl; return 0; } for(int i=0;i<t.size();i++) { if(t[i]=='1' and f==0) { ans=max(ans,i-id); id=9999; f=1; } if(t[i]=='0' and f==1) { f=0; id=i; } } // if(t.back()=='0' and f==0) // { // if(t.size()-id>ans) // { // ans=t.size()-id; // } // } cout << ans << endl; return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #448 (Div. 2)/B. XK Segments.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 int n,x,k; int l=-1,r=-1; void range(int t) { if(t%x==0) { int d=t/x; l=x*d; r=x*(d+k); } else { int d=t/x; d++; l=x*d; r=x*(d+k); } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> x >> k; if(k==0) { cout << n << endl; return 0; } vector<int>vt; for(int i=0; i<n; i++) { int t; cin >> t; vt.push_back(t); } vt.push_back(inf); sort(vt.begin(),vt.end()); cout << vt[n] << endl; cout << upper_bound(vt.begin(), vt.end(), 98)-vt.begin() << endl; ll ans=0; for(int i=0;i<n;i++) { l=inf,r=inf; range(vt[i]); cout << vt[i] << " er jonno " << l << " " << r << endl; int b=upper_bound(vt.begin(), vt.end(), r)-vt.begin(); int a=lower_bound(vt.begin(), vt.end(), l)-vt.begin(); // if() cout << a << " " << b << endl; ans+=(b-a); } cout << ans << endl; return 0; } /* */ <file_sep>/LightOJ/1140 – How Many Zeroes.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 char digits[20]; ll dp[20][3][3][] int main() { int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { ll m,n; sf("%lld %lld",&m,&n); } return 0; } /* */ <file_sep>/Codeforces/Contests/Codeforces Round #299 (Div. 2)/C. Number of Ways.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<ll,ll> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf ll_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf prllf #define pcase(x) prllf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) prllf("%d\n",a); #define pf2(a,b) prllf("%d %d\n",a,b) #define pf3(a,b,c) prllf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) prllf("%lld\n",a); #define pf2ll(a,b) prllf("%lld %lld\n",a,b) #define pf3ll(a,b,c) prllf("%lld %lld %lld\n",a,b,c) #define maxn 500007 ll pre[maxn],suff[maxn]; ll ara[maxn]; int main() { ios_base::sync_with_stdio(0); ll n; cin >> n; ll sum=0; for(ll i=0;i<n;i++) { cin >> ara[i]; sum+=ara[i]; } if(sum%3) { cout << 0 << endl; return 0; } sum/=3; memset(pre,0,sizeof pre); memset(suff,0,sizeof suff); ll t=0; for(ll i=0;i<n;i++) { t+=ara[i]; if(t==sum) { pre[i] = 1; } } t=0; for(ll i=n-1;i>=0;i--) { t+=ara[i]; if(t==sum ) { suff[i] =1; } } for(ll i=n-1;i>=0;i--) { suff[i]+=suff[i+1]; } ll cnt=0; for(ll i=0;i<n;i++) { if(pre[i]==1) { cnt+=suff[i+2]; } } cout << cnt << endl; return 0; } /* */ <file_sep>/LightOJ/1027 - A Dangerous Maze.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); return 0; } /* */ <file_sep>/Contest/ACM ICPC Dhaka Regional 2017 Online Preliminary Round Hosted by University of Asia Pacific/d.cpp /* author : <NAME> CSE'15 SUST */ #include<bits/stdc++.h> #define pii pair<int,int> #define tii pair<int,pair<int,int> > #define mkp make_pair #define fs first #define sc second #define pb push_back #define ppb pop_back() #define pcase(x) printf("Case %d:\n",x) #define hi cout<<"hi"<<endl; #define mod 1000000007 #define inf 1000000107 #define pi acos(-1.0) #define mem(arr,x) memset((arr), (x), sizeof((arr))); #define FOR(i,x) for(int i=0;i<(x); i++) #define FOR1(i,x) for(int i = 1; i<=(x) ; i++) #define jora(a,b) make_pair(a,b) #define tora(a,b,c) jora(a,jora(b,c)) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define N 100005 #define level 26 // #define noya vector< vector<int> >(6,vector<int>(6,0)) // #define mat vector<vector<int> > // #define m 6 using namespace std; typedef long long int lint; typedef double dbl; int main() { // #ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); //#endif int test,case_no=1; sf1(test); while(test--) { int n,e; sf2(n,e); vector<pii>vt[n+5]; int mark[n+5]; for (int i = 0;i<=n;i++) mark[i] = -inf; //mem(mark,-1); for(int i=0;i<e;i++) { int u,v,w; sf3(u,v,w); vt[u].push_back(jora(v,w)); vt[v].push_back(jora(u,w)); } mark[1]=inf; priority_queue< pii, vector<pii> >pq; pq.push(jora(0,1)); while(pq.size()) { int u=pq.top().sc; pq.pop(); for(int i=0;i<vt[u].size();i++) { int v=vt[u][i].fs; int w=vt[u][i].sc; if(mark[v]<min(w,mark[u])) { mark[v]=min(w,mark[u]); pq.push(jora(mark[v],v)); } } } vector<int>vv; vector<int>::iterator it; pcase(case_no++); for(int i=2;i<=n;i++) { vv.push_back(mark[i]); //cout<<i<<" "<<mark[i]<<endl; } sort(vv.begin(),vv.end()); int q; sf1(q); while(q--) { int c; sf1(c); it=lower_bound(vv.begin(),vv.end(),c); int x=(it-vv.begin()); //cout<<"meaw "<<x<<endl; printf("%d\n",vv.size()-x); } } return 0; } /*inpt 2 4 3 2 3 2 1 2 3 4 3 4 3 2 3 4 4 4 1 2 3 2 4 2 3 4 1 1 3 4 3 -12 -15 0 */ <file_sep>/Marathon/Mathematics/lcm sieve.cpp // lcm[n]=lcm(1,2,3,....n); int primeflag[maxn]; ll lcm[maxn]; void lcm_sieve() { fill(lcm,lcm+maxn,1LL); for(ll i=2;i<=maxn;i++) { if(!primeflag[i]) { for(ll j=i*i;j<maxn;j+=i) { primeflag[j]=1; } ll t=i; while(t<maxn) { lcm[t]=i; t*=i; } } } for(int i=2;i<maxn;i++) { lcm[i]=(lcm[i-1]*lcm[i])%mod; } } <file_sep>/Codeforces/D numbers/D. Longest k-Good Segment.cpp #include<bits/stdc++.h> using namespace std; int ara[1000007],cnt[1000007]; int main() { int n,k; scanf("%d %d",&n,&k); for(int i=0; i<n; i++) { scanf("%d",&ara[i]); } int ansx=0,ansy=0,x=0,y=0,len=0,temp=0; memset(cnt,0,sizeof cnt); for(; y<n; y++) { if(cnt[ara[y]]==0) temp++; cnt[ara[y]]++; while(temp>k) { if(cnt[ara[x]]==1) { temp--; cnt[ara[x]]=0; } else { cnt[ara[x]]--; } x++; } if(y-x+1>len && temp<=k) { len=y-x+1; ansx=x,ansy=y; } } printf("%d %d",ansx+1,ansy+1); return 0; } <file_sep>/Contest/Team Forming Contest 3 (08-09-2017) (2015)/E - Super Mario.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 vector<int>tree[4*maxn]; int ara[maxn]; void bulid(int id,int l,int r) { if(l==r) { tree[id].push_back(ara[l]); return ; } int mid=(l+r)/2; bulid(id*2,l,mid); bulid(id*2+1,mid+1,r); merge(tree[id*2].begin(),tree[id*2].end(), tree[id*2+1].begin(),tree[id*2+1].end(), back_inserter(tree[id]) ); } int query(int id,int l,int r,int ql,int qr,int val) { if(r<ql || l>qr) return 0; if(l>=ql and r<=qr) { /*cout << id << " " << l << " " << r << endl; cout << (upper_bound(tree[id].begin(),tree[id].end(),val)- tree[id].begin() ) << endl;*/ return (upper_bound(tree[id].begin(),tree[id].end(),val)- tree[id].begin()); } int mid=(l+r)/2; int t1=query(id*2,l,mid,ql,qr,val); int t2=query(id*2+1,mid+1,r,ql,qr,val); return t1+t2; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; int qq=1; while(tc--) { for(int i=0;i<4*maxn;i++) { tree[i].clear(); } int n,m; cin >> n >> m; for(int i=0;i<n;i++) cin >> ara[i]; bulid(1,0,n-1); /*cout << upper_bound(tree[6].begin(),tree[6].end(),6)-tree[6].begin() << endl;*/ cout << "Case " << qq++ << ":" << endl; while(m--) { int l,r,h; cin >> l >> r >> h; cout << query(1,0,n-1,l,r,h) << endl; } } return 0; } <file_sep>/Codechef/Contests/August Long Challenge 2017/C - Funky Numbers.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); vector<ll>vt; for(ll i=1;i<100007;i++) { vt.push_back(i*(i+1)/2LL); } sort(vt.begin(),vt.end()); ll n; cin >> n; for(int i=0;i<vt.size();i++) { if(binary_search(vt.begin(),vt.end(),n-vt[i])) { cout << "YES" ; return 0; } } cout << "NO" ; return 0; }<file_sep>/LightOJ/1031 - Easy Game.cpp #include<bits/stdc++.h> using namespace std; vector<int>vt; int dp[107][107]; int rec(int i,int j) { if(i>j) return 0; int& ret=dp[i][j]; if(ret!=-1) return ret; int p=0,diff=INT_MIN; for(int k=i;k<=j;k++) { p+=vt[k]; diff=max(diff,p-rec(k+1,j)); } p=0; for(int k=j;k>=i;k--) { p+=vt[k]; diff=max(diff,p-rec(i,k-1)); } return ret=diff; } int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n; cin >> n; vt.clear(); for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back(t); } memset(dp,-1,sizeof dp); cout << "Case " << qq << ": " << rec(0,n-1) << '\n'; } return 0; } <file_sep>/Codeforces/B numbers/C.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 vector<int>vt; void seive() { int flag[1000007]; memset(flag,0,sizeof flag); for(int i=3; i<=1000; i+=2) { if(flag[i]==0) { for(int j=i*i; j<=1000006; j+=(2*i)) { flag[j]=1; } } } vt.push_back(2); for(int i=3; i<1000007; i+=2) { if(flag[i]==0) { vt.push_back(i); } } } vector< ll > temp; void func(int n) { // DB; for(int i=0; i<vt.size() and vt[i]<=n; i++) { int t=vt[i]; // cout << t << endl; int cnt=0; int m=t; while(t<n) { cnt++; t*=m; // cout << t << endl; } if(t==n) temp.push_back(t); else temp.push_back(t/m); } } ll lcm(ll a,ll b,ll c) { ll aa=__gcd(a,b); ll bb=__gcd(aa,c); return (a*b*c)/bb; } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); seive(); // cout << vt.back(); ll n; cin >> n; // const clock_t begin_time = clock(); ll ans=n; ans=max(ans,max(n*(n-1),n*(n-1)*(n-2)) ); func(n); // ll ans=1; sort(temp.begin(),temp.end(),greater<int>()); // for(int i=0;i<temp.size();i++) cout << temp[i] << " "; if(temp.size()>=1) ans=max(ans,temp[0]); if(temp.size()>=2) ans=max(ans,temp[0]*temp[1]); if(temp.size()>=3) ans=max(ans,temp[0]*temp[1]*temp[2]); vector<int>vtt; int m=n; // cout << ans << endl; while(1) { vtt.push_back(m--); if(m==0 || vtt.size()>500) { break; } } // for(int i:vtt) cout << i << " "; sort(vtt.begin(),vtt.end(),greater<int>()); // cout << lcm(50,50,50) << endl; for(int i=0; i<vtt.size(); i++) { for(int j=i+1; j<vtt.size(); j++) { for(int k=j+1; k<vtt.size(); k++) { if(lcm(vtt[i],vtt[j],vtt[k])>ans) { // cout << vtt[i] << " " << vtt[j] << " " << vtt[k] << endl; ans=lcm(vtt[i],vtt[j],vtt[k]); // cout << i << " " << j << " " << k << endl; } } } } cout << ans; // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/Contest/Individual Practice Contest 8/Untitl.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 300007 vector<int>gr[maxn]; int flag[maxn]; int id,cy=0; void dfs(int u) { for(int i=0;i<gr[u].size();i++) { int v = gr[u][i]; if(v==id and flag[v]==1) { cy=1; return; } if(flag[v]==0) { dfs(v); } } return; } char str[maxn]; int main() { int n,m; sf2(n,m); sf("%s",str); for(int i=0;i<m;i++) { int u,v; sf2(u,v); gr[u].push_back(v); } cout << "input sesh " << endl; memset(flag,0,sizeof flag); for(int i=1;i<=n;i++) { if(flag[i]==0) { id=i; cout << i << " ehd dfs " << endl; dfs(i); } } if(cy) { pf("-1"); } else { cout << "ok " << endl; } return 0; } /* */ <file_sep>/Contest/Team Forming Contest 1 (25-8-2017) (2015)/C - New Year Snowmen.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; vector<int>vt; map<int,int>mp; for(int i=0;i<n;i++) { int t; cin >> t; mp[t]++; } vector< pair<int,int> >p; for(auto it=mp.begin();it!=mp.end();it++) { p.push_back({it->second,it->first}); } sort(p.begin(),p.end()); vector< pair<int,pair<int,int> > > ans; for(int i=0;i<p.size()-2;i++) { if(p[i].first==0) continue; int t=min(p[i].first,min(p[i+1].first,p[i+2].first)); int s=t; while(s--) { ans.push_back({p[i].second,{p[i+1].second,p[i+2].second}}); } p[i].first-=t; p[i+1].first-=t; p[i+2].first-=t; } cout << ans.size() << endl; for(int i=0;i<ans.size();i++) { vector<int>temp; temp.push_back(ans[i].first); temp.push_back(ans[i].second.first); temp.push_back(ans[i].second.second); sort(temp.rbegin(),temp.rend()); for(auto i:temp) cout << i << " "; cout << endl; } return 0; }<file_sep>/Marathon/BPM Marathon/Factors and Multiplesv2.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 107 #define SET(x) memset(x,-1,sizeof x) #define CLR(x) memset(x,0,sizeof x) vector<int>gr[maxn]; bool vist[maxn]; int Left[maxn], Right[maxn]; bool dfs(int u) { if(vist[u]) return 0; vist[u] = 1; for(int i=0;i<gr[u].size();i++) { int v = gr[u][i]; if(Right[v] == -1) { Right[v] = u; Left[u] = v; return 1; } } for(int i=0;i<gr[u].size();i++) { int v = gr[u][i]; if( dfs(Right[v]) ) { Right[v] = u; Left[u] = v; return 1; } } return 0; } int match(int n) { SET(Left); SET(Right); int i, ret = 0; bool done; for(int i=0;i<n;i++) { CLR(vist); for(int j=0;j<n;j++) { if(dfs(j)); } } for(int i=0;i<n;i++) { ret+= (Left[i] != -1); } return ret; } int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); int tc; sf1(tc); for(int qq=1;qq<=tc;qq++) { for(int i=0;i<maxn;i++) { gr[i].clear(); } int n; sf1(n); vector<int>l; for(int i=0;i<n;i++) { int t; sf1(t); l.push_back(t); } int m; sf1(m); vector<int>r; for(int i=0;i<m;i++) { int t; sf1(t); r.push_back(t); } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(l[i]!=0 and r[j]%l[i]==0) { gr[i].push_back(j); } } } int ans = match(n); pcase(qq); pf1(ans); // cout << ans << endl; } return 0; } /* */ <file_sep>/Codeforces/Contests/Educational Codeforces Round 33 (Rated for Div. 2)/E. Counting Arrays.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define DB cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 1000557 int spf[maxn]; void sieve() { for(int i=2; i<maxn; i++) spf[i] = i; for(int i=2; i<maxn; i+=2) spf[i] = 2; for(int i=3; i*i<maxn; i+=2) { if(spf[i]==i) { for(int j=i*i,k=2*i; j<maxn; j+=k) { if(spf[j] == j) spf[j]=i; } } } } ll bigmod(ll b,ll p) { ll temp=1; while(p>0) { if(p&1) temp = (temp*b)%mod; p>>=1; b = (b*b)%mod; } return temp; } ll fac[1000507]; void pre() { fac[0]=1; for(ll i=1; i<1000507; i++) { fac[i] = (fac[i-1]*i) % mod; } } ll ncr(ll n,ll r) { ll nu=fac[n]; ll de = ( fac[r] * fac[n-r] ) % mod ; nu = nu * bigmod(de,mod-2) ; return nu%mod; } int y; ll prime_factor(int n) { ll ans=1; while(n != 1) { int x=spf[n]; int cnt=0; while(n%x==0) { n/=x; cnt++; } ans*=ncr(y+cnt-1,cnt); ans%=mod; ans+=mod; } return ans%mod; } void solve(int x) { ll ans = prime_factor(x); cout << ans%mod << endl; ll t = bigmod(2,y-1) ; ans*=t; ans%=mod; pf1ll( (ans+mod) % mod ); } int main() { sieve(); pre(); int q; sf1(q); while(q--) { int x; sf2(x, y); solve(x); } return 0; } /* */ <file_sep>/LightOJ/1057 - Collecting Gold.cpp #include<bits/stdc++.h> using namespace std; vector<string>vt; int dis[25][25]; int ng; void generating_dis(int m,int n) { vector<int>xx,yy; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(vt[i][j]=='x') { vector<int>::iterator it; it=xx.begin(); xx.insert(it,i); it=yy.begin(); yy.insert(it,j); } else if(vt[i][j]=='g') { xx.push_back(i); yy.push_back(j); } } } memset(dis,0,sizeof dis); for(int i=0;i<xx.size();i++) { for(int j=0;j<xx.size();j++) { dis[i][j]=max(abs(xx[i]-xx[j]),abs(yy[i]-yy[j])); } } ng=xx.size(); } int dp[1<<16][16]; int rec(int mask,int u) { if(mask==(1<<ng)-1) { return dis[u][0]; } int& ret=dp[mask][u]; if(ret!=-1) return ret; ret=INT_MAX; for(int v=0;v<ng;v++) { if(!(mask&(1<<v))) { ret=min(ret,rec(mask|(1<<v),v)+dis[u][v]); } } return ret; } int main() { int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int m,n; cin >> m >> n; vt.clear(); for(int i=0;i<m;i++) { string t; cin >> t; vt.push_back(t); } generating_dis(m,n); memset(dp,-1,sizeof dp); int t=rec(0,0); cout << "Case " << qq << ": " << t << '\n'; } return 0; } <file_sep>/Marathon/Weekly Marathon #2 by DJ/n.cpp #include<bits/stdc++.h> using namespace std; int main() { int tc; cin >> tc; while(tc--) { int n; cin >> n; set<int>st; int t; while(n--) { cin >> t; st.insert(t); } cout << st.size() << '\n'; } return 0; } <file_sep>/csacademy/Round #65 (Div. 2 only)/c.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100000 vector<int>gr[maxn],node; int vist[maxn],cnt=0,n; int ok =0; void dfs(int u,int p) { vist[u] = 1; cnt++; if(cnt <= n) { ok++; node.push_back(u); } for(int v : gr[u]) { if(v!=p) { dfs(v,u); if(cnt < n) { ok++; node.push_back(u); } } } } int vist1[maxn]; void dfs1(int u,int p) { vist1[u] = 1; cnt++; if(cnt <= n) { pf("%d ",u); } for(int v : gr[u]) { if(v!=p) { dfs1(v,u); if(cnt < n) { pf("%d ",u); } } } } int main() { sf1(n); for(int i=0; i<n-1; i++) { int u,v; sf2(u,v); gr[u].push_back(v); gr[v].push_back(u); } int mn=maxn+7,id=-1; for(int i=1; i<=n; i++) { if(gr[i].size()<mn) { mn=gr[i].size(); id=i; } } dfs(id,-1); cnt=0; pf1(ok-1); dfs1(id,-1); // pf1(node.size()-1); // for(int x : node) // { // pf("%d ",x); // } return 0; } /* */ <file_sep>/LightOJ/1189 - Sum of Factorials.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { vector<ll>vt; vt.push_back(0); vt.push_back(1); for(int i=2 ;i<=20 ;i++ ) { vt.push_back(vt[i-1]*i); } int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { ll num; sf("%lld",&num); vector<int>res; int f=0; while(num>0) { vector<ll>::iterator it; it=lower_bound(vt.begin(),vt.end(),num); if(vt[it-vt.begin()]!=num)it--; if(!res.empty() and res.back()==it-vt.begin()) { if(num==2) { res.push_back(0); res.push_back(1); break; } pf("Case %d: impossible\n",qq); f=1; break; } res.push_back(it-vt.begin()); num-=vt[it-vt.begin()]; } if(f)continue; sort(res.begin(),res.end()); pf("Case %d: %d!",qq,res[0]); for(int i=1 ;i<res.size() ;i++ ) { pf("+%d!",res[i]); } pf("\n"); } return 0; } /* 9 9 */ <file_sep>/Codeforces/Contests/Codeforces Round #332 (Div. 2)/B. Spongebob and Joke.cpp #include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); int n,m; vector<int>vt; cin >> n >> m; int fc[100007],b[100007]; memset(fc,0,sizeof fc); for(int i=1; i<=n; i++) { int t; cin >> t; if(fc[t]!=0) { fc[t]=-1; } else fc[t]=i; } int ff=0; for(int i=0; i<m; i++) { int t; cin >> t; if(fc[t]==0) { cout << "Impossible" << endl; return 0; } if(fc[t]==-1) { ff=1; } else { vt.push_back(fc[t]); } } if(ff==1) { cout << "Ambiguity" << endl; } else { cout << "Possible" << endl; for(int i:vt) cout << i << " "; } return 0; } <file_sep>/LightOJ/1010 - Knights in Chessboard .cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { int tc; sf("%d",&tc); for(int qq=1 ; qq<=tc ; qq++ ) { int n,m; sf("%d %d",&n,&m); if(n==1) { pf("Case %d: %d\n",qq,m); } else if(m==1) { pf("Case %d: %d\n",qq,n); } else if(n==2) { int ans=4*(m/4); if(m%4==1) ans+=2; else if(m%4==2 or m%4==3) ans+=4; pf("Case %d: %d\n",qq,ans); } else if(m==2) { int ans=4*(n/4); if(n%4==1) ans+=2; else if(n%4==2 or n%4==3) ans+=4; pf("Case %d: %d\n",qq,ans); } else { int ans=n*m; int t=ans/2; if(ans%2==1) t++; pf("Case %d: %d\n",qq,t ); } } return 0; } /* */ <file_sep>/Codeforces/Contests/Codeforces Round #428 (Div. 2/C. Journey.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int vector<int>gr[100000+7]; double sum=0.0,cnt=0.0; int dist[100000+7]; long double pro[100000+7]; void dfs(int u,int par) { for(auto v: gr[u]) { if(v!=par) { if(par!=-1) { pro[v]=pro[u]/(gr[u].size()-1); } else { pro[v]=pro[u]/gr[u].size(); } dist[v]=dist[u]+1; /*cout << u << " ---> " << v << endl; cout << "pro " << pro[u] << " " << pro[v] << endl; cout << "dist " << dist[u] << " " <<dist[v] << endl;*/ dfs(v,u); } } } /*void bfs(int src) { queue<int>Q; Q.push(src); while(!Q.empty()) { int u=Q.front(); Q.pop(); for(auto v:gr[u]) { if(dist[v]==0) { dist[v]=dist[u]+1; pro[v]=1/gr. Q.push(v); } } } }*/ int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; for(int i=0;i<n-1;i++) { int u,v; cin >> u >> v; gr[u].push_back(v); gr[v].push_back(u); } pro[1]=1.0; dfs(1,-1); for(int i=1;i<=n;i++) { if(gr[i].size()==1) { sum+=(dist[i]*pro[i]); /*cnt++;*/ } } /* for(int i=1;i<=n;i++) { cout << dist[i] <<" " << pro[i] << endl; }*/ cout << fixed << setprecision(10) << sum << endl; return 0; }<file_sep>/Print/Sieve and Segmented_sieve and Prime Factorization.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int //Problem Statement: // //Your are given two integers a and b. You have to find all the primes within range a and b. Here, 1 ≤ a ≤ b ≤ 231-1 and b - a ≤ 105. // //Note: You have to handle 1, 2 and even numbers for appropriate case of your own. // //Solution: #define MAX 46656 ///joto porjonto sieve korte cai #define LMT 216 /// sqrt(MAX) #define LEN 4830 ///appx number of primes #define RNG 100032 ///range for segmentflaged sieve #define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31))) #define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31))) unsigned primeflag[MAX/64+7], segmentflag[RNG/64+7], primes[LEN+7]; /* Generates all the necessary prime numbers and marks them in primeflag[]*/ void sieve() { unsigned long long int i, j, k; for(i=3; i<LMT; i+=2) if(!chkC(primeflag, i)) for(j=i*i, k=i<<1; j<MAX; j+=k) setC(primeflag, j); j=0; primes[j++]=2; for(i=3; i<MAX; i+=2) if(!chkC(primeflag, i)) primes[j++] = i; } /* Returns the prime-count within range [a,b] and marks them in segmentflag[] */ unsigned long long int segmented_sieve(int a, int b) { unsigned long long int i, j, k, cnt = (a<=2 && 2<=b)? 1 : 0; if(b<2) return 0; if(a<3) a = 3; if(a%2==0) a++; memset(segmentflag,0,sizeof segmentflag); for(i=1; primes[i]*primes[i]<=b; i++) { j = primes[i] * ( (a+primes[i]-1) / primes[i] ); if(j%2==0) j += primes[i]; for(k=primes[i]<<1; j<=b; j+=k) if(j!=primes[i]) setC(segmentflag, (j-a)); } for(i=0; i<=b-a; i+=2) if(!chkC(segmentflag, i)) cnt++; return cnt; } /*prime factor gula factors vectors a store kore rakhe complexity:sqrt(n) */ void prime_factorize(ll n) { vector<int>factors; int sqrtn = sqrt ( n ); for ( int i = 0; i < LEN && primes[i] <= sqrtn; i++ ) { if ( n % primes[i] == 0 ) { while ( n % primes[i] == 0 ) { n /= primes[i]; factors.push_back(primes[i]); } sqrtn = sqrt ( n ); } } if ( n != 1 ) { factors.push_back(n); } } int main() { sieve(); cout << segmented_sieve(1,100) << endl; prime_factorize(100); return 0; } <file_sep>/Codeforces/C numbers/C. Ordering Pizza.cpp #include<bits/stdc++.h> using namespace std; bool cmp(pair<int,pair<int,int> > x, pair<int,pair<int,int> > y) { if(x.first==y.first) { int dx=abs(x.first-x.second.first); int dy=abs(y.first-y.second.first); if(dx==dy) { return x.first>y.first; } else return dx>dy; } else return x.first>y.first; } int main() { int n,s; scanf("%d %d",&n,&s); vector< pair<int,pair<int,int> > >temp; for(int i=0;i<n;i++) { int p,a,b; scanf("%d %d %d",&p,&a,&b); temp.push_back({a,{b,p}}); } sort(temp.begin(),temp.end(),cmp); for(int i=0;i<n;i++) cout << temp[i].first << endl; return 0; }<file_sep>/LightOJ/1097 - Lucky Number.cpp #include<bits/stdc++.h> using namespace std; #define mxn 1429531 int tree[4*mxn+7]; int lucky[100007]; void build(int id,int l,int r) { if(l==r) { tree[id]=l&1; return; } int mid=(l+r)/2; build(id*2,l,mid); build(id*2+1,mid+1,r); tree[id]=tree[id*2]+tree[id*2+1]; } int query(int id,int l,int r,int ps) { if(l==r) return l; int mid=(l+r)/2; if(tree[id*2]>=ps) return query(id*2,l,mid,ps); else return query(id*2+1,mid+1,r,ps-tree[id*2]); } void updt(int id,int l,int r,int ps) { if(l==r) { tree[id]=0; return; } int mid=(l+r)/2; if(tree[id*2]>=ps) updt(id*2,l,mid,ps); else updt(id*2+1,mid+1,r,ps-tree[id*2]); tree[id]=tree[id*2]+tree[id*2+1]; } void init() { build(1,1,mxn); lucky[1]=1; vector<int>vt,tt; for(int i=2; i<=100000; i++) { int q=query(1,1,mxn,i); lucky[i]=q; int j = (mxn / q) * q; for(; j>=q; j -= q ) { updt(1,1,mxn,j); } } } int main() { ios_base::sync_with_stdio(0); init(); int tc; cin >> tc; for(int qq=1; qq<=tc; qq++) { int n; cin >> n; cout << "Case " << qq << ": " << lucky[n] << '\n'; } return 0; } <file_sep>/Codeforces/Contests/191/C. Magic Five.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 #define mod 1000000007 ll bigmod(ll b,ll p) { ll ans=1; while(p>0) { if(p&1) ans=(ans*b)%mod; p>>=1; b=(b*b)%mod; } return ans%mod; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string str; cin >> str; int k; cin >> k; ll ans=0; for(int i=0;i<str.size();i++) { if(str[i]=='0' || str[i]=='5') { ans+=bigmod(2,i); ans%=mod; } } ll n=str.size(); ll t=bigmod(2,n)-1; ll s=( bigmod(2,k*n)-1 ) * bigmod(t,mod-2); s%=mod; cout << (ans*s)%mod << endl; return 0; } <file_sep>/USACO/Section 1.5/Number Triangles2.cpp /* ID:shishir10 LANG:C++11 TASK:numtri */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define sf scanf #define pf printf int n; int ara[1000+7][1000+7]; int fx[]={1,1}; int fy[]={0,1}; bool ok(int x,int y) { if(x>=0 and x<n and y>=0 and y<n and y<=x ) return true; return false; } int mx=0; int dp[1007][1007]; int solve(int x,int y) { if(y>x) return 0; if(x==n-1) { return ara[x][y]; } int &ret=dp[x][y]; if(ret != -1) return ret; for(int i=0;i<2;i++) { int tx = x+fx[i] ; int ty = y+fy[i] ; if( ok(tx,ty)) { ret=max(ret,ara[x][y]+solve(tx,ty) ); } } return ret; } int main() { freopen("numtri.in","r",stdin); freopen("numtri.out","w",stdout); sf("%d",&n); for(int i=0;i<n;i++) { for(int j=0;j<i+1;j++) { sf("%d",&ara[i][j]); } } memset(dp,-1,sizeof dp); pf("%d\n",solve(0,0)); return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #299 (Div. 2)/D. Tavas and Malekas.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { int n,m,t; cin >> n >> m; char ara[n+7]; memset(ara,0,sizeof ara); string str; cin >> str; while(m--) { sf("%d",&t); int s=0; for(int i=t ;s<str.size() and i<=n ;i++,s++ ) { ara[i]=str[s]; // cout << ara[i] << endl; } } int cnt=0; for(int i=1 ;i<=n ;i++ ) { cout << ara[i] ; } for(int i=1 ;i<=n ;i++ ) { if(ara[i]==0){ cout << i << endl; cnt++; } } ll ans=1; while(cnt--) { ans*=26; ans%=1000000007; } cout << ans ; return 0; } /* */ <file_sep>/Python/Rubik's cube/taking input.py ''' x = int(input('Enter an integer: ')) y = int(input('Enter another integer: ')) formatStr = '{0} + {1} = {2}; {0} * {1} = {3}.' equations = formatStr.format(x, y, x+y, x*y) print(equations) name= input('enter yout name: ') print('Hello ',name, '!',sep='') a = 5 b = 9 setStr = 'The set is {{{}, {}}}.'.format(a, b) print(setStr) y=input('enter second number: ') x=input('enter first number: ') tx=int(x); ty=int(y); #print("the sum of two number is ",tx+ty,sep='') print("the summation of {} and {} is {} \n".format(tx,ty,tx+ty)) person=input("enter the name of the person") gret="hi {}".format(person) print(gret) ''' #import queue q = queue.Queue() for i in range(5): q.put(i) while not q.empty(): print(q.get(), end=' ') print()<file_sep>/Marathon/CUET Workshop - Data Structure Volume/Sum of Squares with Segment Tree.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 1000000 pair<int,int> tree[maxn*4]; pair<int,int> lazy[4*maxn]; int ara[maxn+500]; void build(int id,int l,int r) { if(l==r) { tree[id].first=ara[l]*ara[l]; tree[id].second=ara[l]; return ; } int mid=(l+r)/2; build(id*2,l,mid); build(id*2+1,mid+1,r); tree[id].first=tree[id*2].first+tree[id*2+1].first; tree[id].second=tree[id*2].second+tree[id*2+1].second; } void shift(int id,int l,int r) { if(l!=r) { int mid=(l+r)/2; if(lazy[id].first) { tree[id*2].first=tree[id*2].first+2LL*lazy[id].first*tree[id*2].second+(mid-l+1)*lazy[id].first*lazy[id].first; tree[id*2].second+=(mid-l+1)*lazy[id].first; tree[id*2+1].first=tree[id*2+1].first+2LL*lazy[id].first*tree[id*2+1].second+(r-mid)*lazy[id].first*lazy[id].first; tree[id*2].second+=(r-mid+1)*lazy[id].first; lazy[id].first=0; } if(lazy[id].second) { tree[id*2].first=(mid-l+1)*lazy[id].second*lazy[id].second; tree[id*2].second=(mid-l+1)*lazy[id].second; tree[id*2+1].first=(r-mid)*lazy[id].second*lazy[id].second; tree[id*2].second=(r-mid+1)*lazy[id].second; lazy[id].second=0; } } return; } void updt(int id,int l,int r,int ql,int qr,int typ,int val) { if(r<ql || l>qr) return; shift(id,l,r); if(l>=ql and r<=qr) { if(typ==1) { tree[id].first=tree[id].first+2LL*val*tree[id].second+(r-l+1)*val*val; tree[id].second+=1LL*(r-l+1)*val; lazy[id].first+=1LL*val; } else if(typ==0) { tree[id].first=1LL*(r-l+1)*val*val; tree[id].second=1LL*(r-l+1)*val; lazy[id].second=val; } return; } int mid=(l+r)/2; updt(id*2,l,mid,ql,qr,typ,val); updt(id*2+1,mid+1,r,ql,qr,typ,val); tree[id].first=tree[id*2].first+tree[id*2+1].first; tree[id].second=tree[id*2].second+tree[id*2+1].second; } int query(int id,int l,int r,int ql,int qr) { if(r<ql || l>qr) return 0; if(l>=ql and r<=qr) { return tree[id].first; } int mid=(l+r)/2; return ( query(id*2,l,mid,ql,qr) + query(id*2+1,mid+1,r,ql,qr) ); } int main() { int tc; scanf("%d",&tc); for(int qq=1;qq<=tc;qq++) { printf("Case %d:\n",qq); int n,m; scanf("%d %d",&n,&m); for(int i=1;i<=n;i++) { scanf("%d",&ara[i]); } build(1,1,n); while(m--) { int typ; scanf("%d",&typ); if(typ==2) { int l,r; scanf("%d %d",&l,&r); printf("%d\n",query(1,1,n,l,r)); } else if(typ==1) { int l,r,x; scanf("%d %d %d",&l,&r,&x); updt(1,1,n,l,r,typ,x); } else { int l,r,x; scanf("%d %d %d",&l,&r,&x); updt(1,1,n,l,r,typ,x); } } } return 0; }<file_sep>/Marathon/Suffix Array/test.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 struct entry{ int nr[3],p; }L[maxn]; int lcp[maxn]; bool cmp(entry a,entry b) { return (a.nr[0] == b.nr[0]) ? (a.nr[1] < b.nr[1] ? 1 : 0) : (a.nr[0] < b.nr[0] ? 1 : 0); } int P[20][maxn]; inline void sa(string str) { int n = str.size(); memset(P,-1,sizeof P); for(int i=0;i<n;i++) { P[0][i] = str[i] - 'a'; } int stp,cnt; for(stp = 1,cnt=1; cnt < n; stp++,cnt<<=1) { for(int i=0;i<n;i++) { L[i].nr[0] = P[stp-1][i]; L[i].nr[1] = i+cnt<n ? P[stp-1][i+cnt] : -1; L[i].p = i; } sort(L,L+n,cmp); for(int i=0;i<n;i++) { P[stp][L[i].p] = i>0 && L[i-1].nr[0] == L[i].nr[0] && L[i-1].nr[1] == L[i].nr[1] ? P[stp][L[i-1].p] : i ; } } lcp[0] = 0; for(int i=1;i<n;i++) { int x = L[i-1].p; int y = L[i].p; lcp[i] = 0; for(int k=stp-1;k>=0;k--) { if( (P[k][x] == P[k][y])) { lcp[i] += (1<<k); x+=(1<<k); y+=(1<<k); } } } cout << " --> " << lcp[1] << " " << lcp[2] << endl; } int main() { sa("abab"); return 0; } /* */ <file_sep>/Codeforces/Contests/Educational Codeforces Round 18/B. Tea Queue.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 1000007 int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; while(tc--) { int n; cin >> n; vector< pair<int,pii> > vt; for(int i=1;i<=n;i++) { int l,r; cin >> l >> r; vt.push_back( {l,{i,r}} ); } sort(vt.begin(),vt.end()); int tim=1; int ans[n+7]; memset(ans,0,sizeof ans); for(int i=0;i<vt.size();i++) { if(tim<=vt[i].sc.sc) { if(tim<vt[i].fs) { tim = vt[i].fs; } ans[vt[i].sc.fs] = tim; tim++; } } for(int i=1;i<n;i++) { cout << ans[i] << " "; } cout << ans[n] << endl; } return 0; } /* */ <file_sep>/Codeforces/Contests/Codeforces Round 225/A. Milking cows.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); int n; cin >> n; int ara[n+7]; for(int i=0;i<n;i++) { cin >> ara[i]; } ll ans=0; ll flag[n+7]; memset(flag,0,sizeof flag); for(int i=n-1;i>=0;i--) { if(ara[i]==0) { flag[i]++; } flag[i]+=flag[i+1]; } for(int i=0;i<n;i++) { if(ara[i]==1) { ans+=flag[i+1]; } } // int rr[n+7]; // memset(rr,0,sizeof rr); // for(int i=0;i<n;i++) // { // if(ara[i]==1) // { // rr[i]++; // } // if(i !=0 ) // { // rr[i]+=rr[i-1]; // } // } // // int ans1=0; // for(int i=n-1;i>=0;i--) // { // if(ara[i]==0) // { // ans1+=rr[i]; // } // } // cout << min(ans,ans1) << endl; cout << ans << endl; return 0; } <file_sep>/Stuffs/all header.cpp #include <cstdio> #include <sstream> #include <cstdlib> #include <cctype> #include <cmath> #include <algorithm> #include <set> #include <queue> #include <stack> #include <list> #include <iostream> #include <fstream> #include <numeric> #include <string> #include <vector> #include <cstring> #include <map> #include <iterator> #include<complex> ///#include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); return 0; } /* */ <file_sep>/Marathon/Mathematics/Q - Probability UVA - 11346.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 #define eps 1e-6 int main() { // cout << log(2.71828) << endl; ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; while(tc--) { double a,b,s; cin >> a >> b >> s; double c=s/b; double d=a; double ar=a*b; double ans; if( s==0.0 ) ans=100.0; // else if(s>a*b) ans=0.0; else { double total=s* log(a*b/s) + b*c; ans=1-(total/ar); ans*=100.0; } cout << setprecision(6) << fixed << ans << "%" << endl; } return 0; } <file_sep>/LightOJ/1200 - Thief.cpp #include<bits/stdc++.h> using namespace std; int p[107],w[107]; int dp[107][10007]; int n; int rec(int ps,int sum) { if(ps>=n) { return 0; } int& ret=dp[ps][sum]; if(ret!=-1) return ret; if(sum>=w[ps]) ret=rec(ps,sum-w[ps])+p[ps]; ret=max(ret,rec(ps+1,sum)); return ret; } int main() { int tc; scanf("%d",&tc); for(int qq=1;qq<=tc;qq++) { int tw,s=0; scanf("%d %d",&n,&tw); for(int i=0;i<n;i++) { int t=0; scanf("%d %d %d",&p[i],&t,&w[i]); s+=(t*w[i]); } int cap=tw-s; if(cap<0) { printf("Case %d: Impossible\n",qq); } else if(cap==0) { printf("Case %d: 0\n",qq); } else { /*cout << "cap " << cap << endl;*/ memset(dp,-1,sizeof dp); int ans=rec(0,cap); printf("Case %d: %d\n",qq,ans ); } } return 0; }<file_sep>/Marathon/CodeChef DP/R - The Number Of Solutions.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define mod 1000000007 ll bigmod(ll a,ll b,ll m) { /// a^b%m ll ans=1; while(b>0) { if(b&1) ans=(a*ans)%m; b>>=1; a=(a*a)%m; } return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; while(tc--) { int n; cin >> n; int ara[n+7]; for(int i=1;i<=n;i++) { cin >> ara[i]; } for(int i=1;i<=n;i++) cout << ara[i] << " "; cout << endl; ll sum[107],dp[n+7]; ll ans=0; for(int diff=1;diff<=1;diff++) { memset(sum,0,sizeof sum); memset(dp,0,sizeof dp); ll cur=0; for(int i=1;i<=n;i++) { if( (ara[i]-diff) >= 0 and (ara[i]-diff) <= 100 ) { /*cout << "difference " << diff << " " << ara[i]-diff << " " << i << endl;*/ dp[i]=dp[ara[i]-diff]+1; /*cout << dp[i] << " ok " << endl;*/ sum[ara[i]]+=dp[i]; cur+=dp[i]; cur%=mod; sum[i]%=mod; } } /* cout << dp[1] << " " << dp[2] << " " << dp[3] << endl; cout << diff << " diff er jonno " << cur << endl;*/ if(cur) { ans+=cur; ans-=n; ans%=mod; /*cout << "ans " << ans << " diff " << diff << " cur " << cur << endl;*/ } } cout << ans << endl; cout << "####" << endl; for(int diff=-10;diff<0;diff++) { memset(sum,0,sizeof sum); memset(dp,0,sizeof dp); ll cur=0; for(int i=1;i<=n;i++) { int f=0; if( (ara[i]+diff) >= 0 and (ara[i]+diff) <= 100 ) { cout << "difference " << diff << " " << ara[i]+diff << " " << i << endl; f=1; dp[i]=dp[ara[i]+diff]+1; sum[ara[i]]+=dp[i]; cur+=dp[i]; cur%=mod; sum[i]%=mod; } } cout << diff << " diff er jonno " << cur << endl; if(cur) { ans+=cur; ans-=n; ans%=mod; /*cout << "ans " << ans << " diff " << diff << " cur " << cur << endl;*/ } } cout << " ans " << ans << endl; ans+=n; cout << bigmod(2,n,mod) << " big " << endl; ans=bigmod(2,n,mod)-1-ans; cout << ans << endl; } return 0; }<file_sep>/Marathon/CodeChef DP/test.cpp #include<bits/stdc++.h> using namespace std; #define mx 200005 int SQ; struct data{ int l, r, idx; bool operator < (const data &a) const{ if(l/SQ == a.l/SQ) return r < a.r; else return l/SQ < a.l/SQ; } }Q[mx]; int ara[mx]; int cnt[1000005]; long long ans[mx]; long long counti = 0; inline void add(int i) { counti += 1ll * ara[i] * (2 * cnt[ara[i]] + 1); cnt[ara[i]]++; } inline void remove(int i) { counti += 1ll * ara[i] * (- 2 * cnt[ara[i]] + 1); cnt[ara[i]]--; } int main() { int n, m; scanf("%d %d", &n, &m); for(int i = 1; i<=n; i++) scanf("%d", &ara[i]); for(int i = 0; i<m; i++){ scanf("%d %d", &Q[i].l, &Q[i].r); Q[i].idx = i; } SQ = sqrt(n); sort(Q, Q+m); cnt[0] = 2; //Here prevL and prevR represents inclusive information int prevL = 0, prevR = 0; for(int i = 0; i<m; i++) { while(prevL < Q[i].l) remove(prevL++); while(prevL > Q[i].l) add(--prevL); while(prevR < Q[i].r) add(++prevR); while(prevR > Q[i].r) remove(prevR--); ans[Q[i].idx] = counti; } for(int i = 0; i<m; i++) printf("%lld\n", ans[i]); return 0; }<file_sep>/Codeforces/Contests/Educational Codeforces Round 18/B. Counting-out Rhyme.cpp #include<bits/stdc++.h> using namespace std; int main() { int n,k; cin >> n >>k ; vector<int>vt,numbers; for(int i=0; i<k; i++) { int t; cin >> t; vt.push_back(t); } for(int i=1; i<=n; i++) { numbers.push_back(i); } vector<int>ans; int j=0; for(int i=0; i<k; i++) { int t=1; while(t<=vt[i]) { t++; j++; if(j>=numbers.size()) j=0; } ans.push_back(numbers[j]); numbers.erase(numbers.begin()+j); if(j>=numbers.size()) j=0; } for(auto it: ans) cout << it << " "; return 0; } <file_sep>/Codeforces/C numbers/A. Between the Offices.cpp #include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; string str; cin >> str; int s=0,f=0; for(int i=1;i<str.size();i++) { if(str[i]=='F' and str[i-1]=='S') f++; if(str[i]=='S' and str[i-1]=='F')s++; } if(s<f) { cout << "YES" << endl; } else { cout << "NO" << endl; } return 0; } <file_sep>/Codeforces/B numbers/testint.cpp #include<bits/stdc++.h> using namespace std; int tree[507][507*4],ara[507][507]; void build(int id,int l,int r,int row) { if(l==r) { tree[row][id]=ara[row][l]; return; } int mid=(l+r)/2; build(id*2,l,mid,row); build(id*2+1,mid+1,r,row); tree[row][id]=max(tree[row][id*2],tree[row][id*2+1]); } int query(int id,int l,int r,int row,int ql,int qr) { if(r<ql || l>qr) return INT_MIN; if(l>=ql and r<=qr) return tree[row][id]; int mid=(l+r)/2; return max(query(id*2,l,mid,row,ql,qr),query(id*2+1,mid+1,r,row,ql,qr)); } int main() { int tc; scanf("%d",&tc); for(int qq=1;qq<=tc;qq++) { printf("Case %d:\n",qq); int n,q; scanf("%d %d",&n,&q); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) scanf("%d",&ara[i][j]); for(int i=1;i<=n;i++) build(1,1,n,i); while(q--) { int p,q,s; scanf("%d %d %d",&p,&q,&s); int ans=INT_MIN; for(int i=p;i<=p+s-1;i++) { ans=max(ans,query(1,1,n,i,q,q+s-1)); } printf("%d\n",ans ); } } return 0; }<file_sep>/Codeforces/Contests/Codeforces Round #305 (Div. 2)/A. Mike and Fax.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 100000 string str; int k,j; bool ok(int i) { string temp=str.substr(i,j); string t=temp; reverse(temp.begin(),temp.end()); if(t==temp) return 1; return 0; } int main() { cin >> str; cin >> k; int l=str.size(); if(l%k==0) { j=l/k; for(int i=0 ;i<l ;i+=j ) { if(!ok(i)) { cout << "NO"; return 0; } } cout << "YES"; return 0; } else cout << "NO"; return 0; } /* fff 2 */ <file_sep>/LightOJ/1145 - Dice (I).cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define mod 100000007 ll dp[15007],pre[15007]; int main() { int tc; scanf("%d",&tc); for(int qq=1;qq<=tc;qq++) { int n,k,sum; scanf("%d %d %d",&n,&k,&sum); memset(dp,0,sizeof dp); memset(pre,0,sizeof pre); for(int pos=1;pos<=n;pos++) { for(int s=1;s<=sum;s++) { pre[s]=(pre[s-1]+dp[s])%mod; } for(int s=1;s<=sum;s++) { if(pos==1) { if(s<=k) dp[s]=1; else dp[s]=0; } else { int l=max(s-k,1); int r=s-1; dp[s]=(pre[r]-pre[l-1]+mod)%mod; } } } printf("Case %d: %lld\n", qq,dp[sum]%mod); } return 0; }<file_sep>/LightOJ/1188 - Fast Queries.cpp #include<bits/stdc++.h> using namespace std; vector< unordered_set<int> >tree(3*100000+7); int ara[100000+7]; void build(int id,int left,int right) { if(left==right) { tree[id].insert(ara[left]); return; } int mid=(left+right)/2; build(id*2,left,mid); build(id*2+1,mid+1,right); tree[id].insert(tree[id*2].begin(),tree[id*2].end() ); tree[id].insert(tree[id*2+1].begin(),tree[id*2+1].end() ); } set<int> temp; void query(int id,int left,int right,int i,int j) { if(left>j or right<i) return ; if(left>=i and right<=j) { temp.insert(tree[id].begin(),tree[id].end()); return ; } int mid=(left+right)/2; query(id*2,left,mid,i,j); query(id*2+1,mid+1,right,i,j); } int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n,q; cin >> n >> q; for(int i=1;i<=n;i++) { cin >> ara[i]; } tree.clear(); build(1,1,n); cout << "Case " << qq << ":" << '\n'; while(q--) { int l,r; cin >> l >> r; temp.clear(); query(1,1,n,l,r); cout << temp.size() << endl; } } return 0; } <file_sep>/Contest/Battle of Brains, 2017 (Replay)/Meena o Rajur Boring Class.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; while(tc--) { int n; cin >> n; double ara[40]; ara[0]=0,ara[1]=1; for(int i=2;i<40;i++) { ara[i]=ara[i-1]+ara[i-2]; } double sum=0; for(int i=1;i<=n;i++) { sum+=ara[i]*ara[i]*(1.0-3.141593/4); } cout << fixed << setprecision(2) << sum << endl; } return 0; }<file_sep>/Marathon/Weekly Marathon #3 by DJ/I - Saitama Destroys Hotel.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 bool cmp(pii a, pii b) { if(a.fs>b.fs) return 1; else return 0; } int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); // const clock_t begin_time = clock(); int n,top; cin >> n >> top; ll sum=0; vector<pii>vt; for(int i=0;i<n;i++) { int f,t; cin >> f >> t; vt.push_back({f,t}); } sort(vt.begin(),vt.end(),cmp); int l=top; for(int i=0;i<n;i++) { sum+=(l-vt[i].fs); l=vt[i].fs; if(sum<vt[i].sc) { sum+=(vt[i].sc-sum); } } sum+=(l-0); cout << sum << endl; // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/Codeforces/Contests/Educational Codeforces Round 18/A. Water The Garden.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 1000007 int main() { int tc; cin >> tc; while(tc--) { int n,k; cin >> n >> k; int ara[k+7]; for(int i=0; i<k; i++) { cin >> ara[i]; } int mx = ara[0]; mx = max(mx,n-ara[k-1]+1); for(int i=1; i<k; i++) { mx = max(mx,(ara[i]-ara[i-1])/2 + 1); } cout << mx << endl; } return 0; } /* */ <file_sep>/Marathon/Weekly Marathon #5 by DJ/K - Lefthanders and Righthanders.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); int n; cin >> n; string str; cin >> str; int d=n/2; for(int i=0;i<d;i++) { if(str[i]=='R' && str[i+d]=='L') { cout << i+d+1 << " " << i+1 << endl; } else { cout << i+1 << " " << i+d+1 << endl; } } return 0; }<file_sep>/Codeforces/Contests/AIM Tech Round 4 (Div. 2)/A. Diversity.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string str; int t; cin >> str >> t; set<char>st; for(auto it : str) { st.insert(it); } int k=t-st.size(); if(st.size()>=t) { cout << 0; } else if(t>26 || t>str.size()) { cout << "impossible" << endl; } else { cout << k; } return 0; }<file_sep>/Contest/Team Forming Contest 2 (26-8-2017) (2015)/F - Multiply game.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define mod 1000000007 #define maxn 50000+7 ll tree[5*maxn]; ll ara[maxn]; void build(int id,int l,int r) { if(l==r) { tree[id]=ara[l]; return ; } int mid=(l+r)/2; build(id*2,l,mid); build(id*2+1,mid+1,r); tree[id]=(tree[id*2]*tree[id*2+1])%mod; } void updt(int id,int l,int r,int ps,int u) { if(l==r) { tree[id]=u; return; } int mid=(l+r)/2; if(ps<=mid) updt(id*2,l,mid,ps,u); else updt(id*2+1,mid+1,r,ps,u); tree[id]=(tree[id*2]*tree[id*2+1])%mod; } ll query(int id,int l,int r,int ql,int qr) { if(r<ql || l>qr) return 1; if(l>=ql and r<=qr) return tree[id]; int mid=(l+r)/2; return (query(id*2,l,mid,ql,qr)*query(id*2+1,mid+1,r,ql,qr) )%mod; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; while(tc--) { int n; cin >> n; for(int i=1;i<=n;i++) { cin >> ara[i]; } build(1,1,n); int q; cin >> q; while(q--) { int a,b,c; cin >> a >> b >> c; if(a==1) { updt(1,1,n,b,c%mod); } else { cout << query(1,1,n,b,c) << endl; } } } return 0; }<file_sep>/LightOJ/1089.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { int tc; sf(""%d",&tc); for(int qq=1;qq<=tc;qq++) { int n,q; sf("%d %d",&n,&q); unorderd_map<ll,int>mp; hv=1; vector<pii>seg; for(int i=0;i<n;i++) { int x,y; sf("%d %d",&x,&y); if(mp.find(x)==mp.end()) { mp[x]=hv++; } if(mp.find(y)==mp.end()) { mp[y]=hv++; } seg.push_back({mp[x],mp[y]}); } vector<int>points; for(int i=0;i<q;i++) { int t; sf("%d",&t); if(mp.find(t)==mp.begin()) { mp[t]=hv++; } points.push_back(mp[t]); } `} return 0; } } return 0; } /* */ <file_sep>/Contest/SPC Individual Contest 02 [18-03-2017]/Little Girl and Maximum XOR.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { ll l,r; cin >> l >> r ; unsigned long long int ara[56]; ara[1]=1; for(int i=2;i<56;i++) { ara[i]=ara[i-1]*2; } if(l==r) cout << 0; else { int i=1; while(1) { if(ara[i++]>r) { break; } } cout << ara[i-1]-1 ; } return 0; } /* */ <file_sep>/LightOJ/1079 - Just another Robbery.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 double gp, cau[107]; int igp,icau[107]; int tak[107],n; int dp[107][10007]; double rec(int ps,int amt,int p) { if(ps>=n) return 0; int& ret=dp[ps][amt]; if(ret!=-1) return ret; int p1=0,p2=0; if(p+(100-p)*icau[ps] <= igp) { p1=tak[ps]+rec(ps+1,amt+tak[ps],p+(100-p)*icau[ps]); } p2=rec(ps+1,amt,p); return ret=max(p1,p2); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { cin >> gp >> n; // gp-=.0001; igp=gp*100; cout << "igp " << igp << endl; for(int i=0;i<n;i++) { cin >> tak[i] >> cau[i]; icau[i]=cau[i]*1000; cout << cau[i] << " fine " << icau[i] << endl; // cout << icau[i] << endl; } memset(dp,-1,sizeof dp); int ans=rec(0,0,0); cout << "Case " << qq << ": " << ans << endl; } return 0; } /* 5 0.27 6 10 0.86 5 0.11 6 0.61 2 0.89 9 0.27 4 0.81 */ <file_sep>/Marathon/Weekly Marathon #7 by DJ/A - Chat Order.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; unordered_map<string,bool>mp; cin >> n; vector<string>vt,ans; for(int i=0;i<n;i++) { string t; cin >> t; vt.push_back(t); } reverse(vt.begin(),vt.end()); for(auto it:vt) { if(mp[it]==0) { ans.push_back(it); mp[it]=1; } } for(auto it:ans) cout << it << endl; return 0; }<file_sep>/Marathon/Weekly Marathon #2 by DJ/f.cpp #include<bits/stdc++.h> using namespace std; int main() { freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); int tc; cin >> tc; while(tc--) { int n; cin >> n; unordered_map<int,int>mp; int st=1; int mx=0,i; for(i=1;i<=n;i++) { int t; cin >> t; if(mp[t] && mp[t]>=st) { mx=max(mx,i-st); st=max(st,mp[t])+1; } mp[t]=i; } mx=max(mx,i-st); cout << mx << '\n'; } // cout << '\n'; return 0; } <file_sep>/Marathon/Weekly Marathon #3 by DJ/e.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { /* freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); */ // const clock_t begin_time = clock(); string str; cin >> str; cout << 26*(str.size()+1)-str.size(); // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/Novice/Sparse table/rmq.cpp #include<bits/stdc++.h> using namespace std; int table[100][9]; int ara[]={2,4,3,1,6,7,8,9,1,7}; void prep(int n) { for(int i=0;i<n;i++) { table[i][0]=i; } for(int j=1;(1<<j)<n;j++) { for(int i=0;(i+(1<<j)-1)<n;i++) { if(ara[table[i][j-1] ]<ara[table[i+(1<<(j-1))][j-1] ]) { table[i][j]=table[i][j-1]; } else { table[i][j]=table[i+(1<<(j-1))][j-1]; } } } } int query(int l,int r) { int e=r-l+1; int k=log(e); return min(ara[table[l][k]],ara[table[l+e-(1<<k)][k]]); } int main() { int n=(sizeof ara)/(sizeof (int)); prep(n); cout << query(4,7); return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #429 (Div. 2)/C. Leha and Function.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; int ara[n+7]; vector< pair<int,int> >vt; vector<int>fir,sc; for(int i=0;i<n;i++) { int t; cin >> t; fir.push_back(t); } for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back({t,i}); } sort(fir.rbegin(),fir.rend()); sort(vt.begin(),vt.end()); for(int i=0;i<n;i++) { ara[vt[i].second]=fir[i]; } for(int i=0;i<n;i++) cout << ara[i] << " "; return 0; }<file_sep>/Codeforces/Contests/Codeforces Round #405(Div. 1)/A. Bear and Different Names.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,k; cin >> n >> k; vector<string>vt; for(char i='A';i<='Z';i++) { for(char j='a';j<='z';j++) { string t; t+=i; t+=j; vt.push_back(t); } } for(int i=0;i<n-k+1;i++) { string t; cin >> t; if(t=="NO") { vt[i+k-1]=vt[i]; } } for(int i=0;i<n;i++) { cout << vt[i] << " "; } return 0; }<file_sep>/Marathon/Weekly Marathon #2 by DJ/mergesort.cpp #include<bits/stdc++.h> using namespace std; void merge(int ara[],int p,int q,int r) { int n1=q-p+1; int n2=r-p; int left[n1+3],right[n2+3]; for(int i=0;i<n1;i++) left[i]=ara[i+p]; for(int i=0;i<n2;i++) right[i]=ara[i+q+1]; left[n1]=321; right[n2]=321; int i=0,j=0,k=p; cout << "copy sesh " << endl; while(k<=r) { if(left[i]<=right[j]) { ara[k]=left[i]; i++; } else { ara[k]=right[j]; j++; } k++; } } void mergesort(int ara[],int p,int r) { if(p<r) { int q=(p+r)/2; mergesort(ara,p,q); mergesort(ara,q+1,r); merge(ara,p,q,r); } } int main() { int ara[]={1,78,5,7,99,4,6,8}; mergesort(ara,0,7); for(int i=0;i<8;i++) cout << ara[i] << " "; return 0; } <file_sep>/Codeforces/B numbers/digit.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int dp[12][93][93][3]; ll a,b,k; int l; char vt[12]; int rec(int ps,int dgt_sum,int num,int flag) { if(ps==l) { if(dgt_sum%k==0 and num%k==0) return 1; return 0; } int &ret=dp[ps][dgt_sum][num][flag]; if(ret!=-1) return ret; ret=0; int d= flag==1 ? vt[ps]-'0' : 9; for(int i=0 ;i<=d ;i++ ) { ret+=rec(ps+1,(dgt_sum+i)%k,(num*10+i)%k,i<d?0:flag); } return ret; } int main() { int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { sf("%lld %lld %lld",&a,&b,&k); if(k>90) pf("Case %d: 0\n",qq); else if(k==1) pf("Case %d: %lld\n",qq,b-a+1); else { /// sprintf returns koi ta character newya hoice l=sprintf(vt,"%lld",a-1); memset(dp,-1,sizeof dp); int aa=rec(0,0,0,1); l=sprintf(vt,"%lld",b); memset(dp,-1,sizeof dp); int bb=rec(0,0,0,1); pf("Case %d: %d\n",qq,bb-aa); } } return 0; } /* */ <file_sep>/Codeforces/Contests/Codeforces Round #332 (Div. 2)/D. Spongebob and Squares.cpp #include<bits/stdc++.h> using namespace std; int main() { long long int x; cin >> x; if(x==1) { cout << 1 << endl; cout << 1 << " " << 1 ; return 0; } vector< pair<long long int,long long int> > vt; long long int n=1,m=x,pre=0,lim=x; while(n<lim) { long long int den=n*(n+1)/2; long long int nu=(x+pre); long long int m=nu/den; lim=min(lim,m); // cout << n << " ---> " << m << endl; if(nu%den==0) { if(n!=m) vt.push_back({n,m}); vt.push_back({m,n}); } pre=den+pre; n++; } sort(vt.begin(),vt.end()); cout << vt.size() << '\n'; for(int i=0; i<vt.size(); i++) cout << vt[i].first << " " << vt[i].second << '\n'; return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #299 (Div. 2)/experiment.cpp #include <bits/stdc++.h> using namespace std; #define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i) #define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i)) #define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i)) #define rep(i, c) for(auto &(i) : (c)) #define x first #define y second #define pb push_back #define PB pop_back() #define iOS ios_base::sync_with_stdio(false) #define sqr(a) (((a) * (a))) #define all(a) a.begin() , a.end() #define error(x) cerr << #x << " = " << (x) <<endl #define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n"; #define errop(a) cerr<<#a<<" = ( "<<((a).x)<<" , "<<((a).y)<<" )\n"; #define coud(a,b) cout<<fixed << setprecision((b)) << (a) #define L(x) ((x)<<1) #define R(x) (((x)<<1)+1) #define umap unordered_map //#define max(x,y) ((x) > (y) ? (x) : (y)) #define double long double typedef long long ll; typedef pair<int,int>pii; typedef vector<int> vi; typedef complex<double> point; ll A,B,n,l,t,m,s; inline ll comb(ll x) { return (x * (x-1LL))/2LL; } inline ll h(ll i) { return A + (i-1LL) * B; } inline bool check(ll r) { ll e = comb(r) - comb(l-1LL); // if(B && (double)e > 2e18 / (double)B) // return false; if(h(r) > t) return false; s = m * t; s -= e * B; s -= A * (r - l + 1LL); cout << r << " sum " << m*t-s << " m*t= " << m*t << endl; return (s >= 0LL); } int main() { iOS; cin >> A >> B >> n; while(n --) { cin >> l >> t >> m; if(h(l) > t) { cout << -1 << '\n'; continue; } ll lo = l, hi = max(t, m) + l + 5; while(lo < hi) { ll mid = (lo + hi)/2LL; if(check(mid)) lo = mid; else hi = mid - 1LL; // cout << mid << ' ' << h(mid) << ' ' << check(mid) << endl; if(lo + 1LL == hi) { if(check(hi)) lo = hi; else hi = lo; } } cout << lo << '\n'; } } <file_sep>/USACO/Section 1.3/Prime Cryptarithm.cpp /* ID:shishir10 LANG:C++11 TASK:crypt1 */ #include<bits/stdc++.h> using namespace std; int main() { freopen("crypt1.in","r",stdin); freopen("crypt1.out","w",stdout); int n; cin >> n; vector<int>vt; for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back(t); } sort(vt.begin(),vt.end()); vector<int>three,two; unordered_map<int,int>mp,ff; for(int i=0;i<vt.size();i++) { for(int j=0;j<vt.size();j++) { for(int k=0;k<vt.size();k++) { int a=vt[i]*100+vt[j]*10+vt[k]; three.push_back(a); mp[a]++; for(int l=0;l<vt.size();l++) { int b=vt[l]*1000+a; ff[b]++; } } } } for(int i=0;i<vt.size();i++) { for(int j=0;j<vt.size();j++) { int a=vt[i]*10+vt[j]; two.push_back(a); } } sort(three.begin(),three.end()); sort(two.begin(),two.end()); int cnt=0; for(int i=0;i<three.size();i++) { for(int j=0;j<two.size();j++) { int a=three[i]*two[j]; int b=three[i]*(two[j]%10); int c=three[i]*(two[j]/10); if(a>9999) break; if(ff.find(a)!= ff.end() and mp.find(b)!=mp.end() and mp.find(c)!=mp.end()) { cnt++; } } } cout << cnt << '\n'; return 0; } <file_sep>/Marathon/Weekly Marathon #2 by DJ/c.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; while(tc--) { int n; cin >> n; int mx,ans=INT_MIN; cin >> mx; n--; while(n--) { int t; cin >> t; ans=max(ans,mx-t); mx=max(mx,t); cout << ans << '\n'; } return 0; } <file_sep>/Contest/Individual Practice Contest 1/D - Treediff.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 vector<int>gr[maxn]; set<int>st[maxn]; int val[maxn]; int ans[maxn]; void dfs(int u) { ans[u]=INT_MAX; for(int v : gr[u]) { dfs(v); ans[u]=min(ans[u], ans[v]); if( st[u].size() > st[v].size() ) { swap(st[v],st[u]); } for(auto x : st[v]) { auto it = st[u].upper_bound(x); if(it != st[u].end() ) ans[u]=min(ans[u], (int)abs(x - *it ) ); if(it != st[u].begin() ) { --it; ans[u]=min(ans[u], abs( x - *it) ); } st[u].insert(x); } } if(st[u].empty()) st[u].insert(val[u]); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,m; cin >> n >> m; for(int i=2; i<=n; i++) { int x; cin >> x; gr[x].push_back(i); } for(int i=n-m+1; i<=n; i++) cin >> val[i]; dfs(1); cout << ans[1]; for(int i=2; i<=(n-m); i++) { cout << " " << ans[i]; } return 0; } <file_sep>/Print/mat expo.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int ll mod; struct matrix { int row=0,col=0; ll mat[17][17]; matrix(int a,int b) { row=a; col=b; memset(mat,0,sizeof mat); } }; matrix matmult(const matrix &a, const matrix &b) { /// depending on the problem statement mod sum assert(a.col==b.row); matrix ans(a.row,b.col); for(int i=0; i<a.row; i++) { for(int j=0; j<b.col; j++) { ll sum=0; for(int k=0; k<a.col; k++) { sum+=(a.mat[i][k]*b.mat[k][j]); sum%=mod; } ans.mat[i][j]=sum; } } return ans; } matrix matexpo(matrix base,int p) { /// a matrix is only exponenable when its row==col that means it must have to be a square matrix. matrix ans(base.row,base.row); for(int i=0; i<base.col; i++) { for(int j=0; j<base.col; j++) { ans.mat[i][j]=(i==j); } } while(p) { if(p&1) ans=matmult(ans,base); base=matmult(base,base); p>>=1; } return ans; } void show(const matrix& temp) { printf("-----------------------------\n"); for(int i=0;i<temp.row;i++) { for(int j=0;j<temp.col;j++) cout << temp.mat[i][j] << " "; cout << endl; } printf("-----------------------------\n"); } int main() { long long int n,m; while(cin >> n >> m) { mod=(1LL<<m); matrix M,A,B; M.row=M.col=2; M.mat[0][0]=M.mat[0][1]=M.mat[1][0]=1; M.mat[1][1]=0; A.mat[0][0]=1; A.mat[0][1]=1; A.row=2,A.col=1; matrix temp=matexpo(M,n); B=matmult(temp,A); cout << B.mat[1][0]%mod << endl; } return 0; } <file_sep>/Codeforces/Contests/8VC Venture Cup 2017 - Elimination Round/A. PolandBall and Hypothesis.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 #define sh 1000017 #define c(n) (primeflag[n>>5]&(1<<(n&31))) #define s(n) (primeflag[n>>5]|=(1<<(n&31))) int primeflag[maxn+7]; void sieve() { int l=sqrt(maxn); for(int i=2 ;i<=l ;i++ ) { if(primeflag[i]==0) { for(int j=i*i ;j<=maxn ;j+=i ) { primeflag[j]=1; } } } } int main() { sieve(); int n; cin >> n; for(int i=1 ;i<=1000 ;i++ ) { int t=n*i+1; if(primeflag[t]==1) { cout << i << '\n'; return 0; } } return 0; } /* */ <file_sep>/LightOJ/1129 - Consistency Checker.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 200007 #define next _next int sz = 0 ; int next[15][maxn]; int en[maxn]; bool created[maxn]; int flag = 1; void insert(string &s) { int v = 0; for(int i=0; i<s.size(); i++) { int c = s[i] - '0'; if(! created[next[c][v]]) { next[c][v] = ++sz; created[sz] = true; } v = next[c][v]; if(en[v]>0) { flag = 1; } } ++en[v]; } void clr() { sz = 0; flag = 0; memset(created,false,sizeof created); memset(en,0,sizeof en); memset(next,-1,sizeof next); } bool cmp(string a,string b) { if(a.size() == b.size() ) return a < b; return a.size() < b.size() ; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1; qq<=tc; qq++) { clr(); int n; cin >> n; vector<string>vt; for(int i=0; i<n; i++) { string str; cin >> str; vt.push_back(str); } sort(vt.begin(),vt.end(),cmp); for(int i=0;i<n;i++) { // cout << vt[i] << endl; insert(vt[i]); } if(flag) { cout << "Case " << qq << ": NO" << endl; } else { cout << "Case " << qq << ": YES" << endl; } } return 0; } /* */ <file_sep>/LightOJ/1132 - Summing up Powers2.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 ll mod=4294967296; unsigned int bio[105][105]; void binomial() { for(int i=0;i<75;i++) { bio[i][0]=bio[i][i]=1; bio[i][1]=i; for(int j=2;j<i;j++) { bio[i][j]=( bio[i-1][j]+bio[i-1][j-1] )%mod; } } } struct matrix { int row=57,col=57; unsigned int mat[107][107]; matrix(int a,int b) { row=a; col=b; memset(mat,0,sizeof mat); } }; matrix matmult(const matrix &a, const matrix &b) { /// depending on the problem statement mod sum assert(a.col==b.row); matrix ans(a.row,b.col); for(int i=0; i<a.row; i++) { for(int j=0; j<b.col; j++) { unsigned int sum=0; for(int k=0; k<a.col; k++) { sum+=(a.mat[i][k]*b.mat[k][j]); } ans.mat[i][j]=sum%mod; } } return ans; } matrix matexpo(matrix base,ll p) { /// a matrix is only exponenable when its row==col that means it must have to be a square matrix. matrix ans(base.row,base.row); for(int i=0; i<base.col; i++) { for(int j=0; j<base.col; j++) { ans.mat[i][j]=(i==j); } } while(p) { if(p&1) ans=matmult(ans,base); base=matmult(base,base); p>>=1; } return ans; } void show(const matrix& temp) { printf("-----------------------------\n"); for(int i=0;i<temp.row;i++) { for(int j=0;j<temp.col;j++) cout << temp.mat[i][j] << " "; cout << endl; } printf("-----------------------------\n"); } int main() { // freopen("input.txt","r",stdin); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); binomial(); // cout << bio[25][0] << endl; int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { ll n,k; cin >> n >> k; if(n==1) { cout << "Case " << qq << ": " << 1 << endl ; continue; } matrix M(k+2,k+2); M.mat[0][0]=1; for(int i=1;i<k+2;i++) { M.mat[0][i]=bio[k][k-(i-1)] ; M.mat[1][i]=bio[k][k-(i-1)]; } for(int i=2;i<k+2;i++) { int t=k-(i-1); for(int j=i;j<k+2;j++) { M.mat[i][j]=bio[k-(i-1)][t--]; } } matrix A(k+2,1); for(int i=0;i<k+2;i++) { A.mat[i][0]=1; } M=matexpo(M,n-1); A=matmult(M,A); cout << "Case " << qq << ": " << A.mat[0][0] << endl ; } return 0; } <file_sep>/Marathon/Weekly Marathon #3 by DJ/J - Ebony and Ivory.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); // const clock_t begin_time = clock(); ll a,b,c; cin >> a >> b >> c; if(!(c%a)) cout << "Yes" ; else if(!(c%b)) cout << "Yes" ; else { int f=1; ll tt=c; while(c>0) { if(c%a==0) { f=0; break; } c-=b; } while(tt>0) { if(tt%b==0) { f=0; break; } tt-=a; } if(f) cout << "No" ; else cout << "Yes"; } // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/LightOJ/1188 - Fast Queries via mos.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 1000000+7 int block; struct data { int l,r,idx; bool operator < (const data &a) const { if(l/block!=a.l/block) return l/block < a.l/block; return r < a.r; } }Q[maxn]; // the size of the cnt should be equal to largest element of the array int ara[maxn],cnt[1000000+7],ans[maxn],counti=0; inline void add(int ps) { cnt[ara[ps]]++; if(cnt[ara[ps]]==1) counti++; } inline void remove(int ps) { cnt[ara[ps]]--; if(cnt[ara[ps]]==0) counti--; } int main() { int tc; scanf("%d",&tc); for(int qq=1;qq<=tc;qq++) { int n,m; scanf("%d %d",&n, &m); block=sqrt(n); for(int i=1;i<=n;i++) { scanf("%d", &ara[i]); } for(int i=0;i<m;i++) { scanf("%d %d",&Q[i].l, &Q[i].r); Q[i].idx=i; } sort(Q,Q+m); memset(cnt,0,sizeof cnt); counti=0; int curL=0 ,curR=0; add(0); for(int i=0;i<m;i++) { while(curL < Q[i].l) remove(curL++); while(curL > Q[i].l) add(--curL); while(curR < Q[i].r) add(++curR); while(curR > Q[i].r) remove(curR--); ans[Q[i].idx]=counti; } printf("Case %d:\n", qq); for(int i=0;i<m;i++) printf("%d\n",ans[i]); } return 0; }<file_sep>/USACO/Section 1.2/Palindromic Squares.cpp /* ID:shishir10 LANG:C++ TASK:palsquare */ #include<bits/stdc++.h> using namespace std; int b; string con(int num) { char ara[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L'}; string str; while(num>0) { str+=ara[num%b]; num/=b; } return str; } int main() { freopen("palsquare.in","r",stdin); freopen("palsquare.out","w",stdout); cin >> b; for(int i=1;i<=300;i++) { string t=con(i*i); string tt=t; reverse(t.begin(),t.end()); if(t==tt) { string a=con(i); reverse(a.begin(),a.end()); cout << a << " " << t << '\n'; } } return 0; } <file_sep>/Contest/Battle of Brains, 2017 (Replay)/Circle and Square.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; while(tc--) { double r; cin >> r; double d=1/sqrt(2); double ans=r/(1-d); cout << fixed << setprecision(1) << ans << endl; } return 0; }<file_sep>/Contest/2016-2017 CTU Open Contest/A - FizzBuzz.cpp #include<bits/stdc++.h> using namespace std; int main() { int n,x,y; while(cin >> x >> y >> n) { for(int i=1;i<=n;i++) { if(i%x==0 && i%y==0) { cout << "FizzBuzz" << endl; } else if(i%x==0) { cout << "Fizz" << endl; } else if(i%y==0) { cout << "Buzz" << endl; } else cout << i << endl; } } return 0; } <file_sep>/UVALive/6832 Bit String Reordering.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int target1[15+7],target2[15+7],given[20],hint[20]; int n,m,gcnt; void make() { int f,j=0; for(int i=0 ; i<m ; i++ ) { int t=hint[i]; if(i==0) { f=1; } for(int k=0; k<t ; k++ ) { if(f) { target1[j++]=0; } else { target1[j++]=1; } } if(f)f=0; else f=1; } /// j=0; for(int i=0 ; i<m ; i++ ) { int t=hint[i]; if(i==0) { f=0; } for(int k=0; k<t ; k++ ) { if(f) { target2[j++]=0; } else { target2[j++]=1; } } if(f)f=0; else f=1; } } int cal1() { int cnt=0; for(int i=0 ; i<n ; i++ ) { if(target1[i]) cnt++; } if(cnt!=gcnt) return inf; int x=0,y=0; cnt=0; for( ; x<n && y <n ; ) { if(target1[x]==given[y] ) { cnt+=(x-y); swap(target1[x],target1[y]); if(x==y) { x++,y++; } else y++; } else { x++; } } return cnt; } int cal2() { int cnt=0; for(int i=0 ; i<n ; i++ ) { if(target2[i]) cnt++; } if(cnt!=gcnt) return inf; int x=0,y=0; cnt=0; for( ; x<n && y <n ; ) { if(target2[x]==given[y]) { cnt+=(x-y); swap(target2[x],target2[y]); if(x==y) { x++,y++; } else y++; } else { x++; } } return cnt; } int main() { freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); while(sf("%d%d",&n,&m)==2) { gcnt=0; for(int i=0 ; i<n ; i++ ) { sf("%d",&given[i]); if(given[i]==1) gcnt++; } for(int i=0 ; i<m ; i++ ) { sf("%d",&hint[i]); } make(); cout << "target1 " << endl; for(int i=0 ; i<n ; i++ ) { cout << target1[i]; } cout << endl; cout << "target2 " << endl; for(int i=0 ; i<n ; i++ ) { cout << target2[i]; } cout << endl; int a=cal1(); int b=cal2(); cout << "after target1 " << endl; for(int i=0 ; i<n ; i++ ) { cout << target2[i]; } cout << endl; cout << "a " << a << " b " << b << endl; int ans=min(a,b); cout << a << '\n'; } return 0; } /* */ <file_sep>/Codeforces/Contests/Educational Codeforces Round 18/C. Swap Adjacent Elements.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 1000007 int main() { ios_base::sync_with_stdio(0); int n; cin >> n; int ara[n+7],mn[n+7],mx[n+7]; for(int i=0;i<n;i++) { cin >> ara[i]; } string str; cin >> str; mx[0]=ara[0]; for(int i=1;i<n;i++) { mx[i] = max(mx[i-1],ara[i]); } mn[n-1]=ara[n-1]; for(int i=n-2;i>=0;i--) { mn[i] = min(mn[i+1],ara[i]); } int f=1; for(int i=0;i<n-1;i++) { if(str[i]=='0' and mn[i+1]< (i+1) ) { f=0; } else if(str[i]=='0' and mx[i]>(i+1)) { f=0; } } if(f) { cout << "YES" << endl; } else { cout << "NO" << endl; } return 0; } /* for(int i=0;vt.size()-1;i++) { cout << vt[i] << " "; } cout << vt.back(); */ <file_sep>/LightOJ/1134 - Be Efficient.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { int tc; scanf("%d",&tc); for(int qq=1;qq<=tc;qq++) { int n,m; scanf("%d %d",&n,&m); ll temp[m+7]; memset(temp,0,sizeof temp); ll sum=0; for(int i=0;i<n;i++) { int t; scanf("%d",&t); sum+=t; sum%=m; temp[sum]++; } ll ans=temp[0]; for(int i=0;i<m;i++) { ans+=(temp[i]*(temp[i]-1)/2); } printf("Case %d: %lld\n", qq,ans); } return 0; }<file_sep>/Implementation/more.cpp #include <iostream> #include <cstdio> #include <vector> #include <cstring> using namespace std; typedef long long ll; ll MOD; #define MAX_N 2 struct Matrix { ll mat[MAX_N][MAX_N]; }; Matrix matMul(Matrix a, Matrix b) { Matrix ans; int i, j, k; for (i = 0; i < MAX_N; i++) for (j = 0; j < MAX_N; j++) for (ans.mat[i][j] = k = 0; k < MAX_N; k++) { ans.mat[i][j] += (a.mat[i][k] % MOD) * (b.mat[k][j] % MOD); ans.mat[i][j] %= MOD; } return ans; } Matrix matPow(Matrix base, int p) { Matrix ans; int i, j; for (i = 0; i < MAX_N; i++) for (j = 0; j < MAX_N; j++) ans.mat[i][j] = (i == j); while (p) { if (p & 1) ans = matMul(ans, base); // update ans base = matMul(base, base); p >>= 1; for(int i=0; i<2; i++) { for(int j=0; j<2; j++) { cout << ans.mat[i][j] << " "; } cout << endl; } cout << "###########" << endl; } return ans; } int main() { int n,m,i; while (scanf("%d %d", &n, &m) == 2) { Matrix ans; ans.mat[0][0] = 1; ans.mat[0][1] = 1; ans.mat[1][0] = 1; ans.mat[1][1] = 0; for (MOD = 1, i = 0; i < m; i++) MOD *= 2; ans = matPow(ans, n); printf("%lld\n", ans.mat[0][1]); } return 0; } <file_sep>/Codeforces/B numbers/A. I'm bored with life.cpp #include<bits/stdc++.h> using namespace std; int main() { long long int a,b; cin >> a >> b; long long int t=min(a,b),tt=1; for(int i=1;i<=t;i++) { tt*=i; } cout << tt ; return 0; } <file_sep>/LightOJ/1081 - Square Queries using sparse table.cpp #include<bits/stdc++.h> using namespace std; int table[507][507][12]; int ara[507][507]; int n; void prepocess(int row) { for(int i=0;i<n;i++) { table[row][i][0]=i; } for(int j=1;(1<<j)<=n;j++) { for(int i=0;(i+(1<<j)-1)<n;i++) { if(ara[row][table[row][i][j-1]]>ara[row][table[row][i+(1<<(j-1))][j-1]]) { table[row][i][j]=table[row][i][j-1]; } else { table[row][i][j]=table[row][i+(1<<(j-1))][j-1]; } } } } int query(int row,int l,int r) { int e=r-l+1; int t=log2(e); return std::max( ara[row][table[row][l][t]], ara[row][table[row][r-(1<<t)+1][t]] ); } int main() { int tc; scanf("%d",&tc); for(int qq=1;qq<=tc;qq++) { printf("Case %d:\n",qq); int q; scanf("%d %d",&n,&q); for(int i=0;i<n;i++) for(int j=0;j<n;j++) scanf("%d",&ara[i][j]); for(int i=0;i<n;i++) prepocess(i); /*cout << "test " << query(1,0,3) << endl;*/ while(q--) { int p,q,s; scanf("%d %d %d",&p,&q,&s); int ans=INT_MIN; p--,q--; /*cout << p << " " << q << endl; cout << p+s-1 << " " << q+s-1 << endl;*/ for(int i=p;i<=p+s-1;i++) { ans=max(ans,query(i,q,q+s-1)); } printf("%d\n",ans ); } } return 0; }<file_sep>/USACO/Section 1.3/Barn Repair.cpp /* ID:shishir10 LANG:C++ TASK:barn1 */ #include<bits/stdc++.h> using namespace std; int main() { freopen("barn1.in","r",stdin); freopen("barn1.out","w",stdout); ios_base::sync_with_stdio(0); int m,s,c; cin >> m >> s >> c; int flag[200+7]; int mn=9000,mx=-1; memset(flag,-1,sizeof flag); while(c--) { int t; cin >> t; flag[t]=1; mn=min(mn,t); mx=max(mx,t); } int cnt=1; int seg[200+7]; for(int i=0;i<200+7;i++) { seg[i]=1; } while(cnt<m) { int x=0,mxx=-1,u,v; for(int i=mn;i<=mx;i++) { if(seg[i]==1 and flag[i]==-1 and x==0) { x=i; } else if(seg[i]==0 or flag[i]==1) { if(i-x>mxx and x!=0) { mxx=max(mxx,i-x); u=x; v=i; } x=0; } } for(int i=u;i<v;i++) { seg[i]=0; } cnt++; } int ans=0; for(int i=mn;i<=mx;i++) { if(seg[i]==1) ans++; } cout << ans << '\n'; return 0; } <file_sep>/Codeforces/B numbers/B. Makes And The Product.cpp #include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); int n; cin >> n; vector<int>a; map<long long int,long long int>mp; for(int i=0;i<n;i++) { int t; cin >> t; a.push_back(t); mp[a[i]]++; } sort(a.begin(),a.end()); if(a[0]==a[1] and a[1]==a[2]) { long long int t=mp[a[0]]; cout << t*(t-1)*(t-2)/6; } else if(a[0]!=a[1] and a[1]==a[2]) { long long int t=mp[a[1]]; cout << t*(t-1)/2; } else { cout << mp[a[2]] ; } return 0; } <file_sep>/Marathon/Mathematics/Fast Typing.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int ara[60]; string str; cin >> str; for(int i=0;i<26;i++) cin >> ara[i]; int ans=0; for(int i=0;i<str.size();i++) { ans+=ara[str[i]-'a']; } cout << ans << endl; return 0; } <file_sep>/Marathon/Mathematics/Foxes on a Wheel.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int node[maxn]; bool ok(int i,int j) { return node[i]+node[j]==3; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,k; cin >> n >> k; for(int i=0;i<k;i++) { int t; cin >> t; node[t]=1; } for(int i=0;i<k;i++) { int t; cin >> t; node[t]=2; } int ans1=0; for(int i=1;i<=n;i++) { if(ok(i,i+1)) { i++; ans1++; } } int ans2=ok(1,n); for(int i=n-1;i>2;i--) { if(ok(i,i-1)) { i--; ans2++; } } int t=max(ans1,ans2); cout << t+(k-t)*2 << endl; return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #426 (Div. 1)/A. The Meaningless Game.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; while(n--) { ll x,y; cin >> x >> y; ll mult=x*y; ll a=pow(mult,1.0/3.0)-2; while(a*a*a<mult) { a++; } if(a*a*a==x*y and x%a==0 and y%a==0 ) { cout << "yes" << '\n'; } else { cout << "no" << '\n'; } } return 0; } <file_sep>/LightOJ/1039 - A Toy Company.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define ll long long int #define maxn 100007 string st,des; string a[57],b[57],c[57]; set<string>pro; int n; int bfs() { map<string,int>mp; queue<string>q; q.push(st); mp[st]=0; while(!q.empty()) { string u=q.front(); q.pop(); string x=u,y=u; for(int i=0;i<3;i++) { if(u[i]!=des[i]) { x[i]++,y[i]--; if(x[i]>'z')x[i]='a'; if(y[i]<'a')x[i]='z'; break; } } cout << u << " theke " << x << " " << y << endl; if(x==des or y==des) { break; } if(mp.find(y)==mp.end()) { if(mp[x]==0) { mp[x]=mp[u]+1; q.push(x); } } if(pro.find(y)!=pro.end()) { if(mp.find(y)==mp.end()) { mp[y]=mp[u]+1; q.push(y); } } } if(mp.find(des)==mp.end()) { return -1; } else return mp[des]; } void mak() { pro.clear(); for(int i=0; i<n; i++) { for(int j=0; j<a[i].size(); j++) { for(int k=0; k<b[i].size(); k++) { for(int l=0; l<c[i].size(); l++) { string t; t+=a[i][j]; t+=b[i][k]; t+=c[i][k]; cout << t << endl; pro.insert(t); } } } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1; qq<=tc; qq++) { cin >> st >> des; cin >> n; for(int i=0; i<n; i++) { cin >> a[i] >> b[i] >> c[i]; } mak(); int t=bfs(); cout << t << endl; } return 0; } <file_sep>/USACO/Section 1.2/Milking Cows.cpp /* ID:shishir10 LANG:C++ TASK:milk2 */ #include<bits/stdc++.h> using namespace std; int main() { freopen("milk2.in","r",stdin); freopen("milk2.out","w",stdout); int n; cin >> n; vector< pair<int,int> > vt; for(int i=0;i<n;i++) { int a,b; cin >> a >> b; vt.push_back(make_pair(a,b)); } sort(vt.begin(),vt.end()); int u=vt[0].first; int v=vt[0].second; int mc=v-u,nmc=0,i; for(i=0;i<n-1;i++) { if(vt[i+1].first>v) { mc=max(mc,v-u); nmc=max(nmc,vt[i+1].first-v); u=vt[i+1].first; // v=vt[i+1].second; } v=max(v,vt[i+1].second); } mc=max(mc,vt[i].second-u); cout << mc << " " << nmc << '\n'; return 0; } <file_sep>/Codeforces/Contests/Educational Codeforces Round 26/E. Vasya's Function.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int vector<ll>primes; void factor(ll n) { for(ll i=2; i*i<=n; i++) { if(n%i==0) { while(n%i==0) { n/=i; primes.push_back(i); } } } if(n!=1) primes.push_back(n); } ll find_max(ll a,ll b) { ll mx=0; for(auto it:primes) { if(a%it==0) { mx=max(mx,(b/it)*it); } } return mx; } ll func(ll a,ll b) { ll ans=0; while(b>0) { ll g=__gcd(a,b); a/=g; b/=g; ll nb=find_max(a,b); ans+=(b-nb); b=nb; } return ans; } int main() { ll a,b; cin >> a >> b; factor(a); ll t=func(a,b); cout << t << '\n'; return 0; } <file_sep>/Contest/CUET NCPC 2017 Preliminary Contest/a.cpp #include<bits/stdc++.h> #define LL long long #define ff first #define ss second #define pb push_back #define mp make_pair #define mx 2000000009 using namespace std; LL gcd(LL a,LL b) { if (b==0) return a; return gcd(b,a%b); } LL lcm(LL a,LL b) { return (a/gcd(a,b))*b; } int main() { int tc,caseno=0; cin>>tc; while (tc--) { LL n,p; cin>>n>>p; p=100-p; LL lc=1; for (int i=2; i<=n; i++) { lc=lcm(lc,i); } printf("%lld \n",lc); LL nc=0; for (int i=1; i<=n; i++) nc+=lc/i; cout << nc << endl; nc=nc*100*n; lc=lc*p; printf("%lld \n",nc); LL gc=gcd(nc,lc); nc=nc/gc; lc=lc/gc; printf("Case %d: %lld/%lld\n",++caseno,nc,lc); } return 0; } <file_sep>/Codeforces/B numbers/C - Can you answer these queries III.cpp #include<bits/stdc++.h> using namespace std; class node { public: long long int sum=0,mxpre=0,mxsuf=0,mxsb=0; }; node tree[4*5000+7]; vector<int>vt(5000+7); void build(int id,int l,int r) { if(l==r) { tree[id].sum=tree[id].mxpre=tree[id].mxsuf=tree[id].mxsb=vt[l]; return; } int mid=(l+r)/2; build(id*2,l,mid); build(id*2+1,mid+1,r); tree[id].sum=tree[id*2].sum + tree[id*2+1].sum; tree[id].mxpre=max(tree[id*2].mxpre,tree[id*2].sum+tree[id*2+1].mxpre); tree[id].mxsuf=max(tree[id*2+1].mxsuf,tree[id*2+1].sum+tree[id*2].mxsuf); tree[id].mxsb=max(tree[id*2].mxsb,max(tree[id*2+1].mxsb,tree[id*2].mxsuf+tree[id*2+1].mxpre)); } void updt(int id,int l,int r,int pos,int val) { if(pos<l || r<pos) { return ; } if(l==r and l==pos) { tree[id].sum=tree[id].mxpre=tree[id].mxsuf=tree[id].mxsb=val; return ; } int mid=(l+r)/2; updt(id*2,l,mid,pos,val); updt(id*2+1,mid+1,r,pos,val); tree[id].sum=tree[id*2].sum+tree[id*2+1].sum; tree[id].mxpre=max(tree[id*2].mxpre,tree[id*2].sum+tree[id*2+1].mxpre); tree[id].mxsuf=max(tree[id*2+1].mxsuf,tree[id*2+1].sum+tree[id*2].mxsuf); tree[id].mxsb=max(tree[id*2].mxsb,max(tree[id*2+1].mxsb,tree[id*2].mxsuf+tree[id*2+1].mxpre)); } node query(int id,int l,int r,int ql,int qr) { if(l>qr || r<ql) { node a; a.sum=a.mxpre=a.mxsuf=a.mxsb=INT_MIN; return a; } if(l>=ql && r<=qr) { return tree[id]; } int mid=(l+r)/2; node left,right,ans; left=query(id*2,l,mid,ql,qr); right=query(id*2+1,mid+1,r,ql,qr); ans.sum=left.sum+right.sum; ans.mxpre=max(left.mxpre,left.sum+right.mxpre); ans.mxsuf=max(right.mxsuf,right.sum+left.mxsuf); ans.mxsb=max(left.mxsb,max(right.mxsb,left.mxsuf+right.mxpre)); return ans; } int main() { ios_base::sync_with_stdio(0); int n; cin >> n; for(int i=1;i<=n;i++) cin >> vt[i]; build(1,1,n); int m; cin >> m; while(m--) { int t,ql,qr; cin >> t >> ql >> qr; if(t==0) { updt(1,1,n,ql,qr); } else { cout << query(1,1,n,ql,qr).mxsb << endl; } } return 0; } <file_sep>/Marathon/Suffix Array/C - Distinct Substrings.cpp #include <cstdio> #include <sstream> #include <cstdlib> #include <cctype> #include <cmath> #include <algorithm> #include <set> #include <queue> #include <stack> #include <list> #include <iostream> #include <fstream> #include <numeric> #include <string> #include <vector> #include <cstring> #include <map> #include <iterator> #include <stdio.h> /* printf */ #include <math.h> /* log2 */ #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 struct entry{ int nr[3],p; }; bool cmp(const entry &a,const entry &b) { return ( a.nr[0] == b.nr[0] ) ? (a.nr[1]<b.nr[1] ? 1 : 0) : (a.nr[0]<b.nr[0] ? 1 : 0); } int lcp[maxn]; string str; inline void SAp() { cout << "celeron " << str << endl; cout << "yeah " << endl; int n = str.size(); int P[20][maxn]; for(int i=0;i<n;i++) { P[0][i] = str[i] - 'A'; } int stp=1; entry L[maxn]; cout << "fine " << endl; for(int cnt=1; cnt<n; stp++,cnt<<=1) { for(int i=0;i<n;i++) { L[i].nr[0] = P[stp-1][i]; L[i].nr[1] = i+cnt<n ? P[stp-1][i+cnt] : -1; L[i].p = i; } sort(L,L+n,cmp); for(int i=0;i<n;i++) { P[stp][L[i].p] = i>0 && L[i].nr[0] == L[i-1].nr[0] && L[i].nr[1] == L[i-1].nr[1] ? P[stp][L[i-1].p] : i; } } for(int i=0;i<n-1;i++) { int x = L[i].p; int y = L[i+1].p; lcp[i] = 0; cout << x << " " << y ; for(int k=stp-1;k>=0;k--) { if(P[k][x] == P[k][y]) { lcp[i]+=(1<<k); x+=(1<<k); y+=(1<<k); } } cout << " --> " << lcp[i] << endl; } } int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; while(tc--) { cout << "its ok" << endl; cin >> str; cout << str << " after" << endl; cout << "calling" << endl; SAp(); } return 0; } /* */ <file_sep>/Codeforces/Contests/Codeforces Round #427 (Div. 2)/D. Palindromic characteristics.cpp #include<bits/stdc++.h> using namespace std; int ans[5050]; int dp[5050][5050]; string str; int main() { cin >> str; int n=str.size(); for(int len=1; len<=n; len++) { for(int l=0; l+len-1<n; l++) { int r=l+len-1; if(len==1) { dp[l][r]=1; } else if(len==2 and str[l]==str[r]) { dp[l][r]=2; } else if(str[l]!=str[r] or dp[l+1][r-1]==0) { continue; } dp[l][r]=1; long long int mid=(l+r)/2; if(len%2==1) { dp[l][r]=1+dp[l][mid-1]; } else { dp[l][r]=1+dp[l][mid]; } } } for(int len=1; len<=n; len++) { for(int l=0; l+len-1<n; l++) { int r=l+len-1; ans[dp[l][r]]++; } } // for(int i=0; i<n; i++) // cout << ans[i+1] << " "; for(int i=n; i>=0; i--) { ans[i]+=ans[i+1]; } for(int i=0; i<n; i++) cout << ans[i+1] << " "; return 0; } <file_sep>/LightOJ/1159 - Batman.cpp #include<bits/stdc++.h> using namespace std; string a,b,c; int dp[57][57][57]; int rec(int i,int j,int k) { // cout << "call ing " << endl; if(i==0 || j==0 || k==0) return 0; int& ret=dp[i][j][k]; if(ret!=-1) return ret; if(a[i-1]==b[j-1] and a[i-1]==c[k-1]) { // cout << "###" << endl; // cout << a[i] << endl; ret=1+rec(i-1,j-1,k-1); } else { ret=0; ret=max(ret,rec(i-1,j,k)); ret=max(ret,rec(i,j-1,k)); ret=max(ret,rec(i,j,k-1)); ret=max(ret,rec(i-1,j-1,k)); ret=max(ret,rec(i,j-1,k-1)); ret=max(ret,rec(i-1,j,k-1)); } return ret; } int main() { int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { cin >> a >> b >> c; memset(dp,-1,sizeof dp); int t=rec(a.size(),b.size(),c.size()); cout << "Case " << qq << ": " << t << '\n'; } return 0; } <file_sep>/Marathon/Sack (dsu on tree)/E - Blood Cousin.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 #define level 20 vector<int>gr[maxn]; vector< pair<int,int> >query[maxn]; int st[maxn],ft[maxn],sz[maxn],depth[maxn],ver[maxn],par[maxn][level+7],cnt[maxn],ans[maxn]; int n,timer=0; void getsz(int u,int p) { sz[u]=1; st[u]=timer; ver[timer]=u; par[u][0]=p; timer++; for(int v: gr[u]) { if(v!=p) { depth[v]=depth[u]+1; getsz(v,u); sz[u]+=sz[v]; } } ft[u]=timer; } void preprocess() { for(int j=1;j<level;j++) { for(int node=1;node<=n;node++) { if(par[node][j-1]!=-1) { par[node][j]=par[par[node][j-1]][j-1]; } } } } int jump(int u,int k) { for(int j=level-1;j>=0;j--) { if((k>>j)&1) { u=par[u][j]; } } int t=par[u][0]; if(t) return t; return -1; } void dfs(int u,int p,int keep) { int mx=-1,bigchild=-1; for(int v: gr[u]) { if(v!=p and sz[v]>mx) { mx=sz[v]; bigchild=v; } } for(int v:gr[u]) { if(v!=p and v!=bigchild) { dfs(v,u,0); } } if(bigchild!=-1) { dfs(bigchild,u,1); } for(int v : gr[u]) { if(v!=p and v!=bigchild) { for(int p=st[v];p<ft[v];p++) { cnt[depth[ver[p]]]++; } } } cnt[depth[u]]++; for(auto q:query[u]) { ans[q.second]=cnt[q.first+depth[u]]-1; } if(keep==0) { for(int p=st[u];p<ft[u];p++) { cnt[depth[ver[p]]]--; } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; for(int i=1;i<=n;i++) { int p; cin >> p; gr[p].push_back(i); gr[i].push_back(p); } memset(par,-1,sizeof par); getsz(0,-1); preprocess(); /*cout << jump(2,0) << endl;*/ int q; cin >> q; for(int i=0;i<q;i++) { int v,h; cin >> v >>h; int t=jump(v,h-1); if(t==-1) ans[i]=0; else { query[t].push_back({h,i}); } } /* cout << "####" << endl;*/ dfs(0,-1,1); for(int i=0;i<q;i++) cout << ans[i] << " "; return 0; }<file_sep>/Marathon/CodeChef DP/f.cpp /* author : <NAME> CSE'15 SUST */ #include<bits/stdc++.h> #define pii pair<int,int> #define tii pair<int,pair<int,int> > #define mkp make_pair #define fs first #define sc second #define pb push_back #define ppb pop_back() #define pcase(x) printf("Case %d: ",x) #define hi cout<<"hi"<<endl; #define mod 1000000007 #define inf 1000000007 #define pi acos(-1.0) #define mem(arr,x) memset((arr), (x), sizeof((arr))); #define FOR(i,x) for(int i=0;i<(x); i++) #define FOR1(i,x) for(int i = 1; i<=(x) ; i++) #define jora(a,b) make_pair(a,b) #define tora(a,b,c) jora(a,jora(b,c)) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define N 100005 #define level 26 // #define noya vector< vector<int> >(6,vector<int>(6,0)) // #define mat vector<vector<int> > // #define m 6 using namespace std; typedef long long int lint; typedef double dbl; int main() { int test,case_no=1; lint p,q,y; cin>>p>>q>>y; // cout<<p<<q<<y<<endl; cout<<((5*p+2*q)*y*52)<<endl; return 0; } <file_sep>/LightOJ/1025 - The Specials Menu.cpp #include<bits/stdc++.h> using namespace std; string str; long long int dp[70][70]; long long int rec(int i,int j) { if(i>j || j<i ) return 0; long long int& ret=dp[i][j]; if(ret!=-1) return ret; if(str[i]==str[j]) { ret=1+ rec(i+1,j-1) + rec(i+1,j) + rec(i,j-1) - rec(i+1,j-1); } else { ret=rec(i+1,j) + rec(i,j-1) - rec(i+1,j-1); } return ret; } int main() { int tc; cin >> tc; for(int qq=1; qq<=tc; qq++) { cin >>str; memset(dp,-1,sizeof dp); cout << "Case " << qq << ": " << rec(0,str.size()-1) << '\n'; } return 0; } <file_sep>/Marathon/Mathematics/M - Race UVA - 12034.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int int n,mod=10056; ll table[1007][1007]; void nCr() { for(int i=0;i<1007;i++) { table[i][0],table[i][i]=1; table[i][1]=i; for(int j=2;j<i;j++) { table[i][j]=(table[i-1][j]+table[i-1][j-1])%mod; } } } ll dp[1007]; ll rec(int rem) { if(rem==0) return 1; if(rem<0 ) return 0; ll& ret=dp[rem]; if(ret!=-1) return ret; ret=0; for(int i=1;i<=n;i++) { ret+=( table[rem][i]*rec(rem-i) ) %mod; ret%=mod; } return ret; } int main() { nCr(); int tc; scanf("%d",&tc); memset(dp,-1,sizeof dp); for(int qq=1;qq<=tc;qq++) { scanf("%d",&n); int ret=rec(n)%mod; printf("Case %d: %d\n",qq,ret); } return 0; } <file_sep>/csacademy/Round #65 (Div. 2 only)/Crossing Tree.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100000 vector<int>gr[maxn],node; int n; //int vist[maxn],cnt=0,n; //void dfs(int u,int p) //{ // vist[u] = 1; // cnt++; // if(cnt <= n) // { // node.push_back(u); // } // for(int v : gr[u]) // { // if(v!=p) // { // dfs(v,u); // if(cnt < n) // { // node.push_back(u); // } // } // } //} void DFS(int s) { // Initially mark all verices as not visited vector<bool> visited(maxn+7); // Create a stack for DFS stack<int> stack; // Push the current source node. stack.push(s); while (!stack.empty()) { // Pop a vertex from stack and print it s = stack.top(); stack.pop(); // Stack may contain same vertex twice. So // we need to print the popped item only // if it is not visited. if (!visited[s]) { // cout << s << " "; visited[s] = true; } // Get all adjacent vertices of the popped vertex s // If a adjacent has not been visited, then puah it // to the stack. for (auto i = gr[s].begin(); i != gr[s].end(); ++i) if (!visited[*i]) { if(!node.empty() and node.back()!=s) node.push_back(s); node.push_back(*i); stack.push(*i); } } } int main() { sf1(n); for(int i=0; i<n-1; i++) { int u,v; sf2(u,v); gr[u].push_back(v); gr[v].push_back(u); } int mn=maxn+7,id=-1; for(int i=1; i<=n; i++) { if(gr[i].size()<mn) { mn=gr[i].size(); id=i; } } // dfs(id,-1); node.push_back(id); DFS(id); pf1(node.size()-1); for(int x : node) { pf("%d ",x); } return 0; } /* */ <file_sep>/Codeforces/Contests/Educational Codeforces Round 26/C. Two Seals.cpp #include<bits/stdc++.h> using namespace std; int func(int a,int b,int x1,int y1,int x2,int y2) { if(x1>a) return 0; if(y1>b) return 0; int aa1=a-x1; int bb1=b-y1; if(aa1>=x2 and b>=y2) return x1*y1+x2*y2; if(a>=x2 and bb1>=y2) return x1*y1+x2*y2; return 0; } int main() { int n,a,b; cin >> n >> a >> b; vector< pair<int,int> > vt; for(int i=0;i<n;i++) { int p,q; cin >> p >> q; vt.push_back({p,q}); } int mx=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(i==j) continue; mx=max(mx,func(a,b,vt[i].first,vt[i].second,vt[j].first,vt[j].second) ); mx=max(mx,func(a,b,vt[i].second,vt[i].first,vt[j].first,vt[j].second) ); mx=max(mx,func(a,b,vt[i].second,vt[i].first,vt[j].second,vt[j].first) ); mx=max(mx,func(a,b,vt[i].first,vt[i].second,vt[j].second,vt[j].first) ); // cout << func(a,b,vt[i],vt[j]) << endl; } } cout << mx ; return 0; } <file_sep>/Marathon/Weekly Marathon #5 by DJ/C - Jzzhu and Chocolat.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll n,m,k; cin >> n >> m >> k; if(n<m) swap(n,m); ll ans=0; if(k>n+m-2) { cout << -1 ; return 0; } else if(k<n-1) { ans=max(m*(n/(k+1)),n*(m/(k+1)) ); } else { ans=max(m/(k-n+2),n/(k-m+2) ); } cout << ans << endl; return 0; }<file_sep>/Codeforces/B numbers/C. Petya and Catacombs.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; int ghor[n+7],tim[n+7]; ghor[0]=1; tim[1]=0; set<int>st; st.insert(1); for(int i=1;i<=n;i++) { int x; cin >> x; if(tim[ghor[x]]==x) { ghor[x]=i; tim[i]=ghor[x]; } else { st.insert(st.size()+1); ghor[x]=i; tim[i]=st.size(); } } cout << st.size() << endl; return 0; } <file_sep>/Contest/Individual Practice Contest 1/A - Extreme GCD.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 #define MAX 10050 ///joto porjonto sieve korte cai #define LMT 105 /// sqrt(MAX) #define LEN 1233 ///appx number of primes #define RNG 100032 ///range for segmentflaged sieve #define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31))) #define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31))) unsigned primeflag[MAX/64+7], segmentflag[RNG/64+7], primes[LEN+7]; /* Generates all the necessary prime numbers and marks them in primeflag[]*/ void sieve() { unsigned long long int i, j, k; for(i=3; i<LMT; i+=2) if(!chkC(primeflag, i)) for(j=i*i, k=i<<1; j<MAX; j+=k) setC(primeflag, j); j=0; primes[j] primes[j++]=2; for(i=3; i<MAX; i+=2) if(!chkC(primeflag, i)) primes[j++] = i; } ll ncr[10007][10]; void bio() { for(int i=1;i<10007;i++) { ncr[i][0]=ncr[i][i]=1; ncr[i][1]=i; for(int j=2;j<10;j++) { ncr[i][j] = ( ncr[i-1][j] + ncr[i-1][j-1] )%mod; } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); sieve(); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n; cin >> n; int ara[n+7]; int mx=0; for(int i=0;i<n;i++) { cin >> ara[i]; mx=max(mx,ara[i]); } int sq= sqrt(mx); sq+=5; ll ans=ncr[n][4]; for(int i=0;i<1233 && primes[i]<=sq;i++) { int cnt=0; for(int j=0;j<n;j++) { if(ara[j]%primes[i]==0) { ara[j]=-1; cnt++; } } } } return 0; } <file_sep>/Marathon/Weekly Marathon #7 by DJ/O - Powerful array.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 200000+7 #define B 450 int ara[maxn],cnt[2000000]; long long int ans=0; struct node { int l,r,id; }Q[maxn]; bool cmp(node p,node q) { int bp=p.l/B,bq=q.l/B; if(bp!=bq) { return bp<bq; } if(bp&1) { return p.r<q.r; } else { return p.r>q.r; } } inline void add(int ps) { ans-=(1LL*cnt[ara[ps]]*cnt[ara[ps]]*ara[ps]); cnt[ara[ps]]++; ans+=(1LL*cnt[ara[ps]]*cnt[ara[ps]]*ara[ps]); } inline void rmv(int ps) { ans-=(1LL*cnt[ara[ps]]*cnt[ara[ps]]*ara[ps]); cnt[ara[ps]]--; ans+=(1LL*cnt[ara[ps]]*cnt[ara[ps]]*ara[ps]); } int main() { /*ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);*/ int n,t; scanf("%d %d",&n,&t); for(int i=0;i<n;i++) { scanf("%lld",&ara[i]); /*cin >> ara[i];*/ } for(int i=0;i<t;i++) { scanf("%d %d",&Q[i].l,&Q[i].r); /*cin >> Q[i].l >> Q[i].r ;*/ Q[i].l--,Q[i].r--; Q[i].id=i; } sort(Q,Q+t,cmp); int curl=0,curr=0; ll ansarray[t+7]; /*cout << "YES" << endl;*/ for(int i=0;i<t;i++) { int L=Q[i].l,R=Q[i].r; while(curl<L) { rmv(curl); curl++; } while(curl>L) { add(curl-1); curl--; } while(curr<=R) { add(curr); curr++; } while(curr>R+1) { rmv(curr-1); curr--; } /*cout << curl << " " << curr << endl;*/ ansarray[Q[i].id]=ans; } for(int i=0;i<t;i++) { printf("%lld\n",ansarray[i]); /*cout << ansarray[i] << endl;*/ } return 0; }<file_sep>/Marathon/Weekly Marathon #3 by DJ/c.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { /* freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); */ // const clock_t begin_time = clock(); int n; cin >> n; vector<int>vt; for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back(t); } sort(vt.begin(),vt.end()); vector<ll>sums; sums.push_back(vt[0]); for(int i=1;i<n;i++) { sums.push_back(sums.back()+vt[i]); } ll ans=sums.back(); for(int i=0;i<n-1;i++) { ans+=vt[i]; ans+=(sums.back()-sums[i]); } cout << ans <<endl; // cout << endl << float( clock () - begin_time ) / CLOCKS_PER_SEC; return 0; } /* */ <file_sep>/Contest/ACM ICPC Dhaka Regional 2017 Online Preliminary Round Hosted by University of Asia Pacific/b.cpp /* author : <NAME> CSE'15 SUST */ #include<bits/stdc++.h> #define pii pair<int,int> #define tii pair<int,pair<int,int> > #define mkp make_pair #define fs first #define sc second #define pb push_back #define ppb pop_back() #define pcase(x) printf("Case %d: ",x) #define hi cout<<"hi"<<endl; #define mod 1000000007 #define inf 1000000007 #define pi acos(-1.0) #define mem(arr,x) memset((arr), (x), sizeof((arr))); #define FOR(i,x) for(int i=0;i<(x); i++) #define FOR1(i,x) for(int i = 1; i<=(x) ; i++) #define jora(a,b) make_pair(a,b) #define tora(a,b,c) jora(a,jora(b,c)) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define N 100005 #define level 26 // #define noya vector< vector<int> >(6,vector<int>(6,0)) // #define mat vector<vector<int> > // #define m 6 using namespace std; typedef long long int lint; typedef double dbl; lint fac[200005]; lint inv[200005]; inline lint bigmod(lint a,lint b,lint m) { /// a^b%m lint ans=1; while(b>0) { if(b&1ll) ans=(a*ans)%m; b>>=1; a=(a*a)%m; } return ans; } inline void pre() { fac[0]=1; for(lint i=1;i<=200003;i++) fac[i]=(fac[i-1]*i)%mod; for(lint i=0;i<=200003;i++) inv[i]=bigmod(fac[i],mod-2,mod); return ; } inline lint ncr(int n,int k) { if(n==0 || k==0) return 1ll; return (((fac[n+k-1]*inv[k])%mod)*inv[n-1])%mod; } int main() { int test,case_no=1; sf1(test); pre(); while(test--) { int n,x; sf2(n,x); int mark[n+4]; mem(mark,-1); for(int i=0;i<x;i++) { int x,y; sf2(x,y); mark[x]=y; } lint ans=1; int last=1; int cnt=0; for(int i=0;i<n;i++) { if(mark[i]!=-1) { // cout<<mark[i]-last+1<<" "<<cnt<<endl; ans=(ans*ncr(mark[i]-last+1,cnt))%mod; cnt=0; last=mark[i]; } else cnt++; } ans=(ans*ncr(n-last+1,cnt))%mod; pcase(case_no++); printf("%lld\n",ans); } return 0; } <file_sep>/LightOJ/1064 - Throwing Dice.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int n,x; unsigned long long int dp[27][157]; unsigned long long int rec(int ps,int sum) { if(ps>=n) { if(sum>=x) return 1; return 0; } unsigned long long int &ret=dp[ps][sum]; if(ret!=-1) return ret; ret=0ULL; for(int i=1;i<=6;i++) { ret+=rec(ps+1,sum+i); } return ret; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { cin >> n >> x; memset(dp,-1,sizeof dp); unsigned long long int a=rec(0,0), b=1; for(unsigned long long int i=1;i<=n;i++) { b*=6; } unsigned long long int c=__gcd(a,b); a/=c; b/=c; if(a%b==0) { cout << "Case " << qq << ": " << a/b << endl; } else { cout << "Case " << qq << ": " << a << "/" << b << endl; } } return 0; }<file_sep>/Codeforces/Contests/Codeforces Round #305 (Div. 2)/B. Mike and Fun.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int ara[maxn] inline void calc(int r) { } int main() { int n,m,q; sf("%d%d%d",&n,&m,&q); int ara[n+7][m+7]; for(int i=1 ;i<=n ;i++ ) { for(int j=1 ;j<=m ;j++ ) { sf("%d",&ara[i][j]); } } while(q--) { int i,j; sf("%d%d",&i,&j); } return 0; } /* */ <file_sep>/LightOJ/team/g.cpp /*input 6 1 2 3 4 5 6 6 5 4 3 2 1 */ /* author : <NAME> CSE'15 SUST */ #include <iostream> #include <string> #include <vector> #include <algorithm> #include <sstream> #include <queue> #include <deque> #include <bitset> #include <iterator> #include <list> #include <stack> #include <map> #include <set> #include <functional> #include <numeric> #include <utility> #include <limits> #include <time.h> #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <iomanip> #define pii pair<int,int> #define tii pair<int,pair<int,int> > #define mkp make_pair #define fs first #define sc second #define pb push_back #define ppb pop_back() #define pcase(x) printf("Case %d: ",x) #define hi cout<<"hi"<<endl; #define mod 1000000007 #define inf 1000000007 // #define n 10000007 #define pi acos(-1.0) #define mem(arr,x) memset((arr), (x), sizeof((arr))); #define FOR(i,x) for(int i=0;i<(x); i++) #define FOR1(i,x) for(int i = 1; i<=(x) ; i++) #define jora(a,b) make_pair(a,b) #define tora(a,b,c) jora(a,jora(b,c)) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define eps 1e-5 // #define noya vector< vector<int> >(6,vector<int>(6,0)) // #define mat vector<vector<int> > // #define m 6 using namespace std; typedef long long int lint; inline double hudai(lint n) { int f=0; for(int i=0;i<5;i++) { if((n+5)%10>=5) f=1; else f=0; n/=10; } if((n+f)%10>=5) n=(n/10)+1; else n=n/10; return n/100.0; } int main() { int test,case_no=1; sf1(test); while(test--) { lint n; lint u=0ll,v=0ll; scanf("%lld",&n); for(lint i=0;i<n;i++) { lint x,y; scanf("%lld %lld",&x,&y); u+=(x*100000000); v+=(y*100000000); } //cout<<" ghg "<<fround(u)<,endl; //double nn=n*1.0; //cout<<u<<" "<<v<<endl; double uu=hudai(u/n); double vv=hudai(v/n); printf("%.2lf %.2lf\n",uu,vv); } return 0; }<file_sep>/USACO/Section 1.4/Mother's Milk.cpp /* ID:shishir10 LANG:C++11 TASK:milk3 */ #include<bits/stdc++.h> using namespace std; #define ll long long int int a,b,c; vector<int>vt; int vis[30][30][30]; void rec(int ta,int tb,int tc) { /*cout <<ta << " " << tb << " " << tc << endl;*/ if(vis[ta][tb][tc]==0) { vis[ta][tb][tc]=1; // a->b if(ta>b-tb) rec(ta-b+tb,b,tc); else rec(0,tb+ta,tc); // b->a if(tb>a-ta) rec(a,tb-a+ta,tc); else rec(ta+tb,0,tc); // a->c if(ta>c-tc) rec(ta-c+tc,tb,c); else rec(0,tb,tc+ta); //c->a if(tc>a-ta) rec(a,tb,tc-a+ta); else rec(ta+tc,tb,0); //b->c if(tb>c-tc) rec(ta,tb-c+tc,c); else rec(ta,0,tc+tb); //c->b if(tc>b-tb) rec(ta,b,tc-b+tb); else rec(ta,tb+tc,0); } } int main() { freopen("milk3.in","r",stdin); freopen("milk3.out","w",stdout); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> a >> b >> c; rec(0,0,c); for(int i=0;i<=b;i++) { for(int j=0;j<=c;j++) { if(vis[0][i][j]) { vt.push_back(j); } } } sort(vt.begin(),vt.end()); if(!vt.empty()) cout << vt[0]; for(int i=1;i<vt.size();i++) { cout << " " << vt[i] ; } cout << endl; return 0; }<file_sep>/csacademy/Round #65 (Div. 2 only)/Count 4-cycles.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100000 int main() { int n; sf1(n); map< pair<int,int> , bool > mp; for(int i=0; i<n-1; i++) { int u,v; sf2(u,v); mp[ {u,v}] = 1; } int cnt =0 ; for(int i=0; i<n-1; i++) { int u,v; sf2(u,v); if( mp.find({u,v})!=mp.end() || mp.find({v,u})!=mp.end() ) { cnt++; } } cout << cnt << endl; return 0; } /* */ <file_sep>/LightOJ/1133 - Array Simulation.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; sf("%d",&tc); for(int qq=1;qq<=tc;qq++) { int n,m; sf("%d %d",&n,&m); vector<ll>vt; for(int i=0;i<n;i++) { int t; sf("%d",&t); vt.push_back(t); } // DB; while(m--) { char ch; cin >> ch; if(ch=='S') { int t; sf("%d",&t); for(int i=0;i<n;i++) { vt[i]+=t; } } else if(ch=='M') { int t; sf("%d",&t); for(int i=0;i<n;i++) { vt[i]*=t; } } else if(ch=='D') { int t; sf("%d",&t); for(int i=0;i<n;i++) { vt[i]/=t; } } else if(ch=='R') { reverse(vt.begin(),vt.end()); } else if(ch=='P') { int a,b; sf("%d %d",&a,&b); swap(vt[a],vt[b]); } } pf("Case %d:\n",qq); pf("%lld",vt[0]); for(int i=1 ;i<n ;i++ ) { pf(" %lld",vt[i]); } pf("\n"); } return 0; } /* */ <file_sep>/Novice/Marathon Week - 9 ArticulationBridgeSCC/C - Tourist Guide.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 107 vector<int>gh[maxn]; vector<string>vt; set<int>st; int n,r,num; map<string,int>mp; bool visit[maxn]; int parent[maxn],d[maxn],low[maxn],root,ti; void art(int u) { visit[u]=1; d[u]=low[u]=ti++; int child=0; for(int i=0 ;i<gh[u].size() ;i++ ) { int v=gh[u][i]; if(v==parent[u]) continue; else if(visit[v]) { low[u]=min(low[u],d[v]); } else { parent[v]=u; art(v); child++; low[u]=min(low[u],low[v]); if(d[u]<=low[v] and u!=root) { st.insert(u); } } } if(child>1 && u==root) { st.insert(u); } } void make() { mp.clear(); st.clear(); for(int i=0 ;i<=n ;i++ ) { gh[i].clear(); } string u,v; num=1; for(int i=0 ;i<n ;i++ ) { cin >> u; mp[u]=num++; } sf("%d",&r); for(int i=0 ;i<r ;i++ ) { cin >> u >> v; gh[mp[u]].push_back(mp[v]); gh[mp[v]].push_back(mp[u]); } } int main() { freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); int qq=1; while(sf("%d",&n) && n!=0) { make(); memset(visit,0,sizeof visit); ti=1; for(int i=1 ;i<num ;i++ ) { if(!visit[i]) { // cout << "root are " << i << endl; root=i; art(i); } } map<string,int>::iterator itt; vt.clear(); for(auto it:st ) { for(itt=mp.begin();itt!=mp.end();itt++) { if(itt -> second==it) { vt.push_back(itt->fs); } } } if(qq!=1) pf("\n"); pf("City map #%d: %d camera(s) found\n",qq++,st.size()); sort(vt.begin(),vt.end(),[](string a,string b) { return a<b; } ); for(auto it: vt ) { cout << it << '\n'; } } return 0; } /* */ <file_sep>/Codeforces/B numbers/D - Painful Bases.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 bool check(ll num,int ps) { return (bool)( num&(1<<ps) ); } int sett(ll num,int ps) { return num|=(1<<ps); } ll bse,k,l,s; string str; ll dp[(1<<17)][25]; ll rec(ll mask,ll num) { if(mask>=l) { if(num%k==0) return 1; return 0; } ll &ret=dp[mask][num]; if(ret!=-1) return ret; ret=0; for(int i=0 ;i<s ;i++ ) { if(check(mask,i)==0) { int t=0; if(str[i]>='0' && str[i]<='9') t=str[i]-'0'; else t=str[i]-'A'+10; ret+=rec(sett(mask,i),(num*bse+t)%k); } } return ret; } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { sf("%lld %lld",&bse,&k); cin >> str; s=str.size(); l=(1<<s)-1; memset(dp,-1,sizeof dp); ll ans=rec(0,0); pf("Case %d: %lld\n",qq,ans); } return 0; } /* */ <file_sep>/LightOJ/1036 - A Refining Company.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 int m,n; int rad[507][507], ura[507][507]; int dp[507][507]; int rec(int r,int c) { if(r<1 || c<1) { return 0; } int &ret=dp[r][c]; if(ret != -1) { return ret; } ret=0; ret = max( ura[r][c]+rec(r-1,c), rad[r][c]+rec(r,c-1) ); return ret; } int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); int tc; sf1(tc); for(int qq=1; qq<=tc; qq++) { sf2(m,n); memset(rad,0,sizeof rad); memset(ura,0,sizeof ura); for(int i=1; i<=m; i++) { for(int j=1; j<=n; j++) { int x; sf1(x); ura[i][j] = ura[i][j-1] + x; } } for(int i=1; i<=m; i++) { for(int j=1; j<=n; j++) { int x; sf1(x); rad[i][j] = rad[i-1][j] + x; } } memset(dp,-1,sizeof dp); int t = rec(m,n); pcase(qq); pf1(t); } return 0; } /* */ <file_sep>/Codechef/Contests/August Long Challenge 2017/Greedy Candidates.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n,m; cin >> n >> m; int minsalary[n+7]; for(int i=0;i<n;i++) { cin >> minsalary[i]; } vector< pair<int,int> > vt,temp; for(int i=0;i<m;i++) { int salary,vacant; cin >> salary >> vacant; vt.push_back({salary,vacant}); } temp=vt; vector<string>qual; for(int i=0;i<n;i++) { string str; cin >> str; qual.push_back(str); } int cnt=0; ll sum=0; for(int i=0;i<n;i++) { int mx=minsalary[i]; int id=-1; for(int j=0;j<m;j++) { if(qual[i][j]=='1' && temp[j].second>0 && temp[j].first>=minsalary[i]) { if(temp[j].first>=mx) { mx=temp[j].first; id=j; } } } if(id!=-1) { temp[id].second--; sum+=mx; /*cout << sum << " sum print " << cnt << endl;*/ cnt++; } } int tt=0; for(int i=0;i<m;i++) { if(vt[i].second==temp[i].second) { tt++; } } cout << cnt << " " << sum << " " << tt << endl; } return 0; }<file_sep>/Codeforces/D numbers/E. Sum of Remainders.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define mod 1000000007 int main() { ll m,n; cin >> n >> m; ll ans=( (m%mod)*(n%mod) )%mod; ll k=min(n,m); for(ll i=1;i*i<=k;i++) { ans-=(i*(n/i)); while(ans<0) ans+=mod; } ll i=sqrt(k)-2; while(i*i<k)i++; if(k%i==0) i=sqrt(n)-1; else i=sqrt(n); for(;i>=1;i--) { ll u=min(n/i,k); ll l=n/(i+1); l++; ll t=u*(u+1)/2 - l*(l+1)/2; ans-=(t*i); while(ans<0) ans+=mod; } cout << ans%mod << endl; return 0; } <file_sep>/LightOJ/1095 - Arrange the Numbers.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 #define mod 1000000007 ll fac[1007]; ll ncr[1007][1007]; void bio() { for(int i=1;i<1007;i++) { ncr[i][0]=ncr[i][i]=1; ncr[i][1]=i; for(int j=2;j<i;j++) { ncr[i][j] = ( ncr[i-1][j] + ncr[i-1][j-1] )%mod; } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); bio(); fac[0]=1; fac[1]=1; for(ll i=2;i<1007;i++) { fac[i] = ( fac[i-1] * i ) % mod; } int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n,m,k; cin >> n >> m >> k; ll ans=ncr[m][k]; ll x=n-k, y=m-k; ll temp=fac[x]; // cout << "temp " << temp << " x " << x << endl; for(int i=1;i<=y;i++) { if(i&1) temp-=( ncr[y][i] * fac[x-i] ) %mod; else temp+= ( ncr[y][i] * fac[x-i] ) %mod; temp=(temp+mod)%mod; } cout << "Case " << qq << ": " << (ans*temp)%mod << endl; } return 0; } <file_sep>/UVALive/At most twice UVALive - 7203.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int l; char str[25],res[25]; int ara[25]; bool check(int ps,int val) { memset(ara,0,sizeof ara); cout << ps << ' ' << val << endl; for(int i=0 ; i<=ps ; i++ ) { ara[res[i]]++; if(ara[res[i]]>2) return false; } for(int i=0 ;i<=ps ;i++ ) { cout << ara[i] ; } cout << endl; if(ara[val]>=2) return false; return 1; } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); ll num; while(sf("%lld",&num)==1) { memset(ara,0,sizeof ara); int flag=0,it; l=sprintf(str,"%lld",num); for(int i=0 ; i<l ; i++ ) { ara[str[i]-'0']++; if(ara[str[i]-'0']>2) { flag=1; it=i; break; } res[i]=str[i]-'0'; } if(!flag) cout << num << endl; else { for(int i=it ; i>=0 ; i-- ) { int a=str[i]-'0'; for(int j=a-1 ; j>=0 ; j-- ) { if(check(i,j)) { res[i]=j; it=i; flag=0; break; } } if(!flag) break; } cout << it+1 << endl; for(int j=it+1; j<l ; j++ ) { for(int i=9 ; i>=0 ; i-- ) { if(check(j,i)) { res[j]=i; break; } else { for(int i=0 ;i<l ;i++ ) { pf("%d",res[i]) ; } cout << endl; } } } cout << " result " << endl; for(int i=0 ;i<l ;i++ ) { pf("%d",res[i]); } cout << endl; } } return 0; } /* 2210102960 */ <file_sep>/Codeforces/B numbers/linear.cpp #include<bits/stdc++.h> using namespace std; long long int egcd(long long int a,long long int b,long long int& x,long long int& y) { if(b==0) { x=1; y=0; return a; } long long int x1,y1; long long int g=egcd(b,a%b,x1,y1); x=y1; y=x1-(a/b)*y1; return g; } long long int gcd(long long int a,long long int b) { if(b==0) return a; return gcd(b,a%b); } /// returning number of solutions /// form of the equation ax + by = c long long int linear_diaphontic(long long int a,long long int b,long long int c,long long int xmin, long long int xmax,long long int ymin,long long int ymax) { if(a==0 and b==0 and c==0) { return -1; } else if(a==0 and b==0 and c!=0) { return 0; } else if(a==0 and (b==c)) { return 1; } else if(a==0 and (b!=c)) { return 0; } else if(b==0 and (a==c)) { return 1; } else if(b==0 and (a!=c)) { return 0; } long long int xg,yg; /// egcd theke pawya equation form :: a xg + b yg = g; long long int g=egcd(abs(a),abs(b),xg,yg); cout << g << " " << xg << " " << yg << endl; if(c%g) { return 0; } else { long long int x0=xg*(c/g); long long int y0=yg*(c/g); if(a<0) x0*=(-1); if(b<0) y0*=(-1); cout << x0 << " " << y0 << endl; cout << g << endl; long long int p,q,r,s; if(x0<0) { x0*=(-1); xmin+=x0; xmax+=x0; p=xmin/abs(b/g); q=xmax/abs(b/g); if(xmin-(xmin/abs(b/g))*abs(b/g))p+=1; } else { xmin-=x0; xmax-=x0; p=xmin/abs(b/g); q=xmax/abs(b/g); if(xmin-(xmin/abs(b/g))*abs(b/g))p+=1; } // cout << p << " " << q << endl; if(y0<0) { y0*=(-1); ymin+=y0; ymax+=y0; r=ymin/abs(a/g); s=ymax/abs(a/g); if(ymin-(ymin/abs(a/g))*abs(a/g))r+=1; } else { ymin-=y0; ymax-=y0; r=ceil(ymin/abs(a/g)); s=ymax/abs(a/g); if(ymin-(ymin/abs(a/g))*abs(a/g))r+=1; } // cout << r << " " << s << endl; r*=(-1); s*=(-1); swap(r,s); long long int u=max(p,r); long long int v=min(q,s); return abs(u-v)+1; } } int main() { ios_base::sync_with_stdio(0); long long int tc; cin >> tc; for(int qq=1; qq<=tc; qq++) { long long int a,b,c,xmin,xmax,ymin,ymax; cin >> a >> b >> c >> xmin >> xmax >> ymin >> ymax ; long long int t=linear_diaphontic(a,b,-c,xmin,xmax,ymin,ymax); // cout << "-----> " << t << endl; cout << "Case " << qq << ": " << t << endl; } return 0; } /* 5 -2 -2 -48 -12 10 -29 -27 */ <file_sep>/Codeforces/Contests/Codeforces Round #299 (Div. 2)/A. Tavas and Nafas.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 void print(int n) { if(n==1) { cout << "one"; } else if(n==2) { cout << "two"; } else if(n==3) { cout << "three"; } else if(n==4) { cout << "four"; } else if(n==5) { cout << "five"; } else if(n==6) { cout << "six"; } else if(n==7) { cout << "seven"; } else if (n==8) { cout << "eight"; } else if(n==9) { cout << "nine"; } } void print1(int n) { if(n==2) cout << "twenty"; else if(n==3) cout << "thirty"; else if(n==4) cout << "forty"; else if(n==5) cout << "fifty"; else if(n==6) cout << "sixty"; else if(n==7) cout << "seventy"; else if(n==8) cout << "eighty"; else if(n==9) cout << "ninety"; } int main() { int n; cin >> n; if(n==0) cout << "zero"; else if(n>=1 and n<=9) print(n); else if(n==10) cout << "ten"; else if(n==11) cout << "eleven"; else if(n==12) cout << "twelve"; else if(n==13) cout << "thirteen"; else if(n==14) cout << "fourteen"; else if(n==15) cout << "fifteen"; else if(n==16) cout << "sixteen"; else if(n==17) cout << "seventeen"; else if(n==18) cout << "eighteen"; else if(n==19) cout << "nineteen"; else if(n==20) cout << "twenty"; else if(n==30) cout << "thirty"; else if(n==40) cout << "forty"; else if(n==50) cout << "fifty"; else if(n==60) cout << "sixty"; else if(n==70) cout << "seventy"; else if(n==80) cout << "eighty"; else if(n==90) cout << "ninety"; else { int a=n%10; n/=10; print1(n); cout << "-"; print(a); } // main(); return 0; } /* */ <file_sep>/Contest/Individual Practice Contest 4/G - Ants Colony.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define DB cout<<" **** "<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define level 18 #define maxn 100007 vector<pii>tree[maxn]; int depth[maxn]; int parent[maxn][20]; ll cost[maxn]; int vist[maxn]; void dfs(int u) { for(int i=0; i<tree[u].size(); i++) { int v = tree[u][i].fs; if(vist[v] == -1) { vist[v] = 1; // cout << u << " ---> " << v << endl; parent[v][0] = u; depth[v] = depth[u] + 1; cost[v] = cost[u] + tree[u][i].sc; dfs(v); } } } void pre(int n) { for(int i=1; i<level; i++) { for(int node=0; node<n; node++) { if( parent[node][i-1] != -1) { parent[node][i] = parent[ parent[node][i-1] ] [i-1]; } } } } bool is_par(int u,int v) { if(depth[v] < depth[u]) { swap(u,v); } int diff = depth[v] - depth[u]; for(int i=0; i<level; i++) { if( (diff>>i)&1 ) { v = parent[v][i]; } } if(u==v) { return 1; } return 0; } int lca(int u,int v) { if(depth[v] < depth[u]) { swap(u,v); } int diff = depth[v] - depth[u]; for(int i=0; i<level; i++) { if( (diff>>i)&1 ) { v = parent[v][i]; } } if(u==v) { return u; } for(int i=level-1; i>=0; i--) { if(parent[u][i] != parent[v][i]) { u = parent[u][i]; v = parent[v][i]; } } return parent[u][0]; } int main() { int n; while(sf1(n)) { if(n==0) { return 0; } for(int i=0; i<maxn; i++) { tree[i].clear(); } memset(parent,-1,sizeof parent); memset(depth,0,sizeof depth); memset(cost,0,sizeof cost); for(int i=1; i<=n-1; i++) { int x,w; sf2(x,w); tree[i].push_back(pii(x,w)); tree[x].push_back(pii(i,w)); } memset(vist,-1,sizeof vist); vist[0]=1; cost[0]=0; // depth[0] dfs(0); pre(n); // for(int i=0; i<n; i++) // { // cout <<i << " --> " << cost[i] << endl; // } // cout << "lca " << lca(2,3) << endl; int q,f=0; sf1(q); while(q--) { int u,v; sf2(u,v); int l = lca(u,v); if(f) { pf(" "); } f=1; if(is_par(u,v)) { pf1ll(abs(cost[v]-cost[u])); } else { pf1ll(cost[u]+cost[v]-2*cost[l]); } } pf("\n"); } return 0; } /* 6 0 1000000000 1 1000000000 2 1000000000 3 1000000000 4 1000000000 1 5 0 */ <file_sep>/LightOJ/1032 - Fast Bit Calculations.cpp #include<bits/stdc++.h> using namespace std; string str; int sz; void getbinary(long long int n) { str.clear(); while(n!=0) { str+=((n%2)+'0'); n/=2; } reverse(str.begin(),str.end()); sz=str.size(); } long long int dp[40][3][3][40]; long long int rec(int ps,int flag,int prev,int cnt) { if(ps>=sz) { return cnt; } long long int& ret=dp[ps][flag][prev][cnt]; if(ret!=-1)return dp[ps][flag][prev][cnt]; int d= flag==1 ? str[ps]-'0' : 1; ret=0; for(int i=0;i<=d;i++) { ret+=rec(ps+1,i<d?0:flag,i,(prev==1 && i==1)+cnt); } return ret; } int main() { int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { long long int n; cin >> n; getbinary(n); memset(dp,-1,sizeof dp); long long int t=rec(0,1,0,0); cout << "Case " << qq << ": " << t << '\n'; } return 0; } <file_sep>/LightOJ/1085 - All Possible Increasing Subsequences.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 100007 #define mod 1000000007 struct data { int val=0,ps=0; }; data ara[maxn]; bool cmp(const data a,const data b) { if(a.val!=b.val) { return a.val<b.val; } return a.ps>b.ps; } ll tree[4*maxn]; void update(int id,int l,int r,int ps,int val) { if(l>ps || r<ps) return ; if(l==r) { tree[id]=val; return; } int mid=(l+r)/2; update(id*2,l,mid,ps,val); update(id*2+1,mid+1,r,ps,val); tree[id*2]%=mod; tree[id*2+1]%=mod; tree[id]=tree[id*2]+tree[id*2+1]; tree[id]%=mod; } ll query(int id,int l,int r,int i,int j) { if(l>j || r<i) return 0; if(l>=i && r<=j) { return tree[id]; } int mid=(l+r)/2; int p1=query(id*2,l,mid,i,j); int p2=query(id*2+1,mid+1,r,i,j); p1%=mod; p2%=mod; return p1+p2; } int save[maxn]; int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { int n; sf("%d",&n); for(int i=1 ;i<=n ;i++ ) { sf("%d",&ara[i].val); ara[i].ps=i; } sort(ara+1,ara+n+1,cmp); memset(tree,0,sizeof tree); for(int i=1 ;i<=n ;i++ ) { data temp=ara[i]; ll q=query(1,1,n,1,temp.ps); // cout << temp.val << ' ' << temp.ps << endl; q%=mod; update(1,1,n,temp.ps,q+1); } pf("Case %d: %lld\n",qq,tree[1]%mod); } return 0; } /* 2 5 1 2 1000 1000 1001 */ <file_sep>/LightOJ/1238 - Power Puff Girls.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 char str[25][25]; int n,m; int dis[25][25]; pii des; vector<pii>vt; void Input() { vt.clear(); char ch; sf("%d %d",&n,&m); for(int i=0 ; i<n ; i++ ) { for(int j=0 ; j<m ; j++ ) { while(1) { sf("%c",&ch); if(ch=='a' || ch=='b' || ch=='c') { str[i][j]=ch; vt.push_back({i,j}); break; } else if(ch=='m'|| ch=='#') { str[i][j]='#'; break; } else if(ch=='h') { str[i][j]='.'; des={i,j}; break; } else if(ch=='.') { str[i][j]=ch; break; } } } } } int fx[]={-1,1,0,0}; int fy[]={0,0,-1,1}; int bfs(pii st) { memset(dis,-1,sizeof dis); queue<pii>Q; Q.push(st); dis[st.fs][st.sc]=0; while(!Q.empty()) { pii u=Q.front(); Q.pop(); for(int i=0 ;i<4 ;i++ ) { int tx=u.fs+fx[i],ty=u.sc+fy[i]; if(tx>=0 && tx<n && ty>=0 && ty<m && dis[tx][ty]==-1 && str[tx][ty]!='m'&& str[tx][ty]!='#') { dis[tx][ty]=1+dis[u.fs][u.sc]; if(des.fs==tx && des.sc==ty ) return dis[tx][ty]; Q.push({tx,ty}); } } } } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; sf("%d",&tc); for(int qq=1 ; qq<=tc ; qq++ ) { Input(); int ans=INT_MIN; for(int i=0 ;i<vt.size() ;i++ ) { int d=bfs(vt[i]); ans=max(ans,d); } pf("Case %d: %d\n",qq,ans); } return 0; } /* */ <file_sep>/LightOJ/1276 - Very Lucky Numbers.cpp #include<bits/stdc++.h> using namespace std; vector<long long int>lucky,vlucky; void lucky_gen(long long int num) { if(num>1000000100000LL) { return; } if(num!=0) { lucky.push_back(num); } lucky_gen(num*10+4); lucky_gen(num*10+7); } set<long long int>st; void vlucky_gen(int ps,long long int num) { if(num>1000000100000LL) { return; } if(num<=1000000100000LL and num>1) { st.insert(num); } if(ps>=lucky.size()) { return; } if(num<=1000000100000LL/lucky[ps])vlucky_gen(ps+1,num); if(num<=1000000100000LL/lucky[ps])vlucky_gen(ps+1,num*lucky[ps]); if(num<=1000000100000LL/lucky[ps])vlucky_gen(ps,num*lucky[ps]); } int main() { // clock_t b=clock(); lucky_gen(0); sort(lucky.begin(),lucky.end()); vlucky_gen(0,1LL); copy(st.begin(),st.end(),back_inserter(vlucky)); sort(vlucky.begin(),vlucky.end()); // clock_t e=clock(); // cout << (float)(e-b)/CLOCKS_PER_SEC << endl; int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { long long int a,b; cin >> a >> b; long long int ans=upper_bound(vlucky.begin(),vlucky.end(),b)-lower_bound(vlucky.begin(),vlucky.end(),a-1); cout << "Case " << qq << ": " << ans << '\n'; } return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #459/D. MADMAX.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 vector<pii>gr[507]; int lvl[507],st[507]; string str; vector<string>vt,ct; void dfs(int u,int t) { for(int i=0; i<gr[u].size(); i++) { int v = gr[u][i].fs; int x = gr[u][i].sc; if(x>=t) { str.push_back(x+'a'); // cout << u << " --> " << v << endl; // lvl[v] = max(lvl[v],lvl[u] + 1); dfs(v,x); str=str.substr(0,str.size()-1); } } vt.push_back(str); } void dfs2(int u,int t) { for(int i=0; i<gr[u].size(); i++) { int v = gr[u][i].fs; int x = gr[u][i].sc; if(x>=t) { str.push_back(x+'a'); // cout << u << " --> " << v << endl; // lvl[v] = max(lvl[v],lvl[u] + 1); dfs(v,x); str=str.substr(0,str.size()-1); } } ct.push_back(str); } int main() { int n,m; sf2(n,m); for(int i=0; i<m; i++) { int u,v; char ch; sf2(u,v); sf(" %c",&ch); int t = ch-'a'; gr[u].push_back({v,t}); } // dfs(1,-1); for(int i=1; i<=n; i++) { memset(lvl,0,sizeof lvl); lvl[i] = 1; // cout << "call dfs " << i << endl; dfs(i,-1); int mx = 0; for(int j=1; j<=n; j++) { mx = max(mx,lvl[j]); } st[i] = mx; } for(int i=1; i<=n; i++) { cout << st[i] << " "; } cout << endl; int ans[507][507]; for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { if(st[i]<=st[j]) { ans[i][j] = 0; } else { ans[i][j] = 1; } } } for(int i=1; i<=n; i++) { vt.clear(); dfs(i,-1); sort(vt.rbegin(),vt.rend()); string temp = vt[0]; cout << i << " er jonno " << temp << endl; for(int j=1; j<=n; j++) { ct.clear(); dfs2(j,-1); int f =0; for(string s : ct) { cout << s << " "; } cout << endl; for(int ii=0; ii<ct.size(); ii++) { if(temp<=ct[ii]) { cout << i << " er jonno " << temp << " " << j << " er jonno " << ct[ii] << endl; f=1; break; } } if(f) { pf("B"); } else { pf("A"); } } pf("\n"); } return 0; } /* */ <file_sep>/LightOJ/1073 - DNA Sequence.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int return 0; } <file_sep>/Codeforces/Contests/191/B. Hungry Sequence.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 #define MAX 10000000 ///joto porjonto sieve korte cai #define LMT 3163 /// sqrt(MAX) #define LEN 664579 ///appx number of primes #define RNG 100032 ///range for segmentflaged sieve #define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31))) #define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31))) unsigned primeflag[MAX/64+7], segmentflag[RNG/64+7], primes[LEN+7]; /* Generates all the necessary prime numbers and marks them in primeflag[]*/ void sieve() { unsigned long long int i, j, k; for(i=3; i<LMT; i+=2) if(!chkC(primeflag, i)) for(j=i*i, k=i<<1; j<MAX; j+=k) setC(primeflag, j); j=0; primes[j++]=2; for(i=3; i<MAX; i+=2) if(!chkC(primeflag, i)) primes[j++] = i; // cout << j << endl; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); sieve(); int n; cin >> n; for(int i=0;i<n;i++) cout << primes[i] << " "; return 0; } <file_sep>/Novice/Marathon Week - 9 ArticulationBridgeSCC/L - Efficient Traffic System.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 20000 int n,e; int visit[maxn+7],sccnum=1; vector<int>gh[maxn+7],tgh[maxn+7]; stack<int>st; void dfs(int u) { visit[u]=1; for(int i=0 ; i<gh[u].size() ; i++ ) { int v=gh[u][i]; if(!visit[v]) { dfs(v); } } st.push(u); } void dfss(int u) { visit[u]=sccnum; for(int i=0 ; i<tgh[u].size() ; i++ ) { int v=tgh[u][i]; if(!visit[v]) { dfss(v); } } } void scc() { memset(visit,0,sizeof visit); while(!st.empty()) st.pop(); for(int i=1 ; i<=n ; i++ ) { if(!visit[i]) { dfs(i); } } memset(visit,0,sizeof visit); sccnum=1; while(!st.empty()) { int u=st.top(); st.pop(); if(!visit[u]) { // cout << u << sccnum << endl; dfss(u); sccnum++; } } } int dag() { // cout << "scc num " << sccnum << endl; if(sccnum==2) return 0; int x,y; int in[maxn+7],out[maxn+7]; memset(in,0,sizeof in); memset(out,0,sizeof out); for(int u=1 ; u<=n ; u++ ) { for(int j=0 ; j<gh[u].size() ; j++ ) { int v=gh[u][j]; x=visit[u],y=visit[v]; if(x==y) continue; in[y]++,out[x]++; } } int ii=0,oo=0; // for(int i=1 ; i<=5 ; i++ ) // { // cout << i << " sccnum " << visit[i] << endl; // } // cout << "scc num " << sccnum << endl; for(int i=1 ; i<sccnum ; i++ ) { if(in[i]==0) { // cout << "indegree " << i << endl; ii++; } if(out[i]==0) { // cout << "outdegree " << i << endl; oo++; } } // cout << ii << endl; // cout << oo << endl; return max(ii,oo); } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; sf("%d",&tc); for(int qq=1 ; qq<=tc ; qq++ ) { sf("%d%d",&n,&e); for(int i=0 ; i<=n ; i++ ) { gh[i].clear(); tgh[i].clear(); } int u,v; for(int i=0 ; i<e ; i++ ) { sf("%d %d",&u,&v); gh[u].push_back(v); tgh[v].push_back(u); } scc(); int t=dag(); pf("Case %d: %d\n",qq,t); } return 0; } /* 1 4 4 1 2 2 3 3 2 1 4 */ <file_sep>/Marathon/Weekly Marathon #7 by DJ/N - Remainders Game.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int ll lcm(ll a,ll b) { return a*b/__gcd(a,b); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll n,k; cin >> n >> k; ll temp=1; while(n--) { ll t; cin >> t; temp=__gcd(k,lcm(temp,t)); } if(temp==k) { cout << "YES"; } else { cout << "NO"; } return 0; }<file_sep>/Codeforces/Contests/Educational Codeforces Round 33 (Rated for Div. 2)/B. Beautiful Divisors.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 100007 int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll pre[100]; for(int i=1;i<100;i++) { pre[i]=( (1<<i)-1 ) * ( 1<<(i-1) ); } int n; cin >> n; ll mx=0; for(int i=1;i<100 && pre[i]<=n;i++) { if(n%pre[i]==0) { mx=max(mx,pre[i]); } } cout << mx << endl; return 0; } <file_sep>/Contest/Individual Practice Contest 7/D - Qwerty78 Trip.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 1000007 ll bigmod(ll a,ll b,ll m) { /// a^b%m ll ans=1; while(b>0) { if(b&1) ans=(a*ans)%m; b>>=1; a=(a*a)%m; } return ans; } ll modInv(ll a,ll m) { ll x=bigmod(a,m-2,m)%m; return x; } ll fact[maxn+7]; ll ncr(ll n,ll r,ll p) { ll a = (fact[r]*fact[n-r])%mod; ll t = modInv(a,mod); ll rr = (fact[n]*t)%mod; return rr; } ll func(ll a,ll b,ll x,ll y) { return ncr( (x-a)+(y-b) , x-a ,mod ); } int main() { fact[0]= 1; for(ll i=1;i<maxn;i++) { fact[i] = (fact[i-1]*i)%mod; } int tc; sf1(tc); while(tc--) { int n,m; sf2(n,m); int a,b; sf2(a,b); ll ans = func(1,1,n,m) - ( func(1,1,a,b)*func(a,b,n,m) ); ans+=mod; ans%=mod; pf1ll(ans); } return 0; } /* */ <file_sep>/Contest/Individual Practice Contest 3/E - Tree Weights.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 vector<int>gr[maxn]; int st[maxn],ft[maxn],dep[maxn],is_child[maxn]; int tim=0; ll bigmod(ll b,ll p) { ll ans = 1; while(p) { if(p&1) ans = (ans*b) % mod; p>>=1; b = (b*b) % mod; } return ans; } void dfs(int u,int p,int h) { dep[u] = h; st[u] = ++tim; int f=0; for(int v : gr[u]) { if(v != p) { f=1; dfs(v,u,dep[u]+1); } } if(!f) { is_child[u] = 1; } ft[u] = tim; } ll tree[10*maxn]; void updt(int id,int l,int r,int ps,ll val) { if(l == r) { tree[id]+=val; return ; } int mid = (l+r)/2; if(ps<=mid) { updt(id*2,l,mid,ps,val); } else { updt(id*2+1,mid+1,r,ps,val); } tree[id] = ( tree[id*2] + tree[id*2+1] + mod )%mod; } ll query(int id,int l,int r,int ql,int qr) { if(l>qr || r<ql) { return 0; } if(l>=ql and r<=qr) { return tree[id]; } int mid = (l+r)/2; return ( query(id*2,l,mid,ql,qr) + query(id*2+1,mid+1,r,ql,qr) ) % mod; } void clr() { for(int i=0; i<maxn; i++) { gr[i].clear(); } tim = 0; memset(tree,0,sizeof tree); } int main() { ll two[maxn+7]; two[0] = 1LL; for(int i=1; i<maxn; i++) { two[i] = (two[i-1]*2LL) % mod; } // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); int tc; sf1(tc); for(int qq=1; qq<=tc; qq++) { int n; sf1(n); clr(); for(int i=0; i<n-1; i++) { int u,v; sf2(u,v); gr[u].push_back(v); gr[v].push_back(u); } dfs(1,-1,0); int s = st[1]; int e = ft[1]; // cout << s << " " << e << endl; int q; pcase(qq); sf1(q); while(q--) { int ty; sf1(ty); if(ty == 2) { ll u,x; sf2ll(u,x); ll val = ( x*two[dep[u]-1] ) % mod; updt(1,s,e,st[u],val); } else { ll u; sf1(u); if(is_child[u]) { ll x = query(1,s,e,st[u],ft[u]) ; ll d = two[dep[u]-1]; ll t = ( x * bigmod(d,mod-2) + mod ) % mod; pf1ll(t); } else { ll x = query(1,s,e,st[u],ft[u]) ; ll d = two[dep[u]]; ll t = ( x * bigmod(d,mod-2) + mod ) % mod; pf1ll(t); } } } } return 0; } /* */ <file_sep>/Codechef/Contests/August Cook-Off 2017/Real obtuse.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; while(tc--) { ll k,a,b; cin >> k >> a >> b; ll c=min(a,b); ll d=max(a,b); ll e=d-c-1; ll f=k-(e+2); if(k&1) { cout << min(e,f) << endl; } else { if(abs(a-b)==k/2) { cout << 0 << endl; } else { cout << min(e,f) << endl; } } } return 0; }<file_sep>/LightOJ/1245 - Harmonic Number (II).cpp #include<bits/stdc++.h> using namespace std; long long int h(long long int n) { long long int ans=0,t=sqrt(n); for(int i=1;i<=t;i++) { ans+=(n/i); int t=(n/i) - (n/(i+1)); if(t>0) { ans+=(t*i); } } if(t==n/t) ans-=t; return ans; } int main() { ios_base::sync_with_stdio(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { long long int n; cin >> n; cout << "Case " << qq << ": " << h(n) << '\n'; } return 0; } <file_sep>/Marathon/Mathematics/10791 Minimum Sum LCM.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define MAX 1000000 ///joto porjonto sieve korte cai #define LMT 1000 /// sqrt(MAX) #define LEN 300000 ///appx number of primes #define RNG 100032 ///range for segmentflaged sieve #define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31))) #define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31))) unsigned primeflag[MAX/64+7], segmentflag[RNG/64+7], primes[LEN+7]; /* Generates all the necessary prime numbers and marks them in primeflag[]*/ int tt; void sieve() { unsigned long long int i, j, k; for(i=3; i<LMT; i+=2) if(!chkC(primeflag, i)) for(j=i*i, k=i<<1; j<MAX; j+=k) setC(primeflag, j); j=0; primes[j++]=2; for(i=3; i<MAX; i+=2) if(!chkC(primeflag, i)) primes[j++] = i; tt=j; } ll prime_factorize(ll n) { int cnt=0; ll ans=0; int sqrtn = sqrt ( n ); for ( int i = 0; i < tt && primes[i] <= sqrtn; i++ ) { if ( n % primes[i] == 0 ) { ll temp=1LL; while ( n % primes[i] == 0 ) { n /= primes[i]; temp*=primes[i]; /* cout << primes[i] << endl;*/ } cnt++; ans+=temp; sqrtn = sqrt ( n ); } } if ( n != 1 ) { /*cout << n << endl;*/ cnt++; ans+=n; } if(cnt==1) ans++; return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); sieve(); int qq=1; ll n; while(cin >> n) { if(n==0) return 0; ll t=0; if(n==1) t=2; else t=prime_factorize(n); cout << "Case " << qq++ << ": " << t << endl; } }<file_sep>/LightOJ/1110 - An Easy LCS2.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 string str1,str2; string dp[107][107]; int l,m; string rec(int i,int j) { if(i>=l || j>=m) return ""; string &ret=dp[i][j]; if(ret!="-1") return ret; if(str1[i]==str2[j]) { ret=str1[i]+rec(i+1,j+1); } else { string temp=rec(i+1,j); string tem=rec(i,j+1); if(temp.size()>tem.size()) ret=temp; else if(temp.size()<tem.size()) ret=tem; else ret=min(temp,tem); } return ret; } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { cin >> str1 >> str2; l=str1.size(),m=str2.size(); for(int i=0 ;i<107 ;i++ ) { for(int j=0 ;j<107 ;j++ ) { dp[i][j]="-1"; } } string ans=rec(0,0); pf("Case %d: ",qq); if(ans.empty()) pf(":(\n"); else cout << ans << '\n'; } return 0; } /* */ <file_sep>/Contest/Team Forming Contest 2 (26-8-2017) (2015)/A - Shortest path of the king.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int fx[]={-1,1,0,0,1,1,-1,-1}; int fy[]={0,0,-1,1,1,-1,1,-1}; int flag[10][10]; pair<int,int> path[10][10]; std::vector< pair<int,int> > vt; string nota[]={"U","D","L","R","RD","LD","RU","LU"}; vector<string>temp; void bfs(int sx,int sy) { memset(path,-1,sizeof path); memset(flag,-1,sizeof flag); queue< pair<int,int> >Q; Q.push({sx,sy}); flag[sx][sy]=0; while(!Q.empty()) { pair<int,int> u=Q.front(); Q.pop(); for(int i=0;i<8;i++) { int vx=u.first+fx[i]; int vy=u.second+fy[i]; if(vx<8 and vx>=0 and vy<8 and vy>=0 and flag[vx][vy]==-1) { /*cout << u.first <<" " << u.second << " theke jacci " << vx <<" " << vy << endl;*/ flag[vx][vy]=flag[u.first][u.second]+1; path[vx][vy]={u.first,u.second}; /*cout << u.first << " " << u.second << endl;*/ Q.push({vx,vy}); } } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string s,t; cin >> s >> t; /*cout << s[1] << endl;*/ int sy=s[0]-'a'; int sx='8'-s[1]; int ty=t[0]-'a'; int tx='8'-t[1]; /*cout <<sx << " " << sy << endl; cout << tx << " " << ty << endl; cout <<"###" << endl;*/ bfs(sx,sy); /*cout << "bfs sesh " << endl; cout << path[sx][sy].first << " " << path[sx][sy].second << endl;*/ while(path[tx][ty].first!=-1 and path[tx][ty].second!=-1) { /*cout << tx << " " << ty << endl; cout << path[tx][ty].first << " " << path[tx][ty].second << endl;*/ int ax=path[tx][ty].first,bx=path[tx][ty].second; /*cout << ax << " " << bx << endl;*/ vt.push_back({tx,ty}); tx=ax; ty=bx; /*vt.push_back({tx,ty});*/ /*cout << tx << " " << ty << endl << endl;*/ } /*cout << " loop " << endl;*/ vt.push_back({sx,sy}); reverse(vt.begin(),vt.end()); /* cout << "path shuru " << endl; for(auto it : vt) { cout << it.first << " " << it.second << endl; } cout << "path sesh" << endl;*/ cout << vt.size()-1 << endl; for(int i=0;i<vt.size()-1;i++) { for(int j=0;j<8;j++) { /*cout << vt[i].first << " " << vt[i].second << endl; cout << vt[i].first+fx[i] << " " << vt[i].second+fy[i] << endl << endl;*/ if(vt[i].first+fx[j]==vt[i+1].first and vt[i].second+fy[j]==vt[i+1].second) { /*cout <<"if er vitre " << endl;*/ temp.push_back(nota[j]); } } } for(auto it:temp) { cout << it <<endl; } return 0; }<file_sep>/Contest/Individual Practice Contest 2/jv2.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 500007 int ara[maxn]; int flag[maxn]; ll lcm[maxn]; void pre() { for(int i=1; i<maxn; i++) { lcm[i]=1LL; } for(int i=2; i<maxn; i*=2) { lcm[i]*=2LL; } for(ll i=3; i*i<=maxn; i+=2) { if(flag[i]==0) { for(int j=i*i; j<maxn; j+=(i+i)) { flag[j]=1; } for(int j=i; j<maxn; j*=i) { lcm[j]*=i; lcm[j]%=mod; } } } for(int i=2; i<maxn; i++) { lcm[i]= (lcm[i] * lcm[i-1]) % mod ; } } int tree[4*300000+7][5]; void build(int id,int l,int r) { if(l==r) { tree[id][0] = tree[id][1] = ara[l]; return ; } int mid= (l+r)/2; build(id*2,l,mid); build(id*2+1,mid+1,r); tree[id][0] = min( tree[id*2][0], tree[id*2+1][0] ); tree[id][1] = max( tree[id*2][1], tree[id*2+1][1] ); // cout << id << " " << tree[id][0] << " " << tree[id][1] << endl; } int lazy[4*300000+7]; void shift(int id,int l,int r) { // cout << "before propagate " << id << " " << tree[id*2][0] << " " << tree[id*2+1][0] << endl; if(l!=r) { tree[id*2][0]+=lazy[id]; tree[id*2][1]+=lazy[id]; tree[id*2+1][0]+=lazy[id]; tree[id*2+1][1]+=lazy[id]; lazy[id*2]+=lazy[id]; lazy[id*2+1]+=lazy[id]; lazy[id]=0; } // else // { // lazy[id]=0; // } // cout << "after propagate " << id << " " << tree[id*2][0] << " " << tree[id*2+1][0] << endl; } void updt(int id,int l,int r,int ql,int qr,int val) { if(lazy[id]) { shift(id,l,r); } if(l>qr || r<ql ) return ; if(l>=ql and r<=qr) { lazy[id]+=val; tree[id][0]+=val; tree[id][1]+=val; return ; } int mid = (l+r)/2; updt(id*2,l,mid,ql,qr,val); updt(id*2+1,mid+1,r,ql,qr,val); tree[id][0] = min( tree[id*2][0], tree[id*2+1][0] ); tree[id][1] = max( tree[id*2][1], tree[id*2+1][1] ); } pair<int,int> query(int id,int l,int r,int ql,int qr) { if(lazy[id]) { shift(id,l,r); } if(l>qr || r<ql ) return make_pair(inf,-inf); if(l>=ql and r<=qr) { // cout << id << " " << l << " " << r << " *---> " << tree[id][0] << " " << tree[id][1] << endl; return make_pair(tree[id][0], tree[id][1] ); } int mid = (l+r)/2; pair<int,int> a,b; a=query(id*2,l,mid,ql,qr); b=query(id*2+1,mid+1,r,ql,qr); tree[id][0] = min( tree[id*2][0], tree[id*2+1][0] ); tree[id][1] = max( tree[id*2][1], tree[id*2+1][1] ); // cout << id << " theke return hocce " << min(a.fs,b.fs) << " " << max(a.sc,b.sc) << endl; return make_pair( min(a.fs,b.fs), max(a.sc,b.sc) ); } int main() { memset(lazy,0,sizeof lazy); pre(); int n,m; sf2(n,m); for(int i=0; i<n; i++) sf1(ara[i]); build(1,0,n-1); // cout << "after bulid " << endl; // for(int i=1;i<10;i++) // { // cout << i << " --> " << tree[i][0] << " " << tree[i][1] << endl; // } // cout << tree[1][0] << " " << tree[1][1] << endl; while(m--) { int t; sf1(t); if(t==0) { int i,j,p; sf2(i,j); sf1(p); updt(1,0,n-1,i,j,p); cout << "after updt " << endl; for(int i=1;i<10;i++) { cout << i << " --> " << tree[i][0] << " " << tree[i][1] << endl; } } else if(t==1) { int i,j; sf2(i,j); pair<int,int> t = query(1,0,n-1,i,j); cout << "after query " << endl; for(int i=1;i<10;i++) { cout << i << " --> " << tree[i][0] << " " << tree[i][1] << endl; } cout << t.sc << endl; pf1ll(lcm[t.sc]); } else if(t==2) { int i,j; sf2(i,j); pair<int,int> t = query(1,0,n-1,i,j); // cout << t.fs << endl; pf1ll(lcm[t.fs]); } } return 0; } /* 5 5 4 2 5 6 2 1 0 0 0 0 1 -2 1 0 0 2 0 1 0 0 1 4 */ <file_sep>/Marathon/[15] Weekly Marathon #8 by DJ/B. Maximize Sum of Digits.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int vector<int>vt; int sum(ll t) { int ans=0; while(t>0) { vt.push_back(t%10); ans+=(t%10); t/=10; } reverse(vt.begin(),vt.end()); return ans; } void solve(ll x) { int a=sum(x); vector<int>res; int sum=0,p=0; for(int i=0;i<vt.size();i++) { if(vt[i]==0) continue; int t=p+vt[i]-1+9*(vt.size()-i-1); p=p+vt[i]; if(t>=sum) { sum=t; res.clear(); for(int j=0;j<i;j++) res.push_back(vt[j]); res.push_back(vt[i]-1); for(int j=i+1;j<vt.size();j++) res.push_back(9); } } if(sum<=a) { res=vt; } int i=0; for(;i<res.size();i++) { if(res[i]!=0) break; } for(;i<res.size();i++) { cout << res[i]; } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll x; cin >> x; solve(x); return 0; }<file_sep>/Contest/Team Forming Contest 1 (25-8-2017) (2015)/G - Funny Knapsack.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int vector<ll>vt,fir,sec; ll sum=0; int p,q; void rec1(int ps) { if(ps>=p) { fir.push_back(sum); return; } sum+=vt[ps]; rec1(ps+1); sum-=vt[ps]; rec1(ps+1); } void rec2(int ps) { if(ps>=q) { sec.push_back(sum); return; } sum+=vt[ps]; rec2(ps+1); sum-=vt[ps]; rec2(ps+1); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { ll n,k; cin >> n >> k; vt.clear(); fir.clear(); sec.clear(); for(int i=0;i<n;i++) { ll t; cin >> t; vt.push_back(t); } p=n/2; q=n; sum=0; rec1(0); /*for(int i: fir) cout << i << " "; cout << endl;*/ sum=0; rec2(p); /*for(int i: sec) cout << i << " "; cout << endl;*/ sort(sec.begin(),sec.end()); ll ans=0; /*cout << lower_bound(sec.begin(),sec.end(),3)-sec.begin() << endl;*/ for(int i=0;i<fir.size();i++) { /*int t=upper_bound(sec.begin(),sec.end(),k-fir[i])-sec.begin();*/ /*cout << "t " << t << endl;*/ ans+=(upper_bound(sec.begin(),sec.end(),k-fir[i])-sec.begin()); } cout << "Case " << qq << ": " << ans << endl; } return 0; }<file_sep>/Codeforces/B numbers/GSS4 - Can you answer these queries IV.cpp #include<bit/stdc++.h> using namespace std; vector<int>tree(4*100000+7),lazy(4*100000+7),vt(100000+7); void bulid(int id,int l,int r) { if(l==r) { tree[id]=vt[l]; return; } int mid=(l+r)/2; build(id*2,l,mid); build(id*2+1,mid+1,r); tree[id]=tree[id*2]+tree[id*2+1]; } int main() { ios_base::sync_with_stdio(0); return 0; } <file_sep>/Codeforces/Contests/Codeforces Round 225/D. Antimatter.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 10007 ll dp[1007][20007]; int n; ll ara[maxn+7]; ll rec(int ps,int sum) { ll ret = (sum==maxn); if(ps>=n) { return ret; } if(dp[ps][sum] != -1) { return dp[ps][sum]; } ret+= rec(ps+1,sum+ara[ps]); ret+= rec(ps+1,sum-ara[ps]); ret %= mod; return dp[ps][sum] = ret; } int main() { sf1(n); for(int i=0;i<n;i++) { sf1ll(ara[i]); } ll ans = 0; memset(dp,-1,sizeof dp); for(int i=0;i<n;i++) { ans += rec(i+1,maxn+ara[i]); ans += rec(i+1,maxn-ara[i]); ans %= mod; // cout << i << " er jonno " << ans << endl; } pf1ll(ans); return 0; } /* */ <file_sep>/Codeforces/Contests/Codeforces Round #444 (Div. 2)/B. Cubes for Masha.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int ara[10][10]; int n; set<int>vt; int flag[10]; void rec(int num) { vt.insert(num); for(int k=0;k<n;k++) { if(flag[k]==0) { flag[k]=1; for(int t=0;t<6;t++) { rec(num*10+ara[k][t]); } flag[k]=0; } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; for(int i=0; i<n; i++) { for(int j=0; j<6; j++) { cin >> ara[i][j]; } } memset(flag,0,sizeof flag); rec(0); int t=0; for(auto it=vt.begin(); it!=vt.end(); it++,t++) { if(*it!=t) { cout << max(0,t-1) << endl; return 0; } } return 0; } <file_sep>/Codeforces/Contests/Codeforces Round #448 (Div. 2)/C. Square Subsetsv2.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define mod 1000000007 #define sf scanf int seti(int n,int ps) { return ( n|=(1<<ps) ); } int num_mask[100]; ll pwr[1000007]; void pre() { vector<int>primes; primes.push_back(2); for(int i=3; i<71; i+=2) { int f=1; for(int j=2; j*j<=i; j++) { if(i%j==0) { f=0; break; } } if(f) { primes.push_back(i); } } // for(int x : primes) cout << x << " "; // cout << "fine " << endl; for(int num=2; num<71; num++) { int x=0, t=num; for(int i=0; i<primes.size(); i++) { if( t%primes[i] == 0) { int cnt=0; while(t%primes[i] == 0) { cnt++; t/=primes[i]; } if(cnt&1) { x=seti(x,i); } } } num_mask[num]=x; } num_mask[1]=0; pwr[0]=1; for(int i=1; i<1000007; i++) { pwr[i] = (pwr[i-1]*2LL) %mod; } } int ara[75]; int dp[71][(1<<19)]; ll rec(int ps,int mask) { if(ps>=71) { if(mask==0) return 1LL; return 0LL; } if(ara[ps]==0) return rec(ps+1,mask); if(dp[ps][mask] != -1) return dp[ps][mask]; long long int ret=0; ret = ( pwr[ara[ps]-1] * rec(ps+1,mask) ) % mod; ret%=mod; ret += ( pwr[ara[ps]-1] * rec(ps+1,mask^num_mask[ps]) ) %mod; ret%=mod; return dp[ps][mask]=ret; } int main() { pre(); int n; sf("%d",&n); for(int i=0; i<n; i++) { int t; sf("%d",&t); ara[t]++; } memset(dp,-1,sizeof dp); ll temp = rec(1,0) ; printf("%d\n",temp-1); return 0; } <file_sep>/LightOJ/1166 - Old Sortin.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; for(int qq=1;qq<=tc;qq++) { int n; cin >> n; vector<int>vt; for(int i=0;i<n;i++) { int t; cin >> t; vt.push_back(t); } vector<int>temp=vt; sort(temp.begin(),temp.end()); int cnt=0; for(int i=0;i<n;i++) { if(temp[i]!=vt[i]) { for(int j=i;j<n;j++) { if(vt[j]==temp[i]) { swap(vt[j],vt[i]); cnt++; } } } } cout << "Case " << qq << ": " << cnt << endl; } return 0; }<file_sep>/LightOJ/1002 - Country Roads.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define maxn 507 #define ll long long int vector< pair<int,int> >gr[maxn]; struct cmp { bool operator () (pair<int,int>& a, pair<int,int> & b) { return a.second > b.second; } }; void dijkstra(int src,int n) { int visit[maxn]; int dis[maxn]; memset(visit,0,sizeof visit); fill(dis,dis+maxn,INT_MAX); priority_queue< pair<int,int> , vector< pair<int,int> > , cmp > pq; pq.push(make_pair(src,INT_MIN)); dis[src]=0; while(!pq.empty()) { int u=pq.top().first; pq.pop(); for(int i=0;i<gr[u].size();i++) { int v=gr[u][i].first; int w=gr[u][i].second; int t=max(dis[u],w) ; if( dis[v]> t) { dis[v]=t ; pq.push(make_pair(v,dis[v])); } } } for(int i=0;i<n;i++) { if(dis[i]!=INT_MAX) { pf("%d\n",dis[i]); } else { pf("Impossible\n"); } } } int main() { int tc; sf("%d",&tc); for(int qq=1;qq<=tc;qq++) { int n,m; sf("%d %d",&n,&m); for(int i=0;i<maxn;i++) gr[i].clear(); for(int i=0;i<m;i++) { int u,v,w; sf("%d %d %d",&u,&v,&w); gr[u].push_back(make_pair(v,w)); gr[v].push_back(make_pair(u,w)); } int src; sf("%d",&src); pf("Case %d:\n",qq); dijkstra(src,n); } return 0; }<file_sep>/Contest/2016-2017 CTU Open Contest/I - Stacking Cups.cpp #include<bits/stdc++.h> using namespace std; int f(string str) { int t=1,ans=0; for(int i=str.size()-1;i>=0;i--) { ans+=(str[i]-'0')*t; t*=10; } return ans; } int main() { int n; while(cin >>n) { vector< pair<int,string> >vt; for(int i=0;i<n;i++) { string s,t; cin >> s >> t; if(s[0]>='a' && s[0]<='z') { vt.push_back({f(t),s}); } else { vt.push_back({f(s)/2,t}); } } sort(vt.begin(),vt.end()); for(auto it:vt) { cout << it.second << endl; } } return 0; } <file_sep>/LightOJ/1033 - Generating Palindromes.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 string str; int dp[107][107]; int rec(int i,int j) { // cout << str[i] << ' ' << str[j] << endl; if(i>=j) return 0; int &ret=dp[i][j]; if(ret!=-1) return ret; if(str[i]==str[j]) ret=rec(i+1,j-1); else ret=1+ min(rec(i+1,j),rec(i,j-1)); return ret; } int main() { int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { cin >> str; memset(dp,-1,sizeof dp); pf("Case %d: %d\n",qq,rec(0,str.size()-1)); } return 0; } /* */ <file_sep>/Codeforces/Contests/8VC Venture Cup 2017 - Elimination Round/E. PolandBall and White-Red graph.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { int n,k; cin >> n >> k ; int d=n/2; if(n%2==1) d++; if(k>d or k==1) { cout << "-1" ; } else { cout << n-1 << endl; for(int i=1 ;i<n ;i++ ) { cout << i << ' ' << i+1 << '\n'; } } return 0; } /* */ <file_sep>/csacademy/Triplet Min Sum.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define maxn 100007 #define level 18 vector<int>gr[maxn]; int depth[maxn],par[maxn][level]; void dfs(int u,int p) { depth[u]=depth[p]+1; par[u][0]=p; for(int i=0;i<gr[u].size();i++) { if(gr[u][i]!=p) { dfs(gr[u][i],u); } } } void pre(int n) { for(int i=1;i<level;i++) { for(int node=1;node<=n;node++) { if(par[node][i-1]!=-1) { par[node][i] = par[par[node][i-1]][i-1]; } } } } int lca(int u,int v) { if(depth[v]<depth[u]) swap(u,v); int diff=depth[v]-depth[u]; for(int i=0;i<level;i++) { if((diff>>i)&1) { v=par[v][i]; } } if(v==u) return v; for(int i=level-1;i>=0;i--) { if(par[u][i] != par[v][i]) { u=par[u][i]; v=par[v][i]; } } return par[u][0]; } int dist(int u,int v) { int l=lca(u,v); int d=depth[u]+depth[v]-2*depth[l]; return d; } int main() { int n,q; sf("%d %d",&n,&q); for(int i=1;i<=n-1;i++) { int u,v; sf("%d %d",&u,&v); gr[u].push_back(v); gr[v].push_back(u); } depth[0]=0; memset(par,-1,sizeof par); dfs(1,0); pre(n); while(q--) { int a,b,c; sf("%d %d %d",&a,&b,&c); vector< pair<int,int> > vt; vt.push_back({dist(b,a)+dist(a,c),a}); vt.push_back({dist(a,b)+dist(b,c),b}); vt.push_back({dist(a,c)+dist(c,b),c}); int l=lca(a,b); vt.push_back({dist(a,l)+dist(b,l)+dist(c,l),l}); l=lca(b,c); vt.push_back({dist(a,l)+dist(b,l)+dist(c,l),l}); l=lca(a,c); vt.push_back({dist(a,l)+dist(b,l)+dist(c,l),l}); sort(vt.begin(),vt.end()); cout << vt[0].second << " " << vt[0].first << endl; } return 0; } <file_sep>/Implementation/test.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 ll bigmod(ll a,ll b,ll m) { /// a^b%m ll ans=1; while(b>0) { if(b&1) ans=(a*ans)%m; b>>=1; a=(a*a)%m; } return ans; } ll egcd (ll a,ll b,ll &x,ll &y) { /// ax+by=1 finding x and y where a<b if (a == 0) { x = 0; y = 1; return b; } ll x1, y1; ll d = egcd (b%a,a,x1,y1); x = y1 - (b/a) * x1; y = x1; return d; } ll modInv(ll a,ll m) { /// works only when (a,m)=1; /// ax=1 (mod m) finding x ll x,y; if(a<=m) egcd(a,m,x,y); else egcd(m,a,y,x); x%=m; if(x<0) x+=m; /// if x can be very large nand m is prime then use big mod // x=bigmod(a,m-2,m)%m; return x; } ll CRT(const vector< pair<ll, ll> > &vt) { /// pair<ai(residues),pi(primes)> ll M = 1; for(int i = 0; i<vt.size(); i++) M *= vt[i].second; ll ret = 0; for(int i = 0; i<vt.size(); i++) { ll ai = vt[i].first; ll Mi = (M/vt[i].second); ret += ai * Mi * modInv(Mi % vt[i].second, vt[i].second); ret %= M; } return ret; } int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); int tc; sf1(tc); for(int qq=1; qq<=tc; qq++) { int n; sf1(n); vector< pair<ll,ll> > vt; for(int i=0; i<n; i++) { ll p,r; sf2ll(p,r); vt.push_back( {r,p} ); } ll ans = CRT( vt ); pcase(qq); if(ans == -1) { pf("Impossible\n"); } else { pf1ll(ans); } } return 0; } /* */ <file_sep>/LightOJ/1027.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { int tc; sf("%d",&tc); for(int qq=1;qq<=tc;qq++) { int n; sf("%d",&n); int cnt=0; ll nu=0; int f=0; for(int i=0;i<n;i++) { int t; sf("%d",&t); if(t<0) { cnt++; } else f=1; if(t<0)t*=-1; nu+=t; } ll du=n-cnt; if(!f) { pf("Case %d: inf\n",qq); } else { ll g=__gcd(nu,du); pf("Case %d: %lld/%lld\n",qq,nu/g,du/g); } } return 0; } /* */ <file_sep>/Hudai/Tree.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 60000+7 #define level 15 vector< pair<int,ll> > gr[maxn]; int depth[maxn],par[maxn][level+7]; ll dis[maxn]; ll temp[maxn]; void dfs1(int u,int p) { for(auto v:gr[u]) { if(v.first!=p) { temp[v.first]=temp[u]+v.second; dfs1(v.first,u); } } } void dfs(int u,int p) { depth[u]=depth[p]+1; par[u][0]=p; for(auto v:gr[u]) { if(v.first!=p) { dis[v.first]=dis[u]+v.second; dfs(v.first,u); } } } void preprocess(int n) { for(int j=1;j<level;j++) { for(int node=1;node<=n;node++) { if(par[node][j-1]!=-1) { par[node][j]=par[par[node][j-1]][j-1]; } } } } int lca(int u,int v) { if(depth[u]<depth[v]) { swap(u,v); } int diff=depth[u]-depth[v]; for(int i=0;i<level;i++) { if((diff>>i)&1) { u=par[u][i]; } } if(u==v) return u; for(int i=level-1;i>=0;i--) { if(par[u][i]!=par[v][i]) { u=par[u][i]; v=par[v][i]; } } return par[u][0]; } int main() { /*freopen("I.IN","r",stdin);*/ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; for(int i=0;i<n-1;i++) { int u,v,w; cin >> u >> v >> w; gr[u].push_back({v,w}); gr[v].push_back({u,w}); } dfs(1,-1); /*cout << "ok" << endl;*/ preprocess(n); int a=-1,mx=-1; for(int i=1;i<=n;i++) { if(dis[i]>mx) { mx=dis[i]; a=i; } } cout << "a " << a << " " << dis[a] << endl; dfs1(a,-1); int b=-1; mx=-1; for(int i=1;i<=n;i++) { if(temp[i]>mx) { mx=temp[i]; b=i; } } cout << "b " << b << " " << dis[b] << endl; ll ans[maxn]; for(int i=1;i<=n;i++) { ans[i]=max( dis[a]+dis[i]-2*dis[lca(a,i)], dis[b]+dis[i]-2*dis[lca(b,i)] ); } for(int i=1;i<=n;i++) cout << ans[i] << endl; return 0; }<file_sep>/Contest/Individual Practice Contest 3/H - And Or.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d: ",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 bool chk(ll num,int ps) { return (bool) ( num&(1LL<<ps) ); } ll seti(ll num,int ps) { return num|=(1LL<<ps); } int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); int tc; sf1(tc); for(int qq=1; qq<=tc; qq++) { ll a,b; sf2ll(a,b); ll o=0LL,an=0LL; int f=0,st=0; for(int i=63; i>=0; i--) { if(chk(b,i)==1 and st==0) { st=1; } if(f) { o=seti(o,i); // cout << "flag " << o << " ** " << an << endl; continue; } if(chk(a,i) != chk(b,i) and st==1) { // cout << i << " position " << endl; o=seti(o,i); f=1; // cout << o << " " << an << endl; } else if(chk(a,i) == chk(b,i) and chk(b,i)==1) { // cout << "fine " << endl; o=seti(o,i); an=seti(an,i); } } pcase(qq); pf2ll(o,an); } return 0; } /* */ <file_sep>/Marathon/Suffix Array/E - Power Strings.cpp #include<bits/stdc++.h> using namespace std; #define maxn 1000007 int lps[maxn]; void compute_lps(string pat) { int j=0,i=1; lps[0]=0; while(i<pat.size()) { if(pat[i]==pat[j]) { lps[i]=j+1; i++,j++; } else { if(j!=0) { j=lps[j-1]; } else { lps[i]=0; i++; } } } } int main() { compute_lps("abcdabab"); for(int i=0;i<8;i++) { cout << lps[i] << " "; } return 0; } <file_sep>/Codeforces/B numbers/D. My pretty girl Noora.cpp #include<bits/stdc++.h> using namespace std; #define mxn 5000507 #define mod 1000000007 int p[mxn+7]; void seive() { for(int i=2; i<mxn; i+=2) p[i]=2; for(int i=3;i<mxn;i+=2) { if(!p[i]) { for(int j=i;j<mxn;j+=i) { if(!p[j])p[j]=i; } } } } long long int dp[mxn+7]; long long int rec(long long int n) { if(n==1) return 0; if(n==2) return 1; if(n==3) return 3; long long int& ret=dp[n]; if(ret!=-1) return ret; ret=(n*(p[n]-1)/2)+ rec(n/p[n]); ret%=mod; return ret; } int main() { ios_base::sync_with_stdio(0); seive(); memset(dp,-1,sizeof dp); for(int i=1; i<mxn; i++) { dp[i]=rec(i); } long long int t,l,r; cin >> t >> l >> r; long long int tt=1,ans=0; for(int i=l; i<=r; i++) { long long int temp=tt*dp[i]; ans+=(temp%mod); tt*=t; tt%=mod; ans%=mod; } cout << ans%mod; return 0; } // 1000000000 5000000 5000000 <file_sep>/Contest/Team Forming Contest 3 (08-09-2017) (2015)/A - Distance in the Tree.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int #define level 20 #define maxn 50000+7 vector< pair<int,int> >gr[maxn]; int depth[maxn],dis[maxn],par[maxn][level+7]; void dfs(int u,int p) { depth[u]=depth[p]+1; par[u][0]=p; for(auto v:gr[u]) { if(v.first!=p) { dis[v.first]=dis[u]+v.second; dfs(v.first,u); } } } void preprocess(int n) { for(int j=1;j<level;j++) { for(int node=0;node<n;node++) { if(par[node][j-1]!=-1) { par[node][j]=par[par[node][j-1]][j-1]; } } } } int lca(int u,int v) { if(depth[u]<depth[v]) { swap(u,v); } int diff=depth[u]-depth[v]; for(int i=0;i<level;i++) { if((diff>>i)&1) { u=par[u][i]; } } if(u==v) return u; for(int i=level-1;i>=0;i--) { if(par[u][i]!=par[v][i]) { u=par[u][i]; v=par[v][i]; } } return par[u][0]; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; for(int i=0;i<n-1;i++) { int u,v,w; cin >> u >> v >> w; gr[u].push_back({v,w}); gr[v].push_back({u,w}); } dfs(0,-1); preprocess(n); int m; cin >> m; while(m--) { int u,v; cin >> u >> v; int t=lca(u,v); /*cout << t << endl;*/ cout << dis[u]+dis[v]-dis[t]*2 << endl; } return 0; }<file_sep>/LightOJ/1277 - Looking for a Subsequence.cpp #include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define fs first #define sc second #define hi cout<<"****"<<endl; #define mod 1000000007 #define inf INT_MAX #define pi acos(-1.0) #define ll long long int #define sf scanf #define pf printf #define pcase(x) printf("Case %d:\n",x) #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%lld %lld",&a,&b) #define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%lld %lld\n",a,b) #define pf3ll(a,b,c) printf("%lld %lld %lld\n",a,b,c) #define maxn 100007 int main() { // ios_base::sync_with_stdio(0); // cin.tie(0); // cout.tie(0); int tc; sf1(tc); for(int qq=1; qq<=tc; qq++) { int n,q; sf2(n,q); int ara[n+7]; for(int i=0; i<n; i++) { sf1(ara[i]); } pcase(qq); while(q--) { int m; sf1(m); set<int>st,ans; set<int>::iterator it; for(int i=n-1; i>=0; i--) { st.insert(ara[i]); // cout << "insert hocce " << ara[i] << endl; cout << endl; it = st.find(ara[i]); if(it != st.begin() ) { it=st.begin(); // cout << "erase hocce " << *it << endl; st.erase(it); } cout << "set contains " << endl; for(int x : st) { cout << x << " "; } if(st.size()>m) { it = st.end(); it--; st.erase(it); } if(st.size()==m) { ans.clear(); ans = st; } } cout << "lis ---> " << endl; for(int x : st) { cout << x << " "; } cout << endl; if(ans.size()==m) { it = ans.begin(); pf("%d",*it); it++; for(; it != ans.end(); it++) { pf(" %d",*it); } pf("\n"); } else { pf("Impossible\n"); } } } return 0; } /* 3 8 5 8 7 5 6 5 1 2 7 3 */ <file_sep>/Marathon/CodeChef DP/B - Cards, bags and coins.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int n,m; ll dp[100007][3][107]; int ara[100007]; ll rec(int ps,int flag,int sum) { // cout << sum << endl; if(ps>=n) { if(sum%m==0) { return 1; } return 0; } ll &ret=dp[ps][flag][sum]; if(ret!=-1) return ret; ret=rec(ps+1,1,(sum+ara[ps])%m); ret%=1000000009; ret+=rec(ps+1,0,sum%m); ret%=1000000009; return ret; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tc; cin >> tc; while(tc--) { int q; scanf("%d %d",&n,&q); for(int i=0;i<n;i++) { scanf("%d",&ara[i]); } while(q--) { // cout << "####" << endl; scanf("%d",&m); memset(dp,-1,sizeof dp); ll ans=rec(0,0,0); printf("%d\n", ans%1000000009); } } return 0; } <file_sep>/Marathon/Weekly Marathon #2 by DJ/h.cpp #include<bits/stdc++.h> using namespace std; int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); int n; while(cin>>n) { if(n==0) return 0; char ch=getchar(); //cout << ch << endl; int ara[n+8]; int index[n+8]; for(int i=0;i<n;i++) { cin >> ara[i]; index[ara[i]]=i; } int f=1; //cout << index[4] << ara[3] << endl; for(int i=0;i<n and f;i++) { for(int j=i+1;j<n and f;j++) { int k=ara[j]+ara[j]-ara[i]; //cout << i << endl; if(k>=0 and k<n and index[k]>j) { f=0; cout << "no" << '\n'; } } } if(f) { cout << "yes" << '\n'; } } return 0; } <file_sep>/USACO/Section 1.1/Bear and Ladder.cpp #include<bits/stdc++.h> using namespace std; int main() { int q; cin >> q; while(q--) { int a,b; cin >> a >> b; if(a&1) { if(b==a-2 or b==a+1 or b==a+2) { cout << "YES" << '\n'; } else { cout << "NO" << '\n'; } } else { if(b==a-2 or b==a-1 or b==a+2) { cout << "YES" << '\n'; } else { cout << "NO" << '\n'; } } } return 0; } <file_sep>/Codeforces/B numbers/ok.cpp /*input */ #include<bits/stdc++.h> using namespace std; #define ll long long int int ara[10][10]; int n; vector<int>vt; void rec(int i,int j,int num) { if(i>=3 || j>=6) return; for(int t=0;t<6;t++) { vt.push_back(ara[i][j]); rec(i,t,ara[i][j]); } for(int t=0;t<6;t++) { vt.push_back(i+1,t,num*10+ara[i][j]); } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; for(int i=0;i<n;i++) { for(int j=0;j<6;j++) { cin >> ara[i][j]; } sort(ara[i],ara[i]+6); } rec(0,0,0); sort(vt.begin(),vt.end()); for(int i=0;i<vt.size();i++) { cout << vt[i] << endl; } return 0; }<file_sep>/Contest/Individual Practice Contest 1/E - Socks.cpp #include<bits/stdc++.h> using namespace std; #define ll long long int #define maxn 200007 #define sf scanf #define pf printf vector<int>gr[maxn]; int col[maxn]; unordered_map<int,int>mp; int mx=0,flag[maxn]; int tn=0; void dfs(int u) { flag[u]=1; tn++; mp[col[u]]++; mx=max(mx,mp[col[u]]); for(int i=0;i<gr[u].size();i++) { int v=gr[u][i]; if(flag[v]==-1) { dfs(v); } } } int main() { int n,m,k; sf("%d %d %d", &n, &m, &k); for(int i=1;i<=n;i++) { sf("%d ", & col[i]); } for(int i=0;i<m;i++) { int u,v; sf("%d %d", &u ,&v); gr[u].push_back(v); gr[v].push_back(u); } int ans=0; memset(flag,-1,sizeof flag); for(int i=1;i<=n;i++) { if(flag[i]==-1) { mp.clear(); mx=0; tn=0; dfs(i); ans+=(tn-mx); } } cout << ans << endl; return 0; } <file_sep>/LightOJ/1282 - Leading and Trailing.cpp #include<bits/stdc++.h> using namespace std; #define DB printf("*****\n") #define sf scanf #define pf printf #define ll long long int #define pii pair<int,int> #define inf 2147483647 #define maxn 104 ll bidmod(ll b,ll p) { ll ans=1; while(p>0) { if(p&1) { b%=1000000; ans=(ans*b)%1000; } b=(b*b)%1000; p>>=1; } return ans; } int main() { int tc; sf("%d",&tc); for (int qq=1; qq<=tc ; qq++ ) { ll n,k; sf("%lld %lld",&n,&k); double t=(double)k * log(n)/log(10); int te=(int) t; double a=pow(10,t-(double)te); int ans=ceil(a*100.0); if(ans>=999.99) {ans/=10.0;} pf("Case %d: %0.lf ",qq,ans); int b=bidmod(n,k); if(b<10) pf("00%d\n",b); else if(b<99) pf("0%d\n",b); else pf("%d\n",b); } return 0; } /* 5 1000000000 10000000 */ <file_sep>/Codeforces/B numbers/GSS1 - Can you answer these queries I v.2.cpp #include<bits/stdc++.h> using namespace std; vector<long long int>vt(50000+8); class node { public: long long int sum=0,left=0,right=0,best=0; }; node tree[4*50000]; void build(int id,int l,int r) { if(l==r) { tree[id].sum=tree[id].left=tree[id].right=tree[id].best=vt[l]; return ; } int mid=(l+r)/2; build(id*2,l,mid); build(id*2+1,mid+1,r); tree[id].sum=tree[id*2].sum+tree[id*2+1].sum; tree[id].left=max(tree[id*2].left, tree[id*2].sum+tree[id*2+1].left); tree[id].right=max(tree[id*2+1].right,tree[id*2+1].sum+tree[id*2].right); tree[id].best=max(tree[id*2].best,max(tree[id*2+1].best,tree[id*2].right+tree[id*2+1].left) ); } node query(int id,int l,int r,int ql,int qr) { if(l>qr || r<ql) { node a; a.sum=a.left=a.right=a.best=INT_MIN; return a; } if(l>=ql && r<=qr) return tree[id]; int mid=(l+r)/2; node ans,ll,rr; ll=query(id*2,l,mid,ql,qr); rr=query(id*2+1,mid+1,r,ql,qr); ans.sum=ll.sum+rr.sum; ans.left=max(ll.left,ll.sum+rr.left); ans.right=max(rr.right,rr.sum+ll.right); ans.best=max(ll.best,max(rr.best,ll.right+rr.left) ); return ans; } int main() { ios_base::sync_with_stdio(0); int n; cin >> n; for(int i=1;i<=n;i++) cin >> vt[i]; build(1,1,n); int m; cin >> m; while(m--) { int ql,qr; cin >> ql >> qr; long long int ans=query(1,1,n,ql,qr).best; if(ql==qr) ans=vt[ql]; cout << ans << '\n'; } return 0; } <file_sep>/USACO/Section 1.1/Broken Necklace.cpp /* ID:shishir10 LANG:C++ TASK:beads */ #include<bits/stdc++.h> using namespace std; int main() { freopen("beads.in","r",stdin); freopen("beads.out","w",stdout); int n; cin >> n; string str; cin >> str; str+=str; int mx=0; int f=1; for(int i=0;i<n;i++) { if(str[i]!='w') f=0; } if(f) { cout << n << endl; return 0; } // cout << str[5] << " " << str[6] << endl; for(int i=0;i<str.size() and i<n;i++) { if(str[i]=='b') { int rpaisi=0; int j; for(j=i+1;j<str.size();j++) { if(j==n+i){ // j--; break; } if(str[j]=='r') { rpaisi=1; } if(rpaisi==1 and str[j]=='b') { break; } } int cur=i; while(1&cur) { if(str[cur-1]!='w') { break; } cur--; } /* if(mx<j-cur+1) { cout << "b theke print hocce " << endl; cout << j << " " << cur << endl; cout << j-cur+1 << endl << endl; } */ mx=max(mx,j-cur); } else if(str[i]=='r') { int bpaisi=0; int j; for(j=i+1;j<str.size();j++) { if(j==n+i){ // j--; break; } if(str[j]=='b') { bpaisi=1; } if(bpaisi==1 and str[j]=='r') { break; } } int cur=i; while(1*cur) { if(str[cur-1]!='w') { break; } cur--; } /* if(mx<j-cur+1) { cout << "r theke print hocce " << endl; cout << j << " " << cur << endl; cout << j-cur+1 << endl << endl; } */ mx=max(mx,j-cur); } } cout << mx << endl; return 0; } <file_sep>/Contest/SPC Individual Contest 02 [18-03-2017]/E - PICK UP DROP ESCAPE.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int dp[25][25]; int rec(int ps,int cnt) { if(ps>=n) { if(cnt==k) return 0; return } } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; int a=5^1^3; cout << a << endl; cin >> tc; while(tc--) { int n,k; cin >> n >>k; int ara[n+8]; for(int i=0; i<n; i++) { cin >> ara[i]; } memset(dp,-1,sizeof dp); int ans=rec(0,0); } return 0; } /* 2 5 3 1 2 3 4 5 */ <file_sep>/LightOJ/1014 - Ifter Party.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; sf("%d",&tc); for(int qq=1 ; qq<=tc ; qq++ ) { ll p,l; sf("%lld %lld",&p,&l); vector<int>vt; int s=sqrt(p); int t=p-l; for(int i=1 ; i<=s ; i++ ) { if(t%i==0) { if(t/i>l) { vt.push_back(t/i); } if(i>l && t/i!=i) { vt.push_back(i); } } } sort(vt.begin(),vt.end()); if(vt.empty()) { pf("Case %d: impossible",qq); } else { pf("Case %d: %d",qq,vt[0]); for(int i=1 ; i<vt.size() ; i++ ) { pf(" %d",vt[i]); } } pf("\n"); } return 0; } /* 2147483648 */ <file_sep>/LightOJ/1110 - An Easy LCS.cpp #include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define DB printf("*****\n") #define ll long long int #define pii pair<int,int> #define fs first #define sc second #define inf 2147483647.0 #define eps 1e-12 #define maxn 1000007 string str1,str2; int dp[107][107],n,m,t; vector<string>vt; string sto[107][107]; int rec(int i,int j,string str) { if(i>=m || j>=n) return 0; int &ret=dp[i][j]; if(ret!=-1) return ret; if(str1[i]==str2[j]) { sto[i][j]=sto[i-1][j-1]+str1[i]; ret=1+rec(i+1,j+1,sto[i-1][j-1]+str1[i]); } else { ret=max(rec(i+1,j),rec(i,j+1)); } return ret; } string ss; void all(int i,int j) { if(i>=m || j>=n) { if(ss.size()==t) vt.push_back(ss); return; } if(str1[i]==str2[j]) { ss+=str1[i]; all(i+1,j+1); ss.erase(ss.end()-1); } else if(dp[i+1][j]>dp[i][j+1]) { all(i+1,j); } else if(dp[i+1][j]<dp[i][j+1]) { all(i,j+1); } else { all(i+1,j); all(i,j+1); } } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int tc; sf("%d",&tc); for(int qq=1 ;qq<=tc ;qq++ ) { cin >> str1 >> str2; m=str1.size(),n=str2.size(); memset(dp,-1,sizeof dp); t=rec(0,0); if(t==0) { pf("Case %d: :(\n",qq); } else { vt.clear(); ss.clear(); all(0,0); sort(vt.begin(),vt.end()); pf("Case %d: ",qq); cout << vt[0] << '\n'; } } return 0; } /* */ <file_sep>/USACO/Section 1.2/Transformations.cpp /* ID:shishir10 LANG:C++ TASK:transform */ #include<bits/stdc++.h> using namespace std; int n; vector<string> rotat(vector<string>temp) { vector<string> tt=temp; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { tt[i][j]=temp[j][n-i-1]; } } return tt; } vector<string> reff(vector<string>temp) { vector<string> tt; for(int i=0;i<n;i++) { reverse(temp[i].begin(),temp[i].end()); tt.push_back( temp[i] ); } return tt; } int main() { freopen("transform.in","r",stdin); freopen("transform.out","w",stdout); cin >> n; vector<string>before,after; // cout << "n " << n << endl; for(int i=0;i<n;i++) { string t; cin >> t; before.push_back(t); } for(int i=0;i<n;i++) { string t; cin >> t; after.push_back(t); } if(before==rotat(after)) { cout << 1 << '\n'; } else if(before==rotat(rotat(after))) { cout << 2 << '\n'; } else if(before==rotat(rotat(rotat(after)))) { cout << 3 << '\n'; } else if(before==reff(after)) { cout << 4 << '\n'; } else if( before== reff(rotat(after)) or before== reff(rotat(rotat(after))) or before==reff(rotat(rotat(rotat(after)))) ) { cout << 5 << '\n'; } else if(before==after) { cout << 6 << '\n'; } else { cout << 7 << '\n'; } return 0; }
0a4bac7a61ebb61c495c0cdb1da0054a764a4d74
[ "C", "Python", "C++" ]
396
C++
shishir-roy/competitive-programming-master
b598996ac9da07ab2d09c904eefdda9274ce20ad
cb631523949d653d55f498aebc28a041fc6f5ace
refs/heads/master
<file_sep><!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]--> <title>Vanity</title> <meta name="keywords" content="" /> <meta name="description" content="" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript" src="js/vanity.js"></script> <link rel="stylesheet" href="css/style.css" type="text/css" media="screen, projection" /> <!--[if lte IE 6]><link rel="stylesheet" href="css/style_ie.css" type="text/css" media="screen, projection" /><![endif]--> <meta name="viewport" content="width=device-width, initial-scale=1"/> </head> <body> <div id="wrapper"> <header class="welcome"> <a href="#" onclick="learnAbout()"><img src="images/logo.png" alt="Vanity logo" title="Vanity the game" /></a> <h1>Are you dying to look good?</h1> </header> <section id="middle"> <div id="container"> <div id="content"> <!-- INTRO --> <div data-role="page" id="intro"> <section class="welcome"> <!-- welcome screen --> <p>Welcome to the glitzy world of VANITY!</p> <p>You may just be a nobody actor trying to make it to the big time right now, but the future is yours to decide. The road is a long one: You’ll need to go to casting calls to land some gigs and earn bigger and bigger roles to build up you reputation in Hollywood and reach Superstardom!</p> <p>But to get those gigs, you’ll need to put in some hard work! You’ll need to maintain your <em>FITNESS</em> at the gym, make sure you’re sufficiently <em>TAN</em> to appear healthy, and always be mindful of your <em>STYLE</em>.</p> <p><em><strong>FITNESS, TAN, and STYLE</strong></em> - Just keep these 3 things in mind, and you’ll own the silver screen in no time! </p> <p>First things first, are you a male or female aspiring actor?</p> <!-- <div id="enterName"> <input class="field" type="text" name="playerName" /> <a class="button" onclick="chooseGender()"><img src="images/button_play.svg" alt="Play button" title="Play" /></a> </div> --> <a class="button" onclick="startGameAsMale()"><img src="images/button_male.svg" alt="Male" /></a> <a class="button" onclick="startGameAsFemale()"><img src="images/button_female.svg" alt="Female" /></a> </section> </div> <!-- CHOOSE GENDER --> <div data-role="page" id="chooseGender"> <h1>What's your gender?</h1> <a class="button" onclick="startGameAsMale()"><img src="images/button_male.svg" alt="Male" /></a> <a class="button" onclick="startGameAsFemale()"><img src="images/button_female.svg" alt="Female" /></a> </div> <!-- HOME --> <div data-role="page" id="gameHome"> <!-- #header--> <section class="gameHome"> <h1>Select what you would like to do now.</h1> <article class="progress"> <a href="#" onclick="getFitness()"><img src="images/fitness_button.png" alt="fitness" title="fitness" /></a> <div class="bar fitness"> <div class="amount"></div> </div> </article> <article class="progress"> <a href="#" onclick="getTan()"><img src="images/tan_button.png" alt="tan" title="tan" /></a> <div class="bar tan"> <div class="amount"></div> </div> </article> <article class="progress"> <a href="#" onclick="getStyle()"><img src="images/style_button.png" alt="style" title="style" /> </a> <div class="bar style"> <div class="amount"></div> </div> </article> <footer> <!-- <a href="#" onclick="learnAbout()"><img class="logo" src="images/logo.png" alt="Vanity logo" title="Vanity the game" /></a> --> <a href="#" onclick="castingCall()"><img class="casting_call" src="images/casting_call.png" alt="casting call" title="casting call" /></a> <a href="#" onclick="doctorsOffice()"><img class="doctor" src="images/doctor_button.png" alt="doctor" title="doctor" /></a> </footer> </section> </div> <!-- MAKE PROGRESS --> <div data-role="page" id="makeProgress"> <section class="makeProgress"> <article class="progress"> <img src="images/style.png" alt="progress" title="progress" /> <div class="bar"> <div class="amount"></div> </div> <!-- need something to show increase, like animated arrow elongating --> </article> <article class="activity"> <p class="activityDesc" id="activityDescription"></p> <img src="images/activity.png" alt="activity" title="activity" id="activityImage" /> <a class="button" onclick="progressResultReceived()"><img src="images/button_ok.svg" alt="ok" /></a> </article> </section> </div> <!-- CHOOSE TAN --> <div data-role="page" id="chooseTan"> <section class="chooseTan"> <article class="progress"> <img src="images/tan.png" alt="tan" title="tan" /> <div class="bar tan"> <div class="amount"></div> </div> </article> <article class="activity"> <p>How would you like to get your tan on?</p> <section class="options"> <a class="button" onclick="getNaturalTan()"><img src="images/naturalTan.svg" alt="natural tan" /></a> <a class="button" onclick="getTanningBed()"><img src="images/tanningBed.svg" alt="tanning bed" /></a> </section> </article> </section> </div> <!-- SKIN EXAM --> <div data-role="page" id="skinExam"> <section class="skinExam"> <article class="activity"> <h2>Skin Exam</h2> <p>The doctor conducts a skin exam and discovers a concerning mole... What do you want to do?</p> <input class="button" type="submit" name="Remove" value="Remove mole (Requires time off to heal.)" onclick="removeMole()"/> <input class="button" onclick="noExam()" type="submit" name="Home" value="Head home (I'm not worried about it.)" /> </article> </section> </div> <div data-role="page" id="removeMole"> <section class="removeMole"> <article class="activity"> <h2>Good decision!</h2> <p>This time, the mole removed by the doctor turned out not to be cancerous.</p> <img src="images/doctor.png" alt="doctor" title="doctor" /> <a class="button" onclick="removedMole()"><img src="images/button_ok.svg" alt="ok" /></a> </article> </section> </div> <!-- STATUS --> <div data-role="page" id="fameStatus"> <section class="fameStatus"> <article class="activity"> <h2>You're a nobody...</h2> <p>So you're just a nobody, but you're far from being a somebody on the A List. Book a commercial and you may just make it to the D List.</p> <img class="fameStatus" src="images/status_nobody.png" alt="D List" title="D List" /> <div class="player"> <!--<div class="tan"><img src="images/male_tan_0.png"></div>--> <!-- <div class="avatar"><img src="images/male_style0_buff0.png"></div> --> </div> <a class="button" onclick="sawStatus()"><img src="images/button_ok.svg" alt="Status" /></a> <!-- figure out another image to put here --> </article> </section> </div> <!-- CASTING CALL --> <div data-role="page" id="castingCall"> <section class="castingCall"> <article class="activity"> <h2>Casting Call</h2> <p>Which one of these do you want to audition for?</p> <section class="options"> <a class="button" onclick="auditionForCommercial()"><img src="images/commercial.svg" alt="Commercial" /></a> <a class="button" onclick="auditionForIndie()"><img src="images/indie.svg" alt="Indie" /></a> <a class="button" onclick="auditionForBlockbuster()"><img src="images/blockbuster.svg" alt="Blockbuster" /></a> <a class="button" onclick="dontAudition()"><img src="images/casting_none.svg" alt="No Audition" /></a> </article> </section> </div> <!-- CASTING CALL RESULT --> <div data-role="page" id="castingCallResult"> <section class="castingCallResult"> <article class="activity"> <h2 id="castingResultHeader"></h2> <p id="castingResult"></p> <div id="auditioning"/> <img id="auditionImage" src="images/nope.png" alt="Casting Call Result" title="Casting Call Result" /> <img id="failedAudition" src="images/castingFail.svg" alt="Failed Attempt" title="Failed Attempt" style="display:none"/> </div> <a class="button" onclick="castingResultReceived()"><img src="images/button_ok.svg" alt="ok" /></a> </article> </section> </div> <!-- ABOUT --> <div data-role="page" id="about"> <section class="about"> <article class="activity"> <p>Vanity has been developed to help people like you take a serious look at the dangers of using tanning beds.</p> <p>Vanity takes you through the process of moving from hopeful to A-list mega-star - but you'll have to figure out how to get there with the right combination of work at the gym, trips to hairdressers, salons, and spas, and developing the body that will get you the big roles.</p> <p>Vanity is a collaborative effort between the University of Ottawa’s Division of Dermatology, University of Miami’s Department of Cinema and Interactive Media, and the Canadian Dermatology Association (CDA). It is part of the CDA’s 2013 May “Melanoma Awareness” Month Campaign.</p> <h2>Credits</h2> <ul> <li> Dr. <NAME>, MD CCFP(EM) FRCPSC FAAD: medical lead and advisor; University of Ottawa, Division of Dermatology </li> <li> <NAME>, MPH: public health content expert and game development: University of Ottawa, Faculty of Medicine </li> <li> <NAME>: lead game design and programming; University of Miami </li> <li><NAME>: lead game design and user interface; University of Miami </li> <li> <NAME>: illustrator </li> <li> HyperActive Productions Inc.: project implementation and coordination </li> <li> Canadian Dermatology Association: primary sponsor </li> <li> Mach-Gaensslen Foundation of Canada: sponsor </li> <a class="button" onclick="enoughAbout()"><img src="images/button_ok.svg" alt="ok" /></a> </article> </section> </div> <!-- OBITUARY --> <div data-role="page" id="final"> <section class="final"> <article class="activity"> <!-- <h2>Obituary</h2>--> <p>You were loved.... but were a failed actor.</p> <section class="options final"> <div> <a href="https://www.facebook.com/sharer/sharer.php?u=vanity.dataplayed.com" target="_blank"><img src="images/facebookShare.gif" alt="ok" /></a> </div> <div> <a href="https://twitter.com/share" class="twitter-share-button" data-text="Can you make the A List? http://vanity.dataplayed.com" data-size="large" data-count="none">Tweet</a> </div> </section> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <a class="button playAgain" onclick="playAgain()"><img src="images/playAgain.svg" alt="play again" /></a> </article> </section> </div> </div><!-- #content--> </div><!-- #container--> <aside id="sideLeft"> </aside><!-- #sideLeft --> <aside id="sideRight"> </aside><!-- #sideRight --> </section><!-- #middle--> <footer id="footer"> </footer><!-- #footer --> </div><!-- #wrapper --> </body> </html><file_sep>/* Vanity JS */ var player = { name:"", fitness:0, style:0, tan:0, moles: [], vanity: 0, daysLeft: 50, gender: "male", image: "male_style0_buff0.png", timeSince: { fitness: 0, style: 0, tan: 0 }, fameIndex: 0, }; var atrophy = { fitness: 3, style: 3, tan: 3 } var characters = { levels: { fitness: [0, 6, 10], style: [0,6,10], tan: [0,3,10,15] }, tan: ["male_tan_0.png", "male_tan_1.png", "male_tan_2.png", "male_tan_3.png"], male: { standard: "male_style0_buff0.png", buff: "male_style0_buff1.png", ripped: "male_style0_buff2.png", fashionable: "male_style1_buff0.png", stylish: "male_style2_buff0.png", buffAndFashionable: "male_style1_buff1.png", rippedAndFashionable: "male_style1_buff2.png", stylishAndBuff: "male_style2_buff1.png", rippedAndStylish: "male_style2_buff2.png" }, female: { standard: "female_style0_buff0.png", buff: "female_style0_buff1.png", ripped: "female_style0_buff2.png", fashionable: "female_style1_buff0.png", stylish: "female_style2_buff0.png", buffAndFashionable: "female_style1_buff1.png", rippedAndFashionable: "female_style1_buff2.png", stylishAndBuff: "female_style2_buff1.png", rippedAndStylish: "female_style2_buff2.png" } } var activities = { baseline: 10, male: { fitness: {attributes: [{image: "fitness_activity_m_0.png", caption: "A drill sargeant will make sure to give you that six pack!"}, {image: "fitness_activity_m_1.png", caption: "Those biceps are looking good!"}, {image: "fitness_activity_m_2.png", caption: "That five mile run really got your heart racing!"}, {image: "fitness_activity_m_3.png", caption: "A couple of hours on the treadmill will definitely get you looking good."}, {image: "fitness_activity_m_4.png", caption: "Lifting at the gym, there's no quicker way to good fitness."} ], baseline: 2, variance: 7}, style: {attributes: [{image: "style_activity_m_0.png", caption: "Nice watch! That's sure to impress someone."}, {image: "style_activity_m_1.png", caption: "It took all day, but you found the perfect cologne!"}, {image: "style_activity_m_2.png", caption: "Nothing like a new hairdo to reinvent yourself."}, ], baseline: 2, variance: 8}, natural: {attributes: [{image: "natural_tan_activity_m_0.png", caption:"Running on the beach, that's a way one way to get a tan."}, {image: "natural_tan_activity_m_1.png", caption: "The breeze on the roof was perfect for sunbathing today."}, {image: "natural_tan_activity_m_2.png", caption: "A day of yard work in you bathing suit left you a few shades darker."}, {image: "natural_tan_activity_m_3.png", caption: "Reading and sunbathing in the park- good job building your mind, too."}, {image: "natural_tan_activity_m_4.png", caption: "Swimming at the beach always leaves you tan and energized, too!"}, {image: "natural_tan_activity_m_5.png", caption: "You lounged by the pool all day. Good thing you didn’t fall asleep!"}, ], baseline: 2, variance: 5}, bed: {attributes: [{image: "tanning_bed_activity_m_0.png", caption: "That all day tanning bed coupon was a steal, and your skin looks radiant!"}, {image: "tanning_bed_activity_m_1.png", caption: "Shame the timer's up. Your positively glowing!"}, {image: "tanning_bed_activity_m_2.png", caption: "One catnap on the bed and you’ve got a nice, even tan."} ], baseline: 5, variance: 10} }, female: { fitness: {attributes: [{image: "fitness_activity_m_0.png", caption: "A drill sargeant will make sure to give you that six pack!"}, {image: "fitness_activity_m_1.png", caption: "Those biceps are looking good!"}, {image: "fitness_activity_m_2.png", caption: "That five mile run really got your heart racing!"}, {image: "fitness_activity_m_3.png", caption: "A couple of hours on the treadmill will definitely get you looking good."}, {image: "fitness_activity_m_4.png", caption: "Lifting at the gym, there's no quicker way to good fitness."} ], baseline: 2, variance: 7}, style: {attributes: [{image: "style_activity_f_0.png", caption: "That perm is going to look awesome!"}, {image: "style_activity_f_1.png", caption: "It took all day, but you found the perfect perfume!"}, {image: "style_activity_f_2.png", caption: "Nothing like a new hairdo to reinvent yourself."}, {image: "style_activity_f_3.png", caption: "Nothing like shopping for accessories to kick up your style!"}], baseline: 2, variance: 8}, natural: {attributes: [ {image: "natural_tan_activity_f_0.png", caption: "Running on the beach, that's one way to get a tan."}, {image: "natural_tan_activity_f_1.png", caption: "The breeze on the roof was perfect for sunbathing today."}, {image: "natural_tan_activity_f_2.png", caption: "A day of yard work in you bathing suit left you a few shades darker."}, {image: "natural_tan_activity_f_3.png", caption: "Reading and sunbathing in the park- good job building your mind, too."}, {image: "natural_tan_activity_f_4.png", caption: "Swimming at the beach always leaves you tan and energized, too!"}, {image: "natural_tan_activity_f_5.png", caption: "You lounged by the pool all day. Good thing you didn’t fall asleep!"} ], baseline: 2, variance: 5}, bed: {attributes: [{image: "tanning_bed_activity_f_0.png", caption: "That all day tanning bed coupon was a steal, and your skin looks radiant!"}, {image: "tanning_bed_activity_f_1.png", caption: "Shame the timer's up. Your positively glowing!"}, {image: "tanning_bed_activity_f_2.png", caption: "One catnap on the bed and you’ve got a nice, even tan."} ], baseline: 5, variance: 10} } } var auditions = { commercial: { male: { fail: [ {image: "audition_commercial_fail_0.png", caption: "Tough break kid, you didn’t get the gig."}, {image: "audition_commercial_fail_0.png", caption: "Bad luck, kid... keep at it and try again"}, {image: "audition_commercial_fail_0.png", caption: "Those are the breaks, kid. Back to the old grindstone, and try again."}, {image: "audition_commercial_fail_0.png", caption: "Sorry, kid. Work a little harder and try again."} ], success:[ {image: "audition_commercial_m_0.png", caption: "It may be a small gig, but you got the role in the ad. Slow and steady wins the race, kid. Keep it up."}, {image: "audition_commercial_m_1.png", caption: "Everyone will want to use Re-Clox’s new wristwatch thanks to you. Way to get you face out there, kid."}, {image: "audition_commercial_m_0.png", caption: "Fee-Fi-Fo-Fum Inc. wants to send you a year’s supply of their beanbag chairs. I guess they were desperate for someone to take this role, kid."}, {image: "audition_commercial_m_1.png", caption: "You’re going to be the face selling rubber duck for Quack-Pott Co. from now on. Congratulations, kid. I guess."} ], }, female: { fail: [ {image: "audition_commercial_fail_0.png", caption: "Tough break kid, you didn’t get the gig."}, {image: "audition_commercial_fail_0.png", caption: "Bad luck, kid... keep at it and try again"}, {image: "audition_commercial_fail_0.png", caption: "Those are the breaks, kid. Back to the old grindstone, and try again."}, {image: "audition_commercial_fail_0.png", caption: "Sorry, kid. Work a little harder and try again."} ], success:[ {image: "audition_commercial_f_0.png", caption: "It may be a small gig, but you got the role in the ad. Slow and steady wins the race, kid. Keep it up."}, {image: "audition_commercial_f_1.png", caption: "Everyone will want to use Re-Clox’s new wristwatch thanks to you. Way to get you face out there, kid."}, {image: "audition_commercial_f_0.png", caption: "Fee-Fi-Fo-Fum Inc. wants to send you a year’s supply of their beanbag chairs. I guess they were desperate for someone to take this role, kid."}, {image: "audition_commercial_f_1.png", caption: "You’re going to be the face selling rubber duck for Quack-Pott Co. from now on. Congratulations, kid. I guess."} ], }, style: 3, tan: 5, fitness: 3, vanity: 10, days: 4, variance: 4 }, indie: { male: { fail: [ {image: "audition_indie_fail_0.png", caption: "You may not have gotten this part, but don’t give up, kid."}, {image: "audition_indie_fail_1.png", caption: "You were too good for a movie about talking roaches stopping terrorists anyway."}, {image: "audition_indie_fail_2.png", caption: "Sorry, you didn’t get the part. I should have known to stay away from anything called ‘Bark-ula.’"}, {image: "audition_indie_fail_3.png", caption: "Hate to say it, kid, but you didn’t get that Feel-Good/Survival-Horror gig."} ], success: [ {image: "audition_indie_m_0.png", caption: "You scored the role, kid. You’re names really getting out there, now."}, {image: "audition_indie_m_1.png", caption: "I don’t know how you did it, but you managed to score a role in that Western/Sci-fi/Thriller/Rom-com. Keep it up, kid."}, {image: "audition_indie_m_0.png", caption: "I’m not sure how big ‘JFK: Space-Time Astronaut’ will be, but you got the role anyway. Good work."}, {image: "audition_indie_m_1.png", caption: "Good job, kid. You got the role where you save the day from the Chihuahuas from space. You’ll have a cult following in no time."} ] }, female: { fail: [ {image: "audition_indie_fail_0.png", caption: "You may not have gotten this part, but don’t give up, kid."}, {image: "audition_indie_fail_1.png", caption: "You were too good for a movie about talking roaches stopping terrorists anyway."}, {image: "audition_indie_fail_2.png", caption: "Sorry, you didn’t get the part. I should have known to stay away from anything called ‘Bark-ula.’"}, {image: "audition_indie_fail_3.png", caption: "Hate to say it, kid, but you didn’t get that Feel-Good/Survival-Horror gig."} ], success: [ {image: "audition_indie_f_0.png", caption: "You scored the role, kid. You’re names really getting out there, now."}, {image: "audition_indie_f_1.png", caption: "I don’t know how you did it, but you managed to score a role in that Western/Sci-fi/Thriller/Rom-com. Keep it up, kid."}, {image: "audition_indie_f_0.png", caption: "I’m not sure how big ‘JFK: Space-Time Astronaut’ will be, but you got the role anyway. Good work."}, {image: "audition_indie_f_1.png", caption: "Good job, kid. You got the role where you save the day from the Chihuahuas from space. You’ll have a cult following in no time."} ] }, style: 4, tan: 7, fitness: 6, vanity: 22, days: 6, variance: 5 }, blockbuster: { male: { fail: [ {image: "audition_blockbuster_fail_0.png", caption: "Don’t feel too bad, kid. These are the hard ones to get."}, {image: "audition_blockbuster_fail_0.png", caption: "They said you’re ‘just not what they’re looking for’ to star in ‘Metal Match.’"}, {image: "audition_blockbuster_fail_1.png", caption: "They didn’t think you were lead material for ‘Game Control.’"}, {image: "audition_blockbuster_fail_2.png", caption: "They decided someone else was better suited to lead in 'Behind the Badge: The True Faces of the Law.'"} ], success: [ {image: "audition_blockbuster_m_0.png", caption: "Way to land the lead role, kid. You’re reaching the big time, now."}, {image: "audition_blockbuster_m_1.png", caption: "You’re doing it, kid. You got the lead in ‘Lethal Death II.’ Great work."}, {image: "audition_blockbuster_m_0.png", caption: "‘Dino-Flight’ is definitely going to be a huge hit. Good thing that you got the lead. Keep at it, kid."}, {image: "audition_blockbuster_m_1.png", caption: "You’re going to be the next big sensation after people see you in ‘Sundown: The Illuminated.’ You did great, kid."} ] }, female: { fail: [ {image: "audition_blockbuster_fail_0.png", caption: "Don’t feel too bad, kid. These are the hard ones to get."}, {image: "audition_blockbuster_fail_0.png", caption: "They said you’re ‘just not what they’re looking for’ to star in ‘Metal Match.’"}, {image: "audition_blockbuster_fail_1.png", caption: "They didn’t think you were lead material for ‘Game Control.’"}, {image: "audition_blockbuster_fail_2.png", caption: "They decided someone else was better suited to lead in 'Behind the Badge: The True Faces of the Law.'"} ], success: [ {image: "audition_blockbuster_f_0.png", caption: "Way to land the lead role, kid. You’re reaching the big time, now."}, {image: "audition_blockbuster_f_1.png", caption: "You’re doing it, kid. You got the lead in ‘Lethal Death II.’ Great work."}, {image: "audition_blockbuster_f_0.png", caption: "‘Dino-Flight’ is definitely going to be a huge hit. Good thing that you got the lead. Keep at it, kid."}, {image: "audition_blockbuster_f_1.png", caption: "You’re going to be the next big sensation after people see you in ‘Sundown: The Illuminated.’ You did great, kid."} ] }, style: 7, tan: 9, fitness: 10, vanity: 50, days: 8, variance: 4 }, } var moles = { tanningBed: {amount: 4, modifier: 3}, natural: {amount: 2, modifier: 10}, baselineSeverity: 20, removalTime: 10, images: ["mole1.png", "mole2.png", "mole3.png", "mole4.png", "mole5.png", "mole6.png", "mole7.png", "mole8.png", "mole9.png", "mole10.png", "mole11.png", "mole12.png", "mole13.png", "mole14.png", "mole15.png", "mole16.png", "mole17.png", "mole18.png"] } var fame = [{amount: 0, status: "Nobody", image: "status_nobody.png", description: "Everyone has to start somewhere, right? Land your first role, and you’ll move up to the D-list."}, {amount: 10, status: "D Lister", image: "status_d.png", description: "So, you’ve been an extra or you’ve starred in a complete flop. Try for some more commercials and score an indie film role until you build up your rep to the C-list."}, {amount: 22, status: "C Lister", image: "status_c.png", description: "Okay, you’ve gotten a few small roles, and people are starting to recognize your face. Keep up the good work and try to score a role in a blockbuster, and you’ll make it to the B-list."}, {amount: 44, status: "B Lister", image: "status_b.png", description: "Great, you’re an accomplished actor, even if your name isn’t quite a household name yet. Solidify your fame with a few more blockbusters, and you’ll reach A-list Superstardom!"}, {amount: 50, status: "A Lister", image: "status_a.png", description: "You did it. You're a superstar!"} ]; var obituaries = [ { rank: "Nobody", text: "You never really did anything, you were a ghost." }, { rank: "D List", text: "Some shoddy extra work, but <span class='playerName'></span> never accomplished much.. not much at all." }, { rank: "C List", text: "Star of those commercials you love to fast forward through, <span class='playerName'></span> really could have been somebody." }, { rank: "B List", text: "An accomplished actor, but <span class='playerName'></span> never had that break out role. What a shame." }, { rank: "A List", text: "The world will always remember <span class='playerName'></span>..." }, ]; var melanomaObituary = "Focusing all of their attention on making it big, they sadly forgot about their health. If only they had avoided the tanning salon, perhaps another death from melanoma could have been prevented."; var tips = ["Get a tan", "Get some muscles"]; var tipPrefix = [" Maybe you should work on your ", " They said you needed more ", " I bet they wanted someone with more "]; var playing = false; var dead = false; var creditsAtTheEnd = false; var maxAttributes = 30; function playerAtrophy() { if (player.timeSince.fitness > atrophy.fitness) { if (player.fitness > 0) { player.fitness--; player.timeSince.fitness = 1; } } if (player.timeSince.style > atrophy.style) { if (player.style > 0) { player.style--; player.timeSince.style = 1; } } if (player.timeSince.tan > atrophy.tan) { if (player.tan > 0) { player.tan--; player.timeSince.tan = 1; } } } function getCurrentAvatar() { if (player.gender == "male") { var image = characters.male.standard; if (player.fitness > characters.levels.fitness[1]) { image = characters.male.buff; if (player.fitness > characters.levels.fitness[2]) { image = characters.male.ripped; if (player.style > characters.levels.style[1]) { image = characters.male.rippedAndFashionable; if (player.style > characters.levels.style[2]) { image = characters.male.rippedAndStylish; } } } else { if (player.style > characters.levels.style[1]) { image = characters.male.buffAndFashionable; if (player.style > characters.levels.style[2]) { image = characters.male.stylishAndBuff; } } } } else { if (player.style > characters.levels.style[1]) { image = characters.male.fashionable; if (player.style > characters.levels.style[2]) { image = characters.male.stylish; } } } return image; } else { var image = characters.female.standard; if (player.fitness > characters.levels.fitness[1]) { image = characters.female.buff; if (player.fitness > characters.levels.fitness[2]) { image = characters.female.ripped; if (player.style > characters.levels.style[1]) { image = characters.female.rippedAndFashionable; if (player.style > characters.levels.style[2]) { image = characters.female.rippedAndStylish; } } } else { if (player.style > characters.levels.style[1]) { image = characters.female.buffAndFashionable; if (player.style > characters.levels.style[2]) { image = characters.female.stylishAndBuff; } } } } else { if (player.style > characters.levels.style[1]) { image = characters.female.fashionable; if (player.style > characters.levels.style[2]) { image = characters.female.stylish; } } } return image; } } function getTan() { $('div#makeProgress article.progress div.bar .amount').css('width', $('div#makeProgress .progress div.bar').width() * (player.tan/maxAttributes)); $('div#chooseTan').show(); $('div#gameHome').hide(); } function getNaturalTan() { if (player.gender == "male") { var tan = getActivity(activities.male.natural); } if (player.gender == "female") { var tan = getActivity(activities.female.natural); } player.tan += tan.value; var numberOfMoles = randomInt(moles.natural.amount); for (var i = 0; i < numberOfMoles; i++) { var moleSeverity = randomInt(moles.baselineSeverity) + moles.natural.modifier; player.moles.push({turnsLeft: moleSeverity, age: 0}); mole(); } $('#activityDescription').html(tan.caption); $('#activityImage').attr('src', 'images/' + tan.image); $('div#makeProgress article.progress div.bar').addClass("tan"); $('div#makeProgress article.progress img').attr('src', 'images/tan.png'); $('div#chooseTan').hide(); $('div#makeProgress').show(); $('div#makeProgress article.progress div.bar .amount').animate({width:$('div#makeProgress .progress div.bar').width() * (player.tan/maxAttributes)}); $('div .bar.tan .amount').css('width', $('div#makeProgress .progress div.bar').width() * (player.tan/maxAttributes)); return tan.caption; } function getTanningBed() { $('div#makeProgress article.progress div.bar .amount').css('width', $('div#gameHome article.progress div.bar.tan .amount').width()); player.timeSince.fitness++; player.timeSince.style++; if (player.gender == "male") { var tan = getActivity(activities.male.bed); } else { var tan = getActivity(activities.female.bed); } player.tan += tan.value; var numberOfMoles = randomInt(moles.tanningBed.amount); for (var i = 0; i < numberOfMoles; i++) { var moleSeverity = randomInt(moles.baselineSeverity) + moles.tanningBed.modifier; player.moles.push({turnsLeft: moleSeverity, age: 0}); mole(); } $('#activityDescription').html(tan.caption); $('#activityImage').attr('src', 'images/' + tan.image); $('div#makeProgress article.progress div.bar').addClass("tan"); $('div#makeProgress article.progress img').attr('src', 'images/tan.png'); $('div#chooseTan').hide(); $('div#makeProgress').show(); $('div#makeProgress article.progress div.bar .amount').animate({width:$('div#makeProgress .progress div.bar').width() * (player.tan/maxAttributes)}); $('div .bar.tan .amount').css('width', $('div#makeProgress .progress div.bar').width() * (player.tan/maxAttributes)); return tan.caption; } function getStyle() { $('div#makeProgress article.progress div.bar .amount').css('width', $('div#gameHome article.progress div.bar.style .amount').width()); player.timeSince.fitness++; player.timeSince.tan++; if (player.gender == "male") { var style = getActivity(activities.male.style); } else { var style = getActivity(activities.female.style); } player.style += style.value; $('#activityDescription').html(style.caption); $('#activityImage').attr('src', 'images/' + style.image); $('div#makeProgress article.progress div.bar').addClass("style"); $('div#makeProgress article.progress img').attr('src', 'images/style.png'); $('div#gameHome').hide(); $('div#makeProgress').show(); $('div#makeProgress article.progress div.bar .amount').animate({width:$('div#makeProgress .progress div.bar').width() * (player.style/maxAttributes)}); $('div#gameHome article.progress div.bar.style .amount').css('width', $('div#makeProgress .progress div.bar').width() * (player.style/maxAttributes)); return style.caption; } function getFitness() { $('div#makeProgress article.progress div.bar .amount').css('width', $('div#gameHome article.progress div.bar.fitness .amount').width()); player.timeSince.style++; player.timeSince.tan++; if (player.gender == "male") { var fitness = getActivity(activities.male.fitness); } else { var fitness = getActivity(activities.female.fitness); } player.fitness += fitness.value; $('#activityDescription').html(fitness.caption); $('#activityImage').attr('src', 'images/' + fitness.image); $('div#makeProgress article.progress div.bar').addClass("fitness"); $('div#makeProgress article.progress img').attr('src', 'images/fitness.png'); $('div#gameHome').hide(); $('div#makeProgress').show(); $('div#makeProgress article.progress div.bar .amount').animate({width:$('div#makeProgress .progress div.bar').width() * (player.fitness/maxAttributes)}); $('div#gameHome article.progress div.bar.fitness .amount').css('width', $('div#makeProgress .progress div.bar').width() * (player.fitness/maxAttributes)); return fitness.caption; } function getActivity(activity) { var earned = randomInt(activity.baseline)+randomInt(activity.variance); var selectedIndex = randomInt(activity.attributes.length); var action = activity.attributes[selectedIndex]; player.daysLeft--; if (player.daysLeft < 0) { player.daysLeft = 0; } $('#daysLeft').html(player.daysLeft); return {value: earned, caption: action.caption, image: action.image, index: selectedIndex} } function getCurrentTan() { if (player.tan > characters.levels.tan[0]) { if (player.tan > characters.levels.tan[1]) { if (player.tan > characters.levels.tan[2]) { if (player.tan > characters.levels.tan[3]) { return characters.tan[3]; } else { return characters.tan[2]; } } else { return characters.tan[2]; } } else { return characters.tan[1]; } } else { return characters.tan[0]; } } function randomInt(range) { return Math.floor(Math.random()*range); } function removeMole() { player.daysLeft -= moles.removalTime; if (player.daysLeft < 0) { player.daysLeft = 0; } $('#daysLeft').html(player.daysLeft); var moleToRemove = randomInt(player.moles.length); player.moles.splice(moleToRemove,1); $('#moles').children().eq(moleToRemove).remove(); $('div#skinExam').hide(); $('div#removeMole').show(); } function removedMole() { $('div#removeMole').hide(); if(dayPassedDidIDie()) { obituary(); } else { $('div#gameHome').show(); } } function castingCall() { $('div#castingCall').show(); $('div#gameHome').hide(); } function audition(call) { player.timeSince.fitness++; player.timeSince.tan++; player.timeSince.style++; var requiredTan = call.tan + randomInt(call.variance); var requiredStyle = call.style + randomInt(call.variance); var requiredFitness = call.fitness + randomInt(call.variance); if (player.fitness >= requiredFitness && player.style >= requiredStyle && player.tan >= requiredTan) { player.vanity += call.vanity; $('img#failedAudition').hide(); if (player.gender == "male") { var selectedHeader = randomInt(call.male.success.length); $("div#castingResultHeader").html(call.male.success[selectedHeader]); return {success: true}; } else { var selectedHeader = randomInt(call.female.success.length); $("div#castingResultHeader").html(call.female.success[selectedHeader]); return {success: true}; } } else { $('img#failedAudition').show(); //TODO: Show Fail SVG if (player.gender == "male") { var selectedHeader = randomInt(call.male.success.length); $("div#castingResultHeader").html(call.male.success[selectedHeader]); } else { var selectedHeader = randomInt(call.female.success.length); $("div#castingResultHeader").html(call.female.success[selectedHeader]); } var attributesNeeded = []; if (player.tan < requiredTan) { attributesNeeded.push("tan"); } if (player.fitness < requiredFitness) { attributesNeeded.push("fitness"); } if (player.style < requiredStyle) { attributesNeeded.push("style"); } return {success:false, attributes: attributesNeeded}; } } function getTip(call, result) { var tipIndex = randomInt(tipPrefix.length); selectedIndex = randomInt(call.fail.length); if (result.attributes.length == 1) { return call.fail[selectedIndex].caption + tipPrefix[tipIndex] + result.attributes[0] + "."; } if (result.attributes.length == 2) { return call.fail[selectedIndex].caption + tipPrefix[tipIndex] + result.attributes[0] + " and " + result.attributes[1] + "."; } if (result.attributes.length == 3) { return call.fail[selectedIndex].caption + tipPrefix[tipIndex] + result.attributes[0] + ", " + result.attributes[1] + " and " + result.attributes[2] + "."; } } function auditionForIndie() { var result = audition(auditions.indie); player.daysLeft -= auditions.indie.days; getFameStatus(); if (player.daysLeft < 0) { player.daysLeft = 0; } $('#daysLeft').html(player.daysLeft); var selectedIndex; if (result.success) { if (player.gender == "male") { selectedIndex = randomInt(auditions.indie.male.success.length); $('p#castingResult').html(auditions.indie.male.success[selectedIndex].caption); $('img#auditionImage').attr('src', 'images/' + auditions.indie.male.success[selectedIndex].image); } else { selectedIndex = randomInt(auditions.indie.female.success.length); $('p#castingResult').html(auditions.indie.female.success[selectedIndex].caption); $('img#auditionImage').attr('src', 'images/' + auditions.indie.female.success[selectedIndex].image); } } else { //TODO: Fail SVG if (player.gender == "male") { selectedIndex = randomInt(auditions.indie.female.success.length); $('p#castingResult').html(getTip(auditions.indie.male, result)); $('img#auditionImage').attr('src', 'images/' + auditions.indie.male.success[selectedIndex].image); } else { selectedIndex = randomInt(auditions.indie.female.success.length); $('p#castingResult').html(getTip(auditions.indie.female, result)); $('img#auditionImage').attr('src', 'images/' + auditions.indie.female.success[selectedIndex].image); } } showAudition(); } function auditionForCommercial() { var result = audition(auditions.commercial); player.daysLeft -= auditions.commercial.days; if (player.daysLeft < 0) { player.daysLeft = 0; } $('#daysLeft').html(player.daysLeft); getFameStatus(); var selectedIndex; if (result.success) { if (player.gender == "male") { selectedIndex = randomInt(auditions.commercial.male.success.length); $('p#castingResult').html(auditions.commercial.male.success[selectedIndex].caption); $('img#auditionImage').attr('src', 'images/' + auditions.commercial.male.success[selectedIndex].image); } else { selectedIndex = randomInt(auditions.commercial.female.success[selectedIndex].length); $('p#castingResult').html(auditions.commercial.female.success[selectedIndex].caption); $('img#auditionImage').attr('src', 'images/' + auditions.commercial.female.success[selectedIndex].image); } } else { if (player.gender == "male") { selectedIndex = randomInt(auditions.commercial.male.success.length); $('p#castingResult').html(getTip(auditions.commercial.male, result)); $('img#auditionImage').attr('src', 'images/' + auditions.commercial.male.success[selectedIndex].image); } else { selectedIndex = randomInt(auditions.commercial.female.success.length); $('p#castingResult').html(getTip(auditions.commercial.female, result)); $('img#auditionImage').attr('src', 'images/' + auditions.commercial.female.success[selectedIndex].image); } } showAudition(); } function auditionForBlockbuster() { var result = audition(auditions.blockbuster); player.daysLeft -= auditions.blockbuster.days; getFameStatus(); if (player.daysLeft <= 0) { player.daysLeft = 0; } $('#daysLeft').html(player.daysLeft); var selectedIndex; if (result.success) { if (player.gender == "male") { selectedIndex = randomInt(auditions.blockbuster.male.success.length); $('p#castingResult').html(auditions.blockbuster.male.success[selectedIndex].caption); $('img#auditionImage').attr('src', 'images/' + auditions.blockbuster.male.success[selectedIndex].image); } else { selectedIndex = randomInt(auditions.blockbuster.female.success.length); $('p#castingResult').html(auditions.blockbuster.female.success[selectedIndex]); $('img#auditionImage').attr('src', 'images/' + auditions.blockbuster.female.success[selectedIndex].image); } } else { //TODO: Fail SVG if (player.gender =="male") { selectedIndex = randomInt(auditions.commercial.male.success.length); $('p#castingResult').html(getTip(auditions.commercial.male, result)); $('img#auditionImage').attr('src', 'images/' + auditions.commercial.male.success[selectedIndex].image); } else { selectedIndex = randomInt(auditions.blockbuster.female.success.length); $('p#castingResult').html(getTip(auditions.blockbuster.female, result)); $('img#auditionImage').attr('src', 'images/' + auditions.blockbuster.female.success[selectedIndex].image); } } showAudition(); } function castingResultReceived() { playerAtrophy(); getFameStatus(); $('div#castingCallResult').hide(); if(dayPassedDidIDie()) { obituary(); } else { $('div#gameHome').show(); } } function progressResultReceived() { getFameStatus(); $('div#makeProgress article.progress div.bar .amount').css('width', 0); $('div#makeProgress').hide(); if(dayPassedDidIDie()) { obituary(); } else { playerAtrophy(); $('div#gameHome').show(); $('div#makeProgress article.progress div.bar').attr('class', 'bar'); } } function showAudition() { $('div#castingCall').hide(); $('div#castingCallResult').show(); } function dontAudition() { $('div#castingCall').hide(); $('div#gameHome').show(); } function noExam() { $('div#skinExam').hide(); $('div#gameHome').show(); } function getFameStatus() { var statusImg = $('img#status'); var avatar = $('.player .avatar img'); var avatarTan = $('.player .tan img'); avatar.attr('src', 'images/' + getCurrentAvatar()); avatarTan.attr('src', 'images/' + getCurrentTan()); for (var i = 0; i < fame.length; i++) { if (player.vanity >= fame[i].amount) { fameIndex = i; statusImg.attr("src", "images/" + fame[i].image); statusImg.attr("alt", fame[i].status); statusImg.attr("title", fame[i].status); player.fameIndex = i; if (i == fame.length -1) { // dead = true; } } } $('#fameStatus p').html(fame[player.fameIndex].description); } function dayPassedDidIDie() { if (player.daysLeft <= 0) { daysLeft = 0; return true; } var melanoma = false; for (var i = 0; i < player.moles.length; i++) { player.moles[i].age++; if (player.moles[i].turnsLeft - player.moles[i].age <= 0) { melanoma = true; dead = true; } } return melanoma; } function chooseGender() { $('div#intro').hide(); $('div#chooseGender').show(); } function startGameAsMale() { player.gender = "male"; startGame(); } function startGameAsFemale() { player.gender = "female"; startGame(); } function startGame() { $('#intro').hide(); playing = true; // $('div#chooseGender').hide(); player.name = $("input[name=playerName]").val(); var headerHTML = "<a onclick='getStatus()'><div class='player'><div class='tan'><img src=''></div><div class='avatar'><img src=''></div></div></a><a href='#'' onclick='learnAbout()'><img src='images/logo.png' alt='Vanity logo' title='Vanity the game'/></a><h1>You've got <span id='daysLeft'>"+player.daysLeft+"</span> Days to get famous!</h1><div id='moles'></div>"; $('header.welcome').html(headerHTML); getFameStatus(); $('div#gameHome').show(); } function doctorsOffice() { $('div#gameHome').hide(); $('div#skinExam').show(); } function getStatus() { if (playing) { getFameStatus(); $('div#fameStatus h2').html(fame[player.fameIndex].status); $('div#gameHome').hide(); $('div#intro').hide(); $('div#final').hide(); $('div#castingCall').hide(); $('div#castingCallResult').hide(); $('div#skinExam').hide(); $('div#makeProgress').hide(); $('div#chooseTan').hide(); $('div#about').hide(); $('div#fameStatus').show(); } } function sawStatus() { $('div#fameStatus').hide(); $('div#gameHome').show(); } function mole() { var mNum = randomInt(moles.images.length); var newMole = $('#moles').append("<div class='mole'><img src='images/"+moles.images[mNum]+"'/></div>"); newMole.children(".mole").last().css({ position: 'absolute', left: randomInt(newMole.width()), top: randomInt(newMole.height()) }); } function obituary() { playing = false; creditsAtTheEnd = true; if (dead) { $("header.welcome h1").html("You died from melanoma: too much tanning"); $("#final p").html(melanomaObituary); } else { $("header.welcome h1").html("Time's up!"); $("#final p").html(obituaries[player.fameIndex].text); } $("#final .playerName").html(player.name); $('div#gameHome').hide(); $('div#castingCall').hide(); $('div#castingCallResult').hide(); $('div#final').show(); } function learnAbout() { $('div#intro').hide(); $('div#gameHome').hide(); $('div#final').hide(); $('div#castingCall').hide(); $('div#castingCallResult').hide(); $('div#skinExam').hide(); $('div#makeProgress').hide(); $('div#chooseTan').hide(); $('div#fameStatus').hide(); $('div#about').show(); } function enoughAbout() { $('div#about').hide(); if (playing) { $('div#gameHome').show(); } else { if (creditsAtTheEnd) { $('div#final').show(); } else { $('div#intro').show(); } } } function playAgain() { player.fitness = 0; player.style = 0; player.tan = 0; player.moles = []; player.vanity = 0; player.daysLeft = 50; $('div#makeProgress article.progress div.bar .amount').animate({width:0}); $('.bar.tan .amount').css('width', 0); $('div#gameHome article.progress div.bar.fitness .amount').css('width', 0); $('div#gameHome article.progress div.bar.style .amount').css('width', 0); $('div#final').hide(); startGame(); }
3c1c37db9013ccdd9c4374349d7b2e9a219c8c19
[ "JavaScript", "HTML" ]
2
HTML
claytical/Vanity
aab9e7f58c2b65cd43f1b90c856c6322dd175d27
a6d74127cebf630675e9326ad97f90dab5b81af1
refs/heads/main
<repo_name>RiyazurRazak/STL_in_node_js<file_sep>/cpp/headers/snailsort.h #include "napi.h" #include "bits/stdc++.h" namespace snailsort { std::vector<int> sort(std::vector<std::vector<int>>); Napi::Object Init(Napi::Env env, Napi::Object exports); Napi::Value sortWrap(const Napi::CallbackInfo &info); }<file_sep>/cpp/src/queue/wrapper.cpp #include "../../headers/queue/wrapper.h" Napi::FunctionReference QueueWrapper::constructor; QueueWrapper::QueueWrapper(const Napi::CallbackInfo &info) : Napi::ObjectWrap<QueueWrapper>(info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); this->_queue = new Queue(); } void QueueWrapper::pushWrap(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); int value = info[0].As<Napi::Number>(); this->_queue->push(value); } Napi::Value QueueWrapper::popWrap(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); int value = this->_queue->pop(); return Napi::Number::New(env, value); } Napi::Object QueueWrapper::Init(Napi::Env env, Napi::Object exports) { Napi::HandleScope scope(env); Napi::Function func = DefineClass(env, "queue", { InstanceMethod("push", &QueueWrapper::pushWrap), InstanceMethod("pop", &QueueWrapper::popWrap), }); constructor = Napi::Persistent(func); constructor.SuppressDestruct(); exports.Set("queue", func); return exports; }<file_sep>/cpp/src/heap/wrapper.cpp #include "napi.h" #include "../../headers/heap/wrapper.h" #include "bits/stdc++.h" Napi::FunctionReference HeapWrapper::constructor; Napi::Object HeapWrapper::Init(Napi::Env env, Napi::Object exports) { Napi::HandleScope scope(env); Napi::Function func = DefineClass(env, "heap", { InstanceMethod("pop", &HeapWrapper::popWrap), }); constructor = Napi::Persistent(func); constructor.SuppressDestruct(); exports.Set("heap", func); return exports; } HeapWrapper::HeapWrapper(const Napi::CallbackInfo &info) : Napi::ObjectWrap<HeapWrapper>(info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); int length = info.Length(); if (length != 2 || !info[0].IsArray()) { Napi::TypeError::New(env, "Arguments Missing. (Array, String)").ThrowAsJavaScriptException(); } Napi::Array value = info[0].As<Napi::Array>(); std::string type = info[1].As<Napi::String>().ToString(); std::vector<int> ele; for (int i = 0; i < value.Length(); i++) { Napi::Value val = value[i]; ele.push_back((int)val.As<Napi::Number>()); } this->_heap = new Heap(ele, type); } Napi::Value HeapWrapper::popWrap(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); int min = this->_heap->pop(); return Napi::Number::New(env, min); }<file_sep>/cpp/headers/heap/heap.h #include "bits/stdc++.h" class Heap { std::priority_queue<int, std::vector<int>, std::greater<int>> _min; std::priority_queue<int, std::vector<int>, std::less<int>> _max; std::string _type = "min"; public: Heap(std::vector<int>, std::string); int pop(); };<file_sep>/README.md # Node Addons (DSA) ### Implementing STL using node addons. ### Usefull repo for beginners to understand node addons. ```bash yarn run build yarn run heap #for heap yarn run stack #for stack yarn run queue #for queue yarn run snailsort #for snail sort ``` # Data Structures - Stack - Queue - Heap (priority_queue) # Algorithms - Reverse a number - Snail Sort ## More DS and Algorithms updated soon. ### feel free to contribute. <file_sep>/cpp/src/reversenumber.cpp #include "../headers/reversenumber.h" long long reversenumber::Reverse(long long value) { long long reverseValue = 0; while (value != 0) { reverseValue = reverseValue * 10 + value % 10; value /= 10; } return reverseValue; } Napi::Value reversenumber::ReverseNumberWrap(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); long long input = info[0].As<Napi::Number>(); return Napi::Number::New(env, reversenumber::Reverse(input)); } Napi::Object reversenumber::Init(Napi::Env env, Napi::Object exports) { exports.Set("reversenumber", Napi::Function::New(env, reversenumber::ReverseNumberWrap)); return exports; }<file_sep>/js/Heap.js // import heap from addon const { heap } = require("../build/Release/dsaAddon.node"); // create random number of array with length 15 const input = Array.from({ length: 15 }, () => Math.floor(Math.random() * 1000) ); const minResult = []; const maxResult = []; /* initialize the heap class from cpp * @param {Array} - array of type number * @param {String} - "min" \ "max" */ // create two class instance from cpp one with min Heap and another with max heap const minHeap = new heap(input, "min"); const maxHeap = new heap(input, "max"); for (let i = 0; i < input.length; i++) { //remove the priority number from the heap minResult.push(minHeap.pop()); maxResult.push(maxHeap.pop()); } // log the sorted output console.table({ input: input, minimum: minResult, maximum: maxResult }); <file_sep>/cpp/headers/heap/wrapper.h #include "napi.h" #include "./heap.h" class HeapWrapper : public Napi::ObjectWrap<HeapWrapper> { public: static Napi::Object Init(Napi::Env env, Napi::Object exports); HeapWrapper(const Napi::CallbackInfo &info); private: static Napi::FunctionReference constructor; Napi::Value popWrap(const Napi::CallbackInfo &info); Heap *_heap; };<file_sep>/js/Queue.js // import Queue addon from cpp const { queue } = require("../build/Release/dsaAddon.node"); // input const input = [100, 65, 23, 09, 876]; const result = []; // initialize our Queue from js to cpp const Queue = new queue(); // load elements in the Queue for (let i = 0; i < input.length; i++) { Queue.push(input[i]); } // remove elements from the Queue (FIFO) for (let i = 0; i < input.length; i++) { result.push(Queue.pop()); } //log the result console.table({ input: input, result: result }); <file_sep>/js/SnailSort.js const { snailsort } = require("../build/Release/dsaAddon.node"); const input = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; console.log("input: ", input); /* * @param {Array} - [[Interger]] */ console.log("output: ", snailsort(input)); <file_sep>/cpp/src/queue/queue.cpp #include "../../headers/queue/queue.h" Queue::Queue(){}; void Queue::push(int value) { this->_queue.push(value); } int Queue::pop() { int value = this->_queue.front(); this->_queue.pop(); return value; }<file_sep>/cpp/src/snailsort.cpp #include "../headers/snailsort.h" using namespace std; std::vector<int> snailsort::sort(std::vector<std::vector<int>> input) { if (input.size() > 1) { std::vector<int> answers; for (int &ele : input[0]) { answers.push_back(ele); } input.erase(input.begin()); for (int i = 0; i < input.size(); i++) { answers.push_back(input[i].back()); input[i].pop_back(); } for (int i = input[input.size() - 1].size() - 1; i >= 0; i--) { answers.push_back(input[input.size() - 1][i]); } std::reverse(input.begin(), input.end()); input.erase(input.begin()); for (int i = 0; i < input.size(); i++) { answers.push_back(input[i].front()); input[i].erase(input[i].begin()); } if (input.size() > 0) { std::reverse(input.begin(), input.end()); std::vector<int> recursive = snailsort::sort(input); for (int &e : recursive) { answers.push_back(e); } } return answers; } else { return input[0]; } } Napi::Value snailsort::sortWrap(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); Napi::Array input = info[0].As<Napi::Array>(); int length = input.Length(); std::vector<std::vector<int>> vecInput; for (int i = 0; i < length; i++) { Napi::Value elements = input[i]; Napi::Array row = elements.As<Napi::Array>(); std::vector<int> vec; for (int j = 0; j < row.Length(); j++) { Napi::Value val = row[j]; vec.push_back((int)val.As<Napi::Number>()); } vecInput.push_back(vec); } std::vector<int> result = snailsort::sort(vecInput); Napi::Array val = Napi::Array::New(env, result.size()); for (int i = 0; i < result.size(); i++) { val[i] = result[i]; } return val; } Napi::Object snailsort::Init(Napi::Env env, Napi::Object exports) { exports.Set("snailsort", Napi::Function::New(env, snailsort::sortWrap)); return exports; }<file_sep>/cpp/headers/reversenumber.h #include "napi.h" namespace reversenumber { long long Reverse(long long); Napi::Object Init(Napi::Env env, Napi::Object exports); Napi::Value ReverseNumberWrap(const Napi::CallbackInfo &info); }<file_sep>/cpp/src/stack/wrapper.cpp #include "../../headers/stack/wrapper.h" Napi::FunctionReference StackWrapper::constructor; StackWrapper::StackWrapper(const Napi::CallbackInfo &info) : Napi::ObjectWrap<StackWrapper>(info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); this->_stack = new Stack(); } void StackWrapper::pushWrap(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); int value = info[0].As<Napi::Number>(); this->_stack->push(value); } Napi::Value StackWrapper::popWrap(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); Napi::HandleScope scope(env); int value = this->_stack->pop(); return Napi::Number::New(env, value); } Napi::Object StackWrapper::Init(Napi::Env env, Napi::Object exports) { Napi::HandleScope scope(env); Napi::Function func = DefineClass(env, "stack", { InstanceMethod("push", &StackWrapper::pushWrap), InstanceMethod("pop", &StackWrapper::popWrap), }); constructor = Napi::Persistent(func); constructor.SuppressDestruct(); exports.Set("stack", func); return exports; }<file_sep>/cpp/src/main.cpp #include <napi.h> #include "../headers/heap/wrapper.h" #include "../headers/stack/wrapper.h" #include "../headers/queue/wrapper.h" #include "../headers/reversenumber.h" #include "../headers/snailsort.h" Napi::Object InitAll(Napi::Env env, Napi::Object exports) { HeapWrapper::Init(env, exports); StackWrapper::Init(env, exports); QueueWrapper::Init(env, exports); reversenumber::Init(env, exports); snailsort::Init(env, exports); return exports; } NODE_API_MODULE(NODE_GYP_MODULE_NAME, InitAll)<file_sep>/cpp/headers/queue/wrapper.h #include "napi.h" #include "./queue.h" class QueueWrapper : public Napi::ObjectWrap<QueueWrapper> { static Napi::FunctionReference constructor; void pushWrap(const Napi::CallbackInfo &info); Napi::Value popWrap(const Napi::CallbackInfo &info); Queue *_queue; public: static Napi::Object Init(Napi::Env env, Napi::Object exports); QueueWrapper(const Napi::CallbackInfo &info); };<file_sep>/cpp/src/heap/heap.cpp #include "../../headers/heap/heap.h" Heap::Heap(std::vector<int> values, std::string type) { this->_type = type; if (type == "min") { for (int &ele : values) { this->_min.push(ele); } } else { for (int &ele : values) { this->_max.push(ele); } } } int Heap::pop() { if (this->_type == "min") { int val = Heap::_min.top(); this->_min.pop(); return val; } else { int val = Heap::_max.top(); this->_max.pop(); return val; } }<file_sep>/cpp/headers/queue/queue.h #include "bits/stdc++.h" class Queue { std::queue<int> _queue; public: Queue(); void push(int); int pop(); };<file_sep>/cpp/headers/stack/stack.h #include "bits/stdc++.h" class Stack { std::stack<int> _container; public: Stack(); void push(int); int pop(); };<file_sep>/cpp/headers/stack/wrapper.h #include "napi.h" #include "./stack.h" class StackWrapper : public Napi::ObjectWrap<StackWrapper> { static Napi::FunctionReference constructor; void pushWrap(const Napi::CallbackInfo &info); Napi::Value popWrap(const Napi::CallbackInfo &info); Stack *_stack; public: static Napi::Object Init(Napi::Env env, Napi::Object exports); StackWrapper(const Napi::CallbackInfo &info); };<file_sep>/cpp/src/stack/stack.cpp #include "../../headers/stack/stack.h" Stack::Stack(){}; void Stack::push(int value) { this->_container.push(value); } int Stack::pop() { int value = this->_container.top(); this->_container.pop(); return value; }
308ba14053b29aee3d27eb50befdc4570b8fbc67
[ "Markdown", "JavaScript", "C++" ]
21
C++
RiyazurRazak/STL_in_node_js
5e147e97acbb6d828f90b65e46337ca5b68d4ff7
d5376a1dcc5f9e2f1ad65a6de3675057ba1a115e
refs/heads/master
<file_sep>#include "Score.h" #include <cstdlib> using namespace std; using namespace sf; Score::Score() { WinW=1366; WinH=768; ScorePoints=0; //Fonts! Score_Font.loadFromFile("Data/Fonts/Sansation-BoldItalic.ttf"); font.loadFromFile("Data/Fonts/Leander.ttf"); vivaldi_Font.loadFromFile("Data/Fonts/vivaldi.ttf"); //Textures! Bonus10_Texture.loadFromFile("Data/Score/10.png"); Bonus15_Texture.loadFromFile("Data/Score/15.png"); //Shapes Bonus10_Sprite.setPosition(WinW-100,70); Bonus10_Sprite.setTexture(Bonus10_Texture); Bonus10_Sprite.setColor(Color::Cyan); Bonus15_Sprite.setPosition(WinW-100,70); Bonus15_Sprite.setTexture(Bonus15_Texture); //Text! Score_Text.setFont(Score_Font); Score_Text.setString("SCORE:"); Score_Text.setCharacterSize(30); Score_Text.setPosition(WinW-200,30); Score_Text.setColor(Color::White); Score_Text.setStyle(Text::Bold); Score_Number.setFont(Score_Font); Score_Number.setCharacterSize(30); Score_Number.setPosition(Score_Text.getPosition().x+115,30); Score_Number.setColor(Color::White); Score_Number.setStyle(Text::Bold); HighScore_Text.setFont(Score_Font); HighScore_Text.setString("HighScore:"); HighScore_Text.setCharacterSize(20); HighScore_Text.setPosition(WinW-196,10); HighScore_Text.setColor(Color::White); HighScore_Text.setStyle(Text::Bold); HighScore_Number.setFont(Score_Font); HighScore_Number.setCharacterSize(20); HighScore_Number.setPosition(HighScore_Text.getPosition().x+115,10); HighScore_Number.setColor(Color::White); HighScore_Number.setStyle(Text::Bold); setHighScore(); } void Score::ChangeColor() { randNum=rand()%3; if(randNum==0) { HighScore_Text.setColor(Color::White); HighScore_Number.setColor(Color::White); } if(randNum==1) { HighScore_Text.setColor(Color::Blue); HighScore_Number.setColor(Color::Blue); randNum=rand()%3; } if(randNum==2) { HighScore_Text.setColor(Color::Red); HighScore_Number.setColor(Color::Red); randNum=rand()%3; } } void Score::setHighScore() { fstream HighScore_File; HighScore_File.open("HighScore.txt",ios::in); HighScore_File>>HighScore; } void Score::setFile(float PlayerScore) { newScore=PlayerScore; if(PlayerScore>HighScore) { HighScore=PlayerScore; fstream HighScore_File; HighScore_File.open("HighScore.txt",ios::out); HighScore_File<<PlayerScore; HighScore_File.close(); setHighScore(); ChangeColor(); } } void Score::RestartColor() { HighScore_Text.setColor(Color::White); HighScore_Number.setColor(Color::White); } void Score::SetScore(bool &DisplayGame,bool &RestartGame,Time &GameTimer) { ScorePoints+=0.015; if(RestartGame == true) { if(GameTimer<seconds(0.1)) { ScorePoints=0; } } } void Score::setBonus(RenderWindow &Window) { if(Bonus10==true) { Bonus10_Sprite.move(0,-0.90); ScorePoints+=0.25; } if(Bonus15==true) { Bonus15_Sprite.move(0,-0.90); ScorePoints+=0.5; } if(Bonus10_Sprite.getPosition().y<35) { Bonus10_Sprite.setPosition(WinW-100,70); Bonus10=false; } if(Bonus15_Sprite.getPosition().y<45) { Bonus15_Sprite.setPosition(WinW-100,70); Bonus15=false; } } void Score::DrawScore(RenderWindow &Window) { PlayerScore = int (ScorePoints); setFile(PlayerScore); ostringstream buffer; buffer<<PlayerScore; Score_Number.setString(buffer.str()); ostringstream HighScore_buffer; HighScore_buffer<<HighScore; HighScore_Number.setString(HighScore_buffer.str()); Window.draw(Score_Text); Window.draw(Score_Number); Window.draw(HighScore_Text); Window.draw(HighScore_Number); if(Bonus10==true) { Window.draw(Bonus10_Sprite); setBonus(Window); } if(Bonus15==true) { Window.draw(Bonus15_Sprite); setBonus(Window); } } <file_sep>#ifndef HOWTOPLAY_H #define HOWTOPLAY_H #include <SFML/Graphics.hpp> using namespace std; using namespace sf; class HowToPlay { public: HowToPlay(); void draw(RenderWindow &Window); void Menu_Control(Event MainEvent,RenderWindow &Window, bool &DisplayMainMenu,bool &DisplayHowToPlay); private: //Data float WinW; float WinH; //Textures! Texture HowToPlay_Texture; //Shapes! RectangleShape HowToPlay_Shape; }; #endif <file_sep>#ifndef METEORS_H #define METEORS_H #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include <stdlib.h> using namespace std; using namespace sf; class Meteors { public: Meteors(); void MeteorsDraw(RenderWindow &Window,float timer1,float timer2); void MoveMeteors(float timer1,float timer2); void RestartMeteors(); void RestartMeteorType(); int Meteors0_MoveY; int Meteors1_MoveY; //Shapes! RectangleShape RockDrop_Shape[30]; RectangleShape RockRaise_Shape[30]; private: //Variables! int WinW; int WinH; float RocksMoveY; float RockMoveY1; int MeteorDropType1; int MeteorRaiseType1; //int x,y; //Randoms! int randomNumber[30]; int randomPositions1[30]; int randomPositions2[30]; float randomSize0[30]; float randomSize1[30]; int randomDegrees[30]; int randomMoveX[30]; int randomRockCrashSize[30]; float randomScale[30]; //Textures Texture Rock_texture1; Texture Rock_texture2; }; #endif <file_sep> #include <iostream> #include <cstdlib> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include "GameState.h" #include "time.h" using namespace std; using namespace sf; int main() { //Screen width & height int WinW=1366; int WinH=768; //Create the Window RenderWindow Window(VideoMode(WinW,WinH) ,"Asteroid War"); Window.setMouseCursorVisible(false); Window.setFramerateLimit(60); Window.setKeyRepeatEnabled(true); GameState GameState_Object; while(Window.isOpen()) { Event MainEvent; while(Window.pollEvent(MainEvent)) { if(MainEvent.type == Event::Closed) { Window.close(); } GameState_Object.setControlState(MainEvent,Window); } GameState_Object.setGameOn(Window); Window.clear(); GameState_Object.setDrawState(Window); Window.display(); } } <file_sep>#include "InGameMenu.h" using namespace sf; InGameMenu::InGameMenu() { WinW=1366; WinH=768; //variables SelectedElementIndex=0; MusicCounter=0; EscapeCounter=0; ScreenModeCount=0; //Fonts! font.loadFromFile("Data/Fonts/Leander.ttf"); //Textures! BackGround_Texture.loadFromFile("Data/Pictures/Game BackGround/backGround0.png"); //Shapes BackGround_Shape.setSize(Vector2f(WinW,WinH)); BackGround_Shape.setPosition(0,0); BackGround_Shape.setTexture(&BackGround_Texture); //Lines Line_xOffset=150; Line_yOffset=0; for(int i=0;i<7;i++) { Line[i].setSize(Vector2f(200,2)); Line[i].setFillColor(Color(230,230,230)); Line[i].setPosition(WinW/2-Line_xOffset,WinH/2+Line_yOffset); Line_yOffset+=34; } Line[0].setFillColor(Color::Cyan); Line[1].setFillColor(Color::Cyan); //Text! for(int i=0;i<6;i++) { InGameMenu_Text[i].setFont(font); InGameMenu_Text[i].setColor(Color(230,230,230)); InGameMenu_Text[i].setCharacterSize(21); } InGameMenu_Text[0].setString("Resume"); InGameMenu_Text[0].setPosition(Line[0].getPosition().x+InGameMenu_Text[0].getCharacterSize()*3,Line[0].getPosition().y+4); InGameMenu_Text[0].setColor(Color::Cyan); //Selected By Default! InGameMenu_Text[1].setString("Start NewGame"); InGameMenu_Text[1].setPosition(Line[1].getPosition().x+InGameMenu_Text[1].getCharacterSize()*1,Line[1].getPosition().y+4); InGameMenu_Text[2].setString("Full Screen Mode"); InGameMenu_Text[2].setPosition(Line[2].getPosition().x+InGameMenu_Text[2].getCharacterSize()*0.8,Line[2].getPosition().y+4); InGameMenu_Text[3].setString("Music ON"); InGameMenu_Text[3].setPosition(Line[3].getPosition().x+InGameMenu_Text[3].getCharacterSize()*2.5,Line[3].getPosition().y+4); InGameMenu_Text[4].setString("Exit to MainMenu"); InGameMenu_Text[4].setPosition(Line[4].getPosition().x+InGameMenu_Text[4].getCharacterSize()*0.6,Line[4].getPosition().y+4); InGameMenu_Text[5].setString("Exit to Desktop"); InGameMenu_Text[5].setPosition(Line[5].getPosition().x+InGameMenu_Text[5].getCharacterSize()*1.1,Line[5].getPosition().y+4); } void InGameMenu::InGameMenu_Control(Event event,RenderWindow &Window,bool &DisplayMenu,bool &DisplayGame,bool &DisplayInGameMenu,bool &RestartGame,Clock &c1,float &timer1,float &timer2) { if(event.type == Event::KeyPressed) { if(event.key.code == Keyboard::Up) { MoveUp(); } if(event.key.code == Keyboard::Down) { MoveDown(); } if(event.key.code == Keyboard::Return) { if(SelectedElementIndex==0) { DisplayInGameMenu=false; DisplayGame=true; } if(SelectedElementIndex==1) { DisplayGame=true; RestartGame=true; DisplayInGameMenu=false; c1.restart(); timer1=0; timer2=0; } if(SelectedElementIndex==2) { } if(SelectedElementIndex==3) { } if(SelectedElementIndex==4) { DisplayInGameMenu=false; DisplayMenu=true; } if(SelectedElementIndex==5) { Window.close(); } } } if(event.type==Event::KeyReleased) { if(event.key.code==Keyboard::Return) { if(SelectedElementIndex==1) { } } } } void InGameMenu::MoveUp() { if(SelectedElementIndex-1>=0) { InGameMenu_Text[SelectedElementIndex].setColor(Color(230,230,230)); Line[SelectedElementIndex+1].setFillColor(Color(230,230,230)); SelectedElementIndex--; InGameMenu_Text[SelectedElementIndex].setColor(Color::Cyan); Line[SelectedElementIndex].setFillColor(Color::Cyan); GameMusic_Object.setMenuSelect_Sound(); } } void InGameMenu::MoveDown() { if(SelectedElementIndex+1 < 6) { InGameMenu_Text[SelectedElementIndex].setColor(Color(230,230,230)); Line[SelectedElementIndex].setFillColor(Color(230,230,230)); Line[SelectedElementIndex-1].setFillColor(Color(230,230,230)); SelectedElementIndex++; InGameMenu_Text[SelectedElementIndex].setColor(Color::Cyan); Line[SelectedElementIndex].setFillColor(Color::Cyan); Line[SelectedElementIndex+1].setFillColor(Color::Cyan); GameMusic_Object.setMenuSelect_Sound(); } } void InGameMenu::setScreenMode(RenderWindow &Window) { if(SelectedElementIndex==2) { ScreenModeCount++; if(ScreenModeCount%2==0) { InGameMenu_Text[2].setString("Full Screen Mode"); InGameMenu_Text[2].setPosition(Line[2].getPosition().x+InGameMenu_Text[2].getCharacterSize()*0.8,Line[2].getPosition().y+4); Window.create(VideoMode(WinW,WinH),"Ship!" ,Style::Default); Window.setFramerateLimit(60); } else { InGameMenu_Text[2].setString("Window Mode"); InGameMenu_Text[2].setPosition(Line[2].getPosition().x+InGameMenu_Text[2].getCharacterSize()*1.3,Line[2].getPosition().y+4); Window.create(VideoMode(WinW,WinH) ,"Ship!", Style::Fullscreen); Window.setFramerateLimit(60); Window.setMouseCursorVisible(false); Window.setKeyRepeatEnabled(false); } } } void InGameMenu::setMusicState() { MusicCounter++; if(MusicCounter%2==0) { InGameMenu_Text[3].setString("Music ON"); InGameMenu_Text[3].setPosition(Line[3].getPosition().x+InGameMenu_Text[3].getCharacterSize()*2.5,Line[3].getPosition().y+4); } else { InGameMenu_Text[3].setString("Music OFF"); InGameMenu_Text[3].setPosition(Line[3].getPosition().x+InGameMenu_Text[3].getCharacterSize()*2.4,Line[3].getPosition().y+4); } } void InGameMenu::InGameMenu_Draw(RenderWindow &Window) { //BackGround! Window.draw(BackGround_Shape); //Lines! for(int i=0;i<7;i++) { Window.draw(Line[i]); } //Text! for(int i=0;i<6;i++) { Window.draw(InGameMenu_Text[i]); } } <file_sep>#include "OptionsMenu.h" using namespace sf; OptionsMenu::OptionsMenu() { WinW=1366; WinH=768; //Variables SelectedElementIndex = 0; MusicStateCount=0; ScreenModeCount=0; //Textures! OptionsScreen_Texture[0].loadFromFile("Data/Pictures/MainMenu/Options-Menu/OptionsMenu0.png"); OptionsScreen_Texture[1].loadFromFile("Data/Pictures/MainMenu/Options-Menu/OptionsMenu1.png"); OptionsScreen_Texture[2].loadFromFile("Data/Pictures/MainMenu/Options-Menu/OptionsMenu2.png"); //Shapes! setShapes(); //Fonts! font.loadFromFile("Data/Fonts/Leander.ttf"); vivaldi_Font.loadFromFile("Data/Fonts/vivaldi.ttf"); //Sound Buffers! MenuSelect_buffer.loadFromFile("Data/Sounds/MenuSelect.wav"); //Sounds! MenuSelect_Sound.setBuffer(MenuSelect_buffer); } void OptionsMenu::setShapes() { OptionsScreen_Shape.setSize(Vector2f(WinW,WinH)); OptionsScreen_Shape.setPosition(0,0); OptionsScreen_Shape.setTexture(&OptionsScreen_Texture[0]); } void OptionsMenu::Menu_Control(Event MainEvent,RenderWindow &Window,bool &DisplayMainMenu,bool &DisplayOptions) { if(MainEvent.type == Event::KeyPressed) { if(MainEvent.key.code == Keyboard::Right) { MoveRight(); } if(MainEvent.key.code == Keyboard::Left) { MoveLeft(); } if(MainEvent.key.code==Keyboard::Escape) { DisplayMainMenu=true; DisplayOptions=false; } } } void OptionsMenu::MoveRight() { if(SelectedElementIndex+1<3) { MenuSelect_Sound.play(); SelectedElementIndex++; OptionsScreen_Shape.setTexture(&OptionsScreen_Texture[SelectedElementIndex]); } } void OptionsMenu::MoveLeft() { if(SelectedElementIndex-1>=0) { MenuSelect_Sound.play(); SelectedElementIndex--; OptionsScreen_Shape.setTexture(&OptionsScreen_Texture[SelectedElementIndex]); } } void OptionsMenu::draw(RenderWindow &Window) { Window.draw(OptionsScreen_Shape); } <file_sep>#ifndef GAMEMUSIC_H #define GAMEMUSIC_H #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include "OptionsMenu.h" using namespace std; using namespace sf; class GameMusic { public: GameMusic(); void setMainMenu_Music(); void setInGame_Music(); void setCredits_Music(); void setMenuSelect_Sound(); void setLaser_Sound(); void setTurbo_Sound(); void setShipCrash_Sound(); void setRockCrash_Sound(); void setActivateShield_Sound(); private: //Music Music MainMenu_Music; Music InGame_Music; Music Credits_Music; //Sound Buffers! SoundBuffer MenuSelect_Buffer; SoundBuffer laser_buffer; SoundBuffer turbo_buffer; SoundBuffer ShipCrash_buffer; SoundBuffer RockCrash_buffer; SoundBuffer ActivateShield_buffer; //Sounds! Sound MenuSelect_Sound; Sound laser_Sound; Sound turbo_Sound; Sound ShipCrash_Sound; Sound RockCrash_Sound; Sound ActivateShield_Sound; }; #endif <file_sep>#ifndef GAMESTATE_H #define GAMESTATE_H #include "Menu.h" #include "GameBackGround.h" #include "GameMusic.h" #include "Ship.h" #include "InGameMenu.h" #include "Meteors.h" #include "time.h" #include "Collision.h" #include "EndGame.h" #include "Score.h" using namespace sf; class GameState { public: GameState(); void setControlState(Event MainEvent,RenderWindow &Window); void setGameOn(RenderWindow &Window); //Move things .-. void setDrawState(RenderWindow &Window); private: //States bool DisplayMenu; bool DisplayGame; bool DisplayInGameMenu; bool DisplayEndGame; bool RestartGame; ///Timers Clock c1; Time GameTimer; float timer1; float timer2; float ScorePoints; //Objects MainMenu MainMenu_Object; GameBackGround GameBackGround_Object; GameMusic GameMusic_Object; Ship Ship_Object; InGameMenu InGameMenu_Object; Meteors Meteors_Object; Collision Collision_Object; EndGame EndGame_Object; Score Score_Object; }; #endif <file_sep>#include "Collision.h" using namespace sf; Collision::Collision() { CollisionTime1=0; CollisionTime2=0; //Textures ShipCrash_Texture.loadFromFile("Data/Pictures/ShipCrash/ShipCrash1.png"); RockCrash_texture.loadFromFile("Data/Pictures/Asteroids/asteroid.png"); Shield_Texture.loadFromFile("Data/Pictures/Shield/bubble2.png"); //Shapes ShipeCrash_Sprite.setTexture(ShipCrash_Texture); ShipeCrash_Sprite.setOrigin(ShipeCrash_Sprite.getGlobalBounds().width/2,ShipeCrash_Sprite.getGlobalBounds().height/2); Shield_Shape.setTexture(&Shield_Texture); Shield_Shape.setRadius(MiniShield_Radius); Shield_Shape.setPosition(-500,-500); for(int i=0;i<30;i++) { for(int j=0;j<10;j++) { RockCrash_Shape[i][j].setTexture(&RockCrash_texture); } } } void Collision::Check_LifeState(Sprite Shipsprite,RectangleShape RockDrop_Shape[30],RectangleShape RockRaise_Shape[30],bool &DisplayGame,bool &DisplayEndGame) { bool checkRockDropCollision=false; bool checkRockRaiseCollision=false; for(int i=0;i<30;i++) { if((Shipsprite.getGlobalBounds().intersects(RockDrop_Shape[i].getGlobalBounds()))&&(RockDrop_Shape[i].getPosition().x>Shipsprite.getGlobalBounds().left)&&(RockDrop_Shape[i].getPosition().x<(Shipsprite.getGlobalBounds().left+Shipsprite.getGlobalBounds().width))&&(RockDrop_Shape[i].getPosition().y>Shipsprite.getGlobalBounds().top)&&(RockDrop_Shape[i].getPosition().y<(Shipsprite.getGlobalBounds().top+Shipsprite.getGlobalBounds().height))) { if(ActivateShield==false) { checkRockDropCollision=true; CollisionTime1+=0.001; if(checkRockDropCollision==true) { if(CollisionTime1>0.006) { DisplayGame=false; DisplayEndGame=true; ShipeCrash_Sprite.setPosition(Shipsprite.getPosition().x , Shipsprite.getPosition().y); GameMusic_Object.setShipCrash_Sound(); } } } } if((Shipsprite.getGlobalBounds().intersects(RockRaise_Shape[i].getGlobalBounds()))&&(RockRaise_Shape[i].getPosition().x>Shipsprite.getGlobalBounds().left)&&(RockRaise_Shape[i].getPosition().x<(Shipsprite.getGlobalBounds().left+Shipsprite.getGlobalBounds().width))&&(RockRaise_Shape[i].getPosition().y>Shipsprite.getGlobalBounds().height)&&(RockRaise_Shape[i].getPosition().y<(Shipsprite.getGlobalBounds().top+Shipsprite.getGlobalBounds().height))) { if(ActivateShield==false) { checkRockRaiseCollision=true; CollisionTime2+=0.001; if(checkRockRaiseCollision==true) { if(CollisionTime2>0.005) { ShipeCrash_Sprite.setPosition(Shipsprite.getPosition().x , Shipsprite.getPosition().y); GameMusic_Object.setShipCrash_Sound(); DisplayEndGame=true; DisplayGame=false; } } } } } if(checkRockDropCollision==false) { CollisionTime1=0; } if(checkRockRaiseCollision==false) { CollisionTime2=0; } if(Shipsprite.getGlobalBounds().intersects(Shield_Shape.getGlobalBounds())) { ActivateShield_Timer+=0.01; if(ActivateShield_Timer<=5) { if(ActivateShield_Timer<=0.7){GameMusic_Object.setActivateShield_Sound();} ActivateShield_Radius+=2; if(ActivateShield_Radius==90){ActivateShield_Radius-=2;} ActivateShield=true; Shield_Shape.setPosition(Shipsprite.getPosition().x,Shipsprite.getPosition().y); Shield_Shape.setOrigin(Shield_Shape.getGlobalBounds().width/2,Shield_Shape.getGlobalBounds().height/2); Shield_Shape.setRadius(MiniShield_Radius+ActivateShield_Radius); } if(ActivateShield_Timer>5) { ActivateShield=false; Shield_Shape.setRadius(MiniShield_Radius); ActivateShield_Radius=0; ActivateShield_Timer=0; Shield_Shape.setPosition(-500,-500); } } if(DisplayEndGame==true) { ActivateShield_Radius=0; Shield_Shape.setRadius(MiniShield_Radius); Shield_Shape.setPosition(-500,-500); } } void Collision::DrawShipCrash(RenderWindow &Window) { Window.draw(ShipeCrash_Sprite); } void Collision::Check_RockCrash(RenderWindow &Window, bool &Laser,RectangleShape Laser_Shape,RectangleShape RockDrop_Shape[30],RectangleShape RockRaise_Shape[30],bool &Bonus10,bool &Bonus15) { for(int i=0;i<30;i++) { if(Laser==true) { if(Laser_Shape.getGlobalBounds().intersects(RockDrop_Shape[i].getGlobalBounds())) { RockCrash=true; RockDrop_Shape[i].setSize(Vector2f(0,0)); GameMusic_Object.setRockCrash_Sound(); if(i%5==0) { Bonus15=true; } if(i%5!=0) { Bonus10=true; } for(int j=0;j<10;j++) { RockCrash_Shape[i][j].setPosition(RockDrop_Shape[i].getPosition().x+x,RockDrop_Shape[i].getPosition().y+y); RockCrash_Shape[i][j].setSize(Vector2f(5,2.5)); x=rand()%20+5; y=rand()%15+5; } if(i==4) { if(ActivateShield==false) { Shield_Shape.setPosition(RockDrop_Shape[i].getPosition().x,RockDrop_Shape[i].getPosition().y); } } } if(Laser_Shape.getGlobalBounds().intersects(RockRaise_Shape[i].getGlobalBounds())) { RockCrash=true; RockRaise_Shape[i].setSize(Vector2f(0,0)); GameMusic_Object.setRockCrash_Sound(); if(i%5==0) { Bonus15=true; } if(i%5!=0) { Bonus10=true; } for(int j=0;j<10;j++) { RockCrash_Shape[i][j].setPosition(RockRaise_Shape[i].getPosition().x+x,RockRaise_Shape[i].getPosition().y+y); RockCrash_Shape[i][j].setSize(Vector2f(5,2.5)); x=rand()%20+5; y=rand()%15+5; } if(i==4) { if(ActivateShield==false) { Shield_Shape.setPosition(RockRaise_Shape[i].getPosition().x,RockRaise_Shape[i].getPosition().y); } } } } } } void Collision::DrawRockCrash(RenderWindow &Window,int &Meteors1_MoveY) { if(RockCrash==true) { for(int i=0;i<30;i++) { for(int j=0;j<10;j++) { Window.draw(RockCrash_Shape[i][j]); RockCrash_Shape[i][j].move(0,Meteors1_MoveY); } } Window.draw(Shield_Shape); if(ActivateShield==false) { Shield_Shape.move(0,Meteors1_MoveY); } } } <file_sep>#include "GameState.h" using namespace std; using namespace sf; GameState::GameState() { DisplayMenu=true; DisplayGame=false; DisplayInGameMenu=false; DisplayEndGame=false; RestartGame=false; //Timers timer1=0; timer2=0; } void GameState::setControlState(Event MainEvent,RenderWindow &Window) { if(DisplayMenu==true) { MainMenu_Object.Menu_Control(MainEvent,Window,DisplayMenu,DisplayGame,c1); } if(DisplayGame==true) { Ship_Object.ShipControl(MainEvent,DisplayInGameMenu,DisplayGame); } if(DisplayInGameMenu==true) { InGameMenu_Object.InGameMenu_Control(MainEvent,Window,DisplayMenu,DisplayGame,DisplayInGameMenu,RestartGame,c1,timer1,timer2); } if(DisplayEndGame==true) { EndGame_Object.EndGame_Control(MainEvent,DisplayMenu,DisplayGame,DisplayEndGame,RestartGame,&c1,timer1,timer2); Ship_Object.Upbutton=false; Ship_Object.Downbutton=false; Ship_Object.Rightbutton=false; Ship_Object.Leftbutton=false; Ship_Object.Laser=false; Ship_Object.SpeedUp=false; } } void GameState::setGameOn(RenderWindow &Window) { Collision_Object.Check_RockCrash(Window,Ship_Object.Laser,Ship_Object.Laser_Shape,Meteors_Object.RockDrop_Shape,Meteors_Object.RockRaise_Shape,Score_Object.Bonus10,Score_Object.Bonus15); if(DisplayGame==true) { GameTimer=c1.getElapsedTime(); timer1+=0.01; timer2+=0.005; Ship_Object.Logics(); Score_Object.SetScore(DisplayGame,RestartGame,GameTimer); if(GameTimer>seconds(0.1)) { GameBackGround_Object.MovingBackGround(); //Meteors_Object.MoveMeteors(timer1,timer2); //Collision_Object.Check_LifeState(Ship_Object.Ship1_Sprite ,Meteors_Object.RockDrop_Shape ,Meteors_Object.RockRaise_Shape,DisplayGame,DisplayEndGame); } if(RestartGame==true) { if(GameTimer<seconds(0.1)) { GameBackGround_Object.RestartBackGround(); Ship_Object.RestartShip(); Meteors_Object.RestartMeteors(); Meteors_Object.RestartMeteorType(); Score_Object.RestartColor(); } } } } void GameState::setDrawState(RenderWindow &Window) { if(DisplayMenu==true) { MainMenu_Object.draw(Window); } if(DisplayGame==true) { GameBackGround_Object.Draw(Window); Ship_Object.ShipDraw(Window); Meteors_Object.MeteorsDraw(Window,timer1,timer2); Score_Object.DrawScore(Window); Collision_Object.DrawRockCrash(Window,Meteors_Object.Meteors1_MoveY); } if(DisplayInGameMenu==true) { InGameMenu_Object.InGameMenu_Draw(Window); } if(DisplayEndGame==true) { GameBackGround_Object.Draw(Window); Collision_Object.DrawShipCrash(Window); EndGame_Object.Draw_EndGame(Window); } } <file_sep># Astroid-War-Game A very Special thanks to @abalmagid & @osamatnt for making this great project as i left the dev at an early stage. Astroid War is a game where you control a space ship throu space and destroy meteors to score higher, the game was made using C++ and SFML libraries for a school project. @abalmagid https://github.com/abalmagid @osamatnt https://github.com/OsamaTnt <file_sep>#ifndef SHIP_H #define SHIP_H #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include <stdlib.h> #include "InGameMenu.h" #include "GameMusic.h" using namespace std; using namespace sf; class Ship { public: Ship(); void ShipDraw(RenderWindow &Window); void ShipControl(Event event,bool &DisplayInGameMenu,bool &DisplayGame); void Logics(); void RestartShip(); Sprite Ship1_Sprite; RectangleShape Laser_Shape; //States! bool Upbutton; bool Downbutton; bool Rightbutton; bool Leftbutton; bool SpeedUp; bool Laser; private: //Variables! int WinW; int WinH; float diffualtSpeed; float xVelocity; float yVelocity; float IncreaseSpeed; float MaxSpeed; float Laser_Timer=0; //Textures Texture Ship1_Texture; Texture Laser_Texture; Texture Turbo_Texture; //Shapes! Sprite Turbo1_Sprite; Sprite Turbo2_Sprite; //Objects! InGameMenu InGameMenu_Object; GameMusic GameMusic_Object; }; #endif <file_sep>#include "GameMusic.h" using namespace sf; GameMusic::GameMusic() { ActivateShield_buffer.loadFromFile("Data/Sounds/bonusWave.wav"); ActivateShield_Sound.setBuffer(ActivateShield_buffer); } void GameMusic::setMainMenu_Music() { MainMenu_Music.openFromFile("Data/Music/CyaronsGate.ogg"); MainMenu_Music.play(); MainMenu_Music.setVolume(50); MainMenu_Music.setPlayingOffset(seconds(16.176)); } void GameMusic::setInGame_Music() { MainMenu_Music.stop(); InGame_Music.openFromFile("Data/Music/InGame_Music.ogg"); InGame_Music.play(); InGame_Music.setVolume(50); } void GameMusic::setCredits_Music() { MainMenu_Music.pause(); Credits_Music.openFromFile(""); Credits_Music.play(); Credits_Music.setVolume(50); } void GameMusic::setMenuSelect_Sound() { MenuSelect_Buffer.loadFromFile("Data/Sounds/MenuSelect.wav"); MenuSelect_Sound.setBuffer(MenuSelect_Buffer); MenuSelect_Sound.play(); } void GameMusic::setLaser_Sound() { laser_buffer.loadFromFile("Data/Sounds/photon-torpedo.wav"); laser_Sound.setBuffer(laser_buffer); laser_Sound.play(); } void GameMusic::setTurbo_Sound() { turbo_buffer.loadFromFile("Data/Sounds/ShipMove.wav"); turbo_Sound.setBuffer(turbo_buffer); //turbo_Sound.play(); } void GameMusic::setShipCrash_Sound() { ShipCrash_buffer.loadFromFile("Data/Sounds/ShipCrash.wav"); ShipCrash_Sound.setBuffer(ShipCrash_buffer); ShipCrash_Sound.play(); } void GameMusic::setRockCrash_Sound() { RockCrash_buffer.loadFromFile("Data/Sounds/laserhit1.wav"); RockCrash_Sound.setBuffer(RockCrash_buffer); RockCrash_Sound.setVolume(40); RockCrash_Sound.play(); } void GameMusic::setActivateShield_Sound() { ActivateShield_Sound.play(); } <file_sep>#ifndef MENU_H #define MENU_H #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include "GameMusic.h" #include "OptionsMenu.h" #include "HowToPlay.h" #include "Credits.h" using namespace std; using namespace sf; //The Base MainMenu class MainMenu { public: MainMenu(); void setShapes(); void draw(RenderWindow &Window); void Menu_Control(Event MainEvent,RenderWindow &Window,bool &DisplayMenu,bool &DisplayGame,Clock &c1); void MoveUp(); void MoveDown(); void setMusicState(); void setScreenMode(RenderWindow &Window); void ExitMenu(RenderWindow &Window); void PlayMode(bool &DisplayMenu); private: //States! bool DisplayMainMenu; bool DisplayOptions; bool DisplayHowToPlay; bool DisplayCredits; //Data Members! float WinW; float WinH; int Line_xOffset; int Line_yOffset; int SelectedElementIndex; int MusicStateCount; int ScreenModeCount; //Textures! Texture MenuBackground_Texture; //Fonts! Font font; Font vivaldi_Font; //Text! Text Menu_Text[5]; //Shapes! RectangleShape MenuBackground_Shape; RectangleShape Line[6]; //Objects OptionsMenu optionsMenu; HowToPlay howToPlay; Credits credits; GameMusic GameMusic_Object; }; #endif <file_sep>#include "Meteors.h" using namespace sf; Meteors::Meteors() { //Screen Width & Height! WinW=1366; WinH=768; //Variables! Meteors0_MoveY=3; Meteors1_MoveY=5; //Randoms! for(int i=0;i<30;i++) { randomNumber[i]=rand()%WinW-WinW/2; randomSize0[i]=rand()%70+40; randomSize1[i]=rand()%70+40; randomScale[i]=rand()%2; randomPositions1[i]=rand()%WinW+randomSize0[i]*2; randomPositions2[i]=rand()%WinW+randomSize0[i]*2; randomDegrees[i]=rand()%360+1; randomMoveX[i]=rand()%4+(1)-4; //Range(3,-3)! } //Textures Rock_texture1.loadFromFile("Data/Pictures/Asteroids/asteroid.png"); Rock_texture2.loadFromFile("Data/Pictures/Asteroids/asteroid02.png"); //Shapes for(int i=0;i<30;i++) { if(i%5==0) { //Dropped Rocks type 1! RockDrop_Shape[i].setSize(Vector2f(randomSize1[i],randomSize1[i])); RockDrop_Shape[i].setTexture(&Rock_texture2); RockDrop_Shape[i].setPosition(randomPositions1[i],-400); RockDrop_Shape[i].setOrigin(Vector2f(RockDrop_Shape[i].getGlobalBounds().width/2,RockDrop_Shape[i].getGlobalBounds().height/2)); RockDrop_Shape[i].setRotation(randomDegrees[i]); //RaisedRocks type 1! RockRaise_Shape[i].setSize(Vector2f(randomSize1[i],randomSize1[i])); RockRaise_Shape[i].setTexture(&Rock_texture2); RockRaise_Shape[i].setPosition(randomPositions2[i],WinH+400); RockRaise_Shape[i].setOrigin(Vector2f(RockRaise_Shape[i].getGlobalBounds().width/2,RockRaise_Shape[i].getGlobalBounds().height/2)); RockRaise_Shape[i].setRotation(randomDegrees[i]); RockRaise_Shape[i].setFillColor(Color(140,140,150)); } else { //Dropped Rocks! RockDrop_Shape[i].setSize(Vector2f(randomSize0[i],randomSize0[i])); RockDrop_Shape[i].setTexture(&Rock_texture1); RockDrop_Shape[i].setPosition(randomPositions1[i],-400); RockDrop_Shape[i].setOrigin(Vector2f(RockDrop_Shape[i].getGlobalBounds().width/2,RockDrop_Shape[i].getGlobalBounds().height/2)); RockDrop_Shape[i].setRotation(randomDegrees[i]); RockDrop_Shape[i].setFillColor(Color(140,140,125)); //RaisedRocks! RockRaise_Shape[i].setSize(Vector2f(randomSize0[i],randomSize0[i])); RockRaise_Shape[i].setTexture(&Rock_texture1); RockRaise_Shape[i].setPosition(randomPositions2[i],WinH+400); RockRaise_Shape[i].setOrigin(Vector2f(RockRaise_Shape[i].getGlobalBounds().width/2,RockRaise_Shape[i].getGlobalBounds().height/2)); RockRaise_Shape[i].setRotation(randomDegrees[i]); RockRaise_Shape[i].setFillColor(Color(130,140,150)); } } } void Meteors::RestartMeteorType() { MeteorDropType1=0; MeteorRaiseType1=0; } void Meteors::RestartMeteors() { for(int i=0;i<30;i++) { if(i%5==0) { RockDrop_Shape[i].setPosition(randomPositions1[i],-400); RockRaise_Shape[i].setPosition(randomPositions2[i],WinH+400); } else { RockDrop_Shape[i].setPosition(randomPositions1[i],-400); RockRaise_Shape[i].setPosition(randomPositions2[i],WinH+400); } } } void Meteors::MoveMeteors(float timer1,float timer2) { for(int i=0;i<30;i++) { if(timer1>i) { if(i%5==0) { //Dropped Rocks type 1! RockDrop_Shape[i].move(randomMoveX[i],Meteors1_MoveY); if(RockDrop_Shape[i].getPosition().y > WinH) { randomPositions1[i]=rand()%WinW+randomSize0[i]*2; RockDrop_Shape[i].setPosition(randomPositions1[i],-400); RockDrop_Shape[i].setSize(Vector2f(randomSize1[i],randomSize1[i])); } } else { //Dropped Rocks! RockDrop_Shape[i].move(randomMoveX[i],Meteors0_MoveY); if(RockDrop_Shape[i].getPosition().y > WinH) { randomPositions1[i]=rand()%WinW+randomSize0[i]*2; RockDrop_Shape[i].setPosition(randomPositions1[i],-400); RockDrop_Shape[i].setSize(Vector2f(randomSize0[i],randomSize0[i])); } } } if(timer2>i) { if(i%5==0) { //RaisedRocks type 1! RockRaise_Shape[i].move(randomMoveX[i],-Meteors1_MoveY); if(RockRaise_Shape[i].getPosition().y < -100) { randomPositions2[i]=rand()%WinW+randomSize0[i]*2; RockRaise_Shape[i].setSize(Vector2f(randomSize1[i],randomSize1[i])); RockRaise_Shape[i].setPosition(randomPositions2[i],WinH+400); } } else { //RaisedRocks! RockRaise_Shape[i].move(randomMoveX[i],-Meteors0_MoveY); if(RockRaise_Shape[i].getPosition().y < -100) { randomPositions2[i]=rand()%WinW+randomSize0[i]*2; RockRaise_Shape[i].setSize(Vector2f(randomSize0[i],randomSize0[i])); RockRaise_Shape[i].setPosition(randomPositions2[i],WinH+400); } } } } } void Meteors::MeteorsDraw(RenderWindow &Window,float timer1,float timer2) { //Drawing Rocks! for(int i=0;i<30;i++) { if(timer1>i) { Window.draw(RockDrop_Shape[i]); } if(timer2>i) { Window.draw(RockRaise_Shape[i]); } } } <file_sep>#ifndef INGAMEMENU_H #define INGAMEMENU_H #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include "GameMusic.h" using namespace std; using namespace sf; class InGameMenu { public: InGameMenu(); void InGameMenu_Draw(RenderWindow &Window); void InGameMenu_Control(Event event,RenderWindow &Window,bool &DisplayMenu,bool &DisplayGame,bool &DisplayInGameMenu,bool &RestartGame,Clock &c1,float &timer1,float &timer2); void MoveUp(); void MoveDown(); void setScreenMode(RenderWindow &Window); void setMusicState(); private: //Data Members! float WinW; float WinH; int Line_xOffset; int Line_yOffset; int SelectedElementIndex; int MusicCounter; int ScreenModeCount; int EscapeCounter; //Textures! Texture BackGround_Texture; //Shapes! RectangleShape BackGround_Shape; RectangleShape Line[7]; //Fonts! Font font; //Text Text InGameMenu_Text[6]; //Object GameMusic GameMusic_Object; }; #endif <file_sep>#include "GameBackGround.h" using namespace sf; GameBackGround::GameBackGround() { WinW=1366; WinH=768; //Textures! //BackGround for(int i=0;i<20;i+=2) { backGround[i].loadFromFile("Data/Pictures/Game BackGround/backGround0.png"); } for(int i=1;i<20;i+=2) { backGround[i].loadFromFile("Data/Pictures/Game BackGround/backGround1.png"); } //Planets! Earth.loadFromFile("Data/Pictures/Game BackGround/Earth.png"); Mars.loadFromFile("Data/Pictures/Game BackGround/Mars.png"); jupiter.loadFromFile("Data/Pictures/Game BackGround/jupiter.png"); Saturn.loadFromFile("Data/Pictures/Game BackGround/Saturn.png"); Uranus.loadFromFile("Data/Pictures/Game BackGround/uranus.png"); Neptune.loadFromFile("Data/Pictures/Game BackGround/Neptune.png"); Pluto.loadFromFile("Data/Pictures/Game BackGround/Pluto.png"); //EndGame! BlackHole.loadFromFile("Data/Pictures/Game BackGround/backGround10.png"); setShapes(); } void GameBackGround::setShapes() { //background for(int i=0;i<20;i++) { backGround_Shape[i].setSize(Vector2f(WinW,WinH)); backGround_Shape[i].setPosition(0,-WinH*i); backGround_Shape[i].setTexture(&backGround[i]); } //Planets earth_sprite.setPosition(WinW-WinW/2-Earth.getSize().x, WinH-Earth.getSize().y); earth_sprite.setTexture(Earth); mars_sprite.setPosition(WinW-WinW/2-Mars.getSize().x-250,-WinH*2); mars_sprite.setTexture(Mars); jupiter_sprite.setPosition(WinW-WinW/2-jupiter.getSize().x,-WinH*4); jupiter_sprite.setTexture(jupiter); Saturn_sprite.setPosition(WinW-WinW/2-750,-WinH*6); Saturn_sprite.setTexture(Saturn); Uranus_sprite.setPosition(WinW-WinW/2,-WinH*8); Uranus_sprite.setTexture(Uranus); Neptune_sprite.setPosition(WinW-WinW/2-Neptune.getSize().x,-WinH*10); Neptune_sprite.setTexture(Neptune); Pluto_sprite.setPosition(WinW-WinW/2-Pluto.getSize().x+300,-WinH*12); Pluto_sprite.setTexture(Pluto); //EndGame BlackHole_Shape.setPosition(0,-WinH*20); BlackHole_Shape.setSize(Vector2f(WinW,WinH)); BlackHole_Shape.setTexture(&BlackHole); } void GameBackGround::MovingBackGround() { //BackGround for(int i=0;i<20;i++) { if(BlackHole_Shape.getPosition().y<0) { backGround_Shape[i].move(0,1.0); } } //Planets! earth_sprite.move(0,1.0); mars_sprite.move(0,1.0); jupiter_sprite.move(0,1.0); Saturn_sprite.move(0,1.0); Uranus_sprite.move(0,1.0); Neptune_sprite.move(0,1.0); Pluto_sprite.move(0,1.0); //EndGame if(BlackHole_Shape.getPosition().y<0) { BlackHole_Shape.move(0,1.0); } } void GameBackGround::UpdateScreen(float W,float H) { WinW=W; WinH=H; } void GameBackGround::Draw(RenderWindow &Window) { //Background! for(int i=0;i<20;i++) { Window.draw(backGround_Shape[i]); } //Planets! Window.draw(earth_sprite); Window.draw(mars_sprite); Window.draw(jupiter_sprite); Window.draw(Saturn_sprite); Window.draw(Uranus_sprite); Window.draw(Neptune_sprite); Window.draw(Pluto_sprite); //EngGame Window.draw(BlackHole_Shape); } void GameBackGround::RestartBackGround() { //background for(int i=0;i<20;i++) { backGround_Shape[i].setPosition(0,-WinH*i); } //Planets earth_sprite.setPosition(WinW-WinW/2-Earth.getSize().x, WinH-Earth.getSize().y); mars_sprite.setPosition(WinW-WinW/2-Mars.getSize().x-250,-WinH*2); jupiter_sprite.setPosition(WinW-WinW/2-jupiter.getSize().x,-WinH*4); Saturn_sprite.setPosition(WinW-WinW/2-750,-WinH*6); Uranus_sprite.setPosition(WinW-WinW/2,-WinH*8); Neptune_sprite.setPosition(WinW-WinW/2-Neptune.getSize().x,-WinH*10); Pluto_sprite.setPosition(WinW-WinW/2-Pluto.getSize().x+300,-WinH*12); //EndGame BlackHole_Shape.setPosition(0,-WinH*20); } <file_sep>#ifndef ENDGAME_H #define ENDGAME_H #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include <cstdlib> using namespace sf; class EndGame { public: EndGame(); void setEndGameText(); void EndGame_Control(Event MainEvent,bool &DisplayMenu,bool &DisplayGame,bool &DisplayEndGame,bool &RestartGame,Clock *c1,float &timer1,float &timer2); void Draw_EndGame(RenderWindow &Window); private: //Variables int WinW , WinH; //Fonts! Font font; //Text! Text BacktoMainMenu_Text; Text StartNewGame_Text; }; #endif <file_sep>#ifndef COLLISION_H #define COLLISION_H #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include "GameMusic.h" #include <cstdlib> using namespace sf; class Collision { public: Collision(); void Check_LifeState(Sprite Shipsprite,RectangleShape RockDrop_Shape[30],RectangleShape RockRaise_Shape[30],bool &DisplayGame,bool &DisplayEndGame); void Check_RockCrash(RenderWindow &Window,bool &Laser,RectangleShape Laser_Shape,RectangleShape RockDrop_Shape[30],RectangleShape RockRaise_Shape[30],bool &Bonus10,bool &Bonus15); void DrawShipCrash(RenderWindow &Window); void DrawRockCrash(RenderWindow &Window,int &Meteors1_MoveY); private: bool RockCrash=false; int x=0,y=0; int randomRockCrashSize[10]; float CollisionTime1; float CollisionTime2; //Textures Texture RockCrash_texture; //Shapes Sprite ShipeCrash_Sprite; RectangleShape RockCrash_Shape[30][10]; //Textures Texture ShipCrash_Texture; //Objects! GameMusic GameMusic_Object; ///Shield! bool ActivateShield=false; Texture Shield_Texture; CircleShape Shield_Shape; float ActivateShield_Timer=0; float MiniShield_Radius=10; float ActivateShield_Radius=0; }; #endif <file_sep>#include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include <cstdlib> using namespace std; using namespace sf; class Credits { public: Credits(); void setCredits_Text(); void setCreditsBackGround(); void setShapes(); void ShowCredits(RenderWindow &Window); void MoveCredits(); void Credits_Control(Event MainEvent, RenderWindow &Window,bool &DisplayMainMenu,bool &DisplayCredits); void ResetCredits(); private: //Variables int WinW , WinH; //Fonts! Font font; Font calibri_Font; Font vivaldi_Font; //Textures! Texture CreditsBackGround[2]; //Shapes! RectangleShape backGround_Shape[2]; //Text! Text GameDevelopment; Text GameDevelopment_Text[4]; Text BetaTesters; Text BetaTesters_Text[5]; Text SpecialThanks; Text SpecialThanks_Text[18]; Text ProductionTeam; Text CopyRight; Text End_Credit; }; <file_sep>#include "Menu.h" using namespace sf; MainMenu::MainMenu() { WinW=1366; WinH=768; //States! DisplayMainMenu=true; DisplayOptions=false; DisplayHowToPlay=false; DisplayCredits=false; //Music GameMusic_Object.setMainMenu_Music(); //Textures! MenuBackground_Texture.loadFromFile("Data/Pictures/MainMenu/BackGround/MainMenuBackGround.jpg"); //Shapes setShapes(); //Fonts! font.loadFromFile("Data/Fonts/Leander.ttf"); vivaldi_Font.loadFromFile("Data/Fonts/vivaldi.ttf"); //MainMenu Text! for(int i=0;i<5;i++) { Menu_Text[i].setFont(font); Menu_Text[i].setColor(Color(230,230,230)); Menu_Text[i].setCharacterSize(21); } Menu_Text[0].setString("New Game"); Menu_Text[0].setPosition(Line[0].getPosition().x+Menu_Text[0].getCharacterSize()*2.1,Line[0].getPosition().y+4); Menu_Text[0].setColor(Color::Cyan); Menu_Text[1].setString("Options"); Menu_Text[1].setPosition(Line[1].getPosition().x+Menu_Text[1].getCharacterSize()*2.9,Line[1].getPosition().y+4); Menu_Text[2].setString("How to play"); Menu_Text[2].setPosition(Line[2].getPosition().x+Menu_Text[2].getCharacterSize()*1.8,Line[2].getPosition().y+4); Menu_Text[3].setString("Credits"); Menu_Text[3].setPosition(Line[3].getPosition().x+Menu_Text[3].getCharacterSize()*3.2,Line[3].getPosition().y+4); Menu_Text[4].setString("Exit to Desktop"); Menu_Text[4].setPosition(Line[4].getPosition().x+Menu_Text[4].getCharacterSize()*1.1,Line[4].getPosition().y+4); //Variables SelectedElementIndex = 0; MusicStateCount=0; ScreenModeCount=0; } void MainMenu::setShapes() { //BackGround! MenuBackground_Shape.setSize(Vector2f(WinW,WinH)); MenuBackground_Shape.setPosition(0,0); MenuBackground_Shape.setTexture(&MenuBackground_Texture); //Lines! Line_xOffset=150; Line_yOffset=170; for(int i=0;i<6;i++) { Line[i].setSize(Vector2f(200,2)); Line[i].setFillColor(Color(230,230,230)); Line[i].setPosition(WinW/2-Line_xOffset,WinH/2+Line_yOffset); Line_yOffset+=34; } Line[0].setFillColor(Color::Cyan); Line[1].setFillColor(Color::Cyan); } void MainMenu::MoveUp() { if(SelectedElementIndex-1>=0) { Menu_Text[SelectedElementIndex].setColor(Color(230,230,230)); Line[SelectedElementIndex+1].setFillColor(Color(230,230,230)); SelectedElementIndex--; Menu_Text[SelectedElementIndex].setColor(Color::Cyan); Line[SelectedElementIndex].setFillColor(Color::Cyan); GameMusic_Object.setMenuSelect_Sound(); } } void MainMenu::MoveDown() { if(SelectedElementIndex+1<5) { Menu_Text[SelectedElementIndex].setColor(Color(230,230,230)); Line[SelectedElementIndex].setFillColor(Color(230,230,230)); Line[SelectedElementIndex-1].setFillColor(Color(230,230,230)); SelectedElementIndex++; Menu_Text[SelectedElementIndex].setColor(Color::Cyan); Line[SelectedElementIndex].setFillColor(Color::Cyan); Line[SelectedElementIndex+1].setFillColor(Color::Cyan); GameMusic_Object.setMenuSelect_Sound(); } } void MainMenu::setScreenMode(RenderWindow &Window) { if(SelectedElementIndex==1) { if(ScreenModeCount%2==0) { } else { } } } void MainMenu::setMusicState() { if(SelectedElementIndex==2) { if(MusicStateCount%2==0) { } else { } } } void MainMenu::ExitMenu(RenderWindow &Window) { if(SelectedElementIndex==4) { Window.close(); } } void MainMenu::Menu_Control(Event MainEvent,RenderWindow &Window,bool &DisplayMenu,bool &DisplayGame,Clock &c1) { if(DisplayMainMenu==true) { if(MainEvent.type == Event::KeyPressed) { if(MainEvent.key.code == Keyboard::Up) { MoveUp(); } if(MainEvent.key.code == Keyboard::Down) { MoveDown(); } if(MainEvent.key.code == Keyboard::Return) { if(SelectedElementIndex==0) { DisplayGame=true; DisplayMenu=false; c1.restart(); GameMusic_Object.setInGame_Music(); } if(SelectedElementIndex==1) { DisplayMainMenu=false; DisplayOptions=true; } if(SelectedElementIndex==2) { DisplayMainMenu=false; DisplayHowToPlay=true; } if(SelectedElementIndex==3) { DisplayCredits=true; DisplayMainMenu=false; } PlayMode(DisplayMenu); //setScreenMode(Window); //setMusicState(); ExitMenu(Window); } } if(MainEvent.type==Event::KeyReleased) { if(MainEvent.key.code==Keyboard::Return) { if(SelectedElementIndex==0) { } } } } if(DisplayMainMenu==false && DisplayOptions==true) { optionsMenu.Menu_Control(MainEvent,Window,DisplayMainMenu,DisplayOptions); } if(DisplayMainMenu==false && DisplayHowToPlay==true) { howToPlay.Menu_Control(MainEvent,Window,DisplayMainMenu,DisplayHowToPlay); } if(DisplayMainMenu==false && DisplayCredits==true) { credits.Credits_Control(MainEvent,Window,DisplayMainMenu,DisplayCredits); } } void MainMenu::PlayMode(bool &DisplayMenu) { if(SelectedElementIndex == 0) { } } void MainMenu::draw(RenderWindow &Window) { if(DisplayMainMenu==true) { //Drawing BackGround! Window.draw(MenuBackground_Shape); //Drawing Lines! for(int i=0;i<6;i++) { Window.draw(Line[i]); } //Drawing MainMenu Text! for(int i=0;i<5;i++) { Window.draw(Menu_Text[i]); } } if(DisplayMainMenu==false && DisplayOptions==true) { optionsMenu.draw(Window); } if(DisplayMainMenu==false && DisplayHowToPlay==true) { howToPlay.draw(Window); } if(DisplayMainMenu==false && DisplayCredits==true) { credits.ShowCredits(Window); } } <file_sep>#include "EndGame.h" using namespace sf; EndGame::EndGame() { WinW=1366; WinH=768; //Fonts font.loadFromFile("Data/Fonts/Leander.ttf"); setEndGameText(); } void EndGame::setEndGameText() { BacktoMainMenu_Text.setFont(font); BacktoMainMenu_Text.setString("Press [ESC] to back to MainMenu"); BacktoMainMenu_Text.setCharacterSize(15); BacktoMainMenu_Text.setPosition(WinW/2-(BacktoMainMenu_Text.getGlobalBounds().width/2)-10,WinH/2-350); StartNewGame_Text.setFont(font); StartNewGame_Text.setString("Press [Enter] to start a new Game"); StartNewGame_Text.setCharacterSize(22); StartNewGame_Text.setPosition(WinW/2-(StartNewGame_Text.getGlobalBounds().width/2)-10,WinH/2-100); } void EndGame::EndGame_Control(Event MainEvent,bool &DisplayMenu,bool &DisplayGame,bool &DisplayEndGame,bool &RestartGame,Clock *c1,float &timer1,float &timer2) { if(MainEvent.type == Event::KeyPressed) { if(MainEvent.key.code == Keyboard::Escape) { DisplayEndGame=false; DisplayMenu=true; } if(MainEvent.key.code == Keyboard::Return) { DisplayEndGame=false; DisplayGame=true; RestartGame=true; c1->restart(); timer1=0; timer2=0; } } } void EndGame::Draw_EndGame(RenderWindow &Window) { Window.draw(BacktoMainMenu_Text); Window.draw(StartNewGame_Text); } <file_sep>#include "Credits.h" using namespace sf; Credits::Credits() { WinW=1366; WinH=768; //Font! font.loadFromFile("Data/Fonts/Leander.ttf"); calibri_Font.loadFromFile("Data/Fonts/calibri.ttf"); vivaldi_Font.loadFromFile("Data/Fonts/vivaldi.ttf"); //Textures! CreditsBackGround[0].loadFromFile("Data/Pictures/Credits/backGround0.png"); CreditsBackGround[1].loadFromFile("Data/Pictures/Credits/backGround1.png"); //Shapes setShapes(); //Text! setCredits_Text(); } void Credits::setShapes() { for(int i=0;i<2;i++) { backGround_Shape[i].setSize(Vector2f(WinW,WinH)); backGround_Shape[i].setPosition(WinW*i,0); backGround_Shape[i].setTexture(&CreditsBackGround[i]); } } void Credits::setCredits_Text() { //GameDevelopment GameDevelopment.setString("Game Development"); GameDevelopment.setFont(font); GameDevelopment.setCharacterSize(40); GameDevelopment.setPosition((WinW/2)-(GameDevelopment.getGlobalBounds().width/2) ,WinH+10); GameDevelopment_Text[0].setString("<NAME>ub"); GameDevelopment_Text[1].setString("<NAME>"); GameDevelopment_Text[2].setString("Taha ben achour"); GameDevelopment_Text[3].setString("Abdulmoneim izmaim"); int yOffset=30; for(int i=0;i<4;i++) { GameDevelopment_Text[i].setFont(font); GameDevelopment_Text[i].setCharacterSize(20); GameDevelopment_Text[i].setPosition((WinW/2)-(GameDevelopment_Text[i].getGlobalBounds().width/2) , GameDevelopment.getPosition().y+30+yOffset); yOffset+=30; } //Beta testers BetaTesters.setString("BetaEditions Testers"); BetaTesters.setFont(font); BetaTesters.setCharacterSize(40); BetaTesters.setPosition((WinW/2)-(BetaTesters.getGlobalBounds().width/2) ,GameDevelopment_Text[3].getPosition().y+300); BetaTesters_Text[0].setString("<NAME>"); BetaTesters_Text[1].setString("<NAME>"); BetaTesters_Text[2].setString("<NAME>"); BetaTesters_Text[3].setString("<NAME>"); BetaTesters_Text[4].setString("<NAME>"); yOffset=30; for(int i=0;i<5;i++) { BetaTesters_Text[i].setFont(font); BetaTesters_Text[i].setCharacterSize(20); BetaTesters_Text[i].setPosition((WinW/2)-(BetaTesters_Text[i].getGlobalBounds().width/2) ,BetaTesters.getPosition().y+30+yOffset); yOffset+=30; } //SpecialThanks SpecialThanks.setString("Special Thanks to"); SpecialThanks.setFont(font); SpecialThanks.setCharacterSize(40); SpecialThanks.setPosition((WinW/2)-(SpecialThanks.getGlobalBounds().width/2) , BetaTesters_Text[4].getPosition().y+300); //EC252 Teachers! SpecialThanks_Text[0].setString("EC252 Teachers:"); SpecialThanks_Text[1].setString("Dr.<NAME>"); SpecialThanks_Text[2].setString("Eng.<NAME>"); //Spring 2016 Students! SpecialThanks_Text[3].setString("EC252 Students:"); SpecialThanks_Text[4].setString("<NAME>"); SpecialThanks_Text[5].setString("<NAME>"); SpecialThanks_Text[6].setString("<NAME>"); SpecialThanks_Text[7].setString("<NAME>"); SpecialThanks_Text[8].setString("<NAME>"); SpecialThanks_Text[9].setString("<NAME>"); SpecialThanks_Text[10].setString("<NAME>"); SpecialThanks_Text[11].setString("<NAME>"); SpecialThanks_Text[12].setString("<NAME>"); SpecialThanks_Text[13].setString("<NAME>"); SpecialThanks_Text[14].setString("<NAME>"); SpecialThanks_Text[15].setString("<NAME>"); SpecialThanks_Text[16].setString("<NAME>"); SpecialThanks_Text[17].setString("<NAME>"); yOffset=30; for(int i=0;i<18;i++) { if(i==0) { SpecialThanks_Text[i].setFont(calibri_Font); SpecialThanks_Text[i].setStyle(Text::Bold); SpecialThanks_Text[i].setCharacterSize(32); SpecialThanks_Text[i].setPosition((WinW/2)-(SpecialThanks_Text[i].getGlobalBounds().width/2) , SpecialThanks.getPosition().y+30+yOffset); yOffset+=30; } else if(i!=0 || i!=3) { SpecialThanks_Text[i].setFont(font); SpecialThanks_Text[i].setCharacterSize(20); if(i<3) { SpecialThanks_Text[i].setPosition((WinW/2)-(SpecialThanks_Text[i].getGlobalBounds().width/2) , SpecialThanks.getPosition().y+40+yOffset); } if(i>3) { SpecialThanks_Text[i].setPosition((WinW/2)-(SpecialThanks_Text[i].getGlobalBounds().width/2) , SpecialThanks.getPosition().y+30+yOffset); } yOffset+=30; } if(i==3) { SpecialThanks_Text[i].setFont(calibri_Font); SpecialThanks_Text[i].setStyle(Text::Bold); SpecialThanks_Text[i].setCharacterSize(32); SpecialThanks_Text[i].setPosition((WinW/2)-(SpecialThanks_Text[i].getGlobalBounds().width/2) , SpecialThanks.getPosition().y+20+yOffset); yOffset+=30; } } //Producers! ProductionTeam.setString("Produced by AlphaCrew"); ProductionTeam.setFont(font); ProductionTeam.setCharacterSize(40); ProductionTeam.setPosition((WinW/2)-(ProductionTeam.getGlobalBounds().width/2), SpecialThanks_Text[17].getPosition().y+300); //CopyRights CopyRight.setString("all rights are reserved 2016"); CopyRight.setFont(font); CopyRight.setCharacterSize(20); CopyRight.setPosition((WinW/2)-(CopyRight.getGlobalBounds().width/2),ProductionTeam.getPosition().y+50); //EndCredits End_Credit.setString("Press [ESC] to back to MainMenu"); End_Credit.setFont(font); End_Credit.setCharacterSize(28); End_Credit.setPosition((WinW/2)-(End_Credit.getGlobalBounds().width/2),WinH/2); } void Credits::ResetCredits() { //BackGround for(int i=0;i<2;i++) { backGround_Shape[i].setPosition(WinW*i,0); } //GameDevelopment GameDevelopment.setPosition((WinW/2)-(GameDevelopment.getGlobalBounds().width/2) ,WinH+20); int yOffset=30; for(int i=0;i<4;i++) { GameDevelopment_Text[i].setPosition((WinW/2)-(GameDevelopment_Text[i].getGlobalBounds().width/2) , GameDevelopment.getPosition().y+30+yOffset); yOffset+=30; } BetaTesters.setPosition((WinW/2)-(BetaTesters.getGlobalBounds().width/2) ,GameDevelopment_Text[3].getPosition().y+300); yOffset=30; for(int i=0;i<5;i++) { BetaTesters_Text[i].setPosition((WinW/2)-(BetaTesters_Text[i].getGlobalBounds().width/2) ,BetaTesters.getPosition().y+30+yOffset); yOffset+=30; } //SpecialThanks SpecialThanks.setPosition((WinW/2)-(SpecialThanks.getGlobalBounds().width/2) , BetaTesters_Text[4].getPosition().y+300); yOffset=30; for(int i=0;i<18;i++) { if(i==0) { SpecialThanks_Text[i].setPosition((WinW/2)-(SpecialThanks_Text[i].getGlobalBounds().width/2) , SpecialThanks.getPosition().y+30+yOffset); yOffset+=30; } else if(i!=0 || i!=3) { if(i<3){SpecialThanks_Text[i].setPosition((WinW/2)-(SpecialThanks_Text[i].getGlobalBounds().width/2) , SpecialThanks.getPosition().y+40+yOffset);} if(i>3){SpecialThanks_Text[i].setPosition((WinW/2)-(SpecialThanks_Text[i].getGlobalBounds().width/2) , SpecialThanks.getPosition().y+30+yOffset);} yOffset+=30; } if(i==3) { SpecialThanks_Text[i].setPosition((WinW/2)-(SpecialThanks_Text[i].getGlobalBounds().width/2) , SpecialThanks.getPosition().y+20+yOffset); yOffset+=30; } } ProductionTeam.setPosition((WinW/2)-(ProductionTeam.getGlobalBounds().width/2), SpecialThanks_Text[17].getPosition().y+300); CopyRight.setPosition((WinW/2)-(CopyRight.getGlobalBounds().width/2),ProductionTeam.getPosition().y+50); End_Credit.setPosition((WinW/2)-(End_Credit.getGlobalBounds().width/2),WinH/2); } void Credits::Credits_Control(Event MainEvent, RenderWindow &Window,bool &DisplayMainMenu,bool &DisplayCredits) { if(MainEvent.type == Event::KeyPressed) { if(MainEvent.key.code == Keyboard::Escape) { DisplayMainMenu=true; DisplayCredits=false; ResetCredits(); } } } void Credits::MoveCredits() { //BackGround for(int i=0;i<2;i++){backGround_Shape[i].move(-0.24,0);} if(backGround_Shape[1].getPosition().x<0){backGround_Shape[1].move(0.24,0);} ///Text //GameDevelopment GameDevelopment.move(0,-0.48); for(int i=0;i<4;i++){GameDevelopment_Text[i].move(0,-0.48);} //BetaTesters BetaTesters.move(0,-0.48); for(int i=0;i<5;i++){BetaTesters_Text[i].move(0,-0.48);} //SpecialThanks SpecialThanks.move(0,-0.48); for(int i=0;i<18;i++){SpecialThanks_Text[i].move(0,-0.48);} //Production && CopyRights ProductionTeam.move(0,-0.48); CopyRight.move(0,-0.48); } void Credits::ShowCredits(RenderWindow &Window) { MoveCredits(); //BackGround for(int i=0;i<2;i++){Window.draw(backGround_Shape[i]);} //GameDevelopment Window.draw(GameDevelopment); for(int i=0;i<4;i++){Window.draw(GameDevelopment_Text[i]);} //BetaTesters Window.draw(BetaTesters); for(int i=0;i<5;i++){Window.draw(BetaTesters_Text[i]);} //SpecialThanks Window.draw(SpecialThanks); for(int i=0;i<18;i++){Window.draw(SpecialThanks_Text[i]);} //ProductionTeam Window.draw(ProductionTeam); //CopyRight Window.draw(CopyRight); //EndCredits if(CopyRight.getPosition().y<-100){Window.draw(End_Credit);} } <file_sep>#include "HowToPlay.h" using namespace sf; HowToPlay::HowToPlay() { WinW=1366; WinH=768; //Textures! HowToPlay_Texture.loadFromFile("Data/Pictures/MainMenu/How to Play-Menu/HowToPlay PopUp-Menu2.png"); //Shapes! HowToPlay_Shape.setSize(Vector2f(WinW,WinH)); HowToPlay_Shape.setPosition(0,0); HowToPlay_Shape.setTexture(&HowToPlay_Texture); } void HowToPlay::Menu_Control(Event MainEvent,RenderWindow &Window,bool &DisplayMainMenu,bool &DisplayHowToPlay) { if(MainEvent.type == Event::KeyPressed) { if(MainEvent.key.code==Keyboard::Escape) { DisplayMainMenu=true; DisplayHowToPlay=false; } } } void HowToPlay::draw(RenderWindow &Window) { Window.draw(HowToPlay_Shape); } <file_sep>#ifndef OPTIONSMENU_H #define OPTIONSMENU_H #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> using namespace std; using namespace sf; class OptionsMenu { public: OptionsMenu(); void setShapes(); void Menu_Control(Event MainEvent,RenderWindow &Window, bool &DisplayMainMenu,bool &DisplayOptions); void draw(RenderWindow &Window); void MoveRight(); void MoveLeft(); private: //Data float WinW; float WinH; int SelectedElementIndex; int MusicStateCount; int ScreenModeCount; //Textures! Texture OptionsScreen_Texture[3]; //Fonts! Font font; Font vivaldi_Font; //Shapes! RectangleShape OptionsScreen_Shape; //Sound buffers! SoundBuffer MenuSelect_buffer; //Sounds! Sound MenuSelect_Sound; }; #endif <file_sep>#ifndef SCORE_H #define SCORE_H #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include <iostream> #include <sstream> #include <time.h> #include <cstdlib> #include <fstream> using namespace sf; class Score { public: Score(); void DrawScore(RenderWindow &Window); void SetScore(bool &DisplayGame,bool &RestartGame,Time &GameTimer); void setFile(float PlayerScore); void setBonus(RenderWindow &Window); void setHighScore(); void ChangeColor(); void RestartColor(); bool Bonus10; bool Bonus15; private: //Variables int WinW; int WinH; float ScorePoints; int PlayerScore; int newScore; int HighScore; int x; int temp; int OldScore; int randNum; //Textures! Texture Bonus10_Texture; Texture Bonus15_Texture; //Shapes Sprite Bonus10_Sprite; Sprite Bonus15_Sprite; //Fonts Font Score_Font; Font font; Font vivaldi_Font; //Text Text Score_Text; Text Score_Number; Text HighScore_Text; Text HighScore_Number; }; #endif <file_sep>#ifndef GAMEBACKGROUND_H #define GAMEBACKGROUND_H #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> using namespace std; using namespace sf; class GameBackGround { public: GameBackGround(); void UpdateScreen(float W,float H); void setShapes(); void MovingBackGround(); void Draw(RenderWindow &Window); void RestartBackGround(); private: //Data Members! float WinW; float WinH; //Textures Texture backGround[20]; Texture Earth; Texture Mars; Texture jupiter; Texture Saturn; Texture Uranus; Texture Neptune; Texture Pluto; Texture BlackHole; //background RectangleShape backGround_Shape[20]; RectangleShape BlackHole_Shape; //Planets! Sprite earth_sprite; Sprite mars_sprite; Sprite jupiter_sprite; Sprite Saturn_sprite; Sprite Uranus_sprite; Sprite Neptune_sprite; Sprite Pluto_sprite; }; #endif <file_sep>#include "Ship.h" using namespace sf; Ship::Ship() { //Screen Width & Height! WinW = 1366; WinH = 768; //Variables diffualtSpeed=4; xVelocity=diffualtSpeed; yVelocity=diffualtSpeed; IncreaseSpeed=6.0; MaxSpeed=3.0; //States Upbutton=false; Downbutton=false; Rightbutton=false; Leftbutton=false; SpeedUp=false; Laser=false; //Textures Ship1_Texture.loadFromFile("Data/Pictures/SpaceShips/ship.png"); Laser_Texture.loadFromFile("Data/Pictures/Laser/laser5.png"); Turbo_Texture.loadFromFile("Data/Pictures/turbo/turbo210.png"); //Shapes Ship1_Sprite.setPosition(WinW/2,WinH-Ship1_Texture.getSize().y); Ship1_Sprite.move(0,0); Ship1_Sprite.setTexture(Ship1_Texture); Ship1_Sprite.setOrigin(Ship1_Sprite.getLocalBounds().height/2,Ship1_Sprite.getLocalBounds().width/2); Laser_Shape.setPosition(Ship1_Sprite.getPosition().x-11.8,6.5); Laser_Shape.setSize(Vector2f(15,(WinH-Ship1_Sprite.getGlobalBounds().height/1.128))); Laser_Shape.setTexture(&Laser_Texture); Laser_Shape.setScale(Vector2f(0.8,Laser_Shape.getScale().y)); Laser_Shape.setFillColor(Color::Cyan); Turbo1_Sprite.setTexture(Turbo_Texture); Turbo2_Sprite.setTexture(Turbo_Texture); } void Ship::ShipControl(Event event,bool &DisplayInGameMenu,bool &DisplayGame) { //KeyPressed if(event.type == Event::KeyPressed) { if(Keyboard::isKeyPressed(Keyboard::Up)) { Upbutton=true; } if(Keyboard::isKeyPressed(Keyboard::Down)) { Downbutton=true; } if(Keyboard::isKeyPressed(Keyboard::Right)) { Rightbutton=true; } if( Keyboard::isKeyPressed(Keyboard::Left)) { Leftbutton=true; } if(event.key.code==Keyboard::Space) { Laser_Timer+=0.01; if(Laser_Timer<0.01){Laser=true;} if(Laser_Timer>0.01){Laser=false;} } if(event.key.code == Keyboard::LShift || event.key.code == Keyboard::RShift) { SpeedUp = true; if(SpeedUp==true) { xVelocity=diffualtSpeed+IncreaseSpeed; yVelocity=diffualtSpeed+IncreaseSpeed; GameMusic_Object.setTurbo_Sound(); } } } //KeyReleased! if(event.type == Event::KeyReleased) { if(event.key.code==Keyboard::Escape) { DisplayInGameMenu=true; DisplayGame=false; } if(event.key.code==Keyboard::Up) { Upbutton=false; } if(event.key.code==Keyboard::Down) { Downbutton=false; } if(event.key.code==Keyboard::Right) { Rightbutton=false; } if(event.key.code==Keyboard::Left) { Leftbutton=false; } if(event.key.code == Keyboard::Space) { Laser=false; Laser_Timer=0; } if(event.key.code == Keyboard::LShift || event.key.code == Keyboard::RShift) { SpeedUp = false; if(SpeedUp == false) { xVelocity=diffualtSpeed; yVelocity=diffualtSpeed; } } } } void Ship::Logics() { if(Upbutton==true) { Ship1_Sprite.move(0,-yVelocity); Laser_Shape.setSize(Vector2f(Laser_Shape.getSize().x,Ship1_Sprite.getPosition().y+15)); } if(Downbutton==true) { Ship1_Sprite.move(0,yVelocity); Laser_Shape.setSize(Vector2f(Laser_Shape.getSize().x,Ship1_Sprite.getPosition().y+15)); } if(Rightbutton==true) { Ship1_Sprite.move(xVelocity,0); Laser_Shape.setPosition(Ship1_Sprite.getPosition().x-11.8,Laser_Shape.getPosition().y); } if(Leftbutton==true) { Ship1_Sprite.move(-xVelocity, 0); Laser_Shape.setPosition(Ship1_Sprite.getPosition().x-11.8,Laser_Shape.getPosition().y); } if(Upbutton==true||Downbutton==true||Rightbutton==true||Leftbutton==true) { Turbo1_Sprite.setPosition(Ship1_Sprite.getPosition().x-Turbo_Texture.getSize().x+22,Ship1_Sprite.getPosition().y+Turbo_Texture.getSize().y+24); Turbo2_Sprite.setPosition(Turbo1_Sprite.getPosition().x-28,Turbo1_Sprite.getPosition().y-0.5); } if(Laser==true) { GameMusic_Object.setLaser_Sound(); } //Out of Screen bounds Check! if(Ship1_Sprite.getPosition().y < 100) { Ship1_Sprite.setPosition(Ship1_Sprite.getPosition().x,100); Laser_Shape.setSize(Vector2f(Laser_Shape.getSize().x,Ship1_Sprite.getPosition().y+15)); Laser_Shape.setScale(Vector2f(0.79,Laser_Shape.getScale().y)); Turbo1_Sprite.setPosition(Ship1_Sprite.getPosition().x-Turbo_Texture.getSize().x+22,Ship1_Sprite.getPosition().y+Turbo_Texture.getSize().y+24); Turbo2_Sprite.setPosition(Turbo1_Sprite.getPosition().x-28,Turbo1_Sprite.getPosition().y-0.5); } if(Ship1_Sprite.getPosition().y > WinH-110) { Ship1_Sprite.setPosition(Ship1_Sprite.getPosition().x,WinH-110); Laser_Shape.setSize(Vector2f(Laser_Shape.getSize().x,Ship1_Sprite.getPosition().y+15)); Turbo1_Sprite.setPosition(Ship1_Sprite.getPosition().x-Turbo_Texture.getSize().x+22,Ship1_Sprite.getPosition().y+Turbo_Texture.getSize().y+24); Turbo2_Sprite.setPosition(Turbo1_Sprite.getPosition().x-28,Turbo1_Sprite.getPosition().y-0.5); } if((Ship1_Sprite.getPosition().x) < 100) { Ship1_Sprite.setPosition(100,Ship1_Sprite.getPosition().y); Laser_Shape.setPosition(Laser_Shape.getPosition().x+3.25,Laser_Shape.getPosition().y); if(Leftbutton==true && SpeedUp==true) { Laser_Shape.setPosition(Laser_Shape.getPosition().x+6,Laser_Shape.getPosition().y); } Turbo1_Sprite.setPosition(Ship1_Sprite.getPosition().x-Turbo_Texture.getSize().x+22,Ship1_Sprite.getPosition().y+Turbo_Texture.getSize().y+24); Turbo2_Sprite.setPosition(Turbo1_Sprite.getPosition().x-28,Turbo1_Sprite.getPosition().y-0.5); } if(Ship1_Sprite.getPosition().x>WinW-100) { Ship1_Sprite.setPosition(WinW-100,Ship1_Sprite.getPosition().y); Laser_Shape.setPosition(Laser_Shape.getPosition().x-3.25,Laser_Shape.getPosition().y); if(Rightbutton==true && SpeedUp==true) { Laser_Shape.setPosition(Laser_Shape.getPosition().x-6,Laser_Shape.getPosition().y); } Turbo1_Sprite.setPosition(Ship1_Sprite.getPosition().x-Turbo_Texture.getSize().x+22,Ship1_Sprite.getPosition().y+Turbo_Texture.getSize().y+24); Turbo2_Sprite.setPosition(Turbo1_Sprite.getPosition().x-28,Turbo1_Sprite.getPosition().y-0.5); } } void Ship::RestartShip() { Ship1_Sprite.move(0,0); Ship1_Sprite.setPosition(WinW/2,WinH-Ship1_Texture.getSize().y); Ship1_Sprite.setOrigin(Ship1_Sprite.getLocalBounds().height/2,Ship1_Sprite.getLocalBounds().width/2); Laser_Shape.setPosition(Ship1_Sprite.getPosition().x-13,6.5); } void Ship::ShipDraw(RenderWindow &Window) { //Ship Window.draw(Ship1_Sprite); //turbo if(Upbutton==true || Downbutton==true || Rightbutton==true || Leftbutton==true) { Window.draw(Turbo1_Sprite); Window.draw(Turbo2_Sprite); } //Laser if(Laser == true) { Window.draw(Laser_Shape); } }
abc236ce827d77e3af05789710715c426e2da47a
[ "Markdown", "C++" ]
28
C++
tahaak67/Astroid-War-Game
cd8fce07c95d1464720fdeaa7f8aaf7f3b02ae17
878a4c87d91accb5ff04cf4e3534b1ecd8638c94
refs/heads/master
<repo_name>testgit008/test2<file_sep>/Test.cpp #include <iostream> using namespace std; int main(int argc,char* argv[]) { cout<<"argc:"<<argc<<endl; for(int i=0;i<argc;i++) { cout<<argv[i]<<endl; } //动态分配二维数组 double *p1=(double*)malloc(2*2*sizeof(double)); double (*p)[2]=(double(*)[2])p1; if(p==NULL) cout<<"malloc error!"<<endl; p[0][0]=1.1; p[0][1]=2.1; p[1][0]=0.8; p[1][1]=0.9; cout<<p<<endl; cout<<sizeof(double)<<endl; for(int j=0;j<2;j++) for(int k=0;k<2;k++) cout<<p[j][k]<<" "<<&(p[j][k])<<endl; return 0; }
33edf15321c95c270fbaf08b506f5c4fe32b8f1e
[ "C++" ]
1
C++
testgit008/test2
726e91ff16e73a181073f6e8da5f703488f7dbc3
2c236f41472ca88c6e13eea2f3b4b58df17bcbd0
HEAD
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BiBo { public class Book { //Member-Variablen Deklaration private ulong bookId; private string author; //<NAME> private string titel; //Titel private string subjectArea; //Fachrichtung private List<Exemplar> exemplare; //Liste aller Exemplare public ulong BookId { get { return this.bookId; } set { this.bookId = value; } } // Setter of the next Property´s can be deleted public string Author { get { return this.author; } set { this.author = value; } } public string Titel { get { return this.titel; } set { this.titel = value; } } public string SubjectArea { get { return this.subjectArea; } set { this.subjectArea = value; } } public List<Exemplar> Exemplare { get { return this.exemplare; } set { this.exemplare= value; } } //Konstruktor public Book(ulong bookId, string author, string titel, string subjectArea) { this.bookId = bookId; this.author = author; this.titel = titel; this.subjectArea = subjectArea; exemplare = new List<Exemplar>(); } //Methoden public string CreateSignatur() { string authorPrefix = this.Author[0].ToString(); string subjectAreaPrefix; if (this.SubjectArea.Length > 3) { subjectAreaPrefix = this.SubjectArea.Substring(0, 3); } else { subjectAreaPrefix = this.SubjectArea; } return "[" + authorPrefix + subjectAreaPrefix; } public override string ToString() { return this.Author + " " + this.Titel + " " + this. subjectArea; } } } <file_sep>using System; using BiBo; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Test { [TestClass()] public class ChargeTest { [TestMethod()] public void ChangeAt_CurrentValue_ChangeValues_Test() { DateTime changedAt = DateTime.Today; decimal currentValue = 500; decimal changeValue = 50; Charge ch = new Charge(currentValue, changeValue); Assert.IsTrue(ch.ChangeAt == changedAt); Assert.IsTrue(ch.CurrentValue == currentValue); Assert.IsTrue(ch.ChangeValues == changeValue); } } } <file_sep>using BiBo; using BiBo.DAO; using BiBo.SQL; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Linq; namespace Test.DAO { [TestClass()] public class BookDAOTest { [TestMethod()] //Add a book with a given number of examples public void AddBookTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong bookId = 100; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); int countOfExamples = 1; for (int i = 0; i < countOfExamples; i++) { Exemplar ex = new Exemplar(boo); ulong id = lib.SQLHandler.ExemplarSQL.AddEntryReturnId(ex); ex.ExemplarId = id; boo.Exemplare.Add(ex); } //insert in db and dummy get the right id boo.BookId = lib.SQLHandler.BookSQL.AddEntryReturnId(boo); //in objects lib.BookList.Add(boo); //refresh GUI-View lib.GUIApi.AddBook(boo); lib.GUIApi.Add_b_Book(boo); //borrow panel lib.GUIApi.Add_c_Book(boo); //customer area BookDAO booDAO = new BookDAO(lib); booDAO.AddBook(boo, countOfExamples); Assert.Inconclusive("Erfolgreich"); } [TestMethod()] //Gibt Buch zu der entsprechenden ID public void GetBookByIdTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong bookId = 100; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); Exemplar ex = new Exemplar(boo); int countOfExamples = 1; lib.BookList.Add(boo); foreach (Book book in lib.BookList) { if (book.BookId == bookId) Assert.IsTrue(true); } BookDAO booDAO = new BookDAO(lib); booDAO.AddBook(boo, countOfExamples); Assert.AreEqual(booDAO.GetBookById(bookId), bookId); } [TestMethod()] //Löscht gegebenes Buch aus Objekt sowie Datenbank - schicht public void DeleteBookTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); BookDAO booDAO = new BookDAO(lib); ulong bookId = 100; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); int countOfExamples = 1; booDAO.AddBook(boo, countOfExamples); if (boo.Exemplare.Count(e => e.Borrower != null) > 0) throw new System.Exception("Es sind noch Exemplare ausgeliehen"); List<ulong> idList = new List<ulong>(); foreach (Exemplar exemplar in boo.Exemplare) { idList.Add(exemplar.ExemplarId); } lib.BookList.Remove(boo); //delete in DB lib.SQLHandler.BookSQL.DeleteEntry(boo); lib.SQLHandler.ExemplarSQL.DeleteEntryByIdList(idList); Assert.IsTrue(lib.SQLHandler.BookSQL.DeleteEntry(boo)); Assert.IsTrue(lib.SQLHandler.ExemplarSQL.DeleteEntryByIdList(idList)); //in gui lib.GUIApi.DeleteBook(boo); Assert.IsNull(boo); booDAO.DeleteBook(boo); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using BiBo.SQL; using BiBo.Persons; namespace BiBo.DAO { public class CardDAO { private Library lib; public CardDAO(Library lib) { this.lib = lib; } public void AddCard(ulong customerID) { Customer customer = lib.CustomerList.Find(cu => cu.CustomerID == customerID); Card card = new Card(customer); //add Card to Customer card.CardID = lib.SQLHandler.CardSQL.AddEntryReturnId(card); //add user in Objects lib.DAOHandler.CustomerDAO.UpdateCustomer(customer); } //verlängert die Gültigkeit des Ausweises eines Kunden public void ExtendValidity(ulong customerID) { Customer customer = lib.CustomerList.Find(cust => cust.CustomerID == customerID); if (customer.ChargeAccount.Charges.Count > 0) { if (customer.ChargeAccount.Charges.Last().CurrentValue != 0) throw new System.Exception("Ausweis kann nicht verlängert werden, ChargeAccount nicht ausgeglichen"); } //on object-layer customer.Card.CardValidUntil = customer.Card.CardValidUntil.AddYears(1); //on db-layer lib.SQLHandler.CardSQL.UpdateEntry(customer.Card); //on gui lib.GUIApi.UpdateCustomer(customer); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using BiBo.SQL; using BiBo.Persons; using BiBo.Exception; using System.Windows; namespace BiBo.DAO { public class CustomerDAO { private Library lib; public CustomerDAO(Library lib) { this.lib = lib; } public Customer FindCustomerWhoBorrowed(ulong expl_id) { return lib.ExemplarList.Find(e => e.ExemplarId == expl_id).Borrower; } //Fügt einen neuen Customer der Datenbank und Objektschicht hinzu public void AddCustomer(Customer customer) { //add an empty ChargeAccount ChargeAccount chargeAccount = new ChargeAccount(customer); chargeAccount.Id = 0; customer.ChargeAccount = chargeAccount; //add user to DB and dummy get the right id customer.CustomerID = lib.SQLHandler.CustomerSQL.AddEntryReturnId(customer); //manybe it is also good to set customer id and the customer chargeAccount.CustomerID = customer.CustomerID; customer.ChargeAccount.Customer = customer; chargeAccount.Id = lib.SQLHandler.ChargeAccountSQL.AddEntryReturnId(chargeAccount); customer.ChargeAccount = chargeAccount; lib.SQLHandler.CustomerSQL.UpdateEntry(customer); //add the customer card Card card = new Card(customer); DateTime valid = new DateTime(); valid = DateTime.Now.AddYears(1); card.CardValidUntil = valid; card.CardID = lib.SQLHandler.CardSQL.AddEntryReturnId(card); customer.Card = card; lib.DAOHandler.ChargeAccountDAO.Burden(customer, (decimal)lib.Fee, "fee"); //add user in Objects lib.CustomerList.Add(customer); //refresh GUI-View lib.GUIApi.AddCustomer(customer); lib.GUIApi.BlockSelectionEvents(true); lib.GUIApi.Add_b_Customer(customer); lib.GUIApi.BlockSelectionEvents(false); } //Setzt den Status eines Kunden in der Datenbank und Objektschicht als gelöscht public void DeleteCustomer(Customer customer) { decimal currentValue = 0; //Last() on empty list will return NULL if (customer.ChargeAccount.Charges.Count > 0) { currentValue = customer.ChargeAccount.Charges.Last().CurrentValue; } if (currentValue == 0 && customer.ExemplarList.Count == 0) { //on object-layer customer.UserState = UserStates.DELETED; //on db-layer we simple need an update to store also data of deleted users customer.UserState = UserStates.DELETED; customer.DeletedAt = DateTime.Now; lib.SQLHandler.CustomerSQL.UpdateEntry(customer); //on view-layer lib.GUIApi.DeleteCustomer(customer); } else throw new System.Exception(customer.FirstName + " " + customer.LastName + " kann nicht gelöscht werden, da entweder Exemplare ausgeliehen sind, oder das Gebührenkonto nicht ausgegelichen ist"); } //method to edit a customer public void UpdateCustomer(Customer customer) { //on object-layer lib.CustomerList.RemoveAll(cu => cu.CustomerID == customer.CustomerID); lib.CustomerList.Add(customer); //on db lib.SQLHandler.CustomerSQL.UpdateEntry(customer); //on view lib.GUIApi.UpdateCustomer(customer); } //gibt zu einer ID den entsprechenden CKunden public Customer GetCustomerById(ulong id) { Customer customer = lib.CustomerList.Find(cust => cust.CustomerID == id); if(customer != null) return customer; throw new CustomerNotFoundException("Benutzer mit gegebener ID nicht vorhanden"); } //Setzt das Passwort eines Kunden public void SetPassword(Customer cust, string password) { cust.Password = getMD5(password); } //Prüft das Passwort auf richtigkeit public bool checkPass(Customer customer, String pass){ return getMD5(pass) == customer.Password; } //Liefert den MD5 Hash public static String getMD5(String from) { MD5 md5 = MD5.Create(); byte[] output = md5.ComputeHash(Encoding.UTF8.GetBytes(from)); StringBuilder builder = new StringBuilder(); foreach (byte by in output) { builder.Append(by.ToString("x2")); } return builder.ToString(); } //Leiht ein Exemplar aus public bool BorrowExemplar(Exemplar exemplar, Customer customer) { //Prüfung, ob Buch bereits ausgeliehen ist if (exemplar.Borrower != null) throw new System.Exception("Buch bereits ausgeliehen"); //Prüfung, ob Karte von Kunden gültig ist if(customer.Card.CardValidUntil.CompareTo(DateTime.Today.AddDays(1)) < 0) throw new System.Exception("Karte nicht gültig"); //Wenn alles Ok ist, leihe das Buch aus if (customer.UserState == UserStates.ACTIVE) { //on object-layer exemplar.LoanPeriod = DateTime.Now.AddMonths(1); exemplar.Borrower = customer; exemplar.CustomerId = customer.CustomerID; customer.ExemplarList.Add(exemplar); //on db-layer update the customer lib.SQLHandler.CustomerSQL.UpdateEntry(customer); //on db-layer update the exemplar lib.SQLHandler.ExemplarSQL.UpdateEntry(exemplar); //on gui Book book = lib.DAOHandler.BookDAO.GetBookById(exemplar.BookId); lib.GUIApi.moveExemplarFormBookToCustomer(exemplar, book); return true; } throw new System.Exception("Kunde ist nicht Aktiv"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SQLite; using System.Data.SqlTypes; using BiBo.Persons; namespace BiBo.SQL { public class ChargeSQL { private SqlConnector SQLHandler; public ChargeSQL(SqlConnector sqlc) { this.SQLHandler = sqlc; } // Add ChargeTransaction public bool AddEntry(Charge obj) { try { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); if (command != null) { command.CommandText = @"INSERT INTO ChargeTransactions ( TransactionID, ChargeAccountID, change, newValue, changedAt, type ) VALUES ( NULL, '" + obj.ChargeAccountId + @"', '" + obj.ChangeValues + @"', '" + obj.CurrentValue + @"', '" + DateTime.Now + @"', '" + obj.Type + @"' );"; command.ExecuteNonQuery(); } return true; } catch (System.Exception) { return false; } } // Add ChageTransaction, return id public ulong AddEntryReturnId(Charge obj) { AddEntry(obj); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "select last_insert_rowid()"; UInt64 lastRowID64 = Convert.ToUInt64(command.ExecuteScalar()); // UInt64 lastRowID64 = (UInt64)command.ExecuteScalar(); // Fehler System.InvalidCastException: Die angegebene Umwandlung ist ungültig. return (ulong)lastRowID64; } // Get all Transactions public List<Charge> GetAllEntrys() { List<Charge> chargeList = new List<Charge>(); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "SELECT * FROM ChargeTransactions"; SQLiteDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { chargeList.Add(InitEntryByReader(reader)); } } return chargeList; } // Reder for Database protected Charge InitEntryByReader(SQLiteDataReader reader) { int intId = reader.GetInt32(reader.GetOrdinal("TransactionID")); ulong transactionId = System.Convert.ToUInt64(intId); intId = reader.GetInt32(reader.GetOrdinal("ChargeAccountID")); ulong chargeAccountId = System.Convert.ToUInt64(intId); decimal change = reader.GetDecimal(reader.GetOrdinal("change")); decimal value = reader.GetDecimal(reader.GetOrdinal("newValue")); DateTime date = DateTime.Parse(reader.GetString(reader.GetOrdinal("changedAt"))); String type = reader.GetString(reader.GetOrdinal("type")); Charge charge = new Charge(value, change); charge.TransactionId = transactionId; charge.ChargeAccountId = chargeAccountId; charge.Type = type; charge.ChangeAt = date; return charge; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BiBo { public enum BookStates { ONLY_VISIBLE, DAMAGED, MISSING, OK } public static class Converter { public static BookStates ToBookState(string stateString) { switch (stateString) { case "only_visible": return BookStates.ONLY_VISIBLE; } throw new System.Exception("Falschen Status angegeben"); } } } <file_sep>using System; using System.Text.RegularExpressions; using BiBo.Exception; namespace BiBo { public class Validation { // Prüfen ob die Eingabe Leer oder NULL Werte enthält public static bool isEmpty(string isEmpty) { try { return String.IsNullOrEmpty(isEmpty.Trim()); } catch (ValidationException) { throw new ValidationException("Es dürfen keine Leeren oder Null Werte übergeben werden!"); } } // Prüfen ob die Eingabe nur Zahlen enthält public static bool isNumeric(string isNumeric) { try { return Regex.IsMatch(isNumeric, "^[0-9]+$"); } catch (ValidationException) { throw new ValidationException("Die Eingabe entspricht nicht der Norm! 0-9"); } } // Prüfen ob die Eingabe Alphabetisch ist public static bool isAlphabetic(string isAlphabetic) { try { return Regex.IsMatch(isAlphabetic, "^[A-Za-zäÄöÖüÜß\\s]+$"); } catch (ValidationException) { throw new ValidationException("Die Eingabe entspricht nicht der Norm! A-Z a-z äÄöÖüÜß"); } } // Prüfen ob die Eingabe Alphabetisch und nicht Leer oder NULL ist public static bool Name(string name) { try { return (!isEmpty(name) && isAlphabetic(name)); } catch (ValidationException) { throw new ValidationException("Die Eingabe entspricht nicht der Norm! A-Z a-z äÄöÖüÜß"); } } // Prüfen ob die Eingabe eine gültige Straße nach folgenden Kriterien ist // Straße-Hausnummer-Kombinationen nach folgenden Regeln für gültig: // Straße muss mit einem dt. Buchstaben beginnen, vor der Hausnummer muss (mind.) // ein Whitespace stehen, der Nummer dürfen andere Zeichen folgen ("1/2", "c" etc.). public static bool Street(string street) { try { return Regex.IsMatch(street, "^(([a-zA-ZäöüÄÖÜ]\\D*)\\s+\\d+?\\s*.*)$"); } catch (ValidationException) { throw new ValidationException("Die Straße muss mit einem dt. Buchstaben beginnen, vor der Hausnummer muss (mind.) ein Leerzeichen stehen, der Nummer dürfen andere Zeichen folgen (1/2, c etc.)"); } } // Prüfen ob die Eingabe der in DE, USA, CA gültigen PLZ entspricht public static bool zipCode(string zipCode) { try { return Regex.IsMatch(zipCode, "[0-9]{5}|[0-9]{5}-[0-9]{4}|([A-Z]{1}[0-9]{1}){3}"); } catch (ValidationException) { throw new ValidationException("Die Eingabe entspricht nicht in DE, USA oder CA gültigen PLZ!"); } } // Prüfen ob es sich bei der Eingabe um eine gültige Telefonnummer handelt public static bool TelNumber(string telNumber) { try { return Regex.IsMatch(telNumber, "^((\\+\\d{1,3}(-| )?\\(?\\d\\)?(-| )?\\d{1,5})|(\\(?\\d{2,6}\\)?))(-| )?(\\d{3,4})(-| )?(\\d{4})(( x| ext)\\d{1,5}){0,1}$"); } catch (ValidationException) { throw new ValidationException("Bei der Eingabe handelt es sich nicht um eine gültige Telefonnummer!"); } } // Prüfen ob es sich bei der Eingabe um eine gültige deutsche Handynummer handelt public static bool MobileNumber(string mobileNumber) { try { return Regex.IsMatch(mobileNumber, "(015[1|2|7|9])\\d{7,9}|(016[0|2|3])\\d{7,9}|(017[0-9])\\d{7,9}"); } catch (ValidationException) { throw new ValidationException("Bei der Eingabe handelt es sich nicht um eine gültige deutsche Handynummer!"); } } // Prüfen ob die Eingabe der Öffungszeit der Norm entspricht public static bool OpeningTime(string openingTime) { try { return Regex.IsMatch(openingTime, "(([0-1][0-9])|([2][0-3])):([0-5][0-9]):([0-5][0-9])"); } catch (ValidationException) { throw new ValidationException("Die Eingabe entspricht nicht der Norm! 00:00:00"); } } // Prüfen ob es sich bei der Eingabe um eine gültige Email-Adresse handelt public static bool EmailAddress(string emailAddress) { try { return Regex.IsMatch(emailAddress, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"); } catch (ValidationException) { throw new ValidationException("Bei der Eingabe handelt es sich nicht um eine gültige Email-Adresse"); } } public static bool validateCustomerAddPanel(/*Control x*/) { return true; /* TextBox firstName = (TextBox)x.Controls.Find("textBoxUserFirstname", true)[0]; if (!Validation.Name(firstName.Text)) { firstName.BackColor = Color.Red; return false; } TextBox lastName = (TextBox)x.Controls.Find("textBoxUserLastname", true)[0]; if (!Validation.Name(lastName.Text)) { lastName.BackColor = Color.Red; return false; } TextBox UserStreet = (TextBox)x.Controls.Find("textBoxUserStreet", true)[0]; if (!Validation.Name(lastName.Text)) { UserStreet.BackColor = Color.Red; return false; } TextBox HomeNumber = (TextBox)x.Controls.Find("textBoxUserHomeNumber", true)[0]; if (!Validation.Name(lastName.Text)) { HomeNumber.BackColor = Color.Red; return false; } TextBox UserCity = (TextBox)x.Controls.Find("textBoxUserCity", true)[0]; if (!Validation.Name(lastName.Text)) { UserCity.BackColor = Color.Red; return false; } TextBox UserPLZ = (TextBox)x.Controls.Find("textBoxUserPLZ", true)[0]; if (!Validation.Name(lastName.Text)) { UserPLZ.BackColor = Color.Red; return false; } */ } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; using System.IO; using BiBo.Persons; using BiBo.SQL; using System.Net; using System.Diagnostics; using System.Text.RegularExpressions; namespace BiBo { public partial class Form1 : Form { private String loginAsUserName; //name of current logged user private String userStatusText; //status of current logged user private Tabs activTab = Tabs.CUSTOMER; //default value of DatePicker for user add birthday private DateTime userAddBirthDayDefault = new DateTime(1980, 1, 1); //Source file of Countries //@todo this could be stored in SQLLite Table private String countriesSource = "../../countries.txt"; //@todo remove this, it is only needed of testing private Random r = new Random(); private Customer selectedUser; //SQLLite Adapters private CustomerSQL sqlCustomer; private BookSQL sqlBook; private Library lib; //constructor with getting SQLLite Adapters /* public Form1(CustomerDAO CustSQL, BookDAO BookSQL) { this.SqlCustomer = CustSQL; this.SqlBook = BookSQL; __construct(); }*/ //default constructor public Form1() { //createRandomBooks();return; this.sqlCustomer = SqlConnector<Customer>.GetCustomerSqlInstance(); this.sqlBook = SqlConnector<Book>.GetBookSqlInstance(); __construct(); } //summary constructor private void __construct() { this.lib = new Library(this); lib.getGuiApi().init(); } private void createRandomBooks() { BookSQL db = new BookSQL(); String Source = "http://www.lovelybooks.de/buecher/romane/Schr%C3%A4ge-Buchtitel-582954334/"; WebClient client = new WebClient(); client.Encoding = Encoding.UTF8; string downloadString = client.DownloadString(Source); Regex regex = new Regex(@">([^<]+)</span></a></h3"); var listTitle = (from Match m in regex.Matches(downloadString) select m).ToList(); regex = new Regex(@"von\s<a[^>]+>([^<]+)<"); var listAuthor = (from Match m in regex.Matches(downloadString) select m).ToList(); for (int i = 0; i < listTitle.Count; i++) { db.AddEntryReturnId(new Book(0, listAuthor[i].Groups[1].Value, listTitle[i].Groups[1].Value, "Roman")); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using BiBo.SQL; using BiBo.Persons; namespace BiBo.DAO { public class ExemplarDAO { Library lib; readonly int loanExtendDays = -14; public ExemplarDAO(Library lib) { this.lib = lib; } //Fügt ein Exemplar allen Schichten zu public void AddExemplar(Exemplar exemplar, Book book) { exemplar.BookId = book.BookId; //first add the exemplar into the db exemplar.ExemplarId = lib.SQLHandler.ExemplarSQL.AddEntryReturnId(exemplar); //make the signatur unic and update the exemplar in the DB exemplar.Signatur = exemplar.Signatur + exemplar.ExemplarId.ToString("x") + "]"; lib.SQLHandler.ExemplarSQL.UpdateEntry(exemplar); //and then add the exemplar into the list in the specific book book.Exemplare.Add(exemplar); //in gui lib.GUIApi.addExemparToDataGrid(exemplar, "EmployeeExemparTable"); } //Läscht Exemplar aus allen Schichten public void RemoveExemplar(ulong exemplarID) { //get the specific Objects from the Lists Exemplar exemplar = lib.ExemplarList.Find(ex => ex.ExemplarId == exemplarID); if (exemplar == null) throw new System.Exception("Exemplar mit ID nicht gefunden"); else if(exemplar.Borrower != null) throw new System.Exception("Exemplar bereits ausgeliehen"); Book book = lib.BookList.Find(bo => bo.BookId == exemplar.BookId); //remove the exemplar on object layer book.Exemplare.Remove(exemplar); List<ulong> idList = new List<ulong>(); idList.Add(exemplar.ExemplarId); //delete in the db lib.SQLHandler.ExemplarSQL.DeleteEntryByIdList(idList); //remove in gui lib.GUIApi.RemoveExemplar(exemplar); } public void UpdateExemplar(Exemplar expl) { //in database lib.SQLHandler.ExemplarSQL.UpdateEntry(expl); //Überschreibt das Objekt aus der Objektschicht mit dem gegebenen Exemplar exemplarInList = lib.ExemplarList.Find(e => e.ExemplarId == expl.ExemplarId); exemplarInList = expl; // update in gui lib.GUIApi.updateExemplar(expl); } //Gibt Datum, wann Exemplar ausgeliehen wurde public DateTime GetDateWhenBorrowed(Exemplar exemplar) { DateTime loanPeriodEnd = exemplar.LoanPeriod; DateTime borrowedDate = loanPeriodEnd.AddMonths(-1); for(int i = 0; i < exemplar.CountBorrow; i++) { borrowedDate = loanPeriodEnd.AddDays(loanExtendDays); } return borrowedDate; } //expand loanPeriod of an exemplar public void ExtendLend(ulong exemplarID) { Exemplar exemplar = lib.ExemplarList.First(expl => expl.ExemplarId == exemplarID); if (exemplar.CountBorrow < 3 && exemplar.PreOrderedList.Count == 0) { //on object-layer exemplar.LoanPeriod = lib.ExemplarList.Find(expl => expl.ExemplarId == exemplarID).LoanPeriod.AddDays(14); exemplar.CountBorrow++; //??? //on db-layer //in database lib.SQLHandler.ExemplarSQL.UpdateEntry(exemplar); //@Marcus-todo update in lib list //TODO: prüfen, ob durch überschreiben des Objektes Dateninkonsistenz auftritt, sowie muss Exemplar voll gefüllt werden Exemplar exemplarInList = lib.ExemplarList.Find(e => e.ExemplarId == exemplar.ExemplarId); exemplarInList = exemplar; //on view-layer Book relatedBook = lib.DAOHandler.BookDAO.GetBookById(exemplar.BookId); if (lib.LoggedUser.Right == Rights.CUSTOMER) { lib.GUIApi.cUpdateExemplarInBorrowedTableIfExists(exemplar, relatedBook); } else { lib.GUIApi.UpdateExemplarInBorrowedTableIfExists(exemplar, relatedBook); } } } //mehod that a customer can bring back a book public void BringBookBack(Customer customer, Exemplar exemplar, BookStates newState) { customer.ExemplarList.Remove(exemplar); //bring exemplar to the default state with new BookState exemplar.CountBorrow = 0; exemplar.Borrower = null; exemplar.LoanPeriod = DateTime.MinValue; // da DateTime nicht auf null gesetzt werden kann, wird hier das ausleihdatum einfach auf den niedrigsten Wert gesetzt exemplar.State = newState; //update in db lib.SQLHandler.ExemplarSQL.UpdateEntry(exemplar); //update view lib.GUIApi.BookBringBack(customer, exemplar); } //Fügt eine Vorbestellung hinzu public void AddPreOrder(Customer customer, Exemplar exemplar) { if (exemplar.PreOrderedList.Any(cu => cu.CustomerID == customer.CustomerID)) throw new System.Exception("Sie haben das Buch bereits vorbestellt"); //on object-layer exemplar.PreOrderedList.Add(customer); customer.PreOrderedList.Add(exemplar); //on db-layer lib.SQLHandler.ExemplarSQL.AddPreOrder(customer, exemplar); } //Löscht eine Vorbestellung public void DeletePreOrder(Customer customer, Exemplar exemplar) { //on object-layer exemplar.PreOrderedList.Remove(customer); customer.PreOrderedList.Remove(exemplar); //on db-layer lib.SQLHandler.ExemplarSQL.DeletePreOrder(customer, exemplar); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using BiBo.Persons; using System.Diagnostics; namespace BiBo { public class LibraryDAO { Library lib; public LibraryDAO(Library lib) { this.lib = lib; } public void ChangeOpeningTime(Dictionary<string, string> openingTime) { //on object-layer lib.OpeningTime = openingTime; //on db-layer lib.SQLHandler.LibrarySQL.SetOpeningTime(openingTime); //on gui lib.GUIApi.SetOpeningTimes(lib.OpeningTime); } public void ChangeFee(double fee) { //TODO: prüfung auf richtigkeit der Werte //on object-layer lib.Fee = fee; //on db-Layer lib.SQLHandler.LibrarySQL.SetFee(fee); //todo on gui lib.GUIApi.SetFee(fee); } public void ChangeName(String Name) { //on object-layer lib.Name = Name; //on db-Layer lib.SQLHandler.LibrarySQL.SetName(Name); //todo on gui lib.GUIApi.SetName(Name); } public void ChangeAdress(String Adress) { //on object-layer lib.Adress = Adress; //on db-Layer lib.SQLHandler.LibrarySQL.SetAdress(Adress); //todo on gui lib.GUIApi.SetAdress(Adress); } public void ChangeBilling(Double Billing) { //on object-layer lib.Billing = Billing; //on db-Layer lib.SQLHandler.LibrarySQL.SetBilling(Billing); //todo on gui lib.GUIApi.SetBilling(Billing); } //Initialisiert Daten der Library public void Init() { //on object-layer lib.Name = lib.SQLHandler.LibrarySQL.GetName(); lib.Adress= lib.SQLHandler.LibrarySQL.GetAdress(); lib.OpeningTime = lib.SQLHandler.LibrarySQL.GetOpeningTime(); lib.Fee = lib.SQLHandler.LibrarySQL.GetFee(); lib.Billing = lib.SQLHandler.LibrarySQL.GetBilling(); //on gui lib.GUIApi.SetName(lib.Name); lib.GUIApi.SetAdress(lib.Adress); lib.GUIApi.SetOpeningTimes(lib.OpeningTime); lib.GUIApi.SetFee(lib.Fee); lib.GUIApi.SetBilling(lib.Billing); } //Erstellt zum Kunden eine Mahnung public String GenerateReminder(Customer customer) { StringBuilder builder = new StringBuilder(); builder.Append("Hallo " + customer.FirstName + " " + customer.LastName + ",\n\n" + "sicherlich ist es Ihnen entgangen, dass nicht alle Ihrer ausgeliegenden Bücher zurückgebracht wurden.\n" + "Folgende Bücher liegen über dem Rückgabedatum:\n\n"); foreach (Exemplar ex in customer.ExemplarList.Where(expl => expl.LoanPeriod.CompareTo(DateTime.Now.AddDays(7)) < 0)) { Book relatedBook = lib.BookList.Single(b => b.BookId == ex.BookId); builder.Append(relatedBook.Titel + " von " + relatedBook.Author + " [Rückgabedatum: " + ex.LoanPeriod.ToShortDateString() + "]\n"); } builder.Append("Wir bitten Sie dir Rückgabe der Bücher bei nächster Gelegenheit vorzunehmen.\n" + "Evtl. kann die Ausleihfirst verlängert werden, bitte check Sie das an einem unserer Computer oder mit einem unser Mitarbeiter.\n\n" + "Liegen die Bücher 14 Tage üben dem Rückgabedatum wir eine Mahngebühr in Höhe von " + (customer.GetAge() < 14 ? (lib.Billing/2).ToString() : lib.Billing.ToString()) +"€ erhoben."); return builder.ToString(); } //belaste alle Konten, die Bücher zurückgeben müssen public void BurdenAccounts() { bool receiveReminder = false; foreach (Customer customer in lib.CustomerList) { foreach (Exemplar exemplar in customer.ExemplarList) { if (exemplar.LoanPeriod.CompareTo(DateTime.Today.AddDays(7)) < 0) { //Also ich habe mir das Ganze hier so gedacht: //Diese Methode wird jeden immer ausgerufen wenn das Programm gestartet wird //Wir ziegen die Mahngebühr (lib.Billing) für jede Woche ab die der Kunde drüber ist //des halb wird, bevor etwas abgezogen wird immer gescheckt ob für die Woche schon was abgezogen wurde //vergangende Mahngebührerhebenungen erkennen wir am Type "notreturned" if (customer.ChargeAccount.Charges.Any(charge => charge.Type == "notreturned")) { //get last burden datetime DateTime lastReminder = customer.ChargeAccount.Charges.Where(charge => charge.Type == "notreturned").Max(charge => charge.ChangeAt); //check is this is older then 14 days if (lastReminder.AddDays(14) < DateTime.Today) { lib.DAOHandler.ChargeAccountDAO.Burden(customer, (decimal)lib.Billing, "notreturned"); } else if (lastReminder.AddDays(7) < DateTime.Today) { receiveReminder = true; } } else { lib.DAOHandler.ChargeAccountDAO.Burden(customer, (decimal)lib.Billing, "notreturned"); } } } if (receiveReminder) { //Sende Mahnung das in 7 Tagen eine Mahngebühr erhoben wird GenerateReminder(customer); receiveReminder = false; } //Die Jährliche Gebühr wird direkt einmal abgezogen sobald der Kunde angelegt wird //dann wird hier immer nur gecheck ob der Kunde schon länger als ein Jahr dabei ist //und wenn ja ob er für dieses Jahr schon bezahl hat if (customer.ChargeAccount.Charges.Count > 0) { if (!customer.ChargeAccount.Charges.Any( charge => charge.Type == "fee" && charge.ChangeAt.AddYears(1).CompareTo(DateTime.Now) > 0) ) { //Kunde hat seit länger als einem Jahr keine Gebühren bezahlt lib.DAOHandler.ChargeAccountDAO.Burden(customer, (decimal)lib.Fee, "fee"); } } else { lib.DAOHandler.ChargeAccountDAO.Burden(customer, (decimal)lib.Fee, "fee"); } } } //sendet mail mit entsprechendem Text public void SendMailToCustomer(Customer customer ,String text) { Mailer.SendMail(customer, text); } //sendet Mahnung an alle Kunden, die Bücher noch nicht zurückgegeben haben public void SendRemainder() { foreach(Customer customer in lib.CustomerList) { //Erste Mahnung nach 7 Tagen if(customer.ExemplarList.Any(ex => ex.LoanPeriod.ToShortDateString().CompareTo(DateTime.Today.AddDays(7).ToShortDateString()) == 0)) SendMailToCustomer(customer, GenerateReminder(customer)); //Zweite Mahnung nach 14 Tagen else if (customer.ExemplarList.Any(ex => ex.LoanPeriod.ToShortDateString().CompareTo(DateTime.Today.AddDays(14).ToShortDateString()) == 0)) SendMailToCustomer(customer, GenerateReminder(customer)); //Dritte Mahnung nach 1 Monat else if (customer.ExemplarList.Any(ex => ex.LoanPeriod.ToShortDateString().CompareTo(DateTime.Today.AddMonths(1).ToShortDateString()) == 0)) SendMailToCustomer(customer, GenerateReminder(customer)); } } } } <file_sep>using BiBo; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Test { [TestClass()] public class BookTest { [TestMethod()] // Erstellen eines Buchs public void BooTest() { ulong bookId = 1; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); Assert.IsTrue(boo.BookId == bookId); Assert.IsTrue(boo.Author == author); Assert.IsTrue(boo.Titel == titel); Assert.IsTrue(boo.SubjectArea == subjectArea); } [TestMethod()] // Erstellen einer Buch Signatur public void CreateSignaturTest() { ulong bookId = 555; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); string authorPrefix = author[0].ToString(); string subjectAreaPrefix; if (subjectArea.Length > 3) { subjectAreaPrefix = subjectArea.Substring(0, 3); } else { subjectAreaPrefix = subjectArea; } string signatur = "[" + authorPrefix + subjectAreaPrefix; Assert.AreEqual(boo.CreateSignatur(), signatur); } [TestMethod()] // Erstellen eines Strings vom Buch mit Author Titel und Richtung public void ToStringTest() { ulong bookId = 1; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); string sString = author + " " + titel + " " + subjectArea; Assert.AreEqual(boo.ToString(), sString); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using BiBo.Persons; using System.Diagnostics; namespace BiBo { public class Exemplar { //Member-Variablen Deklaration private DateTime loanPeriod; //Ausleifrist private BookStates state; //Status des Buches (only_visible, damaged, missing) private string signatur; //signatur des buches private Access accesser; //Zugang zum Exemplar (magazin, freihandausleihe) private Customer borrower; //Ausleiher private ulong customerID; private ulong exemplarId; //Exemplar-Nummer private ulong bookId; //dazugehörige Buch-ID private int countBorrow; //wie oft ausgeliehen private List<Customer> preOrderList; //Vorbesteller Liste //Konstruktor public Exemplar(Book buch) { this.signatur = buch.CreateSignatur(); this.bookId = buch.BookId; this.PreOrderedList = new List<Customer>(); //only for test this.Accesser = Access.FREEHAND_LENDING; this.state = BookStates.OK; } public Exemplar() { this.PreOrderedList = new List<Customer>(); } //Property Deklaration public DateTime LoanPeriod { get { return this.loanPeriod; } set { this.loanPeriod = value; } } public BookStates State { get { return this.state; } set { this.state = value; } } public string Signatur { get { return this.signatur; } set { this.signatur = value; } } public Access Accesser { get { return this.accesser; } set { this.accesser = value; } } public Customer Borrower { get { return this.borrower; } set { this.borrower = value; } } public ulong ExemplarId { get { return this.exemplarId; } set { this.exemplarId = value; } } public ulong BookId { get { return this.bookId; } set { this.bookId = value; } } public int CountBorrow { get { return this.countBorrow; } set { this.countBorrow = value; } } public ulong CustomerId { get { return this.customerID; } set { this.customerID = value; } } public List<Customer> PreOrderedList { get { return this.preOrderList; } set { this.preOrderList = value; } } //Methoden public override bool Equals(object obj) { Exemplar ex; try { ex = (Exemplar)obj; } catch (InvalidCastException ice) { Debug.WriteLine(ice.Message); return false; } return exemplarId.Equals(ex.exemplarId); } public override int GetHashCode() { return exemplarId.GetHashCode(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using BiBo.Persons; using System.Data; using System.Windows.Media; using System.Windows.Threading; namespace BiBo { public class GUIApi { private MainWindow GUI; //Create a Delegate that matches //the Signature of the ProgressBar's SetValue method public delegate void UpdateProgressBarDelegate(DependencyProperty dp, Object value); public UpdateProgressBarDelegate updatePbDelegate; public double ProgressBarMax; public double ProgressBarStep = 0; private ProgressBar ProgressBar; public void increaseProgressBar() { ProgressBarStep++; this.GUI.Dispatcher.Invoke(updatePbDelegate, DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, ProgressBarStep }); } public GUIApi() { this.GUI = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MainWindow) as MainWindow; } public GUIApi(bool test) { GUI = new MainWindow(); } public void SetName(String Name) { GUI.MainName.Content = Name; GUI.cMainName.Content = Name; } public void SetAdress(String Adress) { GUI.MainAdress.Content = Adress; GUI.cMainAdress.Content = Adress; } public void SetFee(Double Fee) { GUI.MainFee.Content = "Jahresgebühren: " + Fee.ToString() + "€"; } public void SetBilling(Double Billing) { GUI.MainBilling.Content = "Mahngebühren: " + Billing.ToString() + "€"; } public void SetOpeningTimes(Dictionary<string, string> openingTimes) { (load("openingTimeMo") as Label).Content = openingTimes["Montag"]; (load("openingTimeTu") as Label).Content = openingTimes["Dienstag"]; (load("openingTimeWe") as Label).Content = openingTimes["Mittwoch"]; (load("openingTimeTh") as Label).Content = openingTimes["Donnerstag"]; (load("openingTimeFr") as Label).Content = openingTimes["Freitag"]; (load("openingTimeSa") as Label).Content = openingTimes["Sonnabend"]; (load("openingTimeSu") as Label).Content = openingTimes["Sonntag"]; (load("c_openingTimeMo") as Label).Content = openingTimes["Montag"]; (load("c_openingTimeTu") as Label).Content = openingTimes["Dienstag"]; (load("c_openingTimeWe") as Label).Content = openingTimes["Mittwoch"]; (load("c_openingTimeTh") as Label).Content = openingTimes["Donnerstag"]; (load("c_openingTimeFr") as Label).Content = openingTimes["Freitag"]; (load("c_openingTimeSa") as Label).Content = openingTimes["Sonnabend"]; (load("c_openingTimeSu") as Label).Content = openingTimes["Sonntag"]; } public void SetOpeningTimesToEditPopup(Dictionary<string, string> openingTimes) { (load("TimesEditPopup_Mo") as TextBox).Text = openingTimes["Montag"]; (load("TimesEditPopup_Tu") as TextBox).Text = openingTimes["Dienstag"]; (load("TimesEditPopup_We") as TextBox).Text = openingTimes["Mittwoch"]; (load("TimesEditPopup_Th") as TextBox).Text = openingTimes["Donnerstag"]; (load("TimesEditPopup_Fr") as TextBox).Text = openingTimes["Freitag"]; (load("TimesEditPopup_Sa") as TextBox).Text = openingTimes["Sonnabend"]; (load("TimesEditPopup_Su") as TextBox).Text = openingTimes["Sonntag"]; } public void initProgressBar(double MaxValue) { ProgressBar = load("pb") as ProgressBar; ProgressBar.Visibility = Visibility.Visible; //Configure the ProgressBar ProgressBar.Minimum = 0; ProgressBar.Maximum = MaxValue; ProgressBar.Value = 0; updatePbDelegate = new UpdateProgressBarDelegate(ProgressBar.SetValue); } public void setLoggedInUser(Customer customer) { //TODO: Hier wird die Version nur bei Customer angezeigt. // Admins und Employees bekommen keine Version angezeigt // Das müsste noch gefixed werden BiBo.Updater.BiboUpdater updater = new BiBo.Updater.BiboUpdater(); string currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); (load("CurrentVersion") as Label).Content = "Version: " + currentVersion; if (customer.Right == Rights.CUSTOMER) { (load("CustomerUserName") as Label).Content = customer.FirstName + " " + customer.LastName; (load("CustomerCreatedAt") as Label).Content = "seit " + customer.CreatedAt.ToShortDateString(); } else { (load("MainUserName") as Label).Content = customer.FirstName + " " + customer.LastName; } Label UserRights = load("MainUserRights") as Label; switch(customer.Right){ case Rights.EMPLOYEE: UserRights.Content = "Mitarbeiter"; break; case Rights.ADMINISTRATOR: UserRights.Content = "Administrator"; break; } } private void addCustomerToDataGrid(Customer customer, String XamlName) { if (customer.UserState != UserStates.DELETED) { DataGrid CustomerTable = load(XamlName) as DataGrid; DataTable TableContent = CustomerTable.DataContext as DataTable; TableContent.Rows.Add( customer.CustomerID, customer.FirstName, customer.LastName, customer.Street, customer.AdditionalRoad, customer.StreetNumber, customer.ZipCode, customer.Town, customer.Country, customer.MobileNumber.ToString(), customer.EMailAddress, customer.ExemplarList.Count, customer.Card.CardValidUntil.ToShortDateString(), customer.CreatedAt.ToShortDateString(), customer.LastUpdate.ToShortDateString(), customer.Right.ToString(), customer.UserState.ToString(), customer.ChargeAccount.Charges.Count > 0 ? customer.ChargeAccount.Charges.Last().CurrentValue.ToString() : "0" ); CustomerTable.DataContext = TableContent; } } public void AddCustomer(Customer customer) { addCustomerToDataGrid(customer,"CustomerTable"); } public void AddBorrowedDataGrid(Exemplar expl, Book RelatedBook, String XamlName) { DataGrid exemplarTable = (load(XamlName) as DataGrid); DataTable dt = exemplarTable.DataContext as DataTable; dt.Rows.Add( expl.ExemplarId, RelatedBook.BookId, RelatedBook.Titel, RelatedBook.Author, expl.Accesser.ToString(), expl.State.ToString(), expl.LoanPeriod.ToString(), expl.CountBorrow ); exemplarTable.DataContext = dt; } public DataTable getBorrowedTable() { DataTable dt = new DataTable(); dt.Columns.Add("ID", typeof(ulong)); dt.Columns.Add("Buch ID", typeof(ulong)); dt.Columns.Add("Title"); dt.Columns.Add("Author"); dt.Columns.Add("Zugang"); dt.Columns.Add("Status"); dt.Columns.Add("Ausleihfirst"); dt.Columns.Add("Verlängerungen", typeof(int)); return dt; } public DataTable getChargeDataTable() { DataTable dt = new DataTable(); dt.Columns.Add("Datum"); dt.Columns.Add("Transaktion"); dt.Columns.Add("Stand"); return dt; } public DataTable getExemplarDataTable() { DataTable New = new DataTable("Exemplar"); New.Columns.Add("ID", typeof(ulong)); New.Columns.Add("Status"); New.Columns.Add("Signaure"); New.Columns.Add("Zugriff"); New.Columns.Add("Ausleihzeit"); New.Columns.Add("Kunden ID"); return New; } public DataTable getCustomerDataTable() { DataTable New = new DataTable("Customers"); New.Columns.Add("ID", typeof(ulong)); New.Columns.Add("Vorname"); New.Columns.Add("Nachname"); New.Columns.Add("Strasse"); New.Columns.Add("Adress Zusatz"); New.Columns.Add("Hausnummer"); New.Columns.Add("PLZ"); New.Columns.Add("Stadt"); New.Columns.Add("Land"); New.Columns.Add("Tel"); New.Columns.Add("Email"); New.Columns.Add("ausgeliehen"); New.Columns.Add("Ausweis gültig bis"); New.Columns.Add("Aufnahme"); New.Columns.Add("Geändert"); New.Columns.Add("Rolle"); New.Columns.Add("Status"); New.Columns.Add("Kontostand"); return New; } public DataTable getBookDataTable() { DataTable New = new DataTable("Books"); New.Columns.Add("ID", typeof(ulong)); New.Columns.Add("Author"); New.Columns.Add("Title"); New.Columns.Add("Fachrichtung"); New.Columns.Add("Anzahl Exemplare"); New.Columns.Add("Verfügbar ab"); return New; } public void addExemparToDataGrid(Exemplar exemplar, String XamlName) { DataGrid ExemplarTable = load(XamlName) as DataGrid; DataTable TableContent = ExemplarTable.DataContext as DataTable; TableContent.Rows.Add( exemplar.ExemplarId, exemplar.State.ToString(), exemplar.Signatur, exemplar.Accesser.ToString(), exemplar.LoanPeriod.ToShortDateString(), exemplar.CustomerId == 0 ? "frei" : exemplar.CustomerId.ToString() ); ExemplarTable.DataContext = TableContent; } public void fillExemplarsToBorrow(Book book) { DataGrid ExemplarTable = load("EmployeeBorrowTableExemplars") as DataGrid; //CustomerTable.DataContext DataTable test = getExemplarDataTable(); ExemplarTable.DataContext = test; foreach (Exemplar expl in book.Exemplare) { addExemparToDataGrid(expl, "EmployeeBorrowTableExemplars"); } } public void Add_b_Customer(Customer customer) { addCustomerToDataGrid(customer, "EmployeeBorrowTableCustomers"); } private void addBookToDataGrid(Book book, String XamlString) { DataGrid BookTable = load(XamlString) as DataGrid; DataTable test = (BookTable.DataContext as DataTable); DateTime earlyestDate = GUI.Lib.DAOHandler.BookDAO.GetEarliestLoanDate(book); test.Rows.Add( book.BookId, book.Author, book.Titel, book.SubjectArea, book.Exemplare.Count, earlyestDate.ToShortDateString() ); BookTable.DataContext = test; } public void addChargeToDataGrid(Charge chr, DataGrid dg) { DataTable test = (dg.DataContext as DataTable); test.Rows.Add( chr.ChangeAt.ToString(), chr.ChangeValues.ToString(), chr.CurrentValue.ToString() ); dg.DataContext = test; } public void AddBook(Book book) { addBookToDataGrid(book, "EmployeeBooksTable"); } public void Add_b_Book(Book book) { addBookToDataGrid(book, "EmployeeBorrowTableBooks"); } public void Add_b_Exemplar(Exemplar ex) { addExemparToDataGrid(ex, "EmployeeBorrowTableExemplars"); } public void Add_c_Book(Book book) { addBookToDataGrid(book, "cBookTable"); } public void DeleteCustomer(Customer customer) { DataGrid table = GUI.FindName("CustomerTable") as DataGrid; table.DataContext = (table.DataContext as DataTable).AsEnumerable().Where( r => (ulong) r.Field<object>("ID") != customer.CustomerID ).CopyToDataTable(); } private object load(String Name) { return GUI.FindName(Name); } public void UpdateCustomer(Customer customer) { DeleteCustomer(customer); AddCustomer(customer); } public void UpdateExemplarInBorrowedTableIfExists(Exemplar UpdatedExemplar, Book RelatedBook) { updateExemplarInBorrowedTableIfExists(UpdatedExemplar, RelatedBook, "CustomerBorrowedTable"); } public void cUpdateExemplarInBorrowedTableIfExists(Exemplar UpdatedExemplar, Book RelatedBook) { updateExemplarInBorrowedTableIfExists(UpdatedExemplar, RelatedBook, "cCustomerBorrwedExemplars"); } private void updateExemplarInBorrowedTableIfExists(Exemplar UpdatedExemplar, Book RelatedBook, String dgName) { DataGrid BorrowedTable = load(dgName) as DataGrid; DataTable TableContent = BorrowedTable.DataContext as DataTable; DataTable NewDataContext = TableContent.Clone(); foreach (DataRow row in TableContent.Rows) { if ((ulong)row["ID"] != UpdatedExemplar.ExemplarId) { NewDataContext.ImportRow(row); } else { NewDataContext.Rows.Add( UpdatedExemplar.ExemplarId, RelatedBook.BookId, RelatedBook.Titel, RelatedBook.Author, UpdatedExemplar.Accesser.ToString(), UpdatedExemplar.State.ToString(), UpdatedExemplar.LoanPeriod.ToString(), UpdatedExemplar.CountBorrow ); } } BorrowedTable.DataContext = NewDataContext; } public void BookBringBack(Customer customer, Exemplar exemplar) { //update in CustomerTable ReplaceInDataGrid(customer, "CustomerTable"); //delte in CustomerBorrowedTable DataTable dt = (load("CustomerBorrowedTable") as DataGrid).DataContext as DataTable; for(int i = dt.Rows.Count-1; i >= 0; i--) { DataRow dr = dt.Rows[i]; if ((ulong)dr["ID"] == exemplar.ExemplarId) { dr.Delete(); } } //update in EmployeeBorrowTableCustomers ReplaceInDataGrid(customer, "EmployeeBorrowTableCustomers"); } private void ReplaceInDataGrid(Exemplar exemplar, String XamlName) { } private void ReplaceInDataGrid(Customer customer ,String XamlName){ DataGrid TableView = load(XamlName) as DataGrid; DataTable TableContent = TableView.DataContext as DataTable; DataTable NewDataContext = TableContent.Clone(); foreach (DataRow row in TableContent.Rows) { if ((ulong)row["ID"] != customer.CustomerID) { NewDataContext.ImportRow(row); } } TableView.DataContext = NewDataContext; addCustomerToDataGrid(customer, XamlName); } public void updateExemplar(Exemplar expl) { deleteIdFromDataGrid(expl.ExemplarId, this.GUI.EmployeeExemparTable); addExemparToDataGrid(expl, "EmployeeExemparTable"); } public void moveExemplarFormBookToCustomer(Exemplar exemplar,Book book) { //EmployeeBorrowTableExemplars deleteIdFromDataGrid(exemplar.ExemplarId, this.GUI.EmployeeBorrowTableExemplars); //CustomersExemplars addExemparToDataGrid(exemplar, "EmployeeBorrowTableExemplars"); AddBorrowedDataGrid(exemplar,book, "CustomersExemplars"); } public void DeleteBook(Book book) { BlockSelectionEvents(true); deleteIdFromDataGrid(book.BookId, load("EmployeeBooksTable") as DataGrid); GUI.EmployeeExemparTable.DataContext = getExemplarDataTable(); BlockSelectionEvents(false); } public void BlockSelectionEvents(bool x) { GUI.BlockSelectionChange = x; } public void deleteIdFromDataGrid(ulong ID,DataGrid dg){ DataTable dt = dg.DataContext as DataTable; for (int i = 0; i < dt.Rows.Count; i++) { if ((ulong)(dt.Rows[i] as DataRow)["ID"] == ID) { dt.Rows.RemoveAt(i); break; } } } public void RemoveExemplar(Exemplar expl) { deleteIdFromDataGrid(expl.ExemplarId, this.GUI.EmployeeExemparTable); } } } <file_sep>using System; using System.Linq; using BiBo; using BiBo.DAO; using BiBo.Persons; using BiBo.SQL; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Test.DAO { [TestClass()] public class ExemplarDAOTest { [TestMethod()] public void AddExemplarTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ExemplarDAO exDAO = new ExemplarDAO(lib); ulong bookId = 5555; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); Exemplar ex = new Exemplar(boo); ex.BookId = boo.BookId; //first add the exemplar into the db ex.ExemplarId = lib.SQLHandler.ExemplarSQL.AddEntryReturnId(ex); //make the signatur unic and update the exemplar in the DB ex.Signatur = ex.Signatur + ex.ExemplarId.ToString("x") + "]"; lib.SQLHandler.ExemplarSQL.UpdateEntry(ex); //and then add the exemplar into the list in the specific book boo.Exemplare.Add(ex); //in gui lib.GUIApi.addExemparToDataGrid(ex, "EmployeeExemparTable"); Assert.AreEqual(ex, lib.ExemplarList[0]); Assert.AreEqual(boo, lib.BookList[0]); } [TestMethod()] //expand loanPeriod of an exemplar public void ExtendLendTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong bookId = 555; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); Exemplar ex = new Exemplar(boo); ExemplarDAO exDAO = new ExemplarDAO(lib); ulong exemplarID = 1; ex = lib.ExemplarList.First(expl => expl.ExemplarId == exemplarID); if (ex.CountBorrow < 3 && ex.PreOrderedList.Count == 0) { //on object-layer ex.LoanPeriod = lib.ExemplarList.Find(expl => expl.ExemplarId == exemplarID).LoanPeriod.AddDays(14); ex.CountBorrow++; //in database lib.SQLHandler.ExemplarSQL.UpdateEntry(ex); Exemplar exemplarInList = lib.ExemplarList.Find(e => e.ExemplarId == ex.ExemplarId); exemplarInList = ex; //on view-layer Book relatedBook = lib.DAOHandler.BookDAO.GetBookById(ex.BookId); if (lib.LoggedUser.Right == Rights.CUSTOMER) { lib.GUIApi.cUpdateExemplarInBorrowedTableIfExists(ex, relatedBook); } else { lib.GUIApi.UpdateExemplarInBorrowedTableIfExists(ex, relatedBook); } } Assert.AreEqual(ex.LoanPeriod, lib.ExemplarList.First(expl => expl.ExemplarId == exemplarID).LoanPeriod); } public void UpdateExemplar(Exemplar expl, Library lib) { //in database lib.SQLHandler.ExemplarSQL.UpdateEntry(expl); Exemplar exemplarInList = lib.ExemplarList.Find(e => e.ExemplarId == expl.ExemplarId); exemplarInList = expl; // update in gui lib.GUIApi.updateExemplar(expl); } [TestMethod()] public void UpdateExemplarTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong bookId = 1; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); Exemplar ex = new Exemplar(boo); lib.ExemplarList.Add(ex); ExemplarDAO exDAO = new ExemplarDAO(lib); exDAO.UpdateExemplar(ex); Assert.Inconclusive("Erfolgreich"); } [TestMethod()] public void GetDateWhenBorrowedTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong bookId = 1; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); Exemplar ex = new Exemplar(boo); int loanExtendDays = -14; DateTime loanPeriod = DateTime.Today.AddDays(-7); ex.LoanPeriod = loanPeriod; DateTime loanPeriodEnd = ex.LoanPeriod; DateTime borrowedDate = loanPeriodEnd.AddMonths(-1); for (int i = 0; i < ex.CountBorrow; i++) { borrowedDate = loanPeriodEnd.AddDays(loanExtendDays); } lib.ExemplarList.Add(ex); ExemplarDAO exDAO = new ExemplarDAO(lib); Assert.AreEqual(exDAO.GetDateWhenBorrowed(ex), borrowedDate); } [TestMethod()] public void PreOrderExemplarTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); ulong bookId = 1; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); Customer cus = new Customer(cusID, firstName, lastName, birthDate); Exemplar ex = new Exemplar(boo); ExemplarDAO exDAO = new ExemplarDAO(lib); exDAO.AddPreOrder(cus, ex); Assert.IsTrue(ex.PreOrderedList[0].Equals(cus)); Assert.IsTrue(cus.PreOrderedList[0].Equals(ex)); } [TestMethod()] public void RemoveExemplarTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ExemplarDAO exDAO = new ExemplarDAO(lib); ulong bookId = 1; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); Exemplar ex = new Exemplar(boo); exDAO.AddExemplar(ex, boo); exDAO.RemoveExemplar(ex.ExemplarId); Assert.Inconclusive("Erfolgreich"); } [TestMethod()] public void BorrowExemplar_BringBookBackTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); ulong bookId = 1; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); Exemplar ex = new Exemplar(boo); string authorPrefix = author[0].ToString(); string subjectAreaPrefix; if (subjectArea.Length > 3) { subjectAreaPrefix = subjectArea.Substring(0, 3); } else { subjectAreaPrefix = subjectArea; } string signatur = "[" + authorPrefix + subjectAreaPrefix + "]"; DateTime dateBookWillBeBack = DateTime.Today.AddDays(5); BookStates newState = BookStates.OK; // bring exemplar to the default state with new BookState ex.CountBorrow = 0; ex.Borrower = null; ex.LoanPeriod = DateTime.MinValue; ex.State = newState; cus.ExemplarList.Remove(ex); //update in db lib.SQLHandler.ExemplarSQL.UpdateEntry(ex); //update view lib.GUIApi.BookBringBack(cus, ex); ExemplarDAO exDAO = new ExemplarDAO(lib); exDAO.BringBookBack(cus, ex, newState); Assert.Inconclusive("Erfolgreich"); } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using BiBo.DAO; using BiBo.Persons; using BiBo.SQL; namespace BiBo { public class Library { //Member-Variablen Deklaration private double fee; //Jahresgebuehren private double billing; //Mahnkosten //name of library private String name = "Ihr Bibliotheks Name"; //Adress of Library private String adress = "Die Bibliotheks Adresse"; //Opening times with default definition private Dictionary<string, string> openingTime = new Dictionary<string, string>(){ {"Montag", "11:00 - 18:00 Uhr"}, {"Dienstag", "08:00 - 18:00 Uhr"}, {"Mittwoch", "08:00 - 18:00 Uhr"}, {"Donnerstag", "08:00 - 18:00 Uhr"}, {"Freitag", "08:00 - 18:00 Uhr"}, {"Sonnabend", "10:00 - 14:00 Uhr"}, {"Sonntag", "geschlossen"} }; //currently logged user private Customer loggedUser; //Lists of the important objects private List<Customer> customerList; private List<Book> bookList; private List<Exemplar> exemplarList; private List<ChargeAccount> chargeAccountList; //Adapter private GUIApi gui; private SqlConnector sqlHandler; private DAOHandler daoHandler; private bool isEmployeeGUILoaded = false; private String Version; //Konstruktor public Library() { this.gui = new GUIApi(); this.GUIApi.initProgressBar(9); AppSettingsReader config = new AppSettingsReader(); BiBo.Updater.BiboUpdater updater = new BiBo.Updater.BiboUpdater(); this.Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); initDAOs(config); this.DAOHandler.LibraryDAO.Init(); this.DAOHandler.LibraryDAO.BurdenAccounts(); this.DAOHandler.LibraryDAO.SendRemainder(); } public String Name { get { return name; } set { name = value; } } public String Adress { get { return adress; } set { adress = value; } } public DAOHandler DAOHandler { get { return this.daoHandler; } set { this.daoHandler = value; } } public SqlConnector SQLHandler { get { return this.sqlHandler; } set { this.sqlHandler = value; } } public Library(GUIApi api) { this.gui = api; this.SQLHandler = new SqlConnector(false); this.DAOHandler = new DAOHandler(); this.DAOHandler.BookDAO = new BookDAO(this); this.DAOHandler.CustomerDAO = new CustomerDAO(this); this.DAOHandler.CardDAO = new CardDAO(this); this.DAOHandler.ChargeAccountDAO = new ChargeAccountDAO(this); this.DAOHandler.ExemplarDAO = new ExemplarDAO(this); this.DAOHandler.LibraryDAO = new LibraryDAO(this); Initializer initialize = new Initializer(this); initialize.InitializeAll(); } //Property Deklaration public Customer LoggedUser { get { return loggedUser; } set { loggedUser = value; } } public double Fee { get { return fee; } set { fee = value; } } public double Billing { get { return billing; } set { billing = value; } } public bool IsEmployeeGUILoaded { get { return this.isEmployeeGUILoaded; } set { this.isEmployeeGUILoaded = value; } } public Dictionary<string,string> OpeningTime { get { return openingTime; } set { openingTime = value; } } public List<Customer> CustomerList { get { return customerList; } set { customerList = value; } } public List<Book> BookList { get { return bookList; } set { bookList = value; } } public List<Exemplar> ExemplarList { get { return exemplarList; } set { exemplarList = value; } } public List<ChargeAccount> ChargeAccountList { get { return chargeAccountList; } set { chargeAccountList = value; } } //Methods public GUIApi GUIApi { get {return this.gui;} set {this.gui = value;} } private void initDAOs(AppSettingsReader config) { this.GUIApi.increaseProgressBar(); this.SQLHandler = new SqlConnector((bool)config.GetValue("ResetWithDummyData", typeof(bool))); this.GUIApi.increaseProgressBar(); this.DAOHandler = new DAOHandler(); this.GUIApi.increaseProgressBar(); this.DAOHandler.BookDAO = new BookDAO(this); this.GUIApi.increaseProgressBar(); this.DAOHandler.CustomerDAO = new CustomerDAO(this); this.GUIApi.increaseProgressBar(); this.DAOHandler.CardDAO = new CardDAO(this); this.GUIApi.increaseProgressBar(); this.DAOHandler.ChargeAccountDAO = new ChargeAccountDAO(this); this.GUIApi.increaseProgressBar(); this.DAOHandler.LibraryDAO = new LibraryDAO(this); this.GUIApi.increaseProgressBar(); this.DAOHandler.ExemplarDAO = new ExemplarDAO(this); this.GUIApi.increaseProgressBar(); Initializer initialize = new Initializer(this); this.GUIApi.increaseProgressBar(); initialize.InitializeAll(); this.GUIApi.increaseProgressBar(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using BiBo.SQL; using BiBo.Persons; namespace BiBo.DAO { //Diese Klasse ist verantwortlich für den Zugriff auf die ChargeAccounts //Sowie alle DAO Klassen ist diese für den Zugriff auf die ChargeAccount Objekte sowie der Datenkonsistenz verantwortlich public class ChargeAccountDAO { Library lib; SqlConnector SQLHandler; public ChargeAccountDAO(SqlConnector SQLHandler) { this.SQLHandler = SQLHandler; } public ChargeAccountDAO(Library lib) { this.lib = lib; this.SQLHandler = lib.SQLHandler; } //Legt eine neue Charge an und holt sich vorher den alten wert private void AddCharge(Customer customer, decimal changeValue, String type) { //create the Charge with the last value if (customer.ChargeAccount.Charges.Count == 0) { //create charge Charge charge = new Charge(changeValue, changeValue); charge.ChargeAccountId = customer.ChargeAccount.Id; charge.Type = type; //on db-layer charge.TransactionId = SQLHandler.ChargeSQL.AddEntryReturnId(charge); //on object layer customer.ChargeAccount.Charges.Add(charge); } else { //create the charge Charge lastCharge = customer.ChargeAccount.Charges.Last(); decimal value = lastCharge.CurrentValue + changeValue; Charge charge = new Charge(value, changeValue); charge.ChargeAccountId = customer.ChargeAccount.Id; charge.Type = type; //on db-layer lib.SQLHandler.ChargeSQL.AddEntryReturnId(charge); //on object-layer customer.ChargeAccount.Charges.Add(charge); } } //einzahlen in das Konto des Kunden um gewissen Betrag public void PayIn(Customer customer, decimal value) { AddCharge(customer, -value, "payin"); } //belastet das Konto des gegebenen Kunden um entsprechenden Betrag public void Burden(Customer customer, decimal value, String type) { if (customer.GetAge() < 14) value = value / 2; AddCharge(customer, value, type); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using BiBo; using BiBo.DAO; using BiBo.Exception; using BiBo.Persons; using BiBo.SQL; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Test.DAO { [TestClass()] public class CustomerDAOTest { [TestMethod()] //Fügt einen neuen Customer der Datenbank und Objektschicht hinzu public void AddCustomerTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); CustomerDAO cusDAO = new CustomerDAO(lib); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); cus.EMailAddress = "<EMAIL>"; cus.CreatedAt = DateTime.Now; cus.LastUpdate = DateTime.Now; cus.DeletedAt = DateTime.MaxValue; cus.AdditionalRoad = "abc"; cus.Right = Rights.CUSTOMER; //add an empty ChargeAccount ChargeAccount chargeAccount = new ChargeAccount(cus); chargeAccount.Id = lib.SQLHandler.ChargeAccountSQL.AddEntryReturnId(chargeAccount); cus.ChargeAccount = chargeAccount; Assert.IsTrue(cus.ChargeAccount == chargeAccount); //add user to DB and dummy get the right id cus.CustomerID = lib.SQLHandler.CustomerSQL.AddEntryReturnId(cus); Assert.IsTrue(cus.CustomerID == lib.SQLHandler.CustomerSQL.AddEntryReturnId(cus)); //maybe it is also good to set the customer cus.ChargeAccount.Customer = cus; //add the customer card Card card = new Card(cus); DateTime valid = new DateTime(); valid = DateTime.Now.AddYears(1); card.CardValidUntil = valid; card.CardID = lib.SQLHandler.CardSQL.AddEntryReturnId(card); cus.Card = card; Assert.IsTrue(cus.Card == card); lib.DAOHandler.ChargeAccountDAO.Burden(cus, (decimal)lib.Fee, "fee"); //add user in Objects lib.CustomerList.Add(cus); //refresh GUI-View lib.GUIApi.AddCustomer(cus); Assert.Inconclusive("Erfolgreich"); } [TestMethod()] public void BorrowExemplarTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); ulong bookId = 1; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); Exemplar ex = new Exemplar(boo); Customer cus = new Customer(cusID, firstName, lastName, birthDate); cus.UserState = UserStates.ACTIVE; //on object-layer ex.LoanPeriod = DateTime.Now.AddMonths(1); ex.Borrower = cus; ex.CustomerId = cus.CustomerID; cus.ExemplarList.Add(ex); //on db-layer update the customer lib.SQLHandler.CustomerSQL.UpdateEntry(cus); //on db-layer update the exemplar lib.SQLHandler.ExemplarSQL.UpdateEntry(ex); //on gui boo = lib.DAOHandler.BookDAO.GetBookById(ex.BookId); lib.GUIApi.moveExemplarFormBookToCustomer(ex, boo); CustomerDAO cusDAO = new CustomerDAO(lib); Assert.IsTrue(cusDAO.BorrowExemplar(ex, cus)); } [TestMethod()] //Setzt den Status eines Kunden in der Datenbank und Objektschicht als gelöscht public void DeleteCustomerTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); CustomerDAO cusDAO = new CustomerDAO(lib); cusDAO.AddCustomer(cus); decimal currentValue = 0; //Last() on empty list will return NULL if (cus.ChargeAccount.Charges.Count > 0) { currentValue = cus.ChargeAccount.Charges.Last().CurrentValue; } if (currentValue == 0 && cus.ExemplarList.Count == 0) { //on object-layer cus.UserState = UserStates.DELETED; //on db-layer we simple need an update to store also data of deleted users cus.UserState = UserStates.DELETED; cus.DeletedAt = DateTime.Now; lib.SQLHandler.CustomerSQL.UpdateEntry(cus); //on view-layer lib.GUIApi.DeleteCustomer(cus); } else throw new System.Exception(cus.FirstName + " " + cus.LastName + " kann nicht gelöscht werden, da entweder Exemplare ausgeliehen sind, oder das Gebührenkonto nicht ausgeglichen ist"); cusDAO.DeleteCustomer(cus); Assert.Inconclusive("Erfolgreich"); } [TestMethod()] public void FindCustomerWhoBorrowedTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); CustomerDAO cusDAO = new CustomerDAO(lib); cusDAO.AddCustomer(cus); ulong bookId = 1; string author = "Mueller"; string titel = "Das Buch"; string subjectArea = "Drama"; Book boo = new Book(bookId, author, titel, subjectArea); Exemplar ex = new Exemplar(boo); ulong expl_id = ex.BookId; Assert.AreEqual(lib.ExemplarList.Find(e => e.ExemplarId == expl_id).Borrower, cusDAO.FindCustomerWhoBorrowed(expl_id)); } [TestMethod()] public void GetCustomerByIdTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); // lib.CustomerList.Add(cus); CustomerDAO cusDAO = new CustomerDAO(lib); cusDAO.AddCustomer(cus); Assert.AreEqual(lib.CustomerList.Find(cust => cust.CustomerID == cusID), cus); } [TestMethod()] public void SetPasswordTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); CustomerDAO cusDAO = new CustomerDAO(lib); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); string password = "<PASSWORD>"; MD5 md5 = MD5.Create(); byte[] output = md5.ComputeHash(Encoding.UTF8.GetBytes(password)); StringBuilder builder = new StringBuilder(); foreach (byte by in output) { builder.Append(by.ToString("x2")); } cus.Password = builder.ToString(); cusDAO.AddCustomer(cus); cusDAO.SetPassword(cus, password); Assert.Inconclusive("E<PASSWORD>"); } [TestMethod()] //Liefert den MD5 Hash public void getMD5Test() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); CustomerDAO cusDAO = new CustomerDAO(lib); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); cusDAO.AddCustomer(cus); string password = "<PASSWORD>"; MD5 md5 = MD5.Create(); byte[] output = md5.ComputeHash(Encoding.UTF8.GetBytes(password)); StringBuilder builder = new StringBuilder(); foreach (byte by in output) { builder.Append(by.ToString("x2")); } cus.Password = builder.ToString(); Assert.AreEqual(cus.Password, builder.ToString()); } [TestMethod()] //method to edit a customer public void UpdateCustomerTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); ulong cusID2 = 1; string firstName2 = "Neu"; string lastName2 = "Nachname"; DateTime birthDate2 = DateTime.Parse("01.04.1999"); Customer cus2 = new Customer(cusID2, firstName2, lastName2, birthDate2); lib.CustomerList.Add(cus); //on object-layer lib.CustomerList.RemoveAll(x => x.CustomerID == cus.CustomerID); lib.CustomerList.Add(cus2); //on db lib.SQLHandler.CustomerSQL.UpdateEntry(cus2); //on view lib.GUIApi.UpdateCustomer(cus2); Assert.Inconclusive("Erfolgreich"); } [TestMethod()] //Setzt das Passwort eines Kunden public void checkPassTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); CustomerDAO cusDAO = new CustomerDAO(lib); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); cusDAO.AddCustomer(cus); // evtl. lib.CustomerList.Add(cus); try { foreach (Customer customer in lib.CustomerList) { if (customer.CustomerID == cusID) Assert.AreEqual(customer, cus); } } catch (Exception) { throw new CustomerNotFoundException("Benutzer mit gegebener ID nicht vorhanden"); } string pass = "<PASSWORD>"; cusDAO.checkPass(cus, pass); Assert.IsTrue(cusDAO.checkPass(cus, pass)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SQLite; using System.Data.SqlTypes; using System.Net; using System.Text.RegularExpressions; using System.Windows; using BiBo.Persons; using BiBo.DAO; namespace BiBo.SQL { class InitDbSQL { SqlConnector SQLHandler; public InitDbSQL(SqlConnector sqlh) { this.SQLHandler = sqlh; } // Create all Tables for Database public bool createAllTables() { string customerSQL = @"CREATE TABLE IF NOT EXISTS Customer ( ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, firstName VARCHAR(100) NOT NULL, lastName VARCHAR(100) NOT NULL, birthDate DATETIME, email VARCHAR(100), mobileNumber VARCHAR(100), createdAt DATETIME, lastUpdate DATETIME, deletedAt DATEIME, street VARCHAR(100), streetNumber VARCHAR(10), additionalRoad VARCHAR(100), zipCode VARCHAR(100), town VARCHAR(100), country VARCHAR(100), rights VARCHAR(100), password VARCHAR(100), chargeAccountId INTEGER, BiboID INTEGER, state VARCHAR(100) );"; SQLiteCommand command = new SQLiteCommand(customerSQL, SQLHandler.Connection); command.ExecuteNonQuery(); string chargeAccountSQL = @"CREATE TABLE IF NOT EXISTS ChargeAccount ( ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, customerId INTEGER NOT NULL );"; SQLiteCommand command2 = new SQLiteCommand(chargeAccountSQL, SQLHandler.Connection); command2.ExecuteNonQuery(); string exemplarSQL = @"CREATE TABLE IF NOT EXISTS Exemplar ( ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, bookId INTEGER, loanPeriod DateTime, state VARCHAR(100), signatur VARCHAR(100), access VARCHAR(100), customerId INTEGER, countBorrow INTEGER );"; SQLiteCommand command3 = new SQLiteCommand(exemplarSQL, SQLHandler.Connection); command3.ExecuteNonQuery(); string bookSQL = @"CREATE TABLE IF NOT EXISTS Book ( ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, author VARCHAR(100) NOT NULL, titel VARCHAR(100) NOT NULL, subjectArea VARCHAR(100) NOT NULL );"; SQLiteCommand command4 = new SQLiteCommand(bookSQL, SQLHandler.Connection); command4.ExecuteNonQuery(); string chargeTransactionSQL = @"CREATE TABLE IF NOT EXISTS ChargeTransactions ( TransactionID Integer NOT NULL PRIMARY KEY AUTOINCREMENT, ChargeAccountID INTEGER NOT NULL, change DECIMAL, newValue DECIMAL, changedAt DATETIME, type VARCHAR(100) );"; SQLiteCommand command5 = new SQLiteCommand(chargeTransactionSQL, SQLHandler.Connection); command5.ExecuteNonQuery(); string cardSQL = @"CREATE TABLE IF NOT EXISTS Card ( ID Integer NOT NULL PRIMARY KEY AUTOINCREMENT, CustomerId INTEGER NOT NULL, cardValidUntil DATETIME NOT NULL );"; SQLiteCommand command6 = new SQLiteCommand(cardSQL, SQLHandler.Connection); command6.ExecuteNonQuery(); string openingTimeSql = @"CREATE TABLE IF NOT EXISTS Library ( ID Integer NOT NULL PRIMARY KEY AUTOINCREMENT, Name VARCHAR(100), Adress VARCHAR(256), Monday VARCHAR(100), Tuesday VARCHAR(100), Wednesday VARCHAR(100), Thursday VARCHAR(100), Friday VARCHAR(100), Saturday VARCHAR(100), Sunday VARCHAR(100), Fee DECIMAL, Billing DECIMAL );"; SQLiteCommand command7 = new SQLiteCommand(openingTimeSql, SQLHandler.Connection); command7.ExecuteNonQuery(); string preOrderSQL = @"CREATE TABLE IF NOT EXISTS PreOrder ( CustomerID INTEGER NOT NULL, ExemplarID INTEGER NOT NULL );"; SQLiteCommand command8 = new SQLiteCommand(preOrderSQL, SQLHandler.Connection); command8.ExecuteNonQuery(); return true; } // Generate Dummy Data and add this to Database public bool createDummyData() { Random r = new Random(); List<Book> bookList = SQLHandler.BookSQL.getAllBooksForNonLib(); String[] fnames = {"Klaus","Peter","Anton","Susan","Ingo","Carlos","Olga","Emiel","Philipp", "Erik", "Dieter", "Sascha", "Pitt", "Johann"}; String[] names = {"Dahse","Münzberg","Korepin","Dambeck","Quittenbaum","Müller","Mayer","Schulze", "Bullmann", "Doschek", "Ender", "Fernow"}; for (int i = 0; i < 20; i++) { Customer customer = new Customer(); if (i == 0) customer.Right = Rights.ADMINISTRATOR; else if (i == 1) customer.Right = Rights.EMPLOYEE; else customer.Right = Rights.CUSTOMER; customer.FirstName = fnames[r.Next(0, fnames.Length - 1)]; customer.LastName = names[r.Next(0, names.Length - 1)]; customer.BirthDate = new DateTime(r.Next(1900, 2000), r.Next(1, 12), r.Next(1, 28)); customer.Country = "Deutschland"; customer.Town = names[r.Next(0, names.Length - 1)] + "stadt"; customer.CustomerID = Convert.ToUInt64(i + 1); customer.EMailAddress = customer.FirstName + "." + customer.LastName + "@gmail.com"; customer.MobileNumber = "0172" + r.Next(1234567, 9999999); customer.AdditionalRoad = ""; customer.BiboID = 1; customer.CreatedAt = DateTime.Now; customer.LastUpdate = DateTime.Now; customer.DeletedAt = DateTime.MaxValue; customer.Street = customer.LastName + "strasse"; customer.StreetNumber = r.Next(1, 100).ToString(); customer.ZipCode = r.Next(10000, 99999).ToString(); //add an empty ChargeAccount ChargeAccount chargeAccount = new ChargeAccount(customer); ulong chargeAccountId = SQLHandler.ChargeAccountSQL.AddEntryReturnId(chargeAccount); chargeAccount.Id = chargeAccountId; customer.ChargeAccount = chargeAccount; //add the customer card Card card = new Card(customer); DateTime valid = new DateTime(); valid = DateTime.Now.AddYears(1); card.CardValidUntil = valid; ulong cardId = SQLHandler.CardSQL.AddEntryReturnId(card); card.CardID = cardId; customer.Card = card; //add exemplar to customer for (int j = 0; j < r.Next(1, 6); j++) { DateTime date = new DateTime(); date = DateTime.Now.AddDays(r.Next(20,30)); Book book = bookList.ElementAt(r.Next(1,20)); //customerDAO.BorrowExemplar(date, book, customer); Exemplar ex = null; foreach (Exemplar exemplar in book.Exemplare) { if (exemplar.Accesser == Access.FREEHAND_LENDING && exemplar.State != BookStates.MISSING && exemplar.State != BookStates.ONLY_VISIBLE) { ex = exemplar; break; } } if (ex != null) { ex.LoanPeriod = date; ex.Borrower = customer; ex.CountBorrow = ex.CountBorrow + 1; customer.ExemplarList.Add(ex); } //on db-layer update the customer //customerSql.UpdateEntry(customer); //on db-layer update the exemplar SQLHandler.ExemplarSQL.UpdateEntry(ex); } //add a charge to customer ChargeAccountDAO chargeAccountDAO = new ChargeAccountDAO(SQLHandler); chargeAccountDAO.Burden(customer, 10, "fee"); customer.Password = <PASSWORD>.<PASSWORD>("<PASSWORD>"); SQLHandler.CustomerSQL.AddEntry(customer); } return true; } //Generate Randome Books public void createRandomBooks() { String Source = "http://www.lovelybooks.de/buecher/romane/Schr%C3%A4ge-Buchtitel-582954334/"; WebClient client = new WebClient(); client.Encoding = Encoding.UTF8; string downloadString = client.DownloadString(Source); Regex regex = new Regex(@">([^<]+)</span></a></h3"); var listTitle = (from Match m in regex.Matches(downloadString) select m).ToList(); regex = new Regex(@"von\s<a[^>]+>([^<]+)<"); var listAuthor = (from Match m in regex.Matches(downloadString) select m).ToList(); Random r = new Random(); int k; Book book; for (int i = 0; i < listTitle.Count; i++) //TODO: there are only 100 exemplars but not for every book { k = r.Next(1, 5); book = new Book(0, listAuthor[i].Groups[1].Value, listTitle[i].Groups[1].Value, "Roman"); book.BookId = SQLHandler.BookSQL.AddEntryReturnId(book); for (int j = 0; j < k; j++) { Exemplar exemplar = new Exemplar(book); exemplar.ExemplarId = SQLHandler.ExemplarSQL.AddEntryReturnId(exemplar); //make the signatur unic and update the exemplar in the DB exemplar.Signatur = exemplar.Signatur + exemplar.ExemplarId.ToString("x") + "]"; SQLHandler.ExemplarSQL.UpdateEntry(exemplar); book.Exemplare.Add(exemplar); } } MessageBox.Show("Book add done"); } // Create all Libarary Data public void createLibraryValues() { SQLHandler.LibrarySQL.SetOpeningTime(new Dictionary<string, string>(){ {"Montag", "09:00 - 18:00 Uhr"}, {"Dienstag", "08:00 - 18:00 Uhr"}, {"Mittwoch", "08:00 - 18:00 Uhr"}, {"Donnerstag", "08:00 - 18:00 Uhr"}, {"Freitag", "08:00 - 18:00 Uhr"}, {"Sonnabend", "10:00 - 14:00 Uhr"}, {"Sonntag", "geschlossen"} }); SQLHandler.LibrarySQL.SetName("<NAME>"); SQLHandler.LibrarySQL.SetAdress("Heidelbergerstr. 23 \n 10486 Berlin"); this.SQLHandler.LibrarySQL.SetFee(10); this.SQLHandler.LibrarySQL.SetBilling(5); } } } <file_sep>using System; using System.Collections.Generic; using BiBo; using BiBo.Persons; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Test.Persons { [TestClass()] public class ChargeAccountTest { [TestMethod()] // Erstellen einer Charge public void ChargesTest() { ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); DateTime changedAt = DateTime.Today; decimal currentValue = 500; decimal changeValue = 50; Charge ch = new Charge(currentValue, changeValue); int capacity = 1; List<Charge> chargelist = new List<Charge>(capacity); chargelist.Add(ch); ChargeAccount chAcc = new ChargeAccount(cus); chAcc.Charges = chargelist; Assert.AreEqual(chargelist[0], ch); Assert.AreEqual(chAcc.Charges, chargelist); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SQLite; using BiBo.Persons; using BiBo.SQL; using System.Data; using System.Windows; using System.Diagnostics; namespace BiBo.SQL { public class LibrarySQL { private SqlConnector SQLHandler; public LibrarySQL(SqlConnector sqlc) { this.SQLHandler = sqlc; } // Set Billing to Library Table public bool SetBilling(Double Billing) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = @"INSERT OR REPLACE INTO Library ( ID, Name, Adress, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, Fee, Billing ) VALUES ( 1, (SELECT Name FROM Library WHERE id = 1), (SELECT Adress FROM Library WHERE id = 1), (SELECT Monday FROM Library WHERE id = 1), (SELECT Tuesday FROM Library WHERE id = 1), (SELECT Wednesday FROM Library WHERE id = 1), (SELECT Thursday FROM Library WHERE id = 1), (SELECT Friday FROM Library WHERE id = 1), (SELECT Saturday FROM Library WHERE id = 1), (SELECT Sunday FROM Library WHERE id = 1), (SELECT Fee FROM Library WHERE id = 1), '" + Billing.ToString() + @"' );"; command.ExecuteNonQuery(); return true; } // Get Billing data public Double GetBilling() { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); SQLiteDataReader reader; command.CommandText = "SELECT Billing FROM Library"; Decimal Billing = 0; try { reader = command.ExecuteReader(); if (reader.HasRows) { reader.Read(); try { Billing = reader.GetDecimal(reader.GetOrdinal("Billing")); } catch (InvalidCastException ice) { Debug.WriteLine(ice.Message); } } } catch (SQLiteException sqle) { MessageBox.Show(sqle.Message); } return (Double)Billing; } // Set Fee public bool SetFee(Double Fee) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = @"INSERT OR REPLACE INTO Library ( ID, Name, Adress, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, Fee, Billing ) VALUES ( 1, (SELECT Name FROM Library WHERE id = 1), (SELECT Adress FROM Library WHERE id = 1), (SELECT Monday FROM Library WHERE id = 1), (SELECT Tuesday FROM Library WHERE id = 1), (SELECT Wednesday FROM Library WHERE id = 1), (SELECT Thursday FROM Library WHERE id = 1), (SELECT Friday FROM Library WHERE id = 1), (SELECT Saturday FROM Library WHERE id = 1), (SELECT Sunday FROM Library WHERE id = 1), '" + Fee.ToString() + @"', (SELECT Billing FROM Library WHERE id = 1) );"; command.ExecuteNonQuery(); return true; } // Get current Fee public Double GetFee() { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); SQLiteDataReader reader; command.CommandText = "SELECT Fee FROM Library"; Decimal Fee = 0; try { reader = command.ExecuteReader(); if (reader.HasRows) { reader.Read(); try { Fee = reader.GetDecimal(reader.GetOrdinal("Fee")); } catch (InvalidCastException ice) { Debug.WriteLine(ice.Message); } } } catch (SQLiteException sqle) { MessageBox.Show(sqle.Message); } return (Double) Fee; } // Set Adress of Library public bool SetAdress(String Adress) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = @"INSERT OR REPLACE INTO Library ( ID, Name, Adress, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, Fee, Billing ) VALUES ( 1, (SELECT Name FROM Library WHERE id = 1), '" + Adress + @"', (SELECT Monday FROM Library WHERE id = 1), (SELECT Tuesday FROM Library WHERE id = 1), (SELECT Wednesday FROM Library WHERE id = 1), (SELECT Thursday FROM Library WHERE id = 1), (SELECT Friday FROM Library WHERE id = 1), (SELECT Saturday FROM Library WHERE id = 1), (SELECT Sunday FROM Library WHERE id = 1), (SELECT Fee FROM Library WHERE id = 1), (SELECT Billing FROM Library WHERE id = 1) );"; command.ExecuteNonQuery(); return true; } //Get Library Adress public String GetAdress() { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); SQLiteDataReader reader; command.CommandText = "SELECT Adress FROM Library"; String Adress = ""; try { reader = command.ExecuteReader(); if (reader.HasRows) { reader.Read(); try { Adress = reader.GetString(reader.GetOrdinal("Adress")); } catch (InvalidCastException ice) { Debug.WriteLine(ice.Message); } } } catch (SQLiteException sqle) { MessageBox.Show(sqle.Message); } return Adress; } // Set Name of Library public bool SetName(String Name) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = @"INSERT OR REPLACE INTO Library ( ID, Name, Adress, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, Fee, Billing ) VALUES ( 1, '" + Name + @"', (SELECT Adress FROM Library WHERE id = 1), (SELECT Monday FROM Library WHERE id = 1), (SELECT Tuesday FROM Library WHERE id = 1), (SELECT Wednesday FROM Library WHERE id = 1), (SELECT Thursday FROM Library WHERE id = 1), (SELECT Friday FROM Library WHERE id = 1), (SELECT Saturday FROM Library WHERE id = 1), (SELECT Sunday FROM Library WHERE id = 1), (SELECT Fee FROM Library WHERE id = 1), (SELECT Billing FROM Library WHERE id = 1) );"; command.ExecuteNonQuery(); return true; } // Get Current Name of Library public String GetName() { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); SQLiteDataReader reader; command.CommandText = "SELECT Name FROM Library"; String Name = ""; try { reader = command.ExecuteReader(); if (reader.HasRows) { reader.Read(); try { Name = reader.GetString(reader.GetOrdinal("Name")); } catch (InvalidCastException ice) { Debug.WriteLine(ice.Message); } } } catch (SQLiteException sqle) { MessageBox.Show(sqle.Message); } return Name; } //Set Opening Time public bool SetOpeningTime(Dictionary<string, string> openingTime) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = @"INSERT OR REPLACE INTO Library ( ID, Name, Adress, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, Fee, Billing ) VALUES ( 1, (SELECT Name FROM Library WHERE id = 1), (SELECT Adress FROM Library WHERE id = 1), '" + openingTime["Montag"] + @"', '" + openingTime["Dienstag"] + @"', '" + openingTime["Mittwoch"] + @"', '" + openingTime["Donnerstag"] + @"', '" + openingTime["Freitag"] + @"', '" + openingTime["Sonnabend"] + @"', '" + openingTime["Sonntag"] + @"', (SELECT Fee FROM Library WHERE id = 1), (SELECT Billing FROM Library WHERE id = 1) );"; command.ExecuteNonQuery(); return true; } // Get current Opening Time public Dictionary<string, string> GetOpeningTime() { Dictionary<string, string> openingTimes = new Dictionary<string, string>(){ {"Montag", ""}, {"Dienstag", ""}, {"Mittwoch", ""}, {"Donnerstag", ""}, {"Freitag", ""}, {"Sonnabend", ""}, {"Sonntag", ""} }; SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); SQLiteDataReader reader; command.CommandText = "SELECT Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday FROM Library"; try { reader = command.ExecuteReader(); if (reader.HasRows) { reader.Read(); try { openingTimes["Montag"] = reader.GetString(reader.GetOrdinal("Monday")); openingTimes["Dienstag"] = reader.GetString(reader.GetOrdinal("Tuesday")); openingTimes["Mittwoch"] = reader.GetString(reader.GetOrdinal("Wednesday")); openingTimes["Donnerstag"] = reader.GetString(reader.GetOrdinal("Thursday")); openingTimes["Freitag"] = reader.GetString(reader.GetOrdinal("Friday")); openingTimes["Sonnabend"] = reader.GetString(reader.GetOrdinal("Saturday")); openingTimes["Sonntag"] = reader.GetString(reader.GetOrdinal("Sunday")); } catch (InvalidCastException ice) { Debug.WriteLine(ice.Message); } } } catch (SQLiteException sqle) { MessageBox.Show(sqle.Message); } return openingTimes; } } } <file_sep>using BiBo; using BiBo.SQL; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Test { [TestClass()] public class LibraryTest { [TestMethod()] // Gui Api Test public void getGuiApiTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); Assert.AreEqual(lib.GUIApi, gui); } } } <file_sep>using BiBo; using BiBo.Persons; using BiBo.SQL; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace Test { [TestClass()] public class CardTest { [TestMethod()] // Erstellen einer Karte public void CardIDTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); Card card = new Card(cus); cus.Card = card; card.CardID = lib.SQLHandler.CardSQL.AddEntryReturnId(card); Assert.IsNotNull(lib.SQLHandler.CardSQL.AddEntryReturnId(card)); } [TestMethod()] // Karte Gültigkeitstest public void CardValidUntilTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); Card card = new Card(cus); cus.Card = card; DateTime valid = new DateTime(); valid = DateTime.Now.AddYears(1); card.CardValidUntil = valid; Assert.IsNotNull(card.CardValidUntil); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BiBo.Exception { [Serializable()] public class CustomerNotFoundException : System.Exception { public CustomerNotFoundException(string message): base(message) { } } } <file_sep>using BiBo.DAO; using BiBo.Exception; using BiBo.Persons; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; namespace BiBo { public partial class MainWindow : Window { Library lib; Tabs CurrentEmployeeAreaTab = Tabs.CUSTOMER; ulong EditCustomerID; ulong ChangePassID; AppSettingsReader config = new AppSettingsReader(); bool blockSelectionChange = false; public bool BlockSelectionChange{ get { return this.blockSelectionChange; } set { this.blockSelectionChange = value; } } public Library Lib { get { return this.lib; } } public MainWindow() { // Unit tests only included in debug build if (Assembly.GetEntryAssembly() == null) { InitializeComponent(); return; } InitializeComponent(); if ((bool)config.GetValue("DirectLogin", typeof(bool))) { lib = new Library(); initElements(); login(lib.CustomerList.Single(c => c.CustomerID == (ulong)config.GetValue("LoginID", typeof(ulong)))); } } public MainWindow(GUIApi api) { InitializeComponent(); lib = new Library(api); initElements(); foreach (Customer cust in lib.CustomerList) { this.lib.DAOHandler.CustomerDAO.AddCustomer(cust); } } public void initMainWindow(){ if (!ProcessLib) { lib.GUIApi.initProgressBar(lib.CustomerList.Count + lib.BookList.Count) ; } foreach (Customer cust in lib.CustomerList) { lib.GUIApi.increaseProgressBar(); if ((lib.LoggedUser.Right == Rights.EMPLOYEE && cust.Right == Rights.CUSTOMER) || lib.LoggedUser.Right == Rights.ADMINISTRATOR ) { this.lib.GUIApi.AddCustomer(cust); this.lib.GUIApi.Add_b_Customer(cust); } } foreach (Book book in lib.BookList) { lib.GUIApi.increaseProgressBar(); this.lib.GUIApi.Add_c_Book(book); this.lib.GUIApi.AddBook(book); this.lib.GUIApi.Add_b_Book(book); } if (lib.LoggedUser.ExemplarList.Count > 0) { foreach (Exemplar expl in lib.LoggedUser.ExemplarList) { Book relatedBook = lib.BookList.Single(b => b.BookId == expl.BookId); lib.GUIApi.AddBorrowedDataGrid(expl, relatedBook, "cCustomerBorrwedExemplars"); } } else { //TODO something or still delete Else } if (lib.LoggedUser.ChargeAccount.Charges.Count > 0) { foreach (Charge chr in lib.LoggedUser.ChargeAccount.Charges) { lib.GUIApi.addChargeToDataGrid(chr, this.cCustomerCharges); } } else { //TODO something or still delete Else } } private void initElements() { initCoutriesComboBox(); initCustomerTable(); init_c_BookTable(); initBookTable(); initBorrowTabels(); init_c_BorrowTable(); init_c_ChargesTable(); } private void init_c_ChargesTable() { this.cCustomerCharges.DataContext = lib.GUIApi.getChargeDataTable(); } private void init_c_BorrowTable() { this.cCustomerBorrwedExemplars.DataContext = lib.GUIApi.getBorrowedTable(); } private void initCoutriesComboBox() { //init Employee_UserAdd_Country ComboBox comBox = this.Employee_UserAdd_Country; //create line string to catch lines from file // Read the file and display it line by line. string resource_data = Properties.Resources.countries; string [] words = resource_data.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries); foreach(string lines in words){ comBox.Items.Add(lines); } comBox.SelectedIndex = 0; } private void initBorrowTabels() { this.EmployeeBorrowTableCustomers.DataContext = lib.GUIApi.getCustomerDataTable(); this.EmployeeBorrowTableBooks.DataContext = lib.GUIApi.getBookDataTable(); this.EmployeeBorrowTableExemplars.DataContext = lib.GUIApi.getExemplarDataTable(); } private void initCustomerTable() { DataTable CustomerTable = lib.GUIApi.getCustomerDataTable(); this.CustomerTable.DataContext = CustomerTable; } private void init_c_BookTable() { DataTable BookTable = lib.GUIApi.getBookDataTable(); this.cBookTable.DataContext = BookTable; } private void initBookTable() { DataTable BookTable = lib.GUIApi.getBookDataTable(); this.EmployeeBooksTable.DataContext = BookTable; } private void resetEmployeeArea() { this.CustomerPanel.Visibility = Visibility.Visible; this.BookPanel.Visibility = Visibility.Hidden; //empty CustomerTable this.CustomerTable.DataContext = lib.GUIApi.getCustomerDataTable(); //empty CustomerBorrowedTable this.CustomerBorrowedTable.DataContext = lib.GUIApi.getBorrowedTable(); //empty EmployeeBooksTable this.EmployeeBooksTable.DataContext = lib.GUIApi.getBookDataTable(); //empty EmployeeBorrowTableCustomers this.EmployeeBorrowTableCustomers.DataContext = lib.GUIApi.getCustomerDataTable(); //empty EmployeeBorrowTableBooks this.EmployeeBorrowTableBooks.DataContext = lib.GUIApi.getBookDataTable(); //empty EmployeeBorrowTableExemplars this.EmployeeBorrowTableExemplars.DataContext = lib.GUIApi.getBorrowedTable(); this.Admin_UserAdd_LabelRights.Visibility = Visibility.Hidden; this.Admin_UserAdd_Rights.Visibility = Visibility.Hidden; this.Admin_ChangeOpeningTimes.Visibility = Visibility.Hidden; this.MainFee.Visibility = Visibility.Collapsed; this.MainBilling.Visibility = Visibility.Collapsed; this.MainFeeChangeButton.Visibility = Visibility.Collapsed; this.MainBillingChangeButton.Visibility = Visibility.Collapsed; } private void MouseUp_BooksImage(object sender, MouseButtonEventArgs e) { HandleTabs_EmployeeArea(Tabs.BOOK); } private void MouseUp_AccountImage(object sender, MouseButtonEventArgs e) { HandleTabs_EmployeeArea(Tabs.CUSTOMER); } private void MouseUp_BorrowImage(object sender, MouseButtonEventArgs e) { HandleTabs_EmployeeArea(Tabs.BORROW); } private void clearBookAddForm(){ (FindName("BookAddAuthor") as TextBox).Text = ""; (FindName("BookAddTitle") as TextBox).Text = ""; (FindName("BookAddSubjectArea") as TextBox).Text = ""; (FindName("BookAddNumberOfExemplars") as TextBox).Text = ""; } private void HandleTabs_EmployeeArea(Tabs show) { if (show == CurrentEmployeeAreaTab) return; //hide popups (FindName("popUpChangePassword") as Popup).IsOpen = false; //hide all (FindName("CustomerPanel") as Grid).Visibility = Visibility.Hidden; (FindName("BookPanel") as Grid).Visibility = Visibility.Hidden; (FindName("BorrowPanel") as Grid).Visibility = Visibility.Hidden; //show switch (show) { case Tabs.CUSTOMER: (FindName("CustomerPanel") as Grid).Visibility = Visibility.Visible; CurrentEmployeeAreaTab = Tabs.CUSTOMER; break; case Tabs.BOOK: (FindName("BookPanel") as Grid).Visibility = Visibility.Visible; CurrentEmployeeAreaTab = Tabs.BOOK; break; case Tabs.BORROW: (FindName("BorrowPanel") as Grid).Visibility = Visibility.Visible; CurrentEmployeeAreaTab = Tabs.BORROW; break; } } private void UserAdd_Click(object sender, RoutedEventArgs e) { if ((sender as Button).Content == "hinzufügen") { String Firstname = (FindName("Employee_UserAdd_Firstname") as TextBox).Text; String Lastname = (FindName("Employee_UserAdd_Lastname") as TextBox).Text; String Street = (FindName("Employee_UserAdd_Street") as TextBox).Text; String StreetNumber = (FindName("Employee_UserAdd_StreetNumber") as TextBox).Text; String zipCode = (FindName("Employee_UserAdd_ZipCode") as TextBox).Text; String Phone = (FindName("Employee_UserAdd_Phone") as TextBox).Text; var bday = (FindName("Employee_UserAdd_Birthday") as DatePicker).SelectedDate; DateTime Birthday = bday is DateTime ? (DateTime)bday : new DateTime(0, 0, 0); String Town = (FindName("Employee_UserAdd_Town") as TextBox).Text; String Country = (FindName("Employee_UserAdd_Country") as ComboBox).SelectedValue as String; String AdditionalRoad = (FindName("Employee_UserAdd_RoadAddition") as TextBox).Text; String Email = (FindName("Employee_UserAdd_Email") as TextBox).Text; Customer dummy = new Customer(0, Firstname, Lastname, Birthday); if (lib.LoggedUser.Right == Rights.ADMINISTRATOR) { ComboBox rights = this.Admin_UserAdd_Rights; String EmunString = (rights.SelectedItem as ComboBoxItem).Content as String; dummy.Right = (Rights)Enum.Parse(typeof(Rights), EmunString); } else { dummy.Right = Rights.CUSTOMER; } dummy.Street = Street; dummy.StreetNumber = StreetNumber; dummy.MobileNumber = Phone; dummy.ZipCode = zipCode; dummy.Town = Town; dummy.Country = Country; dummy.AdditionalRoad = AdditionalRoad; dummy.EMailAddress = Email; dummy.Password = <PASSWORD>("<PASSWORD>"); dummy.CreatedAt = DateTime.Now; dummy.LastUpdate = DateTime.Now; dummy.DeletedAt = DateTime.MaxValue; lib.DAOHandler.CustomerDAO.AddCustomer(dummy); clearAddCustomer(); } else { Customer toEdit = lib.DAOHandler.CustomerDAO.GetCustomerById(EditCustomerID); toEdit.FirstName = (FindName("Employee_UserAdd_Firstname") as TextBox).Text; toEdit.LastName = (FindName("Employee_UserAdd_Lastname") as TextBox).Text; toEdit.Street = (FindName("Employee_UserAdd_Street") as TextBox).Text; toEdit.StreetNumber = (FindName("Employee_UserAdd_StreetNumber") as TextBox).Text; toEdit.ZipCode = (FindName("Employee_UserAdd_ZipCode") as TextBox).Text; toEdit.MobileNumber = (FindName("Employee_UserAdd_Phone") as TextBox).Text; var bday = (FindName("Employee_UserAdd_Birthday") as DatePicker).SelectedDate; toEdit.BirthDate = bday is DateTime ? (DateTime)bday : new DateTime(0, 0, 0); toEdit.Town = (FindName("Employee_UserAdd_Town") as TextBox).Text; toEdit.Country = (FindName("Employee_UserAdd_Country") as ComboBox).SelectedValue as String; toEdit.AdditionalRoad = (FindName("Employee_UserAdd_RoadAddition") as TextBox).Text; toEdit.EMailAddress = (FindName("Employee_UserAdd_Email") as TextBox).Text; toEdit.LastUpdate = DateTime.Now; lib.DAOHandler.CustomerDAO.UpdateCustomer(toEdit); } } private void ToolBarUserAdd_Click(object sender, MouseButtonEventArgs e) { clearAddCustomer(); ToggleAddEditButton("hinzufügen"); showUnderToolBar(true); } private void ToolBarDelte_MouseUp(object sender, MouseButtonEventArgs e) { DataGrid table = FindName("CustomerTable") as DataGrid; if (table.SelectedItems.Count < 1) return; ulong id; List<Customer> customers = new List<Customer>(); foreach(DataRowView row in table.SelectedItems){ id = (ulong)row["ID"]; customers.Add(lib.DAOHandler.CustomerDAO.GetCustomerById(id)); } foreach (Customer c in customers) { try { lib.DAOHandler.CustomerDAO.DeleteCustomer(c); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } } private void showUnderToolBar(bool s) { if (CurrentEmployeeAreaTab == Tabs.CUSTOMER) { if (s) { Grid grid = FindName("CustomerPanel") as Grid; grid.RowDefinitions[0].Height = new GridLength(150); Grid CustomerAddGrid = FindName("CustomerAddGrid") as Grid; CustomerAddGrid.Visibility = Visibility.Visible; } else { Grid grid = FindName("CustomerPanel") as Grid; grid.RowDefinitions[0].Height = new GridLength(30); Grid CustomerAddGrid = FindName("CustomerAddGrid") as Grid; CustomerAddGrid.Visibility = Visibility.Collapsed; } return; } if (CurrentEmployeeAreaTab == Tabs.BOOK) { if (s) { Grid grid = FindName("EmployeeArea_BooksMainGrid") as Grid; grid.RowDefinitions[1].Height = new GridLength(30); /* Grid CustomerAddGrid = FindName("CustomerAddGrid") as Grid; CustomerAddGrid.Visibility = Visibility.Visible;*/ } else { Grid grid = FindName("EmployeeArea_BooksMainGrid") as Grid; grid.RowDefinitions[1].Height = new GridLength(0); /* Grid CustomerAddGrid = FindName("CustomerAddGrid") as Grid; CustomerAddGrid.Visibility = Visibility.Collapsed; * */ } return; } } private void Button_Click(object sender, RoutedEventArgs e) { showUnderToolBar(false); } private void Image_EditCustomerMouseUp(object sender, MouseButtonEventArgs e) { showUnderToolBar(true); EditCustomerID = getSelectedRowID( FindName("CustomerTable") as DataGrid ); if (EditCustomerID == 0) return; Customer customer = lib.DAOHandler.CustomerDAO.GetCustomerById(EditCustomerID); initEditCustomerFromByCustomer(customer); ToggleAddEditButton("bearbeiten"); } private void initEditCustomerFromByCustomer(Customer customer) { (FindName("Employee_UserAdd_Firstname") as TextBox).Text = customer.FirstName; (FindName("Employee_UserAdd_Lastname") as TextBox).Text = customer.LastName; (FindName("Employee_UserAdd_Street") as TextBox).Text = customer.Street; (FindName("Employee_UserAdd_StreetNumber") as TextBox).Text = customer.StreetNumber; (FindName("Employee_UserAdd_Phone") as TextBox).Text = customer.MobileNumber; (FindName("Employee_UserAdd_Birthday") as DatePicker).SelectedDate = customer.BirthDate; (FindName("Employee_UserAdd_Town") as TextBox).Text = customer.Town; (FindName("Employee_UserAdd_ZipCode") as TextBox).Text = customer.ZipCode; (FindName("Employee_UserAdd_Country") as ComboBox).SelectedValue = customer.Country; (FindName("Employee_UserAdd_RoadAddition") as TextBox).Text = customer.AdditionalRoad; (FindName("Employee_UserAdd_Email") as TextBox).Text = customer.EMailAddress; } private void clearAddCustomer() { (FindName("Employee_UserAdd_Firstname") as TextBox).Text = ""; (FindName("Employee_UserAdd_Lastname") as TextBox).Text = ""; (FindName("Employee_UserAdd_Street") as TextBox).Text = ""; (FindName("Employee_UserAdd_StreetNumber") as TextBox).Text = ""; (FindName("Employee_UserAdd_Phone") as TextBox).Text = ""; (FindName("Employee_UserAdd_Birthday") as DatePicker).SelectedDate = DateTime.Now; (FindName("Employee_UserAdd_Town") as TextBox).Text = ""; (FindName("Employee_UserAdd_Country") as ComboBox).SelectedValue = "Deutschland"; (FindName("Employee_UserAdd_RoadAddition") as TextBox).Text = ""; (FindName("Employee_UserAdd_Email") as TextBox).Text = ""; this.Admin_UserAdd_Rights.SelectedIndex = 0; } private void ClearUserAdd_Click(object sender, RoutedEventArgs e) { clearAddCustomer(); } private bool ProcessLib = false; private void Login_Click(object sender, RoutedEventArgs e) { if (lib == null) { lib = new Library(); initElements(); this.ProcessLib = true; } String IdString = (FindName("LoginName") as TextBox).Text; ulong id = 0; String pass = (FindName("LoginPass") as PasswordBox).Password; Customer potentialLogin; if (Validation.isNumeric(IdString)) { id = (ulong)Convert.ToInt64(IdString); try { potentialLogin = lib.DAOHandler.CustomerDAO.GetCustomerById(id); } catch (CustomerNotFoundException cnfe) { MessageBox.Show(cnfe.Message); return; } if (lib.DAOHandler.CustomerDAO.checkPass(potentialLogin, pass)) { //login lib.GUIApi.BlockSelectionEvents(true); login(potentialLogin); lib.GUIApi.BlockSelectionEvents(false); return; } MessageBox.Show("Ungültiges Password"); return; } MessageBox.Show("Die ID muss eine Zahl sein"); } private void login(Customer x) { switch (x.Right) { case Rights.ADMINISTRATOR: admin_login(x); break; case Rights.EMPLOYEE: employee_login(x); break; case Rights.CUSTOMER: customer_login(x); break; } } private void admin_login(Customer admin) { resetEmployeeArea(); lib.LoggedUser = admin; (FindName("Admin_UserAdd_LabelRights") as Label).Visibility = Visibility.Visible; (FindName("Admin_UserAdd_Rights") as ComboBox).Visibility = Visibility.Visible; (FindName("Admin_ChangeOpeningTimes") as Button).Visibility = Visibility.Visible; this.MainFee.Visibility = Visibility.Visible; this.MainBilling.Visibility = Visibility.Visible; this.MainFeeChangeButton.Visibility = Visibility.Visible; this.MainBillingChangeButton.Visibility = Visibility.Visible; initMainWindow(); lib.GUIApi.setLoggedInUser(admin); (FindName("EmployeeArea") as Grid).Visibility = Visibility.Visible; (FindName("Login") as Grid).Visibility = Visibility.Collapsed; } private void employee_login(Customer employee) { resetEmployeeArea(); lib.LoggedUser = employee; initMainWindow(); lib.GUIApi.setLoggedInUser(employee); (FindName("EmployeeArea") as Grid).Visibility = Visibility.Visible; (FindName("Login") as Grid).Visibility = Visibility.Collapsed; } private void resetCustomerArea() { this.cCustomerBorrwedExemplars.DataContext = lib.GUIApi.getBorrowedTable(); this.cBookTable.DataContext = lib.GUIApi.getBookDataTable(); this.cCustomerCharges.DataContext = lib.GUIApi.getChargeDataTable(); ToggleCustomerTabs(true); } private void customer_login(Customer customer) { resetCustomerArea(); lib.LoggedUser = customer; initMainWindow(); lib.GUIApi.setLoggedInUser(customer); (FindName("CustomerArea") as Grid).Visibility = Visibility.Visible; (FindName("Login") as Grid).Visibility = Visibility.Collapsed; } private void ToolBarShowBorrowed_MouseUp(object sender, MouseButtonEventArgs e) { DataGrid table = FindName("CustomerTable") as DataGrid; ulong id = getSelectedRowID(table); Grid grid = FindName("CustomerPanel") as Grid; if (grid.RowDefinitions[3].ActualHeight < 20) { grid.RowDefinitions[3].Height = new GridLength(120); } else { grid.RowDefinitions[3].Height = new GridLength(0); } if (id == 0) return; Customer customer = lib.DAOHandler.CustomerDAO.GetCustomerById(id); //init Datagrid view for exemplars initExemplarTableByCustomer(customer); } private void initExemplarTableByCustomer(Customer customer) { DataGrid exemplarTable = (FindName("CustomerBorrowedTable") as DataGrid); DataTable extable = lib.GUIApi.getBorrowedTable(); exemplarTable.DataContext = extable; //Exemplare hinzufügen foreach (Exemplar ex in customer.ExemplarList) { Book ex2book = lib.DAOHandler.BookDAO.GetBookById(ex.BookId); lib.GUIApi.AddBorrowedDataGrid(ex, ex2book, "CustomerBorrowedTable"); } } private void Employee_Logout_MouseUp(object sender, MouseButtonEventArgs e) { ProgressBar ProgressBar1 = FindName("pb") as ProgressBar; ProgressBar1.Visibility = Visibility.Hidden; ProcessLib = false; ProgressBar1.Value = 0; //hide popups (FindName("popUpChangePassword") as Popup).IsOpen = false; (FindName("EmployeeArea") as Grid).Visibility = Visibility.Collapsed; (FindName("Login") as Grid).Visibility = Visibility.Visible; (FindName("LoginName") as TextBox).Text = ""; (FindName("LoginPass") as PasswordBox).Password = ""; HandleTabs_EmployeeArea(Tabs.CUSTOMER); } private void Customer_Logout_MouseUp(object sender, MouseButtonEventArgs e) { ProgressBar ProgressBar1 = FindName("pb") as ProgressBar; ProgressBar1.Visibility = Visibility.Hidden; ProcessLib = false; ProgressBar1.Value = 0; //CustomerPanel (FindName("CustomerArea") as Grid).Visibility = Visibility.Collapsed; (FindName("Login") as Grid).Visibility = Visibility.Visible; (FindName("LoginName") as TextBox).Text = ""; (FindName("LoginPass") as PasswordBox).Password = ""; } private void EmployeeArea_Unfold(object sender, MouseButtonEventArgs e) { showUnderToolBar(false); } private void LoginInfo_MouseUp(object sender, MouseButtonEventArgs e) { MessageBox.Show("Bitte wenden Sie sich an einen unserer Mitarbeiter. Dieser kann Ihnen über Ihren Zugang informieren"); } private void ToggleAddEditButton(String value) { Button x = FindName("CustomerAddEditButton") as Button; Button reset = FindName("CustomerAddEditResetButton") as Button; if (value != "") { x.Content = value; if (value == "hinzufügen") { reset.Visibility = Visibility.Visible; } else { reset.Visibility = Visibility.Collapsed; } return; } if (x.Content.ToString().CompareTo("hinzufügen") == 0) { x.Content = "bearbeiten"; } else { x.Content = "hinzufügen"; } } private void ToolResetPass_MouseUp(object sender, MouseButtonEventArgs e) { ChangePassID = getSelectedRowID(FindName("CustomerTable") as DataGrid); if (ChangePassID == 0) return; Popup p = FindName("popUpChangePassword") as Popup; p.IsOpen = true; } private void ChangePasswordAbort_Click(object sender, RoutedEventArgs e) { PasswordBox Password = (FindName("changePasswordTextBox") as PasswordBox); PasswordBox Confirm = (FindName("changePasswordConfirm") as PasswordBox); Password.Password = ""; Confirm.Password = ""; (FindName("popUpChangePassword") as Popup).IsOpen = false; } private void ChangePassword_Click(object sender, RoutedEventArgs e) { PasswordBox Password = (FindName("changePasswordTextBox") as PasswordBox); PasswordBox Confirm = (FindName("changePasswordConfirm") as PasswordBox); String pass = Password.Password; String conf = Confirm.Password; if (pass.CompareTo(conf) == 0) { Customer customer = lib.DAOHandler.CustomerDAO.GetCustomerById(ChangePassID); lib.DAOHandler.CustomerDAO.SetPassword(customer, pass); lib.DAOHandler.CustomerDAO.UpdateCustomer(customer); (FindName("popUpChangePassword") as Popup).IsOpen = false; MessageBox.Show("Passwort erfolgreich geändert!"); } else { MessageBox.Show("Wiederholung des Passowrts fehlgeschlagen"); Password.Password = ""; Confirm.Password = ""; } } private ulong getSelectedRowID(DataGrid dg) { DataRowView row; try { row = (DataRowView)dg.SelectedItems[0]; } catch (ArgumentOutOfRangeException aoore) { Debug.WriteLine(aoore.Message); return 0; } return (ulong)row["ID"]; } private void MainCustomerTable_DoubleClick(object sender, MouseButtonEventArgs e) { EditCustomerID = getSelectedRowID(sender as DataGrid); if (EditCustomerID == 0) return; Customer customer = lib.DAOHandler.CustomerDAO.GetCustomerById(EditCustomerID); clearAddCustomer(); initEditCustomerFromByCustomer(customer); ToggleAddEditButton("bearbeiten"); showUnderToolBar(true); } private void LoginName_KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { Login_Click(new Object(), new RoutedEventArgs()); } } private void EmployeeArea_AddBook_MouseUp(object sender, MouseButtonEventArgs e) { (FindName("EmployeeArea_BookAddButton") as Button).Content = "hinzufügen"; (FindName("explCountIdToggle") as Label).Content = "Anzahl der Exemplare"; (FindName("BookAddNumberOfExemplars") as TextBox).IsReadOnly = false; clearBookAddForm(); showUnderToolBar(true); } private void BooksTable_DoubleClick(object sender, RoutedEventArgs e) { DataGrid that = sender as DataGrid; DataRowView Row = that.SelectedItem as DataRowView; ulong id = (ulong) Row["ID"]; Book selectedBook = lib.DAOHandler.BookDAO.GetBookById(id); (FindName("BookAddAuthor") as TextBox).Text = selectedBook.Author; (FindName("BookAddTitle") as TextBox).Text = selectedBook.Titel; (FindName("BookAddSubjectArea") as TextBox).Text = selectedBook.SubjectArea; (FindName("explCountIdToggle") as Label).Content = "Buch ID"; (FindName("BookAddNumberOfExemplars") as TextBox).Text = id.ToString(); (FindName("BookAddNumberOfExemplars") as TextBox).IsReadOnly = true; (FindName("EmployeeArea_BookAddButton") as Button).Content = "bearbeiten"; showUnderToolBar(true); } private void EmployeeArea_BookAddButton_Click(object sender, RoutedEventArgs e) { String author = (FindName("BookAddAuthor") as TextBox).Text; String title = (FindName("BookAddTitle") as TextBox).Text; String subjectArea = (FindName("BookAddSubjectArea") as TextBox).Text; String numberOfExemplars = (FindName("BookAddNumberOfExemplars") as TextBox).Text; if ((FindName("EmployeeArea_BookAddButton") as Button).Content.ToString() != "bearbeiten") { int countExemplars = 1; if (Validation.isNumeric(numberOfExemplars)) { countExemplars = Convert.ToInt32(numberOfExemplars); } else { MessageBox.Show("Anzahl der Exemplare darf nur Zahlen enthalten"); return; } //TODO validation Book dummy = new Book(0, author, title, subjectArea); lib.DAOHandler.BookDAO.AddBook(dummy, countExemplars); (FindName("BookAddAuthor") as TextBox).Text = ""; (FindName("BookAddTitle") as TextBox).Text = ""; (FindName("BookAddSubjectArea") as TextBox).Text = ""; (FindName("BookAddNumberOfExemplars") as TextBox).Text = ""; } else { // ulong ID ulong id = (ulong) Convert.ToInt64((FindName("BookAddNumberOfExemplars") as TextBox).Text); Book changedBook = lib.BookList.Single(b => b.BookId == id); changedBook.Author = author; changedBook.Titel = title; changedBook.SubjectArea = subjectArea; //TODO update book } } private void getExemplarsFromBooksTable(DataGrid sender){ ulong bookId = getSelectedRowID(sender); if(bookId == 0) return; Book SelectedBook; try { SelectedBook = lib.DAOHandler.BookDAO.GetBookById(bookId); } catch (BookNotFoundException bnfe) { Debug.WriteLine(bnfe.Message); return; } lib.GUIApi.fillExemplarsToBorrow(SelectedBook); } private void EmployeeBorrowTableBooks_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (!BlockSelectionChange) { getExemplarsFromBooksTable(sender as DataGrid); } } private void EmployeeBorrowTableCustomers_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (!BlockSelectionChange) { //unselect other tables (FindName("EmployeeBorrowTableBooks") as DataGrid).UnselectAll(); (FindName("EmployeeBorrowTableExemplars") as DataGrid).UnselectAll(); //clear exemplar table (FindName("EmployeeBorrowTableExemplars") as DataGrid).DataContext = lib.GUIApi.getExemplarDataTable(); //fill borrowed grid (FindName("CustomersExemplars") as DataGrid).DataContext = lib.GUIApi.getBorrowedTable(); ulong ID = getSelectedRowID(sender as DataGrid); if (ID == 0) return; Customer selectedCustomer = lib.DAOHandler.CustomerDAO.GetCustomerById(ID); foreach (Exemplar expl in selectedCustomer.ExemplarList) { lib.GUIApi.AddBorrowedDataGrid(expl, lib.DAOHandler.BookDAO.GetBookById(expl.BookId), "CustomersExemplars"); } } } private void EmployeeBorrowTableExemplars_LoadingRow(object sender, DataGridRowEventArgs e) { DataRowView drv = e.Row.Item as DataRowView; DataRow row = drv.Row; if (row["Kunden ID"].ToString() != "frei") { e.Row.Background = Brushes.Red; } else { e.Row.Background = getBrush("61FA67"); } } private void EmployeeBorrowTableBooks_LoadingRow(object sender, DataGridRowEventArgs e) { DataRowView drv = e.Row.Item as DataRowView; DataRow row = drv.Row; ulong bookID = (ulong)row["ID"]; Book book = lib.DAOHandler.BookDAO.GetBookById(bookID); int number = book.Exemplare.Count(expl => expl.CustomerId == 0); if (number == 0) { e.Row.Background = Brushes.Red; } else if (number == 1) { e.Row.Background = Brushes.Yellow; } else { e.Row.Background = getBrush("61FA67"); } } private void EmployeeBorrowTableCustomers_LoadingRow(object sender, DataGridRowEventArgs e) { DataRowView drv = e.Row.Item as DataRowView; DataRow row = drv.Row; ulong customerID = (ulong)row["ID"]; Customer customer = lib.DAOHandler.CustomerDAO.GetCustomerById(customerID); if (customer.UserState == UserStates.BANNED) { e.Row.Background = Brushes.Red; } else { if (customer.ExemplarList.Count > 0) { e.Row.Background = Brushes.Green; } else { e.Row.Background = Brushes.LightGreen; } } } private void CustomerTable_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (!BlockSelectionChange) { ulong id = getSelectedRowID(FindName("CustomerTable") as DataGrid); if (id == 0) return; Customer customer = lib.DAOHandler.CustomerDAO.GetCustomerById(id); initExemplarTableByCustomer(customer); } } private void BorrowFilterCustomer_KeyUp(object sender, KeyEventArgs e) { DataGrid dataGrid = FindName("EmployeeBorrowTableCustomers") as DataGrid; TextBox Input = sender as TextBox; for (int i = 0; i < dataGrid.Items.Count; i++) { DataGridRow dgRow = GetRow(dataGrid, i); DataRowView vRow = dgRow.Item as DataRowView; DataRow Row = vRow.Row; if (Row["ID"].ToString().Contains(Input.Text)) { dgRow.Visibility = Visibility.Visible; } else { dgRow.Visibility = Visibility.Collapsed; } } } private DataGridRow GetRow(DataGrid grid, int index) { DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index); if (row == null) { // May be virtualized, bring into view and try again. grid.UpdateLayout(); grid.ScrollIntoView(grid.Items[index]); row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index); } return row; } private void BorrowFilterBooks_KeyUp(object sender, KeyEventArgs e) { DataGrid dataGrid = FindName("EmployeeBorrowTableBooks") as DataGrid; TextBox Input = sender as TextBox; for (int i = 0; i < dataGrid.Items.Count; i++) { DataGridRow dgRow = GetRow(dataGrid, i); DataRowView vRow = dgRow.Item as DataRowView; DataRow Row = vRow.Row; String SearchString = Row["Author"].ToString() + Row["Title"].ToString(); if (SearchString.ToLower().Contains(Input.Text.ToLower())) { dgRow.Visibility = Visibility.Visible; } else { dgRow.Visibility = Visibility.Collapsed; } } } private void ToolBarSearch_KeyUp(object sender, KeyEventArgs e) { DataGrid dataGrid = FindName("CustomerTable") as DataGrid; TextBox Input = sender as TextBox; for (int i = 0; i < dataGrid.Items.Count; i++) { DataGridRow dgRow = GetRow(dataGrid, i); DataRowView vRow = dgRow.Item as DataRowView; DataRow Row = vRow.Row; String SearchString = "" + Row["ID"] + Row["Vorname"] + Row["Nachname"] + Row["Strasse"] + Row["PLZ"] + Row["Stadt"] + Row["Email"]; if (SearchString.ToLower().Contains(Input.Text.ToLower())) { dgRow.Visibility = Visibility.Visible; } else { dgRow.Visibility = Visibility.Collapsed; } } } private void borrowExemplarButton_Click(object sender, RoutedEventArgs e) { /* * EmployeeBorrowTableCustomers * EmployeeBorrowTableBooks * EmployeeBorrowTableExemplars */ DataGrid custDg = FindName("EmployeeBorrowTableCustomers") as DataGrid; DataGrid bookDg = FindName("EmployeeBorrowTableBooks") as DataGrid; DataGrid explDg = FindName("EmployeeBorrowTableExemplars") as DataGrid; ulong custID = getSelectedRowID(custDg); ulong bookID = getSelectedRowID(bookDg); ulong explID = getSelectedRowID(explDg); if (custID == 0) { MessageBox.Show("Bitte einen Kunden auswählen"); return; } if (bookID == 0) { MessageBox.Show("Bitte einen Buch auswählen"); return; } if (explID == 0) { MessageBox.Show("Bitte einen Exemplar auswählen"); return; } Customer customer = lib.DAOHandler.CustomerDAO.GetCustomerById(custID); Exemplar exemplar = lib.ExemplarList.Single(ex => ex.ExemplarId == explID); //@todo Bedingungen für den Ausleih prüfen try catch try { lib.DAOHandler.CustomerDAO.BorrowExemplar(exemplar, customer); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } private void Admin_ChangeOpeningTimes_Click(object sender, RoutedEventArgs e) { Popup EditTimes = (FindName("popUpChangeOpeningTimes") as Popup); if (!EditTimes.IsOpen) { lib.GUIApi.SetOpeningTimesToEditPopup(lib.OpeningTime); EditTimes.IsOpen = true; } } private void popUpChangeOpeningTimes_Success_Click(object sender, RoutedEventArgs e) { Popup EditTimes = (FindName("popUpChangeOpeningTimes") as Popup); Dictionary<string, string> NewOpeningTimes = new Dictionary<string, string>(); NewOpeningTimes.Add("Montag", (FindName("TimesEditPopup_Mo") as TextBox).Text); NewOpeningTimes.Add("Dienstag", (FindName("TimesEditPopup_Tu") as TextBox).Text); NewOpeningTimes.Add("Mittwoch", (FindName("TimesEditPopup_We") as TextBox).Text); NewOpeningTimes.Add("Donnerstag", (FindName("TimesEditPopup_Th") as TextBox).Text); NewOpeningTimes.Add("Freitag", (FindName("TimesEditPopup_Fr") as TextBox).Text); NewOpeningTimes.Add("Sonnabend", (FindName("TimesEditPopup_Sa") as TextBox).Text); NewOpeningTimes.Add("Sonntag", (FindName("TimesEditPopup_Su") as TextBox).Text); lib.DAOHandler.LibraryDAO.ChangeOpeningTime(NewOpeningTimes); EditTimes.IsOpen = false; } private void popUpChangeOpeningTimes_Abort_Click(object sender, RoutedEventArgs e) { Popup EditTimes = (FindName("popUpChangeOpeningTimes") as Popup); EditTimes.IsOpen = false; } private void DeleteBookImage_MouseUp(object sender, MouseButtonEventArgs e) { ulong ID = getSelectedRowID(FindName("EmployeeBooksTable") as DataGrid); if (ID == 0) return; Book book = lib.DAOHandler.BookDAO.GetBookById(ID); try { lib.DAOHandler.BookDAO.DeleteBook(book); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } private void ExemplarsOfBookImage_MouseUp(object sender, MouseButtonEventArgs e) { Grid grid = FindName("EmployeeArea_BooksMainGrid") as Grid; if (grid.RowDefinitions[4].Height.Value == 0) { grid.RowDefinitions[4].Height = new GridLength(200); } else { grid.RowDefinitions[4].Height = new GridLength(0); } } private void EmployeeBooksTable_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (!BlockSelectionChange) { Book book = lib.DAOHandler.BookDAO.GetBookById(getSelectedRowID(sender as DataGrid)); DataGrid ExemplarTable = FindName("EmployeeExemparTable") as DataGrid; ExemplarTable.DataContext = lib.GUIApi.getExemplarDataTable(); foreach (Exemplar expl in book.Exemplare) { lib.GUIApi.addExemparToDataGrid(expl, "EmployeeExemparTable"); } } } private void AddExemplarImage_MouseUp(object sender, MouseButtonEventArgs e) { Button addButton = FindName("addExemplarButton") as Button; addButton.Content = "hinzufügen"; Grid grid = FindName("CustomerExemplarsWithSideMenue") as Grid; if (grid.ColumnDefinitions[0].MaxWidth == 0) { grid.ColumnDefinitions[0].MaxWidth = Double.MaxValue; grid.ColumnDefinitions[0].Width = new GridLength(150); } else { grid.ColumnDefinitions[0].MaxWidth = 0; grid.ColumnDefinitions[0].Width = new GridLength(0); } } private void EditExemplarImage_MouseUp(object sender, MouseButtonEventArgs e) { ulong ID = getSelectedRowID(FindName("EmployeeExemparTable") as DataGrid); if (ID == 0) { MessageBox.Show("Kein Exemplar Ausgewählt"); return; } Exemplar expl = lib.ExemplarList.Single(ex => ex.ExemplarId == ID); //set comboboxes to current values ComboBox nes = FindName("NewExemplarStatus") as ComboBox; int NesIndex = 0; for (int i = 0; i < nes.Items.Count; i++) { if ((nes.Items[i] as ComboBoxItem).Content.ToString() == expl.State.ToString()) { NesIndex = i; break; } } nes.SelectedIndex = NesIndex; ComboBox nea = FindName("NewExemplarAccess") as ComboBox; int NeaIndex = 0; for (int i = 0; i < nea.Items.Count; i++) { if ((nea.Items[i] as ComboBoxItem).Content.ToString() == expl.Accesser.ToString()) { NeaIndex = i; break; } } nea.SelectedIndex = NeaIndex; AddExemplarImage_MouseUp(new Object(), new Object() as MouseButtonEventArgs); Button addButton = FindName("addExemplarButton") as Button; addButton.Content = ID + " bearbeiten"; } private void DeleteExemplarImage_MouseUp(object sender, MouseButtonEventArgs e) { ulong ID = getSelectedRowID(FindName("EmployeeExemparTable") as DataGrid); if (ID == 0) return; try { lib.DAOHandler.ExemplarDAO.RemoveExemplar(ID); } catch (System.Exception ex) { MessageBox.Show("Exemplar konnte nicht gelöscht werden: " + ex.Message); } } private void extentLeonPeriod_Click(object sender, RoutedEventArgs e) { ulong exid = getSelectedRowID(FindName("CustomerBorrowedTable") as DataGrid); if (exid == 0) return; lib.DAOHandler.ExemplarDAO.ExtendLend(exid); } private void bringBookBack_Click(object sender, RoutedEventArgs e) { ulong customerID = getSelectedRowID(FindName("CustomerTable") as DataGrid); ulong exemplarID = getSelectedRowID(FindName("CustomerBorrowedTable") as DataGrid); Customer customer = lib.DAOHandler.CustomerDAO.GetCustomerById(customerID); Exemplar exemplar = customer.ExemplarList.First(x => x.ExemplarId == exemplarID); BookStates newState = exemplar.State; lib.DAOHandler.ExemplarDAO.BringBookBack(customer, exemplar, newState); } private void addExemplarButton_Click(object sender, RoutedEventArgs e) { ulong bookID = getSelectedRowID(FindName("EmployeeBooksTable") as DataGrid); if (bookID == 0) { MessageBox.Show("Bitte zuerst ein Buch auswählen!"); return; } Book book = lib.DAOHandler.BookDAO.GetBookById(bookID); //get value from NewExemplarStatus ComboBox nes = FindName("NewExemplarStatus") as ComboBox; String value = (nes.SelectedValue as ComboBoxItem).Content.ToString(); BookStates status = (BookStates)Enum.Parse(typeof(BookStates), value); //get value from NewExemplarAccess ComboBox nea = FindName("NewExemplarAccess") as ComboBox; String value2 = (nea.SelectedValue as ComboBoxItem).Content.ToString(); Access access = (Access)Enum.Parse(typeof(Access), value2); Button addButton = FindName("addExemplarButton") as Button; if (addButton.Content.ToString() == "hinzufügen") { Exemplar newExemplar = new Exemplar(book); newExemplar.Accesser = access; newExemplar.State = status; lib.DAOHandler.ExemplarDAO.AddExemplar(newExemplar, book); } else { ulong ID = getSelectedRowID(FindName("EmployeeExemparTable") as DataGrid); if (ID == 0) { MessageBox.Show("Kein Exemplar Ausgewählt"); return; } Exemplar exemplar = lib.ExemplarList.Single(expl => expl.ExemplarId == ID); exemplar.Accesser = access; exemplar.State = status; lib.DAOHandler.ExemplarDAO.UpdateExemplar(exemplar); } } private void abortAddExemplarButton_Click(object sender, RoutedEventArgs e) { //trigger the unfold toggle AddExemplarImage_MouseUp(new Object(), new Object() as MouseButtonEventArgs); } private void cToolBarSearch_KeyUp(object sender, KeyEventArgs e) { Boolean useTitle = (bool)(FindName("cCboxTitle") as CheckBox).IsChecked; Boolean useAuthor = (bool)(FindName("cCboxAuthor") as CheckBox).IsChecked; DataGrid dataGrid = FindName("cBookTable") as DataGrid; TextBox Input = sender as TextBox; for (int i = 0; i < dataGrid.Items.Count; i++) { DataGridRow dgRow = GetRow(dataGrid, i); DataRowView vRow = dgRow.Item as DataRowView; DataRow Row = vRow.Row; String SearchString = (useAuthor ? Row["Author"].ToString() : "") + (useTitle ? Row["Title"].ToString() : ""); if (SearchString.ToLower().Contains(Input.Text.ToLower())) { dgRow.Visibility = Visibility.Visible; } else { dgRow.Visibility = Visibility.Collapsed; } } } private void cBooksMainButton_MouseUp(object sender, MouseButtonEventArgs e) { ToggleCustomerTabs(true); } private void cAccountsMainButton_MouseUp(object sender, MouseButtonEventArgs e) { ToggleCustomerTabs(false); } private void ToggleCustomerTabs(bool swaper) { Grid aGrid = this.cAccountMainPanel; Grid mGrid = this.cCustomerPanel; if (swaper) { mGrid.Visibility = Visibility.Visible; aGrid.Visibility = Visibility.Collapsed; return; } mGrid.Visibility = Visibility.Collapsed; aGrid.Visibility = Visibility.Visible; } private void ExtentCard_MouseUp(object sender, MouseButtonEventArgs e) { //TODO impl ulong ID = getSelectedRowID(this.CustomerTable); try { lib.DAOHandler.CardDAO.ExtendValidity(ID); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } private void MainFeeChangeButton_Click(object sender, RoutedEventArgs e) { this.popUpChangeFee.IsOpen = true; ChangeFeeTextBox.Text = lib.Fee.ToString(); } private void MainBillingChangeButton_Click(object sender, RoutedEventArgs e) { this.popUpChangeBilling.IsOpen = true; ChangeBillingTextBox.Text = lib.Billing.ToString(); } private void ChangeFeeSuccess_Click(object sender, RoutedEventArgs e) { String Input = this.ChangeFeeTextBox.Text; int newFee = 0; if (Validation.isNumeric(Input)) { newFee = Convert.ToInt32(Input); lib.DAOHandler.LibraryDAO.ChangeFee(newFee); this.popUpChangeFee.IsOpen = false; } else { MessageBox.Show("Eingabe muss eine Zahl sein"); } } private void ChangeFeeAbort_Click(object sender, RoutedEventArgs e) { this.popUpChangeFee.IsOpen = false; this.ChangeFeeTextBox.Text = ""; } private void ChangeBillingSuccess_Click(object sender, RoutedEventArgs e) { String Input = this.ChangeBillingTextBox.Text; int newBilling = 0; if (Validation.isNumeric(Input)) { newBilling = Convert.ToInt32(Input); lib.DAOHandler.LibraryDAO.ChangeBilling(newBilling); this.popUpChangeBilling.IsOpen = false; } else { MessageBox.Show("Eingabe muss eine Zahl sein"); } } private void ChangeBillingAbort_Click(object sender, RoutedEventArgs e) { this.popUpChangeBilling.IsOpen = false; this.ChangeBillingTextBox.Text = ""; } private void cExtentLend_Click(object sender, RoutedEventArgs e) { ulong ID = getSelectedRowID(this.cCustomerBorrwedExemplars); if (ID == 0) return; lib.DAOHandler.ExemplarDAO.ExtendLend(ID); } private void PayIn_MouseUp(object sender, MouseButtonEventArgs e) { ulong ID = getSelectedRowID(this.CustomerTable); if (ID == 0) return; this.PayInValueTextBox.Text = ""; this.PayInPopUp.IsOpen = true; } private void PayInSuccess_Click(object sender, RoutedEventArgs e) { ulong ID = getSelectedRowID(this.CustomerTable); if (ID == 0) return; String value = this.PayInValueTextBox.Text; int iValue = 0; Customer customer = lib.DAOHandler.CustomerDAO.GetCustomerById(ID); if (Validation.isNumeric(value)) { iValue = Convert.ToInt32(value); lib.DAOHandler.ChargeAccountDAO.PayIn(customer, (decimal)iValue); lib.GUIApi.UpdateCustomer(customer); this.PayInValueTextBox.Text = ""; this.PayInPopUp.IsOpen = false; } else { MessageBox.Show("Bitte geben Sie eine Zahl ein"); } } private void PayInAbort_Click(object sender, RoutedEventArgs e) { this.PayInValueTextBox.Text = ""; this.PayInPopUp.IsOpen = false; } private void CustomerTable_LoadingRow(object sender, DataGridRowEventArgs e) { DataRowView drv = e.Row.Item as DataRowView; DataRow row = drv.Row; String ChargeValue = (String)row["Kontostand"]; int iChargeValue = 0; try { iChargeValue = Convert.ToInt32(ChargeValue); } catch (System.Exception excp) { Debug.WriteLine(excp); return; } if (iChargeValue > 0 && iChargeValue < 20) { e.Row.Background = getBrush("ff7777"); } else if (iChargeValue < 0) { e.Row.Background = getBrush("33ff33"); } else if (iChargeValue >= 20) { e.Row.Background = Brushes.Red; } else { e.Row.Background = getBrush("61FA67"); } } private Brush getBrush(String ColorHexString) { if (ColorHexString.Length % 3 != 0) return Brushes.White; int Gstart = ColorHexString.Length == 3 ? 1 : 2; int Bstart = ColorHexString.Length == 3 ? 2 : 4; Brush brush = new SolidColorBrush( Color.FromArgb( byte.MaxValue, byte.Parse(ColorHexString.Substring(0, Gstart),NumberStyles.AllowHexSpecifier), byte.Parse(ColorHexString.Substring(Gstart, Gstart),NumberStyles.AllowHexSpecifier), byte.Parse(ColorHexString.Substring(Bstart, Gstart),NumberStyles.AllowHexSpecifier) ) ); return brush; } private void Image_MouseUp(object sender, MouseButtonEventArgs e) { ulong ID = getSelectedRowID(this.cBookTable); Book book = lib.BookList.Single(b => b.BookId == ID); Customer customer = lib.LoggedUser; //todo vorbestellen try caTch try { DateTime earliest = lib.DAOHandler.BookDAO.PreOrderEarliestExemplar(customer, book); MessageBox.Show("Das Buch wurde zum " + earliest.ToShortDateString() + " vorbestellt"); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } private void cBookTable_LoadingRow(object sender, DataGridRowEventArgs e) { DataRowView drv = e.Row.Item as DataRowView; DataRow row = drv.Row; ulong ID = (ulong)row["ID"]; Book book = lib.BookList.Single(b => b.BookId == ID); if (book.Exemplare.All(expl => expl.Borrower != null)) { e.Row.Background = getBrush("ff788a"); } else { e.Row.Background = getBrush("61FA67"); } } private void ImageTurnOff_MouseUp(object sender, MouseButtonEventArgs e) { MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Sind Sie sicher, dass Sie das System ausschalten wollen?", "Ausschalten?", MessageBoxButton.YesNo); if (messageBoxResult == MessageBoxResult.Yes) { this.Close(); } } } } <file_sep>/* * Erstellt mit SharpDevelop. * Benutzer: m588 * Datum: 30.10.2013 * Zeit: 16:22 * * Sie können diese Vorlage unter Extras > Optionen > Codeerstellung > Standardheader ändern. */ using System; using System.Data.SQLite; using System.Data.SqlTypes; using BiBo.Persons; using System.Collections.Generic; using System.Windows; namespace BiBo.SQL { /// <summary> /// Description of CustomerSql. /// </summary> public class CustomerSQL { private SqlConnector SQLHandler; public CustomerSQL(SqlConnector sqlc) { this.SQLHandler = sqlc; } // Add a Customer public bool AddEntry(Customer customer) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = @"INSERT INTO Customer ( id, firstName, lastName, birthDate, email, mobileNumber, createdAt, lastUpdate, deletedAt, street, streetNumber, additionalRoad, zipCode, town, country, rights, password, chargeAccountId, BiboID, state ) VALUES ( NULL, '" + customer.FirstName + @"', '" + customer.LastName + @"', '" + customer.BirthDate.ToShortDateString() + @"', '" + customer.EMailAddress + @"', '" + customer.MobileNumber + @"', '" + customer.CreatedAt + @"', '" + customer.LastUpdate + @"', '" + customer.DeletedAt + @"', '" + customer.Street + @"', '" + customer.StreetNumber + @"', '" + customer.AdditionalRoad + @"', '" + customer.ZipCode + @"', '" + customer.Town + @"', '" + customer.Country + @"', '" + customer.Right.ToString() + @"', '" + customer.Password + @"', '" + customer.ChargeAccount.Id + @"', '" + customer.BiboID + @"', '" + customer.UserState + @"' );"; command.ExecuteNonQuery(); return true; } // Add Dummy Customer public bool AddEntryDummy(Customer customer) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = @"INSERT SQLHandler.Connection Customer ( id, BiboId, firstName, lastName, birthDate, mobileNumber, street, streetNumber, zipCode, town, country ) VALUES ( NULL, '" + customer.BiboID + @"', '" + customer.FirstName + @"', '" + customer.LastName + @"', '" + customer.BirthDate.ToShortDateString() + @"', '" + customer.MobileNumber + @"', '" + customer.Street + @"', '" + customer.StreetNumber + @"', '" + customer.ZipCode + @"', '" + customer.Town + @"', '" + customer.Country + @"' );"; command.ExecuteNonQuery(); return true; } // Add Customer return CustomerID public ulong AddEntryReturnId(Customer customer) { AddEntry(customer); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "SELECT last_insert_rowid()"; Int64 LastRowID64 = (Int64)command.ExecuteScalar(); return (ulong) LastRowID64; } // Update a Customer public bool UpdateEntry(Customer customer) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = @"UPDATE Customer SET email = '" + customer.EMailAddress + @"', mobileNumber = '" + customer.MobileNumber + @"', createdAt = '" + customer.CreatedAt + @"', lastUpdate = '" + customer.LastUpdate + @"', deletedAt = '" + customer.DeletedAt + @"', firstName = '" + customer.FirstName + @"', lastName = '" + customer.LastName + @"', street = '" + customer.Street + @"', streetNumber = '" + customer.StreetNumber + @"', additionalRoad = '" + customer.AdditionalRoad + @"', zipCode = '" + customer.ZipCode + @"', town = '" + customer.Town + @"', country = '" + customer.Country + @"', rights = '" + customer.Right.ToString() + @"', password = '" + customer.Password + @"', chargeAccountId = '" + customer.ChargeAccount.Id + @"', BiboID = '" + customer.BiboID + @"', state = '" + customer.UserState + @"' WHERE id = '" + customer.CustomerID + @"';"; command.ExecuteNonQuery(); return true; } // Delete a List of Customer public bool DeleteEntryByIdList(List<ulong> l) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); string listOfIds = ""; foreach(ulong x in l){ listOfIds = string.Join(",", x); } command.CommandText = "DELETE FROM Customer WHERE id IN ('" + listOfIds + "');"; command.ExecuteNonQuery(); return true; } // Get all Customer public List<Customer> GetAllEntrys() { List<Customer> customerList = new List<Customer>(); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); SQLiteDataReader reader; command.CommandText = "SELECT * FROM Customer"; try { reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { customerList.Add(InitEntryByReader(reader)); } } return customerList; } catch (SQLiteException sqle) { MessageBox.Show(sqle.Message); } return new List<Customer>(); } // Reder for Database protected Customer InitEntryByReader(SQLiteDataReader reader){ Customer tmp; int intId = reader.GetInt32(reader.GetOrdinal("id")); ulong id = System.Convert.ToUInt64(intId); intId = reader.GetInt32(reader.GetOrdinal("BiboID")); ulong biboId = System.Convert.ToUInt64(intId); string firstName = reader.GetString(reader.GetOrdinal("firstName")); string lastName = reader.GetString(reader.GetOrdinal("lastName")); DateTime birthDate = DateTime.Parse(reader.GetString(reader.GetOrdinal("birthDate"))); tmp = new Customer(id, firstName, lastName, birthDate); tmp.BiboID = biboId; tmp.EMailAddress = reader.GetString(reader.GetOrdinal("email")); tmp.MobileNumber = reader.GetString(reader.GetOrdinal("mobileNumber")); string street = reader.GetString(reader.GetOrdinal("street")); tmp.Street = street; tmp.StreetNumber = reader.GetString(reader.GetOrdinal("streetNumber")); tmp.AdditionalRoad = reader.GetString(reader.GetOrdinal("additionalRoad")); tmp.ZipCode = reader.GetString(reader.GetOrdinal("zipCode")); tmp.Town = reader.GetString(reader.GetOrdinal("town")); tmp.Country = reader.GetString(reader.GetOrdinal("country")); tmp.LastUpdate = DateTime.Parse(reader.GetString(reader.GetOrdinal("lastUpdate"))); tmp.CreatedAt = DateTime.Parse(reader.GetString(reader.GetOrdinal("createdAt"))); tmp.DeletedAt = DateTime.Parse(reader.GetString(reader.GetOrdinal("deletedAt"))); string userStateString = reader.GetString(reader.GetOrdinal("state")); UserStates userStates = (UserStates)Enum.Parse(typeof(UserStates), userStateString, true); tmp.UserState = userStates; string rightString = reader.GetString(reader.GetOrdinal("rights")); Rights right = (Rights)Enum.Parse(typeof(Rights), rightString, true); tmp.Right = right; tmp.Password = reader.GetString(reader.GetOrdinal("password")); return tmp; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BiBo { public class Charge { private DateTime changedAt; private decimal changeValue; private decimal currentValue; private ulong transactionId; private ulong chargeAccountId; private String type; //to have an association for what this transaktion was happend public Charge(decimal currentValue, decimal changeValue) { this.changedAt = DateTime.Today; this.currentValue = currentValue; this.changeValue = changeValue; } public String Type { get { return type; } set { this.type = value; } } public DateTime ChangeAt { get { return this.changedAt; } set { this.changedAt = value; } } public decimal ChangeValues { get { return this.changeValue; } set { this.changeValue = value; } } public decimal CurrentValue { get { return this.currentValue; } set { this.currentValue = value; } } public ulong TransactionId { get { return this.transactionId; } set { this.transactionId = value; } } public ulong ChargeAccountId { get { return this.chargeAccountId; } set { this.chargeAccountId = value; } } } }<file_sep>using System; using BiBo.Persons; namespace BiBo.Persons { public class Employee : Customer { //Member-Variablen Deklaration //Konstruktor für Mitarbeiter public Employee(ulong customerID, string firstName, string lastName, DateTime birthDate) : base(customerID, firstName, lastName, birthDate) { Right = Rights.EMPLOYEE; } //Erstelle Kunden public Customer createCustomer(ulong customerID, string firstName, string lastName, DateTime birthDate) { return new Customer(customerID, firstName, lastName, birthDate); } //Aendere Adresse des Kunden public void changeAddress(Customer customer, string street, string streetNumber, string additionalRoad, string zipCode, string town, string country) { customer.Street = street; customer.StreetNumber = streetNumber; customer.AdditionalRoad = additionalRoad; customer.ZipCode = zipCode; customer.Town = town; customer.Country = country; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using BiBo.Persons; using System.Drawing; using System.Diagnostics; using BiBo.Exception; namespace BiBo { partial class Form1 { //click in main tabs in customer private void customerImage_Click(object sender, EventArgs e) { lib.getGuiApi().switchTabTo(Tabs.CUSTOMER); } private void booksImage_Click(object sender, EventArgs e) { lib.getGuiApi().switchTabTo(Tabs.BOOK); } private void borrowImage_Click(object sender, EventArgs e) { lib.getGuiApi().switchTabTo(Tabs.BORROW); } //close application private void close_Click(object sender, EventArgs e) { Application.Exit(); } //delete //delete customer which are selected in datagrid view private void buttonDeleteSelectedRows_Click(object sender, EventArgs e) { switch (this.activTab) { case Tabs.CUSTOMER: lib.getCustomerDAO().DeleteCustomersByIdList(); break; case Tabs.BOOK: lib.getBookDAO().DeleteBooksByIdList(); break; } } //search private void textBoxSearch_KeyUp(object sender, KeyEventArgs e) { //@todo if main tab on user TextBox self = (TextBox)sender; switch (this.activTab) { case Tabs.CUSTOMER: searchUserTable(self.Text); break; case Tabs.BOOK: searchBookTable(self.Text); break; } } //click on user add private void buttonUserAdd_Click(object sender, EventArgs e) { //get values into local vars String UserFName = textBoxUserFirstname.Text; String UserName = textBoxUserLastname.Text; String Street = textBoxUserStreet.Text; String StreetNumber = textBoxUserHomeNumber.Text; String StreetExtention = textBoxUserAdressExtention.Text; DateTime Birthday = dateTimePickerAddUser.Value; String zipCode = textBoxUserPLZ.Text; String City = textBoxUserCity.Text; String Country = comboBoxUserCountries.SelectedValue + ""; //set all textboxes background to white whilteUserAddInputs(); Button su = (Button)sender; if (!Validation.validateCustomerAddPanel(su.Parent)) { return; } if (su.Text == "hinzufügen") { Customer dummy = new Customer( 0, UserFName, UserName, Birthday ); //init dummy dummy.Street = Street; dummy.StreetNumber = StreetNumber; dummy.AdditionalRoad = StreetExtention; dummy.ZipCode = zipCode; dummy.Town = City; dummy.Country = Country; lib.getCustomerDAO().AddCustomer(dummy); } else { Customer newCustomer = new Customer( this.selectedUser.CustomerID, UserFName, UserName, Birthday ); //init dummy newCustomer.Street = Street; newCustomer.StreetNumber = StreetNumber; newCustomer.AdditionalRoad = StreetExtention; newCustomer.ZipCode = zipCode; newCustomer.Town = City; newCustomer.Country = Country; MessageBox.Show(newCustomer.ToString()); CustomerAddEditToggle(); //@todo update customer by DAO } //make textboxes for add user empty clearUserAddFrom(); } private void CustomerAddEditToggle() { if(this.buttonUserAdd.Text == "bearbeiten"){ this.UserAddPanel.BackColor = SystemColors.Control; this.clearCancel.Text = "Leeren"; this.buttonUserAdd.Text = "hinzufügen"; }else{ this.UserAddPanel.BackColor = SystemColors.ControlLight; this.buttonUserAdd.Text = "bearbeiten"; this.clearCancel.Text = "abbrechen"; } } //add book to SQLLite Table private void addBooksActionButton_Click(object sender, EventArgs e) { //author String author = this.textBoxBookAddauthor.Text; String title = this.textBoxBookAddTitel.Text; String genre = this.textBoxBookAddsubjectArea.Text; //all textboxes to white textBoxBookAddauthor.BackColor = Color.White; textBoxBookAddTitel.BackColor = Color.White; textBoxBookAddsubjectArea.BackColor = Color.White; if (Validation.isEmpty(author)) { textBoxBookAddauthor.BackColor = Color.Red; return; } if (Validation.isEmpty(title)) { textBoxBookAddTitel.BackColor = Color.Red; return; } if (Validation.isEmpty(genre)) { textBoxBookAddsubjectArea.BackColor = Color.Red; return; } lib.getBookDAO().AddBook(new Book(0, author, title, genre)); clearBookAddForm(); } //event by clicking cell this selects all cells in rows private void userTableDataSet_CellClick(object sender, DataGridViewCellEventArgs e) { //make all cells selected, so that it looks like the row is selected for (int i = 0; i < userTableDataSet.Rows[e.RowIndex].Cells.Count; i++) //IndexOutOfBoundException wenn man in der Tabelle auf de koopf klickt zum sortieren --> Marcus { userTableDataSet.Rows[e.RowIndex].Cells[i].Selected = true; } //get current user id and pass to show details method ulong custId = (ulong)Convert.ToInt64(userTableDataSet.Rows[e.RowIndex].Cells[1].Value.ToString()); Customer currCustomer = lib.getCustomerDAO().GetCustomerById(custId); displayCustomerDetails(currCustomer); this.selectedUser = currCustomer; } //login private void login_Click(object sender, EventArgs e) { Control container = ((Control)sender).Parent; String sid = container.Controls.Find("UserLoginName", true)[0].Text; String pass = container.Controls.Find("UserLoginPass", true)[0].Text; lib.getCustomerDAO().GetAllCustomer(); ulong id; Customer potentialUser; if (Validation.isNumeric(sid)) { id = (ulong)Convert.ToInt64(sid); } else { MessageBox.Show("Die ID muss eine Zahl sein"); return; } try { potentialUser = lib.getCustomerDAO().GetCustomerById(id); } catch (CustomerNotFoundException err) { MessageBox.Show(err.Message); return; } //@todo check password //@todo remove (force some rights) if(potentialUser.CustomerID == 103){ potentialUser.Right = Rights.ADMINISTRATOR; } if (potentialUser != null) { if (potentialUser.UserState == UserStates.DELETED) { MessageBox.Show("Dieser Benuter wurde aus dem System entfernt. Bitte wenden Sie sich an die Rezeption"); return; } if (potentialUser.UserState == UserStates.BANNED) { MessageBox.Show("Dieser Benuter ist gesperrt. Bitte wenden Sie sich an die Rezeption"); return; } switch (potentialUser.Right) { case Rights.CUSTOMER: this.UserLogin(potentialUser); break; case Rights.EMPLOYEE: this.EmployeeLogin(potentialUser); break; case Rights.ADMINISTRATOR: this.AdminLogin(potentialUser); break; } } return; } private void CustomerSearchBook_KeyUp(object sender, EventArgs e) { String search = ((TextBox)sender).Text.ToUpper(); for (int i = 0; i < customerSearchBook.Rows.Count; i++) { customerSearchBook.Rows[i].Visible = (this.checkBoxCustomerSearchAutor.Checked && customerSearchBook.Rows[i].Cells[1].Value.ToString().ToUpper().Contains(search)) || (this.checkBoxCustomerSearchTitle.Checked && customerSearchBook.Rows[i].Cells[2].Value.ToString().ToUpper().Contains(search)); } } private void imageSearch_Click(object sender, EventArgs e) { this.customerSearchBookPanel.Visible = true; this.customerAccountPanel.Visible = false; } private void imageAccount_Click(object sender, EventArgs e) { this.customerSearchBookPanel.Visible = false; this.customerAccountPanel.Visible = true; } private void Logout_Click(object sender, EventArgs e) { this.SuperPanelCustomer.Visible = false; this.SuperPanelLogin.Visible = true; } private void EmployeeLogout_Click(object sender, EventArgs e) { this.SuperPanelEmployee.Visible = false; this.SuperPanelLogin.Visible = true; } private void EditUser_Click(object sender, EventArgs e){ if (this.selectedUser != null) { this.textBoxUserFirstname.Text = this.selectedUser.FirstName; this.textBoxUserLastname.Text = this.selectedUser.LastName; this.dateTimePickerAddUser.Value = this.selectedUser.BirthDate; this.textBoxUserStreet.Text = this.selectedUser.Street; this.textBoxUserHomeNumber.Text = this.selectedUser.StreetNumber; this.textBoxUserAdressExtention.Text = this.selectedUser.AdditionalRoad; this.textBoxUserPLZ.Text = this.selectedUser.ZipCode; this.textBoxUserCity.Text = this.selectedUser.Town; //@todo this.comboBoxUserCountries CustomerAddEditToggle(); } } private void clearCancel_Click(object sender, EventArgs e) { Button self = (Button)sender; if (self.Text != "Leeren"){ CustomerAddEditToggle(); } clearUserAddFrom(); } private void borrowCustomerIDTextBox_KeyUp(object sender, KeyEventArgs ke) { String value = ((TextBox)sender).Text; this.borrowCustomerInfoLabel.Text = ""; this.imageCustomerCardValidation.BackgroundImage = null; if (value.Trim() == "") { this.imageCustomerFound.BackgroundImage = null; return; } if (Validation.isNumeric(value)) { try { Customer x = lib.getCustomerDAO().GetCustomerById((ulong)Convert.ToInt64(value)); //test: x.UserState = UserStates.BANNED; this.borrowCustomerInfoLabel.Text = x.FirstName + " " + x.LastName + " " + x.Street + " " + x.StreetNumber + " " + x.ZipCode + " " + x.Town; this.imageCustomerFound.BackgroundImage = global::BiBo.Properties.Resources.user_found; if (x.UserState == UserStates.ACTIVE) { this.imageCustomerCardValidation.BackgroundImage = global::BiBo.Properties.Resources.card_valid; return; } this.imageCustomerCardValidation.BackgroundImage = global::BiBo.Properties.Resources.card_invalid; return; } catch (CustomerNotFoundException cnfe) { this.borrowCustomerInfoLabel.Text = cnfe.Message; } } this.imageCustomerFound.BackgroundImage = global::BiBo.Properties.Resources.user_not_found; } } } <file_sep>using System; using BiBo.Persons; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Test.Persons { [TestClass()] public class EmployeeTest { [TestMethod()] // Erstellen eines Mitarbeiters public void createCustomerTest() { ulong cusID = 1; string firstName = "VornameEm"; string lastName = "NachnameEm"; DateTime birthDate = DateTime.Parse("01.04.1990"); Employee em = new Employee(cusID, firstName, lastName, birthDate); cusID = 2; firstName = "VornameCus"; lastName = "NachnameCus"; birthDate = DateTime.Parse("01.04.1998"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); Assert.AreEqual(em.createCustomer(cusID, firstName, lastName, birthDate), cus); } [TestMethod()] public void changeAddressTest() { ulong cusID = 1; string firstName = "VornameEm"; string lastName = "NachnameEm"; DateTime birthDate = DateTime.Parse("01.04.1990"); Employee em = new Employee(cusID, firstName, lastName, birthDate); cusID = 2; firstName = "VornameCus"; lastName = "NachnameCus"; birthDate = DateTime.Parse("01.04.1998"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); string street = "WALKENDCOTTAGE"; string streetNumber = "12a"; string country = "Kanada"; string additionalRoad = ""; string zipCode = "AB51 7LD"; string town = "Inverurie"; em.changeAddress(cus, street, streetNumber, additionalRoad, zipCode, town, country); Assert.IsTrue(cus.Street == street); Assert.IsTrue(cus.StreetNumber == streetNumber); Assert.IsTrue(cus.AdditionalRoad == additionalRoad); Assert.IsTrue(cus.ZipCode == zipCode); Assert.IsTrue(cus.Town == town); Assert.IsTrue(cus.Country == country); } } }<file_sep>using BiBo; using BiBo.Persons; using BiBo.SQL; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; namespace Test.Persons { [TestClass()] public class AdminTest { [TestMethod()] //Erstelle neuen Mitarbeiter public void createEmployeeTest() { ulong customerID = 7; string firstName = "Admin"; string lastName = "Boss"; DateTime birthDate = DateTime.Parse("01.07.1991"); Admin boss = new Admin(customerID, firstName, lastName, birthDate); customerID = 2; firstName = "Klaus"; lastName = "Pong"; birthDate = DateTime.Parse("01.07.1990"); Employee em = boss.createEmployee(customerID, firstName, lastName, birthDate); Assert.IsTrue(em.CustomerID == customerID); Assert.IsTrue(em.FirstName == firstName); Assert.IsTrue(em.LastName == lastName); Assert.IsTrue(em.BirthDate == birthDate); } [TestMethod()] //Erstelle neuen Administrator public void createAdminTest() { ulong customerID = 7; string firstName = "Admin"; string lastName = "Boss"; DateTime birthDate = DateTime.Parse("01.07.1991"); Admin boss = new Admin(customerID, firstName, lastName, birthDate); customerID = 8; firstName = "Mini"; lastName = "Boss"; birthDate = DateTime.Parse("01.07.1995"); Admin littleBOSS = boss.createAdmin(customerID, firstName, lastName, birthDate); // Beide sind nun vom selben Typ Assert.AreEqual(littleBOSS.GetType(), boss.GetType()); } [TestMethod()] //Oeffnungszeiten der Bibliothek aendern public void changeOpeningTimeTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong customerID = 1; string firstName = "BIG"; string lastName = "BOSS"; DateTime birthDate = DateTime.Parse("01.02.1990"); Admin boss = new Admin(customerID, firstName, lastName, birthDate); Dictionary<string, string> openingTime = new Dictionary<string, string>(){ {"Montag", "10:00 - 18:00 Uhr"}, {"Dienstag", "08:00 - 18:00 Uhr"}, {"Mittwoch", "08:00 - 18:00 Uhr"}, {"Donnerstag", "08:00 - 18:00 Uhr"}, {"Freitag", "08:00 - 18:00 Uhr"}, {"Sonnabend", "10:00 - 14:00 Uhr"}, {"Sonntag", "geschlossen"} }; boss.changeOpeningTime(lib, openingTime); Assert.IsTrue(lib.OpeningTime == openingTime); } [TestMethod()] //Gebuehren aendern public void changeFeeTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); double fee = 1.00; ulong customerID = 1; string firstName = "BIG"; string lastName = "BOSS"; DateTime birthDate = DateTime.Parse("01.02.1990"); Admin boss = new Admin(customerID, firstName, lastName, birthDate); boss.Right = Rights.ADMINISTRATOR; boss.changeFee(lib, fee); Assert.IsTrue(lib.Fee == fee); } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SQLite; using System.Xml.Linq; using System.Data; namespace BiBo.SQL { /// <summary> /// Description of BookSql. /// </summary> public class BookSQL { private SqlConnector SQLHandler; public BookSQL(SqlConnector sqlh) { this.SQLHandler = sqlh; } // Add a Book public bool AddEntry(Book book) { try { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = @"INSERT INTO Book ( id, author, titel, subjectArea ) VALUES ( NULL, '" + book.Author + @"', '" + book.Titel + @"', '" + book.SubjectArea + @"' );"; command.ExecuteNonQuery(); return true; } catch (System.Exception) { return false; } } // Add a Book and return the bookId public ulong AddEntryReturnId(Book book) { AddEntry(book); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "SELECT last_insert_rowid()"; Int64 lastRowID64 = Convert.ToInt64(command.ExecuteScalar()); return (ulong)lastRowID64; } public bool DeleteEntry(Book book) { if (book.Author != "") { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "DELETE FROM Book WHERE author='" + book.Author + "';"; return (command.ExecuteNonQuery() == 1); } return false; } public bool DeleteEntryByIdList(List<ulong> l) { foreach (ulong x in l) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "DELETE FROM Book WHERE id ='" + x + "';"; command.ExecuteNonQuery(); } return true; } public List<Book> GetAllEntrys() { List<Book> bookList = new List<Book>(); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "SELECT * FROM Book"; SQLiteDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { bookList.Add(InitEntryByReader(reader)); } } return bookList; } // Reder for Database protected Book InitEntryByReader(SQLiteDataReader reader) { ulong id = System.Convert.ToUInt64(reader.GetInt32(reader.GetOrdinal("id"))); string author = reader.GetString(reader.GetOrdinal("author")); string titel = reader.GetString(reader.GetOrdinal("titel")); string subjectArea = reader.GetString(reader.GetOrdinal("subjectArea")); return new Book(id, author, titel, subjectArea); } // Get all Exemplar of one Book public List<Exemplar> GetExemplarListOfBook(Book book) { List<Exemplar> exemplars = new List<Exemplar>(); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "SELECT * FROM Exemplar WHERE bookId = " + book.BookId; SQLiteDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { Exemplar ex = SQLHandler.ExemplarSQL.GetInitEntryByReader(reader); exemplars.Add(ex); } } return exemplars; } // Delete all Exemplars of a Book public void DeleteAllExemplars(Book book) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "DELETE FROM Exemplar WHERE id = '" + book.BookId + "';"; command.ExecuteNonQuery(); book.Exemplare.Clear(); } public List<Book> getAllBooksForNonLib() { List<Book> bookList = this.GetAllEntrys(); int i = 0; foreach (Book book in bookList) { book.Exemplare = SQLHandler.ExemplarSQL.GetAllEntrysByBook(book); i++; if (i == 30) return bookList; } return bookList; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SQLite; using System.Data.SqlTypes; using BiBo.Persons; namespace BiBo.SQL { public class ChargeAccountSQL { private SqlConnector SQLHandler; public ChargeAccountSQL(SqlConnector sqlc) { this.SQLHandler = sqlc; } // Add CargeAccount to Database public bool AddEntry(ChargeAccount obj) { try { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); if (command != null) { command.CommandText = @"INSERT INTO ChargeAccount ( id, customerId ) VALUES ( NULL, '" + obj.Customer.CustomerID + @"' );"; command.ExecuteNonQuery(); } return true; } catch (System.Exception) { return false; } } // Add ChargeAccount return ChargeAccountId public ulong AddEntryReturnId(ChargeAccount obj) { AddEntry(obj); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "select last_insert_rowid()"; UInt64 lastRowID64 = Convert.ToUInt64(command.ExecuteScalar()); // UInt64 lastRowID64 = (UInt64)command.ExecuteScalar(); // Fehler System.InvalidCastException: Die angegebene Umwandlung ist ungültig. return (ulong)lastRowID64; } // Get all ChargeAccounts public List<ChargeAccount> GetAllEntrys() { List<ChargeAccount> chargeAccountList = new List<ChargeAccount>(); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "SELECT * FROM ChargeAccount"; SQLiteDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { chargeAccountList.Add(InitEntryByReader(reader)); } } return chargeAccountList; } // Reder for Database protected ChargeAccount InitEntryByReader(SQLiteDataReader reader) { ChargeAccount chargeAccount = new ChargeAccount(); int intId = reader.GetInt32(reader.GetOrdinal("ID")); ulong chargeAccountId = System.Convert.ToUInt64(intId); intId = reader.GetInt32(reader.GetOrdinal("customerID")); ulong customerId = System.Convert.ToUInt64(intId); chargeAccount.CustomerID = customerId; chargeAccount.Id = chargeAccountId; return chargeAccount; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; //using System.Threading.Tasks; namespace BiBo.Persons { public class Customer { //Member-Variablen Deklaration private ulong customerID; //Kunden-ID private string firstName; //Vorname private string lastName; //Nachname private DateTime birthDate; //Geburtstag private string street; //Strasse private string streetNumber; //Strassennummer private string additionalRoad; //zusätzlich private string zipCode; //PLZ private string town; //Stadt private string country; //Land private Rights right = Rights.CUSTOMER; //Rechte private ChargeAccount chargeAccount; //Gebuehrenkonto private ulong biboID; //Bibliotheks-ID private Card card; //Ausweis private UserStates userState; //Benutzer- private string mobileNumber; //Handy- private string eMailAddress; //Email-Adresse private string password; //<PASSWORD> des <PASSWORD> private DateTime createdAt; //Kunde erstellt am private DateTime lastUpdate; //Kunde geändert am private DateTime deletedAt; //Kunde ausgetreten am private List<Exemplar> exemplarList; //Liste aller vom Customer ausgeliehen Buechern private List<Exemplar> preOrderList; //Liste aller vorbestellter Bücher //Konstruktor public Customer(ulong customerID, string firstName, string lastName, DateTime birthDate) { this.customerID = customerID; this.firstName = firstName; this.lastName = lastName; this.birthDate = birthDate; this.password = ""; this.exemplarList = new List<Exemplar>(); this.preOrderList = new List<Exemplar>(); } public Customer() { this.password = ""; this.ExemplarList = new List<Exemplar>(); this.preOrderList = new List<Exemplar>(); } //Property Deklaration public ulong CustomerID { get { return this.customerID; } set { this.customerID = value; } } public string FirstName { get { return this.firstName; } set { this.firstName = value; } } public string LastName { get { return this.lastName; } set { this.lastName = value; } } public DateTime BirthDate { get { return this.birthDate; } set { this.birthDate = value; } } public string Street { get { return this.street; } set { this.street = value; } } public string StreetNumber { get { return this.streetNumber; } set { this.streetNumber = value; } } public string AdditionalRoad { get { return this.additionalRoad; } set { this.additionalRoad = value; } } public string ZipCode { get { return this.zipCode; } set { this.zipCode = value; } } public string Town { get { return this.town; } set { this.town = value; } } public string Country { get { return this.country; } set { this.country = value; } } public Rights Right { get { return this.right; } set { this.right = value; } } public ChargeAccount ChargeAccount { get { return this.chargeAccount; } set { this.chargeAccount = value; } } public ulong BiboID { get { return this.biboID; } set { this.biboID = value; } } public UserStates UserState { get { return this.userState; } set { this.userState = value; } } public string MobileNumber { get { return this.mobileNumber; } set { this.mobileNumber = value; } } public string EMailAddress { get { return this.eMailAddress; } set { this.eMailAddress = value; } } public List<Exemplar> ExemplarList { get { return this.exemplarList; } set { this.exemplarList = value; } } public List<Exemplar> PreOrderedList { get { return this.preOrderList; } set { this.preOrderList = value; } } public string Password { get { return this.password; } set { this.password = value; } } public Card Card { get { return this.card; } set { this.card = value; } } public DateTime CreatedAt { get { return this.createdAt; } set { this.createdAt = value; } } public DateTime LastUpdate { get { return this.lastUpdate; } set { this.lastUpdate = value; } } public DateTime DeletedAt { get { return this.deletedAt; } set { this.deletedAt = value; } } //Methoden public String getFullAdress() { return this.Street + " " + this.StreetNumber + "\n" + (this.AdditionalRoad == "" ? "" : (this.AdditionalRoad + "\n")) + this.ZipCode + " " + this.Town + "\n" + this.Country; } public int GetAge() { int years = DateTime.Now.Year - this.BirthDate.Year; DateTime birthday = this.BirthDate; birthday = birthday.AddYears(years); if (DateTime.Now.CompareTo(birthday) < 0) { years--; } return years; } public override string ToString() { return CustomerID + " " + FirstName + " " + LastName + " " + BirthDate + " " + Street + " " + StreetNumber + " " + Town; } public override bool Equals(object obj) { return obj.GetHashCode() == this.GetHashCode(); } public override int GetHashCode() { string hashString = this.firstName + this.lastName + this.birthDate + this.street + this.streetNumber + this.town; return hashString.GetHashCode(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using BiBo.Persons; namespace BiBo { public class PreOrder { private ulong customerID; private ulong exemplarID; public ulong CustomerID { get { return this.customerID; } set { this.customerID = value; } } public ulong ExemplarID { get { return this.exemplarID; } set { this.exemplarID = value; } } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SQLite; using System.Xml.Linq; using BiBo.Persons; using BiBo.SQL; namespace BiBo.SQL { public class CardSQL { private SqlConnector SQLHandler; public CardSQL(SqlConnector sqlc) { this.SQLHandler = sqlc; } // Add Card to Database public bool AddEntry(Card card) { try { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = @"INSERT INTO Card ( ID, CustomerId, cardValidUntil ) VALUES ( NULL, '" + card.Customer.CustomerID + @"', '" + card.CardValidUntil + @"' );"; command.ExecuteNonQuery(); return true; } catch (System.Exception) { return false; } } // Add Card and return ID public ulong AddEntryReturnId(Card card) { AddEntry(card); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "SELECT last_insert_rowid()"; Int64 lastRowID64 = Convert.ToInt64(command.ExecuteScalar()); return (ulong)lastRowID64; } // Not needed public bool DeleteEntryByIdList(List<ulong> l) { throw new NotImplementedException(); } // Not needed public bool UpdateEntry(Card obj) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = @"UPDATE Card SET ID = '" + obj.CardID + "', CustomerId = '" + obj.CustomerID + "', cardValidUntil = '" + obj.CardValidUntil + "' WHERE ID ='" + obj.CardID + "';"; command.ExecuteNonQuery(); return true; } // Get all Cards from Database public List<Card> GetAllEntrys() { List<Card> cardList = new List<Card>(); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "SELECT * FROM Card"; SQLiteDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { cardList.Add(InitEntryByReader(reader)); } } return cardList; } // Reder for Database protected Card InitEntryByReader(System.Data.SQLite.SQLiteDataReader reader) { ulong cardId= System.Convert.ToUInt64(reader.GetInt32(reader.GetOrdinal("id"))); ulong customerId = System.Convert.ToUInt64(reader.GetInt32(reader.GetOrdinal("CustomerId"))); DateTime valid = DateTime.Parse(reader.GetString(reader.GetOrdinal("cardValidUntil"))); Card card = new Card(); card.CardID = cardId; card.CardValidUntil = valid; card.CustomerID = customerId; return card; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BiBo.Exception { [Serializable()] public class BookNotFoundException : System.Exception { public BookNotFoundException(string message): base(message) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BiBo.Persons { public class Admin : Employee { //Konstruktor für Administrator public Admin(ulong customerID, string firstName, string lastName, DateTime birthDate) : base(customerID, firstName, lastName, birthDate) { Right = Rights.ADMINISTRATOR; } //Erstelle neuen Mitarbeiter public Employee createEmployee(ulong customerID, string firstName, string lastName, DateTime birthDate) { return new Employee(customerID, firstName, lastName, birthDate); } //Erstelle neuen Administrator public Admin createAdmin(ulong customerID, string firstName, string lastName, DateTime birthDate) { return new Admin(customerID, firstName, lastName, birthDate); } //Oeffnungszeiten der Bibliothek aendern public void changeOpeningTime(Library library, Dictionary<string, string> openingTime) { library.OpeningTime = openingTime; } //Gebuehren aendern public void changeFee(Library library, double fee) { library.Fee = fee; } } } <file_sep>using BiBo; using BiBo.Persons; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace Test.Persons { [TestClass()] public class CustomerTest { [TestMethod()] // Erstellen eines Customers public void CusTest() { ulong cusID = 555; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); Assert.IsTrue(cus.CustomerID == cusID); Assert.IsTrue(cus.FirstName == firstName); Assert.IsTrue(cus.LastName == lastName); Assert.IsTrue(cus.BirthDate == birthDate); string street = "Straße 342"; string streetNumber = "1a"; string additionalRoad = ""; string zipCode = "13589"; string town = "Berlin"; string country = "Deutschland"; cus.Street = street; cus.StreetNumber = streetNumber; cus.AdditionalRoad = additionalRoad; cus.ZipCode = zipCode; cus.Town = town; cus.Country = country; Assert.IsTrue(cus.Street == street); Assert.IsTrue(cus.StreetNumber == streetNumber); Assert.IsTrue(cus.AdditionalRoad == additionalRoad); Assert.IsTrue(cus.ZipCode == zipCode); Assert.IsTrue(cus.Town == town); Assert.IsTrue(cus.Country == country); ulong biboID = 2; string mobileNumber = "01707714316"; string eMailAddress = "<EMAIL>"; ChargeAccount chargeAccount = new ChargeAccount(cus); Card card = new Card(cus); UserStates userState = UserStates.ACTIVE; cus.BiboID = biboID; cus.MobileNumber = mobileNumber; cus.EMailAddress = eMailAddress; cus.ChargeAccount = chargeAccount; cus.Card = card; cus.UserState = userState; Assert.IsTrue(cus.BiboID == biboID); Assert.IsTrue(cus.ChargeAccount == chargeAccount); Assert.IsTrue(cus.Card == card); Assert.IsTrue(cus.UserState == userState); Assert.IsTrue(cus.MobileNumber == mobileNumber); Assert.IsTrue(cus.EMailAddress == eMailAddress); } [TestMethod()] public void EqualsTest() { ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); Assert.IsTrue(cus.Equals(cus)); } [TestMethod()] public void GetHashCodeTest() { ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); cus.Street = "An der Burg"; cus.StreetNumber = "123"; cus.Town = "Berlin"; string hashString = firstName + lastName + birthDate + cus.Street + cus.StreetNumber + cus.Town; Assert.AreEqual(cus.GetHashCode(), hashString.GetHashCode()); } [TestMethod()] public void getFullAdressTest() { ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); string street = "Straße 342"; string streetNumber = "1a"; string additionalRoad = ""; string zipCode = "13589"; string town = "Berlin"; string country = "Deutschland"; cus.Street = street; cus.StreetNumber = streetNumber; cus.AdditionalRoad = additionalRoad; cus.ZipCode = zipCode; cus.Town = town; cus.Country = country; string adress = street + " " + streetNumber + "\n" + (additionalRoad == "" ? "" : (additionalRoad + "\n")) + zipCode + " " + town + "\n" + country; Assert.AreEqual(cus.getFullAdress(), adress); } [TestMethod()] public void ToStringTest() { ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); string street = "Straße 342"; string streetNumber = "1a"; string town = "Berlin"; cus.Street = street; cus.StreetNumber = streetNumber; cus.Town = town; string sString = cusID + " " + firstName + " " + lastName + " " + birthDate + " " + street + " " + streetNumber + " " + town; Assert.AreEqual(sString, cus.ToString()); } } } <file_sep>BiBo ==== So liebe Leute, ich danke euch für diese Mitarbeit ! Hiermit mache ich den letzten Commit für dieses verdammte Projekt. <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BiBo { public enum Tabs { CUSTOMER, BOOK, BORROW } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Deployment.Application; using System.Xml; namespace BiBo.Updater { class BiboUpdater { string url = ""; XmlTextReader reader; Version newVersion = null; public void checkForNewVersion() { try { string xmlURL = "http://bibo.vicodambeck.de/app_version.xml"; reader = new XmlTextReader(xmlURL); reader.MoveToContent(); string elementName = ""; if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "versionInfo")) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) elementName = reader.Name; else { if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue)) { switch (elementName) { case "version": newVersion = new Version(reader.Value); break; case "url": url = reader.Value; break; } } } } } } finally { if (reader != null) reader.Close(); } Version curVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; if (curVersion < newVersion) { System.Diagnostics.Process.Start(url); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using BiBo.SQL; using BiBo.Persons; using BiBo.Exception; using System.Windows; namespace BiBo.DAO { /// <summary> /// BookDAO handle the access to the Type Book. /// To save and restore objects in the DB and in the object-layer, you have to use this class. /// It also refresh the GUI-View /// </summary> public class BookDAO { private Library lib; public BookDAO(Library lib) { this.lib = lib; } public BookDAO() { } //Add a book with a given number of examples public void AddBook(Book book, int countOfExamples) { //insert in db and dummy get the right id book.BookId = lib.SQLHandler.BookSQL.AddEntryReturnId(book); for (int i = 0; i < countOfExamples; i++) { Exemplar ex = new Exemplar(book); ulong id = lib.SQLHandler.ExemplarSQL.AddEntryReturnId(ex); ex.ExemplarId = id; book.Exemplare.Add(ex); } //in objects lib.BookList.Add(book); //refresh GUI-View lib.GUIApi.AddBook(book); lib.GUIApi.Add_b_Book(book); //borrow panel lib.GUIApi.Add_c_Book(book); //customer area } //Löscht gegebenes Buch aus Objekt sowie Datenbank - schicht public void DeleteBook(Book book) { if(book.Exemplare.Count(e => e.Borrower != null) > 0) throw new System.Exception("Es sind noch Exemplare ausgeliehen"); //TODO: eigene Exception List<ulong> idList = new List<ulong>(); foreach (Exemplar exemplar in book.Exemplare) { idList.Add(exemplar.ExemplarId); } //delete in Object <----- must be go better !!! SCHAU DA NOCHMAL NACH MARCUS !!!!! lib.BookList.Remove(book); //delete in DB lib.SQLHandler.BookSQL.DeleteEntry(book); lib.SQLHandler.ExemplarSQL.DeleteEntryByIdList(idList); //in gui lib.GUIApi.DeleteBook(book); } //Gibt Buch zu der entsprechenden ID public Book GetBookById(ulong id) { Book book = lib.BookList.Find(bo => bo.BookId == id); if(book != null) return book; throw new BookNotFoundException("Buch mit gegebener ID nicht vorhanden"); } //gibt das Datum, wann ein Exemplar eines Buches frühestens wieder ausgeliehen werden kann public DateTime GetEarliestLoanDate(Book book) { DateTime earliest = new DateTime(); earliest = book.Exemplare.First().LoanPeriod; if (book.Exemplare.All(ex => ex.Borrower != null)) { foreach (Exemplar exemplar in book.Exemplare) { DateTime tmp = exemplar.LoanPeriod; tmp.AddMonths(exemplar.PreOrderedList.Count); if (tmp.CompareTo(earliest) < 0) earliest = tmp; } return earliest; } return DateTime.Today; } //Bestellt das früheste Exemplar eines Exemplars vor und gibt dieses Datum wieder public DateTime PreOrderEarliestExemplar(Customer customer, Book book) { DateTime earliestLoanPeriod = book.Exemplare.First().LoanPeriod; Exemplar earliestExemplar = book.Exemplare.First(); if (book.Exemplare.All(ex => ex.Borrower != null)) { foreach (Exemplar exemplar in book.Exemplare) { DateTime tmp = exemplar.LoanPeriod; tmp.AddMonths(exemplar.PreOrderedList.Count); if (tmp.CompareTo(earliestLoanPeriod) < 0) earliestExemplar = exemplar; } lib.DAOHandler.ExemplarDAO.AddPreOrder(customer, earliestExemplar); return earliestLoanPeriod; } throw new System.Exception("Von diesem Buch sind noch Exemplare zum Ausleihen verfügbar"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BiBo { public enum UserStates { ACTIVE, BANNED, DELETED } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BiBo { public enum Access { MAGAZIN, FREEHAND_LENDING } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using BiBo.DAO; namespace BiBo { public class DAOHandler { private BookDAO bookDAO; private CardDAO cardDAO; private ChargeAccountDAO chargeAccountDAO; private CustomerDAO customerDAO; private ExemplarDAO exemplarDAO; private LibraryDAO libraryDAO; public DAOHandler() { } public BookDAO BookDAO { set { this.bookDAO = value; } get { return this.bookDAO; } } public CardDAO CardDAO { set { this.cardDAO = value; } get { return this.cardDAO; } } public ChargeAccountDAO ChargeAccountDAO { set { this.chargeAccountDAO = value; } get { return this.chargeAccountDAO; } } public CustomerDAO CustomerDAO { set { this.customerDAO = value; } get { return this.customerDAO; } } public ExemplarDAO ExemplarDAO { set { this.exemplarDAO = value; } get { return this.exemplarDAO; } } public LibraryDAO LibraryDAO { set { this.libraryDAO = value; } get { return this.libraryDAO; } } } } <file_sep>using BiBo; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Test { [TestClass()] public class ConverterTest { [TestMethod()] // Konvertieren des Status (Buch) public void ToBookStateTest() { string stateString = "only_visible"; Converter.ToBookState(stateString); BookStates booStates = BookStates.ONLY_VISIBLE; Assert.AreEqual(Converter.ToBookState(stateString), booStates); } } } <file_sep>/* * Created by SharpDevelop. * User: m588 * Date: 12.12.2013 * Time: 14:59 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using BiBo.SQL; using BiBo.Persons; namespace BiBo { /// <summary> /// Description of Initializer. /// </summary> public class Initializer { Library lib; List<Customer> customerList; List<Exemplar> exemplarList; List<ChargeAccount> chargeAccountList; List<Charge> chargeList; List<Book> bookList; List<Card> cardList; List<PreOrder> preOrderList; public Initializer(Library lib) { this.lib = lib; customerList = lib.SQLHandler.CustomerSQL.GetAllEntrys(); exemplarList = lib.SQLHandler.ExemplarSQL.GetAllEntrys(); chargeAccountList = lib.SQLHandler.ChargeAccountSQL.GetAllEntrys(); chargeList = lib.SQLHandler.ChargeSQL.GetAllEntrys(); bookList = lib.SQLHandler.BookSQL.GetAllEntrys(); cardList = lib.SQLHandler.CardSQL.GetAllEntrys(); preOrderList = lib.SQLHandler.ExemplarSQL.GetAllPreOrderEntrys(); } public void InitializeAll() { initializeCustomer(); initializeChargeAccount(); initializeExemplar(); initializeCard(); initializeBook(); lib.CustomerList = customerList; //@todo remove [fake UserStates] lib.CustomerList[2].UserState = UserStates.BANNED; lib.CustomerList[3].UserState = UserStates.DELETED; // lib.ChargeAccountList = chargeAccountList; lib.ExemplarList = exemplarList; lib.BookList = bookList; } private void initializeCustomer() { foreach(Customer customer in customerList) { customer.Card = cardList.Find(c => c.CustomerID == customer.CustomerID); customer.ChargeAccount = chargeAccountList.Find(c => c.CustomerID == customer.CustomerID); customer.ExemplarList = exemplarList.FindAll(e => e.CustomerId == customer.CustomerID); //to fill the PreOrder List of Exemplars List<PreOrder> preOrderInCustomer = preOrderList.FindAll(pre => pre.CustomerID == customer.CustomerID); foreach (PreOrder preOrder in preOrderInCustomer) { customer.PreOrderedList.Add(exemplarList.Find(ex => ex.ExemplarId == preOrder.ExemplarID)); } } } private void initializeChargeAccount() { foreach(ChargeAccount chargeAccount in chargeAccountList) { chargeAccount.Customer = customerList.Find(c => c.CustomerID == chargeAccount.CustomerID); chargeAccount.Charges = chargeList.FindAll(c => c.ChargeAccountId == chargeAccount.Id); } } private void initializeExemplar() { //aus ExemplarSQL foreach(Exemplar exemplar in exemplarList) { exemplar.Borrower = customerList.Find(c => c.CustomerID == exemplar.CustomerId); //to fill the PreOrder List of Customers List<PreOrder> preOrderInCustomer = preOrderList.FindAll(pre => pre.ExemplarID == exemplar.ExemplarId); foreach (PreOrder preOrder in preOrderInCustomer) { exemplar.PreOrderedList.Add(customerList.Find(cus => cus.CustomerID == preOrder.CustomerID)); } } } private void initializeCard() { //Aus CardSQL foreach(Card card in cardList) { card.Customer = customerList.Find(c => c.CustomerID == card.CustomerID); } } private void initializeBook() { foreach(Book book in bookList) { book.Exemplare = exemplarList.FindAll(e => e.BookId == book.BookId); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BiBo { public enum Rights { ADMINISTRATOR, EMPLOYEE, CUSTOMER } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SQLite; using BiBo.Persons; using BiBo.SQL; using System.Data; namespace BiBo.SQL { public class ExemplarSQL { private SqlConnector SQLHandler; public ExemplarSQL(SqlConnector sqlc) { this.SQLHandler = sqlc; } //Member-Variablen Deklaration private DateTime loanPeriod; //Ausleifrist private BookStates state; //Status des Buches (only_visible, damaged, missing) private string signatur; //signatur des buches private Access accesser; //Zugang zum Exemplar (magazin, freihandausleihe) private Customer borrower; //Ausleiher private ulong exemplarId; //Exemplar-Nummer private ulong bookId; //dazugehörige Buch-ID //Add a Exemplar public bool AddEntry(Exemplar exemplar) { try { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); if (command != null) { command.CommandText = @"INSERT INTO Exemplar ( id, bookId, loanPeriod, state, signatur, access, countBorrow ) VALUES ( NULL, '" + exemplar.BookId.ToString() + @"', '" + exemplar.LoanPeriod.ToShortDateString() + @"', '" + exemplar.State.ToString() + @"', '" + exemplar.Signatur + @"', '" + exemplar.Accesser.ToString() + @"', '" + exemplar.CountBorrow.ToString() + @"' );"; command.ExecuteNonQuery(); } return true; } catch (System.Exception) { return false; } } //Add Exemplar and return this ID public ulong AddEntryReturnId(Exemplar exemplar) { AddEntry(exemplar); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "select last_insert_rowid()"; UInt64 lastRowID64 = Convert.ToUInt64(command.ExecuteScalar()); // UInt64 lastRowID64 = (UInt64)command.ExecuteScalar(); // Fehler System.InvalidCastException: Die angegebene Umwandlung ist ungültig. return (ulong)lastRowID64; } // Update Exemplar public bool UpdateEntry(Exemplar obj) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = ("UPDATE Exemplar SET countBorrow = '" + obj.CountBorrow.ToString() + "', bookId = '" + obj.BookId.ToString() + "', loanPeriod = '" + obj.LoanPeriod.ToShortDateString() + "', state = '" + obj.State.ToString() + "', signatur = '" + obj.Signatur + "', access = '" + obj.Accesser.ToString() + "', customerId = " + (obj.Borrower == null ? "null" : "'" + obj.Borrower.CustomerID + "'") + " WHERE ID = '" + obj.ExemplarId + "'"); command.ExecuteNonQuery(); return true; } //Delete ExemplarList public bool DeleteEntryByIdList(List<ulong> l) { foreach (ulong x in l) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "DELETE FROM Exemplar WHERE id = '" + x + "';"; command.ExecuteNonQuery(); } return true; } //Get all Exemplar public List<Exemplar> GetAllEntrys() { List<Exemplar> exemplarList = new List<Exemplar>(); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "SELECT * FROM Exemplar"; SQLiteDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { exemplarList.Add(InitEntryByReader(reader)); } } return exemplarList; } //Get all Exemplars by Book public List<Exemplar> GetAllEntrysByBook(Book book) { List<Exemplar> exemplarList = new List<Exemplar>(); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "SELECT * FROM Exemplar WHERE bookId = '" + book.BookId + "'"; SQLiteDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { exemplarList.Add(InitEntryByReader(reader)); } } return exemplarList; } //Get all Exemplar by Customer public List<Exemplar> GetAllEntrysByCustomer(Customer customer) { List<Exemplar> exemplarList = new List<Exemplar>(); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "SELECT * FROM Exemplar WHERE customerId = '" + customer.CustomerID + "'"; SQLiteDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { exemplarList.Add(InitEntryByReader(reader)); } } return exemplarList; } // Reader for Database protected Exemplar InitEntryByReader(System.Data.SQLite.SQLiteDataReader reader) { Exemplar exemplar = new Exemplar(); ulong id = System.Convert.ToUInt64(reader.GetInt32(reader.GetOrdinal("id"))); string loanPeriodAsString = reader.GetString(reader.GetOrdinal("loanPeriod")); DateTime loanPeriod = new DateTime(); if(loanPeriodAsString != null && loanPeriodAsString != "") loanPeriod = DateTime.Parse(loanPeriodAsString); string stateString = reader.GetString(reader.GetOrdinal("state")); BookStates state = (BookStates) Enum.Parse(typeof(BookStates), stateString, true); string accessString = reader.GetString(reader.GetOrdinal("access")); Access access = (Access)Enum.Parse(typeof(Access), accessString, true); string signatur = reader.GetString(reader.GetOrdinal("signatur")); Int32 countBorrow = reader.GetInt32(reader.GetOrdinal("countBorrow")); ulong customerId = 0; try { customerId = System.Convert.ToUInt64(reader.GetInt32(reader.GetOrdinal("customerID"))); } catch(System.InvalidCastException ex){ System.Diagnostics.Debug.WriteLine(ex.Message); } ulong bookId = System.Convert.ToUInt64(reader.GetInt32(reader.GetOrdinal("bookID"))); //exemplar.Borrower = specificCustomer; exemplar.CustomerId = customerId; exemplar.ExemplarId = id; exemplar.LoanPeriod = loanPeriod; exemplar.State = state; exemplar.Accesser = access; exemplar.Signatur = signatur; exemplar.BookId = bookId; exemplar.CountBorrow = countBorrow; return exemplar; } //to make it possile to call the method outside public Exemplar GetInitEntryByReader(SQLiteDataReader reader) { return InitEntryByReader(reader); } // Add a PreOder for Exemplar by Customer public bool AddPreOrder(Customer customer, Exemplar exemplar) { try { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); if (command != null) { command.CommandText = @"INSERT INTO PreOrder ( CustomerID, ExemplarID ) VALUES ( '" + customer.CustomerID + @"', '" + exemplar.ExemplarId + @"' );"; command.ExecuteNonQuery(); } return true; } catch (System.Exception) { return false; } } // Delete a PreOrder by Customer public void DeletePreOrder(Customer customer, Exemplar exemplar) { SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "DELETE FROM PreOrder WHERE CustomerID = '" + customer.CustomerID + "'" + "AND ExemplarID = '" + exemplar.ExemplarId + "';"; command.ExecuteNonQuery(); } // Get all PreOrders public List<PreOrder> GetAllPreOrderEntrys() { List<PreOrder> preOrderList = new List<PreOrder>(); SQLiteCommand command = new SQLiteCommand(SQLHandler.Connection); command.CommandText = "SELECT * FROM PreOrder"; SQLiteDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { preOrderList.Add(InitPreOrderEntryByReader(reader)); } } return preOrderList; } // Reader for Database public PreOrder InitPreOrderEntryByReader(System.Data.SQLite.SQLiteDataReader reader) { PreOrder preOrder = new PreOrder(); preOrder.CustomerID = System.Convert.ToUInt64(reader.GetInt32(reader.GetOrdinal("customerID"))); preOrder.ExemplarID = System.Convert.ToUInt64(reader.GetInt32(reader.GetOrdinal("exemplarID"))); return preOrder; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Mail; using BiBo.Persons; namespace BiBo { public class Mailer { public static void SendMail(Customer customer, string text) { MailMessage email = new MailMessage(); MailAddress sender = new MailAddress("<EMAIL>"); email.From = sender; email.To.Add(customer.EMailAddress); email.Subject = "Mahnung!"; email.Body = text; // Nachrichtentext hinzufügen string serverName = "mail.gmx.net"; string port = "25"; SmtpClient mailClient = new SmtpClient(serverName, int.Parse(port)); // Postausgangsserver definieren string userName = "<EMAIL>"; string password = "<PASSWORD>"; System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(userName, password); mailClient.Credentials = credentials; mailClient.Send(email); // Email senden } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using BiBo; using BiBo.DAO; using BiBo.Persons; using BiBo.SQL; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Test.DAO { [TestClass()] public class ChargeAccountDAOTest { [TestMethod()] public void GetChargeAccountToCustomerTest() { int capacity = 2; decimal currentValue = 500; decimal changeValue = 50; Charge ch = new Charge(currentValue, changeValue); List<Charge> chlist = new List<Charge>(capacity); chlist.Add(ch); ulong cusID = 1; string firstName = "Vorname1"; string lastName = "Nachname1"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus1 = new Customer(cusID, firstName, lastName, birthDate); ChargeAccount chAcc1 = new ChargeAccount(cus1); chAcc1.Charges = chlist; cus1.ChargeAccount = chAcc1; Assert.AreEqual(cus1.ChargeAccount.Charges, chlist); } //Legt eine neue Charge an und holt sich vorher den alten wert public void AddCharge(Customer cus, decimal changeValue, String type) { SqlConnector sqlh = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); //create the Charge with the last value if (cus.ChargeAccount.Charges.Count == 0) { //create charge Charge charge = new Charge(changeValue, changeValue); charge.ChargeAccountId = cus.ChargeAccount.Id; charge.Type = type; //on db-layer charge.TransactionId = sqlh.ChargeSQL.AddEntryReturnId(charge); //on object layer cus.ChargeAccount.Charges.Add(charge); } else { //create the charge Charge lastCharge = cus.ChargeAccount.Charges.Last(); decimal value = lastCharge.CurrentValue + changeValue; Charge charge = new Charge(value, changeValue); charge.ChargeAccountId = cus.ChargeAccount.Id; charge.Type = type; //on db-layer lib.SQLHandler.ChargeSQL.AddEntryReturnId(charge); //on object-layer cus.ChargeAccount.Charges.Add(charge); } } [TestMethod()] //belastet das Konto des gegebenen Kunden um entsprechenden Betrag public void BurdenTest() { SqlConnector sqlh = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); lib.CustomerList.Add(cus); ChargeAccount chAcc = new ChargeAccount(cus); cus.ChargeAccount = chAcc; ChargeAccountDAO chAccDAO = new ChargeAccountDAO(lib); decimal value = 50; string type = "burd"; if (cus.GetAge() < 14) value = value / 2; AddCharge(cus, value, type); Assert.AreEqual(chAcc.Charges, cus.ChargeAccount.Charges); } [TestMethod()] //einzahlen in das Konto des Kunden um gewissen Betrag public void PayInTest() { SqlConnector sqlh = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); lib.CustomerList.Add(cus); ChargeAccount chAcc = new ChargeAccount(cus); cus.ChargeAccount = chAcc; ChargeAccountDAO chAccDAO = new ChargeAccountDAO(lib); decimal value = 50; chAccDAO.PayIn(cus, value); Assert.AreEqual(cus.ChargeAccount.Charges, chAcc.Charges); } } } <file_sep>using System; using System.Linq; using BiBo; using BiBo.DAO; using BiBo.Persons; using BiBo.SQL; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Test.DAO { [TestClass()] public class CardDAOTest { [TestMethod()] // Anlegen einer Karte zum Benutzer public void AddCardTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); //add the customer card Card card = new Card(cus); DateTime valid = new DateTime(); valid = DateTime.Now.AddYears(1); card.CardValidUntil = valid; //add Card to Customer card.CardID = lib.SQLHandler.CardSQL.AddEntryReturnId(card); //add user in Objects lib.DAOHandler.CustomerDAO.UpdateCustomer(cus); lib.CustomerList.Add(cus); CardDAO caDAO = new CardDAO(lib); caDAO.AddCard(cusID); Assert.Inconclusive("Erfolgreich"); } [TestMethod()] //verlängert die Gültigkeit des Ausweises eines Kunden public void ExtendValidityTest() { SqlConnector sql = new SqlConnector(true); GUIApi gui = new GUIApi(true); Library lib = new Library(gui); ulong cusID = 1; string firstName = "Vorname"; string lastName = "Nachname"; DateTime birthDate = DateTime.Parse("01.04.1999"); Customer cus = new Customer(cusID, firstName, lastName, birthDate); lib.CustomerList.Add(cus); CardDAO caDAO = new CardDAO(lib); caDAO.AddCard(cusID); cus = lib.CustomerList.Find(cust => cust.CustomerID == cusID); if (cus.ChargeAccount.Charges.Count > 0) { if (cus.ChargeAccount.Charges.Last().CurrentValue != 0) throw new System.Exception("Ausweis kann nicht verlängert werden, ChargeAccount nicht ausgeglichen"); } //on object-layer cus.Card.CardValidUntil = cus.Card.CardValidUntil.AddYears(1); //on db-layer lib.SQLHandler.CardSQL.UpdateEntry(cus.Card); //on gui lib.GUIApi.UpdateCustomer(cus); Assert.Inconclusive("Erfolgreich"); } } }<file_sep>using BiBo; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Test { [TestClass()] public class ValidationTest { [TestMethod()] public void NameTest() { //test, if only letters ok Assert.IsTrue(Validation.Name("Marcus")); //test, if numbers give false result Assert.IsFalse(Validation.Name("1234567890")); } [TestMethod()] public void StreetTest() { //test if validation of street strings is ok Assert.IsTrue(Validation.Street("Am Plan 3c")); Assert.IsTrue(Validation.Street("Hauptstr. 4 1/2")); Assert.IsTrue(Validation.Street("A-Weg 8")); //test if validation of street strings failed Assert.IsFalse(Validation.Street("Am Plan")); Assert.IsFalse(Validation.Street("Hauptstr.5")); Assert.IsFalse(Validation.Street("Heideweg Drei")); } [TestMethod()] public void TelNumberTest() { //test if validation of telephonnumbers is ok Assert.IsTrue(Validation.TelNumber("+1-234-567-8901")); Assert.IsTrue(Validation.TelNumber("+46-234 5678901")); //test if validation of telephonnumbers failed Assert.IsFalse(Validation.TelNumber("0172coolman")); } [TestMethod()] public void isAlphabeticTest() { //test if validation of alphabetic strings is ok Assert.IsTrue(Validation.isAlphabetic("abcdefghijklmnopqrstuvwxyzäöü")); //test if validation of alphabetic strings failed Assert.IsFalse(Validation.isAlphabetic("abcdefghijklmnopqrstuvwxyzäöü123")); } [TestMethod()] public void isEmptyTest() { //test if validation of empty strings is ok Assert.IsTrue(Validation.isEmpty("")); //test if validation of empty strings failed Assert.IsFalse(Validation.isEmpty("a non empty string")); } [TestMethod()] public void isNumericTest() { //test if validation of numeric string is ok Assert.IsTrue(Validation.isNumeric("1234567890")); //test if validation of numeric string failed Assert.IsFalse(Validation.isNumeric("1234567890abc")); } [TestMethod()] public void zipCodeTest() { //test if validation of zipCode string is ok Assert.IsTrue(Validation.zipCode("03242")); Assert.IsTrue(Validation.zipCode("12394")); Assert.IsTrue(Validation.zipCode("K7P3K6")); Assert.IsTrue(Validation.zipCode("W7P3K6")); Assert.IsTrue(Validation.zipCode("123456789")); Assert.IsTrue(Validation.zipCode("12345-6789")); Assert.IsTrue(Validation.zipCode("12345-0000")); Assert.IsTrue(Validation.zipCode("00000-0000")); //test if validation of zipCode string failed Assert.IsFalse(Validation.zipCode("3520")); } [TestMethod()] public void OpeningTimeTest() { //test if validation of OpeningTime string is ok Assert.IsTrue(Validation.OpeningTime("09:30:00")); Assert.IsTrue(Validation.OpeningTime("17:45:20")); Assert.IsTrue(Validation.OpeningTime("23:59:59")); //test if validation of OpeningTime string failed Assert.IsFalse(Validation.OpeningTime("24:00:00")); } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SQLite; using System.IO; using BiBo; using System.Diagnostics; using System.Reflection; namespace BiBo.SQL { /// <summary> /// Description of SqlConnector. /// </summary> public class SqlConnector { private SQLiteConnection connection; private readonly string DATABASE_NAME = "Database.dat"; private LibrarySQL librarySQL; private BookSQL bookSQL; private CardSQL cardSQL; private ChargeAccountSQL chargeAccountSQL; private ChargeSQL chargeSQL; private CustomerSQL customerSQL; private ExemplarSQL exemplarSQL; private InitDbSQL iniDbSQL; public SqlConnector(Boolean createTestData) { if (File.Exists(DATABASE_NAME) && Assembly.GetEntryAssembly() == null) { this.Connect(); return; } if (createTestData) { if (File.Exists(DATABASE_NAME)) { File.Delete(DATABASE_NAME); } } this.Connect(); if (createTestData) { this.iniDbSQL = new InitDbSQL(this); iniDbSQL.createAllTables(); iniDbSQL.createRandomBooks(); iniDbSQL.createDummyData(); iniDbSQL.createLibraryValues(); } } public void Connect() { this.Connection = new SQLiteConnection("Data Source=" + DATABASE_NAME); this.Connection.Open(); LibrarySQL = new LibrarySQL(this); BookSQL = new BookSQL(this); CardSQL = new CardSQL(this); ChargeAccountSQL = new ChargeAccountSQL(this); ChargeSQL = new ChargeSQL(this); CustomerSQL = new CustomerSQL(this); ExemplarSQL = new ExemplarSQL(this); } public SQLiteConnection Connection { get { return this.connection; } set { this.connection = value; } } public LibrarySQL LibrarySQL { get { return this.librarySQL; } set { this.librarySQL = value; } } public BookSQL BookSQL { get { return this.bookSQL; } set { this.bookSQL = value; } } public CardSQL CardSQL { get { return this.cardSQL; } set { this.cardSQL = value; } } public ChargeAccountSQL ChargeAccountSQL { get { return this.chargeAccountSQL; } set { this.chargeAccountSQL = value; } } public ChargeSQL ChargeSQL { get { return this.chargeSQL; } set { this.chargeSQL = value; } } public CustomerSQL CustomerSQL { get { return this.customerSQL; } set { this.customerSQL = value; } } public ExemplarSQL ExemplarSQL { get { return this.exemplarSQL; } set { this.exemplarSQL = value; } } ~SqlConnector() { try { connection.Close(); } catch (ObjectDisposedException ode) { Debug.WriteLine(ode.Message); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BiBo.Persons { public class ChargeAccount { private Customer customer; private ulong customerID; private List<Charge> charges; private ulong id; //Konstruktor public ChargeAccount() { this.charges = new List<Charge>(); } public ChargeAccount(Customer customer) { this.customer = customer; this.charges = new List<Charge>(); } public Customer Customer { get { return this.customer; } set { this.customer = value; } } public List<Charge> Charges { get { return this.charges; } set { this.charges = value; } } public ulong Id { get { return this.id; } set { this.id = value; } } public ulong CustomerID { get { return this.customerID; } set { this.customerID = value; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using BiBo.Persons; namespace BiBo { public class Card { private ulong customerID; //dazugehöriger Benutzer ID private Customer customer; //dazugehöriger Benutzer private ulong cardID; //Ausweis private DateTime cardValidUntil; //Gültigkeitdatum des Ausweises public Card() { } public Card(Customer customer) { this.customer = customer; this.customerID = customer.CustomerID; } public ulong CardID { get { return this.cardID; } set { this.cardID = value; } } public DateTime CardValidUntil { get { return this.cardValidUntil; } set { this.cardValidUntil = value; } } public ulong CustomerID { get { return this.customerID; } set { this.customerID = value; } } public Customer Customer { get { return this.customer; } set { this.customer = value; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using BiBo.Persons; using System.Windows.Forms; using System.Drawing; using System.IO; using System.Windows.Forms.DataVisualization.Charting; using System.Diagnostics; namespace BiBo { partial class Form1 { public void SetLoggedUserName(String name) { this.userName.Text = name;//hj } public void init() { //get current screen size int width = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width; int height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height; //load GUI elements, calculated by screen size (responsive) //@see: Form1.Designer InitializeComponent(width, height); } //fill GUI elements with content private bool publishContent(Customer logginUser) { //set name of current logged user userName.Text = logginUser.FirstName + " " + logginUser.LastName; switch(logginUser.Right){ case Rights.ADMINISTRATOR: userStat.Text = "Admin"; break; case Rights.EMPLOYEE: userStat.Text = "Mitarbeiter"; break; case Rights.CUSTOMER: userStat.Text = "Kunde"; break; } //fill content on customer tab //@see Form1.Customer this.publishCustomerContent(); //fill content on books tab //@see Form1.Books this.publishBookContent(); return true; } private void switchTabTo(Tabs tab) { switch (tab) { case Tabs.CUSTOMER: //show customer Main Panel hide others this.CustomerMainPanel.Visible = true; this.BooksMainPanel.Visible = false; this.BorrowMainPanel.Visible = false; this.activTab = Tabs.CUSTOMER; break; case Tabs.BOOK: //show books Main Panel hide others this.CustomerMainPanel.Visible = false; this.BorrowMainPanel.Visible = false; this.BooksMainPanel.Visible = true; this.activTab = Tabs.BOOK; break; case Tabs.BORROW: //show borrow panel hide otheres this.CustomerMainPanel.Visible = false; this.BooksMainPanel.Visible = false; this.BorrowMainPanel.Visible = true; break; } } public void AddBook(Book book) { this.booksTableDataSet.Rows.Add( false, book.BookId, book.Author, book.Titel, book.SubjectArea ); } //adds a Customer to user´datagridview public void AddCustomer(Customer cust) { //calcualte age by birtday TimeSpan age = DateTime.Now - cust.BirthDate; //whole adress to string String adress = cust.getFullAdress(); //add new row with customer informations //@todo add status and number of borrowed books userTableDataSet.Rows.Add( false, cust.CustomerID.ToString(), cust.FirstName, cust.LastName, ((int)Math.Floor((DateTime.Now - cust.BirthDate).TotalDays / 365.25D)).ToString(), "test", "0", adress ); //set read only again List<int> exceptions = new List<int>(); exceptions.Add(0); //checkbox colum setDataGridViewReadOnly(userTableDataSet, exceptions); } public List<ulong> DeleteCustomersByIdList() { //init a list for collecting id that should be deleted List<ulong> potentialDeletedIds = new List<ulong>(); //placeholder of id ulong id; //run through all rows for (int i = 0; i < userTableDataSet.Rows.Count; i++) { //get DataGridViewCheckBoxCell Object from checkbox colum DataGridViewCheckBoxCell chkchecking = userTableDataSet.Rows[i].Cells[0] as DataGridViewCheckBoxCell; //get value of checkbox if ((bool)chkchecking.Value == true) //if checkbox id checked { //get customer id from row and add to list of ids id = (ulong)Convert.ToInt64(userTableDataSet.Rows[i].Cells[1].Value.ToString()); potentialDeletedIds.Add(id); } } foreach (ulong x in potentialDeletedIds) { foreach (DataGridViewRow row in userTableDataSet.Rows) { if (x == (ulong)Convert.ToInt64(row.Cells[1].Value.ToString())) { userTableDataSet.Rows.RemoveAt(row.Index); break; } } } return potentialDeletedIds; } public List<ulong> DeleteBooksByIdList() { //init a list for collecting id that should be deleted List<ulong> potentialDeletedIds = new List<ulong>(); //placeholder of id ulong id; //run through all rows for (int i = 0; i < booksTableDataSet.Rows.Count; i++) { //get DataGridViewCheckBoxCell Object from checkbox colum DataGridViewCheckBoxCell chkchecking = booksTableDataSet.Rows[i].Cells[0] as DataGridViewCheckBoxCell; //get value of checkbox if ((bool)chkchecking.Value == true) //if checkbox id checked { //get customer id from row and add to list of ids id = (ulong)Convert.ToInt64(booksTableDataSet.Rows[i].Cells[1].Value.ToString()); potentialDeletedIds.Add(id); } } //remove book from table foreach (ulong x in potentialDeletedIds) { foreach (DataGridViewRow row in booksTableDataSet.Rows) { if (x == (ulong)Convert.ToInt64(row.Cells[1].Value.ToString())) { booksTableDataSet.Rows.RemoveAt(row.Index); break; } } } return potentialDeletedIds; } //fill age chart with values private void initAgeChart() { //colors Color[] colors = new Color[] { ColorTranslator.FromHtml("#4140A8"), ColorTranslator.FromHtml("#8483A8"), ColorTranslator.FromHtml("#C0BFF5"), ColorTranslator.FromHtml("#A8A8A8"), ColorTranslator.FromHtml("#605DF5"), ColorTranslator.FromHtml("#cccccc") //ColorTranslator.FromHtml("#575757") }; //init age tmp and counter vars int age = 0; int count_less18 = 0; int count_less25 = 0; int count_less35 = 0; int count_less50 = 0; int count_less60 = 0; int count_gt60 = 0; //run through all rows foreach (DataGridViewRow row in userTableDataSet.Rows) { //get age try { age = Convert.ToInt32(row.Cells[4].Value.ToString()); } catch (FormatException err) { } //increase the right counter if (age < 18) { count_less18++; } else if (age < 25) { count_less25++; } else if (age < 35) { count_less35++; } else if (age < 50) { count_less50++; } else if (age < 60) { count_less60++; } else { count_gt60++; } } //create dictionary for values names and values Dictionary<string, int> tags = new Dictionary<string, int>() { { "< 18", count_less18 }, { "< 25", count_less25 }, { "< 35", count_less35 }, { "< 50", count_less50 }, { "< 60", count_less60 }, { ">= 60", count_gt60 } }; //init age chart by dictionary foreach (string tagname in tags.Keys) { chartUserAge.Series[0].Points.AddXY(tagname, tags[tagname]); } foreach (Series series in chartUserAge.Series) { foreach (DataPoint point in series.Points) { point.Color = colors[series.Points.IndexOf(point)]; } } } private void initRegDateChart() { //Random reg dates List<fakeCustomer> customers = new List<fakeCustomer>(); for (int i = 0; i < 100; i++) { customers.Add(new fakeCustomer(new DateTime(r.Next(2012,2014), r.Next(1, 12), r.Next(1, 28)))); if (r.Next(2) == 1) { customers[i].DeletedAt = customers[i].CreatedAt.Add(TimeSpan.FromDays(r.Next(1,14))); } } customers.Sort( (cust1,cust2) => cust1.CreatedAt.CompareTo(cust2.CreatedAt) ); DateTime oldesRegDate = customers[0].CreatedAt; DateTime latesRegDate = customers[customers.Count - 1].CreatedAt; DateTime startDate = new DateTime(oldesRegDate.Year, oldesRegDate.Month, 1); DateTime endDate = new DateTime(latesRegDate.Year, latesRegDate.Month, 1); int count = 0; for (DateTime it = startDate; it < endDate;it = it.AddMonths(1)) { count += ( from cust in customers where cust.CreatedAt.Year == it.Year && cust.CreatedAt.Month == it.Month select cust ).Count() - ( from cust in customers where cust.DeletedAt != null && cust.DeletedAt.Year == it.Year && cust.DeletedAt.Month == it.Month select cust ).Count(); chartRegDate.Series[0].Points.AddXY(it.Day + "." + it.Month + "." + it.Year, count); } } //set background of all textboxes for user add to white //is is like a clear for validation errors private void whilteUserAddInputs() { textBoxUserFirstname.BackColor = Color.White; textBoxUserLastname.BackColor = Color.White; textBoxUserStreet.BackColor = Color.White; textBoxUserHomeNumber.BackColor = Color.White; textBoxUserCity.BackColor = Color.White; textBoxUserPLZ.BackColor = Color.White; } //set all textboxes for user add empty private void clearUserAddFrom() { textBoxUserFirstname.Text = ""; textBoxUserLastname.Text = ""; textBoxUserStreet.Text = ""; textBoxUserHomeNumber.Text = ""; textBoxUserAdressExtention.Text = ""; //set default as empty dateTimePickerAddUser.Value = userAddBirthDayDefault; textBoxUserPLZ.Text = ""; textBoxUserCity.Text = ""; } //get customer details and show in details panel private void displayCustomerDetails(Customer customer) { labelUserDetailsName.Text = "Name: " + customer.FirstName + " " + customer.LastName; labelUserDetailsAdress.Text = "Adresse: " + customer.getFullAdress(); } //fill GUI in customer tab with content private void publishCustomerContent() { //userAddBirthDay Default; dateTimePickerAddUser.Value = userAddBirthDayDefault; //set number of culoms userTableDataSet.ColumnCount = 7; //set colum names userTableDataSet.Columns[0].Name = "ID"; userTableDataSet.Columns[1].Name = "Vorname"; userTableDataSet.Columns[2].Name = "Nachname"; userTableDataSet.Columns[3].Name = "Alter"; userTableDataSet.Columns[4].Name = "Status"; userTableDataSet.Columns[5].Name = "ausgeliehende Bücher"; userTableDataSet.Columns[6].Name = "Adresse"; //insert a special colum for checkboxes userTableDataSet.Columns.Insert(0, new DataGridViewCheckBoxColumn()); //insert customers from SQLLite table foreach (Customer customer in lib.getCustomerDAO().GetAllCustomer()) { //add user to datagrid view lib.getGuiApi().AddCustomer(customer); } //set customer table to read only List<int> exceptions = new List<int>(); exceptions.Add(0); //checkbox colum setDataGridViewReadOnly(userTableDataSet, exceptions); //insert all countries to comboBox initCourtries(); //calculate and insert values to age chart initAgeChart(); initRegDateChart(); } //read country names source and insert to comboBox private void initCourtries() { List<String> countrieNames = new List<String>(); //create line string to catch lines from file string line; // Read the file and display it line by line. StreamReader file = new System.IO.StreamReader(this.countriesSource); while ((line = file.ReadLine()) != null) { //add to country dataTable countrieNames.Add(line); } file.Close(); comboBoxUserCountries.DataSource = countrieNames; } //search in data grid view and hide dismatched rows private void searchUserTable(String str) { Customer tmp; ulong id; string sid; //run througth rows for (int i = 0; i < userTableDataSet.Rows.Count; i++) { //get customer id as string sid = userTableDataSet.Rows[i].Cells[1].Value.ToString(); //convert id string to ulong id = (ulong)Convert.ToInt64(sid); //get customer form SQLLite table tmp = lib.getCustomerDAO().GetCustomerById(id); //check if search input is in toString value of customer if (!tmp.ToString().ToUpper().Contains(str.ToUpper())) { //hide row userTableDataSet.Rows[i].Visible = false; } else { //show row userTableDataSet.Rows[i].Visible = true; } } } //fill GUI with content private void publishBookContent() { //create data table for datagridview //set number of culoms this.booksTableDataSet.ColumnCount = 4; //set colum names this.booksTableDataSet.Columns[0].Name = "ID"; this.booksTableDataSet.Columns[1].Name = "Author"; this.booksTableDataSet.Columns[2].Name = "Title"; this.booksTableDataSet.Columns[3].Name = "Genre"; //insert a special colum for checkboxes this.booksTableDataSet.Columns.Insert(0, new DataGridViewCheckBoxColumn()); foreach (Book book in lib.getBookDAO().getAllBooks()) { lib.getGuiApi().AddBook(book); } //make table readonly List<int> exceptions = new List<int>(); exceptions.Add(0); //checkbox colum setDataGridViewReadOnly(this.booksTableDataSet, exceptions); } //clear book add form private void clearBookAddForm() { this.textBoxBookAddauthor.Text = ""; this.textBoxBookAddsubjectArea.Text = ""; this.textBoxBookAddTitel.Text = ""; } private void setDataGridViewReadOnly(DataGridView dgv) { setDataGridViewReadOnly(dgv, new List<int>()); } private void setDataGridViewReadOnly(DataGridView dgv, List<int> excludedColums) { //run through all rows for (int i = 0; i < dgv.Rows.Count; i++) { //run through all cells of row for (int j = 0; j < dgv.Rows[i].Cells.Count; j++) { if (excludedColums.IndexOf(j) == -1) // exclude exceptions { //set cell readonly dgv.Rows[i].Cells[j].ReadOnly = true; } } } } private void searchBookTable(String str) { Book tmp; ulong id; string sid; //run througth rows for (int i = 0; i < booksTableDataSet.Rows.Count; i++) { //get customer id as string sid = booksTableDataSet.Rows[i].Cells[1].Value.ToString(); //convert id string to ulong id = (ulong)Convert.ToInt64(sid); //get customer form SQLLite table tmp = lib.getBookDAO().GetBookById(id); //check if search input is in toString value of customer if (!tmp.ToString().ToUpper().Contains(str.ToUpper())) { //hide row booksTableDataSet.Rows[i].Visible = false; } else { //show row booksTableDataSet.Rows[i].Visible = true; } } } private void UserLogin(Customer logginUser){ this.SuperPanelLogin.Visible = false; this.SuperPanelCustomer.Visible = true; publishCustomerSearchLogin(logginUser); } private void EmployeeLogin(Customer logginUser) { this.SuperPanelLogin.Visible = false; this.SuperPanelEmployee.Visible = true; //init content //fill GUI elemens with content if (!lib.IsEmployeeGUILoaded) { lib.IsEmployeeGUILoaded = publishContent(logginUser); ; } } private void AdminLogin(Customer logginUser) { this.SuperPanelLogin.Visible = false; this.SuperPanelEmployee.Visible = true; //init content //fill GUI elemens with content if (!lib.IsEmployeeGUILoaded) { lib.IsEmployeeGUILoaded = publishContent(logginUser); ; } } private void publishCustomerSearchLogin(Customer logginUser) { this.loggedInAs_Name.Text = "Name: " + logginUser.FirstName + " " + logginUser.LastName; this.loggedInAs_Adress.Text = "Adresse: " + logginUser.getFullAdress(); this.customerSearchBook.ColumnCount = 4; //set colum names this.customerSearchBook.Columns[0].Name = "ID"; this.customerSearchBook.Columns[1].Name = "Author"; this.customerSearchBook.Columns[2].Name = "Title"; this.customerSearchBook.Columns[3].Name = "Genre"; foreach (Book book in lib.getBookDAO().getAllBooks()) { lib.getGuiApi().AddBookCustomerSearch(book); } //make table readonly setDataGridViewReadOnly(customerSearchBook); } public void AddBookCustomerSearch(Book book){ customerSearchBook.Rows.Add( book.BookId, book.Author, book.Titel, book.SubjectArea ); } } class fakeCustomer { private DateTime createdAt; private DateTime deletedAt; public fakeCustomer(DateTime cd){ this.CreatedAt = cd; } public DateTime CreatedAt{ get { return createdAt; } set { createdAt = value; } } public DateTime DeletedAt { get { return deletedAt; } set { deletedAt = value; } } } }
b9041c66b5d66269ae05cef6a1f3f8a1cc6bbd58
[ "Markdown", "C#" ]
58
C#
marsteff/BiBo
06a732a6ac28e12e6279f52a83f61056960328ea
25fadaa217a739b220ec226986eee665fe56e682
refs/heads/master
<file_sep>import React from "react"; import ReactDOM from "react-dom"; import nlp from 'compromise'; function checkSentiment(comment){ let doc = nlp(comment) // match an implicit term doc.has('going') // true // transform doc.contractions().expand() comment = doc.text() //remove contractions line wasn't->was not alert('contractions removed: ' + comment); var Sentiment = require('sentiment'); var sentiment = new Sentiment(); var result = sentiment.analyze(comment); alert('comparative = ' + result.comparative) if (result.comparative>0){ return 'Positive'; } else if (result.score===0){ return 'Neutral'; } else{ return 'Negative'; } } function filterProfanity(comment){ var Filter = require('bad-words'); var customFilter = new Filter({ placeHolder: '#'}); var newBadWords = ['gandu', 'bsdk', 'bullshit']; //add as many bad words to this list customFilter.addWords(...newBadWords); return customFilter.clean(comment); } class NameForm extends React.Component { constructor(props) { super(props); this.state = {value: ''}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({value: event.target.value}); } handleSubmit(event) { var filteredComment = filterProfanity(this.state.value); var mSentiment = checkSentiment(this.state.value); if (filteredComment!==this.state.value && mSentiment!=='Negative'){ mSentiment = 'Negative'; //comment was filtered so it should be negative } alert('Analysed sentiment for \'' + this.state.value + '\': ' + mSentiment); alert('Filtered output for \'' + this.state.value + '\': ' + filteredComment); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit} > <div > <label > Type review: <input type="text" value={this.state.value} size="100" onChange={this.handleChange} /> </label> <input type="submit" value="Check sentiment" /> </div> </form> ); } } ReactDOM.render( <NameForm />, document.getElementById('root') );
88c2afba8ac0210563ebf22817207313a90d339b
[ "JavaScript" ]
1
JavaScript
UmarNaeem7/ReviewAnalysis
acef3ff5ad0589efa0af0edbc33e8fc9cdc2bbb6
1d4dfe119b5b1381b5af283520a4e9e0f4046f04
refs/heads/master
<repo_name>yueranwu/practical<file_sep>/prac_08/texi_test.py """ CP1404 Practical This is a test program for testing Taxi class """ from taxi import Taxi def main(): """ print taxi information """ prius_taxi = Taxi("Prius 1", 100) prius_taxi.drive(40) # Drive the taxi 40m print(prius_taxi) # print the taxi's current details and the current fare print(" +-- Current fare {:.2f}".format(prius_taxi.get_fare())) prius_taxi.start_fare() # restart the meter (start a new fare) prius_taxi.drive(100) print(prius_taxi) print(" +-- Current fare {:.2f}".format(prius_taxi.get_fare())) main() <file_sep>/prac_09/sort_files_2.py """ CP1404 practical 09 Use python os and shutil to sort files """ import os import shutil def main(): """Sort file according to their file suffix""" # access to the file folder os.chdir("FilesToSort") # get all types of the file suffix file_types = get_file_types() # make folders and store file types according to different folders in dictionary folder_dictionary = categorize_files(file_types) sort_files(folder_dictionary) def categorize_files(file_types): """make folders according to user input and store corresponding files""" folder_list = [] folder_dictionary = {} for file_type in file_types: folder = input("What category would you like to sort {} files into? ".format(file_type)) if folder not in folder_list: folder_list.append(folder) # make folder os.mkdir(folder) # store folder and the file type folder_dictionary[file_type] = folder return folder_dictionary def sort_files(folder_dictionary): """Sort files based on the user's behalf' stored in dictionary""" for file in os.listdir("."): file_split = file.split(".") try: folder = folder_dictionary[file_split[1]] shutil.move(file, folder + "/" + file) except IndexError: pass def get_file_types(): """get all file types for the files and return the list""" file_types = [] # get all file suffix types and store them in the list try: for file in os.listdir("."): file = file.split(".") if file[1] not in file_types: file_types.append(file[1]) # ignore folders except IndexError: pass return file_types main() <file_sep>/prac_09/cleanup_files.py """ CP1404/CP5632 Practical Reformat file names """ import os def main(): """Process all subdirectories using os.walk().""" os.chdir('Lyrics') for directory_name, subdirectories, filenames in os.walk('.'): for file in filenames: # join the path path = os.path.join(directory_name, file) # get new name new_name = os.path.join(directory_name, get_fixed_filename(file)) # replace new name with old name os.rename(path, new_name) def get_fixed_filename(filename): """Return a 'fixed' version of filename.""" name = filename.replace(" ", "_").replace(".TXT", ".txt") new_name = "" # iterate through each character in the name for index, char in enumerate(name): new_name += char try: # reformat through adding underscore if name[index].islower() and name[index + 1].isupper(): new_name += "_" # reformat through changing the first letter after underscore to uppercase elif name[index] == "_" and name[index + 1].islower(): name[index + 1].upper() # handle index error except IndexError: pass return new_name main() <file_sep>/prac_08/unreliable_car.py """ CP1404 Practical """ from car import Car import random class UnrealiableCar(Car): """A unreliable version of car""" def __init__(self, name, fuel, reliability): """ Initialize a unreliable car base on Car class """ super().__init__(name, fuel) self.reliability = reliability def drive(self, distance): """ drive the car randomly """ random_number = random.randint(0, 100) # generate a random number if random_number >= self.reliability: # not drive the car when random number is larger than reliability distance = 0 distance_driven = super().drive(distance) # call parent class return distance_driven # return a distance <file_sep>/prac_07/KivyDemos-master/convert_miles_km.py """ CP1404/CP5632 Practical Kivy GUI program to convert miles to kilometers <NAME> """ from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window from kivy.app import StringProperty CONVERSION = 1.6093 class ConvertMileKilometer(App): """ ConvertMileKilometer is a Kivy App for converting miles into kilometers """ conversion = StringProperty() def build(self): Window.size = (200, 100) self.title = "Miles to Kilometers" self.root = Builder.load_file('convert_miles_km.kv') return self.root def handle_calculate(self, text): """ handle calculation (could be button press or other call), output result to label widget """ try: number = float(text) except ValueError: self.root.ids.output_number.text = "0.0" return result = number * CONVERSION self.root.ids.output_number.text = str(result) self.conversion = str(result) def handle_increment(self, text, value): """handle increment/decrement when button pressed""" try: number = float(text) except ValueError: number = 0 result = number + value self.root.ids.input_number.text = str(result) ConvertMileKilometer().run() <file_sep>/prac_09/sort_files_1.py """ CP1404 practical 09 Use python os and shutil to sort files """ import os import shutil def main(): """Sort file according to their file suffix""" # access to the file folder os.chdir("FilesToSort") # get all types of the file suffix file_types = get_file_types() # create folders according to the types of suffix make_folders(file_types) sort_files() def sort_files(): for file in os.listdir('.'): file_split = file.split(".") try: shutil.move(file, file_split[1] + "/" + file) except IndexError: pass def make_folders(file_types): """make folders with suffix""" try: for file_type in file_types: os.mkdir(file_type) # pass when the file is already created except FileExistsError: pass def get_file_types(): """get all file types for the files and return the list""" file_types = [] # get all file suffix types and store them in the list try: for file in os.listdir('.'): file = file.split(".") if file[1] not in file_types: file_types.append(file[1]) # ignore folders except IndexError: pass return file_types main() <file_sep>/prac_08/silver_service_taxi_test.py """ CP1404 practical 08 This is the test program for SilverServiceTaxi class """ from silver_service_taxi import SilverServiceTaxi def main(): silver = SilverServiceTaxi("silver", 100, 2) silver.drive(18) print(silver) fare = silver.get_fare() print(fare) main()<file_sep>/prac_07/KivyDemos-master/dynamic_labels.py """ Kivy practical for CP1404, IT@JCU Dynamically create labels based on content of list <NAME> """ from kivy.app import App from kivy.lang import Builder from kivy.uix.label import Label class DynamicLabelsApp(App): """Main program - Kivy app to demo dynamic label creation.""" def __init__(self, **kwargs): """Construct main app.""" super().__init__(**kwargs) self.names = ["<NAME>", "<NAME>", "<NAME>"] def build(self): """Build the Kivy GUI.""" self.title = "Dynamic Labels" self.root = Builder.load_file("dynamic_labels.kv") self.create_widgets() return self.root def create_widgets(self): """Create widgets from list and add them to the GUI""" for name in self.names: label = Label(text=name, id=name) self.root.ids.labels_box.add_widget(label) DynamicLabelsApp().run() <file_sep>/prac_10/wiki.py """ CP1404 Practical 10 A small program asking for a Wikipedia page title through user input and return the Wikipedia page's summary, title and url """ import wikipedia def main(): """While input is not empty, print the page's summary, title and url""" page = input("Please enter a title: ") while page != "": try: wiki = wikipedia.page(page) # store the page to load and access data print("Summary: {}\n".format(wikipedia.summary(page))) # return the Wikipedia summary of the page print("Title: {}\n".format(wiki.title)) # return the Wikipedia title of the page print("URL: {}\n".format(wiki.url)) # return the Wikipedia url of the page print("-------------------------------------------------------------------------------") except wikipedia.exceptions.DisambiguationError as e: # handle ambiguous error print("Please choose one clear title in the list below") print(e.options) print("-------------------------------------------------------------------------------") page = input("Please enter a title: ") return main()
2d9e17c4815932f5ac4950460bd1a050042ac89a
[ "Python" ]
9
Python
yueranwu/practical
94ff9c5c075b08846c30a930f57cc92d962b5b06
1d439e9d814ce8524e20344707f3bb9d5744ea87
refs/heads/master
<repo_name>Riinkesh/iaac_tools<file_sep>/README.md # Context This repository can be used to setup the necessary tools for running git, terraform, terragrunt and awscli in an ubuntu docker container. ## Setup Clone this repository in a local directory. This directory shall then be mounted to the ubuntu linux docker container's workspace we will create for the tutorial. ```bash git clone https://github.com/Riinkesh/iaac_tools.git ``` ## Usage 1) Run a docker container using the command as below- ```bash docker run -it -v C:\Users\IAMUser\Desktop\IAAC:/opt/workspace ubuntu ``` Here *C:\Users\IAMUser\Desktop\IAAC* is the path in a windows system, where the repository has been cloned. 2) Exec into the docker container and navigate (cd) to the path */opt/workspace*. 3) Run the startup script mounted from the repository in local- ```bash ./startup-script.sh ``` This script will install- - Git - AWS CLI Version 2 - Terraform (v 0.13.2) - Terragrunt (v 0.23.40) - and few other necessary packages (curl, vim, and unzip). Run the below commands to confirm the installation once the above script completes. ```bash git --version aws --version terraform -v terragrunt -v ``` ## Configuring the AWS CLI This section explains how to configure the settings that the AWS CLI uses to interact with AWS. These include your security credentials, the default output format, and the default AWS Region. Among different methods of configuring these settings is the environment variables method, which can be useful for scripting or temporarily setting a named profile (IAM User) as the default. We are using the environment variables method in this tutorial. The following examples show how you can configure environment variables for the default user. ```bash export AWS_ACCESS_KEY_ID=YOURIAMUSERACCESSKEY export AWS_SECRET_ACCESS_KEY=YOURIAMUSERSECRETaBcDxYzEXAMPLEACCESSKEY export AWS_DEFAULT_REGION=us-central-1 ``` Setting the environment variable changes the value used until the end of your session, or until you set the variable to a different value. ## License [MIT](https://choosealicense.com/licenses/mit/) <file_sep>/startup-script.sh #! /bin/bash echo "###################################" echo "Installing curl, git, vim and unzip" echo "###################################" apt-get update apt-get install curl git vim unzip -y echo "############################################" echo "Installing AWS CLI, Terraform and Terragrunt" echo "############################################" curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" unzip awscliv2.zip ./aws/install curl -L -o terraform.zip https://releases.hashicorp.com/terraform/0.13.2/terraform_0.13.2_linux_amd64.zip && unzip -o terraform.zip -d /usr/local/bin/ curl -L -o /usr/local/bin/terragrunt https://github.com/gruntwork-io/terragrunt/releases/download/v0.23.40/terragrunt_linux_386 && chmod u+x /usr/local/bin/terragrunt
bf4f33076c8e96508397c0c5aa3533d6251ea719
[ "Markdown", "Shell" ]
2
Markdown
Riinkesh/iaac_tools
139276774f068a68a59edfa4caa74c99ae37c22d
b2f56e4cae89f2dde75cdc57aeefd48af0af7620
refs/heads/master
<repo_name>banixc/hsync<file_sep>/shell/restart.sh #!/bin/sh bash stop.sh bash start.sh<file_sep>/shell/stop.sh #!/bin/sh for ii in `ps auxf|grep "example_hsync"|grep -v grep|awk '{print $2}'`; do kill -9 ${ii}; done <file_sep>/hsync/server.py #!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import json import os from flask import Flask, request from werkzeug.routing import BaseConverter from .dir import ServerDir, File def _parse_args_server(): parser = argparse.ArgumentParser() parser.add_argument('-p', '--port', default=6688, help='http server bind port default: 6688') parser.add_argument( '-v', '--version', action='version', version='%(prog)s 1.0.1', ) return parser.parse_args() class RegexConverter(BaseConverter): def __init__(self, _map, *args): super(RegexConverter, self).__init__(_map) self.map = map self.regex = args[0] app = Flask(__name__) app.url_map.converters['regex'] = RegexConverter app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 @app.route('/<regex("([:\/\w-]+)*$"):root_path>', methods=['GET']) def get(root_path): root_path = '/' + root_path server_dir = ServerDir(root_path, (), ()) return json.dumps([i.__dict__ for i in server_dir.get_file_list()]) @app.route('/<regex("([:\/\w-]+)*$"):root_path>', methods=['POST']) def post(root_path): root_path = '/' + root_path os.chdir(root_path) f = File.from_json(json.dumps(request.form)) file_body = request.files.get('file_body') f.write_file(file_body) return 'success!' def run(): args = _parse_args_server() app.run(host='0.0.0.0', debug=False, port=args.port) if __name__ == '__main__': run() <file_sep>/requirements.txt werkzeug requests>=2.11.0 Flask>=0.11.1 <file_sep>/shell/uwsgi.ini [uwsgi] socket = /tmp/example/hsync.sock module = hsync.server:app processes = 1 threads = 1 daemonize = /home/example/.log/hsync_uwsgi.log procname = example_hsync <file_sep>/README.md # hsync 基于HTTP的文件同步工具 ## 2017.10.12 update - 添加配置文件夹忽略项 ## 2017.10.18 update - 添加服务器多目录支持 - 添加本地上传多服务器支持 ## 2017.10.26 update - 修复不能传送二进制文件的BUG - 现在服务器端不需要配置文件 通过客户端进行设置 - 现在客户端可以传送同一个目录到多个服务器IP - 添加CLI模式 可直接在命令行中调用 - 修改名字为 hsync - 更新cli参数 - 修复文件打开BUG ## TODO List - [x] 服务器全目录支持 - [x] 客户端多服务器支持 - [x] 添加CLI模式 - [ ] 远程执行命令 - [ ] 双向同步 - [ ] 严格模式 - [ ] 合并文件 - [ ] 本地监听 <file_sep>/hsync/__main__.py #!/usr/bin/env python # -*- coding: utf-8 -*- from local import run as local from server import run as server from server import app if __name__ == '__main__': local() <file_sep>/setup.py #!/usr/bin/env python # -*- coding: utf-8 -*- from distutils.core import setup from setuptools import find_packages setup( name='hsync', version='1.0.5', description='a file sync tools based http', author='banixc', author_email='<EMAIL>', url='https://github.com/banixc/hsync', py_modules=['hsync'], packages=find_packages(), install_requires=[ 'flask>=0.11.1', 'requests>=2.11.0' ], entry_points={ 'console_scripts': [ 'hsync = hsync.__main__:local', 'hsyncd = hsync.__main__:server', ], } )
6724f0dbf714d641d58b95172f59146f70669c95
[ "Markdown", "INI", "Python", "Text", "Shell" ]
8
Shell
banixc/hsync
77804489b673fc23743b37d9639833161377e5f8
2c2e0c5a96e1848364c1b2a11052be5d81005afd
refs/heads/master
<file_sep># gulp-visual-regression-report Compares screenshots of your apps and creates a report, using [visual-regression-report](TODO link). ## Installation Install package with NPM and add it to your development dependencies: `npm install --save-dev gulp-visual-regression-report` ## Usage ```javascript const gulp = require("gulp"); const gulpVisualRegressionReport = require("gulp-visual-regression-report"); gulp.task("regression-report", function() { return gulp.src("./screenshots/after/*.png") .pipe(gulpVisualRegressionReport({ beforeDir: "./screenshots/before", reportsDir: "./report" })) }); ``` ## Options * `beforeDir`: mandatory, the folder which contains the previous screenshots * `reportsDir`: mandatory, the folder which will contain the generated report * `reportTemplate`: optional, path to the report template file to use. Any file contained in that folder will also be copied verbatim to to `reportsDir` ## License Copyright 2018 Engage Technology Partners Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. <file_sep>/* Copyright 2018 Engage Technology Partners Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ "use strict"; const PluginError = require("plugin-error"); const through = require("through2"); const PLUGIN_NAME = require("./package").name; const visualRegressionReportConstructor = require("visual-regression-report"); function visualRegressionReport(opts) { let newVisualRegressionReport; try { newVisualRegressionReport = visualRegressionReportConstructor(opts); } catch (error) { throw new PluginError(PLUGIN_NAME, error); } function compare(file, enc, callback) { newVisualRegressionReport.compareScreenshot(file.path) .then(() => callback()) .catch((error) => callback(error)); } function createReport(callback) { newVisualRegressionReport.createReport() .then((statistics) => callback(null, statistics)) .catch(callback); } return through.obj(compare, createReport); } module.exports = visualRegressionReport;
fd955e67a25f76efc21da52c8e5ab93f8d4114f2
[ "Markdown", "JavaScript" ]
2
Markdown
engagetech/gulp-visual-regression-report
707dc5dd56b38198f877f888a46bc9483e8d8321
c4298583d2ab9ac51f2f503304dd38ae8325e507
refs/heads/master
<repo_name>RachnaReddyM/Web-Development-Coursework<file_sep>/README.md # Web-Development-Coursework This repository consists of assignments done as part of Web Development course work in Spring 2018.<br> HW01 - Few Configuration files of nginx setup<br> HW02 - Basic HTML, CSS and Javascript tasks. (rachnareddym.com)<br> HW03 - A memory game built using React.js and Bootstrap.<br> HW04 - A calculator to perform addition, subtraction, multiplication and division of infix operators, built using Elixir on Erlang VM.<br> HW05 - A memory game bulit using Elixir(to save state of the game played by each user), React.js and Bootstrap. (http://multi-player-memory.rachnareddym.com/).<br> HW06 - Task Tracker App to create and assign tasks. Stored data in Postgres SQL. ( tasks1.rachnareddym.com)<br> HW07 - Task Tracker App to retrieve stored information using REST APIs in JSON format. (tasks2.rachnareddym.com)<br> HW08 - A Single Page Task Tracker App. (tasks3.rachnareddym.com)<br> <file_sep>/Task Tracker App (hw06)/issuetracker/README.md # Issuetracker http://tasks1.rachnareddym.com/ <file_sep>/Task Tracker App (hw06)/issuetracker/start.sh #!/bin/bash export PORT=5110 cd ~/www/tasktracker ./bin/issuetracker stop || true ./bin/issuetracker start <file_sep>/Memory Game (hw03)/assets/js/demo.jsx import React from 'react'; import ReactDOM from 'react-dom'; import classnames from 'classnames'; import shuffle from 'shuffle-array'; export default function run_demo(root) { ReactDOM.render(<Demo />, root); } //List of characters in the game const cardLetters= ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H']; // Function to create a card object and shuffle them function makecardShow() { let makeCards=[]; for(let i=0;i<16;i++) { let pair={ id:i, key:cardLetters[i], matched: false, flipped:false }; makeCards.push(pair); } //Attribution: Javascript utility used to shuffle elements in an array from New Programs Makers shuffle(makeCards); return makeCards; } class Demo extends React.Component { constructor(props) { super(props); this.state = { cards:makecardShow(), // a set of cards openCard:false, // sets to true when a card is displayed openCardId:0, // Card ID of the flipped card openCardValue:'', // Card letter of the flipped card noOfMatches:0, // No. of cards matched noOfClicks:0, // No. of cards flipped open freeze:false, // is set to true when 2 cards are displayed // and should ignore any clicks for 1 sec score:0 // to maintain the player's score }; this.showAllCards = this.showAllCards.bind(this); this.cardsReset = this.cardsReset.bind(this); } // Function to create the cards showAllCards(cards) { return cards.map((card,index) => { return ( <Card key={index} id={index} item={card} value={card.key} flipped={card.flipped} matched={card.matched} cardFlip={this.cardFlip.bind(this)} />); }); } // Funtion called when a card is clicked on cardFlip(cardId,cardValue){ var allCards = this.state.cards; if(!allCards[cardId].flipped) // when a card is unflipped { if(!this.state.freeze) // when only one card or no card is dispalyed { var clicks = parseInt(this.state.noOfClicks)+1; var scores = 500-(parseInt(this.state.noOfClicks)*2); allCards[cardId].flipped = true; this.setState({cards : allCards, noOfClicks:clicks,freeze:true, score:scores}); if(this.state.openCard) // when a single card is opened { if(this.state.openCardValue == cardValue) // when both the flipped cards match { var matches= parseInt(this.state.noOfMatches)+1; console.log(matches); allCards[this.state.openCardId].matched = true; allCards[cardId].matched = true; this.setState({ cards:allCards, openCard: false, openCardId:0, openCardValue:'', noOfMatches:matches, freeze:false }); } else // when cards do not match { // cards close in 1 second delay. setTimeout(() => { allCards[this.state.openCardId].flipped = false; allCards[cardId].flipped = false; this.setState({cards: allCards, openCard:false, openCardId:0, openCardValue:'', freeze:false })},1000); } } else // when only one card is clicked open { this.setState ({ cards:allCards, openCard: true, openCardId: cardId, openCardValue: cardValue, freeze:false }); } } } } // Function to reset the game cardsReset() { console.log(this.state.noOfMatches); console.log("enterted restart fucntion"); this.setState ({ cards:makecardShow(), openCard:false, openCardId:0, openCardValue:'', noOfMatches:0, noOfClicks:0, freeze:false, score:0 }); } render() { var buttonText = "Restart"; var matches = parseInt(this.state.noOfMatches); if ( matches == 8) { var finalscore =(this.state.score); setTimeout(() => { alert("You Won!!!"+"\n"+"Your score is: "+finalscore)},1000); setTimeout(() => {this.cardsReset()},3000); } let cardShow= this.showAllCards(this.state.cards); return ( <div> <div className="container"> <p className="clicks">Flipped cards until now:{this.state.noOfClicks}</p> <p className="scores">Score:{this.state.score}</p> <div className="row"> {cardShow} </div> <button onClick={this.cardsReset}>{buttonText}</button> </div> <div className="footer"> </div> </div> ); } } function Card(props) { let item= props.item; //Attribution: Javascript utility used to set multiple classnames based on condition from New Programs Makers var className = classnames( 'card':true, {'flipped': props.flipped}, {'matched': props.matched} ); var cardValue =' '; if (props.flipped) { cardValue= props.value; } return ( <div className ="col-sm-3"> <div className ={className} onClick={() =>props.cardFlip(props.id,props.value)}> <p className="letters">{cardValue}</p> </div> </div> ); }
715ded3a74bc16ce763c36add35c537015ba5ef1
[ "Markdown", "JavaScript", "Shell" ]
4
Markdown
RachnaReddyM/Web-Development-Coursework
20780e9b9d131d524e6e1194e41d623efe50527c
26872023835fe784063e21152a243775d08b1cf5
refs/heads/master
<repo_name>ManhHuuNguyen/SoftwareRasterizer<file_sep>/RayTracer/Matrix4x4.h #pragma once #include <math.h> #include "Vector4f.h" #include "CONSTANTS.h" #define IDENTITYMATRIX4X4 Matrix4x4(1.0f, 0.0f, 0.0f, 0.0f,\ 0.0f, 1.0f, 0.0f, 0.0f,\ 0.0f, 0.0f, 1.0f, 0.0f,\ 0.0f, 0.0f, 0.0f, 1.0f) class Matrix4x4 { // column matrix public: float e11, e21, e31, e41; float e12, e22, e32, e42; float e13, e23, e33, e43; float e14, e24, e34, e44; Matrix4x4(); // construct an identity matrix Matrix4x4(float e11, float e21, float e31, float e41, float e12, float e22, float e32, float e42, float e13, float e23, float e33, float e43, float e14, float e24, float e34, float e44); Matrix4x4 operator * (float k); Matrix4x4 operator / (float k); Matrix4x4 operator * (const Matrix4x4 & m); Vector4f operator * (const Vector4f & V); void identityMatrix(); }; Matrix4x4 operator *(float k, const Matrix4x4 & m); std::ostream & operator << (std::ostream &os, Matrix4x4 &m); Matrix4x4 rotationMatrixAboutX(float theta); Matrix4x4 rotationMatrixAboutY(float theta); Matrix4x4 rotationMatrixAboutZ(float theta); Matrix4x4 rotationMatrixAboutRandAxis(Vector4f v, float theta); Matrix4x4 translationMatrix(float tx, float ty, float tz); Matrix4x4 scaleMatrix(float sx, float sy, float sz); Matrix4x4 orthoProjectionMatrix(float l, float r, float b, float t, float n, float f); Matrix4x4 viewportMatrix(float w, float h); Matrix4x4 frustumMatrix(float l, float r, float b, float t, float n, float f); Matrix4x4 perspectiveProjectionMatrix(float fovy, float a, float n, float f); Matrix4x4 cameraMatrix(Vector4f & eyeVect, Vector4f & spotVect, Vector4f & upVect); <file_sep>/RayTracer/Raster.h #pragma once #include "Colorf.h" #include <iostream> #include <fstream> #include "TriangleArray.h" class Raster { public: int width; int height; PixelColor * pixels; float * zBuffer; Raster(); Raster(int width, int height); void writeToBMPFile(const char * path); void writeToPPMFile(const char * path); void clear(); }; void getBarycentricCoordinate(Vector4f & v1, Vector4f & v2, Vector4f & v3, int X, int Y, float * l1, float * l2, float * l3); void getBarycentricCoordinate2D(Vector3f & v1, Vector3f & v2, Vector3f & v3, int X, int Y, float * l1, float * l2, float * l3); <file_sep>/RayTracer/Vector4f.h #pragma once #include <math.h> #include <string> #include "CONSTANTS.h" class Vector4f { public: float x; float y; float z; float w; Vector4f(); Vector4f(float X, float Y, float Z); Vector4f(float X, float Y, float Z, float W); bool operator == (const Vector4f & V); bool operator != (const Vector4f & V); Vector4f operator + (const Vector4f & V); Vector4f operator - (const Vector4f & V); Vector4f operator * (float a); Vector4f operator / (float a); float operator * (const Vector4f & V); Vector4f operator - (); void zero(); void normalize(); void homogenize(); }; Vector4f operator *(float k, const Vector4f & V); std::ostream & operator << (std::ostream &os, Vector4f &V); Vector4f crossProduct(Vector4f & v1, Vector4f & v2); <file_sep>/RayTracer/Main.cpp #include <stdio.h> #include <iostream> #include <string> #include "Raster.h" #include "Helper.h" #include "Matrix3x3.h" #include "Matrix4x4.h" #include "Scene.h" #include "TriangleArray.h" #include <time.h> using namespace std; void generateWalkAroundScene(Scene & scene, Raster & raster); int main(int argc, const char * argv[]) { int close; const clock_t begin_time = clock(); vector<string> geometry; Scene scene = readSceneFile("scene.u3d"); Raster raster(scene.rasterWidth, scene.rasterHeight); generateWalkAroundScene(scene, raster); /*cout << "Number of seconds reading file: " << float(clock() - begin_time) / CLOCKS_PER_SEC << endl; const clock_t begin_time1 = clock(); scene.draw(raster); cout << "Number of seconds drawing 3D world: " << float(clock() - begin_time1) / CLOCKS_PER_SEC << endl; raster.writeToPPMFile("image.ppm"); raster.writeToBMPFile("image.bmp");*/ std::cout << "Enter st to exit: "; std::cin >> close; return 0; } void generateWalkAroundScene(Scene & scene, Raster & raster) { int numberOfScenes = 40; float R = 5.0f; for (int i = 0; i < numberOfScenes; i++) { raster.clear(); string fileName = "./animations/a" + to_string(i) + ".bmp"; float alpha = 2 * PI * (float) i / numberOfScenes; float sinAlpha = sinf(alpha); float cosAlpha = cosf(alpha); scene.eyeX = sinAlpha*R; scene.eyeZ = cosAlpha*R; scene.draw(raster); raster.writeToBMPFile(fileName.c_str()); } } <file_sep>/README.md # Software rasterizer A simple software rasterizer as homework of CS 5600 University of Utah ![Sample image](a0.bmp?raw=true "head object linear texturing") ![Sample image](a18.bmp?raw=true "<NAME>") ![Sample image](a30.bmp?raw=true "<NAME>") <file_sep>/RayTracer/Colorf.h #pragma once #define BLACK Colorf(0.0f, 0.0f, 0.0f, 0.0f) #define WHITE Colorf(1.0f, 1.0f, 1.0f, 0.0f) #define RED Colorf(1.0f, 0.0f, 0.0f, 0.0f) #define GREEN Colorf(0.0f, 1.0f, 0.0f, 0.0f) #define BLUE Colorf(0.0f, 0.0f, 1.0f, 0.0f) #include <iostream> #include <math.h> class Colorf { public: float R; float G; float B; float A; Colorf(); Colorf(float Rvalue, float Gvalue, float Bvalue, float Avalue); Colorf operator * (float k); Colorf operator * (const Colorf & c); Colorf operator + (const Colorf & c); }; struct PixelColor { uint8_t R; //0-255 uint8_t G; uint8_t B; uint8_t A; }; Colorf operator * (float k, const Colorf & c); Colorf intColorToFloatColor(PixelColor & i); PixelColor floatColorToIntColor(Colorf & f); std::ostream & operator << (std::ostream &os, Colorf &p); <file_sep>/RayTracer/PixelColor.h #pragma once #define BLACK PixelColor(0, 0, 0, 0) #define WHITE PixelColor(255, 255, 255, 0) #define RED PixelColor(255, 0, 0, 0) #define GREEN PixelColor(0, 255, 0, 0) #define BLUE PixelColor(0, 0, 255, 0) #include <iostream> class PixelColor { public: uint8_t R; //0-255 uint8_t G; uint8_t B; uint8_t A; PixelColor(); PixelColor(int Rvalue, int Gvalue, int Bvalue, int Avalue); PixelColor operator * (float k); PixelColor operator + (const PixelColor & c); }; PixelColor operator * (float k, const PixelColor & c); std::ostream & operator << (std::ostream &os, PixelColor &p); <file_sep>/RayTracer/Scene.cpp #include "Scene.h" Scene::Scene() { } void Scene::addObject(TriangleArray & ta) { objects.push_back(ta); } int Scene::size() { return objects.size(); } TriangleArray & Scene::getLastObj() { return objects.back(); } void Scene::draw(Raster & raster) { Vector4f eyeVect(eyeX, eyeY, eyeZ); Vector4f spotVect(spotX, spotY, spotZ); Vector4f upVect(upX, upY, upZ); Matrix4x4 camMatrix = cameraMatrix(eyeVect, spotVect, upVect); Matrix4x4 projectionMatrix = perspectiveProjectionMatrix(fov, aspect, near, far); Matrix4x4 viewport = viewportMatrix(rasterWidth, rasterHeight); // moving light into eye coordinate Vector4f lightInEyeCoor = camMatrix * pointLight.position; for (int k = 0; k < objects.size(); k++) { Matrix4x4 modelViewMatrix = camMatrix; for (int i = 0; i < objects[k].transformations.size(); i++) { modelViewMatrix = modelViewMatrix * objects[k].transformations[i]; } if (objects[k].texture.size() == 0) { // if there is no texture // move into eye coordinate int culledTriangle = 0; for (int i = 0; i < objects[k].faces.size(); i++) { std::vector<int> face = objects[k].faces[i]; int v1Index = face[0]; int v2Index = face[1]; int v3Index = face[2]; int vn1Index = face[3]; int vn2Index = face[4]; int vn3Index = face[5]; Vector4f v1 = modelViewMatrix * objects[k].vertices[v1Index]; Vector4f v2 = modelViewMatrix * objects[k].vertices[v2Index]; Vector4f v3 = modelViewMatrix * objects[k].vertices[v3Index]; // back-face culling Vector4f va = v2 - v1; Vector4f vb = v3 - v1; Vector4f normalVect = crossProduct(va, vb); if (normalVect * v1 > 0.0f) { culledTriangle++; continue; } // projection matrix v1 = projectionMatrix * v1; v2 = projectionMatrix * v2; v3 = projectionMatrix * v3; // homogenize v1.homogenize(); v2.homogenize(); v3.homogenize(); // viewport matrix v1 = viewport * v1; v2 = viewport * v2; v3 = viewport * v3; int minX = v1.x; int maxX = v3.x; int minY = v1.y; int maxY = v3.y; if (v1.x > maxX) { maxX = v1.x; } if (v2.x > maxX) { maxX = v2.x; } if (v2.x < minX) { minX = v2.x; } if (v3.x < minX) { minX = v3.x; } if (v1.y > maxY) { maxY = v1.y; } if (v2.y > maxY) { maxY = v2.y; } if (v2.y < minY) { minY = v2.y; } if (v3.y < minY) { minY = v3.y; } if (minX < 0) { minX = 0; } if (minY < 0) { minY = 0; } if (maxX >= rasterWidth) { maxX = rasterWidth - 1; } if (maxY >= rasterHeight) { maxY = rasterHeight - 1; } float zA = v1.z; float zB = v2.z; float zC = v3.z; for (int Y = minY; Y <= maxY; Y++) { for (int X = minX; X <= maxX; X++) { float lambda1, lambda2, lambda3; getBarycentricCoordinate(v1, v2, v3, X, Y, &lambda1, &lambda2, &lambda3); if ((0.0f <= lambda1 && 0.0f <= lambda2 && 0.0f <= lambda3)) { float zValue = lambda1 * zA + lambda2 * zB + lambda3 * zC; if (abs(zValue) < abs(raster.zBuffer[Y * rasterWidth + X])) {// If a point is closer to the eye, which is at (0, 0, 0) then draw. Vector4f eyeCoorV1 = modelViewMatrix * objects[k].vertices[v1Index]; Vector4f eyeCoorV2 = modelViewMatrix * objects[k].vertices[v2Index]; Vector4f eyeCoorV3 = modelViewMatrix * objects[k].vertices[v3Index]; Vector4f incidentPoint = lambda1 * eyeCoorV1 + lambda2 * eyeCoorV2 + lambda3 * eyeCoorV3; Vector4f l = lightInEyeCoor - incidentPoint; Vector4f normal1 = modelViewMatrix * objects[k].vertexNormal[vn1Index]; Vector4f normal2 = modelViewMatrix * objects[k].vertexNormal[vn2Index]; Vector4f normal3 = modelViewMatrix * objects[k].vertexNormal[vn3Index]; Vector4f normal = lambda1 * normal1 + lambda2 * normal2 + lambda3 * normal3; l.normalize(); normal.normalize(); Colorf color = pointLight.LdLs * objects[k].KaKd * fmaxf(l*normal, 0.0f); // add diffuse color color = color + ambientLight * objects[k].KaKd; // add ambient color Vector4f r = 2 * (normal * l) * normal - l; Vector4f v = -incidentPoint; // because eye is at (0, 0, 0) in eye coordinate r.normalize(); v.normalize(); color = color + pointLight.LdLs * objects[k].Ks * powf(fmax(r*v, 0.0f), objects[k].Ks.A); raster.pixels[Y * rasterWidth + X] = floatColorToIntColor(color); raster.zBuffer[Y * rasterWidth + X] = zValue; } } } } } std::cout << "Percent saved: " << (float)culledTriangle / objects[k].size() * 100 << std::endl; } else { // if there is texture Raster textureMap = readBitMapFile(objects[k].texture.c_str()); // move into eye coordinate int culledTriangle = 0; for (int i = 0; i < objects[k].faces.size(); i++) { std::vector<int> face = objects[k].faces[i]; int v1Index = face[0]; int v2Index = face[1]; int v3Index = face[2]; int vn1Index = face[3]; int vn2Index = face[4]; int vn3Index = face[5]; int vt1Index = face[6]; int vt2Index = face[7]; int vt3Index = face[8]; Vector4f v1 = modelViewMatrix * objects[k].vertices[v1Index]; Vector4f v2 = modelViewMatrix * objects[k].vertices[v2Index]; Vector4f v3 = modelViewMatrix * objects[k].vertices[v3Index]; // back-face culling Vector4f va = v2 - v1; Vector4f vb = v3 - v1; Vector4f normalVect = crossProduct(va, vb); if (normalVect * v1 > 0.0f) { culledTriangle++; continue; } // projection matrix v1 = projectionMatrix * v1; v2 = projectionMatrix * v2; v3 = projectionMatrix * v3; // homogenize v1.homogenize(); v2.homogenize(); v3.homogenize(); // viewport matrix v1 = viewport * v1; v2 = viewport * v2; v3 = viewport * v3; int minX = v1.x; int maxX = v3.x; int minY = v1.y; int maxY = v3.y; if (v1.x > maxX) { maxX = v1.x; } if (v2.x > maxX) { maxX = v2.x; } if (v2.x < minX) { minX = v2.x; } if (v3.x < minX) { minX = v3.x; } if (v1.y > maxY) { maxY = v1.y; } if (v2.y > maxY) { maxY = v2.y; } if (v2.y < minY) { minY = v2.y; } if (v3.y < minY) { minY = v3.y; } if (minX < 0) { minX = 0; } if (minY < 0) { minY = 0; } if (maxX >= rasterWidth) { maxX = rasterWidth - 1; } if (maxY >= rasterHeight) { maxY = rasterHeight - 1; } float zA = v1.z; float zB = v2.z; float zC = v3.z; for (int Y = minY; Y <= maxY; Y++) { for (int X = minX; X <= maxX; X++) { float lambda1, lambda2, lambda3; getBarycentricCoordinate(v1, v2, v3, X, Y, &lambda1, &lambda2, &lambda3); if ((0.0f <= lambda1 && 0.0f <= lambda2 && 0.0f <= lambda3)) { float zValue = lambda1 * zA + lambda2 * zB + lambda3 * zC; if (abs(zValue) < abs(raster.zBuffer[Y * rasterWidth + X])) {// If a point is closer to the eye, which is at (0, 0, 0) then draw. Vector4f eyeCoorV1 = modelViewMatrix * objects[k].vertices[v1Index]; Vector4f eyeCoorV2 = modelViewMatrix * objects[k].vertices[v2Index]; Vector4f eyeCoorV3 = modelViewMatrix * objects[k].vertices[v3Index]; Vector4f incidentPoint = lambda1 * eyeCoorV1 + lambda2 * eyeCoorV2 + lambda3 * eyeCoorV3; Vector4f l = lightInEyeCoor - incidentPoint; Vector4f normal1 = modelViewMatrix * objects[k].vertexNormal[vn1Index]; Vector4f normal2 = modelViewMatrix * objects[k].vertexNormal[vn2Index]; Vector4f normal3 = modelViewMatrix * objects[k].vertexNormal[vn3Index]; Vector4f normal = lambda1 * normal1 + lambda2 * normal2 + lambda3 * normal3; l.normalize(); normal.normalize(); Vector3f vTexture1 = objects[k].vertexTexture[vt1Index]; Vector3f vTexture2 = objects[k].vertexTexture[vt2Index]; Vector3f vTexture3 = objects[k].vertexTexture[vt3Index]; Vector3f currentTexture = lambda1 * vTexture1 + lambda2 * vTexture2 + lambda3 * vTexture3; int tx = (int)(currentTexture.x * textureMap.width); int ty = (int)(currentTexture.y * textureMap.height); Colorf colorAtPixel = intColorToFloatColor( textureMap.pixels[ty * textureMap.width + tx]); Colorf color = pointLight.LdLs * colorAtPixel * fmaxf(l*normal, 0.0f); // add diffuse color color = color + ambientLight * colorAtPixel; // add ambient color Vector4f r = 2 * (normal * l) * normal - l; Vector4f v = -incidentPoint; // because eye is at (0, 0, 0) in eye coordinate r.normalize(); v.normalize(); color = color + pointLight.LdLs * objects[k].Ks * powf(fmax(r*v, 0.0f), objects[k].Ks.A); raster.pixels[Y * rasterWidth + X] = floatColorToIntColor(color); raster.zBuffer[Y * rasterWidth + X] = zValue; } } } } } std::cout << "Percent saved: " << (float)culledTriangle / objects[k].size() * 100 << std::endl; } } } Raster readBitMapFile(const char * path) { int i; FILE* f = fopen(path, "rb"); if (f == NULL) throw "Argument Exception"; unsigned char info[54]; fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header // extract image height and width from header int width = *(int*)&info[18]; int height = *(int*)&info[22]; Raster raster(width, height); for (int i = 0; i < height; i++){ for (int j = 0; j < width * 3; j += 3){ // Convert (B, G, R) to (R, G, B) uint8_t blue; fread(&blue, 1, 1, f); //uint8_t blue = data; uint8_t green; fread(&green, 1, 1, f); uint8_t red; fread(&red, 1, 1, f); raster.pixels[i * width + j/3] = PixelColor{red, green, blue, 0}; } } fclose(f); return raster; }<file_sep>/RayTracer/Matrix3x3.cpp #include "Matrix3x3.h" Matrix3x3::Matrix3x3() { e11 = 1.0f; e21 = 0.0f; e31 = 0.0f; e12 = 0.0f; e22 = 1.0f; e32 = 0.0f; e13 = 0.0f; e23 = 0.0f; e33 = 1.0f; } Matrix3x3::Matrix3x3(float e11, float e21, float e31, float e12, float e22, float e32, float e13, float e23, float e33) { this->e11 = e11; this->e21 = e21; this->e31 = e31; this->e12 = e12; this->e22 = e22; this->e32 = e32; this->e13 = e13; this->e23 = e23; this->e33 = e33; } Matrix3x3 Matrix3x3::operator * (float k) { return Matrix3x3(k*e11, k*e21, k*e31, k*e12, k*e22, k*e32, k*e13, k*e23, k*e33); } Matrix3x3 Matrix3x3::operator / (float k) { return Matrix3x3(e11 / k, e21 / k, e31 / k, e12 / k, e22 / k, e32 / k, e13 / k, e23 / k, e33 / k); } float Matrix3x3::getDeterminant() { return e11 * e22*e33 + e21 * e32*e13 + e31 * e12*e23 - e31 * e22*e13 - e21 * e12*e33 - e11 * e32*e23; } void Matrix3x3::identityMatrix() { e11 = 1.0f; e21 = 0.0f; e31 = 0.0f; e12 = 0.0f; e22 = 1.0f; e32 = 0.0f; e13 = 0.0f; e23 = 0.0f; e33 = 1.0f; } Matrix3x3 Matrix3x3::operator * (const Matrix3x3 & m) { float a11 = e11 * m.e11 + e21 * m.e12 + e31 * m.e13; float a21 = e11 * m.e21 + e21 * m.e22 + e31 * m.e23; float a31 = e11 * m.e31 + e21 * m.e32 + e31 * m.e33; float a12 = e12 * m.e11 + e22 * m.e12 + e32 * m.e13; float a22 = e12 * m.e21 + e22 * m.e22 + e32 * m.e23; float a32 = e12 * m.e31 + e22 * m.e32 + e32 * m.e33; float a13 = e13 * m.e11 + e23 * m.e12 + e33 * m.e13; float a23 = e13 * m.e21 + e23 * m.e22 + e33 * m.e23; float a33 = e13 * m.e31 + e23 * m.e32 + e33 * m.e33; return Matrix3x3(a11, a21, a31, a12, a22, a32, a13, a23, a33); } Vector3f Matrix3x3::operator * (const Vector3f & v) { float vx = e11 * v.x + e21 * v.y + e31 * v.z; float vy = e12 * v.x + e22 * v.y + e32 * v.z; return Vector3f(vx, vy); } Matrix3x3 operator *(float k, Matrix3x3 & m) { return Matrix3x3(k*m.e11, k*m.e21, k*m.e31, k*m.e12, k*m.e22, k*m.e32, k*m.e13, k*m.e23, k*m.e33); } std::ostream & operator << (std::ostream &os, Matrix3x3 &m) { return os << "Matrix3x3<" << m.e11 << ", " << m.e21 << ", " << m.e31 << "\n " << m.e12 << ", " << m.e22 << ", " << m.e32 << "\n " << m.e13 << ", " << m.e23 << ", " << m.e33 << ">"; } Matrix3x3 rotationMatrix(float theta) { float cosTheta = cosf(theta); float sinTheta = sinf(theta); return Matrix3x3( cosTheta, -sinTheta, 0.0f, sinTheta, cosTheta, 0.0f, 0.0f, 0.0f, 1.0f ); } Matrix3x3 translationMatrix(float tx, float ty) { return Matrix3x3( 1.0f, 0.0f, tx, 0.0f, 1.0f, ty, 0.0f, 0.0f, 1.0f ); } Matrix3x3 scaleMatrix(float sx, float sy) { return Matrix3x3( sx, 0.0f, 0.0f, 0.0f, sy, 0.0f, 0.0f, 0.0f, 1.0f ); }<file_sep>/RayTracer/Helper.cpp #include "Helper.h" std::vector<std::string> splitString(std::string str) { std::vector<std::string> vect; std::string substring; for (char & c : str) { if (c == ' ' || c == '\n'){ if (substring != "") { vect.push_back(substring); substring.clear(); } } else { substring += c; } } if (substring != "") { vect.push_back(substring); } return vect; } Scene readSceneFile(const char * path) { std::vector<std::string> geometry; std::ifstream f(path); if (!f) { std::cout << "Cannot open scene file" << std::endl; throw; } Scene scene; std::string str = "\n"; std::getline(f, str); std::vector<std::string> vect = splitString(str); if (vect[0] != "U3") { throw; } getline(f, str); // get width and height of raster vect = splitString(str); scene.rasterWidth = atoi(vect[0].c_str()); scene.rasterHeight = atoi(vect[1].c_str()); getline(f, str); // get eye coordinate vect = splitString(str); scene.eyeX = strtof(vect[0].c_str(), 0); scene.eyeY = strtof(vect[1].c_str(), 0); scene.eyeZ = strtof(vect[2].c_str(), 0); getline(f, str); // get spot coordinate vect = splitString(str); scene.spotX = strtof(vect[0].c_str(), 0); scene.spotY = strtof(vect[1].c_str(), 0); scene.spotZ = strtof(vect[2].c_str(), 0); getline(f, str); // get up coordinate vect = splitString(str); scene.upX = strtof(vect[0].c_str(), 0); scene.upY = strtof(vect[1].c_str(), 0); scene.upZ = strtof(vect[2].c_str(), 0); getline(f, str); // get frustum info vect = splitString(str); scene.fov = strtof(vect[0].c_str(), 0); scene.aspect = strtof(vect[1].c_str(), 0); scene.near = strtof(vect[2].c_str(), 0); scene.far = strtof(vect[3].c_str(), 0); getline(f, str); // get ambient light vect = splitString(str); scene.ambientLight = Colorf(strtof(vect[0].c_str(), 0), strtof(vect[1].c_str(), 0), strtof(vect[2].c_str(), 0), 0.0f); while (getline(f, str)) { vect = splitString(str); if (vect.size() > 0) { if (vect[0] == "g") { TriangleArray a = TriangleArray(); geometry.push_back(vect[1]); scene.addObject(a); } else if (vect[0] == "c") { scene.getLastObj().KaKd = Colorf(strtof(vect[2].c_str(), 0), strtof(vect[3].c_str(), 0), strtof(vect[4].c_str(), 0), strtof(vect[1].c_str(), 0)); } else if (vect[0] == "p") { scene.getLastObj().Ks = Colorf(strtof(vect[1].c_str(), 0), strtof(vect[2].c_str(), 0), strtof(vect[3].c_str(), 0), strtof(vect[4].c_str(), 0)); } else if (vect[0] == "m") { scene.getLastObj().texture = vect[1]; } else if (vect[0] == "t") { Matrix4x4 m = translationMatrix(strtof(vect[1].c_str(), 0), strtof(vect[2].c_str(), 0), strtof(vect[3].c_str(), 0)); scene.getLastObj().transformations.push_back(m); } else if (vect[0] == "r") { Vector4f v(strtof(vect[2].c_str(), 0), strtof(vect[3].c_str(), 0), strtof(vect[4].c_str(), 0)); Matrix4x4 m = rotationMatrixAboutRandAxis(v, strtof(vect[1].c_str(), 0)); scene.getLastObj().transformations.push_back(m); } else if (vect[0] == "s") { Matrix4x4 m = scaleMatrix(strtof(vect[1].c_str(), 0), strtof(vect[2].c_str(), 0), strtof(vect[3].c_str(), 0)); scene.getLastObj().transformations.push_back(m); } else if (vect[0] == "l") { Light light(strtof(vect[1].c_str(), 0), strtof(vect[2].c_str(), 0), strtof(vect[3].c_str(), 0), strtof(vect[4].c_str(), 0), strtof(vect[5].c_str(), 0), strtof(vect[6].c_str(), 0)); scene.pointLight = light; } } } f.close(); //add vertex info to triangle array for (int i = 0; i < scene.size(); i++) { readObjFile(geometry[i].c_str(), scene.objects[i]); } return scene; } void readObjFile(const char * path, TriangleArray & arr) { std::ifstream f(path); if (!f) { std::cout << "Cannot open scene file" << std::endl; throw; } std::string str; while (getline(f, str)) { std::vector<std::string> vect = splitStringWithDelimiter(str, '/'); if (vect.size() > 0) { if (vect[0] == "v") { Vector4f v(strtof(vect[1].c_str(), 0), strtof(vect[2].c_str(), 0), strtof(vect[3].c_str(), 0)); arr.vertices.push_back(v); } else if (vect[0] == "vn") { Vector4f vn(strtof(vect[1].c_str(), 0), strtof(vect[2].c_str(), 0), strtof(vect[3].c_str(), 0), 0); arr.vertexNormal.push_back(vn); } else if (vect[0] == "vt") { Vector3f vt(strtof(vect[1].c_str(), 0), strtof(vect[2].c_str(), 0), strtof(vect[3].c_str(), 0)); arr.vertexTexture.push_back(vt); } else if (vect[0] == "f") { std::vector<int> face; if (vect.size() == 10) { // has texture data // index of vertices face.push_back(atoi(vect[1].c_str()) - 1); face.push_back(atoi(vect[4].c_str()) - 1); face.push_back(atoi(vect[7].c_str()) - 1); // index of normals face.push_back(atoi(vect[3].c_str()) - 1); face.push_back(atoi(vect[6].c_str()) - 1); face.push_back(atoi(vect[9].c_str()) - 1); // index of texture face.push_back(atoi(vect[2].c_str()) - 1); face.push_back(atoi(vect[5].c_str()) - 1); face.push_back(atoi(vect[8].c_str()) - 1); } else { // no texture data face.push_back(atoi(vect[1].c_str()) - 1); face.push_back(atoi(vect[3].c_str()) - 1); face.push_back(atoi(vect[5].c_str()) - 1); // index of normals face.push_back(atoi(vect[2].c_str()) - 1); face.push_back(atoi(vect[4].c_str()) - 1); face.push_back(atoi(vect[6].c_str()) - 1); } arr.faces.push_back(face); } } } } std::vector<std::string> splitStringWithDelimiter(std::string str, char c) { std::vector<std::string> vect; std::string substring; for (char & character : str) { if (character == c || character == ' ') { if (substring != "") { vect.push_back(substring); substring.clear(); } } else { substring += character; } } if (substring != "") { vect.push_back(substring); } return vect; }<file_sep>/RayTracer/Vector3f.h #pragma once #include <math.h> #include <string> class Vector3f { public: float x; float y; float z; Vector3f(); Vector3f(float X, float Y); Vector3f(float X, float Y, float Z); bool operator == (const Vector3f & V); bool operator != (const Vector3f & V); Vector3f operator + (const Vector3f & V); Vector3f operator - (const Vector3f & V); Vector3f operator * (float a); Vector3f operator / (float a); float operator * (const Vector3f & V); Vector3f operator - (); void normalize(); }; Vector3f operator *(float k, const Vector3f & V); std::ostream & operator << (std::ostream &os, Vector3f &V); <file_sep>/RayTracer/Raster.cpp #include "Raster.h" #include "CONSTANTS.h" Raster::Raster() { } Raster::Raster(int w, int h) { width = w; height = h; pixels = new PixelColor[width*height]; zBuffer = new float[width*height]; for (int i = 0; i < width*height; i++) { zBuffer[i] = -INFINITY; } } void Raster::clear() { PixelColor blackInt = { 0, 0, 0, 0 }; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { pixels[i * width + j] = blackInt; } } for (int i = 0; i < width*height; i++) { zBuffer[i] = -INFINITY; } } void Raster::writeToBMPFile(const char * path) { FILE * f = fopen(path, "wb"); if (f == NULL) { printf("Couldnt open file for writing!!"); return; } char b = 'B'; fwrite(&b, sizeof(char), 1, f); char m = 'M'; fwrite(&m, sizeof(char), 1, f); int fileSize = 54 + 3 * width * height; fwrite(&fileSize, sizeof(int), 1, f); char bfReserve[4] = { 0, 0, 0, 0 }; fwrite(bfReserve, 1, 4, f); int bfOffbits = 54; fwrite(&bfOffbits, sizeof(int), 1, f); int biSize = 40; fwrite(&biSize, sizeof(int), 1, f); fwrite(&width, sizeof(int), 1, f); fwrite(&height, sizeof(int), 1, f); uint16_t biPlanes = 1; fwrite(&biPlanes, 2, 1, f); uint16_t biBitCount = 24; fwrite(&biBitCount, 2, 1, f); int biCompression = 0; fwrite(&biCompression, sizeof(int), 1, f); int biSizeImage = 0; fwrite(&biSizeImage, sizeof(int), 1, f); int pixelPerMeter = 0; fwrite(&pixelPerMeter, sizeof(int), 1, f); fwrite(&pixelPerMeter, sizeof(int), 1, f); int biClrUsed = 0; fwrite(&biClrUsed, sizeof(int), 1, f); int biClrImportant = 0; fwrite(&biClrImportant, sizeof(int), 1, f); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { PixelColor pixelValue = pixels[y*width+x]; fwrite(&pixelValue.B, 1, 1, f); fwrite(&pixelValue.G, 1, 1, f); fwrite(&pixelValue.R, 1, 1, f); } } fclose(f); } void Raster::writeToPPMFile(const char * path) { FILE * f = fopen(path, "w"); if (f == NULL) { printf("Couldnt open file for writing!!"); return; } fprintf(f, "P3\n"); fprintf(f, "%i ", width); fprintf(f, "%i\n", height); fprintf(f, "%i\n", 255); for (int y = height - 1; y >= 0; y--) { for (int x = 0; x < width; x++) { fprintf(f, "%i ", pixels[y*width + x].R); fprintf(f, "%i ", pixels[y*width + x].G); fprintf(f, "%i ", pixels[y*width + x].B); } } fclose(f); } void getBarycentricCoordinate(Vector4f & v1, Vector4f & v2, Vector4f & v3, int X, int Y, float * l1, float * l2, float * l3) { float denonimator = (float)((v2.y - v3.y) * (v1.x - v3.x) + (v3.x - v2.x) * (v1.y - v3.y)); float lambda1 = ((v2.y - v3.y)*(X - v3.x) + (v3.x - v2.x)*(Y - v3.y)) / denonimator; float lambda2 = ((v3.y - v1.y)*(X - v3.x) + (v1.x - v3.x)*(Y - v3.y)) / denonimator; *l1 = lambda1; *l2 = lambda2; *l3 = 1 - lambda1 - lambda2; } void getBarycentricCoordinate2D(Vector3f & v1, Vector3f & v2, Vector3f & v3, int X, int Y, float * l1, float * l2, float * l3) { float denonimator = (float)((v2.y - v3.y) * (v1.x - v3.x) + (v3.x - v2.x) * (v1.y - v3.y)); float lambda1 = ((v2.y - v3.y)*(X - v3.x) + (v3.x - v2.x)*(Y - v3.y)) / denonimator; float lambda2 = ((v3.y - v1.y)*(X - v3.x) + (v1.x - v3.x)*(Y - v3.y)) / denonimator; *l1 = lambda1; *l2 = lambda2; *l3 = 1 - lambda1 - lambda2; }<file_sep>/RayTracer/Colorf.cpp #include "Colorf.h" Colorf::Colorf() { } Colorf::Colorf(float Rvalue, float Gvalue, float Bvalue, float Avalue) { R = Rvalue; G = Gvalue; B = Bvalue; A = Avalue; } Colorf Colorf::operator * (float k) { return Colorf(k*R, k*G, k*B, k*A); } Colorf Colorf::operator * (const Colorf & c) { return Colorf(c.R*R, c.G*G, c.B*B, c.A*A); } Colorf Colorf::operator + (const Colorf & c) { return Colorf(R + c.R, G + c.G, B + c.B, A + c.A); } Colorf operator * (float k, const Colorf & c) { return Colorf(k * c.R, k * c.G, k *c.B, k *c.A); } std::ostream & operator << (std::ostream &os, Colorf & p) { return os << "PixelColorf<" << p.R << ", " << p.G << ", " << p.B << ", " << p.A << ">"; } Colorf intColorToFloatColor(PixelColor & i) { return Colorf(i.R/255.0f, i.G/255.0f, i.B/255.0f, i.A/255.0f); } PixelColor floatColorToIntColor(Colorf & f) { PixelColor i; i.R = (uint8_t)floorf(f.R >= 1.0 ? 255 : f.R*256.0f); i.G = (uint8_t)floorf(f.G >= 1.0 ? 255 : f.G*256.0f); i.B = (uint8_t)floorf(f.B >= 1.0 ? 255 : f.B*256.0f); i.A = (uint8_t)floorf(f.A >= 1.0 ? 255 : f.A*256.0f); return i; }<file_sep>/RayTracer/Vector3f.cpp #include "Vector3f.h" #include "CONSTANTS.h" Vector3f::Vector3f() { } Vector3f::Vector3f(float X, float Y) { x = X; y = Y; z = 1.0f; } Vector3f::Vector3f(float X, float Y, float Z) { x = X; y = Y; z = Z; } bool Vector3f::operator == (const Vector3f & V) { return abs(x - V.x) <= CLOSE_VALUE && abs(y - V.y) <= CLOSE_VALUE; } bool Vector3f::operator != (const Vector3f & V) { return abs(x - V.x) > CLOSE_VALUE || abs(y - V.y) > CLOSE_VALUE; } Vector3f Vector3f::operator + (const Vector3f & V) { return Vector3f(x + V.x, y + V.y); } Vector3f Vector3f::operator - (const Vector3f & V) { return Vector3f(x - V.x, y - V.y); } Vector3f Vector3f::operator * (float a) { return Vector3f(a * x, a * y); } Vector3f Vector3f::operator / (float a) { return Vector3f(x / a, y / a); } float Vector3f::operator * (const Vector3f & V) { return x * V.x + y * V.y; } Vector3f Vector3f::operator - () { return Vector3f(-x, -y); } void Vector3f::normalize() { float magnitude = sqrtf(x * x + y * y); x = x / magnitude; y = y / magnitude; } Vector3f operator *(float k, const Vector3f & V) { return Vector3f(k * V.x, k * V.y); } std::ostream & operator << (std::ostream &os, Vector3f &V) { return os << "Vector3f<" << V.x << ", " << V.y << ", " << V.z << ">"; } <file_sep>/RayTracer/CONSTANTS.h #pragma once #define CLOSE_VALUE 0.00001f #define PI 3.14159265<file_sep>/RayTracer/Matrix4x4.cpp #include "Matrix4x4.h" Matrix4x4::Matrix4x4() { } Matrix4x4::Matrix4x4(float e11, float e21, float e31, float e41, float e12, float e22, float e32, float e42, float e13, float e23, float e33, float e43, float e14, float e24, float e34, float e44) { this->e11 = e11; this->e21 = e21; this->e31 = e31; this->e41 = e41; this->e12 = e12; this->e22 = e22; this->e32 = e32; this->e42 = e42; this->e13 = e13; this->e23 = e23; this->e33 = e33; this->e43 = e43; this->e14 = e14; this->e24 = e24; this->e34 = e34; this->e44 = e44; } Matrix4x4 Matrix4x4::operator * (float k) { return Matrix4x4(k*e11, k*e21, k*e31, k*e41, k*e12, k*e22, k*e32, k*e42, k*e13, k*e23, k*e33, k*e43, k*e14, k*e24, k*e34, k*e44); } Matrix4x4 Matrix4x4::operator / (float k) { return Matrix4x4(e11/k, e21/k, e31/k, e41/k, e12/k, e22/k, e32/k, e42/k, e13/k, e23/k, e33/k, e43/k, e14/k, e24/k, e34/k, e44/k); } Matrix4x4 Matrix4x4::operator * (const Matrix4x4 & m) { float c11 = e11 * m.e11 + e21 * m.e12 + e31 * m.e13 + e41 * m.e14; float c21 = e11 * m.e21 + e21 * m.e22 + e31 * m.e23 + e41 * m.e24; float c31 = e11 * m.e31 + e21 * m.e32 + e31 * m.e33 + e41 * m.e34; float c41 = e11 * m.e41 + e21 * m.e42 + e31 * m.e43 + e41 * m.e44; float c12 = e12 * m.e11 + e22 * m.e12 + e32 * m.e13 + e42 * m.e14; float c22 = e12 * m.e21 + e22 * m.e22 + e32 * m.e23 + e42 * m.e24; float c32 = e12 * m.e31 + e22 * m.e32 + e32 * m.e33 + e42 * m.e34; float c42 = e12 * m.e41 + e22 * m.e42 + e32 * m.e43 + e42 * m.e44; float c13 = e13 * m.e11 + e23 * m.e12 + e33 * m.e13 + e43 * m.e14; float c23 = e13 * m.e21 + e23 * m.e22 + e33 * m.e23 + e43 * m.e24; float c33 = e13 * m.e31 + e23 * m.e32 + e33 * m.e33 + e43 * m.e34; float c43 = e13 * m.e41 + e23 * m.e42 + e33 * m.e43 + e43 * m.e44; float c14 = e14 * m.e11 + e24 * m.e12 + e34 * m.e13 + e44 * m.e14; float c24 = e14 * m.e21 + e24 * m.e22 + e34 * m.e23 + e44 * m.e24; float c34 = e14 * m.e31 + e24 * m.e32 + e34 * m.e33 + e44 * m.e34; float c44 = e14 * m.e41 + e24 * m.e42 + e34 * m.e43 + e44 * m.e44; return Matrix4x4(c11, c21, c31, c41, c12, c22, c32, c42, c13, c23, c33, c43, c14, c24, c34, c44); } Vector4f Matrix4x4::operator * (const Vector4f & V) { float x = e11 * V.x + e21 * V.y + e31 * V.z + e41 * V.w; float y = e12 * V.x + e22 * V.y + e32 * V.z + e42 * V.w; float z = e13 * V.x + e23 * V.y + e33 * V.z + e43 * V.w; float w = e14 * V.x + e24 * V.y + e34 * V.z + e44 * V.w; return Vector4f(x, y, z, w); } void Matrix4x4::identityMatrix() { e11 = 1.0f; e21 = 0.0f; e31 = 0.0f; e41 = 0.0f; e12 = 0.0f, e22 = 1.0f; e32 = 0.0f; e42 = 0.0f; e13 = 0.0f; e23 = 0.0f; e33 = 1.0f; e43 = 0.0f; e14 = 0.0f; e24 = 0.0f; e34 = 0.0f; e44 = 1.0f; } Matrix4x4 operator *(float k, const Matrix4x4 & m) { return Matrix4x4(k*m.e11, k*m.e21, k*m.e31, k*m.e41, k*m.e12, k*m.e22, k*m.e32, k*m.e42, k*m.e13, k*m.e23, k*m.e33, k*m.e43, k*m.e14, k*m.e24, k*m.e34, k*m.e44); } std::ostream & operator << (std::ostream &os, Matrix4x4 &m) { return os << "Matrix4x4<" << m.e11 << ", " << m.e21 << ", " << m.e31 << ", " << m.e41 << "\n " << m.e12 << ", " << m.e22 << ", " << m.e32 << ", " << m.e42 << "\n " << m.e13 << ", " << m.e23 << ", " << m.e33 << ", " << m.e43 << "\n " << m.e14 << ", " << m.e24 << ", " << m.e34 << ", " << m.e44 << ">"; } Matrix4x4 scaleMatrix(float sx, float sy, float sz) { return Matrix4x4( sx, 0.0f, 0.0f, 0.0f, 0.0f, sy, 0.0f, 0.0f, 0.0f, 0.0f, sz, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); } Matrix4x4 translationMatrix(float tx, float ty, float tz) { return Matrix4x4(1.0f, 0.0f, 0.0f, tx, 0.0f, 1.0f, 0.0f, ty, 0.0f, 0.0f, 1.0f, tz, 0.0f, 0.0f, 0.0f, 1.0f ); } Matrix4x4 rotationMatrixAboutX(float theta) { float cosTheta = cosf(theta); float sinTheta = sinf(theta); return Matrix4x4(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, cosTheta, -sinTheta, 0.0f, 0.0f, sinTheta, cosTheta, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } Matrix4x4 rotationMatrixAboutY(float theta) { float cosTheta = cosf(theta); float sinTheta = sinf(theta); return Matrix4x4(cosTheta, 0.0f, sinTheta, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -sinTheta, 0.0f, cosTheta, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } Matrix4x4 rotationMatrixAboutZ(float theta) { float cosTheta = cosf(theta); float sinTheta = sinf(theta); return Matrix4x4(cosTheta, -sinTheta, 0.0f, 0.0f, sinTheta, cosTheta, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); } Matrix4x4 rotationMatrixAboutRandAxis(Vector4f N, float theta) { N.normalize(); float cosTheta = cosf(theta); float sinTheta = sinf(theta); float oneMinusCosTheta = 1.0f - cosTheta; float x = N.x; float y = N.y; float z = N.z; float a11 = x * x * oneMinusCosTheta + cosTheta; float a21 = x * y * oneMinusCosTheta - z * sinTheta; float a31 = x * z * oneMinusCosTheta + y * sinTheta; float a12 = x * y * oneMinusCosTheta + z * sinTheta; float a22 = y * y * oneMinusCosTheta + cosTheta; float a32 = y * z * oneMinusCosTheta - x * sinTheta; float a13 = x * z * oneMinusCosTheta - y * sinTheta; float a23 = y * z * oneMinusCosTheta + x * sinTheta; float a33 = z * z * oneMinusCosTheta + cosTheta; return Matrix4x4(a11, a21, a31, 0.0f, a12, a22, a32, 0.0f, a13, a23, a33, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } Matrix4x4 cameraMatrix(Vector4f & eyeVect, Vector4f & spotVect, Vector4f & upVect) { Vector4f look = spotVect - eyeVect; look.normalize(); Vector4f right = crossProduct(look, upVect); right.normalize(); Vector4f up = crossProduct(right, look); float rx = right.x, ry = right.y, rz = right.z; float ux = up.x, uy = up.y, uz = up.z; float lx = look.x, ly = look.y, lz = look.z; float ex = eyeVect.x, ey = eyeVect.y, ez = eyeVect.z; return Matrix4x4( rx, ry, rz, -rx * ex - ry * ey - rz * ez, ux, uy, uz, -ux * ex - uy * ey - uz * ez, -lx, -ly, -lz, lx * ex + ly * ey + lz * ez, 0.0f, 0.0f, 0.0f, 1.0f ); } Matrix4x4 orthoProjectionMatrix(float l, float r, float b, float t, float n, float f) { return Matrix4x4( 2.0f/(r - l), 0.0f, 0.0f, (r + l)/(l - r), 0.0f, 2/(t-b), 0.0f, (t+b)/(b-t), 0.0f, 0.0f, 2.0f/(n-f), (f+n)/(n-f), 0.0f, 0.0f, 0.0f, 1.0f ); } Matrix4x4 viewportMatrix(float w, float h) { return Matrix4x4(w/2.0f, 0.0f, 0.0f, w/2.0f, 0.0f, h/2.0f, 0.0f, h/2.0f, 0.0f, 0.0f, 1.0f, 0.0f, // shouldnt this be 0? but if it is, I dont have any info to do z-buffering 0.0f, 0.0f, 0.0f, 1.0f); } Matrix4x4 frustumMatrix(float l, float r, float b, float t, float n, float f) { return Matrix4x4( 2*n/(r-l), 0.0f, (r+l)/(r-l), 0.0f, 0.0f, 2*n/(t-b), (t+b)/(t-b), 0.0f, 0.0f, 0.0f, -(f+n)/(f-n), -2*f*n/(f-n), 0.0f, 0.0f, -1.0f, 0.0f ); } Matrix4x4 perspectiveProjectionMatrix(float fovy, float a, float n, float f) { float tangent = tanf(fovy/2); float deltaZ = f - n; return Matrix4x4( 1/(tangent * a), 0.0f, 0.0f, 0.0f, 0.0f, 1/tangent, 0.0f, 0.0f, 0.0f, 0.0f, -(f+n)/deltaZ, -2*n*f/deltaZ, 0.0f, 0.0f, -1.0f, 0.0f ); }<file_sep>/RayTracer/PixelColor.cpp #include "PixelColor.h" PixelColor::PixelColor() { } PixelColor::PixelColor(int Rvalue, int Gvalue, int Bvalue, int Avalue) { R = Rvalue; G = Gvalue; B = Bvalue; A = Avalue; } PixelColor PixelColor::operator * (float k) { // this causes loss of precision. might need to rewrite return PixelColor((int)(k*R), (int)(k*G), (int)(k*B), (int)(k*A)); } PixelColor PixelColor::operator + (const PixelColor & c) { return PixelColor(R + c.R, G + c.G, B + c.B, A + c.A); } PixelColor operator * (float k, const PixelColor & c) { // this causes loss of precision. might need to rewrite later return PixelColor((int) (k * c.R), (int)(k * c.G), (int)(k *c.B), (int)(k *c.A)); } std::ostream & operator << (std::ostream &os, PixelColor &p) { return os << "PixelColor<" << (unsigned)p.R << ", " << (unsigned)p.G << ", " << (unsigned)p.B << ", " << (unsigned)p.A << ">"; } <file_sep>/RayTracer/Scene.h #pragma once #include <vector> #include "TriangleArray.h" #include <string> #include "Raster.h" #include "Light.h" class Scene { public: int rasterWidth, rasterHeight; float eyeX, eyeY, eyeZ; float spotX, spotY, spotZ; float upX, upY, upZ; float fov, aspect, near, far; Colorf ambientLight; Light pointLight; std::vector<TriangleArray> objects; Scene(); void addObject(TriangleArray & ta); TriangleArray & getLastObj(); int size(); // size of instance member object void draw(Raster & raster); }; Raster readBitMapFile(const char * path);<file_sep>/RayTracer/Light.h #pragma once #include "Vector4f.h" #include "Colorf.h" class Light { public: Vector4f position; Colorf LdLs; // Ld and Ls, intensity Light(); Light(float x, float y, float z, float r, float g, float b); };<file_sep>/RayTracer/Vector4f.cpp #include "Vector4f.h" #include <iostream> Vector4f::Vector4f() { } Vector4f::Vector4f(float X, float Y, float Z) { x = X; y = Y; z = Z; w = 1.0f; } Vector4f::Vector4f(float X, float Y, float Z, float W) { x = X; y = Y; z = Z; w = W; } bool Vector4f::operator == (const Vector4f & V) { return abs(x - V.x) <= CLOSE_VALUE && (y - V.y) <= CLOSE_VALUE && (z - V.z) <= CLOSE_VALUE; } bool Vector4f::operator != (const Vector4f & V) { return abs(x - V.x) > CLOSE_VALUE || abs(y - V.y) > CLOSE_VALUE || (z - V.z) > CLOSE_VALUE; } Vector4f Vector4f::operator + (const Vector4f & V) { return Vector4f(x + V.x, y + V.y, z + V.z, w); } Vector4f Vector4f::operator - (const Vector4f & V) { return Vector4f(x - V.x, y - V.y, z - V.z, w); } Vector4f Vector4f::operator * (float a) { return Vector4f(a * x, a * y, a* z, w); } Vector4f Vector4f::operator / (float a) { return Vector4f(x / a, y / a, z / a, w); } float Vector4f::operator * (const Vector4f & V) { return x * V.x + y * V.y + z * V.z; } Vector4f Vector4f::operator - () { return Vector4f(-x, -y, -z, w); } void Vector4f::zero() { x = y = z = 0.0f; w = 1.0f; } void Vector4f::normalize() { float magnitude = sqrtf(x * x + y * y + z * z); x = x / magnitude; y = y / magnitude; z = z / magnitude; } void Vector4f::homogenize() { x = x / w; y = y / w; z = z / w; w = w / w; } Vector4f operator *(float k, const Vector4f & V) { return Vector4f(k * V.x, k * V.y, k * V.z, V.w); } std::ostream & operator << (std::ostream &os, Vector4f &V) { return os << "Vector4f<" << V.x << ", " << V.y << ", " << V.z << ", " << V.w << ">"; } Vector4f crossProduct(Vector4f & v1, Vector4f & v2) { return Vector4f(v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x, v1.w); }<file_sep>/RayTracer/Helper.h #pragma once #include <string> #include <vector> #include "TriangleArray.h" #include <iostream> #include <fstream> #include "Scene.h" #include "Light.h" std::vector<std::string> splitString(std::string str); std::vector<std::string> splitStringWithDelimiter(std::string str, char c); void readObjFile(const char * path, TriangleArray & arr); Scene readSceneFile(const char * path); <file_sep>/RayTracer/TriangleArray.h #pragma once #include <vector> #include "Colorf.h" #include "Matrix4x4.h" #include "Vector3f.h" class TriangleArray { public: // does it need destructor? std::vector<std::vector<int>> faces; Colorf KaKd; // essentially color of object Colorf Ks; // object's shininess, specular coefficent std::vector<Vector4f> vertices; std::vector<Vector4f> vertexNormal; std::vector<Vector3f> vertexTexture; std::vector<Matrix4x4> transformations; std::string texture; int culledTriangle = 0; TriangleArray(); //~TriangleArray(); std::vector<int> operator[](int index); int size(); }; <file_sep>/RayTracer/TriangleArray.cpp #include "TriangleArray.h" TriangleArray::TriangleArray() { } std::vector<int> TriangleArray::operator[](int index) { if (index >= faces.size()) { std::cout << "Index out of bound"; throw; } return faces[index]; } int TriangleArray::size() { return faces.size(); } <file_sep>/RayTracer/Matrix3x3.h #pragma once #include <math.h> #include "Vector3f.h" #include "CONSTANTS.h" #define IDENTITYMATRIX3X3 Matrix3x3(1.0f, 0.0f, 0.0f, \ 0.0f, 1.0f, 0.0f, \ 0.0f, 0.0f, 1.0f) class Matrix3x3 { // column matrix public: float e11, e21, e31; float e12, e22, e32; float e13, e23, e33; Matrix3x3(); // construct an identity matrix Matrix3x3(float e11, float e21, float e31, float e12, float e22, float e32, float e13, float e23, float e33); Matrix3x3 operator * (float k); Matrix3x3 operator / (float k); Matrix3x3 operator * (const Matrix3x3 & m); Vector3f operator * (const Vector3f & V); void identityMatrix(); float getDeterminant(); }; Matrix3x3 operator *(float k, const Matrix3x3 & m); std::ostream & operator << (std::ostream &os, Matrix3x3 &m); Matrix3x3 rotationMatrix(float theta); Matrix3x3 translationMatrix(float tx, float ty); Matrix3x3 scaleMatrix(float sx, float sy); <file_sep>/RayTracer/Light.cpp #include "Light.h" Light::Light() { } Light::Light(float x, float y, float z, float r, float g, float b) { LdLs = Colorf(r, g, b, 0.0f); position = Vector4f(x, y, z); }
cc176f094f51b2514793b2c98ffd6f4d64247684
[ "Markdown", "C", "C++" ]
25
C++
ManhHuuNguyen/SoftwareRasterizer
df74d940714d36ee03571ae68d985a8a59a8b722
8917cb228a3f739270421e1d3d26b9b1f7ecfcca
refs/heads/master
<repo_name>MaceTheAce/MaceTheAce.github.io<file_sep>/mainproject/index.php <?php if(isset($_POST['register_submit'])) { $username = $_POST['username']; $password = $_POST['<PASSWORD>']; $confirm_password = $_POST['<PASSWORD>_password']; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!-- This file has been downloaded from Bootsnipp.com. Enjoy! --> <title>Registration/Login</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet"> <!CSS> <style type="text/css"> #regContainer{ margin-top: 3%; } .panel-login { border-color: #ccc; background-color: #f9f8f8; -webkit-box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.2); -moz-box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.2); box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.2); } .panel-login>.panel-heading { text-align:center; } .panel-login>.panel-heading a{ text-decoration: none; font-weight: bold; font-size: 28px; -webkit-transition: all 0.1s linear; -moz-transition: all 0.1s linear; transition: all 0.1s linear; } .panel-login>.panel-heading a.active{ font-size: 34px; } .panel-login>.panel-heading hr{ margin-top: 10px; margin-bottom: 0px; clear: both; border: 0; height: 1px; background-image: -webkit-linear-gradient(left,rgba(0, 0, 0, 0),rgba(0, 0, 0, 0.15),rgba(0, 0, 0, 0)); background-image: -moz-linear-gradient(left,rgba(0,0,0,0),rgba(0,0,0,0.15),rgba(0,0,0,0)); background-image: -ms-linear-gradient(left,rgba(0,0,0,0),rgba(0,0,0,0.15),rgba(0,0,0,0)); background-image: -o-linear-gradient(left,rgba(0,0,0,0),rgba(0,0,0,0.15),rgba(0,0,0,0)); } .panel-login input[type="text"],.panel-login input[type="email"],.panel-login input[type="password"],.panel-login input[type="grade"] { height: 45px; border: 1px solid #ddd; font-size: 16px; -webkit-transition: all 0.1s linear; -moz-transition: all 0.1s linear; transition: all 0.1s linear; } .panel-login input:hover, .panel-login input:focus { outline:none; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; border-color: #ccc; } .btn-login { background-color:#3D9DB3; outline: none; color: #fff; font-size: 14px; height: auto; font-weight: normal; padding: 14px 0; text-transform: uppercase; border-color: #2d92a9; } .btn-login:hover, .btn-login:focus { color: #fff; background-color: #198da8; border-color: #53A3CD; } .btn-register { background-color: #17ae47; outline: none; color: #fff; font-size: 14px; height: auto; font-weight: normal; padding: 14px 0; text-transform: uppercase; border-color: #1CB94A; } .btn-register:hover, .btn-register:focus { color: #fff; background-color: #1CA347; border-color: #1CA347; } .fullscreen_bg { position: fixed; top: 0; right: 0; bottom: 0; left: 0; background-size: cover; background-position: 50% 50%; background-image: url('https://jointgroup.es/wp-content/uploads/2016/11/joint-network-group.jpg'); background-repeat:repeat; } .panel-heading a{ font-size: 48px; color: rgb(6, 106, 117); padding: 2px 0 10px 0; font-family: 'FranchiseRegular','Arial Narrow',Arial,sans-serif; font-weight: bold; text-align: center; padding-bottom: 30px; } .panel-heading a{ background: -webkit-repeating-linear-gradient(-45deg, rgb(18, 83, 93) , rgb(18, 83, 93) 20px, rgb(64, 111, 118) 20px, rgb(64, 111, 118) 40px, rgb(18, 83, 93) 40px); -webkit-text-fill-color: transparent; -webkit-background-clip: text; } input[type="radio"]{ margin: 0 0px 0 10px; } </style> <!HTML> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> </head> <body> <div id="fullscreen_bg" class="fullscreen_bg"/> <div id="regContainer" class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="panel panel-login"> <div class="panel-heading"> <div class="row"> <div class="col-xs-6"> <a href="#" class="active" id="login-form-link">Login</a> </div> <div class="col-xs-6"> <a href="#" id="register-form-link">Register</a> </div> </div> <hr> </div> <div class="panel-body"> <div class="row"> <div class="col-lg-12"> <form id="login-form" action="#" method="POST" role="form" style="display: block;"> <div class="form-group"> <label for="username">Username</label> <input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value=""> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="<PASSWORD>"> </div> <div class="form-group text-center"> <input type="checkbox" tabindex="3" class="" name="remember" id="remember"> <label for="remember"> Remember Me</label> </div> <div class="form-group"> <div class="row"> <div class="col-sm-6 col-sm-offset-3"> <input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-login" value="Log In"> </div> </div> </div> </form> <form id="register-form" action="#" method="POST" role="form" style="display: none;"> <div class="form-group"> <label for="username">Full Name</label> <input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="First & Last Name" value=""> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password"> </div> <div class="form-group"> <label for="confirm-password">Confirm password</label> <input type="password" name="confirm_password" id="confirm_password" tabindex="2" class="form-control" placeholder="Confirm Password"> </div> <div class="form-group"> <label for="grade">What grade are you in?</label> <br><input type="radio" name="grade" value="9"> 9 <input type="radio" name="grade" value="10"> 10 <input type="radio" name="grade" value="11"> 11 <input type="radio" name="grade" value="12"> 12 </div> <div class="form-group"> <label for="class">What are you more into?</label> <br><input type="radio" name="class" value="education"> Education <input type="radio" name="class" value="clubs"> Clubs <input type="radio" name="class" value="sports"> Sports </div> <div class="form-group"> <div class="row"> <div class="col-sm-6 col-sm-offset-3"> <input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now"> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> </div> <!JavaScript> <script type="text/javascript"> $(function() { $('#login-form-link').click(function(e) { $("#login-form").delay(100).fadeIn(100); $("#register-form").fadeOut(100); $('#register-form-link').removeClass('active'); $(this).addClass('active'); e.preventDefault(); }); $('#register-form-link').click(function(e) { $("#register-form").delay(100).fadeIn(100); $("#login-form").fadeOut(100); $('#login-form-link').removeClass('active'); $(this).addClass('active'); e.preventDefault(); }); }); </script> </body> </html>
de48a701dff532e609b1da18a352167cb37a9e1c
[ "PHP" ]
1
PHP
MaceTheAce/MaceTheAce.github.io
a7148fc05a2630ecc3f79db873d8fb4fc06170a9
daa02dbd0df136540bc220a7e2c0d03901d63107
refs/heads/master
<file_sep><?php class Delete_Status_From_Users_Table { public function up() { Schema::table('users', function($table) { $table->drop_column('status'); }); } public function down() { Schema::table('users', function($table) { $table->string('status'); }); } }<file_sep><?php class Create_Project_User_Table { public function up() { Schema::create('project_user', function($table) { $table->increments('id'); $table->integer('user_id'); $table->integer('project_id'); $table->timestamps(); }); } public function down() { Schema::drop('project_user'); } }<file_sep><?php class User extends Eloquent { //public static $timestamps = false; public function roles() { return $this->has_many_and_belongs_to('Role'); } public function jobs() { return $this->has_many('Job'); } public function projects() { return $this->has_many_and_belongs_to('Project'); } }<file_sep><?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Simply tell Laravel the HTTP verbs and URIs it should respond to. It is a | breeze to setup your application using Laravel's RESTful routing and it | is perfectly suited for building large applications and simple APIs. | | Let's respond to a simple GET request to http://example.com/hello: | | Route::get('hello', function() | { | return 'Hello World!'; | }); | | You can even respond to more than one URI: | | Route::post(array('hello', 'world'), function() | { | return 'Hello World!'; | }); | | It's easy to allow URI wildcards using (:num) or (:any): | | Route::put('hello/(:any)', function($name) | { | return "Welcome, $name."; | }); | */// user Resource Route::get('users', array('as' => 'users', 'before'=>'auth','uses' => 'users@index')); Route::get('/users/(:num)/projects', array('as' => 'user_projects', 'uses' => 'users@projects')); Route::get('/users/(:num)/jobs', array('as' => 'user_jobs', 'uses' => 'users@jobs')); Route::get('users/new/(:num)', array('as'=>'add_new_user', 'uses'=>'users@new')); Route::get('users/new', array('as' => 'new_user', 'uses' => 'users@new')); Route::get('users/(:any)', array('as' => 'user', 'uses' => 'users@show')); Route::get('projects/(:num)/users/(:num)', array('as' => 'single_user', 'uses' => 'users@single')); Route::get('users/(:any)/edit', array('as' => 'edit_user', 'uses' => 'users@edit')); Route::put('users/update', 'users@update'); Route::get('users/(:any)/delete', 'projects@destroy'); // job Resource Route::get('jobs', array('as' => 'jobs', 'uses' => 'jobs@index')); Route::get('jobs/(:any)/delete', 'jobs@destroy'); Route::get('jobs/new/(:num)', array('as'=>'new_job', 'uses'=>'jobs@new')); Route::get('jobs/(:num)', array('as' => 'job', 'uses' => 'jobs@show')); Route::get('jobs/(:any)/edit', array('as' => 'edit_job', 'uses' => 'jobs@edit')); Route::post('jobs', 'jobs@create'); Route::put('jobs/update', 'jobs@update'); Route::get('jobs/(:any)/reassign', 'jobs@reassign'); Route::put('jobs/reassign', 'jobs@reassign'); Route::get('jobs/(:any)/close', 'jobs@close'); Route::put('jobs/close', 'jobs@close'); Route::get('jobs/(:any)/desc', 'jobs@desc'); //Registering Routes Route::get('register', array('as' => 'new_user', 'uses' => 'users@new')); Route::post('register', array('before'=>'csrf', 'uses' => 'users@create')); //Logining in Routes Route::get('login', array('as' => 'login', 'uses' => 'users@login')); Route::post('login', array('before'=>'csrf','uses'=>'users@login')); //Logout Route::get('logout', array('as' => 'logout', 'uses' => 'users@logout')); // project Resource Route::get('projects', array('as' => 'projects','before'=>'auth', 'uses' => 'projects@index')); Route::get('projects/(:any)', array('as' => 'project', 'uses' => 'projects@show')); Route::get('/projects/(:num)/jobs', array('as' => 'project_jobs', 'uses' => 'projects@jobs')); Route::get('users/(:num)/projects/(:num)', array('as' => 'single_project', 'uses' => 'projects@single')); Route::get('users/(:num)/jobs/(:num)', array('as' => 'single_job', 'uses' => 'jobs@single')); Route::get('projects/new', array('as' => 'new_project', 'uses' => 'projects@new')); Route::get('projects/(:any)/edit', array('as' => 'edit_project', 'uses' => 'projects@edit')); Route::get('projects/(:num)/members', array('as' => 'project_members', 'uses' => 'projects@members')); Route::post('projects', 'projects@create'); Route::put('projects/update', 'projects@update'); Route::get('projects/(:any)/delete', 'projects@destroy'); Route::get('projects/(:any)/desc', 'projects@desc'); Route::get('projects/(:any)/reassign', 'projects@reassign'); Route::put('projects/reassign', 'projects@reassign'); Route::get('projects/(:any)/close', 'projects@close'); Route::put('projects/close', 'projects@close'); //Home Routes Route::get('/',array('as'=>'home', 'uses'=>'home@index')); //Authenticate //Route::filter('pattern: users/*', 'auth'); Route::filter('pattern: projects/*', 'auth'); Route::filter('pattern: jobs/*', 'auth'); //Route::filter('pattern: /*', 'auth'); /* |-------------------------------------------------------------------------- | Application 404 & 500 Error Handlers |-------------------------------------------------------------------------- | | To centralize and simplify 404 handling, Laravel uses an awesome event | system to retrieve the response. Feel free to modify this function to | your tastes and the needs of your application. | | Similarly, we use an event to handle the display of 500 level errors | within the application. These errors are fired when there is an | uncaught exception thrown in the application. | */ Event::listen('404', function() { return Response::error('404'); }); Event::listen('500', function() { return Response::error('500'); }); /* |-------------------------------------------------------------------------- | Route Filters |-------------------------------------------------------------------------- | | Filters provide a convenient method for attaching functionality to your | routes. The built-in before and after filters are called before and | after every request to your application, and you may even create | other filters that can be attached to individual routes. | | Let's walk through an example... | | First, define a filter: | | Route::filter('filter', function() | { | return 'Filtered!'; | }); | | Next, attach the filter to a route: | | Router::register('GET /', array('before' => 'filter', function() | { | return 'Hello World!'; | })); | */ Route::filter('before', function() { // Do stuff before every request to your application... }); Route::filter('after', function($response) { // Do stuff after every request to your application... }); Route::filter('csrf', function() { if (Request::forged()) return Response::error('500'); }); Route::filter('auth', function() { if (Auth::guest()) return Redirect::to('login'); });<file_sep><!-- application/views/template.php --> <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>My Ajax Page</title> </head> <body> <div id="content"> <p>Hello and welcome to the site!</p> </div> <a href="#" id="load-content">Load Content</a> <!-- javascript files --> <script type="text/javascript">var BASE = "<?php echo URL::base(); ?>";</script> <?php echo HTML::script('js/vendors/jquery-latest.js'); ?> <?php echo HTML::script('js/script.js'); ?> </body> </html><file_sep><?php class Project extends Eloquent { public static $timestamps = false; public function jobs() { return $this->has_many('Job'); } public function users() { return $this->has_many_and_belongs_to('User'); } }<file_sep>-- MySQL dump 10.13 Distrib 5.5.28, for debian-linux-gnu (i686) -- -- Host: localhost Database: imanage -- ------------------------------------------------------ -- Server version 5.5.28-0ubuntu0.12.10.2 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `comments` -- DROP TABLE IF EXISTS `comments`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `comments` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(200) NOT NULL, `body` varchar(200) NOT NULL, `author_id` int(11) NOT NULL, `d_id` int(11) NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `comments` -- LOCK TABLES `comments` WRITE; /*!40000 ALTER TABLE `comments` DISABLE KEYS */; /*!40000 ALTER TABLE `comments` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `create` -- DROP TABLE IF EXISTS `create`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `create` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(200) NOT NULL, `body` varchar(200) NOT NULL, `author_id` int(11) NOT NULL, `project_id` int(11) NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `create` -- LOCK TABLES `create` WRITE; /*!40000 ALTER TABLE `create` DISABLE KEYS */; /*!40000 ALTER TABLE `create` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `discussions` -- DROP TABLE IF EXISTS `discussions`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `discussions` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(200) NOT NULL, `body` varchar(200) NOT NULL, `author_id` int(11) NOT NULL, `project_id` int(11) NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `discussions` -- LOCK TABLES `discussions` WRITE; /*!40000 ALTER TABLE `discussions` DISABLE KEYS */; /*!40000 ALTER TABLE `discussions` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `jobs` -- DROP TABLE IF EXISTS `jobs`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `jobs` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(200) NOT NULL, `shortdesc` varchar(200) DEFAULT NULL, `desc` varchar(200) NOT NULL, `project_id` int(11) DEFAULT NULL, `user_id` int(11) DEFAULT NULL, `startdate` datetime NOT NULL, `enddate` datetime NOT NULL, `status` varchar(200) NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, `thumb` varchar(200) DEFAULT 'img/task.png', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `jobs` -- LOCK TABLES `jobs` WRITE; /*!40000 ALTER TABLE `jobs` DISABLE KEYS */; INSERT INTO `jobs` VALUES (1,'Photoshop Design',NULL,'detailed desc goes here',5,11,'2013-03-02 00:00:00','2013-03-04 00:00:00','On Progress','2013-02-19 17:52:35','2013-02-19 18:06:08','img/task.png'),(2,'editing the logo',NULL,'the front end of the site is dedicatly given to one developer ',6,11,'2013-03-02 00:00:00','2013-03-04 00:00:00','On Progress','2013-02-20 05:19:05','2013-02-20 05:19:05','img/task.png'); /*!40000 ALTER TABLE `jobs` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `laravel_migrations` -- DROP TABLE IF EXISTS `laravel_migrations`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `laravel_migrations` ( `bundle` varchar(50) NOT NULL, `name` varchar(200) NOT NULL, `batch` int(11) NOT NULL, PRIMARY KEY (`bundle`,`name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `laravel_migrations` -- LOCK TABLES `laravel_migrations` WRITE; /*!40000 ALTER TABLE `laravel_migrations` DISABLE KEYS */; INSERT INTO `laravel_migrations` VALUES ('application','2013_02_03_201651_create_users_table',1),('application','2013_02_03_232227_add_thumb_to_users_table',2),('application','2013_02_05_152602_delete_status_from_users_table',3),('application','2013_02_05_171329_delete_thumb_from_users_table',4),('application','2013_02_08_170158_create_projects_table',5),('application','2013_02_08_170404_delete_column_role_from_users_table',6),('application','2013_02_08_170711_create_roles_table',7),('application','2013_02_08_171922_create_role_user_table',8),('application','2013_02_08_182231_create_tasks_table',9),('application','2013_02_09_175459_create_project_user_table',10),('application','2013_02_19_142051_create_table_discussions',11),('application','2013_02_19_142421_create_discussions_table',12),('application','2013_02_19_142858_create_comments_table',13); /*!40000 ALTER TABLE `laravel_migrations` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `project_user` -- DROP TABLE IF EXISTS `project_user`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `project_user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `project_id` int(11) NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `project_user` -- LOCK TABLES `project_user` WRITE; /*!40000 ALTER TABLE `project_user` DISABLE KEYS */; INSERT INTO `project_user` VALUES (11,9,5,'2013-02-19 17:40:29','2013-02-19 17:40:29'),(12,13,5,'2013-02-19 17:40:29','2013-02-19 17:40:29'),(13,11,5,'2013-02-19 17:52:35','2013-02-19 17:52:35'),(14,9,6,'2013-02-20 05:14:57','2013-02-20 05:14:57'),(15,13,6,'2013-02-20 05:14:57','2013-02-20 05:14:57'),(16,11,6,'2013-02-20 05:19:05','2013-02-20 05:19:05'); /*!40000 ALTER TABLE `project_user` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `projects` -- DROP TABLE IF EXISTS `projects`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `projects` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(200) NOT NULL, `shortdesc` varchar(200) DEFAULT NULL, `desc` varchar(200) NOT NULL, `sup_id` int(11) DEFAULT NULL, `pm_id` int(11) DEFAULT NULL, `startdate` datetime NOT NULL, `enddate` datetime NOT NULL, `status` varchar(200) NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, `thumb` varchar(200) DEFAULT 'img/project.png', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `projects` -- LOCK TABLES `projects` WRITE; /*!40000 ALTER TABLE `projects` DISABLE KEYS */; INSERT INTO `projects` VALUES (6,'Website Design','a website for a start up company','this start up company is known Dasna plc',9,13,'2013-03-02 00:00:00','2013-03-04 00:00:00','On Progress','0000-00-00 00:00:00','0000-00-00 00:00:00','img/project.png'); /*!40000 ALTER TABLE `projects` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `role_user` -- DROP TABLE IF EXISTS `role_user`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `role_user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `role_id` int(11) NOT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `role_user` -- LOCK TABLES `role_user` WRITE; /*!40000 ALTER TABLE `role_user` DISABLE KEYS */; INSERT INTO `role_user` VALUES (25,9,1,'2013-02-19 17:28:24','2013-02-19 17:28:24'),(27,11,3,'2013-02-19 17:37:02','2013-02-19 17:37:02'),(28,12,3,'2013-02-19 17:37:02','2013-02-19 17:37:02'),(29,13,2,'2013-02-19 17:38:12','2013-02-19 17:38:12'),(30,14,2,'2013-02-19 17:38:12','2013-02-19 17:38:12'); /*!40000 ALTER TABLE `role_user` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `roles` -- DROP TABLE IF EXISTS `roles`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `roles` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(200) NOT NULL, `desc` varchar(200) NOT NULL, `created_at` date DEFAULT NULL, `updated_at` date DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `roles` -- LOCK TABLES `roles` WRITE; /*!40000 ALTER TABLE `roles` DISABLE KEYS */; INSERT INTO `roles` VALUES (1,'Supervisor','Supervises Every Project',NULL,NULL),(2,'Project Manager','Manages Projects Assigned',NULL,NULL),(3,'Member','Collaborates on any project assigned',NULL,NULL); /*!40000 ALTER TABLE `roles` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `users` -- DROP TABLE IF EXISTS `users`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `fname` varchar(200) NOT NULL, `lname` varchar(200) NOT NULL, `email` varchar(200) NOT NULL, `phone` varchar(200) NOT NULL, `skills` varchar(200) NOT NULL, `password` varchar(200) NOT NULL, `updated_at` date DEFAULT NULL, `created_at` date DEFAULT NULL, `thumb` varchar(200) DEFAULT 'img/user.png', `sup_id` int(10) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `users` -- LOCK TABLES `users` WRITE; /*!40000 ALTER TABLE `users` DISABLE KEYS */; INSERT INTO `users` VALUES (9,'Naomi','H','<EMAIL>','0914741037','Laravel Expert,RoR,Joomla','$2a$08$1M79U5stpvvG6NcrXe9qOOmepYtpRAHd3LIHZ9.RhswHHXHGAe6yS','2013-02-20','2013-02-19','img/user.png',9),(11,'Tesfit','G/meskel','<EMAIL>','0914741037','Photoshop Artist','$2a$08$ABbzflduEkfHrmbt.5YrzOGAD85MgdQL.XXom/jx0oisRv/nzHM26','2013-02-19','2013-02-19','img/user.png',9),(12,'Tesfit','G/meskel','<EMAIL>','0914741037','Photoshop Artist','$2a$08$uqQHK.kG.dvzQhNNB4je4.yLazZA77husTw5c30e6xMk1t4wQSIei','2013-02-19','2013-02-19','img/user.png',12),(13,'Solomon','Hailemariam','<EMAIL>','0914741037','Project Mgmt, RoR','$2a$08$FKzJ4k26KIhLZha1p6AP0.KnwMn7d1JhMck/TP3wAbhfeXMCWS46u','2013-02-19','2013-02-19','img/user.png',9),(14,'Solomon','Hailemariam','<EMAIL>','0914741037','Project Mgmt, RoR','$2a$08$Zfaz7BdIeXSpNWgnTzzixucZg/qVn3KjpCX4Pd0XriU4kFpiKXm62','2013-02-19','2013-02-19','img/user.png',14); /*!40000 ALTER TABLE `users` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2013-02-20 13:54:46 <file_sep><?php class Create_Tasks_Table { public function up() { Schema::create('tasks', function($table) { $table->increments('id'); $table->string('title'); $table->string('shortDesc'); $table->string('desc'); $table->integer('pid'); $table->integer('empid'); $table->date('startdate'); $table->date('enddate'); $table->string('status'); $table->timestamps(); }); } public function down() { Schema::drop('tasks'); } }<file_sep><?php class Role_User extends Eloquent { public static $timestamps=false; public function role() { return $this->has_one('Role'); } public function user() { return $this->has_one('User'); } } <file_sep><?php class Create_Projects_Table { public function up() { Schema::create('projects', function($table) { $table->increments('id'); $table->string('title'); $table->string('shortDesc'); $table->string('desc'); $table->integer('supervisor'); $table->integer('pm'); $table->date('startdate'); $table->date('enddate'); $table->string('status'); $table->timestamps(); }); } public function down() { Schema::drop('projects'); } }<file_sep><?php class Projects_Controller extends Base_Controller { public $restful = true; public function get_index() { $user_id=Auth::user()->id; $projects=User::find($user_id)->projects()->paginate(2); return View::make('project.index')->with('projects',$projects); } //Display members of a project public function get_members($id) { $members=Project::find($id)->users()->paginate(2); return View::make('user.index') ->with('users',$members); } public function get_jobs($id) { $project=Project::find($id); $jobs=$project->jobs()->paginate(3); return View::make('job.index') ->with('jobs',$jobs); } public function get_desc($id) { $project=Project::find($id); return View::make('project.desc' , $project->to_array()); //return Response::json($project->to_array()); } public function post_create() { $pm_email=Input::get('projectmanager'); //$user = User::where_email($email)->first(); $pm=User::where_email($pm_email); $pm_id=$pm->id; $sup_id=Auth::user()->id; $input=array( 'title'=>Input::get('title'), 'shortdesc'=>Input::get('shortdesc'), 'desc'=>Input::get('desc'), 'pm_id'=>$pm_id, 'sup_id'=>$sup_id, 'startdate'=>Input::get('sdate'), 'enddate'=>Input::get('edate'), 'status'=>'On Progress' ); $project=Project::create($input); if ($sup_id==$pm_id) { $project->users()->attach($sup_id); } else { $project->users()->attach($sup_id); $project->users()->attach($pm_id); } if($project) { return Redirect::to_route('project',$project->id); } } //View Single Project from a normalr user public function get_single() { $id=URI::segment(4); return Redirect::to_route('project' , $id); } public function get_show($id) { $project=Project::find($id); return View::make('project.show' , $project->to_array()); } public function get_edit($id) { $project=Project::find($id); if(!$project) return Redirect::to_route('new_project'); return View::make('project.edit' , $project->to_array()); } public function get_new() { return View::make('project.new'); } public function put_update() { $id=Input::get('id'); $pm_email=Input::get('projectmanager'); $pm=User::where_email($pm_email)->first(); $pm_id=$pm->id; $input=array( 'title'=>Input::get('title'), 'shortdesc'=>Input::get('shortdesc'), 'desc'=>Input::get('desc'), 'pm_id'=>$pm_id, 'startdate'=>Input::get('sdate'), 'enddate'=>Input::get('edate'), ); Project::update($id,$input); return Redirect::to_route('project', $id); } public function get_reassign($id) { $project=Project::find($id); return View::make('project.reassign' , $project->to_array()); } public function put_reassign() { $id=Input::get('id'); $pm_email=Input::get('projectmanager'); $pm=User::where_email($pm_email)->first(); $pm_id=$pm->id; $input=array( 'pm_id'=>$pm_id, ); Project::update($id,$input); return Redirect::to_route('project', $id); } public function get_close($id) { $project=Project::find($id); return View::make('project.close' , $project->to_array()); } public function put_close() { $id=Input::get('id'); $status=Input::get('status'); $input=array( 'status'=>$status ); Project::update($id,$input); return Redirect::to_route('project', $id); } public function get_destroy($id) { Project::find($id)->jobs()->delete(); Project::find($id)->users()->delete(); Project::find($id)->delete(); return Redirect::to_route('projects'); } }<file_sep><?php class Create_Role_User_Table { public function up() { Schema::create('role_user', function($table) { $table->increments('id'); $table->integer('user_id'); $table->integer('role_id'); }); } public function down() { Schema::drop('user'); } }<file_sep><?php class Users_Controller extends Base_Controller { public $restful = true; public function get_index() { if (Auth::check()) { $sup_id=Auth::user()->id; $users=User::where_sup_id($sup_id)->paginate(2); return View::make('user.index')->with('users',$users); } else { return Redirect::to_route('login'); } } public function get_projects($id) { $projects=User::find($id)->projects()->paginate(2); return View::make('project.index') ->with('projects',$projects); } public function get_jobs($id) { $jobs=User::find($id)->jobs()->where_status('on Progress')->paginate(2); return View::make('job.index') ->with('jobs',$jobs); } public function get_login() { return View::make('user.login'); } public function get_logout() { if (Auth::check()) { Auth::logout(); return Redirect::to_route('login'); } else { return Redirect::to_route('home'); } } public function post_login() { $user=array( 'username'=>Input::get('email'), 'password'=>Input::get('<PASSWORD>') ); if(Auth::attempt($user)) { $id=Auth::user()->id; $roles=User::find($id)->roles()->get(); foreach ($roles as $role) { if ($role->id==1) { return Redirect::to_route('home'); } } return Redirect::to_route('user',$id)->with('title','projects'); } else { return Redirect::to_route('login') ->with('login_errors', true); } } public function post_create() { // Add Validation Here $role_id=Input::get('role'); if (Auth::check()) { $sup_id=Auth::user()->id; $input=array( 'fname'=>Input::get('fname'), 'lname'=>Input::get('lname'), 'email'=>Input::get('email'), 'sup_id'=>$sup_id, 'password'=><PASSWORD>::Make(Input::get('pass')), 'phone'=>Input::get('phone'), 'skills'=>Input::get('skills') ); $user=User::create($input); $user->roles()->attach($role_id); } else { $input=array( 'fname'=>Input::get('fname'), 'lname'=>Input::get('lname'), 'email'=>Input::get('email'), 'password'=>Hash::Make(Input::get('pass')), 'phone'=>Input::get('phone'), 'skills'=>Input::get('skills') ); $user=User::create($input); $id=$user->id; $user->roles()->attach($role_id); $supid=array('sup_id' => $id ); User::update($id,$supid); } $id=$user->id; //After Adding the User Attach him to a project if (Input::get('id')) { $p_id=Input::get('id'); $user->projects()->attach($p_id); return Redirect::to_route('project',$p_id); } else { return Redirect::to_route('user',$id); } // } public function get_single() { $id=URI::segment(4); return Redirect::to_route('user' , $id); } public function get_show($id) { if (Auth::check()) { $user=User::find($id); return View::make('user.show' , $user->to_array()); } else { $msg='Login to access your account!'; return Redirect::to_route('login') ->with('msg' , $msg); } } public function get_edit($id) { $user=User::find($id); if(!$user) return Redirect::to_route('new_user'); return View::make('user.edit' , $user->to_array()); } public function get_new() { $id=$segment = URI::segment(3); return View::make('user.new')->with('id',$id); } public function put_update() { $id=Input::get('id'); $input=array( 'fname'=>Input::get('fname'), 'email'=>Input::get('email'), 'lname'=>Input::get('lname'), 'phone'=>Input::get('phone'), 'skills'=>Input::get('skills') ); User::update($id,$input); return Redirect::to_route('user', $id); } public function get_destroy($id) { User::find($id)->jobs()->delete(); User::find($id)->projects()->delete(); User::find($id)->delete(); return Redirect::to_route('users'); } }<file_sep>#iManage ======= iManage is a role based project management web app built with laravel! <file_sep><?php class Jobs_Controller extends Base_Controller { public $restful = true; public function get_index() { if(Auth::check()) { $user_id=Auth::user()->id; $jobs=User::find($user_id)->jobs()->paginate(3); return View::make('job.index')->with('jobs',$jobs); } else { return Redirect::to_route('login'); } } public function get_single() { $id=URI::segment(4); return Redirect::to_route('job' , $id); } public function post_create() { $member_email=Input::get('ass'); $member=User::where_email($member_email)->first(); $member_id=$member->id; $input=array( 'title'=>Input::get('title'), 'shortdesc'=>Input::get('shortdesc'), 'desc'=>Input::get('desc'), 'project_id'=>Input::get('id'), 'user_id'=>$member_id, 'startdate'=>Input::get('sdate'), 'enddate'=>Input::get('edate'), 'status'=>'On Progress' ); $job=Job::create($input); //After assigning a task make the user member of the project $project_id=Input::get('id'); $project=Project::find($project_id); $project->users()->attach($member_id); if($job) { return Redirect::to_route('job' , $job->id); } } public function get_show($id) { $job=Job::find($id); return View::make('job.show',$job->to_array()); } public function get_edit($id) { $job=Job::find($id); if(!$job) return Redirect::to_route('new_job'); return View::make('job.edit' , $job->to_array()); } public function get_reassign($id) { $job=Job::find($id); return View::make('job.reassign' , $job->to_array()); } public function put_reassign() { $id=Input::get('id'); $ass_email=Input::get('ass'); $ass=User::where_email($ass_email)->first(); $ass_id=$ass->id; $input=array( 'user_id'=>$ass_id, ); Job::update($id,$input); return Redirect::to_route('job', $id); } public function get_desc($id) { $job=Job::find($id); return View::make('job.desc' , $job->to_array()); //return Response::json($project->to_array()); } public function get_close($id) { $job=Job::find($id); return View::make('job.close' , $job->to_array()); } public function put_close() { $id=Input::get('id'); $status=Input::get('status'); $input=array( 'status'=>$status ); Job::update($id,$input); return Redirect::to_route('job', $id); } public function get_new() { $id = URI::segment(3); return View::make('job.new')->with('id',$id); } public function put_update() { $id=Input::get('id'); $ass_email=Input::get('ass'); $ass=User::where_email($ass_email)->first(); $ass_id=$ass->id; $input=array( 'title'=>Input::get('title'), 'shortdesc'=>Input::get('shortdesc'), 'desc'=>Input::get('desc'), 'user_id'=>$ass_id, 'startdate'=>Input::get('sdate'), 'enddate'=>Input::get('edate'), ); Job::update($id,$input); return Redirect::to_route('job', $id); } public function get_destroy($id) { Job::find($id)->delete(); return Redirect::to_route('jobs'); } }<file_sep>// public/js/script.js $(document).ready(function() { $('#descs').click(function(e) { // prevent the links default action // from firing e.preventDefault(); // attempt to GET the new content $.ajax({ type: "GET", dataType: "JSON", url: BASE+'/projects/1', success: processJSON }); }) function processJSON(data){ alert(data.title); } });<file_sep><?php class Task extends Eloquent { public static $timestamps = false; }
5b0e076e84ef0a1a7147beb34d4973429b28c19c
[ "Markdown", "SQL", "JavaScript", "PHP" ]
17
PHP
iamtekeste/imanage
df2cb0a49e998d5be19ee19aaf43ffd5786213ad
d3a8e72bd03825aa2e2b0c3c0696b9e90c7d79cd
refs/heads/master
<file_sep>'use strict'; import * as vscode from 'vscode'; export function activate(context: vscode.ExtensionContext) { const disposable1 = vscode.commands.registerTextEditorCommand('extension.embraceParenthesis', (textEditor, edit) => { doSurround(textEditor, edit, '(', ')'); }); const disposable2 = vscode.commands.registerTextEditorCommand('extension.embraceSquareBrackets', (textEditor, edit) => { doSurround(textEditor, edit, '[', ']'); }); const disposable3 = vscode.commands.registerTextEditorCommand('extension.embraceCurlyBrackets', (textEditor, edit) => { doSurround(textEditor, edit, '{', '}'); }); const disposable4 = vscode.commands.registerTextEditorCommand('extension.embraceAngleBrackets', (textEditor, edit) => { doSurround(textEditor, edit, '<', '>'); }); const disposable5 = vscode.commands.registerTextEditorCommand('extension.embraceSingleQuotes', (textEditor, edit) => { doSurround(textEditor, edit, '\'', '\''); }); const disposable6 = vscode.commands.registerTextEditorCommand('extension.embraceDoubleQuotes', (textEditor, edit) => { doSurround(textEditor, edit, '\"', '\"'); }); context.subscriptions.push(disposable1); context.subscriptions.push(disposable2); context.subscriptions.push(disposable3); context.subscriptions.push(disposable4); context.subscriptions.push(disposable5); context.subscriptions.push(disposable6); } export function deactivate() { } function doSurround(textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit, insBefore: string, insAfter: string) { const document = textEditor.document; const newSelections: vscode.Selection[] = []; textEditor.edit(editBuilder => { textEditor.selections.forEach(selection => { const adjust = selection.start.line == selection.end.line ? 1 : 0; editBuilder.insert(selection.start, insBefore); editBuilder.insert(selection.end, insAfter); newSelections.push(new vscode.Selection(selection.start.translate(0, 1), selection.end.translate(0, adjust))); }); }).then(() => { textEditor.selections textEditor.selections = newSelections; }); }
eba8750121c586b62c03b86c3c1be994a2ef63f8
[ "TypeScript" ]
1
TypeScript
LTKort/vsc-embrace
0ba7e6480a957b46dea1f6561b0652385ef89312
1129a048e331cdece27590eac902eb2850e56f54
refs/heads/main
<file_sep># memory Simple single header memory file for internal / external. Make sure to compile on X64 , Release, And multibyte charset <file_sep>#pragma once #ifndef MEMORY_H #include <Windows.h> #include <TlHelp32.h> #include <string> #include <vector> #define EASY_USE 0 namespace Mem { #if EASY_USE using namespace External; using namespace Internal; #endif const void KillProcess(const char* ProcessName) noexcept(true) { std::string buffer = "taskkill /IM "; buffer += ProcessName; buffer += " /F"; system(buffer.c_str()); } const void CloseSafeHandle(const HANDLE handle) { if (handle != INVALID_HANDLE_VALUE && handle != nullptr) { try { CloseHandle(handle); } catch (std::exception& e) { MessageBoxA(0, e.what(), "CloseSafeHandle: Exception", MB_OK | MB_ICONERROR); } } } namespace Utils { BOOL IsDebugged() { BOOL result; return CheckRemoteDebuggerPresent(GetCurrentProcess(), &result); } const char* GetCurrentProcessName() { char buffer[MAX_PATH]; if (GetModuleFileNameA(GetModuleHandleA(0), buffer, MAX_PATH)) return buffer; } void RenameCurrentProcess(const char* newName) { try { rename(GetCurrentProcessName(), newName); } catch (...) {} } std::string ConvertToString(const char* ptr) { return static_cast<std::string>(ptr); } const char* ConvertToCharPtr(std::string str) { return str.c_str(); } } namespace External { #if _WIN32 #if UNICODE std::uint32_t GetProcId32(const wchar_t* processName) { std::uint32_t ProcessId = NULL; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (!(hSnap == NULL)) { PROCESSENTRY32 pe32; pe32.dwSize = sizeof(pe32); if (Process32First(hSnap, &pe32)) while (Process32Next(hSnap, &pe32)) if (wcscmp(processName, pe32.szExeFile)) { ProcessId = pe32.th32ProcessID; break; } } CloseSafeHandle(hSnap); return ProcessId; } std::uint32_t GetModuleBase32(std::uint32_t ProcessId, const wchar_t* moduleName) { std::uint32_t BaseAddress = NULL; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE32 | TH32CS_SNAPMODULE, ProcessId); if (!(hSnap == NULL)) { MODULEENTRY32 me32; me32.dwSize = sizeof(me32); if (Module32FirstW(hSnap, &me32)) while (Module32NextW(hSnap, &me32)) if (wcscmp(moduleName, me32.szModule)) { BaseAddress = reinterpret_cast<std::uint32_t>(me32.modBaseAddr); break; } } CloseSafeHandle(hSnap); return BaseAddress; } #else std::uint32_t GetProcId32(const char* processName) { std::uint32_t ProcessId = NULL; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (!(hSnap == NULL)) { PROCESSENTRY32 pe32; pe32.dwSize = sizeof(pe32); if (Process32First(hSnap, &pe32)) while (Process32Next(hSnap, &pe32)) if (strcmp(processName, pe32.szExeFile)) { ProcessId = pe32.th32ProcessID; break; } } CloseSafeHandle(hSnap); return ProcessId; } std::uint32_t GetModuleBase32(std::uint32_t ProcessId, const char* moduleName) { std::uint32_t BaseAddress = NULL; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE32 | TH32CS_SNAPMODULE, ProcessId); if (!(hSnap == NULL)) { MODULEENTRY32 me32; me32.dwSize = sizeof(me32); if (Module32First(hSnap, &me32)) while (Module32Next(hSnap, &me32)) if (!strcmp(moduleName, me32.szModule)) { BaseAddress = reinterpret_cast<std::uint32_t>(me32.modBaseAddr); break; } } CloseSafeHandle(hSnap); return BaseAddress; } #endif std::uintptr_t GetPointerAddress(HANDLE ProcessHandle, std::uintptr_t baseOfModule, std::vector<std::uintptr_t> pointers) { std::uintptr_t address = baseOfModule; for (std::uintptr_t i{ 0 }; i < pointers.size(); i++) { address = ReadProcessMemory(ProcessHandle, (BYTE*)address, &address, sizeof(address), 0); address += pointers[i]; } return address; } template<typename T> inline void WPM(HANDLE ProcessHandle, ULONG Address, T value) { WriteProcessMemory(ProcessHandle, reinterpret_cast<LPVOID>(Address), &value, sizeof(value), 0); } template<typename T> inline T RPM(HANDLE ProcessHandle, ULONG Address) { T buffer; ReadProcessMemory(ProcessHandle, reinterpret_cast<LPVOID>(Address), &buffer, sizeof(buffer), 0); return buffer; } #else #if !UNICODE std::uint64_t GetProcId64(std::string process_name) { std::uint32_t ProcessId = NULL; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (!(hSnap == NULL)) { PROCESSENTRY32 pe32; pe32.dwSize = sizeof(pe32); if (Process32First(hSnap, &pe32)) while (Process32Next(hSnap, &pe32)) if (!strcmp(process_name.c_str(), (const char*)pe32.szExeFile)) { ProcessId = pe32.th32ProcessID; break; } } CloseHandle(hSnap); return ProcessId; } std::uint64_t GetModuleBase64(std::uint64_t ProcessId, const char* moduleName) { std::uint32_t BaseAddress = NULL; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE32 | TH32CS_SNAPMODULE, ProcessId); if (!(hSnap == NULL)) { MODULEENTRY32 me32; me32.dwSize = sizeof(me32); if (Module32First(hSnap, &me32)) while (Module32Next(hSnap, &me32)) if (strcmp(moduleName, (const char*)me32.szModule)) { BaseAddress = reinterpret_cast<std::uint32_t>(me32.modBaseAddr); break; } } CloseHandle(hSnap); return BaseAddress; } #else std::uint64_t GetProcId64(const wchar_t* process_name) { std::uint32_t ProcessId = NULL; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (!(hSnap == NULL)) { PROCESSENTRY32W pe32; pe32.dwSize = sizeof(pe32); if (Process32FirstW(hSnap, &pe32)) while (Process32NextW(hSnap, &pe32)) if (!wcscmp(process_name, pe32.szExeFile)) { ProcessId = pe32.th32ProcessID; break; } } CloseHandle(hSnap); return ProcessId; } std::uint64_t GetModuleBase64(std::uint64_t ProcessId, const wchar_t* moduleName) { std::uint32_t BaseAddress = NULL; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE32 | TH32CS_SNAPMODULE, ProcessId); if (!(hSnap == NULL)) { MODULEENTRY32W me32; me32.dwSize = sizeof(me32); if (Module32FirstW(hSnap, &me32)) while (Module32NextW(hSnap, &me32)) if (wcscmp(moduleName, me32.szModule)) { BaseAddress = reinterpret_cast<std::uint32_t>(me32.modBaseAddr); break; } } CloseHandle(hSnap); return BaseAddress; } #endif #endif } namespace Internal { template<typename T> inline void WPM(ULONG Address, T value) { try { *(T*)Address = value; } catch (...) {} } template<typename T> inline T RPM(ULONG Address) { try { return *(T*)Address; } catch (...) {} } inline FARPROC GetExportAddress(const char* ModuleName, const char* FunctionName) { FARPROC Address = GetProcAddress(GetModuleHandleA(ModuleName), FunctionName); return Address; } std::uintptr_t GetPointerAddress(std::uintptr_t baseOfModule, std::vector<std::uintptr_t> pointers) { std::uintptr_t address = baseOfModule; for (std::uintptr_t i{ 0 }; i < pointers.size(); i++) { address = *reinterpret_cast<std::uintptr_t*>(address); address += pointers[i]; } return address; } PVOID GetUnhookedPointer(PVOID pointer) { if (*(unsigned char*)pointer == 0xF1) return (PVOID)((ULONG)pointer + 0x1); } PVOID Nop(PVOID Address, INT Bytes) { try { ULONG OldProtection, NewProtection; VirtualProtect(Address, Bytes, PAGE_EXECUTE_READWRITE, &OldProtection); memset(Address, 0x90, Bytes); VirtualProtect(Address, Bytes, OldProtection, &NewProtection); } catch (std::exception*& e) { MessageBoxA(0, e->what(), "Nop: Exception", MB_OK | MB_ICONERROR); } } const void KillCurrentProcess() { #if !_DLL HANDLE handle = GetCurrentProcess(); TerminateProcess(handle, 0); #else ExitProcess(0); #endif } } namespace Prototypes { /* pT = Prototype, feel free to change this to what ever you'd like :) */ typedef HANDLE(*_pTCreateToolhelp32Snapshot) ( DWORD dwFlags, DWORD th32ProcessID ); _pTCreateToolhelp32Snapshot pTCreateToolhelp32Snapshot = (_pTCreateToolhelp32Snapshot)Internal::GetExportAddress("kernel32.dll", "CreateToolhelp32Snapshot"); typedef BOOL(*_pTVirtualProtect) ( LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect ); _pTVirtualProtect pTVirtualProtect = (_pTVirtualProtect)Internal::GetExportAddress("kernel32.dll", "VirtualProtect"); /* TODO: * NtWriteVirtualMemory * NtProtectVirutalMemory * NtOpenProcess * NtReadVirtualMemory * ZwWriteVirutalMemory * ZwReadVirtualMemory */ } } #define MEMORY_H #endif
effb130a088cf191545aa04af7e064138e396f35
[ "Markdown", "C++" ]
2
Markdown
chaos444/memory
818e08428eacd1e0caf723c57197794ae3cbaa52
e5c6c1385262509f3e901b741593c5a9cd7b91c0
refs/heads/master
<file_sep># hackerRankMySQL mySQL solutions on hackerRank simple select, more advanced select queries, basic join, aggregations <file_sep>select sum(city.population) from city, country where city.countrycode=country.code and country.continent='Asia'; select city.name from city, country where city.countrycode=country.code and country.continent='Africa'; select country.continent, floor(avg(city.population)) from city, country where city.countrycode=country.code group by continent; select CASE when grades.grade>7 then students.name end, grades.grade, students.marks from students, grades where students.marks>=grades.min_mark and students.marks<=grades.max_mark order by grades.grade DESC, students.name, students.marks ASC; --didn't specify that marks couldn't be ascending for result rows with names!!--<file_sep>select count(name) from city where population > 100000; select sum(population) from CITY where district = 'California'; select avg(population) from city where district = 'California'; select floor(avg(population)) from city; select sum(population) from city where countrycode='JPN'; select (max(population)-min(population)) from city; select concat(round(sum(lat_n),2),' ',round(sum(long_w),2)) from station; select truncate(sum(lat_n),4) from station where lat_n >38.7880 and lat_n< 137.2345; select truncate(max(lat_n),4) from station where lat_n<137.2345; select round(long_w,4) from station where lat_n<137.2345 order by lat_n DESC limit 1; select round(min(lat_n),4) from station where lat_n>38.7780; select round(long_w,4) from STATION where lat_n>38.7780 order by lat_n ASC limit 1; select round(abs(min(lat_n)-min(long_w)) + abs(max(lat_n)-max(long_w)),4) from station; select round(sqrt(power((min(lat_n)-min(long_w)),2)+power((max(lat_n)-max(long_w)),2)),4) from station; select round(x.lat_n,4) from station x, station y group by x.lat_n having sum(sign(y.lat_n-x.lat_n))=0; /**this gives correct median value as long as there's an odd number of values**/ select ceiling(avg(salary) - avg(replace(salary,'0',''))) from employees; /** replace treats salary like string, not integer. while average treats the result as an integer, not string**/<file_sep>select concat(name,'(',substring(occupation, 1,1),')') from OCCUPATIONS order by name ASC; select concat('There are total ',COUNT(occupation), ' ',lower(occupation),'s.') from OCCUPATIONS group by occupation order by COUNT(occupation) ASC, occupation ASC; select CASE when occupation="Doctor" then name else null end, CASE when occupation="Professor" then name else null end, CASE when occupation="Singer" then name else null end, CASE when occupation="Actor" then name else null end, from OCCUPATIONS; select doctor from (select CASE when occupation="Doctor" then name end as "doctor", CASE when occupation="Professor" then name end as "professor", CASE when occupation="Singer" then name end as "singer", CASE when occupation="Actor" then name end as "actor", from OCCUPATIONS) as pivot --derived tables need an alias-- where doctor is not NULL; --returns rows where doctor has a value but this doesn't get rid of the nulls alongside...-- select * from BST as t1, BST as t2 where t1.p=t2.n and t2.p is not NULL; --returns all the inners, nodes that are also parents that have parents-- select * from BST where p is NULL; --returns the root node-- select n, case when (p is null) then 'Root' when (n in (select p from bst)) then 'Inner' else 'Leaf' end from bst order by n; --solution-- SELECT N, IF(P IS NULL,'Root',IF((SELECT COUNT(*) FROM BST WHERE P=B.N)>0,'Inner','Leaf')) FROM BST AS B ORDER BY N; --(another solution)USING ALIASES???-- <file_sep>select * from CITY where population > 100000 and countrycode='USA'; select distinct city from STATION where ID%2=0; select (select COUNT(city) from STATION)- (select COUNT(distinct city) from STATION); select city, char_length(city) from STATION order by char_length(city) ASC, city ASC limit 1; select city, char_length(city) from STATION order by char_length(city) DESC, city ASC limit 1; select distinct city from STATION where city regex '^[aeiou].*[aeiou]$'; select distinct city from STATION where city regexp '^[^aeiou]'; select distinct city from STATION where city regexp '^[^aeiou]' or city regexp '[^aeiou]$'; select name from STUDENTS where marks>75 order by substring(name, -3), ID ASC;
6753db8bfed6bb4912b40be2fbd84f5989638856
[ "Markdown", "SQL" ]
5
Markdown
EmOnTheWeb/hackerRankBasicSQL
0a40bf0ea1ac06fd13e3c00f8904a86c360db773
d918dd9dba2d47f626208a76b72b80a213e526f8
refs/heads/master
<file_sep>import React from "react"; import { withStyles } from '@material-ui/core/styles'; import { Slider, Rail, Handles, Tracks, Ticks } from 'react-compound-slider' import Handle from './Handle'; import Track from './Track'; import SettingsTick from './SettingsTick'; // https://sghall.github.io/react-compound-slider/#/getting-started/tutorial const styles = theme => ({ sliderStyle: { // Give the slider some width position: 'relative', width: '100%', height: 60 }, railStyle: { position: 'absolute', width: '100%', height: 2, marginTop: 25, borderRadius: 5, backgroundColor: 'lightgray' } }); /** Component used to build settings panel datarange slider */ const DataRangeSlider = (props) => { return ( <Slider className={props.classes.sliderStyle} domain={[props.absoluteMin, props.absoluteMax]} step={props.interval} mode={2} values={[props.currentMin, props.currentMax]} onChange={(vals) => props.handleLayerSettingsUpdate(props.layerID, 'data-range', vals)} > <Rail> {({ getRailProps }) => ( <div className={props.classes.railStyle} {...getRailProps()} /> )} </Rail> <Handles> {({ handles, getHandleProps }) => ( <div className="slider-handles"> {handles.map(handle => ( <Handle key={handle.id} handle={handle} getHandleProps={getHandleProps} /> ))} </div> )} </Handles> <Tracks left={false} right={false}> {({ tracks, getTrackProps }) => ( <div className="slider-tracks"> {tracks.map(({ id, source, target }) => ( <Track key={id} source={source} target={target} getTrackProps={getTrackProps} /> ))} </div> )} </Tracks> <Ticks count={10}> {({ ticks }) => ( <div className="slider-ticks"> {ticks.map(tick => ( <SettingsTick key={tick.id} tick={tick} count={ticks.length} /> ))} </div> )} </Ticks> </Slider> ); } export default withStyles(styles, { withTheme: true })(DataRangeSlider); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import ReactHighcharts from 'react-highcharts'; import { constructTitle, constructSubTitle } from '../scripts/chartUtils'; const HighchartsVector = require('highcharts/modules/vector.js') HighchartsVector(ReactHighcharts.Highcharts) const config = { chart: { height: 500, zoomType: 'xy', type: 'line', inverted: true }, title: { text: 'Title', }, subtitle: { text: 'Subtitle Text', useHTML: true, }, xAxis: { title: { text: 'Level' }, gridLineWidth: 1, reversed: false, opposite: false }, yAxis: { title: { text: 'YAxis Title' } }, plotOptions: { series: { tooltip: { followTouchMove: false, headerFormat: `<span style="font-size: 10px">{point.x} {series.options.levelUnit}</span><br/>`, pointFormatter: function() { var tooltipHTML = `<span style="color:${this.color}">\u25CF</span>`; if (this.options.direction) { tooltipHTML += ` ${this.series.name}: <b>${this.options.y.toFixed(1)} ${this.series.options.units} @ ${this.options.direction.toFixed(1)}°</b><br/> `; } else { tooltipHTML += ` ${this.series.name}: <b>${this.options.y.toFixed(1)} ${this.series.options.units}</b><br/> `; } return tooltipHTML; } } }, vector: { rotationOrigin: 'start', showInLegend: false, enableMouseTracking: false } }, series: [], credits: { enabled: false }, responsive: { rules: [{ condition: { maxWidth: 650 }, chartOptions: { chart: { height: 300 }, navigator: { enabled: false } } }] } } const MetOceanProfile = (props) => { const constructYAxis = (chartData) => { let yAxisArr = [], yAxisItem, vectorSeries = false; chartData.forEach((dataSource,indx) => { // no label if vector series if (dataSource['series'].length === 1 & dataSource['series'][0]['type'] === 'vector') { vectorSeries = true; } yAxisItem = { gridLineWidth: indx > 0 ? 0 : 1, labels: { format: `{value} ${dataSource['units']}`, enabled: !vectorSeries }, title: { text: dataSource['shortName'], }, opposite: false, min: 0 } yAxisArr.push(yAxisItem); }) return yAxisArr; } const buildConfig = () => { const { chartData, activeLocation, chartLoadingErrors } = props; let title = constructTitle(chartData); let subTitle = constructSubTitle(activeLocation, chartLoadingErrors, chartData); let yAxis = constructYAxis(chartData); // lets build the series array first let seriesArr = []; chartData.forEach((dataSource, indx) => { dataSource['series'].forEach(series => { let seriesObj = { name: dataSource['niceName'], color: ReactHighcharts.Highcharts.getOptions().colors[indx], type: series['type'], yAxis: indx, levelUnit: dataSource['levelUnit'], data: series['data'] }; if (series['type'] !== 'vector') { seriesObj['units'] = dataSource['units']; } seriesArr.push(seriesObj); }) }) // populate config config['title']['text'] = title; config['subtitle']['text'] = subTitle; config['yAxis'] = yAxis; config['xAxis']['labels'] = {format: `{value} ${chartData[0]['levelUnit']}`}; // just pick the first series to figure out units config['series'] = seriesArr; return config } return ( <div> <ReactHighcharts config={buildConfig()}> </ReactHighcharts> </div> ) } MetOceanProfile.propTypes = { chartData: PropTypes.arrayOf(PropTypes.object).isRequired }; export default MetOceanProfile; <file_sep>import mercantile import geopandas import pyproj import matplotlib matplotlib.use('agg') from matplotlib import pyplot as plt import io import base64 from utils.tile_utils import make_tile_figure, get_min_zoom # def get_min_zoom(series): # if 'MIN_ZOOM' in series: # min_zoom = series.MIN_ZOOM # elif 'min_zoom' in series: # min_zoom = series.min_zoom # else: # min_zoom = 0 # return min_zoom # def make_tile_figure(height=256, width=256, dpi=256): # """ # make_tile_figure(height=256, width=256, dpi=256) # create a transparent figure with a specified width, # height, and dpi with no x/y ticks and axis turned off # Ouput: figure and axes object # """ # fig = plt.figure(dpi=dpi, facecolor='none', edgecolor='none') # fig.set_alpha(0) # fig.set_figheight(height/dpi) # fig.set_figwidth(width/dpi) # figax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[]) # figax.set_axis_off() # return fig, figax def build_tile_from_shape(incoming_tile, shapefile_path, style={}): """ build_tile_from_shape(incoming_tile, shapefile_path, config={}) Create a single tile with specific styling for consumption in a map ----------------------------------------------------------------------- Inputs: incoming_tile (mercantile.Tile): a mercanatile tile with z,x,y params shapefile_path (str): filepath or url to .zip folder additional_params (obj): an object containing additional config params which are used to override defaults ----------------------------------------------------------------------- Ouput: base64 encoded image converted to a utf-8 string ----------------------------------------------------------------------- Author: <NAME> Date Modified: 03/28/2020 """ # override default config if necessary config = {'linewidth': 0.9,'edgecolor': '#ff3300'} config.update(style) # deconstruct incoming tile i,j,zoom=[*incoming_tile] # create the figure and axes fig, ax = make_tile_figure() ax.set_frame_on(False) ax.set_clip_on(False) ax.set_position([0, 0, 1, 1]) # project to EPSG:3857 for plotting EPSG3857 = pyproj.Proj(init='EPSG:3857') #read shapefile and make sure we dont have any missing values in geometry column df = geopandas.read_file(shapefile_path) trimmed_df = df[(get_min_zoom(df) <= zoom) & (df.geometry.notnull())] trimmed_df_reproject = trimmed_df.to_crs(epsg=3857) trimmed_df_reproject.plot(facecolor='none', edgecolor=config['edgecolor'], linewidth=config['linewidth'], ax=ax) # get extents of incoming tile and crop accordingly ll = mercantile.bounds(i, j, zoom) _epsg_x_min, _epsg_y_min = EPSG3857(*ll[:2]) _epsg_x_max, _epsg_y_max = EPSG3857(*ll[2:]) # set x/y limits to match available tile extents ax.set_xlim(_epsg_x_min,_epsg_x_max) ax.set_ylim(_epsg_y_min, _epsg_y_max) # convert image into base64 encoded string dpi = 256 with io.BytesIO() as out_img: # fig.savefig(out_img, format='png', dpi=dpi, pad_inches=0.0, transparent=True) fig.savefig(out_img, format='png', transparent=True) out_img.seek(0) encoded_img = base64.b64encode(out_img.read()).decode('utf-8') return encoded_img <file_sep>hycom_catalog_root = 'http://tds.hycom.org/thredds/catalog/datasets/GLBv0.08/expt_93.0/data/forecasts/' hycom_opendapp_root = 'http://tds.hycom.org/thredds/dodsC/datasets/GLBv0.08/expt_93.0/data/forecasts/' hycom_data_prefix = 'hycom_glbv_930_'<file_sep>import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { withStyles } from '@material-ui/core/styles'; import Drawer from '@material-ui/core/Drawer'; import CssBaseline from '@material-ui/core/CssBaseline'; import Divider from '@material-ui/core/Divider'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'; import ChevronRightIcon from '@material-ui/icons/ChevronRight'; import TableOfContents from './TableOfContents'; import TimeSlider from './TimeSlider'; import externalStyles from '../scripts/styleVariables'; const drawerZIndex = externalStyles.drawerZIndex; const drawerWidth = externalStyles.drawerWidth; const drawerWidthNarrow = externalStyles.drawerWidthNarrow; // for small viewports (< 600px) const styles = theme => ({ root: { display: 'flex', }, appBar: { transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), 'zIndex': drawerZIndex, 'background': 'transparent', 'boxShadow': 'none', 'display': 'none' }, appBarShift: { width: `calc(100% - ${drawerWidth}px)`, marginLeft: drawerWidth, [`${theme.breakpoints.down('sm')}`]: { width: `calc(100% - ${drawerWidthNarrow}px)`, marginLeft: drawerWidthNarrow, }, transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), }, menuButton: { left: 20, top: 20, zIndex: drawerZIndex + 1, border: `2px solid ${theme.palette.secondary.main}`, backgroundColor: theme.palette.primary.main, '&:hover': { backgroundColor: theme.palette.secondary.main, }, }, hide: { display: 'none', }, drawer: { width: drawerWidth, [`${theme.breakpoints.down('sm')}`]: { width: drawerWidthNarrow, }, flexShrink: 0, }, drawerPaper: { zIndex: drawerZIndex, width: drawerWidth, [`${theme.breakpoints.down('sm')}`]: { width: drawerWidthNarrow, } }, drawerHeader: { display: 'flex', alignItems: 'center', ...theme.mixins.toolbar, justifyContent: 'flex-end', }, content: { position: 'absolute', left: 0, right: 0, bottom: 0, top: 0, } }); class PersistentDrawerLeft extends React.Component { constructor(props) { super(props); // TODO: set this in config this.state = { open: true, }; this.handleDrawerOpen = this.handleDrawerOpen.bind(this); this.handleDrawerClose = this.handleDrawerClose.bind(this); } handleDrawerOpen() { this.setState({ open: true }); }; handleDrawerClose() { this.setState({ open: false }); }; render() { const { classes, theme, ...other } = this.props; const { open } = this.state; return ( <div className={classes.root}> <CssBaseline /> <Drawer className={classes.drawer} variant="persistent" anchor="left" open={open} classes={{ paper: classes.drawerPaper, }} > <div className={classes.drawerHeader}> <IconButton onClick={this.handleDrawerClose}> {theme.direction === 'ltr' ? <ChevronLeftIcon /> : <ChevronRightIcon />} </IconButton> </div> <Divider /> <TableOfContents {...other}/> <p style={{fontSize: '0.8em', padding: 10, color: '#595959', fontFamily: 'Roboto, arial'}}> &copy; {(new Date()).getFullYear()} <NAME>. All rights reserved. </p> </Drawer> <main className={classes.content}> <IconButton aria-label="Open drawer" onClick={this.handleDrawerOpen} className={classNames(classes.menuButton, open && classes.hide)} > <MenuIcon /> </IconButton> <TimeSlider open={open} {...other} /> </main> </div> ); } } PersistentDrawerLeft.propTypes = { classes: PropTypes.object.isRequired, theme: PropTypes.object.isRequired, }; export default withStyles(styles, { withTheme: true })(PersistentDrawerLeft); <file_sep>import React from 'react'; import Tooltip from '@material-ui/core/Tooltip'; import IconButton from '@material-ui/core/IconButton'; import SettingsIcon from '@material-ui/icons/Settings'; import { withStyles } from '@material-ui/core/styles'; const styles = theme => ({ settingsCog: { // [`${theme.breakpoints.down('sm')}`]: { // display: 'none', // } } }) /** Component used to display layer settings */ const SettingsCog = (props) => { const handleCogClick = (layerID, e) => { e.stopPropagation(); e.preventDefault(); props.handleSettingsPanelVisibility(layerID) } return ( <React.Fragment> <Tooltip title="Layer Settings" placement="right-start"> <IconButton aria-label="Settings" onClick={(e) => handleCogClick(props.layerID, e)}> <SettingsIcon /> </IconButton> </Tooltip> </React.Fragment> ); } export default withStyles(styles, { withTheme: true })(SettingsCog);<file_sep>import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib import cm import io import boto3 s3 = boto3.client('s3') bucket_name = 'oceanmapper-data-storage' cmap_list = ['viridis', 'magma', 'jet', 'rainbow', 'cool'] gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) for name in cmap_list: fig = plt.figure(frameon=False) fig.set_size_inches(4,.25) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(gradient, aspect='auto',cmap=plt.get_cmap(name)) extent = ax.get_window_extent().transformed(plt.gcf().dpi_scale_trans.inverted()) # save figure locally # filename = 'colorramps/{0}_colorbar.png'.format(name) # fig.savefig(filename,format='png', bbox_inches=extent, transparent=True) # save the figure to S3 filename = 'colorramps/{0}_colorbar.png'.format(name) with io.BytesIO() as out_img: fig.savefig(out_img,format='png', bbox_inches=extent, transparent=True) out_img.seek(0) s3.put_object(Body=out_img, Bucket=bucket_name, Key=filename, ACL='public-read') <file_sep>import pickle import datetime import copy import io import os import boto3 import numpy as np import mercantile import pyproj import matplotlib matplotlib.use('agg') from matplotlib import pyplot as plt, cm import matplotlib.colors as colors import cmocean s3 = boto3.client('s3') cmap_config = { 'wind_speed': { 'color_map': cm.get_cmap('viridis'), 'data_range': [0,25], 'cb_ticks': [0,5,10,15,20,25], 'cb_label': 'Wind Speed (m/s)' }, 'current_speed': { 'color_map': cm.get_cmap('magma'), 'data_range': [0,2], 'cb_ticks': [0,0.5,1.0,1.5,2.0], 'cb_label': 'Current Speed (m/s)' }, 'wave_amp': { 'color_map': cm.get_cmap('jet'), 'data_range': [0,11], 'cb_ticks': range(11), 'cb_label': 'Significant Wave Height (m)' }, 'wave_dir': {'color_map': None, 'data_range': [None, None]}, 'wave_period': { 'color_map': cm.get_cmap('cool'), 'data_range': [0,21], 'cb_ticks': range(0,21,5), 'cb_label': 'Primary Wave Period (s)' }, } bucket_name = 'oceanmapper-data-storage' def create_legend(info): """ create_legend(info) This function is used to create legend graphics for various datasets ----------------------------------------------------------------------- Inputs: info (obj) -information object that contains these keys: 'pickle_filepath': (string) the location of the pickle data file 'data_type': (string) - one of 'wind_speed', 'current_speed', 'wave_height', 'wave_period' ----------------------------------------------------------------------- Notes: https://stackoverflow.com/questions/40813148/save-colorbar-for-scatter-plot-separately ----------------------------------------------------------------------- Output: A .png legend image which is saved to S3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/16/2018 """ # get info paramaters pickle_filepath = info['pickle_filepath'] data_type = info['data_type'] # load data pickle_data = s3.get_object(Bucket=bucket_name, Key=pickle_filepath) body_string = pickle_data['Body'].read() data = pickle.loads(body_string) # process the data in preparation for tiling if np.ma.is_masked(data['lat']): lat = data['lat'].data else: lat = data['lat'] if np.ma.is_masked(data['lon']): lon = data['lon'].data else: lon = data['lon'] # remove the north/south pole lats since these cause issues when projecting to epsg:3857 keep_lat_bool = np.logical_and(lat<90, lat>-90) keep_lat_indx = np.argwhere(keep_lat_bool).ravel() lat_trim = lat[keep_lat_indx] # create lat/lon mesh grid _lon,_lat = np.meshgrid(lon,lat_trim) # project to EPSG:3857 for plotting EPSG3857 = pyproj.Proj(init='EPSG:3857') lo,la = EPSG3857(_lon,_lat) # sort by EPSG3857 because our drawing surface is in EPSG3857, data still ordered by lon/lat so = np.argsort(lo[1,:]) sa = np.argsort(la[:,1]) proj_lon_array = lo[sa,:][:,so] proj_lat_array = la[sa,:][:,so] data_cmap = cmap_config[data_type]['color_map'] cmin, cmax = cmap_config[data_type]['data_range'] FIGSIZE = (3.5,3.5) plt.figure(figsize=FIGSIZE) if data_type == 'wind_speed' or data_type == 'current_speed': u_vel = (data['u_vel'][keep_lat_indx,:]).astype('float64') v_vel = (data['v_vel'][keep_lat_indx,:]).astype('float64') data_array = np.sqrt((u_vel**2) + (v_vel**2)) nlvls = 100 lvls = np.linspace(cmin, cmax, nlvls) ## filled contour (use SORTED indexes for the EPSG3857 drawing surface) contourf = plt.contourf(proj_lon_array, proj_lat_array, data_array[sa,:][:,so], levels=lvls, cmap=data_cmap) elif data_type == 'wave_amp': height_raw = data['sig_wave_height'][keep_lat_indx,:] palette = copy.copy(data_cmap) palette.set_bad(alpha = 0.0) # ax.pcolormesh(proj_lon_array, proj_lat_array, height_raw, shading='flat', cmap=palette, # norm=colors.BoundaryNorm([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],ncolors=palette.N)) lvls = range(cmin, cmax) contourf = plt.contourf(proj_lon_array, proj_lat_array, height_raw[sa,:][:,so], cmap=palette, levels=lvls) elif data_type == 'wave_period': period_raw = data['primary_wave_period'][keep_lat_indx,:] palette = copy.copy(data_cmap) palette.set_bad(alpha = 0.0) lvls = range(cmin, cmax) contourf = plt.contourf(proj_lon_array, proj_lat_array, period_raw[sa,:][:,so], cmap=palette, levels=lvls) else: pass build_colormap(contourf, data_type, FIGSIZE) plt.close() def build_colormap(plot_obj, data_type, FIGSIZE): """ build_colormap(plot_obj, data_type, FIGSIZE) This function is used to build a standalone colormap which is properly cropped ----------------------------------------------------------------------- Inputs: plot_obj (obj) - plotting object data_type: (string) - one of 'wind_speed', 'current_speed', 'wave_height', 'wave_period' FIGSIZE: (tuple) - width, height of the figure in inches ----------------------------------------------------------------------- Notes: https://stackoverflow.com/questions/40813148/save-colorbar-for-scatter-plot-separately ----------------------------------------------------------------------- Output: A .png legend image which is saved to S3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/16/2018 """ # draw a new figure and replot the colorbar there fig,ax = plt.subplots(figsize=FIGSIZE) cb_ticks = cmap_config[data_type]['cb_ticks'] cb_ticks_labels = [str(tick) for tick in cb_ticks] cb_ticks_labels[-1] = cb_ticks_labels[-1] + '+' cbar = plt.colorbar(plot_obj, ticks=cb_ticks, orientation='horizontal', ax=ax) cb_label = cmap_config[data_type]['cb_label'] cbar.ax.set_xlabel(cb_label) # update the tick labels cbar.ax.set_xticklabels(cb_ticks_labels) ax.remove() # save the figure to S3 filename = 'map_legends/{0}_colorbar.png'.format(data_type) with io.BytesIO() as out_img: fig.savefig(out_img,format='png', bbox_inches='tight') out_img.seek(0) s3.put_object(Body=out_img, Bucket=bucket_name, Key=filename, ACL='public-read') if __name__ == "__main__": data_info_obj = { 'ww3_period': { 'pickle_filepath': 'WW3_DATA/20181121_00/primary_wave_period/pickle/ww3_perpwsfc_20181121_00.pickle', 'data_type': 'wave_period', }, 'ww3_height': { 'pickle_filepath': 'WW3_DATA/20181121_00/sig_wave_height/pickle/ww3_htsgwsfc_20181121_00.pickle', 'data_type': 'wave_amp', }, 'hycom_currents': { 'pickle_filepath': 'HYCOM_DATA/20181121_00/ocean_current_speed/0m/pickle/hycom_currents_20181121_00.pickle', 'data_type': 'current_speed', }, 'gfs_winds': { 'pickle_filepath': 'GFS_DATA/20181121_00/wind_speed/10m/pickle/gfs_winds_20181121_00.pickle', 'data_type': 'wind_speed', } } for element in data_info_obj: create_legend(data_info_obj[element]) <file_sep># -*- coding: utf-8 -*- """ Created on Mon Apr 2 17:20:30 2018 @author: <NAME> """ import datetime import json import time import boto3 import numpy as np from RTOFS_forecast_info import get_latest_RTOFS_forecast_time from build_model_times import assemble_model_timesteps lam = boto3.client('lambda') def lambda_handler(event, context): """ lambda_handler(event, context): This function invokes concurrent lambda functions to read, parse, and save daily (24 hour) RTOFS ocean current data for the water column at specific levitus depths ----------------------------------------------------------------------- Inputs: event: AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type. context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Output: No output ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/21/2022 """ rtofs_url = 'https://nomads.ncep.noaa.gov/dods/rtofs' available_data = get_latest_RTOFS_forecast_time(rtofs_url, '3d') output_info = assemble_model_timesteps(available_data, 'daily') # use only the forecast data to simplify things product_type = 'forecast' zipped_time_and_indx = np.array(tuple(zip(output_info['products'][product_type]['field_datetimes'], output_info['products'][product_type]['forecast_indx']))) for model_field in zipped_time_and_indx: model_field_indx = model_field[1] # only grab the upper 10m levels = output_info['general']['levels'] stop_depth_indx = levels.index(100) + 1 for level_indx, level_depth in enumerate(levels[:stop_depth_indx]): # build payload for initiation of lambda function payload = { 'url': output_info['products'][product_type]['url'], 'forecast_time': datetime.datetime.strftime(model_field[0], '%Y%m%dT%H:%M'), 'forecast_indx': model_field_indx, 'level': {'level_depth': level_depth, 'level_indx': level_indx} } # InvocationType = RequestResponse # this is used for synchronous lambda calls try: response = lam.invoke(FunctionName='grab_rtofs_3d', InvocationType='Event', Payload=json.dumps(payload)) except Exception as e: print(e) raise e print(response) time.sleep(0.1) if __name__ == "__main__": lambda_handler('', '') <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import MenuItem from '@material-ui/core/MenuItem'; import Select from '@material-ui/core/Select'; import { colorPaletteMapping } from '../scripts/layers.js'; const styles = theme => ({ selectMenu: { margin: theme.spacing.unit, maxWidth: '100%' } }); /** Component used to build settings panel colormap selector */ const ColormapDropdown = (props) => { const { classes } = props; return ( <div> <Select disableUnderline value={props.colormap} autoWidth={false} onChange={(e) => props.handleLayerSettingsUpdate(props.layerID, 'colormap', e.target.value)} name="colormaps" className={classes.selectMenu} > {colorPaletteMapping.map((colormapObj, indx) => { if (props.colorramps.indexOf(Object.keys(colormapObj)[0]) > -1) { return ( <MenuItem key={indx.toString()} value={Object.keys(colormapObj)[0]} title={Object.keys(colormapObj)[0]} > <img src={colormapObj[Object.keys(colormapObj)[0]]} alt='colorramp'/> </MenuItem> ) } else { return null } })} </Select> </div> ) } ColormapDropdown.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(ColormapDropdown);<file_sep>import boto3 import pickle import datetime import numpy as np import mercantile import os import pyproj from matplotlib import pyplot as plt, cm import matplotlib.colors as colors import cmocean import copy import io import os import PIL # import shapefile as shp # Requires the pyshp package # from descartes import PolygonPatch from pathlib import Path import pandas import geopandas def make_tile_figure(height=256, width=256, dpi=256): """ make_tile_figure(height=256, width=256, dpi=256) create a transparent figure with a specified width, height, and dpi with no x/y ticks and axis turned off Ouput: figure and axes object """ fig = plt.figure(dpi=dpi, facecolor='none', edgecolor='none') fig.set_alpha(0) fig.set_figheight(height/dpi) fig.set_figwidth(width/dpi) figax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[]) figax.set_axis_off() return fig, figax def get_min_zoom(series): if 'MIN_ZOOM' in series: min_zoom = series.MIN_ZOOM elif 'min_zoom' in series: min_zoom = series.min_zoom else: min_zoom = 0 return min_zoom layers = [ { 'name': 'states_lines', 'shapefile_path': '/home/mchriste/Desktop/shapefiles/ne_10m_admin_1_states_provinces/ne_10m_admin_1_states_provinces.shp', 'linewidth': 0.3, 'edgecolor': '#b3b3b3' }, { 'name': 'countries', 'shapefile_path': '/home/mchriste/Desktop/shapefiles/ne_10m_admin_0_countries/ne_10m_admin_0_countries.shp', 'linewidth': 0.5, 'edgecolor': '#cccccc' }, { 'name': 'ne_10m_rivers_lake_centerlines', 'shapefile_path': '/home/mchriste/Desktop/shapefiles/ne_10m_rivers_lake_centerlines/ne_10m_rivers_lake_centerlines.shp', 'linewidth': 0.3, 'edgecolor': '#00ccff' }, { 'name': 'lakes', 'shapefile_path': '/home/mchriste/Desktop/shapefiles/ne_10m_lakes/ne_10m_lakes.shp', 'linewidth': 0.3, 'edgecolor': '#00ccff' } ] # project to EPSG:3857 for plotting EPSG3857 = pyproj.Proj(init='EPSG:3857') tile_zoom_levels = range(3,9) for zoom in tile_zoom_levels: # create the figure and axes fig, ax = make_tile_figure() ax.set_frame_on(False) ax.set_clip_on(False) ax.set_position([0, 0, 1, 1]) # add layers to figure axes # import pdb; pdb.set_trace() for layer in layers: #read shapefile and make sure we dont have any missing values in geometry column df = geopandas.read_file(layer['shapefile_path']) trimmed_df = df[(get_min_zoom(df) <= zoom) & (df.geometry.notnull())] trimmed_df_reproject = trimmed_df.to_crs(epsg=3857) trimmed_df_reproject.plot(facecolor='none', edgecolor=layer['edgecolor'], linewidth=layer['linewidth'], ax=ax) # get list of all tiles for certain geographic extents and zoom tiles_gen = mercantile.tiles(west=-180, south=-89.9, east=180, north=89.9, zooms=zoom) tiles = [tile for tile in tiles_gen] # create and save tiles for tile_indx in range(0,len(tiles)): print('Working on {} of {}'.format(tile_indx,len(tiles)-1)) tile = tiles[tile_indx] i,j,zoom=[*tile] ll = mercantile.bounds(i, j, zoom) _epsg_x_min, _epsg_y_min = EPSG3857(*ll[:2]) _epsg_x_max, _epsg_y_max = EPSG3857(*ll[2:]) # set x/y limits to match available tile extents ax.set_xlim(_epsg_x_min,_epsg_x_max) ax.set_ylim(_epsg_y_min, _epsg_y_max) filename = '{0}/{1}/{2}/{3}.png'.format('coastline_tiles', zoom, i, j) # import pdb; pdb.set_trace() if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) # only run during local testing dpi=256 # dpi for output tile fig.savefig(filename, dpi=dpi, pad_inches=0.0, transparent=True) # release memory plt.close() # EXTRA -- HOW TO ADD LABELS -- # for index, row in df_countries.iterrows(): # try: # if row.NAME_EN and row.geometry.centroid.coords[0]: # ax.text(row.geometry.centroid.coords[0][0],row.geometry.centroid.coords[0][1],row.NAME_EN, # ha='center', va='center', fontsize=4) # except: # continue <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import classNames from 'classnames'; import Typography from '@material-ui/core/Typography'; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import LoadingSpinner from './LoadingSpinner'; import MetOceanTimeseries from './MetOceanTimeseries'; import MetOceanProfile from './MetOceanProfile'; import withMobileDialog from '@material-ui/core/withMobileDialog'; const styles = theme => ({ loadingText: { display: 'block', fontSize: 16, }, loadingContent: { textAlign: 'center' } }); class ChartModal extends React.Component { state = { open: true, }; handleClose = () => { this.setState({ open: false }, () => { this.props.closeChartModal(); }); }; buildChartObj = () => { if (this.props.chartType === 'timeseries') { return ( <MetOceanTimeseries chartData={this.props.chartData} activeLocation={this.props.activeLocation} chartLoadingErrors={this.props.chartLoadingErrors} /> ) } else { return ( <MetOceanProfile chartData={this.props.chartData} activeLocation={this.props.activeLocation} chartLoadingErrors={this.props.chartLoadingErrors} /> ) } } render() { const { classes, fullScreen } = this.props; // let isTimeseries = this.props.chartType === 'timeseries'; return ( <React.Fragment> <Dialog fullScreen={fullScreen} fullWidth={true} maxWidth={'lg'} open={this.state.open} onClose={this.handleClose} aria-labelledby="max-width-dialog-title" > <DialogContent className={classNames({[classes.loadingContent]: this.props.chartLoading})}> {this.props.chartLoading ? <React.Fragment> <LoadingSpinner largeStyle={true}/> <Typography className={classes.loadingText} variant="overline" gutterBottom> Fetching Data </Typography> </React.Fragment> : this.buildChartObj() } </DialogContent> <DialogActions> <Button onClick={this.handleClose} style={{backgroundColor: 'lightgray'}}> Close </Button> </DialogActions> </Dialog> </React.Fragment> ); } } ChartModal.propTypes = { classes: PropTypes.object.isRequired, }; const StyledModal = withStyles(styles, { withTheme: true })(ChartModal); export default withMobileDialog({breakpoint: 'sm'})(StyledModal); <file_sep># -*- coding: utf-8 -*- """ Created on Mon Apr 09 19:12:40 2018 @author: Michael """ import collections import datetime import re import urllib.request as urllib import numpy as np from bs4 import BeautifulSoup def get_latest_RTOFS_forecast_time(rtofs_url, grid_dim='2d'): """ get_latest_RTOFS_forecast_time(rtofs_url) This function assembles an object with the latest available date and data url for both the nowcast and forecast ----------------------------------------------------------------------- Inputs: {string} rtofs_url - the RTOFS opendap url {string} grid_dim - the RTOFS grid dimension '2d' or '3d' (i.e. the 2d surface data or 3d full water column data) ex: 'https://nomads.ncep.noaa.gov/dods/rtofs/rtofs_global20180516/rtofs_glo_2ds_nowcast_daily_prog' ----------------------------------------------------------------------- Output: object with this structure: available_data = {'nowcast': {'latest_date': 'yyyymmdd', 'url': xxx}, 'forecast': {'forecast': {'latest_date': 'yyyymmdd', 'url': xxx}} ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/21/2022 """ page = urllib.urlopen(rtofs_url).read() soup = BeautifulSoup(page,'html.parser') soup.prettify() date_array=np.array([]) for anchor in soup.findAll('a', href=True): anchor_str = anchor['href'] match = re.search(r'rtofs_global(\d{8})$', anchor_str) if match: unformatted_date = match.group(1) datetime_element = datetime.datetime.strptime(unformatted_date,'%Y%m%d') date_array = np.append(date_array, datetime_element) #sort available forecast dates in reverse order so most recent is first sorted_dates = np.sort(date_array)[::-1] sorted_dates_str = [datetime.datetime.strftime(d,'%Y%m%d') for d in sorted_dates] forecast_info = collections.OrderedDict() if grid_dim is '2d': nowcast_suffix = 'rtofs_glo_2ds_nowcast_3hrly_prog' forecast_suffix = 'rtofs_glo_2ds_forecast_3hrly_prog' else: # assume that if uvel is present vvel is also present nowcast_suffix = 'rtofs_glo_3dz_nowcast_daily_uvel' forecast_suffix = 'rtofs_glo_3dz_forecast_daily_uvel' if len(sorted_dates_str): for forecast_indx, forecast_date in enumerate(sorted_dates_str): rtofs_product_page_url = rtofs_url + '/rtofs_global' + sorted_dates_str[forecast_indx] rtofs_product_page = urllib.urlopen(rtofs_product_page_url).read().decode('utf-8') nowcast_data_available = nowcast_suffix in rtofs_product_page forecast_data_available = forecast_suffix in rtofs_product_page if nowcast_data_available and not 'nowcast' in forecast_info: forecast_info['nowcast']={'latest_date': forecast_date, 'url': rtofs_product_page_url + '/' + nowcast_suffix} if forecast_data_available and not 'forecast' in forecast_info: forecast_info['forecast']={'latest_date': forecast_date, 'url': rtofs_product_page_url + '/' + forecast_suffix} #return a dictionary with the date and data_url to grab from return forecast_info if __name__ == "__main__": rtofs_url = 'https://nomads.ncep.noaa.gov/dods/rtofs' get_latest_RTOFS_forecast_time(rtofs_url) <file_sep>import boto3 import pickle import datetime import time import numpy as np import mercantile import pyproj from scipy import interpolate from matplotlib import pyplot as plt, cm import matplotlib.colors as colors import cmocean import copy import io import os import PIL import pyproj cmap_config = { 'wind_speed': {'color_map': cm.get_cmap('rainbow'), 'data_range': [0,25]}, 'current_speed': {'color_map': cmocean.cm.speed, 'data_range': [0,2]}, 'wave_amp': {'color_map': cm.get_cmap('rainbow'), 'data_range': [0,10]}, 'wave_dir': {'color_map': None, 'data_range': [None, None]} } #def build_tiles(data_struct, data_type, bucket_name, output_file_path, zoom_array=range(4,5)): def lambda_handler(event, context): """ build_tiles(data_struct, data_type, bucket_name, output_file_path, zoom_array=range(4,9)): This function creates tiles (.png) and saves them in S3 ----------------------------------------------------------------------- Inputs: data_struct: (object) - an object containing latitude, longitude, data, level, and datetime information i.e. {'lat': lat_trim, 'lon': lon_ordered, 'u_vel': u_data_cleaned, 'v_vel': v_data_cleaned, 'datetime': '20180828_00', 'level': '10m'} data_type: (string) - one of 'wind_speed', 'current_speed', 'wave_height', 'wave_period' bucket_name: (string) the name of the S3 bucket ('oceanmapper-data-storage') output_file_path: (string) - the location where the file will be saved on S3 zoom_array: (array) the zoom levels to make tiles for *(http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/) ----------------------------------------------------------------------- Output: A .png files are saved to S3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 07/28/2018 """ # process the data in preparation for tiling if np.ma.is_masked(data['lat']): lat = data['lat'].data else: lat = data['lat'] if np.ma.is_masked(data['lon']): lon = data['lon'].data else: lon = data['lon'] # remove the north/south pole lats since these cause issues when projecting to epsg:3857 keep_lat_bool = np.logical_and(lat<90, lat>-90) keep_lat_indx = np.argwhere(keep_lat_bool).ravel() lat_trim = lat[keep_lat_indx] # create lat/lon mesh grid _lon,_lat = np.meshgrid(lon,lat_trim) # project to EPSG:3857 for plotting EPSG3857 = pyproj.Proj(init='EPSG:3857') lo,la = EPSG3857(_lon,_lat) # sort by EPSG3857 because our drawing surface is in EPSG3857, data still ordered by lon/lat so = np.argsort(lo[1,:]) sa = np.argsort(la[:,1]) for zoom in zoom_array: # tile logic (only render tiles where data exists) tiles = mercantile.tiles(west=lon.min(), south=lat.min(), east=lon.max(), north=lat.max(), zooms=[zoom]) #TODO: plot entire image on 256 by 256 image then crop to tile extents height = 256 width = 256 dpi = 256 fig = plt.figure(dpi=dpi, facecolor='none', edgecolor='none') fig.set_alpha(0) fig.set_figheight(height/dpi) fig.set_figwidth(width/dpi) ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[]) ax.set_axis_off() proj_lon_array = lo[sa,:][:,so] proj_lat_array = la[sa,:][:,so] data_cmap = cmap_config[data_type]['color_map'] cmin, cmax = cmap_config[data_type]['data_range'] if data_type == 'wind_speed' or data_type == 'current_speed': u_vel = data['u_vel'][keep_lat_indx,:] v_vel = data['v_vel'][keep_lat_indx,:] data_array = np.sqrt(u_vel[sa,:][:,so]**2 + v_vel[sa,:][:,so]**2) nlvls = 100 lvls = np.linspace(cmin, cmax, nlvls) ## filled contour (use SORTED indexes for the EPSG3857 drawing surface) contourf = ax.contourf(proj_lon_array, proj_lat_array, data_array[sa,:][:,so], levels=lvls, cmap=data_cmap) elif data_type == 'wave_amp': height_raw = data['sig_wave_height'][keep_lat_indx,:] palette = copy.copy(data_cmap) palette.set_bad(alpha = 0.0) # ax.pcolormesh(proj_lon_array, proj_lat_array, height_raw, shading='flat', cmap=palette, # norm=colors.BoundaryNorm([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],ncolors=palette.N)) ax.contourf(proj_lon_array, proj_lat_array, height_raw[sa,:][:,so], cmap=palette, levels=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) elif data_type == 'wave_dir': dir_raw = data['primary_wave_dir'][keep_lat_indx,:] #directions are in degrees already import pdb; pdb.set_trace() else: pass #TODO the interval will vary for lat vs lon... figure out the correct interval dynamically # for wave directions.. get directions in degrees then find the corresponding u and v for magnitude 1 # using md2uv... all the vectors will have the same magnitude... for wave we start with directions (make this test_data) # wind_abs = data_array # wind_dir_trig_to = atan2(u_ms/wind_abs, v_ms/wind_abs) # wind_dir_trig_to_degrees = wind_dir_trig_to * 180/pi ## -111.6 degrees # intv=10 # # add quiver when working with wave height/direction # quiver = ax.quiver(proj_lon_array[::intv,::intv], proj_lat_array[::intv,::intv], # u_vel[sa,:][:,so][::intv,::intv], v_vel[sa,:][:,so][::intv,::intv], # width=.0005, headwidth=4.2, headlength=4, headaxislength=3.8, minlength=0) ax.set_frame_on(False) ax.set_clip_on(False) ax.set_position([0, 0, 1, 1]) t0 = time.time() for tile in tiles: i,j,zoom=[*tile] ll = mercantile.bounds(i, j, zoom) _epsg_x_min, _epsg_y_min = EPSG3857(*ll[:2]) _epsg_x_max, _epsg_y_max = EPSG3857(*ll[2:]) # set x/y limits to match available tile extents ax.set_xlim(_epsg_x_min,_epsg_x_max) ax.set_ylim(_epsg_y_min, _epsg_y_max) if bucket_name is 'local': filename = '{0}{1}_{2}_{3}.png'.format(output_file_path, zoom, i, j) else: filename = '{0}/{1}/{2}/{3}.png'.format(output_file_path, zoom, i, j) print('working on: ' + filename) # only run during local testing if bucket_name is 'local': if not os.path.exists(os.path.dirname(filename)): try: os.makedirs(os.path.dirname(filename)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise fig.savefig(filename, dpi=dpi, pad_inches=0.0, transparent=True) else: # save image to memory and then push to s3 with io.BytesIO() as out_img: fig.savefig(out_img,format='png', dpi=dpi, pad_inches=0.0, transparent=True) out_img.seek(0) client = boto3.client('s3') client.put_object(Body=out_img, Bucket=bucket_name, Key=filename, ACL='public-read') # print timing metrics t1 = time.time() print(t1-t0, 'seconds for zoom level: ', zoom) # release memory fig.clf() plt.close() def md2uv(magnitude, direction, orientation='from'): """ md2uv(magnitude, dir) convert magnitude and direction to u and v components """ # fig, axes = plt.subplots(111) # fig = plt.figure() # ax = fig.add_subplot(111) # convert direction to compass direction direction = np.array([[0.0, 45.0], [90.0, 135.0]]) if orientation == 'toward': direction_compass = np.mod(90.0 - direction, 360) else: direction_compass = np.mod(90.0 - direction + 180, 360) #convert directions to radians direction_rad = direction_compass * (np.pi/180) # this is just for testing.. it should be passed in as an argument magnitude = np.ones_like(direction_compass) u_comp = magnitude * np.cos(direction_rad) v_comp = magnitude * np.sin(direction_rad) # ax.quiver(u_comp[0,0],v_comp[0,0]) # fig.show() # rad = 4.0*atan(1.0)/180. # u_comp = -spd*sin(rad*dir) # v = -spd*cos(rad*dir) return (u_comp,v_comp) if __name__ == "__main__": # with open("gfs_winds_20180725_06.pickle", "rb") as f: # data = pickle.load(f) with open("wave_data_good.pickle", "rb") as f: data = pickle.load(f) # datetime_today_floor = datetime.date.today().strftime('%Y%m%d_00') # output_file_path = 'test_folder/' + datetime_today_floor + '/10m/tiles/' # build_tiles(data, 'wind_speed', 'local', output_file_path, 2) # output_file_path = 'test_tiles' output_file_path = 'test_tiles_waves' # output_file_path = 'GFS_WINDS/20180801_00/10m/tiles/gfs_winds' # build_tiles(data, 'wind_speed', 'oceanmapper-data-storage', output_file_path, range(4,5)) build_tiles(data, 'wave_amp', 'oceanmapper-data-storage', output_file_path, range(4,5)) # build_tiles(data, 'wave_dir', 'oceanmapper-data-storage', output_file_path, range(4,5)) # with open('wave_data_good.pickle', 'wb') as handle: # pickle.dump(raw_data, handle, protocol=pickle.HIGHEST_PROTOCOL) # with open('wave_data_good.pickle', 'rb') as handle: # b = pickle.load(handle) # import io # import os # with open("test.xlsx",'rb') as f: # g=io.BytesIO(f.read()) ## Getting an Excel File represented as a BytesIO Object # temporarylocation="testout.xlsx" # with open(temporarylocation,'wb') as out: ## Open temporary file as bytes # out.write(g.read()) ## Read bytes into file # ## Do stuff with module/file # os.remove(temporarylocation) ## Delete file when done <file_sep>attrs==22.1.0 beautifulsoup4==4.11.1 boto3==1.24.93 botocore bs4==0.0.1 certifi==2022.9.24 cftime==1.6.2 chardet==3.0.4 click==8.1.3 click-plugins==1.1.1 cligj==0.7.2 cmocean==1.2 contourpy==1.0.5 cycler==0.11.0 Fiona==1.8.22 fonttools==4.37.4 geopandas==0.11.1 idna==2.7 jmespath==1.0.1 kiwisolver==1.4.4 matplotlib==3.6.1 mercantile==1.0.4 munch==2.5.0 netCDF4==1.6.1 numpy==1.23.4 packaging==21.3 pandas==1.5.0 Pillow==9.2.0 pyparsing==3.0.9 PyPDF2==1.26.0 pyproj==3.4.0 python-dateutil==2.8.2 pytz==2022.5 requests s3transfer==0.6.0 scipy==1.9.2 Shapely==1.8.5.post1 six==1.16.0 soupsieve==2.3.2.post1 typing_extensions==4.4.0 urllib3 xarray==2022.10.0 <file_sep>import sys sys.path.append("..") import boto3 import datetime import json import re from harvest_utils.remote_data_info import get_max_date from GFS.GFS_forecast_info import get_gfs_forecast_info s3 = boto3.resource('s3') AWS_BUCKET_NAME = 'oceanmapper-data-storage' def is_data_fresh(): ''' Checks if the latest available forecast field in s3 bucket matches the extent of the latest GFS forecast run. Returns True if the forecast extents match (i.e. the data is fresh) ''' s3_max_date = get_max_date('GFS_DATA') # get the max of s3_dates and compare to max_remote_date gfs_url = 'https://nomads.ncep.noaa.gov:9090/dods/gfs_0p25' forecast_info = get_gfs_forecast_info(gfs_url) max_datasource_date = forecast_info['data'][-1][1] if s3_max_date != max_datasource_date: return False return True if __name__ == "__main__": is_data_fresh() <file_sep>import sys sys.path.append("..") import urllib.request as urllib from bs4 import BeautifulSoup import datetime import numpy as np import re from harvest_utils.fetch_utils import get_opendapp_netcdf def get_gfs_forecast_info(gfs_url): """ get_gfs_forecast_info(gfs_url) This function assembles an array tuples containing the model forecast field datetime as well as the index of the forecast field. This facilitates to concurrent downloads of model data. ----------------------------------------------------------------------- Input: {string} gfs_url - displays available GFS forecast model runs i.e. http://nomads.ncep.noaa.gov:9090/dods/gfs_0p25 ----------------------------------------------------------------------- Output: array of tuples with this structure: forecast_info = [(forecast_indx, forecast_field_datetime), ...] """ page = urllib.urlopen(gfs_url).read() soup = BeautifulSoup(page,'html.parser') soup.prettify() date_array = np.array([]) for anchor in soup.findAll('a', href=True): anchor_str = anchor['href'] match = re.search(r'gfs(\d{8})$', anchor_str) if match: unformatted_date = match.group(1) datetime_element = datetime.datetime.strptime(unformatted_date,'%Y%m%d') date_array = np.append(date_array, datetime_element) max_forecast_run_date = np.max(date_array) formatted_latest_date = datetime.datetime.strftime(max_forecast_run_date, '%Y%m%d') # find the latest run using bs4 forecast_run_url = gfs_url +'/gfs' + formatted_latest_date page = urllib.urlopen(forecast_run_url).read() soup = BeautifulSoup(page,'html.parser') soup.prettify() forecast_run_array = {} for model_run in soup.findAll('b'): match = re.search(r'(gfs_.*_(\d{2})z):$', model_run.string) if match: run_name = match.group(1) forecast_run_hour = match.group(2) forecast_run_array.setdefault(int(forecast_run_hour), run_name) # build forecast field datetime/indx array max_run = max(forecast_run_array.keys()) opendapp_url = forecast_run_url + '/' + run_name with get_opendapp_netcdf(opendapp_url) as file: product_times = file.variables['time'][:] forecast_info = {} forecast_info['url'] = opendapp_url forecast_info['data'] = [] for forecast_indx, forecast_time in enumerate(product_times): basetime_int = int(forecast_time) extra_days = forecast_time - basetime_int # need to subtract 1 since GFS is days since 0001-01-01 (yyyy-mm-dd) full_forecast_time = (datetime.datetime.fromordinal(basetime_int) + datetime.timedelta(days = extra_days) - datetime.timedelta(days=1)) forecast_info['data'].append((forecast_indx, full_forecast_time)) return forecast_info if __name__ == "__main__": gfs_url = 'https://nomads.ncep.noaa.gov:9090/dods/gfs_0p25' get_gfs_forecast_info(gfs_url) <file_sep># -*- coding: utf-8 -*- """ Created on Mon Apr 2 17:20:30 2018 @author: <NAME> """ import json import datetime import pickle import time import numpy as np from scipy import interpolate import netCDF4 import boto3 from utils.fetch_utils import get_opendapp_netcdf from utils.tile_task_distributor import tile_task_distributor from utils.pickle_task_distributor import pickle_task_distributor from utils.datasets import datasets def lambda_handler(event, context): """ lambda_handler(event, context): This function creates .json, .pickle, and .png files from a netCDF file. This netCDF file comes from an opendapp url (contained within the event paramater object). ----------------------------------------------------------------------- Inputs: event: AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type. context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Output: .json file, .pickle file, and .png files are save to S3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/08/2018 """ AWS_BUCKET_NAME = 'oceanmapper-data-storage' TOP_LEVEL_FOLDER = 'GFS_DATA' SUB_RESOURCE = 'wind_speed' DATA_PREFIX = 'gfs_winds' # unpack event data url = event['url'] model_field_time = datetime.datetime.strptime(event['forecast_time'],'%Y%m%dT%H:%M') model_field_indx = event['forecast_indx'] level = '10m' file = get_opendapp_netcdf(url) formatted_folder_date = datetime.datetime.strftime(model_field_time,'%Y%m%d_%H') output_json_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE + '/' + level + '/json/' + DATA_PREFIX + '_' + formatted_folder_date + '.json') output_pickle_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE + '/' + level + '/pickle/' + DATA_PREFIX + '_' + formatted_folder_date + '.pickle') output_tile_scalar_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE + '/' + level + '/tiles/scalar/') output_tile_data_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE + '/' + level + '/tiles/data/') output_info_path = TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/info.json' # get model origin time init_time = file.variables['time'][0] basetime_int = int(init_time) extra_days = init_time - basetime_int time_origin = (datetime.datetime.fromordinal(basetime_int) + datetime.timedelta(days = extra_days) - datetime.timedelta(days=1)) lat = file.variables['lat'][:] lon = file.variables['lon'][:] u_data_raw = file.variables['ugrd10m'][model_field_indx,:,:] #[time,lat,lon] v_data_raw = file.variables['vgrd10m'][model_field_indx,:,:] # ordered lat array lat_sort_indices = np.argsort(lat) lat_ordered = lat[lat_sort_indices] # remap and sort to -180 to 180 grid lon_translate = np.where(lon>180, lon-360.0, lon) lon_sort_indices = np.argsort(lon_translate) # ordered longitude arrays lon_ordered = lon_translate[lon_sort_indices] # rebuild u/v data with correct longitude sorting (monotonic increasing) u_data_cleaned = u_data_raw[lat_sort_indices,:][:,lon_sort_indices] v_data_cleaned = v_data_raw[lat_sort_indices,:][:,lon_sort_indices] # assign the raw data to a variable so we can pickle it for use with other scripts raw_data = {'lat': lat_ordered, 'lon': lon_ordered, 'u_vel': u_data_cleaned, 'v_vel': v_data_cleaned, 'datetime': formatted_folder_date, 'level': level, 'time_origin': time_origin} raw_data_pickle = pickle.dumps(raw_data) # create interpolation functions u_interp_func = interpolate.interp2d(lon_ordered, lat_ordered, u_data_cleaned, kind='cubic') v_interp_func = interpolate.interp2d(lon_ordered, lat_ordered, v_data_cleaned, kind='cubic') output_lat_array = np.arange(int(min(lat)),int(max(lat))+0.5,0.5) # last point is excluded with arange (80 to -80) output_lon_array = np.arange(-180,180.5,0.5) # last point is excluded with arange (-180 to 180) u_data_interp = u_interp_func(output_lon_array, output_lat_array) v_data_interp = v_interp_func(output_lon_array, output_lat_array) minLat = np.min(output_lat_array) maxLat = np.max(output_lat_array) minLon = np.min(output_lon_array) maxLon = np.max(output_lon_array) dx = np.diff(output_lon_array)[0] dy = np.diff(output_lat_array)[0] output_data = [ {'header': { 'parameterUnit': "m.s-1", 'parameterNumber': 2, 'dx': dx, 'dy': dy, 'parameterNumberName': "Eastward wind", 'la1': maxLat, 'la2': minLat, 'parameterCategory': 2, 'lo1': minLon, 'lo2': maxLon, 'nx': len(output_lon_array), 'ny': len(output_lat_array), 'refTime': datetime.datetime.strftime(model_field_time,'%Y-%m-%d %H:%M:%S'), 'timeOrigin': datetime.datetime.strftime(time_origin,'%Y-%m-%d %H:%M:%S'), }, 'data': [float('{:.3f}'.format(el)) if np.abs(el) > 0.0001 else 0 for el in u_data_interp[::-1].flatten().tolist()] }, {'header': { 'parameterUnit': "m.s-1", 'parameterNumber': 3, 'dx': dx, 'dy': dy, 'parameterNumberName': "Northward wind", 'la1': maxLat, 'la2': minLat, 'parameterCategory': 2, 'lo1': minLon, 'lo2': maxLon, 'nx': len(output_lon_array), 'ny': len(output_lat_array), 'refTime': datetime.datetime.strftime(model_field_time,'%Y-%m-%d %H:%M:%S'), 'timeOrigin': datetime.datetime.strftime(time_origin,'%Y-%m-%d %H:%M:%S'), }, 'data': [float('{:.3f}'.format(el)) if np.abs(el) > 0.0001 else 0 for el in v_data_interp[::-1].flatten().tolist()] }, ] client = boto3.client('s3') client.put_object(Body=json.dumps(output_data), Bucket=AWS_BUCKET_NAME, Key=output_json_path) client.put_object(Body=raw_data_pickle, Bucket=AWS_BUCKET_NAME, Key=output_pickle_path) # save an info file for enhanced performance (get_model_field_api.py) client.put_object(Body=json.dumps({'time_origin': datetime.datetime.strftime(time_origin,'%Y-%m-%d %H:%M:%S')}), Bucket=AWS_BUCKET_NAME, Key=output_info_path) # call an intermediate function to distribute pickling workload (subsetting data by tile) data_zoom_level = datasets[TOP_LEVEL_FOLDER]['sub_resource'][SUB_RESOURCE]['data_tiles_zoom_level'] pickle_task_distributor(output_pickle_path, AWS_BUCKET_NAME, output_tile_data_path, data_zoom_level) file.close() if __name__ == "__main__": lambda_handler('','') <file_sep>import json import re import boto3 s3 = boto3.resource('s3') AWS_BUCKET_NAME = 'oceanmapper-data-storage' datasets = ['HYCOM_DATA', 'RTOFS_DATA', 'WW3_DATA', 'GFS_DATA'] def lambda_handler(event, context): data_bucket = s3.Bucket(AWS_BUCKET_NAME) availability_struct = {} for dataset_value in datasets: availability_struct[dataset_value] = {} filtered_objects = data_bucket.objects.filter(Prefix=dataset_value) for object in filtered_objects: pattern = r'model_folder/(\d{8}_\d{2})/(\w*)/?(\w*)/(json|pickle)/.*[.](json|pickle)$'.replace('model_folder',dataset_value) match = re.search(pattern,object.key) if match: parsed_date = match.group(1) parsed_sub_resource = match.group(2) parsed_level = match.group(3) parsed_type = match.group(4) availability_struct[dataset_value].setdefault(parsed_sub_resource,{}) availability_struct[dataset_value][parsed_sub_resource].setdefault('level',{}) availability_struct[dataset_value][parsed_sub_resource]['level'].setdefault(parsed_level,{}) availability_struct[dataset_value][parsed_sub_resource]['level'][parsed_level].setdefault(parsed_type,[]).append(parsed_date) # dump json file to s3 output_json_path = 'data_availability.json' client = boto3.client('s3') client.put_object(Body=json.dumps(availability_struct), Bucket=AWS_BUCKET_NAME, Key=output_json_path) if __name__ == '__main__': lambda_handler('','') <file_sep>import boto3 import datetime import numpy as np import json import re s3 = boto3.resource('s3') bucket = 'oceanmapper-data-storage' datasets = { 'hycom_currents': 'HYCOM_OCEAN_CURRENTS_3D', 'rtofs_currents': 'RTOFS_OCEAN_CURRENTS_3D/', 'gfs_winds': 'GFS_WINDS/' } def lambda_handler(event, context): if event['queryStringParameters']: if 'time' in event['queryStringParameters']: model_time = event['queryStringParameters']['time'] datetime_pattern=r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z' datetime_match = re.search(datetime_pattern,model_time) if datetime_match: model_time_datetime = datetime.datetime.strptime(model_time,'%Y-%m-%dT%H:%MZ') if 'model' in event['queryStringParameters']: model = event['queryStringParameters']['model'] dataset_value = datasets[model] if 'level' in event['queryStringParameters']: level = event['queryStringParameters']['level'] level_formatted = str(level) + 'm' # TODO: need to make sure all required query params are present before moving forward.. # if not return some message 404... # TODO: to speed things up should we be running some kind of chron job to keep track of what times # are available for each data source.. save that as json in a folder data_bucket = s3.Bucket(bucket) filtered_model_times = data_bucket.objects.filter(Prefix=dataset_value) # empty arrays to be populated available_times = [] available_keys = [] for object in data_bucket.objects.filter(Prefix=dataset_value): pattern = r'model_folder/(\d{8}_\d{2})/level/json/.*[.]json$'.replace( 'model_folder',dataset_value).replace('level',level_formatted) match = re.search(pattern,object.key) if match: model_field_date = datetime.datetime.strptime(match.group(1),'%Y%m%d_%H') if (model_field_date <= model_time_datetime): available_times.append(model_field_date) available_keys.append(object.key) # get nearest time (going backwards) available_times_arr = np.array(available_times) trimmed_available_times = available_times_arr[available_times_arr <= model_time_datetime] # select the last time available_time = None # default value data_key = None if len(trimmed_available_times): available_time = trimmed_available_times[-1] available_time_str = datetime.datetime.strftime(available_time,'%Y-%m-%dT%H:%MZ') available_indx = len(trimmed_available_times) - 1 data_key = available_keys[available_indx] # get the file raw_data = s3.Object(bucket, data_key) try: response_body = { 'model': model, 'valid_time': available_time_str, 'data': raw_data.get()['Body'].read().decode('utf-8') } return { 'statusCode': 200, 'body': json.dumps(response_body), 'headers': {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'} } except Exception as e: response_body = { 'status': 'data not available', } return { 'statusCode': 404, 'body': json.dumps(response_body), 'headers': {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'} } else: response_body = { 'model': model, 'valid_time': None, 'data': None } return { 'statusCode': 200, 'body': json.dumps(response_body), 'headers': {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'} } if __name__ == '__main__': event = { "queryStringParameters": { "level": 10, "model": "hycom_currents", "time": "2018-09-03T02:00Z" } } lambda_handler(event,'') <file_sep># -*- coding: utf-8 -*- """ Created on Mon Apr 2 17:20:30 2018 @author: <NAME> """ import json import boto3 import numpy as np from RTOFS_forecast_info import get_latest_RTOFS_forecast_time from build_model_times import assemble_model_timesteps import datetime lam = boto3.client('lambda') def lambda_handler(event, context): """ lambda_handler(event, context): This function invokes concurrent lambda functions to read, parse, and save high temporal resolution (3hrly) RTOFS ocean current data for the surface level ----------------------------------------------------------------------- Inputs: event: AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type. context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Output: No output ----------------------------------------------------------------------- Author: <NAME> Date Modified: 02/06/2019 """ rtofs_url = 'https://nomads.ncep.noaa.gov:9090/dods/rtofs' available_data = get_latest_RTOFS_forecast_time(rtofs_url, '2d') output_info = assemble_model_timesteps(available_data, '3hrly') for product_type in output_info['products'].keys(): zipped_time_and_indx = np.array(tuple(zip(output_info['products'][product_type]['field_datetimes'], output_info['products'][product_type]['forecast_indx']))) for model_field in zipped_time_and_indx: model_field_indx = model_field[1] # build payload for initiation of lambda function payload = {} payload['url'] = output_info['products'][product_type]['url'] payload['forecast_time'] = datetime.datetime.strftime(model_field[0],'%Y%m%dT%H:%M') payload['forecast_indx'] = model_field_indx # InvocationType = RequestResponse # this is used for synchronous lambda calls try: response = lam.invoke(FunctionName='grab_rtofs_highres', InvocationType='Event', Payload=json.dumps(payload)) except Exception as e: print(e) raise e print(response) if __name__ == "__main__": lambda_handler('','') <file_sep>import express from 'express'; import request from 'request'; const apiGatewayRouter = express.Router(); // creating a mapping object to facilitate condensing code below const apiGatewayRouteMapping = { '/individual-field': process.env.INDIVIDUAL_FIELD_ENDPOINT, '/point-data': process.env.POINT_DATA_ENDPOINT, '/timeseries-data': process.env.TIMESERIES_DATA_ENDPOINT, '/profile-data': process.env.PROFILE_DATA_ENDPOINT } // https://stackoverflow.com/questions/39301227/external-api-calls-with-express-node-js-and-require-module apiGatewayRouter.get(['/individual-field', '/point-data', '/timeseries-data','/profile-data'], function(req, res, next) { let path = req.path; let uri = apiGatewayRouteMapping[path]; request({ uri: uri, headers: { 'x-api-key': process.env.AWS_API_GATEWAY_KEY }, qs: req.query, }).pipe(res); }); export default apiGatewayRouter; <file_sep>/* * Import required packages. * Packages should be installed with "npm install". */ const express = require('express'); const aws = require('aws-sdk'); const path = require('path'); const morgan = require('morgan'); const bodyParser = require('body-parser'); const errorHandler = require('errorhandler'); const listFilesRouter = require('./scripts/serverside_nodejs_scripts/listFiles.js'); aws.config.region = 'us-east-1'; const S3_BUCKET = process.env.S3_BUCKET_NAME; /* * Set-up and run the Express app. */ const app = express(); // app.set('views', './views'); app.use(express.static('views')) app.use('/scripts', express.static('scripts')) app.use('/external_libraries', express.static('external_libraries')) // logging middleware app.use(morgan('dev')); // body parsing middleware attaches body to request object app.use(bodyParser.json()); // app.use(express.static(path.join(__dirname))); // app.use("/styles", express.static(__dirname + '/styles')); // app.use("/images", express.static(__dirname + '/images')); // app.use("/scripts", express.static(__dirname + '/scripts')); app.engine('html', require('ejs').renderFile); // viewed at based directory http://localhost:8080/ app.get('/', function (req, res) { // res.sendFile(path.join(__dirname + '/views/index.html')); res.render('index.html'); }); // add other routes below app.get('/about', function (req, res) { // res.sendFile(path.join(__dirname + 'views/about.html')); console.log(res); }); app.get('/sign-s3', (req, res) => { const s3 = new aws.S3(); // console.log(s3) console.log(S3_BUCKET) // s3.getObject( // { Bucket: S3_BUCKET, Key: "RTOFS_OC/0m/rtofs_currents_20160512_00.json" }, // function (error, data) { // if (error != null) { // alert("Failed to retrieve an object: " + error); // } else { // alert("Loaded " + data.ContentLength + " bytes"); // // do something with data.Body // } // } // ); // const fileName = req.query['file-name']; // const fileType = req.query['file-type']; // let fileName = 'RTOFS_OC/0m/rtofs_currents_20160512_00.json'; let fileName = req.query['file-name']; console.log(fileName); const s3Params = { Bucket: S3_BUCKET, Key: fileName, }; s3.getSignedUrl('getObject', s3Params, (err, data) => { if(err){ console.log(err); return res.end(); } const returnData = { signedRequest: data, url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}` }; res.write(JSON.stringify(returnData)); res.end(); }); }); // Import and mount the listFilesRouter app.use('/list-files', listFilesRouter); app.get('/download', (req, res) => { // const fileName = req.query['file-name']; // const bucket = req.query['bucket']; const s3 = new aws.S3(); const s3Params = { Bucket: S3_BUCKET, Key: "RTOFS_OC/0m/rtofs_currents_20160512_00.json" }; s3.getObject(s3Params, function (error, data) { if (error != null) { // alert("Failed to retrieve an object: " + error); } else { // alert("Loaded " + data.ContentLength + " bytes"); // Convert Body from a Buffer to a String res.write(JSON.stringify(data.Body.toString('utf-8'))); //.toString('utf-8'); // console.log(data.ContentLength + ' bytes'); res.end(); } } ); }); // error handler here: (prior middleware should pass next(errorObj)) app.use(errorHandler()); // 404 on failed get (doesnt exist) // 400 dont do something for some reason // 204 sucessful delete // 200 sucessful get app.listen(process.env.PORT || 3000);<file_sep>import pickle import io import boto3 import numpy as np import mercantile from harvest_utils.datasets import datasets s3 = boto3.client('s3') def generate_pickle_files(data, dataset, sub_resource, output_tile_data_path, zoom, bucket_name): """ generate_pickle_files(data, dataset, sub_resource, output_tile_data_path, zoom, bucket_name) This function creates data 'tiles' (.pickle) -- subsetted data -- and saves them in S3 ----------------------------------------------------------------------- Inputs: data (dict) - dictionary containing raw forecast data dataset (str) - the top level dataset name (i.e. HYCOM_DATA, GFS_DATA, WW3_DATA) sub_resource (str) - the model subresource (i.e. ocean_current_speed, wind_speed, significant_wave_height) output_tile_data_path (str) - the output path for 'tile' data zoom (int) - the zoom level to create data tiles bucket_name (str) - the aws s3 bucket name ----------------------------------------------------------------------- Output: pickle files are saved to S3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 04/13/2019 """ # process the data in preparation for data 'tiling' if hasattr(data['lat'],'mask'): lat = data['lat'].data else: lat = data['lat'] if hasattr(data['lon'],'mask'): lon = data['lon'].data else: lon = data['lon'] lat_diff = np.abs(np.diff(lat)[0]) lon_diff = np.abs(np.diff(lon)[0]) time_origin = data['time_origin'] # get variables based on dataset variables = datasets[dataset]['sub_resource'][sub_resource]['variables'] # get list of all tiles for certain geographic extents and zooms tiles_gen = mercantile.tiles(west=lon.min(), south=lat.min(), east=lon.max(), north=lat.max(), zooms=zoom) tiles = [tile for tile in tiles_gen] for tile in tiles: i,j,zoom=[*tile] ll = mercantile.bounds(i, j, zoom) _wgs84_lon_min, _wgs84_lat_min = ll[:2] _wgs84_lon_max, _wgs84_lat_max = ll[2:] # extend bounds slightly to avoid issue with data being cut off at tile boundaries _wgs84_lon_min_padded = _wgs84_lon_min - (10 * lon_diff) _wgs84_lon_max_padded = _wgs84_lon_max + (10 * lon_diff) _wgs84_lat_min_padded = _wgs84_lat_min - (10 * lat_diff) _wgs84_lat_max_padded = _wgs84_lat_max + (10 * lat_diff) # trimming here based on the extents of the tile keep_lat_bool = np.logical_and(lat<=_wgs84_lat_max_padded, lat>=_wgs84_lat_min_padded) keep_lat_indx = np.argwhere(keep_lat_bool).ravel() keep_lon_bool = np.logical_and(lon<=_wgs84_lon_max_padded, lon>=_wgs84_lon_min_padded) keep_lon_indx = np.argwhere(keep_lon_bool).ravel() # TODO: add model valid time to output data output_data = {} output_data['lat'] = lat[keep_lat_indx] output_data['lon'] = lon[keep_lon_indx] output_data['time_origin'] = time_origin for var in variables: output_data[var] = data[var][keep_lat_indx,:][:,keep_lon_indx] filename = '{0}{1}/{2}/{3}.pickle'.format(output_tile_data_path, str(zoom), str(i), str(j)) # save the file with io.BytesIO() as f: pickle.dump(output_data,f,pickle.HIGHEST_PROTOCOL) f.seek(0) s3.upload_fileobj(f,bucket_name, filename) <file_sep># -*- coding: utf-8 -*- """ Created on Mon Apr 2 17:20:30 2018 @author: <NAME> """ import datetime import json import pickle import boto3 import numpy as np from scipy import interpolate from utils.datasets import datasets from utils.fetch_utils import get_opendapp_netcdf from utils.pickle_task_distributor import pickle_task_distributor def lambda_handler(event, context): """ lambda_handler(event, context): This function reads, parses, and saves a .json and .pickle file from a netCDF file from a provided opendapp url (contained within the event paramater object). ----------------------------------------------------------------------- Inputs: event: AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type. context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Output: A .json file and a .pickle file are save to S3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/21/2022 """ AWS_BUCKET_NAME = 'oceanmapper-data-storage' TOP_LEVEL_FOLDER = 'RTOFS_DATA' SUB_RESOURCE = 'ocean_current_speed' DATA_PREFIX = 'rtofs_currents' # unpack event data url = event['url'] model_field_time = datetime.datetime.strptime(event['forecast_time'], '%Y%m%dT%H:%M') model_field_indx = event['forecast_indx'] model_level_depth = event['level']['level_depth'] model_level_indx = event['level']['level_indx'] u_comp_url = url v_comp_url = url.replace('uvel', 'vvel') file_u = get_opendapp_netcdf(u_comp_url) file_v = get_opendapp_netcdf(v_comp_url) formatted_folder_date = datetime.datetime.strftime(model_field_time, '%Y%m%d_%H') output_json_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE + '/' + str(model_level_depth) + 'm/json/' + DATA_PREFIX + '_' + formatted_folder_date + '.json') output_pickle_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE + '/' + str(model_level_depth) + 'm/pickle/' + DATA_PREFIX + '_' + formatted_folder_date + '.pickle') output_tile_data_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE + '/' + str(model_level_depth) + 'm/tiles/data/') output_info_path = TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/info.json' # get model origin time if 'nowcast' in u_comp_url: time_orig_str = file_u.variables['time'].maximum else: time_orig_str = file_u.variables['time'].minimum time_origin = datetime.datetime.strptime(time_orig_str, '%Hz%d%b%Y') lat = file_u.variables['lat'][:] lon = file_u.variables['lon'][:] # transform masked values to 0 u_data_raw = file_u.variables['u'][model_field_indx,model_level_indx,:,:] #[time,level,lat,lon] v_data_raw = file_v.variables['v'][model_field_indx,model_level_indx,:,:] u_data_mask_applied = np.where(~u_data_raw.mask, u_data_raw, 0) v_data_mask_applied = np.where(~v_data_raw.mask, v_data_raw, 0) # ordered lat array lat_sort_indices = np.argsort(lat) lat_ordered = lat[lat_sort_indices] # rtofs longitudes go from 74.16 to 434.06227 -- remap and sort to -180 to 180 grid lon_translate = np.where(lon > 180, lon - 360.0, lon) lon_sort_indices = np.argsort(lon_translate) # ordered longitude arrays lon_ordered = lon_translate[lon_sort_indices] # rebuild u/v data with correct longitude sorting (monotonic increasing) u_data_cleaned_filled = u_data_mask_applied[lat_sort_indices, :][:, lon_sort_indices] v_data_cleaned_filled = v_data_mask_applied[lat_sort_indices, :][:, lon_sort_indices] u_data_cleaned = u_data_raw[lat_sort_indices, :][:, lon_sort_indices] v_data_cleaned = v_data_raw[lat_sort_indices, :][:, lon_sort_indices] # assign the raw data to a variable so we can pickle it for use with other scripts raw_data = {'lat': lat_ordered, 'lon': lon_ordered, 'u_vel': u_data_cleaned, 'v_vel': v_data_cleaned, 'time_origin': time_origin} raw_data_pickle = pickle.dumps(raw_data) output_lat_array = np.arange(int(min(lat)), int(max(lat)) + 0.5, 0.5) # last point is excluded with arange (90 to -90) output_lon_array = np.arange(-180, 180.5, 0.5) # last point is excluded with arange (-180 to 180) u_interp_func = interpolate.interp2d(lon_ordered, lat_ordered, u_data_cleaned_filled, kind='cubic') v_interp_func = interpolate.interp2d(lon_ordered, lat_ordered, v_data_cleaned_filled, kind='cubic') u_data_interp = u_interp_func(output_lon_array, output_lat_array) v_data_interp = v_interp_func(output_lon_array, output_lat_array) minLat = np.min(output_lat_array) maxLat = np.max(output_lat_array) minLon = np.min(output_lon_array) maxLon = np.max(output_lon_array) dx = np.diff(output_lon_array)[0] dy = np.diff(output_lat_array)[0] output_data = [ {'header': { 'parameterUnit': "m.s-1", 'parameterNumber': 2, 'dx': dx, 'dy': dy, 'parameterNumberName': "Eastward current", 'la1': maxLat, 'la2': minLat, 'parameterCategory': 2, 'lo1': minLon, 'lo2': maxLon, 'nx': len(output_lon_array), 'ny': len(output_lat_array), 'refTime': datetime.datetime.strftime(model_field_time, '%Y-%m-%d %H:%M:%S'), 'timeOrigin': datetime.datetime.strftime(time_origin, '%Y-%m-%d %H:%M:%S'), }, 'data': [float('{:.3f}'.format(el)) if np.abs(el) > 0.0001 else 0 for el in u_data_interp[::-1].flatten().tolist()] }, {'header': { 'parameterUnit': "m.s-1", 'parameterNumber': 3, 'dx': dx, 'dy': dy, 'parameterNumberName': "Northward current", 'la1': maxLat, 'la2': minLat, 'parameterCategory': 2, 'lo1': minLon, 'lo2': maxLon, 'nx': len(output_lon_array), 'ny': len(output_lat_array), 'refTime': datetime.datetime.strftime(model_field_time, '%Y-%m-%d %H:%M:%S'), 'timeOrigin': datetime.datetime.strftime(time_origin, '%Y-%m-%d %H:%M:%S'), }, 'data': [float('{:.3f}'.format(el)) if np.abs(el) > 0.0001 else 0 for el in v_data_interp[::-1].flatten().tolist()] }, ] client = boto3.client('s3') client.put_object(Body=json.dumps(output_data), Bucket=AWS_BUCKET_NAME, Key=output_json_path) client.put_object(Body=raw_data_pickle, Bucket=AWS_BUCKET_NAME, Key=output_pickle_path) # save an info file for enhanced performance (get_model_field_api.py) client.put_object(Body=json.dumps({'time_origin': datetime.datetime.strftime(time_origin, '%Y-%m-%d %H:%M:%S')}), Bucket=AWS_BUCKET_NAME, Key=output_info_path) # call an intermediate function to distribute pickling workload (subsetting data by tile) data_zoom_level = datasets[TOP_LEVEL_FOLDER]['sub_resource'][SUB_RESOURCE]['data_tiles_zoom_level'] pickle_task_distributor(output_pickle_path, AWS_BUCKET_NAME, output_tile_data_path, data_zoom_level) file_u.close() file_v.close() if __name__ == "__main__": event = { 'url': 'http://nomads.ncep.noaa.gov:80/dods/rtofs/rtofs_global20221021/rtofs_glo_3dz_forecast_daily_uvel', 'forecast_time': '20221021T00:00', 'forecast_indx': 1, 'level': {'level_depth': 0, 'level_indx': 0} } lambda_handler(event, '') <file_sep>import boto3 import pickle import numpy as np import mercantile import pyproj # import matplotlib # matplotlib.use('agg') from matplotlib import pyplot as plt import matplotlib.colors as colors import copy import io import base64 from future.utils import string_types from process_tiles import make_tile_figure, md2uv from utils.tile_config import cmap_config s3 = boto3.client('s3') bucket = 'oceanmapper-data-storage' def build_tile_image(incoming_tile, data_key, data_type, additional_params={}): """ build_tile_image(incoming_tile, data_key, data_type, additional_params={}) Create a single tile with specific styling for consumption in a map ----------------------------------------------------------------------- Inputs: incoming_tile (mercantile.Tile): a mercanatile tile with z,x,y params data_key (str): the aws s3 location where the 'data tile' exists to create this image tile data_type (str): the sub_resource (i.e. ocean_current_speed, wind_speed, signficant_wave_height) (see datasets.py) additional_params (obj): an object containing additional style params which are used to override defaults provided in utils/tile_config.py ----------------------------------------------------------------------- Ouput: base64 encoded image converted to a utf-8 string ----------------------------------------------------------------------- Author: <NAME> Date Modified: 02/23/2018 """ # deconstruct incoming tile i,j,zoom=[*incoming_tile] # additional params take precedence over tile config settings tile_settings = cmap_config[data_type] for prop, val in tile_settings.items(): param_val = additional_params[prop] if prop in additional_params else val tile_settings[prop] = param_val # load the data try: pickle_data = s3.get_object(Bucket=bucket, Key=data_key) body_string = pickle_data['Body'].read() data = pickle.loads(body_string) except Exception as e: print('failed on pickle load') return # process the data in preparation for tiling if np.ma.is_masked(data['lat']): lat = data['lat'].data else: lat = data['lat'] if np.ma.is_masked(data['lon']): lon = data['lon'].data else: lon = data['lon'] # remove the north/south pole lats since these cause issues when projecting to epsg:3857 keep_lat_bool = np.logical_and(lat<90, lat>-90) keep_lat_indx = np.argwhere(keep_lat_bool).ravel() lat_trim = lat[keep_lat_indx] # create lat/lon mesh grid _lon,_lat = np.meshgrid(lon,lat_trim) # project to EPSG:3857 for plotting EPSG3857 = pyproj.Proj(init='EPSG:3857') lo,la = EPSG3857(_lon,_lat) # 492 x 540 # sort by EPSG3857 because our drawing surface is in EPSG3857, data still ordered by lon/lat so = np.argsort(lo[1,:]) # (540,) sa = np.argsort(la[:,1]) # (492,) proj_lon_array = lo[sa,:][:,so] proj_lat_array = la[sa,:][:,so] data_cmap = tile_settings['color_map'] # cmap_config[data_type]['color_map'] #if data_range is a string then convert to an array if isinstance(tile_settings['data_range'],string_types): tile_settings['data_range'] = [float(val) for val in tile_settings['data_range'].split(',')] cmin, cmax = tile_settings['data_range'] # set the contour levels if not tile_settings['interval'] is None: interval = float(tile_settings['interval']) lvls = np.arange(cmin, cmax + interval, interval) # plot entire image on 256 by 256 image then crop to tile extents fig, ax = make_tile_figure() if data_type == 'wind_speed' or data_type == 'ocean_current_speed': u_vel = (data['u_vel'][keep_lat_indx,:]).astype('float64') v_vel = (data['v_vel'][keep_lat_indx,:]).astype('float64') data_array = np.sqrt((u_vel**2) + (v_vel**2)) ## filled contour (use SORTED indexes for the EPSG3857 drawing surface) contourf = ax.contourf(proj_lon_array, proj_lat_array, data_array[sa,:][:,so], levels=lvls, cmap=data_cmap, extend='both') elif data_type == 'sig_wave_height': height_raw = data['sig_wave_height'][keep_lat_indx,:] # ax.pcolormesh(proj_lon_array, proj_lat_array, height_raw, shading='flat', cmap=palette, # norm=colors.BoundaryNorm([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],ncolors=palette.N)) ax.contourf(proj_lon_array, proj_lat_array, height_raw[sa,:][:,so], cmap=data_cmap, levels=lvls, extend='both') elif data_type == 'primary_wave_dir': dir_raw = data['primary_wave_dir'][keep_lat_indx,:] #directions are in degrees already dir_array = dir_raw[sa,:][:,so] # convert directions into u,v constituents (use unit vector) mag_array = np.ones_like(dir_array) u_comp,v_comp = md2uv(mag_array, dir_array,'from') # TODO: if interpolation is needed in the future see this resource: # http://christopherbull.com.au/python/scipy-interpolate-griddata/ scale = 17.0 if zoom <= 3: row_int = 4 col_int = 4 elif zoom == 4: row_int = 2 col_int = 2 else: # show all data col_int = 1 row_int = 1 scale = 14.0 quiver = ax.quiver(proj_lon_array[::row_int,::col_int], proj_lat_array[::row_int,::col_int], u_comp[::row_int,::col_int], v_comp[::row_int,::col_int], headwidth=9.0,headlength=8.5, headaxislength=8.0, scale_units='width', scale=scale) elif data_type == 'primary_wave_period': period_raw = data['primary_wave_period'][keep_lat_indx,:] ax.contourf(proj_lon_array, proj_lat_array, period_raw[sa,:][:,so], cmap=data_cmap, levels=lvls, extend='both') else: pass # more axes manipulation ax.set_frame_on(False) ax.set_clip_on(False) ax.set_position([0, 0, 1, 1]) # get extents of incoming tile and crop accordingly ll = mercantile.bounds(i, j, zoom) _epsg_x_min, _epsg_y_min = EPSG3857(*ll[:2]) _epsg_x_max, _epsg_y_max = EPSG3857(*ll[2:]) # set x/y limits to match available tile extents ax.set_xlim(_epsg_x_min,_epsg_x_max) ax.set_ylim(_epsg_y_min, _epsg_y_max) # convert image into base64 encoded string dpi = 256 with io.BytesIO() as out_img: # fig.savefig(out_img, format='png', dpi=dpi, pad_inches=0.0, transparent=True) fig.savefig(out_img, format='png', transparent=True) out_img.seek(0) encoded_img = base64.b64encode(out_img.read()).decode('utf-8') return encoded_img <file_sep># -*- coding: utf-8 -*- """ Created on Mon Apr 2 17:20:30 2018 @author: <NAME> """ import datetime import json import time import boto3 from HYCOM_forecast_info import get_hycom_forecast_info lam = boto3.client('lambda') def lambda_handler(event, context): """ lambda_handler(event, context): This function invokes concurrent lambda functions to read, parse, and save 3d HYCOM ocean current data ----------------------------------------------------------------------- Inputs: event: AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type. context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Output: No output ----------------------------------------------------------------------- Notes: Check here for hycom version updates: http://tds.hycom.org/thredds/catalog/datasets/catalog.html ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/17/2022 """ hycom_url = 'https://tds.hycom.org/thredds/catalog/GLBy0.08/expt_93.0/FMRC/runs/catalog.html' forecast_info = get_hycom_forecast_info(hycom_url) field_datetimes = forecast_info['forecast']['field_datetimes'] data_url = forecast_info['forecast']['data_url'] levels = forecast_info['forecast']['levels'] for forecast_time_indx, forecast_time in enumerate(field_datetimes): # only use a subset of the available forecast fields for cost savings if forecast_time.hour % 6 == 0: # only grab the upper 100m stop_depth_indx = levels.index(100) # use a depth of 100 as the stop indx for level_indx, level_depth in enumerate(levels[:stop_depth_indx]): # only utilize depths at intervals of 10 if level_depth % 10 == 0: # build payload for initiation of lambda function payload = { 'url': data_url, 'forecast_time': datetime.datetime.strftime(forecast_time, '%Y%m%dT%H:%M'), 'forecast_time_indx': forecast_time_indx, 'level': {'level_depth': level_depth, 'level_indx': level_indx} } # InvocationType = RequestResponse # this is used for synchronous lambda calls try: response = lam.invoke(FunctionName='grab_hycom_3d', InvocationType='Event', Payload=json.dumps(payload)) except Exception as e: print(e) raise e print(response) time.sleep(0.1) if __name__ == "__main__": lambda_handler('', '') <file_sep># -*- coding: utf-8 -*- """ Created on Mon Apr 2 17:20:30 2018 @author: <NAME> """ import datetime import json import pickle import boto3 import numpy as np from utils.datasets import datasets from utils.fetch_utils import get_opendapp_netcdf from utils.pickle_task_distributor import pickle_task_distributor def lambda_handler(event, context): """ lambda_handler(event, context): This function reads, parses, and saves a .json and .pickle file from a netCDF file from a provided opendapp url (contained within the event paramater object). ----------------------------------------------------------------------- Inputs: event: AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type. context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Output: A .pickle file are save to S3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/20/2022 """ AWS_BUCKET_NAME = 'oceanmapper-data-storage' TOP_LEVEL_FOLDER = 'WW3_DATA' SUB_RESOURCE_HTSGWSFC = 'sig_wave_height' SUB_RESOURCE_DIRPWSFC = 'primary_wave_dir' SUB_RESOURCE_PERPWSFC = 'primary_wave_period' # unpack event data url = event['url'] model_field_time = datetime.datetime.strptime(event['forecast_time'],'%Y%m%dT%H:%M') model_field_indx = event['forecast_indx'] file = get_opendapp_netcdf(url) formatted_folder_date = datetime.datetime.strftime(model_field_time,'%Y%m%d_%H') output_pickle_path_htsgwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_HTSGWSFC + '/pickle/' +'ww3_htsgwsfc_' + formatted_folder_date + '.pickle') output_tile_data_path_htsgwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_HTSGWSFC + '/tiles/data/') output_pickle_path_dirpwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_DIRPWSFC + '/pickle/' +'ww3_dirpwsfc_' + formatted_folder_date + '.pickle') output_tile_data_path_dirpwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_DIRPWSFC + '/tiles/data/') output_pickle_path_perpwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_PERPWSFC + '/pickle/' +'ww3_perpwsfc_' + formatted_folder_date + '.pickle') output_tile_data_path_perpwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_PERPWSFC + '/tiles/data/') output_info_path = TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/info.json' # get model origin time init_time = file.variables['time'][0] basetime_int = int(init_time) extra_days = init_time - basetime_int time_origin = (datetime.datetime.fromordinal(basetime_int) + datetime.timedelta(days = extra_days) - datetime.timedelta(days=1)) lat = file.variables['lat'][:] lon = file.variables['lon'][:] # significant height of combined wind waves and swell [m] height_raw = file.variables['htsgwsfc'][model_field_indx,:,:] #[time,lat,lon] # primary wave direction [deg] primary_dir_raw = file.variables['dirpwsfc'][model_field_indx,:,:] #[time,lat,lon] # primary wave mean period [s] primary_period_raw = file.variables['perpwsfc'][model_field_indx,:,:] #[time,lat,lon] # ordered lat array lat_sort_indices = np.argsort(lat) lat_ordered = lat[lat_sort_indices] # remap and sort to -180 to 180 grid lon_translate = np.where(lon>180, lon-360.0, lon) lon_sort_indices = np.argsort(lon_translate) # ordered longitude arrays lon_ordered = lon_translate[lon_sort_indices] # rebuild sig wave height data with correct longitude sorting (monotonic increasing) height_data_cleaned = height_raw[lat_sort_indices,:][:,lon_sort_indices] # rebuild primary wave direction data with correct longitude sorting (monotonic increasing) direction_data_cleaned = primary_dir_raw[lat_sort_indices,:][:,lon_sort_indices] # rebuild primary wave period data with correct longitude sorting (monotonic increasing) period_data_cleaned = primary_period_raw[lat_sort_indices,:][:,lon_sort_indices] # assign the raw data to variables so we can pickle it for use with other scripts raw_data_htsgwsfc = {'lat': lat_ordered, 'lon': lon_ordered, 'sig_wave_height': height_data_cleaned, 'time_origin': time_origin} raw_data_pickle_htsgwsfc = pickle.dumps(raw_data_htsgwsfc) raw_data_dirpwsfc = {'lat': lat_ordered, 'lon': lon_ordered,'primary_wave_dir': direction_data_cleaned, 'time_origin': time_origin} raw_data_pickle_dirpwsfc = pickle.dumps(raw_data_dirpwsfc) raw_data_perpwsfc = {'lat': lat_ordered, 'lon': lon_ordered,'primary_wave_period': period_data_cleaned, 'time_origin': time_origin} raw_data_pickle_perpwsfc = pickle.dumps(raw_data_perpwsfc) client = boto3.client('s3') client.put_object(Body=raw_data_pickle_htsgwsfc, Bucket=AWS_BUCKET_NAME, Key=output_pickle_path_htsgwsfc) client.put_object(Body=raw_data_pickle_dirpwsfc, Bucket=AWS_BUCKET_NAME, Key=output_pickle_path_dirpwsfc) client.put_object(Body=raw_data_pickle_perpwsfc, Bucket=AWS_BUCKET_NAME, Key=output_pickle_path_perpwsfc) # save an info file for enhanced performance (get_model_field_api.py) client.put_object(Body=json.dumps({'time_origin': datetime.datetime.strftime(time_origin,'%Y-%m-%d %H:%M:%S')}), Bucket=AWS_BUCKET_NAME, Key=output_info_path) # call an intermediate function to distribute pickling workload (subsetting data by tile) data_zoom_level_htsgwsfc = datasets[TOP_LEVEL_FOLDER]['sub_resource'][SUB_RESOURCE_HTSGWSFC]['data_tiles_zoom_level'] pickle_task_distributor(output_pickle_path_htsgwsfc, AWS_BUCKET_NAME, output_tile_data_path_htsgwsfc, data_zoom_level_htsgwsfc) data_zoom_level_dirpwsfc = datasets[TOP_LEVEL_FOLDER]['sub_resource'][SUB_RESOURCE_DIRPWSFC]['data_tiles_zoom_level'] pickle_task_distributor(output_pickle_path_dirpwsfc, AWS_BUCKET_NAME, output_tile_data_path_dirpwsfc, data_zoom_level_dirpwsfc) data_zoom_level_perpwsfc = datasets[TOP_LEVEL_FOLDER]['sub_resource'][SUB_RESOURCE_PERPWSFC]['data_tiles_zoom_level'] pickle_task_distributor(output_pickle_path_perpwsfc, AWS_BUCKET_NAME, output_tile_data_path_perpwsfc, data_zoom_level_perpwsfc) file.close() if __name__ == "__main__": # event = {'url': 'https://nomads.ncep.noaa.gov/dods/wave/gfswave/20221020/gfswave.global.0p25_12z', 'forecast_time': '20221020T12:00', 'forecast_indx': 0}; lambda_handler('','') <file_sep>import json def update_process_status(dataset, status): """ update_process_status(dataset, status) This function updates the harvest processing status of a particular dataset Inputs: dataset (str) - the name of the datset (i.e. hycom, rtofs, gfs, ww3) status (st) - the process status ('ready' or 'processing') Returns: 0 - success 1 - failure ----------------------------------------------------------------------- Notes: harvest_status.json is updated ----------------------------------------------------------------------- Author: <NAME> Date Modified: 4/24/2019 """ try: with open('../harvest_utils/harvest_status.json') as f: harvest_status = json.loads(f.read()) harvest_status[dataset] = status with open('../harvest_utils/harvest_status.json','w') as f: json.dump(harvest_status,f) return 0 except Exception as e: return 1<file_sep>import boto3 import datetime import numpy as np import json import re from utils.s3_filepath_utils import build_file_path, build_date_path from utils.datasets import datasets from api_utils.response_constructor import generate_response from api_utils.check_query_params import check_query_params, filter_failed_params from api_utils.fetch_data_availability import grab_data_availability from api_utils.nearest_model_time import get_available_model_times from api_utils.get_model_init import get_model_init s3 = boto3.client('s3') bucket = 'oceanmapper-data-storage' def lambda_handler(event, context): """ lambda_handler(event, context): This function is used in conjunction with aws api gateway (lambda proxy integration) to pass json data representing a specific model field (closest to the requested time looking backwards). If no data is available within 24 hours of the request time then empty data is returned. ----------------------------------------------------------------------- Inputs: event: Event data (queryStringParameters) are parsed from call to aws api endpoint context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Output: response object ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/21/2022 """ required_query_params = ['time','dataset','sub_resource','level'] # default headers for request headers = {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'} # load data availability file from s3 availability_struct = grab_data_availability() if not availability_struct: response_body = { 'status': 'Failed to load data availability structure.', } return generate_response(404, headers, response_body) query_param_validation = check_query_params(event,required_query_params, availability_struct, datasets) # make sure we have all required and valid inputs failed_query_param_obj = filter_failed_params(query_param_validation) if len(failed_query_param_obj.keys()): response_body = { 'status': failed_query_param_obj, } return generate_response(404, headers, response_body) # model time model_time = event['queryStringParameters']['time'] model_time_datetime = datetime.datetime.strptime(model_time,'%Y-%m-%dT%H:%MZ') # dataset (model) dataset = event['queryStringParameters']['dataset'] # sub resource sub_resource = event['queryStringParameters']['sub_resource'] # model level level = event['queryStringParameters']['level'] level_formatted = str(level) + 'm' if len(str(level)) else '' # wave data have no level sub_resource_folder = datasets[dataset]['sub_resource'][sub_resource] dataset_prefix = sub_resource_folder['data_prefix'] dataset_type = sub_resource_folder['data_type'] scalar_tiles = sub_resource_folder['scalar_tiles'] vector_tiles = sub_resource_folder['vector_tiles'] available_time = get_available_model_times(dataset,sub_resource, model_time_datetime, level_formatted, dataset_type,availability_struct) if available_time: available_time_str = datetime.datetime.strftime(available_time,'%Y-%m-%dT%H:%MZ') data_key, tile_keys = build_file_path(dataset, sub_resource, dataset_prefix, available_time, dataset_type, scalar_tiles, vector_tiles, level_formatted) # get model init time by looking at top level info.json file info_file_path = build_date_path('info.json', dataset, available_time) init_time = get_model_init(info_file_path, bucket) init_time_str = datetime.datetime.strftime(init_time,'%Y-%m-%dT%H:%MZ') if init_time else None # get the file (if we arent dealing with waves) if not dataset == 'WW3_DATA': try: raw_data = s3.get_object(Bucket=bucket, Key=data_key) unpacked_data = raw_data.get('Body').read().decode('utf-8') except Exception as e: response_body = { 'status': 'data not available', } return generate_response(404, headers, response_body) else: unpacked_data = None # construct the response body response_body = { 'model': dataset, 'valid_time': available_time_str, 'init_time': init_time_str, 'data': unpacked_data, 'tile_paths': tile_keys } return generate_response(200, headers, response_body) else: response_body = { 'model': dataset, 'valid_time': None, 'init_time': None, 'data': None, 'tile_paths': None, } return generate_response(200, headers, response_body) if __name__ == '__main__': # event = { # "queryStringParameters": { # "level": "0", # "dataset": "HYCOM_DATA", # "sub_resource": "ocean_current_speed", # "time": "2022-10-21T19:00Z" # } # } lambda_handler('','') <file_sep>import json import sys sys.path.append("..") import json import datetime import pickle import time import io import logging import boto3 import numpy as np from scipy import interpolate import netCDF4 from harvest_utils.fetch_utils import get_opendapp_netcdf from harvest_utils.process_pickle import generate_pickle_files from harvest_utils.datasets import datasets logger = logging.getLogger('data-harvest') def process_fields(data_url, forecast_time, model_field_indx): """ process_3d_fields(data_url, forecast_time, model_field_indx) This function reads, parses, and saves a .json and .pickle file from a netCDF file from a provided opendapp url ----------------------------------------------------------------------- Inputs: ----------------------------------------------------------------------- Output: A .json file and a .pickle file are save to S3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 04/20/2019 """ AWS_BUCKET_NAME = 'oceanmapper-data-storage' TOP_LEVEL_FOLDER = 'WW3_DATA' SUB_RESOURCE_HTSGWSFC = 'sig_wave_height' SUB_RESOURCE_DIRPWSFC = 'primary_wave_dir' SUB_RESOURCE_PERPWSFC = 'primary_wave_period' with get_opendapp_netcdf(data_url) as file: formatted_folder_date = datetime.datetime.strftime(forecast_time,'%Y%m%d_%H') logger.info('processing WW3_DATA data: {}'.format(formatted_folder_date)) # get model origin time init_time = file.variables['time'][0] basetime_int = int(init_time) extra_days = init_time - basetime_int time_origin = (datetime.datetime.fromordinal(basetime_int) + datetime.timedelta(days = extra_days) - datetime.timedelta(days=1)) lat = file.variables['lat'][:] lon = file.variables['lon'][:] # output model info.json filepath output_info_path = TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/info.json' output_pickle_path_htsgwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_HTSGWSFC + '/pickle/' +'ww3_htsgwsfc_' + formatted_folder_date + '.pickle') output_tile_scalar_path_htsgwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_HTSGWSFC + '/tiles/scalar/') output_tile_data_path_htsgwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_HTSGWSFC + '/tiles/data/') output_pickle_path_dirpwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_DIRPWSFC + '/pickle/' +'ww3_dirpwsfc_' + formatted_folder_date + '.pickle') output_tile_vector_path_dirpwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_DIRPWSFC + '/tiles/vector/') output_tile_data_path_dirpwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_DIRPWSFC + '/tiles/data/') output_pickle_path_perpwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_PERPWSFC + '/pickle/' +'ww3_perpwsfc_' + formatted_folder_date + '.pickle') output_tile_scalar_path_perpwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_PERPWSFC + '/tiles/scalar/') output_tile_data_path_perpwsfc = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE_PERPWSFC + '/tiles/data/') # significant height of combined wind waves and swell [m] height_raw = file.variables['htsgwsfc'][model_field_indx,:,:] #[time,lat,lon] # primary wave direction [deg] primary_dir_raw = file.variables['dirpwsfc'][model_field_indx,:,:] #[time,lat,lon] # primary wave mean period [s] primary_period_raw = file.variables['perpwsfc'][model_field_indx,:,:] #[time,lat,lon] # ordered lat array lat_sort_indices = np.argsort(lat) lat_ordered = lat[lat_sort_indices] # remap and sort to -180 to 180 grid lon_translate = np.where(lon>180, lon-360.0, lon) lon_sort_indices = np.argsort(lon_translate) # ordered longitude arrays lon_ordered = lon_translate[lon_sort_indices] # rebuild sig wave height data with correct longitude sorting (monotonic increasing) height_data_cleaned = height_raw[lat_sort_indices,:][:,lon_sort_indices] # rebuild primary wave direction data with correct longitude sorting (monotonic increasing) direction_data_cleaned = primary_dir_raw[lat_sort_indices,:][:,lon_sort_indices] # rebuild primary wave period data with correct longitude sorting (monotonic increasing) period_data_cleaned = primary_period_raw[lat_sort_indices,:][:,lon_sort_indices] # assign the raw data to variables so we can pickle it for use with other scripts raw_data_htsgwsfc = {'lat': lat_ordered, 'lon': lon_ordered, 'sig_wave_height': height_data_cleaned, 'time_origin': time_origin} raw_data_dirpwsfc = {'lat': lat_ordered, 'lon': lon_ordered,'primary_wave_dir': direction_data_cleaned, 'time_origin': time_origin} raw_data_perpwsfc = {'lat': lat_ordered, 'lon': lon_ordered,'primary_wave_period': period_data_cleaned, 'time_origin': time_origin} s3 = boto3.client('s3') pickle_tuple = [ (raw_data_htsgwsfc, output_pickle_path_htsgwsfc), (raw_data_dirpwsfc, output_pickle_path_dirpwsfc), (raw_data_perpwsfc,output_pickle_path_perpwsfc) ] for pkfile, pkpath in pickle_tuple: with io.BytesIO() as f: pickle.dump(pkfile,f,pickle.HIGHEST_PROTOCOL) f.seek(0) s3.upload_fileobj(f,AWS_BUCKET_NAME, pkpath) # fix output_pickle_path with io.BytesIO() as f: info = {'time_origin': datetime.datetime.strftime(time_origin,'%Y-%m-%d %H:%M:%S')} f.write(json.dumps(info).encode()) f.seek(0) s3.upload_fileobj(f,AWS_BUCKET_NAME, output_info_path) # call an intermediate function to distribute pickling workload (subsetting data by tile) data_zoom_level_htsgwsfc = datasets[TOP_LEVEL_FOLDER]['sub_resource'][SUB_RESOURCE_HTSGWSFC]['data_tiles_zoom_level'] generate_pickle_files(raw_data_htsgwsfc, TOP_LEVEL_FOLDER, SUB_RESOURCE_HTSGWSFC, output_tile_data_path_htsgwsfc, data_zoom_level_htsgwsfc, AWS_BUCKET_NAME) data_zoom_level_dirpwsfc = datasets[TOP_LEVEL_FOLDER]['sub_resource'][SUB_RESOURCE_DIRPWSFC]['data_tiles_zoom_level'] generate_pickle_files(raw_data_dirpwsfc, TOP_LEVEL_FOLDER, SUB_RESOURCE_DIRPWSFC, output_tile_data_path_dirpwsfc, data_zoom_level_dirpwsfc, AWS_BUCKET_NAME) data_zoom_level_perpwsfc = datasets[TOP_LEVEL_FOLDER]['sub_resource'][SUB_RESOURCE_PERPWSFC]['data_tiles_zoom_level'] generate_pickle_files(raw_data_perpwsfc, TOP_LEVEL_FOLDER, SUB_RESOURCE_PERPWSFC, output_tile_data_path_perpwsfc, data_zoom_level_perpwsfc, AWS_BUCKET_NAME) <file_sep>import React, { Component } from 'react'; import deepEqual from 'deep-equal'; // store the map configuration properties in an object, // we could also move this to a separate file & import it if desired. let config = {}; config.params = { center: [25.8,-89.6], zoom: 6, maxZoom: 14, minZoom: 3, zoomControl: false, attributionControl: false }; class Map extends Component { constructor(props) { super(props); this.state = { // map: null, mapTime: null, mapLayers: null, leafletLayers: null, tileLayer: null, geojsonLayer: null, geojson: null, }; // move mapTime and mapLayers onto this instead of keeping in state this._mapNode = null; this.updateMap = this.updateMap.bind(this); this.determineLayerDiff = this.determineLayerDiff.bind(this); this.addTestLayer = this.addTestLayer.bind(this); this.onEachFeature = this.onEachFeature.bind(this); this.pointToLayer = this.pointToLayer.bind(this); this.filterFeatures = this.filterFeatures.bind(this); this.filterGeoJSONLayer = this.filterGeoJSONLayer.bind(this); } determineLayerDiff(mapLayers, parentLayers) { // check for time change first (Map.js mapTime vs prevProps mapTime... make use of timeSensitive prop to only update those layers that are time // sensitive if nothing else is different // loop through prevProps.mapLayers and compare to prevState.. // if prev state is empty then immediatelly return prevProps.mapLayers // if not return the array of objects to trigger actions for let layerUpdates = [], layerIndx, layerName, previousLayerProps, isEqual; if (!this.mapTime) { for (layerIndx=0; layerIndx<parentLayers['orderedMapLayers'].length; layerIndx++) { layerName = parentLayers['orderedMapLayers'][layerIndx]; previousLayerProps = parentLayers['mapLayers'][layerName]; layerUpdates.push({id: layerName,...previousLayerProps}) } return layerUpdates } else if (this.state.mapTime !== parentLayers['mapTime']) { // loop through all timesensitive layers and call functions to remove/readd layer based on new time console.log('time changed'); return []; } else { // loop through all layers to see if anything is different between parent and map class for (layerIndx=0; layerIndx<parentLayers['orderedMapLayers'].length; layerIndx++) { // debugger layerName = parentLayers['orderedMapLayers'][layerIndx]; previousLayerProps = parentLayers['mapLayers'][layerName]; isEqual = deepEqual(previousLayerProps,this.mapLayers[layerName]) debugger if (!isEqual) { console.log('bang!'); layerUpdates.push(previousLayerProps) } } return layerUpdates; } } componentDidMount() { // code to run just after the component "mounts" / DOM elements are created // we could make an AJAX request for the GeoJSON data here if it wasn't stored locally // this.getData(); // if (!this.state.map) { if (!this.map) { // create the Leaflet map object this.inititialize_map(this._mapNode); // TODO: make some api calls for data } } addTestLayer(layerObj) { // marker2=L.marker([0,10],{pane: 'test'}) console.log('layer being added'); let L = window.L; let rand_lat = Math.floor(Math.random() * 11); let marker=L.marker([rand_lat,0]).bindPopup(layerObj['id']); marker.addTo(this.map); this.layerGroup.addLayer(marker) } componentWillMount() { // code to run just before rendering the component // this destroys the Leaflet map object & related event listeners } componentWillUnmount() { // code to run just before unmounting the component // this destroys the Leaflet map object & related event listeners // this.state.map.remove(); } getData() { // could also be an AJAX request that results in setting state with the geojson data // for simplicity sake we are just importing the geojson data using webpack's json loader // this.setState({ // numEntrances: geojson.features.length, // geojson // }); } addGeoJSONLayer(geojson) { // create a native Leaflet GeoJSON SVG Layer to add as an interactive overlay to the map // an options object is passed to define functions for customizing the layer // const geojsonLayer = L.geoJson(geojson, { // onEachFeature: this.onEachFeature, // pointToLayer: this.pointToLayer, // filter: this.filterFeatures // }); // // add our GeoJSON layer to the Leaflet map object // geojsonLayer.addTo(this.state.map); // // store the Leaflet GeoJSON layer in our component state for use later // this.setState({ geojsonLayer }); // // fit the geographic extent of the GeoJSON layer within the map's bounds / viewport // this.zoomToFeature(geojsonLayer); } filterGeoJSONLayer() { // clear the geojson layer of its data // this.state.geojsonLayer.clearLayers(); // // re-add the geojson so that it filters out subway lines which do not match state.filter // this.state.geojsonLayer.addData(geojson); // // fit the map to the new geojson layer's geographic extent // this.zoomToFeature(this.state.geojsonLayer); } zoomToFeature(target) { // pad fitBounds() so features aren't hidden under the Filter UI element // var fitBoundsParams = { // paddingTopLeft: [200,10], // paddingBottomRight: [10,10] // }; // // set the map's center & zoom so that it fits the geographic extent of the layer // this.state.map.fitBounds(target.getBounds(), fitBoundsParams); } filterFeatures(feature, layer) { // filter the subway entrances based on the map's current search filter // returns true only if the filter value matches the value of feature.properties.LINE // const test = feature.properties.LINE.split('-').indexOf(this.state.subwayLinesFilter); // if (this.state.subwayLinesFilter === '*' || test !== -1) { // return true; // } } pointToLayer(feature, latlng) { // renders our GeoJSON points as circle markers, rather than Leaflet's default image markers // parameters to style the GeoJSON markers // var markerParams = { // radius: 4, // fillColor: 'orange', // color: '#fff', // weight: 1, // opacity: 0.5, // fillOpacity: 0.8 // }; // return L.circleMarker(latlng, markerParams); } onEachFeature(feature, layer) { // if (feature.properties && feature.properties.NAME && feature.properties.LINE) { // // if the array for unique subway line names has not been made, create it // // there are 19 unique names total // if (subwayLineNames.length < 19) { // // add subway line name if it doesn't yet exist in the array // feature.properties.LINE.split('-').forEach(function(line, index){ // if (subwayLineNames.indexOf(line) === -1) subwayLineNames.push(line); // }); // // on the last GeoJSON feature // if (this.state.geojson.features.indexOf(feature) === this.state.numEntrances - 1) { // // use sort() to put our values in alphanumeric order // subwayLineNames.sort(); // // finally add a value to represent all of the subway lines // subwayLineNames.unshift('All lines'); // } // } // // assemble the HTML for the markers' popups (Leaflet's bindPopup method doesn't accept React JSX) // const popupContent = `<h3>${feature.properties.NAME}</h3> // <strong>Access to MTA lines: </strong>${feature.properties.LINE}`; // // add our popups // layer.bindPopup(popupContent); // } } inititialize_map(id) { // if (this.state.map) return; if (this.map) return; // this function creates the Leaflet map object and is called after the Map component mounts let L = window.L; let map = this.map = L.map(id, config.params); L.esri.basemapLayer("DarkGray").addTo(map); // zoom control position L.control.zoom({ position:'topright' }).addTo(map); // add an empty layer group to the map this.layerGroup = L.layerGroup([]); this.layerGroup.addTo(map); // set our map state // this.setState({ map }); } updateMap() { // TODO continue on this path.. render calls this function which triggers necessary DOM actions let layerUpdates; if (this.props.initializedLayers) { debugger layerUpdates = this.determineLayerDiff(this.mapLayers, this.props); if (layerUpdates.length) { // debugger // trigger layer updates... loop through and call the layers respective update function layerUpdates.forEach((layerObj) => { this.addTestLayer(layerObj); }); // set properties instead of setting state this.mapTime = this.props.mapTime; this.mapLayers = Object.assign({},this.props.mapLayers); } } } render() { // TODO: include function to update layers here... use determine diff function which can then call another function // to manipulate DOM.. we don't need componentDidUpdate.. componentWillRecieveProps.. (THIS ISNT WORKING) // PASS THE DIEFFERENCE ARRAY FROM THE PARENT... that can be saved in the parent state... it gets generated whenever // a layer is toggled, level is changed, or time is changed... still need a function here to do DOM manipulation // IF difference object is empty then need to add them all.... rerenders do happen when none of these actions happen.. what to do about that? // CAN ALSO add custom info in leaflet layer inside options... could use this to check props.mapLayers vs whats on the map (this might be the way to go)... // loop through all items in a layer group... might not need difference... would be good if we can find a layer by its id on the map return ( <div ref={(node) => this._mapNode = node} id="map" /> ) } } export default Map; <file_sep>import boto3 import datetime import re s3 = boto3.resource('s3') AWS_BUCKET_NAME = 'oceanmapper-data-storage' def get_max_date(dataset): ''' ''' data_bucket = s3.Bucket(AWS_BUCKET_NAME) filtered_objects = data_bucket.objects.filter(Prefix=dataset) s3_dates = [] for object in filtered_objects: pattern = r'model_folder/(\d{8}_\d{2})/(\w*)/?(\w*)/(json|pickle)/.*[.](json|pickle)$'.replace('model_folder',dataset) match = re.search(pattern,object.key) if match: parsed_date = datetime.datetime.strptime(match.group(1),'%Y%m%d_%H') s3_dates.append(parsed_date) return max(s3_dates)<file_sep>import numpy as np import datetime def get_available_model_times(dataset_folder,sub_resource_folder,model_time_datetime, level_formatted,file_type,availability_struct): """ get_available_model_times(dataset_folder,sub_resource_folder,model_time_datetime, level_formatted,file_type,availability_struct) This function is used to get the nearest available time with data for a specific model ----------------------------------------------------------------------- Inputs: dataset_folder (str): the s3 'folder' to search sub_resource_folder (str): the s3 sub folder to search (i.e. ocean_current_speeds) model_time_datetime (datetime): the requested time to search against level_formatted (str): the level (altitude/depth) of the data (i.e. 10m) file_type (str): one of [json, pickle] availability_struct (obj): information on data availability for environmental datasets stored on S3 ----------------------------------------------------------------------- Output: datetime representing the nearest available time (looking in reverse) ----------------------------------------------------------------------- Author: <NAME> Date Modified: 09/20/2018 """ dataset_type = file_type available_times = availability_struct[dataset_folder][sub_resource_folder]['level'][level_formatted][dataset_type] available_times_dt = [datetime.datetime.strptime(datetime_str,'%Y%m%d_%H') for datetime_str in available_times] # turn into numpy array (unique and sorted) available_times_dt_array = np.unique(np.array(available_times_dt)) trimmed_available_times = available_times_dt_array[available_times_dt_array <= model_time_datetime] # select the last time available_time = None # default value data_key = None if len(trimmed_available_times): available_time = trimmed_available_times[-1] # if available time is more than 24 hours before requested time then return no data time_req_diff = model_time_datetime - available_time if time_req_diff > datetime.timedelta(hours=24): available_time = None return available_time <file_sep># some configuration variables for apis datasets = { 'HYCOM_DATA': { 'sub_resource': { 'ocean_current_speed': { 'data_prefix': 'hycom_currents', 'variables': ['u_vel','v_vel'], 'overlay_type': 'ocean', 'data_type': 'json', 'scalar_tiles': True, 'vector_tiles': False, 'data_tiles_zoom_level': [3], 'units': 'm/s' } } }, 'RTOFS_DATA': { 'sub_resource': { 'ocean_current_speed': { 'data_prefix': 'rtofs_currents', 'variables': ['u_vel','v_vel'], 'overlay_type': 'ocean', 'data_type': 'json', 'scalar_tiles': True, 'vector_tiles': False, 'data_tiles_zoom_level': [3], 'units': 'm/s' } } }, 'GFS_DATA': { 'sub_resource': { 'wind_speed': { 'data_prefix': 'gfs_winds', 'variables': ['u_vel','v_vel'], 'overlay_type': 'all', 'data_type': 'json', 'scalar_tiles': True, 'vector_tiles': False, 'data_tiles_zoom_level': [3], 'units': 'm/s' } } }, 'WW3_DATA': { 'sub_resource': { 'sig_wave_height': { 'data_prefix': 'ww3_htsgwsfc', 'variables': ['sig_wave_height'], 'overlay_type': 'ocean', 'data_type': 'pickle', 'scalar_tiles': True, 'vector_tiles': False, 'data_tiles_zoom_level': [3], 'units': 'm' }, 'primary_wave_dir': { 'data_prefix': 'ww3_dirpwsfc', 'variables': ['primary_wave_dir'], 'overlay_type': 'ocean', 'data_type': 'pickle', 'scalar_tiles': False, 'vector_tiles': True, 'data_tiles_zoom_level': [3], 'units': 'deg' }, 'primary_wave_period': { 'data_prefix': 'ww3_perpwsfc', 'variables': ['primary_wave_period'], 'overlay_type': 'ocean', 'data_type': 'pickle', 'scalar_tiles': True, 'vector_tiles': False, 'data_tiles_zoom_level': [3], 'units': 's' } } } }<file_sep>import boto3 import datetime import numpy as np import json import re import os from multiprocessing import Process, Pipe from utils.s3_filepath_utils import build_tiledata_path from utils.datasets import datasets from api_utils.response_constructor import generate_response from api_utils.check_query_params import check_query_params, filter_failed_params from api_utils.fetch_data_availability import grab_data_availability from api_utils.intermediate_model_times import get_model_times_in_range from api_utils.get_model_value import get_model_value from point_locator import in_ocean s3 = boto3.client('s3') lam = boto3.client('lambda') bucket = 'oceanmapper-data-storage' def lambda_handler(event, context): """ lambda_handler(event, context): This function is used in conjunction with aws api gateway (lambda proxy integration) to pass back the interpolated value of a dataset at a specific geographic coordinate ----------------------------------------------------------------------- Inputs: event: Event data (queryStringParameters) are parsed from call to aws api endpoint context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Notes: https://aws.amazon.com/blogs/compute/parallel-processing-in-python-with-aws-lambda/ ----------------------------------------------------------------------- Output: response object ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/17/2018 """ # default headers for request headers = {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'} required_query_params = ['start_time','end_time','dataset','sub_resource','level','coordinates'] # load data availability file from s3 availability_struct = grab_data_availability() if not availability_struct: response_body = { 'status': 'Failed to load data availability structure.', } return generate_response(404, headers, response_body) query_param_validation = check_query_params(event,required_query_params, availability_struct, datasets) # make sure we have all required and valid inputs failed_query_param_obj = filter_failed_params(query_param_validation) if len(failed_query_param_obj.keys()): response_body = { 'status': failed_query_param_obj, } return generate_response(404, headers, response_body) # model start time model_start_time = event['queryStringParameters']['start_time'] model_start_time_datetime = datetime.datetime.strptime(model_start_time,'%Y-%m-%dT%H:%MZ') # model end time model_end_time = event['queryStringParameters']['end_time'] model_end_time_datetime = datetime.datetime.strptime(model_end_time,'%Y-%m-%dT%H:%MZ') # dataset (model) dataset = event['queryStringParameters']['dataset'] # sub resource sub_resource = event['queryStringParameters']['sub_resource'] sub_resource_folder = datasets[dataset]['sub_resource'][sub_resource] dataset_prefix = sub_resource_folder['data_prefix'] dataset_units = sub_resource_folder['units'] # model level level = event['queryStringParameters']['level'] level_formatted = str(level) + 'm' if len(str(level)) else '' # wave data have no level # coordinates coords = [float(coord) for coord in event['queryStringParameters']['coordinates'].split(',')] overlay_type = datasets[dataset]['sub_resource'][sub_resource]['overlay_type'] coord_in_ocean = False # default is not in ocean if overlay_type == 'ocean': coord_in_ocean = in_ocean(coords[0], coords[1]) # if model is (ocean only) then check the coords to make sure they are in the ocean if not coord_in_ocean and overlay_type == 'ocean': response_body = { 'data': None, 'status': 'point on land', } return generate_response(200, headers, response_body) dataset_vars = sub_resource_folder['variables'] dataset_type = 'pickle' available_times = get_model_times_in_range(dataset,sub_resource,model_start_time_datetime, model_end_time_datetime,level_formatted,dataset_type,availability_struct) # loop through the available times using multiprocessing if len(available_times): # create a list to keep all processes processes = [] # create a list to keep connections parent_connections = [] # create a process per instance for mtime in available_times: # this is the subsetted .pickle data data_key = build_tiledata_path(dataset, sub_resource, level_formatted, mtime, coords) # create a pipe for communication parent_conn, child_conn = Pipe() parent_connections.append(parent_conn) # create the process, pass instance and connection process = Process(target=get_model_value, args=(coords, data_key, sub_resource, dataset_vars, child_conn,)) processes.append(process) # start all processes for process in processes: process.start() # make sure that all processes have finished for process in processes: process.join() # build output value array value_array = [] for mtime_indx, mtime in enumerate(available_times): mtime_formatted = datetime.datetime.strftime(mtime,'%Y-%m-%dT%H:%MZ') data_point = {mtime_formatted: parent_connections[mtime_indx].recv()} value_array.append(data_point) # construct the response body response_body = { 'model': dataset, 'sub_resource': sub_resource, 'data': value_array, 'units': dataset_units } print(value_array) return generate_response(200, headers, response_body) else: response_body = { 'model': dataset, 'sub_resource': sub_resource, 'data': None, 'units': None, } return generate_response(200, headers, response_body) if __name__ == '__main__': # event = { # "queryStringParameters": { # "level": "0", # "dataset": "RTOFS_DATA", # "sub_resource": "ocean_current_speed", # "start_time": "2019-02-28T01:00Z", # "end_time": "2019-03-03T19:00Z", # "coordinates": "-81.58,23.88" # } # } lambda_handler('','') <file_sep>import sys sys.path.append("..") import os import json import io import subprocess from HYCOM.check_remote import is_data_fresh as is_hycom_fresh from RTOFS.check_remote import is_data_fresh as is_rtofs_fresh from GFS.check_remote import is_data_fresh as is_gfs_fresh from WW3.check_remote import is_data_fresh as is_ww3_fresh dataset_mapping = { 'hycom': {'status_checker': is_hycom_fresh, 'harvest_func_path': 'HYCOM/hycom_3d_data_fetch_init.py'}, 'rtofs': {'status_checker': is_rtofs_fresh, 'harvest_func_path': 'RTOFS/rtofs_3d_data_fetch_init.py'}, 'gfs': {'status_checker': is_gfs_fresh, 'harvest_func_path': 'GFS/gfs_data_fetch_init.py'}, 'ww3': {'status_checker': is_ww3_fresh, 'harvest_func_path': 'WW3/ww3_data_fetch_init.py'} } def harvest_data(): ''' This function loops through datasets in harvest_status.json file and triggers data harvesting ''' with open('harvest_status.json') as f: harvest_status = json.loads(f.read()) # count number of harvest processes running num_processing = len([i for i in harvest_status.values() if i == 'processing']) # filter on the jobs that are ready to run ready_jobs = dict([i for i in harvest_status.items() if i[1] == 'ready']) for dataset, status in ready_jobs.items(): num_processing += 1 # only allow 2 data harvest processes to run if num_processing < 3: # kick of harvest for particular datset and increment num_processing # check if data is fresh before harvesting.. if it is then continue is_fresh = dataset_mapping[dataset]['status_checker']() if not is_fresh: # construct filepath of specific harvest script harvest_script_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), dataset_mapping[dataset]['harvest_func_path']) print('launching harvest script for: {}'.format(dataset)) subprocess.Popen(['python', harvest_script_path]) if __name__ == "__main__": harvest_data() # run from this parent folder <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import ExpansionPanel from './ExpansionPanel'; import ExpansionPanelSummary from './ExpansionPanelSummary'; import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails'; import Typography from '@material-ui/core/Typography'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import AddIcon from '@material-ui/icons/Add'; import RemoveIcon from '@material-ui/icons/Remove'; // https://github.com/mui-org/material-ui/pull/10961 // https://stackoverflow.com/questions/46066675/how-to-add-multiple-classes-in-material-ui-using-the-classes-props const styles = theme => ({ root: { width: '100%', }, heading: { fontSize: theme.typography.pxToRem(15), fontWeight: theme.typography.fontWeightRegular, } }); function SimpleExpansionPanel(props) { const { classes } = props; return ( <div className={classes.root}> <ExpansionPanel> <ExpansionPanelSummary expandIcon={<AddIcon />} collapseIcon={<RemoveIcon />} > <Typography className={classes.heading}>Expansion Panel 1</Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget. </Typography> </ExpansionPanelDetails> </ExpansionPanel> <ExpansionPanel> <ExpansionPanelSummary> <Typography className={classes.heading}>Expansion Panel 2</Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget. </Typography> </ExpansionPanelDetails> </ExpansionPanel> <ExpansionPanel > <ExpansionPanelSummary> <Typography className={classes.heading}>Disabled Expansion Panel</Typography> </ExpansionPanelSummary> </ExpansionPanel> </div> ); } SimpleExpansionPanel.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(SimpleExpansionPanel);<file_sep>import base64 import matplotlib matplotlib.use('agg') from matplotlib import pyplot as plt import io def get_min_zoom(series): if 'MIN_ZOOM' in series: min_zoom = series.MIN_ZOOM elif 'min_zoom' in series: min_zoom = series.min_zoom else: min_zoom = 0 return min_zoom def make_tile_figure(height=256, width=256, dpi=256): """ make_tile_figure(height=256, width=256, dpi=256) create a transparent figure with a specified width, height, and dpi with no x/y ticks and axis turned off Ouput: figure and axes object """ fig = plt.figure(dpi=dpi, facecolor='none', edgecolor='none') fig.set_alpha(0) fig.set_figheight(height/dpi) fig.set_figwidth(width/dpi) figax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[]) figax.set_axis_off() return fig, figax def blank_tile(height=256, width=256, dpi=256): """ blank_tile(height=256, width=256, dpi=256) create and return a transparent image as a bytes-like object Ouput: image represented as a string """ fig, ax = make_tile_figure(height, width, dpi) ax.set_frame_on(False) ax.set_clip_on(False) ax.set_position([0, 0, 1, 1]) with io.BytesIO() as out_img: fig.savefig(out_img, format='png', dpi=dpi, pad_inches=0.0, transparent=True) out_img.seek(0) encoded_img = base64.b64encode(out_img.read()).decode('utf-8') return encoded_img<file_sep>import boto3 import numpy as np import mercantile import pickle import json s3 = boto3.client('s3') lam = boto3.client('lambda') def pickle_task_distributor(pickle_filepath, bucket_name, output_picklepath, zoom=3): """ tile_task_distributor(pickle_filepath, data_type, bucket_name, output_picklepath, zoom=3) ----------------------------------------------------------------------- Inputs: picke_data_path: (str) - the path of the .pickle data file bucket_name: (str) the AWS bucket name output_picklepath: (str) - the location where subsetted data are saved zoom: (int) - the zoom level to generate data 'tiles' ----------------------------------------------------------------------- Output: Invokes process_pickle.py lambda function on AWS with fully specified event ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/08/2018 """ pickle_data = s3.get_object(Bucket=bucket_name, Key=pickle_filepath) body_string = pickle_data['Body'].read() data = pickle.loads(body_string) lat = data['lat'] lon = data['lon'] tiles = mercantile.tiles(west=lon.min(), south=lat.min(), east=lon.max(), north=lat.max(), zooms=zoom) x,y,z = zip(*[t for t in tiles]) #break into groups of 50 group_size = 50 tile_break_points=(list(range(0,len(x), group_size))) tile_break_points.append(len(x)) # check that the event is valid format for break_indx in range(len(tile_break_points)-1): # build payload for initiation of lambda function payload = {} payload['pickle_filepath'] = pickle_filepath payload['bucket_name'] = bucket_name payload['output_picklepath'] = output_picklepath payload['xyz_info'] = {'start_indx': tile_break_points[break_indx], 'end_indx': tile_break_points[break_indx+1]} payload['zoom'] = zoom # invoke process_tiles with appropriate payload try: response = lam.invoke(FunctionName='process_pickle', InvocationType='Event', Payload=json.dumps(payload)) except Exception as e: raise e if __name__ == "__main__": lambda_handler('','')<file_sep>import sys sys.path.append("..") import urllib.request as urllib from bs4 import BeautifulSoup import netCDF4 import datetime import numpy as np import re from harvest_utils.fetch_utils import get_opendapp_netcdf def get_ww3_forecast_info(ww3_url): """ get_ww3_forecast_info(ww3_url) This function assembles an array tuples containing the model forecast field datetime as well as the index of the forecast field. This facilitates to concurrent downloads of model data. ----------------------------------------------------------------------- Input: {string} ww3_url - displays available Wave Watch 3 forecast model runs i.e. https://nomads.ncep.noaa.gov:9090/dods/wave/nww3 ----------------------------------------------------------------------- Output: array of tuples with this structure: forecast_info = [(forecast_indx, forecast_field_datetime), ...] ----------------------------------------------------------------------- Author: <NAME> Date Modified: 04/20/2019 """ page = urllib.urlopen(ww3_url).read() soup = BeautifulSoup(page,'html.parser') soup.prettify() date_array = np.array([]) for datetime_element in soup.findAll('b'): match = re.search(r'(\d{8})[/]:$', datetime_element.string) if match: unformatted_date = match.group(1) datetime_element = datetime.datetime.strptime(unformatted_date,'%Y%m%d') date_array = np.append(date_array, datetime_element) max_forecast_run_date = np.max(date_array) formatted_latest_date = datetime.datetime.strftime(max_forecast_run_date, '%Y%m%d') # find the latest run using bs4 forecast_run_url = ww3_url +'/nww3' + formatted_latest_date page = urllib.urlopen(forecast_run_url).read() soup = BeautifulSoup(page,'html.parser') soup.prettify() forecast_run_array = {} for model_run in soup.findAll('b'): match = re.search(r'nww3\d{8}_(\d{2})z', model_run.string) if match: run_name = match.group(0) forecast_run_hour = match.group(1) forecast_run_array.setdefault(int(forecast_run_hour), run_name) # build forecast field datetime/indx array max_run = max(forecast_run_array.keys()) opendapp_url = forecast_run_url + '/' + run_name file = get_opendapp_netcdf(opendapp_url) product_times = file.variables['time'][:] file.close() forecast_info = {} forecast_info['url'] = opendapp_url forecast_info['data'] = [] for forecast_indx, forecast_time in enumerate(product_times): basetime_int = int(forecast_time) extra_days = forecast_time - basetime_int # need to subtract 1 since WW3 is days since 0001-01-01 (yyyy-mm-dd) full_forecast_time = (datetime.datetime.fromordinal(basetime_int) + datetime.timedelta(days = extra_days) - datetime.timedelta(days=1)) forecast_info['data'].append((forecast_indx, full_forecast_time)) return forecast_info if __name__ == '__main__': ww3_url = 'https://nomads.ncep.noaa.gov:9090/dods/wave/nww3' get_ww3_forecast_info(ww3_url) <file_sep>import json import boto3 s3 = boto3.client('s3') def grab_data_availability(): """ grab_data_availability() This function is used to read the data_availability.json file on s3 and convert to json ----------------------------------------------------------------------- Inputs: no inputs ----------------------------------------------------------------------- Output: the data availability object ----------------------------------------------------------------------- Author: <NAME> Date Modified: 09/16/2018 """ bucket='oceanmapper-data-storage' key='data_availability.json' try: raw_data = s3.get_object(Bucket=bucket, Key=key) availability_struct = json.loads(raw_data['Body'].read().decode('utf-8')) return availability_struct except Exception as e: return None<file_sep>let priority = { lowest: 400, low: 401, medium: 402, high: 403, highest: 404 } export default priority;<file_sep>import random import time import netCDF4 class NetworkError(RuntimeError): pass # http://pragmaticcoders.com/blog/retrying-exceptions-handling-internet-connection-problems/ def retryer(max_retries=100, max_wait=3): def wraps(func): os_exceptions = ( OSError ) def inner(*args, **kwargs): for i in range(max_retries): try: result = func(*args, **kwargs) except os_exceptions: time.sleep(random.randrange(max_wait)) continue else: return result else: raise NetworkError return inner return wraps @retryer(max_retries=100, max_wait=3) def get_opendapp_netcdf(url): return netCDF4.Dataset(url) <file_sep>from pylab import * # viridis # magmga cmap = cm.get_cmap('Greys', 5) # PiYG for i in range(cmap.N): rgb = cmap(i)[:3] # will return rgba, we take only first 3 so we get rgb print(matplotlib.colors.rgb2hex(rgb))<file_sep>import sys sys.path.append("..") import os import json import boto3 import numpy as np import datetime import time import logging from WW3_forecast_info import get_ww3_forecast_info from WW3_process_fields import process_fields from harvest_utils.status_utility import update_process_status # create logger logger = logging.getLogger('data-harvest') logger.setLevel(logging.INFO) # create console handler ch = logging.StreamHandler() ch.setLevel(logging.INFO) logger.addHandler(ch) # create file handler logfile_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'data-harvest.log') fh = logging.FileHandler("{0}".format(logfile_path)) fh.setLevel(logging.INFO) logger.addHandler(fh) # create formatter formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s') # add formatter to ch and fh ch.setFormatter(formatter) fh.setFormatter(formatter) def main(): """ main(): This function kicks off a script to read, process, and save ww3 forecast data to s3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 4/20/2019 """ logger.info('-- FETCHING GFS DATA --') # update the harvest status file status_update = update_process_status('ww3', 'processing') ww3_url = 'https://nomads.ncep.noaa.gov:9090/dods/wave/nww3' forecast_info = get_ww3_forecast_info(ww3_url) for model_field_indx, forecast_time in forecast_info['data']: # only utilize certain forecast times for efficiency if forecast_time.hour % 6 == 0: data_url = forecast_info['url'] try: process_fields(data_url, forecast_time, model_field_indx) except Exception as e: logger.error('An error occured!! - {}'.format(e)) continue # set processing status back to ready status_update = update_process_status('ww3', 'ready') if __name__ == "__main__": main() <file_sep># -*- coding: utf-8 -*- """ Created on Mon Apr 2 17:20:30 2018 @author: <NAME> """ import json import boto3 import numpy as np from scipy import interpolate import datetime import netCDF4 import pickle from utils.fetch_utils import get_opendapp_netcdf def lambda_handler(event, context): """ lambda_handler(event, context): This function reads, parses, and saves a .json and .pickle file from a netCDF file from a provided opendapp url (contained within the event paramater object). ----------------------------------------------------------------------- Inputs: event: AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type. context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Output: A .json file and a .pickle file are save to S3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 08/26/2018 """ AWS_BUCKET_NAME = 'oceanmapper-data-storage' TOP_LEVEL_FOLDER = 'RTOFS_OCEAN_CURRENTS_HIGHRES' # unpack event data url = event['url'] model_field_time = datetime.datetime.strptime(event['forecast_time'],'%Y%m%dT%H:%M') model_field_indx = event['forecast_indx'] file = get_opendapp_netcdf(url) formatted_folder_date = datetime.datetime.strftime(model_field_time,'%Y%m%d_%H') # update this when fetching 4d data (right now only use surface depth output_json_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/0m/json/' + 'rtofs_currents_' + formatted_folder_date + '.json') output_pickle_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/0m/pickle/' + 'rtofs_currents_' + formatted_folder_date + '.pickle') output_tile_scalar_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + str(model_level_depth) + 'm/tiles/scalar/') lat = file.variables['lat'][:] lon = file.variables['lon'][:] # transform masked values to 0 u_data_raw = file.variables['u_velocity'][model_field_indx,0,:,:] #[time,level,lat,lon] v_data_raw = file.variables['v_velocity'][model_field_indx,0,:,:] u_data_mask_applied = np.where(~u_data_raw.mask, u_data_raw, 0) v_data_mask_applied = np.where(~v_data_raw.mask, v_data_raw, 0) # rtofs longitudes go from 74.16 to 434.06227 -- remap and sort to -180 to 180 grid lon_translate = np.where(lon>180, lon-360.0, lon) lon_sort_indices = np.argsort(lon_translate) # ordered clongitude arrays lon_ordered = lon_translate[lon_sort_indices] # rebuild u/v data with correct longitude sorting (monotonic increasing) u_data_cleaned = np.array([lat_row[lon_sort_indices] for lat_row in u_data_mask_applied]) v_data_cleaned = np.array([lat_row[lon_sort_indices] for lat_row in v_data_mask_applied]) # assign the raw data to a variable so we can pickle it for use with other scripts raw_data = {'lat': lat, 'lon': lon_ordered, 'u_vel': u_data_cleaned, 'v_vel': v_data_cleaned} raw_data_pickle = pickle.dumps(raw_data) output_lat_array = np.arange(-90,90.5,0.5) # last point is excluded with arange (90 to -90) output_lon_array = np.arange(-180,180.5,0.5) # last point is excluded with arange (-180 to 180) u_interp_func = interpolate.interp2d(lon_ordered, lat, u_data_cleaned, kind='cubic') v_interp_func = interpolate.interp2d(lon_ordered, lat, v_data_cleaned, kind='cubic') u_data_interp = u_interp_func(output_lon_array, output_lat_array) v_data_interp = v_interp_func(output_lon_array, output_lat_array) minLat = np.min(output_lat_array) maxLat = np.max(output_lat_array) minLon = np.min(output_lon_array) maxLon = np.max(output_lon_array) dx = np.diff(output_lon_array)[0] dy = np.diff(output_lat_array)[0] output_data = [ {'header': { 'parameterUnit': "m.s-1", 'parameterNumber': 2, 'dx': dx, 'dy': dy, 'parameterNumberName': "Eastward current", 'la1': maxLat, 'la2': minLat, 'parameterCategory': 2, 'lo1': minLon, 'lo2': maxLon, 'nx': len(output_lon_array), 'ny': len(output_lat_array), 'refTime': datetime.datetime.strftime(model_field_time,'%Y-%m-%d %H:%M:%S'), }, 'data': [float('{:.3f}'.format(el)) if np.abs(el) > 0.0001 else 0 for el in u_data_interp[::-1].flatten().tolist()] }, {'header': { 'parameterUnit': "m.s-1", 'parameterNumber': 3, 'dx': dx, 'dy': dy, 'parameterNumberName': "Northward current", 'la1': maxLat, 'la2': minLat, 'parameterCategory': 2, 'lo1': minLon, 'lo2': maxLon, 'nx': len(output_lon_array), 'ny': len(output_lat_array), 'refTime': datetime.datetime.strftime(model_field_time,'%Y-%m-%d %H:%M:%S'), }, 'data': [float('{:.3f}'.format(el)) if np.abs(el) > 0.0001 else 0 for el in v_data_interp[::-1].flatten().tolist()] }, ] client = boto3.client('s3') client.put_object(Body=json.dumps(output_data), Bucket=AWS_BUCKET_NAME, Key=output_json_path) client.put_object(Body=raw_data_pickle, Bucket=AWS_BUCKET_NAME, Key=output_pickle_path) # call an intermediate function to distribute tiling workload tile_task_distributor(output_pickle_path, 'current_speed', AWS_BUCKET_NAME, output_tile_scalar_path, range(3,5)) file.close() if __name__ == "__main__": lambda_handler('','') <file_sep>import json def generate_response(status_code, headers, response_body): """ This function generates a response object that an application frontend will consume ----------------------------------------------------------------------- Inputs: status_code (int): http status codes headers (obj): response headers response_body (obj): contains key/value pairs ----------------------------------------------------------------------- Output: response object ----------------------------------------------------------------------- Author: <NAME> Date Modified: 09/08/2018 """ return { 'statusCode': status_code, 'body': json.dumps(response_body), 'headers': headers } <file_sep>import mercantile from build_tile_from_shape import build_tile_from_shape from utils.tile_utils import blank_tile import json def lambda_handler(event, context): """ lambda_handler(event, context): This function is used in conjunction with aws api gateway (lambda proxy integration) to generate an tile image on the fly ----------------------------------------------------------------------- Inputs: event: Event data (pathParameters and queryStringParameters) are parsed from call to aws api endpoint context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Notes: https://stackoverflow.com/questions/35804042/aws-api-gateway-and-lambda-to-return-image ----------------------------------------------------------------------- Output: response object ----------------------------------------------------------------------- Author: <NAME> Date Modified: 03/28/2020 """ response_obj = { "isBase64Encoded": True, "statusCode": 200, "headers": {'Content-Type': 'image/png', 'Access-Control-Allow-Origin': '*'}, "body": None # base64.b64encode(content_bytes).decode("utf-8") #TODO drop image bytes in here } shapefile_path = event['queryStringParameters']['shapefile_path'] #TODO: str needs to be converted to number query_params = { "linewidth": float(event['queryStringParameters'].get('linewidth')) if event['queryStringParameters'].get('linewidth') else None, "edgecolor": event['queryStringParameters'].get('edgecolor') } override_config = {k: v for k, v in query_params.items() if v is not None} zoom, i, j = tuple([int(val) for val in event['pathParameters']['proxy'].split('/')]) incoming_tile = mercantile.Tile(i, j, zoom) try: response_obj['body'] = build_tile_from_shape(incoming_tile, shapefile_path, override_config) except Exception as e: print('failed on tile image build') print(e) response_obj['body'] = blank_tile() return response_obj if __name__ == '__main__': event = { "queryStringParameters": { "shapefile_path": "https://www.boem.gov/BOEM-Renewable-Energy-Shapefiles.zip", "linewidth": 0.9, "edgecolor": "#ff3300" }, "pathParameters": { "proxy": "8/77/95" } } lambda_handler(event,'') # https://a7vap1k0cl.execute-api.us-east-2.amazonaws.com/staging/dynamic-tile/5/8/13?dataset=RTOFS_DATA&sub_resource=ocean_current_speed&level=0&time=2019-02-21T23:00Z # https://a7vap1k0cl.execute-api.us-east-2.amazonaws.com/staging/dynamic-tile/2/1/2?dataset=GFS_DATA&sub_resource=wind_speed&level=10&time=2019-02-26T23:00Z&n_levels=100&color_map=magma&data_range=0,100 <file_sep>import fiona from shapely import geometry def lambda_handler(event, context): lat = event['lat'] lon = event['lon'] coord_in_ocean = in_ocean(lon, lat) return coord_in_ocean def in_ocean(point_lon,point_lat): """ in_ocean(point_lon,point_lat) This function determines if a provided point is in the ocean ----------------------------------------------------------------------- Inputs: point_lon (float) - the coordinate longitude point_lat (float) - the coordinate latitude ----------------------------------------------------------------------- Output: (bool) - true/false ----------------------------------------------------------------------- Author: <NAME> Date Modified: 09/23/2018 """ coord_in_ocean = False with fiona.open("utils/ne_10m_ocean/ne_10m_ocean.shp") as fiona_collection: shapefile_record = fiona_collection.next() #TODO: deal with null island # need to create a 1km square island # Use Shapely to create the polygon shape = geometry.asShape( shapefile_record['geometry'] ) point = geometry.Point(point_lon, point_lat) # longitude, latitude # Alternative: if point.within(shape) if shape.contains(point): coord_in_ocean = True return coord_in_ocean if __name__ == '__main__': event = { 'lat': 25.0, 'lon': -95 } lambda_handler(event,'')<file_sep>import sys sys.path.append("..") import os import json import boto3 import numpy as np import datetime import time import logging from HYCOM_forecast_info import get_hycom_forecast_info from HYCOM_process_3d_fields import process_3d_fields from harvest_utils.data_endpoints import hycom_catalog_root from harvest_utils.status_utility import update_process_status # create logger logger = logging.getLogger('data-harvest') logger.setLevel(logging.INFO) # create console handler ch = logging.StreamHandler() ch.setLevel(logging.INFO) logger.addHandler(ch) # create file handler logfile_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'data-harvest.log') fh = logging.FileHandler("{0}".format(logfile_path)) fh.setLevel(logging.INFO) logger.addHandler(fh) # create formatter formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s') # add formatter to ch and fh ch.setFormatter(formatter) fh.setFormatter(formatter) def main(): """ main(): This function kicks off a script to read, process, and save hycom forecast data to s3 ----------------------------------------------------------------------- Notes: Check here for hycom version updates: http://tds.hycom.org/thredds/catalog/datasets/catalog.html ----------------------------------------------------------------------- Author: <NAME> Date Modified: 4/13/2019 """ logger.info('-- FETCHING HYCOM DATA --') # update the harvest status file status_update = update_process_status('hycom', 'processing') hycom_catalog_url = '{}catalog.html'.format(hycom_catalog_root) forecast_info = get_hycom_forecast_info(hycom_catalog_url) zipped_time_and_indx = np.array(tuple(zip(forecast_info['forecast']['field_datetimes'], forecast_info['forecast']['data_urls']))) # generate an array of tuples [(level indx, level)...] levels = forecast_info['levels'] stop_level = 100 levels_array=[(level_indx, level) for level_indx, level in enumerate(levels) if level % 10 == 0 and level <= stop_level] for forecast_time, data_url in zipped_time_and_indx: # only utilize certain forecast times for efficiency if forecast_time.hour % 6 == 0: try: process_3d_fields(data_url, forecast_time, levels_array) except Exception as e: logger.error('An error occured!! - {}'.format(e)) continue # set processing status back to ready status_update = update_process_status('hycom', 'ready') if __name__ == "__main__": main() <file_sep>import boto3 import base64 import pickle import datetime import numpy as np import mercantile import pyproj # import matplotlib # matplotlib.use('agg') from matplotlib import pyplot as plt, cm import matplotlib.colors as colors import cmocean import copy import io import os s3 = boto3.client('s3') def lambda_handler(event, context): """ This function creates tiles (.png) and saves them in S3 ----------------------------------------------------------------------- Inputs: event: AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type. In this case the event contains these keys: 'pickle_filepath': (string) the location of the pickle data file 'data_type': (string) - one of 'wind_speed', 'current_speed', 'wave_height', 'wave_period' 'bucket_name': (string) the name of the S3 bucket ('oceanmapper-data-storage') 'output_tilepath': (string) - the location where the file will be saved on S3 'xyz_info': the start and end indx of the tiles to be processed from the mercantile generator 'zoom_array': (array) the zoom levels to make tiles for *(http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/) context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Output: A .png files are saved to S3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 08/19/2018 """ # config object cmap_config = { 'wind_speed': {'color_map': cm.get_cmap('viridis'), 'data_range': [0,25]}, 'current_speed': {'color_map': cm.get_cmap('magma'), 'data_range': [0,2]}, 'wave_amp': {'color_map': cm.get_cmap('jet'), 'data_range': [0,11]}, 'wave_dir': {'color_map': None, 'data_range': [None, None]}, 'wave_period': {'color_map': cm.get_cmap('cool'), 'data_range': [0,21]}, } # get event paramaters bucket_name = event['bucket_name'] pickle_filepath = event['pickle_filepath'] data_type = event['data_type'] output_tilepath = event['output_tilepath'] zoom_array = event['zoom_array'] start_indx = event['xyz_info']['start_indx'] end_indx = event['xyz_info']['end_indx'] # load data pickle_data = s3.get_object(Bucket=bucket_name, Key=pickle_filepath) body_string = pickle_data['Body'].read() data = pickle.loads(body_string) # process the data in preparation for tiling if np.ma.is_masked(data['lat']): lat = data['lat'].data else: lat = data['lat'] if np.ma.is_masked(data['lon']): lon = data['lon'].data else: lon = data['lon'] # remove the north/south pole lats since these cause issues when projecting to epsg:3857 keep_lat_bool = np.logical_and(lat<90, lat>-90) keep_lat_indx = np.argwhere(keep_lat_bool).ravel() lat_trim = lat[keep_lat_indx] # create lat/lon mesh grid _lon,_lat = np.meshgrid(lon,lat_trim) # project to EPSG:3857 for plotting EPSG3857 = pyproj.Proj(init='EPSG:3857') lo,la = EPSG3857(_lon,_lat) # sort by EPSG3857 because our drawing surface is in EPSG3857, data still ordered by lon/lat so = np.argsort(lo[1,:]) sa = np.argsort(la[:,1]) proj_lon_array = lo[sa,:][:,so] proj_lat_array = la[sa,:][:,so] data_cmap = cmap_config[data_type]['color_map'] cmin, cmax = cmap_config[data_type]['data_range'] # plot entire image on 256 by 256 image then crop to tile extents if data_type == 'wind_speed' or data_type == 'current_speed': fig, ax = make_tile_figure() u_vel = (data['u_vel'][keep_lat_indx,:]).astype('float64') v_vel = (data['v_vel'][keep_lat_indx,:]).astype('float64') data_array = np.sqrt((u_vel**2) + (v_vel**2)) nlvls = 100 lvls = np.linspace(cmin, cmax, nlvls) ## filled contour (use SORTED indexes for the EPSG3857 drawing surface) contourf = ax.contourf(proj_lon_array, proj_lat_array, data_array[sa,:][:,so], levels=lvls, cmap=data_cmap, extend='both') ax.set_frame_on(False) ax.set_clip_on(False) ax.set_position([0, 0, 1, 1]) elif data_type == 'wave_amp': fig, ax = make_tile_figure() height_raw = data['sig_wave_height'][keep_lat_indx,:] palette = copy.copy(data_cmap) palette.set_bad(alpha = 0.0) # ax.pcolormesh(proj_lon_array, proj_lat_array, height_raw, shading='flat', cmap=palette, # norm=colors.BoundaryNorm([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],ncolors=palette.N)) lvls = range(cmin, cmax) ax.contourf(proj_lon_array, proj_lat_array, height_raw[sa,:][:,so], cmap=palette, levels=lvls, extend='both') ax.set_frame_on(False) ax.set_clip_on(False) ax.set_position([0, 0, 1, 1]) elif data_type == 'wave_dir': fig, ax = make_tile_figure() dir_raw = data['primary_wave_dir'][keep_lat_indx,:] #directions are in degrees already dir_array = dir_raw[sa,:][:,so] # convert directions into u,v constituents (use unit vector) mag_array = np.ones_like(dir_array) u_comp,v_comp = md2uv(mag_array, dir_array,'from') # TODO: if interpolation is needed in the future see this resource: # http://christopherbull.com.au/python/scipy-interpolate-griddata/ figure_container = {} for zoom in zoom_array: if zoom <= 3: row_int = 4 col_int = 4 elif zoom == 4: row_int = 2 col_int = 2 else: # show all data col_int = 1 row_int = 1 # create separate figures for dif zooms (for wave direction) fig_container, ax_container = make_tile_figure() quiver = ax_container.quiver(proj_lon_array[::row_int,::col_int], proj_lat_array[::row_int,::col_int], u_comp[::row_int,::col_int], v_comp[::row_int,::col_int], headwidth=9.0,headlength=8.5, headaxislength=8.0, scale_units='width', scale=17.0) ax.set_frame_on(False) ax.set_clip_on(False) ax.set_position([0, 0, 1, 1]) figure_container[zoom] = fig_container elif data_type == 'wave_period': fig, ax = make_tile_figure() period_raw = data['primary_wave_period'][keep_lat_indx,:] palette = copy.copy(data_cmap) palette.set_bad(alpha = 0.0) lvls = range(cmin, cmax) ax.contourf(proj_lon_array, proj_lat_array, period_raw[sa,:][:,so], cmap=palette, levels=lvls, extend='both') ax.set_frame_on(False) ax.set_clip_on(False) ax.set_position([0, 0, 1, 1]) else: pass # get list of all tiles for certain geographic extents and zooms tiles_gen = mercantile.tiles(west=lon.min(), south=lat.min(), east=lon.max(), north=lat.max(), zooms=zoom_array) tiles = [tile for tile in tiles_gen] for tile_indx in range(start_indx,end_indx): tile = tiles[tile_indx] i,j,zoom=[*tile] ll = mercantile.bounds(i, j, zoom) _epsg_x_min, _epsg_y_min = EPSG3857(*ll[:2]) _epsg_x_max, _epsg_y_max = EPSG3857(*ll[2:]) # if working with wave direction data pick correct figure/axes for particular zoom if data_type == 'wave_dir': fig = figure_container[zoom] ax = fig.gca() # set x/y limits to match available tile extents ax.set_xlim(_epsg_x_min,_epsg_x_max) ax.set_ylim(_epsg_y_min, _epsg_y_max) if bucket_name is 'local': filename = '{0}{1}_{2}_{3}.png'.format(output_tilepath, zoom, i, j) else: filename = '{0}{1}/{2}/{3}.png'.format(output_tilepath, str(zoom), str(i), str(j)) # only run during local testing dpi=256 # dpi for output tile if bucket_name is 'local': if not os.path.exists(os.path.dirname(filename)): try: os.makedirs(os.path.dirname(filename)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise fig.savefig(filename, dpi=dpi, pad_inches=0.0, transparent=True) else: # save image to memory and then push to s3 with io.BytesIO() as out_img: fig.savefig(out_img,format='png', dpi=dpi, pad_inches=0.0, transparent=True) out_img.seek(0) s3.put_object(Body=out_img, Bucket=bucket_name, Key=filename, ACL='public-read') # release memory fig.clf() plt.close() def md2uv(magnitude, direction, orientation='from'): """ md2uv(magnitude, dir) convert magnitude and direction to u and v components """ # convert direction to compass direction if orientation == 'toward': direction_compass = np.mod(90.0 - direction, 360) else: direction_compass = np.mod(90.0 - direction + 180, 360) #convert directions to radians direction_rad = direction_compass * (np.pi/180) u_comp = magnitude * np.cos(direction_rad) v_comp = magnitude * np.sin(direction_rad) return (u_comp,v_comp) def make_tile_figure(height=256, width=256, dpi=256): """ make_tile_figure(height=256, width=256, dpi=256) create a transparent figure with a specified width, height, and dpi with no x/y ticks and axis turned off Ouput: figure and axes object """ fig = plt.figure(dpi=dpi, facecolor='none', edgecolor='none') fig.set_alpha(0) fig.set_figheight(height/dpi) fig.set_figwidth(width/dpi) figax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[]) figax.set_axis_off() return fig, figax def blank_tile(height=256, width=256, dpi=256): """ blank_tile(height=256, width=256, dpi=256) create and return a transparent image as a bytes-like object Ouput: image represented as a string """ fig, ax = make_tile_figure(height, width, dpi) ax.set_frame_on(False) ax.set_clip_on(False) ax.set_position([0, 0, 1, 1]) with io.BytesIO() as out_img: fig.savefig(out_img, format='png', dpi=dpi, pad_inches=0.0, transparent=True) out_img.seek(0) encoded_img = base64.b64encode(out_img.read()).decode('utf-8') return encoded_img if __name__ == "__main__": event = { 'pickle_filepath': 'WW3_DATA/20181216_00/sig_wave_height/pickle/ww3_htsgwsfc_20181216_00.pickle', 'data_type': 'wave_amp', 'bucket_name': 'oceanmapper-data-storage', 'output_tilepath': 'test_tiles', 'xyz_info': {'start_indx': 0, 'end_indx': 50}, 'zoom_array': [3,4,5] } context = {} lambda_handler(event,context) <file_sep>import re import datetime def check_query_params(event_query_params, required_query_params, availability_struct, datasets): """ check_query_params(event_query_params, required_query_params, availability_struct, datasets) This function is used to generalize the checking of whether or not specific query parameters are valid. ----------------------------------------------------------------------- Inputs: event_query_params (obj) - the query parameters passed on the api call required_query_params (list) - a list of required params to check availability_struct (obj) - information on data availability for environmental datasets stored on S3 datasets (obj) - basic information about environmental datasets stored on S3 ----------------------------------------------------------------------- Output: object detailing the status: OK or FAIL of specific query parameters ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/11/2018 """ query_param_checker_mapping = { 'time': (check_time_param, []), 'start_time': (check_time_param, []), 'end_time': (check_time_param, []), 'dataset': (check_dataset_param, []), 'sub_resource': (check_dataset_subresources_param,[]), 'level': (check_level_param, []), 'coordinates': (check_coordinates_param, []) } query_param_status = {} for param in required_query_params: query_param_status[param] = {'status': 'FAIL'} # default to fail then update func, func_args = query_param_checker_mapping[param] input = event_query_params['queryStringParameters'][param] or None # need to keep track of the specific_dataset in certain cases try: specific_dataset = event_query_params['queryStringParameters']['dataset'] sub_resource = event_query_params['queryStringParameters']['sub_resource'] except Exception as e: specific_dataset = None sub_resource = None if param == 'dataset': func_args.extend([input, datasets]) elif param == 'level': func_args.extend([input, specific_dataset, sub_resource, datasets, availability_struct]) elif param == 'sub_resource': func_args.extend([input, specific_dataset, datasets]) else: func_args.append(input) output_status = func(*func_args) query_param_status[param]['status'] = output_status return query_param_status def filter_failed_params(query_param_validation): failed_query_param_obj = {} for param in query_param_validation: if query_param_validation[param]['status'] == 'FAIL': failed_query_param_obj[param] = 'invalid' return failed_query_param_obj def check_time_param(dataset_time): datetime_pattern=r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z$' datetime_match = re.search(datetime_pattern,dataset_time) if datetime_match: return 'OK' else: return 'FAIL' def check_dataset_param(specific_dataset,datasets): valid_dataset = specific_dataset in datasets.keys() if valid_dataset: return 'OK' else: return 'FAIL' def check_dataset_subresources_param(sub_resource,specific_dataset,datasets): valid_sub_resource = sub_resource in datasets[specific_dataset]['sub_resource'] if valid_sub_resource: return 'OK' else: return 'FAIL' def check_level_param(level, specific_dataset, sub_resource, datasets, availability_struct): if not level and specific_dataset == 'WW3_DATA': return 'OK' else: try: level_formatted = level + 'm' if level_formatted in availability_struct[specific_dataset][sub_resource]['level'].keys(): return 'OK' else: return 'FAIL' except Exception as e: return 'FAIL' def check_coordinates_param(coordinates): coords = [float(coord) for coord in coordinates.split(',')] if (len(coords) == 2 and coords[0] >= -180 and coords[0] <= 180 and coords[1] >= -90 and coords[1] <= 90): return 'OK' else: return 'FAIL' if __name__ == '__main__': datasets = { 'HYCOM_DATA': { 'sub_resource': { 'ocean_current_speed': { 's3_folder': 'ocean_current_speed', 'data_prefix': 'hycom_currents', 'overlay_type': 'ocean', 'data_type': 'json', 'scalar_tiles': True, 'vector_tiles': False } } }, 'RTOFS_DATA': { 'sub_resource': { 'ocean_current_speed': { 's3_folder': 'ocean_current_speed', 'data_prefix': 'rtofs_currents', 'overlay_type': 'ocean', 'data_type': 'json', 'scalar_tiles': True, 'vector_tiles': False } } }, 'GFS_DATA': { 'sub_resource': { 'wind_speed': { 's3_folder': 'wind_speed', 'data_prefix': 'gfs_winds', 'overlay_type': 'all', 'data_type': 'json', 'scalar_tiles': True, 'vector_tiles': False } } }, 'WW3_DATA': { 'sub_resource': { 'sig_wave_height': { 's3_folder': 'sig_wave_height', 'data_prefix': 'ww3_htsgwsfc', 'overlay_type': 'ocean', 'data_type': 'json', 'scalar_tiles': True, 'vector_tiles': False }, 'primary_wave_dir': { 's3_folder': 'primary_wave_dir', 'data_prefix': 'ww3_dirpwsfc', 'overlay_type': 'ocean', 'data_type': 'json', 'scalar_tiles': False, 'vector_tiles': True }, 'primary_wave_period': { 's3_folder': 'primary_wave_period', 'data_prefix': 'ww3_perpwsfc', 'overlay_type': 'ocean', 'data_type': 'json', 'scalar_tiles': True, 'vector_tiles': False } } } } event = { "queryStringParameters": { "level": "10", "dataset": "HYCOM_DATA", "sub_resource": "ocean_current_speed", "time": "2018-09-16T08:00Z", "coordinates": "-72.0,42.0" } } required_query_params = ['time','dataset','level','coordinates'] check_query_params(event,required_query_params, datasets)<file_sep>import sys sys.path.append("..") import urllib.request as urllib from bs4 import BeautifulSoup import netCDF4 import datetime import numpy as np import collections import re from harvest_utils.fetch_utils import get_opendapp_netcdf from harvest_utils.data_endpoints import hycom_opendapp_root, hycom_data_prefix def get_hycom_forecast_info(hycom_url): """ get_hycom_forecast_info(hycom_url) This function assembles an object the latest available forecast date that contains the full forecast extent (168hrs) as well as an array of all opendapp urls (1 for each timestep) as well as an array containing the various depth levels supported by this model. Model Info: https://www.hycom.org/dataserver/gofs-3pt1/analysis ----------------------------------------------------------------------- Input: {string} hycom_url - the HYCOM forecast data catalog url i.e. http://tds.hycom.org/thredds/catalog/datasets/GLBv0.08/expt_93.0/data/forecasts/catalog.html ----------------------------------------------------------------------- Output: object with this structure: forecast_info = {forecast: {'latest_date': 'yyyymmdd', 'data_urls': [xxx, xxx, xxx], 'field_datetimes': [dt,dt...]}, 'levels': [0,2,...]}} """ page = urllib.urlopen(hycom_url).read() soup = BeautifulSoup(page,'html.parser') soup.prettify() forecast_dict = {} for anchor in soup.findAll('a', href=True): anchor_str = anchor['href'] search_str = '{}'.format(hycom_data_prefix) + r'(\d{10})_t(\d{3})_uv3z.nc$' match = re.search(search_str, anchor_str) if match: unformatted_date = match.group(1) datetime_element = datetime.datetime.strptime(unformatted_date,'%Y%m%d%H') forecast_hour_extent = int(match.group(2)) full_forecast_time = datetime_element + datetime.timedelta(hours = forecast_hour_extent) forecast_dict.setdefault(datetime_element, []).append({'forecast_date': full_forecast_time, 'forecast_hour_extent': forecast_hour_extent}) # sort available unique forecast dates in reverse order so most recent is first unique_dates = sorted(forecast_dict.keys(),reverse=True) max_forecast_run_date = unique_dates[0] # use the forecast which gets full coverage (at this point in time its 168 hrs into the future) # deal with possibility of only 1 date available if len(unique_dates) > 1: previous_forecast_extent = forecast_dict[unique_dates[1]][-1]['forecast_hour_extent'] else: previous_forecast_extent = 0 present_forecast_extent = forecast_dict[unique_dates[0]][-1]['forecast_hour_extent'] if present_forecast_extent >= previous_forecast_extent: latest_date = unique_dates[0] else: latest_date = unique_dates[1] formatted_latest_date = datetime.datetime.strftime(latest_date, '%Y%m%d%H') # base_opendapp_url = 'http://tds.hycom.org/thredds/dodsC/datasets/GLBv0.08/expt_93.0/data/forecasts/hycom_glbv_930_' base_opendapp_url = '{}{}'.format(hycom_opendapp_root, hycom_data_prefix) data_urls = [] field_datetimes=[] for forecast_field in forecast_dict[latest_date]: formatted_hour_extent = str(forecast_field['forecast_hour_extent']).zfill(3) output_url = base_opendapp_url + formatted_latest_date + '_t' + formatted_hour_extent + '_uv3z.nc' data_urls.append(output_url) field_datetimes.append(forecast_field['forecast_date']) forecast_info = {'forecast': {'latest_date': datetime.datetime.strftime(latest_date,'%Y%m%d_%H%M'), 'data_urls': data_urls, 'field_datetimes': field_datetimes}} # use the first data url to get the various depth levels (they are the same for each .nc file) file = get_opendapp_netcdf(data_urls[0]) levels = file.variables['depth'][:] file.close() # add levels to output data structure forecast_info['levels'] = [int(lev) for lev in levels.tolist()] return forecast_info if __name__ == "__main__": hycom_url = "http://tds.hycom.org/thredds/catalog/datasets/GLBv0.08/expt_93.0/data/forecasts/catalog.html" get_hycom_forecast_info(hycom_url) <file_sep>#!/bin/sh cd /data_harvest/harvest_utils/ python harvest_initiator.py<file_sep>import boto3 import datetime import os import re s3 = boto3.resource('s3') data_bucket = s3.Bucket('oceanmapper-data-storage') datasets = ['HYCOM_DATA', 'RTOFS_DATA', 'WW3_DATA', 'GFS_DATA'] # get present time in UTC utc_now = datetime.datetime.utcnow() def lambda_handler(event, context): """ This function deletes files from s3 that are older than the 'keep_days' environment variable ----------------------------------------------------------------------- Output: None """ keep_days = os.getenv('keep_days', 10) for dataset_value in datasets: for object in data_bucket.objects.filter(Prefix=dataset_value): pattern = r'\d{8}_\d{2}' match = re.search(pattern,object.key) if match: model_field_date = datetime.datetime.strptime(match.group(0),'%Y%m%d_%H') if model_field_date < (utc_now - datetime.timedelta(days=int(keep_days))): object.delete() if __name__ == '__main__': lambda_handler('', '')<file_sep>import moment from 'moment'; export const formatDateTime = (milliseconds, date_format = 'MM-DD-YYYY', suffix = ' UTC') => { let formattedDateTime = `${moment(milliseconds).utc().format(date_format)}${suffix}`; return formattedDateTime }<file_sep> /** * Construct title for chart * * @param {array} chartData - an array of objects containing series specific information * @returns {str} */ export const constructTitle = (chartData) => { let datasetTitleArr = [], datasetName, datasetLevel; chartData.forEach(dataSource => { datasetName = dataSource['niceName']; datasetLevel = dataSource['level'] === 'n/a' ? '' : ` (${dataSource['level']}${dataSource['levelUnit']})`; // append title fragment to array datasetTitleArr.push(`${datasetName}${datasetLevel}`) }) return datasetTitleArr.join(', '); } /** * Construct subtitle for chart * * @param {obj} activeLocation - object containing keys 'lat', 'lng' representing the active location * @param {array} chartLoadingErrors - list of dataset names for which data could not be fetched * @returns {str} */ export const constructSubTitle = (activeLocation, chartLoadingErrors, chartData=null) => { let subTitle = `<span>Coordinates: (${activeLocation['lat'].toFixed(4)}, ${activeLocation['lng'].toFixed(4)})</span>`; // loop through errors and append them as new lines to subtitle if (chartLoadingErrors.length) { let failedFetches = chartLoadingErrors.join(', '); let errorText = `<br /><span>*Failed to load: ${failedFetches}</span>`; subTitle += errorText; } if (chartData) { // loop through each data source an extract the date valid time let modelValidTime, validTimeStr = ''; chartData.forEach((dataSource, indx) => { modelValidTime =`<br /><span>*${dataSource['niceName']} (date valid): ${dataSource['validTime']}</span>`; validTimeStr += modelValidTime }) subTitle += validTimeStr; } return subTitle; }<file_sep>// leaflet gateway export const addCustomLeafletHandlers = (L) => { // const L = window.L; // add custom map event L.TimeseriesChartClickHandler = L.Handler.extend({ addHooks: function() { L.DomEvent.on(window, 'timeSeriesClick', this._timeSeriesClick, this); }, removeHooks: function() { L.DomEvent.off(window, 'timeSeriesClick', this._timeSeriesClick, this); }, _timeSeriesClick: function(ev) { // Treat Gamma angle as horizontal pan (1 degree = 1 pixel) and Beta angle as vertical pan // this._map.panBy( L.point( ev.gamma, ev.beta ) ); console.log(ev); } }); L.Map.addInitHook('addHandler', 'timeSeriesClick', L.TimeseriesChartClickHandler); // return L } <file_sep>import React from "react"; import { withStyles } from '@material-ui/core/styles'; import { Slider, Rail, Handles, Tracks, Ticks } from 'react-compound-slider' import Handle from './Handle'; import Track from './Track'; import SettingsTick from './SettingsTick'; // https://sghall.github.io/react-compound-slider/#/getting-started/tutorial const styles = theme => ({ sliderStyle: { // Give the slider some width position: 'relative', width: '100%', height: 60 }, railStyle: { position: 'absolute', width: '100%', height: 2, // 5 marginTop: 25, // 35 borderRadius: 5, backgroundColor: 'lightgray' } }); /** Component used to build settings panel opacity slider */ const OpacitySlider = (props) => { return ( <Slider className={props.classes.sliderStyle} domain={[0, 100]} step={1} mode={2} values={[props.opacity*100]} onChange={(val) => props.handleLayerSettingsUpdate(props.layerID, 'opacity', val)} > <Rail> {({ getRailProps }) => ( // adding the rail props sets up events on the rail <div className={props.classes.railStyle} {...getRailProps()} /> )} </Rail> <Handles> {({ handles, getHandleProps }) => ( <div className="slider-handles"> {handles.map(handle => ( <Handle key={handle.id} handle={handle} getHandleProps={getHandleProps} /> ))} </div> )} </Handles> <Tracks right={false}> {({ tracks, getTrackProps }) => ( <div className="slider-tracks"> {tracks.map(({ id, source, target }) => ( <Track key={id} source={source} target={target} getTrackProps={getTrackProps} /> ))} </div> )} </Tracks> <Ticks values={[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]}> {({ ticks }) => ( <div className="slider-ticks"> {ticks.map(tick => ( <SettingsTick key={tick.id} tick={tick} count={ticks.length} /> ))} </div> )} </Ticks> </Slider> ); } export default withStyles(styles, { withTheme: true })(OpacitySlider); <file_sep>u_data_reformatted = [float('{:.3f}'.format(el)) for el in u_data_cleaned_filled.flatten().tolist()] v_data_reformatted = [float('{:.3f}'.format(el)) for el in v_data_cleaned_filled.flatten().tolist()] mask_reformatted = [el for el in u_data_cleaned.mask.flatten().tolist()] # u_data_trunc = np.array(u_data_reformatted).reshape(u_data_cleaned_filled.shape) # v_data_trunc = np.array(v_data_reformatted).reshape(v_data_cleaned_filled.shape) lat_reformatted = [float('{:.4f}'.format(el)) for el in lat.tolist()] lon_reformatted = [float('{:.4f}'.format(el)) for el in lon.tolist()] full_raw_data_json = { 'lat': lat_reformatted, 'lon': lon_reformatted, 'u_vel': u_data_reformatted, 'v_vel': v_data_reformatted, 'mask': mask_reformatted, 'time_origin': datetime.datetime.strftime(time_origin, '%Y%m%d_%H')}<file_sep>import datetime from multiprocessing import Process, Pipe import boto3 from api_utils.check_query_params import check_query_params, filter_failed_params from api_utils.fetch_data_availability import grab_data_availability from api_utils.get_model_value import get_model_value from api_utils.nearest_model_time import get_available_model_times from api_utils.response_constructor import generate_response from point_locator import in_ocean from utils.datasets import datasets from utils.s3_filepath_utils import build_tiledata_path s3 = boto3.client('s3') lam = boto3.client('lambda') bucket = 'oceanmapper-data-storage' def lambda_handler(event, context): """ lambda_handler(event, context): This function is used in conjunction with aws api gateway (lambda proxy integration) to pass back the interpolated value of a dataset at a specific geographic coordinate and at all its available levels/depths ----------------------------------------------------------------------- Inputs: event: Event data (queryStringParameters) are parsed from call to aws api endpoint context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Notes: https://aws.amazon.com/blogs/compute/parallel-processing-in-python-with-aws-lambda/ ----------------------------------------------------------------------- Output: response object ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/31/2022 """ # default headers for request headers = {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'} required_query_params = ['time','dataset','sub_resource','coordinates'] # load data availability file from s3 availability_struct = grab_data_availability() if not availability_struct: response_body = { 'status': 'Failed to load data availability structure.', } return generate_response(404, headers, response_body) query_param_validation = check_query_params(event,required_query_params, availability_struct, datasets) # make sure we have all required and valid inputs failed_query_param_obj = filter_failed_params(query_param_validation) if len(failed_query_param_obj.keys()): response_body = { 'status': failed_query_param_obj, } return generate_response(404, headers, response_body) # model time model_time = event['queryStringParameters']['time'] model_time_datetime = datetime.datetime.strptime(model_time,'%Y-%m-%dT%H:%MZ') # dataset (model) dataset = event['queryStringParameters']['dataset'] # sub resource sub_resource = event['queryStringParameters']['sub_resource'] sub_resource_folder = datasets[dataset]['sub_resource'][sub_resource] dataset_units = sub_resource_folder['units'] # get all available levels then select the first one for data availability available_levels = [level for level in availability_struct[dataset][sub_resource]['level'] if level] or [''] level_formatted = available_levels[0] if len(available_levels[0]) else '' # wave data have no level # coordinates coords = [float(coord) for coord in event['queryStringParameters']['coordinates'].split(',')] overlay_type = datasets[dataset]['sub_resource'][sub_resource]['overlay_type'] coord_in_ocean = False # default is not in ocean if overlay_type == 'ocean': coord_in_ocean = in_ocean(coords[0], coords[1]) # if model is (ocean only) then check the coords to make sure they are in the ocean if not coord_in_ocean and overlay_type == 'ocean': response_body = { 'data': None, 'status': 'point on land', } return generate_response(200, headers, response_body) dataset_vars = sub_resource_folder['variables'] dataset_type = 'pickle' available_time = get_available_model_times(dataset,sub_resource, model_time_datetime, level_formatted, dataset_type, availability_struct) # loop through the available times using multiprocessing if available_time: available_time_str = datetime.datetime.strftime(available_time,'%Y-%m-%dT%H:%MZ') # create a list to keep all processes processes = [] # create a list to keep connections parent_connections = [] # create a process per instance for level_formatted in available_levels: # this is the subsetted .pickle data data_key = build_tiledata_path(dataset, sub_resource, level_formatted, available_time, coords) # create a pipe for communication parent_conn, child_conn = Pipe() parent_connections.append(parent_conn) # create the process, pass instance and connection process = Process(target=get_model_value, args=(coords, data_key, sub_resource, dataset_vars, child_conn,)) processes.append(process) # start all processes for process in processes: process.start() # make sure that all processes have finished for process in processes: process.join() # build output value array value_array = [] for level_indx, level in enumerate(available_levels): level_formatted = (level or '0m') data_point = {level_formatted: parent_connections[level_indx].recv()} value_array.append(data_point) # construct the response body response_body = { 'model': dataset, 'sub_resource': sub_resource, 'valid_time': available_time_str, 'data': value_array, 'units': dataset_units } print(value_array) return generate_response(200, headers, response_body) else: response_body = { 'model': dataset, 'sub_resource': sub_resource, 'valid_time': None, 'data': None, 'units': None, } return generate_response(200, headers, response_body) if __name__ == '__main__': # event = { # "queryStringParameters": { # "dataset": "HYCOM_DATA", # "sub_resource": "ocean_current_speed", # "time": "2022-10-31T12:00Z", # "coordinates": "-75.19,37.57" # } # } lambda_handler('','') <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import InputLabel from '@material-ui/core/InputLabel'; import FormControl from '@material-ui/core/FormControl'; import Select from '@material-ui/core/Select'; const styles = theme => ({ root: { display: 'flex', flexWrap: 'wrap', }, formControl: { // margin: theme.spacing.unit, minWidth: '100%', } }); function LevelSelector(props) { const buildLevels = availableLevels => { return ( availableLevels.map((level, index) => <option key={index} value={level} index={index}>{level}</option> ) ) } const { classes, availableLevels, presentLevel, id, levelName, handleLevelChange } = props; return ( <div className={classes.root}> <FormControl className={classes.formControl}> <InputLabel htmlFor='level-select'>{levelName}</InputLabel> <Select native autowidth='true' value={presentLevel || 0} // this might fix itself once the onChange is updated onChange={handleLevelChange.bind(this, id)} // handleChange(id) inputProps={{ name: 'levels', id: id, }} > {buildLevels(availableLevels)} </Select> </FormControl> </div> ); } LevelSelector.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(LevelSelector);<file_sep>import {getProfileData} from './dataFetchingUtils'; export const parseProfileData = (app, abortSignal) => { let mapLayers = app.state.mapLayers, orderedMapLayers = app.state.orderedMapLayers, activeLocation = app.state.activeLocation, profileData, profileFetchArray = [], activeLayers = [], arrowLen = 150; orderedMapLayers.forEach(layer => { if (mapLayers[layer] && mapLayers[layer]['isOn'] && mapLayers[layer]['dataset']) activeLayers.push(mapLayers[layer]); }) // stop execution if no active layers if (!activeLayers.length) { app.setState({chartLoading: false}); return } // fetch data for each active layer activeLayers.forEach(activeLayer => { profileData = getProfileData(activeLayer['dataset'],activeLayer['subResource'], app.state.mapTime, [activeLocation['lng'], activeLocation['lat']], abortSignal); profileFetchArray.push(profileData); }) let chartLoadingErrors = []; Promise.all(profileFetchArray).then(responses => { let outputHighChartsArray = [], datasetIDs = [], seriesData, vectorData, layerObj; responses.forEach((resp,indx) => { // skip the following logic if there was an error (so we could end up with empty outputHighChartsArray) // can i build an error object? and display error in subtitle?? if (resp['error']) { chartLoadingErrors.push(activeLayers[indx]['niceName']); return; } // build an array of names to determine if a wave data merge is necessary datasetIDs.push(activeLayers[indx]['id']); let directionConvention = activeLayers[indx]['directionConvention']; seriesData = {type: 'line', data: [] }; vectorData = {type: 'vector', data: [] }; layerObj = { niceName: activeLayers[indx]['niceName'], shortName: activeLayers[indx]['shortName'], levelUnit: activeLayers[indx]['levelUnit'], units: resp['units'], series: [] }; // based on chart type parse and package data differently let datapointKey, dateTime, depth, value, direction, origDirection, timeOrigin; resp['data'].forEach(datapoint => { datapointKey = Object.keys(datapoint)[0]; depth = parseInt(datapointKey); // no datetime is returned might need to fix that // dateTime = moment(datapointKey, 'YYYY-MM-DDTHH:mmZ').utc().valueOf(); value = datapoint[datapointKey]['val']; timeOrigin = datapoint[datapointKey]['time_origin']; if (activeLayers[indx]['chartType'] === 'series-vector') { // original direction already accounts for to/from standards for winds/waves/currents origDirection = datapoint[datapointKey]['direction']; // add 180 degrees if working with certain datasets so arrow displays correctly in charts direction = directionConvention === 'from' ? datapoint[datapointKey]['direction'] : (datapoint[datapointKey]['direction'] + 180) % 360; seriesData['data'].push({x: depth, y: value, direction: origDirection, timeOrigin}); vectorData['data'].push([depth, value, arrowLen, direction]) } else if (activeLayers[indx]['chartType'] === 'vector') { direction = directionConvention === 'from' ? value : (value + 180) % 360; // vector gets plot at a constant y value of 1 vectorData['data'].push([depth, 1, arrowLen, direction]); } else { seriesData['data'].push({x: depth, y: value, timeOrigin}); } }) // only push non empty data arrays to output array to be shipped to highcharts component let comboSeries = [seriesData, vectorData]; comboSeries.forEach(dataObj => { if (dataObj['data'].length > 0) { layerObj['series'].push(dataObj) } }) // push object into output array outputHighChartsArray.push(layerObj); }) // merge wave height and direction at this point if both exist in outputHighChartsArray if (datasetIDs.includes('ww3_sig_wave_height') & datasetIDs.includes('ww3_primary_wave_dir')) { var waveHeightIndx = datasetIDs.indexOf('ww3_sig_wave_height'); var waveDirIndx = datasetIDs.indexOf('ww3_primary_wave_dir'); // note that modifying waveHeightArr in forEach loop below modifies outputHighChartsArray let waveHeightArr = outputHighChartsArray[waveHeightIndx].series[0].data.slice(); let waveDirectionObj = {}; // create an object with forecast times as keys and direction as values outputHighChartsArray[waveDirIndx].series[0].data.forEach(el => { waveDirectionObj[el[0]] = el[3]; }) // empty vector data before adding new data vectorData['data'] = []; outputHighChartsArray[waveHeightIndx].series.push(vectorData) // for each wave height entry see if corresponding data exists for wave direction // and add it to the vector series if it does waveHeightArr.forEach((waveHeightData,arrIndx) => { let dpth = waveHeightData['x']; let val = waveHeightData['y']; if (waveDirectionObj[dpth]) { outputHighChartsArray[waveHeightIndx].series[1].data.push( [dpth, val, arrowLen, waveDirectionObj[dpth]]) // updates outputHighChartsArray to include direction property alongside wave height waveHeightData['direction'] = waveDirectionObj[dpth]; } }) // remove wave direction from output array since its now combined with wave height outputHighChartsArray.splice(waveDirIndx, 1); } // TODO: need to sort the arrays by depth app.setState({chartLoading: false, chartData: outputHighChartsArray, chartLoadingErrors}); }) } <file_sep>import React from "react"; import classNames from 'classnames'; import { withStyles } from '@material-ui/core/styles'; import { staticLegendEndpoint } from '../scripts/layers'; const styles = theme => ({ img: { width: '95%', }, }); /** Component used to build a dynamic legend */ const DynamicLegend = (props) => { // TODO do i need a function to execute when onload.. show text before that.. (legend building..) const colorMap = props['layer']['rasterProps']['colormap']; const dataRange = `${props['layer']['rasterProps']['currentMin']},${props['layer']['rasterProps']['currentMax']}`; const interval = props['layer']['rasterProps']['interval']; const label = props['layer']['rasterProps']['label']; const buildStaticLegendUrl = () => { // backend save legends with 3 decimal places let dataRangeLongFormat = `${Number(props['layer']['rasterProps']['currentMin']).toFixed(3)}_ ${Number(props['layer']['rasterProps']['currentMax']).toFixed(3)}`.replace(/\s/g, ""); let intervalLongFormat = Number(interval).toFixed(3); let labelWithUnits = label.replace(/ /g,'_').replace('/','_'); return `${staticLegendEndpoint}${colorMap}_${dataRangeLongFormat}_${intervalLongFormat}_${labelWithUnits}_legend.png`; } const buildDynamicLegendUrl = (e) => { e.target.onerror = null; e.target.src = `${props['legendUrl']}?color_map=${colorMap}&data_range=${dataRange}&interval=${interval}&label=${label}`; } return ( <div> <img src={buildStaticLegendUrl()} alt='data-legend' className={classNames(props.classes.img)} onError={buildDynamicLegendUrl} /> </div> ); } export default withStyles(styles, { withTheme: true })(DynamicLegend); <file_sep>git+https://github.com/jswhit/pyproj.git boto3 bs4==0.0.1 mercantile==1.0.4 netCDF4==1.3.1 python-dateutil==2.7.2 pytz==2018.4 requests==2.19.1 scipy==1.0.1<file_sep>import React from "react"; import { withTheme } from '@material-ui/core/styles'; const Track = ({ source, target, getTrackProps, theme }) => { // your own track component return ( <div style={{ position: 'absolute', height: 2, zIndex: 1, marginTop: 25, backgroundColor: theme.palette.secondary.main, borderRadius: 5, cursor: 'pointer', left: `${source.percent}%`, width: `${target.percent - source.percent}%`, }} {...getTrackProps()} /> ) } export default withTheme()(Track);<file_sep>import boto3 import pdb # from boto.s3.key import Key s3 = boto3.resource('s3') my_bucket = s3.Bucket('oceanmapper-data-storage') # k = Key(bucket,srcFileName) #Get the key of the given object # k.delete() #Delete the object for object in my_bucket.objects.filter(Prefix='RTOFS_OC/0m/rtofs_currents'): print(object.key) pdb.set_trace() <file_sep># -*- coding: utf-8 -*- """ Created on Mon Apr 2 17:20:30 2018 @author: <NAME> """ import datetime import json import time import boto3 from WW3_forecast_info import get_ww3_forecast_info lam = boto3.client('lambda') def lambda_handler(event, context): """ lambda_handler(event, context): This function invokes concurrent lambda functions to read, parse, and save GFSwave model: Global 0p25deg grid ----------------------------------------------------------------------- Inputs: event: AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type. context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Output: No output ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/20/2022 """ ww3_url = 'https://nomads.ncep.noaa.gov/dods/wave/gfswave' forecast_info = get_ww3_forecast_info(ww3_url) for forecast_indx, forecast_time in forecast_info['data']: # build payload for initiation of lambda function payload = {} payload['url'] = forecast_info['url'] payload['forecast_time'] = datetime.datetime.strftime(forecast_time,'%Y%m%dT%H:%M') payload['forecast_indx'] = forecast_indx # InvocationType = RequestResponse # this is used for synchronous lambda calls try: response = lam.invoke(FunctionName='grab_ww3', InvocationType='Event', Payload=json.dumps(payload)) except Exception as e: print(e) raise e print(response) time.sleep(0.1) if __name__ == "__main__": lambda_handler('','') <file_sep>from matplotlib import cm cmap_config = { 'wind_speed': { 'color_map': cm.get_cmap('viridis'), 'data_range': [0,25], 'interval': 1 }, 'ocean_current_speed': { 'color_map': cm.get_cmap('magma'), 'data_range': [0,2], 'interval': 0.25 }, 'sig_wave_height': { 'color_map': cm.get_cmap('jet'), 'data_range': [0,11], 'interval': 1 }, 'primary_wave_dir': { 'color_map': None, 'data_range': [None, None], 'interval': None }, 'primary_wave_period': { 'color_map': cm.get_cmap('cool'), 'data_range': [0,21], 'interval': 1 }, }<file_sep>export const imageLayers = ['getLeaseAreas', 'getLeaseBlocks', 'getTropicalActivity']; export const tileLayers = ['getModelField', 'getGebcoBathy']; export const dataLayers = ['getModelField','getActiveDrilling']; export const staticLegendEndpoint = 'https://s3.us-east-2.amazonaws.com/oceanmapper-data-storage/dynamic_legend_cache/'; export const colorPaletteMapping = [ {viridis: 'https://s3.us-east-2.amazonaws.com/oceanmapper-data-storage/colorramps/viridis_colorbar.png'}, {magma: 'https://s3.us-east-2.amazonaws.com/oceanmapper-data-storage/colorramps/magma_colorbar.png'}, {jet: 'https://s3.us-east-2.amazonaws.com/oceanmapper-data-storage/colorramps/jet_colorbar.png'}, {rainbow: 'https://s3.us-east-2.amazonaws.com/oceanmapper-data-storage/colorramps/rainbow_colorbar.png'}, {cool: 'https://s3.us-east-2.amazonaws.com/oceanmapper-data-storage/colorramps/cool_colorbar.png'} ]; const dynamicLegendEndpoint = 'https://5qkqvek867.execute-api.us-east-2.amazonaws.com/staging/legend'; export const layers = [ { Category: 'MetOcean', visibleTOC: true, expanded: true, Layers: [{ s3Name: 'HYCOM_DATA', niceName: 'HYCOM', visibleTOC: true, subResources: [ { id: 'hycom_currents', s3Name: 'ocean_current_speed', niceName: 'HYCOM Currents', shortName: 'Current Speed', overlayType: 'ocean', legendUrl: dynamicLegendEndpoint, availableLevels: [], levelName: 'Depth (m)', addDataFunc: 'getModelField', chartType: 'series-vector', directionConvention: 'toward', maxNativeZoom: 3, minNativeZoom: 3, streamFlowLayer: true, maxVelocity: 1.0, velocityScale: 0.1, timeSensitive: true, rasterProps: { opacity: 1.0, absoluteMin: 0, absoluteMax: 4, currentMin: 0, currentMax: 2, interval: 0.125, colormap: 'magma', label: 'Current Speed (m/s)', dataRangeIntervals: [0.125, .25, .5, 1], colorramps: ['viridis', 'magma', 'jet', 'rainbow', 'cool'] }, settingsTools: ['opacity', 'datarange', 'interval', 'colormap'], visibleTOC: true, defaultOn: true } ] }, { s3Name: 'RTOFS_DATA', niceName: 'RTOFS', visibleTOC: false, subResources: [ { id: 'rtofs_currents', s3Name: 'ocean_current_speed', niceName: 'RTOFS Currents', shortName: 'Current Speed', overlayType: 'ocean', legendUrl: dynamicLegendEndpoint, availableLevels: [], levelName: 'Depth (m)', addDataFunc: 'getModelField', chartType: 'series-vector', directionConvention: 'toward', maxNativeZoom: 3, minNativeZoom: 3, streamFlowLayer: true, maxVelocity: 1.0, velocityScale: 0.15, streamFlowColorScale: ['#000004', '#51127c', '#b73779', '#fc8961', '#fcfdbf'], timeSensitive: true, rasterProps: { opacity: 1.0, absoluteMin: 0, absoluteMax: 4, currentMin: 0, currentMax: 2, interval: 0.125, colormap: 'magma', label: 'Current Speed (m/s)', dataRangeIntervals: [0.125, .25, .5, 1], colorramps: ['viridis', 'magma', 'jet', 'rainbow', 'cool'] }, settingsTools: ['opacity', 'datarange', 'interval', 'colormap'], visibleTOC: false, defaultOn: false } ] }, { s3Name: 'GFS_DATA', niceName: 'GFS', visibleTOC: true, subResources: [ { id: 'gfs_winds', s3Name: 'wind_speed', niceName: 'GFS Winds', shortName: 'Wind Speed', overlayType: 'all', legendUrl: dynamicLegendEndpoint, availableLevels: [], levelName: 'Height (m)', addDataFunc: 'getModelField', chartType: 'series-vector', directionConvention: 'from', maxNativeZoom: 3, minNativeZoom: 3, streamFlowLayer: true, maxVelocity: 20.0, velocityScale: 0.01, streamFlowColorScale: ['#440154', '#3b528b', '#21918c', '#5ec962', '#fde725'], timeSensitive: true, rasterProps: { opacity: 1.0, absoluteMin: 0, absoluteMax: 80, currentMin: 0, currentMax: 25, interval: 1, colormap: 'viridis', label: 'Wind Speed (m/s)', dataRangeIntervals: [1, 5, 10], colorramps: ['viridis', 'magma', 'jet', 'rainbow', 'cool'] }, settingsTools: ['opacity', 'datarange', 'interval', 'colormap'], visibleTOC: true, defaultOn: false } ] }, { s3Name: 'WW3_DATA', niceName: 'WAVEWATCH3', visibleTOC: true, subResources: [ { id: 'ww3_sig_wave_height', s3Name: 'sig_wave_height', niceName: 'WW3 Signficant Wave Height', shortName: 'Significant Wave Height', overlayType: 'ocean', legendUrl: dynamicLegendEndpoint, availableLevels: [], addDataFunc: 'getModelField', chartType: 'series', maxNativeZoom: 3, minNativeZoom: 3, timeSensitive: true, rasterProps: { opacity: 1.0, absoluteMin: 0, absoluteMax: 20, currentMin: 0, currentMax: 10, interval: 1, colormap: 'jet', label: 'Significant Wave Height (m)', dataRangeIntervals: [0.5, 1, 2], colorramps: ['viridis', 'magma', 'jet', 'rainbow', 'cool'] }, settingsTools: ['opacity', 'datarange', 'interval', 'colormap'], visibleTOC: true, defaultOn: false }, { id: 'ww3_primary_wave_dir', s3Name: 'primary_wave_dir', niceName: 'WW3 Primary Wave Direction', shortName: 'Primary Wave Direction', overlayType: 'ocean', overlayPriority: 'high', legendUrl: '', availableLevels: [], addDataFunc: 'getModelField', chartType: 'vector', directionConvention: 'from', maxNativeZoom: 4, minNativeZoom: 3, timeSensitive: true, rasterProps: { opacity: 1.0 }, settingsTools: ['opacity'], visibleTOC: true, defaultOn: false }, { id: 'ww3_primary_wave_period', s3Name: 'primary_wave_period', niceName: 'WW3 Primary Wave Period', shortName: 'Primary Wave Period', overlayType: 'ocean', legendUrl: dynamicLegendEndpoint, availableLevels: [], addDataFunc: 'getModelField', chartType: 'series', maxNativeZoom: 3, minNativeZoom: 3, timeSensitive: true, rasterProps: { opacity: 1.0, absoluteMin: 0, absoluteMax: 25, currentMin: 0, currentMax: 20, interval: 1, colormap: 'cool', label: 'Primary Wave Period (s)', dataRangeIntervals: [1], colorramps: ['viridis', 'magma', 'jet', 'rainbow', 'cool'] }, settingsTools: ['opacity', 'datarange', 'interval', 'colormap'], visibleTOC: true, defaultOn: false } ] }] }, { Category: 'Oil & Gas', visibleTOC: true, expanded: false, Layers: [ { id: 'active_drilling', niceName: 'Current Deepwater Activity', overlayPriority: 'highest', addDataFunc: 'getActiveDrilling', endPoint: '/download/current_deepwater_activity.json', timeSensitive: false, visibleTOC: true, defaultOn: false } ] }, { Category: 'Tropical Cyclones', visibleTOC: true, expanded: true, Layers: [ { id: 'tropcial_storms_track_forecast', niceName: 'Track Forecast', overlayPriority: 'medium', addDataFunc: 'getTropicalActivity', endPoint: 'https://nowcoast.noaa.gov/arcgis/rest/services/nowcoast/wwa_meteocean_tropicalcyclones_trackintensityfcsts_time/MapServer/export?dpi=96&transparent=true&format=png32&layers=show:3,4,5,6,2,8,9&bbox=#bbox&bboxSR=3857&imageSR=3857&size=#width,#height&f=image', endPointInfo: 'https://nowcoast.noaa.gov/layerinfo?request=prodtime&service=wwa_meteocean_tropicalcyclones_trackintensityfcsts_time&format=json', legendUrl: 'https://nowcoast.noaa.gov/layerinfo?request=legend&format=html&service=wwa_meteocean_tropicalcyclones_trackintensityfcsts_time&layers=3,4,5,6,2,8,9', nowCoastDataset: true, movementSensitive: true, timeSensitive: false, rasterProps: { opacity: 1.0 }, visibleTOC: true, defaultOn: true } ] }, { Category: 'Overlays', visibleTOC: true, expanded: false, Layers: [ { id: 'boem_wind_leases', niceName: 'BOEM Renewable Energy Lease Areas', overlayPriority: 'high', endPoint: 'https://df3aeoynrb.execute-api.us-east-2.amazonaws.com/staging/shape2tile/{z}/{x}/{y}?shapefile_path=https://oceanmapper-data-storage.s3.us-east-2.amazonaws.com/SHAPEFILES/BOEM_Renewable_Energy_Areas_Shapefiles_2_13_2019/BOEM_Renewable_Energy_Areas_Shapefiles_2_13_2019.zip&edgecolor=red&linewidth=0.2', addDataFunc: 'boemWindLease', timeSensitive: false, rasterProps: { opacity: 1.0 }, visibleTOC: true, defaultOn: false }, { id: 'ocs_leasing_extents', niceName: 'BOEM OCS Protraction Diagrams & Leasing Maps', overlayPriority: 'high', endPoint: 'https://gis.boem.gov/arcgis/rest/services/BOEM_BSEE/MMC_Layers/MapServer/export?dpi=96&transparent=true&format=png32&layers=show:10&bbox=#bbox&bboxSR=102100&imageSR=102100&size=#width,#height&f=image', addDataFunc: 'getLeaseAreas', timeSensitive: false, movementSensitive: true, rasterProps: { opacity: 1.0 }, visibleTOC: true, defaultOn: false }, { id: 'ocs_lease_blocks', niceName: 'BOEM OCS Lease Blocks', overlayPriority: 'medium', endPoint: 'https://gis.boem.gov/arcgis/rest/services/BOEM_BSEE/MMC_Layers/MapServer/export?dpi=96&transparent=true&format=png32&layers=show:11&bbox=#bbox&bboxSR=102100&imageSR=102100&size=#width,#height&f=image', addDataFunc: 'getLeaseBlocks', timeSensitive: false, movementSensitive: true, rasterProps: { opacity: 1.0 }, visibleTOC: true, defaultOn: false }, { id: 'gebco_bathy', niceName: '<NAME>', overlayPriority: 'medium', endPoint: 'https://tiles.arcgis.com/tiles/C8EMgrsFcRFL6LrL/arcgis/rest/services/GEBCO_contours/MapServer/tile/{z}/{y}/{x}', addDataFunc: 'getGebcoBathy', timeSensitive: false, rasterProps: { opacity: 1.0 }, visibleTOC: true, defaultOn: false }, { id: 'transparent_basemap', niceName: 'Transparent Basemap', overlayPriority: 'high', endPoint: 'https://s3.us-east-2.amazonaws.com/oceanmapper-data-storage/basemap_tiles/{z}/{x}/{y}.png', addDataFunc: 'getTransparentBasemap', maxNativeZoom: 8, // change to 8 when ready minNativeZoom: 3, timeSensitive: false, rasterProps: { opacity: 1.0 }, visibleTOC: false, defaultOn: false }, ] }, ]; // export default TOC; <file_sep>import cluster from 'cluster'; import os from 'os'; import bodyParser from 'body-parser'; import express from 'express'; import path from 'path'; import morgan from 'morgan'; import errorHandler from 'errorhandler'; import downloadFromS3Router from './scripts/downloadFromS3'; import apiGatewayRouter from './scripts/apiGatewayRouter'; // Code to run if we're in the master process if (cluster.isMaster) { // Count the machine's CPUs var cpuCount = os.cpus().length; console.log(`Number of available CPUs: ${cpuCount}`); // Create a worker for each CPU for (var i = 0; i < cpuCount; i += 1) { cluster.fork(); } // restart an exited worker cluster.on('exit', (worker, code, signal) => { console.log('worker %d died (%s). restarting...', worker.process.pid, signal || code); cluster.fork(); }); } else { // worker process const app = express(); app.use(bodyParser.json()); // app.use(bodyParser.urlencoded({extended: false})); const router = express.Router(); const staticFiles = express.static(path.join(__dirname, '../../client/build')); app.use(staticFiles); const S3_BUCKET = process.env.S3_BUCKET_NAME; // logging middleware app.use(morgan('dev')); // add other routes below app.use('/download', downloadFromS3Router); app.use('/data', apiGatewayRouter); // for testing app.get('/test', (req, res) => { const cities = [ {name: 'New York City', population: 8175133}, {name: 'Los Angeles', population: 3792621}, {name: 'Chicago', population: 2695598} ] res.json(cities) }); // error handler here: (prior middleware should pass next(errorObj)) app.use(errorHandler()); app.use('/*', staticFiles) app.set('port', (process.env.PORT || 3001)) app.listen(app.get('port'), () => { console.log(`Worker ${cluster.worker.id} listening on ${app.get('port')}`) }) } <file_sep>import collections import datetime import netCDF4 def assemble_model_timesteps(available_data, model_res): """ assemble_model_timesteps(available_data, model_res) This function assembles the available model times and associated urls ----------------------------------------------------------------------- Input: object with this structure: available_data ={'nowcast': {'latest_date': 'yyyymmdd', 'url': xxxx}, 'forecast': {'latest_date': 'yyyymmdd', 'url': xxxx} ----------------------------------------------------------------------- Output: object with this structure (dt=python datetime): info = {'nowcast': {'url': xxx, 'field_datetimes': [dt,dt,dt]}, 'forecast': {url: xxx, 'field_datetimes': [dt, dt, dt]}} ----------------------------------------------------------------------- Other info: RTOFS: nowcast --> only need the last nowcast field (all prior fields are model spin up) RTOFS: forecast --> the first field is the same date as the nowcast and is all NaNs ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/21/2022 """ # the first 15 fields are model initialization when working with 3hrly data start_info = {'daily': {'nowcast': 1, 'forecast': 1}, '3hrly': {'nowcast': 16, 'forecast': 1}} info = {} info['products'] = collections.OrderedDict() info['general'] = {} info['general']['levels'] = [] for product_type in available_data.keys(): time_array = [] info['products'][product_type] = {} info['products'][product_type]['url'] = available_data[product_type]['url'] info['products'][product_type]['field_datetimes'] = [] # provide empty array info['products'][product_type]['forecast_indx'] = [] # provide empty array file = netCDF4.Dataset(available_data[product_type]['url']) product_times = file.variables['time'][start_info[model_res][product_type]:] levels = file.variables['lev'][:] for forecast_indx, forecast_time in enumerate(product_times): basetime_int = int(forecast_time) extra_days = forecast_time - basetime_int # need to subtract 1 since RTOFS is days since 0001-01-01 (yyyy-mm-dd) full_forecast_time = (datetime.datetime.fromordinal(basetime_int) + datetime.timedelta(days=extra_days) - datetime.timedelta(days=1)) time_array.append(full_forecast_time) info['products'][product_type]['field_datetimes'].append(full_forecast_time) info['products'][product_type]['forecast_indx'].append( start_info[model_res][product_type] + forecast_indx) file.close() # add levels to output data structure info['general']['levels'] = [int(lev) for lev in levels.tolist()] return info <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { withStyles } from '@material-ui/core/styles'; import Slider from '@material-ui/lab/Slider'; import Typography from '@material-ui/core/Typography'; import moment from 'moment'; import externalStyles from '../scripts/styleVariables'; import _LinearScale from 'react-compound-slider/Slider/LinearScale'; import { Ticks } from "react-compound-slider"; import Tick from './Tick'; import { formatDateTime } from '../scripts/formatDateTime'; import IconButton from '@material-ui/core/IconButton'; import AddCircleOutlineIcon from '@material-ui/icons/AddCircleOutline'; import RemoveCircleOutlineIcon from '@material-ui/icons/RemoveCircleOutline'; const scale = new _LinearScale(); const drawerWidth = externalStyles.drawerWidth; const drawerWidthNarrow = externalStyles.drawerWidthNarrow; // for small viewports (< 600px) const timeSliderMargin = externalStyles.timeSliderMargin; const timeSliderOpacity = externalStyles.timeSliderOpacity; // TODO: move slider percent width to external style sheet and use direct media // queries to get sizing correct const styles = theme => ({ sliderDiv: { position: 'absolute', bottom: 0, left: 0, width: '400px', margin: timeSliderMargin, opacity: timeSliderOpacity, zIndex: 500, overflow: 'hidden', borderRadius: '2px', backgroundColor: theme.palette.primary.main, transition: theme.transitions.create(['left', 'width'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), [`${theme.breakpoints.down('sm')}`]: { width: `calc(100% - ${timeSliderMargin*2}px)`, }, }, sliderDivShift: { left: drawerWidth, transition: theme.transitions.create(['left'], { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), [`${theme.breakpoints.down('sm')}`]: { left: drawerWidthNarrow, width: `calc(100% - ${drawerWidthNarrow}px - ${timeSliderMargin*2}px)`, }, }, slider: { padding: '22px 0', backgroundColor: theme.palette.primary.main }, sliderTrackBefore: { backgroundColor: theme.palette.secondary.main }, sliderTrackAfter: { backgroundColor: 'black' }, sliderThumb: { backgroundColor: theme.palette.secondary.main, }, dateTimeExtreme: { display: 'inline-block', fontSize: 13 }, sliderTicks: { zIndex: 500, height: 30, marginTop: '-15px', position: 'relative' }, sliderHide: { [`${theme.breakpoints.down('xs')}`]: { display: 'none', } }, resetButton: { position: 'absolute', color: 'gray', right: 0, padding: '3px 12px', '&:hover': { cursor: 'pointer', fontWeight: 'bold' } }, timeAdjustButton: { alignSelf: 'flex-start' } }); function TimeSlider(props) { const handleChange = (event, value) => { props.handleTimeChange(value); }; const handleReset = () => { // present UTC time props.handleTimeChange(moment.utc().startOf('hour').valueOf()); } const incrementTime = () => { // add 1 hour props.handleTimeChange(moment(props.mapTime).add(1,'h').startOf('hour').valueOf()); } const decrementTime = () => { // add 1 hour props.handleTimeChange(moment(props.mapTime).subtract(1,'h').startOf('hour').valueOf()); } const constructTickValueArray = (startTime, endTime, timeInterval) => { let currentTime = startTime, tickValueArray = [startTime]; while (currentTime <= (endTime - timeInterval)) { currentTime += timeInterval; tickValueArray.push(currentTime); } tickValueArray.push(endTime); return tickValueArray; } const { classes, open, startTime, endTime, mapTime} = props; scale.domain = [startTime, endTime] let tickVals = constructTickValueArray(startTime, endTime, 3600000*24*3); return ( <div className={classNames(classes.sliderDiv, { [classes.sliderDivShift]: open, [classes.sliderHide]: open })}> <span onClick={handleReset} className={classes.resetButton}> reset </span> <Typography style={{textAlign: 'center'}} id="label"> {formatDateTime(mapTime,'YYYY-MM-DD HH:mm',' UTC')} </Typography> <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start'}}> <IconButton aria-label="back" title='-1 hr'> <RemoveCircleOutlineIcon onClick={decrementTime}/> </IconButton> <div style={{flexGrow: 1}}> <Slider classes={{ container: classes.slider, thumb: classes.sliderThumb, trackBefore: classes.sliderTrackBefore, trackAfter: classes.sliderTrackAfter }} value={mapTime} min={startTime} max={endTime} step={3600000} onChange={handleChange} /> <Ticks scale={scale} count={4} values={tickVals}> {({ ticks }) => ( <div className={classes.sliderTicks}> {ticks.map((tick, index) => ( <Tick key={index} tick={tick} count={ticks.length} /> ))} </div> )} </Ticks> </div> <IconButton aria-label="back" title='+1 hr'> <AddCircleOutlineIcon onClick={incrementTime}/> </IconButton> </div> </div> ); } // https://codesandbox.io/s/plzyr7lmj (how to do ticks) // import { ticks } from 'd3-array' // fix Ticks.js so we don't need to use 'scale' TimeSlider.propTypes = { classes: PropTypes.object.isRequired, theme: PropTypes.object.isRequired, }; export default withStyles(styles, { withTheme: true })(TimeSlider); <file_sep>import React from "react"; import { withStyles } from '@material-ui/core/styles'; const styles = theme => ({ handleDiv: { position: 'absolute', marginLeft: -6, marginTop: 20, zIndex: 2, width: 12, height: 12, border: 0, textAlign: 'center', cursor: 'pointer', borderRadius: '50%', backgroundColor: theme.palette.secondary.main, color: '#333', // [`${theme.breakpoints.down('xs')}`]: { // marginTop: 14, // marginLeft: -12, // width: 24, // height: 24, // }, }, handleLabel: { fontFamily: 'Roboto', fontSize: 13, marginTop: -17 } }) const Handle = ({ handle: { id, value, percent }, getHandleProps, classes}) => { return ( <div className={classes.handleDiv} style={{ left: `${percent}%` }} {...getHandleProps(id)} > <div className={classes.handleLabel}> {value} </div> </div> ) } export default withStyles(styles, { withTheme: true })(Handle);<file_sep>import sys sys.path.append("..") import boto3 import datetime import json import re from harvest_utils.remote_data_info import get_max_date from harvest_utils.data_endpoints import hycom_catalog_root from HYCOM.HYCOM_forecast_info import get_hycom_forecast_info s3 = boto3.resource('s3') AWS_BUCKET_NAME = 'oceanmapper-data-storage' def is_data_fresh(): ''' Checks if the latest available forecast field in s3 bucket matches the extent of the latest HYCOM forecast run. Returns True if the forecast extents match (i.e. the data is fresh) ''' s3_max_date = get_max_date('HYCOM_DATA') # get the max of s3_dates and compare to max_remote_date hycom_catalog_url = '{}catalog.html'.format(hycom_catalog_root) forecast_info = get_hycom_forecast_info(hycom_catalog_url) max_datasource_date = max(forecast_info['forecast']['field_datetimes']) if s3_max_date != max_datasource_date: return False return True if __name__ == "__main__": is_data_fresh() <file_sep>import datetime import mercantile from utils.datasets import datasets def build_file_path(model_top_level_folder, sub_resource, model_prefix_str, field_datetime, file_type, scalar_tiles=True, vector_tiles=False, level=None): """ build_file_path(model_top_level_folder, sub_resource, model_prefix_str, field_datetime, file_type, scalar_tiles=True, vector_tiles=False, level=None) This function builds a s3 filepath ----------------------------------------------------------------------- Inputs: model_top_level_folder (str) - the top level folder for a particular data source (i.e. GFS_WINDS) sub_resource (str) - the sub resource name (i.e. primary_wave_direction) model_prefix_str (str) - the model prefix used when composing a filename (i.e. gfs_winds) field_datetime (datetime.datetime) - a datetime object for a particular model time file_type (str) - the file type (i.e. json, pickle) scalar_tiles (bool) - whether or not to include a scalar tilepath vector_tiles (bool) - whether or not to include a vector tilepath level (str): the model level formatted str (i.e. 10m) ----------------------------------------------------------------------- Output: (str) - the output s3 filepath and tilepaths (scalar and vector - if available) ----------------------------------------------------------------------- Author: <NAME> Date Modified: 09/23/2018 """ formatted_folder_date = datetime.datetime.strftime(field_datetime,'%Y%m%d_%H') output_tilepaths = {'scalar': '', 'vector': ''} if level: output_filepath = (model_top_level_folder + '/' + formatted_folder_date + '/' + sub_resource + '/' + level + '/' + file_type + '/' + model_prefix_str + '_' + formatted_folder_date + '.' + file_type) scalar_tilepath = (model_top_level_folder + '/' + formatted_folder_date + '/' + sub_resource + '/' + level + '/tiles/scalar/{z}/{x}/{y}.png') if scalar_tiles else None vector_tilepath = (model_top_level_folder + '/' + formatted_folder_date + '/' + sub_resource + '/' + level + '/tiles/vector/{z}/{x}/{y}.png') if vector_tiles else None else: output_filepath = (model_top_level_folder + '/' + formatted_folder_date + '/' + sub_resource + '/' + file_type + '/' + model_prefix_str + '_' + formatted_folder_date + '.' + file_type) scalar_tilepath = (model_top_level_folder + '/' + formatted_folder_date + '/' + sub_resource + '/tiles/scalar/{z}/{x}/{y}.png') if scalar_tiles else None vector_tilepath = (model_top_level_folder + '/' + formatted_folder_date + '/' + sub_resource + '/tiles/vector/{z}/{x}/{y}.png') if vector_tiles else None output_tilepaths['scalar'] = scalar_tilepath output_tilepaths['vector'] = vector_tilepath return output_filepath, output_tilepaths def build_tiledata_path(model_top_level_folder, sub_resource, level, field_datetime, coords, override_zoom = None): """ build_tiledata_path(model_top_level_folder, sub_resource, field_datetime, coords, override_zoom = None) This function builds a s3 filepath to a subsetted 'tile' dataset ----------------------------------------------------------------------- Inputs: model_top_level_folder (str) - the top level folder for a particular data source (i.e. GFS_WINDS) sub_resource (str) - the sub resource name (i.e. primary_wave_direction) level (str): the model level formatted str (i.e. 10m) field_datetime (datetime.datetime) - a datetime object for a particular model time coords (array) - [longitude, latitude] coordinates override_zoom (int) - used to specifying building a tile data path with a specific zoom ----------------------------------------------------------------------- Output: (str) - the output s3 filepath to a specific data 'tile' ----------------------------------------------------------------------- Author: <NAME> Date Modified: 02/21/2019 """ formatted_folder_date = datetime.datetime.strftime(field_datetime,'%Y%m%d_%H') # override zoom is used when specifying a specific zoom to use as is the case when building tile images on the fly if override_zoom: available_zoom = override_zoom else: available_zoom = datasets[model_top_level_folder]['sub_resource'][sub_resource]['data_tiles_zoom_level'][-1] parent_tile = mercantile.tile(coords[0], coords[1], available_zoom, truncate=False) i,j,zoom=[*parent_tile] tile_folder_str = '{0}/{1}/{2}'.format(zoom, i, j) # build tiledata path given the x,y,z coords of the parent tile if level: output_filepath = (model_top_level_folder + '/' + formatted_folder_date + '/' + sub_resource + '/' + level + '/tiles/data/' + tile_folder_str + '.pickle') else: output_filepath = (model_top_level_folder + '/' + formatted_folder_date + '/' + sub_resource + '/tiles/data/' + tile_folder_str + '.pickle') return output_filepath def build_date_path(info_filename, model_top_level_folder, field_datetime): """ build_date_path(info_filename, model_top_level_folder, field_datetime) This function builds a s3 filepath to the 'info.json' file ----------------------------------------------------------------------- Inputs: info_filename (str) - the name of the info file (i.e. info.json) model_top_level_folder (str) - the top level folder for a particular data source (i.e. GFS_WINDS) field_datetime (datetime.datetime) - a datetime object for a particular model time ----------------------------------------------------------------------- Output: (str) - the output s3 filepath ----------------------------------------------------------------------- Author: <NAME> Date Modified: 03/24/2019 """ formatted_folder_date = datetime.datetime.strftime(field_datetime,'%Y%m%d_%H') output_folderpath = (model_top_level_folder + '/' + formatted_folder_date + '/' + info_filename) return output_folderpath<file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import AppRouter from './AppRouter'; import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles'; import purple from '@material-ui/core/colors/purple'; import './index.css'; const theme = createMuiTheme({ palette: { primary: { main: '#cccccc', // '#e0e0e0' }, secondary: purple }, status: { danger: 'orange', } }); function MuiAppContainer() { return ( <MuiThemeProvider theme={theme}> <AppRouter /> </MuiThemeProvider> ); } ReactDOM.render(<MuiAppContainer />, document.getElementById('root')); <file_sep>import numpy as np import pickle from scipy import interpolate import datetime import time import boto3 from functools import wraps s3 = boto3.client('s3') bucket = 'oceanmapper-data-storage' def retry(ExceptionToCheck, tries=5, delay=.1): """ retry(ExceptionToCheck, tries=4, delay=.1) Retry calling the decorated function a certain number of times with some sleep interval between. ----------------------------------------------------------------------- http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry ----------------------------------------------------------------------- Inputs: ExceptionToCheck (Exception or tuple): the exception to check. may be a tuple of exceptions to check tries (int): number of times to try (not retry) before giving up delay (float): delay between retries in seconds """ def deco_retry(f): @wraps(f) def f_retry(*args, **kwargs): mtries, mdelay = tries, delay while mtries > 1: try: return f(*args, **kwargs) except ExceptionToCheck as e: time.sleep(mdelay) mtries -= 1 else: if 'conn' in kwargs: conn.send(None) conn.close() return return f_retry # true decorator return deco_retry @retry(Exception, tries=5, delay=.1) def get_model_value(coords, data_key, sub_resource, dataset_vars, conn=None): """ get_model_value(coords, data_key, sub_resource, dataset_vars, conn=None) ----------------------------------------------------------------------- Inputs: coords: (array) - geographic coordinates data_key: (str) - the location of a file in s3 bucket sub_resource: (str) - the sub resource (i.e. HYCOM_DATA --> ocean_current_speed) dataset_vars: (array)- dataset variables(i.e. u_vel, v_vel) conn: (obj) - child connection object for multiprocessing ----------------------------------------------------------------------- Notes: https://www.eol.ucar.edu/content/wind-direction-quick-reference ----------------------------------------------------------------------- Output: ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/23/2022 """ try: pickle_data = s3.get_object(Bucket=bucket, Key=data_key) body_string = pickle_data['Body'].read() data = pickle.loads(body_string) except Exception as e: raise Exception("Failed to load data from s3") if hasattr(data['lat'],'mask'): lat = data['lat'].data else: lat = data['lat'] if hasattr(data['lon'],'mask'): lon = data['lon'].data else: lon = data['lon'] interp_vals = [] for var in dataset_vars: if hasattr(data[var],'mask'): # transform masked values to 0 data_raw = data[var].data # determine whether or not to apply the mask. If the mask is uniform (i.e. every item is false (unmasked) then the mask isn't helpful) all_masked = np.all(~data[var].mask) if ~all_masked: data_mask_applied = np.where(~data[var].mask, data_raw, 0) else: data_mask_applied = np.where(data_raw < data[var].fill_value, data_raw, 0) interp_func = interpolate.interp2d(lon, lat, data_mask_applied, kind='cubic') interp_vals.append(interp_func(coords[0], coords[1])[0]) # get model time origin time_origin = datetime.datetime.strftime(data['time_origin'],'%Y-%m-%d %H:%M:%S') if sub_resource == 'ocean_current_speed' or sub_resource == 'wind_speed': u_vel = interp_vals[0] v_vel = interp_vals[1] var_abs = np.sqrt(u_vel**2 + v_vel**2) # if sub_resource is wind then convert this wind vector to the meteorological convention (from) if sub_resource == 'wind_speed': compass_deg = (270 - (np.arctan2(v_vel, u_vel) * (180/np.pi))) % 360 elif sub_resource == 'ocean_current_speed': compass_deg = (90 - (np.arctan2(v_vel, u_vel) * (180/np.pi))) % 360 output = {'val': var_abs, 'direction': compass_deg, 'time_origin': time_origin} else: output = {'val': interp_vals[0], 'time_origin': time_origin} if sub_resource == 'primary_wave_dir' and (output['val'] > 360 or output['val'] < 0): output['val'] = output['val'] % 360 # if this is being used as part of a multiprocessing call need to send data via conn if conn: conn.send(output) conn.close() return output if __name__ == '__main__': # coords=[-68.9337, 41.7016] # dataset_vars = ['u_vel','v_vel'] # sub_resource = 'ocean_current_speed' # data_key='HYCOM_DATA/20221101_18/ocean_current_speed/0m/pickle/hycom_currents_20221101_18.pickle' # coords=[-68.9337, 41.7016] # dataset_vars = ['sig_wave_height'] # sub_resource = 'sig_wave_height' # data_key='WW3_DATA/20221027_18/sig_wave_height/tiles/data/3/2/2.pickle' coords = [-68.9337, 41.7016] dataset_vars = ['primary_wave_dir'] sub_resource = 'primary_wave_dir' data_key = 'WW3_DATA/20221027_18/primary_wave_dir/tiles/data/3/2/2.pickle' get_model_value(coords, data_key, sub_resource, dataset_vars, conn='mock_con') <file_sep>import boto3 import datetime import json s3 = boto3.client('s3') def get_model_init(key, bucket): raw_data = s3.get_object(Bucket=bucket, Key=key) try: json_data = json.loads(raw_data['Body'].read().decode('utf-8')) init_time = datetime.datetime.strptime(json_data['time_origin'],'%Y-%m-%d %H:%M:%S') except Exception as e: return None return init_time<file_sep>// Left Drawer exports.drawerZIndex = 1201; exports.drawerWidth = 365; exports.drawerWidthNarrow = 280; // for small viewports (< 600px) // Timeslider and coordinate viewer exports.timeSliderMargin = 5; exports.timeSliderOpacity = 0.8; // Settings Panel exports.settingsPanelWidth = 400; <file_sep>import React from 'react'; import { withStyles } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; import TOCExpansionPanel from './TOCExpansionPanel'; import FormGroup from '@material-ui/core/FormGroup'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Switch from '@material-ui/core/Switch'; import LevelSelector from './LevelSelector'; import DynamicLegend from './DynamicLegend'; import LegendContainer from './LegendContainer'; import LoadingSpinner from './LoadingSpinner'; import SettingsCog from './SettingsCog'; import { library } from '@fortawesome/fontawesome-svg-core'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faExclamationTriangle } from '@fortawesome/free-solid-svg-icons'; library.add(faExclamationTriangle); // https://stackoverflow.com/questions/35905988/react-js-how-to-append-a-component-on-click const styles = theme => ({ img: { width: '100%', }, timeInfo: { lineHeight: '1.6', fontSize: '.65rem' } }); function TableOfContents(props) { const {toc } = props; const constructLabel = (labelText, layerID, includeSettings) => ( <React.Fragment> {(props['mapLayers'][layerID] ? props['mapLayers'][layerID]['isLoading'] : false) && <LoadingSpinner />} {labelText} {(props['mapLayers'][layerID]['loadError'] && !props['mapLayers'][layerID]['isLoading'] && props['mapLayers'][layerID]['isOn']) && <FontAwesomeIcon icon="exclamation-triangle" title={'Failed to load layer!'} style={{color: 'red', marginLeft: 5, fontSize: '1.2em'}} /> } {(includeSettings && !props['mapLayers'][layerID]['isLoading'] && props['mapLayers'][layerID]['isOn']) && <SettingsCog layerID = {layerID} handleSettingsPanelVisibility = {props.handleSettingsPanelVisibility} /> } </React.Fragment> ) const buildContents = categoryObj => { return ( categoryObj['Layers'].map((layer, indx) => { if ('subResources' in layer) { return ( layer['subResources'].map((subresource, indx) => { if (subresource['visibleTOC']) { return ( <React.Fragment key={indx}> <FormGroup row={false}> <FormControlLabel control={ <Switch checked={props['mapLayers'][subresource['id']]['isOn']} color='secondary' onChange={props.handleLayerToggle.bind(this, subresource['id'])} value={subresource['id']} /> } label={constructLabel(subresource['niceName'], subresource['id'], true)} /> </FormGroup> {(props['mapLayers'][subresource['id']]['isOn'] && !props['mapLayers'][subresource['id']]['isLoading'] && !props['mapLayers'][subresource['id']]['loadError']) && <React.Fragment> <Typography variant="overline" classes={{overline: props.classes['timeInfo']}}> Date Valid: {props['mapLayers'][subresource['id']]['validTime']} </Typography> <Typography variant="overline" classes={{overline: props.classes['timeInfo']}} gutterBottom> Model Initialized: {props['mapLayers'][subresource['id']]['initTime']} </Typography> {subresource['legendUrl'] && <DynamicLegend layer={props['mapLayers'][subresource['id']]} legendUrl={subresource['legendUrl']} />} {!isNaN(props['mapLayers'][subresource['id']]['level']) && <LevelSelector availableLevels={subresource['availableLevels']} levelName={subresource['levelName']} presentLevel={props['mapLayers'][subresource['id']]['level']} handleLevelChange={props.handleLevelChange} id={subresource['id']} />} </React.Fragment> } </React.Fragment> ) } else { return null } }) ) } else { if (layer['visibleTOC']) { return ( <React.Fragment key={indx}> <FormGroup key={indx} row={false}> <FormControlLabel control={ <Switch checked={props['mapLayers'][layer['id']]['isOn']} color='secondary' onChange={props.handleLayerToggle.bind(this, layer['id'])} value={layer['id']} /> } label={constructLabel(layer['niceName'], layer['id'], false)} /> </FormGroup> {(props['mapLayers'][layer['id']]['isOn'] && props['mapLayers'][layer['id']]['nowCoastDataset'] && !props['mapLayers'][layer['id']]['isLoading'] && !props['mapLayers'][layer['id']]['loadError']) && <React.Fragment> <Typography variant="overline" gutterBottom> {props['mapLayers'][layer['id']]['prodTime'] ? `${props['mapLayers'][layer['id']]['prodTimeLabel']}: ${props['mapLayers'][layer['id']]['prodTime'] || ''}` : ''} </Typography> <LegendContainer> <div dangerouslySetInnerHTML={{__html: props['mapLayers'][layer['id']]['legendContent']}} /> </LegendContainer> </React.Fragment> } </React.Fragment> ) } else { return null } } }) ) } const categories = toc.map((category, index) => { if (category['Category'] === 'MetOcean' && !props['initializedLayers']) { return null } // check if visible TOC if (category['visibleTOC']) { return ( <TOCExpansionPanel key = {index} categoryName = {category['Category']} defaultExpanded = {category['expanded']} > {buildContents(toc[index])} </TOCExpansionPanel> )} else { return null } } ) return ( <React.Fragment> {categories} </React.Fragment> ) } export default withStyles(styles, { withTheme: true })(TableOfContents); <file_sep>import boto3 import pickle import datetime import numpy as np import mercantile from utils.s3_filepath_utils import build_tiledata_path from utils.datasets import datasets from api_utils.fetch_data_availability import grab_data_availability from api_utils.nearest_model_time import get_available_model_times from build_tile_image import build_tile_image from process_tiles import blank_tile s3 = boto3.client('s3') bucket = 'oceanmapper-data-storage' def lambda_handler(event, context): """ lambda_handler(event, context): This function is used in conjunction with aws api gateway (lambda proxy integration) to generate an tile image on the fly ----------------------------------------------------------------------- Inputs: event: Event data (pathParameters and queryStringParameters) are parsed from call to aws api endpoint context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Notes: https://stackoverflow.com/questions/35804042/aws-api-gateway-and-lambda-to-return-image ----------------------------------------------------------------------- Output: response object ----------------------------------------------------------------------- Author: <NAME> Date Modified: 02/23/2018 """ response_obj = { "isBase64Encoded": True, "statusCode": 200, "headers": {'Content-Type': 'image/png', 'Access-Control-Allow-Origin': '*'}, "body": None # base64.b64encode(content_bytes).decode("utf-8") #TODO drop image bytes in here } # load data availability file from s3 availability_struct = grab_data_availability() if not availability_struct: # build a blank image and inject data into response print('data availability file not available') response_obj['body'] = blank_tile() return response_obj # model time model_time = event['queryStringParameters']['time'] model_time_datetime = datetime.datetime.strptime(model_time,'%Y-%m-%dT%H:%MZ') # dataset (model) dataset = event['queryStringParameters']['dataset'] # sub resource sub_resource = event['queryStringParameters']['sub_resource'] sub_resource_folder = datasets[dataset]['sub_resource'][sub_resource] # model level level = event['queryStringParameters']['level'] level_formatted = str(level) + 'm' if len(str(level)) else '' # wave data have no level # dataset type dataset_type = 'pickle' available_time = get_available_model_times(dataset,sub_resource, model_time_datetime, level_formatted, dataset_type, availability_struct) target_zoom = datasets[dataset]['sub_resource'][sub_resource]['data_tiles_zoom_level'][-1] zoom, i, j = tuple([int(val) for val in event['pathParameters']['proxy'].split('/')]) # need to find the smallest available data from s3 to load and construct a tile # dataset.py provides info on data_tiles_zoom_levels incoming_tile = mercantile.Tile(i, j, zoom) west, south, east, north = [*mercantile.bounds(incoming_tile)] lon_average = np.average(np.array([west, east])) lat_average = np.average(np.array([south, north])) if zoom < target_zoom: target_zoom = zoom if available_time: available_time_str = datetime.datetime.strftime(available_time,'%Y-%m-%dT%H:%MZ') # this is the subsetted .pickle data data_key = build_tiledata_path(dataset, sub_resource, level_formatted, available_time, [lon_average, lat_average], target_zoom) # TODO: future task: check s3 cache first before building image # is it faster to load an image from s3 and then send to client opposed to building here? try: response_obj['body'] = build_tile_image(incoming_tile, data_key, sub_resource, event['queryStringParameters']) except: print('failed on tile image build') response_obj['body'] = blank_tile() else: print('no available time') response_obj['body'] = blank_tile() return response_obj if __name__ == '__main__': event = { "queryStringParameters": { "dataset": "WW3_DATA", "sub_resource": "primary_wave_dir", "time": "2019-03-18T23:00Z", "level": "", "interval": "1", "data_range": "0,10" }, "pathParameters": { "proxy": "4/4/6"# "6/16/27" } } lambda_handler(event,'') # https://a7vap1k0cl.execute-api.us-east-2.amazonaws.com/staging/dynamic-tile/5/8/13?dataset=RTOFS_DATA&sub_resource=ocean_current_speed&level=0&time=2019-02-21T23:00Z # https://a7vap1k0cl.execute-api.us-east-2.amazonaws.com/staging/dynamic-tile/2/1/2?dataset=GFS_DATA&sub_resource=wind_speed&level=10&time=2019-02-26T23:00Z&n_levels=100&color_map=magma&data_range=0,100 <file_sep>import boto3 import json import pdb # s3 = boto3.resource('s3') s3 = boto3.client('s3') bucket = 'oceanmapper-data-storage' key = 'example.json' try: raw_data = s3.get_object(Bucket=bucket, Key=key) data = json.loads(raw_data['Body'].read().decode('utf-8')) #pdb.set_trace() print(data) except Exception as e: print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))<file_sep>import express from 'express'; import s3Obj from './awsS3Obj'; const downloadFromS3Router = express.Router(); downloadFromS3Router.get('/:filename', (req, res) => { const s3 = s3Obj; const s3Params = { Bucket: process.env.S3_BUCKET_NAME, Key: req.params.filename }; s3.getObject(s3Params, function (error, data) { if (error != null) { res.json({"error": error}); } else { // Convert Body from a Buffer to a String res.write(data.Body.toString('utf-8')); res.end(); } } ); }); export default downloadFromS3Router; <file_sep>#!/bin/sh set -eux pip install --no-cache-dir -r /requirements.txt <file_sep>import boto3 import numpy as np # import matplotlib # matplotlib.use('agg') from matplotlib import pyplot as plt, cm, ticker import io import base64 s3 = boto3.client('s3') def build_legend_image(params): """ build_legend_image(params) Create a legend image and returns it as a bas64encoded string ----------------------------------------------------------------------- Inputs: params (obj): an object containing params detailing the specific information necessary to build the colorbar ----------------------------------------------------------------------- Ouput: base64 encoded image converted to a utf-8 string ----------------------------------------------------------------------- Author: <NAME> Date Modified: 03/14/2019 """ bucket_name = 'oceanmapper-data-storage' color_map = params['color_map'] data_range = [float(val) for val in params['data_range'].split(',')] interval = float(params['interval']) label = params['label'] range_val = np.ptp(data_range, axis=0) nlvls = range_val/interval levelsArr = np.arange(np.min(data_range), np.max(data_range) + interval, interval) formatted_label = params['label'].replace(' ','_').replace('/','_') # create a filename legend_filename = 'dynamic_legend_cache/{}_{:{prec}}_{:{prec}}_{:{prec}}_{}_legend.png'.format( color_map, data_range[0], data_range[1], interval, formatted_label, prec='.3f') # create some fake data extraExtension = range_val/20.0 sampl = np.random.uniform(low=np.min(data_range) - extraExtension, high=np.max(data_range) + extraExtension, size=(100,100)) FIGSIZE = (3.5,3.5) fig, ax = plt.subplots(figsize=FIGSIZE) contourf = ax.contourf(sampl, levels=levelsArr, cmap=cm.get_cmap(color_map), extend='both') cbar = plt.colorbar(contourf, orientation='horizontal', extend='both', ax=ax) cbar.ax.tick_params(labelsize=7) cbar.ax.set_xlabel(label, size=8) # remove axes ax.remove() # convert image into base64 encoded string with io.BytesIO() as out_img: fig.savefig(out_img, format='png', transparent=True, bbox_inches='tight', pad_inches=0, dpi='figure') out_img.seek(0) # save in s3 bucket as well for caching s3.put_object(Body=out_img, Bucket=bucket_name, Key=legend_filename, ACL='public-read') out_img.seek(0) encoded_img = base64.b64encode(out_img.read()).decode('utf-8') return encoded_img <file_sep>const express = require('express'); const { s3 } = require('../../aws_s3.js'); const S3_BUCKET = process.env.S3_BUCKET_NAME; downloadFilesRouter = express.Router(); downloadFilesRouter.get('/', (req, res) => { // const fileName = req.query['file-name']; // const bucket = req.query['bucket']; // Key: "RTOFS_OC/0m/rtofs_currents_20160512_00.json" const s3Params = { Bucket: S3_BUCKET, Key: "RTOFS_OC/0m/rtofs_currents_20160512_00.json" }; s3.getObject(s3Params, function (error, data) { if (error != null) { // alert("Failed to retrieve an object: " + error); } else { // alert("Loaded " + data.ContentLength + " bytes"); // Convert Body from a Buffer to a String res.write(JSON.stringify(data.Body.toString('utf-8'))); //.toString('utf-8'); // console.log(data.ContentLength + ' bytes'); res.end(); } } ); }); module.exports = downloadFilesRouter;<file_sep>import pickle import datetime import copy import io import os import re import boto3 import numpy as np import mercantile import PIL from utils.datasets import datasets s3 = boto3.client('s3') def lambda_handler(event, context): """ This function creates data 'tiles' (.pickle) -- subsetted data -- and saves them in S3 ----------------------------------------------------------------------- Inputs: event: AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type. In this case the event contains these keys: 'pickle_filepath': (string) the location of the pickle data file 'data_type': (string) - one of 'wind_speed', 'current_speed', 'wave_height', 'wave_period' 'bucket_name': (string) the name of the S3 bucket ('oceanmapper-data-storage') 'output_picklepath': (string) - the location where the file will be saved on S3 'xyz_info': the start and end indx of the tiles to be processed from the mercantile generator 'zoom': (int) the zoom level to make data 'tiles' for *(http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/) context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Output: pickle files are saved to S3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/08/2018 """ # get event paramaters bucket_name = event['bucket_name'] pickle_filepath = event['pickle_filepath'] output_picklepath = event['output_picklepath'] zoom = event['zoom'] start_indx = event['xyz_info']['start_indx'] end_indx = event['xyz_info']['end_indx'] # load data pickle_data = s3.get_object(Bucket=bucket_name, Key=pickle_filepath) body_string = pickle_data['Body'].read() data = pickle.loads(body_string) # process the data in preparation for data 'tiling' if hasattr(data['lat'],'mask'): lat = data['lat'].data else: lat = data['lat'] if hasattr(data['lon'],'mask'): lon = data['lon'].data else: lon = data['lon'] lat_diff = np.abs(np.diff(lat)[0]) lon_diff = np.abs(np.diff(lon)[0]) time_origin = data['time_origin'] # parse top level folder and sub resource from path so we can use datasets to loop through vars pattern = r'(\w*)/\d{8}_\d{2}/(\w*)' match = re.search(pattern,pickle_filepath) dataset = match.group(1) sub_resource = match.group(2) variables = datasets[dataset]['sub_resource'][sub_resource]['variables'] # get list of all tiles for certain geographic extents and zooms tiles_gen = mercantile.tiles(west=lon.min(), south=lat.min(), east=lon.max(), north=lat.max(), zooms=zoom) tiles = [tile for tile in tiles_gen] for tile_indx in range(start_indx,end_indx): tile = tiles[tile_indx] i,j,zoom=[*tile] ll = mercantile.bounds(i, j, zoom) _wgs84_lon_min, _wgs84_lat_min = ll[:2] _wgs84_lon_max, _wgs84_lat_max = ll[2:] # extend bounds slightly to avoid issue with data being cut off at tile boundaries _wgs84_lon_min_padded = _wgs84_lon_min - (10 * lon_diff) _wgs84_lon_max_padded = _wgs84_lon_max + (10 * lon_diff) _wgs84_lat_min_padded = _wgs84_lat_min - (10 * lat_diff) _wgs84_lat_max_padded = _wgs84_lat_max + (10 * lat_diff) # trimming here based on the extents of the tile keep_lat_bool = np.logical_and(lat<=_wgs84_lat_max_padded, lat>=_wgs84_lat_min_padded) keep_lat_indx = np.argwhere(keep_lat_bool).ravel() keep_lon_bool = np.logical_and(lon<=_wgs84_lon_max_padded, lon>=_wgs84_lon_min_padded) keep_lon_indx = np.argwhere(keep_lon_bool).ravel() # TODO: add model valid time to output data output_data = {} output_data['lat'] = lat[keep_lat_indx] output_data['lon'] = lon[keep_lon_indx] output_data['time_origin'] = time_origin for var in variables: output_data[var] = data[var][keep_lat_indx,:][:,keep_lon_indx] filename = '{0}{1}/{2}/{3}.pickle'.format(output_picklepath, str(zoom), str(i), str(j)) # save the file raw_data_pickle = pickle.dumps(output_data) s3.put_object(Body=raw_data_pickle, Bucket=bucket_name, Key=filename) if __name__ == "__main__": event = { 'pickle_filepath': 'RTOFS_DATA/20190301_00/ocean_current_speed/0m/pickle/rtofs_currents_20190301_00.pickle', 'bucket_name': 'oceanmapper-data-storage', 'output_picklepath': 'test_data/', 'xyz_info': {'start_indx': 0, 'end_indx': 50}, 'zoom': 3 } context = {} lambda_handler(event,context) <file_sep>import aws from 'aws-sdk'; aws.config.region = process.env.AWS_REGION; let s3Obj = new aws.S3({ accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY }); export default s3Obj;<file_sep># -*- coding: utf-8 -*- """ Created on Mon Apr 09 19:12:40 2018 @author: Michael """ import datetime import re import urllib.request as urllib from bs4 import BeautifulSoup from utils.fetch_utils import get_opendapp_netcdf def get_hycom_forecast_info(hycom_url): """ get_hycom_forecast_info(hycom_url) This function assembles an object the latest available forecast date that contains the full forecast extent (168hrs) as well as an array of all opendapp urls (1 for each timestep) as well as an array containing the various depth levels supported by this model. Model Info: https://www.hycom.org/dataserver/gofs-3pt1/analysis ----------------------------------------------------------------------- Input: {string} hycom_url - the HYCOM forecast data catalog url i.e. https://tds.hycom.org/thredds/catalog/GLBy0.08/expt_93.0/FMRC/runs/catalog.html ----------------------------------------------------------------------- Output: object with this structure: forecast_info = {forecast: {'latest_date': 'yyyymmdd', 'data_urls': [xxx, xxx, xxx], 'field_datetimes': [dt,dt...]}, 'levels': [0,2,...]}} """ page = urllib.urlopen(hycom_url).read() soup = BeautifulSoup(page, 'html.parser') soup.prettify() forecast_dict = {} for anchor in soup.findAll('a', href=True): anchor_str = anchor['href'] match = re.search(r'FMRC_RUN_(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$', anchor_str) if match: forecast_year = int(match.group(1)) forecast_month = int(match.group(2)) forecast_day = int(match.group(3)) forecast_hour = int(match.group(4)) datetime_element = datetime.datetime(forecast_year, forecast_month, forecast_day, forecast_hour) forecast_hour_extent = forecast_hour forecast_dict.setdefault(datetime_element, []).append({'forecast_date': datetime_element, 'forecast_hour_extent': forecast_hour_extent}) # sort available unique forecast dates in reverse order so most recent is first unique_dates = sorted(forecast_dict.keys(), reverse=True) max_forecast_run_date = unique_dates[0] formatted_latest_date = datetime.datetime.strftime(max_forecast_run_date, '%Y-%m-%dT%H:%M:%SZ') output_url = f"https://tds.hycom.org/thredds/dodsC/GLBy0.08/expt_93.0/FMRC/runs/GLBy0.08_930_FMRC_RUN_{formatted_latest_date}" file = get_opendapp_netcdf(output_url) levels = file.variables['depth'][:] time = file.variables['time'] base_time_str_match = re.search(r'(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})', time.units) base_time = datetime.datetime.strptime(base_time_str_match.group(0), '%Y-%m-%d %H:%M:%S') forecast_time_offsets = time[:] file.close() # assemble field datetimes field_datetimes = [base_time + datetime.timedelta(hours=hour_offset) for hour_offset in forecast_time_offsets] forecast_info = { 'forecast': { 'latest_date': datetime.datetime.strftime(max_forecast_run_date, '%Y%m%d_%H%M'), 'data_url': output_url, 'field_datetimes': field_datetimes, 'levels': [int(lev) for lev in levels.tolist()], 'forecast_time_indx': list(range(len(field_datetimes))) } } return forecast_info if __name__ == "__main__": hycom_url = "https://tds.hycom.org/thredds/catalog/GLBy0.08/expt_93.0/FMRC/runs/catalog.html" get_hycom_forecast_info(hycom_url) <file_sep>import json import sys sys.path.append("..") import json import datetime import pickle import time import io import logging import boto3 import numpy as np from scipy import interpolate import netCDF4 from harvest_utils.fetch_utils import get_opendapp_netcdf from harvest_utils.process_pickle import generate_pickle_files from harvest_utils.datasets import datasets logger = logging.getLogger('data-harvest') def process_3d_fields(data_url, forecast_time, model_field_indx, levels): """ process_3d_fields(data_url, forecast_time, model_field_indx, levels) This function reads, parses, and saves a .json and .pickle file from a netCDF file from a provided opendapp url ----------------------------------------------------------------------- Inputs: ----------------------------------------------------------------------- Output: A .json file and a .pickle file are save to S3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 04/20/2019 """ AWS_BUCKET_NAME = 'oceanmapper-data-storage' TOP_LEVEL_FOLDER = 'RTOFS_DATA' SUB_RESOURCE = 'ocean_current_speed' DATA_PREFIX = 'rtofs_currents' u_comp_url = data_url; v_comp_url = data_url.replace('uvel','vvel') with get_opendapp_netcdf(u_comp_url) as file_u, get_opendapp_netcdf(v_comp_url) as file_v: formatted_folder_date = datetime.datetime.strftime(forecast_time,'%Y%m%d_%H') logger.info('processing RTOFS_DATA data: {}'.format(formatted_folder_date)) # output model info.json filepath output_info_path = TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/info.json' # get model origin time if 'nowcast' in u_comp_url: time_orig_str = file_u.variables['time'].maximum else: time_orig_str = file_u.variables['time'].minimum time_origin = datetime.datetime.strptime(time_orig_str,'%Hz%d%b%Y') lat = file_u.variables['lat'][:] lon = file_u.variables['lon'][:] # loop through all desire levels for a given time for model_level_indx, model_level_depth in levels: logger.info('level: {}m'.format(model_level_depth)) output_json_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE + '/' + str(model_level_depth) + 'm/json/' + DATA_PREFIX + '_' + formatted_folder_date + '.json') output_pickle_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE + '/' + str(model_level_depth) + 'm/pickle/' + DATA_PREFIX + '_' + formatted_folder_date + '.pickle') output_tile_scalar_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE + '/' + str(model_level_depth) + 'm/tiles/scalar/') output_tile_data_path = (TOP_LEVEL_FOLDER + '/' + formatted_folder_date + '/' + SUB_RESOURCE + '/' + str(model_level_depth) + 'm/tiles/data/') # transform masked values to 0 u_data_raw = file_u.variables['u'][model_field_indx,model_level_indx,:,:] #[time,level,lat,lon] v_data_raw = file_v.variables['v'][model_field_indx,model_level_indx,:,:] u_data_mask_applied = np.where(~u_data_raw.mask, u_data_raw, 0) v_data_mask_applied = np.where(~v_data_raw.mask, v_data_raw, 0) # ordered lat array lat_sort_indices = np.argsort(lat) lat_ordered = lat[lat_sort_indices] # rtofs longitudes go from 74.16 to 434.06227 -- remap and sort to -180 to 180 grid lon_translate = np.where(lon>180, lon-360.0, lon) lon_sort_indices = np.argsort(lon_translate) # ordered longitude arrays lon_ordered = lon_translate[lon_sort_indices] # rebuild u/v data with correct longitude sorting (monotonic increasing) u_data_cleaned_filled = u_data_mask_applied[lat_sort_indices,:][:,lon_sort_indices] v_data_cleaned_filled = v_data_mask_applied[lat_sort_indices,:][:,lon_sort_indices] u_data_cleaned = u_data_raw[lat_sort_indices,:][:,lon_sort_indices] v_data_cleaned = v_data_raw[lat_sort_indices,:][:,lon_sort_indices] # assign the raw data to a variable so we can pickle it for use with other scripts raw_data = {'lat': lat_ordered, 'lon': lon_ordered, 'u_vel': u_data_cleaned, 'v_vel': v_data_cleaned, 'time_origin': time_origin} output_lat_array = np.arange(int(min(lat)),int(max(lat))+0.5,0.5) # last point is excluded with arange (90 to -90) output_lon_array = np.arange(-180,180.5,0.5) # last point is excluded with arange (-180 to 180) u_interp_func = interpolate.interp2d(lon_ordered, lat_ordered, u_data_cleaned_filled, kind='cubic') v_interp_func = interpolate.interp2d(lon_ordered, lat_ordered, v_data_cleaned_filled, kind='cubic') u_data_interp = u_interp_func(output_lon_array, output_lat_array) v_data_interp = v_interp_func(output_lon_array, output_lat_array) minLat = np.min(output_lat_array) maxLat = np.max(output_lat_array) minLon = np.min(output_lon_array) maxLon = np.max(output_lon_array) dx = np.diff(output_lon_array)[0] dy = np.diff(output_lat_array)[0] output_data = [ {'header': { 'parameterUnit': "m.s-1", 'parameterNumber': 2, 'dx': dx, 'dy': dy, 'parameterNumberName': "Eastward current", 'la1': maxLat, 'la2': minLat, 'parameterCategory': 2, 'lo1': minLon, 'lo2': maxLon, 'nx': len(output_lon_array), 'ny': len(output_lat_array), 'refTime': datetime.datetime.strftime(forecast_time,'%Y-%m-%d %H:%M:%S'), 'timeOrigin': datetime.datetime.strftime(time_origin,'%Y-%m-%d %H:%M:%S'), }, 'data': [float('{:.3f}'.format(el)) if np.abs(el) > 0.0001 else 0 for el in u_data_interp[::-1].flatten().tolist()] }, {'header': { 'parameterUnit': "m.s-1", 'parameterNumber': 3, 'dx': dx, 'dy': dy, 'parameterNumberName': "Northward current", 'la1': maxLat, 'la2': minLat, 'parameterCategory': 2, 'lo1': minLon, 'lo2': maxLon, 'nx': len(output_lon_array), 'ny': len(output_lat_array), 'refTime': datetime.datetime.strftime(forecast_time,'%Y-%m-%d %H:%M:%S'), 'timeOrigin': datetime.datetime.strftime(time_origin,'%Y-%m-%d %H:%M:%S'), }, 'data': [float('{:.3f}'.format(el)) if np.abs(el) > 0.0001 else 0 for el in v_data_interp[::-1].flatten().tolist()] }, ] s3 = boto3.client('s3') with io.BytesIO() as f: pickle.dump(raw_data,f,pickle.HIGHEST_PROTOCOL) f.seek(0) s3.upload_fileobj(f,AWS_BUCKET_NAME, output_pickle_path) with io.BytesIO() as f: f.write(json.dumps(output_data).encode()) f.seek(0) s3.upload_fileobj(f,AWS_BUCKET_NAME, output_json_path) with io.BytesIO() as f: info = {'time_origin': datetime.datetime.strftime(time_origin,'%Y-%m-%d %H:%M:%S')} f.write(json.dumps(info).encode()) f.seek(0) s3.upload_fileobj(f,AWS_BUCKET_NAME, output_info_path) # subset and save data by tile data_zoom_level = datasets[TOP_LEVEL_FOLDER]['sub_resource'][SUB_RESOURCE]['data_tiles_zoom_level'] generate_pickle_files(raw_data, TOP_LEVEL_FOLDER, SUB_RESOURCE, output_tile_data_path, data_zoom_level, AWS_BUCKET_NAME) <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import Paper from '@material-ui/core/Paper'; const styles = theme => ({ root: { ...theme.mixins.gutters(), paddingTop: theme.spacing.unit * 2, paddingBottom: theme.spacing.unit * 2, fontFamily: 'Roboto, Helvetica, Arial, sans-serif', fontSize: '0.75rem', fontWeight: 400 }, }); function LegendContainer(props) { const { classes } = props; return ( <div> <Paper className={classes.root} elevation={1}> {props.children} </Paper> </div> ); } LegendContainer.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(LegendContainer);<file_sep>import boto3 from build_legend_image import build_legend_image from process_tiles import blank_tile s3 = boto3.client('s3') bucket = 'oceanmapper-data-storage' def lambda_handler(event, context): """ lambda_handler(event, context): This function is used in conjunction with aws api gateway (lambda proxy integration) to generate a legend image on the fly ----------------------------------------------------------------------- Inputs: event: Event data (pathParameters and queryStringParameters) are parsed from call to aws api endpoint context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Notes: https://stackoverflow.com/questions/35804042/aws-api-gateway-and-lambda-to-return-image ----------------------------------------------------------------------- Output: response object ----------------------------------------------------------------------- Author: <NAME> Date Modified: 03/11/2019 """ response_obj = { "isBase64Encoded": True, "statusCode": 200, "headers": {'Content-Type': 'image/png', 'Access-Control-Allow-Origin': '*'}, "body": None # base64.b64encode(content_bytes).decode("utf-8") #TODO drop image bytes in here } try: response_obj['body'] = build_legend_image(event['queryStringParameters']) except: # build blank legend image response_obj['body'] = blank_tile(30,300) return response_obj if __name__ == '__main__': event = { "queryStringParameters": { "color_map": "magma", "data_range": "0,2", "interval": "0.25", "label": "Current Speed (m/s)" } } lambda_handler(event,'') # https://5qkqvek867.execute-api.us-east-2.amazonaws.com/staging/legend?color_map=jet&data_range=0,2&interval=0.25&label=Current Speed (m/s) # https://a7vap1k0cl.execute-api.us-east-2.amazonaws.com/staging/dynamic-tile/5/8/13?dataset=RTOFS_DATA&sub_resource=ocean_current_speed&level=0&time=2019-02-21T23:00Z # https://a7vap1k0cl.execute-api.us-east-2.amazonaws.com/staging/dynamic-tile/2/1/2?dataset=GFS_DATA&sub_resource=wind_speed&level=10&time=2019-02-26T23:00Z&n_levels=100&color_map=magma&data_range=0,100 <file_sep>import sys sys.path.append("..") import os import json import boto3 import numpy as np import datetime import time import logging from RTOFS_forecast_info import get_latest_RTOFS_forecast_time from RTOFS_process_3d_fields import process_3d_fields from build_model_times import assemble_model_timesteps from harvest_utils.status_utility import update_process_status # create logger logger = logging.getLogger('data-harvest') logger.setLevel(logging.INFO) # create console handler ch = logging.StreamHandler() ch.setLevel(logging.INFO) logger.addHandler(ch) # create file handler logfile_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'data-harvest.log') fh = logging.FileHandler("{0}".format(logfile_path)) fh.setLevel(logging.INFO) logger.addHandler(fh) # create formatter formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s') # add formatter to ch and fh ch.setFormatter(formatter) fh.setFormatter(formatter) def main(): """ main(): This function kicks off a script to read, process, and save rtofs forecast data to s3 ----------------------------------------------------------------------- Author: <NAME> Date Modified: 4/18/2019 """ logger.info('-- FETCHING RTOFS DATA --') # update the harvest status file status_update = update_process_status('rtofs', 'processing') rtofs_url = 'https://nomads.ncep.noaa.gov:9090/dods/rtofs' available_data = get_latest_RTOFS_forecast_time(rtofs_url, '3d') output_info = assemble_model_timesteps(available_data,'daily') levels = output_info['general']['levels'] stop_level = 100 levels_array=[(level_indx, level) for level_indx, level in enumerate(levels) if level % 10 == 0 and level <= stop_level] for product_type in output_info['products'].keys(): zipped_time_and_indx = np.array(tuple(zip(output_info['products'][product_type]['field_datetimes'], output_info['products'][product_type]['forecast_indx']))) data_url = output_info['products'][product_type]['url'] for forecast_time, model_field_indx in zipped_time_and_indx: # only utilize certain forecast times for efficiency if forecast_time.hour % 6 == 0: try: process_3d_fields(data_url, forecast_time, model_field_indx, levels_array) except Exception as e: logger.error('An error occured!! - {}'.format(e)) continue # set processing status back to ready status_update = update_process_status('rtofs', 'ready') if __name__ == "__main__": main()<file_sep>import numpy as np import datetime def get_model_times_in_range(dataset_folder,sub_resource_folder,model_start_time_datetime, model_end_time_datetime,level_formatted,file_type,availability_struct): """ get_model_times_in_range(dataset_folder,sub_resource_folder,model_start_time_datetime, model_end_time_datetime,level_formatted,file_type,availability_struct) This function is used to find the available model times between a provided start and end time ----------------------------------------------------------------------- Inputs: dataset_folder (str): the s3 'folder' to search sub_resource_folder (str): the s3 sub folder to search (i.e. ocean_current_speeds) model_start_time_datetime (datetime): the requested start time of the timeseries range model_end_time_datetime (datetime): the requested end time of the timeseries range level_formatted (str): the level (altitude/depth) of the data (i.e. 10m) file_type (str): one of [json, pickle] availability_struct (obj): information on data availability for environmental datasets stored on S3 ----------------------------------------------------------------------- Output: an array of datetimes representing valid model times between a provided start and end time ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/13/2018 """ dataset_type = file_type available_times = availability_struct[dataset_folder][sub_resource_folder]['level'][level_formatted][dataset_type] available_times_dt = [datetime.datetime.strptime(datetime_str,'%Y%m%d_%H') for datetime_str in available_times] # turn into numpy array (unique and sorted) available_times_dt_array = np.unique(np.array(available_times_dt)) trimmed_available_times = available_times_dt_array[np.logical_and(available_times_dt_array >= model_start_time_datetime, available_times_dt_array <= model_end_time_datetime)] return trimmed_available_times <file_sep>import datetime import json import os import boto3 from api_utils.check_query_params import check_query_params, filter_failed_params from api_utils.fetch_data_availability import grab_data_availability from api_utils.get_model_value import get_model_value from api_utils.nearest_model_time import get_available_model_times from api_utils.response_constructor import generate_response from utils.datasets import datasets from utils.s3_filepath_utils import build_tiledata_path from point_locator import in_ocean s3 = boto3.client('s3') lam = boto3.client('lambda') bucket = 'oceanmapper-data-storage' def lambda_handler(event, context): """ lambda_handler(event, context): This function is used in conjunction with aws api gateway (lambda proxy integration) to pass back the interpolated value of a dataset at a specific geographic coordinate ----------------------------------------------------------------------- Inputs: event: Event data (queryStringParameters) are parsed from call to aws api endpoint context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Output: response object ----------------------------------------------------------------------- Author: <NAME> Date Modified: 10/17/2018 """ # default headers for request headers = {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'} required_query_params = ['time','dataset','sub_resource','level','coordinates'] # load data availability file from s3 availability_struct = grab_data_availability() if not availability_struct: response_body = { 'status': 'Failed to load data availability structure.', } return generate_response(404, headers, response_body) query_param_validation = check_query_params(event,required_query_params, availability_struct, datasets) # make sure we have all required and valid inputs failed_query_param_obj = filter_failed_params(query_param_validation) if len(failed_query_param_obj.keys()): response_body = { 'status': failed_query_param_obj, } return generate_response(404, headers, response_body) # model time model_time = event['queryStringParameters']['time'] model_time_datetime = datetime.datetime.strptime(model_time,'%Y-%m-%dT%H:%MZ') # dataset (model) dataset = event['queryStringParameters']['dataset'] # sub resource sub_resource = event['queryStringParameters']['sub_resource'] sub_resource_folder = datasets[dataset]['sub_resource'][sub_resource] dataset_prefix = sub_resource_folder['data_prefix'] dataset_units = sub_resource_folder['units'] # model level level = event['queryStringParameters']['level'] level_formatted = str(level) + 'm' if len(str(level)) else '' # wave data have no level # coordinates coords = [float(coord) for coord in event['queryStringParameters']['coordinates'].split(',')] overlay_type = datasets[dataset]['sub_resource'][sub_resource]['overlay_type'] coord_in_ocean = False # default is not in ocean if overlay_type == 'ocean': coord_in_ocean = in_ocean(coords[0], coords[1]) # if model is (ocean only) then check the coords to make sure they are in the ocean if not coord_in_ocean and overlay_type == 'ocean': response_body = { 'data': None, 'status': 'point on land', } return generate_response(200, headers, response_body) dataset_vars = sub_resource_folder['variables'] dataset_type = 'pickle' available_time = get_available_model_times(dataset,sub_resource, model_time_datetime, level_formatted, dataset_type, availability_struct) if available_time: available_time_str = datetime.datetime.strftime(available_time,'%Y-%m-%dT%H:%MZ') # this is the subsetted .pickle data data_key = build_tiledata_path(dataset, sub_resource, level_formatted, available_time, coords) data_value = get_model_value(coords, data_key, sub_resource, dataset_vars) # construct the response body response_body = { 'model': dataset, 'sub_resource': sub_resource, 'valid_time': available_time_str, 'data': data_value, 'units': dataset_units } return generate_response(200, headers, response_body) else: response_body = { 'model': dataset, 'sub_resource': sub_resource, 'valid_time': None, 'data': None, 'units': None, } return generate_response(200, headers, response_body) if __name__ == '__main__': # TODO: check on value returned for WW3.. getting strange point values.. interpolation issue, masked vals, fill vals? # Check near coast and inland event = { "queryStringParameters": { "level": "", "dataset": "WW3_DATA", "sub_resource": "sig_wave_height", "time": "2022-10-27T20:00Z", "coordinates": "-68.93371582031251,41.701627343789205" #"-81.58,23.88" } } lambda_handler(event,'') <file_sep>import sys sys.path.append("..") import boto3 import datetime import json import re from harvest_utils.remote_data_info import get_max_date from RTOFS.RTOFS_forecast_info import get_latest_RTOFS_forecast_time from RTOFS.build_model_times import assemble_model_timesteps s3 = boto3.resource('s3') AWS_BUCKET_NAME = 'oceanmapper-data-storage' def is_data_fresh(): ''' Checks if the latest available forecast field in s3 bucket matches the extent of the latest RTOFS forecast run. Returns True if the forecast extents match (i.e. the data is fresh) ''' s3_max_date = get_max_date('RTOFS_DATA') # get the max of s3_dates and compare to max_remote_date rtofs_url = 'https://nomads.ncep.noaa.gov:9090/dods/rtofs' available_data = get_latest_RTOFS_forecast_time(rtofs_url, '3d') output_info = assemble_model_timesteps(available_data,'daily') max_datasource_date = max(output_info['products']['forecast']['field_datetimes']) if s3_max_date != max_datasource_date: return False return True if __name__ == "__main__": is_data_fresh() <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import ExpansionPanel from './ExpansionPanel'; import ExpansionPanelSummary from './ExpansionPanelSummary'; import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails'; import Typography from '@material-ui/core/Typography'; import AddIcon from '@material-ui/icons/Add'; import RemoveIcon from '@material-ui/icons/Remove'; // https://github.com/mui-org/material-ui/pull/10961 // https://stackoverflow.com/questions/46066675/how-to-add-multiple-classes-in-material-ui-using-the-classes-props const styles = theme => ({ root: { width: '100%', }, heading: { fontSize: theme.typography.pxToRem(15), fontWeight: 600, }, expansionDetailRoot: { display: 'block', paddingTop: 0 } }); function TOCExpansionPanel(props) { const { classes, defaultExpanded } = props; return ( <div className={classes.root}> <ExpansionPanel defaultExpanded={defaultExpanded} > <ExpansionPanelSummary expandIcon={<AddIcon />} collapseIcon={<RemoveIcon />} > <Typography className={classes.heading}>{props.categoryName}</Typography> </ExpansionPanelSummary> <ExpansionPanelDetails classes={{ root: classes.expansionDetailRoot }} > {props.children} </ExpansionPanelDetails> </ExpansionPanel> </div> ); } TOCExpansionPanel.propTypes = { classes: PropTypes.object.isRequired, theme: PropTypes.object.isRequired, }; export default withStyles(styles, { withTheme: true })(TOCExpansionPanel);<file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import MenuItem from '@material-ui/core/MenuItem'; import Select from '@material-ui/core/Select'; const styles = theme => ({ selectMenu: { margin: theme.spacing.unit, maxWidth: '100%' }, selectItem: { fontSize: '0.9rem' } }); const IntervalDropdown = (props) => { const { classes } = props; return ( <div> <Select disableUnderline value={props.interval} autoWidth={false} onChange={(e) => props.handleLayerSettingsUpdate(props.layerID, 'interval', e.target.value)} name="interval" className={classes.selectMenu} classes={{ select: classes.selectItem }} > {props.intervalArr.map((intervalVal, indx) => <MenuItem key={indx.toString()} value={intervalVal} > {intervalVal} </MenuItem> )} </Select> </div> ) } IntervalDropdown.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(IntervalDropdown);<file_sep>import moment from 'moment'; import {getProfileData, getTimeSeriesData} from './dataFetchingUtils'; const compareObj = (a,b) => { if (a.x < b.x) return -1; if (a.x > b.x) return 1; return 0; } const compareArr = (a,b) => { if (a[0] < b[0]) return -1; if (a[0] > b[0]) return 1; return 0; } export const parseData = (app, chartType, abortSignal) => { let mapLayers = app.state.mapLayers, orderedMapLayers = app.state.orderedMapLayers, activeLocation = app.state.activeLocation, data, fetchArray = [], activeLayers = [], arrowLen = 150; orderedMapLayers.forEach(layer => { if (mapLayers[layer] && mapLayers[layer]['isOn'] && mapLayers[layer]['dataset']) activeLayers.push(mapLayers[layer]); }) // stop execution if no active layers if (!activeLayers.length) { // TODO: return something so a modal can be displayed app.setState({chartLoading: false, chartModalOpen: false}); return } // fetch data for each active layer activeLayers.forEach(activeLayer => { if (chartType === 'timeseries') { data = getTimeSeriesData(activeLayer['dataset'],activeLayer['subResource'], activeLayer['level'],app.state.startTime, app.state.endTime, [activeLocation['lng'], activeLocation['lat']], abortSignal); } else { data = getProfileData(activeLayer['dataset'],activeLayer['subResource'], app.state.mapTime, [activeLocation['lng'], activeLocation['lat']], abortSignal); } fetchArray.push(data); }) let chartLoadingErrors = []; Promise.all(fetchArray).then(responses => { let outputHighChartsArray = [], datasetIDs = [], seriesData, vectorData, layerObj; responses.forEach((resp,indx) => { // skip the following logic if there was an error (so we could end up with empty outputHighChartsArray) // can i build an error object? and display error in subtitle?? if (resp['error'] || !resp['data']) { chartLoadingErrors.push(activeLayers[indx]['niceName']); return; } // build an array of names to determine if a wave data merge is necessary datasetIDs.push(activeLayers[indx]['id']); let directionConvention = activeLayers[indx]['directionConvention']; seriesData = {type: 'line', data: [] }; vectorData = {type: 'vector', data: [] }; layerObj = { niceName: activeLayers[indx]['niceName'], shortName: activeLayers[indx]['shortName'], level: activeLayers[indx]['level'] || 'n/a', levelUnit: activeLayers[indx]['levelUnit'], dataType: activeLayers[indx]['overlayType'], validTime: resp['valid_time'] || null, units: resp['units'], series: [] }; // based on chart type parse and package data differently let datapointKey, depth, dateTime, value, direction, origDirection, timeOrigin; resp['data'].forEach(datapoint => { datapointKey = Object.keys(datapoint)[0]; if (chartType === 'timeseries') { dateTime = moment(datapointKey, 'YYYY-MM-DDTHH:mmZ').utc().valueOf(); } else { depth = layerObj['dataType'] === 'ocean' ? -1 * parseInt(datapointKey) : parseInt(datapointKey); // TODO: need to update backend to return datetime } value = datapoint[datapointKey]['val']; timeOrigin = datapoint[datapointKey]['time_origin']; if (activeLayers[indx]['chartType'] === 'series-vector') { // original direction already accounts for to/from standards for winds/waves/currents origDirection = datapoint[datapointKey]['direction']; // add 180 degrees if working with certain datasets so arrow displays correctly in charts direction = directionConvention === 'from' ? datapoint[datapointKey]['direction'] : (datapoint[datapointKey]['direction'] + 180) % 360; // axis is inverted when working with profile plots.. this fudges the direction so its // represented properly direction = chartType === 'timeseries' ? direction : (90 - direction) % 360; seriesData['data'].push({ x: chartType === 'timeseries' ? dateTime : depth, y: value, direction: origDirection, timeOrigin}); vectorData['data'].push([chartType === 'timeseries' ? dateTime : depth, value, arrowLen, direction]); } else if (activeLayers[indx]['chartType'] === 'vector') { direction = directionConvention === 'from' ? value : (value + 180) % 360; // axis is inverted when working with profile plots.. this fudges the direction so its // represented properly direction = chartType === 'timeseries' ? direction : (90 - direction) % 360; // vector gets plot at a constant y value of 1 vectorData['data'].push([chartType === 'timeseries' ? dateTime : depth, 1, arrowLen, direction]); } else { seriesData['data'].push({x: chartType === 'timeseries' ? dateTime : depth, y: value, timeOrigin}); } }) // only push non empty data arrays to output array to be shipped to highcharts component let comboSeries = [seriesData, vectorData]; comboSeries.forEach(dataObj => { if (dataObj['data'].length > 0) { layerObj['series'].push(dataObj) } }) // push object into output array outputHighChartsArray.push(layerObj); }) // merge wave height and direction at this point if both exist in outputHighChartsArray if (datasetIDs.includes('ww3_sig_wave_height') & datasetIDs.includes('ww3_primary_wave_dir')) { var waveHeightIndx = datasetIDs.indexOf('ww3_sig_wave_height'); var waveDirIndx = datasetIDs.indexOf('ww3_primary_wave_dir'); // note that modifying waveHeightArr in forEach loop below modifies outputHighChartsArray let waveHeightArr = outputHighChartsArray[waveHeightIndx].series[0].data.slice(); let waveDirectionObj = {}; // create an object with forecast times as keys and direction as values outputHighChartsArray[waveDirIndx].series[0].data.forEach(el => { waveDirectionObj[el[0]] = el[3]; }) // empty vector data before adding new data vectorData['data'] = []; outputHighChartsArray[waveHeightIndx].series.push(vectorData) // for each wave height entry see if corresponding data exists for wave direction // and add it to the vector series if it does waveHeightArr.forEach((waveHeightData,arrIndx) => { let xval = waveHeightData['x']; let val = waveHeightData['y']; if (waveDirectionObj[xval]) { outputHighChartsArray[waveHeightIndx].series[1].data.push( [xval, val, arrowLen, waveDirectionObj[xval]]) // updates outputHighChartsArray to include direction property alongside wave height waveHeightData['direction'] = waveDirectionObj[xval]; } }) // remove wave direction from output array since its now combined with wave height outputHighChartsArray.splice(waveDirIndx, 1); } // sort if profile data if (chartType === 'profile') { outputHighChartsArray.forEach(dataset => { dataset['series'].forEach((subDataset, subIndx) => { let dataArr = subDataset['data']; subIndx === 0 ? dataArr.sort(compareObj) : dataArr.sort(compareArr); }) }) } app.setState({chartLoading: false, chartData: outputHighChartsArray, chartLoadingErrors}); }) } <file_sep>import React from "react"; function SettingsTick({ tick, count }) { // your own tick component return ( <div> <div style={{ position: 'absolute', marginTop: 32, marginLeft: -0.5, width: 1, height: 8, backgroundColor: 'silver', left: `${tick.percent}%`, }} /> <div style={{ position: 'absolute', marginTop: 40, fontSize: 12, // 10, textAlign: 'center', marginLeft: `${-(100 / count) / 2}%`, width: `${100 / count}%`, left: `${tick.percent}%`, }} > {tick.value} </div> </div> ) } export default SettingsTick;<file_sep>// import buttonTextSize from './styleVariables'; export const activeDrillingPopupStaticContent = drillingInfo => { let popupContent = ` <p class="rig-name-header"><b>${drillingInfo['rig_name']}</b> (${drillingInfo['block']})</p> <hr style="margin: 1px"> <p class="active-drilling-info">Prospect Name: ${drillingInfo['prospect_name']}</p> <p class="active-drilling-info">Well Target Lease: ${drillingInfo['well_target_lease']}</p> <p class="active-drilling-info">Water Depth: ${drillingInfo['water_depth']}</p> ` return popupContent; } export const customLocationPopupStaticContent = coords => { let popupContent = ` <p class="rig-name-header"><b>Custom Location</b></p> <hr style="margin: 1px"> <p class="active-drilling-info">Latitude: ${coords['lat'].toFixed(4)}</p> <p class="active-drilling-info">Longitude: ${coords['lng'].toFixed(4)}</p> ` return popupContent; } export const buildActiveDrillingPopupButtons = () => { let buttonContent = ` <hr style="margin: 1px"> <p><i class="fas fa-plus-circle popup-button"></i><a class="popup-button-text" href="#" data-chart-type="timeseries" onclick="mymap.fire('timeseriesClick')">Plot Timeseries</a></p> <p><i class="fas fa-plus-circle popup-button"></i><a class="popup-button-text" href="#" data-chart-type="profile" onclick="mymap.fire('profileClick')">Plot Profile</a></p> ` return buttonContent } <file_sep>FROM python:3.7-alpine RUN apk update && apk upgrade # https://github.com/occ-data/docker-jupyter/blob/master/Dockerfile # https://gist.github.com/orenitamar/f29fb15db3b0d13178c1c4dd611adce2 # https://github.com/gliderlabs/docker-alpine/blob/master/docs/usage.md # https://github.com/smizy/docker-keras-tensorflow/blob/master/Dockerfile RUN apk add --no-cache \ --repository http://dl-cdn.alpinelinux.org/alpine/edge/main \ --repository http://dl-cdn.alpinelinux.org/alpine/edge/testing \ alpine-sdk \ libxslt-dev \ libxml2-dev \ libc-dev \ openssl-dev \ libffi-dev \ openssh \ ca-certificates \ cmake \ freetype-dev \ build-base \ g++ \ gcc \ gfortran \ git \ lapack-dev \ libpng-dev \ libstdc++ \ linux-headers \ m4 \ make \ unzip \ musl-dev \ wget \ zlib-dev \ hdf5 \ hdf5-dev \ sqlite \ sqlite-libs \ sqlite-dev \ curl \ curl-dev \ # proj4 \ # proj4-dev \ gdal-dev \ geos-dev \ && ln -s /usr/include/locale.h /usr/include/xlocale.h \ && pip3 install --upgrade pip # HDF5 Installation from source # RUN wget https://www.hdfgroup.org/package/bzip2/?wpdmdl=4300 \ # && mv "index.html?wpdmdl=4300" hdf5-1.10.1.tar.bz2 \ # && tar xf hdf5-1.10.1.tar.bz2 \ # && cd hdf5-1.10.1 \ # && ./configure --prefix=/usr --enable-cxx --with-zlib=/usr/include,/usr/lib/x86_64-linux-gnu \ # && make -j4 \ # && make install \ # && cd .. \ # && rm -rf hdf5-1.10.1 \ # && rm -rf hdf5-1.10.1.tar.bz2 \ # && export HDF5_DIR=/usr RUN export HDF5_DIR=/usr RUN HDF5_LIBDIR=/usr/lib HDF5_INCDIR=/usr/include python3 -m pip --no-cache-dir install \ --no-binary=h5py h5py cython # PROJ4 Installation RUN wget http://download.osgeo.org/proj/proj-6.0.0.tar.gz \ && tar -zxvf proj-6.0.0.tar.gz \ && cd proj-6.0.0 \ && ./configure --prefix=/usr \ && make -j4 \ && make install \ && cd .. \ && rm -rf proj-6.0.0 \ && rm -rf proj-6.0.0.tar.gz # NetCDF Installation RUN wget ftp://ftp.unidata.ucar.edu/pub/netcdf/netcdf-c-4.6.3.tar.gz \ && tar -zxvf netcdf-c-4.6.3.tar.gz \ && cd netcdf-c-4.6.3 \ && ./configure --enable-netcdf-4 --enable-dap --enable-shared --prefix=/usr \ && make -j4 \ && make install \ && cd .. \ && rm -rf netcdf-c-4.6.3 \ && rm -rf netcdf-c-4.6.3.tar.gz # GEOS Installation # RUN wget http://download.osgeo.org/geos/geos-3.6.2.tar.bz2 \ # && tar xf geos-3.6.2.tar.bz2 \ # && cd geos-3.6.2 \ # && ./configure --prefix=/usr \ # && make -j4 \ # && make install \ # && cd .. \ # && rm -rf geos-3.6.2 \ # && rm -rf geos-3.6.2.tar.bz2 # GDAL Installation # RUN git clone https://github.com/OSGeo/gdal.git /gdalgit \ # && cd /gdalgit/gdal \ # && ./configure --prefix=/usr \ # && make \ # && make install \ # && cd / \ # && rm -rf gdalgit # Copy the project dependencies COPY install/install_python_packages.sh /install/install_python_packages.sh COPY requirements.txt /requirements.txt # Install the project dependencies RUN chmod 755 /install/install_python_packages.sh RUN /install/install_python_packages.sh # Copy data harvesting scripts COPY /data_harvest /data_harvest ADD crontab.txt /crontab.txt ADD data_harvest_script.sh /data_harvest_script.sh COPY entry.sh /entry.sh RUN chmod 755 /data_harvest_script.sh /entry.sh RUN /usr/bin/crontab /crontab.txt CMD ["/entry.sh"]<file_sep> // Shorthand for $( document ).ready() $(function() { console.log( "ready!" ); // $('#grab-data').click(function(){alert('going to s3 to grab data')}); let fileName = 'RTOFS_OC/0m/rtofs_currents_20160512_00.json'; // getSignedRequest(fileName); // listFiles(); // downloadFile() }); function getSignedRequest(fileName){ const xhr = new XMLHttpRequest(); xhr.open('GET', `/sign-s3?file-name=${fileName}`); xhr.onreadystatechange = () => { if(xhr.readyState === 4){ if(xhr.status === 200){ debugger const response = JSON.parse(xhr.responseText); alert(response.signedRequest); alert(response.url) downloadFile(filename, response.signedRequest, response.url); } else{ alert('Could not get signed URL.'); } } }; xhr.send(); } function downloadFile(){ debugger const xhr = new XMLHttpRequest(); xhr.open('GET', `/download`); xhr.onreadystatechange = () => { if(xhr.readyState === 4){ if(xhr.status === 200){ debugger // document.getElementById('preview').src = url; // document.getElementById('avatar-url').value = url; } else{ alert('Could not upload file.'); } } }; xhr.send(); } function listFiles(){ const xhr = new XMLHttpRequest(); xhr.open('GET', `/list-files`); xhr.onreadystatechange = () => { if(xhr.readyState === 4){ if(xhr.status === 200){ debugger const response = JSON.parse(xhr.responseText); // downloadFile(filename, response.signedRequest, response.url); } else{ alert('Could not get signed URL.'); } } }; xhr.send(); } var velocityLayer = L.velocityLayer({ displayValues: true, displayOptions: { velocityType: 'GBR Water', displayPosition: 'bottomleft', displayEmptyString: 'No water data' }, data: data, maxVelocity: 1.0, velocityScale: 0.1 // arbitrary default 0.005 }); map.addLayer(velocityLayer) // getSignedRequest(file);<file_sep>#!/bin/sh cd /data_harvest/harvest_utils/ python data_availability.py<file_sep>import React from "react"; import PropTypes from "prop-types"; import { formatDateTime } from '../scripts/formatDateTime'; function Tick({ tick, count, format }) { return ( <div> <div style={{ position: "absolute", width: 1, height: 5, backgroundColor: "rgb(200,200,200)", left: `${tick.percent*100}%` }} /> <div style={{ position: "absolute", marginTop: 7, fontSize: 10, fontFamily: "Arial", textAlign: "center", marginLeft: `${-(100 / count) / 2}%`, width: `${100 / count}%`, left: `${tick.percent*100}%` }} > {format(tick.value,'MM/DD','')} </div> </div> ); } Tick.propTypes = { tick: PropTypes.shape({ id: PropTypes.string.isRequired, value: PropTypes.number.isRequired, percent: PropTypes.number.isRequired }).isRequired, count: PropTypes.number.isRequired, format: PropTypes.func.isRequired }; Tick.defaultProps = { //format: d => d format: formatDateTime }; export default Tick<file_sep>import io import json import re import boto3 import geopandas import requests from PyPDF2 import PdfFileReader AWS_BUCKET_NAME = 'oceanmapper-data-storage' DEEPWATER_ACTIVITY_URL = "https://bsee.gov/weeklyreport/deepwater_activity/current_report" def text_extractor(fileObj): """ text_extractor(fileObj) Extracts text from a pdf file object using pyPDF2 library Inputs: fileObj: file object """ pdf = PdfFileReader(fileObj) # Note: must use v1.26.0 combined_text = '' for page_indx in range(pdf.getNumPages()): page = pdf.getPage(page_indx) text = page.extractText() header_row_tail = 'Rig Name\n' start_indx = text.index(header_row_tail) + len(header_row_tail) trimmed_text = text[start_indx:] combined_text += trimmed_text return combined_text def lambda_handler(event, context): """ lambda_handler(event, context): This function is used to fetch and parse the current deepwater activity pdf report. Data is saved to s3 bucket as a json file ----------------------------------------------------------------------- Inputs: event: AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type. context: AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type. ----------------------------------------------------------------------- Output: None ----------------------------------------------------------------------- Author: <NAME> Date Modified: 01/06/2019 """ resp = requests.get(DEEPWATER_ACTIVITY_URL) with io.BytesIO() as pdf: pdf.write(resp.content) raw_text = text_extractor(pdf).replace('\n', '::').replace('\r', '') pattern = r'[\w\s.&]+::\w{2}\s+\d*::[\w\d]+::[^:]*::[\d,]*:{0,2}[^:]+' # good!!! records = re.findall(pattern, raw_text) # update when running locally # block_path = '/home/mchriste/Desktop/shapefiles/blocks/blocks.shp' block_path = 'blocks/blocks.shp' df_blocks = geopandas.read_file(block_path) block_dict = {} for index, row in df_blocks.iterrows(): try: block_name = row['AC_LAB'] block_center = [row.geometry.centroid.coords[0][0],row.geometry.centroid.coords[0][1]] # lon, lat block_dict.setdefault(block_name, block_center) except: print('block failed!!') continue # various patterns depth_pattern = r'[\d,]+' # loop through records and create some json active_drilling_output = [] for record in records: # Assume a record will always contain an operator, block, well_target_lease, rig name try: record_split = record.split('::') operator = record_split[0] block = record_split[1].replace(' ','') well_target_lease = record_split[2] prospect_name = record_split[3] if not re.search(depth_pattern, record_split[3]) else 'n/a' # water depth is second to last water_depth = record_split[-2] if re.search(depth_pattern, record_split[-2]) else 'n/a' # rig name is always last rig_name = record_split[-1] if len(record_split)>=5 else 'n/a' #get coordinates of block coords = block_dict.get(block, None) drilling_info_obj = { 'operator': operator, 'block': block, 'coordinates': coords or '', 'well_target_lease': well_target_lease, 'prospect_name': prospect_name, 'water_depth': water_depth + '(ft)', 'rig_name': rig_name } active_drilling_output.append(drilling_info_obj) except: print('in failure block!') print(record) continue output_json_path = 'current_deepwater_activity.json' client = boto3.client('s3') client.put_object(Body=json.dumps(active_drilling_output), Bucket=AWS_BUCKET_NAME, Key=output_json_path) if __name__ == '__main__': lambda_handler('','')
bd087a13431c6329a6333b39f9e1a5372e1541b2
[ "JavaScript", "Python", "Text", "Dockerfile", "Shell" ]
108
JavaScript
christensenmichael0/OceanMapper
21aefc224240f276d0c7b8cb01feb9b432470ada
00102017e93781a83dfb72b06ac9f0cd2ff0e9eb
refs/heads/master
<file_sep>requests==2.18.4 html5lib==1.0.1 lxml==4.2.1 beautifulsoup4==4.6.0 pillow==5.0.0 <file_sep>import time from jsondb import JsonDB def days_until_summer(): current_time = time.localtime() if current_time[0] % 4 == 0: days_in_year = 366 first_summer_day = 153 last_summer_day = 244 else: days_in_year = 365 first_summer_day = 152 last_summer_day = 243 if current_time[1] > 8: result = "{} days until summer".format(first_summer_day + (days_in_year - current_time[7]) - 1) elif current_time[1] < 6: result = "{} days until summer".format(first_summer_day - current_time[7]) else: result = "{} days until the end of summer".format(last_summer_day-current_time[7]) return result def days_until_newyear(): current_time = time.localtime() if current_time[0] % 4 == 0: days_in_year = 366 else: days_in_year = 365 return "{} days until New Year".format(days_in_year - current_time[7] + 1) def check_holiday(): holidays = JsonDB("holidays.json").dictionary current_local_time = time.localtime() result = "Today there is no holiday(" for date in holidays.keys(): if date.split(".") == [str(current_local_time[1]), str(current_local_time[2])]: result = holidays[date] break return result <file_sep>import random from jsondb import JsonDB def usual_lootbox(): return random.choice(JsonDB("lootbox.json").dictionary["usual_items"]) <file_sep>Just simple telegram bot Features: 1. bot responses on "/" and "?" commands that are specified in the file "commands.json" (answers also there); 2. shows random quote on "/quote" command (quotes are stored in "quotes.json"); 3. shows available currencies commands on "/currencies" command; 4. throws N-edged dice M times on "/dice N-edged M times" command; 5. randomly chooses variant on "/random 1st_variant 2nd_variant 3rd_variant etc"; 6. shows days until New Year and summer on "/newyear" and "/summer" commands; 7. gives location with coordinates on "/where <location>" command; 8. shows the location on map by coordinates on "/location <latitude> <longitude>" command; 9. shows telegram chat id on "/chat_id" command; 10. shows seconds since 00:00:00 1 January 1970 on "/unix_time" command; 11. shows what holiday is today on "/holiday" command; 12. shows color specified in RGB format on "/rgb <Red> <Green> <Blue>" command. Installation: 1. copy repository; 2. create bot and get token from BotFather(t.me/BotFather); 3. insert token in db.json; 4. run main.py.<file_sep>import random def throw_dice(command="/dice", output_type=str): # command looks like '/dice N-edged M times' numbers = command.split(" ") # n - number of edges (default) try: n = int(numbers[1].split("-")[0]) m = int(numbers[2]) except: n = 6 m = 1 finally: if n < 2 or n > 99: n = 6 if m < 1 or m > 100: m = 1 if output_type is str: return str([random.randint(1, n) for _ in range(m)])[1:-1] else: return [random.randint(1, n) for _ in range(m)] <file_sep>""" this module stores functions that collect some data from websites """ from bs4 import BeautifulSoup import requests # requests look "suspicious" for server without this header headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:45.0) Gecko/20100101 Firefox/59.0' } # getting links from cryptocurrencychart.com r = requests.get("https://www.cryptocurrencychart.com/", headers=headers) soup = BeautifulSoup(r.text, "lxml") trs = soup.find_all("tr", {"class": "row"}) cc_chart_currencies = {} [cc_chart_currencies.update({tr.find("td", {"class": "name"})["data-value"].lower().replace(" ", "_"): tr.find("td", {"class": "name"}).find("a")["href"]}) for tr in trs] def cc_chart_price_usd(name, output_format="text"): try: r = requests.get(cc_chart_currencies[name], headers=headers) soup = BeautifulSoup(r.text, "lxml") value = soup.find("td", {"class": "right currency"})["data-value"] except: value = -1 name = name.capitalize().replace("_", " ") if output_format == "text": value = "{}: {} $".format(name, value) if value != -1 else "{} rate is unavailable".format(name) else: if value != -1: while "," in value: value = value.replace(",", "") value = float(value) return value
26b5306c77e6a09122cdc1f6e704a799830039a2
[ "Markdown", "Python", "Text" ]
6
Text
Kt00s/simple_telegram_bot
5fef69cf295f6ea5b4905070eb0cbe21bbc14acd
2baa70e92961eeae5486efa5852f0965941a5d33
refs/heads/master
<repo_name>bvklim/herald-client-php<file_sep>/README.md Herald PHP client ============== Send beautiful messages from your application. ## Installation ``` composer require herald-project/client-php ``` ## Example ```php use Herald\Client\Client as HeraldClient; use Herald\Client\Message as HeraldMessage; // get the client $herald = new HeraldClient( '[herald api username]', '[herald api password]', '[herald server uri]', '[herald transport, e.g. smtp]') ); // check template existance. if ($herald->templateExists('signup')) { // get the message $message = new HeraldMessage(); // use the template $message->setTemplate('signup'); // set to address $message->setToAddress($emailAddress, $customerName); // populate data $message->setData('firstname', 'Hongliang'); $message->setData('nickname', 'exploder hater'); // send $herald->send($message); } ``` ## CLI usage ```sh #!/bin/sh common_param="\ --username=api_username \ --password=<PASSWORD> \ --apiurl=http://localhost:8787/api/v2 \ --account=test \ --library=test" # get list of all contact lists bin/herald-client list:list ${common_param} # get list of contacts in contact list #1 bin/herald-client list:contacts ${common_param} --listId=1 # get list of segments for list #1 bin/herald-client list:segments ${common_param} --listId=1 # get available list_fields for list #1 bin/herald-client list:fields ${common_param} --listId=1 # delete contact #42 #bin/herald-client contact:delete ${common_param} --contactId=42 # get properties of contact #6 bin/herald-client contact:properties ${common_param} --contactId=6 # add new contact with address '<EMAIL>' to list #1 bin/herald-client contact:add ${common_param} --listId=1 --address=<EMAIL> # add new property to contact #36 bin/herald-client property:add ${common_param} --contactId=36 --listFieldId=4 --value="some value" # send message based on tamplate #1 to all contacts in list #1 bin/herald-client list:send ${common_param} --listId=1 --templateId=1 # send message based on tamplate #1 to contacts in list #1 that meet the conditions for segment #6 bin/herald-client list:send ${common_param} --listId=1 --templateId=1 --segmentId=6 <file_sep>/src/Command/MessageListCommand.php <?php namespace Herald\Client\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Herald\Client\Client as HeraldClient; use Herald\Client\Message; class MessageListCommand extends Command { protected function configure() { $this ->setName('message:list') ->setDescription('List recently sent messages for this herald account') ->addOption( 'username', null, InputOption::VALUE_REQUIRED, 'Username for the herald server' ) ->addOption( 'password', null, InputOption::VALUE_REQUIRED, 'Password for the herald server' ) ->addOption( 'apiurl', null, InputOption::VALUE_REQUIRED, 'API URL of the herald server' ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $c = new HeraldClient( $input->getOption('username'), $input->getOption('password'), $input->getOption('apiurl'), null ); $messages = $c->getMessages(); print_r($messages); } } <file_sep>/src/Command/PropertyAddCommand.php <?php namespace Herald\Client\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Herald\Client\Client as HeraldClient; use Herald\Client\Message; class PropertyAddCommand extends CommonCommand { protected function configure() { parent::configure(); $this ->setName('property:add') ->setDescription('Add contact property') ->addOption( 'contactId', null, InputOption::VALUE_REQUIRED, 'Contact ID' ) ->addOption( 'listFieldId', null, InputOption::VALUE_REQUIRED, 'List field ID' ) ->addOption( 'value', null, InputOption::VALUE_REQUIRED, 'Value' ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $c = new HeraldClient( $input->getOption('username'), $input->getOption('password'), $input->getOption('apiurl'), $input->getOption('account'), $input->getOption('library'), null ); $res = $c->addProperty( intval($input->getOption('contactId')), intval($input->getOption('listFieldId')), $input->getOption('value') ); print_r($res); } } <file_sep>/src/Command/CheckTemplateCommand.php <?php namespace Herald\Client\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Herald\Client\Client as HeraldClient; use Herald\Client\Message; class CheckTemplateCommand extends Command { protected function configure() { $this ->setName('message:check-template') ->setDescription('Check if a message template exists on the Herald server') ->addArgument( 'template', InputArgument::REQUIRED, 'Name of the template' ) ->addOption( 'username', null, InputOption::VALUE_REQUIRED, 'Username for the herald server' ) ->addOption( 'password', null, InputOption::VALUE_REQUIRED, 'Password for the herald server' ) ->addOption( 'apiurl', null, InputOption::VALUE_REQUIRED, 'API URL of the herald server' ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $c = new HeraldClient( $input->getOption('username'), $input->getOption('password'), $input->getOption('apiurl'), null ); if ($c->templateExists($input->getArgument('template'))) { $output->writeln('<info>Success!</info>'); } else { $output->writeln('<error>Failed!</error>'); } } } <file_sep>/src/Command/ListListCommand.php <?php namespace Herald\Client\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Herald\Client\Client as HeraldClient; use Herald\Client\Message; class ListListCommand extends CommonCommand { protected function configure() { parent::configure(); $this ->setName('list:list') ->setDescription('Show list of contact lists on the Herald server') ; } protected function execute(InputInterface $input, OutputInterface $output) { $c = new HeraldClient( $input->getOption('username'), $input->getOption('password'), $input->getOption('apiurl'), $input->getOption('account'), $input->getOption('library'), null ); $contacts = $c->getLists(); print_r($contacts); } } <file_sep>/src/Command/MessageGetCommand.php <?php namespace Herald\Client\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Herald\Client\Client as HeraldClient; use Herald\Client\Message; class MessageGetCommand extends Command { protected function configure() { $this ->setName('message:get') ->setDescription('Get a recently sent messages from this herald account') ->addArgument( 'messageId', InputArgument::REQUIRED, 'ID of the message' ) ->addOption( 'username', null, InputOption::VALUE_REQUIRED, 'Username for the herald server' ) ->addOption( 'password', null, InputOption::VALUE_REQUIRED, 'Password for the herald server' ) ->addOption( 'apiurl', null, InputOption::VALUE_REQUIRED, 'API URL of the herald server' ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $c = new HeraldClient( $input->getOption('username'), $input->getOption('password'), $input->getOption('apiurl'), null ); $messageId = (string) $input->getArgument('messageId'); $messages = $c->getMessageById($messageId); print_r($messages); } } <file_sep>/src/Command/CommonCommand.php <?php namespace Herald\Client\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; abstract class CommonCommand extends Command { protected function configure() { $this ->addOption( 'username', null, InputOption::VALUE_REQUIRED, 'Username for the herald server' ) ->addOption( 'password', null, InputOption::VALUE_REQUIRED, 'Password for the herald server' ) ->addOption( 'apiurl', null, InputOption::VALUE_REQUIRED, 'API URL of the herald server' ) ->addOption( 'account', null, InputOption::VALUE_REQUIRED, 'Account name on the herald server' ) ->addOption( 'library', null, InputOption::VALUE_REQUIRED, 'Library name on the herald server' ) ; } }
fde31e8b76f794f12214ec5386dfa1da55b060ed
[ "Markdown", "PHP" ]
7
Markdown
bvklim/herald-client-php
0a07fe13f9ba8584017831d49a0b1471076bc11d
12b9ea88ba1603d8717228286911fbc845c6c773
refs/heads/master
<repo_name>smolynets/kvitka_final<file_sep>/shop/util.py # -*- coding: utf-8 -*- from .models import Flower from django.utils.translation import ugettext as _ def basket_list(request): flowers=Flower.objects.all() list = [] for p in flowers: p = request.COOKIES.get(p.lat_title) if p: c=Flower.objects.get(lat_title=p) if c: list.append(c) return list def suma(request): flowers=Flower.objects.all() price_list = 0 for p in flowers: p = request.COOKIES.get(p.lat_title) if p: c=Flower.objects.get(lat_title=p) if c: price_list = price_list + int(c.price) return price_list def flow_count_name(request): count = len(basket_list(request)) if count == 1: a='квітка' elif count > 1 and count<5: a='квітки' elif count > 4: a='квіток' elif count == 0: return None else: return 0 return a def is_digit(string): if string.isdigit(): return 1 else: try: float(string) return None except ValueError: return None def get_lang(request): if request.COOKIES.get('django_language') == 'en': pk = 'english' return pk elif request.COOKIES.get('django_language') == 'uk': pk = u'українська' return pk else: pk = u'українська' return pk<file_sep>/shop/urls.py from django.conf.urls import url from . import views from myshop.settings import MEDIA_ROOT, DEBUG from django.conf.urls.static import static from django.conf import settings from shop.views import FlowerDelete urlpatterns = [ url(r'^$', views.main_page, name='main'), url(r'^pro_mene/', views.about_me, name='about'), url(r'^kontakty', views.contacts, name='contacts'), #url(r'^koshyk', views.basket, name='basket'), url(r'^basket', views.basket, name='basket'), url(r'^samovlenya', views.orders, name='orders'), url(r'^kabinet', views.kabinet, name='kabinet'), url(r'^flower/(?P<pk>\d+)/one/', views.one_flower, name='one_flower'), url(r'^kupyty/', views.main_page, name='buy'), url(r'^oformlenya_zamovlenya/', views.OrderCreate, name='OrderCreate'), url(r'^dodaty_kvitku', views.flower_add, name='flower_add'), url(r'^redahuvaty/(?P<pk>\d+)/kvitku', views.flower_edit, name='flower_edit'), url(r'^vydalyty/(?P<pk>\d+)/kvitku', FlowerDelete.as_view(), name='flower_del'), url(r'^order/(?P<pk>\d+)/one/', views.one_order, name='one_order'), url(r'^add/(?P<flower_id>\d+)/$', views.CartAdd, name='CartAdd'), url(r'^ad/(?P<flower_id>\d+)/$', views.CartAdd_basket, name='CartAdd_basket'), url(r'^remove/(?P<flower_id>\d+)/$', views.CartRemove, name='CartRemove'), url(r'^search', views.search, name='search'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <file_sep>/shop/templates/shop/one_order.html {% extends 'shop/base.html' %} {% load static from staticfiles %} <title>{% block title %}Купівля насіння та саджанців квітів{% endblock title %}</title> {% block content %} <div id='one_order'> <table class="table"> <tbody> <tr> <td>імя</td> <td>{{ order.name }}</td> </tr> <tr> <td>телефон</td> <td>{{ order.number }}</td> </tr> <tr> <td>Додаткові нотатки</td> <td>{{ order.note }}</td> </tr> </tbody> </table> <table> <tbody> {% for item in products %} <tr> <td> {{item.product}} </td> <td> {{item.quantity}} </td> </tr> {% endfor %} </tbody> </table> </div> </div> {% endblock content %} <file_sep>/registration_user/models.py from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class StProfile(models.Model): user = models.OneToOneField(User) class Meta(object): verbose_name = _(u"User Profile") mobile_phone = models.CharField( max_length=12, blank=True, verbose_name=_(u"Mobile Phone"), ) lang = models.CharField( max_length=12, blank=True, verbose_name=_(u"lang"), ) def __unicode__(self): return self.user.username class logentry(models.Model): level = models.CharField( max_length=20, blank=False) asctime = models.DateTimeField( blank=False, null=True) module = models.CharField( max_length=100, blank=False,) message = models.TextField( blank=False,) def __unicode__(self): return u"%s %s %s %s" % (self.level, self.asctime, self.module, self.message)<file_sep>/shop/views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from .models import Flower from .models import Order, OrderItem from .util import basket_list from .util import flow_count_name from .util import suma from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.views.generic import UpdateView, CreateView, ListView, DeleteView from django.forms import ModelForm from django import forms from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import permission_required from time import time from .util import is_digit from datetime import datetime from .cart import Cart from .forms import CartAddProductForm from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger ########################################################################### def main_page(request): cart = Cart(request) flowers = Flower.objects.all() fl_count = flow_count_name(request) count = len(Cart(request)) # try to order flowers list order_by = request.GET.get('order_by', '') if order_by in ('price', '#'): flowers = flowers.order_by(order_by) if request.GET.get('reverse', '') == '1': flowers = flowers.reverse() #pagination paginator = Paginator(flowers, 4) page = request.GET.get('page') try: flowers = paginator.page(page) except PageNotAnInteger: flowers = paginator.page(1) except EmptyPage: flowers= paginator.page(paginator.num_pages) return render(request, 'shop/main.html', {'flowers':flowers, 'count': count, 'fl_count': fl_count, 'count': count, 'cart': cart}) def CartAdd(request, flower_id): cart = Cart(request) flower = get_object_or_404(Flower, id=flower_id) cart.add(flower=flower, quantity=1) return redirect('main') def CartAdd_basket(request, flower_id): cart = Cart(request) flower = get_object_or_404(Flower, id=flower_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(flower=flower, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('basket') def CartRemove(request, flower_id): cart = Cart(request) flower = get_object_or_404(Flower, id=flower_id) cart.remove(flower) return redirect('basket') def basket(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm( initial={ 'quantity': item['quantity'], 'update': True }) return render(request, 'shop/basket.html', {'cart': cart}) ##################################################################### def about_me(request): return render(request, 'shop/about.html', {}) #################################################################### def contacts(request): return render(request, 'shop/contacts.html', {}) #################################################################### @login_required def kabinet(request): return render(request, 'shop/cabinet.html', {}) ################################################################ #order_confirm def OrderCreate(request): cart = Cart(request) if request.method == 'POST': errors = {} data = {} # validate user input name = request.POST.get('name', '').strip() if not name: errors['name'] = u"Ім'я є обов'язковим" else: data['name'] = name number = request.POST.get('number', '').strip() if not number: errors['number'] = u"Номер телефону є обов'язковим" else: data['number'] = number notes = request.POST.get('notes', '').strip() if notes: data['notes'] = notes total_cost = request.POST.get('total_cost', '').strip() data['total_cost'] = total_cost if not errors: order = Order(**data) order.save() for item in cart: OrderItem.objects.create(order=order, product=item['flower'], price=item['price'], quantity=item['quantity']) cart.clear() return HttpResponseRedirect( u'%s?status_message=Замовлення успішно збережено!' % reverse('main')) else: return render(request, 'shop/ordering.html', {'errors': errors}) return render(request, 'shop/ordering.html', {'cart': cart}) ##################################################################### def one_flower(request, pk): flower = Flower.objects.filter(pk=pk) fl_count = flow_count_name(request) count = len(basket_list(request)) return render(request, 'shop/one_flower.html', {'flower':flower, 'count': count, 'fl_count': fl_count}) ###################################################################### @permission_required('auth.add_user') def orders(request): orders = Order.objects.all() return render(request, 'shop/orders.html', {'orders': orders}) ######################################################################### #flower_add def flower_add(request): # was form posted? if request.method == "POST": # was form add button clicked? if request.POST.get('add_button') is not None: # errors collection errors = {} # data for student object data = {} # validate user input title = request.POST.get('title', '').strip() if not title: errors['title'] = u"Ім'я є обов'язковим" else: data['title'] = title data['lat_title'] = time() price = request.POST.get('price', '').strip() if not price: errors['price'] = u"Ціна є обов'язковою" else: if is_digit(price) == 1: data['price'] = price else: errors['price'] = u"Введіть ціле число!" description = request.POST.get('description', '').strip() if not description: errors['description'] = u"Опис є обов'язковим" else: data['description'] = description photo_main = request.FILES.get('photo_main') if not photo_main: errors['photo_main'] = u"Одне фото є обов'язковим" else: data['photo_main'] = photo_main photo_big = request.FILES.get('photo_big') if photo_big: data['photo_big'] = photo_big # save flovwer if not errors: flower = Flower(**data) flower.save() # redirect to students list return HttpResponseRedirect( u'%s?status_message=Квітку успішно додано!' % reverse('main')) else: # render form with errors and previous user input return render(request, 'shop/flower_add.html', {'errors': errors}) elif request.POST.get('cancel_button') is not None: # redirect to home page on cancel button return HttpResponseRedirect( u'%s?status_message=Додавання квітки скасовано!' % reverse('main')) else: # initial form render return render(request, 'shop/flower_add.html', {}) ##################################################################### #flower_edit def flower_edit(request, pk): flower = Flower.objects.filter(pk=pk) if request.method == "POST": data = Flower.objects.get(pk=pk) if request.POST.get('add_button') is not None: errors = {} title = request.POST.get('title', '').strip() if not title: errors['title'] = u"Імʼя є обовʼязковим." else: data.title = title data.lat_title = time() price = request.POST.get('price', '').strip() if not price: errors['price'] = u"Ціна є обов'язковою" else: if is_digit(price) == 1: data.price = price else: errors['price'] = u"Введіть ціле число!" description = request.POST.get('description', '').strip() if not description: errors['description'] = u"Опис є обов'язковим" else: data.description = description photo_main = request.FILES.get('photo_main') if not photo_main: errors['photo_main'] = u"Одне фото є обов'язковим" else: data.photo_main = photo_main photo_big = request.FILES.get('photo_big') if photo_big: data.photo_big = photo_big if errors: return render(request, 'shop/flower_edit.html', {'pk': pk, 'flower': data, 'errors': errors}) else: data.save() return HttpResponseRedirect(u'%s?status_message=Редагування квітки завершено' % reverse('main')) elif request.POST.get('cancel_button') is not None: return HttpResponseRedirect(u'%s?status_message=Редагування квітки скасовано!' % reverse('main')) else: return render(request, 'shop/flower_edit.html', {'pk': pk, 'flower': flower[0]}) ######################################## #flower delete class FlowerDelete(DeleteView): model = Flower template_name = 'shop/flower_delete.html' def get_success_url(self): return u'%s?status_message=Квітку успішно видалено!' % reverse('main') def post(self, request, *args, **kwargs): if request.POST.get('no_delete_button'): return HttpResponseRedirect(u'%s?status_message=Видалення квітки відмінено!'% reverse('main')) else: return super(FlowerDelete, self).post(request, *args, **kwargs) @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(FlowerDelete, self).dispatch(*args, **kwargs) ############################################################################### def one_order(request, pk): order = Order.objects.get(pk=pk) products = OrderItem.objects.filter(order=order) return render(request, 'shop/one_order.html', {'order':order, 'products': products}) ############################################################################### def search(request): errors = {} title = request.POST.get('search', '').strip() if not title: errors['title'] = u"Введіть назву квітки" flw = Flower.objects.filter(title=title) if title: return render(request, 'shop/one_flower.html', {'flower':flw, 'errors': errors }) else: return render(request, 'shop/no_one_flower.html', {}) <file_sep>/shop/context_processors.py from .util import basket_list from .cart import Cart from .util import get_lang def buy_processor(request): return {'buy_status': basket_list(request)} def cart(request): return {'cart': Cart(request)} #select language def lang_processor(request): return {'PK': get_lang(request)} <file_sep>/shop/static/js/main.js function to_basket() { $('button.to_basket').click(function(event){ var flow = $(this).val(); $.cookie(flow, flow, {'path': '/'}); location.reload(true); return true; }); } function from_basket() { $('button.from_basket').click(function(event){ var flow = $(this).val(); $.removeCookie(flow, {'path': '/'}); location.reload(true); return false; }); } function basket_form() { $('a.buy_ajax').click(function(event){ var link = $(this); $.ajax({ 'url': link.attr('href'), 'dataType': 'html', 'type': 'get', 'success': function(data, status, xhr){ if (status != 'success') { alert('Помилка на сервері. Спробуйте будь-ласка пізніше.'); return false; } var modal = $('#myModal'), html = $(data), form = html.find('#myform'); modal.find('.modal-title').html(html.find('#basket_title').text()); modal.find('.modal-body').html(form); modal.modal('show'); } }); return false; }); } function initLangSelector() { $('#lang-selector select').change(function(event){ var lan = $(this).val(); if (lan) { $.cookie('django_language', lan, {'path': '/', 'expires': 365}); } else { $.removeCookie('django_language', {'path': '/'}); } location.reload(true); return true; }); } $(document).ready(function(){ to_basket(); from_basket(); basket_form(); initLangSelector() });<file_sep>/shop/migrations/0005_auto_20170821_1359.py # -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-08-21 13:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0004_order_total_cost'), ] operations = [ migrations.AlterField( model_name='order', name='total_cost', field=models.CharField(max_length=256), ), ]
c3db5ff77292694e2128693949c7454ae8868639
[ "JavaScript", "Python", "HTML" ]
8
Python
smolynets/kvitka_final
b76dbbc43801cdbd63b7f9972c3d9eaea2e8ae87
f136f4fa1a8f44fbb301af6f03174523f3693be1
refs/heads/master
<file_sep>{% extends "base.html" %} {% block content %} <table class="table table-hover"> <thead> <tr scope = "col"> <th> ID </th> <th>Name </th> <th>Asset </th> <th>Department </th> <th> Time_from </th> <th>Time_to </th> <th>Date </th> <th>Action </th> </tr> </thead> <tbody> {% for delay in delays %} <tr class="active-row"> <td>{{delay.id}}</td> <td>{{delay.name}}</td> <td>{{Asset.query.filter_by(id = delay.asset_id).first().name }}</td> <td>{{Department.query.filter_by(id = delay.department_id).first().department}}</td> <td>{{delay.time_from}}</td> <td>{{delay.time_to}}</td> <td>{{delay.date}}</td> <td>{{delay.action}}</td> <td> <form method="post"> {{ delete_form.csrf_token }} {{ delete_form.delete_id(value=delay.id) }} {{ delete_form.delete(class="btn btn-danger") }} </form> </td> {% endfor %} </tbody> </table> {% endblock %}<file_sep>from flask import render_template, url_for, flash, redirect, request from app.forms import DelayForm, AssetForm, DeleteForm, WaterForm from app import app, db from app.models import Location, Asset, Department, Delayance, Water, Water_Type, Area @app.route('/', methods=['GET', 'POST']) def delay(): form = DelayForm() if form.validate_on_submit(): ass = form.asset.data # asset = Asset.query.filter_by(name=ass).first() delay = Delayance(name=form.name.data, asset=ass, department=form.department.data, time_from = form.time_from.data, time_to = form.time_to.data, date=form.date.data, action = form.action_taken.data) db.session.add(delay) db.session.commit() flash(f'Delay has been added to the database', 'Success') return redirect(url_for('delay')) return render_template('delay.html', title='Delay', form=form) @app.route('/asset', methods=['GET', 'POST']) def assets(): form = AssetForm() if form.validate_on_submit(): assets = Asset(name=form.asset.data, asset_type = form.asset_type.data, location=form.location.data) db.session.add(assets) db.session.commit() flash(f'Asset has been added to the database', 'Success') return redirect(url_for('assets')) return render_template('asset.html', title='Delay', form=form) @app.route('/delete', methods=['GET', 'POST']) def listing(): delete_form = DeleteForm() delays = Delayance.query.order_by(Delayance.id.desc()).limit(10).all() if delete_form.validate_on_submit(): entry_to_delete = Delayance.query.get(delete_form.delete_id.data) db.session.delete(entry_to_delete) db.session.commit() flash("Delay has been removed from the Database") return redirect(url_for("listing")) return render_template('list.html', title='List', delays=delays, Asset=Asset, Department=Department, delete_form=delete_form) @app.route('/water', methods=['GET', 'POST']) def water(): form = WaterForm() if form.validate_on_submit(): jimi = Water(asset_id = 1, water_id=1, area_id = 7, volume=form.raw_water.data , date= form.date.data) biney = Water(asset_id = 3, water_id=2, area_id = 1, volume=form.biney.data, date= form.date.data) toytown = Water(asset_id = 3, water_id=2, area_id =2 , volume=form.toytown.data, date= form.date.data) monsi_valley = Water(asset_id =3, water_id=2, area_id =3, volume=form.monsi_valley.data, date= form.date.data) sam_jonah = Water(asset_id = 2, water_id=2, area_id = 5, volume=form.sam_jonah.data, date= form.date.data) bill_hussey = Water(asset_id =2 , water_id=2, area_id = 4, volume=form.bill_hussey.data, date= form.date.data) old_anyinam= Water(asset_id =2 , water_id=2, area_id = 6, volume=form.old_anyinam.data, date= form.date.data) db.session.add(jimi) db.session.add(biney) db.session.add(toytown) db.session.add(monsi_valley) db.session.add(sam_jonah) db.session.add(bill_hussey) db.session.add(old_anyinam) db.session.commit() flash("Data has been removed from the Database") return redirect(url_for("water")) return render_template('water.html', form=form) @app.route('/water_list', methods=['GET', 'POST']) def waters(): delete_form=DeleteForm() records = Water.query.order_by(Water.id.desc()).limit(10).all() if delete_form.validate_on_submit(): entry_to_delete = Water.query.get(delete_form.delete_id.data) db.session.delete(entry_to_delete) db.session.commit() flash("Record has been removed from the Database") return redirect(url_for("home")) return render_template('water_list.html', title='Water list', records=records, Asset=Asset, delete_form=delete_form,Area =Area, Water_Type=Water_Type) @app.route('/api/v1/') def myendpoint(): return 'We are computering now'<file_sep>from flask_wtf import FlaskForm from wtforms_sqlalchemy.fields import QuerySelectField from wtforms import StringField, SubmitField, BooleanField, IntegerField, FloatField, HiddenField from wtforms.fields.html5 import DateField, TimeField from wtforms.validators import DataRequired from app.models import Location, Asset, Asset_Type, Department, Delayance, Area, Water, Water_Type def department_query(): return Department.query def asset_type_query(): return Asset_Type.query def location_query(): return Location.query def asset_query(): return Asset.query class DelayForm(FlaskForm): name = StringField('DELAY', validators=[DataRequired()]) asset = QuerySelectField(query_factory = asset_query, allow_blank=False, get_label='name', validators=[DataRequired()]) department = QuerySelectField(query_factory = department_query, allow_blank=False, get_label='department', validators=[DataRequired()]) time_from = TimeField('START TIME', validators=[DataRequired()]) time_to = TimeField('STOP TIME', validators=[DataRequired()]) date = DateField('DATE', validators=[DataRequired()] ) action_taken = StringField('ACTION TAKEN') submit = SubmitField('SUBMIT') class AssetForm(FlaskForm): asset = StringField('NAME', validators=[DataRequired()]) asset_type = QuerySelectField(query_factory = asset_type_query, allow_blank=False, get_label='asset_type', validators=[DataRequired()]) location = QuerySelectField(query_factory = location_query, allow_blank=False, get_label='location', validators=[DataRequired()]) submit = SubmitField('SUBMIT') class DeleteForm(FlaskForm): delete_id = HiddenField("Hidden table row ID") delete = SubmitField("Delete") class WaterForm(FlaskForm): raw_water = FloatField('RAW WATER') biney = FloatField('Biney Estate') toytown = FloatField('Toy Town') monsi_valley = FloatField('Monsi Valley') sam_jonah = FloatField('<NAME> ') bill_hussey = FloatField('<NAME>') old_anyinam = FloatField('Old Anyinam') date = DateField('Date', validators=[DataRequired()]) submit = SubmitField('Sumbit') <file_sep>from flask import Flask from flask_sqlalchemy import SQLAlchemy from waitress import serve app = Flask(__name__, instance_relative_config=False) app.config['SECRET_KEY'] = '<KEY>' app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:STpass@9@localhost/report' db = SQLAlchemy(app) # Import parts of our core Flask app from app import routes<file_sep>from app import db from datetime import datetime class Location(db.Model): __tablename__ = 'location' id = db.Column(db.Integer, primary_key=True) location = db.Column(db.String(60), unique=True, nullable=False) place = db.relationship('Asset', backref='location') def __repr__(self): return f"Location('{self.location}')" class Asset_Type (db.Model): __tablename__ = 'asset_type' id = db.Column(db.Integer, primary_key=True) asset_type = db.Column(db.String(60), unique=False, nullable=False) types = db.relationship('Asset', backref='asset_type') def __repr__(self): return f"Asset_Type('{self.asset_type}')" class Asset(db.Model): __tablename__ = 'asset' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(60), unique=True, nullable=False) asset_type_id = db.Column(db.Integer, db.ForeignKey('asset_type.id'), unique=False, nullable=False) location_id = db.Column(db.Integer, db.ForeignKey('location.id'), unique=False, nullable=False) asset_delay = db.relationship('Delayance', backref='asset') water_asset = db.relationship('Water', backref = 'water_asset') def __repr__(self): return f"Asset('{self.name}')" class Department(db.Model): __tablename__ = 'department' id = db.Column(db.Integer, primary_key=True) department = db.Column(db.String(60), unique=True, nullable=False) dept = db.relationship('Delayance', backref='department') def __repr__(self): return f"Department('{self.department}')" class Delayance (db.Model): __tablename__ = 'delayance' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False) asset_id = db.Column(db.Integer, db.ForeignKey('asset.id'), unique=False, nullable=False) department_id = db.Column(db.Integer, db.ForeignKey('department.id'), unique=False, nullable=False) time_from = db.Column(db.Time, nullable=False) time_to = db.Column(db.Time, nullable=False) date = db.Column(db.Date, nullable = False) action = db.Column(db.String(200), unique=False, nullable=True) date_created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) def __repr__(self): return f"Delayance('{self.name}','{self.time_from}', '{self.time_to}', '{self.date}', '{self.action}')" class Water_Type(db.Model): __tablename__ = 'water_type' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20), unique=True, nullable=False) types = db.relationship('Water', backref='type') def __repr__(self): return f"Water_Type('{self.name})" class Area(db.Model): __tablename__ = 'area' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(60), unique=False, nullable=True) area = db.relationship('Water', backref='area') def __repr__(self): return f"Area('{self.area}')" class Water(db.Model): __tablename__ = 'water' id = db.Column(db.Integer, primary_key=True) asset_id = db.Column(db.Integer, db.ForeignKey('asset.id'), unique=False, nullable=False) water_id= db.Column(db.Integer, db.ForeignKey('water_type.id'), unique=False, nullable=False) area_id = db.Column(db.Integer, db.ForeignKey('area.id'), unique=False, nullable=False) volume = db.Column(db.Float, unique=False, nullable=True ) date = db.Column(db.Date, nullable = False) def __repr__(self): return f"Water('{self.volume}', '{self.date}')"
047d0e827f1b9173bb2db9b1f3811fb6beed19e0
[ "Python", "HTML" ]
5
HTML
daniel-stephens/availability_report
8687e5ddcc1dd2be2508bb474e18826314aaa231
c5623775f834a2866b56eeba0b755e4577263b45
refs/heads/master
<repo_name>aayushKhandpur/creativei_inquiry_client<file_sep>/src/app/app.component.ts import { Component, ViewChild } from '@angular/core'; import { Nav, Platform } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { InqProvider } from '../providers/inq/inq'; import { FollowUpProvider } from '../providers/follow-up/follow-up'; import { HomePage } from '../pages/home/home'; import { CounselorDashboardPage } from '../pages/counselor/home/home'; import { InqListPage } from '../pages/counselor/inq-list/inq-list'; @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any = HomePage; visitorPages: Array<{title: string, component: any}>; counselorPages: Array<{title: string, component: any}>; user: String = "Admin" constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, private inqProvider: InqProvider, private followUpProvider: FollowUpProvider) { this.initializeApp(); // used for an example of ngFor and navigation this.visitorPages = [ { title: 'Home', component: HomePage }, ]; this.counselorPages = [ { title: 'Dashboard', component: CounselorDashboardPage}, { title: 'Inquiries', component: InqListPage}, { title: 'Logout', component: HomePage} ]; } initializeApp() { this.platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. this.statusBar.styleDefault(); this.splashScreen.hide(); //Getting all the enum values for the application here this.inqProvider.getEnums(); this.followUpProvider.getEnums(); }); } openPage(page) { // Reset the content nav to have just this page // we wouldn't want the back button to show in this scenario this.nav.setRoot(page.component); } } <file_sep>/src/pages/counselor/inq-close-modal/inq-close-modal.ts import { Component } from '@angular/core'; import { NavController, NavParams, ViewController } from 'ionic-angular'; import { FormGroup } from '@angular/forms'; import { FormBuilder } from '@angular/forms'; import { Validators } from '@angular/forms'; import { FollowUpProvider } from '../../../providers/follow-up/follow-up' @Component({ selector: 'page-inq-close-modal', templateUrl: 'inq-close-modal.html', }) export class InqCloseModalPage { private enums; private closingStatus; private closingSubStatus; private inqCloseForm: FormGroup constructor(public navCtrl: NavController, public navParams: NavParams, private view: ViewController,private formBuilder: FormBuilder,private followUpProvider: FollowUpProvider) { this.inqCloseForm = this.formBuilder.group({ closingStatus: ['', Validators.required], closingSubStatus: ['', Validators.required], closingRemark: [''] }); this.setEnums(); this.setClosingStatus(); this.setClosingSubStatus(); } ionViewDidLoad() { console.log('ionViewDidLoad InqCloseModalPage'); } closeInquiry(){ if(this.inqCloseForm.valid){ console.log(this.inqCloseForm.value); this.view.dismiss(this.inqCloseForm.value); } } closeModal(){ this.view.dismiss(null); } setEnums(){ this.enums = this.followUpProvider.getEnums(); } setClosingStatus(){ this.closingStatus = this.enums.data.followUpStatus; } setClosingSubStatus(){ this.closingSubStatus = this.enums.data.followUpSubStatus; } } <file_sep>/src/pages/counselor/follow-up-modal/follow-up-modal.ts import { Component } from '@angular/core'; import { NavController, NavParams, ViewController } from 'ionic-angular'; import { FormGroup } from '@angular/forms'; import { FormBuilder } from '@angular/forms'; import { Validators } from '@angular/forms'; import { DatePipe } from '@angular/common'; import { FollowUpProvider } from '../../../providers/follow-up/follow-up' import { NotificationProvider } from '../../../providers/notification/notification'; import { NotificationMessageProvider } from '../../../providers/notification-message/notification-message'; import { HelperProvider } from '../../../providers/helper/helper'; @Component({ selector: 'page-follow-up-modal', templateUrl: 'follow-up-modal.html', }) export class FollowUpModalPage { private enums; private followUpStatus; private subStatus; private followUpType; private caseIndex; private inquiryId; private inquiryName; private currentFollowUp; private followUpForm: FormGroup constructor(public navCtrl: NavController, public navParams: NavParams, private view: ViewController,private formBuilder: FormBuilder,private followUpProvider: FollowUpProvider, private notify: NotificationProvider, private message: NotificationMessageProvider, private datePipe: DatePipe, private helper: HelperProvider) { this.followUpForm = this.formBuilder.group({ followUpType: ['', Validators.required], followUpStatus: ['', Validators.required], remark: [''], caseIndex: ['', Validators.required], subStatus: ['', Validators.required] }); this.inquiryId = this.navParams.get('id'); this.inquiryName = this.navParams.get('name'); this.patchForm(); this.setEnums(); this.setFollowUpStatus(); this.setSubStatus(); this.setFollowUpType(); this.setCaseIndex(); } ionViewDidLoad() { console.log('ionViewDidLoad FollowUpModalPage'); } logForm(){ if(!this.currentFollowUp){ if(this.followUpForm.valid){ let request = this.followUpForm.value; request.inquiryId = this.inquiryId; request.followUpDate = this.getToday(); console.log(request); this.followUpProvider.create(request) .subscribe( data => { let response: any = data; if(response.data){ this.notify.showInfo("Follow up created successfully"); console.log("Follow up creation successful, the response data is:", data); }else if(response.exception){ this.notify.showError("Follow up creation failed"); console.log("Follow up creation failed, the response data is:", data); } }, error => {console.log("POST unsuccessful, the server returned this error:", error);}, () => { console.log("Complete"); this.view.dismiss(this.followUpForm.value); } ) } }else if(this.currentFollowUp){ if(this.followUpForm.valid){ let request = this.followUpForm.value; request.id = this.currentFollowUp.id; request.inquiryId = this.inquiryId; request.followUpDate = this.getToday(); console.log(request); this.followUpProvider.update(request) .subscribe( data => { let response: any = data; if(response.data){ this.notify.showInfo("Follow up updated successfully"); console.log("Follow up updation successful, the response data is:", data); }else if(response.exception){ this.notify.showError("Follow up updation failed"); console.log("Follow up updation failed, the response data is:", data); } }, error => {console.log("POST unsuccessful, the server returned this error:", error);}, () => { console.log("Complete"); this.view.dismiss(this.followUpForm.value); } ) } } } patchForm(){ if(this.navParams.get('followUp')){ this.currentFollowUp = this.navParams.get('followUp'); let patch = this.helper.removeEmptyFromObject(this.currentFollowUp); this.followUpForm.patchValue(patch); } } closeModal(){ this.view.dismiss(null); } getToday(){ return this.datePipe.transform(Date.now(),'yyyy-MM-dd'); } setEnums(){ this.enums = this.followUpProvider.getEnums(); } setFollowUpStatus(){ this.followUpStatus = this.enums.data.followUpStatus; } setSubStatus(){ this.subStatus = this.enums.data.followUpSubStatus; } setFollowUpType(){ this.followUpType = this.enums.data.followUpType; } setCaseIndex(){ this.caseIndex = this.enums.data.caseIndex; } } <file_sep>/src/pages/counselor/home/home.ts import { Component } from '@angular/core'; import { NavController, ModalController } from 'ionic-angular'; import { HelperProvider } from '../../../providers/helper/helper'; import { InqDetailsPage } from '../inq-details/inq-details'; import { InqProvider } from '../../../providers/inq/inq'; import { ReminderProvider } from '../../../providers/reminder/reminder'; import { ReminderModalPage } from '../reminder-modal/reminder-modal'; import { NotificationProvider } from '../../../providers/notification/notification'; import { NotificationMessageProvider } from '../../../providers/notification-message/notification-message'; import { InqSummaryPage } from '../inq-summary/inq-summary'; import { SortProvider } from '../../../providers/sort/sort'; import { QuoteProvider } from '../../../providers/quote/quote'; @Component({ selector: 'page-counselor-dashboard', templateUrl: 'home.html' }) export class CounselorDashboardPage { private activeMenu: string = "counselor"; private responseData; private unattendedInq; private inqStats; private todos; private quote; today = Date.now(); constructor(public navCtrl: NavController, private inqProvider: InqProvider, private reminderProvider: ReminderProvider, private helper: HelperProvider, private sort: SortProvider, private quoteProvider: QuoteProvider, private notify: NotificationProvider, private message: NotificationMessageProvider, private modalCtrl: ModalController) { this.helper.setActiveMenu(this.activeMenu); this.getUnattendedInq(); this.getInqStats(); this.getTodo(); this.getQuote(); } createInq(){ this.navCtrl.push(InqDetailsPage); } viewInq(id){ this.navCtrl.push(InqSummaryPage,id); } getUnattendedInq(){ this.inqProvider.getUnattendedInquiries() .subscribe( data => {this.responseData = data}, error => {console.log("GET unsucessful, the server returned this error: ",error)}, () => { this.unattendedInq = this.sort.byString(this.responseData.data,'inquiryDate','descending'); console.log("GET complete"); } ) } getInqStats(){ this.inqProvider.getInquiryStats() .subscribe( data => {this.responseData = data}, error => {console.log("GET unsucessful, the server returned this error: ",error)}, () => { this.inqStats = this.responseData.data; console.log("GET complete"); } ) } getTodo(){ this.reminderProvider.getReminderForToday() .subscribe( data => {this.responseData = data}, error => {console.log("GET unsucessful, the server returned this error: ",error)}, () => { this.todos = this.responseData.data; console.log("GET complete"); } ) } getQuote(){ this.quote = this.quoteProvider.getQuote(); } showAddReminderModal(){ let modal = this.modalCtrl.create( ReminderModalPage ) modal.present(); modal.onDidDismiss(data =>{ if(data){ console.log(data); } }); } showViewReminderModal(reminder){ let modal = this.modalCtrl.create( ReminderModalPage, {reminder: reminder,view: "true"} ) modal.present(); modal.onDidDismiss(data =>{ if(data){ console.log(data); } }); } } <file_sep>/src/providers/reminder/reminder.ts import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { DatePipe } from '@angular/common'; @Injectable() export class ReminderProvider { private baseUrl: string = 'http://localhost:9002/reminder'; constructor(public http: HttpClient, private datePipe: DatePipe) { console.log('Hello ReminderProvider Provider'); } create(data){ return this.http.post(this.baseUrl+'/create', data); } update(data){ return this.http.post(this.baseUrl+'/update', data); } getReminderForToday(){ let today = this.datePipe.transform(Date.now(), 'yyyy-MM-dd'); return this.http.get(this.baseUrl+'/getByDate',{ params: new HttpParams().set('from',today).set('to',today) }) } getReminderForRange(from,to){ return this.http.get(this.baseUrl+'/getByDate',{ params: new HttpParams().set('from',from).set('to',to) }) } } <file_sep>/src/pages/counselor/reminder-modal/reminder-modal.ts import { Component } from '@angular/core'; import { NavController, NavParams, ViewController } from 'ionic-angular'; import { FormGroup } from '@angular/forms'; import { FormBuilder } from '@angular/forms'; import { Validators } from '@angular/forms'; import { ReminderProvider } from '../../../providers/reminder/reminder' import { HelperProvider } from '../../../providers/helper/helper'; import { NotificationProvider } from '../../../providers/notification/notification'; @Component({ selector: 'page-reminder-modal', templateUrl: 'reminder-modal.html', }) export class ReminderModalPage { private reminderId; private currentReminder; private canEdit = true; private reminderForm: FormGroup constructor(public navCtrl: NavController, public navParams: NavParams, private view: ViewController,private formBuilder: FormBuilder,private reminderProvider: ReminderProvider, private helper: HelperProvider, private notify: NotificationProvider) { this.reminderForm = this.formBuilder.group({ title: ['', Validators.required], description: [''], time: ['', Validators.required] }); this.reminderId = this.navParams.get('id'); if(this.navParams.get('view')) this.canEdit = false; this.patchForm(); } ionViewDidLoad() { console.log('ionViewDidLoad ReminderModalPage'); } logForm(){ if(!this.currentReminder){ if(this.reminderForm.valid){ let request = this.reminderForm.value; console.log(request); this.reminderProvider.create(request) .subscribe( data => { let response: any = data; if(response.data){ this.notify.showInfo("Reminder created successfully"); console.log("Reminder creation successful, the response data is:", data); }else if(response.exception){ this.notify.showError("Reminder creation failed"); console.log("Reminder creation failed, the response data is:", data); } }, error => {console.log("POST unsuccessful, the server returned this error:", error);}, () => { console.log("Complete"); this.view.dismiss(this.reminderForm.value); } ) } }else if(this.currentReminder){ if(this.reminderForm.valid){ let request = this.reminderForm.value; request.id = this.currentReminder.id; console.log(request); this.reminderProvider.update(request) .subscribe( data => { let response: any = data; if(response.data){ this.notify.showInfo("Reminder updated successfully"); console.log("Reminder updation successful, the response data is:", data); }else if(response.exception){ this.notify.showError("Reminder updation failed"); console.log("Reminder updation failed, the response data is:", data); } }, error => {console.log("POST unsuccessful, the server returned this error:", error);}, () => { console.log("Complete"); this.view.dismiss(this.reminderForm.value); } ) } } } closeModal(){ this.view.dismiss(null); } patchForm(){ if(this.navParams.get('reminder')){ this.currentReminder = this.navParams.get('reminder'); let patch = this.helper.removeEmptyFromObject(this.currentReminder); this.reminderForm.patchValue(patch); } } toggleEdit(){ this.canEdit = !this.canEdit; } } <file_sep>/src/providers/notification/notification.ts import { Injectable } from '@angular/core'; import { ToastController, Toast } from 'ionic-angular'; @Injectable() export class NotificationProvider { private toast: Toast; constructor(public toastCtrl: ToastController) { console.log('Hello NotificationProvider Provider'); } showInfo(message) { try { this.toast.dismiss(); } catch(e) {} this.toast = this.toastCtrl.create({ message: message, position: "top", showCloseButton: true, closeButtonText: "X", cssClass: 'info-notification', dismissOnPageChange: true }); console.log('Info Toast Presented'); this.toast.present(); } showError(message) { try { this.toast.dismiss(); } catch(e) {} this.toast = this.toastCtrl.create({ message: message, position: "top", showCloseButton: true, closeButtonText: "X", cssClass: 'error-notification', dismissOnPageChange: true }); console.log('Error Toast Presented'); this.toast.present(); } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { DatePipe } from '@angular/common'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { Ng2CompleterModule } from "ng2-completer"; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { InqFormPersonalPage } from '../pages/visitor/inq-form-personal/inq-form-personal'; import { InqFormEducationGuardianPage } from '../pages/visitor/inq-form-education-guardian/inq-form-education-guardian'; import { InqFormMarketingPage } from '../pages/visitor/inq-form-marketing/inq-form-marketing'; import { ThankyouPage } from '../pages/visitor/thankyou/thankyou'; import { CounselorDashboardPage } from '../pages/counselor/home/home'; import { InqDetailsPage } from '../pages/counselor/inq-details/inq-details'; import { InqListPage } from '../pages/counselor/inq-list/inq-list'; import { InqSummaryPage } from '../pages/counselor/inq-summary/inq-summary'; import { InqCloseModalPage } from '../pages/counselor/inq-close-modal/inq-close-modal'; import { FollowUpModalPage } from '../pages/counselor/follow-up-modal/follow-up-modal'; import { ReminderModalPage } from '../pages/counselor/reminder-modal/reminder-modal'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { InqProvider } from '../providers/inq/inq'; import { NotificationProvider } from '../providers/notification/notification'; import { LocalityProvider } from '../providers/locality/locality'; import { NotificationMessageProvider } from '../providers/notification-message/notification-message'; import { HelperProvider } from '../providers/helper/helper'; import { FollowUpProvider } from '../providers/follow-up/follow-up'; import { AuthProvider } from '../providers/auth/auth'; import { ReminderProvider } from '../providers/reminder/reminder'; import { SortProvider } from '../providers/sort/sort'; import { QuoteProvider } from '../providers/quote/quote'; @NgModule({ declarations: [ MyApp, HomePage, InqFormPersonalPage, InqFormEducationGuardianPage, InqFormMarketingPage, InqDetailsPage, InqListPage, InqSummaryPage, ThankyouPage, InqCloseModalPage, CounselorDashboardPage, FollowUpModalPage, ReminderModalPage ], imports: [ BrowserModule, HttpClientModule, Ng2CompleterModule, IonicModule.forRoot(MyApp), ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage, InqFormPersonalPage, InqFormEducationGuardianPage, InqFormMarketingPage, InqDetailsPage, InqListPage, InqSummaryPage, ThankyouPage, InqCloseModalPage, CounselorDashboardPage, FollowUpModalPage, ReminderModalPage ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler}, DatePipe, InqProvider, NotificationProvider, LocalityProvider, NotificationMessageProvider, HelperProvider, FollowUpProvider, AuthProvider, ReminderProvider, SortProvider, QuoteProvider ] }) export class AppModule {} <file_sep>/src/providers/follow-up/follow-up.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable() export class FollowUpProvider { private baseUrl: string = 'http://localhost:9002/follow-up'; private enums; constructor(public http: HttpClient) { console.log('Hello FollowUpProvider Provider'); } setEnums(){ this.http.get(this.baseUrl+'/server-info') .subscribe( data => {this.enums = data}, error => {console.log("Error getting enums")}, () => {console.log("Set enum complete")} ); } getEnums(){ if(this.enums){ return this.enums; }else{ this.setEnums(); return this.enums; } } create(data){ return this.http.post(this.baseUrl+'/create',data); } update(data){ return this.http.post(this.baseUrl+'/update',data); } } <file_sep>/src/pages/home/home.ts import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { CounselorDashboardPage } from '../counselor/home/home'; import { InqFormPersonalPage } from '../visitor/inq-form-personal/inq-form-personal'; import { AuthProvider } from '../../providers/auth/auth'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { private isLogin: boolean = false; private loginForm: FormGroup; constructor(public navCtrl: NavController, private auth: AuthProvider, private formBuilder: FormBuilder) { this.loginForm = this.formBuilder.group({ id: ['',Validators.required], password: ['',Validators.required] }); } login(){ if(this.auth.login(this.loginForm.value.id, this.loginForm.value.password)){ this.goToCounselorDash(); } } goToCounselorDash(){ this.navCtrl.setRoot(CounselorDashboardPage, {}, {animate: true, direction: 'forward'}); } goToVisitorPage(){ this.navCtrl.setRoot(InqFormPersonalPage, {}, {animate: true, direction: 'forward'}); } toggleLogin(){ this.isLogin = !this.isLogin; } } <file_sep>/src/providers/notification-message/notification-message.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable() export class NotificationMessageProvider { constructor(public http: HttpClient) { console.log('Hello NotificationMessageProvider Provider'); } INQUIRY = { REGISTER : { SUCCESS : "Inquiry Registered Successfully", FAILURE : "Server retutned an error. Cannot register inquiry." }, UPDATE : { SUCCESS : "Inquiry Updated Successfully", FAILURE : "Server retutned an error. Cannot update inquiry." } } FORM = { INVALID : "Invalid or missing inquiry details." } } <file_sep>/src/pages/counselor/inq-list/inq-list.ts import { Component } from '@angular/core'; import { NavController, NavParams, LoadingController, ModalController } from 'ionic-angular'; import { InqProvider } from '../../../providers/inq/inq'; import { HelperProvider } from '../../../providers/helper/helper'; import { SortProvider } from '../../../providers/sort/sort'; import { InqDetailsPage } from '../inq-details/inq-details'; import { InqSummaryPage } from '../inq-summary/inq-summary'; import { FollowUpModalPage } from '../follow-up-modal/follow-up-modal'; @Component({ selector: 'page-inq-list', templateUrl: 'inq-list.html', }) export class InqListPage { private inquiries; private sortedInquiries; private responseData; private sortBy; constructor(public navCtrl: NavController, public navParams: NavParams, private loadingCtrl: LoadingController, private inqProvider: InqProvider, private helper: HelperProvider, private sort: SortProvider, private modalCtrl: ModalController) { this.getAllInq(); this.sortBy = { id : { bool : false, ascending : false, descending : false }, caseIndex : { bool : false, ascending : false, descending : false }, name : { bool : false, ascending : false, descending : false }, inquiryDate : { bool : false, ascending : false, descending : false }, areaOfInterest : { bool : false, ascending : false, descending : false } } } ionViewDidLoad() { console.log('ionViewDidLoad InqListPage'); } private loading; presentLoadingCustom() { this.loading = this.loadingCtrl.create({ spinner: 'hide', content: ` <img src="../../assets/imgs/loading.svg" /> ` }); this.loading.onDidDismiss(() => { console.log('Dismissed loading'); }); this.loading.present(); } getAllInq(){ this.presentLoadingCustom(); this.inqProvider.getAllInq() .subscribe( data => { this.responseData = data; }, error => { console.log("GET unsucessful, the server returned this error:", error), this.loading.dismissAll(); }, () => { console.log("complete"); this.loading.dismissAll(); this.inquiries = this.responseData.data; } ) } editInq(id){ this.navCtrl.push(InqDetailsPage,id); } viewInq(id){ this.navCtrl.push(InqSummaryPage,id); } toggleSeeMore(i){ this.inquiries[i].seeMore = !this.inquiries[i].seeMore; } defaultSortingCase(object){ Object.keys(object).forEach(key => { object[key]['bool'] = false; object[key]['ascending'] = false; object[key]['descending'] = false; }) } toggleSort(sortByThis){ if(!this.sortBy[sortByThis]['bool']){ this.defaultSortingCase(this.sortBy); this.sortBy[sortByThis]['bool'] = true; this.sortBy[sortByThis]['ascending'] = true; this.sortInqList(this.inquiries,sortByThis,'ascending'); }else{ if(this.sortBy[sortByThis]['ascending']) this.sortInqList(this.inquiries,sortByThis,'descending'); this.sortBy[sortByThis]['ascending'] = !this.sortBy[sortByThis]['ascending'] if(this.sortBy[sortByThis]['descending']) this.sortInqList(this.inquiries,sortByThis,'ascending'); this.sortBy[sortByThis]['descending'] = !this.sortBy[sortByThis]['descending'] } } sortInqList(data,field,order){ if(field != 'followUpDetails' && field != 'caseIndex'){ this.sortedInquiries = this.sort.byString(data,field,order); } } filterInqByDate(from,to){ this.inquiries = this.inquiries.filter(inq => inq.inquiryDate >= from && inq.inquiryDate <= to); console.log(this.inquiries); } openFollowUpModal(id,name){ let modal = this.modalCtrl.create( FollowUpModalPage, {id: id, name: name} ) modal.present(); modal.onDidDismiss(data =>{ if(data){ console.log(data); } }); } } <file_sep>/src/providers/locality/locality.ts import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable() export class LocalityProvider { private baseUrl: string = 'http://localhost:9002/locality'; constructor(public http: HttpClient) { console.log('Hello LocalityProvider Provider'); } getLocality(pincode){ return this.http.get(this.baseUrl+'/pincode', { params: new HttpParams().set('pincode', pincode) }); } } <file_sep>/src/providers/inq/inq.ts import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable() export class InqProvider { private baseUrl: string = 'http://localhost:9002/inquiry'; private enums; constructor(public http: HttpClient,) { console.log('Hello InqProvider Provider'); } getInqById(id){ return this.http.get(this.baseUrl+'/getById',{ params: new HttpParams().set('id', id) }); } getInqByStatus(status){ return this.http.get(this.baseUrl+'/getByStatus',{ params: new HttpParams().set('status', status) }); } getAllInq(){ return this.http.get(this.baseUrl+'/getAll'); } getUnattendedInquiries(){ return this.http.get(this.baseUrl+'/getUnattended-inquiry',{ params: new HttpParams().set('boolParam', 'false').set('statusParam', 'open') }); } getInquiryStats(){ return this.http.get(this.baseUrl+'/counsellor/dashboard/inquiryCounts'); } createInq(data){ return this.http.post(this.baseUrl+'/register',data); } updateInq(data){ return this.http.post(this.baseUrl+'/update',data); } setEnums(){ this.http.get(this.baseUrl+'/server-info') .subscribe( data => {this.enums = data}, error => {console.log("Error getting enums")}, () => {console.log("Set enum complete")} ); } getEnums(){ if(this.enums){ return this.enums; }else{ this.setEnums(); return this.enums; } } } <file_sep>/src/pages/visitor/thankyou/thankyou.ts import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; // import { HomePage } from '../../pages/home/home'; import { InqFormPersonalPage } from '../inq-form-personal/inq-form-personal'; @Component({ selector: 'page-thankyou', templateUrl: 'thankyou.html', }) export class ThankyouPage { constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad ThankyouPage'); } // goToHome() { // this.navCtrl.setRoot(HomePage); // } newInquiry() { this.navCtrl.setRoot(InqFormPersonalPage); } } <file_sep>/src/providers/sort/sort.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; enum SortDirection { ASCENDING = "ascending", DESCENDING = "descending" } @Injectable() export class SortProvider { constructor(public http: HttpClient) { console.log('Hello SortProvider Provider'); } byString(data,field,order){ if(order == SortDirection.ASCENDING){ return data.sort(function(a, b) { var valueA = a[field].toString().toUpperCase(); // ignore upper and lowercase var valueB = b[field].toString().toUpperCase(); // ignore upper and lowercase if (valueA < valueB) { return -1; } if (valueA > valueB) { return 1; } // values must be equal return 0; }); }else if(order == SortDirection.DESCENDING){ return data.sort(function(a, b) { var valueA = a[field].toString().toUpperCase(); // ignore upper and lowercase var valueB = b[field].toString().toUpperCase(); // ignore upper and lowercase if (valueA > valueB) { return -1; } if (valueA < valueB) { return 1; } // values must be equal return 0; }); } } byNumber(data,order){ if(order == SortDirection.ASCENDING){ return data.sort((a, b) => a - b); }else if(order == SortDirection.DESCENDING){ return data.sort((a, b) => b - a); } } } <file_sep>/src/providers/auth/auth.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { CounselorDashboardPage } from '../../pages/counselor/home/home'; @Injectable() export class AuthProvider { private id: string = 'admin'; private password: string = '<PASSWORD>'; constructor(public http: HttpClient) { console.log('Hello AuthProvider Provider'); } login(id: string, password: string){ if(this.authenticateUser(id, password)){ return true; }else{ console.log("Invalid Credentials.") return false; } } authenticateUser(id: string, password: string){ if(id === this.id && password === this.password){ return true; }else{ return false; } } } <file_sep>/src/pages/visitor/inq-form-personal/inq-form-personal.ts import { Component } from '@angular/core'; import { NavController, NavParams, LoadingController } from 'ionic-angular'; import { TitleCasePipe } from '@angular/common'; import { FormGroup } from '@angular/forms'; import { FormBuilder } from '@angular/forms'; import { Validators } from '@angular/forms'; import { CompleterService, RemoteData, CompleterItem } from 'ng2-completer'; import { InqProvider } from '../../../providers/inq/inq'; import { NotificationProvider } from '../../../providers/notification/notification'; import { NotificationMessageProvider } from '../../../providers/notification-message/notification-message'; import { LocalityProvider } from '../../../providers/locality/locality'; import { HelperProvider } from '../../../providers/helper/helper'; import { SortProvider } from '../../../providers/sort/sort'; import { InqFormEducationGuardianPage } from '../inq-form-education-guardian/inq-form-education-guardian'; @Component({ selector: 'page-inq-form-personal', templateUrl: 'inq-form-personal.html', }) export class InqFormPersonalPage { private diffState: boolean; private responseData; private inqForm: FormGroup; private pinService: RemoteData; private localities; private areas; private city; private state; private country; private enums; private genders; private hQualifications; private computerKnowledge; private areasOfInterest; today: string = new Date().toISOString(); private activeMenu: string = "visitor"; constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, private loadingCtrl: LoadingController, private inqProvider: InqProvider, private notify: NotificationProvider, private message: NotificationMessageProvider, private localityProvider: LocalityProvider, private helper: HelperProvider, private sort: SortProvider, private completerService: CompleterService) { this.inqForm = this.formBuilder.group({ name: ['', Validators.required], gender: ['', Validators.required], dob: ['', Validators.required], address: this.formBuilder.group({ addressLine1: [''], locationId: ['', Validators.required], pin: ['', Validators.required] }), mobile: ['', [Validators.required,Validators.minLength(10),Validators.maxLength(10)]], email: ['', [Validators.required, Validators.email]], hQualification: ['', Validators.required], computerKnowledge: ['', Validators.required], areaOfInterest: ['', Validators.required] }); this.helper.setActiveMenu(this.activeMenu); this.setEnums(); this.setGenders(); this.setQualifications(); this.setComputerKnowledge(); this.setAreasOfInterest(); this.diffState = false; this.pinService = this.completerService.remote(null); this.pinService.urlFormater(term => { return `http://localhost:9002/pincodes?pincode=${term}`; }); this.pinService.dataField("data"); } ionViewDidLoad() { console.log('ionViewDidLoad InqFormPersonalPage'); } private loading; presentLoadingCustom() { this.loading = this.loadingCtrl.create({ spinner: 'hide', content: ` <img src="../../assets/imgs/loading.svg" /> ` }); this.loading.onDidDismiss(() => { console.log('Dismissed loading'); }); this.loading.present(); } logForm1() { if(this.inqForm.valid){ console.log("Form to be logged", this.inqForm.value); this.presentLoadingCustom(); this.inqProvider.createInq(this.inqForm.value) .subscribe( data => { this.responseData = data; if(this.responseData.data){ this.notify.showInfo(this.message.INQUIRY.REGISTER.SUCCESS); console.log("POST successful, the response data is:", data); }else{ this.notify.showError(this.message.INQUIRY.REGISTER.FAILURE); console.log("POST unsucessful, server responded with error", this.responseData.exception); } }, error => { console.log("POST unsuccessful, the server returned this error:", error); this.loading.dismissAll(); }, () => { console.log("complete"); this.loading.dismissAll(); if(this.responseData.data){ this.navCtrl.push(InqFormEducationGuardianPage,{ data: this.responseData }); } } ); }else{ this.notify.showError(this.message.FORM.INVALID); console.log(this.inqForm); this.helper.markInvalidFields(this.inqForm); this.helper.markInvalidSelect(this.inqForm, 'gender'); this.helper.markInvalidSelect(this.inqForm, 'dob'); this.helper.markInvalidSelect(this.inqForm, 'hQualification'); this.helper.markInvalidSelect(this.inqForm, 'computerKnowledge'); this.helper.markInvalidSelect(this.inqForm, 'areaOfInterest'); if(this.areas && this.inqForm.value.address.pin.length == 6)this.helper.markInvalidSelect(this.inqForm.get('address'), 'locationId'); } } changeState() { this.diffState = !this.diffState; } setLocality(locality){ this.city = locality.data.city; this.state = locality.data.state; this.country = locality.data.country; this.areas = this.sort.byString(locality.data.locality, 'name','ascending'); } getLocality(pincode){ console.log("Getting localities for: ",pincode) this.localityProvider.getLocality(pincode) .subscribe( data => {console.log(data), this.localities = data;}, error => {console.log("ERROR GETTING LOCALITIES")}, () => {console.log("COMPLETE"), this.setLocality(this.localities);} ) } onPincodeSelected(pincode: CompleterItem){ if(pincode){ console.log(pincode); this.getLocality(pincode.originalObject); } } setPincodeFieldTypeNumber(){ document.getElementById('completer-input').setAttribute('type','number'); } setEnums(){ this.enums = this.inqProvider.getEnums(); } setGenders(){ this.genders = this.enums.data.gender; } setQualifications(){ this.hQualifications = this.enums.data.highestEducation; } setComputerKnowledge(){ this.computerKnowledge = this.enums.data.computerKnowledge; } setAreasOfInterest(){ this.areasOfInterest = this.enums.data.areaOfInterest; } } <file_sep>/src/pages/counselor/inq-details/inq-details.ts import { Component } from '@angular/core'; import { NavController, NavParams, LoadingController, ModalController } from 'ionic-angular'; import { TitleCasePipe } from '@angular/common'; import { FormGroup } from '@angular/forms'; import { FormBuilder } from '@angular/forms'; import { Validators } from '@angular/forms'; import { CompleterService, RemoteData, CompleterItem } from 'ng2-completer'; import { InqProvider } from '../../../providers/inq/inq'; import { NotificationProvider } from '../../../providers/notification/notification'; import { NotificationMessageProvider } from '../../../providers/notification-message/notification-message'; import { LocalityProvider } from '../../../providers/locality/locality'; import { HelperProvider } from '../../../providers/helper/helper'; import { SortProvider } from '../../../providers/sort/sort'; import { InqCloseModalPage } from '../inq-close-modal/inq-close-modal'; @Component({ selector: 'page-inq-details', templateUrl: 'inq-details.html', }) export class InqDetailsPage { private pinService: RemoteData; private localities; private areas; private city; private state; private country; private enums; private genders; private hQualifications; private computerKnowledge; private areasOfInterest; private streams; private eduStatus; private eduType; private markScheme; private guardianRelation; private guardianOccupation; private enqSource; private responseData; private currentInq; private currentInqId; private currentInqAddressId; private currentInqEducationId; private currentInqGuardianId; private currentInqMarketingId; private currentInqStatus; private currentInqClosingStatus; private currentInqClosingSubStatus; private currentInqClosingRemark; private requestData; private inqForm: FormGroup; today : string = new Date().toISOString(); constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, private loadingCtrl: LoadingController, private modalCtrl: ModalController, private inqProvider: InqProvider, private notify: NotificationProvider, private message: NotificationMessageProvider, private localityProvider: LocalityProvider, private helper: HelperProvider, private sort: SortProvider, private completerService: CompleterService) { this.updateInq(); this.inqForm = this.formBuilder.group({ name: ['', Validators.required], gender: ['', Validators.required], dob: ['', Validators.required], address: this.formBuilder.group({ addressLine1: [''], locationId: ['', Validators.required], pin: ['', Validators.required] }), mobile: ['', [Validators.required,Validators.minLength(10),Validators.maxLength(10)]], email: ['', [Validators.required, Validators.email]], hQualification: ['', Validators.required], computerKnowledge: ['', Validators.required], areaOfInterest: ['', Validators.required], education: this.formBuilder.array([ this.formBuilder.group({ educationQualification: ['',Validators.required], instituteName: [''], stream: [''], status: [''], year: [''], type: [''], aggregateMarks: [''], markScheme: [''] }) ]), guardian: this.formBuilder.group({ name: ['',Validators.required], relation: ['',Validators.required], phoneNumber: ['',[Validators.required,Validators.minLength(10),Validators.maxLength(10)]], email: ['',this.helper.emailOrEmptyValidator], occupation: [''] }), marketing: this.formBuilder.group({ source: ['',Validators.required], referred: [false], referant: [''] }) }); this.setEnums(); this.setGenders(); this.setQualifications(); this.setComputerKnowledge(); this.setAreasOfInterest(); this.setStreams(); this.setEduStatus(); this.setEduType(); this.setMarkScheme(); this.setGuardianRelation(); this.setGuardinaOccupation(); this.setMarketingSource(); this.pinService = this.completerService.remote(null); this.pinService.urlFormater(term => { return `http://localhost:9002/pincodes?pincode=${term}`; }); this.pinService.dataField("data"); } ionViewDidLoad() { console.log('ionViewDidLoad InqDetailsPage'); } private loading; presentLoadingCustom() { this.loading = this.loadingCtrl.create({ spinner: 'hide', content: ` <img src="../../assets/imgs/loading.svg" /> ` }); this.loading.onDidDismiss(() => { console.log('Dismissed loading'); }); this.loading.present(); } logForm() { if(this.inqForm.valid){ if(this.currentInq){ this.requestData = Object.assign({},this.inqForm.value); this.requestData.id = this.currentInqId; this.requestData.address.id = this.currentInqAddressId; this.requestData.education[0].id = this.currentInqEducationId; this.requestData.guardian.id = this.currentInqGuardianId; this.requestData.marketing.id = this.currentInqMarketingId; this.requestData.inquiryStatus = this.currentInqStatus; this.requestData.closingStatus = this.currentInqClosingStatus; this.requestData.closingSubStatus = this.currentInqClosingSubStatus; this.requestData.closingRemark = this.currentInqClosingRemark; }else{ this.requestData = Object.assign({},this.inqForm.value); } console.log("Form to be logged", this.requestData); this.presentLoadingCustom(); this.inqProvider.createInq(this.requestData) .subscribe( data => { this.responseData = data; if(this.responseData.data){ if(this.currentInq){ this.notify.showInfo(this.message.INQUIRY.UPDATE.SUCCESS); }else this.notify.showInfo(this.message.INQUIRY.REGISTER.SUCCESS); console.log("POST successful, the response data is:", data); }else{ if(this.currentInq){ this.notify.showError(this.message.INQUIRY.UPDATE.FAILURE); }else this.notify.showError(this.message.INQUIRY.REGISTER.FAILURE); console.log("POST unsucessful, server responded with error", this.responseData.exception); } }, error => { console.log("POST unsuccessful, the server returned this error:", error); this.loading.dismissAll(); }, () => { console.log("complete"); this.loading.dismissAll(); } ); }else{ this.notify.showError(this.message.FORM.INVALID); console.log(this.inqForm); this.helper.markInvalidFields(this.inqForm); this.helper.markInvalidSelect(this.inqForm, 'gender'); this.helper.markInvalidSelect(this.inqForm, 'dob'); this.helper.markInvalidSelect(this.inqForm, 'hQualification'); this.helper.markInvalidSelect(this.inqForm, 'computerKnowledge'); this.helper.markInvalidSelect(this.inqForm, 'areaOfInterest'); if(this.areas && this.inqForm.value.address.pin.length == 6)this.helper.markInvalidSelect(this.inqForm.get('address'), 'locationId'); let educationFormGroup: any = this.inqForm.get('education'); this.helper.markInvalidSelect(educationFormGroup.at(0), 'educationQualification'); this.helper.markInvalidSelect(educationFormGroup.at(0), 'stream'); this.helper.markInvalidSelect(educationFormGroup.at(0), 'status'); this.helper.markInvalidSelect(educationFormGroup.at(0), 'type'); this.helper.markInvalidSelect(educationFormGroup.at(0), 'markScheme'); this.helper.markInvalidSelect(this.inqForm.get('guardian'), 'relation'); this.helper.markInvalidSelect(this.inqForm.get('guardian'), 'occupation'); this.helper.markInvalidSelect(this.inqForm.get('marketing'), 'source'); } } updateInq(){ if(typeof this.navParams.data === 'number'){ this.currentInqId = this.navParams.data; console.log("Inquiry ID to be edited is",this.currentInqId); this.presentLoadingCustom(); this.inqProvider.getInqById(this.currentInqId) .subscribe( data => { this.currentInq = data; }, error => { console.log("GET unsucessful, the server returned this error:", error), this.loading.dismissAll(); }, () => { console.log("complete"); this.patchData(this.currentInq.data); this.getLocality(this.currentInq.data.address.pin); this.currentInqAddressId = this.currentInq.data.address.id; if(this.currentInq.data.education[0]) this.currentInqEducationId = this.currentInq.data.education[0].id; if(this.currentInq.data.guardian) this.currentInqGuardianId = this.currentInq.data.guardian.id; if(this.currentInq.data.marketing) this.currentInqMarketingId = this.currentInq.data.marketing.id; this.setClosingStatus(this.currentInq.data.closingStatus); this.setClosingSubStatus(this.currentInq.data.closingSubStatus); this.setClosingRemark(this.currentInq.data.closingRemark); this.setInqStatus(this.currentInq.data.inquiryStatus); this.loading.dismissAll(); } ) } } patchData(inq){ let patch = this.helper.removeEmptyFromObject(inq); console.log("Object to be patched:", patch); this.inqForm.patchValue(patch); } isInqOpen(status){ return status == "open"?true:false; } changeInqStatus(e){ console.log(e); if(e == "close"){ this.showInqCloseModal(); }else if(e == "open"){ this.setInqStatus('open'); this.setClosingStatus(null); this.setClosingSubStatus(null); this.setClosingRemark(null); this.logForm(); } } showInqCloseModal(){ let modal = this.modalCtrl.create( InqCloseModalPage ) modal.present(); modal.onDidDismiss(data =>{ if(data){ console.log(data); this.setClosingStatus(data.closingStatus); this.setClosingSubStatus(data.closingSubStatus); this.setClosingRemark(data.closingRemark); this.setInqStatus('close'); this.logForm(); } }); } setClosingStatus(data){ if(data){ this.currentInqClosingStatus = data; }else{ this.currentInqClosingStatus = ''; } } setClosingSubStatus(data){ if(data){ this.currentInqClosingSubStatus = data; }else{ this.currentInqClosingSubStatus = ''; } } setClosingRemark(data){ if(data){ this.currentInqClosingRemark = data; }else{ this.currentInqClosingRemark = ''; } } setInqStatus(status){ this.currentInqStatus = status.toLowerCase(); } setLocality(locality){ this.city = locality.data.city; this.state = locality.data.state; this.country = locality.data.country; this.areas = this.sort.byString(locality.data.locality,'name','ascending'); } getLocality(pincode){ console.log("Getting localities for: ",pincode) this.localityProvider.getLocality(pincode) .subscribe( data => {console.log(data), this.localities = data;}, error => {console.log("ERROR GETTING LOCALITIES")}, () => {console.log("COMPLETE"), this.setLocality(this.localities);} ) } onPincodeSelected(pincode: CompleterItem){ if(pincode){ console.log(pincode); this.getLocality(pincode.originalObject); } } setPincodeFieldTypeNumber(){ document.getElementById('completer-input').setAttribute('type','number'); } setEnums(){ this.enums = this.inqProvider.getEnums(); } setGenders(){ this.genders = this.enums.data.gender; } setQualifications(){ this.hQualifications = this.enums.data.highestEducation; } setComputerKnowledge(){ this.computerKnowledge = this.enums.data.computerKnowledge; } setAreasOfInterest(){ this.areasOfInterest = this.enums.data.areaOfInterest; } setStreams(){ this.streams = this.enums.data.stream; } setEduStatus(){ this.eduStatus = this.enums.data.educationStatus; } setEduType(){ this.eduType = this.enums.data.educationType; } setMarkScheme(){ this.markScheme = this.enums.data.markScheme; } setGuardianRelation(){ this.guardianRelation = this.enums.data.relation; } setGuardinaOccupation(){ this.guardianOccupation = this.enums.data.occupation; } setMarketingSource(){ this.enqSource = this.enums.data.marketingSource; } } <file_sep>/src/pages/visitor/inq-form-education-guardian/inq-form-education-guardian.ts import { Component } from '@angular/core'; import { NavController, NavParams, LoadingController } from 'ionic-angular'; import { FormBuilder } from '@angular/forms'; import { FormGroup } from '@angular/forms'; import { Validators } from '@angular/forms'; import { InqProvider } from '../../../providers/inq/inq'; import { NotificationProvider } from '../../../providers/notification/notification'; import { NotificationMessageProvider } from '../../../providers/notification-message/notification-message'; import { HelperProvider } from '../../../providers/helper/helper'; import { InqFormMarketingPage } from '../inq-form-marketing/inq-form-marketing'; @Component({ selector: 'page-inq-form-education-guardian', templateUrl: 'inq-form-education-guardian.html', }) export class InqFormEducationGuardianPage { private enums; private hQualifications; private streams; private eduStatus; private eduType; private markScheme; private guardianRelation; private guardianOccupation; private inqForm: FormGroup; private currentInq; private responseData; private requestData; private education; constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, private loadingCtrl: LoadingController, private inqProvider: InqProvider, private notify: NotificationProvider, private message: NotificationMessageProvider, private helper: HelperProvider) { this.currentInq = this.navParams.get('data'); this.education = this.currentInq.data.hQualification; this.inqForm = this.formBuilder.group({ education: this.formBuilder.array([ this.formBuilder.group({ educationQualification: [this.education, Validators.required], instituteName: [''], stream: [''], status: [''], year: [''], type: [''], aggregateMarks: [''], markScheme: [''] }) ]), guardian: this.formBuilder.group({ name: ['',Validators.required], relation: ['',Validators.required], phoneNumber: ['',[Validators.required,Validators.minLength(10),Validators.maxLength(10)]], email: ['',this.helper.emailOrEmptyValidator], occupation: [''] }) }); this.setEnums(); this.setQualifications(); this.setStreams(); this.setEduStatus(); this.setEduType(); this.setMarkScheme(); this.setGuardianRelation(); this.setGuardinaOccupation(); } ionViewDidLoad() { console.log('ionViewDidLoad InqFormEducationGuardianPage'); } private loading; presentLoadingCustom() { this.loading = this.loadingCtrl.create({ spinner: 'hide', content: ` <img src="../../assets/imgs/loading.svg" /> ` }); this.loading.onDidDismiss(() => { console.log('Dismissed loading'); }); this.loading.present(); } logForm2(){ if(this.inqForm.valid){ this.requestData = Object.assign({},this.currentInq.data,this.inqForm.value) console.log("Form to be logged", this.requestData); this.presentLoadingCustom(); this.inqProvider.updateInq(this.requestData) .subscribe( data => { this.responseData = data; if(this.responseData.data){ this.notify.showInfo(this.message.INQUIRY.UPDATE.SUCCESS); console.log("POST successful, the response data is:", data); }else{ this.notify.showError(this.message.INQUIRY.UPDATE.FAILURE); console.log("POST unsucessful, server responded with error", this.responseData.exception); } }, error => { console.log("POST unsuccessful, the server returned this error:", error); this.loading.dismissAll(); }, () => { console.log("complete"); this.loading.dismissAll(); if(this.responseData.data){ this.navCtrl.push(InqFormMarketingPage,{ data: this.responseData }); } } ); }else{ this.notify.showError(this.message.FORM.INVALID); console.log(this.inqForm); this.helper.markInvalidFields(this.inqForm); let educationFormGroup: any = this.inqForm.get('education'); this.helper.markInvalidSelect(educationFormGroup.at(0), 'educationQualification'); this.helper.markInvalidSelect(educationFormGroup.at(0), 'stream'); this.helper.markInvalidSelect(educationFormGroup.at(0), 'status'); this.helper.markInvalidSelect(educationFormGroup.at(0), 'type'); this.helper.markInvalidSelect(educationFormGroup.at(0), 'markScheme'); this.helper.markInvalidSelect(this.inqForm.get('guardian'), 'relation'); this.helper.markInvalidSelect(this.inqForm.get('guardian'), 'occupation'); } } skip(){ this.navCtrl.push(InqFormMarketingPage,{ data: this.currentInq }); } setEnums(){ this.enums = this.inqProvider.getEnums(); } setQualifications(){ this.hQualifications = this.enums.data.highestEducation; } setStreams(){ this.streams = this.enums.data.stream; } setEduStatus(){ this.eduStatus = this.enums.data.educationStatus; } setEduType(){ this.eduType = this.enums.data.educationType; } setMarkScheme(){ this.markScheme = this.enums.data.markScheme; } setGuardianRelation(){ this.guardianRelation = this.enums.data.relation; } setGuardinaOccupation(){ this.guardianOccupation = this.enums.data.occupation; } } <file_sep>/src/providers/helper/helper.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { FormGroup, AbstractControl, ValidationErrors, Validators } from '@angular/forms'; import { MenuController } from 'ionic-angular'; @Injectable() export class HelperProvider { constructor(public http: HttpClient, private menu: MenuController) { console.log('Hello HelperProvider Provider'); } setActiveMenu(menuID:string){ this.menu.enable(true,menuID); } markInvalidFields(formGroup: FormGroup) { for(let control in formGroup.controls){ formGroup.controls[control].markAsTouched(); formGroup.controls[control].updateValueAndValidity(); } let ionItems = document.getElementsByTagName("ion-item"); if(ionItems){ for(var i = 0; i < ionItems.length; i++){ if (ionItems[i].classList.contains('ng-untouched')) { ionItems[i].classList.remove('ng-untouched'); ionItems[i].classList.add('ng-touched'); } } } let pinAutoComplete = document.getElementsByTagName("ng2-completer")[0]; if(pinAutoComplete && pinAutoComplete.classList.contains('ng-untouched')){ pinAutoComplete.classList.remove('ng-untouched'); pinAutoComplete.classList.add('ng-touched'); } } removeEmptyFromObject = (obj) => { const o = JSON.parse(JSON.stringify(obj)); // Clone source oect. Object.keys(o).forEach(key => { if (o[key] && typeof o[key] === 'object') o[key] = this.removeEmptyFromObject(o[key]); // Recurse. else if (o[key] === undefined || o[key] === null) delete o[key]; // Delete undefined and null. else o[key] = o[key]; // Copy value. }); return o; // Return new object. }; emailOrEmptyValidator(control: AbstractControl): ValidationErrors | null { return control.value === '' ? null : Validators.email(control); } markInvalidSelect(formGroup, ctrlName: string) { let shadesEl = document.querySelector('[formControlName="' + ctrlName + '"]').parentElement.parentElement.parentElement; const control = formGroup.get(ctrlName); if (control.errors != null) { shadesEl.classList.remove('ng-untouched'); shadesEl.classList.add('ng-invalid', 'ng-touched', 'ng-dirty'); } else { shadesEl.classList.remove('ng-dirty', 'ng-invalid'); } } } <file_sep>/src/pages/counselor/inq-summary/inq-summary.ts import { Component } from '@angular/core'; import { NavController, NavParams, LoadingController, ModalController } from 'ionic-angular'; import { TitleCasePipe } from '@angular/common'; import { InqProvider } from '../../../providers/inq/inq'; import { SortProvider } from '../../../providers/sort/sort'; import { FollowUpModalPage } from '../follow-up-modal/follow-up-modal'; import { ReminderModalPage } from '../reminder-modal/reminder-modal'; @Component({ selector: 'page-inq-summary', templateUrl: 'inq-summary.html', }) export class InqSummaryPage { private currentInq; private currentInqId; private currentInqFollowUps; private currentInqReminders; constructor(public navCtrl: NavController, public navParams: NavParams, private loadingCtrl: LoadingController, private inqProvider: InqProvider, private sort: SortProvider, private modalCtrl: ModalController) { this.currentInqId = this.navParams.data; this.getCurrentInq(); } ionViewDidLoad() { console.log('ionViewDidLoad InqSummaryPage'); } private loading; presentLoadingCustom() { this.loading = this.loadingCtrl.create({ spinner: 'hide', content: ` <img src="../../assets/imgs/loading.svg" /> ` }); this.loading.onDidDismiss(() => { console.log('Dismissed loading'); }); this.loading.present(); } getCurrentInq(){ this.presentLoadingCustom(); this.inqProvider.getInqById(this.currentInqId) .subscribe( data => { let responseData; responseData = data; this.currentInq = responseData.data; if(responseData.data.followUps)this.currentInqFollowUps = this.sort.byString(responseData.data.followUps,'followUpDate','descending'); if(responseData.data.reminders)this.currentInqReminders = this.sort.byString(responseData.data.reminders,'time','ascending'); console.log("Inquiry to be viewed is: ",this.currentInq); }, error => { console.log("GET unsuccessful, the server returned this error: ", error) this.loading.dismissAll(); }, () => { console.log("complete") this.loading.dismissAll(); } ); } addFollowUp(){ let modal = this.modalCtrl.create( FollowUpModalPage, {id: this.currentInq.id, name: this.currentInq.name} ) modal.present(); modal.onDidDismiss(data =>{ if(data){ console.log(data); } }); } updateFollowUp(followUp){ let modal = this.modalCtrl.create( FollowUpModalPage, {id: this.currentInq.id, name: this.currentInq.name, followUp: followUp} ) modal.present(); modal.onDidDismiss(data =>{ if(data){ console.log(data); } }); } showViewReminderModal(reminder){ let modal = this.modalCtrl.create( ReminderModalPage, {reminder: reminder,view: "true"} ) modal.present(); modal.onDidDismiss(data =>{ if(data){ console.log(data); } }); } } <file_sep>/src/pages/visitor/inq-form-marketing/inq-form-marketing.ts import { Component } from '@angular/core'; import { NavController, NavParams, LoadingController } from 'ionic-angular'; import { FormGroup } from '@angular/forms'; import { FormBuilder } from '@angular/forms'; import { Validators } from '@angular/forms'; import { InqProvider } from '../../../providers/inq/inq'; import { NotificationProvider } from '../../../providers/notification/notification'; import { NotificationMessageProvider } from '../../../providers/notification-message/notification-message'; import { HelperProvider } from '../../../providers/helper/helper'; import { ThankyouPage } from '../thankyou/thankyou'; @Component({ selector: 'page-inq-form-marketing', templateUrl: 'inq-form-marketing.html', }) export class InqFormMarketingPage { private enums; private enqSource; private currentInq; private responseData; private requestData; private inqForm: FormGroup; constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, private loadingCtrl: LoadingController, private inqProvider: InqProvider, private notify: NotificationProvider, private message: NotificationMessageProvider, private helper: HelperProvider) { this.currentInq = this.navParams.get('data'); this.inqForm = this.formBuilder.group({ marketing: this.formBuilder.group({ source: ['',Validators.required], referred: [false], referant: [''] }) }); this.setEnums(); this.setMarketingSource(); } ionViewDidLoad() { console.log('ionViewDidLoad InqFormMarketingPage'); } private loading; presentLoadingCustom() { this.loading = this.loadingCtrl.create({ spinner: 'hide', content: ` <img src="../../assets/imgs/loading.svg" /> ` }); this.loading.onDidDismiss(() => { console.log('Dismissed loading'); }); this.loading.present(); } logForm3(){ if(this.inqForm.valid){ this.requestData = Object.assign({},this.currentInq.data,this.inqForm.value) console.log("Form to be logged", this.requestData); this.presentLoadingCustom(); this.inqProvider.updateInq(this.requestData) .subscribe( data => { this.responseData = data; if(this.responseData.data){ this.notify.showInfo(this.message.INQUIRY.UPDATE.SUCCESS); console.log("POST successful, the response data is:", data) }else{ this.notify.showError(this.message.INQUIRY.UPDATE.FAILURE) console.log("POST unsucessful, server responded with error", this.responseData.exception) } }, error => { console.log("POST unsuccessful, the server returned this error:", error); this.loading.dismissAll(); }, () => { console.log("complete"); this.loading.dismissAll(); if(this.responseData.data){ this.navCtrl.setRoot(ThankyouPage); } } ); }else{ this.notify.showError(this.message.FORM.INVALID); console.log(this.inqForm); this.helper.markInvalidFields(this.inqForm); this.helper.markInvalidSelect(this.inqForm.get('marketing'), 'source'); } } setEnums(){ this.enums = this.inqProvider.getEnums(); } setMarketingSource(){ this.enqSource = this.enums.data.marketingSource; } skip(){ this.navCtrl.setRoot(ThankyouPage) } }
98ec1030f230569325ee936361c75cf854247124
[ "TypeScript" ]
23
TypeScript
aayushKhandpur/creativei_inquiry_client
7e47510b1ac1222f6f215a0b03699b8ebe66c443
cbf2fc5d929501ee83ac65ab5a18dcc7be7144cd
refs/heads/master
<file_sep> class Array def my_uniq result = [] self.each do |el| if ! result.include?(el) result << el end end return result.sort end def my_two_sums result = [] self.each_with_index do |num1, idx1| self.each_with_index do |num2, idx2| if num1 + num2 == 0 && idx1 < idx2 result << [idx1, idx2] end end end result end end def my_transpose(array) result = Array.new(array.length) { Array.new } # [nil, nil, nil] array.each do |row| # [0, 1, 2] # [0, 3, 6] # [3, 4, 5] # [1, 4, 7] # [6, 7, 8] # [2, 5, 8] row.each_with_index do |col_val, idx| result[idx] << col_val end end result end # [14, 3, 8, 3, 5, 10] # [pair of days] # [[1, 2],[3, 5]] # [1, 5] # [14, 3, 8, 3, 5, 10] # diff = X # result = [1, 2] # arr.each_index once # arr.each_index twice # if arr[once] - arr[twice] > diff && twice < once # result = [twice, once] class StealingError < StandardError ; end def stock_picker(array) diff = array[0] - array[1] result = [array[0], array[1]] array.each_with_index do |num1, idx1| array.each_with_index do |num2, idx2| if num1 - num2 > diff && idx2 < idx1 diff = num1 - num2 result = [idx2, idx1] end end end if result[0] > result[1] raise StealingError end result end<file_sep>require 'hand' require 'rspec' RSpec.describe "hand" do let(:hand) { Hand.new() } # Need to test current_winning_hand variable # need to test current_winning_hand_score variable describe "#hand_score" do it "Checks for high single" do high_single_hand = [[[1, "Spades"], [3, "Diamonds"], [6, "Hearts"], [7, "Clubs"], [12, "Spades"]]] expect(hand_score(hand)).to eq(12) end it "Checks for a single pair" do single_pair_hand = [[[1, "Spades"], [6, "Diamonds"], [6, "Hearts"], [7, "Clubs"], [12, "Spades"]]] expect(hand_score(hand)).to eq(14) end it "Checks for a two pair" do two_pair_hand = [[[7, "Spades"], [6, "Diamonds"], [6, "Hearts"], [7, "Clubs"], [12, "Spades"]]] expect(hand_score(hand)).to eq(15) end it "Checks for three of a kind" do three_of_a_kind_hand = [[[6, "Spades"], [6, "Diamonds"], [6, "Hearts"], [7, "Clubs"], [12, "Spades"]]] expect(hand_score(hand)).to eq(16) end it "Checks for a straight" do straight_hand = [[[1, "Spades"], [2, "Diamonds"], [3, "Hearts"], [4, "Clubs"], [5, "Spades"]]] expect(hand_score(hand)).to eq(17) end it "Checks for a flush" do flush_hand = [[[1, "Spades"], [6, "Spades"], [8, "Spades"], [7, "Spades"], [12, "Spades"]]] expect(hand_score(hand)).to eq(18) end it "Checks for a full house" do full_house_hand = [[[2, "Spades"], [2, "Diamonds"], [3, "Hearts"], [3, "Clubs"], [3, "Spades"]]] expect(hand_score(hand)).to eq(19) end it "Checks for four of a kind" do four_of_a_kind_hand = [[[2, "Spades"], [3, "Diamonds"], [3, "Hearts"], [3, "Clubs"], [3, "Spades"]]] expect(hand_score(hand)).to eq(20) end it "Checks for a straight flush" do straight_flush_hand = [[[2, "Spades"], [3, "Spades"], [4, "Spades"], [5, "Spades"], [6, "Spades"]]] expect(hand_score(hand)).to eq(21) end it "Checks for a royal flush" do royal_hand = [[[13, "Spades"], [12, "Spades"], [11, "Spades"], [10, "Spades"], [1, "Spades"]]] expect(hand_score(hand)).to eq(22) end end describe "#winning_hand" do it "Checks for the highest scoring hand" do low_hand = [[1, "Spades"], [3, "Diamonds"], [6, "Hearts"], [7, "Clubs"], [12, "Spades"]] high_hand = [[13, "Spades"], [12, "Spades"], [11, "Spades"], [10, "Spades"], [1, "Spades"]] hand.winning_hand(low_hand, high_hand) expect(hand.current_winning_hand).to eq(high_hand) expect(current_winning_hand_score).to eq(hand.hand_score([high_hand])) end it "Tie breaker logic -- four of a kind" it "Tie breaker logic -- three of a kind (And full house)" it "Tie breaker logic -- High single" it "Tie breaker logic -- two pair" it "Tie breaker logic -- one pair" it "Tie breaker logic -- striaghts" single_pair_hand = [[[1, "Spades"], [6, "Diamonds"], [6, "Hearts"], [7, "Clubs"], [12, "Spades"]]] single_pair_hand2 = [[[2, "Diamonds"], [8, "Spades"], [8, "Hearts"], [6, "Spades"], [11, "Clubs"]]] hand.winning_hand(single_pair_hand, single_pair_hand2) expect(hand.current_winning_hand).to eq() end end <file_sep>require_relative "card" class Deck attr_reader :cards def initialize @cards = [] end def generate nums = *(1..13) suits = %w(Diamonds Spades Hearts Clubs) nums.each do |num| suits.each do |suit| cards << Card.new(num, suit) end end return '' end def shuffle cards.shuffle! end end<file_sep>require 'tdd' RSpec.describe "my_uniq" do it "should have only 1 of each instance" do array = [1, 2, 2, 3, 2, 3, 5] expect(array.my_uniq).to eq(array.uniq) end it "should sort output" do array = [5, 5, 3, 2, 3, 1] expect(array.my_uniq).to eq(array.uniq.sort) end end RSpec.describe "my_two_sums" do it "should find index of pairs where value equals 0" do expect([1, -1].my_two_sums).to eq([[0, 1]]) end it "should sort smaller index first" do expect([0, 0, 1, -1].my_two_sums).to eq([[0, 1], [2, 3]]) end it "should sort smaller second index" do expect([0, 0, 0].my_two_sums).to eq([[0,1], [0,2], [1,2]]) end end RSpec.describe "my_transpose" do array = [ [0, 1, 2], [3, 4, 5], [6, 7, 8] ] it "checks transposed row 1" do expect(my_transpose(array)[0]).to eq([0, 3, 6]) end it "checks transposed row 2" do expect(my_transpose(array)[1]).to eq([1, 4, 7]) end it "checks transposed row 3" do expect(my_transpose(array)[2]).to eq([2, 5, 8]) end end RSpec.describe "stock_picker" do it "return an output array of length 2" do array = [1, 2, 3, 4, 5] expect(stock_picker(array).length).to eq(2) end it "checks if output is most profitable" do array = [1, 4, 10, 15] expect(stock_picker(array)).to eq([0, 3]) end # it "checks if stock is sold before it is bought" do # # # array = [10, 3, 5, 6] # # allow([1,2]).to receive(:stock_picker).and_return([1,0]) # # expect { stock_picker([1, 2]) }.to # end end #Check if user is picking from an empty pile #Cannot move piece on to smaller piece #Array = [3, 2, 1] not on starting position # RSpec.describe "towers_of_hanoi" do # context "#move" do # it "makes sure pieces are placed properly" do # expect(towers_of_hanoi.move()) # end # end # end <file_sep>require 'card' require 'rspec' RSpec.describe "card" do let(:card) { Card.new(8, "Diamonds") } it "sets parameter num to an integer" do expect(card.num.class).to be(Integer) end it "sets parameter suit to a string" do suits = ["Diamonds", "Spades", "Hearts", "Clubs"] expect(suits.include?(card.suit)).to be(true) end end <file_sep>require 'card' require 'rspec' require 'deck' RSpec.describe "deck" do let(:deck) { Deck.new } before(:each) do deck.generate end describe "#generate" do it "builds the deck" do expect(deck.cards.count).to eq(52) end it "should not contain duplicates" do expect(deck.cards).to eq(deck.cards.uniq) end end describe "#shuffle" do it "shuffles the deck" do pre_shuffle = deck.cards.dup deck.shuffle expect(deck.cards).to_not eq(pre_shuffle) end end end<file_sep> class Card attr_reader :num, :suit def initialize(num, suit) @num = num @suit = suit end end
6083d2ac9ff275141e05e6f7bfc161b50feda379
[ "Ruby" ]
7
Ruby
Mesona/W2D3
7f00797abbe7cf13f7f91214e905867ea50a4809
a96404fb1f7ea0073644de528fa4f29b4459e62d
refs/heads/master
<file_sep>--SELECT * FROM Genre; --INSERT INTO Artist ( ArtistName, YearEstablished) VALUES ('<NAME>', 1982); --SELECT * FROM Artist; --INSERT INTO Album (AlbumLength, ArtistId, [Label],Title, ReleaseDate) VALUES (2032, 29,'ColoradoRiver', 'Arkansas Bound', '2/3/2014'); --SELECT * FROM Album; --INSERT INTO Song (AlbumId, ArtistId, ReleaseDate, Title, SongLength, GenreId) VALUES (22, 29, '2/3/2014', 'Gamblin Bar Room Blues', 180, 8); --INSERT INTO Song (AlbumId, ArtistId, ReleaseDate, Title, SongLength, GenreId) VALUES (22, 28, '2/3/2014', 'Arkansas Bound', 180, 8); --SELECT s.Title, al.Title from Song s LEFT JOIN Album al on s.AlbumId=al.id; --SELECT COUNT(AlbumId) as 'SongCount', al.Title FROM Song s Left Join Album al on s.AlbumId=al.Id --GROUP BY AlbumId, al.Title; --SELECT COUNT(ArtistId) as 'SongCount', ar.ArtistName FROM Song s Left Join Artist ar on s.ArtistId=ar.Id --GROUP BY ArtistId, ar.ArtistName; --SELECT COUNT(GenreId) as 'SongCount', g.Label FROM Song s Left Join Genre g on s.GenreId=g.Id --GROUP BY GenreId, g.Label; --SELECT Title, AlbumLength as 'Album Length' FROM Album --WHERE AlbumLength = (SELECT MAX(AlbumLength)FROM Album); SELECT s.Title, al.Title as 'Album Title', SongLength as 'Song Length' FROM Song s LEFT JOIN Album al on s.AlbumId=al.Id WHERE SongLength= (SELECT MAX(SongLength) FROM Song);
b7c02a7d10b1038ebc58cc2417c24f30f2be40f2
[ "SQL" ]
1
SQL
rebeccapatek/Music-History
a4b1a5f281c5f162ac00190a5716c1edc0d76eb5
640e68655cd48da67060dd54f2cde2a669d8c776
refs/heads/master
<repo_name>PaperCrafter/react_study<file_sep>/chapter7/src/lifeCycleMount.js import React, {Component} from 'react'; class lifeCycleMount extends Component{ state={ number:0, } constructor(props){ super(props); console.log('constructor called'); console.log(`state:${this.state.number}`); console.log(`state:${this.props.number}`); } //state의 변화가 필요할 경우 state 객체를 반환합니다. //변화가 필요 없을 경우 null을 반환합니다. static getDerivedStateFromProps(nextProps, prevState){ console.log('getDerivedStateFromProps called'); if(nextProps.number !== prevState.number){ return{number:nextProps.number} } return null; } render(){ console.log(`state:${this.state.number}`); console.log(`state:${this.props.number}`); console.log('render called'); return( <div> <p>예제1 - mount 과정 lifeCycle</p> <p>props:{this.props.number}</p> <p>state:{this.state.number}</p> </div> ); } componentDidMount(){ console.log('componentDidMount called'); } } export default lifeCycleMount;
5cb2dda20be0e9ae02150352e83f78e22ba11a98
[ "JavaScript" ]
1
JavaScript
PaperCrafter/react_study
13c1fb3a87ab52d34c983d56e63e964d56be7cd2
7d4609a016a734beb6e16a53a538b027fb04b275
refs/heads/master
<file_sep> # sentry [![GoDoc](https://godoc.org/github.com/altipla-consulting/sentry?status.svg)](https://godoc.org/github.com/altipla-consulting/sentry) [![Build Status](https://travis-ci.org/altipla-consulting/sentry.svg?branch=master)](https://travis-ci.org/altipla-consulting/sentry) Sentry client with additional functionality and helpers to complement the official one. ### Install ```shell go get github.com/altipla-consulting/sentry ``` This library has the following dependencies: - [github.com/getsentry/raven-go](github.com/getsentry/raven-go) - [github.com/juju/errors](github.com/juju/errors) - [github.com/sirupsen/logrus](github.com/sirupsen/logrus) - [golang.org/x/net/context](golang.org/x/net/context) ### Contributing You can make pull requests or create issues in GitHub. Any code you send should be formatted using `gofmt`. ### Running tests Run the tests ```shell make test ``` ### License [MIT License](LICENSE) <file_sep>package sentry import ( "time" "golang.org/x/net/context" ) type Breadcrumbs struct { Values []*Breadcrumb `json:"values,omitempty"` } func (b *Breadcrumbs) Class() string { return "breadcrumbs" } type Breadcrumb struct { Timestamp time.Time `json:"timestamp"` Type string `json:"type"` Message string `json:"message"` Data map[string]string `json:"data,omitempty"` Category string `json:"category"` Level Level `json:"level"` } type Level string const ( LevelCritical = Level("critical") LevelWarning = Level("warning") LevelError = Level("error") LevelInfo = Level("info") LevelDebug = Level("debug") ) func LogBreadcrumb(ctx context.Context, level Level, category, message string) { info := FromContext(ctx) info.breadcrumbs = append(info.breadcrumbs, &Breadcrumb{ Timestamp: time.Now(), Type: "default", Message: message, Category: category, Level: level, }) } <file_sep>package sentry import ( "context" ) type key int var keySentry key = 1 type Sentry struct { breadcrumbs []*Breadcrumb } func FromContext(ctx context.Context) *Sentry { return ctx.Value(keySentry).(*Sentry) } func WithContext(ctx context.Context) context.Context { return context.WithValue(ctx, keySentry, new(Sentry)) } <file_sep>package sentry import ( "context" "net/http" "os" "strconv" "strings" "time" "github.com/getsentry/raven-go" "github.com/juju/errors" log "github.com/sirupsen/logrus" ) type Client struct { dsn string } func NewClient(dsn string) *Client { return &Client{ dsn: dsn, } } func (client *Client) ReportInternal(ctx context.Context, appErr error) { client.report(ctx, appErr, nil) } func (client *Client) ReportRequest(appErr error, r *http.Request) { client.report(r.Context(), appErr, r) } type Extra struct { RequestID string `json:"Request ID"` InstanceID string `json:"Instance ID"` } func (extra *Extra) Class() string { return "extra" } type Exception struct { Value string `json:"value"` Module string `json:"module"` Stacktrace *raven.Stacktrace `json:"stacktrace"` Type string `json:"type"` } func (e *Exception) Class() string { return "exception" } func (client *Client) report(ctx context.Context, appErr error, r *http.Request) { event := make(chan string, 1) go func() { jujuErr, ok := appErr.(*errors.Err) if !ok { jujuErr = errors.Errorf("unknown error type: %s", appErr.Error()).(*errors.Err) } stacktrace := new(raven.Stacktrace) for _, entry := range jujuErr.StackTrace() { parts := strings.Split(entry, ":") if len(parts) > 2 { n, err := strconv.ParseInt(parts[1], 10, 64) if err == nil { stacktrace.Frames = append(stacktrace.Frames, &raven.StacktraceFrame{ Filename: parts[0], Lineno: int(n), ContextLine: entry, }) continue } } // Fallback to avoid erroring out here if no location is found stacktrace.Frames = append(stacktrace.Frames, &raven.StacktraceFrame{ Filename: entry, ContextLine: entry, }) } // Invert frames to show them in the correct order in the Sentry UI for i, j := 0, len(stacktrace.Frames)-1; i < j; i, j = i+1, j-1 { stacktrace.Frames[i], stacktrace.Frames[j] = stacktrace.Frames[j], stacktrace.Frames[i] } client, err := raven.New(client.dsn) if err != nil { log.WithField("error", err).Error("Cannot create client") return } client.SetRelease(os.Getenv("VERSION")) info := FromContext(ctx) interfaces := []raven.Interface{ &Exception{ Stacktrace: stacktrace, Module: "backend", Value: appErr.Error(), Type: appErr.Error(), }, &Breadcrumbs{ Values: info.breadcrumbs, }, } if r != nil { interfaces = append(interfaces, raven.NewHttp(r), &raven.User{IP: r.RemoteAddr}) } packet := raven.NewPacket(appErr.Error(), interfaces...) eventID, ch := client.Capture(packet, nil) <-ch event <- eventID }() select { case eventID := <-event: log.WithField("eventID", eventID).Info("Error logged to sentry") case <-time.After(5 * time.Second): log.Error("Timeout trying to reach sentry") } }
f27f382b3e1d0bb1792bfe33a201d866d7fb75c3
[ "Markdown", "Go" ]
4
Markdown
albertomoreno/sentry
ee5f2d84bc5c37bc7c383d820c3f07044f9a506d
2561d118d0cdc3e42951507c9fb6ec22cffdd5e3
refs/heads/master
<repo_name>justucru/composer<file_sep>/composer/composer/README.md # composer Quête Composer <file_sep>/composer/public/index.php <?php require_once '../vendor/autoload.php'; $hello = new \App\Wcs\Hello(); echo $hello->talk(); echo "<br>"; $helloAgain = new \HelloWorld\SayHello(); echo $helloAgain->world();
dd71e7cf63fedbd567f4b490be2b6a4bb6827558
[ "Markdown", "PHP" ]
2
Markdown
justucru/composer
cf1da9eabb2fd00af395459cdfe3e4ca8478a91b
bc3ddeffda5aca76267f70a39e2ca3c29ad25fca
refs/heads/master
<file_sep>/** * Created by sinamasnadi on 11/4/16. */ var spawn = require('child_process').spawn; module.exports = exports = pdfInfo; function pdfInfo() { return { "options": [], "_input": null, "lambdaExecPath": false, "option": function (option) { this.options.push(option); return this; }, "input": function (file) { this._input = file; return this; }, "lambda": function (path) { this.lambdaExecPath = path; return this; }, "exec": function (callback) { var _this = this; if (!_this.input) { return callback.call(_this, 'Input not selected'); } var process = spawn(_this.lambdaExecPath ? _this.lambdaExecPath : 'pdfinfo', _this.options.concat([_this._input])); process.stdin.on('error', callback); process.stdout.on('error', callback); var _data = []; var totalBytes = 0; process.stdout.on('data', function (data) { totalBytes += data.length; _data.push(data); }); process.on('close', function () { var buffer = Buffer.concat(_data, totalBytes); var input = buffer.toString(); if (input === '' || input.includes('Error')) { return callback.call(_this, 'File is not PDF'); } var lines = input.split('\n'); var output = {}; lines.forEach(function (line) { var key = line.substr(0, line.indexOf(':')); var value = line.substr(line.indexOf(':') + 1); while (value.charAt(0) === ' ') { value = value.substr(1); } output[key] = value; }); return callback.call(_this, null, output); }); process.on('exit', function () { process.kill(); }); } } } <file_sep># node-pdfinfo A node js package to use xpdf pdfinfo component. This package will retrieve a PDF file info (such as page size, number of pages, file size, author, etc). # Installation `npm install https://github.com/sina-masnadi/node-pdfinfo/tarball/master`
ff630036baf73ccebc96c53a453fd5193d8de5fc
[ "JavaScript", "Markdown" ]
2
JavaScript
sina-masnadi/node-pdfinfo
47c9b3ccae04a247b18bc64371f01c7be7539308
8b25b6c0b5bc5c3b1c27b2adc9c191059722b772
refs/heads/master
<repo_name>annauk/roman<file_sep>/src/romannumerals/RomanNumeralGenerator.java package romannumerals; public interface RomanNumeralGenerator { public String generate(int number); public void FinalResult(); }
36fc504e782cb5db230d049627f31d5e6694e86e
[ "Java" ]
1
Java
annauk/roman
12d0fd2d88957067b507931e1b026fba6a7ba424
899f73d55cb5c78860be5dfaa9d3763d9ab122ca
refs/heads/master
<repo_name>rzazo131586/proteo.ui.buscador-contacto.filtro<file_sep>/src/proteo.ui.buscador-contacto.filtro-directive.js /* Buscador-Contacto.FILTRO DIRECTIVE */ angular.module('proteo.ui.buscador-contacto.filtro').directive('buscadorContacto.filtro',function() { return { scope: { contactsResult : "=" }, restrict : "E", controller : 'buscadorContactoFiltroCtrl', templateUrl : 'src/proteo.ui.buscador-contacto.filtro.tpl.html', link: function($scope){ $scope.returnItemsFilter = function(){ //console.log("contactsFiltered || "+JSON.stringify($scope.contactsFiltered)); $scope.contactsResult($scope.contactFilteredFn()); }; } }; }); /* END Buscador-Contacto.FILTRO DIRECTIVE */ <file_sep>/src/proteo.ui.buscador-contacto.filtro-controller.js /* Buscador-Contacto.FILTRO CONTROLLER */ angular.module('proteo.ui.buscador-contacto.filtro').controller('buscadorContactoFiltroCtrl', function($scope, $http) { // Code fo Controller $scope.filter={}; $scope.datatitle = "AGENDA DE CONTACTOS"; // Call to service $http.get('http://localhost:3000/users').success(function(data) { $scope.contacts = data; $scope.contactsFiltered = data; }); // Reset INPUTS & LIST constacts ( future : service ) $scope.contactReset = function(){ // reasign data into contactsFiltered for reset list contacts $scope.contactsFiltered = undefined; } // Validate if Inputs are empty && search into result service compare with filter $scope.contactFilteredFn = function (){ $scope.contactsFiltered = []; for(var i = 0; i < $scope.contacts.length ; i++) { if ($scope.filter.username == undefined && $scope.filter.name == undefined && $scope.filter.company == undefined){ // no data in any input $scope.contactReset(); return; }else{ // validate its username like to name if( $scope.contacts[i].username.indexOf($scope.filter.username) != -1 || $scope.contacts[i].name.indexOf($scope.filter.name) != -1 || $scope.contacts[i].company.name.indexOf($scope.filter.company) != -1 ){ $scope.contactsFiltered.push($scope.contacts[i]); } } }; return $scope.contactsFiltered; } }); /* END Buscador-Contacto.FILTRO CONTROLLER */ <file_sep>/src/proteo.ui.buscador-contacto.filtro-module.js /* Buscador-Contacto.FILTRO MODULE */ angular.module('proteo.ui.buscador-contacto.filtro',['pascalprecht.translate']) .config(['$translateProvider', function ($translateProvider) { // custom code }]); /* END Buscador-Contacto.FILTRO MODULE */
2447fa8852bd06e7c4f55d43e79f719799a6e133
[ "JavaScript" ]
3
JavaScript
rzazo131586/proteo.ui.buscador-contacto.filtro
1e5f1368a58413fc2330603e0146147b0b532185
e9b0b59f5b6fb092e7182b402c2b08a1b2cab7dd
refs/heads/master
<repo_name>halkar/tess-two-xamarin-android-binding<file_sep>/README.md # tess-two-xamarin-android-binding <file_sep>/Test.Test/MainActivity.cs using System; using Android.App; using Android.Content; using Android.Graphics; using Android.Media; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Com.Googlecode.Leptonica.Android; using Com.Googlecode.Tesseract.Android; namespace Test.Test { [Activity(Label = "Test.Test", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { int count = 1; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button>(Resource.Id.MyButton); button.Click += delegate { TessBaseAPI api = new TessBaseAPI(new MyProcessNotifier()); bool result = api.Init("/mnt/sdcard/tesseract-ocr/", "eng"); ///storage/emulated/0/DCIM/Camera/IMG_20150530_124916.jpg //ExifInterface exif = new ExifInterface("/storage/emulated/0/DCIM/Camera/IMG_20150530_124916.jpg"); BitmapFactory.Options options = new BitmapFactory.Options(); options.InSampleSize = 4; Bitmap bitmap = BitmapFactory.DecodeFile("/storage/emulated/0/DCIM/Camera/IMG_20150530_124916.jpg", options); api.SetImage(bitmap); String recognizedText = api.UTF8Text; api.End(); }; } } public class MyProcessNotifier : Java.Lang.Object, TessBaseAPI.IProgressNotifier { public void OnProgressValues(TessBaseAPI.ProgressValues p0) { } } } <file_sep>/Tess.Binding/Additions/PixIterator.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Tess.Binding.Additions { // public partial class PixIterator // { // // } }
61ecae6f9408a056a3f1a7d5396ea73a3fef88d6
[ "Markdown", "C#" ]
3
Markdown
halkar/tess-two-xamarin-android-binding
c098bcdfbc9ee50f1045247fea004503e5ab8056
94eff0876c2f9a39e7e3c5c23a5f84ad4a0c9f08
refs/heads/master
<repo_name>sdeepak97/shopX-fullstack<file_sep>/backend/src/database/cart/repo/cart.repo.ts import { EntityRepository, getCustomRepository, Repository } from "typeorm"; import { Request, Response } from "express"; import dotenv from "dotenv"; import { CartEntity } from "../entity/cart.entity"; import { UserRepository } from "../../user/repository/user.repo"; dotenv.config(); @EntityRepository(CartEntity) export class CartRepository extends Repository<CartEntity> { //! Adding data in cart async addToCart(req: Request, res: Response) { let { useremail, product_price, product_name } = req.body; try { let userRepo = getCustomRepository(UserRepository); let user = await userRepo.findOne({ useremail: useremail }); if (user) { const cartitem = new CartEntity(); cartitem.user = user; cartitem.product_name = product_name; cartitem.product_price = product_price; await cartitem.save(); return res.json({ added: true, message: "Product added to cart", }); } } catch (err) { console.log(err); return res.send({ added: false, message: "Something went wrong, try again", }); } } //! Get cart prodcuts async getCartProducts(req: Request, res: Response) { let { useremail } = req.params; let userRepository = getCustomRepository(UserRepository); let user = await userRepository.findOne({ useremail: useremail }); try { let cartData = await this.createQueryBuilder("cart") .select() .leftJoin("cart.user", "user") .where("user.id = :id", { id: user?.id }) .getMany(); if (cartData.length === 0) { return res.send({ received: true, filled: false, data: "Oops! Cart is empty!", }); } return res.send({ received: true, filled: true, data: cartData, }); } catch (error) { return res.send({ received: false, filled: false, data: "Something went wrong, try again", }); } } //! Delete Cart data async deleteCartData(req: Request, res: Response) { let { productId } = req.params; try { await this.createQueryBuilder("cart") .delete() .where("cart.product_id = :product_id", { product_id: productId }) .execute() .then((data: any) => { return res.send({ deleted: true, data: data, }); }); } catch (error) { console.log(error); return res.send({ deleted: false, data: "Something went wrong, try again", }); } } } <file_sep>/backend/src/database/user/repository/user.repo.ts import { EntityRepository, Repository } from "typeorm"; import { UserEntity } from "../entity/user.entity"; import { Request, Response } from "express"; import * as EmailValidator from "email-validator"; import dotenv from "dotenv"; import jwt from "jsonwebtoken"; import bcrypt from "bcrypt"; dotenv.config(); @EntityRepository(UserEntity) export class UserRepository extends Repository<UserEntity> { //!Login under the application async login(req: Request, res: Response) { let { useremail, newuserpassword } = req.body; let isValidated = EmailValidator.validate(useremail); let jwt_secret = process.env.JWT_SECRET as string; if (!isValidated) { return res.send({ authentication: false, data: "Invalid email", }); } else { //! Find the user password from the database let findUserPasswordFromDb = await this.createQueryBuilder("users") .select("users.userpassword") .where("users.useremail = :query", { query: useremail }) .getOne(); //! Find the user id from the database let userId = await this.createQueryBuilder("users") .select("users.id") .where("users.useremail = :query", { query: useremail }) .getOne(); bcrypt.compare( newuserpassword, findUserPasswordFromDb?.userpassword as string, (error: any, isPasswordMatched: any) => { console.log(newuserpassword, findUserPasswordFromDb?.userpassword); if (error) { return res.send({ authentication: false, data: error, }); } if (!isPasswordMatched) { return res.send({ authentication: false, data: "Incorrect password", }); } if (isPasswordMatched) { jwt.sign( { useremail: useremail, }, jwt_secret, { expiresIn: "2h", }, async (error: any, authdata: any) => { if (error) { return res.send({ authentication: false, data: error, }); } else { return res.send({ authentication: true, data: authdata, }); } } ); } } ); } } //!Create a new user async signUp(req: Request, res: Response) { let { username, useremail, userpassword } = req.body; let isValidated = EmailValidator.validate(useremail); let jwt_secret = process.env.JWT_SECRET as string; //If the email is fraud or invalid if (!isValidated) { return res.send({ authentication: false, data: "Invalid email", }); } //!Check if the user already exists in database or not let emailExists = (await this.createQueryBuilder("users") .where("users.useremail = :query", { query: useremail }) .getCount()) > 0; //Output is boolean if (emailExists) { return res.send({ authentication: false, data: "Email is taken, Try another one!", }); } else { const salt = await bcrypt.genSalt(10); console.log(salt); bcrypt.hash( //!HMAC userpassword, salt, async (error: any, hashedpassword: any) => { if (error) { return res.send({ authentication: false, data: error, }); } else { //! Creating new user let user = new UserEntity(); user.username = username; user.userpassword = <PASSWORD>; //! Adding hashed password instead of plain user.useremail = useremail; //!Saving the user await this.save(user); //! Create JWT => Sign jwt let userid = this.createQueryBuilder("users") .select("users.id") .where("users.useremail = :query", { query: useremail }) .getOne(); jwt.sign( { useremail: useremail, }, jwt_secret, { expiresIn: "2h", }, async (error: any, authData: any) => { if (error) { return res.send({ authentication: false, data: error, }); } else { return res.send({ authentication: true, data: authData, }); } } ); } } ); } } //! Decoding users JWT async decodeUserData(req: Request, res: Response) { let jwt_secret = process.env.JWT_SECRET as string; let tokendata = req.headers.authorization as string; jwt.verify(tokendata, jwt_secret, async (error: any, userdata: any) => { if (error) { console.log(error); return res.send({ received: false, data: null, }); } else { return res.send({ received: true, data: userdata, }); } }); } } <file_sep>/backend/src/ormconfig.ts import { join } from "path"; import { ConnectionOptions } from "typeorm"; import { CartEntity } from "./database/cart/entity/cart.entity"; import { ProductEntity } from "./database/products/entity/products.entity"; import { UserEntity } from "./database/user/entity/user.entity"; import { UserInfoEntity } from "./database/user_info/entity/userinfo.entity"; import dotenv from "dotenv"; dotenv.config(); const connectionOptions: ConnectionOptions = { url: process.env.DATABASE_URL, ssl: { rejectUnauthorized: false }, type: "postgres", host: process.env.Host || "localhost", port: 5432 || process.env.DB_Port, username: process.env.User || "postgres", password: process.env.DB_Password || "<PASSWORD>", database: process.env.Database || "postgres", entities: [UserEntity, CartEntity, UserInfoEntity, ProductEntity], synchronize: true, dropSchema: false, migrationsRun: true, logging: false, logger: "debug", migrations: [join(__dirname, "src/migration/**/*.ts")], }; export = connectionOptions; <file_sep>/backend/src/controllers/cart.controller.ts import { Response, Request } from "express"; import dotenv from "dotenv"; import { getManager } from "typeorm"; import { CartRepository } from "../database/cart/repo/cart.repo"; dotenv.config(); export class CartController { static async addToCart(req: Request, res: Response) { let connectionmanager = getManager().getCustomRepository(CartRepository); await connectionmanager.addToCart(req, res); } static async getCartProducts(req: Request, res: Response) { let connectionmanager = getManager().getCustomRepository(CartRepository); await connectionmanager.getCartProducts(req, res); } static async deleteCartData(req: Request, res: Response) { let connectionmanager = getManager().getCustomRepository(CartRepository); await connectionmanager.deleteCartData(req, res); } } <file_sep>/backend/src/database/user/entity/user.entity.ts import { BaseEntity, Column, Entity, JoinColumn, OneToMany, OneToOne, PrimaryGeneratedColumn, } from "typeorm"; import { CartEntity } from "../../cart/entity/cart.entity"; import { UserInfoEntity } from "../../user_info/entity/userinfo.entity"; @Entity("users") export class UserEntity extends BaseEntity{ @PrimaryGeneratedColumn("increment") id!: string; @Column({ nullable: true, unique: false, }) username!: string; @Column({ nullable: true, unique: true, }) useremail!: string; @Column({ nullable: true, unique: false, }) userpassword!: string; //! OTM with cart @OneToMany(() => CartEntity, (cart) => cart.user) @JoinColumn() item!: CartEntity[]; //! OTO with info @OneToOne(() => UserInfoEntity, (info) => info.user) info!: UserInfoEntity; } <file_sep>/backend/src/database/user_info/entity/userinfo.entity.ts import { BaseEntity, Column, Entity, JoinColumn, OneToOne, PrimaryGeneratedColumn, } from "typeorm"; import { UserEntity } from "../../user/entity/user.entity"; @Entity("info") export class UserInfoEntity extends BaseEntity{ @PrimaryGeneratedColumn("increment") id!: string; @Column() useraddress!: string; @Column() userphoneno!: string; //! OTO with user @OneToOne(() => UserEntity, (user) => user.info, { cascade: ["update"], createForeignKeyConstraints: false, }) @JoinColumn() user!: UserEntity; } <file_sep>/backend/src/database/user_info/repo/userinfo.repo.ts import { EntityRepository, getCustomRepository, Repository } from "typeorm"; import { Request, Response } from "express"; import dotenv from "dotenv"; import { UserInfoEntity } from "../entity/userinfo.entity"; import { UserRepository } from "../../user/repository/user.repo"; dotenv.config(); @EntityRepository(UserInfoEntity) export class UserInfoRepository extends Repository<UserInfoEntity> { //! Adding some user info async addUserInfo(req: Request, res: Response) { let { useremail, useraddress, userphoneno } = req.body; let userRepo = getCustomRepository(UserRepository); let user = await userRepo.findOne({ useremail: useremail }); try { let userInfo = new UserInfoEntity(); (userInfo.useraddress = useraddress), (userInfo.userphoneno = userphoneno), (userInfo.user = user!); await userInfo.save(); return res.send({ added: true, message: "User info added", }); } catch (error) { console.log(error); if (error) { } return res.send({ added: false, message: "Something went wrong", }); } } //! Get user info async showUserInfo(req: Request, res: Response) { let { useremail } = req.params; let userRepo = getCustomRepository(UserRepository); let user = await userRepo.findOne({ useremail: useremail }); try { let userInfoData = await this.createQueryBuilder("info") .leftJoinAndSelect("info.user", "user") .where("info.id = :id", { id: user?.id }) .getOne(); if (userInfoData !== undefined) { return res.send({ info: userInfoData, filled: true, received: true, }); } else { return res.send({ info: "Fill some info first", received: true, filled: false, }); } } catch (error) { if (error) { return res.send({ info: "Something went wrong, Please try again", received: false, }); } } } //! Updating user info async updateUserInfo(req: Request, res: Response) { let { infoId } = req.params; let { useraddress, userphoneno } = req.body; try { await this.createQueryBuilder("info") .leftJoinAndSelect("info.user", "user") .update(UserInfoEntity) .set({ useraddress: useraddress, userphoneno: userphoneno, }) .where("info.id = :id", { id: infoId }) .execute() .then((updatedData: any) => { return res.send({ updated: true, data: updatedData, }); }); } catch (error) { if (error) { console.log(error); return res.send({ updated: false, data: "Something went wrong", }); } } } } <file_sep>/backend/src/database/products/entity/products.entity.ts import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from "typeorm"; @Entity("products") export class ProductEntity { @PrimaryGeneratedColumn() product_id!: string; @Column() product_name!: string; @Column() product_price!: string; @Column() product_image!: string; @Column() product_description!: string; @Column() product_category!: string; } <file_sep>/backend/src/app.ts import express from "express"; import dotenv from "dotenv"; import "reflect-metadata"; import cors from "cors"; import { authrouter } from "./routes/authentication.routes"; import { createConnection, ConnectionOptions } from "typeorm"; import config from "./ormconfig"; import { productrouter } from "./routes/products.routes"; import { cartrouter } from "./routes/cart.routes"; import { inforouter } from "./routes/userinfo.routes"; dotenv.config(); createConnection(config as ConnectionOptions) .then(async (connection) => { if (connection.isConnected) { console.log(`📅 is connected!!`); } const app = express(); app.use(cors()); app.use(express.json()); app.use(express.urlencoded({ extended: false })); const port = process.env.PORT || 8000; app.set("port", port); app.get("/", (req, res) => { res.send("SHOPEX API"); }); //! Authentication routes app.use("/user", authrouter); //! Product routes app.use("/products", productrouter); //! Cart routes app.use("/cart", cartrouter); //! Userinfo routes app.use("/info", inforouter); //! Listening to port app.listen(app.get("port"), () => { console.log(`Server is rocking at ${app.get("port")}🚀`); }); }) .catch((error) => { console.log(error); }); <file_sep>/backend/src/routes/authentication.routes.ts import Router from "express"; import { AuthenticationController } from "../controllers/authentication.controller"; const authrouter = Router(); //! @GET authrouter.get("/verify", AuthenticationController.decodeUserData); //!POST authrouter.post("/signup", AuthenticationController.signUp); authrouter.post("/login", AuthenticationController.login); export { authrouter }; <file_sep>/backend/src/routes/userinfo.routes.ts import Router from "express"; import { UserInfoController } from "../controllers/userinfo.controller"; const inforouter = Router(); //! @GET inforouter.get("/:useremail", UserInfoController.showUserInfo); //! @POST inforouter.post("/add-user-info", UserInfoController.addUserInfo); //! @PUT inforouter.put("/update/:infoId", UserInfoController.updateUserInfo); export { inforouter }; <file_sep>/backend/src/controllers/product.controller.ts import { Response, Request } from "express"; import dotenv from "dotenv"; import { getManager } from "typeorm"; import { ProductRepository } from "../database/products/repo/products.repo"; dotenv.config(); export class ProductController { static async addProducts(req: Request, res: Response) { let connectionmanager = getManager().getCustomRepository(ProductRepository); await connectionmanager.addProducts(req, res); } static async showProducts(req: Request, res: Response) { let connectionmanager = getManager().getCustomRepository(ProductRepository); await connectionmanager.showProducts(req, res); } static async loadProductDetails(req: Request, res: Response) { let connectionmanager = getManager().getCustomRepository(ProductRepository); await connectionmanager.loadProductDetails(req, res); } static async deleteProduct(req: Request, res: Response) { let connectionmanager = getManager().getCustomRepository(ProductRepository); await connectionmanager.deleteProduct(req, res); } } <file_sep>/backend/src/routes/cart.routes.ts import Router from "express"; import { AuthenticationController } from "../controllers/authentication.controller"; import { CartController } from "../controllers/cart.controller"; const cartrouter = Router(); //! @GET cartrouter.get("/:useremail", CartController.getCartProducts); //! @POST cartrouter.post("/add-to-cart", CartController.addToCart); //! @DELETE cartrouter.delete("/delete/:productId", CartController.deleteCartData); export { cartrouter }; <file_sep>/backend/src/database/cart/entity/cart.entity.ts import { BaseEntity, Column, Entity, ManyToOne, PrimaryGeneratedColumn, } from "typeorm"; import { UserEntity } from "../../user/entity/user.entity"; @Entity("cart") export class CartEntity extends BaseEntity { @PrimaryGeneratedColumn() product_id!: string; @Column() product_name!: string; @Column({ type: "bigint" }) product_price!: bigint; //! MTO with user @ManyToOne(() => UserEntity, (user) => user.item) user!: UserEntity; } <file_sep>/backend/src/controllers/authentication.controller.ts import jwt from "jsonwebtoken"; import { Response, Request } from "express"; import dotenv from "dotenv"; import { getManager } from "typeorm"; import { UserRepository } from "../database/user/repository/user.repo"; dotenv.config(); export class AuthenticationController { static async signUp(req: Request, res: Response) { let connectionmanager = getManager().getCustomRepository(UserRepository); await connectionmanager.signUp(req, res); } static async login(req: Request, res: Response) { let connectionmanager = getManager().getCustomRepository(UserRepository); await connectionmanager.login(req, res); } static async decodeUserData(req: Request, res: Response) { let connectionmanager = getManager().getCustomRepository(UserRepository); await connectionmanager.decodeUserData(req, res); } } <file_sep>/backend/src/database/products/repo/products.repo.ts import { EntityRepository, Repository } from "typeorm"; import { Request, Response } from "express"; import dotenv from "dotenv"; import { ProductEntity } from "../entity/products.entity"; dotenv.config(); @EntityRepository(ProductEntity) export class ProductRepository extends Repository<ProductEntity> { //! Add products in database async addProducts(req: Request, res: Response) { let { product_name, product_price, product_image, product_description, product_category, } = req.body; await this.createQueryBuilder() .insert() .into(ProductEntity) .values({ product_name: product_name, product_price: product_price, product_image: product_image, product_description: product_description, product_category: product_category, }) .execute() .catch((error: any) => { if (error) { return res.send({ added: false, data: error, }); } }) .then((productData: any) => { return res.send({ added: true, data: productData, }); }); } //! Show products to the user async showProducts(req: Request, res: Response) { let products = await this.createQueryBuilder().select().getMany(); if (products != null) { if (products.length === 0) { return res.send({ data: "No products available", filled: false, received: true, }); } return res.send({ data: products, filled: true, received: true, }); } else { return res.send({ data: "No products available", filled: false, received: false, }); } } //! Loading products details to the user async loadProductDetails(req: Request, res: Response) { let { productId } = req.params; try { let detailedProductData = await this.createQueryBuilder() .select() .where("product_id = :productId", { productId: productId }) .getOne(); if (detailedProductData !== undefined) { return res.send({ data: detailedProductData, available: true, received: true, }); } else { return res.send({ available: false, data: "Product is unavailable", received: true, }); } } catch (error) { console.log(error); return res.send({ received: false, data: "Something went wrong, Try again", }); } } //! Delete products async deleteProduct(req: Request, res: Response) { let adminsecret = req.headers.authorization; if (adminsecret === "9848755758") { let { product_id } = req.params; await this.createQueryBuilder() .delete() .where("products.product_id = :product_id", { product_id: product_id }) .execute() .then((data: any) => { return res.send({ deleted: true, message: data, }); }); } else { return res.send({ deleted: false, message: "You are not any admin, Brush your teeth", }); } } } <file_sep>/backend/src/routes/products.routes.ts import Router from "express"; import { ProductController } from "../controllers/product.controller"; const productrouter = Router(); //! @GET productrouter.get("/", ProductController.showProducts); productrouter.get("/details/:productId", ProductController.loadProductDetails); //! @POST productrouter.post("/add-products", ProductController.addProducts); //! @DELETE productrouter.delete("/delete/:product_id", ProductController.deleteProduct); export { productrouter }; <file_sep>/backend/src/controllers/userinfo.controller.ts import { Response, Request } from "express"; import dotenv from "dotenv"; import { getManager } from "typeorm"; import { UserInfoRepository } from "../database/user_info/repo/userinfo.repo"; dotenv.config(); export class UserInfoController { static async addUserInfo(req: Request, res: Response) { let connectionmanager = getManager().getCustomRepository(UserInfoRepository); await connectionmanager.addUserInfo(req, res); } static async showUserInfo(req: Request, res: Response) { let connectionmanager = getManager().getCustomRepository(UserInfoRepository); await connectionmanager.showUserInfo(req, res); } static async updateUserInfo(req: Request, res: Response) { let connectionmanager = getManager().getCustomRepository(UserInfoRepository); await connectionmanager.updateUserInfo(req, res); } }
01b5d7793403bf393eefb9ef7f24e3e258697614
[ "TypeScript" ]
18
TypeScript
sdeepak97/shopX-fullstack
fbaf9af336d238de86aeb10c06eb83aa20bbf0c2
bfe06bd9d185d8a157d3a99acd4eefdd0d27dd9f
refs/heads/master
<file_sep>package sample; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.stage.Stage; import java.io.IOException; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Controller { public Button bMain, bRegistration, bPerInfo, bRecords; @FXML public TextField campusId, password; @FXML public Button loginB; @FXML public Label userPassWrong; @FXML private Label Hiname; @FXML public Label gpaText, degreeText; java.sql.Connection conn = null; ResultSet rs = null; Statement st; @FXML private void mainBClicked(ActionEvent event) throws IOException { Stage stage; Parent root; stage=(Stage) ((Button)(event.getSource())).getScene().getWindow(); root = FXMLLoader.load(getClass().getResource("MainMenu.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Main Menu"); stage.show(); } @FXML private void recordsBClicked(ActionEvent event) throws IOException { Stage stage; Parent root; stage=(Stage) ((Button)(event.getSource())).getScene().getWindow(); root = FXMLLoader.load(getClass().getResource("Records.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Records Menu"); stage.show(); } @FXML private void infoBClicked(ActionEvent event) throws IOException { Stage stage; Parent root; stage=(Stage) ((Button)(event.getSource())).getScene().getWindow(); root = FXMLLoader.load(getClass().getResource("PersonalInfo.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Personal Information Menu"); stage.show(); } @FXML private void registrationBClicked(ActionEvent event) throws IOException { Stage stage; Parent root; stage=(Stage) ((Button)(event.getSource())).getScene().getWindow(); root = FXMLLoader.load(getClass().getResource("Registration.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Registration Menu"); stage.show(); } @FXML private void mainHClicked(ActionEvent event) throws IOException { Stage stage; Parent root; stage=(Stage) ((Hyperlink)(event.getSource())).getScene().getWindow(); root = FXMLLoader.load(getClass().getResource("MainMenu.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Main Menu"); stage.show(); } @FXML private void recordsHClicked(ActionEvent event) throws IOException { Stage stage; Parent root; stage=(Stage) ((Hyperlink)(event.getSource())).getScene().getWindow(); root = FXMLLoader.load(getClass().getResource("Records.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Records Menu"); stage.show(); } @FXML private void perInfoHClicked(ActionEvent event) throws IOException { Stage stage; Parent root; stage=(Stage) ((Hyperlink)(event.getSource())).getScene().getWindow(); root = FXMLLoader.load(getClass().getResource("PersonalInfo.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Personal Information Menu"); stage.show(); } @FXML private void registrationHClicked(ActionEvent event) throws IOException { Stage stage; Parent root; stage=(Stage) ((Hyperlink)(event.getSource())).getScene().getWindow(); root = FXMLLoader.load(getClass().getResource("Registration.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Registration Menu"); stage.show(); } @FXML private void classScheduleSearchClicked(ActionEvent event) throws IOException { Stage stage; Parent root; stage=(Stage) ((Hyperlink)(event.getSource())).getScene().getWindow(); root = FXMLLoader.load(getClass().getResource("/application/Main.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Schedule Search"); stage.show(); } @FXML public void Login(ActionEvent event) throws Exception{ try { if (!campusId.getText().isEmpty() && !password.getText().isEmpty()) { String user = campusId.getText(); String pass = password.getText(); conn = DriverManager.getConnection("jdbc:sqlite:UpdatedDB.db"); st = (Statement) conn.createStatement(); rs = st.executeQuery("SELECT * FROM StudentTable where Username = '" + user + "' AND Password_Plain = '" + pass+"'"); if(rs.next()) { if (rs.getString(16).equals(user) && rs.getString(17).equals(pass)) { Stage stage; Parent root; stage = (Stage) ((Button) (event.getSource())).getScene().getWindow(); root = FXMLLoader.load(getClass().getResource("MainMenu.fxml")); Scene scene = new Scene(root); String str = rs.getString(2); stage.setScene(scene); stage.show(); rs.close(); } Hiname.setText("Hello"); } else{ userPassWrong.setText("CampusId or Password wrong."); } } } catch (Exception e ){ throw e; } } @FXML public void setName(String name) { Hiname.setText(name); } } <file_sep>#include <stdio.h> #include <math.h> int main(){ float final, loan, interest, pay_num, r, p, in, l, c, balance; printf("Enter amount of loan : "); scanf("%f", &loan); printf("Enter Interest rate per year : "); scanf("%f", &interest); printf("Enter number of payments : "); scanf("%f", &pay_num); r = pow(1 + (interest/12/100), pay_num); balance = loan; final = loan * ((interest/12/100 * r)/(r - 1)); printf(" Montly payment should be %.2f\n", final); printf("======================AMORTIZATION SCHEDULE=======================\n"); printf("#\t Payment\t Principal\t Interest\t Balance\t\n"); int i; for(i = 1; i <= pay_num; i++){ in = balance * (interest/12/100); p = final - in; balance -= final; balance += in; printf("%d \t %.2f \t %.2f \t %.2f \t %.2f \t\n", i, final, p, in, balance); } } <file_sep># testt # testt # GuessTheNumber <file_sep>package sample; public class Personal_Info_Controller { } <file_sep>#include <stdio.h> #include <math.h> #include <stdlib.h> struct loan{ double INTEG; double B; double P; } object[100]; int main(int argc, char *argv[]){ float final, r, p, in, l, c, balance, interest, pay_num, loan; interest = atoi(argv[2]); loan = atoi(argv[1]); in = interest/1200; pay_num = atoi(argv[3]); r = pow(1 + (in), pay_num); object[0].B = loan; final = loan * ((interest/12/100 * r)/(r - 1)); printf(" Montly payment should be %.2f\n", final); printf("======================AMORTIZATION SCHEDULE=======================\n"); printf("#\t Payment\t Principal\t Interest\t Balance\t\n"); int i; for(i = 1; i <= pay_num; i++){ object[i].INTEG = object[i-1].B * in; object[i].P = final - object[i].INTEG; object[i].B = object[i-1].B - object[i].P; printf("%d \t %.2f \t %.2f \t %.2f \t %.2f \t\n", i, final, object[i].P, object[i].INTEG, object[i].B); } return 0; }
b6199abe08586e153408063afa96a6e4f40be1aa
[ "Markdown", "Java", "C" ]
5
Java
mikeshprd/testt
4b29104b350e4e19bc2126af4412880e8bc10725
3aa2a61740512b2dc8235ae2ae9a51bd28437e09
refs/heads/master
<repo_name>dma446/currency-converter<file_sep>/README.md # currency-converter Allows you to convert from one currency to another using current exchange rates. <file_sep>/currency_converter/js/cc_popup.js $(document).ready(function() { $('#button').click(function() { $.getJSON('http://data.fixer.io/api/latest?access_key=dc44288a96a8f50e5253344272e5c835&format=1', function(exchange_rates) { var base_value = $('#base_value').val(); var base_curr = $('#base_curr').val(); var new_curr = $('#new_curr').val(); var new_value = base_value / exchange_rates.rates[base_curr] * exchange_rates.rates[new_curr]; new_value = Math.round((new_value + 0.00001) * 100) / 100; $('#new_value').val(new_value); }); }); });
af9a66586a49dab0f659a5ad80a4a9ef5febfe9e
[ "Markdown", "JavaScript" ]
2
Markdown
dma446/currency-converter
2b50a262b5fe9a03020e4d722808df76c35c91d5
10498b92a7a455c822ebfc57fe7dc5db1fb37fa6
refs/heads/master
<file_sep># bashScripting Scripting exercises from http://www.tldp.org/LDP/abs/html/<br> (The linux documentation project) <file_sep>#!/bin/bash LOGFILE=log2_2prelim.txt echo "Date:" 1>$LOGFILE echo "Date:" date 1>>$LOGFILE date echo "Logged in users:" 1>>$LOGFILE echo "Logged in users:" who 1>>$LOGFILE who
6b6af96580296a2855b9f5d71610aff4ff052d01
[ "Markdown", "Shell" ]
2
Markdown
sachdevs/bash_Scripting
55df4a66eabc93b6faca5fbb8bb51857c4aaf443
5cb792fbfebaac656cbd21ae29dd2634fa10a06a
refs/heads/master
<file_sep>from tkinter import * import time import math #file-rwc def rwc_copy(file, copyFile): f1 = open(Originale, "r") f2 = open(Copia, "w") while 1: Testo = f1.read(50) if Testo == "": break f2.write(Testo) f1.close() f2.close() return def rwc_open(file): try: f=open(file,"r") text=f.read() f.close() except: print('=> Il file "'+str(fI)+'" non esiste\n') def rwc_create(file): f=open(file,"w") f.close() #mat def add(a,b): ad=a+b print("=> Il risultato è:",ad) def sot(a,b): so=a-b print("=> Il risultato è:",so) def mol(a,b): mo=a*b print("=> Il risultato è:",mo) def div(a,b): di=a/b print("=> Il risultato è:",di) def pot(a,b): a1=a for i in range(b,1,-1): a=a*a1 print("=> Il risultato è:",int(a)) def rad(a): ra=math.sqrt(a) print("=> Il risultato è:",ra) def add3(a,b,c): ad=a+b+c print("=> Il risultato è:",ad) def sot3(a,b,c): so=a-b-c print("=> Il risultato è:",so) def mol3(a,b,c): mo=a*b*c print("=> Il risultato è:",mo) def div3(a,b,c): di=a/b/c print("=> Il risultato è:",di) def equa2(a,b,c): r=0 de=(b*b)-4*a*c if(de<0): print("=> L'equazione di secondo grado è impossibile perché delta è 0.") print("") else: e=((b*-1)+math.sqrt(de)) q=(2*a) e1=e q1=q if(e<q): r=q q=e e=r while(q!=0): r=e%q e=q q=r mcd=e e=int(e1/mcd) q=int(q1/mcd) if(q<0): q=q*-1 e=e*-1 if(q==1): print("=> x1=",e) elif(q!=1): print("=> x1=",e,"/",q) r=0 e2=((b*-1)-math.sqrt(de)) q2=(2*a) e3=e2 q3=q2 if(e2<q2): r=q2 q2=e2 e2=r while(q2!=0): r=e2%q2 e2=q2 q2=r mcd2=e2 e2=int(e3/mcd2) q2=int(q3/mcd2) if(q2<0): q2=q2*-1 e2=e2*-1 if(q==1): print("=> x2=",e2) elif(q!=1): print("=> x2=",e2,"/",q2) #sistema def sis(a,b,c,a1,b1,c1): D=a*b1-a1*b Dx=c*b1-c1*b Dy=a*c1-a1*c Dx1=Dx D1=D r=0 if(Dx<D): r=D D=Dx Dx=r while(D!=0): r=Dx%D Dx=D D=r mcd=Dx Dx=int(Dx1/mcd) D=int(D1/mcd) if(D<0): D=D*-1 Dx=Dx*-1 if(D==1): print("=> X=",Dx) elif(D!=1): print("=> X=",Dx,"/",D) print("") Dy1=Dy D1=D r=0 if(Dy<D): r=D D=Dy Dy=r while(D!=0): r=Dy%D Dy=D D=r mcd=Dy Dy=int(Dy1/mcd) D=int(D1/mcd) if(D<0): D=D*-1 Dy=Dy*-1 if(D==1): print("=> Y=",Dy) elif(D!=1): print("=> Y=",Dy,"/",D) #My_Window def add_text(text, teext): texxt="" t=text.get(1.0,END) texxt += str(teext) text.insert(END, texxt) def delete(text): text.delete(0.0, END) def prt(prtx): print(prtx) def exit_prog(root): root.destroy() exit() def backup(nameBackup, nameProg, text): backup=open(nameBackup+".dat","w") prog=open(nameProg+".py","r") PG=prog.read() backup.write(PG) backup.close() prog.close() texxt="" text.delete(0.0, END) texxt += "=> Il backup è stato eseguito con successo...\n" text.insert(0.0, texxt) def entry_open(entry, text): fI=entry.get() try: f=open(fI,"r") texxt=str(f.read())+"\n" text.insert(0.0, texxt) f.close() except: text.delete(0.0, END) texxt='=> Il file "'+str(fI)+'" non esiste\n' text.insert(0.0, texxt) def entry_save(entry, text): texxt="" fI=entry.get() try: f=open(fI,"r") f.close() f=open(fI,"w") f.write(text.get(1.0,END)) f.close() except: text.delete(0.0, END) texxt='=> Il file "'+str(fI)+'" non esiste\n' text.insert(0.0, texxt) def entry_create(entry): fI=entry.get() f=open(fI,"w") f.close() def root(nameRoot, nameWindow, dimX, dimY): nameRoot = Tk() nameRoot.title(nameWindow) dimX=str(dimX) dimY=str(dimY) nameRoot.geometry(dimX+"x"+dimY) def loop(nameRoot): name.mainloop() <file_sep># My_Library #this library interacts in various fields, expanding and simplifying, helps you manage the files: math and tkinter <file_sep>from setuptools import setup, find_packages setup(name='My_Library', version='0.1', url='https://github.com/DAEXDO3240/My_Library', license='MIT', author='<NAME>', author_email='<EMAIL>', description='this library interacts in various fields, expanding and simplifying, helps you manage the files: math and tkinter', packages=find_packages(exclude=['tests']), long_description=open('README.md').read(), zip_safe=False)
1e97cbad11e32d5c613e798de0102339980e569e
[ "Markdown", "Python" ]
3
Python
DAEXDO3240/My_Library
7a166ff4df0f2f4f7fdae81610103d9bb417bba0
95e4d9b8c4628a09adf8b023edb9c321f3b40ccd
refs/heads/master
<file_sep>using System; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Converters; /* http://help.mandrill.com/entries/21738186-introduction-to-webhooks Simple MVC Controller example [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post | HttpVerbs.Head)] public ActionResult Hook(string id, FormCollection val) { //... var events = Mandrill.JSON.Parse<List<Mandrill.WebHookEvent>> (val.Get("mandrill_events")); //... return View(); } */ namespace Mandrill { public enum WebHookEventType { Send, // message has been sent Hard_bounce, // message has hard bounced Soft_bounce, // message has soft bounced Open, // recipient opened a message; will only occur when open tracking is enabled Click, // recipient clicked a link in a message; will only occur when click tracking is enabled Spam, // recipient marked a message as spam Unsub, // recipient unsubscribed Reject // message was rejected } public enum WebHookMessageState { Sent, Rejected, Spam, Unsub, Bounced, Soft_bounced } public class WebHookEvent { [JsonConverter(typeof(StringEnumConverter))] public WebHookEventType Event { get; set; } public uint TS { get; set; } public DateTime TimeStamp { get { return FromUnixTime (TS); } } public WebHookMessage Msg { get; set; } // TODO Need to find the time zone for Mandrill time stamps public static DateTime FromUnixTime (long unixTime) { var epoch = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return epoch.AddSeconds (unixTime); } } public class WebHookMessage { [JsonProperty("_id")] public string Id { get; set; } [JsonConverter(typeof(StringEnumConverter))] public WebHookMessageState State { get; set; } public uint TS { get; set; } public DateTime TimeStamp { get { return WebHookEvent.FromUnixTime (TS); } } public string Subject { get; set; } public string Sender { get; set; } public string Email { get; set; } public List<WebHookOpen> Opens { get; set; } public List<WebHookClick> Clicks { get; set; } } public class WebHookOpen { public uint TS { get; set; } public DateTime TimeStamp { get { return WebHookEvent.FromUnixTime (TS); } } } public class WebHookClick { public uint TS { get; set; } public DateTime TimeStamp { get { return WebHookEvent.FromUnixTime (TS); } } public string Url { get; set; } } }
f4dbf694ff8263cb6bd0ac1d4d1c3c18b4ebe172
[ "C#" ]
1
C#
ajtatum/Mandrill-dotnet
4b49af54beccd9ff649224d62b5b0b43bf4b8c6a
ad3079a3562eb4e5e7381046fcd69f26dae6f181
refs/heads/master
<file_sep>-- -- PostgreSQL database dump -- -- Dumped from database version 9.5.4 -- Dumped by pg_dump version 9.5.1 -- Started on 2016-11-06 23:43:02 SET statement_timeout = 0; SET lock_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SET check_function_bodies = false; SET client_min_messages = warning; SET row_security = off; -- -- TOC entry 9 (class 2615 OID 5347635) -- Name: weev; Type: SCHEMA; Schema: -; Owner: omntoujyfmjjuv -- CREATE SCHEMA weev; ALTER SCHEMA weev OWNER TO omntoujyfmjjuv; SET search_path = weev, pg_catalog; SET default_tablespace = ''; SET default_with_oids = false; -- -- TOC entry 186 (class 1259 OID 5347741) -- Name: users; Type: TABLE; Schema: weev; Owner: omntoujyfmjjuv -- CREATE TABLE users ( username character varying(16) NOT NULL, password character(32) ); ALTER TABLE users OWNER TO omntoujyfmjjuv; -- -- TOC entry 3001 (class 0 OID 5347741) -- Dependencies: 186 -- Data for Name: users; Type: TABLE DATA; Schema: weev; Owner: omntoujyfmjjuv -- COPY users (username, password) FROM stdin; larry <PASSWORD> john <PASSWORD> david <PASSWORD>4427 \. -- -- TOC entry 2886 (class 2606 OID 5347745) -- Name: users_pkey; Type: CONSTRAINT; Schema: weev; Owner: omntoujyfmjjuv -- ALTER TABLE ONLY users ADD CONSTRAINT users_pkey PRIMARY KEY (username); -- Completed on 2016-11-06 23:43:03 -- -- PostgreSQL database dump complete -- <file_sep># weev test jira<file_sep>import React from 'react' import { render } from 'react-dom' import App from '../common/components/App' // import MainStore from '../common/stores/MainStore' import packageJson from '../../package.json' import { autorun } from 'mobx' import injectTapEventPlugin from 'react-tap-event-plugin' injectTapEventPlugin() const preloadedState = window.PRELOADED_STATE // const store = new MainStore(preloadedState) const store = {} const rootElement = document.getElementById('app') render( <App store={store} />, rootElement )<file_sep>import express from 'express' import React from 'react' import { renderToString } from 'react-dom/server' import db from './database' import pjson from '../../package.json' import App from '../common/components/App' // import MainStore from '../common/stores/MainStore' const router = express.Router() function renderFullPage(app, preloadedState) { return ` <!doctype html> <html> <head> <title>${pjson.name} server rendering</title> <link rel="shortcut icon" type="image/png" href="http://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico?v=4f32ecc8f43d"/> </head> <body> <div id="app">${app}</div> <script> window.PRELOADED_STATE = ${JSON.stringify(preloadedState).replace(/</g, '\\x3c')} </script> <script src="/static/bundle.js"></script> </body> </html> ` } function handleRender(req, res) { // const store = new MainStore({ // title: pjson.name, // userAgent: req.headers['user-agent'], // version: pjson.version, // params: req.query, // }) const store = {} const app = renderToString( <App store={store} /> ) // const finalState = store.serialize() res.send(renderFullPage(app, {})) } router.get('/', handleRender) router.get('/tables', async (req, res) => { res.send(await db.query('SELECT * FROM pg_tables')) }) router.get('/version', (req, res) => { res.send(pjson.version) }) router.get('/users', (req, res) => { db.query('SELECT * FROM weev.users').then(data => { res.send(data) }) }) router.get('/users/:username', (req, res) => { const username = req.params.username const query = `SELECT * FROM weev.users where username='${username}'` console.log(query) db.query(query).then(data => { res.send(data) }) }) module.exports = router<file_sep>import express from 'express' import routes from './routes' import qs from 'qs' import webpack from 'webpack' import webpackDevMiddleware from 'webpack-dev-middleware' import webpackHotMiddleware from 'webpack-hot-middleware' import webpackConfig from '../../webpack.config' const PORT = process.env.PORT || 3000 const app = express() const compiler = webpack(webpackConfig) app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath })) app.use(webpackHotMiddleware(compiler)) app.use('/', routes) app.listen(PORT, () => { console.log(`Server running at: ${PORT}`) })
db78d7ad9ba332070e84b45e2c254aa8fe406d78
[ "Markdown", "SQL", "JavaScript" ]
5
SQL
warycat/weev
bf6627d38bd9270bbae1ebfa3ce153978906fddf
cc9d6d32390db0e1a6d8e1143d8b3a79080219b1
refs/heads/master
<repo_name>fringers/nextjs-demo<file_sep>/README.md ## Fringers Next.js Demo This is an example project created with [Next.js](https://nextjs.org/), [TypeScript](https://www.typescriptlang.org/) and [Firebase](https://firebase.google.com/). Cats images downloaded from [Pexels](https://www.pexels.com/). ## Articles 1. [Creating project (PL)](https://fringers.pl/blog/20201106_statyczna-strona-w-next-js-1-konfiguracja-projektu) 2. [Adding pages (PL)](https://fringers.pl/blog/20201110_statyczna-strona-w-next-js-2-dynamiczne-podstrony) **more articles comming soon** ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. <file_sep>/lib/gallery.ts import database from '../content/gallery.json' export interface Image { id: string src: string description: string } export function getAllImages(): Image[] { return Object.entries(database).map(image => { return { id: image[0], src: image[1].src, description: image[1].description } }) } export function getAllIds(): string[] { return Object.keys(database) } export function getImageById(id: string): Image { return { id, src: database[id].src, description: database[id].description } }
3c5061fbbf77f7dc2173155a0c61f66ddbff7787
[ "Markdown", "TypeScript" ]
2
Markdown
fringers/nextjs-demo
5f6a1d30811f97eb40632add47decbec2f5b4847
097b90cb913e7a2098222f90d04e38fb16a63034
refs/heads/master
<file_sep>#!/bin/bash # Helper functions used by several scripts. export OPENSHIFT_RUNTIME_DIR=${OPENSHIFT_HOMEDIR}/diy-0.1/runtime/ export OPENSHIFT_RUN_DIR=${OPENSHIFT_HOMEDIR}/diy-0.1/run/ export OPENSHIFT_LOG_DIR=${OPENSHIFT_DIY_LOG_DIR} export OPENSHIFT_BIN=${OPENSHIFT_RUNTIME_DIR}/bin/ export PATH=${OPENSHIFT_BIN}:$PATH<file_sep>#!/bin/bash # Exit on first error. set -e # OpenShift sets GIT_DIR to . which terminates pull with an error: # Not a git repository: '.' unset GIT_DIR umask 077 # Load common source ${OPENSHIFT_REPO_DIR}/.openshift/action_hooks/common # Configure versions NGINX_VERSION='1.5.1' ZLIB_VERSION='1.2.8' PCRE_VERSION='8.33' PHP_VERSION='5.4.15' ICU_VERSION='51.2' LIBMCRYPT_VERSION='2.5.7' #NODE_VERSION='0.8.19' NODE_VERSION='0.10.10' declare -A PHP_PECL declare -A PHP_PECL_CONFIGURE PHP_PECL=( ["APC"]='3.1.13' ["mongo"]='1.3.4' ) PHP_PECL_CONFIGURE=( ["APC"]='--enable-apc --enable-apc-debug' ) # Setup dir references ROOT_DIR=${OPENSHIFT_RUNTIME_DIR} BUILD_DIR=${OPENSHIFT_TMP_DIR}/build CONFIG_DIR=${OPENSHIFT_RUNTIME_DIR}/etc TEMPLATE_DIR=${OPENSHIFT_REPO_DIR}/.openshift/tmpl # Load functions source ${OPENSHIFT_REPO_DIR}/.openshift/action_hooks/build_nginx source ${OPENSHIFT_REPO_DIR}/.openshift/action_hooks/build_php source ${OPENSHIFT_REPO_DIR}/.openshift/action_hooks/build_node # Check nginx check_nginx # Check PHP check_php # Check pecl extensions for ext in "${!PHP_PECL[@]}"; do check_pecl ${ext} ${PHP_PECL["$ext"]} ${PHP_PECL_CONFIGURE["$ext"]}; done # Check NodeJS check_node #!/bin/bash # ################################################################################################## # sudo apt-get --yes install build-essential openssl libpcre3 libpcre3-dev libssl-dev libgcrypt11-dev libcurl4-openssl-dev libxml2-dev libghc-bzlib-dev bzip2 libpng12-dev libpng12-0 libpq-dev libreadline-dev libxslt1-dev libmcrypt-dev # OPENSHIFT_REPO_DIR=/etc/openshift/repo # OPENSHIFT_RUNTIME_DIR=/etc/openshift/runtime # OPENSHIFT_TMP_DIR=/tmp # mkdir -p ${OPENSHIFT_REPO_DIR} # mkdir -p ${OPENSHIFT_RUNTIME_DIR} # rm -rf ${OPENSHIFT_REPO_DIR} # git clone https://github.com/boekkooi/openshift-diy-nginx-php.git ${OPENSHIFT_REPO_DIR} # ################################################################################################## ^^^ preparing the box to install everything # ##### changes to /etc/openshift/repo/.openshift/action_hooks/build_nginx # local pkg_zlib=zlib-${ZLIB_VERSION}.tar.gz # tar xfvz ${pkg_zlib} # sudo joe /etc/openshift/repo/.openshift/action_hooks/build_nginx # ##### changes to joe /etc/openshift/repo/.openshift/action_hooks/build_php # wget --output-document=./${pkg} http://www.php.net/get/${pkg}/from/us1.php.net/mirror # wget --output-document=./${pkg} "http://downloads.sourceforge.net/project/mcrypt/Libmcrypt/Production/${pkg}?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fmcrypt%2Ffiles%2FLibmcrypt%2FProduction%2F&ts=1370479253&use_mirror=tenet" # php configure # ++ add # --with-mcrypt # ################################################################################################## ^^^ preparing the box to install everything # # Exit on first error. # set -e # # OpenShift sets GIT_DIR to . which terminates pull with an error: # # Not a git repository: '.' # unset GIT_DIR # umask 077 # # Load common # source ${OPENSHIFT_REPO_DIR}/.openshift/action_hooks/common # # Configure versions # NGINX_VERSION='1.5.1' # ZLIB_VERSION='1.2.8' # PCRE_VERSION='8.33' # PHP_VERSION='5.4.15' # ICU_VERSION='51.2' # LIBMCRYPT_VERSION='2.6.7' # #NODE_VERSION='0.8.19' # NODE_VERSION='0.10.10' # declare -A PHP_PECL # declare -A PHP_PECL_CONFIGURE # PHP_PECL=( ["APC"]='3.1.13' ["mongo"]='1.3.4' ) # PHP_PECL_CONFIGURE=( ["APC"]='--enable-apc --enable-apc-debug' ) # # Setup dir references # ROOT_DIR=${OPENSHIFT_RUNTIME_DIR} # BUILD_DIR=${OPENSHIFT_TMP_DIR}/build # CONFIG_DIR=${OPENSHIFT_RUNTIME_DIR}/etc # TEMPLATE_DIR=${OPENSHIFT_REPO_DIR}/.openshift/tmpl # # Load functions # source ${OPENSHIFT_REPO_DIR}/.openshift/action_hooks/build_nginx # source ${OPENSHIFT_REPO_DIR}/.openshift/action_hooks/build_php # source ${OPENSHIFT_REPO_DIR}/.openshift/action_hooks/build_node # # Check nginx # check_nginx # # Check PHP # check_php # # Check pecl extensions # for ext in "${!PHP_PECL[@]}"; do # check_pecl ${ext} ${PHP_PECL["$ext"]} ${PHP_PECL_CONFIGURE["$ext"]}; # done # # Check NodeJS # check_node # function install_icu() { # local pkg=icu4c-${ICU_VERSION//./_}-src.tgz # mkdir -p ${BUILD_DIR} # pushd ${BUILD_DIR} # echo "Downloading ${pkg}." # wget http://download.icu-project.org/files/icu4c/${ICU_VERSION}/${pkg} # echo "Unpacking ${pkg}." # tar xfz ${pkg} # pushd icu/source/ # echo "Configuring ICU." # chmod +x runConfigureICU configure install-sh # ./configure \ # --prefix=${ROOT_DIR}/icu/ # echo "Compiling ICU." # make install # echo "Cleaning build directory." # popd # popd # rm -rf ${BUILD_DIR} # } # function check_icu() { # local icu_bin=${ROOT_DIR}/icu/bin/icu-config # if [[ ! -e ${icu_bin} ]]; then # echo "LibMCrypt not installed." # install_icu # else # local icu_version=`${icu_bin} --version | tr -d '\n'` # if [[ ${ICU_VERSION} != ${icu_version} ]]; then # echo "ICU old, version: ${icu_version}." # install_icu # else # echo "ICU up to date, version: ${icu_version}." # fi # fi # } # function install_libmcrypt() { # local pkg=libmcrypt-${LIBMCRYPT_VERSION}.tar.gz # local ts=`date +%s` # mkdir -p ${BUILD_DIR} # pushd ${BUILD_DIR} # echo "Downloading ${pkg}." # wget "http://sourceforge.net/projects/mcrypt/files/Libmcrypt/${LIBMCRYPT_VERSION}/${pkg}/download?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fmcrypt%2F&ts=${ts}&use_mirror=freefr" # echo "Unpacking ${pkg}." # tar xfz ${pkg} # pushd libmcrypt-${LIBMCRYPT_VERSION} # echo "Configuring LibMCrypt." # ./configure \ # --disable-posix-threads \ # --enable-dynamic-loading \ # --disable-shared \ # --prefix=${ROOT_DIR}/libmcrypt/ # # --libdir=${ROOT_DIR}/libmcrypt/lib64 \ # echo "Compiling LibMCrypt." # make install # echo "Cleaning build directory." # popd # popd # rm -rf ${BUILD_DIR} # } # function check_libmcrypt() { # local mcrypt_bin=${ROOT_DIR}/libmcrypt/bin/libmcrypt-config # if [[ ! -e ${mcrypt_bin} ]]; then # echo "LibMCrypt not installed." # install_libmcrypt # else # local mcrypt_version=`${mcrypt_bin} --version | tr -d '\n'` # if [[ ${LIBMCRYPT_VERSION} != ${mcrypt_version} ]]; then # echo "LibMCrypt old, version: ${mcrypt_version}." # install_libmcrypt # else # echo "LibMCrypt up to date, version: ${mcrypt_version}." # fi # fi # } # function install_php() { # local pkg=php-${PHP_VERSION}.tar.gz # mkdir -p ${BUILD_DIR} # mkdir -p ${ROOT_DIR}/etc/php5/conf.d # pushd ${BUILD_DIR} # echo "Downloading ${pkg}." # wget http://www.php.net/get/${pkg}/from/us1.php.net/mirror # echo "Unpacking ${pkg}." # tar xfz ${pkg} # pushd php-${PHP_VERSION} # echo "Configuring PHP." # ./configure \ # --with-libdir=lib64 \ # --prefix=${ROOT_DIR}/php5 \ # --with-config-file-path=${ROOT_DIR}/etc/php5 \ # --with-config-file-scan-dir=${ROOT_DIR}/etc/php5/conf.d \ # --with-icu-dir=${ROOT_DIR}/icu \ # --with-layout=PHP \ # --with-curl \ # --with-pear \ # --with-gd \ # --with-zlib \ # --with-mhash \ # --with-mysql \ # --with-pgsql \ # --with-mysqli \ # --with-pdo-mysql \ # --with-pdo-pgsql \ # --with-openssl \ # --with-xmlrpc \ # --with-xsl \ # --with-bz2 \ # --with-gettext \ # --with-readline \ # --with-fpm-user=www-data \ # --with-fpm-group=www-data \ # --with-kerberos \ # --disable-debug \ # --enable-fpm \ # --enable-cli \ # --enable-inline-optimization \ # --enable-exif \ # --enable-wddx \ # --enable-zip \ # --enable-bcmath \ # --enable-calendar \ # --enable-ftp \ # --enable-mbstring \ # --enable-soap \ # --enable-sockets \ # --enable-shmop \ # --enable-dba \ # --enable-sysvsem \ # --enable-sysvshm \ # --enable-sysvmsg \ # --enable-intl # echo "Compiling PHP." # make install # # Copy configuration file # local ini=${TEMPLATE_DIR}/php.ini.tmpl # if [[ -e ${ini} ]]; then # echo "Copy ini for ${1}." # yes | cp ${ini} ${ROOT_DIR}/etc/php5/php.ini # fi # local ini=${TEMPLATE_DIR}/php_extra.ini.tmpl # if [[ -e ${ini} ]]; then # echo "Copy ini for ${1}." # yes | cp ${ini} ${ROOT_DIR}/etc/php5/conf.d/php_extra.ini # fi # echo "Cleaning build directory." # popd # popd # rm -rf ${BUILD_DIR} # } # function check_php() { # check_icu # local php_bin=${ROOT_DIR}/php5/bin/php # if [[ ! -e ${php_bin} ]]; then # echo "PHP not installed." # install_php # else # local php_version=`${php_bin} -r "echo phpversion();"` # if [[ ${PHP_VERSION} != ${php_version} ]]; then # echo "PHP old, version: ${php_version}." # install_php # else # echo "PHP up to date, version: ${php_version}." # fi # fi # } # function install_pecl() { # if [ -z "${1}" ] || [ -z "${2}" ]; then # echo "check_pecl: expected two arguments" # return 1 # fi # local pkg=${1}-${2}.tgz # mkdir -p ${BUILD_DIR} # pushd ${BUILD_DIR} # echo "Downloading ${pkg}." # wget http://pecl.php.net/get/${pkg} # echo "Unpacking ${pkg}." # tar xfz ${pkg} # pushd ${1}-${2} # echo "Configuring ${1}." # ${ROOT_DIR}/php5/bin/phpize -clean # ./configure \ # --with-php-config=${ROOT_DIR}/php5/bin/php-config \ # ${3} # echo "Compiling ${1}." # make install # # Copy configuration files # local ini=${TEMPLATE_DIR}/pecl/${1,,}.ini.tmpl # if [[ -e ${ini} ]]; then # echo "Copy ini for ${1}." # yes | cp ${ini} ${ROOT_DIR}/etc/php5/conf.d/${1,,}.ini # fi # echo "Cleaning build directory." # popd # popd # rm -rf ${BUILD_DIR} # } # function check_pecl() { # if [ -z "${1}" ] || [ -z "${2}" ]; then # echo "check_pecl: expected two arguments" # return 1 # fi # local php_bin=${ROOT_DIR}/php5/bin/php # local pecl_version=`${php_bin} -r "echo phpversion('${1}');"` # if [[ ${2} != ${pecl_version} ]]; then # echo "PHP pecl ${1} not installed or old version." # install_pecl ${1} ${2} ${3} # else # echo "PHP pecl ${1} up to date, version: ${2}." # fi # }
38ca099e9910e4f7bae8005c4151b2f4eb05f172
[ "Shell" ]
2
Shell
antonioribeiro/openshift-diy-nginx-php
7f8ba7e83011d1b99839cf2a190e420fbc309ed2
58c317e50551a501eae600521a90f7b8d62b2907
refs/heads/master
<file_sep>import { firebase } from '@firebase/app'; import "firebase/auth"; import "firebase/database"; const firebaseConfig = { apiKey: "<KEY>", authDomain: "vue-10-app.firebaseapp.com", databaseURL: "https://vue-10-app-default-rtdb.europe-west1.firebasedatabase.app", projectId: "vue-10-app", storageBucket: "vue-10-app.appspot.com", messagingSenderId: "412069035241", appId: "1:412069035241:web:8eccf41e88004eaa068478" }; firebase.initializeApp(firebaseConfig); const db = firebase.database(); export const chatsRef = db.ref("chats"); export default firebase;
e3a90f459ce98e3fee96886a33b2b9e846c418b0
[ "JavaScript" ]
1
JavaScript
jasmine8711/vue-10
058d3587741295fa5a5518ee7bb19d0563c410ef
ed664cfb93c3bd6459e208c103a155ac3079a383
refs/heads/master
<repo_name>teppeis/redash-client<file_sep>/setup/setup-sample-db.sh #!/usr/bin/env bash # Run in postgres container set -eux basedir=$(cd "$(dirname "$0")" && pwd) cd "$basedir" createdb -U postgres dvdrental wget http://www.postgresqltutorial.com/wp-content/uploads/2017/10/dvdrental.zip unzip ./dvdrental.zip pg_restore -U postgres -d dvdrental ./dvdrental.tar <file_sep>/setup/README.md # Set up sample Redash service for testing ### Requirements - Docker ### Set up and start services ```console $ npm i $ ./setup.sh ``` and open `http://localhost/` ### Stop services ```console $ docker-compose stop ``` <file_sep>/docs/index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <base data-ice="baseUrl"> <title data-ice="title">Home | redash-client</title> <link type="text/css" rel="stylesheet" href="css/style.css"> <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css"> <script src="script/prettify/prettify.js"></script> <script src="script/manual.js"></script> <meta name="description" content="Redash API Client for JavaScript"><meta property="twitter:card" content="summary"><meta property="twitter:title" content="redash-client"><meta property="twitter:description" content="Redash API Client for JavaScript"></head> <body class="layout-container" data-ice="rootContainer"> <header> <a href="./">Home</a> <a href="identifiers.html">Reference</a> <a href="source.html">Source</a> <a href="test.html" data-ice="testLink">Test</a> <div class="search-box"> <span> <img src="./image/search.png"> <span class="search-input-edge"></span><input class="search-input"><span class="search-input-edge"></span> </span> <ul class="search-result"></ul> </div> <a style="position:relative; top:3px;" href="https://github.com/teppeis/redash-client"><img width="20px" src="./image/github.png"></a></header> <nav class="navigation" data-ice="nav"><div> <ul> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/RedashClient.js~RedashClient.html">RedashClient</a></span></span></li> </ul> </div> </nav> <div class="content" data-ice="content"><div data-ice="index" class="github-markdown"><h1 id="redash-client">redash-client</h1><p>JavaScript Client for <a href="https://redash.io/">Redash</a> API</p> <p><a href="https://npmjs.org/package/redash-client"><img src="https://img.shields.io/npm/v/redash-client.svg" alt="npm version"></a> <img src="https://img.shields.io/badge/Node.js%20support-v8,v10-brightgreen.svg" alt="Node.js Version Support"> <a href="https://circleci.com/gh/teppeis/redash-client"><img src="https://circleci.com/gh/teppeis/redash-client.svg?style=shield" alt="build status"></a> <a href="https://david-dm.org/teppeis/redash-client"><img src="https://img.shields.io/david/teppeis/redash-client.svg" alt="dependency status"></a> <img src="https://img.shields.io/npm/l/redash-client.svg" alt="License"></p> <h5 id="note--this-pacakge-requires-node-v8--for-async-await">Note: This pacakge requires Node v8+ for async/await</h5><h2 id="install">Install</h2><pre><code class="lang-console"><code class="source-code prettyprint">$ npm install redash-client</code> </code></pre> <h2 id="usage">Usage</h2><pre><code class="lang-javascript"><code class="source-code prettyprint">const RedashClient = require(&apos;redash-client&apos;); const redash = new RedashClient({ endPoint: &apos;https://your-redash.com/&apos;, apiToken: &apos;<KEY>apos;, }); redash .queryAndWaitResult({ query: &apos;select * from actor&apos;, data_source_id: 1, }) .then(resp =&gt; { console.log(resp.query_result); });</code> </code></pre> <h2 id="api">API</h2><p>See <a href="https://teppeis.github.io/redash-client/">API document</a></p> <h3 id="supported-rest-api">Supported REST API</h3><ul> <li><code>#getDataSources()</code></li> <li><code>#getDataSource()</code></li> <li><code>#postQuery()</code></li> <li><code>#getQueries()</code></li> <li><code>#getQuery()</code></li> <li><code>#updateQuery()</code></li> <li><code>#postQueryResult()</code></li> <li><code>#getQueryResult()</code></li> <li><code>#getJob()</code></li> </ul> <p>Methods for other REST API are not implemented yet. Help!</p> <h3 id="utility-methods">Utility methods</h3><h4 id="-code--queryandwaitresult----code-"><code>#queryAndWaitResult()</code></h4><p>Internally:</p> <ol> <li><code>postQueryResult()</code></li> <li>Polling <code>getJob()</code></li> <li>Return <code>getQueryResult()</code></li> </ol> <h2 id="license">License</h2><p>MIT License: <NAME> &lt;<a href="mailto:<EMAIL>"><EMAIL></a>&gt;</p> </div> </div> <footer class="footer"> Generated by <a href="https://esdoc.org">ESDoc<span data-ice="esdocVersion">(1.1.0)</span><img src="./image/esdoc-logo-mini-black.png"></a> </footer> <script src="script/search_index.js"></script> <script src="script/search.js"></script> <script src="script/pretty-print.js"></script> <script src="script/inherited-summary.js"></script> <script src="script/test-summary.js"></script> <script src="script/inner-link.js"></script> <script src="script/patch-for-local.js"></script> </body> </html> <file_sep>/setup/init.js 'use strict'; const pptr = require('puppeteer'); async function run() { const browser = await pptr.launch({ // headless: false, // slowMo: 30, }); const page = await browser.newPage(); await page.setViewport({width: 1024, height: 800}); await init(page); await createDataSource(page); // await login(page); const apiKey = await getApiKey(page); console.log(`API_TOKEN=${apiKey}`); await browser.close(); } async function init(page) { console.log('Initialize Redash Admin...'); await page.goto('http://localhost/'); await page.waitFor('input[name="name"]', {timeout: 1000}); await page.type('input[name="name"]', 'redash-client'); await page.type('input[name="email"]', '<EMAIL>'); await page.type('input[name="password"]', '<PASSWORD>'); await page.type('input[name="org_name"]', 'redash-client'); return Promise.all([page.waitForNavigation(), page.click('button[type=submit]')]); } // https://github.com/GoogleChrome/puppeteer/issues/761 async function type(page, selector, text) { const input = await page.$(selector); await input.click({clickCount: 3}); return input.type(text); } async function createDataSource(page) { console.log('Create Data Source...'); await page.goto('http://localhost/data_sources/new'); await page.waitFor('img[alt="PostgreSQL"]', {timeout: 1000}); // PostgreSQL await page.click('img[alt="PostgreSQL"]'); // Name await page.type('form[target=dataSource] > div:nth-child(1) input', 'dvdrental'); // Host await type(page, 'form[target=dataSource] > div:nth-child(3) input', 'postgres'); // User await page.type('form[target=dataSource] > div:nth-child(5) input', 'postgres'); // Password await page.type('form[target=dataSource] > div:nth-child(6) input', '<PASSWORD>'); // Database Name await page.type('form[target=dataSource] > div:nth-child(8) input', 'dvdrental'); // Submit return Promise.all([page.waitForNavigation(), page.click('form[target=dataSource] > button')]); } async function login(page) { console.log('Login...'); await page.goto('http://localhost/'); await page.waitFor('input[name="email"]', {timeout: 1000}); await page.type('input[name="email"]', '<EMAIL>'); await page.type('input[name="password"]', '<PASSWORD>'); return Promise.all([page.waitForNavigation(), page.click('button[type=submit]')]); } async function getApiKey(page) { console.log('Get API Key...'); await page.goto('http://localhost/users/me'); const xpath = '//label[contains(text(), "API Key")]/following-sibling::input'; await page.waitFor(xpath, {timeout: 1000}); const inputs = await page.$x(xpath); if (inputs.length !== 1) { throw new Error('Unexpected selector matching'); } return page.evaluate(input => input.value, inputs[0]); } run(); <file_sep>/test/index.js 'use strict'; const Client = require('../'); const assert = require('assert'); const nockBackMochaFactory = require('@teppeis/nock-back-mocha'); const nockBackMocha = nockBackMochaFactory(); /** @test {RedashClient} */ describe('RedashClient', () => { it('should be a constructor', () => { const client = new Client(); assert(client instanceof Client); }); describe('api', () => { let client; beforeEach(function() { client = new Client({ endPoint: 'http://localhost/', // apiToken: process.env.API_TOKEN || '<PASSWORD>', apiToken: process.env.API_TOKEN || '<PASSWORD>', }); return nockBackMocha.beforeEach.call(this); }); afterEach(nockBackMocha.afterEach); /** @test {RedashClient#getDataSources} */ it('getDataSources', async () => { const actual = await client.getDataSources(); const expectedBody = require(nockBackMocha.fixtureFile)[0].response; assert.deepEqual(actual, expectedBody); }); /** @test {RedashClient#getDataSource} */ it('getDataSource', async () => { const actual = await client.getDataSource(1); const expectedBody = require(nockBackMocha.fixtureFile)[0].response; assert.deepEqual(actual, expectedBody); }); /** @test {RedashClient#postQuery} */ it('postQuery', async () => { const actual = await client.postQuery({ query: 'select * from actor', data_source_id: 1, name: 'List Actors', }); const expectedBody = require(nockBackMocha.fixtureFile)[0].response; assert.deepEqual(actual, expectedBody); nockBackMocha.assertScopesFinished(); }); /** @test {RedashClient#getQueries} */ it('getQueries', async () => { const actual = await client.getQueries(); const expectedBody = require(nockBackMocha.fixtureFile)[0].response; assert.deepEqual(actual, expectedBody); nockBackMocha.assertScopesFinished(); }); /** @test {RedashClient#getQuery} */ it('getQuery', async () => { const actual = await client.getQuery(2); const expectedBody = require(nockBackMocha.fixtureFile)[0].response; assert.deepEqual(actual, expectedBody); nockBackMocha.assertScopesFinished(); }); /** @test {RedashClient#updateQuery} */ it('updateQuery', async () => { const actual = await client.postQuery({ id: 3, query: 'select * from actor limit 10', data_source_id: 1, name: 'Top 10 Actors', }); const expectedBody = require(nockBackMocha.fixtureFile)[0].response; assert.deepEqual(actual, expectedBody); nockBackMocha.assertScopesFinished(); }); /** @test {RedashClient#postQueryResult} */ it('postQueryResult with max_age = 0', async () => { const actual = await client.postQueryResult({ query: 'select * from actor', data_source_id: 1, max_age: 0, }); const expectedBody = require(nockBackMocha.fixtureFile)[0].response; assert.deepEqual(actual, expectedBody); nockBackMocha.assertScopesFinished(); }); /** @test {RedashClient#getQueryResult} */ it('getQueryResult', async () => { const id = 5; const actual = await client.getQueryResult(id); const expectedBody = require(nockBackMocha.fixtureFile)[0].response; assert.deepEqual(actual, expectedBody); nockBackMocha.assertScopesFinished(); }); /** @test {RedashClient#getJob} */ it('getJob', async () => { const id = 'a8822893-7614-4b35-b90d-6ae2dcb44e69'; const actual = await client.getJob(id); const expectedBody = require(nockBackMocha.fixtureFile)[0].response; assert.deepEqual(actual, expectedBody); nockBackMocha.assertScopesFinished(); }); /** @test {RedashClient#queryAndWaitResult} */ it('queryAndWaitResult', async () => { const actual = await client.queryAndWaitResult({ query: 'select * from actor limit 5', data_source_id: 1, max_age: 0, }); const requests = require(nockBackMocha.fixtureFile); const lastRequest = requests[requests.length - 1]; assert(/^\/api\/query_results\/\d+/.test(lastRequest.path)); assert(lastRequest.status === 200); assert.deepEqual(actual, lastRequest.response); nockBackMocha.assertScopesFinished(); }); /** @test {RedashClient#queryAndWaitResult} */ it('queryAndWaitResult: timeout', () => client .queryAndWaitResult( { query: 'select * from actor limit 5', data_source_id: 1, max_age: 0, }, 10 ) .then( () => assert.fail('should be rejected'), e => { assert(/polling timeout/.test(e.message)); nockBackMocha.assertScopesFinished(); } )); }); }); <file_sep>/setup/setup.sh #!/usr/bin/env bash # Clean up and set up Redash service for testing set -eux basedir=$(cd "$(dirname "$0")" && pwd) cd "$basedir" # Clean up echo 'Clean up existing Redash...' docker-compose down rm -rf .postgres-data # Set up mkdir -p .postgres-data echo 'Create Redash DB...' docker-compose run --rm server create_db echo 'Load Sample data...' docker cp ./setup-sample-db.sh "$(docker-compose ps -q postgres)":/tmp/ docker-compose exec postgres bash /tmp/setup-sample-db.sh echo 'Start Redash services...' docker cp ./setup-sample-db.sh "$(docker-compose ps -q postgres)":/tmp/ docker-compose up -d echo 'Initialize Redash...' node ./init.js echo 'Setting done successfully!' echo 'Open http://localhost/' <file_sep>/README.md # redash-client JavaScript Client for [Redash](https://redash.io/) API [![npm version][npm-image]][npm-url] ![Node.js Version Support][node-version] [![build status][circleci-image]][circleci-url] [![dependency status][deps-image]][deps-url] ![License][license] ##### Note: This pacakge requires Node v8+ for async/await ## Install ```console $ npm install redash-client ``` ## Usage ```javascript const RedashClient = require('redash-client'); const redash = new RedashClient({ endPoint: 'https://your-redash.com/', apiToken: '<KEY>', }); redash .queryAndWaitResult({ query: 'select * from actor', data_source_id: 1, }) .then(resp => { console.log(resp.query_result); }); ``` ## API See [API document](https://teppeis.github.io/redash-client/) ### Supported REST API - `#getDataSources()` - `#getDataSource()` - `#postQuery()` - `#getQueries()` - `#getQuery()` - `#updateQuery()` - `#postQueryResult()` - `#getQueryResult()` - `#getJob()` Methods for other REST API are not implemented yet. Help! ### Utility methods #### `#queryAndWaitResult()` Internally: 1. `postQueryResult()` 2. Polling `getJob()` 3. Return `getQueryResult()` ## License MIT License: <NAME> &lt;<EMAIL>&gt; [npm-image]: https://img.shields.io/npm/v/redash-client.svg?logo=npm&style=for-the-badge [npm-url]: https://npmjs.org/package/redash-client [npm-downloads-image]: https://img.shields.io/npm/dm/redash-client.svg [travis-image]: https://img.shields.io/travis/teppeis/redash-client/master.svg?logo=travis&style=for-the-badge [travis-url]: https://travis-ci.org/teppeis/redash-client [deps-image]: https://img.shields.io/david/teppeis/redash-client.svg?style=for-the-badge [deps-url]: https://david-dm.org/teppeis/redash-client [node-version]: https://img.shields.io/badge/Node.js-v8+-brightgreen.svg?logo=Node.js&style=for-the-badge [coverage-image]: https://img.shields.io/coveralls/teppeis/redash-client/master.svg [coverage-url]: https://coveralls.io/github/teppeis/redash-client?branch=master [license]: https://img.shields.io/npm/l/redash-client.svg?style=for-the-badge [appveyor-image]: https://ci.appveyor.com/api/projects/status/22nwyfaf5p0yw54j/branch/master?svg=true [appveyor-url]: https://ci.appveyor.com/project/teppeis/redash-client/branch/master [circleci-image]: https://img.shields.io/circleci/project/github/teppeis/redash-client/master.svg?logo=circleci&style=for-the-badge [circleci-url]: https://circleci.com/gh/teppeis/redash-client <file_sep>/src/RedashClient.js 'use strict'; const fetch = require('cross-fetch'); const delay = require('delay'); const DEFAULT_POLLING_TIMEOUT_MS = 60 * 1000; /** * Redash Client */ class RedashClient { /** * @param {{endPoint: string, apiToken: string, agent: ?http.Agent, authHeaderName: ?string}} options */ constructor({endPoint, apiToken, agent, authHeaderName = 'Authorization'} = {}) { /** * @param {string} path * @param {Object=} body * @param {Object=} options * @return {Promise<Response>} * @private */ this.fetchJson_ = (path, body, options = {}) => { options.headers = { ...options.headers, agent, [authHeaderName]: `Key ${apiToken}`, 'content-type': 'application/json', }; if (body) { options.body = JSON.stringify(body); } return fetch(endPoint + path, options).then(resp => resp.json()); }; } /** * @param {string} path * @return {Promise<Response>} * @private */ get_(path) { const options = { method: 'GET', }; return this.fetchJson_(path, null, options); } /** * @param {string} path * @param {Object=} body * @return {Promise<Response>} * @private */ post_(path, body = {}) { const options = { method: 'POST', }; return this.fetchJson_(path, body, options); } /** * @return {Promise<Array<DataSource>>} */ getDataSources() { return this.get_(`api/data_sources`); } /** * @param {number} id * @return {Promise<DataSource>} */ getDataSource(id) { if (typeof id !== 'number') { throw new TypeError(`Data Source ID should be number: ${id}`); } return this.get_(`api/data_sources/${id}`); } /** * @param {{query: string, data_source_id: number, name: string, description: string?}} query * @return {Promise<Query>} */ postQuery(query) { return this.post_('api/queries', query); } /** * @param {{id: number, query: string, data_source_id: number, name: string, description: string?}} query * @return {Promise<Query>} */ updateQuery(query) { if (typeof query.id !== 'number') { throw new TypeError(`Query ID should be number: ${query.id}`); } return this.post_(`api/queries/${query.id}`, query); } /** * @return {Promise<{count: number, page: number, page_size: number, results: Array<Query>}>} */ getQueries() { return this.get_(`api/queries`); } /** * @param {number} id * @return {Promise<Query>} */ getQuery(id) { return this.get_(`api/queries/${id}`); } /** * @param {{data_source_id: number, max_age: number, query: string, query_id: number}} query * @return {Promise<{job: Job}|{query_result: QueryResult}>} */ postQueryResult(query) { return this.post_('api/query_results', query); } /** * @param {number} queryResultId * @return {Promise<{query_result: QueryResult}>} */ getQueryResult(queryResultId) { if (typeof queryResultId !== 'number') { throw new TypeError(`Query Result ID should be number: ${queryResultId}`); } return this.get_(`api/query_results/${queryResultId}`); } /** * @param {number} id * @return {Promise<{job: Job}>} */ getJob(id) { return this.get_(`api/jobs/${id}`); } /** * @param {{data_source_id: number, query: string, query_id: number}} query * @param {number=} timeout * @return {Promise<{query_result: QueryResult}>} */ async queryAndWaitResult(query, timeout = DEFAULT_POLLING_TIMEOUT_MS) { // `max_age` should be 0 to disable cache always query = {...query, max_age: 0}; const { job: {id}, } = await this.postQueryResult(query); let queryResultId; const start = Date.now(); while (true) { const {job} = await this.getJob(id); if (job.status === 3) { queryResultId = job.query_result_id; break; } if (Date.now() - start > timeout) { throw new Error('polling timeout'); } await delay(1000); } return this.getQueryResult(queryResultId); } } module.exports = RedashClient; <file_sep>/docs/file/redash-client/docs/script/search_index.js.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <base data-ice="baseUrl" href="../../../../"> <title data-ice="title">redash-client/docs/script/search_index.js | redash-client</title> <link type="text/css" rel="stylesheet" href="css/style.css"> <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css"> <script src="script/prettify/prettify.js"></script> <script src="script/manual.js"></script> <meta name="description" content="Redash API Client for JavaScript"><meta property="twitter:card" content="summary"><meta property="twitter:title" content="redash-client"><meta property="twitter:description" content="Redash API Client for JavaScript"></head> <body class="layout-container" data-ice="rootContainer"> <header> <a href="./">Home</a> <a href="identifiers.html">Reference</a> <a href="source.html">Source</a> <div class="search-box"> <span> <img src="./image/search.png"> <span class="search-input-edge"></span><input class="search-input"><span class="search-input-edge"></span> </span> <ul class="search-result"></ul> </div> <a style="position:relative; top:3px;" href="https://github.com/teppeis/redash-client"><img width="20px" src="./image/github.png"></a></header> <nav class="navigation" data-ice="nav"><div> <ul> </ul> </div> </nav> <div class="content" data-ice="content"><h1 data-ice="title">redash-client/docs/script/search_index.js</h1> <pre class="source-code line-number raw-source-code"><code class="prettyprint linenums" data-ice="content">window.esdocSearchIndex = [ [ &quot;redash-client/.external-ecmascript.js~array&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array&quot;, &quot;redash-client/.external-ecmascript.js~Array&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~arraybuffer&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer&quot;, &quot;redash-client/.external-ecmascript.js~ArrayBuffer&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~boolean&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean&quot;, &quot;redash-client/.external-ecmascript.js~Boolean&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~dataview&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView&quot;, &quot;redash-client/.external-ecmascript.js~DataView&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~date&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date&quot;, &quot;redash-client/.external-ecmascript.js~Date&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~error&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error&quot;, &quot;redash-client/.external-ecmascript.js~Error&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~evalerror&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError&quot;, &quot;redash-client/.external-ecmascript.js~EvalError&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~float32array&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array&quot;, &quot;redash-client/.external-ecmascript.js~Float32Array&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~float64array&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array&quot;, &quot;redash-client/.external-ecmascript.js~Float64Array&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~function&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function&quot;, &quot;redash-client/.external-ecmascript.js~Function&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~generator&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator&quot;, &quot;redash-client/.external-ecmascript.js~Generator&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~generatorfunction&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction&quot;, &quot;redash-client/.external-ecmascript.js~GeneratorFunction&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~infinity&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity&quot;, &quot;redash-client/.external-ecmascript.js~Infinity&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~int16array&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array&quot;, &quot;redash-client/.external-ecmascript.js~Int16Array&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~int32array&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array&quot;, &quot;redash-client/.external-ecmascript.js~Int32Array&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~int8array&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array&quot;, &quot;redash-client/.external-ecmascript.js~Int8Array&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~internalerror&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/InternalError&quot;, &quot;redash-client/.external-ecmascript.js~InternalError&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~json&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON&quot;, &quot;redash-client/.external-ecmascript.js~JSON&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~map&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map&quot;, &quot;redash-client/.external-ecmascript.js~Map&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~nan&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN&quot;, &quot;redash-client/.external-ecmascript.js~NaN&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~number&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number&quot;, &quot;redash-client/.external-ecmascript.js~Number&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~object&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object&quot;, &quot;redash-client/.external-ecmascript.js~Object&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~promise&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise&quot;, &quot;redash-client/.external-ecmascript.js~Promise&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~proxy&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy&quot;, &quot;redash-client/.external-ecmascript.js~Proxy&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~rangeerror&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError&quot;, &quot;redash-client/.external-ecmascript.js~RangeError&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~referenceerror&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError&quot;, &quot;redash-client/.external-ecmascript.js~ReferenceError&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~reflect&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect&quot;, &quot;redash-client/.external-ecmascript.js~Reflect&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~regexp&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp&quot;, &quot;redash-client/.external-ecmascript.js~RegExp&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~set&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set&quot;, &quot;redash-client/.external-ecmascript.js~Set&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~string&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String&quot;, &quot;redash-client/.external-ecmascript.js~String&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~symbol&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol&quot;, &quot;redash-client/.external-ecmascript.js~Symbol&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~syntaxerror&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError&quot;, &quot;redash-client/.external-ecmascript.js~SyntaxError&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~typeerror&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError&quot;, &quot;redash-client/.external-ecmascript.js~TypeError&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~urierror&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError&quot;, &quot;redash-client/.external-ecmascript.js~URIError&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~uint16array&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array&quot;, &quot;redash-client/.external-ecmascript.js~Uint16Array&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~uint32array&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array&quot;, &quot;redash-client/.external-ecmascript.js~Uint32Array&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~uint8array&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array&quot;, &quot;redash-client/.external-ecmascript.js~Uint8Array&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~uint8clampedarray&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray&quot;, &quot;redash-client/.external-ecmascript.js~Uint8ClampedArray&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~weakmap&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap&quot;, &quot;redash-client/.external-ecmascript.js~WeakMap&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~weakset&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet&quot;, &quot;redash-client/.external-ecmascript.js~WeakSet&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~boolean&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean&quot;, &quot;redash-client/.external-ecmascript.js~boolean&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~function&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function&quot;, &quot;redash-client/.external-ecmascript.js~function&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~null&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null&quot;, &quot;redash-client/.external-ecmascript.js~null&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~number&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number&quot;, &quot;redash-client/.external-ecmascript.js~number&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~object&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object&quot;, &quot;redash-client/.external-ecmascript.js~object&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~string&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String&quot;, &quot;redash-client/.external-ecmascript.js~string&quot;, &quot;external&quot; ], [ &quot;redash-client/.external-ecmascript.js~undefined&quot;, &quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined&quot;, &quot;redash-client/.external-ecmascript.js~undefined&quot;, &quot;external&quot; ], [ &quot;redash-client/index.js&quot;, &quot;file/redash-client/index.js.html&quot;, &quot;redash-client/index.js&quot;, &quot;file&quot; ], [ &quot;redash-client/test/index.js&quot;, &quot;file/redash-client/test/index.js.html&quot;, &quot;redash-client/test/index.js&quot;, &quot;file&quot; ] ]</code></pre> </div> <footer class="footer"> Generated by <a href="https://esdoc.org">ESDoc<span data-ice="esdocVersion">(1.0.2)</span><img src="./image/esdoc-logo-mini-black.png"></a> </footer> <script src="script/search_index.js"></script> <script src="script/search.js"></script> <script src="script/pretty-print.js"></script> <script src="script/inherited-summary.js"></script> <script src="script/test-summary.js"></script> <script src="script/inner-link.js"></script> <script src="script/patch-for-local.js"></script> </body> </html>
4b7989af1aed42bda7f06193c4e1348d3361dded
[ "Markdown", "JavaScript", "HTML", "Shell" ]
9
Shell
teppeis/redash-client
256f6e9dd21eb3d5c7f218bb257d3282a4c193ca
a352fb5ce025becbc0fe97965f19778d2ace393c
refs/heads/master
<file_sep>const koaRouter = require('koa-router') const router = koaRouter() const user = require('../controller/user') router.post('/deposit', user.deposit); // 存款 router.post('/withdraw', user.withdraw); // 取款 router.post('/transfer', user.transfer); // 转账 router.post('/balance', user.checkBalance); // 查询余额 router.post('/changePwd', user.changePwd); // 更改密码 module.exports = router<file_sep>//import { reset } from '../../../../../.cache/typescript/2.6/node_modules/@types/continuation-local-storage'; const user = require('../models/user'); const jwt = require('jsonwebtoken') const bcrypt = require('bcryptjs') const getUserInfo = async function (ctx){ const id = ctx.params.id; // 获取url里传过来的参数里的id const result = await user.getUserById(id); // 通过yield “同步”地返回查询结果 ctx.body = result // 将请求的结果放到response的body里返回 } const postUserAuth = async function (ctx) { const data = ctx.request.body // post过来的数据存在request.body里 const userInfo = await user.getUserById(data.id) if (data.id == "") { ctx.body = { success: false, info: '请输入银行卡账号!' // 如果用户不存在返回用户不存在 } return } if (userInfo != null) { // 如果查无此用户会返回null if (!bcrypt.compareSync(data.password, userInfo.password)) { var salt = bcrypt.genSaltSync(10); var hash = bcrypt.hashSync("123456", salt); console.log(hash) ctx.body = { success: false, // success标志位是方便前端判断返回是正确与否 info: '密码错误!' } } else { const userToken = { id: userInfo.card_id } const secret = 'ATM-token' // 指定密钥 const token = jwt.sign(userToken, secret) // 签发token ctx.body = { success: true, token: token // 返回token } } } else { ctx.body = { success: false, info: '用户不存在!' // 如果用户不存在返回用户不存在 } } } const deposit = async function (ctx){ const data = ctx.request.body const token = data.token const getToken = jwt.verify(token, 'ATM-token') const id = getToken.id const newMoney = data.new if (newMoney>0){ var real = to_100(newMoney) const Balance = await user.getBalance(id) // 通过yield “同步”地返回查询结果 var newbalance = Balance.balance + parseInt(real) const result = await user.changeBalance(id,newbalance) ctx.body = { success: true, info: '存款成功!' // 如果用户不存在返回用户不存在 } } else { ctx.body = { success: false, info: '输入为负数不符合规范!' // 如果用户不存在返回用户不存在 } } } const withdraw = async function (ctx){ const data = ctx.request.body const token = data.token const getToken = jwt.verify(token, 'ATM-token') const id = getToken.id const withdraw_amount = data.take const Savings = await user.getBalance(id) if (withdraw_amount>0){ if (Savings.balance < withdraw_amount) { ctx.body = { success: false, info: '余额不足!' } } else { var real = to_100(withdraw_amount) var newSavings = Savings.balance - parseInt(real) user.changeBalance(id, newSavings) ctx.body = { success: true, info: '取款成功!' // 如果用户不存在返回用户不存在 } } } else { ctx.body = { success: false, info: '输入为负数不符合规范!' // 如果用户不存在返回用户不存在 } } } const checkBalance = async function (ctx){ const data = ctx.request.body const token = data.token const getToken = jwt.verify(token, 'ATM-token') const id = getToken.id const result = await user.getBalance(id) // 通过yield “同步”地返回查询结果 ctx.body = { success: true, balance: result.balance, info: '查询成功!' } } const transfer = async function (ctx){ const data = ctx.request.body const token = data.token const getToken = jwt.verify(token, 'ATM-token') const from_id = getToken.id const to_id = data.to var toexist = await user.getUserById(to_id) if (toexist != null){ const fromSavings = await user.getBalance(from_id) const toSavings = await user.getBalance(to_id) const transfer_amount = data.transfer var real = to_100(transfer_amount) if (fromSavings.balance < real) { ctx.body = { success: false, info: '余额不足!' // 如果用户不存在返回用户不存在 } } else { var to_new = toSavings.balance + real var from_new = fromSavings.balance - real user.changeBalance(to_id, to_new) user.changeBalance(from_id, from_new) ctx.body = { success: true, info: '转账成功!' // 如果用户不存在返回用户不存在 } } } else { ctx.body = { success: false, info: '银行卡号错误!' // 如果用户不存在返回用户不存在 } return } } const changePwd = async function (ctx) { const data = ctx.request.body const token = data.token const getToken = jwt.verify(token, 'ATM-token') const id = getToken.id const userInfo = await user.getUserById(id) const newPwd = data.newpwd const confirmPwd = data.confirmpwd if (bcrypt.compareSync(data.password, userInfo.password)) { if (newPwd === confirmPwd) { var salt = bcrypt.genSaltSync(10); var hash = bcrypt.hashSync(newPwd, salt); console.log(hash) user.newPassword(userInfo.id,hash) ctx.body = { success: true, info: '密码更新成功!' } } else { ctx.body = { success: false, info: '两次输入密码不一致!' } } } else { ctx.body = { success: false, info: '密码错误!' } } } const to_100 = function (num) { var result = num/100 console.log(result) result = parseInt(result) var newMoney = result*100 return newMoney } module.exports = { getUserInfo, // 把获取用户信息的方法暴露出去 postUserAuth, deposit, withdraw, transfer, checkBalance, changePwd }<file_sep>// db.js const Sequelize = require('sequelize'); // 引入sequelize // 使用url连接的形式进行连接,注意将root: 后面的XXXX改成自己数据库的密码 const ATM = new Sequelize('mysql://root:root@localhost/ATM_system',{ define: { timestamps: false // 取消Sequelzie自动给数据表加入时间戳(createdAt以及updatedAt) } }) module.exports = { ATM // 将ATM暴露出接口方便Model调用 }
a351f64152eadbcbde193404056c19b2ff3102f2
[ "JavaScript" ]
3
JavaScript
Bitnut/SCUT_ATM_system
5572d5711aeed550ac2c95cd65091a5c7e1962bf
09461843926c5acfa036c14934937d9a79cd4759
refs/heads/main
<repo_name>johndoenma/subwaysite-forjiho<file_sep>/js/script.js document.addEventListener('DOMContentLoaded', function() { // TOGGLE NAV MOBILE MANU FOR SMALL SCREENS const menubutton = document.querySelector('.menu-button'); const menunav = document.querySelector('.toggle-nav'); menubutton.addEventListener('click', function() { if (menunav.getAttribute('data-navstate') === 'open') { menunav.setAttribute('data-navstate', 'closed'); } else { menunav.setAttribute('data-navstate', 'open'); }; }); // //STICKY NAV - REMOVE EXPANDED CLASS FOR MOBILE // var stickynavlinks = document.querySelectorAll(".sticky nav a"); // for (var i = 0; i < stickynavlinks.length; i++) { // stickynavlinks[i].onclick = function () { // mytogglenav.classList.remove("closed"); // } // }; //STICKY NAV - CLOSE THE NAV ON STICKY HEADER NAV LINK CLICKS const stickynavlinks = document.querySelectorAll(".sticky nav a"); for (var i = 0; i < stickynavlinks.length; i++) { stickynavlinks[i].addEventListener('click', function () { menunav.setAttribute('data-navstate', 'closed'); }); }; });<file_sep>/README.md # subwaysite-forjiho A temp copy of a student project to help troubleshoot bugs [View Demo](https://johndoenma.github.io/subwaysite-forjiho)
63ade595381e506c242490d604aee13154baf0d4
[ "JavaScript", "Markdown" ]
2
JavaScript
johndoenma/subwaysite-forjiho
3f6d28db88848feae706c1722362479772ace5c6
bb270d2692e2df4ac55eff1fca86d3319c4a8ecc
refs/heads/master
<file_sep>hibernate.show_sql=false hibernate.hbm2ddl.auto=validate mls.datasource.driverClassName=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect <file_sep>Sample project to configure spring boot with embedded tomcat instance. This embedded tomcat instance has JNDI configured and JPA config can use the configured JNDI. <file_sep>rootProject.name = 'spring-boot-jpa-tomcat-jndi' <file_sep>package tomcat.jndi.web; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class TestController { @Autowired private DataSource dataSource; @RequestMapping("/factoryBean") @ResponseBody public String factoryBean() { return "DataSource retrieved from JNDI using JndiObjectFactoryBean: " + dataSource; } @RequestMapping("/direct") @ResponseBody public String direct() throws NamingException { return "DataSource retrieved directly from JNDI: " + new InitialContext().lookup("java:comp/env/jdbc/test"); } } <file_sep>package tomcat.jndi; import org.apache.tomcat.dbcp.dbcp.BasicDataSource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import tomcat.jndi.TomcatJndiApplication; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = TomcatJndiApplication.class) @WebAppConfiguration @IntegrationTest("server.port:0") @DirtiesContext public class TomcatJndiApplicationTests { @Value("${local.server.port}") private int port; @Test public void testDirect() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/direct", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertThat(entity.getBody(), containsString(BasicDataSource.class.getName())); } @Test public void testFactoryBean() throws Exception { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/factoryBean", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertThat(entity.getBody(), containsString(BasicDataSource.class.getName())); } } <file_sep>apply plugin: 'java' apply plugin: 'maven' group = 'org.springframework.boot' version = '0.1.0-SNAPSHOT' description = "spring-boot-jpa-tomcat-jndi" sourceCompatibility = 1.7 targetCompatibility = 1.7 repositories { maven { url "http://repo.maven.apache.org/maven2" } } dependencies { compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version:'1.0.2.RELEASE' compile group: 'org.apache.tomcat', name: 'tomcat-dbcp', version:'7.0.52' testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version:'1.0.2.RELEASE' compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version:'1.0.2.RELEASE' testCompile group: 'junit', name: 'junit', version:'4.11' testCompile group: 'org.mockito', name: 'mockito-core', version:'1.9.5' testCompile group: 'org.hamcrest', name: 'hamcrest-library', version:'1.3' } <file_sep>package tomcat.jndi; import javax.naming.NamingException; import javax.sql.DataSource; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.deploy.ContextResource; import org.apache.catalina.startup.Tomcat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.jndi.JndiObjectFactoryBean; @Configuration @ComponentScan @EnableAutoConfiguration public class TomcatJndiApplication { @Autowired private Environment env; public static void main(String[] args) { SpringApplication.run(TomcatJndiApplication.class, args); } @Bean public TomcatEmbeddedServletContainerFactory tomcatFactory() { return new TomcatEmbeddedServletContainerFactory() { @Override protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer( Tomcat tomcat) { tomcat.enableNaming(); TomcatEmbeddedServletContainer container = super.getTomcatEmbeddedServletContainer(tomcat); for (Container child: container.getTomcat().getHost().findChildren()) { if (child instanceof Context) { ClassLoader contextClassLoader = ((Context)child).getLoader().getClassLoader(); Thread.currentThread().setContextClassLoader(contextClassLoader); break; } } return container; } @Override protected void postProcessContext(Context context) { ContextResource resource = new ContextResource(); resource.setName("jdbc/test"); resource.setType(DataSource.class.getName()); resource.setProperty("driverClassName", env.getProperty("mls.datasource.driverClassName")); resource.setProperty("url", env.getProperty("mls.datasource.url")); resource.setProperty("password",env.getProperty("mls.datasource.password")); resource.setProperty("username", env.getProperty("mls.datasource.username")); context.getNamingResources().addResource(resource); } }; } @Bean(destroyMethod="") public DataSource jndiDataSource() throws IllegalArgumentException, NamingException { JndiObjectFactoryBean bean = new JndiObjectFactoryBean(); bean.setJndiName("java:comp/env/jdbc/test"); bean.setProxyInterface(DataSource.class); bean.setLookupOnStartup(false); bean.afterPropertiesSet(); return (DataSource)bean.getObject(); } }
ed9657183a6c2fd7a18e9b96efed5ce38c62c911
[ "Markdown", "Java", "INI", "Gradle" ]
7
INI
badalb/spring-boot-jpa-tomcat-jndi
a012b1648a5e07f6aaf0dd006796bf20eb44c56a
8d400d68d1b3e64adaeb3bf3669754012a0989bd
refs/heads/master
<repo_name>Avvari590/Myplayer<file_sep>/MyMuzic/MyMuzic/Controllers/UserAccountController.cs using MyMuzic.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MyMuzic.Controllers { public class UserAccountController : Controller { // GET: UserAccount public ActionResult Index() { using (MaaPlayerEntities db = new MaaPlayerEntities()) { return View(db.UserAccounts.ToList()); } } public ActionResult Register() { return View(); } [HttpPost] public ActionResult Register(UserAccount account) { if (ModelState.IsValid) { using (MaaPlayerEntities db = new MaaPlayerEntities()) { account.UserID = Guid.NewGuid(); db.UserAccounts.Add(account); db.SaveChanges(); } ModelState.Clear(); ViewBag.Message = account.FirstName + " " + account.LastName + " successfully registered."; } return View(); } public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(UserAccount user) { try { using (MaaPlayerEntities db = new MaaPlayerEntities()) { var usr = (from userlist in db.UserAccounts where userlist.UserName == user.UserName && userlist.Password == <PASSWORD> select new { userlist.UserID, userlist.UserName }).ToList(); //var usr = db.UserAccounts.Single(u => u.UserName == user.UserName && u.Password == <PASSWORD>); if (usr != null) { Session["UserID"] = usr.FirstOrDefault().UserID.ToString(); Session["UserName"] = usr.FirstOrDefault().UserName.ToString(); return RedirectToAction("Home"); } else { ModelState.AddModelError("", "Username or Pasword is Wong."); } } } catch (Exception ex) { ModelState.AddModelError("", "Username or Pasword is Wong."); } return View(); } public ActionResult LoggedIn() { if (Session["UserID"] != null) { return View(); } else { return RedirectToAction("Login"); } } } }
cee1e219d05089199cd723291b825b690426eadd
[ "C#" ]
1
C#
Avvari590/Myplayer
9bda1d31ff1775d37423c812d7d8a4cb63f855b3
023462c1f36c51e5cb8ace7b2a69fcc1f59da827
refs/heads/master
<file_sep># kaiju-plugin-utils [![Cerner OSS](https://img.shields.io/badge/Cerner-OSS-blue.svg?style=flat)](http://engineering.cerner.com/2014/01/cerner-and-open-source/) [![Build Status](https://travis-ci.org/cerner/kaiju-plugin-utils.svg?branch=master)](https://travis-ci.org/cerner/kaiju-plugin-utils) Kaiju plugin utils is a helpful library of common optional utilities used when creating plugins for Kaiju. ## Development notes This module uses app-root-path to determine root path to the kaiju node server. This library determines the root path by walking up the current directory path to be one level below the last occurrence of 'node_modules'. This works great normally but can be incorrect when this module is setup as a file dependency because the directory is symlinked instead of copied. For this module to work as expected in development you cannot require this module as a file. ## Plugin Utils Common optional utilities to be used when developing kaiju plugins. There is a dependency on webpack for preview creation. If you don't need webpack, you might not want to use these utils. ### Usage ```js const { PluginUtils } = require('kaiju-plugin-utils'); PluginUtils.rootPath() // for example ``` ### runCompiler Runs the webpack compiler on the files included in the memory file system with the config supplied. **Arguments:** Memory File System - A memory file system containing the files to be webpacked. Config - The webpack config to be used by the compiler. **Return values:** Compiler file system - A promise for a memory file system containing the output from the webpack compiler. ### webpackCompiler Creates a webpack compiler setup with the config and memory file system passed in and a new memory file system instance for the output. **Arguments:** Memory File System - A memory file system containing the files to be webpacked. Config - The webpack config to be used by the compiler. **Return values:** A webpack compiler setup with a memory file system. ### defaultWebpackConfig A basic optional webpack config. Importantly it sets up resolve to point to the root app's node modules, output based on arguments and the output and it sets the environment to production. **Arguments:** public path - the path the the preview's assets, this will be supplied by the kaiju server. output path - the location to build the assets to, this should be returned to the kaiju server. **Return values:** A webpack config object. ### webpackFs A setup fallback file system proxy with the passed in memory fs and a standard filesystem. **Arguments:** MemoryFS - a memory file system instance. **Return values:** A fallback file system. ### rootPath The path the the root of the kaiju node server. Uses the app-root-path library. **Return values:** A string representing the root path. ## Fallback File System The fallback file system is a very specific proxy setup on top of a memory file system. This filesystem falls back to the supplied file system when a file isn't found in the memory file system. This was created to allow webpack to use the kaiju servers node modules instead of requiring an npm install on the in memory file system to generate the preview. The fs methods that will 'fallback' are readFileSync, statSync, readlinkSync, existsSync and readdirSync. These were chosen based on webpacks usage. ### Usage ```js const { FallbackFileSystem } = require('kaiju-plugin-utils'); const fileSystem = require('fs'); const MemoryFS = require('memory-fs'); const memFs = new MemoryFS(); const fallbackFs = FallbackFileSystem(memFs.data, fileSystem); ``` ## History [Releases](https://github.com/cerner/kaiju/releases) ## License Copyright 2017 Cerner Innovation, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. <file_sep>const MemoryFS = require('memory-fs'); const appRoot = require('app-root-path'); function updatedArgs(args) { const newArgs = args; if (!newArgs[0].startsWith(appRoot)) { newArgs[0] = `${appRoot}${args[0]}`; } return newArgs; } function fallbackFS(data, fs) { const handler = { get(target, key) { const origMethod = target[key]; if (key === 'readFileSync' || key === 'statSync' || key === 'readlinkSync' || key === 'existsSync' || key === 'readdirSync') { return function apply(...args) { if (target.existsSync(args[0])) { return origMethod.apply(this, args); } return fs[key](...updatedArgs(args)); }; } return origMethod; }, }; return new Proxy(new MemoryFS(data), handler); } module.exports = fallbackFS; <file_sep>const fs = require('fs'); const MemoryFS = require('memory-fs'); const path = require('path'); const fallbackFS = require('../../src/FallbackFileSystem'); describe('FallbackFileSystem', () => { it('finds files in the normal file system', () => { const testFs = fallbackFS({}, fs); expect(testFs.existsSync('/package.json')).toBe(true); expect(testFs.statSync('/package.json')).toBeDefined(); expect(testFs.readFileSync('/package.json')).toBeDefined(); expect(testFs.readlinkSync('/tests/jest/data/package.json')).toBeDefined(); }); it('finds files with the full path', () => { const testFs = fallbackFS({}, fs); const rootPath = path.join(__dirname, '../..'); expect(testFs.existsSync(`${rootPath}/package.json`)).toBe(true); }); it('finds files files in the virtual file system', () => { const testFs = fallbackFS({}, fs); testFs.writeFileSync('/derp.json', 'derp'); expect(testFs.existsSync('/derp.json')).toBe(true); expect(fs.existsSync('/derp.json')).toBe(false); expect(testFs.statSync('/derp.json')).toBeDefined(); expect(testFs.readFileSync('/derp.json')).toBeDefined(); }); it('finds data created previously', () => { const memFS = new MemoryFS(); memFS.writeFileSync('/derp.json', 'derp'); const testFs = fallbackFS(memFS.data, fs); expect(testFs.existsSync('/derp.json')).toBe(true); expect(fs.existsSync('/derp.json')).toBe(false); expect(testFs.statSync('/derp.json')).toBeDefined(); expect(testFs.readFileSync('/derp.json')).toBeDefined(); }); }); <file_sep>const PluginUtils = require('../../src/PluginUtils'); const path = require('path'); const MemoryFS = require('memory-fs'); describe('PluginUtils', () => { describe('rootPath', () => { it('returns the root path', () => { expect(PluginUtils.rootPath()).toBe(path.join(__dirname, '../..')); }); }); describe('webpackFs', () => { it('returns virtual files', () => { const memFS = new MemoryFS(); memFS.writeFileSync('/derp.json', 'derp'); const testFs = PluginUtils.webpackFs(memFS); expect(testFs.existsSync('/derp.json')).toBe(true); }); it('finds real files', () => { const memFS = new MemoryFS(); const testFs = PluginUtils.webpackFs(memFS); expect(testFs.existsSync('/package.json')).toBe(true); }); }); describe('defaultWebpackConfig', () => { it('returns a base webpack config', () => { const publicPath = 'publicPath'; const outputPath = '/build/'; const config = PluginUtils.defaultWebpackConfig(publicPath, outputPath); expect(config.resolve).toEqual({ extensions: ['.js'], modules: [path.join(__dirname, '../..', 'node_modules')], }); expect(config.output).toEqual({ path: outputPath, publicPath, }); expect(config.plugins).toEqual([ { definitions: { 'process.env': { NODE_ENV: '"production"', }, }, }, ]); }); }); describe('runCompiler', () => { it('runs the compiler', (done) => { const config = PluginUtils.defaultWebpackConfig('derp', '/herp/'); const memFS = new MemoryFS(); const testFs = PluginUtils.webpackFs(memFS); config.entry.preview = '/tests/jest/examples/derp.js'; PluginUtils.runCompiler(testFs, config).then((outputFs) => { expect(outputFs.existsSync('/herp/preview.js')).toBe(true); done(); }); }); it('fails running the compiler', (done) => { const config = PluginUtils.defaultWebpackConfig('derp'); const memFS = new MemoryFS(); const testFs = PluginUtils.webpackFs(memFS); config.entry.preview = '/tests/jest/examples/herp.js'; PluginUtils.runCompiler(testFs, config).catch((error) => { expect(error).toBe('Preview failed to compile'); done(); }); }); }); describe('webpackCompiler', () => { it('returns a new webpack compiler', () => { const config = PluginUtils.defaultWebpackConfig('derp'); const memFS = new MemoryFS(); config.entry.preview = '/tests/jest/examples/derp.js'; const compiler = PluginUtils.webpackCompiler(memFS, config); expect(compiler.options.entry.preview).toEqual(config.entry.preview); expect(compiler.inputFileSystem).toBe(memFS); expect(compiler.resolvers.normal.fileSystem).toBe(memFS); expect(compiler.outputFileSystem.constructor.name).toBe('MemoryFileSystem'); }); }); }); <file_sep>// eslint-disable-next-line no-console console.log('derp'); <file_sep>Cerner Corporation - <NAME> [@mjhenkes] [@mjhenkes]: https://github.com/mjhenkes <file_sep>const webpack = require('webpack'); const fileSystem = require('fs'); const MemoryFS = require('memory-fs'); const appRoot = require('app-root-path'); const fallbackFS = require('./FallbackFileSystem'); class PluginUtils { static rootPath() { return appRoot.toString(); } static webpackFs(fs) { return fallbackFS(fs.data, fileSystem); } static defaultWebpackConfig(publicPath, outputPath) { return { entry: { }, resolve: { extensions: ['.js'], modules: [`${PluginUtils.rootPath()}/node_modules`], }, output: { path: outputPath, publicPath, }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), ], }; } static runCompiler(memoryFs, config) { // create webpack compiler // setup compiler filesystem with memory fs const compiler = PluginUtils.webpackCompiler(memoryFs, config); // run compiler return new Promise((resolve, reject) => { compiler.run((err, stats) => { if (err || stats.hasErrors()) { // console.log(err); // console.log(stats); reject('Preview failed to compile'); } resolve(compiler.outputFileSystem); }); }); } static webpackCompiler(compilerFs, config) { const compiler = webpack(config); // hydrate new fs with data compiler.inputFileSystem = compilerFs; compiler.resolvers.normal.fileSystem = compiler.inputFileSystem; // seperate input and output file systems. compiler.outputFileSystem = new MemoryFS(); return compiler; } } module.exports = PluginUtils;
59bb725d67bf089b2242fdcb5753773bf107500e
[ "Markdown", "JavaScript" ]
7
Markdown
ossVerifier/kaiju-plugin-utils
4d886f45a983b71163c14912a189ec5cfebb7870
8122762aa07fa91ef27622676b216f1fd80d6634
refs/heads/master
<file_sep>// // ViewController.swift // appone // // Created by tangbo on 2019/6/18. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import NXDesign enum Type { case toast case alert case camera var title: String { switch self { case .toast: return "HUD" case .alert: return "弹窗" case .camera: return "拍照" } } static var allValues: [Type] { return [.toast, .alert, .camera] } } class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Type.allValues.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellid", for: indexPath) as! TypeCell cell.nameLabel.text = Type.allValues[indexPath.row].title return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let type = Type.allValues[indexPath.row] switch type { case .toast: NXToast.show(text: "哈喽, 我2秒后会消失") case .alert: let cancelAction = NXAlertAction(cancelTitle: "取消") let okAction = NXAlertAction(okTitle: "我知道了") NXAlertView().message("我是内容").title("我是标题").actions([cancelAction, okAction]).show() case .camera: let vc = NXImagePickerController.loadFromStoryboard() vc.delegate = self present(vc, animated: true, completion: nil) } } } extension ViewController: NXImagePickerControllerDelegate { func imagePickerControllerDidCancel(_ picker: NXImagePickerController) { picker.dismiss(animated: true, completion: nil) } } class TypeCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! } <file_sep>// // SFScanCodeProtocol.swift // SFScanCodeKit // // Created by Leo on 2018/12/27. // Copyright © 2018 S.F.Express. All rights reserved. // //MARK: - Load Nib struct NibInfo { /// storyboard 中的 identifier var identifier: String? /// xib 的 name var name: String? } protocol SFScanCodeKitLoadProtocol { static var nibInfo: NibInfo { get } } extension SFScanCodeKitLoadProtocol where Self: UIViewController { static func loadFromNib() -> Self { let storyboard = UIStoryboard(name: "SFScan", bundle: Bundle(for: SFScanCodeViewController.self)) let vc = storyboard.instantiateViewController(withIdentifier: nibInfo.identifier!) as? Self return vc! } } extension SFScanCodeKitLoadProtocol where Self: UIView { static func loadFromNib() -> Self { return Bundle(for: SFScanCodeViewController.self).loadNibNamed(nibInfo.name!, owner: nil, options: nil)?.first as! Self } } //MARK: - Button Info /// - 如果需要新按钮,需要@Leo迭代功能 struct SFScanKitButtonInfo { var icon: UIImage? var title: String? } public enum SFScanKitButtonType { case input case torch var buttonInfo: SFScanKitButtonInfo { switch self { case .input: var info = SFScanKitButtonInfo() info.icon = UIImage(named: "icon_input", in: Bundle(for: SFScanCodeViewController.self), compatibleWith: nil) info.title = "手动输入" return info case .torch: var info = SFScanKitButtonInfo() info.icon = UIImage(named: "icon_torch_off", in: Bundle(for: SFScanCodeViewController.self), compatibleWith: nil) info.title = "手电筒" return info } } } <file_sep>// // NXDesign.swift // NXDesign // // Created by PanDedong on 2018/9/6. // Copyright © 2018年 S.F.Express. All rights reserved. // import UIKit import SFFoundation struct NX {} extension SF { public struct Const { public static var screenWidth: CGFloat { return UIScreen.main.bounds.size.width } public static var screenHeight: CGFloat { return UIScreen.main.bounds.size.height } public static var screenSafeInset: UIEdgeInsets { if #available(iOS 11.0, *) { guard case let window?? = UIApplication.shared.delegate?.window else { return UIEdgeInsets.zero } return window.safeAreaInsets } else { return UIEdgeInsets.zero } } public static var screenSafeBottom: CGFloat { return screenSafeInset.bottom } public static var statusbarHeight: CGFloat { return UIApplication.shared.statusBarFrame.size.height } public static var navigationBarHeight: CGFloat { return (statusbarHeight + 45) } public static var lineHeight: CGFloat { return (1.0 / UIScreen.main.scale) } } } /// 使数组中的第\(activeIndex)个的约束active,其余deactive /// /// - Parameters: /// - constraints: 互斥的约束 /// - activeIndex: 启用约束的数组序号 public func makeActive(constraints: [NSLayoutConstraint], activeIndex: Int) { guard activeIndex >= 0 && activeIndex < constraints.count else { return } constraints.forEach( { if $0.isActive { $0.isActive = false } } ) constraints[activeIndex].isActive = true } /// 使pre和after约束中的一个约束生效,另一个失效 public func makeActive(pre: NSLayoutConstraint, after: NSLayoutConstraint, isPreActive: Bool) { makeActive(constraints: [pre, after], activeIndex: isPreActive ? 0 : 1) } <file_sep>// // SFScanImageCode.swift // SFScanCodeKit // // Created by Leo on 2018/12/28. // Copyright © 2018 S.F.Express. All rights reserved. // import AVKit import CoreImage import SFFoundation extension SFScanCodeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func showImagePickerController() { if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { SFAlertView.alert(withTitle:"提示", message:"相册不可用", cancelButtonTitle: nil, okButtonTitle: "确定", cancelAction: nil, okAction: nil) return } picker.delegate = self picker.sourceType = .photoLibrary picker.modalPresentationStyle = .overFullScreen present(picker, animated: true, completion: nil) } @objc public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { picker.dismiss(animated: true, completion: nil) guard let originalImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { SFToast.show(withText: "二维码错误") return } guard let originalCGImage = originalImage.cgImage else { SFToast.show(withText: "二维码错误") return } let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]) let features = detector?.features(in: CIImage(cgImage: originalCGImage)) if !IsCollectionEmpty(features) { let feature = features?.at(0) as? CIQRCodeFeature let scanResult = feature?.messageString callbackIfNeed(scanResult) } else { SFToast.show(withText: "二维码错误") } } } <file_sep>// // SFScanCodeVC.swift // SFScanCodeKit // // Created by Leo on 2018/12/24. // Copyright © 2018 S.F.Express. All rights reserved. // import UIKit import SFFoundation import CoreGraphics import AVKit public protocol SFScanCodeControllerDelegate: AnyObject { /// 扫描结果 /// - 扫描成功之后,会自动关闭扫描功能 /// - Parameter scanCodeVC: 当前扫描控制器 /// - Parameter codeString: 扫描结果 /// - Returns: 是否需要重新启动扫描 func scanCodeVC(_ scanCodeVC: SFScanCodeViewController, didEndScan codeString: String?) -> Bool } open class SFScanCodeViewController: SFViewController, SFScanCodeVCNavigationBarDelegate { public typealias SFScanCodeCallback = (_ scanViewController: SFScanCodeViewController, _ result: String?) -> (Bool) public weak var delegate: SFScanCodeControllerDelegate? public var scanResultCallback: SFScanCodeCallback? /// 导航栏 public var navigationBar: SFScanCodeViewControllerNavigationBar! /// 提示栏 public var tipsView: SFScanCodeViewControllerTipsView! /// 扫描框 public var scanView: SFScanCodeViewControllerScanView! /// 按钮栏 public var buttonsView = UIView() /// 按钮类型列表 open var buttonTypeList: [SFScanKitButtonType] { return [.input, .torch] } /// 弹窗按钮主体颜色 open var themeColor: UIColor { return UIColor.hex(0x26CEA8) } /// 扫描框区域 open var interestRect: CGRect { get { return CGRect(x: (SF.Const.screenWidth - kScanSideLenth) / 2, y: SF.Const.navigationBarHeight + 40 + 32 + 15, width: kScanSideLenth, height: kScanSideLenth) } } /// 扫描框宽高 public let kScanSideLenth = ceil(SF.Const.screenWidth * 0.747) /// 按钮字典 /// - 依据 buttonTypeList 自动生成 /// - Key: SFScanKitButtonType /// - Value: SFScanCodeButton public private(set) var buttonList = [SFScanKitButtonType: SFScanCodeButton]() /// - 当前手电筒状态 ture:打开 public var isTorchOn = false { didSet { let torchImage = isTorchOn ? UIImage(named: "icon_torch_on", in: Bundle(for: SFScanCodeViewController.self), compatibleWith: nil) : UIImage(named: "icon_torch_off", in: Bundle(for: SFScanCodeViewController.self), compatibleWith: nil) let torchBtn = buttonList[.torch] torchBtn?.imageView.image = torchImage } } /// - 扫码模式:条形码,二维码 open var scanTypes: [AVMetadataObject.ObjectType] = [.qr, .ean8, .ean13, .code128] open override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } var bgView = UIView() var captureView = UIView() var maskLayer = CAShapeLayer() let session = AVCaptureSession() var previewLayer: AVCaptureVideoPreviewLayer? var output = AVCaptureMetadataOutput() var input: AVCaptureDeviceInput! var picker = UIImagePickerController() var isInputting = false //MARK: - Init public convenience init(delegate: SFScanCodeControllerDelegate?) { self.init(nibName: nil, bundle: nil) self.delegate = delegate } public convenience init(completion: SFScanCodeCallback?) { self.init(nibName: nil, bundle: nil) self.scanResultCallback = completion } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { if session.isRunning { session.stopRunning() } } override open func viewDidLoad() { super.viewDidLoad() checkAuthorization() configUI() configCapture() } private func checkAuthorization() { let hasBeenLoaded = UserDefaults.standard.bool(forKey: "SFScanViewControllerHasBeenLoaded") if !hasBeenLoaded { UserDefaults.standard.set(true, forKey: "SFScanViewControllerHasBeenLoaded") UserDefaults.standard.synchronize() return } if !SFScanCodeViewController.checkAuthorized() { SFScanAlertViewController.show(delegate: self, type: .authorization, themeColor: themeColor) } } private func configUI() { /// 添加captureView captureView.backgroundColor = .black sf_view.addSubview(captureView) // 添加previewLayer previewLayer = AVCaptureVideoPreviewLayer(session: session) previewLayer?.videoGravity = .resizeAspectFill previewLayer?.frame = UIScreen.main.bounds captureView.layer.addSublayer(previewLayer!) /// 添加bgView sf_view.addSubview(bgView) /// 添加导航条 navigationBar = SFScanCodeViewControllerNavigationBar.loadFromNib() navigationBar.delegate = self bgView.addSubview(navigationBar) /// 添加提示条 tipsView = SFScanCodeViewControllerTipsView.loadFromNib() bgView.addSubview(tipsView) /// 添加扫描框 scanView = SFScanCodeViewControllerScanView.loadFromNib() scanView.layer.masksToBounds = true sf_view.addSubview(scanView) /// 添加扫描框mask maskLayer.fillRule = .evenOdd bgView.layer.mask = maskLayer /// 添加镂空 let basicPath = UIBezierPath(rect: view.bounds) let maskPath = UIBezierPath(rect: interestRect) basicPath.append(maskPath) maskLayer.path = basicPath.cgPath /// 添加按钮栏 bgView.addSubview(buttonsView) configButtonList() configBackgroudClear() } /// 添加按钮列表 private func configButtonList() { buttonTypeList.forEach { configBottomButton($0) } } private func configBackgroudClear() { bgView.backgroundColor = UIColor(white: 0, alpha: 0.6) navigationBar.backgroundColor = .clear navigationBar.bgView.backgroundColor = .clear tipsView.backgroundColor = UIColor(white: 0, alpha: 0.4) tipsView.bgView.backgroundColor = .clear scanView.backgroundColor = .clear scanView.bgView.backgroundColor = .clear buttonsView.backgroundColor = .clear buttonList.values.forEach { $0.backgroundColor = .clear } } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() captureView.frame = UIScreen.main.bounds bgView.frame = UIScreen.main.bounds previewLayer?.frame = CGRect(x: 0, y: 0, width: bgView.width, height: bgView.height) navigationBar.frame = CGRect(x: 0, y: 0, width: bgView.width, height: SF.Const.navigationBarHeight) tipsView.frame = CGRect(x: (bgView.width - kScanSideLenth) / 2, y: navigationBar.bottom + 40, width: kScanSideLenth, height: 32) scanView.frame = interestRect scanView.animation(isStart: true) buttonsView.size = CGSize(width: bgView.width, height: 82.5) buttonsView.left = 0 buttonsView.bottom = bgView.height - 40 - SF.Const.screenSafeBottom /// 目前只有0,1,2三个按钮的情况,如果有更多按钮,需要视觉给出间距。 let gapInside = buttonList.count == 1 ? -1 : 100 var left = (SF.Const.screenWidth - 100 - 56 * 2) / 2 for type in buttonTypeList { let button = buttonList[type] button!.size = CGSize(width: 56, height: 82.5) if gapInside == -1 { button!.centerX = SF.Const.screenWidth / 2 } else { button!.left = left left += 56 left += 100 } } } //MARK: - Interface /// - 权限检测 public static func checkAuthorized() -> Bool { let status = AVCaptureDevice.authorizationStatus(for: .video) if status == .restricted || status == .denied { return false } else { return true } } /// - 停止扫描 open func stopScan() { scanView.animation(isStart: false) if session.isRunning { session.stopRunning() } isTorchOn = false } /// - 开始扫描 open func startScan() { scanView.animation(isStart: true) if !session.isRunning { session.startRunning() } } /// - 开关手电筒 public func turnTorch() { turn() } /// - 弹出手动输入 public func showInputAlert() { isInputting = true SFScanAlertViewController.show(delegate: self, type: .input, themeColor: themeColor) } /// - 退出 public func back() { if let vc = presentingViewController, vc == self { dismiss(animated: true, completion: nil) return } navigationController?.popViewController(animated: true) } //MARK: - Methods func callbackIfNeed(_ codeString: String?) { if delegate?.scanCodeVC(self, didEndScan: codeString) ?? true { startScan() } guard let callback = scanResultCallback else { return } let shouldRestart = callback(self, codeString) if shouldRestart { startScan() } } private func configBottomButton(_ type: SFScanKitButtonType) { let button = SFScanCodeButton.loadFromNib() button.icon = type.buttonInfo.icon button.title = type.buttonInfo.title button.type = type button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside) buttonsView.addSubview(button) buttonList[type] = button } open override func sf_preferredNavigationBarHidden() -> Bool { return true } //MARK: - Touch event @objc func buttonClicked(sender: SFScanCodeButton) { switch sender.type { case .input?: showInputAlert() case .torch?: turn() default: print("implementation the action") } } //MARK: - delegate func didClickedLeftButton(navigationbar: SFScanCodeViewControllerNavigationBar) { back() } func didClickedRightButton(navigationbar: SFScanCodeViewControllerNavigationBar) { showImagePickerController() } } <file_sep>// // OrderModel.swift // appone // // Created by tangbo on 2019/6/29. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit enum OrderStatus: Int, Codable { ///等待商家确认 case wait = 0 ///制作中 case producting ///等待付款 case waitingForPay ///配送中 case delivering ///完成 case done var description: String { get { switch self { case .wait: return "等待商家确认" case .producting: return "正在制作中" case .waitingForPay: return "菜品已上齐,用餐结束后,请去前台结账" case .delivering: return "配送中" case .done: return "感谢光临" } } } } struct OrderModel: Codable { ///取餐码 var number: String? ///是否外卖 var takeout: Bool? ///订单号 var orderId: String? var foods: [FoodModel]? ///总价 var totalPrice:String? ///状态 var status:OrderStatus? ///送餐地址 var address: String? var name: String? var phone: String? } <file_sep>// // SFConst.swift // Knight // // Created by DoubleHH on 2018/1/15. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // public struct SF { } /// Optional(String) -> String public func ToStr(_ string: String?) -> String { return ToStr(string, "") } /// Optional(String) -> String, if string is nil or emtpy, use default string public func ToStr(_ string: String?, _ defaultString: String) -> String { return (IsCollectionEmpty(string) ? defaultString : string!) } /// if Collection is nil or emtpy public func IsCollectionEmpty<T>(_ collection: T?) -> Bool where T: Collection { guard let collection = collection else { return true } return collection.isEmpty } <file_sep>// // XNConstant.swift // appone // // Created by tangbo on 2019/6/22. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import SFFoundation let AppKey_appId = "1472923117" let Bmob_ApplicationId = "130825ad5b38431c3bbef5193387bfa8" let Bmob_clientKey = "<KEY>" let Bmob_configId = "783dbd1bd7" let Bmob_shopInfoId = "99dcedf7ef" let APPStore_name = "小牛餐厅" let ErrorMessage_default = "网络请求失败,请稍后再试" let Color_Main = UIColor.hex("#f29c2b") let DefaultImage_placeholder = UIColor.hex("#f8f8f8").image(size: CGSize(width: 1, height: 1)) let DefaultImage_main = Color_Main.image(size: CGSize(width: 1, height: 1)) let DefaultAccount_phone = "18514567266" let DefaultAccount_code = "000000" <file_sep>// // SFScanAlertHandle.swift // SFScanCodeKit // // Created by Leo on 2018/12/27. // Copyright © 2018 S.F.Express. All rights reserved. // extension SFScanCodeViewController: SFScanAlertDelegate { func scanAlert(_ scanAlertVC: SFScanAlertViewController, didConfirm code: String) { isInputting = false callbackIfNeed(code) } func scanAlertCancel(_ scanAlertVC: SFScanAlertViewController) { isInputting = false } } <file_sep>// // SFAutoMakeInputVisableProtocol.swift // // Created by DoubleHH on 2018/6/7. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit /// Auto make input view visible public protocol SFAutoMakeInputVisableProtocol: NSObjectProtocol { func findScrollView() -> UIScrollView? func keyboardWillShowNoti(noti: Notification) } extension SFAutoMakeInputVisableProtocol where Self: UIView, Self: UITextInput { public func keyboardWillShowNoti(noti: Notification) { if !self.isFirstResponder { return } guard let scrollView = findScrollView(), let keybordRect = noti.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect, let point = UIApplication.shared.keyWindow?.convert(keybordRect.origin, to: scrollView.superview) else { return } // visible height of scrollview let visibleHeight = point.y - scrollView.frame.origin.y guard visibleHeight > 10 else { return } // make textField visable let editPoint = self.superview!.convert(self.frame.origin, to: scrollView) var offset = scrollView.contentOffset if editPoint.y < offset.y || (editPoint.y + self.frame.height) > (offset.y + visibleHeight) { offset.y = editPoint.y < offset.y ? editPoint.y : (editPoint.y + self.frame.height - visibleHeight) scrollView.setContentOffset(offset, animated: true) } } public func findScrollView() -> UIScrollView? { var sView = self.superview while true { guard let aSuperView = sView else { break } if aSuperView.isKind(of: UIScrollView.self) { break } sView = aSuperView.superview } return sView as? UIScrollView } } <file_sep>// // UIViewExtensions.swift // SFFoundation // // Created by Panda on 2018/9/21. // Copyright © 2018年 SF Intra-city. All rights reserved. // import Foundation import UIKit @objc extension UIView { public var left: CGFloat { get { return self.frame.origin.x } set { var frame = self.frame frame.origin.x = newValue self.frame = frame } } public var top: CGFloat { get { return self.frame.origin.y } set { var frame = self.frame frame.origin.y = newValue self.frame = frame } } public var right: CGFloat { get { return self.frame.origin.x + self.frame.size.width; } set { var frame = self.frame frame.origin.x = newValue - frame.size.width; self.frame = frame } } public var bottom: CGFloat { get { return self.frame.origin.y + self.frame.size.height; } set { var frame = self.frame frame.origin.y = newValue - frame.size.height; self.frame = frame } } public var centerX: CGFloat { get { return self.center.x; } set { var center = self.center center.x = newValue self.center = center } } public var centerY: CGFloat { get { return self.center.y; } set { var center = self.center center.y = newValue self.center = center } } public var width: CGFloat { get { return self.frame.size.width; } set { var frame = self.frame frame.size.width = newValue; self.frame = frame } } public var height: CGFloat { get { return self.frame.size.height; } set { var frame = self.frame frame.size.height = newValue; self.frame = frame } } public var origin: CGPoint { get { return self.frame.origin } set { var frame = self.frame frame.origin = newValue; self.frame = frame } } public var size: CGSize { get { return self.frame.size } set { var frame = self.frame frame.size = newValue; self.frame = frame } } public func removeAllSubviews(){ while self.subviews.count > 0 { let subView = self.subviews.first subView?.removeFromSuperview() } } public func toImage() -> UIImage? { let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(bounds.size, false, scale) guard let context = UIGraphicsGetCurrentContext() else { UIGraphicsEndImageContext() return nil } layer.render(in: context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } public func corner(withRadius radius: CGFloat = 6, color: UIColor = .white) -> CALayer? { var cornerLayer = objc_getAssociatedObject(self, UnsafeRawPointer.init(bitPattern: "ViewCornerLayerKey".hashValue)!) as? CALayer if cornerLayer == nil { cornerLayer = CALayer() layer.addSublayer(cornerLayer!) layer.insertSublayer(cornerLayer!, at: 0) objc_setAssociatedObject(self, UnsafeRawPointer.init(bitPattern: "ViewCornerLayerKey".hashValue)!, cornerLayer!, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } cornerLayer?.masksToBounds = true cornerLayer?.cornerRadius = radius cornerLayer?.backgroundColor = color.cgColor if bounds.size.width == 0 || bounds.size.height == 0 { layoutIfNeeded() } cornerLayer?.frame = bounds return cornerLayer } public func shadow(withColor color: UIColor = UIColor.hex("#000000").withAlphaComponent(0.2), opacity: Float = 0.6, radius: CGFloat = 4, offset: CGSize = CGSize()) { layer.shadowColor = color.cgColor layer.shadowOpacity = opacity layer.shadowRadius = radius layer.shadowOffset = offset } public func addCornerAndShadow(withCornerRadius cornerRadius: CGFloat = 6, cornerColor: UIColor = .white, shadowColor: UIColor = UIColor.hex("#000000").withAlphaComponent(0.2), shadowOpacity: Float = 0.6, shadowRadius: CGFloat = 4, shadowOffset: CGSize = CGSize()) -> CALayer? { shadow(withColor: shadowColor, opacity: shadowOpacity, radius: shadowRadius, offset: shadowOffset) return corner(withRadius: cornerRadius, color: cornerColor) } } <file_sep>// // CharacterSetExtensions.swift // BaseTest // // Created by DoubleHH on 2018/8/17. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation extension CharacterSet { public static var sf_urlQueryNotAllowed: CharacterSet = CharacterSet.init(charactersIn: "!*'();:@&=+$,/?%#[]~") } <file_sep>// // Sheetable.swift // workservice // // Created by Leo on 2019/4/1. // Copyright © 2019 Beijing SF intra-city Technology Co., Ltd. All rights reserved. // import SFFoundation var kSheetDirectionKey = UnsafeRawPointer(bitPattern: "kSheetDirectionKey".hashValue)! var kSheetViewKey = UnsafeRawPointer(bitPattern: "kSheetViewKey".hashValue)! public enum SheetDirection { case toTop, toBottom, toLeft, toRight } public protocol Sheetable { func shouldDismissTouchBackground() -> Bool } public extension Sheetable where Self: UIView { /// 视图出现 /// - Parameter position: 视图开始出现的点 /// - Parameter originSize: 视图大小 /// - Parameter direction: 视图弹出方向 /// - toTop、toBottom: position 为左侧顶点 /// - toLeft、toRight: position 为上侧顶点 func show(_ inView: UIView = UIApplication.shared.delegate!.window!!, withOriginSize originSize: CGSize = CGSize(width: UIScreen.main.bounds.width, height: 245 + SF.Const.screenSafeBottom), position: CGPoint = CGPoint(x: 0, y: SF.Const.screenHeight), direction: SheetDirection = .toTop) { if let _ = objc_getAssociatedObject(inView, kSheetViewKey) { return } objc_setAssociatedObject(inView, kSheetViewKey, self, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(inView, kSheetDirectionKey, direction, .OBJC_ASSOCIATION_COPY_NONATOMIC) let contentView = ContentView(frame: inView.bounds) contentView.bgTap = { [weak self] in if self?.shouldDismissTouchBackground() ?? true { self?.dismiss() } } self.layer.masksToBounds = true contentView.backgroundColor = .clear inView.addSubview(contentView) contentView.addSubview(self) let positionTuple = showPosition(position, originSize, direction) frame = positionTuple.originationFrame UIView.animate(withDuration: 0.25) { contentView.backgroundColor = UIColor.black.withAlphaComponent(0.4) self.frame = positionTuple.destinationFrame } } /// 视图消失 func dismiss() { guard let fatherView = self.superview?.superview else { return } var direction = SheetDirection.toTop if let customDirection = objc_getAssociatedObject(fatherView, kSheetDirectionKey) as? SheetDirection { direction = customDirection } objc_setAssociatedObject(fatherView, kSheetViewKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(fatherView, kSheetDirectionKey, nil, .OBJC_ASSOCIATION_COPY_NONATOMIC) UIView.animate(withDuration: 0.25, animations: { self.frame = self.dismissPosition(direction) self.superview?.backgroundColor = .clear self.layoutIfNeeded() }) { (success) in self.superview?.removeFromSuperview() } } func shouldDismissTouchBackground() -> Bool { return true } private func showPosition(_ position: CGPoint, _ size: CGSize, _ direction: SheetDirection) -> (originationFrame: CGRect, destinationFrame: CGRect) { var originationFrame = CGRect() var destinationFrame = CGRect() switch direction { case .toTop: originationFrame = CGRect(origin: position, size: CGSize(width: size.width, height: 0)) destinationFrame = CGRect(origin: CGPoint(x: position.x, y: position.y - size.height), size: size) case .toLeft: originationFrame = CGRect(origin: position, size: CGSize(width: 0, height: size.height)) destinationFrame = CGRect(origin: CGPoint(x: position.x - size.width, y: position.y), size: size) case .toRight: originationFrame = CGRect(origin: position, size: CGSize(width: 0, height: size.height)) destinationFrame = CGRect(origin: position, size: size) case .toBottom: originationFrame = CGRect(origin: position, size: CGSize(width: size.width, height: 0)) destinationFrame = CGRect(origin: position, size: size) } return (originationFrame, destinationFrame) } private func dismissPosition(_ direction: SheetDirection) -> CGRect { var dismissFrame = CGRect() switch direction { case .toTop: dismissFrame = CGRect(x: left, y: top + height, width: size.width, height: 0) case .toLeft: dismissFrame = CGRect(x: left + width, y: top, width: 0, height: size.height) case .toRight: dismissFrame = CGRect(x: left, y: top, width: 0, height: size.height) case .toBottom: dismissFrame = CGRect(x: left, y: top, width: size.width, height: 0) } return dismissFrame } } private class ContentView: UIView { var bgTap: (()->())? var backgroundView = UIControl() override init(frame: CGRect) { super.init(frame: frame) configureViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configureViews() { backgroundView.frame = bounds backgroundView.backgroundColor = .clear backgroundView.addTarget(self, action: #selector(bgTapped), for: .touchUpInside) addSubview(backgroundView) } @objc private func bgTapped() { bgTap?() } } <file_sep>// // ImageBrowserInteractiveTransition.swift // NXDesign // // Created by tangbo on 2019/2/2. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit import SFFoundation class ImageBrowserInteractiveTransition: UIPercentDrivenInteractiveTransition { private(set) var isInteractive = false private weak var viewController: NXImageBrowserController! var transitionAnimation: ImageBrowserTransitionAnimation! func addPanGesture(forViewController controller: NXImageBrowserController) { self.viewController = controller let pan = UIPanGestureRecognizer(target: self, action: #selector(panGes(pan:))) pan.delegate = self controller.view.addGestureRecognizer(pan) } func transitionAnimationAction(translation: CGPoint, percent: CGFloat) { guard let centerX = transitionAnimation.tempImageOriginFrame?.midX, let centerY = transitionAnimation.tempImageOriginFrame?.midY else { return } guard let size = transitionAnimation.tempImageOriginFrame?.size else { return } transitionAnimation.tempImageView?.center = CGPoint(x: centerX + translation.x, y: centerY + translation.y) transitionAnimation.tempImageView?.size = CGSize(width: size.width * percent, height: size.height * percent) } @objc func panGes(pan: UIPanGestureRecognizer) { let translation = pan.translation(in: pan.view) let viewHeight = SF.Const.screenHeight / 2 let percent = min(max(translation.y, 0) / viewHeight, 1) transitionAnimationAction(translation: translation, percent: max(1 - percent, 0.5)) switch pan.state { case .began: isInteractive = true viewController.navigationController?.popViewController(animated: true) case .changed: update(percent) case .ended, .cancelled: isInteractive = false if (percent > 0.5) { UIView.animate(withDuration: 0.3, animations: { self.transitionAnimation.tempImageView?.alpha = 0 }) { (finished) in self.finish() } } else { UIView.animate(withDuration: 0.3, animations: { guard let frame = self.transitionAnimation.tempImageOriginFrame else { return } self.transitionAnimation.tempImageView?.frame = frame }) { (finished) in self.cancel() } } default: break } } } extension ImageBrowserInteractiveTransition: UIGestureRecognizerDelegate { func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return !viewController.imageZooming } } <file_sep>// // SFCameraDroppableImageView.swift // SFImageKit // // Created by tangbo on 2018/10/26. // Copyright © 2018 S.F.Express. All rights reserved. // import UIKit import SFFoundation class NXCameraDroppableImageView: UIView { private let imageView = UIImageView() private var cornerLayer: CALayer! var originCenter: CGPoint! convenience init(image: UIImage, center: CGPoint) { self.init(frame: CGRect(x: 0, y: 0, width: 60, height: 60)) self.originCenter = center self.center = center imageView.image = image } override init(frame: CGRect) { super.init(frame: frame) imageView.layer.masksToBounds = true imageView.layer.cornerRadius = 3 addSubview(imageView) layer.shadowColor = UIColor.hex("#000000").withAlphaComponent(0.2).cgColor layer.shadowOpacity = 0.6 layer.shadowRadius = 4 layer.shadowOffset = CGSize(width: 10, height: 10) cornerLayer = CALayer() layer.addSublayer(cornerLayer) layer.insertSublayer(cornerLayer, at: 0) cornerLayer.masksToBounds = true cornerLayer.cornerRadius = 3 cornerLayer.backgroundColor = UIColor.hex("#333333").cgColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() imageView.size = CGSize(width: bounds.size.width - 1, height: bounds.size.height - 1) imageView.center = CGPoint(x: width / 2, y: height / 2) cornerLayer.frame = bounds } } <file_sep>// // UserCenterViewController.swift // appone // // Created by tangbo on 2019/6/22. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import NXDesign import SFFoundation class XNUserCenterViewController: BaseViewController, StoryboardLoadable { static var fileInfo = StoryboardFileInfo(name: "tabbar", identifier: "userCenter") @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var callButton: UIButton! @IBOutlet weak var logoutControl: UIControl! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateViews() } override func viewDidLoad() { super.viewDidLoad() callButton.setTitleColor(Color_Main, for: .normal) } func updateViews() { if Account.isLogin { nameLabel.text = Account.phone ?? "18514567266" } else { nameLabel.text = "去登录" } logoutControl.isHidden = !(Account.isLogin) } @IBAction func aboutAction(_ sender: Any) { navigationController?.pushViewController(AboutViewController.loadFromNib()!, animated: true) } @IBAction func loginAction(_ sender: Any) { if Account.isLogin == false { Account.login { [weak self] (success) in self?.updateViews() } } } @IBAction func logoutAction(_ sender: Any) { if Account.isLogin == true { let cancel = NXAlertAction(cancelTitle: "取消") let ok = NXAlertAction(okTitle: "确定", style: .custom(Color_Main)) { Account.logout() self.updateViews() } NXAlertView().message("确定要退出登录吗?").actions([cancel, ok]).show() } } @IBAction func callAction(_ sender: Any) { SFCall.call("18514567266") } } <file_sep>// // UIScrollViewTopMovableExtension.swift // NXDesign // // Created by DoubleHH on 2019/3/29. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation var kIsTopMovable: Bool = false /** * 功能:顶部(contentInset 的 top 部分)可滑动, * 需要做的是: * 1. isTopMovable 设为 true; * 2. 设置contentInset的top值大于0; */ public extension UIScrollView { /// 顶部(contentInset 的 top 部分)是否可穿透,让底层view滑动。默认为false; public var isTopMovable: Bool { get { return objc_getAssociatedObject(self, &kIsTopMovable) as? Bool ?? false } set { objc_setAssociatedObject(self, &kIsTopMovable, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if point.y < 0 && isTopMovable { return nil } return super.hitTest(point, with: event) } } <file_sep>// // NXAlertAction.swift // NXDesign // // Created by tangbo on 2019/2/19. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit public struct NXAlertAction { public enum Style { ///色号为#26CEA8或自定义的颜色 case highlighted ///色号为#333333 100% case dark ///色号为#999999 100% case lightDark ///色号为#C8C8C8 100%,此时按钮不可点击 case lightGray ///自定义颜色 case custom(UIColor) } ///按钮的标题 public var title: String! ///按钮的风格 public var style: Style = .dark ///按钮的唯一识别符 public var identifier: String? ///按钮的点击事件,当点击按钮时需要关闭弹窗的话,返回true,不需要关闭弹窗的话,返回false public var handler: ((NXAlertButton) -> (Bool?))? public init(title: String, style: Style = .dark, identifier: String? = nil, handler: ((NXAlertButton) -> (Bool?))? = nil) { self.title = title self.style = style self.identifier = identifier self.handler = handler } } public extension NXAlertAction { init(cancelTitle: String, handler: (()->())? = nil) { self.title = cancelTitle self.style = .lightDark self.identifier = nil let handlerAction = { (button: NXAlertButton) -> Bool? in handler?() return nil } self.handler = handlerAction } init(okTitle: String, style: Style = .dark, handler: (()->())? = nil) { self.title = okTitle self.style = style self.identifier = nil let handlerAction = { (button: NXAlertButton) -> Bool? in handler?() return nil } self.handler = handlerAction } } public class NXAlertButton: UIView { class ActionControl: UIControl { override var isHighlighted: Bool { set { backgroundColor = newValue ? UIColor.hex("#F7F7F7") : UIColor.white super.isHighlighted = newValue } get { return super.isHighlighted } } } ///当前按钮的配置信息 public var action:NXAlertAction! { didSet { titleLabel.text = action.title configStyle() } } ///当前按钮所在的弹窗 public weak var alertView: NXAlertView? var control = ActionControl() var titleLabel = UILabel() public init(action:NXAlertAction) { self.action = action super.init(frame: CGRect.zero) configUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configUI() { addSubview(control) control.addTarget(self, action: #selector(controlClicked), for: .touchUpInside) control.backgroundColor = UIColor.white addSubview(titleLabel) titleLabel.text = action.title titleLabel.textAlignment = .center titleLabel.font = UIFont.boldSystemFont(ofSize: 16) configStyle() } func configStyle() { titleLabel.textColor = UIColor.hex("#333333") switch action.style { case .highlighted: titleLabel.textColor = NXAlertView.tintColor case .dark: titleLabel.textColor = UIColor.hex("#333333") case .lightDark: titleLabel.textColor = UIColor.hex("#999999") case .lightGray: titleLabel.textColor = UIColor.hex("#C8C8C8") case let .custom(color): titleLabel.textColor = color } switch action.style { case .lightGray: isUserInteractionEnabled = false default: isUserInteractionEnabled = true } } @objc func controlClicked() { if let result = action.handler?(self), !result { return } alertView?.dismiss() } public override func layoutSubviews() { super.layoutSubviews() control.frame = bounds titleLabel.frame = bounds } } class NXActionHorizontalView: UIView { var actions = [NXAlertAction]() weak var alertView: NXAlertView? let topLineView = UIView() init(frame: CGRect, actions: [NXAlertAction], alertView: NXAlertView?) { self.actions = actions self.alertView = alertView super.init(frame: frame) configUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configUI() { let count = CGFloat(actions.count) if count == 0 { return } let lineWidth: CGFloat = 0.5 topLineView.backgroundColor = UIColor.hex("#E6E6E6") addSubview(topLineView) topLineView.frame = CGRect(x: 0, y: 0, width: frame.width, height: lineWidth) let actionViewWidth = (frame.width - lineWidth * (count - 1)) / count let actionViewHeight: CGFloat = 45 var lastView: UIView? for (index, item) in actions.enumerated() { let actionView = NXAlertButton(action: item) actionView.alertView = alertView addSubview(actionView) actionView.frame = CGRect(x: (lastView == nil) ? 0 : (lastView?.frame.maxX ?? 0), y: topLineView.frame.maxY, width: actionViewWidth, height: actionViewHeight) if CGFloat(index) == count - 1 { continue } let lineView = UIView() lineView.backgroundColor = UIColor.hex("#E6E6E6") addSubview(lineView) lineView.frame = CGRect(x: actionView.frame.maxX, y: topLineView.frame.maxY, width: lineWidth, height: actionViewHeight) lastView = lineView } frame = CGRect(x: frame.minX, y: frame.minY, width: frame.width, height: actionViewHeight + lineWidth) } } class NXActionVerticalView: UIView { var actions = [NXAlertAction]() weak var alertView: NXAlertView? init(frame: CGRect, actions: [NXAlertAction], alertView: NXAlertView?) { self.actions = actions self.alertView = alertView super.init(frame: frame) configUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configUI() { var lastView: UIView? let actionViewHeight: CGFloat = 45 let lineHeight: CGFloat = 0.5 for item in actions { let lineView = UIView() lineView.backgroundColor = UIColor.hex("#E6E6E6") addSubview(lineView) lineView.frame = CGRect(x: 0, y: (lastView == nil) ? 0 : (lastView?.frame.maxY ?? 0), width: frame.width, height: lineHeight) let actionView = NXAlertButton(action: item) actionView.alertView = alertView addSubview(actionView) actionView.frame = CGRect(x: 0, y: lineView.frame.maxY, width: frame.width, height: actionViewHeight) lastView = actionView } frame = CGRect(x: frame.minX, y: frame.minY, width: frame.width, height: lastView?.frame.maxY ?? 0) } } <file_sep>// // SFImagePickerController.swift // SFImageKit // // Created by tangbo on 2018/10/23. // Copyright © 2018 S.F.Express. All rights reserved. // import UIKit import SFFoundation import AVFoundation extension UIImagePickerController.CameraFlashMode { mutating func next() -> (UIImagePickerController.CameraFlashMode, String) { switch self { case .off: self = .on case .on: self = .off default: self = .on } return (self, imageIconName()) } func imageIconName() -> String { switch self { case .off: return "sfimagekit_icon_camera_flashlight_close" case .on: return "sfimagekit_icon_camera_flashlight_open" default: return "sfimagekit_icon_camera_flashlight_close" } } } extension UIImagePickerController.CameraDevice { func next() -> UIImagePickerController.CameraDevice { switch self { case .rear: return .front case .front: return .rear } } } public protocol NXImagePickerControllerDelegate: AnyObject { /** 点击下一步的时候调用 * parameter picker: 当前拍照对象, SFImagePickerController * parameter images: 拍的所有照片 */ func imagePickerController(_ picker: NXImagePickerController, didFinishPickingImages images: [UIImage]) /// 点击左上角取消按钮的时候调用 /// - parameter picker: 当前拍照对象, SFImagePickerController func imagePickerControllerDidCancel(_ picker: NXImagePickerController) /// 点击帮助按钮的时候调用 /// - parameter picker: 当前拍照对象, SFImagePickerController func imagePickerControllerDidHelp(_ picker: NXImagePickerController) } public extension NXImagePickerControllerDelegate { func imagePickerController(_ picker: NXImagePickerController, didFinishPickingImages images: [UIImage]) {} func imagePickerControllerDidCancel(_ picker: NXImagePickerController) {} func imagePickerControllerDidHelp(_ picker: NXImagePickerController) {} } open class NXImagePickerController: UIViewController { ///最多拍摄张数,默认10张 open var maxCount: Int = 10 ///最低拍摄张数 open var minCount: Int = 1 ///主题色 open var tintColor = UIColor.hex("#50B722") ///下一步按钮可点击状态下的图片 open var confirmNormalImage = UIImage(named: "sfimagekit_icon_camera_next", in: Bundle(for: NXImagePickerController.self), compatibleWith: nil) ///下一步按钮不可点击状态下的图片 open var confirmDisableImage = UIImage(named: "sfimagekit_icon_camera_next_disable", in: Bundle(for: NXImagePickerController.self), compatibleWith: nil) open var showHelpButton = false open weak var delegate: NXImagePickerControllerDelegate? class var cameraAuth: Bool { let authStatus = AVCaptureDevice.authorizationStatus(for: .video) if authStatus == .restricted || authStatus == .denied { return false } return true } private var images = [UIImage]() private var imagePicker: UIImagePickerController! private var cameraOverlayView: NXCameraOverlayView! private var droppableImageView: NXCameraDroppableImageView? private var garbageContainerView: NXCameraGarbageContainerView? open override var prefersStatusBarHidden: Bool { return true } open override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge { return .all } private var rootViewController: UIViewController? { willSet { rootViewController?.willMove(toParent: nil) rootViewController?.view.removeFromSuperview() rootViewController?.removeFromParent() } didSet { guard let viewController = self.rootViewController else { return } addChild(viewController) viewController.view.frame = view.bounds viewController.view.clipsToBounds = true viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(viewController.view) viewController.didMove(toParent: self) } } open class func loadFromStoryboard() -> NXImagePickerController { return UIStoryboard(name: "ImagePicker", bundle: Bundle(for: NXImagePickerController.self)).instantiateViewController(withIdentifier: "SFImagePickerController") as! NXImagePickerController } override open func viewDidLoad() { super.viewDidLoad() if minCount > maxCount {fatalError("minCount 不能大于 maxCount")} configCameraViewController() } private func configCameraViewController() { if !NXImagePickerController.cameraAuth { } if UIImagePickerController.isSourceTypeAvailable(.camera) { imagePicker = UIImagePickerController() imagePicker.sourceType = .camera imagePicker.cameraFlashMode = .off imagePicker.allowsEditing = false imagePicker.showsCameraControls = false imagePicker.delegate = self configCameraOverlayView() } } private func configCameraOverlayView() { cameraOverlayView = NXCameraOverlayView.loadFromNib() let cameraAspectRatio: CGFloat = 4.0 / 3 let cameraHeight = UIScreen.main.bounds.width * cameraAspectRatio DispatchQueue.main.async {self.rootViewController = self.imagePicker} let translationY = cameraOverlayView.translationY(cameraHeight: cameraHeight) imagePicker.cameraViewTransform = CGAffineTransform(translationX: 0, y: max(0, translationY)) cameraOverlayView.closeButton.addTarget(self, action: #selector(closeButtonClicked), for: .touchUpInside) cameraOverlayView.deleteButton.addTarget(self, action: #selector(deleteButtonClicked), for: .touchUpInside) cameraOverlayView.helpButton.isHidden = !showHelpButton if showHelpButton { cameraOverlayView.helpButton.addTarget(self, action: #selector(helpButtonClicked), for: .touchUpInside) } cameraOverlayView.flashButton.addTarget(self, action: #selector(flashButtonClicked), for: .touchUpInside) cameraOverlayView.deviceButton.addTarget(self, action: #selector(deviceButtonClicked), for: .touchUpInside) cameraOverlayView.takePictureControl.countLabel.textColor = tintColor cameraOverlayView.takePictureControl.addTarget(self, action: #selector(takePictureControlClicked), for: .touchUpInside) cameraOverlayView.commitButton.addTarget(self, action: #selector(commitButtonClicked), for: .touchUpInside) cameraOverlayView.commitButton.setImage(confirmNormalImage, for: .normal) cameraOverlayView.commitButton.setImage(confirmDisableImage, for: .disabled) cameraOverlayView.flashButton.setImage(UIImage(named: imagePicker.cameraFlashMode.imageIconName(), in: Bundle(for: type(of: self)), compatibleWith: nil), for: .normal) cameraOverlayView.collectionView.dataSource = self cameraOverlayView.collectionView.delegate = self cameraOverlayView.frame = CGRect(x: 0, y: 0, width: SF.Const.screenWidth, height: SF.Const.screenHeight) imagePicker.cameraOverlayView = cameraOverlayView reloadCameraOverlayView() } private func reloadCameraOverlayView() { if images.count >= maxCount { if minCount != maxCount {cameraOverlayView.errorMsg = "最多只能拍摄\(maxCount)张"} else {cameraOverlayView.errorMsg = "已拍够\(maxCount)张"} } cameraOverlayView.takePictureControl.count = ((minCount == maxCount) ?(minCount - images.count) :0) cameraOverlayView.takePictureControl.canTouched = (images.count < maxCount) cameraOverlayView.collectionView.isHidden = (images.count == 0) cameraOverlayView.collectionView.reloadData() cameraOverlayView.commitButton.isEnabled = ((images.count >= minCount) ?(images.count <= maxCount) :false) } private func collectionViewSelectImage(index: Int) { cameraOverlayView.state = .preview cameraOverlayView.previewSelectIndex(index, images: images) } private func deleteImage(index: Int) { images.remove(at: index) cameraOverlayView.errorMsg = nil reloadCameraOverlayView() if images.count == 0 { cameraOverlayView.state = .camera return } if cameraOverlayView.state == .preview { let selectedIndex = min(index, images.count - 1) cameraOverlayView.previewSelectIndex(selectedIndex, images: images) cameraOverlayView.collectionView.selectItem(at: IndexPath(item: selectedIndex, section: 0), animated: true, scrollPosition: .right) } } private func addImpactFeedback() { if #available(iOS 10.0, *) { let impact = UIImpactFeedbackGenerator(style: .medium) impact.impactOccurred() } } @objc func closeButtonClicked() { delegate?.imagePickerControllerDidCancel(self) } @objc func deleteButtonClicked() { deleteImage(index: cameraOverlayView.selectedImageIndex) } @objc func helpButtonClicked() { delegate?.imagePickerControllerDidHelp(self) } @objc func flashButtonClicked() { let (flashMode, flashImageName) = imagePicker.cameraFlashMode.next() imagePicker.cameraFlashMode = flashMode cameraOverlayView.flashButton.setImage(UIImage(named: flashImageName, in: Bundle(for: type(of: self)), compatibleWith: nil), for: .normal) } @objc func deviceButtonClicked() { let cameraDevice = imagePicker.cameraDevice.next() imagePicker.cameraDevice = cameraDevice } @objc func takePictureControlClicked() { if cameraOverlayView.takePictureControl.pictureViewState == .camera { if images.count >= maxCount { return } addImpactFeedback() imagePicker.takePicture() return } cameraOverlayView.state = .camera guard let indexPath = cameraOverlayView.collectionView.indexPathsForSelectedItems?.first else { return } cameraOverlayView.collectionView.deselectItem(at: indexPath, animated: false) } @objc func commitButtonClicked() { if images.count < minCount { return } delegate?.imagePickerController(self, didFinishPickingImages: images) } } extension NXImagePickerController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { guard let originImage = info[.originalImage] as?UIImage, images.count < maxCount else { return } if picker.sourceType == .camera {UIImageWriteToSavedPhotosAlbum(originImage, nil, nil, nil)} guard let image = originImage.resizedImage(1500) else { return } images.append(image) reloadCameraOverlayView() cameraOverlayView.collectionView.scrollToItem(at: IndexPath(item: (images.count - 1), section: 0), at: .right, animated: true) } } extension NXImagePickerController: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SFCameraOverlayViewCellId", for: indexPath) as! NXCameraOverlayViewCell let image = images[indexPath.item] cell.selectedBackgroundView?.layer.borderColor = tintColor.cgColor cell.imgView.image = image cell.longPressAction = { [weak self] (longPress) in if self?.cameraOverlayView.state == .preview && longPress.state == .began { self?.collectionViewSelectImage(index: indexPath.item) collectionView.selectItem(at: indexPath, animated: false, scrollPosition: UICollectionView.ScrollPosition()) } guard let attri = collectionView.layoutAttributesForItem(at: indexPath) else { return } guard let point = self?.view.convert(attri.center, from: collectionView) else { return } self?.showDragabledImage(cell, index: indexPath.item, center: point, longPress: longPress) } return cell } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } } extension NXImagePickerController: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionViewSelectImage(index: indexPath.item) } } extension NXImagePickerController { private func showDragabledImage(_ cell: NXCameraOverlayViewCell, index: Int, center: CGPoint, longPress: UILongPressGestureRecognizer) { let point = longPress.location(in: self.view) var canDelete = false cameraOverlayView.deleteStateEnabled = (longPress.state == .began || longPress.state == .changed) cell.alpha = (longPress.state == .began || longPress.state == .changed) ?0.6 :1 if droppableImageView != nil && garbageContainerView != nil { canDelete = (droppableImageView!.centerY >= view.height - garbageContainerView!.height) } if longPress.state == .began { addImpactFeedback() if droppableImageView == nil { guard let image = cell.toImage() else {return} droppableImageView = NXCameraDroppableImageView(image: image, center: center) droppableImageView!.alpha = 0 view.addSubview(droppableImageView!) UIView.animate(withDuration: 0.3) { self.droppableImageView?.alpha = 0.8 } } if garbageContainerView == nil { garbageContainerView = NXCameraGarbageContainerView.showInView(view) if droppableImageView != nil { view.bringSubviewToFront(droppableImageView!) } } } else if longPress.state == .changed { if droppableImageView != nil { droppableImageView?.center = point garbageContainerView?.state = (canDelete ?.highlight :.normal) } } else { defer { garbageContainerView?.dismiss({ [weak self] in self?.garbageContainerView = nil }) } if droppableImageView == nil { return } if canDelete { deleteImage(index: index) self.droppableImageView?.removeFromSuperview() self.droppableImageView = nil return } UIView.animate(withDuration: 0.3, animations: { self.droppableImageView?.center = self.droppableImageView!.originCenter self.droppableImageView?.alpha = 0 }) { (finished) in if finished { self.droppableImageView?.removeFromSuperview() self.droppableImageView = nil } } } } } extension UIImage { func resizedImage(_ maxEdge: CGFloat) -> UIImage? { guard maxEdge > 0 else { return nil } var resizedImage: UIImage? = self if max(self.size.width, self.size.height) > maxEdge { let scale = maxEdge / max(self.size.width, self.size.height) let resizedRect = CGRect.init(x: 0, y: 0, width: self.size.width * scale, height: self.size.height * scale) UIGraphicsBeginImageContext(resizedRect.size) self.draw(in: resizedRect) resizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } return resizedImage } } <file_sep>// // BaseViewController.swift // appone // // Created by tangbo on 2019/6/22. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import NXDesign class BaseViewController: SFViewController { override func viewDidLoad() { super.viewDidLoad() sf_navigationBar.titleLabel.font = UIFont.boldSystemFont(ofSize: 19) sf_navigationBar.leftBarButton.setImage(UIImage(named: "nvabar_white_back"), for: .normal) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>// // ChooseUploadHandler.swift // NXDesign // // Created by DoubleHH on 2019/6/15. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation ///整套流程,选择一张图片(拍照or相册)之后上传,上传的配置参照 NXImageUploader 的 configuration public class ChooseUploadSingleImageHandler : NSObject { public typealias BeginToUploadCallback = (_ image: UIImage) -> Void ///上传完成回调 private var uploadCompletionCallback: NXImageUploaderCompletion ///开始上传回调 private var beginToUploadCallback: BeginToUploadCallback private var imageSourceHandler: ImageSourceHandler! /* 初始化方法,参数分别是开始上传和完成的回调,上传的URL等配置,请看 NXImageUploader default 的 configuration */ public init(beginCallback: @escaping BeginToUploadCallback, completionCallback: @escaping NXImageUploaderCompletion) { uploadCompletionCallback = completionCallback beginToUploadCallback = beginCallback super.init() self.imageSourceHandler = ImageSourceHandler(choosedImageCallback: { [weak self] (images) in guard let image = images.first else { return } self?.uploadImage(image: image) }, maxImageCount: 1) } /// 开始照片的选择(拍照or相册) public func beginToChoose() { imageSourceHandler.showSourceChoices() } } /// Upload extension ChooseUploadSingleImageHandler { private func uploadImage(image: UIImage) { beginToUploadCallback(image) guard let imgData = image.compressedDataForUpload() else { return NXToast.show(text: "请上传正确的图片")} let _ = NXImageUploader.upload(data: imgData, name: nil, progressBlock: nil, completion: uploadCompletionCallback) } } <file_sep>// // UIButtonExtensions.swift // BaseTest // // Created by DoubleHH on 2018/6/25. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit extension UIButton { public func setImageAndTitleSpace(space: CGFloat) { self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: space) self.titleEdgeInsets = UIEdgeInsets(top: 0, left: space, bottom: 0, right: 0) } } <file_sep>// // NXUploadableImageView.swift // NXDesign // // Created by tangbo on 2019/1/30. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit import SFFoundation public enum NXUploadableImageViewStyle { ///删除按钮在图片外部 case `default` ///删除按钮在图片内部 case one } ///图片上传过程中的状态 public enum NXUploadableImageViewState { ///等待上传 case waiting ///上传中 case uploading ///上传成功 case success ///上传失败 case fail ///取消上传 case cancel } @IBDesignable open class NXUploadableImageView: UIView { public private(set) var state: NXUploadableImageViewState = .waiting public private(set) var imageUrl: String? public private(set) var imgView = UIImageView() public var style: NXUploadableImageViewStyle = .default { didSet { deleteButton.setImage(deleteButtonImage, for: .normal) } } ///配置图片上传的网络参数,具体参见NXImageUploaderConfigration的介绍 public var configuration = NXImageUploader.default.configuration ///添加图片 public var selectImageBlock: (()->())? ///删除图片 public var deleteBlock: (()->())? ///展示图片 public var showImageBlock: ((UIImage?)->())? ///上传完成的回调,需要自己解析json数据,并把图片url返回 public var completionBlock: ((Data?)->(String?))? ///上传完成的回调,返回图片url public var exactCompletionBlock: ((String?)->())? private var deleteButtonImage: UIImage? { return (style == .default) ?UIImage(named: "icon_upload_delete_circle", in: Bundle(for: NXUploadableImageView.self), compatibleWith: nil) :UIImage(named: "icon_upload_delete_square", in: Bundle(for: NXUploadableImageView.self), compatibleWith: nil) } ///是否自己解析图片上传完成后的json数据 private var userCustomResult: Bool { return (completionBlock != nil) } private var progress: CGFloat = 0 private var uploadTask:URLSessionTask? private let deleteButton = UIButton(type: .custom) private let progressLabel = UILabel() private let retryLabel = UILabel() private let progressView = UIView() private let control = UIControl() public convenience init(type: NXUploadableImageViewStyle) { let width: CGFloat = (type == .default) ?70 :80 self.init(frame: CGRect(x: 0, y: 0, width: width, height: width)) self.style = type deleteButton.setImage(deleteButtonImage, for: .normal) } public override init(frame: CGRect) { super.init(frame: frame) configUI() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configUI() } public func upload(image: UIImage) { userCustomResult ? upload(image: image, completion: completionBlock) : exactUpload(image: image, completion: exactCompletionBlock) } /** 上传图片,上传完成后,此方法不会对返回的json数据做解析 * parameter image: 需要上传的图片,此方法会对图片做80%的比例压缩 * parameter completion: 图片上传完成的回调 */ func upload(image: UIImage, completion: ((Data?)->(String?))?) { self.imgView.image = image self.state = .uploading self.progressView.isHidden = false self.progressLabel.isHidden = false self.progressLabel.text = "0%" self.retryLabel.isHidden = true guard let imgData = image.compressedDataForUpload() else { return SFToast.show(withText: "请上传正确的图片")} let completionBlock: NXImageUploaderCompletion = { [weak self] (result, response, error) in self?.progress = 0 self?.progressView.isHidden = true self?.progressLabel.isHidden = true self?.imageUrl = completion?(result) if error == nil && self?.imageUrl != nil { self?.state = .success } else if (error as NSError?)?.code == NSURLErrorCancelled { self?.state = .cancel } else { self?.state = .fail self?.progressView.isHidden = false } self?.setNeedsLayout() self?.retryLabel.isHidden = (self?.state != .fail) } let progressBlock: NXImageUploaderProgress = { [weak self] (totalSent, totalExpectedToSend) in self?.state = .uploading self?.progressView.isHidden = false self?.progressLabel.isHidden = false self?.progress = totalSent / totalExpectedToSend self?.progressLabel.text = String(format: "%.0f%%", (self?.progress ?? 0) * 100) self?.setNeedsLayout() } uploadTask = NXImageUploader.upload(to: configuration.url, commonParameters: configuration.commonParameters, data: imgData, name: configuration.imageName, progressBlock: progressBlock, completion: completionBlock) } /** 上传图片,上传完成后,此方法会对返回的json数据解析为默认的ImageUploadResult * parameter image: 需要上传的图片,此方法会对图片做80%的比例压缩 * parameter completion: 图片上传完成的回调,此方法会对返回的json数据解析为默认的ImageUploadResult */ func exactUpload(image: UIImage, completion: ((String?)->())?) { let completionBlock: ((Data?)->(String?)) = { responseData in var imageUrl: String? = nil if let resultData = responseData { let result = try? SFJSONDecoder().decode(NXImageUploadResult.self, from: resultData) imageUrl = result?.data?.img_url } completion?(imageUrl) return imageUrl } upload(image: image, completion: completionBlock) } private func configUI() { control.addTarget(self, action: #selector(controlClicked), for: .touchUpInside) deleteButton.setImage(deleteButtonImage, for: .normal) deleteButton.addTarget(self, action: #selector(deleteClicked), for: .touchUpInside) imgView.contentMode = .scaleAspectFill imgView.layer.masksToBounds = true progressView.isHidden = true progressView.backgroundColor = UIColor.hex("#000000").withAlphaComponent(0.4) progressView.isUserInteractionEnabled = false retryLabel.isHidden = true retryLabel.text = "点击重试" retryLabel.numberOfLines = 0 retryLabel.textAlignment = .center retryLabel.textColor = UIColor.white retryLabel.font = UIFont.boldSystemFont(ofSize: 14) progressLabel.textColor = UIColor.white progressLabel.textAlignment = .center progressLabel.font = UIFont.boldSystemFont(ofSize: 14) progressLabel.isHidden = true addSubview(control) addSubview(imgView) addSubview(progressView) addSubview(retryLabel) addSubview(progressLabel) addSubview(deleteButton) } func showImage(image: UIImage) { let vc = NXImageBrowserController.loadFromStoryboard(images: [image]) if let nvc = viewController?.navigationController { nvc.pushViewController(vc, animated: true) return } viewController?.present(vc, animated: true, completion: nil) } @objc private func controlClicked() { guard let image = imgView.image else { return } if state == .fail { upload(image: image) return } if showImageBlock == nil { showImage(image: image) return } showImageBlock?(imgView.image) } @objc private func deleteClicked() { uploadTask?.cancel() removeFromSuperview() deleteBlock?() } open override func layoutSubviews() { super.layoutSubviews() control.frame = bounds let imgSize = (style == .default) ?CGSize(width: bounds.size.width - 10, height: bounds.size.height - 10) :bounds.size imgView.frame = CGRect(x: 0, y: 0, width: imgSize.width, height: imgSize.height) imgView.center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2) let deleteButtonSize = CGSize(width: 19, height: 19) deleteButton.frame = CGRect(x: bounds.size.width - deleteButtonSize.width, y: 0, width: deleteButtonSize.width, height: deleteButtonSize.height) retryLabel.frame = CGRect(x: 0, y: 0, width: 50, height: 60) retryLabel.center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2) progressLabel.frame = imgView.frame progressView.frame = imgView.frame let progressViewTop = imgView.frame.height * progress + imgView.frame.minX let progressViewHeight = imgView.frame.height * (1 - progress) progressView.frame = CGRect(x: imgView.frame.minX, y: progressViewTop, width: imgView.frame.width, height: progressViewHeight) } } <file_sep>// // NibLoadable.swift // SAASMerchant // // Created by Panda on 2018/6/26. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit public struct NibFileInfo { var name: String var bundle: Bundle = Bundle.main public init(name: String, bundle: Bundle = Bundle.main) { self.name = name self.bundle = bundle } } public protocol NibLoadable where Self: UIView { static var fileInfo: NibFileInfo { get } } extension NibLoadable { public static func loadFromNib() -> Self? { return fileInfo.bundle.loadNibNamed(fileInfo.name, owner: nil, options: nil)?.first as? Self } } extension UIView { open override func awakeAfter(using aDecoder: NSCoder) -> Any? { guard let view = super.awakeAfter(using: aDecoder) as? UIView & NibLoadable, view.subviews.count == 0 else { return super.awakeAfter(using: aDecoder) } let viewType = type(of: view) guard let realView = viewType.loadFromNib() else { return nil } realView.tag = view.tag realView.frame = frame realView.bounds = bounds realView.isHidden = isHidden realView.clipsToBounds = clipsToBounds realView.autoresizingMask = autoresizingMask realView.isUserInteractionEnabled = isUserInteractionEnabled realView.translatesAutoresizingMaskIntoConstraints = translatesAutoresizingMaskIntoConstraints for constraint in constraints { var optionalNewConstraint: NSLayoutConstraint? if constraint.secondItem == nil { optionalNewConstraint = NSLayoutConstraint(item: realView, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: nil, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant) } else if let fistItem = constraint.firstItem as? UIView, let secondItem = constraint.secondItem as? UIView, fistItem == secondItem { optionalNewConstraint = NSLayoutConstraint(item: realView, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: realView, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant) } guard let newConstraint = optionalNewConstraint else { continue } newConstraint.shouldBeArchived = constraint.shouldBeArchived newConstraint.priority = constraint.priority newConstraint.identifier = constraint.identifier realView.addConstraint(newConstraint) } return realView } } <file_sep>// // DataExtensions.swift // Knight // // Created by DoubleHH on 2018/2/7. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation extension Data { public func toDictionary() -> Dictionary<String, CustomStringConvertible>? { guard let obj = try? JSONSerialization.jsonObject(with: self, options: .mutableContainers), let jsonAny = obj as? [String: Any] else { return nil } return (jsonAny as? Dictionary<String, CustomStringConvertible>) } } <file_sep>// // NXAlertInputView.swift // NXDesign // // Created by tangbo on 2019/2/19. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit import SFFoundation public struct NXAlertInput { public enum Style { ///普通的输入框 case normal ///方形的,限定输入个数的,并且只能输入数字的输入框 case limit(Int) } ///输入框的样式 public var style = Style.normal ///输入框的默认提示内容 public var placeholder: String? ///输入框的委托 public weak var delegate: UITextFieldDelegate? ///输入框的return键的样式 public var returnKeyType: UIReturnKeyType = UIReturnKeyType.done ///输入框在输入内容时的回调 public var textChanged: ((NXAlertInputView)->())? public init(style: Style = .normal, placeholder: String? = nil, delegate:UITextFieldDelegate? = nil, returnKeyType: UIReturnKeyType = UIReturnKeyType.done, textChanged: ((NXAlertInputView)->())? = nil) { self.style = style self.placeholder = placeholder self.textChanged = textChanged self.delegate = delegate self.returnKeyType = returnKeyType } } public class NXAlertInputView: UIView { ///输入框下方需要显示的错误文案 public var errorMessage: String? { didSet { errmsgLabel.isHidden = IsCollectionEmpty(errorMessage) errmsgLabel.text = errorMessage (inputTextField as? UITextField)?.layer.borderColor = IsCollectionEmpty(errorMessage) ? UIColor.hex("#E6E6E6").cgColor : NXAlertView.tintColor.cgColor if !IsCollectionEmpty(errorMessage) { if #available(iOS 10.0, *) { let impact = UIImpactFeedbackGenerator(style: .heavy) impact.impactOccurred() } } } } ///输入框的内容 public var text: String? { if let normalTextField = inputTextField as? UITextField { return normalTextField.text } if let limitTextField = inputTextField as? NXAlertLimitInputView { return limitTextField.text } return nil } var input:NXAlertInput! var errmsgLabel = UILabel() var inputTextField: UIView? init(input: NXAlertInput) { self.input = input super.init(frame: .zero) configUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configUI() { errmsgLabel.textColor = NXAlertView.tintColor errmsgLabel.font = UIFont.systemFont(ofSize: 12) errmsgLabel.isHidden = true addSubview(errmsgLabel) inputTextField?.removeFromSuperview() inputTextField = nil switch input.style { case .normal:configNormalTextField() case let .limit(count):configLimitTextField(count: count) } } func configNormalTextField() { let textField = UITextField() textField.delegate = input.delegate ?? self textField.returnKeyType = input.returnKeyType textField.placeholder = input.placeholder textField.becomeFirstResponder() textField.clearButtonMode = .always textField.layer.borderColor = UIColor.hex("#E6E6E6").cgColor textField.layer.borderWidth = 1 textField.layer.cornerRadius = 2 textField.layer.masksToBounds = true textField.tintColor = NXAlertView.tintColor textField.addTarget(self, action: #selector(textFieldValueChanged(sender:)), for: .editingChanged) addSubview(textField) inputTextField = textField } func configLimitTextField(count: Int) { assert(count >= 3 && count <= 6, "the limit count must greater than or equal to 3, less than or equal to 6, but you set limit count is \(count)") let limitInputView = NXAlertLimitInputView(input: input) limitInputView.textFieldValueChanged = { [weak self] in guard let strongSelf = self else { return } strongSelf.input.textChanged?(strongSelf) } addSubview(limitInputView) inputTextField = limitInputView } @objc func textFieldValueChanged(sender: UITextField) { if IsCollectionEmpty(sender.text) { errorMessage = nil } input.textChanged?(self) } override public func layoutSubviews() { super.layoutSubviews() inputTextField?.frame = CGRect(x: 0, y: 0, width: frame.width, height: 40) errmsgLabel.frame = CGRect(x: 0, y: (inputTextField?.frame.maxY ?? 0) + 5, width: frame.width, height: 16) } } extension NXAlertInputView: UITextFieldDelegate { public func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } class NXAlertLimitInputView: UIView { private let itemSpace: (max: CGFloat, min: CGFloat) = (10, 3) private let itemSize = CGSize(width: 40, height: 40) private let hiddenTextField = UITextField() private var input: NXAlertInput! private var items = [UILabel]() private var limit: Int { switch input.style { case let .limit(count):return count default:return 1 } } var text: String? { return hiddenTextField.text } var textFieldValueChanged: (()->())? init(input: NXAlertInput) { self.input = input super.init(frame: .zero) configUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configUI() { hiddenTextField.delegate = input.delegate hiddenTextField.isHidden = true hiddenTextField.keyboardType = .numberPad hiddenTextField.addTarget(self, action: #selector(textFieldValueChanged(sender:)), for: .editingChanged) addSubview(hiddenTextField) hiddenTextField.becomeFirstResponder() for _ in 0..<limit { let label = UILabel() label.font = UIFont.systemFont(ofSize: 30) label.textColor = UIColor.hex("#333333") label.layer.borderColor = UIColor.hex("#E6E6E6").cgColor label.textAlignment = .center label.layer.borderWidth = 1 label.layer.cornerRadius = 2 label.layer.masksToBounds = true addSubview(label) items.append(label) } } @objc func textFieldValueChanged(sender: UITextField) { if (sender.text?.count ?? 0) > limit {sender.text = sender.text?.substring(to: limit)} guard let text = sender.text else { return } items.forEach{$0.text = nil} for (index, char) in text.enumerated() { if let item = items.at(index) { item.text = String(char) } else { break } } textFieldValueChanged?() } override func layoutSubviews() { super.layoutSubviews() let count = CGFloat(items.count) if count < 2 { return } var space = (frame.width - count * itemSize.width) / (count - 1) space = max(min(space, itemSpace.max), itemSpace.min) var padding = (frame.width - (count * itemSize.width + (count - 1) * space)) / 2 padding = max(0, padding) var lastItem: UIView? for item in items { let left = (lastItem != nil) ? ((lastItem?.frame.maxX ?? 0) + space) : padding item.frame = CGRect(x: left, y: 0, width: itemSize.width, height: itemSize.height) lastItem = item } } } <file_sep>// // SFCameraTakePictureView.swift // SFImageKit // // Created by tangbo on 2018/10/29. // Copyright © 2018 S.F.Express. All rights reserved. // import UIKit import SFFoundation enum NXCameraTakePictureViewState { case camera case picture } class NXCameraTakePictureView: UIControl { let backgroundView = UIView() let contentView = UIView() let countLabel = UILabel.label(font: UIFont.systemFont(ofSize: 24), color: UIColor.hex("#50B722")) let pictureTitleLabel = UILabel.label(font: UIFont.systemFont(ofSize: 16), color: UIColor.white) var originCenter: CGPoint! var pictureViewState: NXCameraTakePictureViewState = .camera { didSet { reloadSubViewsFrame(state: pictureViewState) if pictureViewState == .picture { isEnabled = true } else { contentView.alpha = canTouched ?1 :0.3 isEnabled = canTouched } } } var count: Int = 0 { didSet { countLabel.isHidden = true if count > 0 { countLabel.text = "\(count)" countLabel.isHidden = !(pictureViewState == .camera) countLabel.sizeToFit() countLabel.centerX = contentView.centerX countLabel.centerY = contentView.centerY } } } var canTouched: Bool = true { didSet { contentView.alpha = canTouched ?1 :0.6 isEnabled = canTouched } } override init(frame: CGRect) { super.init(frame: CGRect(x: 0, y: 0, width: 70, height: 70)) configUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configUI() } override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { UIView.animate(withDuration: 0.1) { self.contentView.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) self.countLabel.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) } return super.beginTracking(touch, with: event) } override func endTracking(_ touch: UITouch?, with event: UIEvent?) { UIView.animate(withDuration: 0.1) { self.contentView.transform = .identity self.countLabel.transform = .identity } } func configUI() { size = CGSize(width: 70, height: 70) backgroundView.backgroundColor = UIColor.white backgroundView.alpha = 0.4 backgroundView.isUserInteractionEnabled = false addSubview(backgroundView) contentView.backgroundColor = UIColor.white contentView.isUserInteractionEnabled = false addSubview(contentView) pictureTitleLabel.text = "继续拍照" addSubview(pictureTitleLabel) countLabel.isHidden = true addSubview(countLabel) reloadSubViewsFrame(state: .camera) } func reloadSubViewsFrame(state: NXCameraTakePictureViewState) { var backgroundViewSize = CGSize(width: 70, height: 70) let contentViewSize = CGSize(width: 55, height: 55) var selfSize = CGSize(width: 70, height: 70) var backgroundViewAlpha: CGFloat = 0.4 switch state { case .camera: contentView.isHidden = false pictureTitleLabel.isHidden = true countLabel.isHidden = !(count > 0) case .picture: contentView.isHidden = true pictureTitleLabel.isHidden = false countLabel.isHidden = true backgroundViewSize = CGSize(width: 100, height: 40) selfSize = CGSize(width: 100, height: 40) backgroundViewAlpha = 0.2 } UIView.animate(withDuration: 0.3) { self.size = selfSize self.backgroundView.size = backgroundViewSize self.backgroundView.alpha = backgroundViewAlpha self.backgroundView.layer.cornerRadius = self.backgroundView.height / 2 self.backgroundView.layer.masksToBounds = true if self.originCenter != nil {self.center = self.originCenter} self.backgroundView.centerX = self.width / 2 self.backgroundView.centerY = self.height / 2 self.contentView.size = contentViewSize self.contentView.centerX = self.width / 2 self.contentView.centerY = self.height / 2 self.contentView.layer.cornerRadius = self.contentView.height / 2 self.contentView.layer.masksToBounds = true self.pictureTitleLabel.sizeToFit() self.pictureTitleLabel.centerX = self.backgroundView.centerX self.pictureTitleLabel.centerY = self.backgroundView.centerY self.countLabel.sizeToFit() self.countLabel.centerX = self.contentView.centerX self.countLabel.centerY = self.contentView.centerY } } } <file_sep>// // ArrayExtensions.swift // Buyer // // Created by DoubleHH on 2018/5/10. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation extension Array { public func at(_ index: Int) -> Element? { guard index >= 0, index < self.count else { return nil } return self[index]; } } <file_sep>// // NXImageUploader.swift // NXDesign // // Created by tangbo on 2019/1/30. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation import SFFoundation ///上传中的block public typealias NXImageUploaderProgress = ((CGFloat, CGFloat)->()) ///上传完成的block public typealias NXImageUploaderCompletion = ((Data?, URLResponse?, Error?)->()) ///上传完成的block,第一个参数返回json解析后的ImageUploadResult public typealias NXImageUploaderExactlyCompletion = ((NXImageUploadResult?, URLResponse?, Error?)->()) extension URLSessionTask { private static let progressBlockKey = UnsafeRawPointer(bitPattern: "nx_progressBlockKey".hashValue)! var nx_progressBlock: NXImageUploaderProgress? { get { return objc_getAssociatedObject(self, URLSessionTask.progressBlockKey) as? NXImageUploaderProgress } set { objc_setAssociatedObject(self, URLSessionTask.progressBlockKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } ///图片上传完成后,默认的json model public struct NXImageUploadResult: Decodable { struct UploadImageResultData: Decodable { ///图片的url var img_url: String? } var errno: Int? var errmsg: String? var data: UploadImageResultData? } public class NXImageUploader { public static let `default` = NXImageUploader() ///图片上传的网络参数,具体参见NXImageUploaderConfigration的介绍 public var configuration = NXImageUploaderConfigration() private var session: URLSession! private init() { session = URLSession(configuration: URLSessionConfiguration.default, delegate: ImageUploaderProxy.default, delegateQueue: OperationQueue.main) } /** 上传图片,上传完成后,此方法会对返回的json数据解析为默认的ImageUploadResult * parameter url: 上传图片的url地址 * parameter commonParameters:上传图片服务的公共参数,例如机型,经纬度等信息 * parameter data: 图片的二进制数据,建议上传之前做一次压缩处理 * parameter name: 上传图片的name,默认为"img" * parameter progressBlock: 图片上传过程中的回调 * parameter completion: 图片上传完成的回调,此方法会对返回的json数据解析为默认的ImageUploadResult */ public static func exactUpload(to url: URL? = nil, commonParameters: Dictionary<String, CustomStringConvertible>? = nil, data: Data, name: String? = "img", progressBlock: NXImageUploaderProgress?, completion: NXImageUploaderExactlyCompletion?) -> URLSessionTask? { return upload(to: url, commonParameters: commonParameters, data: data, name: name, progressBlock: progressBlock){ (responseData, respose, error) in var result:NXImageUploadResult? if let resultData = responseData { result = try? SFJSONDecoder().decode(NXImageUploadResult.self, from: resultData) } completion?(result, respose, error) } } /** 上传图片,上传完成后,此方法不会对返回的json数据做解析 * parameter url: 上传图片的url地址 * parameter commonParameters:上传图片服务的公共参数,例如机型,经纬度等信息 * parameter data: 图片的二进制数据,建议上传之前做一次压缩处理 * parameter name: 上传图片的name,默认为"img" * parameter progressBlock: 图片上传过程中的回调 * parameter completion: 图片上传完成的回调 */ public static func upload(to url: URL? = nil, commonParameters: Dictionary<String, CustomStringConvertible>? = nil, data: Data, name: String?, progressBlock: NXImageUploaderProgress?, completion: NXImageUploaderCompletion?) -> URLSessionTask? { guard let uploadUrl = url ?? NXImageUploader.default.configuration.url else { return nil } let parameters = commonParameters ?? NXImageUploader.default.configuration.commonParameters let imageName = name ?? NXImageUploader.default.configuration.imageName var request = URLRequest.init(url: uploadUrl, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 18) request.httpMethod = "POST" var formDataArray = parameters?.map { (arg) -> RequestFormData in return RequestFormData.KeyValue(name: arg.key, value: arg.value as? String ?? "") } ?? [RequestFormData]() formDataArray.append(RequestFormData.FormData(name: imageName, fileName: "img.jpeg", contentType: "image/jpeg", data: data)) let boundary = "D3JKIOU8743NMNFQWERTYUIO12345678BNM" let requestData = formDataArray.mutipartFormData(boundary) request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") request.setValue(String(requestData.count), forHTTPHeaderField: "Content-Length") let uploadtask = NXImageUploader.default.session.uploadTask(with: request, from: requestData) { (responseData, response, error) in completion?(responseData, response, error) } uploadtask.nx_progressBlock = progressBlock uploadtask.resume() return uploadtask } } class ImageUploaderProxy: NSObject, URLSessionTaskDelegate { static let `default` = ImageUploaderProxy() func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { task.nx_progressBlock?(CGFloat(totalBytesSent), CGFloat(totalBytesExpectedToSend)) } } <file_sep>// // ImageSourceHandler.swift // NXDesign // // Created by DoubleHH on 2019/6/15. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation /// 选择照片,从相册or拍照,or 可选择的 public class ImageSourceHandler : NSObject { public typealias ChoosedImageCallback = (_ images: [UIImage]) -> Void ///得到一张照片后的回调 public var choosedImageCallback: ChoosedImageCallback ///最多照片数 public var maxImageCount: Int = 1 /* 初始化方法 param choosedImageCallback:ChoosedImageCallback param maxImageCount: Int */ public init(choosedImageCallback: @escaping ChoosedImageCallback, maxImageCount: Int = 1) { self.choosedImageCallback = choosedImageCallback self.maxImageCount = maxImageCount super.init() } /// 弹出可选的actionSheet,相册or拍照 public func showSourceChoices() { SFAlertSheetView.show(withChoices: ["拍照", "相册"]) { (alertView, choosedIndex) in if choosedIndex == -1 { return } choosedIndex == 0 ? self.showCameraImagePicker(): self.showImagePickerPhotoLibrary() } } /// 直接拍照 public func showCameraImagePicker() { let vc = NXImagePickerController.loadFromStoryboard() vc.delegate = self vc.maxCount = maxImageCount presentViewController()?.present(vc, animated: true, completion: nil) } /// 直接图片库选择 public func showImagePickerPhotoLibrary() { guard Authority.checkOpenAndToastErrorIfCameraUnavailable() else { return } let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .photoLibrary DispatchQueue.main.async { [weak self] in self?.presentViewController()?.present(picker, animated: true, completion: nil) } } private func presentViewController() -> UIViewController? { guard let vc = UIApplication.shared.delegate?.window??.rootViewController else { return nil} return vc } } extension ImageSourceHandler: NXImagePickerControllerDelegate { public func imagePickerControllerDidCancel(_ picker: NXImagePickerController) { picker.dismiss(animated: true, completion: nil) } public func imagePickerController(_ picker: NXImagePickerController, didFinishPickingImages images: [UIImage]) { picker.dismiss(animated: true, completion: nil) choosedImageCallback(images) } } extension ImageSourceHandler: UIImagePickerControllerDelegate, UINavigationControllerDelegate { public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { guard let originalImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return } picker.dismiss(animated: true, completion: nil) choosedImageCallback([originalImage]) } } <file_sep>// // Print.swift // Buyer // // Created by DoubleHH on 2018/5/14. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation public func dprint(_ items: Any...) { #if DEBUG for item in items { print(item) } #endif } <file_sep>// // AppUpgrader.swift // appone // // Created by tangbo on 2019/6/22. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import UIKit import NXDesign import SFFoundation private let kSFAppUpgraderAleatIdKey = "kSFAppUpgraderAleatIdKey" class XNAppUpgrader { static let instance = XNAppUpgrader() init() { NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) } @objc private func applicationDidBecomeActive() { guard let model = ConfigModel.loadFromDisk() else { return } checkShowAlertView(model: model) } func upgraderIfNeed() {} private func checkShowAlertView(model: ConfigModel) { if let serverVer = model.new_version { if let dic = Bundle.main.infoDictionary, let ver = dic["CFBundleShortVersionString"] as? String { if ver.compare(serverVer, options: .numeric, range: nil, locale: nil) == ComparisonResult.orderedAscending { showAlert(model: model) } } } } private func showAlert(model: ConfigModel) { NXAlertView.visibleAlertView(withIdentifier: kSFAppUpgraderAleatIdKey)?.dismiss() let okAction = NXAlertAction(okTitle: "去下载", style: .custom(Color_Main)) { self.download(model: model) } NXAlertView().title(ToStr(model.title)).message(ToStr(model.content)).action(okAction).identifier(kSFAppUpgraderAleatIdKey).show() } func download(model: ConfigModel) { if let appid = model.appstoreid, appid.count > 0 { let urlstr = "https://itunes.apple.com/cn/app/id\(appid)?mt=8" if let url = URL.init(string: urlstr) { UIApplication.shared.open(url) { (finished) in } } } } } <file_sep>// // NXAlertable.swift // NXDesign // // Created by tangbo on 2019/2/22. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation /** 任何UIView的子类实现此协议,即可作为弹窗的形式展示在页面上 */ public protocol NXAlertable { /** 在调用show方法之前的校验 * returns: 是否要展示在页面上 */ func shouldShow() -> Bool /** 作为弹窗展示在页面上 * parameter inView: 要展示在哪个页面上 */ func show(_ inView: UIView?) /** 在调用dismiss方法之前执行 */ func willDismiss() /** 使当前弹窗消失 */ func dismiss() } public extension NXAlertable where Self : UIView { func shouldShow() -> Bool { return true } func willDismiss() {} func show(_ inView: UIView? = nil) { if !shouldShow() { return } var targetView = inView if targetView == nil { guard case let window?? = UIApplication.shared.delegate?.window else { return } targetView = window } if let _ = targetView?.subviews.first(where: {$0 is NXAlertContentView}) { return } let alertView = NXAlertContentView(frame: targetView?.bounds ?? .zero, contentView: self) targetView?.addSubview(alertView) } func dismiss() { willDismiss() superview?.removeFromSuperview() } } class NXAlertContentView: UIView { let backgroundView = UIView() var contentView: UIView! var keyboardFrame: CGRect? init(frame: CGRect, contentView: UIView) { self.contentView = contentView super.init(frame: frame) configUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configUI() { NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillChangeFrame(notification:)), name:UIResponder.keyboardWillChangeFrameNotification, object: nil) backgroundView.backgroundColor = UIColor.hex("#000000").withAlphaComponent(0.5) addSubview(backgroundView) addSubview(contentView) backgroundView.frame = bounds contentView.center = CGPoint(x: frame.midX, y: frame.height * 0.44) } @objc func keyboardWillChangeFrame(notification: NSNotification) { if let endframe = notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as? CGRect { contentView.center = CGPoint(x: contentView.center.x, y: endframe.origin.y * 0.44) } } deinit { NotificationCenter.default.removeObserver(self) } } <file_sep>// // SFMaro.h // // Copyright (c) 2017年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // #ifndef SF_PrivateMacro_h #define SF_PrivateMacro_h /*********************************************************************************************************/ #pragma mark - Log开关 #ifndef DEBUG #define NSLog(...) #endif /// 1像素线宽 #define LINE_HEIGHT (1.0 / [UIScreen mainScreen].scale) /*********************************************************************************************************/ #pragma mark - 版本 /// System Version #define SYSTEM_VERSION [[[UIDevice currentDevice] systemVersion] doubleValue] #define SYSTEM_VERSION_ABOVE(v) (SYSTEM_VERSION >= (v)) /*********************************************************************************************************/ #pragma mark - 常用方法 /// Value(nil, string, notString) -> String #define ToSTR(s) ((!s || ![s isKindOfClass:[NSString class]])? @"": s) #define STR(s) ((!s || ![s isKindOfClass:[NSString class]])? nil: s) #define Dictionary(_dict) ([(_dict) isKindOfClass:[NSDictionary class]] ? (_dict): nil) /// Net Reachable #define IsNetReachable ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable ? YES : NO) /// Document Path #define DocumentFilePath(_path) [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:(_path)] /// 浮点型与零的比较 #define FloatGreaterThanZero(__floatValue) ((__floatValue) > 0.000001) #define FloatEqualZero(__floatValue) (fabs(__floatValue) < 0.000001) /*********************************************************************************************************/ /// 强弱引用转换,用于解代码块(block)与强引用对象之间的循环引用 #ifndef weakify #if __has_feature(objc_arc) #define weakify(object) __weak __typeof__(object) weak##object = object; #else #define weakify(object) __block __typeof__(object) block##object = object; #endif #endif #ifndef strongify #if __has_feature(objc_arc) #define strongify(object) __typeof__(object) object = weak##object; #else #define strongify(object) __typeof__(object) object = block##object; #endif #endif #endif <file_sep>// // SFCameraGarbageContainerView.swift // SFImageKit // // Created by tangbo on 2018/10/26. // Copyright © 2018 S.F.Express. All rights reserved. // import UIKit import SFFoundation enum NXCameraGarbageContainerViewState { case normal case highlight } class NXCameraGarbageContainerView: UIView { let iconImageView = UIImageView() let titleLabel = UILabel.label(font: UIFont.systemFont(ofSize: 16), color: UIColor.white) var state: NXCameraGarbageContainerViewState { set { titleLabel.text = ((newValue == .normal) ?"拖动到此删除" :"松手即可删除") let imageName = ((newValue == .normal) ?"sfimagekit_icon_camera_delete" :"sfimagekit_icon_camera_delete_open") iconImageView.image = UIImage(named: imageName, in: Bundle(for: type(of: self)), compatibleWith: nil) backgroundColor = ((newValue == .normal) ?UIColor.hex("#B81111") :UIColor.hex("#F51616")) setNeedsLayout() } get { return .normal } } class func showInView(_ inView: UIView) -> NXCameraGarbageContainerView { let view = NXCameraGarbageContainerView(frame: CGRect(x: 0, y: SF.Const.screenHeight, width: SF.Const.screenWidth, height: 60 + SF.Const.screenSafeBottom)) inView.addSubview(view) UIView.animate(withDuration: 0.3) { view.top = SF.Const.screenHeight - view.height } return view } func dismiss(_ completion: (()->())?) { UIView.animate(withDuration: 0.3, animations: { self.top = SF.Const.screenHeight }) { (finished) in if finished { completion?() self.removeFromSuperview() } } } override init(frame: CGRect) { super.init(frame: frame) addSubview(iconImageView) addSubview(titleLabel) backgroundColor = UIColor.hex("#B81111") self.state = .normal } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() iconImageView.size = CGSize(width: 24, height: 24) iconImageView.centerY = height / 2 titleLabel.size = CGSize() titleLabel.sizeToFit() titleLabel.centerY = height / 2 let margin: CGFloat = 10 iconImageView.left = (width - iconImageView.width - titleLabel.width - margin) / 2 titleLabel.left = iconImageView.right + margin } } <file_sep>// // ShopCartViewController.swift // appone // // Created by tangbo on 2019/6/22. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import NXDesign import SFFoundation class OrderListViewController: BaseViewController, StoryboardLoadable { static var fileInfo = StoryboardFileInfo(name: "tabbar", identifier: "orderList") @IBOutlet weak var tableView: UITableView! var orders: [OrderModel]? override func viewDidLoad() { super.viewDidLoad() sf_navigationBar.title = "我的订单" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) requestData() } func requestData() { if Account.isLogin == false { SFErrorView.show(with: .netError, in: view, title: "请登录", icon: nil, button: "去登录") { Account.loginIfNeed { (success) in self.requestData() } } return } SFLoadingIndicatorView.showLoadingIndicator(for: view, with: .contentBlack)?.backgroundColor = UIColor.white SFErrorView.removeErrorView(in: view) XNAppInfoUpload.queryOrderList { (orderList, success) in SFLoadingIndicatorView.dismissLoadingIndicator(for: self.view) if success { if IsCollectionEmpty(orderList) { SFErrorView.show(with: .noData, in: self.view) } self.orders = orderList self.tableView.reloadData() } else { SFToast.show(withText: ErrorMessage_default) } } } } extension OrderListViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return orders?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "orderCellId", for: indexPath) as! OrderCell cell.model = orders?[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = OrderDetailViewController.loadFromNib()! vc.order = orders?[indexPath.row] navigationController?.pushViewController(vc, animated: true) } } class OrderCell: UITableViewCell { @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var numberLabel: UILabel! @IBOutlet weak var foodView: UIView! @IBOutlet weak var descLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() statusLabel.textColor = Color_Main } var model: OrderModel? { didSet { if model?.takeout == true { numberLabel.text = "订单号:\(model?.orderId ?? "")" } else { numberLabel.text = "您的桌号为\(model?.number ?? "")" } statusLabel.text = model?.status?.description descLabel.text = "共\(model?.foods?.count ?? 0)样菜品 合计¥\(model?.totalPrice ?? "")" configFood() } } func configFood() { foodView.removeAllSubviews() guard let foodList = model?.foods else { return } var lastItemView: UIView? for food in foodList { let itemView = FoodView.loadFromNib()! foodView.addSubview(itemView) itemView.translatesAutoresizingMaskIntoConstraints = false itemView.foodModel = food itemView.leadingAnchor.constraint(equalTo: foodView.leadingAnchor).isActive = true if lastItemView != nil { itemView.topAnchor.constraint(equalTo: lastItemView!.bottomAnchor).isActive = true } else { itemView.topAnchor.constraint(equalTo: foodView.topAnchor).isActive = true } itemView.trailingAnchor.constraint(equalTo: foodView.trailingAnchor).isActive = true itemView.heightAnchor.constraint(equalToConstant: 70).isActive = true lastItemView = itemView } if lastItemView != nil { foodView?.bottomAnchor.constraint(equalTo: lastItemView!.bottomAnchor, constant: 20).isActive = true } } } <file_sep>// // NXImageUploaderConfigration.swift // NXDesign // // Created by tangbo on 2019/1/31. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation ////图片上传所需要配置的网络参数 public struct NXImageUploaderConfigration { public init() {} public init(url: URL?, commonParameters: Dictionary<String, CustomStringConvertible>? = nil, imageName: String = "img") { self.init() self.url = url self.commonParameters = commonParameters self.imageName = imageName } ///图片上传的url地址 public var url: URL? ///上传图片服务的公共参数,例如机型,经纬度等信息 public var commonParameters: Dictionary<String, CustomStringConvertible>? ///上传图片的name,默认为"img" public var imageName = "img" } <file_sep>// // ConfigTask.swift // appone // // Created by tangbo on 2019/6/22. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import SFFoundation struct ConfigModel: Codable, SFCacheable { static var cacheFileName = "ConfigModel" ///最新版本号 var new_version: String? ///webView地址 var web_url: String? ///是否展示webView var show_web: Bool? ///是否强制更新 var upgrade: Bool? var title: String? var content: String? var appstoreid: String? } <file_sep>// // ImageBrowserTransitionAnimation.swift // NXDesign // // Created by tangbo on 2019/2/2. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit enum TransitionAnimationType { case push case pop } class ImageBrowserTransitionAnimation: NSObject, UIViewControllerAnimatedTransitioning { var animationType = TransitionAnimationType.push var tempImageView: UIView? var tempImageOriginFrame: CGRect? func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) guard let broswer = fromViewController as? NXImageBrowserController, let imgView = broswer.showingImageView else { return } guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else { return } guard let tempView = imgView.snapshotView(afterScreenUpdates: false) else { return } let containerView = transitionContext.containerView tempView.frame = imgView.convert(imgView.bounds, to: containerView) containerView.addSubview(toView) let bgView = UIView() bgView.frame = broswer.view.bounds bgView.backgroundColor = UIColor.black containerView.addSubview(bgView) containerView.addSubview(tempView) self.tempImageView = tempView self.tempImageOriginFrame = tempView.frame UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { bgView.alpha = 0 }) { (finished) in if finished { transitionContext.completeTransition(!transitionContext.transitionWasCancelled) tempView.removeFromSuperview() bgView.removeFromSuperview() } } } } <file_sep>// // NXToast.swift // NXDesign // // Created by Leo on 2019/2/18. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation private var kContentKey = UnsafeRawPointer(bitPattern: "kContentKey".hashValue)! private let kContentWidth: CGFloat = 155 private let kDuration: (single: Double, double: Double) = (2, 3) private let kImageWidth: CGFloat = 40 public enum NXToastType { /// 纯文字 case normal /// 成功,对号 case success /// 警告,叹号 case warning /// 失败,叉号 case failure /// 自定义图片 case custom(UIImage?) func image() -> UIImage? { switch self { case .normal: return nil case .success: return UIImage(named: "toast_icon_success", in: Bundle(for: NXToast.self), compatibleWith: nil) case .warning: return UIImage(named: "toast_icon_alert", in: Bundle(for: NXToast.self), compatibleWith: nil) case .failure: return UIImage(named: "toast_icon_failed", in: Bundle(for: NXToast.self), compatibleWith: nil) case .custom(let image): return image } } func maxHeight(singleLine: Bool) -> CGFloat { switch self { case .normal: return singleLine ? 60 : 80 case .success, .warning, .failure, .custom: return singleLine ? 115 : 125 } } } public class NXToast { private static var contentView: UIView? { set { objc_setAssociatedObject(UIApplication.shared.delegate!.window!!, &kContentKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { return objc_getAssociatedObject(UIApplication.shared.delegate!.window!!, &kContentKey) as? UIView } } private static var semaphore = 0 private typealias NXToastLabelInfo = (label: UILabel, lines: Int) private init() {} public static func show(text: String, type: NXToastType = .normal) { if text.count <= 0 { return } configureUI(text, type) } private static func configureUI(_ text: String, _ type: NXToastType) { semaphore += 1 if contentView == nil { contentView = UIView() contentView!.backgroundColor = UIColor.hex(0x333333) contentView!.layer.cornerRadius = 5 contentView!.layer.masksToBounds = true contentView!.frame.size.width = kContentWidth UIApplication.shared.delegate!.window!!.addSubview(contentView!) } else { contentView!.subviews.forEach { $0.removeFromSuperview() } } guard let image = type.image() else { configureNormalType(text, type) return } configureImageType(text, image, type) } private static func configureNormalType(_ text: String, _ type: NXToastType) { let labelInfo = creatLabel(text) let label = labelInfo.label contentView!.frame.size.height = min(label.frame.size.height + 40, type.maxHeight(singleLine: labelInfo.lines == 1)) let contentViewWidth = contentView!.frame.size.width let contentViewHeight = contentView!.frame.size.height label.center = CGPoint(x: contentViewWidth / 2, y: contentViewHeight / 2) contentView!.frame.origin.x = (UIScreen.main.bounds.width - contentViewWidth) / 2 contentView!.frame.origin.y = UIScreen.main.bounds.height * 0.44 - contentViewHeight / 2 dismiss(labelInfo.lines == 1 ? kDuration.single : kDuration.double) } private static func configureImageType(_ text: String, _ image: UIImage, _ type: NXToastType) { let imageView = UIImageView(image: image) imageView.frame.size = CGSize(width: kImageWidth, height: kImageWidth) imageView.frame.origin.x = (contentView!.frame.size.width - imageView.frame.size.width) / 2 imageView.frame.origin.y = 15 contentView!.addSubview(imageView) let labelInfo = creatLabel(text) let label = labelInfo.label label.frame.origin.x = (contentView!.frame.size.width - label.frame.size.width) / 2 label.frame.origin.y = imageView.frame.size.height + imageView.frame.origin.y + 10 contentView!.frame.size.height = min(label.frame.size.height + label.frame.origin.y + 20, type.maxHeight(singleLine: labelInfo.lines == 1)) contentView!.frame.origin.x = (UIScreen.main.bounds.width - contentView!.frame.size.width) / 2 contentView!.frame.origin.y = UIScreen.main.bounds.height * 0.44 - contentView!.frame.size.height / 2 dismiss(labelInfo.lines == 1 ? kDuration.single : kDuration.double) } private static func creatLabel(_ text: String) -> NXToastLabelInfo { let label = UILabel() label.font = UIFont.systemFont(ofSize: 14) label.textColor = UIColor.white label.numberOfLines = 2 label.lineBreakMode = .byWordWrapping label.textAlignment = .center label.text = text label.frame.size.width = kContentWidth - 20 label.sizeToFit() let lineNum = lroundf(Float(label.frame.size.height / UIFont.systemFont(ofSize: 14).lineHeight)) contentView?.addSubview(label) return (label, lineNum) } private static func dismiss(_ duration: Double) { DispatchQueue.main.asyncAfter(deadline: .now() + duration) { UIView.animate(withDuration: 0.1, animations: { semaphore -= 1 if semaphore > 0 { return } contentView?.alpha = 0 }, completion: { (finish) in if semaphore > 0 { return } contentView?.removeFromSuperview() contentView = nil }) } } } <file_sep>// // URLRequest.swift // // Created by DoubleHH on 2018/1/14. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation public protocol RequestProtocol { func urlRequest() -> URLRequest?; } public protocol RequestSendable { mutating func sendSync(completionHandler:(Data?, URLResponse?, Error?) -> Swift.Void) } public struct Request { public var url: String public var getParameters: Dictionary<String, CustomStringConvertible>? public var postParameters: Dictionary<String, CustomStringConvertible>? public var headers: Dictionary<String, CustomStringConvertible>? public var httpBody: String? public var contentType: String? public var httpMethod: String? public var mutiParts: Array<RequestFormData>? public var sessionTask: URLSessionTask? public init(url: String) { self.url = url } private func wholeURL() -> URL? { return URL(string: url.URLString(urlParams: getParameters)) } } extension Request: RequestProtocol { public func urlRequest() -> URLRequest? { guard let url = wholeURL() else { return nil } var request = URLRequest(url: url) request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData request.timeoutInterval = 18 request.allHTTPHeaderFields = self.headers?.mapValues({ $0.description }) var method = "post" if !IsCollectionEmpty(postParameters) || !IsCollectionEmpty(httpBody) || !IsCollectionEmpty(mutiParts) { method = "post" } else { method = httpMethod ?? "get" } request.httpMethod = method if !IsCollectionEmpty(mutiParts) { // multipart/form-data let boundary = "D3JKIOU8743NMNFQWERTYUIO12345678BNM" let requestData = mutiParts!.mutipartFormData(boundary) request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") request.setValue(String(requestData.count), forHTTPHeaderField: "Content-Length") request.httpBody = requestData } else if (!IsCollectionEmpty(postParameters)) { // application/x-www-form-urlencoded request.httpBody = CombinedURLString(params: postParameters).data(using: String.Encoding.utf8) } else if !IsCollectionEmpty(httpBody) { // custom http body request.httpBody = httpBody?.data(using: String.Encoding.utf8) if !IsCollectionEmpty(contentType) { request.setValue(contentType, forHTTPHeaderField: "Content-Type") } } return request } } extension Request: RequestSendable { public mutating func sendSync(completionHandler:(Data?, URLResponse?, Error?) -> Swift.Void) { guard let urlRequest: URLRequest = self.urlRequest() else { completionHandler(nil, nil, nil) return } let semaphore: DispatchSemaphore = DispatchSemaphore(value: 0) var data: Data? = nil var response: URLResponse? = nil var error: Error? = nil let task: URLSessionTask = URLSession.shared.dataTask(with: urlRequest) { (aData, aResponse, aError) in data = aData response = aResponse error = aError semaphore.signal() } task.resume() self.sessionTask = task let _ = semaphore.wait(timeout: DispatchTime.distantFuture) completionHandler(data, response, error) } } <file_sep>// // URLRequestTask.swift // // // Created by PanDedong on 2018/6/17. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation public struct URLRequestTaskParameters { public var url: String public var getParameters: Dictionary<String, CustomStringConvertible>? public var postParameters: Dictionary<String, CustomStringConvertible>? public init(url: String, getParameters: Dictionary<String, CustomStringConvertible>?, postParameters: Dictionary<String, CustomStringConvertible>?) { self.url = url self.getParameters = getParameters self.postParameters = postParameters } } public struct URLRequestTaskResult { public var data: Data? public var URLResponse: HTTPURLResponse? public var error: Error? } public struct URLRequestTaskError: TaskError { public var code: Int public var description: String public var userInfo: Dictionary<AnyHashable, Any>? public init(code: Int, description: String, userInfo: Dictionary<AnyHashable, Any>?) { self.code = code self.description = description self.userInfo = userInfo } } public class URLRequestTask: Task<URLRequestTaskParameters, URLRequestTaskResult, URLRequestTaskError> { var request: Request? required init(_ parameters: URLRequestTaskParameters) { super.init(parameters) request = Request.init(url: self.parameters.url) request?.getParameters = self.parameters.getParameters request?.postParameters = self.parameters.postParameters } override public func main() throws { request?.sendSync(completionHandler: { (data, urlResponse, error) in self.result = URLRequestTaskResult.init(data: data, URLResponse: urlResponse as? HTTPURLResponse, error: error) }) #if DEBUG print(""" ====================RequestTask==================== url:\(String(describing: request?.url ?? ""))\n getParameters:\(String(describing: request?.getParameters ?? [:]))\n postParameters:\(String(describing: request?.postParameters ?? [:]))\n --------------------- error:\(String(describing: self.result?.error))\n urlResponse:\(String(describing: self.result?.URLResponse))\n data:\(String(describing: try? JSONSerialization.jsonObject(with: self.result?.data ?? Data(), options: [])))\n =================================================== """) #endif if let resultError = self.result?.error { let urlError = resultError as? URLError let code = (urlError != nil) ? urlError!.errorCode: -1 let userInfo = (urlError != nil) ? urlError!.errorUserInfo: nil throw URLRequestTaskError(code: code, description: "网络请求失败", userInfo: userInfo) } } override public func wantCancel() { super.wantCancel() request?.sessionTask?.cancel() } } <file_sep>// // SFAutoVisibleTextField.swift // // Created by DoubleHH on 2018/5/21. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit public class SFAutoVisibleTextField: UITextField, SFAutoMakeInputVisableProtocol { override public init(frame: CGRect) { super.init(frame: frame) addKeyboardNotis() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addKeyboardNotis() } deinit { NotificationCenter.default.removeObserver(self) } private func addKeyboardNotis() { NotificationCenter.default.addObserver(self, selector: #selector(beginEditting(noti:)), name: UIResponder.keyboardWillShowNotification, object: nil) } @objc private func beginEditting(noti: Notification) { keyboardWillShowNoti(noti: noti) } } <file_sep>// // SFScanCodeViews.swift // SFScanCodeKit // // Created by Leo on 2019/1/22. // Copyright © 2019 S.F.Express. All rights reserved. // import SFFoundation let kMinTitleWidth: CGFloat = 80 let kMinSideWidth: CGFloat = 44 //MARK: - Scan Input Alert protocol SFScanAlertInputProtocol: AnyObject { func scanInputAlertCancel(_ inputAlertView: SFScanAlertInputView) func scanInputAlert(_ inputAlertView: SFScanAlertInputView, input code: String) } /// - NXAlert开发完成后,需要接入@Leo class SFScanAlertInputView: UIView, SFScanCodeKitLoadProtocol { static var nibInfo: NibInfo = NibInfo(identifier: nil, name: "SFScanAlert") @IBOutlet var titleLabel: UILabel! @IBOutlet var textField: UITextField! @IBOutlet var confirmButton: UIButton! weak var delegate: SFScanAlertInputProtocol? @IBAction func cancel(_ sender: Any) { delegate?.scanInputAlertCancel(self) } @IBAction func confirm(_ sender: Any) { if IsCollectionEmpty(textField.text) { SFToast.show(withText: "请填写码信息") return } delegate?.scanInputAlert(self, input: ToStr(textField.text)) } func stopEdting(_ isStop: Bool) { _ = isStop ? textField.resignFirstResponder() : textField.becomeFirstResponder() } } protocol SFScanCodeVCNavigationBarDelegate: AnyObject { func didClickedLeftButton(navigationbar: SFScanCodeViewControllerNavigationBar) func didClickedRightButton(navigationbar: SFScanCodeViewControllerNavigationBar) } public class SFScanCodeViewControllerNavigationBar: UIView, SFScanCodeKitLoadProtocol { static var nibInfo: NibInfo = NibInfo(identifier: nil, name: "SFScanNavigationBar") weak var delegate: SFScanCodeVCNavigationBarDelegate? @IBOutlet public var bgView: UIView! @IBOutlet public var leftButton: UIButton! @IBOutlet public var rightButton: UIButton! @IBOutlet public var titleLabel: UILabel! @IBOutlet var titleLabelWidthConstraint: NSLayoutConstraint! private var createdLeftButton: UIButton? private var createdRightButton: UIButton? @IBAction func leftButtonClicked(_ sender: Any) { delegate?.didClickedLeftButton(navigationbar: self) } @IBAction func rightBtnClicked(_ sender: Any) { delegate?.didClickedRightButton(navigationbar: self) } public override func layoutSubviews() { super.layoutSubviews() let maxSideWidth = (SF.Const.screenWidth - kMinTitleWidth - 15 * 4) / 2 var leftSideWidth: CGFloat = 44 var rightSideWidth: CGFloat = 44 if createdLeftButton != nil { createdLeftButton!.sizeToFit() var width = min(createdLeftButton!.width, maxSideWidth) width = max(width, kMinSideWidth) leftSideWidth = width createdLeftButton!.size = CGSize(width: width, height: 44) createdLeftButton!.left = 15 createdLeftButton!.bottom = height } if createdRightButton != nil { createdRightButton!.sizeToFit() var width = min(createdRightButton!.width, maxSideWidth) width = max(width, kMinSideWidth) rightSideWidth = width createdRightButton!.size = CGSize(width: width, height: 44) createdRightButton!.right = SF.Const.screenWidth - 15 createdRightButton!.bottom = height } let sideWidth = max(leftSideWidth, rightSideWidth) let titleWidth = min(SF.Const.screenWidth - sideWidth * 2 - 60, titleLabel.text?.size(font: titleLabel.font).width ?? 0) titleLabelWidthConstraint.constant = titleWidth } public func creatLeftBarButton() -> UIButton { return creatBarButton(true) } public func creatRightBarButton() -> UIButton { return creatBarButton(false) } private func creatBarButton(_ isLeft: Bool) -> UIButton { let button = UIButton(type: .custom) button.setTitleColor(UIColor.white, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 16) if isLeft { leftButton.isHidden = true createdLeftButton?.removeFromSuperview() createdLeftButton = button addSubview(button) } else { rightButton.isHidden = true createdRightButton?.removeFromSuperview() createdRightButton = button addSubview(button) } return button } } public class SFScanCodeViewControllerTipsView: UIView, SFScanCodeKitLoadProtocol { static var nibInfo: NibInfo = NibInfo(identifier: nil, name: "SFScanTipsView") @IBOutlet public var bgView: UIView! @IBOutlet public var titleLabel: UILabel! override public func awakeFromNib() { backgroundColor = UIColor(white: 0, alpha: 0.4) layer.cornerRadius = 16 layer.masksToBounds = true } } public class SFScanCodeViewControllerScanView: UIView, SFScanCodeKitLoadProtocol { static var nibInfo: NibInfo = NibInfo(identifier: nil, name: "SFScanView") @IBOutlet public var bgView: UIView! public var border: UIImage? { didSet { borderImageView.image = border } } public var indicator: UIImage? { didSet { indicatorImageView.image = indicator } } public var indicatorHeight: CGFloat = 100 { didSet { indicatorHeightConstraint.constant = indicatorHeight } } @IBOutlet var borderImageView: UIImageView! @IBOutlet var indicatorImageView: UIImageView! @IBOutlet var indicatorHeightConstraint: NSLayoutConstraint! public func animation(isStart: Bool) { if isStart { if !indicatorImageView.isHidden { return } indicatorImageView.isHidden = false let animation = move(from: -indicatorHeight, to: height - indicatorHeight) indicatorImageView.layer.add(animation, forKey: "LineAnimation") } else { if indicatorImageView.isHidden { return } indicatorImageView.isHidden = true indicatorImageView.layer.removeAnimation(forKey: "LineAnimation") } } private func move(from: CGFloat, to: CGFloat) -> CABasicAnimation { let animation = CABasicAnimation(keyPath: "transform.translation.y") animation.fromValue = from animation.toValue = to animation.duration = 2.5 animation.repeatCount = MAXFLOAT animation.fillMode = .forwards animation.isRemovedOnCompletion = false animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) return animation } } public class SFScanCodeButton: UIControl, SFScanCodeKitLoadProtocol { static var nibInfo: NibInfo = NibInfo(identifier: nil, name: "SFScanButton") public var icon: UIImage? { didSet { imageView.image = icon } } public var title: String? { didSet { titleLabel.text = ToStr(title) } } public var type: SFScanKitButtonType? @IBOutlet var imageView: UIImageView! @IBOutlet var titleLabel: UILabel! } protocol SFScanCodeAuthorityAlertDelegate: AnyObject { func didClickCancel(alertView: SFScanCodeAuthorityAlert) func didClickOk(alertView: SFScanCodeAuthorityAlert) } /// - NXAlert开发完成后,需要接入@Leo public class SFScanCodeAuthorityAlert: UIView, SFScanCodeKitLoadProtocol { static var nibInfo: NibInfo = NibInfo(identifier: nil, name: "SFScanAuthrityAlert") @IBOutlet var confirmButton: UIButton! weak var delegate: SFScanCodeAuthorityAlertDelegate? @IBAction func cancel(_ sender: Any) { delegate?.didClickCancel(alertView: self) } @IBAction func gotoOpen(_ sender: Any) { delegate?.didClickOk(alertView: self) } } <file_sep>// // TabBarViewController.swift // appone // // Created by tangbo on 2019/6/22. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import SFFoundation class TabBarViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() assembleViewControllers() customTabBarAppearance() } private func assembleViewControllers() { let homeVC = HomeViewController.loadFromNib()! homeVC.assemble(title: "首页", normalImageName: "tabbar_icon_home_nomal", highlightedImageName: "tabbar_icon_home_selected") let orderVC = OrderListViewController.loadFromNib()! orderVC.assemble(title: "订单", normalImageName: "tabbar_icon_order_nomal", highlightedImageName: "tabbar_icon_order_selected") let ucVC = XNUserCenterViewController.loadFromNib()! ucVC.assemble(title: "我的", normalImageName: "tabbar_icon_user_nomal", highlightedImageName: "tabbar_icon_user_selected") viewControllers = [homeVC, orderVC, ucVC] } private func customTabBarAppearance() { tabBar.selectionIndicatorImage = UIColor.clear.image(with: CGSize(width: 1, height: 1)) tabBar.barTintColor = UIColor.white tabBar.isTranslucent = false tabBar.tintColor = nil let lineView = UIView(frame: CGRect(x: 0, y: 0, width: SF.Const.screenWidth, height: SF.Const.lineHeight)) lineView.backgroundColor = UIColor.hex("#e6e6e6") tabBar.addSubview(lineView) tabBar.height = 50 tabBar.shadowImage = UIImage() tabBar.backgroundImage = UIImage() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } extension UIViewController { func assemble(title: String, normalImageName: String, highlightedImageName: String) { let tabBarItem = UITabBarItem() tabBarItem.title = title let selectedImage = UIImage(named: highlightedImageName) let unselectedImage = UIImage(named: normalImageName)?.withRenderingMode(.alwaysOriginal) tabBarItem.selectedImage = selectedImage?.colorize(with: Color_Main).withRenderingMode(.alwaysOriginal) tabBarItem.image = unselectedImage tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.hex(0xB4BBCC), NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11)], for: .normal) tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: Color_Main, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11)], for: .selected) tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -3) self.tabBarItem = tabBarItem } } <file_sep>// // SFCacheable.swift // GroundService // // Created by Panda on 2018/6/20. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation public protocol SFCacheable: Codable { static var cacheFileName: String { get } } extension SFCacheable { private static var diskPath: String { return NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! + cacheFileName } public static func loadFromDisk() -> Self? { if let data = try? Data.init(contentsOf: URL.init(fileURLWithPath: diskPath), options: []), let model = try? SFJSONDecoder.init().decode(Self.self, from: data) { return model } return nil } public static func updateDiskCache(_ cacheModel: Self?) { if let data = try? SFJSONEncoder.init().encode(cacheModel) { try? data.write(to: URL.init(fileURLWithPath: diskPath)) } else { try? FileManager.default.removeItem(at: URL.init(fileURLWithPath: diskPath)) } } } <file_sep>// // SFAutoSizeTextView.swift // // Created by DoubleHH on 2018/6/6. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit @objc public protocol SFAutoSizeTextViewDelegate: NSObjectProtocol { /// custom @objc optional func autoSizeTextViewHeightChanged(_ textView: SFAutoSizeTextView) @objc optional func autoSizeMaxWordsReached(_ textView: SFAutoSizeTextView) /// system @objc optional func autoSizeTextViewShouldBeginEditing(_ textView: SFAutoSizeTextView) -> Bool @objc optional func autoSizeTextViewShouldEndEditing(_ textView: SFAutoSizeTextView) -> Bool @objc optional func autoSizeTextViewDidBeginEditing(_ textView: SFAutoSizeTextView) @objc optional func autoSizeTextViewDidEndEditing(_ textView: SFAutoSizeTextView) @objc optional func autoSizeTextView(_ textView: SFAutoSizeTextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool @objc optional func autoSizeTextViewDidChange(_ textView: SFAutoSizeTextView) } public class SFAutoSizeTextView: UITextView, UITextViewDelegate, SFAutoMakeInputVisableProtocol { @objc public var maxWords: Int = 0 @objc public weak var autoDelegate: SFAutoSizeTextViewDelegate? private var placeholderLabel: UILabel! private var initHeight: CGFloat = 0 @objc public var shouldResignFirstResponseWhenInputNewLine = true @objc public var rightButton: UIButton? { willSet { rightButton?.removeFromSuperview() } didSet { if let button = rightButton { addSubview(button) } } } override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) inits() } public convenience init(frame: CGRect) { self.init(frame: frame, textContainer: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) inits() } private func inits() { self.delegate = self self.returnKeyType = .done initHeight = frame.size.height placeholderLabel = UILabel.init() placeholderLabel.numberOfLines = 0 placeholderLabel.lineBreakMode = .byTruncatingTail insertSubview(placeholderLabel, at: 0) addKeyboardNotis() } override public var text: String! { didSet { updatePlaceholderHidden() updateHeight(newText: self.text) } } override public func layoutSubviews() { super.layoutSubviews() layoutActions() } private func layoutActions() { resetTextContainerInset() updatePlaceholder() updateRightButton() } private func updateRightButton() { rightButton?.isHidden = !isFirstResponder if isFirstResponder { rightButton?.right = self.width rightButton?.centerY = self.height * 0.5 } } private func resetTextContainerInset() { let top = interval() / 2 let rightInterval = isFirstResponder ? (rightButton?.width ?? 0) : 0 textContainerInset = UIEdgeInsets(top: top, left: 0, bottom: top, right: rightInterval) textContainer.lineFragmentPadding = 0 } public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if let method = autoDelegate?.autoSizeTextView, method(self, range, text) == false { return false } if shouldResignFirstResponseWhenInputNewLine && text == "\n" { self.resignFirstResponder() return false } var newText = textView.text ?? "" if text.count <= 0 { // delete if textView.text.count > 0 { newText = textView.text.substring(to: textView.text.count - 1) ?? "" } else { newText = "" } } else { // add newText = textView.text + text } if maxWords > 0 && markedTextRange == nil && newText.count > maxWords { autoDelegate?.autoSizeMaxWordsReached?(self) return false } updateHeight(newText: newText) return true } private func updateHeight(newText: String) { let maxWidth = self.contentSize.width - self.textContainerInset.left - self.textContainerInset.right; let height = newText.size(font: self.font!, maxWidth: maxWidth).height + interval() self.height = max(height, initHeight); if let method = autoDelegate?.autoSizeTextViewHeightChanged { method(self) } } private func interval() -> CGFloat { let height = "one".size(font: self.font!, maxWidth: 100).height return initHeight - height; } //MARK: - Other delegate public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { return autoDelegate?.autoSizeTextViewShouldBeginEditing?(self) ?? true } public func textViewShouldEndEditing(_ textView: UITextView) -> Bool { return autoDelegate?.autoSizeTextViewShouldEndEditing?(self) ?? true } public func textViewDidBeginEditing(_ textView: UITextView) { layoutActions() updateHeight(newText: self.text) autoDelegate?.autoSizeTextViewDidBeginEditing?(self) } public func textViewDidEndEditing(_ textView: UITextView) { layoutActions() updateHeight(newText: self.text) autoDelegate?.autoSizeTextViewDidEndEditing?(self) } public func textViewDidChange(_ textView: UITextView) { updatePlaceholderHidden() autoDelegate?.autoSizeTextViewDidChange?(self) ensureBelowMaxWords() } //MARK: - Max words private func ensureBelowMaxWords() { if maxWords > 0 && markedTextRange == nil && text.count > maxWords { text = text.substring(to: maxWords) } } //MARK: - placeholder public func setAttrPlaceholder(_ placeholder: NSAttributedString) { placeholderLabel.attributedText = placeholder updatePlaceholder() } private func updatePlaceholderHidden() { placeholderLabel.isHidden = (self.text?.count ?? 0) != 0 } private func updatePlaceholder() { let width = self.width - textContainerInset.left - textContainerInset.right - textContainer.lineFragmentPadding; placeholderLabel.width = width placeholderLabel.sizeToFit() placeholderLabel.top = textContainerInset.top placeholderLabel.left = textContainer.lineFragmentPadding + textContainerInset.left } //MARK: - Keyboard deinit { NotificationCenter.default.removeObserver(self) } private func addKeyboardNotis() { NotificationCenter.default.addObserver(self, selector: #selector(beginEditting(noti:)), name: UIResponder.keyboardWillShowNotification, object: nil) } @objc private func beginEditting(noti: Notification) { keyboardWillShowNoti(noti: noti) } } <file_sep>// // FoodDetailViewController.swift // appone // // Created by tangbo on 2019/6/22. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import NXDesign class FoodDetailViewController: BaseViewController, StoryboardLoadable { static var fileInfo = StoryboardFileInfo(name: "tabbar", identifier: "foodDetail") var foodModel: FoodModel? var operationCompletion: ((FoodOperationType, FoodModel?)->())? @IBOutlet weak var detailImgView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var subButton: UIButton! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var countLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() sf_navigationBar.titleLabel.text = "菜品详情" updateView() } func updateView() { let placeholderImage = UIColor.hex("#f8f8f8").image(size: CGSize(width: 1, height: 1)) detailImgView.image = placeholderImage if let img_url = foodModel?.img_url, let url = URL(string: img_url) { detailImgView.sd_setImage(with: url, placeholderImage: placeholderImage) } nameLabel.text = foodModel?.name priceLabel.text = "¥ \(foodModel?.price ?? "")" priceLabel.textColor = Color_Main if (foodModel?.count ?? 0) > 0 { subButton.isHidden = false countLabel.isHidden = false countLabel.text = "\(foodModel?.count ?? 0)" } else { subButton.isHidden = true countLabel.isHidden = true } } @IBAction func operationAction(_ sender: UIButton) { if sender == addButton { operationCompletion?(.add, foodModel) } else { operationCompletion?(.sub, foodModel) } updateView() } } <file_sep>// // NXUploadableImageContainerView.swift // NXDesign // // Created by tangbo on 2019/2/1. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit import AVKit @IBDesignable open class NXUploadableImageContainerView: UIView { public let uploadImgView = NXUploadableImageView() public let addImgView = NXAddImageView() public override init(frame: CGRect) { super.init(frame: frame) configUI() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configUI() } func configUI() { uploadImgView.deleteBlock = { [weak self] in self?.addImgView.isHidden = false self?.uploadImgView.isHidden = true if self?.uploadImgView != nil { self?.addSubview((self?.uploadImgView)!) } } addSubview(uploadImgView) addSubview(addImgView) addImgView.delegate = self uploadImgView.isHidden = true } func upload(image: UIImage) { addImgView.isHidden = true uploadImgView.isHidden = false uploadImgView.upload(image: image) } open override func layoutSubviews() { super.layoutSubviews() uploadImgView.frame = bounds let addViewSize = (uploadImgView.style == .default) ?CGSize(width: bounds.size.width - 10, height: bounds.size.height - 10) :bounds.size addImgView.frame = CGRect(x: 0, y: 0, width: addViewSize.width, height: addViewSize.height) addImgView.center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2) } } extension NXUploadableImageContainerView: NXAddImageViewDelegate { public func addImageView(_ view: NXAddImageView, didSelectImages images: [UIImage]) { if let image = images.first?.resizedImage(1500) { upload(image: image) } } } <file_sep>// // NavigationControllerExtensions.swift // SFFoundation // // Created by DoubleHH on 2018/12/20. // Copyright © 2018 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation extension UINavigationController { /// 移除UI栈中对应的VC /// /// - Parameters: /// - vcType: 指定移除的VC类型 /// - shouldRemoveLast: 如果移除的vc是最后一个,是否需要移除,默认false不移除 public func remove<VC: UIViewController>(vcType: VC.Type, shouldRemoveLast: Bool = false) { guard let index = viewControllers.firstIndex(where: { type(of: $0) == vcType }) else { return } if index == viewControllers.count - 1 && !shouldRemoveLast { return } viewControllers.remove(at: index) } } <file_sep>// // ArrayExtention.swift // workservice // // Created by Leo on 2019/4/29. // Copyright © 2019 Beijing SF intra-city Technology Co., Ltd. All rights reserved. // import Foundation extension Array { mutating func remove(_ isIncluded:(Element) -> Bool) { for (index, item) in self.enumerated() { if isIncluded(item) { remove(at: index) break } } } } <file_sep>// // DictionaryExtensions.swift // BaseTest // // Created by DoubleHH on 2018/8/17. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation /// URL public func CombinedURLString(params: Dictionary<String, CustomStringConvertible>?) -> String { guard let params = params else { return "" } var paramsArray = Array<String>() params.forEach { (key, value) in let kv = (key.URLEncode() ?? "") + "=" + (value.description.URLEncode() ?? "") paramsArray.append(kv) } return paramsArray.joined(separator: "&") } /// Convert Dictionary to JSON String extension Dictionary { public var jsonString: String? { if let data = try? JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted), let jsonString = String(data: data, encoding: String.Encoding.utf8) { return jsonString } return nil } } <file_sep>// // NetWaterFlowCollectionView.swift // NXDesign // // Created by DoubleHH on 2019/6/16. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation /// 网络照片瀑布流,点击照片可以进入大图预览页 public class NetWaterFlowCollectionView: UICollectionView { private var photos: Array<String> = [] private var batchUpdates: Dictionary<String, CGSize> = [:] private var imageHeights: Dictionary<String, CGFloat> = [:] private var waterFlowLayout: WaterFlowCollectionViewLayout! private let reloadInterval = TimeInterval(0.5) /// 瀑布流的 CollectionViewLayout,获取后可设置间距等,详细请看 WaterFlowCollectionViewLayout public var layout: WaterFlowCollectionViewLayout { return waterFlowLayout } public init(frame: CGRect) { super.init(frame: frame, collectionViewLayout: UICollectionViewLayout()) inits() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) inits() } /// 更新显示的图片,会先移除之前所有图片,再添加参数的photos public func updatePhotos(photos: Array<String>) { self.photos.removeAll() self.photos.append(contentsOf: photos) reloadCollectionView() } private func inits() { waterFlowLayout = WaterFlowCollectionViewLayout(heightBlk: { [weak self](ip) -> CGFloat in return self?.cellHeight(indexPath: ip) ?? 0 }) collectionViewLayout = waterFlowLayout register(NetWaterFlowCell.self, forCellWithReuseIdentifier: "NetWaterFlowCell") delegate = self dataSource = self } private func cellHeight(indexPath: IndexPath) -> CGFloat { let width = waterFlowLayout.cellWidth let height = width * 0.618 guard let url = photos.at(indexPath.item) else { return height } return imageHeights[url] ?? height } private func updateCellHeight(url: String, imageSize: CGSize) { batchUpdates[url] = imageSize NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(batchUpdateHeights), object: nil) perform(#selector(batchUpdateHeights), with: nil, afterDelay: reloadInterval) } @objc private func batchUpdateHeights() { guard batchUpdates.count > 0 else { return } var updated = false let cellWidth = waterFlowLayout.cellWidth for item in batchUpdates { if imageHeights[item.key] == nil { imageHeights[item.key] = ceil(cellWidth * item.value.height / item.value.width) updated = true } } batchUpdates.removeAll() if updated { reloadCollectionView() } } private func reloadCollectionView() { reloadData() } } extension NetWaterFlowCollectionView: UICollectionViewDelegate, UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photos.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NetWaterFlowCell", for: indexPath) if let aCell = cell as? NetWaterFlowCell, let url = photos.at(indexPath.item) { aCell.update(url: url, row: indexPath.item, imageDownloadBlk: { [weak self] (url, imageSize) in guard let url = url else { return } self?.updateCellHeight(url: url, imageSize: imageSize) }) } return cell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let browerVC = NXImageBrowserController.loadFromStoryboard(imageUrls: photos, selectedIndex: indexPath.item) findNearestNavigationController()?.pushViewController(browerVC, animated: true) } private func findNearestNavigationController() -> UINavigationController? { var responder = next while responder != nil { if let vc = responder as? UIViewController { return vc.navigationController } responder = responder?.next } return nil } } class NetWaterFlowCell: UICollectionViewCell { typealias DownloadedCallback = (_ url: String?, _ imageSize: CGSize) -> Void private var imageDownloadBlk: DownloadedCallback? private var iconIv: UIImageView! override init(frame: CGRect) { super.init(frame: frame) iconIv = UIImageView(frame: self.bounds) iconIv.autoresizingMask = [.flexibleWidth, .flexibleHeight] iconIv.contentMode = .scaleAspectFill iconIv.clipsToBounds = true addSubview(iconIv) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(url: String, row: Int, imageDownloadBlk: DownloadedCallback?) { self.imageDownloadBlk = imageDownloadBlk iconIv.sd_setImage(with: URL.init(string: url), placeholderImage: nil) { [weak self](image, _, _, url) in guard let sself = self else { return } if let img = image { sself.iconIv.image = image sself.imageDownloadBlk?(url?.absoluteString, img.size) } } } } <file_sep>// // UIViewControllerExtension.swift // NXDesign // // Created by Leo on 2019/6/3. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // public extension UIViewController { func removeFromFather() { self.willMove(toParent: nil) self.view.removeFromSuperview() self.removeFromParent() } func add(child childViewController: UIViewController) { addChild(childViewController) childViewController.view.frame = view.bounds childViewController.view.clipsToBounds = true childViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(childViewController.view) childViewController.didMove(toParent: self) } } <file_sep>// // LoginViewController.swift // appone // // Created by tangbo on 2019/6/29. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import SFFoundation import NXDesign class LoginViewController: UIViewController, StoryboardLoadable { static var fileInfo = StoryboardFileInfo(name: "tabbar", identifier: "login") @IBOutlet weak var phoneTextField: UITextField! @IBOutlet weak var codeTextField: UITextField! @IBOutlet weak var codeButton: UIButton! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var errorLabel: UILabel! var completion: ((Bool)->())? var timeCountDowm: Int = 60 override func viewDidLoad() { super.viewDidLoad() loginButton.setBackgroundImage(Color_Main.image(size: CGSize(width: 1, height: 1)), for: .normal) errorLabel.textColor = Color_Main let ges = UITapGestureRecognizer(target: self, action: #selector(taped)) ges.delegate = self view.addGestureRecognizer(ges) } @objc func taped() {} @IBAction func loginAction(_ sender: Any) { if IsCollectionEmpty(phoneTextField.text) { errorLabel.text = "请输入手机号" errorLabel.isHidden = false return } if IsCollectionEmpty(codeTextField.text) { errorLabel.text = "请输入验证码" errorLabel.isHidden = false return } guard let phone = phoneTextField.text else { return } guard let code = codeTextField.text else { return } errorLabel.text = "" errorLabel.isHidden = true Account.verifySmsCode(code, phone: phone) { (success) in if success { self.completion?(true) self.dismiss(animated: true, completion: nil) } else { self.errorLabel.text = "登录失败,请确认验证码或手机号是否正确" self.errorLabel.isHidden = false } } } @IBAction func closeAction(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func codeAction(_ sender: Any) { if IsCollectionEmpty(phoneTextField.text) { errorLabel.text = "请输入手机号" errorLabel.isHidden = false return } guard let phone = phoneTextField.text else { return } errorLabel.text = "" errorLabel.isHidden = true SFLoadingIndicatorView.showLoadingIndicator(for: view) Account.smsCode(withPhone: phone) { (success) in SFLoadingIndicatorView.dismissLoadingIndicator(for: self.view) if success { SFPollingTimer.addResponder(self, selector: #selector(self.smsSuccess), withTimeInterval: 1) } else { self.errorLabel.text = "验证码发送失败,请检查网络" self.errorLabel.isHidden = false } } } @objc func smsSuccess() { codeButton.setTitle("\(timeCountDowm)秒", for: .normal) codeButton.isEnabled = false if timeCountDowm > 1 { timeCountDowm -= 1 } else { codeButton.isEnabled = true codeButton.setTitle("获取验证码", for: .normal) timeCountDowm = 60 SFPollingTimer.removeResponder(self, selector: #selector(self.smsSuccess)) } } } extension LoginViewController: UIGestureRecognizerDelegate { func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { view.endEditing(true) return false } } <file_sep>// // FoodView.swift // appone // // Created by tangbo on 2019/6/22. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import NXDesign class FoodView: UIView, NibLoadable { static var fileInfo = NibFileInfo(name: "FoodView") @IBOutlet weak var iconimgView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var countLabel: UILabel! var foodModel: FoodModel? { didSet { iconimgView.image = DefaultImage_placeholder if let img_url = foodModel?.img_url, let url = URL(string: img_url) { iconimgView.sd_setImage(with: url, placeholderImage: DefaultImage_placeholder) } nameLabel.text = foodModel?.name priceLabel.text = "¥\(foodModel?.price ?? "")" countLabel.text = "x\(foodModel?.count ?? 1)" } } } <file_sep>// // Account.swift // appone // // Created by tangbo on 2019/6/29. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import NXDesign struct Account { static var isLogin: Bool { get { return UserDefaults.standard.bool(forKey: "isLogin") } } static var phone: String? { get { return UserDefaults.standard.string(forKey: "phone") } } static func smsCode(withPhone phone: String, completion: ((Bool)->())?) { BmobSMS.requestCodeInBackground(withPhoneNumber: phone, andTemplate: "smslogin") { (msgId, error) in if (error == nil) || (phone == DefaultAccount_phone) { completion?(true) } else { completion?(false) } } } static func verifySmsCode(_ smsCode: String, phone: String, completion:((Bool)->())?) { BmobSMS.verifySMSCodeInBackground(withPhoneNumber: phone, andSMSCode: smsCode) { (success, error) in if success || (phone == DefaultAccount_phone && smsCode == DefaultAccount_code) { UserDefaults.standard.set(true, forKey: "isLogin") UserDefaults.standard.set(phone, forKey: "phone") completion?(true) } else { UserDefaults.standard.set(false, forKey: "isLogin") completion?(false) } } } static func loginIfNeed(completion:((Bool)->())?) { if !isLogin { login(completion: completion) } else { completion?(true) } } static func login(completion:((Bool)->())?) { let loginVC = LoginViewController.loadFromNib()! loginVC.completion = completion BaseViewController.mainViewController?.present(loginVC, animated: true, completion: nil) } static func logout() { UserDefaults.standard.set(false, forKey: "isLogin") UserDefaults.standard.set(nil, forKey: "phone") } } <file_sep>// // OrderDetailViewController.swift // appone // // Created by tangbo on 2019/6/29. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import SFFoundation import NXDesign class OrderDetailViewController: BaseViewController, StoryboardLoadable { static var fileInfo = StoryboardFileInfo(name: "tabbar", identifier: "orderDetail") var order: OrderModel? @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var numberLabel: UILabel! @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var addressView: UIView! @IBOutlet weak var userInfoLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var foodView: UIView! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var callButton: UIButton! @IBOutlet weak var foodViewTopToTopViewConstraint: NSLayoutConstraint! @IBOutlet weak var foodViewTopToAddressViewConstraint: NSLayoutConstraint! override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if order?.takeout == true { foodViewTopToTopViewConstraint.isActive = false foodViewTopToAddressViewConstraint.isActive = true } else { foodViewTopToAddressViewConstraint.isActive = false foodViewTopToTopViewConstraint.isActive = true } } override func viewDidLoad() { super.viewDidLoad() if order?.takeout == true { numberLabel.text = "订单号:\(order?.orderId ?? "")" userInfoLabel.text = "电话: \(order?.phone ?? "")" addressLabel.text = "地址:" + (order?.address ?? "") addressView.isHidden = false } else { numberLabel.text = "您的取餐码为\(order?.number ?? "")" addressView.isHidden = true } sf_navigationBar.title = "订单详情" statusLabel.text = order?.status?.description statusLabel.textColor = Color_Main priceLabel.textColor = Color_Main priceLabel.text = "合计¥\(order?.totalPrice ?? "")" scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 70, right: 0) callButton.setBackgroundImage(DefaultImage_main, for: .normal) callButton.layer.cornerRadius = 15 callButton.layer.masksToBounds = true configFood() } func configFood() { guard let foodList = order?.foods else { return } var lastItemView: UIView? for food in foodList { let itemView = FoodView.loadFromNib()! foodView.addSubview(itemView) itemView.translatesAutoresizingMaskIntoConstraints = false itemView.foodModel = food itemView.leadingAnchor.constraint(equalTo: foodView.leadingAnchor).isActive = true if lastItemView != nil { itemView.topAnchor.constraint(equalTo: lastItemView!.bottomAnchor).isActive = true } else { itemView.topAnchor.constraint(equalTo: foodView.topAnchor).isActive = true } itemView.trailingAnchor.constraint(equalTo: foodView.trailingAnchor).isActive = true itemView.heightAnchor.constraint(equalToConstant: 70).isActive = true lastItemView = itemView } if lastItemView != nil { foodView?.bottomAnchor.constraint(equalTo: lastItemView!.bottomAnchor, constant: 20).isActive = true } } @IBAction func callAction(_ sender: Any) { SFCall.call("18514567266") } } <file_sep>target=$1 ./swiftshield -automatic -project-root ./ -automatic-project-file ./$target.xcodeproj -automatic-project-scheme $target -ignore-modules NXDesign,SFFoundation <file_sep>// // NXAlertMessageTableViewCell.swift // NXDesign // // Created by tangbo on 2019/4/28. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit class NXAlertMessageTableViewCell: UITableViewCell { @IBOutlet weak var indexLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var indexLabelWidthConstraint: NSLayoutConstraint! @IBOutlet weak var indexLabelHeightConstraint: NSLayoutConstraint! var indexSize = CGSize() { didSet { indexLabelWidthConstraint.constant = indexSize.width indexLabelHeightConstraint.constant = indexSize.height } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>// // WebviewViewController.swift // workservice // // Created by Leo on 2019/05/06. // Copyright © 2019 Beijing SF intra-city Technology Co., Ltd. All rights reserved. // import UIKit import NXDesign import SFFoundation class WebViewViewController: BaseViewController { var urlString: String? var navTitle: String? var bounce = false private var webview = UIWebView() convenience init(url: String, navTitle: String = "", bounce: Bool = true) { self.init(nibName: nil, bundle: nil) self.urlString = url self.navTitle = navTitle self.bounce = bounce } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() sf_navigationBar.title = navTitle sf_navigationBar.leftBarButton.isHidden = true configWebview() loadRequest() } private func configWebview() { webview.frame = sf_view.bounds webview.delegate = self webview.scrollView.bounces = bounce webview.autoresizingMask = [.flexibleWidth, .flexibleHeight] webview.isOpaque = false webview.backgroundColor = UIColor.hex(0xffffff) sf_view.addSubview(webview) } private func loadRequest() { let addUrlStr = urlString?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) let url = URL(string: ToStr(addUrlStr)) guard let requestUrl = url else { return } let request = URLRequest(url: requestUrl) webview.loadRequest(request) } } extension WebViewViewController: UIWebViewDelegate { func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool { return true } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { SFLoadingIndicatorView.dismissLoadingIndicator(for: sf_view) } func webViewDidStartLoad(_ webView: UIWebView) { SFLoadingIndicatorView.showLoadingIndicator(for: sf_view, with: .contentBlack) } func webViewDidFinishLoad(_ webView: UIWebView) { if IsCollectionEmpty(navTitle) { sf_navigationBar.title = webView.stringByEvaluatingJavaScript(from: "document.title") } SFLoadingIndicatorView.dismissLoadingIndicator(for: sf_view) } } <file_sep>// // ShopTask.swift // appone // // Created by tangbo on 2019/6/22. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation class ShopModel: Codable { var shop_name: String? var menu_list: [MenuModel]? } class MenuModel: Codable { var menu_name: String? var list: [FoodModel]? } class FoodModel: Codable { var food_id: String? var name: String? var img_url: String? var big_img_url: String? var price: String? var origin_price: String? var discourt: String? var count: Int? } <file_sep>// // SFScanHandle.swift // SFScanCodeKit // // Created by Leo on 2018/12/27. // Copyright © 2018 S.F.Express. All rights reserved. // import AVKit import SFFoundation extension SFScanCodeViewController: AVCaptureMetadataOutputObjectsDelegate { func configCapture() { guard let device = AVCaptureDevice.default(for: .video) else { return } guard let input = try? AVCaptureDeviceInput(device: device) else { return } output.setMetadataObjectsDelegate(self, queue: .main) output.rectOfInterest = CGRect(x: interestRect.origin.y / sf_view.height, y: (sf_view.width - interestRect.size.width - interestRect.origin.x) / sf_view.width, width: interestRect.size.height / sf_view.height, height: interestRect.size.width / sf_view.width) self.input = input if (session.canSetSessionPreset(.high)) { session.sessionPreset = .high } session.addInput(input) session.addOutput(output) /// 一定放在 “session.addOutput(output)” 之后 output.metadataObjectTypes = scanTypes DispatchQueue.global().async { self.session.startRunning() } } public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { if isInputting { return } if metadataObjects.count > 0 { stopScan() let metadataObject = metadataObjects.at(0) as? AVMetadataMachineReadableCodeObject callbackIfNeed(metadataObject?.stringValue) } } } <file_sep>// // StringExtensions.swift // Buyer // // Created by Panda on 2018/5/16. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit /// 金额格式化 extension String { static private var numberFormatter = NumberFormatter.init() static private func priceNumberFormatter() -> NumberFormatter { numberFormatter.maximumFractionDigits = 2 numberFormatter.minimumIntegerDigits = 1 return numberFormatter } /// 将以「分」为单位的字符串格式化为以「元」为单位的字符串 /// /// - Returns: 格式化后的字符串 public func centToYuan() -> String { let yuanPrice = (Double(self) ?? 0) / 100 return String.price(number: yuanPrice) ?? "0" } /// 格式化为价格常用的展示格式:小数点后最多两位。 /// /// - Parameter number: 要格式化的数字(对应价格单位:「元」) /// - Returns: 格式化后的字符串 public static func price<T>(number : T) -> String? where T: Numeric { return priceNumberFormatter().string(from: (number as? NSNumber) ?? 0) } } /// substring extension String { /// substring with range. If range is illeagal, return nil /// /// - Parameter range: indicate start and end. like 0..<2 /// - Returns: sub or nil public func substring(range: Range<Int>) -> String? { return substring(from: range.lowerBound, to: range.upperBound) } /// substring from index public func substring(from: Int) -> String? { return substring(from: from, to: self.count) } /// substring with end index of (to - 1), from 0 public func substring(to: Int) -> String? { return substring(from: 0, to: to) } private func substring(from: Int, to: Int) -> String? { guard from >= 0, to <= self.count, from < to else { return nil } let fromIndex = self.index(self.startIndex, offsetBy: from) let toIndex = self.index(self.startIndex, offsetBy: to) return String(self[fromIndex..<toIndex]) } } /// size extension String { public func width(font: UIFont, maxWidth: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGFloat { return self.size(font: font, maxWidth: maxWidth).width } public func height(font: UIFont, maxWidth: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGFloat { return self.size(font: font, maxWidth: maxWidth).height } public func size(font: UIFont, maxWidth: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGSize { guard self.count > 0 else { return .zero } var strSize = NSString.init(string: self).boundingRect(with: .init(width: maxWidth, height: CGFloat.greatestFiniteMagnitude), options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: [.font: font], context: nil).size strSize.width = min(strSize.width, maxWidth) return CGSize.init(width: ceil(strSize.width), height: ceil(strSize.height)) } public func size(font: UIFont, maxWidth: CGFloat = CGFloat.greatestFiniteMagnitude, maxRowNumber: Int) -> CGSize { var strSize = self.size(font: font, maxWidth: maxWidth) let maxLineHeight = ceil(Double(maxRowNumber) * Double(font.lineHeight)) if Double(strSize.height) > maxLineHeight { strSize.height = CGFloat(maxLineHeight) } return strSize } } /// URL extension String { public func URLEncode() -> String? { return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.sf_urlQueryNotAllowed.inverted) } public func URLString(urlParams: Dictionary<String, CustomStringConvertible>?) -> String { guard let params = urlParams, !params.isEmpty else { return self } let joinFlag = self.contains("?") ? "&" : "?" return self + joinFlag + CombinedURLString(params: params) } public func urlParams() -> Dictionary<String, Any>? { guard let url = URL.init(string: self) else { return nil } let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: true)?.queryItems let queryParameters = queryItems?.reduce(into: [:], { (theParameters, item) in theParameters[item.name] = item.value }) return queryParameters } } @objc public enum SFImageClipType: Int { /// 等比截取型裁剪。该操作会将图像等比缩放直至某一边达到设定最小值,之后将另一边居中裁剪至设定值。如只指定一边,则表示宽高相等的正方形。如原图大小为1000x500,将参数设定为?imageView2/1/w/500/h/400 后,图像会先等比缩放至800x400,之后左右各裁剪150,得到500x400大小的图像 case clip /// 等比压缩。该操作会将图像等比缩放至宽高都小于设定最大值。如原图大小为1000x500,将参数设定为?imageView2/2/w/500/h/400后,图像会等比缩放至500x250。如果只指定一边,则另一边自适应 case notClip } public extension String { public func sf_tencentCosImage(maxSize: CGSize, type: SFImageClipType) -> String { guard let url = URL(string: self), let host = url.host else { return "" } guard host.contains("myqcloud.com") else { return self } let scale = UIScreen.main.scale let typeStr = ((type == .clip) ? "imageView2/1" : "imageView2/2") let format = typeStr + "/w/\(maxSize.width * scale)/h/\(maxSize.height * scale)" if self.contains("?") { return self + "/" + format } return self + "?" + format } } <file_sep>// // SFCameraOverlayViewCell.swift // SFImageKit // // Created by tangbo on 2018/10/26. // Copyright © 2018 S.F.Express. All rights reserved. // import UIKit import SFFoundation class NXCameraOverlayViewCell: UICollectionViewCell { let imgView = UIImageView() var longPressAction: ((UILongPressGestureRecognizer)->())? override init(frame: CGRect) { super.init(frame: frame) configUI() } override var isSelected: Bool { set { super.isSelected = newValue imgView.layer.masksToBounds = true imgView.layer.cornerRadius = newValue ?0 :3 } get { return super.isSelected } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configUI() { imgView.layer.masksToBounds = true imgView.layer.cornerRadius = 3 contentView.addSubview(imgView) selectedBackgroundView = UIView() selectedBackgroundView?.layer.masksToBounds = true selectedBackgroundView?.layer.cornerRadius = 3 selectedBackgroundView?.layer.borderWidth = 2 let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(longPress:))) addGestureRecognizer(longPress) } @objc private func longPressAction(longPress: UILongPressGestureRecognizer) { longPressAction?(longPress) } override func layoutSubviews() { super.layoutSubviews() imgView.size = CGSize(width: 50, height: 50) imgView.centerX = contentView.width / 2 imgView.centerY = contentView.height / 2 } } <file_sep>// // NXAlertView.swift // // // Created by Panda on 2018/9/5. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit import SFFoundation /** * for example * // 取消按钮 let cancel = NXAlertAction(cancelTitle: "取消") { } // 确定按钮 let ok = NXAlertAction(okTitle: "确定") { } NXAlertView().title("标题").message("内容").actions([cancel, ok]).show() // 如果想修改确定按钮的颜色,可以使用以下方法创建按钮: let ok = NXAlertAction(okTitle: "确定", style: .custom(UIColor.red)) { } */ public class NXAlertView: UIView, NXAlertable { var title: String? var message: String? var messages: [String]? var attributedMessage: NSAttributedString? var input: NXAlertInput? var actions = [NXAlertAction]() var closeAction: ((NXAlertView)->())? var showCloseButton = false private let contentView = UIView() ///弹窗的主题色 static public var tintColor = UIColor.hex("#26CEA8") ///弹窗上的输入控件 public var inputTextView: NXAlertInputView? ///在弹窗上输入的内容 public var inputText: String? { return inputTextView?.text } ///弹窗的唯一识别符 public private(set) var identifier: String? { didSet { if IsCollectionEmpty(identifier) { return } guard let identifier = identifier else { return } guard let key = UnsafeRawPointer(bitPattern: ("nxalertView" + identifier).hashValue) else { return } guard case let window?? = UIApplication.shared.delegate?.window else { return } objc_setAssociatedObject(window, key, self, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) } } public init() { super.init(frame: CGRect(x: 0, y: 0, width: SF.Const.screenWidth - 45 * 2, height: 0)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configUI() { contentView.backgroundColor = UIColor.white contentView.layer.masksToBounds = true contentView.layer.cornerRadius = 10 addSubview(contentView) var topMargin: CGFloat = 20 topMargin = config(title: title, message: message, topMargin: topMargin) topMargin = configInput(topMargin: topMargin) topMargin = configActionView(actions: actions, topMargin: topMargin) contentView.frame = CGRect(x: 0, y: 0, width: frame.width, height: topMargin) topMargin = configCloseAction(closeAction, topMargin: contentView.frame.maxY) frame = CGRect(x: frame.minX, y: frame.minY, width: frame.width, height: topMargin) } func config(title: String?, message: String?, topMargin: CGFloat) -> CGFloat { if IsCollectionEmpty(title) && IsCollectionEmpty(message) && IsCollectionEmpty(messages) && IsCollectionEmpty(attributedMessage?.string) { return topMargin } var margin = topMargin if !IsCollectionEmpty(title) { let titleLabel = UILabel() titleLabel.text = title titleLabel.textAlignment = .center titleLabel.font = UIFont.boldSystemFont(ofSize: 18) titleLabel.textColor = UIColor.hex("#333333") contentView.addSubview(titleLabel) titleLabel.sizeToFit() titleLabel.frame = CGRect(x: 15, y: margin, width: frame.width - 15 * 2, height: titleLabel.frame.height) margin = titleLabel.frame.maxY + 8 } let maxHeight = (CGFloat(230) * (SF.Const.screenWidth / 375)) if !IsCollectionEmpty(message) || !IsCollectionEmpty(attributedMessage?.string) { let messageLabel = UILabel() messageLabel.numberOfLines = 0 if !IsCollectionEmpty(message) { messageLabel.text = message } else if !IsCollectionEmpty(attributedMessage?.string) { messageLabel.attributedText = attributedMessage } messageLabel.textAlignment = .center messageLabel.font = UIFont.systemFont(ofSize: 14) if !IsCollectionEmpty(message) { messageLabel.textColor = UIColor.hex("#333333") } messageLabel.frame = CGRect(x: 15, y: margin, width: frame.width - 15 * 2, height: 0) messageLabel.sizeToFit() if messageLabel.frame.height > maxHeight { let scrollView = UIScrollView() contentView.addSubview(scrollView) scrollView.frame = CGRect(x: 15, y: margin, width: frame.width - 15 * 2, height: maxHeight) scrollView.addSubview(messageLabel) messageLabel.frame = CGRect(x: 0, y: 0, width: scrollView.frame.width, height: messageLabel.frame.height) scrollView.contentSize = CGSize(width: scrollView.frame.width, height: messageLabel.frame.maxY) margin = scrollView.frame.maxY } else { contentView.addSubview(messageLabel) messageLabel.frame = CGRect(x: 15, y: margin, width: frame.width - 15 * 2, height: messageLabel.frame.height) margin = messageLabel.frame.maxY } } else if !IsCollectionEmpty(messages) { let messageView = NXAlertMessageView(frame: CGRect(x: 15, y: margin, width: frame.width - 15 * 2, height: 0), messages: messages!) contentView.addSubview(messageView) messageView.isUserInteractionEnabled = (messageView.frame.height > maxHeight) messageView.height = (messageView.frame.height > maxHeight) ? maxHeight : messageView.frame.height margin = messageView.frame.maxY } return margin } func configInput(topMargin: CGFloat) -> CGFloat { guard let input = input else { return topMargin } let inputView = NXAlertInputView(input: input) inputTextView = inputView contentView.addSubview(inputView) inputView.frame = CGRect(x: 15, y: topMargin + 20, width: frame.width - 15 * 2, height: 40) return inputView.frame.maxY } func configActionView(actions: [NXAlertAction], topMargin: CGFloat) -> CGFloat { if actions.count == 0 { return topMargin + 40 } let actionFrame = CGRect(x: 0, y: topMargin + ((input != nil) ? 40 : 20), width: frame.width, height: 0) let actionView = actions.count > 2 ? NXActionVerticalView(frame: actionFrame, actions: actions, alertView: self) : NXActionHorizontalView(frame: actionFrame, actions: actions, alertView: self) contentView.addSubview(actionView) return actionView.frame.maxY } func configCloseAction(_ closeAction: ((NXAlertView)->())?, topMargin: CGFloat) -> CGFloat { if !showCloseButton { return topMargin } let closeButton = UIButton(type: .custom) closeButton.setImage(UIImage(named: "alert_icon_close", in: Bundle(for: NXAlertView.self), compatibleWith: nil), for: .normal) closeButton.addTarget(self, action: #selector(closeButtonClicked), for: .touchUpInside) addSubview(closeButton) closeButton.frame = CGRect(x: (frame.width - 32) / 2, y: topMargin + 25, width: 32, height: 32) return closeButton.frame.maxY } @objc func closeButtonClicked() { closeAction?(self) dismiss() } } public extension NXAlertView { func shouldShow() -> Bool { var hasMessage = false if !IsCollectionEmpty(self.message) || !IsCollectionEmpty(self.messages) || !IsCollectionEmpty(attributedMessage?.string) { hasMessage = true } if IsCollectionEmpty(self.title) && !hasMessage { assert(false, "请设置弹窗需要展示的内容,例如title或者message") return false } if IsCollectionEmpty(self.actions) && !showCloseButton { assert(false, "弹窗至少需要一个按钮,请设置action或者closeButtonVisible") return false } configUI() return true } func willDismiss() { if IsCollectionEmpty(identifier) { return } guard let identifier = identifier else { return } guard let key = UnsafeRawPointer(bitPattern: ("nxalertView" + identifier).hashValue) else { return } guard case let window?? = UIApplication.shared.delegate?.window else { return } objc_setAssociatedObject(window, key, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) } /** 设置弹窗的标题 * parameter title:标题,title与message不能够都为空,否则弹窗不会显示 * returns:当前NXAlertView对象 */ @discardableResult func title(_ title: String) -> Self { self.title = title return self } /** 设置弹窗的内容 * parameter message:内容,title与message不能够都为空,否则弹窗不会显示 * returns:当前NXAlertView对象 */ @discardableResult func message(_ message: String) -> Self { self.message = message return self } /** 设置弹窗的内容 * parameter messages:要显示的内容,会按照数组的顺序展示,title与messages不能够都为空,否则弹窗不会显示 * returns:当前NXAlertView对象 */ @discardableResult func messages(_ messages: [String]) -> Self { self.messages = messages return self } /** 设置弹窗的内容,富文本,不支持修改字号 * parameter attributedMessage:富文本内容,title与attributedMessage不能够都为空,否则弹窗不会显示 * returns:当前NXAlertView对象 */ @discardableResult func attributedMessage(_ attributedMessage: NSAttributedString) -> Self { self.attributedMessage = attributedMessage return self } /** 设置弹窗的输入框 * parameter input:输入框,输入框的具体创建方式见NXAlertInput * returns:当前NXAlertView对象 */ @discardableResult func input(_ input: NXAlertInput) -> Self { self.input = input return self } /** 设置弹窗的按钮 * parameter action:按钮,按钮的具体创建方式见NXAlertAction * returns:当前NXAlertView对象 */ @discardableResult func action(_ action: NXAlertAction) -> Self { self.actions.append(action) return self } /** 一次性设置弹窗的多个按钮 * parameter actions:要显示的按钮数组,按钮的具体创建方式见NXAlertAction * returns:当前NXAlertView对象 */ @discardableResult func actions(_ actions: [NXAlertAction]) -> Self { self.actions += actions return self } /** 显示弹窗底部的关闭按钮,并设置点击事件 * parameter action:关闭按钮的点击事件 * returns:当前NXAlertView对象 */ @discardableResult func closeButtonVisible(withAction action: ((NXAlertView)->())? = nil) -> Self { self.closeAction = action self.showCloseButton = true return self } /** 设置弹窗的唯一识别符 * parameter identifier:弹窗的唯一识别符 * returns:当前NXAlertView对象 */ @discardableResult func identifier(_ identifier: String) -> Self { self.identifier = identifier return self } /** 根据弹窗的唯一识别符找到弹窗并关闭 * parameter identifier:弹窗的唯一识别符 */ class func dismiss(withIdentifier identifier: String) { visibleAlertView(withIdentifier: identifier)?.dismiss() } /** 根据弹窗上的按钮的唯一识别符找到按钮 * parameter identifier:弹窗上的按钮的唯一识别符 * returns:按钮 */ func alertButton(with buttonIdentifier: String) -> NXAlertButton? { let actionContentView = contentView.subviews.filter{($0 is NXActionHorizontalView) || ($0 is NXActionVerticalView)}.first let actionViews = actionContentView?.subviews.compactMap{ $0 as? NXAlertButton } return actionViews?.filter{$0.action.identifier == buttonIdentifier}.first } /** 根据弹窗的唯一识别符找到弹窗,并判断其是否显示在页面上 * parameter identifier:弹窗上的唯一识别符 * returns:是否显示 */ class func visible(withIdentifier identifier: String) -> Bool { guard let _ = visibleAlertView(withIdentifier: identifier) else { return false } return true } /** 根据弹窗的唯一识别符找到弹窗 * parameter identifier:弹窗上的唯一识别符 * returns:找到的弹窗 */ class func visibleAlertView(withIdentifier identifier: String) -> NXAlertView? { if IsCollectionEmpty(identifier) { return nil } guard let key = UnsafeRawPointer(bitPattern: ("nxalertView" + identifier).hashValue) else { return nil } guard case let window?? = UIApplication.shared.delegate?.window else { return nil } guard let alertView = objc_getAssociatedObject(window, key) as? NXAlertView else { return nil } return alertView } } <file_sep>// // NSStringExtensions.swift // SFFoundation // // Created by tangbo on 2019/1/16. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation @objc extension NSString { public func sf_trim() -> NSString { return self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) as NSString } public func sf_tencentCosImage(maxSize: CGSize, type: SFImageClipType) -> NSString { return ((self as String).sf_tencentCosImage(maxSize: maxSize, type: type)) as NSString } } @objc extension NSString { public func sf_height(maxWidth: CGFloat = CGFloat.greatestFiniteMagnitude, font: UIFont) -> CGFloat { return (self as String).height(font: font, maxWidth: maxWidth) } public func sf_width(maxWidth: CGFloat = CGFloat.greatestFiniteMagnitude, font: UIFont) -> CGFloat { return (self as String).width(font: font, maxWidth: maxWidth) } public func sf_size(maxWidth: CGFloat = CGFloat.greatestFiniteMagnitude, font: UIFont) -> CGSize { return (self as String).size(font: font, maxWidth: maxWidth) } public func sf_height(maxWidth: CGFloat = CGFloat.greatestFiniteMagnitude, font: UIFont, maxRowNum: Int) -> CGFloat { return (self as String).size(font: font, maxWidth: maxWidth, maxRowNumber: maxRowNum).height } public func sf_size(maxWidth: CGFloat = CGFloat.greatestFiniteMagnitude, font: UIFont, maxRowNum: Int) -> CGSize { return (self as String).size(font: font, maxWidth: maxWidth, maxRowNumber: maxRowNum) } } @objc extension NSString { public func sf_priceString() -> NSString? { if let double = Double.init(self as String) { return String.price(number: double) as NSString? } return nil } public class func sf_parameters(url: NSString) -> NSDictionary? { guard url.length > 0 else { return nil } return (url as String).urlParams() as NSDictionary? } } <file_sep>// // NotificationCenter.swift // SFFoundation // // Created by DoubleHH on 2018/12/20. // Copyright © 2018 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation extension NotificationCenter { /// 便利方法 public static func post(name: String, userInfo: [AnyHashable: Any]? = nil) { self.default.post(name: NSNotification.Name.init(name), object: nil, userInfo: userInfo) } /// 便利方法 public static func add(observer: Any, selector: Selector, name: String) { self.default.addObserver(observer, selector: selector, name: NSNotification.Name.init(name), object: nil) } /// 便利方法 public static func add(observer: Any, selector: Selector, name: NSNotification.Name) { self.default.addObserver(observer, selector: selector, name: name, object: nil) } } <file_sep>// // SFImageBrowserController.swift // SFImageKit // // Created by tangbo on 2018/10/23. // Copyright © 2018 S.F.Express. All rights reserved. // import UIKit import SFFoundation public protocol NXImageBrowserControllerDelegate: AnyObject { /** 点击删除的时候调用 * parameter browser: 当前图片预览对象, SFImageBrowserController * parameter index: 被删除的图片在图片数组中的位置 */ func imageBrowserController(_ browser: NXImageBrowserController, didDeleteIndex index: Int) } public extension NXImageBrowserControllerDelegate { func imageBrowserController(_ browser: NXImageBrowserController, didDeleteIndex index: Int) {} } enum NXImageBrowserType { case `default` case web } open class NXImageBrowserController: UIViewController { @IBOutlet weak var topViewTopConstraint: NSLayoutConstraint! @IBOutlet weak var topView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var deleteButton: UIButton! ///静态图片数组 var images = [UIImage]() ///网络图片的url数组 var imageUrls = [String]() ///选中的图片的index var selectedIndex: Int = 0 ///是否可删除 open var canDelete = false open weak var delegate: NXImageBrowserControllerDelegate? @IBOutlet weak var layout: UICollectionViewFlowLayout! @IBOutlet weak var collectionView: UICollectionView! private var lastZoomScrollView: UIScrollView? private var statusBarHidden: Bool = false private let transitionAnimation = ImageBrowserTransitionAnimation() private let interactiveTransition = ImageBrowserInteractiveTransition() private weak var originDelegate: UINavigationControllerDelegate? private var type = NXImageBrowserType.default private var imageCount: Int { return (type == .default) ? images.count : imageUrls.count } private var showingImageIndex: Int { return Int(collectionView.contentOffset.x / collectionView.frame.width) } open override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } open override var prefersStatusBarHidden: Bool { return statusBarHidden } class func loadFromStoryboard() -> NXImageBrowserController { return UIStoryboard(name: "ImageBrowser", bundle: Bundle(for: NXImageBrowserController.self)).instantiateViewController(withIdentifier: "SFImageBrowserController") as! NXImageBrowserController } open class func loadFromStoryboard(images: [UIImage], selectedIndex: Int = 0) -> NXImageBrowserController { let vc = NXImageBrowserController.loadFromStoryboard() vc.images = images vc.selectedIndex = selectedIndex vc.type = .default return vc } open class func loadFromStoryboard(imageUrls: [String], selectedIndex: Int = 0) -> NXImageBrowserController { let vc = NXImageBrowserController.loadFromStoryboard() vc.imageUrls = imageUrls vc.selectedIndex = selectedIndex vc.type = .web return vc } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) originDelegate = navigationController?.delegate navigationController?.delegate = self } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) navigationController?.delegate = originDelegate } override open func viewDidLoad() { super.viewDidLoad() deleteButton.isHidden = !canDelete topViewTopConstraint.constant += SF.Const.statusbarHeight let singleTapGesture = UITapGestureRecognizer(target: self, action:#selector(singleTapAction(sender:))) collectionView.addGestureRecognizer(singleTapGesture) let doubleTapGesture = UITapGestureRecognizer(target: self, action:#selector(doubleTapAction(sender:))) doubleTapGesture.numberOfTapsRequired = 2 collectionView.addGestureRecognizer(doubleTapGesture) singleTapGesture.require(toFail: doubleTapGesture) view.layoutIfNeeded() layout.itemSize = CGSize(width: collectionView.width, height: collectionView.height) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 configImages() if navigationController != nil { interactiveTransition.addPanGesture(forViewController: self) interactiveTransition.transitionAnimation = transitionAnimation } } private func configImages() { selectedIndex = max(0, selectedIndex) selectedIndex = min(imageCount - 1, selectedIndex) configTitleLabel(selectedIndex + 1) if imageCount == 0 { return } collectionView.reloadData() collectionView.scrollToItem(at: IndexPath(item: selectedIndex, section: 0), at: .centeredHorizontally, animated: false) } private func configTitleLabel(_ index: Int) { if imageCount > 0 { titleLabel.text = "\(index)"+"/"+"\(imageCount)" } else { titleLabel.text = nil } } @objc private func singleTapAction(sender: UITapGestureRecognizer) { let topViewAlpha: CGFloat = (topView.alpha == 0) ?1 :0 statusBarHidden.toggle() setNeedsStatusBarAppearanceUpdate() UIView.animate(withDuration: 0.3) { self.topView.alpha = topViewAlpha } } @objc private func doubleTapAction(sender: UITapGestureRecognizer) { guard let zoomScrollView = (collectionView.visibleCells.first as? NXImageBrowserCell)?.scrollView else { return } if zoomScrollView.zoomScale > 1 { zoomScrollView.setZoomScale(1.0, animated: true) } else { let touchPoint = collectionView.convert(sender.location(in: collectionView), to: zoomScrollView) let newZoomScale = zoomScrollView.maximumZoomScale let xsize = collectionView.width / newZoomScale let ysize = collectionView.height / newZoomScale zoomScrollView.zoom(to: CGRect(x:touchPoint.x - xsize / 2, y:touchPoint.y - ysize / 2, width:xsize, height:ysize), animated: true) } } @IBAction func backButtonClicked(_ sender: Any) { if navigationController != nil { navigationController?.popViewController(animated: true) } if presentingViewController != nil { dismiss(animated: true, completion: nil) return } } @IBAction func deleteButtonClicked(_ sender: Any) { if type == .default { images.remove(at: showingImageIndex) } else if type == .web { imageUrls.remove(at: showingImageIndex) } configImages() delegate?.imageBrowserController(self, didDeleteIndex: showingImageIndex) } } extension NXImageBrowserController: UIScrollViewDelegate { public func scrollViewDidZoom(_ scrollView: UIScrollView) { lastZoomScrollView = scrollView } public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return scrollView.subviews.first } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == collectionView { configTitleLabel(showingImageIndex + 1) lastZoomScrollView?.setZoomScale(1, animated: false) } } } extension NXImageBrowserController: UINavigationControllerDelegate { public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if interactiveTransition.isInteractive == false { return nil } if imageZooming { return nil } if operation == .pop { transitionAnimation.animationType = .pop return transitionAnimation } else if operation == .push { transitionAnimation.animationType = .push } return nil } public func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return (transitionAnimation.animationType == .pop) ? (interactiveTransition.isInteractive ? interactiveTransition : nil) : nil } } extension NXImageBrowserController { var showingImageView: UIImageView? { return (collectionView.visibleCells.first as? NXImageBrowserCell)?.imagView } var imageZooming: Bool { return lastZoomScrollView != nil && lastZoomScrollView?.zoomScale != lastZoomScrollView?.minimumZoomScale } } extension NXImageBrowserController: UICollectionViewDataSource, UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageCount } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NXImageBrowserCellId", for: indexPath) as! NXImageBrowserCell if type == .default { cell.imagView.image = images.at(indexPath.item) } else if type == .web { if let urlStr = imageUrls.at(indexPath.item), let url = URL(string: urlStr) { cell.imagView.sd_setImage(with: url) } } return cell } } class NXImageBrowserCell: UICollectionViewCell { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var imagView: UIImageView! } <file_sep>// // HomeViewController.swift // appone // // Created by tangbo on 2019/6/22. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import NXDesign import SFFoundation enum FoodOperationType { case add case sub } class HomeViewController: BaseViewController, StoryboardLoadable { static var fileInfo = StoryboardFileInfo(name: "tabbar", identifier: "home") @IBOutlet weak var menuTableView: UITableView! @IBOutlet weak var foodTableView: UITableView! @IBOutlet weak var shopCartView: UIView! @IBOutlet weak var totalPriceLabel: UILabel! @IBOutlet weak var createOrderButton: UIButton! @IBOutlet weak var bottomViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var bottomView: UIView! var totalPrice: String? var shopModel: ShopModel? var selectedFoodList = [FoodModel]() override func viewDidLoad() { super.viewDidLoad() sf_navigationBar.titleLabel.font = UIFont.boldSystemFont(ofSize: 19) sf_navigationBar.leftBarButton.isHidden = true foodTableView.register(FoodHeaderView.self, forHeaderFooterViewReuseIdentifier: "foodHeaderViewId") totalPriceLabel.textColor = Color_Main createOrderButton.setBackgroundImage(Color_Main.image(size: CGSize(width: 1, height: 1)), for: .normal) menuTableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 60 + SF.Const.screenSafeBottom, right: 0) foodTableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 60 + SF.Const.screenSafeBottom, right: 0) bottomViewHeightConstraint.constant = SF.Const.screenSafeBottom requestData() } @IBAction func commitAction(_ sender: Any) { Account.loginIfNeed { [weak self] (success) in let vc = OrderCommitViewController.loadFromNib()! vc.foodModels = self?.selectedFoodList vc.shopName = self?.shopModel?.shop_name vc.price = self?.totalPrice vc.completion = { [weak self] in self?.requestData() } self?.navigationController?.pushViewController(vc, animated: true) } } func operationModel(_ foodModel: FoodModel?, withType type: FoodOperationType) { guard let foodModel = foodModel else { return } let find = selectedFoodList.first(where:{ $0.food_id == foodModel.food_id }) switch type { case .add: if find == nil { selectedFoodList.append(foodModel) } let count = foodModel.count ?? 0 foodModel.count = count + 1 case .sub: if (find?.count ?? 0) <= 1 { selectedFoodList.remove{$0.food_id == find?.food_id} } let count = find?.count ?? 0 find?.count = count - 1 } foodTableView.reloadData() calculateTotalPrice() } func calculateTotalPrice() { shopCartView.isHidden = true bottomView.isHidden = true var total: Double = 0 for food in selectedFoodList { shopCartView.isHidden = false bottomView.isHidden = false let price = (Double(food.price ?? "") ?? 0) * Double(100) total = price * Double(food.count ?? 0) + total } totalPrice = "\(total)".centToYuan() totalPriceLabel.text = "¥ " + (totalPrice ?? "") } func requestData() { SFLoadingIndicatorView.showLoadingIndicator(for: sf_view).backgroundColor = UIColor.white XNAppInfoUpload.queryShop { (shopModel) in SFLoadingIndicatorView.dismissLoadingIndicator(for: self.sf_view) SFErrorView.removeErrorView(in: self.sf_view) if shopModel != nil { self.shopModel = shopModel self.selectedFoodList.removeAll() self.menuTableView.scrollsToTop = true self.foodTableView.scrollsToTop = true self.menuTableView.reloadData() self.foodTableView.reloadData() self.sf_navigationBar.title = shopModel?.shop_name if !IsCollectionEmpty(self.shopModel?.menu_list) { self.menuTableView.selectRow(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: .top) } self.calculateTotalPrice() } else { SFErrorView.show(with: .netError, in: self.sf_view) { [weak self] in self?.requestData() } SFToast.show(withText: ErrorMessage_default) } } } } extension HomeViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { if tableView == menuTableView { return 1 } else { return shopModel?.menu_list?.count ?? 0 } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == menuTableView { return shopModel?.menu_list?.count ?? 0 } else { let menuModel = shopModel?.menu_list?[section] return menuModel?.list?.count ?? 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView == menuTableView { let cell = tableView.dequeueReusableCell(withIdentifier: "menuCellId", for: indexPath) as! MenuCell cell.model = shopModel?.menu_list?[indexPath.row] return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "foodCellId", for: indexPath) as! FoodCell let menuModel = shopModel?.menu_list?[indexPath.section] cell.model = menuModel?.list?[indexPath.row] cell.countChanged = { [weak self] (type, model) in self?.operationModel(model, withType: type) } return cell } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if tableView == menuTableView { return nil } else { let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "foodHeaderViewId") as! FoodHeaderView let menuModel = shopModel?.menu_list?[section] view.nameLabel.text = menuModel?.menu_name return view } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView == menuTableView { foodTableView.scrollToRow(at: IndexPath(row: 0, section: indexPath.row), at: .top, animated: true) } else { let vc = FoodDetailViewController.loadFromNib()! let menuModel = shopModel?.menu_list?[indexPath.section] vc.foodModel = menuModel?.list?[indexPath.row] vc.operationCompletion = { [weak self] (type, model) in self?.operationModel(model, withType: type) } navigationController?.pushViewController(vc, animated: true) } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == foodTableView { let indexPaths = foodTableView.indexPathsForVisibleRows guard let indexPath = indexPaths?.sorted(by: { (first, second) -> Bool in first.section > second.section }).last else { return } menuTableView.selectRow(at: IndexPath(row: indexPath.section, section: 0), animated: false, scrollPosition: .middle) } } } class MenuCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! var selectedView = UIView() var model: MenuModel? { didSet { nameLabel.text = model?.menu_name } } override func awakeFromNib() { super.awakeFromNib() selectedBackgroundView = UIView() selectedBackgroundView?.backgroundColor = UIColor.white selectedView.backgroundColor = Color_Main selectedBackgroundView?.addSubview(selectedView) backgroundView = UIView() backgroundView?.backgroundColor = UIColor.hex("#fafafa") selectedView.backgroundColor = Color_Main } override func layoutSubviews() { super.layoutSubviews() selectedView.width = 2 selectedView.top = 0 selectedView.left = 0 selectedView.height = selectedBackgroundView?.height ?? 0 } } class FoodCell: UITableViewCell { @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var disCourtView: UIView! @IBOutlet weak var disCourtLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var originPriceLabel: UILabel! @IBOutlet weak var subButton: UIButton! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var countLabel: UILabel! var countChanged: ((FoodOperationType, FoodModel?)->())? var model: FoodModel? { didSet { let placeholderImage = UIColor.hex("#f8f8f8").image(size: CGSize(width: 1, height: 1)) imgView.image = placeholderImage if let img_url = model?.img_url, let url = URL(string: img_url) { imgView.sd_setImage(with: url, placeholderImage: placeholderImage) } imgView.layer.masksToBounds = true imgView.contentMode = .scaleAspectFill nameLabel.text = model?.name priceLabel.text = "¥ \(model?.price ?? "")" priceLabel.textColor = Color_Main originPriceLabel.text = model?.origin_price if !IsCollectionEmpty(model?.discourt) { disCourtView.isHidden = false disCourtView.backgroundColor = Color_Main disCourtLabel.text = model?.discourt } else { disCourtView.isHidden = true } if (model?.count ?? 0) > 0 { subButton.isHidden = false countLabel.isHidden = false countLabel.text = "\(model?.count ?? 0)" } else { subButton.isHidden = true countLabel.isHidden = true } } } @IBAction func addCountAction(_ sender: Any) { countChanged?(.add, model) } @IBAction func subCountAction(_ sender: Any) { countChanged?(.sub, model) } } class FoodHeaderView: UITableViewHeaderFooterView { let nameLabel = UILabel() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) contentView.addSubview(nameLabel) backgroundView = UIView() backgroundView?.backgroundColor = UIColor.white } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() nameLabel.sizeToFit() nameLabel.left = 0 nameLabel.centerY = contentView.height / 2 } } <file_sep>// // UIColor+Extension.swift // Knight // // Created by DoubleHH on 2018/1/10. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit extension UIColor { /// note: 如果最高位为 00,会被忽略掉,透明度不生效,默认为 1.0 public class func hex(_ color: Int64) -> UIColor { if color > 0xffffff { return UIColor(red: CGFloat((color)>>16 & 0xff)/255.0, green: CGFloat((color) >> 8 & 0xff)/255.0, blue: CGFloat((color) & 0xff)/255.0, alpha: CGFloat((color)>>24 & 0xff)/255.0) } else { return UIColor(red: CGFloat((color)>>16 & 0xff)/255.0, green: CGFloat((color) >> 8 & 0xff)/255.0, blue: CGFloat((color) & 0xff)/255.0, alpha: 1.0) } } public class func hex(color: Int64, alpha: CGFloat) -> UIColor { return UIColor(red: CGFloat((color)>>16 & 0xff)/255.0, green: CGFloat((color) >> 8 & 0xff)/255.0, blue: CGFloat((color) & 0xff)/255.0, alpha: alpha) } public class func hex(_ string: String) -> UIColor { var str = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if str.count == 0 { return UIColor() } str = str.replacingOccurrences(of: Substring("#"), with: Substring("")) str = str.replacingOccurrences(of: Substring("0x"), with: Substring("")) if str.count > 8 { return UIColor() } var alpha: CGFloat = 1.0 if str.count == 8 { let alphaStrIndex = str.index(str.startIndex, offsetBy: 2) let alphaStr = String(str[..<alphaStrIndex]) alpha = CGFloat((Int64(alphaStr, radix:16) ?? 0) & 0xff) / 255.0 str = String(str[alphaStrIndex...]) } let color: Int64 = Int64(str, radix:16) ?? 0 return UIColor.hex(color: color, alpha: alpha) } public func image(size: CGSize) -> UIImage? { let view = UIView.init(frame: CGRect(origin: CGPoint.zero, size: size)) view.backgroundColor = self UIGraphicsBeginImageContext(size) if let context = UIGraphicsGetCurrentContext() { view.layer.render(in: context) } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } <file_sep>// // UILabelExtensions.swift // Knight // // Created by DoubleHH on 2018/1/10. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit extension UILabel { public class func label(font: UIFont, color: UIColor) -> UILabel { return UILabel.internaLabel(font:font, color:color, text:nil) } public class func label(font: UIFont, color: UIColor, text: String) -> UILabel { return UILabel.internaLabel(font:font, color:color, text:text) } private class func internaLabel(font: UIFont, color: UIColor, text: String?) -> UILabel { let label = UILabel(frame: CGRect.zero) label.font = font; label.textColor = color; if let aText = text { label.text = aText; label.sizeToFit() } return label; } } <file_sep> // // OrderCommitViewController.swift // appone // // Created by tangbo on 2019/6/22. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import NXDesign import SFFoundation enum OrderCommitType { case inHome case delivery } class OrderCommitViewController: BaseViewController, StoryboardLoadable { static var fileInfo = StoryboardFileInfo(name: "tabbar", identifier: "orderCommit") var foodModels: [FoodModel]? var number: String? var price: String? var shopName: String? var completion: (()->())? var commitType = OrderCommitType.inHome @IBOutlet weak var inHomeBottomCOnstraint: NSLayoutConstraint! @IBOutlet weak var deliveryBottomConstraint: NSLayoutConstraint! @IBOutlet weak var deliveryView: UIView! @IBOutlet weak var deliveryPhoneTextField: UITextField! @IBOutlet weak var deliveryAddressTextField: UITextField! @IBOutlet weak var inhomeView: UIView! @IBOutlet weak var phoneTextField: UITextField! @IBOutlet weak var inhomeButton: UIButton! @IBOutlet weak var deliveryButton: UIButton! @IBOutlet weak var totalPriceLabel: UILabel! @IBOutlet weak var commitOrderButton: UIButton! @IBOutlet weak var foodView: UIView! @IBOutlet weak var safeViewHeightConstraint: NSLayoutConstraint! var peopleCount = "1" override func viewDidLoad() { super.viewDidLoad() sf_navigationBar.titleLabel.text = "提交订单" safeViewHeightConstraint.constant = SF.Const.screenSafeBottom totalPriceLabel.text = "¥ \(price ?? "")" totalPriceLabel.textColor = Color_Main commitOrderButton.setBackgroundImage(Color_Main.image(size: CGSize(width: 1, height: 1)), for: .normal) configFood() updateTypeButton() phoneTextField.text = Account.phone deliveryPhoneTextField.text = Account.phone let ges = UITapGestureRecognizer(target: self, action: #selector(taped)) ges.delegate = self view.addGestureRecognizer(ges) } @objc func taped() {} func configFood() { guard let foodList = foodModels else { return } var lastItemView: UIView? for food in foodList { let itemView = FoodView.loadFromNib()! foodView.addSubview(itemView) itemView.translatesAutoresizingMaskIntoConstraints = false itemView.foodModel = food itemView.leadingAnchor.constraint(equalTo: foodView.leadingAnchor).isActive = true if lastItemView != nil { itemView.topAnchor.constraint(equalTo: lastItemView!.bottomAnchor).isActive = true } else { itemView.topAnchor.constraint(equalTo: foodView.topAnchor).isActive = true } itemView.trailingAnchor.constraint(equalTo: foodView.trailingAnchor).isActive = true itemView.heightAnchor.constraint(equalToConstant: 70).isActive = true lastItemView = itemView } if lastItemView != nil { foodView?.bottomAnchor.constraint(equalTo: lastItemView!.bottomAnchor, constant: 20).isActive = true } } func commit() { if commitType == .inHome { SFToast.show(withText: "您的订单已推送到后厨,请稍等。。。") completion?() navigationController?.popViewController(animated: true) BaseViewController.tabBarController?.selectedIndex = 1 } else { let ok = NXAlertAction(okTitle: "我知道了", style: .custom(Color_Main)) { self.completion?() self.navigationController?.popViewController(animated: true) BaseViewController.tabBarController?.selectedIndex = 1 } NXAlertView().title("外卖配送").message("收到菜品后,请支付给送餐员,谢谢!").action(ok).show() } } func updateTypeButton() { let highImage = Color_Main.image(size: CGSize(width: 1, height: 1)) deliveryButton.layer.cornerRadius = 15 deliveryButton.layer.masksToBounds = true inhomeButton.layer.cornerRadius = 15 inhomeButton.layer.masksToBounds = true view.endEditing(true) switch commitType { case .delivery: inhomeButton.setBackgroundImage(nil, for: .normal) inhomeButton.setTitleColor(UIColor.hex("#999999"), for: .normal) deliveryButton.setBackgroundImage(highImage, for: .normal) deliveryButton.setTitleColor(UIColor.white, for: .normal) inhomeView.isHidden = true deliveryView.isHidden = false inHomeBottomCOnstraint.isActive = false deliveryBottomConstraint.isActive = true case .inHome: deliveryButton.setBackgroundImage(nil, for: .normal) inhomeButton.setBackgroundImage(highImage, for: .normal) deliveryButton.setTitleColor(UIColor.hex("#999999"), for: .normal) inhomeButton.setTitleColor(UIColor.white, for: .normal) deliveryView.isHidden = true inhomeView.isHidden = false deliveryBottomConstraint.isActive = false inHomeBottomCOnstraint.isActive = true } } @IBAction func typeAction(_ sender: UIButton) { if sender == inhomeButton { commitType = .inHome } else { commitType = .delivery } updateTypeButton() } @IBAction func commitAction(_ sender: Any) { if commitType == .inHome && IsCollectionEmpty(phoneTextField.text) { SFToast.show(withText: "请输入手机号") return } if commitType == .delivery { if IsCollectionEmpty(deliveryPhoneTextField.text) { SFToast.show(withText: "请输入手机号") return } if IsCollectionEmpty(deliveryAddressTextField.text) { SFToast.show(withText: "请填写配送地址") return } } var order = OrderModel() order.takeout = true if commitType == .inHome { order.number = "64644" order.takeout = false order.phone = phoneTextField.text ?? Account.phone } else { order.phone = deliveryPhoneTextField.text ?? Account.phone order.address = deliveryAddressTextField.text } order.orderId = "53452398113" order.foods = foodModels order.totalPrice = price order.status = .wait SFLoadingIndicatorView.showLoadingIndicator(for: sf_view) XNAppInfoUpload.commitOrder(order) { (success) in SFLoadingIndicatorView.dismissLoadingIndicator(for: self.sf_view) self.commit() } } } extension OrderCommitViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { view.endEditing(true) return true } } extension OrderCommitViewController: UIGestureRecognizerDelegate { func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { view.endEditing(true) return false } } <file_sep>// // SFCameraOverlayView.swift // SFImageKit // // Created by tangbo on 2018/10/25. // Copyright © 2018 S.F.Express. All rights reserved. // import UIKit import SFFoundation enum NXCameraOverlayViewState { case camera case preview } class NXCameraOverlayView: UIView { @IBOutlet weak var maskImgViewTopConstraint: NSLayoutConstraint! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var deviceButton: UIButton! @IBOutlet weak var helpButton: UIButton! @IBOutlet weak var flashButton: UIButton! @IBOutlet weak var closeButtonTopConstraint: NSLayoutConstraint! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var bottomView: UIView! @IBOutlet weak var bottomViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var bottomViewBottomCOnstraint: NSLayoutConstraint! @IBOutlet weak var commitButton: UIButton! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var deleteButton: UIButton! @IBOutlet weak var previewView: UIView! @IBOutlet weak var errorMsgView: UIView! @IBOutlet weak var errorMsgLabel: UILabel! var takePictureControl: NXCameraTakePictureView! var errorMsg: String? { didSet { errorMsgView.isHidden = IsCollectionEmpty(errorMsg) errorMsgLabel.text = ToStr(errorMsg) } } var state: NXCameraOverlayViewState = .camera { didSet { previewView.isHidden = (state == .camera) closeButton.isHidden = (state == .preview) deviceButton.isHidden = closeButton.isHidden helpButton.isHidden = closeButton.isHidden flashButton.isHidden = closeButton.isHidden deleteButton.isHidden = previewView.isHidden takePictureControl.pictureViewState = previewView.isHidden ?.camera :.picture } } var selectedImageIndex: Int { return Int(scrollView.contentOffset.x / previewView.width) } var deleteStateEnabled: Bool = false { didSet { takePictureControl.isHidden = deleteStateEnabled commitButton.isHidden = deleteStateEnabled } } private var selectedIndex: Int = 0 private var images = [UIImage]() class func loadFromNib() -> NXCameraOverlayView { return Bundle(for: NXCameraOverlayView.self).loadNibNamed("NXCameraOverlayView", owner: nil, options: nil)?.first as! NXCameraOverlayView } override func layoutSubviews() { super.layoutSubviews() takePictureControl.centerY = commitButton.centerY takePictureControl.centerX = bottomView.width / 2 takePictureControl.originCenter = CGPoint(x: bottomView.width / 2, y: commitButton.centerY) } override func awakeFromNib() { super.awakeFromNib() closeButtonTopConstraint.constant = (SF.Const.screenSafeBottom > 0) ? 44 :0 maskImgViewTopConstraint.constant = (SF.Const.screenSafeBottom > 0) ? 44 :0 bottomViewBottomCOnstraint.constant += SF.Const.screenSafeBottom collectionView.register(NXCameraOverlayViewCell.self, forCellWithReuseIdentifier: "SFCameraOverlayViewCellId") errorMsgView.layer.masksToBounds = true errorMsgView.layer.cornerRadius = 15 NotificationCenter.default.addObserver(self, selector: #selector(orientationDidChangeNotification), name: UIDevice.orientationDidChangeNotification, object: nil) takePictureControl = NXCameraTakePictureView() bottomView.addSubview(takePictureControl) } func translationY(cameraHeight: CGFloat) -> CGFloat { let topMarign = SF.Const.screenHeight - bottomViewHeightConstraint.constant - cameraHeight let dif = topMarign - closeButtonTopConstraint.constant - 34 if topMarign > 0 && dif < 0 { bottomViewHeightConstraint.constant = SF.Const.screenHeight - cameraHeight - SF.Const.screenSafeBottom bottomView.layoutIfNeeded() return 0 } return SF.Const.screenHeight - cameraHeight - bottomViewHeightConstraint.constant - SF.Const.screenSafeBottom } func previewSelectIndex(_ index: Int, images: [UIImage]) { if images.count == 0 { return } selectedIndex = max(0, index) selectedIndex = min(images.count - 1, index) self.images = images scrollView.removeAllSubviews() var lastImgView: UIImageView? for image in images { let imgView = UIImageView(image: image) imgView.contentMode = .scaleAspectFit scrollView.addSubview(imgView) imgView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ NSLayoutConstraint(item: imgView, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: imgView, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottom, multiplier: 1, constant: 0), NSLayoutConstraint(item: imgView, attribute: .width, relatedBy: .equal, toItem: previewView, attribute: .width, multiplier: 1, constant: 0), NSLayoutConstraint(item: imgView, attribute: .height, relatedBy: .equal, toItem: previewView, attribute: .height, multiplier: 1, constant: 0) ]) if lastImgView == nil { NSLayoutConstraint.activate([NSLayoutConstraint(item: imgView, attribute: .leading, relatedBy: .equal, toItem: scrollView, attribute: .leading, multiplier: 1, constant: 0)]) } else { NSLayoutConstraint.activate([NSLayoutConstraint(item: imgView, attribute: .leading, relatedBy: .equal, toItem: lastImgView!, attribute: .trailing, multiplier: 1, constant: 0)]) } lastImgView = imgView } NSLayoutConstraint.activate([NSLayoutConstraint(item: lastImgView!, attribute: .trailing, relatedBy: .equal, toItem: scrollView, attribute: .trailing, multiplier: 1, constant: 0)]) scrollView.setContentOffset(CGPoint(x: CGFloat(selectedIndex) * previewView.width, y: 0), animated: false) } @objc private func orientationDidChangeNotification() { var buttonTransform: CGAffineTransform = .identity switch UIDevice.current.orientation { case .landscapeLeft: buttonTransform = CGAffineTransform(rotationAngle: CGFloat.pi / 2) case .landscapeRight: buttonTransform = CGAffineTransform(rotationAngle: CGFloat.pi / 2 * -1) default: buttonTransform = .identity } UIView.animate(withDuration: 0.3) { self.commitButton.transform = buttonTransform self.helpButton.transform = buttonTransform self.flashButton.transform = buttonTransform self.deviceButton.transform = buttonTransform self.closeButton.transform = buttonTransform } } } extension NXCameraOverlayView: UIScrollViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if selectedImageIndex > collectionView.numberOfItems(inSection: 0) { return } print(selectedImageIndex) collectionView.selectItem(at: IndexPath(item: selectedImageIndex, section: 0), animated: true, scrollPosition: .centeredHorizontally) } } <file_sep>// // MainViewController.swift // appone // // Created by tangbo on 2019/6/22. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import SFFoundation import NXDesign class XNMainViewController: UIViewController { var rootViewController: UIViewController? { willSet { rootViewController?.willMove(toParent: nil) rootViewController?.view.removeFromSuperview() rootViewController?.removeFromParent() } didSet { guard let viewController = self.rootViewController else { return } addChild(viewController) viewController.view.frame = view.bounds viewController.view.clipsToBounds = true viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(viewController.view) viewController.didMove(toParent: self) let animation = CATransition() animation.duration = 0.25 animation.type = CATransitionType.fade animation.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.linear) view.layer.add(animation, forKey: nil) } } override func viewDidLoad() { super.viewDidLoad() SFLoadingIndicatorView.showLoadingIndicator(for: view)?.backgroundColor = UIColor.white XNAppInfoUpload.queryConfig(){ _ in } XNAppInfoUpload.queryConfig() { [weak self] model in SFLoadingIndicatorView.dismissLoadingIndicator(for: self?.view) if model?.show_web == true && !IsCollectionEmpty(model?.web_url) { self?.rootViewController = WebViewViewController(url: model?.web_url ?? "") } else { let nvc = SFNavigationController(rootViewController: TabBarViewController()) self?.rootViewController = nvc } } } } extension BaseViewController { static var tabBarController: TabBarViewController? { get { guard let nvc = mainViewController?.rootViewController as? SFNavigationController else { return nil } return nvc.viewControllers.first as? TabBarViewController } } static var mainViewController: XNMainViewController? { get { guard let window = UIApplication.shared.delegate?.window else { return nil} return window?.rootViewController as? XNMainViewController } } } <file_sep>// // SFImageUploaderController.swift // SFImageKit // // Created by tangbo on 2018/10/23. // Copyright © 2018 S.F.Express. All rights reserved. // import UIKit import AVKit public protocol NXImageUploaderControllerDelegate: AnyObject { /** 当设置userCustomResult为true之后,需要在此方法解析json数据,并返回图片的url, userCustomResult为false时,不用实现此方法 * parameter uploader: 当前图片上传对象, NXImageUploaderController * parameter responseData: 图片上传完成后,返回的json数据,需要解析并得到图片的url */ func imageUploaderController(_ uploader: NXImageUploaderController?, itemImageDidFinishUpload responseData: Data?) -> String? /** 在添加或者删除需要上传的图片后,整个图片上传区域的高度会发生变化,因此需要你在此方法中对承载NXImageUploaderController的视图的frame做出相应的改变 * parameter uploader: 当前图片上传对象, NXImageUploaderController * parameter height: 在添加或者删除需要上传的图片后,图片上传区域的最新高度 */ func imageUploaderController(_ uploader: NXImageUploaderController?, heightChanged height: CGFloat) } public extension NXImageUploaderControllerDelegate { func imageUploaderController(_ uploader: NXImageUploaderController?, itemImageDidFinishUpload responseData: Data?) -> String? {return ""} func imageUploaderController(_ uploader: NXImageUploaderController?, heightChanged height: CGFloat) {} } open class NXImageUploaderController: UIViewController { ///每行展示的图片个数 public var column: CGFloat = 4 ///最多拍摄张数,默认10张 open var maxCount: Int = 5 ///已上传的图片的url数组 public var imageUrls: [String]? { return view.subviews.compactMap{($0 as? NXUploadableImageView)?.imageUrl} } ///是否存在正在上传的图片 public var imageUploading: Bool { return view.subviews.filter{($0 as? NXUploadableImageView)?.state == .uploading}.count > 0 } ///是否存在上传失败的图片 public var imageUploadFailed: Bool { return view.subviews.filter{($0 as? NXUploadableImageView)?.state == .fail}.count > 0 } ///每列图片之间的左右间隔 public var minimumInteritemSpacing: CGFloat = 10 ///每行图片之间的上下间隔 public var minimumLineSpacing: CGFloat = 15 ///图片上传的显示样式,具体参见NXUploadableImageViewStyle的介绍 public var uploadItemViewStyle = NXUploadableImageViewStyle.default ///是否自己解析图片上传完成后的json数据 public var userCustomResult: Bool = false ///配置图片上传的网络参数,具体参见NXImageUploaderConfigration的介绍 public var configuration = NXImageUploader.default.configuration ///配置加号的icon public var addIconImage: UIImage? { didSet { addImgView.iconImage = addIconImage } } public weak var delegate:NXImageUploaderControllerDelegate? private var currentUploadImageView: NXUploadableImageView? private let addImgView = NXAddImageView() open class func loadFromStoryboard() -> NXImageUploaderController { return UIStoryboard(name: "ImageUploader", bundle: Bundle(for: NXImageUploaderController.self)).instantiateViewController(withIdentifier: "NXImageUploaderController") as! NXImageUploaderController } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() reloadItemViews() } override open func viewDidLoad() { super.viewDidLoad() view.addSubview(addImgView) addImgView.delegate = self } func addUploadImgeView(image: UIImage) { let uploadView = NXUploadableImageView(type: uploadItemViewStyle) uploadView.configuration = configuration uploadView.frame = CGRect(x: 100, y: 100, width: 70, height: 70) view.addSubview(uploadView) uploadView.deleteBlock = { [weak self] in self?.reloadItemViews() } uploadView.showImageBlock = { [weak self] (image) in self?.showImage(image: image) } if userCustomResult { uploadView.completionBlock = {[weak self] (data) -> String? in return self?.delegate?.imageUploaderController(self, itemImageDidFinishUpload: data) } } uploadView.upload(image: image) } func showImage(image: UIImage?) { if image == nil { return } let images = view.subviews.compactMap{($0 as? NXUploadableImageView)?.imgView.image} let index = images.firstIndex(of: image!) ?? 0 let vc = NXImageBrowserController.loadFromStoryboard(images: images, selectedIndex: index) if let nvc = navigationController { nvc.pushViewController(vc, animated: true) return } present(vc, animated: true, completion: nil) } func reloadItemViews() { let subviewsCount = view.subviews.count if subviewsCount == 0 || column == 0 { return } let uploadImgCount = view.subviews.filter{$0 is NXUploadableImageView}.count var itemWidth: CGFloat = (view.frame.width - (column - 1) * minimumInteritemSpacing) / column let minItemWidth: CGFloat = (uploadItemViewStyle == .default) ? 70 : 60 itemWidth = max(itemWidth, minItemWidth) let items = view.subviews.filter{ $0 is NXUploadableImageView } var lastItemView: UIView? for item in items { var left = (lastItemView == nil) ? 0 : ((lastItemView?.frame.maxX ?? 0) + minimumInteritemSpacing) var top = (lastItemView == nil) ? 0 : (lastItemView?.frame.minY ?? 0) if left + itemWidth > view.frame.width { left = 0 top += (minimumLineSpacing + itemWidth) } item.frame = CGRect(x: left, y: top, width: itemWidth, height: itemWidth) lastItemView = item } addImgView.isHidden = (maxCount <= uploadImgCount) let addImgViewWidth = (uploadItemViewStyle == .default) ? (itemWidth - 10) : itemWidth let addImgViewTopMargin: CGFloat = (uploadItemViewStyle == .default) ? 5 : 0 let addImgViewLeftMargin: CGFloat = (uploadItemViewStyle == .default) ? 5 : 0 var addImgViewLeft = (lastItemView == nil) ? 0 : ((lastItemView?.frame.maxX ?? 0) + minimumInteritemSpacing + addImgViewLeftMargin) var addImgViewTop = (lastItemView == nil) ? addImgViewTopMargin : ((lastItemView?.frame.minY ?? 0) + addImgViewTopMargin) if addImgViewLeft + addImgViewWidth > view.frame.width { addImgViewLeft = addImgViewLeftMargin addImgViewTop += (minimumLineSpacing + itemWidth) lastItemView = addImgView } if lastItemView == nil { lastItemView = addImgView } addImgView.frame = CGRect(x: addImgViewLeft, y: addImgViewTop, width: addImgViewWidth, height: addImgViewWidth) delegate?.imageUploaderController(self, heightChanged: lastItemView?.frame.maxY ?? 0) } } extension NXImageUploaderController: NXAddImageViewDelegate { public var pickerImageCount: Int { return maxCount - view.subviews.filter{$0 is NXUploadableImageView}.count } public func addImageView(_ view: NXAddImageView, didSelectImages images: [UIImage]) { for image in images { if let resizedimage = image.resizedImage(1500) { addUploadImgeView(image: resizedimage) } } reloadItemViews() } } <file_sep>// // NXAlertMessageView.swift // NXDesign // // Created by tangbo on 2019/4/28. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit import SFFoundation class NXAlertMessageView: UIView, UITableViewDataSource, UITableViewDelegate { private let tableView = UITableView() private var messages: [String]? private var indexSize = CGSize() init(frame: CGRect, messages: [String]) { super.init(frame: frame) configMessages(messages) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configMessages(_ messages: [String]) { var maxIndexLabelWidth: CGFloat = 0 var maxIndexLabelHeight: CGFloat = 0 for (index, _) in messages.enumerated() { let indexSize = "\(index + 1)、".size(font: UIFont.systemFont(ofSize: 14)) maxIndexLabelWidth = max(indexSize.width, maxIndexLabelWidth) maxIndexLabelHeight = max(indexSize.height, maxIndexLabelHeight) } var contentSumHeight: CGFloat = 0 for (_, content) in messages.enumerated() { let contentHeight = content.size(font: UIFont.systemFont(ofSize: 14), maxWidth: frame.width - maxIndexLabelWidth - 4).height + CGFloat(10) contentSumHeight = contentSumHeight + contentHeight } self.indexSize = CGSize(width: maxIndexLabelWidth, height: maxIndexLabelHeight) self.messages = messages tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 10 tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none tableView.register(UINib(nibName: "NXAlertMessageTableViewCell", bundle: Bundle(for: NXAlertMessageView.self)), forCellReuseIdentifier: "NXAlertMessageTableViewCellId") addSubview(tableView) tableView.reloadData() height = contentSumHeight } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "NXAlertMessageTableViewCellId", for: indexPath) as! NXAlertMessageTableViewCell cell.indexLabel.text = "\(indexPath.row + 1)、" cell.contentLabel.text = messages?[indexPath.row] cell.indexSize = indexSize return cell } override func layoutSubviews() { super.layoutSubviews() tableView.frame = bounds } } <file_sep>// // SFLocalizableUtil.swift // // Created by tianweitao on 2019/1/23. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation open class SFLocalizableUtil: NSObject { @objc public static func localizableString(key: String, defaultVaule: String = "", table: String? = nil, bundle: Bundle = Bundle.main) -> String { var localizedString = "" let language = systemLanguage() ?? "" if language.hasPrefix("zh") || language.hasPrefix("en") { localizedString = bundle.localizedString(forKey: key, value: defaultVaule, table: table) } else { let enBundle = Bundle.init(path: bundle.path(forResource: "en", ofType: "lproj") ?? "") ?? bundle localizedString = enBundle.localizedString(forKey: key, value: defaultVaule, table: table) } return localizedString.count > 0 ? localizedString : key } @objc public static func systemLanguage() -> String? { return UserDefaults.standard.array(forKey: "AppleLanguages")?.first as? String } @objc public static func currentLanguage() -> String { let language = systemLanguage() ?? "" if language.hasPrefix("zh") { return "zh" } else { return "en" } } } <file_sep>// // SFScanAlertVC.swift // SFScanCodeKit // // Created by Leo on 2018/12/24. // Copyright © 2018 S.F.Express. All rights reserved. // import UIKit import SFFoundation enum SFScanAlertType { case input case authorization } protocol SFScanAlertDelegate: AnyObject { func scanAlert(_ scanAlertVC: SFScanAlertViewController, didConfirm code: String) func scanAlertCancel(_ scanAlertVC: SFScanAlertViewController) } class SFScanAlertViewController: UIViewController, SFScanCodeKitLoadProtocol { static var nibInfo: NibInfo = NibInfo(identifier: "SFScanAlertViewController", name: nil) weak var delegate: SFScanAlertDelegate? var type: SFScanAlertType = .input var inputAlert: SFScanAlertInputView? var authorityAlert: SFScanCodeAuthorityAlert? var themeColor: UIColor = UIColor.hex(0x26CEA8) static func show(delegate: SFScanAlertDelegate & SFViewController, type: SFScanAlertType, themeColor: UIColor) { if type == .input { let inputVC = SFScanAlertViewController.loadFromNib() inputVC.modalPresentationStyle = .overFullScreen inputVC.delegate = delegate inputVC.type = .input inputVC.themeColor = themeColor delegate.present(inputVC, animated: false, completion: nil) } else { let inputVC = SFScanAlertViewController.loadFromNib() inputVC.modalPresentationStyle = .overFullScreen inputVC.type = .authorization inputVC.themeColor = themeColor delegate.present(inputVC, animated: false, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() if type == .input { configNoti() configInputUI() } else { configAuthorityUI() } } override func viewDidAppear(_ animated: Bool) { if type == .input { inputAlert?.stopEdting(false) } } private func configNoti() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } private func configInputUI() { inputAlert = SFScanAlertInputView.loadFromNib() inputAlert!.center = CGPoint(x: SF.Const.screenWidth / 2, y: SF.Const.screenHeight / 2) inputAlert!.delegate = self inputAlert!.confirmButton.setTitleColor(themeColor, for: .normal) view.addSubview(inputAlert!) } private func configAuthorityUI() { authorityAlert = SFScanCodeAuthorityAlert.loadFromNib() authorityAlert!.center = CGPoint(x: SF.Const.screenWidth / 2, y: SF.Const.screenHeight / 2) authorityAlert!.delegate = self authorityAlert!.confirmButton.setTitleColor(themeColor, for: .normal) view.addSubview(authorityAlert!) } private func inputAlertAnimation(_ directionUp: Bool, _ keyboardHeight: CGFloat) { let destination = directionUp ? (SF.Const.screenHeight - keyboardHeight) / 2 : SF.Const.screenHeight / 2 UIView.animate(withDuration: 0.2, animations: { [weak self] in self?.inputAlert?.centerY = destination }) { _ in } } private func dismiss() { dismiss(animated: false, completion: nil) } } //MARK: - Notifications extension SFScanAlertViewController { @objc private func keyboardShow(_ noti: Notification) { let userInfo = noti.userInfo let keyboardRect = userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect inputAlertAnimation(true, keyboardRect?.size.height ?? 0) } @objc private func keyboardHide(_ noti: Notification) { let userInfo = noti.userInfo let keyboardRect = userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect inputAlertAnimation(false, keyboardRect?.size.height ?? 0) } } extension SFScanAlertViewController: SFScanAlertInputProtocol, SFScanCodeAuthorityAlertDelegate { func scanInputAlertCancel(_ inputAlertView: SFScanAlertInputView) { dismiss() delegate?.scanAlertCancel(self) } func scanInputAlert(_ inputAlertView: SFScanAlertInputView, input code: String) { dismiss() delegate?.scanAlert(self, didConfirm: code) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { inputAlert?.stopEdting(true) } func didClickCancel(alertView: SFScanCodeAuthorityAlert) { dismiss() } func didClickOk(alertView: SFScanCodeAuthorityAlert) { let settingURL = URL(string: UIApplication.openSettingsURLString)! if UIApplication.shared.canOpenURL(settingURL) { UIApplication.shared.openURL(settingURL) } dismiss() } } <file_sep>// // UIViewControllerSlideable.swift // havitms // // Created by Panda on 2018/8/15. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit public class SFSlideOverControllerContext: NSObject, UIGestureRecognizerDelegate { var transitionView: UIView = UIView() var backgroundView: UIView = UIView() var tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer.init() var currentOverViewController: (UIViewController & UIViewControllerOverable)? public override init() { super.init() tapGestureRecognizer.addTarget(self, action: #selector(handle(_:))) tapGestureRecognizer.delegate = self } @objc private func handle(_ tapGesture: UITapGestureRecognizer) { currentOverViewController?.slideOverController?.dismissOverViewController(animated: true, completion: nil) } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return touch.view == backgroundView ? true: false } } public struct SFOverViewControllerContext { public var preferredSize: CGSize public var orientation: SFSlideOverOrientation = .fromBottom public init(_ preferredSize: CGSize, orientation: SFSlideOverOrientation = .fromBottom) { self.preferredSize = preferredSize } } public enum SFSlideOverOrientation { case fromLeft, fromRight, fromTop, fromBottom } private enum SFOverViewControllerState { case show, dismiss } public protocol UIViewControllerSlidable where Self: UIViewController { var slideContext: SFSlideOverControllerContext { get set } func slide(_ overViewController: UIViewController & UIViewControllerOverable, orientation: SFSlideOverOrientation, animated: Bool, completion: (() -> ())?) func dismissOverViewController(animated: Bool, completion: (() -> ())?) } public protocol UIViewControllerOverable where Self: UIViewController { var slideOverContext: SFOverViewControllerContext { get set } var slideOverController: (UIViewController & UIViewControllerSlidable)? { get } } extension UIViewControllerSlidable { private func p_frame(_ overViewController: UIViewController & UIViewControllerOverable, state: SFOverViewControllerState) -> CGRect { var frame: CGRect = .init(origin: .zero, size: overViewController.slideOverContext.preferredSize) switch overViewController.slideOverContext.orientation { case .fromLeft: frame.origin.x = (state == .dismiss) ? -frame.width: 0 frame.size.height = slideContext.transitionView.frame.height case .fromRight: frame.origin.x = (state == .dismiss) ? slideContext.transitionView.frame.width: slideContext.transitionView.frame.width - frame.width frame.size.height = slideContext.transitionView.frame.height case .fromTop: frame.origin.y = (state == .dismiss) ? -frame.height: 0 frame.size.width = slideContext.transitionView.frame.width case .fromBottom: frame.origin.y = (state == .dismiss) ? slideContext.transitionView.frame.height: slideContext.transitionView.frame.height - frame.height frame.size.width = slideContext.transitionView.frame.width } return frame } private func p_updateCurrentOverViewController(_ state: SFOverViewControllerState, animated: Bool, completion: (() -> ())?) { guard let currentOverViewController = slideContext.currentOverViewController else { return } slideContext.transitionView.isHidden = false slideContext.backgroundView.isHidden = false UIView.animate(withDuration: animated ? 0.25: 0, animations: { [self] in self.slideContext.backgroundView.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: state == .show ? 0.4: 0) currentOverViewController.view.frame = self.p_frame(currentOverViewController, state: state) }) { [self] (finished) in if state == .dismiss { self.p_removeCurrentOverViewController() if finished { self.slideContext.transitionView.isHidden = true self.slideContext.backgroundView.isHidden = true } } completion?() } } private func p_removeCurrentOverViewController() { guard let currentOverViewController = slideContext.currentOverViewController else { return } currentOverViewController.willMove(toParent: nil) currentOverViewController.view.removeFromSuperview() currentOverViewController.removeFromParent() slideContext.currentOverViewController = nil } private func p_add(_ overViewController: UIViewController & UIViewControllerOverable) { if slideContext.currentOverViewController != nil { p_removeCurrentOverViewController() } slideContext.transitionView.frame = view.bounds slideContext.transitionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(slideContext.transitionView) slideContext.transitionView.addGestureRecognizer(slideContext.tapGestureRecognizer) slideContext.backgroundView.frame = slideContext.transitionView.bounds slideContext.backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight] slideContext.transitionView.addSubview(slideContext.backgroundView) slideContext.currentOverViewController = overViewController addChild(overViewController) overViewController.view.frame = p_frame(overViewController, state: .dismiss) overViewController.view.clipsToBounds = true overViewController.view.autoresizingMask = (overViewController.slideOverContext.orientation == .fromLeft || overViewController.slideOverContext.orientation == .fromRight) ? .flexibleWidth: .flexibleHeight slideContext.transitionView.addSubview(overViewController.view) overViewController.didMove(toParent: self) } public func slide(_ overViewController: UIViewController & UIViewControllerOverable, orientation: SFSlideOverOrientation, animated: Bool, completion: (() -> ())?) { var overViewController = overViewController overViewController.slideOverContext.orientation = orientation p_add(overViewController) p_updateCurrentOverViewController(.show, animated: true, completion: completion) } public func dismissOverViewController(animated: Bool, completion: (() -> ())?) { p_updateCurrentOverViewController(.dismiss, animated: animated, completion: completion) } } extension UIViewControllerOverable { public var slideOverController: (UIViewController & UIViewControllerSlidable)? { get { return self.parent as? UIViewController & UIViewControllerSlidable } } } <file_sep>// // StoryboardLoadable.swift // SAASMerchant // // Created by Panda on 2018/6/26. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit public struct StoryboardFileInfo { var name: String var identifier: String? var bundle: Bundle public init(name: String, identifier: String? = nil, bundle: Bundle = .main) { self.name = name self.identifier = identifier self.bundle = bundle } } public protocol StoryboardLoadable { static var fileInfo: StoryboardFileInfo { get } } extension StoryboardLoadable where Self: UIViewController { public static func loadFromNib() -> Self? { return UIStoryboard.init(name: fileInfo.name, bundle: fileInfo.bundle).instantiateViewController(withIdentifier: fileInfo.identifier ?? String(describing: Self.self)) as? Self } } <file_sep>// // AppInfoUpload.swift // appone // // Created by tangbo on 2019/6/24. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import SFFoundation struct XNAppInfoUpload { static func saveConfig() { if let objId = UserDefaults.standard.value(forKey: "kAppConfigId") as? String, !IsCollectionEmpty(objId) { return } let model = ConfigModel(new_version: "1.0.0", web_url: "https://www.baidu.com", show_web: false, upgrade: true, title: "新版本发布了!", content: "新版本发布了!", appstoreid: AppKey_appId) guard let obj = BmobObject(className: "config") else { return } obj.setObject(model.new_version, forKey: "new_version") obj.setObject(model.web_url, forKey: "web_url") obj.setObject(model.show_web, forKey: "show_web") obj.setObject(model.upgrade, forKey: "upgrade") obj.setObject(model.title, forKey: "title") obj.setObject(model.content, forKey: "content") obj.setObject(model.appstoreid, forKey: "appstoreid") obj.saveInBackground { (success, error) in if success { if let objId = obj.objectId { UserDefaults.standard.setValue(objId, forKey: "kAppConfigId") } } } } static func queryConfig(completion: @escaping ((ConfigModel?)->())) { // guard let objId = UserDefaults.standard.value(forKey: "kAppConfigId") as? String else { // saveConfig() // return // } guard let query = BmobQuery(className: "config") else { return } query.getObjectInBackground(withId: Bmob_configId) { (object, error) in if error == nil { let version = object?.object(forKey: "new_version") as? String let web_url = object?.object(forKey: "web_url") as? String let show_web = object?.object(forKey: "show_web") as? Bool let upgrade = object?.object(forKey: "upgrade") as? Bool let title = object?.object(forKey: "title") as? String let content = object?.object(forKey: "content") as? String let appstoreid = object?.object(forKey: "appstoreid") as? String let configModel = ConfigModel(new_version: version, web_url: web_url, show_web: show_web, upgrade: upgrade, title: title, content: content, appstoreid: appstoreid) ConfigModel.updateDiskCache(configModel) completion(configModel) } else { completion(nil) } } } static func formattCategory() -> [CategoryModel]? { guard let path = Bundle.main.path(forResource: "category", ofType: "json") else { return nil } guard let str = try? String(contentsOfFile: path, encoding: .utf8) else { return nil } guard let data = str.data(using: .utf8) else { return nil } let categorys = try? SFJSONDecoder().decode([CategoryModel]?.self, from: data) return categorys } static func formattFood() -> [FoodJsonModel]? { guard let path = Bundle.main.path(forResource: "food", ofType: "json") else {return nil} guard let str = try? String(contentsOfFile: path, encoding: .utf8) else { return nil} guard let data = str.data(using: .utf8) else { return nil} let foods = try? SFJSONDecoder().decode([FoodJsonModel]?.self, from: data) return foods } static func formatShop() -> ShopModel? { guard let categorys = formattCategory(), let foods = formattFood() else { return nil } var menuList = [MenuModel]() for category in categorys { let menuModel = MenuModel() menuModel.menu_name = category.Name let findfoods = foods.filter {$0.FoodCatagoryID == category.FoodCatagoryID} menuModel.list = findfoods.compactMap { (model) -> FoodModel in let food = FoodModel() food.name = model.Name food.food_id = model.FoodID food.img_url = "http://img2.daojia.com.cn\(model.Picture ?? "")" food.big_img_url = "http://img2.daojia.com.cn\(model.BigPicture ?? "")" food.price = model.Price return food } menuList.append(menuModel) } let shop = ShopModel() shop.menu_list = menuList shop.shop_name = APPStore_name return shop } static func saveShop(completion: @escaping (ShopModel?)->()) { if let shopId = UserDefaults.standard.value(forKey: "kShopId") as? String, !IsCollectionEmpty(shopId) { return } guard let shop = formatShop() else { return } completion(shop) guard let shopData = try? SFJSONEncoder().encode(shop) else { return } let shopJson = String(data: shopData, encoding: .utf8) guard let obj = BmobObject(className: "shopInfo") else { return } obj.setObject(shopJson, forKey: "shopInfoJson") obj.saveInBackground { (success, error) in if success { if let objId = obj.objectId { UserDefaults.standard.setValue(objId, forKey: "kShopId") } } } } static func queryShop(completion: @escaping (ShopModel?)->()) { // if let objId = UserDefaults.standard.value(forKey: "kShopId") as? String { guard let query = BmobQuery(className: "shopInfo") else { return } query.getObjectInBackground(withId: Bmob_shopInfoId) { (object, error) in if error != nil { UserDefaults.standard.setValue(nil, forKey: "kShopId") } let shopInfoJson = object?.object(forKey: "shopInfoJson") as? String var shopInfo: ShopModel? if let data = shopInfoJson?.data(using: .utf8) { shopInfo = try? SFJSONDecoder().decode(ShopModel.self, from: data) } completion(shopInfo) } // } else { // saveShop(completion: completion) // } } static func commitOrder(_ order: OrderModel?, completion: @escaping ((Bool)->())) { guard let order = order else { return } guard let data = try? SFJSONEncoder().encode(order) else { return } let str = String(data: data, encoding: .utf8) guard let obj = BmobObject(className: "order") else { return } obj.setObject(str, forKey: "orderInfo") obj.setObject(Account.phone, forKey: "phone") obj.saveInBackground { (success, error) in completion(success) } } static func queryOrderList(completion: @escaping (([OrderModel]?, Bool)->())) { guard let phone = Account.phone else { return completion(nil, false)} var orderList = [OrderModel]() guard let query = BmobQuery(className: "order") else { return } query.whereKey("phone", equalTo: phone) query.selectKeys(["orderInfo"]) query.findObjectsInBackground { (objs, error) in if let objects = objs { for obj in objects { if let obj = obj as? BmobObject { if let orderInfo = obj.object(forKey: "orderInfo") as? String { if let data = orderInfo.data(using: .utf8) { if let order = try? SFJSONDecoder().decode(OrderModel.self, from: data) { orderList.append(order) } } } } } } completion(orderList, error == nil) } } } class CategoryModel: Codable { var Name: String? var FoodCatagoryID: String? } class FoodJsonModel: Codable { var Name: String? var FoodID: String? var Price: String? var Picture: String? var BigPicture: String? var FoodCatagoryID: String? } <file_sep>// // ImageConpress.swift // NXDesign // // Created by DoubleHH on 2019/6/15. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation public extension UIImage { func compressedDataForUpload() -> Data? { return jpegData(compressionQuality: 0.8) } } <file_sep>// // NSArrayExtensions.swift // SFFoundation // // Created by 孔六五 on 2019/1/17. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation @objc extension NSArray { public func safelyAccessObject(atIndex: Int) -> Any? { guard atIndex >= 0, self.count > atIndex else {return nil} return self.object(at:atIndex) } } <file_sep>// // WaterFlowCollectionViewLayout.swift // NXDesign // // Created by DoubleHH on 2019/6/16. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation ///瀑布流的 UICollectionViewLayout,只需要实现 HeightBlock 用于获取每个cell高度 public class WaterFlowCollectionViewLayout: UICollectionViewLayout { /// 根据IndexPath计算cell高度,需要实现 public typealias HeightBlock = ((_ indexPath: IndexPath) -> CGFloat) private var heightBlk: HeightBlock private static let defaultColumn = 2 private var column: Int = defaultColumn /// 瀑布流的列数,默认2 public var columnCount: Int { get { return column } set { column = max(1, newValue) updateCellWidth() } } /// 瀑布流每列之间的间距,默认10 public var horizontalCellInterval: CGFloat = 10 { didSet { updateCellWidth() } } /// 瀑布流竖向的间距,默认10 public var verticalCellInterval: CGFloat = 10 { didSet { updateCellWidth() } } /// 瀑布流四周(所有cell)的间距,上下左右,默认都是10 public var collectionMargin: UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) { didSet { updateCellWidth() } } /** 瀑布流Cell的宽度,当设置各种间距的属性时会立马根据屏幕宽度计算。 该值的作用,比如cell的宽高比要跟图片宽高比一样,那么你就需要知道cell的宽度计算cell的高度 */ private(set) var cellWidth: CGFloat = 0 private var columnHeights: [CGFloat] = [] private var attrs: [UICollectionViewLayoutAttributes] = [] /// 初始化方法,参数是高度计算的BLOCK public init(heightBlk: @escaping HeightBlock) { self.heightBlk = heightBlk super.init() self.columnCount = WaterFlowCollectionViewLayout.defaultColumn } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func prepare() { super.prepare() columnHeights.removeAll() for _ in 0..<column { columnHeights.append(collectionMargin.top) } refreshAttributes() } private func updateCellWidth() { cellWidth = (UIScreen.main.bounds.size.width - collectionMargin.left - collectionMargin.right - horizontalCellInterval * CGFloat((column - 1))) / CGFloat(column) } private func refreshAttributes() { let items = collectionView?.numberOfItems(inSection: 0) ?? 0 var res: [UICollectionViewLayoutAttributes] = [] for index in 0..<items { let indexPath = IndexPath(item: index, section: 0) let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath) let shortestInfo = findShortestColumn() let cellHeight = heightBlk(indexPath) let x = collectionMargin.left + CGFloat(shortestInfo.index) * (cellWidth + horizontalCellInterval) let y = shortestInfo.value + verticalCellInterval attr.frame = CGRect(x: x, y: y, width: cellWidth, height: cellHeight) columnHeights[shortestInfo.index] = y + cellHeight res.append(attr) } attrs = res } private func findShortestColumn() -> (index: Int, value: CGFloat) { var res = (index: 0, value: CGFloat.greatestFiniteMagnitude) for (index, value) in columnHeights.enumerated() { if res.value > value { res.index = index res.value = value } } return res } override public var collectionViewContentSize: CGSize { let maxHeight = columnHeights.reduce(0) { (res, value) -> CGFloat in return max(res, value) } return CGSize(width: collectionView?.width ?? 0, height: max(collectionView?.height ?? 0, maxHeight + collectionMargin.bottom)) } override public func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return attrs[indexPath.item] } override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let attrsInRect = attrs.filter { (attr) -> Bool in return rect.intersects(attr.frame) } return attrsInRect } override public func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } } <file_sep>// // SFScanTorchHandle.swift // SFScanCodeKit // // Created by Leo on 2018/12/28. // Copyright © 2018 S.F.Express. All rights reserved. // import AVKit import SFFoundation extension SFScanCodeViewController { func turn() { guard let device = AVCaptureDevice.default(for: .video) else { if isTorchOn { isTorchOn = false } SFToast.show(withText: "手电筒不可用") return } if !device.isTorchAvailable || !device.hasFlash || !device.hasTorch { if isTorchOn { isTorchOn = false } SFToast.show(withText: "手电筒不可用") return } do { try device.lockForConfiguration() device.torchMode = isTorchOn ? .off : .on isTorchOn = !isTorchOn device.unlockForConfiguration() } catch { isTorchOn = false SFToast.show(withText: "手电筒不可用") return } } } <file_sep>// // AboutViewController.swift // appone // // Created by tangbo on 2019/6/29. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import SFFoundation import NXDesign class AboutViewController: BaseViewController, StoryboardLoadable { static var fileInfo = StoryboardFileInfo(name: "tabbar", identifier: "about") @IBOutlet weak var versionLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() sf_navigationBar.title = "关于" versionLabel.text = "V \(SFDevice.version() ?? "1.0")" nameLabel.text = APPStore_name } } <file_sep>// // CodableExtensions.swift // Knight // // Created by Panda on 2018/2/5. // Copyright © 2018年 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation extension Encodable { public func toDictionary() -> Dictionary<String, CustomStringConvertible>? { guard let data: Data = try? SFJSONEncoder().encode(self) else { return nil } return data.toDictionary() } } <file_sep>// // NXAddImageView.swift // NXDesign // // Created by tangbo on 2019/1/30. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import UIKit import AVKit extension UIView { var viewController: UIViewController? { let nextRes = next if let vc = nextRes as? UIViewController { return vc } return (nextRes as? UIView)?.viewController } } public protocol NXAddImageViewDelegate: AnyObject { /** 需要拍照的图片数量 */ var pickerImageCount: Int { get } /** 用户拍完照片或者从相册选择完照片的回调 * parameter view: 当前对象, NXAddImageView * parameter images: 用户拍的照片或者从相册选择的照片 */ func addImageView(_ view: NXAddImageView, didSelectImages images: [UIImage]) } public extension NXAddImageViewDelegate { var pickerImageCount: Int { return 1 } func addImageView(_ view: NXAddImageView, didSelectImages images: [UIImage]) {} } @IBDesignable open class NXAddImageView: UIView { ///设置加号icon的图片 @IBInspectable var iconImage: UIImage? { didSet { iconImageView.image = iconImage } } public weak var delegate: NXAddImageViewDelegate? private let iconImageView = UIImageView(image: UIImage(named: "icon_upload_photo", in: Bundle(for: NXAddImageView.self), compatibleWith: nil)) private let control = UIControl() private var dashLayer: CAShapeLayer! private var imageSourceHandler: ImageSourceHandler! public override init(frame: CGRect) { super.init(frame: frame) configUI() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configUI() } private func configUI() { imageSourceHandler = ImageSourceHandler(choosedImageCallback: { [weak self] (images) in guard let sself = self else { return } sself.delegate?.addImageView(sself, didSelectImages: images) }, maxImageCount: delegate?.pickerImageCount ?? 1) addSubview(control) control.addTarget(self, action: #selector(controlClicked), for: .touchUpInside) addSubview(iconImageView) } @objc func controlClicked() { imageSourceHandler.showSourceChoices() } open override func layoutSubviews() { super.layoutSubviews() control.frame = bounds iconImageView.frame = CGRect(x: 0, y: 0, width: 30, height: 30) iconImageView.center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2) if dashLayer == nil { dashLayer = CAShapeLayer() layer.addSublayer(dashLayer) dashLayer.strokeColor = UIColor.hex("#E6E6E6").cgColor dashLayer.fillColor = UIColor.clear.cgColor dashLayer.lineWidth = 1.5 dashLayer.lineDashPattern = [4, 2] } dashLayer.path = UIBezierPath(rect: bounds).cgPath } } <file_sep>// // Authority.swift // NXDesign // // Created by DoubleHH on 2019/6/15. // Copyright © 2019 Beijing SF Intra-city Technology Co., Ltd. All rights reserved. // import Foundation import AVKit public struct Authority { ///检查相机权限是否开启,发现未开启则返回false,并toast错误 public static func checkOpenAndToastErrorIfCameraUnavailable() -> Bool { let authStatus = AVCaptureDevice.authorizationStatus(for: .video) if authStatus == .restricted || authStatus == .denied { NXToast.show(text: "请在设置里打开相机权限") return false } if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { SFAlertView.alert(withTitle:"提示", message:"相册不可用", cancelButtonTitle: nil, okButtonTitle: "确定", cancelAction: nil, okAction: nil) return false } return true } }
8f6dbcf92d9340d5a664dc37de1c1c307878d816
[ "Swift", "C", "Shell" ]
90
Swift
tangbo124/xiaoniu
7299f9afe4113312af34aa98cc5283b9b8afe1e1
d4532202baf9f12322eeb5df7a7305669102f1da
refs/heads/master
<repo_name>cacheop/gaussian_naive_bayes<file_sep>/src/classifier.cpp #include <iostream> #include <sstream> #include <fstream> #include <math.h> #include <vector> #include "classifier.h" const double LANE_WIDTH = 4.0; const int NUM_FEATURES = 4; void add_feature(vector<vector<double>> &feature_data, const std::vector<double> data_input) { vector <double> temp_data = data_input; temp_data[1] = data_input[1] / LANE_WIDTH; feature_data.push_back(temp_data); } vector<double> calculate_mean(vector<vector<double>> feature_data){ vector<double> mean_values(NUM_FEATURES); std::size_t num_elements = feature_data.size(); for (std::size_t i=0; i < num_elements; i++){ vector <double> temp_data = feature_data[i]; for (int j = 0; j < NUM_FEATURES; j++){ mean_values[j] += temp_data[j]; } } for (int j = 0; j < NUM_FEATURES; j++){ mean_values[j] /= num_elements; } return mean_values; } vector<double> calculate_stddev(vector<vector<double>> feature_data, vector<double> mean_values) { vector<double> sigma_values(NUM_FEATURES); std::size_t num_elements = feature_data.size(); for (std::size_t i=0; i < num_elements; i++){ vector <double> temp_data = feature_data[i]; for (int j = 0; j < NUM_FEATURES; j++){ sigma_values[j] += pow((temp_data[j] - mean_values[j]),2) / num_elements; } } for (int j = 0; j < NUM_FEATURES; j++){ sigma_values[j] = sqrt(sigma_values[j]); } return sigma_values; } double calculate_prob(vector<double> feature_data, vector<double> means, vector<double> stddev) { double temp_var= 1.0; double pdf_gaussian = 1.0; // Since this is Naive Bayes, we consider the // prob(x1,x2,x3,x4 | class) = p(x1|class) * p(x2|class) * p(x3|lass) * p(x4|class) for (int i = 0; i < NUM_FEATURES; i++) { double x = feature_data[i]; double mean = means[i]; double sigma = stddev[i]; temp_var = (1 / (sigma * sqrt(2 * M_PI))) * exp(-0.5 * pow(((x - mean) / sigma), 2.0 )); pdf_gaussian *= temp_var; } return pdf_gaussian; } /** * Initializes GNB */ GNB::GNB() { } GNB::~GNB() {} void GNB::train(vector<vector<double>> data, vector<string> labels) { /* Trains the classifier with N data points and labels. INPUTS data - array of N observations - Each observation is a tuple with 4 values: s, d, s_dot and d_dot. - Example : [ [3.5, 0.1, 5.9, -0.02], [8.0, -0.3, 3.0, 2.2], ... ] labels - array of N labels - Each label is one of "left", "keep", or "right". */ vector<vector<double>> feature_data_left; vector<vector<double>> feature_data_keep; vector<vector<double>> feature_data_right; for (int i=0; i < labels.size(); i++) { cout << labels[i] << endl; vector<double> data_input = data[i]; if (labels[i] == "left") add_feature(feature_data_left, data_input); else if (labels[i] == "keep") add_feature(feature_data_keep, data_input); else if (labels[i] == "right") add_feature(feature_data_right, data_input); } left_means = calculate_mean(feature_data_left); left_stddev = calculate_stddev(feature_data_left, left_means); keep_means = calculate_mean(feature_data_keep); keep_stddev = calculate_stddev(feature_data_keep, keep_means); right_means = calculate_mean(feature_data_right); right_stddev = calculate_stddev(feature_data_right, right_means); std::cout<< "\nTraining Complete...\n"<< std::endl; } string GNB::predict(vector<double> sample) { /* Once trained, this method is called and expected to return a predicted behavior for the given observation. INPUTS observation - a 4 tuple with s, d, s_dot, d_dot. - Example: [3.5, 0.1, 8.5, -0.2] OUTPUT A label representing the best guess of the classifier. Can be one of "left", "keep" or "right". """ # TODO - complete this */ vector<double> prob_classes; prob_classes.push_back(calculate_prob(sample, left_means, left_stddev)); prob_classes.push_back(calculate_prob(sample, keep_means, keep_stddev)); prob_classes.push_back(calculate_prob(sample, right_means, right_stddev)); int idx = 0; double best_p = 0; for (int p = 0; p < prob_classes.size(); p++) { if (prob_classes[p] > best_p) { best_p = prob_classes[p]; idx = p; } } return possible_labels[idx]; } <file_sep>/README.md # Self driving cars: implementing Naive Bayes to predict lane changes. In this exercise you will implement a Gaussian Naive Bayes classifier to predict the behavior of vehicles on a highway. In the image below you can see the behaviors you'll be looking for on a 3 lane highway (with lanes of 4 meter width). The dots represent the d (y axis) and s (x axis) coordinates of vehicles as they either... 1. change lanes left (shown in blue) 2. keep lane (shown in black) 3. or change lanes right (shown in red) ![alt text](https://github.com/cacheop/gaussian_naive_bayes/blob/master/naive-bayes.png?raw=true") Your job is to write a classifier that can predict which of these three maneuvers a vehicle is engaged in given a single coordinate (sampled from the trajectories shown below). Each coordinate contains 4 features: - s - d - dot s - dot d You also know the lane width is 4 meters (this might be helpful in engineering additional features for your algorithm). ## Instructions 1. Implement the `train(self, data, labels)` method in the class `GNB` in `classifier.cpp`. Training a Gaussian Naive Bayes classifier consists of computing and storing the mean and standard deviation from the data for each label/feature pair. For example, given the label "change lanes left” and the feature s˙\dot{s}s˙, it would be necessary to compute and store the mean and standard deviation of s˙\dot{s}s˙ over all data points with the "change lanes left” label. Additionally, it will be convenient in this step to compute and store the prior probability p(C_k) for each label C_k. This can be done by keeping track of the number of times each label appears in the training data. 2. Implement the predict(self, observation) method in classifier.cpp. Given a new data point, prediction requires two steps: 1. Compute the conditional probabilities for each feature/label combination. For a feature `x` and label `C` with mean μ\muμ and standard deviation σ\sigmaσ (computed in training), the conditional probability can be computed using the formula here: ![alt text](https://github.com/cacheop/gaussian_naive_bayes/blob/master/p1.png?raw=true") Here `v` is the value of feature xxx in the new data point. 2. Use the conditional probabilities in a Naive Bayes classifier. This can be done using the formula here: ![alt text](https://github.com/cacheop/gaussian_naive_bayes/blob/master/p2.png?raw=true") In this formula, the argmax is taken over all possible labels CkC_kCk​ and the product is taken over all features `C(k)` with values `v(i)`. NOTE: The raw value of the `d` coordinate may not be that useful. But `d % lane_width` might be helpful since it gives the relative position of a vehicle in it's lane regardless of which lane the vehicle is in.
14c0c68acb4535fbbf74c436e4a6e99433368081
[ "Markdown", "C++" ]
2
C++
cacheop/gaussian_naive_bayes
cf78739dced873f53ee563f3f6646684b13269b1
105f0e91bba00fd017a4b61d9a83b15d11f53cf6
refs/heads/master
<file_sep>import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import GridContainer from "components/Grid/GridContainer.js"; import GridItem from "components/Grid/GridItem.js"; import Card from "components/Card/Card" import styles from "assets/jss/material-kit-react/views/components.js"; const useStyles = makeStyles(styles); export default function ServicesSection (props){ const classes = useStyles(); return( <div style={{color: 'white', backgroundColor:'#232424', height: '600px'}} className={classes.main} > <GridContainer > <div className={classes.typo}> <GridItem> <div style={{flexDirection:'column'}} justify="center"> <div> <h3 style={{fontWeight: 'bold', color:'gray'}}>SERVICES</h3> </div> <Card> <div style={{ color:'white', backgroundColor:'#232424'}}> <h4>Strategy</h4> <div> <h5>Research & Data</h5> <h5>Branding & Positioning</h5> <h5>Business Consulting</h5> <h5>Go To Market</h5> <h5>Innovation</h5> </div> </div> </Card> <Card color="transparent"> <div style={{ color:'white', backgroundColor:'#232424'}}> <h4 >Design</h4> <div> <h5>User Research & Testing</h5> <h5>UX Design</h5> <h5>Visual Design</h5> <h5>Editorial Design</h5> <h5>Innovation</h5> </div> </div> </Card> {/* <Card color="transparent"> <div style={{ color:'white', backgroundColor:'#232424'}}> <h4 >Content</h4> <div> <h5>Copywriting</h5> <h5>Social Media</h5> <h5>Interactive Media</h5> <h5>Motion Design</h5> <h5>Illustration</h5> <h5>Photography & Video</h5> </div> </div> </Card> <Card color="transparent"> <div style={{ color:'white', backgroundColor:'#232424'}}> <h4 >Technology</h4> <div> <h5>Application Development</h5> <h5>Web Development</h5> <h5>Enterprise CMS</h5> <h5>Emerging Tech</h5> <h5>eCommerce</h5> <h5>CRM</h5> </div> </div> </Card> */} </div> </GridItem> </div> </GridContainer> </div> ); };<file_sep>import React from 'react'; // import classNames from "classnames"; import { makeStyles } from '@material-ui/core/styles'; // Component import Header from "components/Header/Header.js"; import HeaderLinks from "components/Header/HeaderLinks" import styles from "assets/jss/material-kit-react/views/components.js"; const useStyles = makeStyles(styles); export default function CustomNavBar(props){ const classes = useStyles(); const { ...rest } = props; return( <div id="navbar" className={classes.navbar}> <div> <Header brand="Roomie IT" rightLinks={<HeaderLinks />} fixed color="transparent" changeColorOnScroll={{ height: 700, color: "dark" }} {...rest} /> </div> </div> ); }; <file_sep>import React from 'react'; // import classNames from "classnames"; import { makeStyles } from '@material-ui/core/styles'; import GridContainer from "components/Grid/GridContainer.js"; import GridItem from "components/Grid/GridItem.js"; import ImageBack from "assets/img/office.jpg" import styles from "assets/jss/material-kit-react/views/components.js"; const useStyles = makeStyles(styles); export default function ImageBody(props){ const classes = useStyles(); return( <div> <div className={classes.section}> <GridContainer> <GridItem> <img src={ImageBack} alt='off' width="100%" /> </GridItem> </GridContainer> </div> </div> ); } <file_sep>import React from 'react'; import classNames from "classnames"; import { makeStyles } from "@material-ui/core/styles"; // Components import CustomNavBar from "components/CustomComponetsPage/CustomNavBar"; import ImageParallax from "components/CustomComponetsPage/Imageparalax"; import TextMiddle from "components/CustomComponetsPage/TextMiddle"; import ImageVideoPart from "components/CustomComponetsPage/ImageVideoPart"; import TextMiddleTwo from "components/CustomComponetsPage/TextMiddleTwo"; import ImageBody from "components/CustomComponetsPage/ImageBody"; import ServicesSection from "components/CustomComponetsPage/ServicesSection" // Sections import styles from "assets/jss/material-kit-react/views/components.js"; const useStyles = makeStyles(styles); export default function LandingPage(props) { const classes = useStyles(); // const { ...rest } = props; return ( <div> <CustomNavBar/> <ImageParallax/> <div className={classNames(classes.main)}> <TextMiddle/> <ImageVideoPart/> <TextMiddleTwo/> <ImageBody/> </div> <ServicesSection/> </div> ) };<file_sep>import React from "react"; import ReactDOM from "react-dom"; import { createBrowserHistory } from "history"; import { Router, Route, Switch } from "react-router-dom"; import "assets/scss/material-kit-react.scss?v=1.8.0"; <file_sep>import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { Player } from 'video-react'; import GridContainer from "components/Grid/GridContainer.js"; import GridItem from "components/Grid/GridItem.js"; import Card from "components/Card/Card.js"; import styles from "assets/jss/material-kit-react/views/componentsSections/carouselStyle.js"; const useStyles = makeStyles(styles); export default function ImageVideoPart(props){ const classes = useStyles(); return( <GridContainer> <GridItem xs={12} md={8} className={classes.marginAuto} > <Card> <Player playsInline poster="/src/assets/img/home.jpg" src="https://s3.amazonaws.com/cdn.prpl.rs/media/sizzle_supercut.mp4" /> </Card> </GridItem> </GridContainer> ); };
25da9a9471ef0d09a3e9026b0c8268cc7e8e1f15
[ "JavaScript" ]
6
JavaScript
znokdieline/roomiepage
b3870c8072481900cab7fc68146a0365f57ccdc6
25ef211ec0d1fae2463314b92fa188568ee120f6
refs/heads/master
<repo_name>dark-swordsman/battleship<file_sep>/index.js const express = require('express'); const app = express(); app.use('/', express.static('./src')); app.listen(7331, function(){ console.log("Battleship is running on: 7331"); }); <file_sep>/src/indexPage.js /***************************************** TODO Facts: - the same number board is for the same player for example: board1 is player 1's ship board, and board1s is player 1's attack board player 1 attacks player 2, so his board1s corresponds to the attacks on board2, and vice versa TODO Ideas: - board(1,2,1s,2s)[row][column] TODO event log: - fill board with ships - start game *****************************************/ var board1, board2, board1s, board2s; board1 = board2 = board1s = board2s = new Array(10); function fillBoard(board){ for(var i = 0; i < 10; i++){ board[i] = new Array(10); for(var j = 0; j < 10; j++){ board[i][j] = false; } } } var boards = [board1, board2, board1s, board2s]; for(var i = 0; i < 4; i++){ fillBoard(boards[i]); } var players = { "human":{ "ships":{ "carrier":{ "length": 5, "isPlaced": false, "name":"carrier" }, "battleship":{ "length": 4, "isPlaced": false, "name":"battleship" }, "submarine":{ "length": 3, "isPlaced": false, "name":"submarine" }, "cruiser":{ "length": 3, "isPlaced": false, "name":"cruiser" }, "destroyer":{ "length": 2, "isPlaced": false, "name":"destroyer" } } }, "cpu":{ "ships":{ "carrier":{ "length": 5, "isPlaced": false, "name":"carrier" }, "battleship":{ "length": 4, "isPlaced": false, "name":"battleship" }, "submarine":{ "length": 3, "isPlaced": false, "name":"submarine" }, "cruiser":{ "length": 3, "isPlaced": false, "name":"cruiser" }, "destroyer":{ "length": 2, "isPlaced": false, "name":"destroyer" } } } } function placeShip(ship, player){ //false means horizontal, true means vertical var rotation; var location; var board; function detectClick(x, y){ rotation = window.confirm("Ship: " + ship.name + ". Vertical (OK) or Horizontal (Cancel)?"); board = board1; console.log(x + " AND " + y); var isTaken = false; // check if the spot is already there for(var i = y; i < (ship.length + y); i++){ if(board[i][x] === true){ isTaken = true; } } if(isTaken === true){ window.alert("This spot is already taken. Please Try Again"); placeShip(ship, player); }else if(isTaken === false){ if(rotation === true){ for(var i = y; i < (ship.length + y); i++){ board[i][x] = true; } }else if(rotation === false){ for(var i = x; i < (ship.length + x); i++){ board[y][i] = true; } } } ship.isPlaced = true; } if(player === 'h'){ // LOGIC TO MAKE HTML GRID clickable var css = '#board1 td:hover{ background-color: grey }'; var style = document.createElement('style'); style.innerHTML = css; document.getElementById('body').appendChild(style); for(var i = 0; i < htmlX.length; i++){ for(var j = 0; j < 10; j++){ htmlX[i].children[j].onclick = function(){ detectClick(i, j); } } } // LOGIC TO FIND CLICK }else if(player === 'c'){ // TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO // cpu logic // TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO board = board2; } } function placeAllShips(player){ var playerIs; if(player === players.human.ships){ playerIs = 'h'; }else{ playerIs = 'c'; } placeShip(player.carrier, playerIs); placeShip(player.battleship, playerIs); placeShip(player.submarine, playerIs); placeShip(player.cruiser, playerIs); placeShip(player.destroyer, playerIs); } // Make the boards clickable!!!!!!!!!!!!!!!!!!! var htmlX = new Array(10); for(var i = 0; i < htmlX.length; i++){ htmlX[i] = document.getElementById('board1').childNodes[1].children[i]; } // TODO x locations are defined, but y locations are dervied from htmlX. // for example, htmlX[0].chilren[0] is the first column in the first box, AKA (1,1); // place the ships!!! var hS = players.human.ships; var cS = players.cpu.ships; var placeShipsButton = document.getElementById('placeShips'); placeShipsButton.onclick = function(){ placeAllShips(hS); }
6d8a535244f3bd9497d97d3d52620bee02fd44bf
[ "JavaScript" ]
2
JavaScript
dark-swordsman/battleship
da251547e1d000e85cab3d1f7562827100f99343
a47b2d48ca4b5d0673be7416f44e7acabec21a6b