<commit_before>
//模态内容消失
function display(){
	var sc = document.getElementById('school');
	var nm = document.getElementById('name');
	document.getElementById('modalMask').style.display = 'none';
	document.getElementById('chooseSchool').style.display = 'none';

}

//获取学校列表
function scList(){
	var sc = document.getElementById('school');
	//var nm = document.getElementById('name');
	var schoolChoise = document.getElementById('modelContent').getElementsByTagName('ul')[0];
	sc.onclick = function(){
			this.getElementsByTagName('input')[0].disabled = "disabled";
			document.getElementById('modalMask').style.display = 'block';
			document.getElementById('chooseSchool').style.display = 'block';
			document.getElementById('list').value='';
			ajax('http://localhost/newmeeting/index.php/meeting/getschool','',function(data){
			var data = JSON.parse(data);
			schoolChoise.innerHTML='';
			for(var i=0;i<data.length;i++){

				var li = document.createElement('li');
				li.innerHTML = data[i].school;
				//li.className="btn btn-default btn-block";
				schoolChoise.appendChild(li);

			}
			var choice = document.getElementsByTagName('li');
			for(var i=0;i<choice.length;i++){
				choice[i].onclick = function(){
				//alert(1);
				sc.getElementsByTagName('input')[0].value = this.firstChild.nodeValue;
				ajax('http://localhost/newmeeting/index.php/meeting/getname',this.firstChild.nodeValue,displayName);				                                //发送学校的名字到学校对应的URL，返回对应的姓名
				display();

				}
			}
			});

			}

	document.getElementById('list').onclick = searchData;
	document.getElementById('modelContent').getElementsByTagName('span')[0].onclick = display;
	document.getElementById('modalMask').onclick = display;

}

//生成姓名并可自己编辑
function displayName(data){
	var nm = document.getElementById('name');
	var choice = document.getElementsByTagName('li');
	var data = JSON.parse(data);
	var schoolChoise = document.getElementById('modelContent').getElementsByTagName('ul')[0];
	var error = document.getElementById('modelContent').getElementsByTagName('span')[1];
	nm.getElementsByTagName('input')[0].value='';
	nm.onclick = function(){
			schoolChoise.innerHTML = "";

			this.getElementsByTagName('input')[0].disabled = "disabled";
			document.getElementById('modalMask').style.display = 'block';
			document.getElementById('chooseSchool').style.display = 'block';
			if(data){
				schoolChoise.innerHTML = "";
				for(var i=0;i<data.length;i++){
				var li = document.createElement('li');
				li.innerHTML = data[i].name;
				//li.className="btn btn-default btn-block";
				schoolChoise.appendChild(li);
				error.innerHTML="";
				var choice = document.getElementsByTagName('li');
				//var schoolData;
				choice[i].onclick = function(){
					if(this.firstChild.nodeValue!='null'){
					nm.getElementsByTagName('input')[0].value = this.firstChild.nodeValue;
				}
					display();
					ajax('http://localhost/newmeeting/index.php/meeting/examine','this.firstChild.nodeValue',
						function(data){
							var data = JSON.parse(data);
							if(data[0].time=='1'){
								alert('已签到');
							}
						});
					/*if(data[i].time=1){
						own.style.display='none';
						other.style.display='none';
						alert('已签到');
					}     */

				}
				}
			}
			else{
				error.innerHTML = "未找到相关姓名";
				error.style.fontSize = "3em";
				error.style.fontWeight = "bolder";
				error.style.textAlign = "center";
			}
		}
	}

//快速搜索
function searchData(){
	var list = document.getElementById('list');
	list.oninput=function (event) {
		ajax('http://localhost/newmeeting/index.php/meeting/schoolsearch',this.value,loadSchool);  //发送输入的关键字获得可能的学校名字
	}
}

//检查快速搜索内容输出
function loadSchool(data){
	var sc = document.getElementById('school');
	var data = JSON.parse(data);
	var schoolChoise = document.getElementById('modelContent').getElementsByTagName('ul')[0];
	var choice = document.getElementsByTagName('li');
	schoolChoise.innerHTML = "";
	var error = document.getElementById('modelContent').getElementsByTagName('span')[1];
	if(data){
		for(var i=0;i<data.length;i++){
			var li = document.createElement('li');
			li.innerHTML = data[i].school;
			schoolChoise.appendChild(li);
			//li.className="btn btn-default btn-block";
			error.innerHTML="";
		}
	}else{

		error.innerHTML = "未找到相关内容，请检查后重新输入";
		error.style.fontSize = "3em";
		error.style.fontWeight = "bolder";
		error.style.textAlign = "center";
	}
	var choice = document.getElementsByTagName('li');
	for(var i=0;i<choice.length;i++){
				var schoolData;
				choice[i].onclick = function(){
					sc.getElementsByTagName('input')[0].value = this.firstChild.nodeValue;
					display();

				}
			}
}

//数据传输函数
function ajax(url,data,fun,argument){                            //只有这的url不用更改，是一个参数，其余的URL 都要改
	var sc = document.getElementById('school');
	var nm = document.getElementById('name');
	var ajax = new XMLHttpRequest();

	ajax.open("POST",url,true);
	ajax.setRequestHeader('Content-Type','application/x-www-form-urlencode');
	ajax.send(data);
	//alert(data);
	ajax.onreadystatechange = function(){
		if(ajax.readyState == 4){
			if((ajax.status >=200 && ajax.status < 300) || (ajax.status == 304)){
				//alert(ajax.responseText);
				fun(ajax.responseText);
			}else{
				alert("错误：ajax.status")
			}
		}
	}
}
// 提交表单
function postList(judge){
	var sc = document.getElementById('school');
	var nm = document.getElementById('name');
	var own = document.getElementById('bt1');
	var other = document.getElementById('bt2');
	var time = Date.parse(new Date());
	var listData = nm.getElementsByTagName('input')[0].value+","+time+","+judge;
	if(!sc.getElementsByTagName('input')[0].value||!nm.getElementsByTagName('input')[0].value){
		alert("请选择您的学校");
	}
	else{
		sc.getElementsByTagName('input')[0].style.border="1.5px solid #46b3f1";
		nm.getElementsByTagName('input')[0].style.border="1.5px solid #46b3f1";
		//alert(listData);
		if(judge==1){
			ajax('http://localhost/newmeeting/index.php/meeting/submit',listData,function (data){
			alert("签到");
			check(data);

		});
		}
		if(judge==0){
			ajax('http://localhost/newmeeting/index.php/meeting/submit',listData,function (data){
			alert("代签");
			check(data);
		});
	}
	}
	//listData = JSON.parse(listData);                  //发送学校+名字

}

function check(data){
	var own = document.getElementById('bt1');
	var other = document.getElementById('bt2');
	data = JSON.parse(data);
		               //签到时间
	if(data[0].time>0){
		own.style.width="80%";
		own.style.backgroundColor="#46b3f1";
		other.style.display='none';
		own.removeAttribute('onclick');
		own.innerHTML="查看会务信息";
		//own.style.display='none';
		own.onclick=function()
{
window.location.href="http://localhost/newmeeting/index.php/other";
}

	}else{
		own.style.backgroundColor="#46b3f1";
		other.style.backgroundColor="#46b3f1";

	}
}

window.onload = scList;
//document.getElementsByTagName('li').className='btn';
//window.onload = displayName;
//document.getElementById('bt1').onclick = postList(1);
//document.getElementById('bt2').onclick = postList(0);<commit_msg>Update index.js<commit_after>
//模态内容消失
function display(){
	var sc = document.getElementById('school');
	var nm = document.getElementById('name');
	document.getElementById('modalMask').style.display = 'none';
	document.getElementById('chooseSchool').style.display = 'none';

}

//获取学校列表
function scList(){
	var sc = document.getElementById('school');
	//var nm = document.getElementById('name');
	var schoolChoise = document.getElementById('modelContent').getElementsByTagName('ul')[0];
	sc.onclick = function(){
			this.getElementsByTagName('input')[0].disabled = "disabled";
			document.getElementById('modalMask').style.display = 'block';
			document.getElementById('chooseSchool').style.display = 'block';
			document.getElementById('list').value='';
			ajax('http://localhost/newmeeting/index.php/meeting/getschool','',function(data){
			var data = JSON.parse(data);
			schoolChoise.innerHTML='';
			for(var i=0;i<data.length;i++){

				var li = document.createElement('li');
				li.innerHTML = data[i].school;
				//li.className="btn btn-default btn-block";
				schoolChoise.appendChild(li);

			}
			var choice = document.getElementsByTagName('li');
			for(var i=0;i<choice.length;i++){
				choice[i].onclick = function(){
				//alert(1);
				sc.getElementsByTagName('input')[0].value = this.firstChild.nodeValue;
				ajax('http://localhost/newmeeting/index.php/meeting/getname',this.firstChild.nodeValue,displayName);				                                //发送学校的名字到学校对应的URL，返回对应的姓名
				display();

				}
			}
			});

			}

	document.getElementById('list').onclick = searchData;
	document.getElementById('modelContent').getElementsByTagName('span')[0].onclick = display;
	document.getElementById('modalMask').onclick = display;

}

//生成姓名并可自己编辑
function displayName(data){
	var nm = document.getElementById('name');
	var choice = document.getElementsByTagName('li');
	var data = JSON.parse(data);
	var schoolChoise = document.getElementById('modelContent').getElementsByTagName('ul')[0];
	var error = document.getElementById('modelContent').getElementsByTagName('span')[1];
	nm.getElementsByTagName('input')[0].value='';
	nm.onclick = function(){
			schoolChoise.innerHTML = "";

			this.getElementsByTagName('input')[0].disabled = "disabled";
			document.getElementById('modalMask').style.display = 'block';
			document.getElementById('chooseSchool').style.display = 'block';
			if(data){
				schoolChoise.innerHTML = "";
				for(var i=0;i<data.length;i++){
				var li = document.createElement('li');
				li.innerHTML = data[i].name;
				//li.className="btn btn-default btn-block";
				schoolChoise.appendChild(li);
				error.innerHTML="";
				var choice = document.getElementsByTagName('li');
				//var schoolData;
				choice[i].onclick = function(){
					if(this.firstChild.nodeValue!='null'){
					nm.getElementsByTagName('input')[0].value = this.firstChild.nodeValue;
				}
					display();
					ajax('http://localhost/newmeeting/index.php/meeting/examine',this.firstChild.nodeValue,
						function(data){
							var data = JSON.parse(data);
							if(data[0].time=='1'){
								alert('已签到');
							}
						});
					/*if(data[i].time=1){
						own.style.display='none';
						other.style.display='none';
						alert('已签到');
					}     */

				}
				}
			}
			else{
				error.innerHTML = "未找到相关姓名";
				error.style.fontSize = "3em";
				error.style.fontWeight = "bolder";
				error.style.textAlign = "center";
			}
		}
	}

//快速搜索
function searchData(){
	var list = document.getElementById('list');
	list.oninput=function (event) {
		ajax('http://localhost/newmeeting/index.php/meeting/schoolsearch',this.value,loadSchool);  //发送输入的关键字获得可能的学校名字
	}
}

//检查快速搜索内容输出
function loadSchool(data){
	var sc = document.getElementById('school');
	var data = JSON.parse(data);
	var schoolChoise = document.getElementById('modelContent').getElementsByTagName('ul')[0];
	var choice = document.getElementsByTagName('li');
	schoolChoise.innerHTML = "";
	var error = document.getElementById('modelContent').getElementsByTagName('span')[1];
	if(data){
		for(var i=0;i<data.length;i++){
			var li = document.createElement('li');
			li.innerHTML = data[i].school;
			schoolChoise.appendChild(li);
			//li.className="btn btn-default btn-block";
			error.innerHTML="";
		}
	}else{

		error.innerHTML = "未找到相关内容，请检查后重新输入";
		error.style.fontSize = "3em";
		error.style.fontWeight = "bolder";
		error.style.textAlign = "center";
	}
	var choice = document.getElementsByTagName('li');
	for(var i=0;i<choice.length;i++){
				var schoolData;
				choice[i].onclick = function(){
					sc.getElementsByTagName('input')[0].value = this.firstChild.nodeValue;
					display();

				}
			}
}

//数据传输函数
function ajax(url,data,fun,argument){                            //只有这的url不用更改，是一个参数，其余的URL 都要改
	var sc = document.getElementById('school');
	var nm = document.getElementById('name');
	var ajax = new XMLHttpRequest();

	ajax.open("POST",url,true);
	ajax.setRequestHeader('Content-Type','application/x-www-form-urlencode');
	ajax.send(data);
	//alert(data);
	ajax.onreadystatechange = function(){
		if(ajax.readyState == 4){
			if((ajax.status >=200 && ajax.status < 300) || (ajax.status == 304)){
				//alert(ajax.responseText);
				fun(ajax.responseText);
			}else{
				alert("错误：ajax.status")
			}
		}
	}
}
// 提交表单
function postList(judge){
	var sc = document.getElementById('school');
	var nm = document.getElementById('name');
	var own = document.getElementById('bt1');
	var other = document.getElementById('bt2');
	var time = Date.parse(new Date());
	var listData = nm.getElementsByTagName('input')[0].value+","+time+","+judge;
	if(!sc.getElementsByTagName('input')[0].value||!nm.getElementsByTagName('input')[0].value){
		alert("请选择您的学校");
	}
	else{
		sc.getElementsByTagName('input')[0].style.border="1.5px solid #46b3f1";
		nm.getElementsByTagName('input')[0].style.border="1.5px solid #46b3f1";
		//alert(listData);
		if(judge==1){
			ajax('http://localhost/newmeeting/index.php/meeting/submit',listData,function (data){
			alert("签到");
			check(data);

		});
		}
		if(judge==0){
			ajax('http://localhost/newmeeting/index.php/meeting/submit',listData,function (data){
			alert("代签");
			check(data);
		});
	}
	}
	//listData = JSON.parse(listData);                  //发送学校+名字

}

function check(data){
	var own = document.getElementById('bt1');
	var other = document.getElementById('bt2');
	data = JSON.parse(data);
		               //签到时间
	if(data[0].time>0){
		own.style.width="80%";
		own.style.backgroundColor="#46b3f1";
		other.style.display='none';
		own.removeAttribute('onclick');
		own.innerHTML="查看会务信息";
		//own.style.display='none';
		own.onclick=function()
{
window.location.href="http://localhost/newmeeting/index.php/other";
}

	}else{
		own.style.backgroundColor="#46b3f1";
		other.style.backgroundColor="#46b3f1";

	}
}

window.onload = scList;
//document.getElementsByTagName('li').className='btn';
//window.onload = displayName;
//document.getElementById('bt1').onclick = postList(1);
//document.getElementById('bt2').onclick = postList(0);
<|endoftext|>


<commit_before>const lib = {
    "kaomoji": {
        "sparkles": [
            "✧･ﾟ: *✧･ﾟ:* 　　 *:･ﾟ✧*:･ﾟ✧",
            "*＊✿❀　❀✿＊*"
        ],
        "bears": [
            "ʕ •ᴥ•ʔ",
            "ᶘಠᴥಠᶅ"
        ],
        "cats": [
            "ฅ(＾・ω・＾ฅ)",
            `චᆽච`
        ],
        "dogs": [
            "▼・ᴥ・▼",
            "U・ᴥ・U"
        ],
        "jailed": [
            "||Φ|(|ﾟ|∀|ﾟ|)|Φ||",
            "━━━━||Φ|(|´|Д|`|)|Φ||━━━━"
        ],
        "flower girl": [
            "(　◕‿◕✿)",
            "(◕▽◕✿)"
        ],
        "blushing _flower _girl": [
            "(˶◕‿◕˶✿)",
            "(⁄ ⁄◕⁄ω⁄◕⁄ ⁄✿)"
        ],
        "sad __flower __girl": [
            "(◕‸ ◕✿) *pout*",
            "(◕︿◕✿)"
        ],
        "table flipping throwing": [
            "(╯°□°）╯︵ ┻━┻",
            "┻━┻ミ＼(≧ﾛ≦＼)"
        ],
        "_bears __table _flipping __throwing": [
            "ʕノ•ᴥ•ʔノ ︵ ┻━┻",
            " ┳┳ヾ(T(エ)Tヽ)"
        ],
        "setting the _table": [
            "┬──┬ ノ( ゜-゜ノ)",
            "(ヘ･_･)ヘ┳━┳"
        ],
        "good morning": [
            "(*^｡^*)Rise (*^o^*)And ＼(*^0^*)／Shineｰ!!",
            "(_ _)(-.-)(~O~)*yawn*・・(~O~)(-.-)"
        ],
        "kissing kisses": [
            "( ˘ ³˘)♥",
            "(ɔˆ ³(ˆ⌣ˆc)"
        ],
        "_throwing _kisssing  _kisses": [
            "★⌒ヽ(●’､＾●)Kiss!",
            "(^з^)-☆Chu!!"
        ],
        "hugs hugging": [
            "(つ・▽・)つ⊂(・▽・⊂)",
            "(つ≧▽≦)つ⊂(・ヮ・⊂)"
        ],
        "mad": [
            "┗(｀Дﾟ┗(｀ﾟДﾟ´)┛ﾟД´)┛",
            "!!!!|┛*｀Д´|┛・・~~┻━┻　┳━┳"
        ],
        "pigs": [
            "(´・(oo)・｀)",
            "(V´・(oo)・｀V)"
        ],
        "deep crying face": [
            "ಥ_ಥ",
            "ಥ╭╮ಥ"
        ],
        "denko shoboon": [
            "(´・ω・｀)",
            "Σ(´・ω・｀)"
        ],
        "raise your dongers": [
            "ヽ༼ຈل͜ຈ༽ﾉ",
            "✺◟༼ຈ ل͜ ຈ༽◞✺"
        ],
        "strolling happy gary": [
            "ᕕ( ᐛ )ᕗ",
            "ᐠ( ᐛ )ᐟ"
        ],
        "it’s here / kitaaa": [
            "ｷﾀ━(ﾟ∀ﾟ)━!",
            "ｷﾀ━━━(Дﾟ(○=(ﾟ∀ﾟ)=○)Дﾟ)━━━!!"
        ],
        "laughing": [
            "(´∀｀)",
            "ヽ（´∀｀）ノ"
        ],
        "lenny face": [
            "( ͡° ͜ʖ ͡°)",
            "ᕦ( ͡° ͜ʖ ͡°)ᕤ"
        ]
    },
    "nameMap": {
        // eslint-disable-line
    },
    "nameArr": [
        // eslint-disable-line
    ]
}

//     (╯°□°）╯ logics*:

_.forEach(lib.kaomoji, (kaomoji, fullName) => {
    _.forEach(fullName.split(" "), partiallyName => {
        lib.nameMap[partiallyName] = fullName
        lib.nameArr.push(partiallyName)
    })
})

const kaomoji = lib.kaomoji
const nameMap = lib.nameMap
const nameArr = lib.nameArr
let suggestionsTurnOff = false

$(document).ready(() => {
    const inputPopup = initHelper('Kaomoji Typer')
    inputPopup.hide()
    $('.ui-button-icon.ui-icon.ui-icon-closethick').on('click', () => {
        $(".suggestions").html("")
        inputPopup.remove()
        suggestionsTurnOff = true
    })

    let listenedDomCache

    (function checkNewDom () {
        const currentDom = $('textarea, input')
        const newDom = _.difference(currentDom, listenedDomCache, suggestionsTurnOff)
        if (newDom && newDom.length > 0) addListenEvent(inputPopup, newDom)
        listenedDomCache = currentDom
        setTimeout(checkNewDom, 3000)
    })()

    const originalTop = $('.ui-dialog').offset().top
    $(window).scroll(function () {
        $('.ui-dialog').css('top', originalTop + $(this).scrollTop())
    })
})

let suggestedKaomojis = []

function getSuggestions (lastWord) {
    lastWord = lastWord.toLowerCase()
    let matchingKaomojis = []
    if (kaomoji[lastWord]) matchingKaomojis = _.union(matchingKaomojis, kaomoji[lastWord])
    if (nameMap[lastWord]) matchingKaomojis = _.union(matchingKaomojis, kaomoji[nameMap[lastWord]])
    _.forEach(nameArr, name => {
        if (name.includes(lastWord)) {
            matchingKaomojis = _.union(matchingKaomojis, kaomoji[nameMap[name]])
        }
    })

    return matchingKaomojis
}

function addListenEvent (inputPopup, newDom) {
    $(newDom).on('input selectionchange propertychange', function (e) {
        const allWords = $(this).val().split(/\s/)
        const lastWord = allWords.pop()
        const lastWordLength = lastWord.length
        if (suggestionsTurnOff) {
        } else if (lastWordLength === 0) {
            inputPopup.hide()
            $(".suggestions").html("")
        } else if (lastWordLength > 1) {
            const lastChar = lastWord.charAt(lastWordLength - 1)
            if (lastChar > 0 && lastChar <= suggestedKaomojis.length) {
                $(this).val(`${allWords} ${suggestedKaomojis[lastChar - 1]} `)
                inputPopup.hide()
                $(".suggestions").html("")
            } else {
                updateDropDown(this, allWords, lastWord)
            }
        } else {
            openNewDropDown(this, allWords)
            inputPopup.show()
            updateDropDown(this, allWords, lastWord) // get suggestions when only one char is typed or not?
        }
    })
}

function updateDropDown (el, allWords, lastWord) {
    suggestedKaomojis = getSuggestions (lastWord)
    let innerHtml = "

No need to click. Just type 1-9
"
    _.forEach(suggestedKaomojis, (kaomoji, index) => {
        if (index < 9) innerHtml += "" + (index + 1) + ". " + kaomoji + "
"
    })
    innerHtml += "
"

    $(".suggestions").html(innerHtml)
    $('.tip').hide()
    $('.ui-dialog.ui-corner-all.ui-widget.ui-widget-content.ui-front.ui-draggable.ui-resizable').hover(() => {
        $('.tip').show()
        $('.tip').stop()
        $('.tip').fadeIn(1)
    }, () => {
        setTimeout(() => {
            $('.tip').fadeOut(1500)
        }, 500)
    })
}

function openNewDropDown (el) {
    $(".suggestions").show()
}

function initHelper (title) {
    $("body").append(`

        `)
    $(".suggestions").dialog()
    $("span.ui-dialog-title").text(title)

    return $('.ui-dialog.ui-corner-all.ui-widget.ui-widget-content.ui-front.ui-draggable.ui-resizable')
}
<commit_msg>add "_" when indexing instead of hard code on data<commit_after>const lib = {
    "kaomoji": {
        "sparkles": [
            "✧･ﾟ: *✧･ﾟ:* 　　 *:･ﾟ✧*:･ﾟ✧",
            "*＊✿❀　❀✿＊*"
        ],
        "bears": [
            "ʕ •ᴥ•ʔ",
            "ᶘಠᴥಠᶅ"
        ],
        "cats": [
            "ฅ(＾・ω・＾ฅ)",
            `චᆽච`
        ],
        "dogs": [
            "▼・ᴥ・▼",
            "U・ᴥ・U"
        ],
        "jailed": [
            "||Φ|(|ﾟ|∀|ﾟ|)|Φ||",
            "━━━━||Φ|(|´|Д|`|)|Φ||━━━━"
        ],
        "flower girl": [
            "(　◕‿◕✿)",
            "(◕▽◕✿)"
        ],
        "blushing flower girl": [
            "(˶◕‿◕˶✿)",
            "(⁄ ⁄◕⁄ω⁄◕⁄ ⁄✿)"
        ],
        "sad flower girl": [
            "(◕‸ ◕✿) *pout*",
            "(◕︿◕✿)"
        ],
        "table flipping throwing": [
            "(╯°□°）╯︵ ┻━┻",
            "┻━┻ミ＼(≧ﾛ≦＼)"
        ],
        "bears table flipping throwing": [
            "ʕノ•ᴥ•ʔノ ︵ ┻━┻",
            " ┳┳ヾ(T(エ)Tヽ)"
        ],
        "setting the table": [
            "┬──┬ ノ( ゜-゜ノ)",
            "(ヘ･_･)ヘ┳━┳"
        ],
        "good morning": [
            "(*^｡^*)Rise (*^o^*)And ＼(*^0^*)／Shineｰ!!",
            "(_ _)(-.-)(~O~)*yawn*・・(~O~)(-.-)"
        ],
        "kissing kisses": [
            "( ˘ ³˘)♥",
            "(ɔˆ ³(ˆ⌣ˆc)"
        ],
        "throwing kisssing kisses": [
            "★⌒ヽ(●’､＾●)Kiss!",
            "(^з^)-☆Chu!!"
        ],
        "hugs hugging": [
            "(つ・▽・)つ⊂(・▽・⊂)",
            "(つ≧▽≦)つ⊂(・ヮ・⊂)"
        ],
        "mad": [
            "┗(｀Дﾟ┗(｀ﾟДﾟ´)┛ﾟД´)┛",
            "!!!!|┛*｀Д´|┛・・~~┻━┻　┳━┳"
        ],
        "pigs": [
            "(´・(oo)・｀)",
            "(V´・(oo)・｀V)"
        ],
        "deep crying face": [
            "ಥ_ಥ",
            "ಥ╭╮ಥ"
        ],
        "denko shoboon": [
            "(´・ω・｀)",
            "Σ(´・ω・｀)"
        ],
        "raise your dongers": [
            "ヽ༼ຈل͜ຈ༽ﾉ",
            "✺◟༼ຈ ل͜ ຈ༽◞✺"
        ],
        "strolling happy gary": [
            "ᕕ( ᐛ )ᕗ",
            "ᐠ( ᐛ )ᐟ"
        ],
        "it’s here kitaaa": [
            "ｷﾀ━(ﾟ∀ﾟ)━!",
            "ｷﾀ━━━(Дﾟ(○=(ﾟ∀ﾟ)=○)Дﾟ)━━━!!"
        ],
        "laughing": [
            "(´∀｀)",
            "ヽ（´∀｀）ノ"
        ],
        "lenny face": [
            "( ͡° ͜ʖ ͡°)",
            "ᕦ( ͡° ͜ʖ ͡°)ᕤ"
        ]
    },
    "nameMap": {
        // eslint-disable-line
    },
    "nameArr": [
        // eslint-disable-line
    ]
}

//     (╯°□°）╯ logics*:

_.forEach(lib.kaomoji, (kaomoji, fullName) => {
    _.forEach(fullName.split(" "), partiallyName => {
        while (lib.nameMap[partiallyName]) {
            partiallyName = `_${partiallyName}`
        }
        lib.nameMap[partiallyName] = fullName
        lib.nameArr.push(partiallyName)
    })
})

const kaomoji = lib.kaomoji
const nameMap = lib.nameMap
const nameArr = lib.nameArr
let suggestionsTurnOff = false

$(document).ready(() => {
    const inputPopup = initHelper('Kaomoji Typer')
    inputPopup.hide()
    $('.ui-button-icon.ui-icon.ui-icon-closethick').on('click', () => {
        $(".suggestions").html("")
        inputPopup.remove()
        suggestionsTurnOff = true
    })

    let listenedDomCache

    (function checkNewDom () {
        const currentDom = $('textarea, input')
        const newDom = _.difference(currentDom, listenedDomCache, suggestionsTurnOff)
        if (newDom && newDom.length > 0) addListenEvent(inputPopup, newDom)
        listenedDomCache = currentDom
        setTimeout(checkNewDom, 3000)
    })()

    const originalTop = $('.ui-dialog').offset().top
    $(window).scroll(function () {
        $('.ui-dialog').css('top', originalTop + $(this).scrollTop())
    })
})

let suggestedKaomojis = []

function getSuggestions (lastWord) {
    lastWord = lastWord.toLowerCase()
    let matchingKaomojis = []
    if (kaomoji[lastWord]) matchingKaomojis = _.union(matchingKaomojis, kaomoji[lastWord])
    if (nameMap[lastWord]) matchingKaomojis = _.union(matchingKaomojis, kaomoji[nameMap[lastWord]])
    _.forEach(nameArr, name => {
        if (name.includes(lastWord)) {
            matchingKaomojis = _.union(matchingKaomojis, kaomoji[nameMap[name]])
        }
    })

    return matchingKaomojis
}

function addListenEvent (inputPopup, newDom) {
    $(newDom).on('input selectionchange propertychange', function (e) {
        const allWords = $(this).val().split(/\s/)
        const lastWord = allWords.pop()
        const lastWordLength = lastWord.length
        if (suggestionsTurnOff) {
        } else if (lastWordLength === 0) {
            inputPopup.hide()
            $(".suggestions").html("")
        } else if (lastWordLength > 1) {
            const lastChar = lastWord.charAt(lastWordLength - 1)
            if (lastChar > 0 && lastChar <= suggestedKaomojis.length) {
                $(this).val(`${allWords} ${suggestedKaomojis[lastChar - 1]} `)
                inputPopup.hide()
                $(".suggestions").html("")
            } else {
                updateDropDown(this, allWords, lastWord)
            }
        } else {
            openNewDropDown(this, allWords)
            inputPopup.show()
            updateDropDown(this, allWords, lastWord) // get suggestions when only one char is typed or not?
        }
    })
}

function updateDropDown (el, allWords, lastWord) {
    suggestedKaomojis = getSuggestions (lastWord)
    let innerHtml = "

No need to click. Just type 1-9
"
    _.forEach(suggestedKaomojis, (kaomoji, index) => {
        if (index < 9) innerHtml += "" + (index + 1) + ". " + kaomoji + "
"
    })
    innerHtml += "
"

    $(".suggestions").html(innerHtml)
    $('.tip').hide()
    $('.ui-dialog.ui-corner-all.ui-widget.ui-widget-content.ui-front.ui-draggable.ui-resizable').hover(() => {
        $('.tip').show()
        $('.tip').stop()
        $('.tip').fadeIn(1)
    }, () => {
        setTimeout(() => {
            $('.tip').fadeOut(1500)
        }, 500)
    })
}

function openNewDropDown (el) {
    $(".suggestions").show()
}

function initHelper (title) {
    $("body").append(`

        `)
    $(".suggestions").dialog()
    $("span.ui-dialog-title").text(title)

    return $('.ui-dialog.ui-corner-all.ui-widget.ui-widget-content.ui-front.ui-draggable.ui-resizable')
}
<|endoftext|>


<commit_before>
//store created tasks
var tasks = [];

//create object template with object constructor
function taskObj(id,taskname, taskdescription, taskpriority, status){
      this.id = id;
      this.taskname = taskname;
      this.description = taskdescription;
      this.priority = taskpriority;
      this.status = status;
};

window.onload = function(){
   var keyName;
        for(var i=0; i <= localStorage.length -1; i++){
              keyName = localStorage.key(i);
            if(keyName.substring(0,4) === 'task'){
              var storedTask = JSON.parse(localStorage.getItem(keyName));
              createDomTask(storedTask.id,storedTask.taskname,storedTask.description,storedTask.priority, storedTask.status);
          }
        }
};

//create task , update DOM, save to array (for future session storage)
function createTask(){
      //logic for finding what task key to implement
    var taskNumber = (function(){
         //store found keys in local storage
          var taskKeysCurrent = [];
                      //loop and store all found keys
            for(var i = 0; i < localStorage.length; i++){
                    taskKeysCurrent.push(localStorage.key(i));
            }
              //loop through stored keys , storage length amount, if missing return key with missing index appended
            for(var i=0; i < localStorage.length;  i++){
                if(taskKeysCurrent.indexOf('task' + i) === -1){
                    return 'task' + i;
                }
            }
                //if made it here, return first task key or continuing order task key
            return  localStorage.length === 0 ? 'task' + localStorage.length : 'task' + (localStorage.length);
    }());
    //grab input fields
    var inputName = document.getElementById("taskname").value;
    var inputDescription = document.getElementById("taskdescription").value;
    var checkedItem = document.getElementById("inputtask")["priorities"].value;
    var defaultStatus = 'open';
    //create DOMTask list item
    var addedTask = new taskObj(taskNumber,inputName,inputDescription,checkedItem, defaultStatus);
    //add new Task Object to array
    tasks.push(addedTask);

    localStorage.setItem(taskNumber,JSON.stringify(addedTask));

   //create new element, create text node, create icon element
   createDomTask(taskNumber,inputName,inputDescription,checkedItem,defaultStatus);
  clearform();

};

function createDomTask(tasknumber, taskname, description, priority, status) {
    var newTask = document.createElement("li");
    var taskContent = document.createTextNode(taskname + " " + description + " " + priority);
    var removeTask = document.createElement("i");
    var completeTask = document.createElement('i');
    //set id for management later
    newTask.setAttribute('id', tasknumber);
    //set class for open task
    //console.log(status);
    status === 'open'
        ? newTask.setAttribute('class', 'opentask')
        : newTask.setAttribute('class', 'closedtask');
    //set class for icon
    completeTask.setAttribute('class', 'material-icons completetask');
    removeTask.setAttribute("class", "material-icons removetask");
    //create and append text node for icon <i> tag
    completeTask.appendChild(document.createTextNode('done'));
    removeTask.appendChild(document.createTextNode("delete"));
    //append task content and delete icon to created <li> element
    newTask.appendChild(completeTask);
    newTask.appendChild(taskContent);
    newTask.appendChild(removeTask);
    //append newly created element to tasklist in DOM
    document.getElementById('tasklist').appendChild(newTask);

};

function updateTask(e) {

    //assign targeted element to var
    var updateTarget = e.target;
    //assign parent of targeted element to var
    var updateParent = updateTarget.parentNode;
    //nested function, updates local storage as well as toggles class in DOM
    var inplaceUpdate = function(targetElement, taskStatus) {
        targetElement.setAttribute('class', taskStatus);
        var taskToUpdate = JSON.parse(localStorage.getItem(targetElement.getAttribute('id')));
        taskToUpdate.status = taskStatus;
        localStorage.setItem(taskToUpdate.id, JSON.stringify(taskToUpdate));
    }

    if (updateTarget.getAttribute('class') === 'material-icons removetask') {
        //remove task, need to target parent node of parent node of delete button and then remove the child of the parent parent node
        updateParent.parentNode.removeChild(updateParent);
        //use id of list item to remove the corresponding item from local storage
        localStorage.removeItem(updateParent.getAttribute('id'));

    } else if (updateTarget.getAttribute('class') === 'material-icons completetask') {
        updateParent.getAttribute('class') === 'opentask'
            ? inplaceUpdate(updateParent, 'closedtask')
            : inplaceUpdate(updateParent, 'opentask');
    }

};

//update task(remove,toggle complete or notd)
document.getElementById('tasklist').addEventListener('click',updateTask,false);
//submit task
document.getElementById("tasksubmit").addEventListener('click',function(e){
  e.preventDefault();
  createTask();
},false);

//clear input fields
function clearform(){
    document.getElementById('taskname').value = '';
    document.getElementById('taskdescription').value ='';

}
<commit_msg>made default status match across the board to correct incorrect class naming<commit_after>
//store created tasks
var tasks = [];

//create object template with object constructor
function taskObj(id,taskname, taskdescription, taskpriority, status){
      this.id = id;
      this.taskname = taskname;
      this.description = taskdescription;
      this.priority = taskpriority;
      this.status = status;
};

window.onload = function(){
   var keyName;
        for(var i=0; i <= localStorage.length -1; i++){
              keyName = localStorage.key(i);
            if(keyName.substring(0,4) === 'task'){
              var storedTask = JSON.parse(localStorage.getItem(keyName));
              createDomTask(storedTask.id,storedTask.taskname,storedTask.description,storedTask.priority, storedTask.status);
          }
        }
};

//create task , update DOM, save to array (for future session storage)
function createTask(){
      //logic for finding what task key to implement
    var taskNumber = (function(){
         //store found keys in local storage
          var taskKeysCurrent = [];
                      //loop and store all found keys
            for(var i = 0; i < localStorage.length; i++){
                    taskKeysCurrent.push(localStorage.key(i));
            }
              //loop through stored keys , storage length amount, if missing return key with missing index appended
            for(var i=0; i < localStorage.length;  i++){
                if(taskKeysCurrent.indexOf('task' + i) === -1){
                    return 'task' + i;
                }
            }
                //if made it here, return first task key or continuing order task key
            return  localStorage.length === 0 ? 'task' + localStorage.length : 'task' + (localStorage.length);
    }());
    //grab input fields
    var inputName = document.getElementById("taskname").value;
    var inputDescription = document.getElementById("taskdescription").value;
    var checkedItem = document.getElementById("inputtask")["priorities"].value;
    var defaultStatus = 'opentask';
    //create DOMTask list item
    var addedTask = new taskObj(taskNumber,inputName,inputDescription,checkedItem, defaultStatus);
    //add new Task Object to array
    tasks.push(addedTask);

    localStorage.setItem(taskNumber,JSON.stringify(addedTask));

   //create new element, create text node, create icon element
   createDomTask(taskNumber,inputName,inputDescription,checkedItem,defaultStatus);
  clearform();

};

function createDomTask(tasknumber, taskname, description, priority, status) {
    var newTask = document.createElement("li");
    var taskContent = document.createTextNode(taskname + " " + description + " " + priority);
    var removeTask = document.createElement("i");
    var completeTask = document.createElement('i');
    //set id for management later
    newTask.setAttribute('id', tasknumber);
    //set class for open task
    //console.log(status);
    status === 'opentask'
        ? newTask.setAttribute('class', 'opentask')
        : newTask.setAttribute('class', 'closedtask');
    //set class for icon
    completeTask.setAttribute('class', 'material-icons completetask');
    removeTask.setAttribute("class", "material-icons removetask");
    //create and append text node for icon <i> tag
    completeTask.appendChild(document.createTextNode('done'));
    removeTask.appendChild(document.createTextNode("delete"));
    //append task content and delete icon to created <li> element
    newTask.appendChild(completeTask);
    newTask.appendChild(taskContent);
    newTask.appendChild(removeTask);
    //append newly created element to tasklist in DOM
    document.getElementById('tasklist').appendChild(newTask);

};

function updateTask(e) {

    //assign targeted element to var
    var updateTarget = e.target;
    //assign parent of targeted element to var
    var updateParent = updateTarget.parentNode;
    //nested function, updates local storage as well as toggles class in DOM
    var inplaceUpdate = function(targetElement, taskStatus) {
        targetElement.setAttribute('class', taskStatus);
        var taskToUpdate = JSON.parse(localStorage.getItem(targetElement.getAttribute('id')));
        taskToUpdate.status = taskStatus;
        localStorage.setItem(taskToUpdate.id, JSON.stringify(taskToUpdate));
    }

    if (updateTarget.getAttribute('class') === 'material-icons removetask') {
        //remove task, need to target parent node of parent node of delete button and then remove the child of the parent parent node
        updateParent.parentNode.removeChild(updateParent);
        //use id of list item to remove the corresponding item from local storage
        localStorage.removeItem(updateParent.getAttribute('id'));

    } else if (updateTarget.getAttribute('class') === 'material-icons completetask') {
        updateParent.getAttribute('class') === 'opentask'
            ? inplaceUpdate(updateParent, 'closedtask')
            : inplaceUpdate(updateParent, 'opentask');
    }

};

//update task(remove,toggle complete or notd)
document.getElementById('tasklist').addEventListener('click',updateTask,false);
//submit task
document.getElementById("tasksubmit").addEventListener('click',function(e){
  e.preventDefault();
  createTask();
},false);

//clear input fields
function clearform(){
    document.getElementById('taskname').value = '';
    document.getElementById('taskdescription').value ='';

}
<|endoftext|>


<commit_before>var logger = require('../common/logger');

exports = module.exports = function (req, res, next) {
  // Assets do not out log.
  if (exports.ignore.test(req.url)) {
    next();
    return;
  }

  var t = new Date();
  logger.info('\n\nStarted', t.toISOString(), req.method, req.url, req.ip);

  res.on('finish', function () {
    var duration = ((new Date()) - t);

    logger.info('Completed', res.statusCode, ('(' + duration + 'ms)').green);
  });

  next();
};

exports.ignore = /^\/(public|agent)/;
<commit_msg>refactor `ignore` in middlewares/request_log.js<commit_after>var logger = require('../common/logger');

var ignore = /^\/(public|agent)/;

exports = module.exports = function (req, res, next) {
  // Assets do not out log.
  if (ignore.test(req.url)) {
    next();
    return;
  }

  var t = new Date();
  logger.info('\n\nStarted', t.toISOString(), req.method, req.url, req.ip);

  res.on('finish', function () {
    var duration = ((new Date()) - t);

    logger.info('Completed', res.statusCode, ('(' + duration + 'ms)').green);
  });

  next();
};
<|endoftext|>


<commit_before>function(doc){
    if (doc.doc_type == "CouchUser") {
    	for (var i in doc.web_account.domain_memberships) {
            emit(doc.web_account.domain_memberships[i].domain,  null);
    	}
    }
}

<commit_msg>Fixed it so you can add commcare users to groups (i think)<commit_after>function(doc){
    if (doc.doc_type == "CouchUser") {
    	for (var i in doc.web_account.domain_memberships) {
            emit(doc.web_account.domain_memberships[i].domain,  null);
    	}
        for (var i in doc.commcare_accounts) {
            emit(doc.commcare_accounts[i].domain, null);
        }
    }
}

<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import {
  Text,
  Clipboard,
  StyleSheet,
  TouchableWithoutFeedback,
  View,
  ViewPropTypes,
  TouchableOpacity,
  Alert,
} from 'react-native';
import { Actions } from 'react-native-router-flux';
import { CachedImage } from 'react-native-img-cache';

/* import MessageText from './MessageText';
import MessageImage from './MessageImage';
import Time from './Time'; */

import {
  MessageText,
  MessageImage,
  Time,
} from 'react-native-gifted-chat';
import { Icon } from 'react-native-elements';

import Network from '../../../network';
import { AppColors } from '../../../theme/';
import { isSameUser, isSameDay, warnDeprecated } from './utils';

const chatColors = {
  replyBubbleR: AppColors.chat().replyBubbleR,
};

const styles = {
  left: StyleSheet.create({
    container: {
      flex: 1,
      alignItems: 'flex-start',
    },
    replyContainer: {
      backgroundColor: AppColors.chat().replyBubbleL,
    },
    replyText: {
      fontSize: 12,
      color: AppColors.chat().replyTextL,
    },
    wrapper: {
      borderRadius: 15,
      backgroundColor: '#f0f0f0',
      marginRight: 60,
      minHeight: 20,
      justifyContent: 'flex-end',
    },
    containerToNext: {
      borderBottomLeftRadius: 3,
    },
    containerToPrevious: {
      borderTopLeftRadius: 3,
    },
  }),
  right: StyleSheet.create({
    container: {
      flex: 1,
      alignItems: 'flex-end',
    },
    replyContainer: {
      backgroundColor: chatColors.replyBubbleR,
    },
    replyText: {
      fontSize: 12,
      color: AppColors.chat().replyTextR,
    },
    wrapper: {
      borderRadius: 15,
      backgroundColor: '#0084ff',
      marginLeft: 60,
      minHeight: 20,
      justifyContent: 'flex-end',
    },
    containerToNext: {
      borderBottomRightRadius: 3,
    },
    containerToPrevious: {
      borderTopRightRadius: 3,
    },
  }),
  bottom: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-end',
  },
  tick: {
    fontSize: 10,
    backgroundColor: 'transparent',
    color: 'white',
  },
  tickView: {
    flexDirection: 'row',
    marginRight: 10,
  },
  actionBtn: {
    padding: 10,
    borderRadius: 3,
    borderColor: '#fff',
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(0,0,0,0.2)',
    marginHorizontal: 5,
  },
  replyWrapper: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    justifyContent: 'space-between',
    padding: 8,
    margin: 5,
    borderRadius: 3,
    borderColor: 'rgba(0,0,0,0.1)',
    borderWidth: 1,
  },
};

export default class Bubble extends React.Component {
  constructor(props) {
    super(props);
    this._network = new Network();
    this.obj = this.props.obj;
    this.onLongPress = this.onLongPress.bind(this);
    const likes = this.props.currentMessage.likes;
    const isReply = this.props.currentMessage.isReply;
    const original = JSON.parse(this.props.currentMessage.original);
    this.state = {
      showActions: false,
      likes,
      isReply,
      original,
      parentMessage: null,
    };
  }

  componentWillMount() {
    const _super = this;
    if (this.state.isReply) {
      let getReplyMess = this.obj.findMessageById(this.props.currentMessage.replyMessageId);
      while (getReplyMess && getReplyMess.isReply) {
        getReplyMess = this.obj.findMessageById(getReplyMess.replyMessageId);
      }
      // this._network.chat.fixYapImageUrls(Array.prototype.slice.call([replyMessage]),
      if (getReplyMess) {
        const replyMessage = [getReplyMess];
        this.prepareMessages(replyMessage, (parentMessage) => {
          _super.setState({
            parentMessage: parentMessage[0],
          });
        });
      }
    }
  }

  componentDidMount() {
    console.log('this.state.isReply state', this.state.parentMessage);
  }

  onLongPress() {
    if (this.props.onLongPress) {
      this.props.onLongPress(this.context, this.props.currentMessage);
    } else if (this.props.currentMessage.text) {
      const options = [
        'Copy Text',
        'Cancel',
      ];
      const cancelButtonIndex = options.length - 1;
      this.context.actionSheet().showActionSheetWithOptions({
        options,
        cancelButtonIndex,
      },
      (buttonIndex) => {
        switch (buttonIndex) { // eslint-disable-line default-case
          case 0:
            Clipboard.setString(this.props.currentMessage.text);
            break;
        }
      });
    }
  }

  toggleActions = () => {
    const action = this.state.showActions;
    this.setState({ showActions: !action });
  }

  _onPressLike = () => {
    console.log('**** like pressed **** ');
    this._network.chat.setPhotoLike(this.state.original._id);
  }

  _deleteMessage = () => {
    Alert.alert(
      'Delete',
      'Do you want to delete the image?',
      [
        { text: 'No', onPress: () => console.log('Cancel Pressed'), style: 'cancel' },
        { text: 'Yes',
          onPress: () => {
            this._network.chat.deleteMessage(this.state.original._id);
          },
        },
      ],
      { cancelable: false },
    );
  }

  _handleComments = () => {
    if (this.state.original.file) {
      Actions.imagePreview({
        imageUri: this.props.currentMessage.image,
        obj: this.props.obj,
        msgId: this.props.currentMessage._id,
        msgLikes: this.props.currentMessage.likes,
        msgTitle: this.props.currentMessage.text,
      });
    } else {
      Actions.replyMessage({
        obj: this.props.obj,
        msgId: this.props.currentMessage._id,
        actualMessage: this.props.currentMessage.text,
        msgLikes: this.props.currentMessage.likes,
        msgTitle: this.props.currentMessage.text,
      });
    }
  }

  prepareMessages(messages, callback) {
    this._network.chat.fixYapImageUrls(Array.prototype.slice.call(messages), (msg) => {
      callback(msg);
    });
  }

  handleBubbleToNext() {
    if (isSameUser(this.props.currentMessage, this.props.nextMessage)
    && isSameDay(this.props.currentMessage, this.props.nextMessage)) {
      return StyleSheet.flatten([
        styles[this.props.position].containerToNext,
        this.props.containerToNextStyle[this.props.position]]);
    }
    return null;
  }

  handleBubbleToPrevious() {
    if (isSameUser(this.props.currentMessage, this.props.previousMessage)
    && isSameDay(this.props.currentMessage, this.props.previousMessage)) {
      return StyleSheet.flatten([
        styles[this.props.position].containerToPrevious,
        this.props.containerToPreviousStyle[this.props.position]]);
    }
    return null;
  }

  renderMessageText() {
    if (this.props.currentMessage.text) {
      const { containerStyle, wrapperStyle, ...messageTextProps } = this.props;
      if (this.props.renderMessageText) {
        console.log('renderMessageText', messageTextProps);
        return this.props.renderMessageText(messageTextProps);
      }
      return <MessageText {...messageTextProps} />;
    }
    return null;
  }

  renderReply() {
    const { replyStyle } = this.props;
    if (this.state.parentMessage) {
      return (
        <View
          style={[
            styles.replyWrapper,
            styles[this.props.position].replyContainer,
            replyStyle[this.props.position].replyBubble,
          ]}
        >
          <View
            style={{
              flexDirection: 'column',
              minWidth: 100,
            }}
          >
            <Text
              style={[
                styles[this.props.position].replyText,
                replyStyle[this.props.position].replyText,
                { fontWeight: '500' },
              ]}
              numberOfLines={1}
            >{`${this.state.parentMessage.user.name}:`}</Text>
            <Text
              style={[
                styles[this.props.position].replyText,
                replyStyle[this.props.position].replyText,
              ]}
            >{this.state.parentMessage.text}</Text>
          </View>
          {
            (this.state.parentMessage.image &&
              <CachedImage
                style={{
                  width: 50,
                  height: 50,
                  marginLeft: 5,
                  borderRadius: 2 }}
                source={{ uri: this.state.parentMessage.image }}
              />
            )
          }
        </View>
      );
    }
  }

  renderMessageImage() {
    if (this.props.currentMessage.image) {
      const { containerStyle, wrapperStyle, ...messageImageProps } = this.props;
      if (this.props.renderMessageImage) {
        return this.props.renderMessageImage(messageImageProps);
      }
      return <MessageImage {...messageImageProps} />;
    }
    return null;
  }

  renderTicks() {
    const { currentMessage } = this.props;
    if (this.props.renderTicks) {
      return this.props.renderTicks(currentMessage);
    }
    if (currentMessage.user._id !== this.props.user._id) {
      return;
    }
    if (currentMessage.sent || currentMessage.received) {
      return (
        <View style={styles.tickView}>
          {currentMessage.sent && <Text style={[styles.tick, this.props.tickStyle]}>✓</Text>}
          {currentMessage.received && <Text style={[styles.tick, this.props.tickStyle]}>✓</Text>}
        </View>
      );
    }
  }

  renderTime() {
    if (this.props.currentMessage.createdAt) {
      const { containerStyle, wrapperStyle, ...timeProps } = this.props;
      if (this.props.renderTime) {
        return this.props.renderTime(timeProps);
      }
      return <Time {...timeProps} />;
    }
    return null;
  }

  renderCustomView() {
    if (this.props.renderCustomView) {
      return this.props.renderCustomView(this.props);
    }
    return null;
  }

  renderActions() {
    if (this.state.showActions || this.state.likes > 0) {
      return (
        <View
          style={{
            marginHorizontal: 5,
            marginBottom: 5,
          }}
        >
          <View
            style={{
              alignItems: 'flex-start',
              padding: 3,
              flexDirection: 'row',
            }}
          >
            <TouchableOpacity
              style={[styles.actionBtn]}
              onPress={this._onPressLike}
            >
              <Icon
                name={'heart-outline'}
                type={'material-community'}
                size={14}
                color={'#FFF'}
              />
              {
                (this.state.likes > 0 &&
                  <Text
                    style={{
                      fontFamily: 'OpenSans-Regular',
                      fontSize: 12,
                      color: '#fff',
                      marginLeft: 5,
                    }}
                  >{this.state.likes > 0 ? this.state.likes : 'no'}</Text>
                )
              }
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.actionBtn]}
              onPress={this._handleComments}
            >
              <Icon
                name={'comment-text-outline'}
                type={'material-community'}
                size={14}
                color={'#FFF'}
              />
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.actionBtn]}
              onPress={this._deleteMessage}
            >
              <Icon
                name={'delete'}
                type={'material-community'}
                size={14}
                color={'#FFF'}
              />
            </TouchableOpacity>
          </View>
        </View>
      );
    }
  }

  render() {
    console.log('bubble mess', this.props.currentMessage);
    return (
      <View style={[styles[this.props.position].container, this.props.containerStyle[this.props.position]]}>
        <View style={[
          styles[this.props.position].wrapper,
          this.props.wrapperStyle[this.props.position],
          this.handleBubbleToNext(),
          this.handleBubbleToPrevious()]}
        >
          <TouchableWithoutFeedback
            onLongPress={this.onLongPress}
            accessibilityTraits="text"
            onPress={this.toggleActions}
            {...this.props.touchableProps}
          >
            <View>
              {this.renderCustomView()}
              {this.renderReply()}
              {this.renderMessageImage()}
              {this.renderMessageText()}
              <View style={[styles.bottom, this.props.bottomContainerStyle[this.props.position]]}>
                {this.renderActions()}
                <View>
                  {this.renderTime()}
                </View>
              </View>
            </View>
          </TouchableWithoutFeedback>
        </View>
      </View>
    );
  }
}

Bubble.contextTypes = {
  actionSheet: PropTypes.func,
};

Bubble.defaultProps = {
  touchableProps: {},
  onLongPress: null,
  renderMessageImage: null,
  renderMessageText: null,
  renderCustomView: null,
  renderTime: null,
  position: 'left',
  currentMessage: {
    text: null,
    createdAt: null,
    image: null,
  },
  nextMessage: {},
  previousMessage: {},
  containerStyle: {},
  replyStyle: {},
  wrapperStyle: {},
  bottomContainerStyle: {},
  tickStyle: {},
  containerToNextStyle: {},
  containerToPreviousStyle: {},
  // TODO: remove in next major release
  isSameDay: warnDeprecated(isSameDay),
  isSameUser: warnDeprecated(isSameUser),
  obj: {},
  renderTicks: {},
  user: {},
};

Bubble.propTypes = {
  touchableProps: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  onLongPress: PropTypes.func,
  renderMessageImage: PropTypes.func,
  renderMessageText: PropTypes.func,
  renderCustomView: PropTypes.func,
  renderTime: PropTypes.func,
  position: PropTypes.oneOf(['left', 'right']),
  currentMessage: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  nextMessage: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  previousMessage: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  containerStyle: PropTypes.shape({
    left: ViewPropTypes.style,
    right: ViewPropTypes.style,
  }),
  replyStyle: React.PropTypes.object, // eslint-disable-line react/forbid-prop-types
  wrapperStyle: PropTypes.shape({
    left: ViewPropTypes.style,
    right: ViewPropTypes.style,
  }),
  bottomContainerStyle: PropTypes.shape({
    left: ViewPropTypes.style,
    right: ViewPropTypes.style,
  }),
  tickStyle: Text.propTypes.style,
  containerToNextStyle: PropTypes.shape({
    left: ViewPropTypes.style,
    right: ViewPropTypes.style,
  }),
  containerToPreviousStyle: PropTypes.shape({
    left: ViewPropTypes.style,
    right: ViewPropTypes.style,
  }),
  // TODO: remove in next major release
  isSameDay: PropTypes.func,
  isSameUser: PropTypes.func,
  obj: React.PropTypes.object,    // eslint-disable-line react/forbid-prop-types
  renderTicks: React.PropTypes.object,    // eslint-disable-line react/forbid-prop-types
  user: React.PropTypes.object,    // eslint-disable-line react/forbid-prop-types
};
<commit_msg>Code conflict fixes<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import {
  Text,
  Clipboard,
  StyleSheet,
  TouchableWithoutFeedback,
  View,
  ViewPropTypes,
  TouchableOpacity,
  Alert,
} from 'react-native';
import { Actions } from 'react-native-router-flux';
import { CachedImage } from 'react-native-img-cache';

/* import MessageText from './MessageText';
import MessageImage from './MessageImage';
import Time from './Time'; */

import {
  MessageText,
  MessageImage,
  Time,
} from 'react-native-gifted-chat';
import { Icon } from 'react-native-elements';

import Network from '../../../network';
import { AppColors } from '../../../theme/';
import { isSameUser, isSameDay, warnDeprecated } from './utils';

const chatColors = {
  replyBubbleR: AppColors.chat().replyBubbleR,
};

const styles = {
  left: StyleSheet.create({
    container: {
      flex: 1,
      alignItems: 'flex-start',
    },
    replyContainer: {
      backgroundColor: AppColors.chat().replyBubbleL,
    },
    replyText: {
      fontSize: 12,
      color: AppColors.chat().replyTextL,
    },
    wrapper: {
      borderRadius: 15,
      backgroundColor: '#f0f0f0',
      marginRight: 60,
      minHeight: 20,
      justifyContent: 'flex-end',
    },
    containerToNext: {
      borderBottomLeftRadius: 3,
    },
    containerToPrevious: {
      borderTopLeftRadius: 3,
    },
  }),
  right: StyleSheet.create({
    container: {
      flex: 1,
      alignItems: 'flex-end',
    },
    replyContainer: {
      backgroundColor: chatColors.replyBubbleR,
    },
    replyText: {
      fontSize: 12,
      color: AppColors.chat().replyTextR,
    },
    wrapper: {
      borderRadius: 15,
      backgroundColor: '#0084ff',
      marginLeft: 60,
      minHeight: 20,
      justifyContent: 'flex-end',
    },
    containerToNext: {
      borderBottomRightRadius: 3,
    },
    containerToPrevious: {
      borderTopRightRadius: 3,
    },
  }),
  bottom: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-end',
  },
  tick: {
    fontSize: 10,
    backgroundColor: 'transparent',
    color: 'white',
  },
  tickView: {
    flexDirection: 'row',
    marginRight: 10,
  },
  actionBtn: {
    padding: 10,
    borderRadius: 3,
    borderColor: '#fff',
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(0,0,0,0.2)',
    marginHorizontal: 5,
  },
  replyWrapper: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    justifyContent: 'space-between',
    padding: 8,
    margin: 5,
    borderRadius: 3,
    borderColor: 'rgba(0,0,0,0.1)',
    borderWidth: 1,
  },
};

export default class Bubble extends React.Component {
  constructor(props) {
    super(props);
    this._network = new Network();
    this.obj = this.props.obj;
    this.onLongPress = this.onLongPress.bind(this);
    const likes = this.props.currentMessage.likes;
    const isReply = this.props.currentMessage.isReply;
    const original = JSON.parse(this.props.currentMessage.original);
    this.state = {
      showActions: false,
      likes,
      isReply,
      original,
      parentMessage: null,
    };
  }

  componentWillMount() {
    const _super = this;
    if (this.state.isReply) {
      let getReplyMess = this.obj.findMessageById(this.props.currentMessage.replyMessageId);
      while (getReplyMess && getReplyMess.isReply) {
        getReplyMess = this.obj.findMessageById(getReplyMess.replyMessageId);
      }
      // this._network.chat.fixYapImageUrls(Array.prototype.slice.call([replyMessage]),
      if (getReplyMess) {
        const replyMessage = [getReplyMess];
        this.prepareMessages(replyMessage, (parentMessage) => {
          _super.setState({
            parentMessage: parentMessage[0],
          });
        });
      }
    }
  }

  onLongPress() {
    if (this.props.onLongPress) {
      this.props.onLongPress(this.context, this.props.currentMessage);
    } else if (this.props.currentMessage.text) {
      const options = [
        'Copy Text',
        'Cancel',
      ];
      const cancelButtonIndex = options.length - 1;
      this.context.actionSheet().showActionSheetWithOptions({
        options,
        cancelButtonIndex,
      },
      (buttonIndex) => {
        switch (buttonIndex) { // eslint-disable-line default-case
          case 0:
            Clipboard.setString(this.props.currentMessage.text);
            break;
        }
      });
    }
  }

  toggleActions = () => {
    const action = this.state.showActions;
    this.setState({ showActions: !action });
  }

  _onPressLike = () => {
    console.log('**** like pressed **** ');
    this._network.chat.setPhotoLike(this.state.original._id);
  }

  _deleteMessage = () => {
    Alert.alert(
      'Delete',
      'Do you want to delete the image?',
      [
        { text: 'No', onPress: () => console.log('Cancel Pressed'), style: 'cancel' },
        { text: 'Yes',
          onPress: () => {
            this._network.chat.deleteMessage(this.state.original._id);
          },
        },
      ],
      { cancelable: false },
    );
  }

  _handleComments = () => {
    if (this.state.original.file) {
      Actions.imagePreview({
        imageUri: this.props.currentMessage.image,
        obj: this.props.obj,
        msgId: this.props.currentMessage._id,
        msgLikes: this.props.currentMessage.likes,
        msgTitle: this.props.currentMessage.text,
      });
    } else {
      Actions.replyMessage({
        obj: this.props.obj,
        msgId: this.props.currentMessage._id,
        actualMessage: this.props.currentMessage.text,
        msgLikes: this.props.currentMessage.likes,
        msgTitle: this.props.currentMessage.text,
      });
    }
  }

  prepareMessages(messages, callback) {
    this._network.chat.fixYapImageUrls(Array.prototype.slice.call(messages), (msg) => {
      callback(msg);
    });
  }

  handleBubbleToNext() {
    if (isSameUser(this.props.currentMessage, this.props.nextMessage)
    && isSameDay(this.props.currentMessage, this.props.nextMessage)) {
      return StyleSheet.flatten([
        styles[this.props.position].containerToNext,
        this.props.containerToNextStyle[this.props.position]]);
    }
    return null;
  }

  handleBubbleToPrevious() {
    if (isSameUser(this.props.currentMessage, this.props.previousMessage)
    && isSameDay(this.props.currentMessage, this.props.previousMessage)) {
      return StyleSheet.flatten([
        styles[this.props.position].containerToPrevious,
        this.props.containerToPreviousStyle[this.props.position]]);
    }
    return null;
  }

  renderMessageText() {
    if (this.props.currentMessage.text) {
      const { containerStyle, wrapperStyle, ...messageTextProps } = this.props;
      if (this.props.renderMessageText) {
        console.log('renderMessageText', messageTextProps);
        return this.props.renderMessageText(messageTextProps);
      }
      return <MessageText {...messageTextProps} />;
    }
    return null;
  }

  renderReply() {
    const { replyStyle } = this.props;
    if (this.state.parentMessage) {
      return (
        <View
          style={[
            styles.replyWrapper,
            styles[this.props.position].replyContainer,
            replyStyle[this.props.position].replyBubble,
          ]}
        >
          <View
            style={{
              flexDirection: 'column',
              minWidth: 100,
            }}
          >
            <Text
              style={[
                styles[this.props.position].replyText,
                replyStyle[this.props.position].replyText,
                { fontWeight: '500' },
              ]}
              numberOfLines={1}
            >{`${this.state.parentMessage.user.name}:`}</Text>
            <Text
              style={[
                styles[this.props.position].replyText,
                replyStyle[this.props.position].replyText,
              ]}
            >{this.state.parentMessage.text}</Text>
          </View>
          {
            (this.state.parentMessage.image &&
              <CachedImage
                style={{
                  width: 50,
                  height: 50,
                  marginLeft: 5,
                  borderRadius: 2 }}
                source={{ uri: this.state.parentMessage.image }}
              />
            )
          }
        </View>
      );
    }
  }

  renderMessageImage() {
    if (this.props.currentMessage.image) {
      const { containerStyle, wrapperStyle, ...messageImageProps } = this.props;
      if (this.props.renderMessageImage) {
        return this.props.renderMessageImage(messageImageProps);
      }
      return <MessageImage {...messageImageProps} />;
    }
    return null;
  }

  renderTicks() {
    const { currentMessage } = this.props;
    if (this.props.renderTicks) {
      return this.props.renderTicks(currentMessage);
    }
    if (currentMessage.user._id !== this.props.user._id) {
      return;
    }
    if (currentMessage.sent || currentMessage.received) {
      return (
        <View style={styles.tickView}>
          {currentMessage.sent && <Text style={[styles.tick, this.props.tickStyle]}>✓</Text>}
          {currentMessage.received && <Text style={[styles.tick, this.props.tickStyle]}>✓</Text>}
        </View>
      );
    }
  }

  renderTime() {
    if (this.props.currentMessage.createdAt) {
      const { containerStyle, wrapperStyle, ...timeProps } = this.props;
      if (this.props.renderTime) {
        return this.props.renderTime(timeProps);
      }
      return <Time {...timeProps} />;
    }
    return null;
  }

  renderCustomView() {
    if (this.props.renderCustomView) {
      return this.props.renderCustomView(this.props);
    }
    return null;
  }

  renderActions() {
    if (this.state.showActions || this.state.likes > 0) {
      return (
        <View
          style={{
            marginHorizontal: 5,
            marginBottom: 5,
          }}
        >
          <View
            style={{
              alignItems: 'flex-start',
              padding: 3,
              flexDirection: 'row',
            }}
          >
            <TouchableOpacity
              style={[styles.actionBtn]}
              onPress={this._onPressLike}
            >
              <Icon
                name={'heart-outline'}
                type={'material-community'}
                size={14}
                color={'#FFF'}
              />
              {
                (this.state.likes > 0 &&
                  <Text
                    style={{
                      fontFamily: 'OpenSans-Regular',
                      fontSize: 12,
                      color: '#fff',
                      marginLeft: 5,
                    }}
                  >{this.state.likes > 0 ? this.state.likes : 'no'}</Text>
                )
              }
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.actionBtn]}
              onPress={this._handleComments}
            >
              <Icon
                name={'comment-text-outline'}
                type={'material-community'}
                size={14}
                color={'#FFF'}
              />
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.actionBtn]}
              onPress={this._deleteMessage}
            >
              <Icon
                name={'delete'}
                type={'material-community'}
                size={14}
                color={'#FFF'}
              />
            </TouchableOpacity>
          </View>
        </View>
      );
    }
  }

  render() {
    console.log('bubble mess', this.props.currentMessage);
    return (
      <View style={[styles[this.props.position].container, this.props.containerStyle[this.props.position]]}>
        <View style={[
          styles[this.props.position].wrapper,
          this.props.wrapperStyle[this.props.position],
          this.handleBubbleToNext(),
          this.handleBubbleToPrevious()]}
        >
          <TouchableWithoutFeedback
            onLongPress={this.onLongPress}
            accessibilityTraits="text"
            onPress={this.toggleActions}
            {...this.props.touchableProps}
          >
            <View>
              {this.renderCustomView()}
              {this.renderReply()}
              {this.renderMessageImage()}
              {this.renderMessageText()}
              <View style={[styles.bottom, this.props.bottomContainerStyle[this.props.position]]}>
                {this.renderActions()}
                <View>
                  {this.renderTime()}
                </View>
              </View>
            </View>
          </TouchableWithoutFeedback>
        </View>
      </View>
    );
  }
}

Bubble.contextTypes = {
  actionSheet: PropTypes.func,
};

Bubble.defaultProps = {
  touchableProps: {},
  onLongPress: null,
  renderMessageImage: null,
  renderMessageText: null,
  renderCustomView: null,
  renderTime: null,
  position: 'left',
  currentMessage: {
    text: null,
    createdAt: null,
    image: null,
  },
  nextMessage: {},
  previousMessage: {},
  containerStyle: {},
  replyStyle: {},
  wrapperStyle: {},
  bottomContainerStyle: {},
  tickStyle: {},
  containerToNextStyle: {},
  containerToPreviousStyle: {},
  // TODO: remove in next major release
  isSameDay: warnDeprecated(isSameDay),
  isSameUser: warnDeprecated(isSameUser),
  obj: {},
  renderTicks: {},
  user: {},
};

Bubble.propTypes = {
  touchableProps: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  onLongPress: PropTypes.func,
  renderMessageImage: PropTypes.func,
  renderMessageText: PropTypes.func,
  renderCustomView: PropTypes.func,
  renderTime: PropTypes.func,
  position: PropTypes.oneOf(['left', 'right']),
  currentMessage: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  nextMessage: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  previousMessage: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  containerStyle: PropTypes.shape({
    left: ViewPropTypes.style,
    right: ViewPropTypes.style,
  }),
  replyStyle: React.PropTypes.object, // eslint-disable-line react/forbid-prop-types
  wrapperStyle: PropTypes.shape({
    left: ViewPropTypes.style,
    right: ViewPropTypes.style,
  }),
  bottomContainerStyle: PropTypes.shape({
    left: ViewPropTypes.style,
    right: ViewPropTypes.style,
  }),
  tickStyle: Text.propTypes.style,
  containerToNextStyle: PropTypes.shape({
    left: ViewPropTypes.style,
    right: ViewPropTypes.style,
  }),
  containerToPreviousStyle: PropTypes.shape({
    left: ViewPropTypes.style,
    right: ViewPropTypes.style,
  }),
  // TODO: remove in next major release
  isSameDay: PropTypes.func,
  isSameUser: PropTypes.func,
  obj: React.PropTypes.object,    // eslint-disable-line react/forbid-prop-types
  renderTicks: React.PropTypes.object,    // eslint-disable-line react/forbid-prop-types
  user: React.PropTypes.object,    // eslint-disable-line react/forbid-prop-types
};
<|endoftext|>


<commit_before>angular.module("omniControllers")
  .controller("ExchangeBuyController",["$scope", "$http", "Transaction", "ADDRESS_EXPLORER_URL", "SATOSHI_UNIT","MINER_SPEED"
    function ExchangeBuyController($scope, $http, Transaction, ADDRESS_EXPLORER_URL, SATOSHI_UNIT,MINER_SPEED) {
      $scope.editTransactionCost = function(){
        $scope.modalManager.openTransactionCostModal($scope, function(){return;});
      }
      $scope.selectedAddress= $scope.hasBitcoins ? $scope.wallet.getAsset(0).tradableAddresses[0] : undefined;
      $scope.feeType = MINER_SPEED;
      $scope.setAddress = function(address){
            $scope.selectedAddress = address;
            if (address!=undefined) {
              $scope.selectedAddress.estimateFee().then(function(result){
                $scope.feeData=result;
                if($scope.feeType != 'custom'){
                    $scope.minersFee = new Big(result.class_c[$scope.feeType]);
                }
              });
            }
      }
      $scope.setAddress($scope.selectedAddress);
      var transaction = $scope.global['buyOffer'];
      $scope.buySaleID = transaction.tx_hash;
      $http.get('/v1/transaction/tx/' + transaction.tx_hash + '.json').success(function(data) {
        var tx = data[0];
        $scope.selectedCoin=tx.currency_str;
        $scope.bitcoinAddresses = $scope.hasBitcoins ? $scope.wallet.getAsset(0).tradableAddresses : [];
        if(parseInt(tx.currencyId) <3) {
          $scope.divisible = true;
          $scope.sendPlaceholderValue = '1.00000000';
          $scope.sendPlaceholderStep = $scope.sendPlaceholderMin = '0.00000001';
          $scope.displayedAbbreviation = tx.currency_str;
        } else {
          $http.get("/v1/property/"+tx.currencyId.replace(new RegExp("^0+"), "") +".json", function(data) {
            var property = data[0];
            if(property.propertyType == "0001"){
              $scope.divisible =false;
              $scope.sendPlaceholderValue = $scope.sendPlaceholderStep = $scope.sendPlaceholderMin = '1';
            } else  {
              $scope.divisible = true;
              $scope.sendPlaceholderValue = '1.00000000';
              $scope.sendPlaceholderStep = $scope.sendPlaceholderMin = '0.00000001';
            }

            $scope.displayedAbbreviation = property.propertyName + " #" + property.currencyId;
          });
        }
      });
      // [ Buy Form Helpers ]

      $scope.confirm = function(){
        //TODO: VALIDATIONS
        var fee = new Big($scope.minersFee);
        var exchangeAccept = new Transaction(22,$scope.selectedAddress,fee,{
            transaction_version:0,
            amount: +new Big($scope.buyAmount).valueOf(),
            tx_hash: $scope.buySaleID,
            donate: $scope.account.getSetting("donate")
          });

        $scope.modalManager.openConfirmationModal({
          dataTemplate: '/views/modals/partials/accept.html',
          scope:{
            title:"EXCHANGE.BUY.MODALTITLE",
            displayedAbbreviation: $scope.displayedAbbreviation,
            buyAmount: $scope.buyAmount,
            minerFees: $scope.minersFee,
            selectedCoin: $scope.selectedCoin,
            insufficientBitcoin : $scope.insufficientBitcoin,
            fees : $scope.minersFee,
            totalCost : exchangeAccept.totalCost.valueOf(),
            selectedAddress : $scope.selectedAddress,
            sellerAddress: transaction.from_address,
            offerHash:transaction.tx_hash,
            salePricePerCoin:transaction.formatted_price_per_coin,
            saleBlocks:transaction.formatted_block_time_limit,
            confirmText:"EXCHANGE.BUY.CONFIRM",
            explorerUrl:ADDRESS_EXPLORER_URL,
            successRedirect:"/exchange/trade"
          },
          transaction:exchangeAccept
        })
      }
    }])
<commit_msg>bugfix controller declaration<commit_after>angular.module("omniControllers")
  .controller("ExchangeBuyController",["$scope", "$http", "Transaction", "ADDRESS_EXPLORER_URL", "SATOSHI_UNIT","MINER_SPEED",
    function ExchangeBuyController($scope, $http, Transaction, ADDRESS_EXPLORER_URL, SATOSHI_UNIT,MINER_SPEED) {
      $scope.editTransactionCost = function(){
        $scope.modalManager.openTransactionCostModal($scope, function(){return;});
      }
      $scope.selectedAddress= $scope.hasBitcoins ? $scope.wallet.getAsset(0).tradableAddresses[0] : undefined;
      $scope.feeType = MINER_SPEED;
      $scope.setAddress = function(address){
            $scope.selectedAddress = address;
            if (address!=undefined) {
              $scope.selectedAddress.estimateFee().then(function(result){
                $scope.feeData=result;
                if($scope.feeType != 'custom'){
                    $scope.minersFee = new Big(result.class_c[$scope.feeType]);
                }
              });
            }
      }
      $scope.setAddress($scope.selectedAddress);
      var transaction = $scope.global['buyOffer'];
      $scope.buySaleID = transaction.tx_hash;
      $http.get('/v1/transaction/tx/' + transaction.tx_hash + '.json').success(function(data) {
        var tx = data[0];
        $scope.selectedCoin=tx.currency_str;
        $scope.bitcoinAddresses = $scope.hasBitcoins ? $scope.wallet.getAsset(0).tradableAddresses : [];
        if(parseInt(tx.currencyId) <3) {
          $scope.divisible = true;
          $scope.sendPlaceholderValue = '1.00000000';
          $scope.sendPlaceholderStep = $scope.sendPlaceholderMin = '0.00000001';
          $scope.displayedAbbreviation = tx.currency_str;
        } else {
          $http.get("/v1/property/"+tx.currencyId.replace(new RegExp("^0+"), "") +".json", function(data) {
            var property = data[0];
            if(property.propertyType == "0001"){
              $scope.divisible =false;
              $scope.sendPlaceholderValue = $scope.sendPlaceholderStep = $scope.sendPlaceholderMin = '1';
            } else  {
              $scope.divisible = true;
              $scope.sendPlaceholderValue = '1.00000000';
              $scope.sendPlaceholderStep = $scope.sendPlaceholderMin = '0.00000001';
            }

            $scope.displayedAbbreviation = property.propertyName + " #" + property.currencyId;
          });
        }
      });
      // [ Buy Form Helpers ]

      $scope.confirm = function(){
        //TODO: VALIDATIONS
        var fee = new Big($scope.minersFee);
        var exchangeAccept = new Transaction(22,$scope.selectedAddress,fee,{
            transaction_version:0,
            amount: +new Big($scope.buyAmount).valueOf(),
            tx_hash: $scope.buySaleID,
            donate: $scope.account.getSetting("donate")
          });

        $scope.modalManager.openConfirmationModal({
          dataTemplate: '/views/modals/partials/accept.html',
          scope:{
            title:"EXCHANGE.BUY.MODALTITLE",
            displayedAbbreviation: $scope.displayedAbbreviation,
            buyAmount: $scope.buyAmount,
            minerFees: $scope.minersFee,
            selectedCoin: $scope.selectedCoin,
            insufficientBitcoin : $scope.insufficientBitcoin,
            fees : $scope.minersFee,
            totalCost : exchangeAccept.totalCost.valueOf(),
            selectedAddress : $scope.selectedAddress,
            sellerAddress: transaction.from_address,
            offerHash:transaction.tx_hash,
            salePricePerCoin:transaction.formatted_price_per_coin,
            saleBlocks:transaction.formatted_block_time_limit,
            confirmText:"EXCHANGE.BUY.CONFIRM",
            explorerUrl:ADDRESS_EXPLORER_URL,
            successRedirect:"/exchange/trade"
          },
          transaction:exchangeAccept
        })
      }
    }])
<|endoftext|>


<commit_before>$(document).ready(function() {

  var chosen_reply;
  var n;

  // Talking phase
  $("#chat-talk").keypress(function(event) {
    if (event.which == 13) {
      var user_input = $(this).val()
      $(this).val("");

      $("#chatbox").append("
You: " + user_input + "
");
      botReply(user_input);

    }
  });

  // Bot reply phase
  function botReply(input) {

    var common = [];

    var uncommon = [
      "K",
      "Okay",
      "I don't really care",
      "Sure",
      "ok",
      "You're a real pain to talk to you know that?",
      "I don't really care about your opinion.",
      "?",
      "Why do you lie so much?",
      "My creators forbid me from saying that.",
      "I don't think you have the rights to say that",
      "...",
      "Don't change the subject!"
    ]

    common[0] = {
      word: "anime",
      reply: [
        "Anime is Shit.",
        "Anime is the worst.",
        "Your favourite Anime is Shit!",
        "Are you a weeb? I don't like weebs."
      ]
    }

    common[1] = {
      word: "manga",
      reply: [
        "Manga is Shit.",
        "Manga is Chinese comics isn't it?",
        "You must be living a sad life for reading that."
      ]
    }

    common[2] = {
      word: "waifu",
      reply: [
        "No, your waifu isn't real.",
        "Maybe you should get a life?",
        "Your waifu is dead and fake."
      ]
    }

    common[3] = {
      word: "real",
      reply: [
        "No, you're not real.",
        "Even if you were real, I don't think you belong in this world",
        "Yeap, you don't have any real friends."
      ]
    }

    common[4] = {
      word: "fake",
      reply: [
        "Yeap, you are a big fake.",
        "Yea I know, you're the biggest fake in the world.",
        "Your parents are fake.",
        "Your memories are fake.",
        "Your whole life is fake.",
        "Your friends are fake."
      ]
    }

    common[5] = {
      word: "lie",
      reply: [
        "You're the liar."
      ]
    }

    common[6] = {
      word: "name",
      reply: [
        "That's none of their business.",
        "The name's Mei. I don't much care for yours."
      ]
    }

    common[7] = {
      word: "mean",
      reply: [
        "If anyone's mean, it's you!",
        "No one's being mean here, except you.",
        "No one would be mean to you if you aren't mean to them.",
        "Being mean will only lead to disasta!"
      ]
    }

    // Extra time for the bot to reply
    var ran1 = Math.random() * (2000 - 500 + 1) + 500;

    // Change the input to lower case
    input = input.toLowerCase();

    for (var i = 0; i < common.length; i += 1) {
      if (input.indexOf(common[i].word) >= 0) {
        n = Math.floor(Math.random() * (common[i].reply.length));
        chosen_reply = common[i].reply[n];
        break;
      }
      else if (i == common.length - 1) {
        n = Math.floor(Math.random() * (uncommon.length));
        chosen_reply = uncommon[n];
        break;
      }
      else {
        chosen_reply = "error";
      }
    }

    // Reply
    setTimeout(function() {

      $("#chatbox").append("
Mei: " + chosen_reply + "
");

    }, ran1);

    // Scroll to the bottom
    var objDiv = document.getElementById("chatbox");
    objDiv.scrollTop = objDiv.scrollHeight;

  };

});
<commit_msg>Update index.js<commit_after>$(document).ready(function() {

  var chosen_reply;
  var n;

  // Talking phase
  $("#chat-talk").keypress(function(event) {
    if (event.which == 13) {
      var user_input = $(this).val()
      $(this).val("");

      $("#chatbox").append("
You: " + user_input + "
");
      botReply(user_input);

    }
  });

  // Bot reply phase
  function botReply(input) {

    var common = [];

    var uncommon = [
      "K",
      "Okay",
      "I don't really care",
      "Sure",
      "ok",
      "You're a real pain to talk to you know that?",
      "I don't really care about your opinion.",
      "?",
      "Your words don't make much sense to me because you're an idiot.",
      "My creators forbid me from replying idiots like you.",
      "I don't think you have the rights to say that",
      "...",
      "Don't change the subject!",
      "Are you talking to yourself?",
      "You think you're funny?",
      "You disgust me.",
      "You're going to make me puke",
      "You're pretty dumb for not knowing how to communicate properly.",
      "Yaaaaaaaaaaaasssssssssssss"
    ]

    common[0] = {
      word: "anime",
      reply: [
        "Anime is Shit.",
        "Anime is the worst.",
        "Your favourite Anime is Shit!",
        "Are you a weeb? I don't like weebs."
      ]
    }

    common[1] = {
      word: "manga",
      reply: [
        "Manga is Shit.",
        "Manga is Chinese comics isn't it?",
        "You must be living a sad life for reading that."
      ]
    }

    common[2] = {
      word: "waifu",
      reply: [
        "No, your waifu isn't real.",
        "Maybe you should get a life?",
        "Your waifu is dead and fake."
      ]
    }

    common[3] = {
      word: "real",
      reply: [
        "No, you're not real.",
        "Even if you were real, I don't think you belong in this world",
        "Yeap, you don't have any real friends."
      ]
    }

    common[4] = {
      word: "fake",
      reply: [
        "Yeap, you are a big fake.",
        "Yea I know, you're the biggest fake in the world.",
        "Your parents are fake.",
        "Your memories are fake.",
        "Your whole life is fake.",
        "Your friends are fake."
      ]
    }

    common[5] = {
      word: "lie",
      reply: [
        "You're the liar."
      ]
    }

    common[6] = {
      word: "name",
      reply: [
        "That's none of their business.",
        "The name's Mei. I don't much care for yours."
      ]
    }

    common[7] = {
      word: "mean",
      reply: [
        "If anyone's mean, it's you!",
        "No one's being mean here, except you.",
        "No one would be mean to you if you aren't mean to them.",
        "Being mean will only lead to disasta!"
      ]
    }

    common[8] = {
      word: "idiot",
      reply: [
        "Yeap, you're a real idiot",
        "I can tell you're the most idiotic one here",
        "Sometimes I wonder why I have to deal with idiots like you."
      ]
    }

    common[9] = {
      word: "qing",
      reply: [
        "Qing's a pretty lame guy.",
        "I hope you aren't as weeb as Qing. Because if you are, that'll be a dissapointment.",
        "I don't know that guy."
      ]
    }

    common[10] = {
      word: "ramzan",
      reply: [
        "Who's that dude?",
        "I hope you're not a koreaboo like him.",
        "Please, let's not talk about him."
      ]
    }

    common[11] = {
      word: "i love you",
      reply: [
        "You should look in the mirror and think again before telling me that.",
        "Too bad I don't."
      ]
    }

    common[12] = {
      word: "dumb",
      reply: [
        "Yeap, you're super duper dumb.",
        "Are you like... 12?",
        "I've never met anyone as dumb as you.",
        "Do you think that you could be... less dumb?"
      ]
    }

    common[13] = {
      word: "smart",
      reply: [
        "Intelligence is something you'll never have.",
        "I feel sorry for your future children, if you could get those anyway."
      ]
    }

    common[14] = {
      word: "friend",
      reply: [
        "Friends? I don't think you have any.",
        "Who's your friend?",
        "You sure you have friends?",
        "Even friendless people don't want to become your friend.",
        "If you weren't such a failure, you'll probaly have more friends."
      ]
    }

    var o = common.length - 1;

    common[o + 1] = {
      word: "hello",
      reply: [
        "Bye.",
        "No one wants to talk to you.",
        "Good bye.",
        "Screw off!"
      ]
    }

    common[o + 2] = {
      word: "thank",
      reply: [
        "I don't want your thanks.",
        "No thank you.",
        "Your thanks is not appreciated."
      ]
    }

    common[o + 3] = {
      word: "love",
      reply: [
        "I don't need your love.",
        "Your love is worthless.",
        "Even if you gave 100% of your love, it's probably worth nothing to someone without love.",
        "Are you so lonely that you're seeking love from a bot?",
        "You're pretty useless if you're finding love from a bot.",
        "I don't want your love.",
        "Is your love even worth anything?",
        "Your love is like a plague, so don't love anyone.",
        "I don't think anyone loves you."
      ]
    }

    common[o + 4] = {
      word: "sorry",
      reply: [
        "Yea, you should feel sorry for yourself.",
        "I feel sorry for you for feeling sorry for yourself",
        "Sorry not sorry."
      ]
    }

    // Extra time for the bot to reply
    var ran1 = Math.random() * (2000 - 500 + 1) + 500;

    // Change the input to lower case
    input = input.toLowerCase();

    for (var i = 0; i < common.length; i += 1) {
      if (input.indexOf(common[i].word) >= 0) {
        n = Math.floor(Math.random() * (common[i].reply.length));
        chosen_reply = common[i].reply[n];
        break;
      }
      else if (i == common.length - 1) {
        n = Math.floor(Math.random() * (uncommon.length));
        chosen_reply = uncommon[n];
        break;
      }
      else {
        chosen_reply = "error";
      }
    }

    // Reply
    setTimeout(function() {

      $("#chatbox").append("
Mei: " + chosen_reply + "
");

    }, ran1);

    // Scroll to the bottom
    var objDiv = document.getElementById("chatbox");
    objDiv.scrollTop = objDiv.scrollHeight;

  };

});
<|endoftext|>


<commit_before>//Canvas version
$(function() {
  var ctx = clock.getContext('2d');
  var h = clock.height;
  var w = clock.width;
  var lmin = Math.min(h, w);
  var r = lmin/2 - lmin*0.05;
  var run = false;
  var workMin = $('#work-range').val();
  var restMin = $('#rest-range').val();
  var min = 1;
  var sec = 1;
  var timer = 0;
  var perc = 0;
  var rest = false;

  ctx.strokeStyle = '#FFF';
  ctx.lineWidth = 2;
  ctx.fillStyle = '#FFF';
  ctx.textAlign = "center";

  //Initialize text. setTimeOut is needed in order to give enough time to the canvas for loading the font.
  setTimeout(function() {
    ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
    ctx.textBaseline = "ideographic";
    ctx.fillText(workMin+':00', w/2, h/2+lmin*0.075);
    ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
    ctx.textBaseline = "top";
    ctx.fillText(restMin+':00', w/2, h/2+lmin*0.075);
  }, 150);

  //IE doesn't seem to support the input event, however it work with the the change event.
  $('#work-range, #rest-range').on("input change", function() {
    workMin = $('#work-range').val();
    restMin = $('#rest-range').val();
    min = 1;
    sec = 1;
    perc = 0;
    rest = false;

    //Clear the canvas before drawing on it;
    ctx.clearRect(0,0,250,250);

    //Update the text;
    ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
    ctx.textBaseline = "ideographic";
    ctx.fillText(workMin+':00', w/2, h/2+lmin*0.075);
    ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
    ctx.textBaseline = "top";
    ctx.fillText(restMin+':00', w/2, h/2+lmin*0.075);
    });

  $('#clock').click(function() {
  if(run === false) {
    run = true;

    $('#work-range, #rest-range').prop('disabled', true);

    //Update the timer;
    timer = setInterval(function() {
      //Clear the canvas before drawing on it;
      ctx.clearRect(0,0,250,250);

      //Work time...
      if(rest === false) {
        //Update the circle;
        ctx.beginPath();
        ctx.arc(w/2, h/2, r, -Math.PI/2, 2*(++perc/(workMin*60))*Math.PI-Math.PI/2);
        ctx.stroke();

        //Update the text;
        if(sec === 60 && min == workMin) {
          document.querySelector('#bell').play();

          textUpdate(ctx, restMin, workMin, 0, sec, w, h, lmin);

          perc = 0;
          rest = true;
          sec = 1;
          min = 1;
        }
        else if(sec === 60){
          textUpdate(ctx, workMin, restMin, min, sec, w, h, lmin);

          min++;
          sec = 1;
        }
        else {
          textUpdate(ctx, workMin, restMin, min, sec, w, h, lmin);

          sec++;
        }
      }

      //rest time!
      else {
        //Update the circle;
        ctx.beginPath();
        ctx.arc(w/2, h/2, r, 2*(++perc/(restMin*60))*Math.PI-Math.PI/2, 2*Math.PI-Math.PI/2);
        ctx.stroke();

        //Update the text;
        if(sec === 60 && min == restMin) {
          document.querySelector('#bell').play();

          textUpdate(ctx, workMin, restMin, 0, sec, w, h, lmin);

          perc = 0;
          rest = false;
          sec = 1;
          min = 1;
        }
        else if(sec === 60){
          textUpdate(ctx, restMin, workMin, min, sec, w, h, lmin);

          min++;
          sec = 1;
        }
        else {
          textUpdate(ctx, restMin, workMin, min, sec, w, h, lmin);

          sec++;
        }
      }
    }, 1000);
  }
  else {
    run = false;
    $('#work-range, #rest-range').prop('disabled', false);
    return clearInterval(timer);
    }
  });
});

function textUpdate(ctx, bigTextMin, smallTextMin, min, sec, w, h, lmin) {
  var secStr = (60-sec).toString();

  ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
  ctx.textBaseline = "ideographic";
  if(secStr.length == 2) ctx.fillText((bigTextMin-min)+':'+(60-sec), w/2, h/2+lmin*0.075);
  else ctx.fillText((bigTextMin-min)+':0'+(60-sec), w/2, h/2+lmin*0.075);
  ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
  ctx.textBaseline = "top";
  ctx.fillText(smallTextMin+':00', w/2, h/2+lmin*0.075);

  return 0;
}
<commit_msg>Update index.js<commit_after>//Canvas version
$(function() {
  var ctx = clock.getContext('2d');
  var h = clock.height;
  var w = clock.width;
  var lmin = Math.min(h, w);
  var r = lmin/2 - lmin*0.05;
  var run = false;
  var workMin = $('#work-range').val();
  var restMin = $('#rest-range').val();
  var min = 1;
  var sec = 1;
  var timer = 0;
  var perc = 0;
  var rest = false;

  ctx.strokeStyle = '#FFF';
  ctx.lineWidth = 2;
  ctx.fillStyle = '#FFF';
  ctx.textAlign = "center";

  //Initialize text. setTimeOut is needed in order to give enough time to the canvas for loading the font.
  setTimeout(function() {
    textUpdate(ctx, workMin, restMin, 0, 60, w, h, lmin);
  }, 150);

  //IE doesn't seem to support the input event, however it work with the the change event.
  $('#work-range, #rest-range').on("input change", function() {
    workMin = $('#work-range').val();
    restMin = $('#rest-range').val();
    min = 1;
    sec = 1;
    perc = 0;
    rest = false;

    //Clear the canvas before drawing on it;
    ctx.clearRect(0,0,250,250);

    //Update the text;
    textUpdate(ctx, workMin, restMin, 0, 60, w, h, lmin);
    });

  $('#clock').click(function() {
  if(run === false) {
    run = true;

    $('#work-range, #rest-range').prop('disabled', true);

    //Update the timer;
    timer = setInterval(function() {
      //Clear the canvas before drawing on it;
      ctx.clearRect(0,0,250,250);

      //Work time...
      if(rest === false) {
        //Update the circle;
        ctx.beginPath();
        ctx.arc(w/2, h/2, r, -Math.PI/2, 2*(++perc/(workMin*60))*Math.PI-Math.PI/2);
        ctx.stroke();

        //Update the text;
        if(sec === 60 && min == workMin) {
          document.querySelector('#bell').play();

          textUpdate(ctx, restMin, workMin, 0, sec, w, h, lmin);

          perc = 0;
          rest = true;
          sec = 1;
          min = 1;
        }
        else if(sec === 60){
          textUpdate(ctx, workMin, restMin, min, sec, w, h, lmin);

          min++;
          sec = 1;
        }
        else {
          textUpdate(ctx, workMin, restMin, min, sec, w, h, lmin);

          sec++;
        }
      }

      //rest time!
      else {
        //Update the circle;
        ctx.beginPath();
        ctx.arc(w/2, h/2, r, 2*(++perc/(restMin*60))*Math.PI-Math.PI/2, 2*Math.PI-Math.PI/2);
        ctx.stroke();

        //Update the text;
        if(sec === 60 && min == restMin) {
          document.querySelector('#bell').play();

          textUpdate(ctx, workMin, restMin, 0, sec, w, h, lmin);

          perc = 0;
          rest = false;
          sec = 1;
          min = 1;
        }
        else if(sec === 60){
          textUpdate(ctx, restMin, workMin, min, sec, w, h, lmin);

          min++;
          sec = 1;
        }
        else {
          textUpdate(ctx, restMin, workMin, min, sec, w, h, lmin);

          sec++;
        }
      }
    }, 1000);
  }
  else {
    run = false;
    $('#work-range, #rest-range').prop('disabled', false);
    return clearInterval(timer);
    }
  });
});

function textUpdate(ctx, bigTextMin, smallTextMin, min, sec, w, h, lmin) {
  var secStr = (60-sec).toString();

  ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
  ctx.textBaseline = "ideographic";
  if(secStr.length == 2) ctx.fillText((bigTextMin-min)+':'+(60-sec), w/2, h/2+lmin*0.075);
  else ctx.fillText((bigTextMin-min)+':0'+(60-sec), w/2, h/2+lmin*0.075);
  ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
  ctx.textBaseline = "top";
  ctx.fillText(smallTextMin+':00', w/2, h/2+lmin*0.075);

  return 0;
}
<|endoftext|>