file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
hh.js
'use strict'; require('test'); var tpl = Set.Class({ constructor: function() { }, isCompress: false, bound:{left:'{', right:'}'}, boundChar: '%', command: {cond:1, echo:1, getv:1, code:1, for:0, foreach:0, if:3, elseif:3, else:3, html:0, block:0, head:0, body:0, phpend:0}, isNewEngine: ''.trim, replaces: this.isNewEngine? ["$out='';", "$out+=", ";", "$out"] : ["$out=[];", "$out.push(", ");", "$out.join('')"], concat: this.isNewEngine ? "if(content!==undefined){$out+=content;return content;}" : "$out.push(content);", compile: function (id, source) { var params = arguments; var anonymous = 'anonymous'; if (typeof source !== 'string') { source = params[0]; id = anonymous; } try { var Render = _compile(id, source); //编译时错误 } catch (e) { e.id = id || source; e.name = 'Syntax Error'; _debug(e); throw(e); } function render (data) { try { return new Render(data, id) + ''; //运行时错误捕捉 } catch (e) { _debug(e)(); throw(e); } } render.prototype = Render.prototype; render.toString = function () { return Render.toString(); }; if (id !== anonymous) { _cache[id] = render;
return render; }, render: function (id, data) { var cache = template.get(id) || _debug({ id: id, name: 'Render Error', message: 'No Template' }); return cache(data); }, mapFn: function(func) { var partialTpl = ''; switch(func.f) { case 'cond': partialTpl = setLBound+ func.v +setRBound+setLBlock; break; case 'echo': partialTpl = template.isCompress ? partialTpl = compress(func.v) : func.v; partialTpl = replaces[1]+ stringify(partialTpl) +replaces[2]; break; case 'getv': partialTpl = replaces[1]+ func.v +replaces[2]; break; case 'code': partialTpl = func.v; break; case 'for': partialTpl = 'for'; break; case 'foreach': partialTpl = 'foreach'; break; case 'if': partialTpl = 'if'; break; case 'elseif': partialTpl = 'else if'; break; case 'else': partialTpl = 'else'; break; } return partialTpl; }, parseFn: function(input, pos) {//pos为 ( 的位置 var func = '', fVal = '', currChar = '', stack = 1, end = 0; while(currChar=input.charAt(++pos)) { if(end) break;//在这步结束之前多扫了一个字符 if(isEChar(currChar)&&trim(func)!='' || currChar=='(') { func = trim(func); if(fTbl[func]){//如果是终结作用,终结作用右侧不应该有作用 while(currChar=input.charAt(++pos)) { if(currChar==setLBound){ stack++; } else if(currChar==setRBound) {//终结作用集结束 stack--; } if(stack==0){//栈空结束 end = 1; fVal = trim(fVal); break; } fVal += currChar; } } else { break; } } else { func += currChar; } } return {f:func, v:fVal, p:pos-1}; }, syntaxParse: function(code) { var boundChar = this.boundChar, leftBound = this.bound.left, rightBound = this.bound.right, command = this.command, NODETYPE_STR = 0, NODETYPE_OPEN = 1, tokens = [], begin = 0, forward = 0, forwardChar = '', func = '', codeLength = code.length, lastNode = null, currentNode = null, newNode = null; while(forward < codeLength) { //每次吃进一个字符,只有边界和命令做为独立单元解析,其他统一当做普通字符串处理 forwardChar = code.charAt(forward); if(forwardChar == leftBound) { //左边界 forwardChar = code.charAt(++forward); //前进一个字符 if(forwardChar == boundChar) { //如果左边界定位符匹配,进入命令解析 tokens.push({fn:'str', begin:begin, forward:forward-1, nodeType:NODETYPE_INIT}); //推入上一次结束边界到这次开始边界之间字符 begin = forward + 1; //起始指针位置加1 while(forwardChar = code.charAt(++forward)) {//这个循环寻找命令边界,找到结束,进行下一轮的正常扫描 if((isEChar(forwardChar) && trim(code.substring(begin, forward)) != '') || (forwardChar == leftBound && code.charAt(forward+1) == boundChar) || (forwardChar == boundChar && code.charAt(forward+1) == rightBound)) { func = trim(code.substring(begin, forward)); if(command[func] == undefined || func == '') { Set.Logger.error(func + ' not exists'); break;//抛出异常,函数不存在 } tokens.push({fn:func, begin:begin, forward:forward, nodeType:NODETYPE_OPEN}); begin = forward; forward --; //因为在总循环中forward要加1,所以这里要减去1,否则总循环扫描将错过一个字符 break; } } } } else if(forwardChar == rightBound) {//右边界 forwardChar = code.charAt(forward-1); //回溯匹配边界字符 if(forwardChar == boundChar) {//碰到close边界出栈一个open边界,和边界之前的字符命令 tokens.push({fn:'str', begin:begin, forward:forward-1, nodeType:NODETYPE_STR}); lastNode = null; while(currentNode = tokens.pop()) { if(currentNode.nodeType == 1) { newNode = currentNode; newNode.tp = lastNode; break; } else { if(currentNode.nodeType == 4) currentNode.hp.hp = lastNode; else currentNode.hp = lastNode; lastNode = currentNode; } } if(newNode.nodeType!=1) throw new Error('open match error'); currentNode = tokens.pop(); currentNode.nodeType = 4;//衔接节点 currentNode.hp = newNode; newNode.nodeType = 2; tokens.push(currentNode); begin = forward + 1; } } forward++; } tokens.push({fn:'str', begin:begin, forward:forward, nodeType:0}); return tokens; } }); new tpl(); /** * 模板引擎 * 若第二个参数类型为 String 则执行 compile 方法, 否则执行 render 方法 * @name template * @param {String} 模板ID * @param {Object, String} 数据或者模板字符串 * @return {String, Function} 渲染好的HTML字符串或者渲染方法 */ var template = function (id, content) { return template[ typeof content === 'string' ? 'compile' : 'render' ].apply(template, arguments); }; template.isEscape = true; // HTML字符编码输出开关 template.isCompress = false; // 剔除渲染后HTML多余的空白开关 var _cache = template.cache = {}; /** * 渲染模板 * @name template.render * @param {String} 模板ID * @param {Object} 数据 * @return {String} 渲染好的HTML字符串 */ template.render = function (id, data) { var cache = template.get(id) || _debug({ id: id, name: 'Render Error', message: 'No Template' }); return cache(data); }; /** * 编译模板 * 2012-6-6 @TooBug: define 方法名改为 compile,与 Node Express 保持一致 * @name template.compile * @param {String} 模板ID (可选,用作缓存索引) * @param {String} 模板字符串 * @return {Function} 渲染方法 */ template.compile = function (id, source) { var params = arguments; var anonymous = 'anonymous'; if (typeof source !== 'string') { source = params[0]; id = anonymous; } try { var Render = _compile(id, source); //编译时错误 } catch (e) { e.id = id || source; e.name = 'Syntax Error'; _debug(e); throw(e); } function render (data) { try { return new Render(data, id) + ''; //运行时错误捕捉 } catch (e) { _debug(e)(); throw(e); } } render.prototype = Render.prototype; render.toString = function () { return Render.toString(); }; if (id !== anonymous) { _cache[id] = render; } return render; }; // 获取模板缓存 template.get = function (id) { var cache; if (_cache.hasOwnProperty(id)) { cache = _cache[id]; } else if ('document' in global) { var elem = document.getElementById(id); if (elem) { var source = elem.value || elem.innerHTML; cache = template.compile(id, source.replace(/^\s*|\s*$/g, '')); } } return cache; }; // 模板调试器 var _debug = function (e) { template.onerror(e); return function () { return '{Template Error}'; }; }; var _compile = (function () { // 数组迭代 return function (id, source) { var prototype = {}; var isNewEngine = ''.trim;// '__proto__' in {} var replaces = isNewEngine ? ["$out='';", "$out+=", ";", "$out"] : ["$out=[];", "$out.push(", ");", "$out.join('')"]; var concat = isNewEngine ? "if(content!==undefined){$out+=content;return content;}" : "$out.push(content);"; /* * 需要增加include方法和print方法 * */ var code = source, tempCode = replaces[0], l = code.length, i = 0, currChar = '', currFunc = '', nfChar = '', setLBound = '(', setRBound = ')', setLBlock = '{', setRBlock = '}', lastC = 0, fTbl = {cond:1, echo:1, getv:1, code:1, for:0, foreach:0, if:0, elseif:0, else:0}; while(i<l) { currChar = code.charAt(i); switch(currChar) { case setLBound: if(!isEString(nfChar)) tempCode += mapping({f:'echo', v:nfChar, p:-1}); currFunc = getFunc(code, i); tempCode += mapping(currFunc); i = currFunc.p; nfChar = ''; break; case setRBound: if(!isEString(nfChar)) tempCode += mapping({f:'echo', v:nfChar, p:-1}); tempCode += setRBlock; nfChar = ''; break; default: nfChar += currChar; break; } i++; } if(!isEString(nfChar)) tempCode += mapping({f:'echo', v:nfChar, p:-1}); tempCode+='return new String(' + replaces[3] + ');'; try { var Render = new Function("$data", "$id", tempCode); Render.prototype = prototype; return Render; } catch (e) { e.temp = "function anonymous($data,$id) {" + tempCode + "}"; throw e; } function getFunc(input, pos) {//pos为 ( 的位置 var func = '', fVal = '', currChar = '', stack = 1, end = 0; while(currChar=input.charAt(++pos)) { if(end) break;//在这步结束之前多扫了一个字符 if(isEChar(currChar)&&trim(func)!='' || currChar=='(') { func = trim(func); if(fTbl[func]){//如果是终结作用,终结作用右侧不应该有作用 while(currChar=input.charAt(++pos)) { if(currChar==setLBound){ stack++; } else if(currChar==setRBound) {//终结作用集结束 stack--; } if(stack==0){//栈空结束 end = 1; fVal = trim(fVal); break; } fVal += currChar; } } else { break; } } else { func += currChar; } } return {f:func, v:fVal, p:pos-1}; } function mapping(func) { var partialTpl = ''; switch(func.f) { case 'cond': partialTpl = setLBound+ func.v +setRBound+setLBlock; break; case 'echo': partialTpl = template.isCompress ? partialTpl = compress(func.v) : func.v; partialTpl = replaces[1]+ stringify(partialTpl) +replaces[2]; break; case 'getv': partialTpl = replaces[1]+ func.v +replaces[2]; break; case 'code': partialTpl = func.v; break; case 'for': partialTpl = 'for'; break; case 'foreach': partialTpl = 'foreach'; break; case 'if': partialTpl = 'if'; break; case 'elseif': partialTpl = 'else if'; break; case 'else': partialTpl = 'else'; break; } return partialTpl; } function trim(text) { if(String.prototype.trim && !String.prototype.trim.call("\uFEFF\xA0")) { return text == null ? "" : String.prototype.trim.call(text); } else { var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; return text == null ? "" : ( text + "" ).replace(rtrim, ""); } } function isEChar(c) { return /\s/.test(c); } function isEString(c) { return !/\S/.test(c); } function compress(text) { return text.replace(/[ \n\v\f\r\t]+/g, " ") .replace(/<!--.*?-->/g, ''); } // 字符串转义 function stringify (code) { return "'" + code // 单引号与反斜杠转义 .replace(/('|\\)/g, '\\$1') // 换行符转义(windows + linux) .replace(/\r/g, '\\r') .replace(/\n/g, '\\n') + "'"; }; }; })(); //////////////////////////////////////////////////////////////////////// // 辅助方法集合 var _helpers = template.helpers = { $include: template.render, $string: function (value, type) { if (typeof value !== 'string') { type = typeof value; if (type === 'number') { value += ''; } else if (type === 'function') { value = _helpers.$string(value()); } else { value = ''; } } return value; }, $escape: function (content) { var m = { "<": "&#60;", ">": "&#62;", '"': "&#34;", "'": "&#39;", "&": "&#38;" }; return _helpers.$string(content) .replace(/&(?![\w#]+;)|[<>"']/g, function (s) { return m[s]; }); }, $each: function (data, callback) { var isArray = Array.isArray || function (obj) { return ({}).toString.call(obj) === '[object Array]'; }; if (isArray(data)) { for (var i = 0, len = data.length; i < len; i++) { callback.call(data, data[i], i, data); } } else { for (i in data) { callback.call(data, data[i], i); } } } }; /** * 模板错误事件 * @name template.onerror * @event */ template.onerror = function (e) { var message = 'Template Error\n\n'; for (var name in e) { message += '<' + name + '>\n' + e[name] + '\n\n'; } if (global.console) { console.error(message); } }; // RequireJS && SeaJS if (typeof define === 'function') { define(function() { return template; }); // NodeJS } else if (typeof exports !== 'undefined') { module.exports = template; } global.template = template; /* * 模板放置位置 * 模板新增方法 * 模板管理 * 模板引入 * 模板加载 * * * */
}
random_line_split
hh.js
'use strict'; require('test'); var tpl = Set.Class({ constructor: function() { }, isCompress: false, bound:{left:'{', right:'}'}, boundChar: '%', command: {cond:1, echo:1, getv:1, code:1, for:0, foreach:0, if:3, elseif:3, else:3, html:0, block:0, head:0, body:0, phpend:0}, isNewEngine: ''.trim, replaces: this.isNewEngine? ["$out='';", "$out+=", ";", "$out"] : ["$out=[];", "$out.push(", ");", "$out.join('')"], concat: this.isNewEngine ? "if(content!==undefined){$out+=content;return content;}" : "$out.push(content);", compile: function (id, source) { var params = arguments; var anonymous = 'anonymous'; if (typeof source !== 'string') { source = params[0]; id = anonymous; } try { var Render = _compile(id, source); //编译时错误 } catch (e) { e.id = id || source; e.name = 'Syntax Error'; _debug(e); throw(e); } function render (da
try { return new Render(data, id) + ''; //运行时错误捕捉 } catch (e) { _debug(e)(); throw(e); } } render.prototype = Render.prototype; render.toString = function () { return Render.toString(); }; if (id !== anonymous) { _cache[id] = render; } return render; }, render: function (id, data) { var cache = template.get(id) || _debug({ id: id, name: 'Render Error', message: 'No Template' }); return cache(data); }, mapFn: function(func) { var partialTpl = ''; switch(func.f) { case 'cond': partialTpl = setLBound+ func.v +setRBound+setLBlock; break; case 'echo': partialTpl = template.isCompress ? partialTpl = compress(func.v) : func.v; partialTpl = replaces[1]+ stringify(partialTpl) +replaces[2]; break; case 'getv': partialTpl = replaces[1]+ func.v +replaces[2]; break; case 'code': partialTpl = func.v; break; case 'for': partialTpl = 'for'; break; case 'foreach': partialTpl = 'foreach'; break; case 'if': partialTpl = 'if'; break; case 'elseif': partialTpl = 'else if'; break; case 'else': partialTpl = 'else'; break; } return partialTpl; }, parseFn: function(input, pos) {//pos为 ( 的位置 var func = '', fVal = '', currChar = '', stack = 1, end = 0; while(currChar=input.charAt(++pos)) { if(end) break;//在这步结束之前多扫了一个字符 if(isEChar(currChar)&&trim(func)!='' || currChar=='(') { func = trim(func); if(fTbl[func]){//如果是终结作用,终结作用右侧不应该有作用 while(currChar=input.charAt(++pos)) { if(currChar==setLBound){ stack++; } else if(currChar==setRBound) {//终结作用集结束 stack--; } if(stack==0){//栈空结束 end = 1; fVal = trim(fVal); break; } fVal += currChar; } } else { break; } } else { func += currChar; } } return {f:func, v:fVal, p:pos-1}; }, syntaxParse: function(code) { var boundChar = this.boundChar, leftBound = this.bound.left, rightBound = this.bound.right, command = this.command, NODETYPE_STR = 0, NODETYPE_OPEN = 1, tokens = [], begin = 0, forward = 0, forwardChar = '', func = '', codeLength = code.length, lastNode = null, currentNode = null, newNode = null; while(forward < codeLength) { //每次吃进一个字符,只有边界和命令做为独立单元解析,其他统一当做普通字符串处理 forwardChar = code.charAt(forward); if(forwardChar == leftBound) { //左边界 forwardChar = code.charAt(++forward); //前进一个字符 if(forwardChar == boundChar) { //如果左边界定位符匹配,进入命令解析 tokens.push({fn:'str', begin:begin, forward:forward-1, nodeType:NODETYPE_INIT}); //推入上一次结束边界到这次开始边界之间字符 begin = forward + 1; //起始指针位置加1 while(forwardChar = code.charAt(++forward)) {//这个循环寻找命令边界,找到结束,进行下一轮的正常扫描 if((isEChar(forwardChar) && trim(code.substring(begin, forward)) != '') || (forwardChar == leftBound && code.charAt(forward+1) == boundChar) || (forwardChar == boundChar && code.charAt(forward+1) == rightBound)) { func = trim(code.substring(begin, forward)); if(command[func] == undefined || func == '') { Set.Logger.error(func + ' not exists'); break;//抛出异常,函数不存在 } tokens.push({fn:func, begin:begin, forward:forward, nodeType:NODETYPE_OPEN}); begin = forward; forward --; //因为在总循环中forward要加1,所以这里要减去1,否则总循环扫描将错过一个字符 break; } } } } else if(forwardChar == rightBound) {//右边界 forwardChar = code.charAt(forward-1); //回溯匹配边界字符 if(forwardChar == boundChar) {//碰到close边界出栈一个open边界,和边界之前的字符命令 tokens.push({fn:'str', begin:begin, forward:forward-1, nodeType:NODETYPE_STR}); lastNode = null; while(currentNode = tokens.pop()) { if(currentNode.nodeType == 1) { newNode = currentNode; newNode.tp = lastNode; break; } else { if(currentNode.nodeType == 4) currentNode.hp.hp = lastNode; else currentNode.hp = lastNode; lastNode = currentNode; } } if(newNode.nodeType!=1) throw new Error('open match error'); currentNode = tokens.pop(); currentNode.nodeType = 4;//衔接节点 currentNode.hp = newNode; newNode.nodeType = 2; tokens.push(currentNode); begin = forward + 1; } } forward++; } tokens.push({fn:'str', begin:begin, forward:forward, nodeType:0}); return tokens; } }); new tpl(); /** * 模板引擎 * 若第二个参数类型为 String 则执行 compile 方法, 否则执行 render 方法 * @name template * @param {String} 模板ID * @param {Object, String} 数据或者模板字符串 * @return {String, Function} 渲染好的HTML字符串或者渲染方法 */ var template = function (id, content) { return template[ typeof content === 'string' ? 'compile' : 'render' ].apply(template, arguments); }; template.isEscape = true; // HTML字符编码输出开关 template.isCompress = false; // 剔除渲染后HTML多余的空白开关 var _cache = template.cache = {}; /** * 渲染模板 * @name template.render * @param {String} 模板ID * @param {Object} 数据 * @return {String} 渲染好的HTML字符串 */ template.render = function (id, data) { var cache = template.get(id) || _debug({ id: id, name: 'Render Error', message: 'No Template' }); return cache(data); }; /** * 编译模板 * 2012-6-6 @TooBug: define 方法名改为 compile,与 Node Express 保持一致 * @name template.compile * @param {String} 模板ID (可选,用作缓存索引) * @param {String} 模板字符串 * @return {Function} 渲染方法 */ template.compile = function (id, source) { var params = arguments; var anonymous = 'anonymous'; if (typeof source !== 'string') { source = params[0]; id = anonymous; } try { var Render = _compile(id, source); //编译时错误 } catch (e) { e.id = id || source; e.name = 'Syntax Error'; _debug(e); throw(e); } function render (data) { try { return new Render(data, id) + ''; //运行时错误捕捉 } catch (e) { _debug(e)(); throw(e); } } render.prototype = Render.prototype; render.toString = function () { return Render.toString(); }; if (id !== anonymous) { _cache[id] = render; } return render; }; // 获取模板缓存 template.get = function (id) { var cache; if (_cache.hasOwnProperty(id)) { cache = _cache[id]; } else if ('document' in global) { var elem = document.getElementById(id); if (elem) { var source = elem.value || elem.innerHTML; cache = template.compile(id, source.replace(/^\s*|\s*$/g, '')); } } return cache; }; // 模板调试器 var _debug = function (e) { template.onerror(e); return function () { return '{Template Error}'; }; }; var _compile = (function () { // 数组迭代 return function (id, source) { var prototype = {}; var isNewEngine = ''.trim;// '__proto__' in {} var replaces = isNewEngine ? ["$out='';", "$out+=", ";", "$out"] : ["$out=[];", "$out.push(", ");", "$out.join('')"]; var concat = isNewEngine ? "if(content!==undefined){$out+=content;return content;}" : "$out.push(content);"; /* * 需要增加include方法和print方法 * */ var code = source, tempCode = replaces[0], l = code.length, i = 0, currChar = '', currFunc = '', nfChar = '', setLBound = '(', setRBound = ')', setLBlock = '{', setRBlock = '}', lastC = 0, fTbl = {cond:1, echo:1, getv:1, code:1, for:0, foreach:0, if:0, elseif:0, else:0}; while(i<l) { currChar = code.charAt(i); switch(currChar) { case setLBound: if(!isEString(nfChar)) tempCode += mapping({f:'echo', v:nfChar, p:-1}); currFunc = getFunc(code, i); tempCode += mapping(currFunc); i = currFunc.p; nfChar = ''; break; case setRBound: if(!isEString(nfChar)) tempCode += mapping({f:'echo', v:nfChar, p:-1}); tempCode += setRBlock; nfChar = ''; break; default: nfChar += currChar; break; } i++; } if(!isEString(nfChar)) tempCode += mapping({f:'echo', v:nfChar, p:-1}); tempCode+='return new String(' + replaces[3] + ');'; try { var Render = new Function("$data", "$id", tempCode); Render.prototype = prototype; return Render; } catch (e) { e.temp = "function anonymous($data,$id) {" + tempCode + "}"; throw e; } function getFunc(input, pos) {//pos为 ( 的位置 var func = '', fVal = '', currChar = '', stack = 1, end = 0; while(currChar=input.charAt(++pos)) { if(end) break;//在这步结束之前多扫了一个字符 if(isEChar(currChar)&&trim(func)!='' || currChar=='(') { func = trim(func); if(fTbl[func]){//如果是终结作用,终结作用右侧不应该有作用 while(currChar=input.charAt(++pos)) { if(currChar==setLBound){ stack++; } else if(currChar==setRBound) {//终结作用集结束 stack--; } if(stack==0){//栈空结束 end = 1; fVal = trim(fVal); break; } fVal += currChar; } } else { break; } } else { func += currChar; } } return {f:func, v:fVal, p:pos-1}; } function mapping(func) { var partialTpl = ''; switch(func.f) { case 'cond': partialTpl = setLBound+ func.v +setRBound+setLBlock; break; case 'echo': partialTpl = template.isCompress ? partialTpl = compress(func.v) : func.v; partialTpl = replaces[1]+ stringify(partialTpl) +replaces[2]; break; case 'getv': partialTpl = replaces[1]+ func.v +replaces[2]; break; case 'code': partialTpl = func.v; break; case 'for': partialTpl = 'for'; break; case 'foreach': partialTpl = 'foreach'; break; case 'if': partialTpl = 'if'; break; case 'elseif': partialTpl = 'else if'; break; case 'else': partialTpl = 'else'; break; } return partialTpl; } function trim(text) { if(String.prototype.trim && !String.prototype.trim.call("\uFEFF\xA0")) { return text == null ? "" : String.prototype.trim.call(text); } else { var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; return text == null ? "" : ( text + "" ).replace(rtrim, ""); } } function isEChar(c) { return /\s/.test(c); } function isEString(c) { return !/\S/.test(c); } function compress(text) { return text.replace(/[ \n\v\f\r\t]+/g, " ") .replace(/<!--.*?-->/g, ''); } // 字符串转义 function stringify (code) { return "'" + code // 单引号与反斜杠转义 .replace(/('|\\)/g, '\\$1') // 换行符转义(windows + linux) .replace(/\r/g, '\\r') .replace(/\n/g, '\\n') + "'"; }; }; })(); //////////////////////////////////////////////////////////////////////// // 辅助方法集合 var _helpers = template.helpers = { $include: template.render, $string: function (value, type) { if (typeof value !== 'string') { type = typeof value; if (type === 'number') { value += ''; } else if (type === 'function') { value = _helpers.$string(value()); } else { value = ''; } } return value; }, $escape: function (content) { var m = { "<": "&#60;", ">": "&#62;", '"': "&#34;", "'": "&#39;", "&": "&#38;" }; return _helpers.$string(content) .replace(/&(?![\w#]+;)|[<>"']/g, function (s) { return m[s]; }); }, $each: function (data, callback) { var isArray = Array.isArray || function (obj) { return ({}).toString.call(obj) === '[object Array]'; }; if (isArray(data)) { for (var i = 0, len = data.length; i < len; i++) { callback.call(data, data[i], i, data); } } else { for (i in data) { callback.call(data, data[i], i); } } } }; /** * 模板错误事件 * @name template.onerror * @event */ template.onerror = function (e) { var message = 'Template Error\n\n'; for (var name in e) { message += '<' + name + '>\n' + e[name] + '\n\n'; } if (global.console) { console.error(message); } }; // RequireJS && SeaJS if (typeof define === 'function') { define(function() { return template; }); // NodeJS } else if (typeof exports !== 'undefined') { module.exports = template; } global.template = template; /* * 模板放置位置 * 模板新增方法 * 模板管理 * 模板引入 * 模板加载 * * * */
ta) {
identifier_name
translate_baidu.js
console.info("start document") chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { // listen for messages sent from background.js if (request.message === 'url') { if(!request.cookie){ //用户未登录 show_sign_in() } else { add_user_setting() handle_query() } hide_ui_element() } else if(request.message=="login-complete"){ //用户登录成功 var dialog = document.querySelector('dialog'); if(null!=dialog){ dialog.close(); } } else if(request.message=="query-info"){ //popup window 获得查询信息 console.info("query-info") var target = document.getElementById('zonedword-wrap'); let stringify=null if($(target).is(':visible')){ let select_item = get_select_item() stringify=JSON.stringify(select_item) } else { let query_item = get_query_item() stringify=JSON.stringify(query_item) } //返回page-info chrome.runtime.sendMessage({ message: 'page-info', data:stringify }); } else if("query-session-complete"==request.message){ if(request.data){ let session_array = $.parseJSON(request.data); let navigation=$(".mdl-navigation") session_array.forEach(element => { if(element.used){ navigation.append(`<a class="mdl-navigation__link selected" id='${element.id}' href="javascript:;">${element.name}</a>`); } else { navigation.append(`<a class="mdl-navigation__link" id='${element.id}' href="javascript:;">${element.name}</a>`); } }); $(".mdl-navigation__link").click((e)=> { chrome.runtime.sendMessage({ message: 'set_study-session-file', data:e.target.id }); }) } } else if("session-list-selected"==request.message){ session_list_selected(request.data) } else if("user-query-complete"==request.message){ chrome.runtime.sendMessage({ message: 'get-word-tag', data:request.data }); } else if("word-tag-complete"==request.message){ $.each($(".tag-item"),(index,ele)=>{ ele.remove() }); let tag_items = $.parseJSON(request.data); init_word_tag(request.select_tag,tag_items) } }); function hide_ui_element(){ //隐藏界面无用元素 $(".logo-image").hide() $(".download-guide").hide() $(".manual-trans-btn").hide() //下载 $(".manual-trans-info").hide() //人工翻译 $(".trans-machine").hide() //用户收藏 $(".collection-btn .data-hover-tip").hide() //意见反馈 $(".extra-wrap").hide() //分享 $(".follow-btns").hide() $(".copyright").hide() } function init_word_tag(select_tag,tag_items){ let option_menu=$(".option-menu") tag_items.forEach((tag_item)=>{ if(select_tag==tag_item.tag){ option_menu.append(`<div id="${tag_item.tag}" class="tag-item clicked" style="background-color: ${tag_item.color}"></div>`) } else { option_menu.append(`<div id="${tag_item.tag}" class="tag-item" style="ba
s('selected'); }); $(".option-menu .tag-item").mouseout((ev)=>{ $(ev.target).removeClass("selected"); }); $('.option-menu .tag-item').click((ev)=>{ $(ev.target).parent().find('.tag-item').removeClass('clicked'); $(ev.target).addClass('clicked'); let word_item=null var target = document.getElementById('zonedword-wrap'); if($(target).is(':visible')){ let select_item = get_select_item() word_item=select_item.word } else { let query_item = get_query_item() word_item=query_item.word } if(null!=word_item){ //提交数据 chrome.runtime.sendMessage({ message: 'set-word-tag', tag:ev.target.id, data:word_item }); } }); } function show_sign_in(){ if(!$(".record-sign-in").length){ $.get(chrome.extension.getURL('user_sign_in.html'), function(data) { $($.parseHTML(data)).appendTo('body'); document.documentElement.classList.add('mdl-js'); componentHandler.upgradeAllRegistered(); show_sign_in_dialog() }); } else { show_sign_in_dialog() } } function show_sign_in_dialog(){ var dialog = document.querySelector('dialog'); if (!dialog.showModal) { dialogPolyfill.registerDialog(dialog); } dialog.showModal(); dialog.querySelector('.cancel-button').addEventListener('click', function() { dialog.close(); }); dialog.querySelector('.sign-in-button').addEventListener('click', function() { let username=$("#username").val(); let password=$("#password").val(); chrome.runtime.sendMessage({ message: 'user-login', username: username, password: password, }); }); } function handle_query(){ //隐藏二维码下载 let result_container=$('#left-result-container') if($.trim(result_container.text())){ //动态刷新的,会导致DOMSubtreeModified事件不生效 setTimeout(() => { $(".trans-ad-app-wrap").hide() let query_item=get_query_item() chrome.runtime.sendMessage({ message: 'user-query', data:JSON.stringify(query_item) }); }, 300); } else { result_container.bind('DOMSubtreeModified', function(e) { $(this).unbind("DOMSubtreeModified") setTimeout(() => { $(".trans-ad-app-wrap").hide() let query_item=get_query_item() chrome.runtime.sendMessage({ message: 'user-query', data:JSON.stringify(query_item) }); }, 300); }); } } var observer=undefined function add_user_setting(){ if(!$("#user-setting-content").length){ $.get(chrome.extension.getURL('user_setting.html'), function(data) { $("body").append($($.parseHTML(data))) $(".user-settting").hide() $(".more-action-button").click(()=>{ console.info("click user-setting!") $(".user-settting").fadeIn("normal",()=>{ $(document).click(dismiss_user_setting) }) }) //设置己有ip chrome.storage.local.get("address", function(result) { let address="https://192.168.3.8:8080/" if(result.address){ address=result.address } $(".address-item").addClass("is-dirty") $("#host-address").val(address) }); $(".apply-button").click(()=>{ chrome.storage.local.set({address:$("#host-address").val()}); }); document.documentElement.classList.add('mdl-js'); componentHandler.upgradeAllRegistered(); //查询学习系列 chrome.runtime.sendMessage({ message: 'query-session' }); }); //动态弹窗 if(observer){ observer.disconnect() } var target = document.getElementById('zonedword-wrap'); observer = new MutationObserver(function(mutations) { if($(target).is(':visible')){ let query_item=get_select_item() console.info(query_item.word) chrome.runtime.sendMessage({ message: 'user-query', data:JSON.stringify(query_item) }); } }); observer.observe(target, {attributes: true}); } } function get_select_item(){ query_item={} let selectionObj = window.getSelection(); let selectedText = selectionObj.toString(); if($.trim(selectedText)){ query_item.word=$.trim(selectedText); } else if($(".sample-source .high-light-bg").length){ query_item.word=$.trim($(".sample-source .high-light-bg").text()); } if($(".zonedword-content .dictionary-spell").length){ let phonetic_items=$(".zonedword-content .dictionary-spell").find("span.phonetic-transcription").children("b"); if(2==phonetic_items.length){ query_item.uk=phonetic_items[0].innerText; query_item.us=phonetic_items[1].innerText; } } //解释信息 if($(".zonedword-content .dictionary-comment").length){ query_item.desc_items={} $.each($(".zonedword-content .dictionary-comment p"),(index,ele)=>{ let type=$(ele).children("b").text() let info=$(ele).children("span").text() query_item.desc_items[type]=info }) } //加入当前学习系列 query_item.session_id=$('.mdl-navigation__link.selected').attr('id'); return query_item; } function get_query_item(){ //输入框 query_item={} query_item.word=$("#baidu_translate_input").val(); //翻译对照框 query_item.info=$(".ordinary-output.target-output.clearfix").text(); if($("#left-result-container .dictionary-output").length){ console.info("dictionary-output") //简明释义 apple pear etc... //音标信息 if($(".dictionary-spell").length){ let phonetic_items=$(".dictionary-spell").find("span.phonetic-transcription").children("b"); if(2==phonetic_items.length){ query_item.uk=phonetic_items[0].innerText; query_item.us=phonetic_items[1].innerText; } } //解释信息 console.info("词义:"+$(".dictionary-comment").length) if($(".dictionary-comment").length){ query_item.desc_items={} $.each($(".dictionary-comment p"),(index,ele)=>{ let type=$(ele).children("b").text() let info=$(ele).children("strong").text() query_item.desc_items[type]=info }) } } else if($("#left-result-container .keywords-container").length){ //第二种情况,句子长,没有其他解释 console.info("keywords-container") //重点词汇 suddenly it hit me how i was going to get back at her query_item.key_items=[] console.info("keywords:"+$(".keywords-container li").length) $.each($(".keywords-container li"),(index,ele)=>{ query_item.key_items.push({"key":$(ele).children("a").text(), "info":$(ele).children("span").text()}) }) } //双语例句 if($(".double-sample").length){ query_item.double_samples=[] $.each($(".double-sample ol > li:lt(3)"),(index,ele)=>{ let source=$(ele).find(".sample-source").text() let target=$(ele).find(".sample-target").text() let resource=$(ele).find(".sample-resource").text() query_item.double_samples.push({"source":source,"target":target,"resource":resource}) }) } //加入当前学习系列 query_item.session_id=$('.mdl-navigation__link.selected').attr('id'); return query_item; } function session_list_selected(select_id){ $.each($('.mdl-navigation .mdl-navigation__link'),(index,ele)=>$(ele).removeClass('selected')); $(`.mdl-navigation #${select_id}`).addClass('selected'); } //点击外围让阴影层消失 function dismiss_user_setting(){ if (event.target.closest(".user-settting")) return; let user_setting=$(".user-settting") if(user_setting.length){ user_setting.fadeOut("normal") } $(this).off("click") }
ckground-color: ${tag_item.color}"></div>`) } }) $(".option-menu .tag-item").mouseover((ev)=>{ $(ev.target).addClas
conditional_block
translate_baidu.js
console.info("start document") chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { // listen for messages sent from background.js if (request.message === 'url') { if(!request.cookie){ //用户未登录 show_sign_in() } else { add_user_setting() handle_query() } hide_ui_element() } else if(request.message=="login-complete"){ //用户登录成功 var dialog = document.querySelector('dialog'); if(null!=dialog){ dialog.close(); } } else if(request.message=="query-info"){ //popup window 获得查询信息 console.info("query-info") var target = document.getElementById('zonedword-wrap'); let stringify=null if($(target).is(':visible')){ let select_item = get_select_item() stringify=JSON.stringify(select_item) } else { let query_item = get_query_item() stringify=JSON.stringify(query_item) } //返回page-info chrome.runtime.sendMessage({ message: 'page-info', data:stringify }); } else if("query-session-complete"==request.message){ if(request.data){ let session_array = $.parseJSON(request.data); let navigation=$(".mdl-navigation") session_array.forEach(element => { if(element.used){ navigation.append(`<a class="mdl-navigation__link selected" id='${element.id}' href="javascript:;">${element.name}</a>`); } else { navigation.append(`<a class="mdl-navigation__link" id='${element.id}' href="javascript:;">${element.name}</a>`); } }); $(".mdl-navigation__link").click((e)=> { chrome.runtime.sendMessage({ message: 'set_study-session-file', data:e.target.id }); }) } } else if("session-list-selected"==request.message){ session_list_selected(request.data) } else if("user-query-complete"==request.message){ chrome.runtime.sendMessage({ message: 'get-word-tag', data:request.data }); } else if("word-tag-complete"==request.message){ $.each($(".tag-item"),(index,ele)=>{ ele.remove() }); let tag_items = $.parseJSON(request.data); init_word_tag(request.select_tag,tag_items) } }); function hide_ui_element(){ //隐藏界面无用元素 $(".logo-image").hide() $(".download-guide").hide() $(".manual-trans-btn").hide() //下载 $(".manual-trans-info").hide() //人工翻译 $(".trans-machine").hide() //用户收藏 $(".collection-btn .data-hover-tip").hide() //意见反馈 $(".extra-wrap").hide() //分享 $(".follow-btns").hide() $(".copyright").hide() } function init_word_tag(select_tag,tag_items){ let option_menu=$(".option-menu") tag_ite
ag_item)=>{ if(select_tag==tag_item.tag){ option_menu.append(`<div id="${tag_item.tag}" class="tag-item clicked" style="background-color: ${tag_item.color}"></div>`) } else { option_menu.append(`<div id="${tag_item.tag}" class="tag-item" style="background-color: ${tag_item.color}"></div>`) } }) $(".option-menu .tag-item").mouseover((ev)=>{ $(ev.target).addClass('selected'); }); $(".option-menu .tag-item").mouseout((ev)=>{ $(ev.target).removeClass("selected"); }); $('.option-menu .tag-item').click((ev)=>{ $(ev.target).parent().find('.tag-item').removeClass('clicked'); $(ev.target).addClass('clicked'); let word_item=null var target = document.getElementById('zonedword-wrap'); if($(target).is(':visible')){ let select_item = get_select_item() word_item=select_item.word } else { let query_item = get_query_item() word_item=query_item.word } if(null!=word_item){ //提交数据 chrome.runtime.sendMessage({ message: 'set-word-tag', tag:ev.target.id, data:word_item }); } }); } function show_sign_in(){ if(!$(".record-sign-in").length){ $.get(chrome.extension.getURL('user_sign_in.html'), function(data) { $($.parseHTML(data)).appendTo('body'); document.documentElement.classList.add('mdl-js'); componentHandler.upgradeAllRegistered(); show_sign_in_dialog() }); } else { show_sign_in_dialog() } } function show_sign_in_dialog(){ var dialog = document.querySelector('dialog'); if (!dialog.showModal) { dialogPolyfill.registerDialog(dialog); } dialog.showModal(); dialog.querySelector('.cancel-button').addEventListener('click', function() { dialog.close(); }); dialog.querySelector('.sign-in-button').addEventListener('click', function() { let username=$("#username").val(); let password=$("#password").val(); chrome.runtime.sendMessage({ message: 'user-login', username: username, password: password, }); }); } function handle_query(){ //隐藏二维码下载 let result_container=$('#left-result-container') if($.trim(result_container.text())){ //动态刷新的,会导致DOMSubtreeModified事件不生效 setTimeout(() => { $(".trans-ad-app-wrap").hide() let query_item=get_query_item() chrome.runtime.sendMessage({ message: 'user-query', data:JSON.stringify(query_item) }); }, 300); } else { result_container.bind('DOMSubtreeModified', function(e) { $(this).unbind("DOMSubtreeModified") setTimeout(() => { $(".trans-ad-app-wrap").hide() let query_item=get_query_item() chrome.runtime.sendMessage({ message: 'user-query', data:JSON.stringify(query_item) }); }, 300); }); } } var observer=undefined function add_user_setting(){ if(!$("#user-setting-content").length){ $.get(chrome.extension.getURL('user_setting.html'), function(data) { $("body").append($($.parseHTML(data))) $(".user-settting").hide() $(".more-action-button").click(()=>{ console.info("click user-setting!") $(".user-settting").fadeIn("normal",()=>{ $(document).click(dismiss_user_setting) }) }) //设置己有ip chrome.storage.local.get("address", function(result) { let address="https://192.168.3.8:8080/" if(result.address){ address=result.address } $(".address-item").addClass("is-dirty") $("#host-address").val(address) }); $(".apply-button").click(()=>{ chrome.storage.local.set({address:$("#host-address").val()}); }); document.documentElement.classList.add('mdl-js'); componentHandler.upgradeAllRegistered(); //查询学习系列 chrome.runtime.sendMessage({ message: 'query-session' }); }); //动态弹窗 if(observer){ observer.disconnect() } var target = document.getElementById('zonedword-wrap'); observer = new MutationObserver(function(mutations) { if($(target).is(':visible')){ let query_item=get_select_item() console.info(query_item.word) chrome.runtime.sendMessage({ message: 'user-query', data:JSON.stringify(query_item) }); } }); observer.observe(target, {attributes: true}); } } function get_select_item(){ query_item={} let selectionObj = window.getSelection(); let selectedText = selectionObj.toString(); if($.trim(selectedText)){ query_item.word=$.trim(selectedText); } else if($(".sample-source .high-light-bg").length){ query_item.word=$.trim($(".sample-source .high-light-bg").text()); } if($(".zonedword-content .dictionary-spell").length){ let phonetic_items=$(".zonedword-content .dictionary-spell").find("span.phonetic-transcription").children("b"); if(2==phonetic_items.length){ query_item.uk=phonetic_items[0].innerText; query_item.us=phonetic_items[1].innerText; } } //解释信息 if($(".zonedword-content .dictionary-comment").length){ query_item.desc_items={} $.each($(".zonedword-content .dictionary-comment p"),(index,ele)=>{ let type=$(ele).children("b").text() let info=$(ele).children("span").text() query_item.desc_items[type]=info }) } //加入当前学习系列 query_item.session_id=$('.mdl-navigation__link.selected').attr('id'); return query_item; } function get_query_item(){ //输入框 query_item={} query_item.word=$("#baidu_translate_input").val(); //翻译对照框 query_item.info=$(".ordinary-output.target-output.clearfix").text(); if($("#left-result-container .dictionary-output").length){ console.info("dictionary-output") //简明释义 apple pear etc... //音标信息 if($(".dictionary-spell").length){ let phonetic_items=$(".dictionary-spell").find("span.phonetic-transcription").children("b"); if(2==phonetic_items.length){ query_item.uk=phonetic_items[0].innerText; query_item.us=phonetic_items[1].innerText; } } //解释信息 console.info("词义:"+$(".dictionary-comment").length) if($(".dictionary-comment").length){ query_item.desc_items={} $.each($(".dictionary-comment p"),(index,ele)=>{ let type=$(ele).children("b").text() let info=$(ele).children("strong").text() query_item.desc_items[type]=info }) } } else if($("#left-result-container .keywords-container").length){ //第二种情况,句子长,没有其他解释 console.info("keywords-container") //重点词汇 suddenly it hit me how i was going to get back at her query_item.key_items=[] console.info("keywords:"+$(".keywords-container li").length) $.each($(".keywords-container li"),(index,ele)=>{ query_item.key_items.push({"key":$(ele).children("a").text(), "info":$(ele).children("span").text()}) }) } //双语例句 if($(".double-sample").length){ query_item.double_samples=[] $.each($(".double-sample ol > li:lt(3)"),(index,ele)=>{ let source=$(ele).find(".sample-source").text() let target=$(ele).find(".sample-target").text() let resource=$(ele).find(".sample-resource").text() query_item.double_samples.push({"source":source,"target":target,"resource":resource}) }) } //加入当前学习系列 query_item.session_id=$('.mdl-navigation__link.selected').attr('id'); return query_item; } function session_list_selected(select_id){ $.each($('.mdl-navigation .mdl-navigation__link'),(index,ele)=>$(ele).removeClass('selected')); $(`.mdl-navigation #${select_id}`).addClass('selected'); } //点击外围让阴影层消失 function dismiss_user_setting(){ if (event.target.closest(".user-settting")) return; let user_setting=$(".user-settting") if(user_setting.length){ user_setting.fadeOut("normal") } $(this).off("click") }
ms.forEach((t
identifier_name
translate_baidu.js
console.info("start document") chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { // listen for messages sent from background.js if (request.message === 'url') { if(!request.cookie){ //用户未登录 show_sign_in() } else { add_user_setting() handle_query() } hide_ui_element() } else if(request.message=="login-complete"){ //用户登录成功 var dialog = document.querySelector('dialog'); if(null!=dialog){ dialog.close(); } } else if(request.message=="query-info"){ //popup window 获得查询信息 console.info("query-info") var target = document.getElementById('zonedword-wrap'); let stringify=null if($(target).is(':visible')){ let select_item = get_select_item() stringify=JSON.stringify(select_item) } else { let query_item = get_query_item() stringify=JSON.stringify(query_item) } //返回page-info chrome.runtime.sendMessage({ message: 'page-info', data:stringify }); } else if("query-session-complete"==request.message){ if(request.data){ let session_array = $.parseJSON(request.data); let navigation=$(".mdl-navigation") session_array.forEach(element => { if(element.used){ navigation.append(`<a class="mdl-navigation__link selected" id='${element.id}' href="javascript:;">${element.name}</a>`); } else { navigation.append(`<a class="mdl-navigation__link" id='${element.id}' href="javascript:;">${element.name}</a>`); } }); $(".mdl-navigation__link").click((e)=> { chrome.runtime.sendMessage({ message: 'set_study-session-file', data:e.target.id }); }) } } else if("session-list-selected"==request.message){ session_list_selected(request.data) } else if("user-query-complete"==request.message){ chrome.runtime.sendMessage({ message: 'get-word-tag', data:request.data }); } else if("word-tag-complete"==request.message){ $.each($(".tag-item"),(index,ele)=>{ ele.remove() }); let tag_items = $.parseJSON(request.data); init_word_tag(request.select_tag,tag_items) } }); function hide_ui_element(){ //隐藏界面无用元素 $(".logo-image").hide() $(".download-guide").hide() $(".manual-trans-btn").hide() //下载 $(".manual-trans-info").hide() //人工翻译 $(".trans-machine").hide() //用户收藏 $(".collection-btn .data-hover-tip").hide() //意见反馈 $(".extra-wrap").hide() //分享 $(".follow-btns").hide() $(".copyright").hide() } function init_word_tag(select_tag,tag_items){ let option_menu=$(".option-menu") tag_items.forEach((tag_item)=>{ if(select_tag==tag_item.tag){ option_menu.append(`<div id="${tag_item.tag}" class="tag-item clicked" style="background-color: ${tag_item.color}"></div>`) } else { option_menu.append(`<div id="${tag_item.tag}" class="tag-item" style="background-color: ${tag_item.color}"></div>`) } }) $(".option-menu .tag-item").mouseover((ev)=>{ $(ev.target).addClass('selected'); }); $(".option-menu .tag-item").mouseout((ev)=>{ $(ev.target).removeClass("selected"); }); $('.option-menu .tag-item').click((ev)=>{ $(ev.target).parent().find('.tag-item').removeClass('clicked'); $(ev.target).addClass('clicked'); let word_item=null var target = document.getElementById('zonedword-wrap'); if($(target).is(':visible')){ let select_item = get_select_item() word_item=select_item.word } else { let query_item = get_query_item() word_item=query_item.word } if(null!=word_item){ //提交数据 chrome.runtime.sendMessage({ message: 'set-word-tag', tag:ev.target.id, data:word_item }); } }); } function show_sign_in(){ if(!$(".record-sign-in").length){ $.get(chrome.extension.getURL('user_sign_in.html'), function(data) { $($.parseHTML(data)).appendTo('body'); document.documentElement.classList.add('mdl-js'); componentHandler.upgradeAllRegistered(); show_sign_in_dialog() }); } else { show_sign_in_dialog() } } function show_sign_in_dialog(){ var dialog = document.querySelector('dialog'); if (!dialog.showModal) { dialogPolyfill.registerDialog(dialog); } dialog.showModal(); dialog.querySelector('.cancel-button').addEventListener('click', function() { dialog.close(); }); dialog.querySelector('.sign-in-button').addEventListener('click', function() { let username=$("#username").val(); let password=$("#password").val(); chrome.runtime.sendMessage({ message: 'user-login', username: username, password: password, }); }); } function handle_query(){ //隐藏二维码下载 let result_container=$('#left-result-container') if($.trim(result_container.text())){ //动态刷新的,会导致DOMSubtreeModified事件不生效 setTimeout(() => { $(".trans-ad-app-wrap").hide() let query_item=get_query_item() chrome.runtime.sendMessage({ message: 'user-query', data:JSON.stringify(query_item) }); }, 300); } else { result_container.bind('DOMSubtreeModified', function(e) { $(this).unbind("DOMSubtreeModified") setTimeout(() => { $(".trans-ad-app-wrap").hide() let query_item=get_query_item() chrome.runtime.sendMessage({ message: 'user-query', data:JSON.stringify(query_item) }); }, 300); }); } } var observer=undefined function add_user_setting(){ if(!$("#user-setting-content").length){ $.get(chrome.extension.getURL('user_setting.html'), function(data) { $("body").append($($.parseHTML(data))) $(".user-settting").hide() $(".more-action-button").click(()=>{ console.info("click user-setting!") $(".user-settting").fadeIn("normal",()=>{ $(document).click(dismiss_user_setting) }) }) //设置己有ip chrome.storage.local.get("address", function(result) { let address="https://192.168.3.8:8080/" if(result.address){ address=result.address } $(".address-item").addClass("is-dirty") $("#host-address").val(address) }); $(".apply-button").click(()=>{ chrome.storage.local.set({address:$("#host-address").val()}); }); document.documentElement.classList.add('mdl-js'); componentHandler.upgradeAllRegistered(); //查询学习系列 chrome.runtime.sendMessage({ message: 'query-session' }); }); //动态弹窗 if(observer){ observer.disconnect() } var target = document.getElementById('zonedword-wrap'); observer = new MutationObserver(function(mutations) { if($(target).is(':visible')){ let query_item=get_select_item() console.info(query_item.word) chrome.runtime.sendMessage({ message: 'user-query', data:JSON.stringify(query_item) }); } }); observer.observe(target, {attributes: true}); } } function get_select_item(){ query_item={} let selectionObj = window.getSelection(); let selectedText = selectionObj.toString(); if($.trim(selectedText)){ query_item.word=$.trim(selectedText); } else if($(".sample-source .high-light-bg").length){ query_item.word=$.trim($(".sample-source .high-light-bg").text()); } if($(".zonedword-content .dictionary-spell").length){ let phonetic_items=$(".zonedword-content .dictionary-spell").find("span.phonetic-transcription").children("b"); if(2==phonetic_items.length){ query_item.uk=phonetic_items[0].innerText; query_item.us=phonetic_items[1].innerText; } } //解释信息 if($(".zonedword-content .dictionary-comment").length){ query_item.desc_items={} $.each($(".zonedword-content .dictionary-comment p"),(index,ele)=>{ let type=$(ele).children("b").text() let info=$(ele).children("span").text() query_item.desc_items[type]=info }) } //加入当前学习系列 query_item.session_id=$('.mdl-navigation__link.selected').attr('id'); return query_item; } function get_query_item(){ //输入框 query_item={} query_item.word=$("#baidu_translate_input").val(); //翻译对照框 query_item.info=$(".ordinary-output.target-output.clearfix").text(); if($("#left-result-container .dictionary-output").length){ console.info("dictionary-output") //简明释义 apple pear etc... //音标信息 if($(".dictionary-spell").length){ let phonetic_items=$(".dictionary-spell").find("span.phonetic-transcription").children("b"); if(2==phonetic_items.length){ query_item.uk=phonetic_items[0].innerText; query_item.us=phonetic_items[1].innerText; } } //解释信息 console.info("词义:"+$(".dictionary-comment").length) if($(".dictionary-comment").length){ query_item.desc_items={} $.each($(".dictionary-comment p"),(index,ele)=>{ let type=$(ele).children("b").text() let info=$(ele).children("strong").text() query_item.desc_items[type]=info }) } } else if($("#left-result-container .keywords-container").length){ //第二种情况,句子长,没有其他解释 console.info("keywords-container") //重点词汇 suddenly it hit me how i was going to get back at her query_item.key_items=[] console.info("keywords:"+$(".keywords-container li").length) $.each($(".keywords-container li"),(index,ele)=>{ query_item.key_items.push({"key":$(ele).children("a").text(), "info":$(ele).children("span").text()}) }) } //双语例句 if($(".double-sample").length){ query_item.double_samples=[] $.each($(".double-sample ol > li:lt(3)"),(index,ele)=>{ let source=$(ele).find(".sample-source").text() let target=$(ele).find(".sample-target").text() let resource=$(ele).find(".sample-resource").text() query_item.double_samples.push({"source":source,"target":target,"resource":resource}) }) } //加入当前学习系列 query_item.session_id=$('.mdl-navigation__link.selected').attr('id'); return query_item; } function session_list_selected(select_id){ $.each($('.mdl-navigation .mdl-navigation__link'),(index,ele)=>$(ele).removeClass('selected')); $(`.mdl-navigation #${select_id}`).addClass('selected'); } //点击外围让阴影层消失 function dismiss_user_setting(){ if (event.target.closest(".user-settting")) return; let user_setting=$(".use
r-settting") if(user_setting.length){ user_setting.fadeOut("normal") } $(this).off("click") }
identifier_body
translate_baidu.js
console.info("start document") chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { // listen for messages sent from background.js if (request.message === 'url') { if(!request.cookie){ //用户未登录 show_sign_in() } else { add_user_setting() handle_query() } hide_ui_element() } else if(request.message=="login-complete"){ //用户登录成功 var dialog = document.querySelector('dialog'); if(null!=dialog){ dialog.close(); } } else if(request.message=="query-info"){ //popup window 获得查询信息 console.info("query-info") var target = document.getElementById('zonedword-wrap'); let stringify=null if($(target).is(':visible')){ let select_item = get_select_item() stringify=JSON.stringify(select_item) } else { let query_item = get_query_item() stringify=JSON.stringify(query_item) } //返回page-info chrome.runtime.sendMessage({ message: 'page-info', data:stringify }); } else if("query-session-complete"==request.message){ if(request.data){ let session_array = $.parseJSON(request.data); let navigation=$(".mdl-navigation") session_array.forEach(element => { if(element.used){ navigation.append(`<a class="mdl-navigation__link selected" id='${element.id}' href="javascript:;">${element.name}</a>`); } else { navigation.append(`<a class="mdl-navigation__link" id='${element.id}' href="javascript:;">${element.name}</a>`); } }); $(".mdl-navigation__link").click((e)=> { chrome.runtime.sendMessage({ message: 'set_study-session-file', data:e.target.id }); }) } } else if("session-list-selected"==request.message){ session_list_selected(request.data) } else if("user-query-complete"==request.message){ chrome.runtime.sendMessage({ message: 'get-word-tag', data:request.data }); } else if("word-tag-complete"==request.message){ $.each($(".tag-item"),(index,ele)=>{ ele.remove() }); let tag_items = $.parseJSON(request.data); init_word_tag(request.select_tag,tag_items) } }); function hide_ui_element(){ //隐藏界面无用元素 $(".logo-image").hide() $(".download-guide").hide() $(".manual-trans-btn").hide() //下载 $(".manual-trans-info").hide() //人工翻译 $(".trans-machine").hide() //用户收藏 $(".collection-btn .data-hover-tip").hide() //意见反馈 $(".extra-wrap").hide() //分享 $(".follow-btns").hide() $(".copyright").hide() } function init_word_tag(select_tag,tag_items){ let option_menu=$(".option-menu") tag_items.forEach((tag_item)=>{ if(select_tag==tag_item.tag){ option_menu.append(`<div id="${tag_item.tag}" class="tag-item clicked" style="background-color: ${tag_item.color}"></div>`) } else { option_menu.append(`<div id="${tag_item.tag}" class="tag-item" style="background-color: ${tag_item.color}"></div>`) } }) $(".option-menu .tag-item").mouseover((ev)=>{ $(ev.target).addClass('selected'); }); $(".option-menu .tag-item").mouseout((ev)=>{ $(ev.target).removeClass("selected"); }); $('.option-menu .tag-item').click((ev)=>{ $(ev.target).parent().find('.tag-item').removeClass('clicked'); $(ev.target).addClass('clicked'); let word_item=null var target = document.getElementById('zonedword-wrap'); if($(target).is(':visible')){ let select_item = get_select_item() word_item=select_item.word } else { let query_item = get_query_item() word_item=query_item.word } if(null!=word_item){ //提交数据 chrome.runtime.sendMessage({ message: 'set-word-tag', tag:ev.target.id, data:word_item }); } }); } function show_sign_in(){ if(!$(".record-sign-in").length){ $.get(chrome.extension.getURL('user_sign_in.html'), function(data) { $($.parseHTML(data)).appendTo('body'); document.documentElement.classList.add('mdl-js'); componentHandler.upgradeAllRegistered(); show_sign_in_dialog() }); } else { show_sign_in_dialog() } } function show_sign_in_dialog(){ var dialog = document.querySelector('dialog'); if (!dialog.showModal) { dialogPolyfill.registerDialog(dialog); } dialog.showModal(); dialog.querySelector('.cancel-button').addEventListener('click', function() { dialog.close(); }); dialog.querySelector('.sign-in-button').addEventListener('click', function() { let username=$("#username").val(); let password=$("#password").val(); chrome.runtime.sendMessage({ message: 'user-login', username: username, password: password, }); }); } function handle_query(){ //隐藏二维码下载 let result_container=$('#left-result-container') if($.trim(result_container.text())){ //动态刷新的,会导致DOMSubtreeModified事件不生效 setTimeout(() => { $(".trans-ad-app-wrap").hide() let query_item=get_query_item() chrome.runtime.sendMessage({ message: 'user-query', data:JSON.stringify(query_item) }); }, 300); } else { result_container.bind('DOMSubtreeModified', function(e) { $(this).unbind("DOMSubtreeModified") setTimeout(() => { $(".trans-ad-app-wrap").hide() let query_item=get_query_item() chrome.runtime.sendMessage({ message: 'user-query', data:JSON.stringify(query_item) }); }, 300); }); } } var observer=undefined function add_user_setting(){ if(!$("#user-setting-content").length){ $.get(chrome.extension.getURL('user_setting.html'), function(data) { $("body").append($($.parseHTML(data))) $(".user-settting").hide() $(".more-action-button").click(()=>{ console.info("click user-setting!") $(".user-settting").fadeIn("normal",()=>{ $(document).click(dismiss_user_setting) }) }) //设置己有ip chrome.storage.local.get("address", function(result) { let address="https://192.168.3.8:8080/" if(result.address){ address=result.address } $(".address-item").addClass("is-dirty") $("#host-address").val(address) }); $(".apply-button").click(()=>{ chrome.storage.local.set({address:$("#host-address").val()}); }); document.documentElement.classList.add('mdl-js'); componentHandler.upgradeAllRegistered(); //查询学习系列 chrome.runtime.sendMessage({ message: 'query-session' }); }); //动态弹窗 if(observer){ observer.disconnect() } var target = document.getElementById('zonedword-wrap'); observer = new MutationObserver(function(mutations) { if($(target).is(':visible')){ let query_item=get_select_item() console.info(query_item.word) chrome.runtime.sendMessage({ message: 'user-query', data:JSON.stringify(query_item) }); } }); observer.observe(target, {attributes: true}); } } function get_select_item(){ query_item={} let selectionObj = window.getSelection(); let selectedText = selectionObj.toString(); if($.trim(selectedText)){ query_item.word=$.trim(selectedText); } else if($(".sample-source .high-light-bg").length){ query_item.word=$.trim($(".sample-source .high-light-bg").text()); } if($(".zonedword-content .dictionary-spell").length){ let phonetic_items=$(".zonedword-content .dictionary-spell").find("span.phonetic-transcription").children("b"); if(2==phonetic_items.length){ query_item.uk=phonetic_items[0].innerText; query_item.us=phonetic_items[1].innerText; } } //解释信息 if($(".zonedword-content .dictionary-comment").length){ query_item.desc_items={} $.each($(".zonedword-content .dictionary-comment p"),(index,ele)=>{ let type=$(ele).children("b").text() let info=$(ele).children("span").text() query_item.desc_items[type]=info }) } //加入当前学习系列 query_item.session_id=$('.mdl-navigation__link.selected').attr('id'); return query_item; } function get_query_item(){ //输入框 query_item={} query_item.word=$("#baidu_translate_input").val(); //翻译对照框 query_item.info=$(".ordinary-output.target-output.clearfix").text(); if($("#left-result-container .dictionary-output").length){ console.info("dictionary-output") //简明释义 apple pear etc... //音标信息 if($(".dictionary-spell").length){ let phonetic_items=$(".dictionary-spell").find("span.phonetic-transcription").children("b"); if(2==phonetic_items.length){ query_item.uk=phonetic_items[0].innerText; query_item.us=phonetic_items[1].innerText; } } //解释信息 console.info("词义:"+$(".dictionary-comment").length) if($(".dictionary-comment").length){ query_item.desc_items={} $.each($(".dictionary-comment p"),(index,ele)=>{ let type=$(ele).children("b").text() let info=$(ele).children("strong").text() query_item.desc_items[type]=info }) } } else if($("#left-result-container .keywords-container").length){ //第二种情况,句子长,没有其他解释 console.info("keywords-container") //重点词汇 suddenly it hit me how i was going to get back at her query_item.key_items=[] console.info("keywords:"+$(".keywords-container li").length) $.each($(".keywords-container li"),(index,ele)=>{ query_item.key_items.push({"key":$(ele).children("a").text(), "info":$(ele).children("span").text()}) }) } //双语例句 if($(".double-sample").length){ query_item.double_samples=[] $.each($(".double-sample ol > li:lt(3)"),(index,ele)=>{ let source=$(ele).find(".sample-source").text() let target=$(ele).find(".sample-target").text() let resource=$(ele).find(".sample-resource").text() query_item.double_samples.push({"source":source,"target":target,"resource":resource}) }) } //加入当前学习系列 query_item.session_id=$('.mdl-navigation__link.selected').attr('id'); return query_item; } function session_list_selected(select_id){ $.each($('.mdl-navigation .mdl-navigation__link'),(index,ele)=>$(ele).removeClass('selected')); $(`.mdl-navigation #${select_id}`).addClass('selected'); }
let user_setting=$(".user-settting") if(user_setting.length){ user_setting.fadeOut("normal") } $(this).off("click") }
//点击外围让阴影层消失 function dismiss_user_setting(){ if (event.target.closest(".user-settting")) return;
random_line_split
dict.js
$(function() { var t = { "Home": { pt: "Iní­cio", es: "Inicio", }, "Watch instructions": { pt: "Assista as instruções", es: "Ver las instrucciones", }, "Contact": { pt: "Contato", es: "Contacto", }, "Arrival time": { pt: "Tempo de chegada", es: "Hora de llegada", }, "Algorithm type:": { pt: "Política de escalonamento:", es: "Tipo de algoritmo:", }, "Add Random Job": { pt: "Adicionar job aleatório", es: "Generar aleatoriamente", }, "New Experiment": { pt: "Novo experimento", es: "Nuevo experimento", }, "Execution Queue": { pt: "Fila de execução", es: "Lista de ejecución", }, "Execution Steps": { pt: "Passos da execução", es: "Pasos de ejecución", }, "Experiment Parameters": { pt: "Parâmetros de execução", es: "Parámetros de ejecución", }, "New Experiment": { pt: "Novo experimento", es: "Nuevo experimento" }, "Instructions (P: CPU | B: I/O)": { pt: "Instruções (P: CPU | B: I/O)", es: "Instrucciones (P: CPU | B: I/O)", }, "Action": { pt: "Ações", es: "Acciones", }, "Language": { pt: "Idioma", es: "Idioma" }, "Input Jobs": { pt: "Tarefas de entrada", es: "Entrada de tareas", }, "Flow of execution": { pt: "Fluxo de execução", es: "Flujo de ejecución", }, "Start": { pt: "Iniciar", es: "Iniciar", }, "Add" : { pt: "Adicionar", es: "Añadir", }, "<b>CPU usage (Time Unit | Percentual): </b>": { pt: "<b>Uso de CPU (Unidade de Tempo | Percentual): </b>", es: "<b>Uso de CPU (Unidad Tiempo | Porcentaje): </b>", }, "<b>Time spent with Context Change (Time Unit | Percentual): </b>":{ pt: "<b>Tempo gasto com troca de contexto (Unidade de Tempo | Percentual): </b>", es: "<b>Tiempo gasto com cambio de contexto (Unidad Tiempo | Porcentaje): </b>", }, "Performance Statistics":{ pt: "Desempenho", es: "Rendiemento", }, "Policy:":{ pt: "Política:", es: "Politica:", }, "Legend":{ pt: "Legenda</b>", es: "Leyenda</b>", }, "AT: Arrival Time":{ pt: "AT: Tempo de Chegada", es: "AT: Hora de llegada", }, "JID: Job Identificator":{ pt: "JID: Identificador do Processo", es: "JID: Manejar el Proceso", }, "INST: Instructions":{ pt: "INST: Instruções", es: "INST: Instrucciones", }, "Instructions":{ pt: "Instruções", es: "Instrucciones", }, "WT: Waiting Time":{ pt: "WT: Tempo de Espera", es: "WT: Tiempo de Espera", }, "Sample Lists":{ pt: "Exemplos de Listas", es: "Lista de muestra", }, "This project has been developed by Henrique Yoshikazu Shishido e Leonildo José de Melo de Azevedo during the Operating Systems class under supervision of Professor Ph.D. Paulo Sergio Lopes de Souza. Actually (2015), both computer scientists are graduate students of the Computer Science and Computational Mathematics Program in Institute of Mathematical and Computer Sciences - University of São Paulo.":{ pt: "Este projeto foi desenvolvido por Henrique Yoshikazu Shishido e Leonildo José de Melo de Azevedo, durante a disciplina de Sistemas Operacionais sob supervisão do professor Dr. Paulo Sergio Lopes de Souza. Atualmente (2015), ambos são estudantes do curso de Pós-graduação em Ciência da Computação e Matemática Computacional Programa no Instituto de Matemática e Ciências da Computação - Universidade de São Paulo.", es: "Este proyecto ha sido desarrollado por Henrique Yoshikazu Shishido e Leonildo José de Melo de Azevedo, durante la clase de sistemas operativos bajo la supervisión del Profesor Ph.D. Paulo Sergio Lopes de Souza. En realidad (2015), ambos científicos de la computación son estudiantes de posgrado del Programa Matemática Computacional Ciencias de la Computación y en el Instituto de Matemática y Ciencias de la Computación - Universidad de São Paulo.", }, "About the authors":{ pt: "Sobre os autores", es: "Sobre los autores", }, "PC: Program Counter":{ pt: "PC: Contador de Programa", es: "PC: Contador de Programa", }, "↔: Context Change":{ pt: "↔: Troca de contexto", es: "↔: Cambio de contexto", }, " - : CPU idle":{ pt: " - : CPU ociosa", es: " - : CPU ociosa", }, "Execution":{ pt: "Execução", es: "Ejecución", }, "P: Processing":{ pt: "P: Processando", es: "P: Tratamiento", },
pt: "B: Bloqueado", es: "B: Obstruido", }, "Ready Queue":{ pt: "Fila de Pronto", es: "Cola Ready", }, "Blocked Queue":{ pt: "Fila de Bloqueado", es: "Cola Locked", }, "Run Statistics":{ pt: "Estatística de execução", es: "Estadísticas de Ejecución", }, "Ph.D. Student in Distributed Systems":{ pt: "Doutorando em Sistemas Distribuídos", es: "Estudiante de doctorado en sistemas distribuidos", }, "Masters Student in Distributed Systems":{ pt: "Mestrando em Sistemas Distribuídos", es: "Estudiante de mestrado en sistemas distribuidos", }, "Distributed Systems and Concurrent Programming Laboratory":{ pt: "Laboratório de Sistemas Distribuídos e Programação Concorrente", es: "Laboratorio de Sistemas Distribuidos y Pragramación Concurrente", }, "Watch the video in order to understand how to use this Open Educational Resource in english or portuguese.":{ pt: "Assista o video para entender como usar o recurso educacional aberto em inglês ou português.", es: "Vea el video con el fin de entender cómo usar este recurso educativo abierto en inglés o portugués.", }, "How to use":{ pt: "Como usar", es: "Cómo utilizar", }, "About BASOPER":{ pt: "Sobre o BASOPER", es: "Sobre el BASOPER", }, "What is a batch processing?":{ pt: "O que é processamento batch?", es: "¿Qué es un proceso por lotes?", }, "Batch processing is the execution of a list of jobs on a computer system without manual intervention.":{ pt: "Processamento batch é a execução de uma lista de trabalhos em um sistema computacional sem intervenção manual.", es: "El procesamiento por lotes es la ejecución de una lista de puestos de trabajo en un sistema informático sin intervención manual.", }, "Objectives:":{ pt: "Objetivos:", es: "Objetivos:", }, "- Assist the teaching batch systems scheduling algorithms;":{ pt: "- Ajudar no ensino de algoritmos de sistemas em lote;", es: "- Ayudar a los algoritmos de planificación de sistemas de lotes enseñanza;", }, "- Promote the visualization of functional, structural, and performance aspects.":{ pt: "- Promover a visualização do aspecto funcional, estrutural e de desempenho.", es: "- Promover la visualización de, aspectos estructurales y de rendimiento funcional.", }, "What BASOPER does?":{ pt: "O que o BASOPER ensina?", es: "Qué BASOPER enseña?", }, "- Simulate the execution of three scheduling algorithms of batch systems such as FCFS, SJF, and SRTN;":{ pt: "- Simula a execução de três algoritmos de sistemas batch como FCFS, SJF e SRTN;", es: "- Simular la ejecución de tres algoritmos de planificación de sistemas de lotes como FCFS, SJF y SRTN;", }, "- Display to the student a timestep execution table in order to assist the interaction of the jobs and the execution, ready and blocked queues;":{ pt: "- Exibe ao estudante uma tabela de execução passo-a-passo a fim de auxiliar na interação de trabalhos e as filas de execução, pronto e bloqueado;", es: "- Pantalla al estudiante una mesa ejecución paso de tiempo con el fin de ayudar a la interacción de los puestos de trabajo y la ejecución, listo y bloqueado colas;", }, "- Allow the student follow the execution of each instruction of a job and its performance parameters such as Waiting Time (WT) and Turnaround Time (TT).":{ pt: "- Permite ao estudante acompanhar a execução de cada instrução de um trabalho e seus parâmetros de desempenho tais como Tempo de Espera (WT) e Tempo de execução (TT)", es: "- Permitir que el estudiante siga la ejecución de cada instrucción de un trabajo y sus parámetros de rendimiento tales como Tiempo de espera (WT) y Plazo de Entrega (TT).", }, "Considerations in performance computation":{ pt: "Considerações no cálculo de desempenho", es: "Consideraciones en el cálculo de rendimiento", }, "- When a process is blocked, the time spent with input and output is disregarded;":{ pt: "- Quando um processo é bloqueado, o tempo gasto com entrada e saída é desconsiderado;", es: "- Cuando se bloquea un proceso, el tiempo empleado entrada y salida no se tienen en cuenta;", }, "- When there is a block instruction and there is no process in ready queue, the block is counted as idle time;":{ pt: "- Quando ocorrer um bloqueio e não houver nenhum processo na fila de pronto, o bloqueio é contabilizado como tempo ocioso;", es: "- Cuando hay un bloqueo y no hay un proceso en línea de listo, el bloqueo se cuenta como tiempo de inactividad;", }, "- When there is a block instruction and there is another process in ready queue, the block is not counted as idle time.":{ pt: "- Quando ocorrer um bloqueio e houver outro processo na fila de pronto, o bloqueio não é contabilizado como tempo ocioso.", es: "- Cuando hay un bloqueo y no hay otro proceso en línea de listo, el bloqueo no se cuenta como tiempo de inactividad.", }, "About":{ pt: "Sobre", es: "Sobre", }, "TT: Turnaround Time":{ pt: "TT: Tempo de Retorno", es: "TT: Tiempo de Volver", }}; var _t = $('body').translate({lang: "en", t: t}); var str = _t.g("translate"); console.log(str); $(".lang_selector").click(function(ev) { var lang = $(this).attr("data-value"); _t.lang(lang); console.log("chamouuuu"); console.log(lang); ev.preventDefault(); }); });
"B: Blocked":{
random_line_split
functional.py
from __future__ import division import torch import math import random from PIL import Image, ImageOps try: import accimage except ImportError: accimage = None import numpy as np import numbers import types import collections from skimage.external import tifffile from skimage import transform, filters, util import cv2 def _is_pil_image(img): if accimage is not None: return isinstance(img, (Image.Image, accimage.Image)) else: return isinstance(img, Image.Image) def _is_tensor_image(img): return torch.is_tensor(img) and img.ndimension() == 3 def _is_numpy_image(img): return isinstance(img, np.ndarray) and (img.ndim in {2, 3}) def to_tensor(pic): if not (_is_pil_image(pic) or _is_numpy_image(pic)): raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic))) if isinstance(pic, np.ndarray): # get max value of dtype, if the dtype is not uint8 and uint 16, change this # denominator = _get_dtype_max(pic) denominator = np.iinfo(np.uint8).max if pic.dtype == np.uint8 else np.iinfo(np.uint16).max # handle numpy array if len(pic.shape) == 2: img = torch.from_numpy(pic) img = torch.unsqueeze(img, 0) else: img = torch.from_numpy(pic.transpose((2, 0, 1))) # backward compatibility return img.float().div(denominator) if accimage is not None and isinstance(pic, accimage.Image): nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32) pic.copyto(nppic) return torch.from_numpy(nppic) # handle PIL Image if pic.mode == 'I': img = torch.from_numpy(np.array(pic, np.int32, copy=False)) elif pic.mode == 'I;16': img = torch.from_numpy(np.array(pic, np.int16, copy=False)) else: img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes())) # PIL image mode: 1, L, P, I, F, RGB, YCbCr, RGBA, CMYK if pic.mode == 'YCbCr': nchannel = 3 elif pic.mode == 'I;16': nchannel = 1 else: nchannel = len(pic.mode) img = img.view(pic.size[1], pic.size[0], nchannel) # put it from HWC to CHW format # yikes, this transpose takes 80% of the loading time/CPU img = img.transpose(0, 1).transpose(0, 2).contiguous() if isinstance(img, torch.ByteTensor): return img.float().div(255) else: return def to_ndarray(pic, dtype='uint8'):
def normalize(tensor, mean, std): """Normalize a tensor image with mean and standard deviation. See ``Normalize`` for more details. Args: tensor (Tensor): Tensor image of size (C, H, W) to be normalized. mean (sequence): Sequence of means for each channel. std (sequence): Sequence of standard deviations for each channely. Returns: Tensor: Normalized Tensor image. """ if not _is_tensor_image(tensor): raise TypeError('tensor is not a torch image.') # TODO: make efficient for t, m, s in zip(tensor, mean, std): t.sub_(m).div_(s) return tensor def flip(img, flip_mode): if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if not (isinstance(flip_mode, int)): raise TypeError('flipCode should be integer. Got {}'.format(type(flip_mode))) return cv2.flip(img, flip_mode) def rotate(img, angle=0, order=1): """Rotate image by a certain angle around its center. Parameters ---------- img : ndarray(uint16 or uint8) Input image. angle : integer Rotation angle in degrees in counter-clockwise direction. Returns ------- rotated : ndarray(uint16 or uint8) Rotated version of the input. Examples -------- rotate(image, 30) rotate(image, 180) """ if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if not (isinstance(angle, numbers.Number)): raise TypeError('Angle should be integer. Got {}'.format(type(angle))) img_new = transform.rotate(img, angle, order=order, preserve_range=True) img_new = img_new.astype(img.dtype) return img_new def shift(img, right_shift=5, down_shift=5): """ :param img: the image input :param right_shift: the pixels of shift right :param down_shift: the pixels of down right :return: transformed img """ if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if not (isinstance(right_shift, int)): raise TypeError('shift.rightshift should be integer. Got {}'.format(type(right_shift))) if not (isinstance(down_shift, int)): raise TypeError('shift.downshift should be integer. Got {}'.format(type(down_shift))) tform = transform.SimilarityTransform(translation=(-right_shift, -down_shift)) img_new = transform.warp(img, tform, preserve_range=True) img_new = img_new.astype(img.dtype) return img_new def crop(img, top, left, width, height): """crop image from position top and left, width and height Arguments: img {numpy.ndarray} -- input image top {int} -- start position row left {int} -- start position column width {int} -- crop width height {int} -- crop height """ if not all([isinstance(x, int) for x in (top, left, width, height)]): raise ValueError("params should be integer!") if (width > img.shape[0] or height > img.shape[1]): raise ValueError("the output imgage size should be small than input image!!!") if len(img.shape) == 2: img_height, img_width = img.shape else: img_height, img_width, _ = img.shape right = img_width - (left + width) bottom = img_height - (top + height) if len(img.shape) == 2: img_croped = util.crop(img,((top,bottom),(left,right))) else: img_croped = util.crop(img,((top,bottom),(left,right),(0,0))) return img_croped def center_crop(img, output_size): if isinstance(output_size, numbers.Number): output_size = (int(output_size), int(output_size)) if len(img.shape) == 2: h, w = img.shape else: h, w, _ = img.shape th, tw = output_size i = int(round((h - th) / 2.)) j = int(round((w - tw) / 2.)) return crop(img, i, j, th, tw) def resize(img, size, interpolation=Image.BILINEAR): """Resize the input PIL Image to the given size. Note: cv2.resize do not support int32, weird Args: img (Numpy Array): Image to be resized. size (sequence or int): Desired output size. If size is a sequence like (h, w), the output size will be matched to this. If size is an int, the smaller edge of the image will be matched to this number maintaing the aspect ratio. i.e, if height > width, then image will be rescaled to (size * height / width, size) interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR`` Returns: PIL Image: Resized image. """ if not _is_numpy_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) if not (isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)): raise TypeError('Got inappropriate size arg: {}'.format(size)) if isinstance(size, int): size = (size, size) if img.dtype == np.int32: resized = img.astype(np.uint16) resized = cv2.resize(resized, size , interpolation) else: resized = cv2.resize(img, size , interpolation) resized = resized.astype(img.dtype) return resized def crop_resize(img, top, left, width, height, size, interpolation=Image.BILINEAR): """Crop the given PIL Image and resize it to desired size. Notably used in RandomResizedCrop. Args: img (PIL Image): Image to be cropped. i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: Width of the cropped image. size (sequence or int): Desired output size. Same semantics as ``scale``. interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR``. Returns: PIL Image: Cropped image. """ assert _is_numpy_image(img), 'img should be PIL Image' img = crop(img, top, left, width, height) img = resize(img, size, interpolation) return img def pad(img, pad_width, mode='reflect', **kwargs): """Pad the given image. Args: pad_width : int, padding width mode: str or function. contain{‘constant’,‘edge’,‘linear_ramp’,‘maximum’,‘mean’ , ‘median’, ‘minimum’, ‘reflect’,‘symmetric’,‘wrap’} Examples -------- >>> Transformed_img = pad(img,[(20,20),(20,20),(0,0)],mode='reflect') """ if len(img.shape) == 2: pad_width = ((pad_width, pad_width), (pad_width, pad_width)) else: pad_width = ((pad_width, pad_width), (pad_width, pad_width), (0, 0)) return np.pad(img, pad_width, mode) def noise(img, dtype='uint8', mode='gaussian', mean=0, var=0.01): """TODO """ if dtype == 'uint16': img_new = img.astype(np.uint16) img_new = util.random_noise(img, mode, mean=mean, var=var) if dtype == 'uint8': img_new = (img_new * np.iinfo(np.uint8).max).astype(np.uint8) elif dtype == 'uint16': img_new = (img_new * np.iinfo(np.int32).max).astype(np.int32) else: raise ValueError('not support type') return img_new def gaussian_blur(img, sigma=1, dtype='uint8', multichannel=False): """Multi-dimensional Gaussian filter. Parameters ---------- image : ndarray Input image (grayscale or color) to filter. sigma : scalar or sequence of scalars, optional Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. multichannel : bool, optional (default: None) Whether the last axis of the image is to be interpreted as multiple channels. If True, each channel is filtered separately (channels are not mixed together). Only 3 channels are supported. If `None`, the function will attempt to guess this, and raise a warning if ambiguous, when the array has shape (M, N, 3). Returns ------- filtered_image : ndarray """ if np.any(np.asarray(sigma) < 0.0): raise ValueError("Sigma values less than zero are not valid") img_new = filters.gaussian(img, sigma, multichannel) if dtype == 'uint8': print(img_new.max(), img_new.min()) img_new = (img_new * np.iinfo(np.uint8).max).astype(np.uint8) elif dtype == 'uint16': img_new = (img_new * np.iinfo(np.int32).max).astype(np.int32) else: raise ValueError('not support type') return img_new def piecewise_transform(image, numcols=5, numrows=5, warp_left_right=10, warp_up_down=10, order=1): """2D piecewise affine transformation. Control points are used to define the mapping. The transform is based on a Delaunay triangulation of the points to form a mesh. Each triangle is used to find a local affine transform. Parameters ---------- img : ndarray numcols : int, optional (default: 5) numbers of the colums to transformation numrows : int, optional (default: 5) numbers of the rows to transformation warp_left_right: int, optional (default: 10) the pixels of transformation left and right warp_up_down: int, optional (default: 10) the pixels of transformation up and down Returns ------- Transformed_image : ndarray Examples -------- >>> Transformed_img = piecetransform(image,numcols=10, numrows=10, warp_left_right=5, warp_up_down=5) """ rows, cols = image.shape[0], image.shape[1] numcols = numcols numrows = numrows src_cols = np.linspace(0, cols, numcols, dtype=int) src_rows = np.linspace(0, rows, numrows, dtype=int) src_rows, src_cols = np.meshgrid(src_rows, src_cols) src = np.dstack([src_cols.flat, src_rows.flat])[0] src_rows_new = np.ndarray.transpose(src_rows) src_cols_new = np.ndarray.transpose(src_cols) # src_new = np.dstack([src_cols_new.flat, src_rows_new.flat])[0] dst_cols = np.ndarray(src_cols.shape) dst_rows = np.ndarray(src_rows.shape) for i in range(0, numcols): for j in range(0, numrows): if src_cols[i, j] == 0 or src_cols[i, j] == cols: dst_cols[i, j] = src_cols[i, j] else: dst_cols[i, j] = src_cols[i, j] + np.random.uniform(-1, 1) * warp_left_right if src_rows[i, j] == 0 or src_rows[i, j] == rows: dst_rows[i, j] = src_rows[i, j] else: dst_rows[i, j] = src_rows[i, j] + np.random.uniform(-1, 1) * warp_up_down dst = np.dstack([dst_cols.flat, dst_rows.flat])[0] # dst_rows_new = np.ndarray.transpose(dst_rows) # dst_cols_new = np.ndarray.transpose(dst_cols) # dst_new = np.dstack([dst_cols_new.flat, dst_rows_new.flat])[0] tform = transform.PiecewiseAffineTransform() tform.estimate(src, dst) img_new = transform.warp(image, tform, output_shape=(rows, cols), order=order, preserve_range=True) img_new = img_new.astype(image.dtype) return img_new if __name__ == '__main__': img = tifffile.imread('sample-data/MUL_AOI_4_Shanghai_img1920.tif') # tifffile.imshow(img[:,:,[3,2,1]]) img = img.astype(np.int32) out = resize(img, (224,224)) # out = filters.gaussian_filter(img, sigma=2) # out2 = gaussian_blur(img, dtype='uint16') # out2 = to_tensor(out2) # out3 = to_ndarray(out2, dtype='uint16') # pass
if not (_is_numpy_image(pic) or _is_tensor_image(pic)): raise TypeError('pic should be Tensor or ndarray. Got {}.'.format(type(pic))) npimg = pic if isinstance(pic, torch.FloatTensor): if dtype == 'uint8': npimg = (pic.numpy() * np.iinfo(np.uint8).max).astype(np.uint8) elif dtype == 'uint16': npimg = (pic.numpy() * np.iinfo(np.int32).max).astype(np.int32) else: raise ValueError('not support dtype') npimg = np.transpose(npimg, (1, 2, 0)) else: npimg = np.transpose(pic.numpy(), (1, 2, 0)) assert isinstance(npimg, np.ndarray) return npimg
identifier_body
functional.py
from __future__ import division import torch import math import random from PIL import Image, ImageOps try: import accimage except ImportError: accimage = None import numpy as np import numbers import types import collections from skimage.external import tifffile from skimage import transform, filters, util import cv2 def _is_pil_image(img): if accimage is not None: return isinstance(img, (Image.Image, accimage.Image)) else: return isinstance(img, Image.Image) def _is_tensor_image(img): return torch.is_tensor(img) and img.ndimension() == 3 def
(img): return isinstance(img, np.ndarray) and (img.ndim in {2, 3}) def to_tensor(pic): if not (_is_pil_image(pic) or _is_numpy_image(pic)): raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic))) if isinstance(pic, np.ndarray): # get max value of dtype, if the dtype is not uint8 and uint 16, change this # denominator = _get_dtype_max(pic) denominator = np.iinfo(np.uint8).max if pic.dtype == np.uint8 else np.iinfo(np.uint16).max # handle numpy array if len(pic.shape) == 2: img = torch.from_numpy(pic) img = torch.unsqueeze(img, 0) else: img = torch.from_numpy(pic.transpose((2, 0, 1))) # backward compatibility return img.float().div(denominator) if accimage is not None and isinstance(pic, accimage.Image): nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32) pic.copyto(nppic) return torch.from_numpy(nppic) # handle PIL Image if pic.mode == 'I': img = torch.from_numpy(np.array(pic, np.int32, copy=False)) elif pic.mode == 'I;16': img = torch.from_numpy(np.array(pic, np.int16, copy=False)) else: img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes())) # PIL image mode: 1, L, P, I, F, RGB, YCbCr, RGBA, CMYK if pic.mode == 'YCbCr': nchannel = 3 elif pic.mode == 'I;16': nchannel = 1 else: nchannel = len(pic.mode) img = img.view(pic.size[1], pic.size[0], nchannel) # put it from HWC to CHW format # yikes, this transpose takes 80% of the loading time/CPU img = img.transpose(0, 1).transpose(0, 2).contiguous() if isinstance(img, torch.ByteTensor): return img.float().div(255) else: return def to_ndarray(pic, dtype='uint8'): if not (_is_numpy_image(pic) or _is_tensor_image(pic)): raise TypeError('pic should be Tensor or ndarray. Got {}.'.format(type(pic))) npimg = pic if isinstance(pic, torch.FloatTensor): if dtype == 'uint8': npimg = (pic.numpy() * np.iinfo(np.uint8).max).astype(np.uint8) elif dtype == 'uint16': npimg = (pic.numpy() * np.iinfo(np.int32).max).astype(np.int32) else: raise ValueError('not support dtype') npimg = np.transpose(npimg, (1, 2, 0)) else: npimg = np.transpose(pic.numpy(), (1, 2, 0)) assert isinstance(npimg, np.ndarray) return npimg def normalize(tensor, mean, std): """Normalize a tensor image with mean and standard deviation. See ``Normalize`` for more details. Args: tensor (Tensor): Tensor image of size (C, H, W) to be normalized. mean (sequence): Sequence of means for each channel. std (sequence): Sequence of standard deviations for each channely. Returns: Tensor: Normalized Tensor image. """ if not _is_tensor_image(tensor): raise TypeError('tensor is not a torch image.') # TODO: make efficient for t, m, s in zip(tensor, mean, std): t.sub_(m).div_(s) return tensor def flip(img, flip_mode): if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if not (isinstance(flip_mode, int)): raise TypeError('flipCode should be integer. Got {}'.format(type(flip_mode))) return cv2.flip(img, flip_mode) def rotate(img, angle=0, order=1): """Rotate image by a certain angle around its center. Parameters ---------- img : ndarray(uint16 or uint8) Input image. angle : integer Rotation angle in degrees in counter-clockwise direction. Returns ------- rotated : ndarray(uint16 or uint8) Rotated version of the input. Examples -------- rotate(image, 30) rotate(image, 180) """ if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if not (isinstance(angle, numbers.Number)): raise TypeError('Angle should be integer. Got {}'.format(type(angle))) img_new = transform.rotate(img, angle, order=order, preserve_range=True) img_new = img_new.astype(img.dtype) return img_new def shift(img, right_shift=5, down_shift=5): """ :param img: the image input :param right_shift: the pixels of shift right :param down_shift: the pixels of down right :return: transformed img """ if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if not (isinstance(right_shift, int)): raise TypeError('shift.rightshift should be integer. Got {}'.format(type(right_shift))) if not (isinstance(down_shift, int)): raise TypeError('shift.downshift should be integer. Got {}'.format(type(down_shift))) tform = transform.SimilarityTransform(translation=(-right_shift, -down_shift)) img_new = transform.warp(img, tform, preserve_range=True) img_new = img_new.astype(img.dtype) return img_new def crop(img, top, left, width, height): """crop image from position top and left, width and height Arguments: img {numpy.ndarray} -- input image top {int} -- start position row left {int} -- start position column width {int} -- crop width height {int} -- crop height """ if not all([isinstance(x, int) for x in (top, left, width, height)]): raise ValueError("params should be integer!") if (width > img.shape[0] or height > img.shape[1]): raise ValueError("the output imgage size should be small than input image!!!") if len(img.shape) == 2: img_height, img_width = img.shape else: img_height, img_width, _ = img.shape right = img_width - (left + width) bottom = img_height - (top + height) if len(img.shape) == 2: img_croped = util.crop(img,((top,bottom),(left,right))) else: img_croped = util.crop(img,((top,bottom),(left,right),(0,0))) return img_croped def center_crop(img, output_size): if isinstance(output_size, numbers.Number): output_size = (int(output_size), int(output_size)) if len(img.shape) == 2: h, w = img.shape else: h, w, _ = img.shape th, tw = output_size i = int(round((h - th) / 2.)) j = int(round((w - tw) / 2.)) return crop(img, i, j, th, tw) def resize(img, size, interpolation=Image.BILINEAR): """Resize the input PIL Image to the given size. Note: cv2.resize do not support int32, weird Args: img (Numpy Array): Image to be resized. size (sequence or int): Desired output size. If size is a sequence like (h, w), the output size will be matched to this. If size is an int, the smaller edge of the image will be matched to this number maintaing the aspect ratio. i.e, if height > width, then image will be rescaled to (size * height / width, size) interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR`` Returns: PIL Image: Resized image. """ if not _is_numpy_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) if not (isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)): raise TypeError('Got inappropriate size arg: {}'.format(size)) if isinstance(size, int): size = (size, size) if img.dtype == np.int32: resized = img.astype(np.uint16) resized = cv2.resize(resized, size , interpolation) else: resized = cv2.resize(img, size , interpolation) resized = resized.astype(img.dtype) return resized def crop_resize(img, top, left, width, height, size, interpolation=Image.BILINEAR): """Crop the given PIL Image and resize it to desired size. Notably used in RandomResizedCrop. Args: img (PIL Image): Image to be cropped. i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: Width of the cropped image. size (sequence or int): Desired output size. Same semantics as ``scale``. interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR``. Returns: PIL Image: Cropped image. """ assert _is_numpy_image(img), 'img should be PIL Image' img = crop(img, top, left, width, height) img = resize(img, size, interpolation) return img def pad(img, pad_width, mode='reflect', **kwargs): """Pad the given image. Args: pad_width : int, padding width mode: str or function. contain{‘constant’,‘edge’,‘linear_ramp’,‘maximum’,‘mean’ , ‘median’, ‘minimum’, ‘reflect’,‘symmetric’,‘wrap’} Examples -------- >>> Transformed_img = pad(img,[(20,20),(20,20),(0,0)],mode='reflect') """ if len(img.shape) == 2: pad_width = ((pad_width, pad_width), (pad_width, pad_width)) else: pad_width = ((pad_width, pad_width), (pad_width, pad_width), (0, 0)) return np.pad(img, pad_width, mode) def noise(img, dtype='uint8', mode='gaussian', mean=0, var=0.01): """TODO """ if dtype == 'uint16': img_new = img.astype(np.uint16) img_new = util.random_noise(img, mode, mean=mean, var=var) if dtype == 'uint8': img_new = (img_new * np.iinfo(np.uint8).max).astype(np.uint8) elif dtype == 'uint16': img_new = (img_new * np.iinfo(np.int32).max).astype(np.int32) else: raise ValueError('not support type') return img_new def gaussian_blur(img, sigma=1, dtype='uint8', multichannel=False): """Multi-dimensional Gaussian filter. Parameters ---------- image : ndarray Input image (grayscale or color) to filter. sigma : scalar or sequence of scalars, optional Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. multichannel : bool, optional (default: None) Whether the last axis of the image is to be interpreted as multiple channels. If True, each channel is filtered separately (channels are not mixed together). Only 3 channels are supported. If `None`, the function will attempt to guess this, and raise a warning if ambiguous, when the array has shape (M, N, 3). Returns ------- filtered_image : ndarray """ if np.any(np.asarray(sigma) < 0.0): raise ValueError("Sigma values less than zero are not valid") img_new = filters.gaussian(img, sigma, multichannel) if dtype == 'uint8': print(img_new.max(), img_new.min()) img_new = (img_new * np.iinfo(np.uint8).max).astype(np.uint8) elif dtype == 'uint16': img_new = (img_new * np.iinfo(np.int32).max).astype(np.int32) else: raise ValueError('not support type') return img_new def piecewise_transform(image, numcols=5, numrows=5, warp_left_right=10, warp_up_down=10, order=1): """2D piecewise affine transformation. Control points are used to define the mapping. The transform is based on a Delaunay triangulation of the points to form a mesh. Each triangle is used to find a local affine transform. Parameters ---------- img : ndarray numcols : int, optional (default: 5) numbers of the colums to transformation numrows : int, optional (default: 5) numbers of the rows to transformation warp_left_right: int, optional (default: 10) the pixels of transformation left and right warp_up_down: int, optional (default: 10) the pixels of transformation up and down Returns ------- Transformed_image : ndarray Examples -------- >>> Transformed_img = piecetransform(image,numcols=10, numrows=10, warp_left_right=5, warp_up_down=5) """ rows, cols = image.shape[0], image.shape[1] numcols = numcols numrows = numrows src_cols = np.linspace(0, cols, numcols, dtype=int) src_rows = np.linspace(0, rows, numrows, dtype=int) src_rows, src_cols = np.meshgrid(src_rows, src_cols) src = np.dstack([src_cols.flat, src_rows.flat])[0] src_rows_new = np.ndarray.transpose(src_rows) src_cols_new = np.ndarray.transpose(src_cols) # src_new = np.dstack([src_cols_new.flat, src_rows_new.flat])[0] dst_cols = np.ndarray(src_cols.shape) dst_rows = np.ndarray(src_rows.shape) for i in range(0, numcols): for j in range(0, numrows): if src_cols[i, j] == 0 or src_cols[i, j] == cols: dst_cols[i, j] = src_cols[i, j] else: dst_cols[i, j] = src_cols[i, j] + np.random.uniform(-1, 1) * warp_left_right if src_rows[i, j] == 0 or src_rows[i, j] == rows: dst_rows[i, j] = src_rows[i, j] else: dst_rows[i, j] = src_rows[i, j] + np.random.uniform(-1, 1) * warp_up_down dst = np.dstack([dst_cols.flat, dst_rows.flat])[0] # dst_rows_new = np.ndarray.transpose(dst_rows) # dst_cols_new = np.ndarray.transpose(dst_cols) # dst_new = np.dstack([dst_cols_new.flat, dst_rows_new.flat])[0] tform = transform.PiecewiseAffineTransform() tform.estimate(src, dst) img_new = transform.warp(image, tform, output_shape=(rows, cols), order=order, preserve_range=True) img_new = img_new.astype(image.dtype) return img_new if __name__ == '__main__': img = tifffile.imread('sample-data/MUL_AOI_4_Shanghai_img1920.tif') # tifffile.imshow(img[:,:,[3,2,1]]) img = img.astype(np.int32) out = resize(img, (224,224)) # out = filters.gaussian_filter(img, sigma=2) # out2 = gaussian_blur(img, dtype='uint16') # out2 = to_tensor(out2) # out3 = to_ndarray(out2, dtype='uint16') # pass
_is_numpy_image
identifier_name
functional.py
from __future__ import division import torch import math import random from PIL import Image, ImageOps try: import accimage except ImportError: accimage = None import numpy as np import numbers import types import collections from skimage.external import tifffile from skimage import transform, filters, util import cv2 def _is_pil_image(img): if accimage is not None: return isinstance(img, (Image.Image, accimage.Image)) else: return isinstance(img, Image.Image) def _is_tensor_image(img): return torch.is_tensor(img) and img.ndimension() == 3 def _is_numpy_image(img): return isinstance(img, np.ndarray) and (img.ndim in {2, 3}) def to_tensor(pic): if not (_is_pil_image(pic) or _is_numpy_image(pic)): raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic))) if isinstance(pic, np.ndarray): # get max value of dtype, if the dtype is not uint8 and uint 16, change this # denominator = _get_dtype_max(pic) denominator = np.iinfo(np.uint8).max if pic.dtype == np.uint8 else np.iinfo(np.uint16).max # handle numpy array if len(pic.shape) == 2: img = torch.from_numpy(pic) img = torch.unsqueeze(img, 0) else:
# backward compatibility return img.float().div(denominator) if accimage is not None and isinstance(pic, accimage.Image): nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32) pic.copyto(nppic) return torch.from_numpy(nppic) # handle PIL Image if pic.mode == 'I': img = torch.from_numpy(np.array(pic, np.int32, copy=False)) elif pic.mode == 'I;16': img = torch.from_numpy(np.array(pic, np.int16, copy=False)) else: img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes())) # PIL image mode: 1, L, P, I, F, RGB, YCbCr, RGBA, CMYK if pic.mode == 'YCbCr': nchannel = 3 elif pic.mode == 'I;16': nchannel = 1 else: nchannel = len(pic.mode) img = img.view(pic.size[1], pic.size[0], nchannel) # put it from HWC to CHW format # yikes, this transpose takes 80% of the loading time/CPU img = img.transpose(0, 1).transpose(0, 2).contiguous() if isinstance(img, torch.ByteTensor): return img.float().div(255) else: return def to_ndarray(pic, dtype='uint8'): if not (_is_numpy_image(pic) or _is_tensor_image(pic)): raise TypeError('pic should be Tensor or ndarray. Got {}.'.format(type(pic))) npimg = pic if isinstance(pic, torch.FloatTensor): if dtype == 'uint8': npimg = (pic.numpy() * np.iinfo(np.uint8).max).astype(np.uint8) elif dtype == 'uint16': npimg = (pic.numpy() * np.iinfo(np.int32).max).astype(np.int32) else: raise ValueError('not support dtype') npimg = np.transpose(npimg, (1, 2, 0)) else: npimg = np.transpose(pic.numpy(), (1, 2, 0)) assert isinstance(npimg, np.ndarray) return npimg def normalize(tensor, mean, std): """Normalize a tensor image with mean and standard deviation. See ``Normalize`` for more details. Args: tensor (Tensor): Tensor image of size (C, H, W) to be normalized. mean (sequence): Sequence of means for each channel. std (sequence): Sequence of standard deviations for each channely. Returns: Tensor: Normalized Tensor image. """ if not _is_tensor_image(tensor): raise TypeError('tensor is not a torch image.') # TODO: make efficient for t, m, s in zip(tensor, mean, std): t.sub_(m).div_(s) return tensor def flip(img, flip_mode): if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if not (isinstance(flip_mode, int)): raise TypeError('flipCode should be integer. Got {}'.format(type(flip_mode))) return cv2.flip(img, flip_mode) def rotate(img, angle=0, order=1): """Rotate image by a certain angle around its center. Parameters ---------- img : ndarray(uint16 or uint8) Input image. angle : integer Rotation angle in degrees in counter-clockwise direction. Returns ------- rotated : ndarray(uint16 or uint8) Rotated version of the input. Examples -------- rotate(image, 30) rotate(image, 180) """ if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if not (isinstance(angle, numbers.Number)): raise TypeError('Angle should be integer. Got {}'.format(type(angle))) img_new = transform.rotate(img, angle, order=order, preserve_range=True) img_new = img_new.astype(img.dtype) return img_new def shift(img, right_shift=5, down_shift=5): """ :param img: the image input :param right_shift: the pixels of shift right :param down_shift: the pixels of down right :return: transformed img """ if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if not (isinstance(right_shift, int)): raise TypeError('shift.rightshift should be integer. Got {}'.format(type(right_shift))) if not (isinstance(down_shift, int)): raise TypeError('shift.downshift should be integer. Got {}'.format(type(down_shift))) tform = transform.SimilarityTransform(translation=(-right_shift, -down_shift)) img_new = transform.warp(img, tform, preserve_range=True) img_new = img_new.astype(img.dtype) return img_new def crop(img, top, left, width, height): """crop image from position top and left, width and height Arguments: img {numpy.ndarray} -- input image top {int} -- start position row left {int} -- start position column width {int} -- crop width height {int} -- crop height """ if not all([isinstance(x, int) for x in (top, left, width, height)]): raise ValueError("params should be integer!") if (width > img.shape[0] or height > img.shape[1]): raise ValueError("the output imgage size should be small than input image!!!") if len(img.shape) == 2: img_height, img_width = img.shape else: img_height, img_width, _ = img.shape right = img_width - (left + width) bottom = img_height - (top + height) if len(img.shape) == 2: img_croped = util.crop(img,((top,bottom),(left,right))) else: img_croped = util.crop(img,((top,bottom),(left,right),(0,0))) return img_croped def center_crop(img, output_size): if isinstance(output_size, numbers.Number): output_size = (int(output_size), int(output_size)) if len(img.shape) == 2: h, w = img.shape else: h, w, _ = img.shape th, tw = output_size i = int(round((h - th) / 2.)) j = int(round((w - tw) / 2.)) return crop(img, i, j, th, tw) def resize(img, size, interpolation=Image.BILINEAR): """Resize the input PIL Image to the given size. Note: cv2.resize do not support int32, weird Args: img (Numpy Array): Image to be resized. size (sequence or int): Desired output size. If size is a sequence like (h, w), the output size will be matched to this. If size is an int, the smaller edge of the image will be matched to this number maintaing the aspect ratio. i.e, if height > width, then image will be rescaled to (size * height / width, size) interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR`` Returns: PIL Image: Resized image. """ if not _is_numpy_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) if not (isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)): raise TypeError('Got inappropriate size arg: {}'.format(size)) if isinstance(size, int): size = (size, size) if img.dtype == np.int32: resized = img.astype(np.uint16) resized = cv2.resize(resized, size , interpolation) else: resized = cv2.resize(img, size , interpolation) resized = resized.astype(img.dtype) return resized def crop_resize(img, top, left, width, height, size, interpolation=Image.BILINEAR): """Crop the given PIL Image and resize it to desired size. Notably used in RandomResizedCrop. Args: img (PIL Image): Image to be cropped. i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: Width of the cropped image. size (sequence or int): Desired output size. Same semantics as ``scale``. interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR``. Returns: PIL Image: Cropped image. """ assert _is_numpy_image(img), 'img should be PIL Image' img = crop(img, top, left, width, height) img = resize(img, size, interpolation) return img def pad(img, pad_width, mode='reflect', **kwargs): """Pad the given image. Args: pad_width : int, padding width mode: str or function. contain{‘constant’,‘edge’,‘linear_ramp’,‘maximum’,‘mean’ , ‘median’, ‘minimum’, ‘reflect’,‘symmetric’,‘wrap’} Examples -------- >>> Transformed_img = pad(img,[(20,20),(20,20),(0,0)],mode='reflect') """ if len(img.shape) == 2: pad_width = ((pad_width, pad_width), (pad_width, pad_width)) else: pad_width = ((pad_width, pad_width), (pad_width, pad_width), (0, 0)) return np.pad(img, pad_width, mode) def noise(img, dtype='uint8', mode='gaussian', mean=0, var=0.01): """TODO """ if dtype == 'uint16': img_new = img.astype(np.uint16) img_new = util.random_noise(img, mode, mean=mean, var=var) if dtype == 'uint8': img_new = (img_new * np.iinfo(np.uint8).max).astype(np.uint8) elif dtype == 'uint16': img_new = (img_new * np.iinfo(np.int32).max).astype(np.int32) else: raise ValueError('not support type') return img_new def gaussian_blur(img, sigma=1, dtype='uint8', multichannel=False): """Multi-dimensional Gaussian filter. Parameters ---------- image : ndarray Input image (grayscale or color) to filter. sigma : scalar or sequence of scalars, optional Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. multichannel : bool, optional (default: None) Whether the last axis of the image is to be interpreted as multiple channels. If True, each channel is filtered separately (channels are not mixed together). Only 3 channels are supported. If `None`, the function will attempt to guess this, and raise a warning if ambiguous, when the array has shape (M, N, 3). Returns ------- filtered_image : ndarray """ if np.any(np.asarray(sigma) < 0.0): raise ValueError("Sigma values less than zero are not valid") img_new = filters.gaussian(img, sigma, multichannel) if dtype == 'uint8': print(img_new.max(), img_new.min()) img_new = (img_new * np.iinfo(np.uint8).max).astype(np.uint8) elif dtype == 'uint16': img_new = (img_new * np.iinfo(np.int32).max).astype(np.int32) else: raise ValueError('not support type') return img_new def piecewise_transform(image, numcols=5, numrows=5, warp_left_right=10, warp_up_down=10, order=1): """2D piecewise affine transformation. Control points are used to define the mapping. The transform is based on a Delaunay triangulation of the points to form a mesh. Each triangle is used to find a local affine transform. Parameters ---------- img : ndarray numcols : int, optional (default: 5) numbers of the colums to transformation numrows : int, optional (default: 5) numbers of the rows to transformation warp_left_right: int, optional (default: 10) the pixels of transformation left and right warp_up_down: int, optional (default: 10) the pixels of transformation up and down Returns ------- Transformed_image : ndarray Examples -------- >>> Transformed_img = piecetransform(image,numcols=10, numrows=10, warp_left_right=5, warp_up_down=5) """ rows, cols = image.shape[0], image.shape[1] numcols = numcols numrows = numrows src_cols = np.linspace(0, cols, numcols, dtype=int) src_rows = np.linspace(0, rows, numrows, dtype=int) src_rows, src_cols = np.meshgrid(src_rows, src_cols) src = np.dstack([src_cols.flat, src_rows.flat])[0] src_rows_new = np.ndarray.transpose(src_rows) src_cols_new = np.ndarray.transpose(src_cols) # src_new = np.dstack([src_cols_new.flat, src_rows_new.flat])[0] dst_cols = np.ndarray(src_cols.shape) dst_rows = np.ndarray(src_rows.shape) for i in range(0, numcols): for j in range(0, numrows): if src_cols[i, j] == 0 or src_cols[i, j] == cols: dst_cols[i, j] = src_cols[i, j] else: dst_cols[i, j] = src_cols[i, j] + np.random.uniform(-1, 1) * warp_left_right if src_rows[i, j] == 0 or src_rows[i, j] == rows: dst_rows[i, j] = src_rows[i, j] else: dst_rows[i, j] = src_rows[i, j] + np.random.uniform(-1, 1) * warp_up_down dst = np.dstack([dst_cols.flat, dst_rows.flat])[0] # dst_rows_new = np.ndarray.transpose(dst_rows) # dst_cols_new = np.ndarray.transpose(dst_cols) # dst_new = np.dstack([dst_cols_new.flat, dst_rows_new.flat])[0] tform = transform.PiecewiseAffineTransform() tform.estimate(src, dst) img_new = transform.warp(image, tform, output_shape=(rows, cols), order=order, preserve_range=True) img_new = img_new.astype(image.dtype) return img_new if __name__ == '__main__': img = tifffile.imread('sample-data/MUL_AOI_4_Shanghai_img1920.tif') # tifffile.imshow(img[:,:,[3,2,1]]) img = img.astype(np.int32) out = resize(img, (224,224)) # out = filters.gaussian_filter(img, sigma=2) # out2 = gaussian_blur(img, dtype='uint16') # out2 = to_tensor(out2) # out3 = to_ndarray(out2, dtype='uint16') # pass
img = torch.from_numpy(pic.transpose((2, 0, 1)))
conditional_block
functional.py
from __future__ import division import torch import math import random from PIL import Image, ImageOps try: import accimage except ImportError: accimage = None import numpy as np import numbers import types import collections from skimage.external import tifffile from skimage import transform, filters, util import cv2 def _is_pil_image(img): if accimage is not None: return isinstance(img, (Image.Image, accimage.Image)) else: return isinstance(img, Image.Image) def _is_tensor_image(img): return torch.is_tensor(img) and img.ndimension() == 3 def _is_numpy_image(img): return isinstance(img, np.ndarray) and (img.ndim in {2, 3}) def to_tensor(pic): if not (_is_pil_image(pic) or _is_numpy_image(pic)): raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic))) if isinstance(pic, np.ndarray): # get max value of dtype, if the dtype is not uint8 and uint 16, change this # denominator = _get_dtype_max(pic) denominator = np.iinfo(np.uint8).max if pic.dtype == np.uint8 else np.iinfo(np.uint16).max # handle numpy array if len(pic.shape) == 2: img = torch.from_numpy(pic) img = torch.unsqueeze(img, 0) else: img = torch.from_numpy(pic.transpose((2, 0, 1))) # backward compatibility return img.float().div(denominator) if accimage is not None and isinstance(pic, accimage.Image): nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32) pic.copyto(nppic) return torch.from_numpy(nppic) # handle PIL Image if pic.mode == 'I': img = torch.from_numpy(np.array(pic, np.int32, copy=False)) elif pic.mode == 'I;16': img = torch.from_numpy(np.array(pic, np.int16, copy=False)) else: img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes())) # PIL image mode: 1, L, P, I, F, RGB, YCbCr, RGBA, CMYK if pic.mode == 'YCbCr': nchannel = 3 elif pic.mode == 'I;16': nchannel = 1 else: nchannel = len(pic.mode) img = img.view(pic.size[1], pic.size[0], nchannel) # put it from HWC to CHW format # yikes, this transpose takes 80% of the loading time/CPU img = img.transpose(0, 1).transpose(0, 2).contiguous() if isinstance(img, torch.ByteTensor): return img.float().div(255) else: return def to_ndarray(pic, dtype='uint8'): if not (_is_numpy_image(pic) or _is_tensor_image(pic)): raise TypeError('pic should be Tensor or ndarray. Got {}.'.format(type(pic))) npimg = pic if isinstance(pic, torch.FloatTensor): if dtype == 'uint8': npimg = (pic.numpy() * np.iinfo(np.uint8).max).astype(np.uint8) elif dtype == 'uint16': npimg = (pic.numpy() * np.iinfo(np.int32).max).astype(np.int32) else: raise ValueError('not support dtype') npimg = np.transpose(npimg, (1, 2, 0)) else: npimg = np.transpose(pic.numpy(), (1, 2, 0)) assert isinstance(npimg, np.ndarray) return npimg def normalize(tensor, mean, std): """Normalize a tensor image with mean and standard deviation. See ``Normalize`` for more details. Args: tensor (Tensor): Tensor image of size (C, H, W) to be normalized. mean (sequence): Sequence of means for each channel. std (sequence): Sequence of standard deviations for each channely. Returns: Tensor: Normalized Tensor image. """ if not _is_tensor_image(tensor): raise TypeError('tensor is not a torch image.') # TODO: make efficient for t, m, s in zip(tensor, mean, std): t.sub_(m).div_(s) return tensor def flip(img, flip_mode): if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if not (isinstance(flip_mode, int)): raise TypeError('flipCode should be integer. Got {}'.format(type(flip_mode))) return cv2.flip(img, flip_mode) def rotate(img, angle=0, order=1): """Rotate image by a certain angle around its center. Parameters ---------- img : ndarray(uint16 or uint8) Input image. angle : integer Rotation angle in degrees in counter-clockwise direction. Returns ------- rotated : ndarray(uint16 or uint8) Rotated version of the input. Examples -------- rotate(image, 30) rotate(image, 180) """ if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if not (isinstance(angle, numbers.Number)): raise TypeError('Angle should be integer. Got {}'.format(type(angle))) img_new = transform.rotate(img, angle, order=order, preserve_range=True) img_new = img_new.astype(img.dtype) return img_new def shift(img, right_shift=5, down_shift=5): """ :param img: the image input :param right_shift: the pixels of shift right :param down_shift: the pixels of down right :return: transformed img """ if not _is_numpy_image(img): raise TypeError('img should be numpy ndarray. Got {}'.format(type(img))) if not (isinstance(right_shift, int)): raise TypeError('shift.rightshift should be integer. Got {}'.format(type(right_shift))) if not (isinstance(down_shift, int)): raise TypeError('shift.downshift should be integer. Got {}'.format(type(down_shift))) tform = transform.SimilarityTransform(translation=(-right_shift, -down_shift)) img_new = transform.warp(img, tform, preserve_range=True) img_new = img_new.astype(img.dtype) return img_new def crop(img, top, left, width, height): """crop image from position top and left, width and height Arguments: img {numpy.ndarray} -- input image top {int} -- start position row left {int} -- start position column width {int} -- crop width height {int} -- crop height """ if not all([isinstance(x, int) for x in (top, left, width, height)]): raise ValueError("params should be integer!") if (width > img.shape[0] or height > img.shape[1]): raise ValueError("the output imgage size should be small than input image!!!") if len(img.shape) == 2: img_height, img_width = img.shape else: img_height, img_width, _ = img.shape right = img_width - (left + width) bottom = img_height - (top + height) if len(img.shape) == 2: img_croped = util.crop(img,((top,bottom),(left,right))) else: img_croped = util.crop(img,((top,bottom),(left,right),(0,0))) return img_croped def center_crop(img, output_size): if isinstance(output_size, numbers.Number): output_size = (int(output_size), int(output_size)) if len(img.shape) == 2: h, w = img.shape else: h, w, _ = img.shape th, tw = output_size i = int(round((h - th) / 2.)) j = int(round((w - tw) / 2.)) return crop(img, i, j, th, tw) def resize(img, size, interpolation=Image.BILINEAR): """Resize the input PIL Image to the given size. Note: cv2.resize do not support int32, weird Args: img (Numpy Array): Image to be resized. size (sequence or int): Desired output size. If size is a sequence like (h, w), the output size will be matched to this. If size is an int, the smaller edge of the image will be matched to this number maintaing the aspect ratio. i.e, if height > width, then image will be rescaled to (size * height / width, size) interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR`` Returns: PIL Image: Resized image. """ if not _is_numpy_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) if not (isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)): raise TypeError('Got inappropriate size arg: {}'.format(size)) if isinstance(size, int): size = (size, size) if img.dtype == np.int32: resized = img.astype(np.uint16) resized = cv2.resize(resized, size , interpolation) else: resized = cv2.resize(img, size , interpolation) resized = resized.astype(img.dtype) return resized def crop_resize(img, top, left, width, height, size, interpolation=Image.BILINEAR): """Crop the given PIL Image and resize it to desired size. Notably used in RandomResizedCrop. Args: img (PIL Image): Image to be cropped. i: Upper pixel coordinate. j: Left pixel coordinate. h: Height of the cropped image. w: Width of the cropped image. size (sequence or int): Desired output size. Same semantics as ``scale``. interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR``. Returns: PIL Image: Cropped image. """ assert _is_numpy_image(img), 'img should be PIL Image' img = crop(img, top, left, width, height) img = resize(img, size, interpolation) return img def pad(img, pad_width, mode='reflect', **kwargs): """Pad the given image. Args: pad_width : int, padding width mode: str or function. contain{‘constant’,‘edge’,‘linear_ramp’,‘maximum’,‘mean’ , ‘median’, ‘minimum’, ‘reflect’,‘symmetric’,‘wrap’} Examples -------- >>> Transformed_img = pad(img,[(20,20),(20,20),(0,0)],mode='reflect') """ if len(img.shape) == 2: pad_width = ((pad_width, pad_width), (pad_width, pad_width)) else: pad_width = ((pad_width, pad_width), (pad_width, pad_width), (0, 0)) return np.pad(img, pad_width, mode) def noise(img, dtype='uint8', mode='gaussian', mean=0, var=0.01): """TODO """ if dtype == 'uint16': img_new = img.astype(np.uint16) img_new = util.random_noise(img, mode, mean=mean, var=var) if dtype == 'uint8': img_new = (img_new * np.iinfo(np.uint8).max).astype(np.uint8) elif dtype == 'uint16': img_new = (img_new * np.iinfo(np.int32).max).astype(np.int32) else: raise ValueError('not support type') return img_new def gaussian_blur(img, sigma=1, dtype='uint8', multichannel=False): """Multi-dimensional Gaussian filter. Parameters ---------- image : ndarray Input image (grayscale or color) to filter. sigma : scalar or sequence of scalars, optional Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. multichannel : bool, optional (default: None) Whether the last axis of the image is to be interpreted as multiple channels. If True, each channel is filtered separately (channels are not mixed together). Only 3 channels are supported. If `None`, the function will attempt to guess this, and raise a warning if ambiguous, when the array has shape (M, N, 3). Returns ------- filtered_image : ndarray """ if np.any(np.asarray(sigma) < 0.0): raise ValueError("Sigma values less than zero are not valid")
img_new = (img_new * np.iinfo(np.int32).max).astype(np.int32) else: raise ValueError('not support type') return img_new def piecewise_transform(image, numcols=5, numrows=5, warp_left_right=10, warp_up_down=10, order=1): """2D piecewise affine transformation. Control points are used to define the mapping. The transform is based on a Delaunay triangulation of the points to form a mesh. Each triangle is used to find a local affine transform. Parameters ---------- img : ndarray numcols : int, optional (default: 5) numbers of the colums to transformation numrows : int, optional (default: 5) numbers of the rows to transformation warp_left_right: int, optional (default: 10) the pixels of transformation left and right warp_up_down: int, optional (default: 10) the pixels of transformation up and down Returns ------- Transformed_image : ndarray Examples -------- >>> Transformed_img = piecetransform(image,numcols=10, numrows=10, warp_left_right=5, warp_up_down=5) """ rows, cols = image.shape[0], image.shape[1] numcols = numcols numrows = numrows src_cols = np.linspace(0, cols, numcols, dtype=int) src_rows = np.linspace(0, rows, numrows, dtype=int) src_rows, src_cols = np.meshgrid(src_rows, src_cols) src = np.dstack([src_cols.flat, src_rows.flat])[0] src_rows_new = np.ndarray.transpose(src_rows) src_cols_new = np.ndarray.transpose(src_cols) # src_new = np.dstack([src_cols_new.flat, src_rows_new.flat])[0] dst_cols = np.ndarray(src_cols.shape) dst_rows = np.ndarray(src_rows.shape) for i in range(0, numcols): for j in range(0, numrows): if src_cols[i, j] == 0 or src_cols[i, j] == cols: dst_cols[i, j] = src_cols[i, j] else: dst_cols[i, j] = src_cols[i, j] + np.random.uniform(-1, 1) * warp_left_right if src_rows[i, j] == 0 or src_rows[i, j] == rows: dst_rows[i, j] = src_rows[i, j] else: dst_rows[i, j] = src_rows[i, j] + np.random.uniform(-1, 1) * warp_up_down dst = np.dstack([dst_cols.flat, dst_rows.flat])[0] # dst_rows_new = np.ndarray.transpose(dst_rows) # dst_cols_new = np.ndarray.transpose(dst_cols) # dst_new = np.dstack([dst_cols_new.flat, dst_rows_new.flat])[0] tform = transform.PiecewiseAffineTransform() tform.estimate(src, dst) img_new = transform.warp(image, tform, output_shape=(rows, cols), order=order, preserve_range=True) img_new = img_new.astype(image.dtype) return img_new if __name__ == '__main__': img = tifffile.imread('sample-data/MUL_AOI_4_Shanghai_img1920.tif') # tifffile.imshow(img[:,:,[3,2,1]]) img = img.astype(np.int32) out = resize(img, (224,224)) # out = filters.gaussian_filter(img, sigma=2) # out2 = gaussian_blur(img, dtype='uint16') # out2 = to_tensor(out2) # out3 = to_ndarray(out2, dtype='uint16') # pass
img_new = filters.gaussian(img, sigma, multichannel) if dtype == 'uint8': print(img_new.max(), img_new.min()) img_new = (img_new * np.iinfo(np.uint8).max).astype(np.uint8) elif dtype == 'uint16':
random_line_split
eip.go
// Copyright 2019 Yunion // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package qcloud import ( "fmt" "strings" "time" "yunion.io/x/jsonutils" "yunion.io/x/log" billing_api "yunion.io/x/onecloud/pkg/apis/billing" api "yunion.io/x/onecloud/pkg/apis/compute" "yunion.io/x/onecloud/pkg/cloudprovider" "yunion.io/x/onecloud/pkg/multicloud" ) type TInternetChargeType string const ( InternetChargeByTraffic = TInternetChargeType("PayByTraffic") InternetChargeByBandwidth = TInternetChargeType("PayByBandwidth") ) const ( EIP_STATUS_CREATING = "CREATING" EIP_STATUS_BINDING = "BINDING" EIP_STATUS_BIND = "BIND" EIP_STATUS_UNBINDING = "UNBINDING" EIP_STATUS_UNBIND = "UNBIND" EIP_STATUS_OFFLINING = "OFFLINING" EIP_STATUS_BIND_ENI = "BIND_ENI" EIP_STATUS_CREATE_FAILED = "CREATE_FAILED" EIP_TYPE_CALCIP = "CalcIP" //表示设备ip EIP_TYPE_WANIP = "WanIP" //普通公网ip EIP_TYPE_EIP = "EIP" //弹性公网ip EIP_TYPE_ANYCASTEIP = "AnycastEIP" //加速EIP ) type SEipAddress struct { region *SRegion multicloud.SEipBase AddressId string // EIP的ID,是EIP的唯一标识。 AddressName string // EIP名称。 AddressStatus string // EIP状态。 AddressIp string // 外网IP地址 InstanceId string // 绑定的资源实例ID。可能是一个CVM,NAT。 CreatedTime time.Time // 创建时间。按照ISO8601标准表示,并且使用UTC时间。格式为:YYYY-MM-DDThh:mm:ssZ。 NetworkInterfaceId string // 绑定的弹性网卡ID PrivateAddressIp string // 绑定的资源内网ip IsArrears bool // 资源隔离状态。true表示eip处于隔离状态,false表示资源处于未隔离装填 IsBlocked bool // 资源封堵状态。true表示eip处于封堵状态,false表示eip处于未封堵状态 IsEipDirectConnection bool // eip是否支持直通模式。true表示eip支持直通模式,false表示资源不支持直通模式 AddressType string // eip资源类型,包括"CalcIP","WanIP","EIP","AnycastEIP"。其中"CalcIP"表示设备ip,“WanIP”表示普通公网ip,“EIP”表示弹性公网ip,“AnycastEip”表示加速EIP CascadeRelease bool // eip是否在解绑后自动释放。true表示eip将会在解绑后自动释放,false表示eip在解绑后不会自动释放 } func (self *SEipAddress) GetId() string { return self.AddressId } func (self *SEipAddress) GetName() string { if len(self.AddressName) > 0 && self.AddressName != "未命名" { return self.AddressName } return self.AddressId } func (self *SEipAddress) GetGlobalId() string { return self.AddressId } func (self *SEipAddress) GetStatus() string { switch self.AddressStatus { case EIP_STATUS_CREATING: return api.EIP_STATUS_ALLOCATE case EIP_STATUS_BINDING: return api.EIP_STATUS_ASSOCIATE case EIP_STATUS_UNBINDING: return api.EIP_STATUS_DISSOCIATE case EIP_STATUS_UNBIND, EIP_STATUS_BIND, EIP_STATUS_OFFLINING, EIP_STATUS_BIND_ENI: return api.EIP_STATUS_READY case EIP_STATUS_CREATE_FAILED: return api.EIP_STATUS_ALLOCATE_FAIL default: return api.EIP_STATUS_UNKNOWN } } func (self *SEipAddress) Refresh() error { if self.IsEmulated() { return nil } new, err := self.region.GetEip(self.AddressId) if err != nil { return err } return jsonutils.Update(self, new) } func (self *SEipAddress) IsEmulated() bool { if self.AddressId == self.InstanceId { // fixed Public IP return true } else { return false } } func (self *SEipAddress) GetMetadata() *jsonutils.JSONDict { return nil } func (self *SEipAddress) GetIpAddr() string { return self.AddressIp } func (self *SEipAddress) GetMode() string { if self.InstanceId == self.AddressId { return api.EIP_MODE_INSTANCE_PUBLICIP } return api.EIP_MODE_STANDALONE_EIP } func (self *SEipAddress) GetAssociationType() string { if len(self.InstanceId) > 0 { for prefix, instanceType := range map[string]string{ "nat-": api.EIP_ASSOCIATE_TYPE_NAT_GATEWAY, "ins-": api.EIP_ASSOCIATE_TYPE_SERVER, "lb-": api.EIP_ASSOCIATE_TYPE_LOADBALANCER, "lbl-": api.EIP_ASSOCIATE_TYPE_LOADBALANCER, } { if strings.HasPrefix(self.InstanceId, prefix) { return instanceType } } return api.EIP_ASSOCIATE_TYPE_UNKNOWN } return "" } func (self *SEipAddress) GetAssociationExternalId() string { return self.InstanceId } func (self *SEipAddress) Delete() error { return self.region.DeallocateEIP(self.AddressId) } func (self *SEipAddress) GetBandwidth() int { if len(self.InstanceId) > 0 { if strings.HasPrefix(self.InstanceId, "ins-") { if instance, err := self.region.GetInstance(self.InstanceId); err == nil { return instance.InternetAccessible.InternetMaxBandwidthOut } } } return 0 } func (self *SEipAddress) GetINetworkId() string { return "" } func (self *SEipAddress) GetBillingType() string { return billing_api.BILLING_TYPE_POSTPAID } func (self *SEipAddress) GetCreatedAt() time.Time { return self.CreatedTime } func (self *SEipAddress) GetExpi
self.region.GetInstance(self.InstanceId); err == nil { switch instance.InternetAccessible.InternetChargeType { case InternetChargeTypeTrafficPostpaidByHour: return api.EIP_CHARGE_TYPE_BY_TRAFFIC default: return api.EIP_CHARGE_TYPE_BY_BANDWIDTH } } } } return api.EIP_CHARGE_TYPE_BY_TRAFFIC } func (self *SEipAddress) Associate(conf *cloudprovider.AssociateConfig) error { err := self.region.AssociateEip(self.AddressId, conf.InstanceId) if err != nil { return err } if conf.Bandwidth > 0 { err = self.region.UpdateInstanceBandwidth(conf.InstanceId, conf.Bandwidth) if err != nil { log.Warningf("failed to change instance %s bandwidth -> %d error: %v", conf.InstanceId, conf.Bandwidth, err) } } return cloudprovider.WaitStatusWithDelay(self, api.EIP_STATUS_READY, 5*time.Second, 10*time.Second, 180*time.Second) } func (self *SEipAddress) Dissociate() error { err := self.region.DissociateEip(self.AddressId) if err != nil { return err } return cloudprovider.WaitStatusWithDelay(self, api.EIP_STATUS_READY, 5*time.Second, 10*time.Second, 180*time.Second) } func (self *SEipAddress) ChangeBandwidth(bw int) error { if len(self.InstanceId) > 0 { return self.region.UpdateInstanceBandwidth(self.InstanceId, bw) } return nil } func (region *SRegion) GetEips(eipId string, instanceId string, offset int, limit int) ([]SEipAddress, int, error) { if limit > 50 || limit <= 0 { limit = 50 } params := make(map[string]string) params["Limit"] = fmt.Sprintf("%d", limit) params["Offset"] = fmt.Sprintf("%d", offset) if len(eipId) > 0 { params["AddressIds.0"] = eipId } if len(instanceId) > 0 { params["Filters.0.Name"] = "instance-id" params["Filters.0.Values.0"] = instanceId } body, err := region.vpcRequest("DescribeAddresses", params) if err != nil { log.Errorf("DescribeEipAddresses fail %s", err) return nil, 0, err } eips := make([]SEipAddress, 0) err = body.Unmarshal(&eips, "AddressSet") if err != nil { log.Errorf("Unmarshal EipAddress details fail %s", err) return nil, 0, err } total, _ := body.Float("TotalCount") for i := 0; i < len(eips); i++ { eips[i].region = region } return eips, int(total), nil } func (region *SRegion) GetEip(eipId string) (*SEipAddress, error) { eips, total, err := region.GetEips(eipId, "", 0, 1) if err != nil { return nil, err } if total != 1 { return nil, cloudprovider.ErrNotFound } return &eips[0], nil } func (region *SRegion) AllocateEIP(name string, bwMbps int, chargeType TInternetChargeType) (*SEipAddress, error) { params := make(map[string]string) params["Region"] = region.Region addRessSet := []string{} body, err := region.vpcRequest("AllocateAddresses", params) if err != nil { return nil, err } err = body.Unmarshal(&addRessSet, "AddressSet") if err != nil { return nil, err } if len(name) > 20 { name = name[:20] } if len(addRessSet) > 0 { params["AddressId"] = addRessSet[0] params["AddressName"] = name _, err = region.vpcRequest("ModifyAddressAttribute", params) if err != nil { return nil, err } eip, err := region.GetEip(addRessSet[0]) if err != nil { return nil, err } return eip, cloudprovider.WaitStatus(eip, api.EIP_STATUS_READY, time.Second*5, time.Second*300) } return nil, cloudprovider.ErrNotFound } // https://cloud.tencent.com/document/api/215/16699 // 腾讯云eip不支持指定项目 func (region *SRegion) CreateEIP(eip *cloudprovider.SEip) (cloudprovider.ICloudEIP, error) { var ctype TInternetChargeType switch eip.ChargeType { case api.EIP_CHARGE_TYPE_BY_TRAFFIC: ctype = InternetChargeByTraffic case api.EIP_CHARGE_TYPE_BY_BANDWIDTH: ctype = InternetChargeByBandwidth } return region.AllocateEIP(eip.Name, eip.BandwidthMbps, ctype) } func (region *SRegion) DeallocateEIP(eipId string) error { params := make(map[string]string) params["Region"] = region.Region params["AddressIds.0"] = eipId _, err := region.vpcRequest("ReleaseAddresses", params) if err != nil { log.Errorf("ReleaseAddresses fail %s", err) } return err } func (region *SRegion) AssociateEip(eipId string, instanceId string) error { params := make(map[string]string) params["AddressId"] = eipId params["InstanceId"] = instanceId _, err := region.vpcRequest("AssociateAddress", params) if err != nil { log.Errorf("AssociateAddress fail %s", err) } return err } func (region *SRegion) DissociateEip(eipId string) error { params := make(map[string]string) params["Region"] = region.Region params["AddressId"] = eipId _, err := region.vpcRequest("DisassociateAddress", params) if err != nil { log.Errorf("UnassociateEipAddress fail %s", err) } return err } func (region *SRegion) UpdateInstanceBandwidth(instanceId string, bw int) error { params := make(map[string]string) params["Region"] = region.Region params["InstanceIds.0"] = instanceId params["InternetAccessible.InternetMaxBandwidthOut"] = fmt.Sprintf("%d", bw) _, err := region.cvmRequest("ResetInstancesInternetMaxBandwidth", params, true) return err } func (self *SEipAddress) GetProjectId() string { return "" }
redAt() time.Time { return time.Time{} } func (self *SEipAddress) GetInternetChargeType() string { if len(self.InstanceId) > 0 { if strings.HasPrefix(self.InstanceId, "ins-") { if instance, err :=
conditional_block
eip.go
// Copyright 2019 Yunion // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package qcloud import ( "fmt" "strings" "time" "yunion.io/x/jsonutils" "yunion.io/x/log" billing_api "yunion.io/x/onecloud/pkg/apis/billing" api "yunion.io/x/onecloud/pkg/apis/compute" "yunion.io/x/onecloud/pkg/cloudprovider" "yunion.io/x/onecloud/pkg/multicloud" ) type TInternetChargeType string const ( InternetChargeByTraffic = TInternetChargeType("PayByTraffic") InternetChargeByBandwidth = TInternetChargeType("PayByBandwidth") ) const ( EIP_STATUS_CREATING = "CREATING" EIP_STATUS_BINDING = "BINDING" EIP_STATUS_BIND = "BIND" EIP_STATUS_UNBINDING = "UNBINDING" EIP_STATUS_UNBIND = "UNBIND" EIP_STATUS_OFFLINING = "OFFLINING" EIP_STATUS_BIND_ENI = "BIND_ENI" EIP_STATUS_CREATE_FAILED = "CREATE_FAILED" EIP_TYPE_CALCIP = "CalcIP" //表示设备ip EIP_TYPE_WANIP = "WanIP" //普通公网ip EIP_TYPE_EIP = "EIP" //弹性公网ip EIP_TYPE_ANYCASTEIP = "AnycastEIP" //加速EIP ) type SEipAddress struct { region *SRegion multicloud.SEipBase AddressId string // EIP的ID,是EIP的唯一标识。 AddressName string // EIP名称。 AddressStatus string // EIP状态。 AddressIp string // 外网IP地址 InstanceId string // 绑定的资源实例ID。可能是一个CVM,NAT。 CreatedTime time.Time // 创建时间。按照ISO8601标准表示,并且使用UTC时间。格式为:YYYY-MM-DDThh:mm:ssZ。 NetworkInterfaceId string // 绑定的弹性网卡ID PrivateAddressIp string // 绑定的资源内网ip IsArrears bool // 资源隔离状态。true表示eip处于隔离状态,false表示资源处于未隔离装填 IsBlocked bool // 资源封堵状态。true表示eip处于封堵状态,false表示eip处于未封堵状态 IsEipDirectConnection bool // eip是否支持直通模式。true表示eip支持直通模式,false表示资源不支持直通模式 AddressType string // eip资源类型,包括"CalcIP","WanIP","EIP","AnycastEIP"。其中"CalcIP"表示设备ip,“WanIP”表示普通公网ip,“EIP”表示弹性公网ip,“AnycastEip”表示加速EIP CascadeRelease bool // eip是否在解绑后自动释放。true表示eip将会在解绑后自动释放,false表示eip在解绑后不会自动释放 } func (self *SEipAddress) GetId() string { return self.AddressId } func (self *SEipAddress) GetName() string { if len(self.AddressName) > 0 && self.AddressName != "未命名" { return self.AddressName } return self.AddressId } func (self *SEipAddress) GetGlobalId() string { return self.AddressId } func (self *SEipAddress) GetStatus() string { switch self.AddressStatus { case EIP_STATUS_CREATING: return api.EIP_STATUS_ALLOCATE case EIP_STATUS_BINDING: return api.EIP_STATUS_ASSOCIATE case EIP_STATUS_UNBINDING: return api.EIP_STATUS_DISSOCIATE case EIP_STATUS_UNBIND, EIP_STATUS_BIND, EIP_STATUS_OFFLINING, EIP_STATUS_BIND_ENI: return api.EIP_STATUS_READY case EIP_STATUS_CREATE_FAILED: return api.EIP_STATUS_ALLOCATE_FAIL default: return api.EIP_STATUS_UNKNOWN } } func (self *SEipAddress) Refresh() error { if self.IsEmulated() { return nil } new, err := self.region.GetEip(self.AddressId) if err != nil { return err } return jsonutils.Update(self, new) } func (self *SEipAddress) IsEmulated() bool { if self.AddressId == self.InstanceId { // fixed Public IP return true } else { return false } } func (self *SEipAddress) GetMetadata() *jsonutils.JSONDict { return nil } func (self *SEipAddress) GetIpAddr() string { return self.AddressIp } func (self *SEipAddress) GetMode() string { if self.InstanceId == self.AddressId { return api.EIP_MODE_INSTANCE_PUBLICIP } return api.EIP_MODE_STANDALONE_EIP } func (self *SEipAddress) GetAssociationType() string { if len(self.InstanceId) > 0 { for prefix, instanceType := range map[string]string{ "nat-": api.EIP_ASSOCIATE_TYPE_NAT_GATEWAY, "ins-": api.EIP_ASSOCIATE_TYPE_SERVER, "lb-": api.EIP_ASSOCIATE_TYPE_LOADBALANCER, "lbl-": api.EIP_ASSOCIATE_TYPE_LOADBALANCER, } { if strings.HasPrefix(self.InstanceId, prefix) { return instanceType } } return api.EIP_ASSOCIATE_TYPE_UNKNOWN } return "" } func (self *SEipAddress) GetAssociationExternalId() string { return self.InstanceId } func (self *SEipAddress) Delete() error { return self.region.DeallocateEIP(self.AddressId) } func (self *SEipAddress) GetBandwidth() int { if len(self.InstanceId) > 0 { if strings.HasPrefix(self.InstanceId, "ins-") { if instance, err := self.region.GetInstance(self.InstanceId); err == nil { return instance.InternetAccessible.InternetMaxBandwidthOut } } } return 0 } func (self *SEipAddress) GetINetworkId() string { return "" } func (self *SEipAddress) GetBillingType() string { return billing_api.BILLING_TYPE_POSTPAID } func (self *SEipAddress) GetCreatedAt() time.Time { return self.CreatedTime } func (self *SEipAddress) GetExpiredAt() time.Time { return time.Time{} } func (self *SEipAddress) GetInternetChargeType() string { if len(self.InstanceId) > 0 { if strings.HasPrefix(self.InstanceId, "ins-") { if instance, err := self.region.GetInstance(self.InstanceId); err == nil { switch instance.InternetAccessible.InternetChargeType { case InternetChargeTypeTrafficPostpaidByHour: return api.EIP_CHARGE_TYPE_BY_TRAFFIC default: return api.EIP_CHARGE_TYPE_BY_BANDWIDTH } } } } return api.EIP_CHA
func (self *SEipAddress) Associate(conf *cloudprovider.AssociateConfig) error { err := self.region.AssociateEip(self.AddressId, conf.InstanceId) if err != nil { return err } if conf.Bandwidth > 0 { err = self.region.UpdateInstanceBandwidth(conf.InstanceId, conf.Bandwidth) if err != nil { log.Warningf("failed to change instance %s bandwidth -> %d error: %v", conf.InstanceId, conf.Bandwidth, err) } } return cloudprovider.WaitStatusWithDelay(self, api.EIP_STATUS_READY, 5*time.Second, 10*time.Second, 180*time.Second) } func (self *SEipAddress) Dissociate() error { err := self.region.DissociateEip(self.AddressId) if err != nil { return err } return cloudprovider.WaitStatusWithDelay(self, api.EIP_STATUS_READY, 5*time.Second, 10*time.Second, 180*time.Second) } func (self *SEipAddress) ChangeBandwidth(bw int) error { if len(self.InstanceId) > 0 { return self.region.UpdateInstanceBandwidth(self.InstanceId, bw) } return nil } func (region *SRegion) GetEips(eipId string, instanceId string, offset int, limit int) ([]SEipAddress, int, error) { if limit > 50 || limit <= 0 { limit = 50 } params := make(map[string]string) params["Limit"] = fmt.Sprintf("%d", limit) params["Offset"] = fmt.Sprintf("%d", offset) if len(eipId) > 0 { params["AddressIds.0"] = eipId } if len(instanceId) > 0 { params["Filters.0.Name"] = "instance-id" params["Filters.0.Values.0"] = instanceId } body, err := region.vpcRequest("DescribeAddresses", params) if err != nil { log.Errorf("DescribeEipAddresses fail %s", err) return nil, 0, err } eips := make([]SEipAddress, 0) err = body.Unmarshal(&eips, "AddressSet") if err != nil { log.Errorf("Unmarshal EipAddress details fail %s", err) return nil, 0, err } total, _ := body.Float("TotalCount") for i := 0; i < len(eips); i++ { eips[i].region = region } return eips, int(total), nil } func (region *SRegion) GetEip(eipId string) (*SEipAddress, error) { eips, total, err := region.GetEips(eipId, "", 0, 1) if err != nil { return nil, err } if total != 1 { return nil, cloudprovider.ErrNotFound } return &eips[0], nil } func (region *SRegion) AllocateEIP(name string, bwMbps int, chargeType TInternetChargeType) (*SEipAddress, error) { params := make(map[string]string) params["Region"] = region.Region addRessSet := []string{} body, err := region.vpcRequest("AllocateAddresses", params) if err != nil { return nil, err } err = body.Unmarshal(&addRessSet, "AddressSet") if err != nil { return nil, err } if len(name) > 20 { name = name[:20] } if len(addRessSet) > 0 { params["AddressId"] = addRessSet[0] params["AddressName"] = name _, err = region.vpcRequest("ModifyAddressAttribute", params) if err != nil { return nil, err } eip, err := region.GetEip(addRessSet[0]) if err != nil { return nil, err } return eip, cloudprovider.WaitStatus(eip, api.EIP_STATUS_READY, time.Second*5, time.Second*300) } return nil, cloudprovider.ErrNotFound } // https://cloud.tencent.com/document/api/215/16699 // 腾讯云eip不支持指定项目 func (region *SRegion) CreateEIP(eip *cloudprovider.SEip) (cloudprovider.ICloudEIP, error) { var ctype TInternetChargeType switch eip.ChargeType { case api.EIP_CHARGE_TYPE_BY_TRAFFIC: ctype = InternetChargeByTraffic case api.EIP_CHARGE_TYPE_BY_BANDWIDTH: ctype = InternetChargeByBandwidth } return region.AllocateEIP(eip.Name, eip.BandwidthMbps, ctype) } func (region *SRegion) DeallocateEIP(eipId string) error { params := make(map[string]string) params["Region"] = region.Region params["AddressIds.0"] = eipId _, err := region.vpcRequest("ReleaseAddresses", params) if err != nil { log.Errorf("ReleaseAddresses fail %s", err) } return err } func (region *SRegion) AssociateEip(eipId string, instanceId string) error { params := make(map[string]string) params["AddressId"] = eipId params["InstanceId"] = instanceId _, err := region.vpcRequest("AssociateAddress", params) if err != nil { log.Errorf("AssociateAddress fail %s", err) } return err } func (region *SRegion) DissociateEip(eipId string) error { params := make(map[string]string) params["Region"] = region.Region params["AddressId"] = eipId _, err := region.vpcRequest("DisassociateAddress", params) if err != nil { log.Errorf("UnassociateEipAddress fail %s", err) } return err } func (region *SRegion) UpdateInstanceBandwidth(instanceId string, bw int) error { params := make(map[string]string) params["Region"] = region.Region params["InstanceIds.0"] = instanceId params["InternetAccessible.InternetMaxBandwidthOut"] = fmt.Sprintf("%d", bw) _, err := region.cvmRequest("ResetInstancesInternetMaxBandwidth", params, true) return err } func (self *SEipAddress) GetProjectId() string { return "" }
RGE_TYPE_BY_TRAFFIC }
identifier_body
eip.go
// Copyright 2019 Yunion // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package qcloud import ( "fmt" "strings" "time" "yunion.io/x/jsonutils" "yunion.io/x/log" billing_api "yunion.io/x/onecloud/pkg/apis/billing" api "yunion.io/x/onecloud/pkg/apis/compute" "yunion.io/x/onecloud/pkg/cloudprovider" "yunion.io/x/onecloud/pkg/multicloud" ) type TInternetChargeType string const ( InternetChargeByTraffic = TInternetChargeType("PayByTraffic") InternetChargeByBandwidth = TInternetChargeType("PayByBandwidth") ) const ( EIP_STATUS_CREATING = "CREATING" EIP_STATUS_BINDING = "BINDING" EIP_STATUS_BIND = "BIND" EIP_STATUS_UNBINDING = "UNBINDING" EIP_STATUS_UNBIND = "UNBIND" EIP_STATUS_OFFLINING = "OFFLINING" EIP_STATUS_BIND_ENI = "BIND_ENI" EIP_STATUS_CREATE_FAILED = "CREATE_FAILED" EIP_TYPE_CALCIP = "CalcIP" //表示设备ip EIP_TYPE_WANIP = "WanIP" //普通公网ip EIP_TYPE_EIP = "EIP" //弹性公网ip EIP_TYPE_ANYCASTEIP = "AnycastEIP" //加速EIP ) type SEipAddress struct { region *SRegion multicloud.SEipBase AddressId string // EIP的ID,是EIP的唯一标识。 AddressName string // EIP名称。 AddressStatus string // EIP状态。 AddressIp string // 外网IP地址 InstanceId string // 绑定的资源实例ID。可能是一个CVM,NAT。 CreatedTime time.Time // 创建时间。按照ISO8601标准表示,并且使用UTC时间。格式为:YYYY-MM-DDThh:mm:ssZ。 NetworkInterfaceId string // 绑定的弹性网卡ID PrivateAddressIp string // 绑定的资源内网ip IsArrears bool // 资源隔离状态。true表示eip处于隔离状态,false表示资源处于未隔离装填 IsBlocked bool // 资源封堵状态。true表示eip处于封堵状态,false表示eip处于未封堵状态 IsEipDirectConnection bool // eip是否支持直通模式。true表示eip支持直通模式,false表示资源不支持直通模式 AddressType string // eip资源类型,包括"CalcIP","WanIP","EIP","AnycastEIP"。其中"CalcIP"表示设备ip,“WanIP”表示普通公网ip,“EIP”表示弹性公网ip,“AnycastEip”表示加速EIP CascadeRelease bool // eip是否在解绑后自动释放。true表示eip将会在解绑后自动释放,false表示eip在解绑后不会自动释放 } func (self *SEipAddress) GetId() string { return self.AddressId } func (self *SEipAddress) GetName() string { if len(self.AddressName) > 0 && self.AddressName != "未命名" { return self.AddressName } return self.AddressId } func (self *SEipAddress) GetGlobalId() string { return self.AddressId } func (self *SEipAddress) GetStatus() string { switch self.AddressStatus { case EIP_STATUS_CREATING: return api.EIP_STATUS_ALLOCATE case EIP_STATUS_BINDING: return api.EIP_STATUS_ASSOCIATE case EIP_STATUS_UNBINDING: return api.EIP_STATUS_DISSOCIATE case EIP_STATUS_UNBIND, EIP_STATUS_BIND, EIP_STATUS_OFFLINING, EIP_STATUS_BIND_ENI: return api.EIP_STATUS_READY case EIP_STATUS_CREATE_FAILED: return api.EIP_STATUS_ALLOCATE_FAIL default: return api.EIP_STATUS_UNKNOWN } } func (self *SEipAddress) Refresh() error { if self.IsEmulated() { return nil } new, err := self.region.GetEip(self.AddressId) if err != nil { return err } return jsonutils.Update(self, new) } func (self *SEipAddress) IsEmulated() bool { if self.AddressId == self.InstanceId { // fixed Public IP return true } else { return false } } func (self *SEipAddress) GetMetadata() *jsonutils.JSONDict { return nil } func (self *SEipAddress) GetIpAddr() string { return self.AddressIp } func (self *SEipAddress) GetMode() string { if self.InstanceId == self.AddressId { return api.EIP_MODE_INSTANCE_PUBLICIP } return api.EIP_MODE_STANDALONE_EIP } func (self *SEipAddress) GetAssociationType() string { if len(self.InstanceId) > 0 { for prefix, instanceType := range map[string]string{ "nat-": api.EIP_ASSOCIATE_TYPE_NAT_GATEWAY, "ins-": api.EIP_ASSOCIATE_TYPE_SERVER, "lb-": api.EIP_ASSOCIATE_TYPE_LOADBALANCER, "lbl-": api.EIP_ASSOCIATE_TYPE_LOADBALANCER, } { if strings.HasPrefix(self.InstanceId, prefix) { return instanceType } } return api.EIP_ASSOCIATE_TYPE_UNKNOWN } return "" } func (self *SEipAddress) GetAssociationExternalId() string { return self.InstanceId } func (self *SEipAddress) Delete() error { return self.region.DeallocateEIP(self.AddressId) } func (self *SEipAddress) GetBandwidth() int { if len(self.InstanceId) > 0 { if strings.HasPrefix(self.InstanceId, "ins-") { if instance, err := self.region.GetInstance(self.InstanceId); err == nil { return instance.InternetAccessible.InternetMaxBandwidthOut } } } return 0 } func (self *SEipAddress) GetINetworkId() string { return "" } func (self *SEipAddress) GetBillingType() string { return billing_api.BILLING_TYPE_POSTPAID } func (self *SEipAddress) GetCreatedAt() time.Time { return self.CreatedTime } func (self *SEipAddress) GetExpiredAt() time.Time { return time.Time{} } func (self *SEipAddress) GetInternetChargeType() string { if len(self.InstanceId) > 0 { if strings.HasPrefix(self.InstanceId, "ins-") { if instance, err := self.region.GetInstance(self.InstanceId); err == nil { switch instance.InternetAccessible.InternetChargeType { case InternetChargeTypeTrafficPostpaidByHour: return api.EIP_CHARGE_TYPE_BY_TRAFFIC default: return api.EIP_CHARGE_TYPE_BY_BANDWIDTH }
} return api.EIP_CHARGE_TYPE_BY_TRAFFIC } func (self *SEipAddress) Associate(conf *cloudprovider.AssociateConfig) error { err := self.region.AssociateEip(self.AddressId, conf.InstanceId) if err != nil { return err } if conf.Bandwidth > 0 { err = self.region.UpdateInstanceBandwidth(conf.InstanceId, conf.Bandwidth) if err != nil { log.Warningf("failed to change instance %s bandwidth -> %d error: %v", conf.InstanceId, conf.Bandwidth, err) } } return cloudprovider.WaitStatusWithDelay(self, api.EIP_STATUS_READY, 5*time.Second, 10*time.Second, 180*time.Second) } func (self *SEipAddress) Dissociate() error { err := self.region.DissociateEip(self.AddressId) if err != nil { return err } return cloudprovider.WaitStatusWithDelay(self, api.EIP_STATUS_READY, 5*time.Second, 10*time.Second, 180*time.Second) } func (self *SEipAddress) ChangeBandwidth(bw int) error { if len(self.InstanceId) > 0 { return self.region.UpdateInstanceBandwidth(self.InstanceId, bw) } return nil } func (region *SRegion) GetEips(eipId string, instanceId string, offset int, limit int) ([]SEipAddress, int, error) { if limit > 50 || limit <= 0 { limit = 50 } params := make(map[string]string) params["Limit"] = fmt.Sprintf("%d", limit) params["Offset"] = fmt.Sprintf("%d", offset) if len(eipId) > 0 { params["AddressIds.0"] = eipId } if len(instanceId) > 0 { params["Filters.0.Name"] = "instance-id" params["Filters.0.Values.0"] = instanceId } body, err := region.vpcRequest("DescribeAddresses", params) if err != nil { log.Errorf("DescribeEipAddresses fail %s", err) return nil, 0, err } eips := make([]SEipAddress, 0) err = body.Unmarshal(&eips, "AddressSet") if err != nil { log.Errorf("Unmarshal EipAddress details fail %s", err) return nil, 0, err } total, _ := body.Float("TotalCount") for i := 0; i < len(eips); i++ { eips[i].region = region } return eips, int(total), nil } func (region *SRegion) GetEip(eipId string) (*SEipAddress, error) { eips, total, err := region.GetEips(eipId, "", 0, 1) if err != nil { return nil, err } if total != 1 { return nil, cloudprovider.ErrNotFound } return &eips[0], nil } func (region *SRegion) AllocateEIP(name string, bwMbps int, chargeType TInternetChargeType) (*SEipAddress, error) { params := make(map[string]string) params["Region"] = region.Region addRessSet := []string{} body, err := region.vpcRequest("AllocateAddresses", params) if err != nil { return nil, err } err = body.Unmarshal(&addRessSet, "AddressSet") if err != nil { return nil, err } if len(name) > 20 { name = name[:20] } if len(addRessSet) > 0 { params["AddressId"] = addRessSet[0] params["AddressName"] = name _, err = region.vpcRequest("ModifyAddressAttribute", params) if err != nil { return nil, err } eip, err := region.GetEip(addRessSet[0]) if err != nil { return nil, err } return eip, cloudprovider.WaitStatus(eip, api.EIP_STATUS_READY, time.Second*5, time.Second*300) } return nil, cloudprovider.ErrNotFound } // https://cloud.tencent.com/document/api/215/16699 // 腾讯云eip不支持指定项目 func (region *SRegion) CreateEIP(eip *cloudprovider.SEip) (cloudprovider.ICloudEIP, error) { var ctype TInternetChargeType switch eip.ChargeType { case api.EIP_CHARGE_TYPE_BY_TRAFFIC: ctype = InternetChargeByTraffic case api.EIP_CHARGE_TYPE_BY_BANDWIDTH: ctype = InternetChargeByBandwidth } return region.AllocateEIP(eip.Name, eip.BandwidthMbps, ctype) } func (region *SRegion) DeallocateEIP(eipId string) error { params := make(map[string]string) params["Region"] = region.Region params["AddressIds.0"] = eipId _, err := region.vpcRequest("ReleaseAddresses", params) if err != nil { log.Errorf("ReleaseAddresses fail %s", err) } return err } func (region *SRegion) AssociateEip(eipId string, instanceId string) error { params := make(map[string]string) params["AddressId"] = eipId params["InstanceId"] = instanceId _, err := region.vpcRequest("AssociateAddress", params) if err != nil { log.Errorf("AssociateAddress fail %s", err) } return err } func (region *SRegion) DissociateEip(eipId string) error { params := make(map[string]string) params["Region"] = region.Region params["AddressId"] = eipId _, err := region.vpcRequest("DisassociateAddress", params) if err != nil { log.Errorf("UnassociateEipAddress fail %s", err) } return err } func (region *SRegion) UpdateInstanceBandwidth(instanceId string, bw int) error { params := make(map[string]string) params["Region"] = region.Region params["InstanceIds.0"] = instanceId params["InternetAccessible.InternetMaxBandwidthOut"] = fmt.Sprintf("%d", bw) _, err := region.cvmRequest("ResetInstancesInternetMaxBandwidth", params, true) return err } func (self *SEipAddress) GetProjectId() string { return "" }
} }
random_line_split
eip.go
// Copyright 2019 Yunion // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package qcloud import ( "fmt" "strings" "time" "yunion.io/x/jsonutils" "yunion.io/x/log" billing_api "yunion.io/x/onecloud/pkg/apis/billing" api "yunion.io/x/onecloud/pkg/apis/compute" "yunion.io/x/onecloud/pkg/cloudprovider" "yunion.io/x/onecloud/pkg/multicloud" ) type TInternetChargeType string const ( InternetChargeByTraffic = TInternetChargeType("PayByTraffic") InternetChargeByBandwidth = TInternetChargeType("PayByBandwidth") ) const ( EIP_STATUS_CREATING = "CREATING" EIP_STATUS_BINDING = "BINDING" EIP_STATUS_BIND = "BIND" EIP_STATUS_UNBINDING = "UNBINDING" EIP_STATUS_UNBIND = "UNBIND" EIP_STATUS_OFFLINING = "OFFLINING" EIP_STATUS_BIND_ENI = "BIND_ENI" EIP_STATUS_CREATE_FAILED = "CREATE_FAILED" EIP_TYPE_CALCIP = "CalcIP" //表示设备ip EIP_TYPE_WANIP = "WanIP" //普通公网ip EIP_TYPE_EIP = "EIP" //弹性公网ip EIP_TYPE_ANYCASTEIP = "AnycastEIP" //加速EIP ) type SEipAddress struct { region *SRegion multicloud.SEipBase AddressId string // EIP的ID,是EIP的唯一标识。 AddressName string // EIP名称。 AddressStatus string // EIP状态。 AddressIp string // 外网IP地址 InstanceId string // 绑定的资源实例ID。可能是一个CVM,NAT。 CreatedTime time.Time // 创建时间。按照ISO8601标准表示,并且使用UTC时间。格式为:YYYY-MM-DDThh:mm:ssZ。 NetworkInterfaceId string // 绑定的弹性网卡ID PrivateAddressIp string // 绑定的资源内网ip IsArrears bool // 资源隔离状态。true表示eip处于隔离状态,false表示资源处于未隔离装填 IsBlocked bool // 资源封堵状态。true表示eip处于封堵状态,false表示eip处于未封堵状态 IsEipDirectConnection bool // eip是否支持直通模式。true表示eip支持直通模式,false表示资源不支持直通模式 AddressType string // eip资源类型,包括"CalcIP","WanIP","EIP","AnycastEIP"。其中"CalcIP"表示设备ip,“WanIP”表示普通公网ip,“EIP”表示弹性公网ip,“AnycastEip”表示加速EIP CascadeRelease bool // eip是否在解绑后自动释放。true表示eip将会在解绑后自动释放,false表示eip在解绑后不会自动释放 } func (self *SEipAddress) GetId() string { return self.AddressId } func (self *SEipAddress) GetName() string { if len(self.AddressName) > 0 && self.AddressName != "未命名" { return self.AddressName } return self.AddressId } func (self *SEipAddress) GetGlobalId() string { return self.AddressId } func (self *SEipAddress) GetStatus() string { switch self.AddressStatus { case EIP_STATUS_CREATING: return api.EIP_STATUS_ALLOCATE case EIP_STATUS_BINDING: return api.EIP_STATUS_ASSOCIATE case EIP_ST
UNBINDING: return api.EIP_STATUS_DISSOCIATE case EIP_STATUS_UNBIND, EIP_STATUS_BIND, EIP_STATUS_OFFLINING, EIP_STATUS_BIND_ENI: return api.EIP_STATUS_READY case EIP_STATUS_CREATE_FAILED: return api.EIP_STATUS_ALLOCATE_FAIL default: return api.EIP_STATUS_UNKNOWN } } func (self *SEipAddress) Refresh() error { if self.IsEmulated() { return nil } new, err := self.region.GetEip(self.AddressId) if err != nil { return err } return jsonutils.Update(self, new) } func (self *SEipAddress) IsEmulated() bool { if self.AddressId == self.InstanceId { // fixed Public IP return true } else { return false } } func (self *SEipAddress) GetMetadata() *jsonutils.JSONDict { return nil } func (self *SEipAddress) GetIpAddr() string { return self.AddressIp } func (self *SEipAddress) GetMode() string { if self.InstanceId == self.AddressId { return api.EIP_MODE_INSTANCE_PUBLICIP } return api.EIP_MODE_STANDALONE_EIP } func (self *SEipAddress) GetAssociationType() string { if len(self.InstanceId) > 0 { for prefix, instanceType := range map[string]string{ "nat-": api.EIP_ASSOCIATE_TYPE_NAT_GATEWAY, "ins-": api.EIP_ASSOCIATE_TYPE_SERVER, "lb-": api.EIP_ASSOCIATE_TYPE_LOADBALANCER, "lbl-": api.EIP_ASSOCIATE_TYPE_LOADBALANCER, } { if strings.HasPrefix(self.InstanceId, prefix) { return instanceType } } return api.EIP_ASSOCIATE_TYPE_UNKNOWN } return "" } func (self *SEipAddress) GetAssociationExternalId() string { return self.InstanceId } func (self *SEipAddress) Delete() error { return self.region.DeallocateEIP(self.AddressId) } func (self *SEipAddress) GetBandwidth() int { if len(self.InstanceId) > 0 { if strings.HasPrefix(self.InstanceId, "ins-") { if instance, err := self.region.GetInstance(self.InstanceId); err == nil { return instance.InternetAccessible.InternetMaxBandwidthOut } } } return 0 } func (self *SEipAddress) GetINetworkId() string { return "" } func (self *SEipAddress) GetBillingType() string { return billing_api.BILLING_TYPE_POSTPAID } func (self *SEipAddress) GetCreatedAt() time.Time { return self.CreatedTime } func (self *SEipAddress) GetExpiredAt() time.Time { return time.Time{} } func (self *SEipAddress) GetInternetChargeType() string { if len(self.InstanceId) > 0 { if strings.HasPrefix(self.InstanceId, "ins-") { if instance, err := self.region.GetInstance(self.InstanceId); err == nil { switch instance.InternetAccessible.InternetChargeType { case InternetChargeTypeTrafficPostpaidByHour: return api.EIP_CHARGE_TYPE_BY_TRAFFIC default: return api.EIP_CHARGE_TYPE_BY_BANDWIDTH } } } } return api.EIP_CHARGE_TYPE_BY_TRAFFIC } func (self *SEipAddress) Associate(conf *cloudprovider.AssociateConfig) error { err := self.region.AssociateEip(self.AddressId, conf.InstanceId) if err != nil { return err } if conf.Bandwidth > 0 { err = self.region.UpdateInstanceBandwidth(conf.InstanceId, conf.Bandwidth) if err != nil { log.Warningf("failed to change instance %s bandwidth -> %d error: %v", conf.InstanceId, conf.Bandwidth, err) } } return cloudprovider.WaitStatusWithDelay(self, api.EIP_STATUS_READY, 5*time.Second, 10*time.Second, 180*time.Second) } func (self *SEipAddress) Dissociate() error { err := self.region.DissociateEip(self.AddressId) if err != nil { return err } return cloudprovider.WaitStatusWithDelay(self, api.EIP_STATUS_READY, 5*time.Second, 10*time.Second, 180*time.Second) } func (self *SEipAddress) ChangeBandwidth(bw int) error { if len(self.InstanceId) > 0 { return self.region.UpdateInstanceBandwidth(self.InstanceId, bw) } return nil } func (region *SRegion) GetEips(eipId string, instanceId string, offset int, limit int) ([]SEipAddress, int, error) { if limit > 50 || limit <= 0 { limit = 50 } params := make(map[string]string) params["Limit"] = fmt.Sprintf("%d", limit) params["Offset"] = fmt.Sprintf("%d", offset) if len(eipId) > 0 { params["AddressIds.0"] = eipId } if len(instanceId) > 0 { params["Filters.0.Name"] = "instance-id" params["Filters.0.Values.0"] = instanceId } body, err := region.vpcRequest("DescribeAddresses", params) if err != nil { log.Errorf("DescribeEipAddresses fail %s", err) return nil, 0, err } eips := make([]SEipAddress, 0) err = body.Unmarshal(&eips, "AddressSet") if err != nil { log.Errorf("Unmarshal EipAddress details fail %s", err) return nil, 0, err } total, _ := body.Float("TotalCount") for i := 0; i < len(eips); i++ { eips[i].region = region } return eips, int(total), nil } func (region *SRegion) GetEip(eipId string) (*SEipAddress, error) { eips, total, err := region.GetEips(eipId, "", 0, 1) if err != nil { return nil, err } if total != 1 { return nil, cloudprovider.ErrNotFound } return &eips[0], nil } func (region *SRegion) AllocateEIP(name string, bwMbps int, chargeType TInternetChargeType) (*SEipAddress, error) { params := make(map[string]string) params["Region"] = region.Region addRessSet := []string{} body, err := region.vpcRequest("AllocateAddresses", params) if err != nil { return nil, err } err = body.Unmarshal(&addRessSet, "AddressSet") if err != nil { return nil, err } if len(name) > 20 { name = name[:20] } if len(addRessSet) > 0 { params["AddressId"] = addRessSet[0] params["AddressName"] = name _, err = region.vpcRequest("ModifyAddressAttribute", params) if err != nil { return nil, err } eip, err := region.GetEip(addRessSet[0]) if err != nil { return nil, err } return eip, cloudprovider.WaitStatus(eip, api.EIP_STATUS_READY, time.Second*5, time.Second*300) } return nil, cloudprovider.ErrNotFound } // https://cloud.tencent.com/document/api/215/16699 // 腾讯云eip不支持指定项目 func (region *SRegion) CreateEIP(eip *cloudprovider.SEip) (cloudprovider.ICloudEIP, error) { var ctype TInternetChargeType switch eip.ChargeType { case api.EIP_CHARGE_TYPE_BY_TRAFFIC: ctype = InternetChargeByTraffic case api.EIP_CHARGE_TYPE_BY_BANDWIDTH: ctype = InternetChargeByBandwidth } return region.AllocateEIP(eip.Name, eip.BandwidthMbps, ctype) } func (region *SRegion) DeallocateEIP(eipId string) error { params := make(map[string]string) params["Region"] = region.Region params["AddressIds.0"] = eipId _, err := region.vpcRequest("ReleaseAddresses", params) if err != nil { log.Errorf("ReleaseAddresses fail %s", err) } return err } func (region *SRegion) AssociateEip(eipId string, instanceId string) error { params := make(map[string]string) params["AddressId"] = eipId params["InstanceId"] = instanceId _, err := region.vpcRequest("AssociateAddress", params) if err != nil { log.Errorf("AssociateAddress fail %s", err) } return err } func (region *SRegion) DissociateEip(eipId string) error { params := make(map[string]string) params["Region"] = region.Region params["AddressId"] = eipId _, err := region.vpcRequest("DisassociateAddress", params) if err != nil { log.Errorf("UnassociateEipAddress fail %s", err) } return err } func (region *SRegion) UpdateInstanceBandwidth(instanceId string, bw int) error { params := make(map[string]string) params["Region"] = region.Region params["InstanceIds.0"] = instanceId params["InternetAccessible.InternetMaxBandwidthOut"] = fmt.Sprintf("%d", bw) _, err := region.cvmRequest("ResetInstancesInternetMaxBandwidth", params, true) return err } func (self *SEipAddress) GetProjectId() string { return "" }
ATUS_
identifier_name
parser.py
from __future__ import annotations import json import os from pathlib import Path from typing import Tuple, Optional, List import jmespath import logging import re import yaml from yaml import YAMLError from checkov.cloudformation.parser import cfn_yaml from checkov.cloudformation.context_parser import ContextParser from checkov.cloudformation.parser.cfn_yaml import CfnParseError from checkov.common.models.consts import SLS_DEFAULT_VAR_PATTERN from checkov.common.parsers.node import DictNode, StrNode from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger logger = logging.getLogger(__name__) add_resource_code_filter_to_logger(logger) IAM_ROLE_STATEMENTS_TOKEN = 'iamRoleStatements' # nosec CFN_RESOURCES_TOKEN = 'resources' # nosec PROVIDER_TOKEN = 'provider' # nosec FUNCTIONS_TOKEN = 'functions' # nosec ENVIRONMENT_TOKEN = 'environment' # nosec STACK_TAGS_TOKEN = 'stackTags' # nosec TAGS_TOKEN = 'tags' # nosec SUPPORTED_PROVIDERS = ['aws'] QUOTED_WORD_SYNTAX = re.compile(r"(?:('|\").*?\1)") FILE_LOCATION_PATTERN = re.compile(r'^file\(([^?%*:|"<>]+?)\)') def parse(filename): template = None template_lines = None try: (template, template_lines) = cfn_yaml.load(filename, cfn_yaml.ContentType.SLS) if not template or not is_checked_sls_template(template): return except IOError as e: if e.errno == 2: logger.error('Template file not found: %s', filename) return elif e.errno == 21: logger.error('Template references a directory, not a file: %s', filename) return elif e.errno == 13: logger.error('Permission denied when accessing template file: %s', filename) return except UnicodeDecodeError: logger.error('Cannot read file contents: %s', filename) return except CfnParseError: logger.warning(f"Failed to parse file {filename} because it isn't a valid template") return except YAMLError: logger.warning(f"Failed to parse file {filename} as a yaml") return process_variables(template, filename) return template, template_lines def is_checked_sls_template(template): if template.__contains__('provider'): # Case provider is a dictionary if isinstance(template['provider'], DictNode): if template['provider'].get('name', '').lower() not in SUPPORTED_PROVIDERS: return False # Case provider is direct provider name if isinstance(template['provider'], StrNode): if template['provider'] not in SUPPORTED_PROVIDERS: return False return True return False def template_contains_cfn_resources(template): if template.__contains__(CFN_RESOURCES_TOKEN) and isinstance(template[CFN_RESOURCES_TOKEN], DictNode): if template[CFN_RESOURCES_TOKEN].get('Resources'): return True return False def template_contains_key(template, key): if ContextParser.search_deep_keys(key, template, []): return True return False def process_variables(template, filename): """ Modifies the template data in-place to resolve variables. """ file_data_cache = {} service_file_directory = os.path.dirname(filename) var_pattern = jmespath.search("provider.variableSyntax", template) if var_pattern is not None: # Remove to prevent self-matching during processing del template["provider"]["variableSyntax"] else: var_pattern = SLS_DEFAULT_VAR_PATTERN compiled_var_pattern = re.compile(var_pattern) # Processing is done in a loop to deal with chained references and the like. # Loop while the data is being changed, stop when no more changes are happening. # To ensure there's not some kind of oscillation, a cap of 25 passes is in place. # More than a couple loops isn't normally expected. # NOTE: If this approach proves to be a performance liability, a DAG will be needed. loop_count = 0 for _ in range(0, 25): loop_count += 1 made_change = False if process_variables_loop(template, compiled_var_pattern, # vt = var type # vl = var location # ft = fallback var type # fl = fallback var location lambda vt, vl, ft, fl: _load_var_data(vt, vl, ft, fl, file_data_cache, template, service_file_directory)): made_change = True if not made_change: break logger.debug("Processing of %s variables took %d loop iterations", filename, loop_count) return template def process_variables_loop(template, var_pattern, param_lookup_function): """ Generic processing loop for variables. :param template: The dictionary currently being processed. This function will be called recursively starting at dict provided. :param var_pattern: A compiled regex pattern which should name match groups if they are needed for looking up the data source. :param param_lookup_function: A Callable taking four arguments: 1) the type (e.g., "self", "file(/path/to/file.yml)") 2) the location (e.g., "custom.my_property") 3) fallback var type (same as above plus None for static value) 4) fallback var location or value if type was None """ # Generic loop for handling a source of key/value tuples (e.g., enumerate() or <dict>.items()) def process_items_helper(key_value_iterator, data_map): made_change = False for key, value in key_value_iterator: if isinstance(value, str): altered_value = value for match in var_pattern.finditer(value): var_type, var_loc, fallback_type, fallback_loc = _parse_var(match[1]) source_value = param_lookup_function(var_type, var_loc, fallback_type, fallback_loc) # If we can't find a value, skip it if source_value is None: continue try: if altered_value == match[0]: # complete replacement altered_value = source_value else: # partial replacement altered_value = altered_value.replace(match[0], source_value) except TypeError: pass if value != altered_value: data_map[key] = altered_value made_change = True elif isinstance(value, dict): if process_variables_loop(value, var_pattern, param_lookup_function): made_change = True elif isinstance(value, list): if process_items_helper(enumerate(value), value): made_change = True return made_change return process_items_helper(template.items(), template) def _load_var_data( var_type, var_location, fallback_var_type, fallback_var_location, file_cache, self_data_source, service_file_directory ): """ Load data based on the type/path (see param_lookup_function parameter of process_variables for more info). :param var_type: Either the type of the variable (see process_variables function) or None to indicate that var_location is a raw value. :param var_location: Either the location of the variable (see process_variables function) or a raw value if var_type is None :return None if the variable could not be resolved """ value = None if var_type is None: value = var_location elif var_type == "self": value = _determine_variable_value_from_dict(self_data_source, var_location, None) elif var_type == "env": value = _determine_variable_value_from_dict(os.environ, var_location, None) elif var_type.startswith("file("): match = FILE_LOCATION_PATTERN.match(var_type) if match is None: return None data_source = _load_file_data(match[1], file_cache, service_file_directory) value = _determine_variable_value_from_dict(data_source, var_location, None) if value is None and fallback_var_location is not None: return _load_var_data(fallback_var_type, fallback_var_location, None, None, file_cache, self_data_source, service_file_directory) return value def _determine_variable_value_from_dict(source_dict, location_str, default): if location_str is None: return source_dict if default is not None: default = default.strip() # NOTE: String must be quoted to avoid issues with dashes and other reserved # characters. If we just wrap the whole thing, dot separators won't work so: # split and join with individually wrapped tokens. # Original: foo.bar-baz # Wrapped: "foo"."bar-baz" location = ".".join([f'"{token}"' for token in location_str.split(".")]) source_value = jmespath.search(location, source_dict) if source_value is None: return default return source_value def _self_var_data_lookup(group_dict, template): location = group_dict["loc"] default = group_dict.get("default") return _determine_variable_value_from_dict(template, location, default) def _load_file_data(file_location, file_data_cache, service_file_directory): file_location = file_location.replace("~", str(Path.home())) file_location = file_location if os.path.isabs(file_location) else \ os.path.join(service_file_directory, file_location) data = file_data_cache.get(file_location) if data is None: try: with open(file_location, "r") as f: if file_location.endswith(".json"): data = json.load(f) elif file_location.endswith(".yml") or file_location.endswith(".yaml"): data = yaml.safe_load(f) except Exception: data = {} file_data_cache[file_location] = data return data def _token_to_type_and_loc(token: str) -> Tuple[Optional[str], Optional[str]]: file_match = FILE_LOCATION_PATTERN.match(token) if file_match is not None: if ":" not in token: return file_match[0], None return file_match[0].strip(), token[len(file_match[0]) + 1 :].strip() # +1 for colon if ":" not in token: return None, token index = token.index(":") return token[:index].strip(), token[index + 1 :].strip() def _parse_var(var_str): """ Returns a tuple of the var type, var loc, fallback type and fallback loc. See docs for the param_lookup_function parameter of process_variables_loop for more info. """ tokens = _tokenize_by_commas(var_str.strip()) if not tokens: return None var_type, var_loc = _token_to_type_and_loc(tokens[0]) if len(tokens) > 1: fallback_type, fallback_loc = _token_to_type_and_loc(tokens[1]) else: fallback_type = None fallback_loc = None return var_type, var_loc, fallback_type, fallback_loc def _tokenize_by_commas(string: str) -> Optional[List[str]]: """ Tokenize the given value by commas, respecting quoted blocks. """ if not string: return None quoted_comma_ranges = [range(m.start(0), m.end(0)) for m in QUOTED_WORD_SYNTAX.finditer(string)] def clean(s: str) -> str: s = s.strip() # whitespace if len(s) > 0 and s[0] == '"' and s[len(s) - 1] == '"': # surrounding quotes s = s[1:-1] if len(s) > 0 and s[0] == "'" and s[len(s) - 1] == "'":
return s block_start_index = 0 search_start_index = block_start_index tokens = [] index = string.find(",", search_start_index) while index > 0: is_quoted = False for quoted_comma_range in quoted_comma_ranges: if index in quoted_comma_range: is_quoted = True break if is_quoted: search_start_index = index + 1 else: tokens.append(clean(string[block_start_index:index])) block_start_index = index + 1 search_start_index = block_start_index index = string.find(",", search_start_index) if block_start_index < len(string): tokens.append(clean(string[block_start_index:])) return tokens
s = s[1:-1]
conditional_block
parser.py
from __future__ import annotations import json import os from pathlib import Path from typing import Tuple, Optional, List import jmespath import logging import re import yaml from yaml import YAMLError from checkov.cloudformation.parser import cfn_yaml from checkov.cloudformation.context_parser import ContextParser from checkov.cloudformation.parser.cfn_yaml import CfnParseError from checkov.common.models.consts import SLS_DEFAULT_VAR_PATTERN from checkov.common.parsers.node import DictNode, StrNode from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger logger = logging.getLogger(__name__) add_resource_code_filter_to_logger(logger) IAM_ROLE_STATEMENTS_TOKEN = 'iamRoleStatements' # nosec CFN_RESOURCES_TOKEN = 'resources' # nosec PROVIDER_TOKEN = 'provider' # nosec FUNCTIONS_TOKEN = 'functions' # nosec ENVIRONMENT_TOKEN = 'environment' # nosec STACK_TAGS_TOKEN = 'stackTags' # nosec TAGS_TOKEN = 'tags' # nosec SUPPORTED_PROVIDERS = ['aws'] QUOTED_WORD_SYNTAX = re.compile(r"(?:('|\").*?\1)") FILE_LOCATION_PATTERN = re.compile(r'^file\(([^?%*:|"<>]+?)\)') def parse(filename): template = None template_lines = None try: (template, template_lines) = cfn_yaml.load(filename, cfn_yaml.ContentType.SLS) if not template or not is_checked_sls_template(template): return except IOError as e: if e.errno == 2: logger.error('Template file not found: %s', filename) return elif e.errno == 21: logger.error('Template references a directory, not a file: %s', filename) return elif e.errno == 13: logger.error('Permission denied when accessing template file: %s', filename) return except UnicodeDecodeError: logger.error('Cannot read file contents: %s', filename) return except CfnParseError: logger.warning(f"Failed to parse file {filename} because it isn't a valid template") return except YAMLError: logger.warning(f"Failed to parse file {filename} as a yaml") return process_variables(template, filename) return template, template_lines def is_checked_sls_template(template): if template.__contains__('provider'): # Case provider is a dictionary if isinstance(template['provider'], DictNode): if template['provider'].get('name', '').lower() not in SUPPORTED_PROVIDERS: return False # Case provider is direct provider name if isinstance(template['provider'], StrNode): if template['provider'] not in SUPPORTED_PROVIDERS: return False return True return False def template_contains_cfn_resources(template): if template.__contains__(CFN_RESOURCES_TOKEN) and isinstance(template[CFN_RESOURCES_TOKEN], DictNode): if template[CFN_RESOURCES_TOKEN].get('Resources'): return True return False def template_contains_key(template, key): if ContextParser.search_deep_keys(key, template, []): return True return False def process_variables(template, filename): """ Modifies the template data in-place to resolve variables. """ file_data_cache = {} service_file_directory = os.path.dirname(filename) var_pattern = jmespath.search("provider.variableSyntax", template) if var_pattern is not None: # Remove to prevent self-matching during processing del template["provider"]["variableSyntax"] else: var_pattern = SLS_DEFAULT_VAR_PATTERN compiled_var_pattern = re.compile(var_pattern) # Processing is done in a loop to deal with chained references and the like. # Loop while the data is being changed, stop when no more changes are happening. # To ensure there's not some kind of oscillation, a cap of 25 passes is in place. # More than a couple loops isn't normally expected. # NOTE: If this approach proves to be a performance liability, a DAG will be needed. loop_count = 0 for _ in range(0, 25): loop_count += 1 made_change = False if process_variables_loop(template, compiled_var_pattern, # vt = var type # vl = var location # ft = fallback var type # fl = fallback var location lambda vt, vl, ft, fl: _load_var_data(vt, vl, ft, fl, file_data_cache, template, service_file_directory)): made_change = True if not made_change: break logger.debug("Processing of %s variables took %d loop iterations", filename, loop_count) return template def process_variables_loop(template, var_pattern, param_lookup_function): """ Generic processing loop for variables. :param template: The dictionary currently being processed. This function will be called recursively starting at dict provided. :param var_pattern: A compiled regex pattern which should name match groups if they are needed for looking up the data source. :param param_lookup_function: A Callable taking four arguments: 1) the type (e.g., "self", "file(/path/to/file.yml)") 2) the location (e.g., "custom.my_property") 3) fallback var type (same as above plus None for static value) 4) fallback var location or value if type was None """ # Generic loop for handling a source of key/value tuples (e.g., enumerate() or <dict>.items()) def process_items_helper(key_value_iterator, data_map): made_change = False for key, value in key_value_iterator: if isinstance(value, str): altered_value = value for match in var_pattern.finditer(value): var_type, var_loc, fallback_type, fallback_loc = _parse_var(match[1]) source_value = param_lookup_function(var_type, var_loc, fallback_type, fallback_loc) # If we can't find a value, skip it if source_value is None: continue try: if altered_value == match[0]: # complete replacement altered_value = source_value else: # partial replacement altered_value = altered_value.replace(match[0], source_value) except TypeError: pass if value != altered_value: data_map[key] = altered_value made_change = True elif isinstance(value, dict): if process_variables_loop(value, var_pattern, param_lookup_function): made_change = True elif isinstance(value, list): if process_items_helper(enumerate(value), value): made_change = True return made_change return process_items_helper(template.items(), template) def _load_var_data( var_type, var_location, fallback_var_type, fallback_var_location, file_cache, self_data_source, service_file_directory ): """ Load data based on the type/path (see param_lookup_function parameter of process_variables for more info). :param var_type: Either the type of the variable (see process_variables function) or None to indicate that var_location is a raw value. :param var_location: Either the location of the variable (see process_variables function) or a raw value if var_type is None :return None if the variable could not be resolved """ value = None if var_type is None: value = var_location elif var_type == "self": value = _determine_variable_value_from_dict(self_data_source, var_location, None) elif var_type == "env": value = _determine_variable_value_from_dict(os.environ, var_location, None) elif var_type.startswith("file("): match = FILE_LOCATION_PATTERN.match(var_type) if match is None: return None data_source = _load_file_data(match[1], file_cache, service_file_directory) value = _determine_variable_value_from_dict(data_source, var_location, None) if value is None and fallback_var_location is not None: return _load_var_data(fallback_var_type, fallback_var_location, None, None, file_cache, self_data_source, service_file_directory) return value def _determine_variable_value_from_dict(source_dict, location_str, default): if location_str is None: return source_dict if default is not None: default = default.strip() # NOTE: String must be quoted to avoid issues with dashes and other reserved # characters. If we just wrap the whole thing, dot separators won't work so: # split and join with individually wrapped tokens. # Original: foo.bar-baz # Wrapped: "foo"."bar-baz" location = ".".join([f'"{token}"' for token in location_str.split(".")]) source_value = jmespath.search(location, source_dict) if source_value is None: return default return source_value def _self_var_data_lookup(group_dict, template): location = group_dict["loc"] default = group_dict.get("default") return _determine_variable_value_from_dict(template, location, default) def
(file_location, file_data_cache, service_file_directory): file_location = file_location.replace("~", str(Path.home())) file_location = file_location if os.path.isabs(file_location) else \ os.path.join(service_file_directory, file_location) data = file_data_cache.get(file_location) if data is None: try: with open(file_location, "r") as f: if file_location.endswith(".json"): data = json.load(f) elif file_location.endswith(".yml") or file_location.endswith(".yaml"): data = yaml.safe_load(f) except Exception: data = {} file_data_cache[file_location] = data return data def _token_to_type_and_loc(token: str) -> Tuple[Optional[str], Optional[str]]: file_match = FILE_LOCATION_PATTERN.match(token) if file_match is not None: if ":" not in token: return file_match[0], None return file_match[0].strip(), token[len(file_match[0]) + 1 :].strip() # +1 for colon if ":" not in token: return None, token index = token.index(":") return token[:index].strip(), token[index + 1 :].strip() def _parse_var(var_str): """ Returns a tuple of the var type, var loc, fallback type and fallback loc. See docs for the param_lookup_function parameter of process_variables_loop for more info. """ tokens = _tokenize_by_commas(var_str.strip()) if not tokens: return None var_type, var_loc = _token_to_type_and_loc(tokens[0]) if len(tokens) > 1: fallback_type, fallback_loc = _token_to_type_and_loc(tokens[1]) else: fallback_type = None fallback_loc = None return var_type, var_loc, fallback_type, fallback_loc def _tokenize_by_commas(string: str) -> Optional[List[str]]: """ Tokenize the given value by commas, respecting quoted blocks. """ if not string: return None quoted_comma_ranges = [range(m.start(0), m.end(0)) for m in QUOTED_WORD_SYNTAX.finditer(string)] def clean(s: str) -> str: s = s.strip() # whitespace if len(s) > 0 and s[0] == '"' and s[len(s) - 1] == '"': # surrounding quotes s = s[1:-1] if len(s) > 0 and s[0] == "'" and s[len(s) - 1] == "'": s = s[1:-1] return s block_start_index = 0 search_start_index = block_start_index tokens = [] index = string.find(",", search_start_index) while index > 0: is_quoted = False for quoted_comma_range in quoted_comma_ranges: if index in quoted_comma_range: is_quoted = True break if is_quoted: search_start_index = index + 1 else: tokens.append(clean(string[block_start_index:index])) block_start_index = index + 1 search_start_index = block_start_index index = string.find(",", search_start_index) if block_start_index < len(string): tokens.append(clean(string[block_start_index:])) return tokens
_load_file_data
identifier_name
parser.py
from __future__ import annotations import json import os from pathlib import Path from typing import Tuple, Optional, List import jmespath import logging import re import yaml from yaml import YAMLError from checkov.cloudformation.parser import cfn_yaml from checkov.cloudformation.context_parser import ContextParser from checkov.cloudformation.parser.cfn_yaml import CfnParseError from checkov.common.models.consts import SLS_DEFAULT_VAR_PATTERN from checkov.common.parsers.node import DictNode, StrNode from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger logger = logging.getLogger(__name__) add_resource_code_filter_to_logger(logger) IAM_ROLE_STATEMENTS_TOKEN = 'iamRoleStatements' # nosec CFN_RESOURCES_TOKEN = 'resources' # nosec PROVIDER_TOKEN = 'provider' # nosec FUNCTIONS_TOKEN = 'functions' # nosec ENVIRONMENT_TOKEN = 'environment' # nosec STACK_TAGS_TOKEN = 'stackTags' # nosec TAGS_TOKEN = 'tags' # nosec SUPPORTED_PROVIDERS = ['aws'] QUOTED_WORD_SYNTAX = re.compile(r"(?:('|\").*?\1)") FILE_LOCATION_PATTERN = re.compile(r'^file\(([^?%*:|"<>]+?)\)') def parse(filename): template = None template_lines = None try: (template, template_lines) = cfn_yaml.load(filename, cfn_yaml.ContentType.SLS) if not template or not is_checked_sls_template(template): return except IOError as e: if e.errno == 2: logger.error('Template file not found: %s', filename) return elif e.errno == 21: logger.error('Template references a directory, not a file: %s', filename) return elif e.errno == 13: logger.error('Permission denied when accessing template file: %s', filename) return except UnicodeDecodeError: logger.error('Cannot read file contents: %s', filename) return except CfnParseError: logger.warning(f"Failed to parse file {filename} because it isn't a valid template") return except YAMLError: logger.warning(f"Failed to parse file {filename} as a yaml") return process_variables(template, filename) return template, template_lines def is_checked_sls_template(template): if template.__contains__('provider'): # Case provider is a dictionary if isinstance(template['provider'], DictNode): if template['provider'].get('name', '').lower() not in SUPPORTED_PROVIDERS: return False # Case provider is direct provider name if isinstance(template['provider'], StrNode): if template['provider'] not in SUPPORTED_PROVIDERS: return False return True return False def template_contains_cfn_resources(template): if template.__contains__(CFN_RESOURCES_TOKEN) and isinstance(template[CFN_RESOURCES_TOKEN], DictNode): if template[CFN_RESOURCES_TOKEN].get('Resources'): return True return False def template_contains_key(template, key): if ContextParser.search_deep_keys(key, template, []): return True return False def process_variables(template, filename):
def process_variables_loop(template, var_pattern, param_lookup_function): """ Generic processing loop for variables. :param template: The dictionary currently being processed. This function will be called recursively starting at dict provided. :param var_pattern: A compiled regex pattern which should name match groups if they are needed for looking up the data source. :param param_lookup_function: A Callable taking four arguments: 1) the type (e.g., "self", "file(/path/to/file.yml)") 2) the location (e.g., "custom.my_property") 3) fallback var type (same as above plus None for static value) 4) fallback var location or value if type was None """ # Generic loop for handling a source of key/value tuples (e.g., enumerate() or <dict>.items()) def process_items_helper(key_value_iterator, data_map): made_change = False for key, value in key_value_iterator: if isinstance(value, str): altered_value = value for match in var_pattern.finditer(value): var_type, var_loc, fallback_type, fallback_loc = _parse_var(match[1]) source_value = param_lookup_function(var_type, var_loc, fallback_type, fallback_loc) # If we can't find a value, skip it if source_value is None: continue try: if altered_value == match[0]: # complete replacement altered_value = source_value else: # partial replacement altered_value = altered_value.replace(match[0], source_value) except TypeError: pass if value != altered_value: data_map[key] = altered_value made_change = True elif isinstance(value, dict): if process_variables_loop(value, var_pattern, param_lookup_function): made_change = True elif isinstance(value, list): if process_items_helper(enumerate(value), value): made_change = True return made_change return process_items_helper(template.items(), template) def _load_var_data( var_type, var_location, fallback_var_type, fallback_var_location, file_cache, self_data_source, service_file_directory ): """ Load data based on the type/path (see param_lookup_function parameter of process_variables for more info). :param var_type: Either the type of the variable (see process_variables function) or None to indicate that var_location is a raw value. :param var_location: Either the location of the variable (see process_variables function) or a raw value if var_type is None :return None if the variable could not be resolved """ value = None if var_type is None: value = var_location elif var_type == "self": value = _determine_variable_value_from_dict(self_data_source, var_location, None) elif var_type == "env": value = _determine_variable_value_from_dict(os.environ, var_location, None) elif var_type.startswith("file("): match = FILE_LOCATION_PATTERN.match(var_type) if match is None: return None data_source = _load_file_data(match[1], file_cache, service_file_directory) value = _determine_variable_value_from_dict(data_source, var_location, None) if value is None and fallback_var_location is not None: return _load_var_data(fallback_var_type, fallback_var_location, None, None, file_cache, self_data_source, service_file_directory) return value def _determine_variable_value_from_dict(source_dict, location_str, default): if location_str is None: return source_dict if default is not None: default = default.strip() # NOTE: String must be quoted to avoid issues with dashes and other reserved # characters. If we just wrap the whole thing, dot separators won't work so: # split and join with individually wrapped tokens. # Original: foo.bar-baz # Wrapped: "foo"."bar-baz" location = ".".join([f'"{token}"' for token in location_str.split(".")]) source_value = jmespath.search(location, source_dict) if source_value is None: return default return source_value def _self_var_data_lookup(group_dict, template): location = group_dict["loc"] default = group_dict.get("default") return _determine_variable_value_from_dict(template, location, default) def _load_file_data(file_location, file_data_cache, service_file_directory): file_location = file_location.replace("~", str(Path.home())) file_location = file_location if os.path.isabs(file_location) else \ os.path.join(service_file_directory, file_location) data = file_data_cache.get(file_location) if data is None: try: with open(file_location, "r") as f: if file_location.endswith(".json"): data = json.load(f) elif file_location.endswith(".yml") or file_location.endswith(".yaml"): data = yaml.safe_load(f) except Exception: data = {} file_data_cache[file_location] = data return data def _token_to_type_and_loc(token: str) -> Tuple[Optional[str], Optional[str]]: file_match = FILE_LOCATION_PATTERN.match(token) if file_match is not None: if ":" not in token: return file_match[0], None return file_match[0].strip(), token[len(file_match[0]) + 1 :].strip() # +1 for colon if ":" not in token: return None, token index = token.index(":") return token[:index].strip(), token[index + 1 :].strip() def _parse_var(var_str): """ Returns a tuple of the var type, var loc, fallback type and fallback loc. See docs for the param_lookup_function parameter of process_variables_loop for more info. """ tokens = _tokenize_by_commas(var_str.strip()) if not tokens: return None var_type, var_loc = _token_to_type_and_loc(tokens[0]) if len(tokens) > 1: fallback_type, fallback_loc = _token_to_type_and_loc(tokens[1]) else: fallback_type = None fallback_loc = None return var_type, var_loc, fallback_type, fallback_loc def _tokenize_by_commas(string: str) -> Optional[List[str]]: """ Tokenize the given value by commas, respecting quoted blocks. """ if not string: return None quoted_comma_ranges = [range(m.start(0), m.end(0)) for m in QUOTED_WORD_SYNTAX.finditer(string)] def clean(s: str) -> str: s = s.strip() # whitespace if len(s) > 0 and s[0] == '"' and s[len(s) - 1] == '"': # surrounding quotes s = s[1:-1] if len(s) > 0 and s[0] == "'" and s[len(s) - 1] == "'": s = s[1:-1] return s block_start_index = 0 search_start_index = block_start_index tokens = [] index = string.find(",", search_start_index) while index > 0: is_quoted = False for quoted_comma_range in quoted_comma_ranges: if index in quoted_comma_range: is_quoted = True break if is_quoted: search_start_index = index + 1 else: tokens.append(clean(string[block_start_index:index])) block_start_index = index + 1 search_start_index = block_start_index index = string.find(",", search_start_index) if block_start_index < len(string): tokens.append(clean(string[block_start_index:])) return tokens
""" Modifies the template data in-place to resolve variables. """ file_data_cache = {} service_file_directory = os.path.dirname(filename) var_pattern = jmespath.search("provider.variableSyntax", template) if var_pattern is not None: # Remove to prevent self-matching during processing del template["provider"]["variableSyntax"] else: var_pattern = SLS_DEFAULT_VAR_PATTERN compiled_var_pattern = re.compile(var_pattern) # Processing is done in a loop to deal with chained references and the like. # Loop while the data is being changed, stop when no more changes are happening. # To ensure there's not some kind of oscillation, a cap of 25 passes is in place. # More than a couple loops isn't normally expected. # NOTE: If this approach proves to be a performance liability, a DAG will be needed. loop_count = 0 for _ in range(0, 25): loop_count += 1 made_change = False if process_variables_loop(template, compiled_var_pattern, # vt = var type # vl = var location # ft = fallback var type # fl = fallback var location lambda vt, vl, ft, fl: _load_var_data(vt, vl, ft, fl, file_data_cache, template, service_file_directory)): made_change = True if not made_change: break logger.debug("Processing of %s variables took %d loop iterations", filename, loop_count) return template
identifier_body
parser.py
from __future__ import annotations import json import os from pathlib import Path from typing import Tuple, Optional, List import jmespath import logging import re import yaml from yaml import YAMLError from checkov.cloudformation.parser import cfn_yaml from checkov.cloudformation.context_parser import ContextParser from checkov.cloudformation.parser.cfn_yaml import CfnParseError from checkov.common.models.consts import SLS_DEFAULT_VAR_PATTERN from checkov.common.parsers.node import DictNode, StrNode from checkov.common.resource_code_logger_filter import add_resource_code_filter_to_logger logger = logging.getLogger(__name__) add_resource_code_filter_to_logger(logger) IAM_ROLE_STATEMENTS_TOKEN = 'iamRoleStatements' # nosec CFN_RESOURCES_TOKEN = 'resources' # nosec PROVIDER_TOKEN = 'provider' # nosec FUNCTIONS_TOKEN = 'functions' # nosec ENVIRONMENT_TOKEN = 'environment' # nosec STACK_TAGS_TOKEN = 'stackTags' # nosec TAGS_TOKEN = 'tags' # nosec SUPPORTED_PROVIDERS = ['aws'] QUOTED_WORD_SYNTAX = re.compile(r"(?:('|\").*?\1)") FILE_LOCATION_PATTERN = re.compile(r'^file\(([^?%*:|"<>]+?)\)') def parse(filename): template = None template_lines = None try: (template, template_lines) = cfn_yaml.load(filename, cfn_yaml.ContentType.SLS) if not template or not is_checked_sls_template(template): return except IOError as e: if e.errno == 2: logger.error('Template file not found: %s', filename) return elif e.errno == 21: logger.error('Template references a directory, not a file: %s', filename) return elif e.errno == 13: logger.error('Permission denied when accessing template file: %s', filename) return except UnicodeDecodeError: logger.error('Cannot read file contents: %s', filename) return except CfnParseError: logger.warning(f"Failed to parse file {filename} because it isn't a valid template") return except YAMLError: logger.warning(f"Failed to parse file {filename} as a yaml") return process_variables(template, filename) return template, template_lines def is_checked_sls_template(template): if template.__contains__('provider'): # Case provider is a dictionary if isinstance(template['provider'], DictNode): if template['provider'].get('name', '').lower() not in SUPPORTED_PROVIDERS: return False # Case provider is direct provider name if isinstance(template['provider'], StrNode): if template['provider'] not in SUPPORTED_PROVIDERS: return False return True return False def template_contains_cfn_resources(template): if template.__contains__(CFN_RESOURCES_TOKEN) and isinstance(template[CFN_RESOURCES_TOKEN], DictNode): if template[CFN_RESOURCES_TOKEN].get('Resources'): return True return False def template_contains_key(template, key): if ContextParser.search_deep_keys(key, template, []): return True return False def process_variables(template, filename): """ Modifies the template data in-place to resolve variables. """ file_data_cache = {} service_file_directory = os.path.dirname(filename) var_pattern = jmespath.search("provider.variableSyntax", template) if var_pattern is not None: # Remove to prevent self-matching during processing del template["provider"]["variableSyntax"] else: var_pattern = SLS_DEFAULT_VAR_PATTERN compiled_var_pattern = re.compile(var_pattern) # Processing is done in a loop to deal with chained references and the like. # Loop while the data is being changed, stop when no more changes are happening. # To ensure there's not some kind of oscillation, a cap of 25 passes is in place. # More than a couple loops isn't normally expected. # NOTE: If this approach proves to be a performance liability, a DAG will be needed. loop_count = 0 for _ in range(0, 25): loop_count += 1 made_change = False if process_variables_loop(template, compiled_var_pattern, # vt = var type # vl = var location # ft = fallback var type # fl = fallback var location lambda vt, vl, ft, fl: _load_var_data(vt, vl, ft, fl, file_data_cache, template, service_file_directory)): made_change = True if not made_change: break logger.debug("Processing of %s variables took %d loop iterations", filename, loop_count) return template def process_variables_loop(template, var_pattern, param_lookup_function): """ Generic processing loop for variables. :param template: The dictionary currently being processed. This function will be called recursively starting at dict provided. :param var_pattern: A compiled regex pattern which should name match groups if they are needed for looking up the data source. :param param_lookup_function: A Callable taking four arguments: 1) the type (e.g., "self", "file(/path/to/file.yml)") 2) the location (e.g., "custom.my_property") 3) fallback var type (same as above plus None for static value) 4) fallback var location or value if type was None """ # Generic loop for handling a source of key/value tuples (e.g., enumerate() or <dict>.items()) def process_items_helper(key_value_iterator, data_map): made_change = False for key, value in key_value_iterator: if isinstance(value, str): altered_value = value for match in var_pattern.finditer(value): var_type, var_loc, fallback_type, fallback_loc = _parse_var(match[1]) source_value = param_lookup_function(var_type, var_loc, fallback_type, fallback_loc) # If we can't find a value, skip it if source_value is None: continue try: if altered_value == match[0]: # complete replacement altered_value = source_value else: # partial replacement altered_value = altered_value.replace(match[0], source_value) except TypeError: pass if value != altered_value: data_map[key] = altered_value made_change = True elif isinstance(value, dict): if process_variables_loop(value, var_pattern, param_lookup_function): made_change = True elif isinstance(value, list): if process_items_helper(enumerate(value), value): made_change = True return made_change return process_items_helper(template.items(), template) def _load_var_data( var_type, var_location, fallback_var_type, fallback_var_location, file_cache, self_data_source, service_file_directory ): """ Load data based on the type/path (see param_lookup_function parameter of process_variables for more info). :param var_type: Either the type of the variable (see process_variables function) or None to indicate that var_location is a raw value. :param var_location: Either the location of the variable (see process_variables function) or a raw value if var_type is None :return None if the variable could not be resolved """ value = None if var_type is None: value = var_location elif var_type == "self": value = _determine_variable_value_from_dict(self_data_source, var_location, None) elif var_type == "env": value = _determine_variable_value_from_dict(os.environ, var_location, None) elif var_type.startswith("file("): match = FILE_LOCATION_PATTERN.match(var_type) if match is None: return None data_source = _load_file_data(match[1], file_cache, service_file_directory) value = _determine_variable_value_from_dict(data_source, var_location, None) if value is None and fallback_var_location is not None: return _load_var_data(fallback_var_type, fallback_var_location, None, None, file_cache, self_data_source, service_file_directory) return value def _determine_variable_value_from_dict(source_dict, location_str, default): if location_str is None: return source_dict if default is not None: default = default.strip() # NOTE: String must be quoted to avoid issues with dashes and other reserved # characters. If we just wrap the whole thing, dot separators won't work so: # split and join with individually wrapped tokens. # Original: foo.bar-baz # Wrapped: "foo"."bar-baz" location = ".".join([f'"{token}"' for token in location_str.split(".")]) source_value = jmespath.search(location, source_dict) if source_value is None: return default return source_value def _self_var_data_lookup(group_dict, template): location = group_dict["loc"] default = group_dict.get("default") return _determine_variable_value_from_dict(template, location, default) def _load_file_data(file_location, file_data_cache, service_file_directory): file_location = file_location.replace("~", str(Path.home())) file_location = file_location if os.path.isabs(file_location) else \ os.path.join(service_file_directory, file_location) data = file_data_cache.get(file_location) if data is None: try: with open(file_location, "r") as f: if file_location.endswith(".json"): data = json.load(f) elif file_location.endswith(".yml") or file_location.endswith(".yaml"): data = yaml.safe_load(f) except Exception: data = {} file_data_cache[file_location] = data return data def _token_to_type_and_loc(token: str) -> Tuple[Optional[str], Optional[str]]: file_match = FILE_LOCATION_PATTERN.match(token) if file_match is not None: if ":" not in token: return file_match[0], None return file_match[0].strip(), token[len(file_match[0]) + 1 :].strip() # +1 for colon if ":" not in token: return None, token index = token.index(":") return token[:index].strip(), token[index + 1 :].strip() def _parse_var(var_str): """ Returns a tuple of the var type, var loc, fallback type and fallback loc. See docs for the param_lookup_function parameter of process_variables_loop for more info. """ tokens = _tokenize_by_commas(var_str.strip()) if not tokens: return None var_type, var_loc = _token_to_type_and_loc(tokens[0]) if len(tokens) > 1: fallback_type, fallback_loc = _token_to_type_and_loc(tokens[1]) else: fallback_type = None fallback_loc = None return var_type, var_loc, fallback_type, fallback_loc def _tokenize_by_commas(string: str) -> Optional[List[str]]: """ Tokenize the given value by commas, respecting quoted blocks. """ if not string: return None quoted_comma_ranges = [range(m.start(0), m.end(0)) for m in QUOTED_WORD_SYNTAX.finditer(string)] def clean(s: str) -> str: s = s.strip() # whitespace if len(s) > 0 and s[0] == '"' and s[len(s) - 1] == '"': # surrounding quotes s = s[1:-1] if len(s) > 0 and s[0] == "'" and s[len(s) - 1] == "'": s = s[1:-1] return s block_start_index = 0 search_start_index = block_start_index tokens = [] index = string.find(",", search_start_index) while index > 0: is_quoted = False for quoted_comma_range in quoted_comma_ranges: if index in quoted_comma_range: is_quoted = True break if is_quoted: search_start_index = index + 1 else: tokens.append(clean(string[block_start_index:index])) block_start_index = index + 1 search_start_index = block_start_index index = string.find(",", search_start_index)
tokens.append(clean(string[block_start_index:])) return tokens
if block_start_index < len(string):
random_line_split
context_test.go
// Copyright 2014 The Cockroach Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // // Author: Spencer Kimball (spencer.kimball@gmail.com) package rpc import ( "net" "sync" "sync/atomic" "testing" "time" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "github.com/cockroachdb/cockroach/testutils" "github.com/cockroachdb/cockroach/util" "github.com/cockroachdb/cockroach/util/hlc" "github.com/cockroachdb/cockroach/util/leaktest" "github.com/cockroachdb/cockroach/util/netutil" "github.com/cockroachdb/cockroach/util/stop" "github.com/cockroachdb/cockroach/util/syncutil" "github.com/pkg/errors" circuit "github.com/rubyist/circuitbreaker" ) func newTestServer(t *testing.T, ctx *Context, manual bool) (*grpc.Server, net.Listener) { tlsConfig, err := ctx.GetServerTLSConfig() if err != nil { t.Fatal(err) } s := grpc.NewServer(grpc.Creds(credentials.NewTLS(tlsConfig))) ln, err := netutil.ListenAndServeGRPC(ctx.Stopper, s, util.TestAddr) if err != nil { t.Fatal(err) } return s, ln } func TestHeartbeatCB(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() serverClock := hlc.NewClock(time.Unix(0, 20).UnixNano) serverCtx := newNodeTestContext(serverClock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() RegisterHeartbeatServer(s, &HeartbeatService{ clock: serverClock, remoteClockMonitor: serverCtx.RemoteClocks, }) // Clocks don't matter in this test. clientCtx := newNodeTestContext(serverClock, stopper) var once sync.Once ch := make(chan struct{}) clientCtx.HeartbeatCB = func() { once.Do(func() { close(ch) }) } _, err := clientCtx.GRPCDial(remoteAddr) if err != nil { t.Fatal(err) } <-ch } // TestHeartbeatHealth verifies that the health status changes after heartbeats // succeed or fail. func TestHeartbeatHealth(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() // Can't be zero because that'd be an empty offset. clock := hlc.NewClock(time.Unix(0, 1).UnixNano) serverCtx := newNodeTestContext(clock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() heartbeat := &ManualHeartbeatService{ ready: make(chan struct{}), stopper: stopper, clock: clock, remoteClockMonitor: serverCtx.RemoteClocks, } RegisterHeartbeatServer(s, heartbeat) clientCtx := newNodeTestContext(clock, stopper) // Make the intervals and timeouts shorter to speed up the tests. clientCtx.HeartbeatInterval = 1 * time.Millisecond clientCtx.HeartbeatTimeout = 1 * time.Millisecond if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } // This code is inherently racy so when we need to verify heartbeats we want // them to always succeed. sendHeartbeats := func() func() { done := make(chan struct{}) go func() { for { select { case <-done: return case heartbeat.ready <- struct{}{}: } } }() return func() { done <- struct{}{} } } // Should be healthy after the first successful heartbeat. stopHeartbeats := sendHeartbeats() util.SucceedsSoon(t, func() error { if !clientCtx.IsConnHealthy(remoteAddr) { return errors.Errorf("expected %s to be healthy", remoteAddr) } return nil }) stopHeartbeats() // Should no longer be healthy after heartbeating stops. util.SucceedsSoon(t, func() error { if clientCtx.IsConnHealthy(remoteAddr) { return errors.Errorf("expected %s to be unhealthy", remoteAddr) } return nil }) // Should return to healthy after another successful heartbeat. stopHeartbeats = sendHeartbeats() util.SucceedsSoon(t, func() error { if !clientCtx.IsConnHealthy(remoteAddr) { return errors.Errorf("expected %s to be healthy", remoteAddr) } return nil }) stopHeartbeats() if clientCtx.IsConnHealthy("non-existent connection") { t.Errorf("non-existent connection is reported as healthy") } } func TestOffsetMeasurement(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() serverTime := time.Unix(0, 20) serverClock := hlc.NewClock(serverTime.UnixNano) serverCtx := newNodeTestContext(serverClock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() RegisterHeartbeatServer(s, &HeartbeatService{ clock: serverClock, remoteClockMonitor: serverCtx.RemoteClocks, }) // Create a client clock that is behind the server clock. clientAdvancing := AdvancingClock{time: time.Unix(0, 10)} clientClock := hlc.NewClock(clientAdvancing.UnixNano) clientClock.SetMaxOffset(time.Millisecond) clientCtx := newNodeTestContext(clientClock, stopper) clientCtx.RemoteClocks.offsetTTL = 5 * clientAdvancing.getAdvancementInterval() if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } expectedOffset := RemoteOffset{Offset: 10, Uncertainty: 0, MeasuredAt: 10} util.SucceedsSoon(t, func() error { clientCtx.RemoteClocks.mu.Lock() defer clientCtx.RemoteClocks.mu.Unlock() if o, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; !ok { return errors.Errorf("expected offset of %s to be initialized, but it was not", remoteAddr) } else if o != expectedOffset { return errors.Errorf("expected:\n%v\nactual:\n%v", expectedOffset, o) } return nil }) // Change the client such that it receives a heartbeat right after the // maximum clock reading delay. clientAdvancing.setAdvancementInterval( maximumPingDurationMult*clientClock.MaxOffset() + 1*time.Nanosecond) util.SucceedsSoon(t, func() error { clientCtx.RemoteClocks.mu.Lock() defer clientCtx.RemoteClocks.mu.Unlock() if o, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; ok { return errors.Errorf("expected offset to have been cleared, but found %s", o) } return nil }) } func TestFailedOffsetMeasurement(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() // Can't be zero because that'd be an empty offset. clock := hlc.NewClock(time.Unix(0, 1).UnixNano) serverCtx := newNodeTestContext(clock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() heartbeat := &ManualHeartbeatService{ clock: clock, remoteClockMonitor: serverCtx.RemoteClocks, ready: make(chan struct{}), stopper: stopper, } RegisterHeartbeatServer(s, heartbeat) // Create a client that never receives a heartbeat after the first. clientCtx := newNodeTestContext(clock, stopper) // Increase the timeout so that failure arises from exceeding the maximum // clock reading delay, not the timeout. clientCtx.HeartbeatTimeout = 20 * clientCtx.HeartbeatInterval if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } heartbeat.ready <- struct{}{} // Allow one heartbeat for initialization. util.SucceedsSoon(t, func() error { clientCtx.RemoteClocks.mu.Lock() defer clientCtx.RemoteClocks.mu.Unlock() if _, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; !ok { return errors.Errorf("expected offset of %s to be initialized, but it was not", remoteAddr) } return nil }) util.SucceedsSoon(t, func() error { serverCtx.RemoteClocks.mu.Lock() defer serverCtx.RemoteClocks.mu.Unlock() if o, ok := serverCtx.RemoteClocks.mu.offsets[remoteAddr]; ok { return errors.Errorf("expected offset of %s to not be initialized, but it was: %v", remoteAddr, o) } return nil }) } type AdvancingClock struct { syncutil.Mutex time time.Time advancementInterval atomic.Value // time.Duration } func (ac *AdvancingClock) setAdvancementInterval(d time.Duration) { ac.advancementInterval.Store(d) } func (ac *AdvancingClock) getAdvancementInterval() time.Duration { v := ac.advancementInterval.Load() if v == nil { return 0 } return v.(time.Duration) } func (ac *AdvancingClock) UnixNano() int64 { ac.Lock() time := ac.time ac.time = time.Add(ac.getAdvancementInterval()) ac.Unlock() return time.UnixNano() } func TestRemoteOffsetUnhealthy(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() const maxOffset = 100 * time.Millisecond type nodeContext struct { offset time.Duration ctx *Context errChan chan error } start := time.Date(2012, 12, 07, 0, 0, 0, 0, time.UTC) offsetClock := func(offset time.Duration) *hlc.Clock { return hlc.NewClock(func() int64 { return start.Add(offset).UnixNano() }) } nodeCtxs := []nodeContext{ {offset: 0}, {offset: 0}, {offset: 0}, // The minimum offset that actually triggers node death. {offset: maxOffset + 1}, } for i := range nodeCtxs { clock := offsetClock(nodeCtxs[i].offset) nodeCtxs[i].errChan = make(chan error, 1) clock.SetMaxOffset(maxOffset) nodeCtxs[i].ctx = newNodeTestContext(clock, stopper) nodeCtxs[i].ctx.HeartbeatInterval = maxOffset s, ln := newTestServer(t, nodeCtxs[i].ctx, true) RegisterHeartbeatServer(s, &HeartbeatService{ clock: clock, remoteClockMonitor: nodeCtxs[i].ctx.RemoteClocks, }) nodeCtxs[i].ctx.Addr = ln.Addr().String() } // Fully connect the nodes. for i, clientNodeContext := range nodeCtxs { for j, serverNodeContext := range nodeCtxs { if i == j { continue } if _, err := clientNodeContext.ctx.GRPCDial(serverNodeContext.ctx.Addr); err != nil { t.Fatal(err) } } } // Wait until all nodes are connected to all other nodes. for _, nodeCtx := range nodeCtxs { util.SucceedsSoon(t, func() error { nodeCtx.ctx.RemoteClocks.mu.Lock() defer nodeCtx.ctx.RemoteClocks.mu.Unlock() if a, e := len(nodeCtx.ctx.RemoteClocks.mu.offsets), len(nodeCtxs)-1; a != e { return errors.Errorf("not yet fully connected: have %d of %d connections: %v", a, e, nodeCtx.ctx.RemoteClocks.mu.offsets) } return nil }) } for i, nodeCtx := range nodeCtxs { if nodeOffset := nodeCtx.offset; nodeOffset > maxOffset { if err := nodeCtx.ctx.RemoteClocks.VerifyClockOffset(); testutils.IsError(err, errOffsetGreaterThanMaxOffset) { t.Logf("max offset: %s - node %d with excessive clock offset of %s returned expected error: %s", maxOffset, i, nodeOffset, err) } else { t.Errorf("max offset: %s - node %d with excessive clock offset of %s returned unexpected error: %s", maxOffset, i, nodeOffset, err) } } else { if err := nodeCtx.ctx.RemoteClocks.VerifyClockOffset(); err != nil { t.Errorf("max offset: %s - node %d with acceptable clock offset of %s returned unexpected error: %s", maxOffset, i, nodeOffset, err) } else { t.Logf("max offset: %s - node %d with acceptable clock offset of %s did not return an error, as expected", maxOffset, i, nodeOffset) } } } } func TestCircuitBreaker(t *testing.T)
{ defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() clock := hlc.NewClock(time.Unix(0, 1).UnixNano) serverCtx := newNodeTestContext(clock, stopper) _, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() clientCtx := newNodeTestContext(clock, stopper) // The first dial will succeed because the breaker is closed. if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } // Wait until the breaker opens. This will occur when the heartbeat fails // (because there is no heartbeat service). util.SucceedsSoon(t, func() error { _, err := clientCtx.GRPCDial(remoteAddr) if err == circuit.ErrBreakerOpen { return nil } return errors.Errorf("breaker not open: %v", err) }) // Reset the breaker. The next dial will succeed. clientCtx.conns.Lock() clientCtx.conns.breakers[remoteAddr].Reset() clientCtx.conns.Unlock() if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } }
identifier_body
context_test.go
// Copyright 2014 The Cockroach Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // // Author: Spencer Kimball (spencer.kimball@gmail.com) package rpc import ( "net" "sync" "sync/atomic" "testing" "time" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "github.com/cockroachdb/cockroach/testutils" "github.com/cockroachdb/cockroach/util" "github.com/cockroachdb/cockroach/util/hlc" "github.com/cockroachdb/cockroach/util/leaktest" "github.com/cockroachdb/cockroach/util/netutil" "github.com/cockroachdb/cockroach/util/stop" "github.com/cockroachdb/cockroach/util/syncutil" "github.com/pkg/errors" circuit "github.com/rubyist/circuitbreaker" ) func newTestServer(t *testing.T, ctx *Context, manual bool) (*grpc.Server, net.Listener) { tlsConfig, err := ctx.GetServerTLSConfig() if err != nil { t.Fatal(err) } s := grpc.NewServer(grpc.Creds(credentials.NewTLS(tlsConfig))) ln, err := netutil.ListenAndServeGRPC(ctx.Stopper, s, util.TestAddr) if err != nil { t.Fatal(err) } return s, ln } func TestHeartbeatCB(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() serverClock := hlc.NewClock(time.Unix(0, 20).UnixNano) serverCtx := newNodeTestContext(serverClock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() RegisterHeartbeatServer(s, &HeartbeatService{ clock: serverClock, remoteClockMonitor: serverCtx.RemoteClocks, }) // Clocks don't matter in this test. clientCtx := newNodeTestContext(serverClock, stopper) var once sync.Once ch := make(chan struct{}) clientCtx.HeartbeatCB = func() { once.Do(func() { close(ch) }) } _, err := clientCtx.GRPCDial(remoteAddr) if err != nil { t.Fatal(err) } <-ch } // TestHeartbeatHealth verifies that the health status changes after heartbeats // succeed or fail. func TestHeartbeatHealth(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() // Can't be zero because that'd be an empty offset. clock := hlc.NewClock(time.Unix(0, 1).UnixNano) serverCtx := newNodeTestContext(clock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() heartbeat := &ManualHeartbeatService{ ready: make(chan struct{}), stopper: stopper, clock: clock, remoteClockMonitor: serverCtx.RemoteClocks, } RegisterHeartbeatServer(s, heartbeat) clientCtx := newNodeTestContext(clock, stopper) // Make the intervals and timeouts shorter to speed up the tests. clientCtx.HeartbeatInterval = 1 * time.Millisecond clientCtx.HeartbeatTimeout = 1 * time.Millisecond if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } // This code is inherently racy so when we need to verify heartbeats we want // them to always succeed. sendHeartbeats := func() func() { done := make(chan struct{}) go func() { for { select { case <-done: return case heartbeat.ready <- struct{}{}: } } }() return func() { done <- struct{}{} } } // Should be healthy after the first successful heartbeat. stopHeartbeats := sendHeartbeats() util.SucceedsSoon(t, func() error { if !clientCtx.IsConnHealthy(remoteAddr) { return errors.Errorf("expected %s to be healthy", remoteAddr) } return nil }) stopHeartbeats() // Should no longer be healthy after heartbeating stops. util.SucceedsSoon(t, func() error { if clientCtx.IsConnHealthy(remoteAddr) { return errors.Errorf("expected %s to be unhealthy", remoteAddr) } return nil }) // Should return to healthy after another successful heartbeat. stopHeartbeats = sendHeartbeats() util.SucceedsSoon(t, func() error { if !clientCtx.IsConnHealthy(remoteAddr) { return errors.Errorf("expected %s to be healthy", remoteAddr) } return nil }) stopHeartbeats() if clientCtx.IsConnHealthy("non-existent connection") { t.Errorf("non-existent connection is reported as healthy") } } func TestOffsetMeasurement(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() serverTime := time.Unix(0, 20) serverClock := hlc.NewClock(serverTime.UnixNano) serverCtx := newNodeTestContext(serverClock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() RegisterHeartbeatServer(s, &HeartbeatService{ clock: serverClock, remoteClockMonitor: serverCtx.RemoteClocks, }) // Create a client clock that is behind the server clock. clientAdvancing := AdvancingClock{time: time.Unix(0, 10)} clientClock := hlc.NewClock(clientAdvancing.UnixNano) clientClock.SetMaxOffset(time.Millisecond) clientCtx := newNodeTestContext(clientClock, stopper) clientCtx.RemoteClocks.offsetTTL = 5 * clientAdvancing.getAdvancementInterval() if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } expectedOffset := RemoteOffset{Offset: 10, Uncertainty: 0, MeasuredAt: 10} util.SucceedsSoon(t, func() error { clientCtx.RemoteClocks.mu.Lock() defer clientCtx.RemoteClocks.mu.Unlock() if o, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; !ok { return errors.Errorf("expected offset of %s to be initialized, but it was not", remoteAddr) } else if o != expectedOffset { return errors.Errorf("expected:\n%v\nactual:\n%v", expectedOffset, o) } return nil }) // Change the client such that it receives a heartbeat right after the // maximum clock reading delay. clientAdvancing.setAdvancementInterval( maximumPingDurationMult*clientClock.MaxOffset() + 1*time.Nanosecond) util.SucceedsSoon(t, func() error { clientCtx.RemoteClocks.mu.Lock() defer clientCtx.RemoteClocks.mu.Unlock() if o, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; ok { return errors.Errorf("expected offset to have been cleared, but found %s", o) } return nil }) } func TestFailedOffsetMeasurement(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() // Can't be zero because that'd be an empty offset. clock := hlc.NewClock(time.Unix(0, 1).UnixNano) serverCtx := newNodeTestContext(clock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() heartbeat := &ManualHeartbeatService{ clock: clock, remoteClockMonitor: serverCtx.RemoteClocks, ready: make(chan struct{}), stopper: stopper, } RegisterHeartbeatServer(s, heartbeat) // Create a client that never receives a heartbeat after the first. clientCtx := newNodeTestContext(clock, stopper) // Increase the timeout so that failure arises from exceeding the maximum // clock reading delay, not the timeout. clientCtx.HeartbeatTimeout = 20 * clientCtx.HeartbeatInterval if _, err := clientCtx.GRPCDial(remoteAddr); err != nil
heartbeat.ready <- struct{}{} // Allow one heartbeat for initialization. util.SucceedsSoon(t, func() error { clientCtx.RemoteClocks.mu.Lock() defer clientCtx.RemoteClocks.mu.Unlock() if _, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; !ok { return errors.Errorf("expected offset of %s to be initialized, but it was not", remoteAddr) } return nil }) util.SucceedsSoon(t, func() error { serverCtx.RemoteClocks.mu.Lock() defer serverCtx.RemoteClocks.mu.Unlock() if o, ok := serverCtx.RemoteClocks.mu.offsets[remoteAddr]; ok { return errors.Errorf("expected offset of %s to not be initialized, but it was: %v", remoteAddr, o) } return nil }) } type AdvancingClock struct { syncutil.Mutex time time.Time advancementInterval atomic.Value // time.Duration } func (ac *AdvancingClock) setAdvancementInterval(d time.Duration) { ac.advancementInterval.Store(d) } func (ac *AdvancingClock) getAdvancementInterval() time.Duration { v := ac.advancementInterval.Load() if v == nil { return 0 } return v.(time.Duration) } func (ac *AdvancingClock) UnixNano() int64 { ac.Lock() time := ac.time ac.time = time.Add(ac.getAdvancementInterval()) ac.Unlock() return time.UnixNano() } func TestRemoteOffsetUnhealthy(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() const maxOffset = 100 * time.Millisecond type nodeContext struct { offset time.Duration ctx *Context errChan chan error } start := time.Date(2012, 12, 07, 0, 0, 0, 0, time.UTC) offsetClock := func(offset time.Duration) *hlc.Clock { return hlc.NewClock(func() int64 { return start.Add(offset).UnixNano() }) } nodeCtxs := []nodeContext{ {offset: 0}, {offset: 0}, {offset: 0}, // The minimum offset that actually triggers node death. {offset: maxOffset + 1}, } for i := range nodeCtxs { clock := offsetClock(nodeCtxs[i].offset) nodeCtxs[i].errChan = make(chan error, 1) clock.SetMaxOffset(maxOffset) nodeCtxs[i].ctx = newNodeTestContext(clock, stopper) nodeCtxs[i].ctx.HeartbeatInterval = maxOffset s, ln := newTestServer(t, nodeCtxs[i].ctx, true) RegisterHeartbeatServer(s, &HeartbeatService{ clock: clock, remoteClockMonitor: nodeCtxs[i].ctx.RemoteClocks, }) nodeCtxs[i].ctx.Addr = ln.Addr().String() } // Fully connect the nodes. for i, clientNodeContext := range nodeCtxs { for j, serverNodeContext := range nodeCtxs { if i == j { continue } if _, err := clientNodeContext.ctx.GRPCDial(serverNodeContext.ctx.Addr); err != nil { t.Fatal(err) } } } // Wait until all nodes are connected to all other nodes. for _, nodeCtx := range nodeCtxs { util.SucceedsSoon(t, func() error { nodeCtx.ctx.RemoteClocks.mu.Lock() defer nodeCtx.ctx.RemoteClocks.mu.Unlock() if a, e := len(nodeCtx.ctx.RemoteClocks.mu.offsets), len(nodeCtxs)-1; a != e { return errors.Errorf("not yet fully connected: have %d of %d connections: %v", a, e, nodeCtx.ctx.RemoteClocks.mu.offsets) } return nil }) } for i, nodeCtx := range nodeCtxs { if nodeOffset := nodeCtx.offset; nodeOffset > maxOffset { if err := nodeCtx.ctx.RemoteClocks.VerifyClockOffset(); testutils.IsError(err, errOffsetGreaterThanMaxOffset) { t.Logf("max offset: %s - node %d with excessive clock offset of %s returned expected error: %s", maxOffset, i, nodeOffset, err) } else { t.Errorf("max offset: %s - node %d with excessive clock offset of %s returned unexpected error: %s", maxOffset, i, nodeOffset, err) } } else { if err := nodeCtx.ctx.RemoteClocks.VerifyClockOffset(); err != nil { t.Errorf("max offset: %s - node %d with acceptable clock offset of %s returned unexpected error: %s", maxOffset, i, nodeOffset, err) } else { t.Logf("max offset: %s - node %d with acceptable clock offset of %s did not return an error, as expected", maxOffset, i, nodeOffset) } } } } func TestCircuitBreaker(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() clock := hlc.NewClock(time.Unix(0, 1).UnixNano) serverCtx := newNodeTestContext(clock, stopper) _, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() clientCtx := newNodeTestContext(clock, stopper) // The first dial will succeed because the breaker is closed. if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } // Wait until the breaker opens. This will occur when the heartbeat fails // (because there is no heartbeat service). util.SucceedsSoon(t, func() error { _, err := clientCtx.GRPCDial(remoteAddr) if err == circuit.ErrBreakerOpen { return nil } return errors.Errorf("breaker not open: %v", err) }) // Reset the breaker. The next dial will succeed. clientCtx.conns.Lock() clientCtx.conns.breakers[remoteAddr].Reset() clientCtx.conns.Unlock() if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } }
{ t.Fatal(err) }
conditional_block
context_test.go
// Copyright 2014 The Cockroach Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // // Author: Spencer Kimball (spencer.kimball@gmail.com) package rpc import ( "net" "sync" "sync/atomic" "testing" "time" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "github.com/cockroachdb/cockroach/testutils" "github.com/cockroachdb/cockroach/util" "github.com/cockroachdb/cockroach/util/hlc" "github.com/cockroachdb/cockroach/util/leaktest" "github.com/cockroachdb/cockroach/util/netutil" "github.com/cockroachdb/cockroach/util/stop" "github.com/cockroachdb/cockroach/util/syncutil" "github.com/pkg/errors" circuit "github.com/rubyist/circuitbreaker" ) func newTestServer(t *testing.T, ctx *Context, manual bool) (*grpc.Server, net.Listener) { tlsConfig, err := ctx.GetServerTLSConfig() if err != nil { t.Fatal(err) } s := grpc.NewServer(grpc.Creds(credentials.NewTLS(tlsConfig))) ln, err := netutil.ListenAndServeGRPC(ctx.Stopper, s, util.TestAddr) if err != nil { t.Fatal(err) } return s, ln } func TestHeartbeatCB(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() serverClock := hlc.NewClock(time.Unix(0, 20).UnixNano) serverCtx := newNodeTestContext(serverClock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() RegisterHeartbeatServer(s, &HeartbeatService{ clock: serverClock, remoteClockMonitor: serverCtx.RemoteClocks, }) // Clocks don't matter in this test. clientCtx := newNodeTestContext(serverClock, stopper) var once sync.Once ch := make(chan struct{}) clientCtx.HeartbeatCB = func() { once.Do(func() { close(ch) }) } _, err := clientCtx.GRPCDial(remoteAddr) if err != nil { t.Fatal(err) } <-ch } // TestHeartbeatHealth verifies that the health status changes after heartbeats // succeed or fail. func TestHeartbeatHealth(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() // Can't be zero because that'd be an empty offset. clock := hlc.NewClock(time.Unix(0, 1).UnixNano) serverCtx := newNodeTestContext(clock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() heartbeat := &ManualHeartbeatService{ ready: make(chan struct{}), stopper: stopper, clock: clock, remoteClockMonitor: serverCtx.RemoteClocks, } RegisterHeartbeatServer(s, heartbeat) clientCtx := newNodeTestContext(clock, stopper) // Make the intervals and timeouts shorter to speed up the tests. clientCtx.HeartbeatInterval = 1 * time.Millisecond clientCtx.HeartbeatTimeout = 1 * time.Millisecond if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } // This code is inherently racy so when we need to verify heartbeats we want // them to always succeed. sendHeartbeats := func() func() { done := make(chan struct{}) go func() { for { select { case <-done: return case heartbeat.ready <- struct{}{}: } } }() return func() { done <- struct{}{} } } // Should be healthy after the first successful heartbeat. stopHeartbeats := sendHeartbeats() util.SucceedsSoon(t, func() error { if !clientCtx.IsConnHealthy(remoteAddr) { return errors.Errorf("expected %s to be healthy", remoteAddr) } return nil }) stopHeartbeats() // Should no longer be healthy after heartbeating stops. util.SucceedsSoon(t, func() error { if clientCtx.IsConnHealthy(remoteAddr) { return errors.Errorf("expected %s to be unhealthy", remoteAddr) } return nil }) // Should return to healthy after another successful heartbeat. stopHeartbeats = sendHeartbeats() util.SucceedsSoon(t, func() error { if !clientCtx.IsConnHealthy(remoteAddr) { return errors.Errorf("expected %s to be healthy", remoteAddr) } return nil }) stopHeartbeats() if clientCtx.IsConnHealthy("non-existent connection") { t.Errorf("non-existent connection is reported as healthy") } } func TestOffsetMeasurement(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() serverTime := time.Unix(0, 20) serverClock := hlc.NewClock(serverTime.UnixNano) serverCtx := newNodeTestContext(serverClock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() RegisterHeartbeatServer(s, &HeartbeatService{ clock: serverClock, remoteClockMonitor: serverCtx.RemoteClocks, }) // Create a client clock that is behind the server clock. clientAdvancing := AdvancingClock{time: time.Unix(0, 10)} clientClock := hlc.NewClock(clientAdvancing.UnixNano) clientClock.SetMaxOffset(time.Millisecond) clientCtx := newNodeTestContext(clientClock, stopper) clientCtx.RemoteClocks.offsetTTL = 5 * clientAdvancing.getAdvancementInterval() if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } expectedOffset := RemoteOffset{Offset: 10, Uncertainty: 0, MeasuredAt: 10} util.SucceedsSoon(t, func() error { clientCtx.RemoteClocks.mu.Lock() defer clientCtx.RemoteClocks.mu.Unlock() if o, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; !ok { return errors.Errorf("expected offset of %s to be initialized, but it was not", remoteAddr) } else if o != expectedOffset { return errors.Errorf("expected:\n%v\nactual:\n%v", expectedOffset, o) } return nil }) // Change the client such that it receives a heartbeat right after the // maximum clock reading delay. clientAdvancing.setAdvancementInterval( maximumPingDurationMult*clientClock.MaxOffset() + 1*time.Nanosecond) util.SucceedsSoon(t, func() error { clientCtx.RemoteClocks.mu.Lock() defer clientCtx.RemoteClocks.mu.Unlock() if o, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; ok { return errors.Errorf("expected offset to have been cleared, but found %s", o) } return nil }) } func TestFailedOffsetMeasurement(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() // Can't be zero because that'd be an empty offset. clock := hlc.NewClock(time.Unix(0, 1).UnixNano) serverCtx := newNodeTestContext(clock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() heartbeat := &ManualHeartbeatService{ clock: clock, remoteClockMonitor: serverCtx.RemoteClocks, ready: make(chan struct{}), stopper: stopper, } RegisterHeartbeatServer(s, heartbeat) // Create a client that never receives a heartbeat after the first. clientCtx := newNodeTestContext(clock, stopper) // Increase the timeout so that failure arises from exceeding the maximum // clock reading delay, not the timeout. clientCtx.HeartbeatTimeout = 20 * clientCtx.HeartbeatInterval if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } heartbeat.ready <- struct{}{} // Allow one heartbeat for initialization. util.SucceedsSoon(t, func() error { clientCtx.RemoteClocks.mu.Lock() defer clientCtx.RemoteClocks.mu.Unlock() if _, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; !ok { return errors.Errorf("expected offset of %s to be initialized, but it was not", remoteAddr) } return nil }) util.SucceedsSoon(t, func() error { serverCtx.RemoteClocks.mu.Lock() defer serverCtx.RemoteClocks.mu.Unlock() if o, ok := serverCtx.RemoteClocks.mu.offsets[remoteAddr]; ok { return errors.Errorf("expected offset of %s to not be initialized, but it was: %v", remoteAddr, o) } return nil }) } type AdvancingClock struct { syncutil.Mutex time time.Time advancementInterval atomic.Value // time.Duration } func (ac *AdvancingClock) setAdvancementInterval(d time.Duration) { ac.advancementInterval.Store(d) } func (ac *AdvancingClock) getAdvancementInterval() time.Duration { v := ac.advancementInterval.Load() if v == nil { return 0 } return v.(time.Duration) } func (ac *AdvancingClock) UnixNano() int64 { ac.Lock() time := ac.time ac.time = time.Add(ac.getAdvancementInterval()) ac.Unlock() return time.UnixNano() } func TestRemoteOffsetUnhealthy(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() const maxOffset = 100 * time.Millisecond type nodeContext struct { offset time.Duration ctx *Context errChan chan error } start := time.Date(2012, 12, 07, 0, 0, 0, 0, time.UTC) offsetClock := func(offset time.Duration) *hlc.Clock { return hlc.NewClock(func() int64 { return start.Add(offset).UnixNano() }) } nodeCtxs := []nodeContext{ {offset: 0}, {offset: 0}, {offset: 0}, // The minimum offset that actually triggers node death. {offset: maxOffset + 1}, } for i := range nodeCtxs {
nodeCtxs[i].ctx.HeartbeatInterval = maxOffset s, ln := newTestServer(t, nodeCtxs[i].ctx, true) RegisterHeartbeatServer(s, &HeartbeatService{ clock: clock, remoteClockMonitor: nodeCtxs[i].ctx.RemoteClocks, }) nodeCtxs[i].ctx.Addr = ln.Addr().String() } // Fully connect the nodes. for i, clientNodeContext := range nodeCtxs { for j, serverNodeContext := range nodeCtxs { if i == j { continue } if _, err := clientNodeContext.ctx.GRPCDial(serverNodeContext.ctx.Addr); err != nil { t.Fatal(err) } } } // Wait until all nodes are connected to all other nodes. for _, nodeCtx := range nodeCtxs { util.SucceedsSoon(t, func() error { nodeCtx.ctx.RemoteClocks.mu.Lock() defer nodeCtx.ctx.RemoteClocks.mu.Unlock() if a, e := len(nodeCtx.ctx.RemoteClocks.mu.offsets), len(nodeCtxs)-1; a != e { return errors.Errorf("not yet fully connected: have %d of %d connections: %v", a, e, nodeCtx.ctx.RemoteClocks.mu.offsets) } return nil }) } for i, nodeCtx := range nodeCtxs { if nodeOffset := nodeCtx.offset; nodeOffset > maxOffset { if err := nodeCtx.ctx.RemoteClocks.VerifyClockOffset(); testutils.IsError(err, errOffsetGreaterThanMaxOffset) { t.Logf("max offset: %s - node %d with excessive clock offset of %s returned expected error: %s", maxOffset, i, nodeOffset, err) } else { t.Errorf("max offset: %s - node %d with excessive clock offset of %s returned unexpected error: %s", maxOffset, i, nodeOffset, err) } } else { if err := nodeCtx.ctx.RemoteClocks.VerifyClockOffset(); err != nil { t.Errorf("max offset: %s - node %d with acceptable clock offset of %s returned unexpected error: %s", maxOffset, i, nodeOffset, err) } else { t.Logf("max offset: %s - node %d with acceptable clock offset of %s did not return an error, as expected", maxOffset, i, nodeOffset) } } } } func TestCircuitBreaker(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() clock := hlc.NewClock(time.Unix(0, 1).UnixNano) serverCtx := newNodeTestContext(clock, stopper) _, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() clientCtx := newNodeTestContext(clock, stopper) // The first dial will succeed because the breaker is closed. if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } // Wait until the breaker opens. This will occur when the heartbeat fails // (because there is no heartbeat service). util.SucceedsSoon(t, func() error { _, err := clientCtx.GRPCDial(remoteAddr) if err == circuit.ErrBreakerOpen { return nil } return errors.Errorf("breaker not open: %v", err) }) // Reset the breaker. The next dial will succeed. clientCtx.conns.Lock() clientCtx.conns.breakers[remoteAddr].Reset() clientCtx.conns.Unlock() if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } }
clock := offsetClock(nodeCtxs[i].offset) nodeCtxs[i].errChan = make(chan error, 1) clock.SetMaxOffset(maxOffset) nodeCtxs[i].ctx = newNodeTestContext(clock, stopper)
random_line_split
context_test.go
// Copyright 2014 The Cockroach Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // // Author: Spencer Kimball (spencer.kimball@gmail.com) package rpc import ( "net" "sync" "sync/atomic" "testing" "time" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "github.com/cockroachdb/cockroach/testutils" "github.com/cockroachdb/cockroach/util" "github.com/cockroachdb/cockroach/util/hlc" "github.com/cockroachdb/cockroach/util/leaktest" "github.com/cockroachdb/cockroach/util/netutil" "github.com/cockroachdb/cockroach/util/stop" "github.com/cockroachdb/cockroach/util/syncutil" "github.com/pkg/errors" circuit "github.com/rubyist/circuitbreaker" ) func newTestServer(t *testing.T, ctx *Context, manual bool) (*grpc.Server, net.Listener) { tlsConfig, err := ctx.GetServerTLSConfig() if err != nil { t.Fatal(err) } s := grpc.NewServer(grpc.Creds(credentials.NewTLS(tlsConfig))) ln, err := netutil.ListenAndServeGRPC(ctx.Stopper, s, util.TestAddr) if err != nil { t.Fatal(err) } return s, ln } func TestHeartbeatCB(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() serverClock := hlc.NewClock(time.Unix(0, 20).UnixNano) serverCtx := newNodeTestContext(serverClock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() RegisterHeartbeatServer(s, &HeartbeatService{ clock: serverClock, remoteClockMonitor: serverCtx.RemoteClocks, }) // Clocks don't matter in this test. clientCtx := newNodeTestContext(serverClock, stopper) var once sync.Once ch := make(chan struct{}) clientCtx.HeartbeatCB = func() { once.Do(func() { close(ch) }) } _, err := clientCtx.GRPCDial(remoteAddr) if err != nil { t.Fatal(err) } <-ch } // TestHeartbeatHealth verifies that the health status changes after heartbeats // succeed or fail. func TestHeartbeatHealth(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() // Can't be zero because that'd be an empty offset. clock := hlc.NewClock(time.Unix(0, 1).UnixNano) serverCtx := newNodeTestContext(clock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() heartbeat := &ManualHeartbeatService{ ready: make(chan struct{}), stopper: stopper, clock: clock, remoteClockMonitor: serverCtx.RemoteClocks, } RegisterHeartbeatServer(s, heartbeat) clientCtx := newNodeTestContext(clock, stopper) // Make the intervals and timeouts shorter to speed up the tests. clientCtx.HeartbeatInterval = 1 * time.Millisecond clientCtx.HeartbeatTimeout = 1 * time.Millisecond if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } // This code is inherently racy so when we need to verify heartbeats we want // them to always succeed. sendHeartbeats := func() func() { done := make(chan struct{}) go func() { for { select { case <-done: return case heartbeat.ready <- struct{}{}: } } }() return func() { done <- struct{}{} } } // Should be healthy after the first successful heartbeat. stopHeartbeats := sendHeartbeats() util.SucceedsSoon(t, func() error { if !clientCtx.IsConnHealthy(remoteAddr) { return errors.Errorf("expected %s to be healthy", remoteAddr) } return nil }) stopHeartbeats() // Should no longer be healthy after heartbeating stops. util.SucceedsSoon(t, func() error { if clientCtx.IsConnHealthy(remoteAddr) { return errors.Errorf("expected %s to be unhealthy", remoteAddr) } return nil }) // Should return to healthy after another successful heartbeat. stopHeartbeats = sendHeartbeats() util.SucceedsSoon(t, func() error { if !clientCtx.IsConnHealthy(remoteAddr) { return errors.Errorf("expected %s to be healthy", remoteAddr) } return nil }) stopHeartbeats() if clientCtx.IsConnHealthy("non-existent connection") { t.Errorf("non-existent connection is reported as healthy") } } func TestOffsetMeasurement(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() serverTime := time.Unix(0, 20) serverClock := hlc.NewClock(serverTime.UnixNano) serverCtx := newNodeTestContext(serverClock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() RegisterHeartbeatServer(s, &HeartbeatService{ clock: serverClock, remoteClockMonitor: serverCtx.RemoteClocks, }) // Create a client clock that is behind the server clock. clientAdvancing := AdvancingClock{time: time.Unix(0, 10)} clientClock := hlc.NewClock(clientAdvancing.UnixNano) clientClock.SetMaxOffset(time.Millisecond) clientCtx := newNodeTestContext(clientClock, stopper) clientCtx.RemoteClocks.offsetTTL = 5 * clientAdvancing.getAdvancementInterval() if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } expectedOffset := RemoteOffset{Offset: 10, Uncertainty: 0, MeasuredAt: 10} util.SucceedsSoon(t, func() error { clientCtx.RemoteClocks.mu.Lock() defer clientCtx.RemoteClocks.mu.Unlock() if o, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; !ok { return errors.Errorf("expected offset of %s to be initialized, but it was not", remoteAddr) } else if o != expectedOffset { return errors.Errorf("expected:\n%v\nactual:\n%v", expectedOffset, o) } return nil }) // Change the client such that it receives a heartbeat right after the // maximum clock reading delay. clientAdvancing.setAdvancementInterval( maximumPingDurationMult*clientClock.MaxOffset() + 1*time.Nanosecond) util.SucceedsSoon(t, func() error { clientCtx.RemoteClocks.mu.Lock() defer clientCtx.RemoteClocks.mu.Unlock() if o, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; ok { return errors.Errorf("expected offset to have been cleared, but found %s", o) } return nil }) } func TestFailedOffsetMeasurement(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() // Can't be zero because that'd be an empty offset. clock := hlc.NewClock(time.Unix(0, 1).UnixNano) serverCtx := newNodeTestContext(clock, stopper) s, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() heartbeat := &ManualHeartbeatService{ clock: clock, remoteClockMonitor: serverCtx.RemoteClocks, ready: make(chan struct{}), stopper: stopper, } RegisterHeartbeatServer(s, heartbeat) // Create a client that never receives a heartbeat after the first. clientCtx := newNodeTestContext(clock, stopper) // Increase the timeout so that failure arises from exceeding the maximum // clock reading delay, not the timeout. clientCtx.HeartbeatTimeout = 20 * clientCtx.HeartbeatInterval if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } heartbeat.ready <- struct{}{} // Allow one heartbeat for initialization. util.SucceedsSoon(t, func() error { clientCtx.RemoteClocks.mu.Lock() defer clientCtx.RemoteClocks.mu.Unlock() if _, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; !ok { return errors.Errorf("expected offset of %s to be initialized, but it was not", remoteAddr) } return nil }) util.SucceedsSoon(t, func() error { serverCtx.RemoteClocks.mu.Lock() defer serverCtx.RemoteClocks.mu.Unlock() if o, ok := serverCtx.RemoteClocks.mu.offsets[remoteAddr]; ok { return errors.Errorf("expected offset of %s to not be initialized, but it was: %v", remoteAddr, o) } return nil }) } type AdvancingClock struct { syncutil.Mutex time time.Time advancementInterval atomic.Value // time.Duration } func (ac *AdvancingClock) setAdvancementInterval(d time.Duration) { ac.advancementInterval.Store(d) } func (ac *AdvancingClock)
() time.Duration { v := ac.advancementInterval.Load() if v == nil { return 0 } return v.(time.Duration) } func (ac *AdvancingClock) UnixNano() int64 { ac.Lock() time := ac.time ac.time = time.Add(ac.getAdvancementInterval()) ac.Unlock() return time.UnixNano() } func TestRemoteOffsetUnhealthy(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() const maxOffset = 100 * time.Millisecond type nodeContext struct { offset time.Duration ctx *Context errChan chan error } start := time.Date(2012, 12, 07, 0, 0, 0, 0, time.UTC) offsetClock := func(offset time.Duration) *hlc.Clock { return hlc.NewClock(func() int64 { return start.Add(offset).UnixNano() }) } nodeCtxs := []nodeContext{ {offset: 0}, {offset: 0}, {offset: 0}, // The minimum offset that actually triggers node death. {offset: maxOffset + 1}, } for i := range nodeCtxs { clock := offsetClock(nodeCtxs[i].offset) nodeCtxs[i].errChan = make(chan error, 1) clock.SetMaxOffset(maxOffset) nodeCtxs[i].ctx = newNodeTestContext(clock, stopper) nodeCtxs[i].ctx.HeartbeatInterval = maxOffset s, ln := newTestServer(t, nodeCtxs[i].ctx, true) RegisterHeartbeatServer(s, &HeartbeatService{ clock: clock, remoteClockMonitor: nodeCtxs[i].ctx.RemoteClocks, }) nodeCtxs[i].ctx.Addr = ln.Addr().String() } // Fully connect the nodes. for i, clientNodeContext := range nodeCtxs { for j, serverNodeContext := range nodeCtxs { if i == j { continue } if _, err := clientNodeContext.ctx.GRPCDial(serverNodeContext.ctx.Addr); err != nil { t.Fatal(err) } } } // Wait until all nodes are connected to all other nodes. for _, nodeCtx := range nodeCtxs { util.SucceedsSoon(t, func() error { nodeCtx.ctx.RemoteClocks.mu.Lock() defer nodeCtx.ctx.RemoteClocks.mu.Unlock() if a, e := len(nodeCtx.ctx.RemoteClocks.mu.offsets), len(nodeCtxs)-1; a != e { return errors.Errorf("not yet fully connected: have %d of %d connections: %v", a, e, nodeCtx.ctx.RemoteClocks.mu.offsets) } return nil }) } for i, nodeCtx := range nodeCtxs { if nodeOffset := nodeCtx.offset; nodeOffset > maxOffset { if err := nodeCtx.ctx.RemoteClocks.VerifyClockOffset(); testutils.IsError(err, errOffsetGreaterThanMaxOffset) { t.Logf("max offset: %s - node %d with excessive clock offset of %s returned expected error: %s", maxOffset, i, nodeOffset, err) } else { t.Errorf("max offset: %s - node %d with excessive clock offset of %s returned unexpected error: %s", maxOffset, i, nodeOffset, err) } } else { if err := nodeCtx.ctx.RemoteClocks.VerifyClockOffset(); err != nil { t.Errorf("max offset: %s - node %d with acceptable clock offset of %s returned unexpected error: %s", maxOffset, i, nodeOffset, err) } else { t.Logf("max offset: %s - node %d with acceptable clock offset of %s did not return an error, as expected", maxOffset, i, nodeOffset) } } } } func TestCircuitBreaker(t *testing.T) { defer leaktest.AfterTest(t)() stopper := stop.NewStopper() defer stopper.Stop() clock := hlc.NewClock(time.Unix(0, 1).UnixNano) serverCtx := newNodeTestContext(clock, stopper) _, ln := newTestServer(t, serverCtx, true) remoteAddr := ln.Addr().String() clientCtx := newNodeTestContext(clock, stopper) // The first dial will succeed because the breaker is closed. if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } // Wait until the breaker opens. This will occur when the heartbeat fails // (because there is no heartbeat service). util.SucceedsSoon(t, func() error { _, err := clientCtx.GRPCDial(remoteAddr) if err == circuit.ErrBreakerOpen { return nil } return errors.Errorf("breaker not open: %v", err) }) // Reset the breaker. The next dial will succeed. clientCtx.conns.Lock() clientCtx.conns.breakers[remoteAddr].Reset() clientCtx.conns.Unlock() if _, err := clientCtx.GRPCDial(remoteAddr); err != nil { t.Fatal(err) } }
getAdvancementInterval
identifier_name
my_optimisation.py
import numpy as np def app_products2optimisation(products): # вес P — x1, к --x2 # c = [-250,-210] #Функция цели 250x1+210x2 – уменьшение расходов на продуктовую корзину ; # A_ub = [[15,4]] #'1' жиры последовательно для Р и К # b_ub = [14] #'1' 15x1+4x2 <=14 – ограничение количества жира; # A_eq = [[150,200]] #'2' 150x1+200x2 =300 – ограничение количества калорий. # b_eq = [300] #'2' # print (linprog(c, A_ub, b_ub, A_eq, b_eq)) if not products: return [] n = len(products)-2 c = [] ub = [] eq = [] for i in range(0,n): c.append(products[i].default_price) ub.append(products[i].fat) eq.append(products[i].calories) i += 1 # Перехожу к столбцу свободных членов для уравнения меньше чем, в продуктах это вещь под назавнием Minimise Fat ub.append(products[i].fat) A_ub = np.array([ub]) c.append(products[i].default_price) i += 1 # Перехожу к столбцу свободных членов для уравнения больше чем, в продуктах это вещь под назавнием Get enough calories eq.append(products[i].calories) A_eq = np.array([eq]) A_eq = -1 * A_eq # Для > меняем знак всех элементов (потом написать в цикл автоматом по условию!) c = np.array([c]) A_eq = np.squeeze(A_eq) # Django мне создала списки двойного уровня вложенности, надо уменьшить это A_ub = np.squeeze(A_ub) c = np.squeeze(c) table = [A_ub, A_eq, c] table = np.asarray(table, dtype=float) b = np.identity(n+1) # создаю единичную матрицу # amount_columns = np.size(table,1) table = np.insert(table,n,b,axis=1) # вставляю единичную матрицу в таблицу перед столбцом с номером amount_columns-1, получается n+1, по столбцам, т.е. axis 1 print('np.size(table)',np.size(table)) print(table) #return type(table) result = minimise(table) result[n] = -1 * result[n] print(result) return result # return [1, 2, 3] def amount_rows(amount_constraints): amount_rows = amount_constraints+1 return amount_rows def amount_columns(amount_variables,amount_constraints): amount_columns = amount_variables+amount_constraints+2 return amount_columns def create_simplex_table(amount_variables,amount_constraints): #Создание двумерного массива r = amount_rows(amount_constraints) c = amount_columns(amount_variables,amount_constraints) empty_table = np.zeros((r, c)) return empty_table #Количество строк = кол-ву ограничений + целевая функция amount_constraints+1 #Количество столбцов = кол-ву переменных + кол-ву дополнительных переменных для приведения системы к каноническому виду + M (max/min) + Колонка свободных членов def input_to_list(equation): #Перевод в list equation = equation.split(',') if '>' in equation: text_index = equation.index('>') del equation[text_index] equation = [float(i) * -1 for i in equation] return equation if '<' in equation: text_index = equation.index('<') del equation[text_index] equation = [float(i) for i in equation] return equation def xi_names(table): # Создание названий переменных x1, x2, ..., xn amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 amount_columns = np.size(table,1) # Подсчет количества столбцов с помощью axis=1 xi = amount_columns - amount_rows -1 names = [] for i in range(xi): names.append('x' + str(i + 1)) return names def lines4constraints_available(filled_table): # Проверка, что в предпоследней строке нули, чтобы добавить ещё ограничение penultimate_row = filled_table[-2:-1] return (~penultimate_row.any(axis=1)).any() #The any method returns True if any value in the array is "truthy". # Nonzero numbers are considered True, and 0 is considered False. # By using the argument axis=1, the method is applied to each row. def add_constraint(table, equation): # Заполнение свободных строк для ограничений if lines4constraints_available(table): amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 amount_columns = np.size(table,1) # Подсчет количества столбцов с помощью axis=1 xi = amount_columns - amount_rows -1 # Количество переменных b = np.where(~table.any(axis=1))[0] # Поиск строк со всеми нулями j = b[0] # Номер первой строки со всеми нулями row = table[j, :] # Первая строка со всеми нулями equation = input_to_list(equation) i = 0 # Наполнение двумерного массива пока в выражении еще есть переменные while i < len(equation) - 1: # Переменные базиса записать в таблицу row[i] = equation[i] i += 1 row[-1] = equation[-1] #Колонка свободных членов row[xi + j] = 1 # Создание 1 для единичной матрицы справа базиса else: print('Свободных строк для ограничений больше не было предусмотрено, начните сначала или введите целевую функцию.') def line4objective_available(filled_table): # Проверка, есть ли нули в последней (и только последней) строке, чтобы вставить целевую функцию last_rows = np.array(filled_table[-2:]) empty = np.where(~last_rows.any(axis=1))[0] if np.array_equal(empty, np.array([1])): return True else: return False def add_objective(table, equation): # добавляет целевую функцию, если есть свободная строка в конце таблицы if line4objective_available(table): equation = [float(i) for i in equation.split(',')] amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 row = table[amount_rows - 1, :] i = 0 # пока в выражении еще есть переменные while i < len(equation)-1: # записать их в таблицу row[i] = equation[i] * -1 i += 1 row[-2] = 1 # Создание 1 для единичной матрицы справа базиса row[-1] = equation[-1] #Хранение значения необходимого бюджета else: print('Остались пустые сроки, введите ограничения или начните сначала.') def convert_min(filled_table): # Для минимизации последняя строка (целевая функция) умножается на -1 filled_table[-1] = -1 * filled_table[-1] return filled_table def check_bi_positifs(filled_table): # Проверка, что в столбце свободных членов не осталось отрицательных min_bi = min(filled_table[:-1,-1]) if min_bi >= 0: return False # Достигнут оптимум, переход к выводу else: return True # Необходимо пересчитать строку def check_cj0(filled_table): #Проверка условия: все ли элементы последней строки отрицательны, cj<=0 amount_conditions = np.size(filled_table,0) # Подсчет количества строк с помощью axis=0 max_cj = max(filled_table[amount_conditions-1,:-1]) # Выбор наибольшего элемента в слайсе [последняя строка, вся таблица без последнего столбца] # return (max_cj <= 0) # идентично if max_cj >= 0: return False #Переход к следующему шагу метода else: return True #Переход к выводу результата def neg_bi_index(filled_table): # Поиск номера строки с отрицательным свободным членом amount_conditions = np.size(filled_table,0)-1 # Подсчет количества строк с помощью axis=0 min_bi_row_number = np.argmin(filled_table[:-1,amount_conditions])# + 1 Возвращает индекс наменьшего элемента в слайсе [вся таблица без последней строки, последний столбец], добавляем 1 чтобы номер столбца был человекочитаемым return min_bi_row_number def column_choice(filled_table): #Выбор разрешающего столбца, cj amount_conditions = np.size(filled_table, 0) - 1 # Подсчет количества строк с помощью axis=0 min_cj_column_number = np.argmin(filled_table[amount_conditions, :-1]) #+ 1 Возвращает индекс наибольшего элемента в слайсе [последняя строка, вся таблица без последнего столбца], добавляем 1 чтобы номер столбца был человекочитаемым return min_cj_column_number def bi_to_positive(filled_table): division = [] # Разрешение двойственной задачи линейного программирования row_index = neg_bi_index(filled_table) min_in_row_column_number = np.argmin(filled_table[row_index,:-1]) #+1  Возвращает индекс наименьшего элемента в слайсе по номеру строки с отрицательным свободным членом, исключая последний столбец , добавляем 1 чтобы номер столбца был человекочитаемым col = filled_table[:-1, min_in_row_column_number] # все коэффициенты ограничений этого столбца last_column = filled_table[:-1,-1] for i, b in zip(col, last_column): if i != 0 and b / i > 0: division.append(b / i) else: division.append(10000) index = division.index(min(division)) #наименьшее позитивное частное return [index,min_in_row_column_number] def row_choice(filled_table): if check_cj0(filled_table):#Надо поднимать ошибку, если не срабатывает!!!! c = column_choice(filled_table) #Номер разрешающего столбца в человеческом формате divided = [] r_column = filled_table[:-1, c - 1] # [вся таблица без последней строки, столбец r в машинном формате] last_column = filled_table[:-1, -1] for r, l in zip(r_column, last_column): if r > 0: divided.append(l/r) else: divided.append(100000) min_air_row_number = divided.index(min(divided)) #+1 #Номер разрешающей строки в человеческом формате return [min_air_row_number, c] def calc(chosen_row, chosen_column, source_table): #Пересчет элементов target_table = np.zeros_like(source_table, dtype=float) # Создание новой нулевой таблицы r = chosen_row #-1 # Номер разрешающей строки в машинном формате c = chosen_column #-1 # Номер разрешающего столбца в машинном формате pivot_row = source_table[r, :] # Разрешающая строка pivot_element = source_table[r, c] # Разрешающий элемент if pivot_element: e = 1 / pivot_element new_chosen_row = pivot_row * e # Делим все элементы разрешающей строки на разрешающий элемент for i in range(np.size(source_table, 0)): # количеств строк с помощью axis=0 if i != r: # Если текущая строка отличается от поворотной строки row = source_table[i, :] # Очередная строка p_c_el = source_table[i, c] # Элемент текущей строки, который в разрешающем столбце target_table[i, :] = list(row-new_chosen_row * p_c_el) # заменяем элементы очередной строки новой таблицы на вычисленные, # домножаем на уже посчитанные элементы разрешающей строки, чтобы не повторять вычисление target_table[r, :] = list(new_chosen_row) # Делим все элементы разрешающей строки на разрешающий элемент, заменяем элементы разрешающей строки на вычисленные return target_table else: print('Разрешающий элемент не позволяет провести пересчет.') def minimise(table, output='результаты'): # Обращается к функциям пересчета и выводит результаты table = convert_min(table) while check_bi_positifs(table): table = calc( bi_to_positive(table)[0], bi_to_positive(table)[1], table ) # Жордановы замены для негативных свободных членов, требуются в двойственном симплексе while check_cj0(table): table = calc( row_choice(table)[0], row_choice(table)[1], table ) # Жордановы замены для последней строки, коэффициентов при целевой функции amount_columns = np.size(table,1) # Подсчет количества столбцов с помощью axis=1 amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 var = amount_columns - amount_rows -1 i = 0 val = {} # Создание пустого словаря для хранения результатов работы алгоритма for i in range(var): # для солбцов переменных вне базиса, поиск числа в солбце и сопоставление числу результату в последнем столбце col = table[:, i] s = sum(col) m = max(col) if float(s) == float(m): loc = np.where(col == m)[0][0] val[xi_names(table)[i]] = table[loc, -1] else: val[xi_names(table)[i]] = 0 val['min'] = table[-1, -1] * -1 # для терминала результаты в виде словаря с ключами по номерам переменных x1,x2...xn и значением бюджета с ключом min val = list(val.values()) # для джанги результаты в виде list # return [1, 2, 3] if output == 'table': return table else: return val if __name__ == "__main__": st = create_simplex_table(2, 4) add_constraint(st,'2,5,>,30') add_constraint(st,'-3,5,>,5') add_constraint(st,'8,3,<,85') add_constraint(st,'-9,7,<,42') add_objective(st,'2,7,0') print(minimise(st)) print('-'*100) st = create_simplex_table(2,2) add_constraint(st,'15,4,<,14') add_constraint(st,'150,200,>,300') add_objective(st,'250,210,0') print(minimise(st)) print('-'*100) st = create_simplex_table(2,2) add_constraint(st,'1450,770,>,1100') add_constraint(st,'560,120,>,800') add_objective(st,'130,30,0') print(minimise(st)) print('-'*100) print('-'*100) a = np.array([ [0.,0.,0.,0.,0.,0.], [0.,0.,0.,0.,0.,0.], [0.,0.,0.,0.,0.,0.]]) assert np.array_equal(create_simplex_table(2,2),a),"ошибка создания nparray" test_table1 = np.array([ [4,6,1,0,0,120], [2,6,0,1,0,72], [0,1,0,0,1,10], [2,4,0,0,0,0]]) test_table2 = np.array([ [4,0,1,0,-6,60], [2,0,0,1,-6,12], [0,1,0,0,1,10], [2,0,0,0,-4,-40]]) test_table3 = np.array([ [0,0,1,-2,6,36], [1,0,0,0.5,-3,6], [0,1,0,0,1,10], [0,0,0,-1,2,-52]]) test_table4 = np.array([ [0,0,1/6,-1/3,1,6], [1,0,0.5,-0.5,0,24], [0,1,-1/6,1/3,0,4], [0,0,-1/3,-1/3,0,-64]]) assert check_cj0(test_table1)==False,"ошибка проверки условия cj<=0" assert check_cj0(test_table2)==False,"ошибка проверки условия cj<=0" assert check_cj0(test_table3)==False,"ошибка проверки условия cj<=0" assert column_choice(test_table1)==2,"ошибка выбора разрешающего столбца" assert np.array_equal(calc(3-1,2-1,test_table1),test_table2),"ошибка пересчета" # везде -1, использует индекс в машинном формате assert np.array_equal(calc(2-1,1-1,test_table2),test_table3),"ошибка пересчета" assert np.allclose(calc(1-1,5-1,test_table3),test_table4),"ошибка пересчета"
conditional_block
my_optimisation.py
import numpy as np def app_products2optimisation(products): # вес P — x1, к --x2 # c = [-250,-210] #Функция цели 250x1+210x2 – уменьшение расходов на продуктовую корзину ; # A_ub = [[15,4]] #'1' жиры последовательно для Р и К # b_ub = [14] #'1' 15x1+4x2 <=14 – ограничение количества жира; # A_eq = [[150,200]] #'2' 150x1+200x2 =300 – ограничение количества калорий. # b_eq = [300] #'2' # print (linprog(c, A_ub, b_ub, A_eq, b_eq)) if not products: return [] n = len(products)-2 c = [] ub = [] eq = [] for i in range(0,n): c.append(products[i].default_price) ub.append(products[i].fat) eq.append(products[i].calories) i += 1 # Перехожу к столбцу свободных членов для уравнения меньше чем, в продуктах это вещь под назавнием Minimise Fat ub.append(products[i].fat) A_ub = np.array([ub]) c.append(products[i].default_price) i += 1 # Перехожу к столбцу свободных членов для уравнения больше чем, в продуктах это вещь под назавнием Get enough calories eq.append(products[i].calories) A_eq = np.array([eq]) A_eq = -1 * A_eq # Для > меняем знак всех элементов (потом написать в цикл автоматом по условию!) c = np.array([c]) A_eq = np.squeeze(A_eq) # Django мне создала списки двойного уровня вложенности, надо уменьшить это A_ub = np.squeeze(A_ub) c = np.squeeze(c) table = [A_ub, A_eq, c] table = np.asarray(table, dtype=float) b = np.identity(n+1) # создаю единичную матрицу # amount_columns = np.size(table,1) table = np.insert(table,n,b,axis=1) # вставляю единичную матрицу в таблицу перед столбцом с номером amount_columns-1, получается n+1, по столбцам, т.е. axis 1 print('np.size(table)',np.size(table)) print(table) #return type(table) result = minimise(table) result[n] = -1 * result[n] print(result) return result # return [1, 2, 3] def amount_rows(amount_constraints): amount_rows = amount_constraints+1 return amount_rows def amount_columns(amount_variables,amount_constraints): amount_columns = amount_variables+amount_constraints+2 return amount_columns def create_simplex_table(amount_variables,amount_constraints): #Создание двумерного массива r = amount_rows(amount_constraints) c = amount_columns(amount_variables,amount_constraints) empty_table = np.zeros((r, c)) return empty_table #Количество строк = кол-ву ограничений + целевая функция amount_constraints+1 #Количество столбцов = кол-ву переменных + кол-ву дополнительных переменных для приведения системы к каноническому виду + M (max/min) + Колонка свободных членов def input_to_list(equation): #Перевод в list equation = equation.split(',') if '>' in equation: text_index = equation.index('>') del equation[text_index] equation = [float(i) * -1 for i in equation] return equation if '<' in equation: text_index = equation.index('<') del equation[text_index] equation = [float(i) for i in equation] return equation def xi_names(table): # Создание названий переменных x1, x2, ..., xn amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 amount_columns = np.size(table,1) # Подсчет количества столбцов с помощью axis=1 xi = amount_columns - amount_rows -1 names = [] for i in range(xi): names.append('x' + str(i + 1)) return names def lines4constraints_available(filled_table): # Проверка, что в предпоследней строке нули, чтобы добавить ещё ограничение penultimate_row = filled_table[-2:-1] return (~penultimate_row.any(axis=1)).any() #The any method returns True if any value in the array is "truthy". # Nonzero numbers are considered True, and 0 is considered False. # By using the argument axis=1, the method is applied to each row. def add_constraint(table, equation): # Заполнение свободных строк для ограничений if lines4constraints_available(table): amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 amount_columns = np.size(table,1) # Подсчет количества столбцов с помощью axis=1 xi = amount_columns - amount_rows -1 # Количество переменных b = np.where(~table.any(axis=1))[0] # Поиск строк со всеми нулями j = b[0] # Номер первой строки со всеми нулями row = table[j, :] # Первая строка со всеми нулями equation = input_to_list(equation) i = 0 # Наполнение двумерного массива пока в выражении еще есть переменные while i < len(equation) - 1: # Переменные базиса записать в таблицу row[i] = equation[i] i += 1 row[-1] = equation[-1] #Колонка свободных членов row[xi + j] = 1 # Создание 1 для единичной матрицы справа базиса else: print('Свободных строк для ограничений больше не было предусмотрено, начните сначала или введите целевую функцию.') def line4objective_available(filled_table): # Проверка, есть ли нули в последней (и только последней) строке, чтобы вставить целевую функцию last_rows = np.array(filled_table[-2:]) empty = np.where(~last_rows.any(axis=1))[0] if np.array_equal(empty, np.array([1])): return True else: return False def add_objective(table, equation): # добавляет целевую функцию, если есть свободная строка в конце таблицы if line4objective_available(table): equation = [float(i) for i in equation.split(',')] amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 row = table[amount_rows - 1, :] i = 0 # пока в выражении еще есть переменные while i < len(equation)-1: # записать их в таблицу row[i] = equation[i] * -1 i += 1 row[-2] = 1 # Создание 1 для единичной матрицы справа базиса row[-1] = equation[-1] #Хранение значения необходимого бюджета else: print('Остались пустые сроки, введите ограничения или начните сначала.') def convert_min(filled_table): # Для минимизации последняя строка (целевая функция) умножается на -1 filled_table[-1] = -1 * filled_table[-1] return filled_table def check_bi_positifs(filled_table): # Проверка, что в ст
е осталось отрицательных min_bi = min(filled_table[:-1,-1]) if min_bi >= 0: return False # Достигнут оптимум, переход к выводу else: return True # Необходимо пересчитать строку def check_cj0(filled_table): #Проверка условия: все ли элементы последней строки отрицательны, cj<=0 amount_conditions = np.size(filled_table,0) # Подсчет количества строк с помощью axis=0 max_cj = max(filled_table[amount_conditions-1,:-1]) # Выбор наибольшего элемента в слайсе [последняя строка, вся таблица без последнего столбца] # return (max_cj <= 0) # идентично if max_cj >= 0: return False #Переход к следующему шагу метода else: return True #Переход к выводу результата def neg_bi_index(filled_table): # Поиск номера строки с отрицательным свободным членом amount_conditions = np.size(filled_table,0)-1 # Подсчет количества строк с помощью axis=0 min_bi_row_number = np.argmin(filled_table[:-1,amount_conditions])# + 1 Возвращает индекс наменьшего элемента в слайсе [вся таблица без последней строки, последний столбец], добавляем 1 чтобы номер столбца был человекочитаемым return min_bi_row_number def column_choice(filled_table): #Выбор разрешающего столбца, cj amount_conditions = np.size(filled_table, 0) - 1 # Подсчет количества строк с помощью axis=0 min_cj_column_number = np.argmin(filled_table[amount_conditions, :-1]) #+ 1 Возвращает индекс наибольшего элемента в слайсе [последняя строка, вся таблица без последнего столбца], добавляем 1 чтобы номер столбца был человекочитаемым return min_cj_column_number def bi_to_positive(filled_table): division = [] # Разрешение двойственной задачи линейного программирования row_index = neg_bi_index(filled_table) min_in_row_column_number = np.argmin(filled_table[row_index,:-1]) #+1  Возвращает индекс наименьшего элемента в слайсе по номеру строки с отрицательным свободным членом, исключая последний столбец , добавляем 1 чтобы номер столбца был человекочитаемым col = filled_table[:-1, min_in_row_column_number] # все коэффициенты ограничений этого столбца last_column = filled_table[:-1,-1] for i, b in zip(col, last_column): if i != 0 and b / i > 0: division.append(b / i) else: division.append(10000) index = division.index(min(division)) #наименьшее позитивное частное return [index,min_in_row_column_number] def row_choice(filled_table): if check_cj0(filled_table):#Надо поднимать ошибку, если не срабатывает!!!! c = column_choice(filled_table) #Номер разрешающего столбца в человеческом формате divided = [] r_column = filled_table[:-1, c - 1] # [вся таблица без последней строки, столбец r в машинном формате] last_column = filled_table[:-1, -1] for r, l in zip(r_column, last_column): if r > 0: divided.append(l/r) else: divided.append(100000) min_air_row_number = divided.index(min(divided)) #+1 #Номер разрешающей строки в человеческом формате return [min_air_row_number, c] def calc(chosen_row, chosen_column, source_table): #Пересчет элементов target_table = np.zeros_like(source_table, dtype=float) # Создание новой нулевой таблицы r = chosen_row #-1 # Номер разрешающей строки в машинном формате c = chosen_column #-1 # Номер разрешающего столбца в машинном формате pivot_row = source_table[r, :] # Разрешающая строка pivot_element = source_table[r, c] # Разрешающий элемент if pivot_element: e = 1 / pivot_element new_chosen_row = pivot_row * e # Делим все элементы разрешающей строки на разрешающий элемент for i in range(np.size(source_table, 0)): # количеств строк с помощью axis=0 if i != r: # Если текущая строка отличается от поворотной строки row = source_table[i, :] # Очередная строка p_c_el = source_table[i, c] # Элемент текущей строки, который в разрешающем столбце target_table[i, :] = list(row-new_chosen_row * p_c_el) # заменяем элементы очередной строки новой таблицы на вычисленные, # домножаем на уже посчитанные элементы разрешающей строки, чтобы не повторять вычисление target_table[r, :] = list(new_chosen_row) # Делим все элементы разрешающей строки на разрешающий элемент, заменяем элементы разрешающей строки на вычисленные return target_table else: print('Разрешающий элемент не позволяет провести пересчет.') def minimise(table, output='результаты'): # Обращается к функциям пересчета и выводит результаты table = convert_min(table) while check_bi_positifs(table): table = calc( bi_to_positive(table)[0], bi_to_positive(table)[1], table ) # Жордановы замены для негативных свободных членов, требуются в двойственном симплексе while check_cj0(table): table = calc( row_choice(table)[0], row_choice(table)[1], table ) # Жордановы замены для последней строки, коэффициентов при целевой функции amount_columns = np.size(table,1) # Подсчет количества столбцов с помощью axis=1 amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 var = amount_columns - amount_rows -1 i = 0 val = {} # Создание пустого словаря для хранения результатов работы алгоритма for i in range(var): # для солбцов переменных вне базиса, поиск числа в солбце и сопоставление числу результату в последнем столбце col = table[:, i] s = sum(col) m = max(col) if float(s) == float(m): loc = np.where(col == m)[0][0] val[xi_names(table)[i]] = table[loc, -1] else: val[xi_names(table)[i]] = 0 val['min'] = table[-1, -1] * -1 # для терминала результаты в виде словаря с ключами по номерам переменных x1,x2...xn и значением бюджета с ключом min val = list(val.values()) # для джанги результаты в виде list # return [1, 2, 3] if output == 'table': return table else: return val if __name__ == "__main__": st = create_simplex_table(2, 4) add_constraint(st,'2,5,>,30') add_constraint(st,'-3,5,>,5') add_constraint(st,'8,3,<,85') add_constraint(st,'-9,7,<,42') add_objective(st,'2,7,0') print(minimise(st)) print('-'*100) st = create_simplex_table(2,2) add_constraint(st,'15,4,<,14') add_constraint(st,'150,200,>,300') add_objective(st,'250,210,0') print(minimise(st)) print('-'*100) st = create_simplex_table(2,2) add_constraint(st,'1450,770,>,1100') add_constraint(st,'560,120,>,800') add_objective(st,'130,30,0') print(minimise(st)) print('-'*100) print('-'*100) a = np.array([ [0.,0.,0.,0.,0.,0.], [0.,0.,0.,0.,0.,0.], [0.,0.,0.,0.,0.,0.]]) assert np.array_equal(create_simplex_table(2,2),a),"ошибка создания nparray" test_table1 = np.array([ [4,6,1,0,0,120], [2,6,0,1,0,72], [0,1,0,0,1,10], [2,4,0,0,0,0]]) test_table2 = np.array([ [4,0,1,0,-6,60], [2,0,0,1,-6,12], [0,1,0,0,1,10], [2,0,0,0,-4,-40]]) test_table3 = np.array([ [0,0,1,-2,6,36], [1,0,0,0.5,-3,6], [0,1,0,0,1,10], [0,0,0,-1,2,-52]]) test_table4 = np.array([ [0,0,1/6,-1/3,1,6], [1,0,0.5,-0.5,0,24], [0,1,-1/6,1/3,0,4], [0,0,-1/3,-1/3,0,-64]]) assert check_cj0(test_table1)==False,"ошибка проверки условия cj<=0" assert check_cj0(test_table2)==False,"ошибка проверки условия cj<=0" assert check_cj0(test_table3)==False,"ошибка проверки условия cj<=0" assert column_choice(test_table1)==2,"ошибка выбора разрешающего столбца" assert np.array_equal(calc(3-1,2-1,test_table1),test_table2),"ошибка пересчета" # везде -1, использует индекс в машинном формате assert np.array_equal(calc(2-1,1-1,test_table2),test_table3),"ошибка пересчета" assert np.allclose(calc(1-1,5-1,test_table3),test_table4),"ошибка пересчета"
олбце свободных членов н
identifier_name
my_optimisation.py
import numpy as np def app_products2optimisation(products): # вес P — x1, к --x2 # c = [-250,-210] #Функция цели 250x1+210x2 – уменьшение расходов на продуктовую корзину ; # A_ub = [[15,4]] #'1' жиры последовательно для Р и К # b_ub = [14] #'1' 15x1+4x2 <=14 – ограничение количества жира; # A_eq = [[150,200]] #'2' 150x1+200x2 =300 – ограничение количества калорий. # b_eq = [300] #'2' # print (linprog(c, A_ub, b_ub, A_eq, b_eq)) if not products: return [] n = len(products)-2 c = [] ub = [] eq = [] for i in range(0,n): c.append(products[i].default_price) ub.append(products[i].fat) eq.append(products[i].calories) i += 1 # Перехожу к столбцу свободных членов для уравнения меньше чем, в продуктах это вещь под назавнием Minimise Fat ub.append(products[i].fat) A_ub = np.array([ub]) c.append(products[i].default_price) i += 1 # Перехожу к столбцу свободных членов для уравнения больше чем, в продуктах это вещь под назавнием Get enough calories eq.append(products[i].calories) A_eq = np.array([eq]) A_eq = -1 * A_eq # Для > меняем знак всех элементов (потом написать в цикл автоматом по условию!) c = np.array([c]) A_eq = np.squeeze(A_eq) # Django мне создала списки двойного уровня вложенности, надо уменьшить это A_ub = np.squeeze(A_ub) c = np.squeeze(c) table = [A_ub, A_eq, c] table = np.asarray(table, dtype=float) b = np.identity(n+1) # создаю единичную матрицу # amount_columns = np.size(table,1) table = np.insert(table,n,b,axis=1) # вставляю единичную матрицу в таблицу перед столбцом с номером amount_columns-1, получается n+1, по столбцам, т.е. axis 1 print('np.size(table)',np.size(table)) print(table) #return type(table) result = minimise(table) result[n] = -1 * result[n] print(result) return result # return [1, 2, 3] def amount_rows(amount_constraints): amount_rows = amount_constraints+1 return amount_rows def amount_columns(amount_variables,amount_constraints): amount_columns = amount_variables+amount_constraints+2 return amount_columns def create_simplex_table(amount_variables,amount_constraints): #Создание двумерного массива r = amount_rows(amount_constraints) c = amount_columns(amount_variables,amount_constraints) empty_table = np.zeros((r, c)) return empty_table #Количество строк = кол-ву ограничений + целевая функция amount_constraints+1 #Количество столбцов = кол-ву переменных + кол-ву дополнительных переменных для приведения системы к каноническому виду + M (max/min) + Колонка свободных членов def input_to_list(equation): #Перевод в list equation = equation.split(',') if '>' in equation: text_index = equation.index('>') del equation[text_index] equation = [float(i) * -1 for i in equation] return equation if '<' in equation: text_index = equation.index('<') del equation[text_index] equation = [float(i) for i in equation] return equation def xi_names(table): # Создание названий переменных x1, x2, ..., xn amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 amount_columns = np.size(table,1) # Подсчет количества столбцов с помощью axis=1 xi = amount_columns - amount_rows -1 names = [] for i in range(xi): names.append('x' + str(i + 1)) return names def lines4constraints_available(filled_table): # Проверка, что в предпоследней строке нули, чтобы добавить ещё ограничение penultimate_row = filled_table[-2:-1] return (~penultimate_row.any(axis=1)).any() #The any method returns True if any value in the array is "truthy". # Nonzero numbers are considered True, and 0 is considered False. # By using the argument axis=1, the method is applied to each row. def add_constraint(table, equation): # Заполнение свободных строк для ограничений if lines4constraints_available(table): amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 amount_columns = np.size(table,1) # Подсчет количества столбцов с помощью axis=1 xi = amount_columns - amount_rows -1 # Количество переменных b = np.where(~table.any(axis=1))[0] # Поиск строк со всеми нулями j = b[0] # Номер первой строки со всеми нулями row = table[j, :] # Первая строка со всеми нулями equation = input_to_list(equation) i = 0 # Наполнение двумерного массива пока в выражении еще есть переменные while i < len(equation) - 1: # Переменные базиса записать в таблицу row[i] = equation[i] i += 1 row[-1] = equation[-1] #Колонка свободных членов row[xi + j] = 1 # Создание 1 для единичной матрицы справа базиса else: print('Свободных строк для ограничений больше не было предусмотрено, начните сначала или введите целевую функцию.') def line4objective_available(filled_table): # Проверка, есть ли нули в последней (и только последней) строке, чтобы вставить целевую функцию last_rows = np.array(filled_table[-2:]) empty = np.where(~last_rows.any(axis=1))[0] if np.array_equal(empty, np.array([1])): return True else: return False def add_objective(table, equation): # добавляет целевую функцию, если есть свободная строка в конце таблицы if line4objective_available(table): equation = [float(i) for i in equation.split(',')] amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 row = table[amount_rows - 1, :] i = 0 # пока в выражении еще есть переменные while i < len(equation)-1: # записать их в таблицу row[i] = equation[i] * -1 i += 1 row[-2] = 1 # Создание 1 для единичной матрицы справа базиса row[-1] = equation[-1] #Хранение значения необходимого бюджета else: print('Остались пустые сроки, введите ограничения или начните сначала.') def convert_min(filled_table): # Для минимизации последняя строка (целевая функция) умножается на -1 filled_table[-1] = -1 * filled_table[-1] return filled_table def check_bi_positifs(filled_table): # Проверка, что в столбце свободных членов не осталось отрицательных min_bi = min(filled_table[:-1,-1]) if min_bi >= 0: return False # Достигнут оптимум, переход к выводу else: return True # Необходимо пересчитать строку def check_cj0(filled_table): #Проверка условия: все ли элементы последней строки отрицательны, cj<=0 amount_conditions = np.size(filled_table,0) # Подсчет количества строк с помощью axis=0 max_cj = max(filled_table[amount_conditions-1,:-1]) # Выбор наибольшего элемента в слайсе [последняя строка, вся таблица без последнего столбца] # return (max_cj <= 0) # идентично if max_cj >= 0: return False #Переход к следующему шагу метода else: return True #Переход к выводу результата def neg_bi_index(filled_table): # Поиск номера строки с отрицательным свободным членом amount_conditions = np.size(filled_table,0)-1 # Подсчет количества строк с помощью axis=0 min_bi_row_number = np.argmin(filled_table[:-1,amount_conditions])# + 1 Возвращает индекс наменьшего элемента в слайсе [вся таблица без последней строки, последний столбец], добавляем 1 чтобы номер столбца был человекочитаемым return min_bi_row_number def column_choice(filled_table): #Выбор разрешающего столбца, cj amount_conditions = np.size(filled_table, 0) - 1 # Подсчет количества строк с помощью axis=0 min_cj_column_number = np.argmin(filled_table[amount_conditions, :-1]) #+ 1 Возвращает индекс наибольшего элемента в слайсе [последняя строка, вся таблица без последнего столбца], добавляем 1 чтобы номер столбца был человекочитаемым return min_cj_column_number def bi_to_positive(filled_table): division = [] # Разрешение двойственной задачи линейного программирования row_index = neg_bi_index(filled_table) min_in_row_column_number = np.argmin(filled_table[row_index,:-1]) #+1  Возвращает индекс наименьшего элемента в слайсе по номеру строки с отрицательным свободным членом, исключая последний столбец , добавляем 1 чтобы номер столбца был человекочитаемым col = filled_table[:-1, min_in_row_column_number] # все коэффициенты ограничений этого столбца
for i, b in zip(col, last_column): if i != 0 and b / i > 0: division.append(b / i) else: division.append(10000) index = division.index(min(division)) #наименьшее позитивное частное return [index,min_in_row_column_number] def row_choice(filled_table): if check_cj0(filled_table):#Надо поднимать ошибку, если не срабатывает!!!! c = column_choice(filled_table) #Номер разрешающего столбца в человеческом формате divided = [] r_column = filled_table[:-1, c - 1] # [вся таблица без последней строки, столбец r в машинном формате] last_column = filled_table[:-1, -1] for r, l in zip(r_column, last_column): if r > 0: divided.append(l/r) else: divided.append(100000) min_air_row_number = divided.index(min(divided)) #+1 #Номер разрешающей строки в человеческом формате return [min_air_row_number, c] def calc(chosen_row, chosen_column, source_table): #Пересчет элементов target_table = np.zeros_like(source_table, dtype=float) # Создание новой нулевой таблицы r = chosen_row #-1 # Номер разрешающей строки в машинном формате c = chosen_column #-1 # Номер разрешающего столбца в машинном формате pivot_row = source_table[r, :] # Разрешающая строка pivot_element = source_table[r, c] # Разрешающий элемент if pivot_element: e = 1 / pivot_element new_chosen_row = pivot_row * e # Делим все элементы разрешающей строки на разрешающий элемент for i in range(np.size(source_table, 0)): # количеств строк с помощью axis=0 if i != r: # Если текущая строка отличается от поворотной строки row = source_table[i, :] # Очередная строка p_c_el = source_table[i, c] # Элемент текущей строки, который в разрешающем столбце target_table[i, :] = list(row-new_chosen_row * p_c_el) # заменяем элементы очередной строки новой таблицы на вычисленные, # домножаем на уже посчитанные элементы разрешающей строки, чтобы не повторять вычисление target_table[r, :] = list(new_chosen_row) # Делим все элементы разрешающей строки на разрешающий элемент, заменяем элементы разрешающей строки на вычисленные return target_table else: print('Разрешающий элемент не позволяет провести пересчет.') def minimise(table, output='результаты'): # Обращается к функциям пересчета и выводит результаты table = convert_min(table) while check_bi_positifs(table): table = calc( bi_to_positive(table)[0], bi_to_positive(table)[1], table ) # Жордановы замены для негативных свободных членов, требуются в двойственном симплексе while check_cj0(table): table = calc( row_choice(table)[0], row_choice(table)[1], table ) # Жордановы замены для последней строки, коэффициентов при целевой функции amount_columns = np.size(table,1) # Подсчет количества столбцов с помощью axis=1 amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 var = amount_columns - amount_rows -1 i = 0 val = {} # Создание пустого словаря для хранения результатов работы алгоритма for i in range(var): # для солбцов переменных вне базиса, поиск числа в солбце и сопоставление числу результату в последнем столбце col = table[:, i] s = sum(col) m = max(col) if float(s) == float(m): loc = np.where(col == m)[0][0] val[xi_names(table)[i]] = table[loc, -1] else: val[xi_names(table)[i]] = 0 val['min'] = table[-1, -1] * -1 # для терминала результаты в виде словаря с ключами по номерам переменных x1,x2...xn и значением бюджета с ключом min val = list(val.values()) # для джанги результаты в виде list # return [1, 2, 3] if output == 'table': return table else: return val if __name__ == "__main__": st = create_simplex_table(2, 4) add_constraint(st,'2,5,>,30') add_constraint(st,'-3,5,>,5') add_constraint(st,'8,3,<,85') add_constraint(st,'-9,7,<,42') add_objective(st,'2,7,0') print(minimise(st)) print('-'*100) st = create_simplex_table(2,2) add_constraint(st,'15,4,<,14') add_constraint(st,'150,200,>,300') add_objective(st,'250,210,0') print(minimise(st)) print('-'*100) st = create_simplex_table(2,2) add_constraint(st,'1450,770,>,1100') add_constraint(st,'560,120,>,800') add_objective(st,'130,30,0') print(minimise(st)) print('-'*100) print('-'*100) a = np.array([ [0.,0.,0.,0.,0.,0.], [0.,0.,0.,0.,0.,0.], [0.,0.,0.,0.,0.,0.]]) assert np.array_equal(create_simplex_table(2,2),a),"ошибка создания nparray" test_table1 = np.array([ [4,6,1,0,0,120], [2,6,0,1,0,72], [0,1,0,0,1,10], [2,4,0,0,0,0]]) test_table2 = np.array([ [4,0,1,0,-6,60], [2,0,0,1,-6,12], [0,1,0,0,1,10], [2,0,0,0,-4,-40]]) test_table3 = np.array([ [0,0,1,-2,6,36], [1,0,0,0.5,-3,6], [0,1,0,0,1,10], [0,0,0,-1,2,-52]]) test_table4 = np.array([ [0,0,1/6,-1/3,1,6], [1,0,0.5,-0.5,0,24], [0,1,-1/6,1/3,0,4], [0,0,-1/3,-1/3,0,-64]]) assert check_cj0(test_table1)==False,"ошибка проверки условия cj<=0" assert check_cj0(test_table2)==False,"ошибка проверки условия cj<=0" assert check_cj0(test_table3)==False,"ошибка проверки условия cj<=0" assert column_choice(test_table1)==2,"ошибка выбора разрешающего столбца" assert np.array_equal(calc(3-1,2-1,test_table1),test_table2),"ошибка пересчета" # везде -1, использует индекс в машинном формате assert np.array_equal(calc(2-1,1-1,test_table2),test_table3),"ошибка пересчета" assert np.allclose(calc(1-1,5-1,test_table3),test_table4),"ошибка пересчета"
last_column = filled_table[:-1,-1]
random_line_split
my_optimisation.py
import numpy as np def app_products2optimisation(products): # вес P — x1, к --x2 # c = [-250,-210] #Функция цели 250x1+210x2 – уменьшение расходов на продуктовую корзину ; # A_ub = [[15,4]] #'1' жиры последовательно для Р и К # b_ub = [14] #'1' 15x1+4x2 <=14 – ограничение количества жира; # A_eq = [[150,200]] #'2' 150x1+200x2 =300 – ограничение количества калорий. # b_eq = [300] #'2' # print (linprog(c, A_ub, b_ub, A_eq, b_eq)) if not products: return [] n = len(products)-2 c = [] ub = [] eq = [] for i in range(0,n): c.append(products[i].default_price) ub.append(products[i].fat) eq.append(products[i].calories) i += 1 # Перехожу к столбцу свободных членов для уравнения меньше чем, в продуктах это вещь под назавнием Minimise Fat ub.append(products[i].fat) A_ub = np.array([ub]) c.append(products[i].default_price) i += 1 # Перехожу к столбцу свободных членов для уравнения больше чем, в продуктах это вещь под назавнием Get enough calories eq.append(products[i].calories) A_eq = np.array([eq]) A_eq = -1 * A_eq # Для > меняем знак всех элементов (потом написать в цикл автоматом по условию!) c = np.array([c]) A_eq = np.squeeze(A_eq) # Django мне создала списки двойного уровня вложенности, надо уменьшить это A_ub = np.squeeze(A_ub) c = np.squeeze(c) table = [A_ub, A_eq, c] table = np.asarray(table, dtype=float) b = np.identity(n+1) # создаю единичную матрицу # amount_columns = np.size(table,1) table = np.insert(table,n,b,axis=1) # вставляю единичную матрицу в таблицу перед столбцом с номером amount_columns-1, получается n+1, по столбцам, т.е. axis 1 print('np.size(table)',np.size(table)) print(table) #return type(table) result = minimise(table) result[n] = -1 * result[n] print(result) return result # return [1, 2, 3] def amount_rows(amount_constraints): amount_rows = amount_constraints+1 return amount_rows def amount_columns(amount_variables,amount_constraints): amount_columns = amount_variables+amount_constraints+2 return amount_columns def create_simplex_table(amount_variables,amount_constraints): #Создание двумерного массива r = amount_rows(amount_constraints) c = amount_columns(amount_variables,amount_constraints) empty_table = np.zeros((r, c)) return empty_table #Количество строк = кол-ву ограничений + целевая функция amount_constraints+1 #Количество столбцов = кол-ву переменных + кол-ву дополнительных переменных для приведения системы к каноническому виду + M (max/min) + Колонка свободных членов def input_to_list(equation): #Перевод в list equation = equation.split(',') if '>' in equation: text_index = equation.index('>') del equation[text_index] equation = [float(i) * -1 for i in equation] return equation if '<' in equation: text_index = equation.index('<') del equation[text_index] equation = [float(i) for i in equation] return equation def xi_names(table): # Создание названий переменных x1, x2, ..., xn amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 amount_columns = np.size(table,1) # Подсчет количества столбцов с помощью axis=1 xi = amount_columns - amount_rows -1 names = [] for i in range(xi): names.append('x' + str(i + 1)) return names def lines4constraints_available(filled_table): # Проверка, что в предпоследней строке нули, чтобы добавить ещё ограничение penultimate_row = filled_table[-2:-1] return (~penultimate_row.any(axis=1)).any() #The any method returns True if any value in the array is "truthy". # Nonzero numbers are considered True, and 0 is considered False. # By using the argument axis=1, the method is applied to each row. def add_constraint(table, equation): # Заполнение свободных строк для ограничений if lines4constraints_available(table): amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 amount_columns = np.size(table,1) # Подсчет количества столбцов с помощью axis=1 xi = amount_columns - amount_rows -1 # Количество переменных b = np.where(~table.any(axis=1))[0] # Поиск строк со всеми нулями j = b[0] # Номер первой строки со всеми нулями row = table[j, :] # Первая строка со всеми нулями equation = input_to_list(equation) i = 0 # Наполнение двумерного массива пока в выражении еще есть переменные while i < len(equation) - 1: # Переменные базиса записать в таблицу row[i] = equation[i] i += 1 row[-1] = equation[-1] #Колонка свободных членов row[xi + j] = 1 # Создание 1 для единичной матрицы справа базиса else: print('Свободных строк для ограничений больше не было предусмотрено, начните сначала или введите целевую функцию.') def line4objective_available(filled_table): # Проверка, есть ли нули в последней (и только последней) строке, чтобы вставить целевую функцию last_rows = np.array(filled_table[-2:]) empty = np.where(~last_rows.any(axis=1))[0] if np.array_equal(empty, np.array([1])): return True else: return False def add_objective(table, equation): # добавляет целевую функцию, если есть свободная строка в конце таблицы if line4objective_available(table): equation = [float(i) for i in equation.split(',')] amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 row = table[amount_rows - 1, :] i = 0 # пока в выражении еще есть переменные while i < len(equation)-1: # записать их в таблицу row[i] = equation[i] * -1 i += 1 row[-2] = 1 # Создание 1 для единичной матрицы справа базиса row[-1] = equation[-1] #Хранение значения необходимого бюджета else: print('Остались пустые сроки, введите ограничения или начните сначала.') def convert_min(filled_table): # Для минимизации последняя строка (целевая функция) умножается на -1 filled_table[-1] = -1 * filled_table[-1] return filled_table def check_bi_positifs(filled_table): # Проверка, что в столбце свободных членов не осталось отрицательных min_bi = min(filled_table[:-1,-1]) if min_bi >= 0: return False # Достигнут оптимум, переход к выводу else: return True # Необходимо пересчитать строку def check_cj0(filled_table): #Проверка условия: все ли элементы последней строки отрицательны, cj<=0 amount_conditions = np.size(filled_table,0) # Подсчет количества строк с помощью axis=0 max_cj = max(filled_table[amount_conditions-1,:-1]) # Выбор наибольшего элемента в слайсе [последняя строка, вся таблица без последнего столбца]
ditions, :-1]) #+ 1 Возвращает индекс наибольшего элемента в слайсе [последняя строка, вся таблица без последнего столбца], добавляем 1 чтобы номер столбца был человекочитаемым return min_cj_column_number def bi_to_positive(filled_table): division = [] # Разрешение двойственной задачи линейного программирования row_index = neg_bi_index(filled_table) min_in_row_column_number = np.argmin(filled_table[row_index,:-1]) #+1  Возвращает индекс наименьшего элемента в слайсе по номеру строки с отрицательным свободным членом, исключая последний столбец , добавляем 1 чтобы номер столбца был человекочитаемым col = filled_table[:-1, min_in_row_column_number] # все коэффициенты ограничений этого столбца last_column = filled_table[:-1,-1] for i, b in zip(col, last_column): if i != 0 and b / i > 0: division.append(b / i) else: division.append(10000) index = division.index(min(division)) #наименьшее позитивное частное return [index,min_in_row_column_number] def row_choice(filled_table): if check_cj0(filled_table):#Надо поднимать ошибку, если не срабатывает!!!! c = column_choice(filled_table) #Номер разрешающего столбца в человеческом формате divided = [] r_column = filled_table[:-1, c - 1] # [вся таблица без последней строки, столбец r в машинном формате] last_column = filled_table[:-1, -1] for r, l in zip(r_column, last_column): if r > 0: divided.append(l/r) else: divided.append(100000) min_air_row_number = divided.index(min(divided)) #+1 #Номер разрешающей строки в человеческом формате return [min_air_row_number, c] def calc(chosen_row, chosen_column, source_table): #Пересчет элементов target_table = np.zeros_like(source_table, dtype=float) # Создание новой нулевой таблицы r = chosen_row #-1 # Номер разрешающей строки в машинном формате c = chosen_column #-1 # Номер разрешающего столбца в машинном формате pivot_row = source_table[r, :] # Разрешающая строка pivot_element = source_table[r, c] # Разрешающий элемент if pivot_element: e = 1 / pivot_element new_chosen_row = pivot_row * e # Делим все элементы разрешающей строки на разрешающий элемент for i in range(np.size(source_table, 0)): # количеств строк с помощью axis=0 if i != r: # Если текущая строка отличается от поворотной строки row = source_table[i, :] # Очередная строка p_c_el = source_table[i, c] # Элемент текущей строки, который в разрешающем столбце target_table[i, :] = list(row-new_chosen_row * p_c_el) # заменяем элементы очередной строки новой таблицы на вычисленные, # домножаем на уже посчитанные элементы разрешающей строки, чтобы не повторять вычисление target_table[r, :] = list(new_chosen_row) # Делим все элементы разрешающей строки на разрешающий элемент, заменяем элементы разрешающей строки на вычисленные return target_table else: print('Разрешающий элемент не позволяет провести пересчет.') def minimise(table, output='результаты'): # Обращается к функциям пересчета и выводит результаты table = convert_min(table) while check_bi_positifs(table): table = calc( bi_to_positive(table)[0], bi_to_positive(table)[1], table ) # Жордановы замены для негативных свободных членов, требуются в двойственном симплексе while check_cj0(table): table = calc( row_choice(table)[0], row_choice(table)[1], table ) # Жордановы замены для последней строки, коэффициентов при целевой функции amount_columns = np.size(table,1) # Подсчет количества столбцов с помощью axis=1 amount_rows = np.size(table,0) # Подсчет количества строк с помощью axis=0 var = amount_columns - amount_rows -1 i = 0 val = {} # Создание пустого словаря для хранения результатов работы алгоритма for i in range(var): # для солбцов переменных вне базиса, поиск числа в солбце и сопоставление числу результату в последнем столбце col = table[:, i] s = sum(col) m = max(col) if float(s) == float(m): loc = np.where(col == m)[0][0] val[xi_names(table)[i]] = table[loc, -1] else: val[xi_names(table)[i]] = 0 val['min'] = table[-1, -1] * -1 # для терминала результаты в виде словаря с ключами по номерам переменных x1,x2...xn и значением бюджета с ключом min val = list(val.values()) # для джанги результаты в виде list # return [1, 2, 3] if output == 'table': return table else: return val if __name__ == "__main__": st = create_simplex_table(2, 4) add_constraint(st,'2,5,>,30') add_constraint(st,'-3,5,>,5') add_constraint(st,'8,3,<,85') add_constraint(st,'-9,7,<,42') add_objective(st,'2,7,0') print(minimise(st)) print('-'*100) st = create_simplex_table(2,2) add_constraint(st,'15,4,<,14') add_constraint(st,'150,200,>,300') add_objective(st,'250,210,0') print(minimise(st)) print('-'*100) st = create_simplex_table(2,2) add_constraint(st,'1450,770,>,1100') add_constraint(st,'560,120,>,800') add_objective(st,'130,30,0') print(minimise(st)) print('-'*100) print('-'*100) a = np.array([ [0.,0.,0.,0.,0.,0.], [0.,0.,0.,0.,0.,0.], [0.,0.,0.,0.,0.,0.]]) assert np.array_equal(create_simplex_table(2,2),a),"ошибка создания nparray" test_table1 = np.array([ [4,6,1,0,0,120], [2,6,0,1,0,72], [0,1,0,0,1,10], [2,4,0,0,0,0]]) test_table2 = np.array([ [4,0,1,0,-6,60], [2,0,0,1,-6,12], [0,1,0,0,1,10], [2,0,0,0,-4,-40]]) test_table3 = np.array([ [0,0,1,-2,6,36], [1,0,0,0.5,-3,6], [0,1,0,0,1,10], [0,0,0,-1,2,-52]]) test_table4 = np.array([ [0,0,1/6,-1/3,1,6], [1,0,0.5,-0.5,0,24], [0,1,-1/6,1/3,0,4], [0,0,-1/3,-1/3,0,-64]]) assert check_cj0(test_table1)==False,"ошибка проверки условия cj<=0" assert check_cj0(test_table2)==False,"ошибка проверки условия cj<=0" assert check_cj0(test_table3)==False,"ошибка проверки условия cj<=0" assert column_choice(test_table1)==2,"ошибка выбора разрешающего столбца" assert np.array_equal(calc(3-1,2-1,test_table1),test_table2),"ошибка пересчета" # везде -1, использует индекс в машинном формате assert np.array_equal(calc(2-1,1-1,test_table2),test_table3),"ошибка пересчета" assert np.allclose(calc(1-1,5-1,test_table3),test_table4),"ошибка пересчета"
# return (max_cj <= 0) # идентично if max_cj >= 0: return False #Переход к следующему шагу метода else: return True #Переход к выводу результата def neg_bi_index(filled_table): # Поиск номера строки с отрицательным свободным членом amount_conditions = np.size(filled_table,0)-1 # Подсчет количества строк с помощью axis=0 min_bi_row_number = np.argmin(filled_table[:-1,amount_conditions])# + 1 Возвращает индекс наменьшего элемента в слайсе [вся таблица без последней строки, последний столбец], добавляем 1 чтобы номер столбца был человекочитаемым return min_bi_row_number def column_choice(filled_table): #Выбор разрешающего столбца, cj amount_conditions = np.size(filled_table, 0) - 1 # Подсчет количества строк с помощью axis=0 min_cj_column_number = np.argmin(filled_table[amount_con
identifier_body
soda.js
/* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS203: Remove `|| {}` from converted for-own loops * DS205: Consider reworking code to avoid use of IIFEs * DS207: Consider shorter variations of null checks * DS208: Avoid top-level this * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ // soda.coffee -- chained, evented, buzzworded library for accessing SODA via JS. // sodaOpts options: // username: https basic auth username // password: https basic auth password // apiToken: socrata api token // // emitterOpts: options to override EventEmitter2 declaration options // TODO: // * we're inconsistent about validating query correctness. do we continue with catch-what-we-can, // or do we just back off and leave all failures to the api to return? let str; const eelib = require('eventemitter2'); const EventEmitter = eelib.EventEmitter2 || eelib; const httpClient = require('superagent'); // internal util funcs const isString = obj => typeof obj === 'string'; const isArray = obj => Array.isArray(obj); const isNumber = obj => !isNaN(parseFloat(obj)); const extend = function(target, ...sources) { for (let source of Array.from(sources)) { for (let k in source) { const v = source[k]; target[k] = v; } } return null; }; // it's really, really, really stupid that i have to solve this problem here const toBase64 = (() => { if (typeof Buffer !== 'undefined' && Buffer !== null) { return str => new Buffer(str).toString('base64'); } else { // adapted/modified from https://github.com/rwz/base64.coffee const base64Lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split(''); const rawToBase64 = typeof btoa !== 'undefined' && btoa !== null ? btoa : function(str) { const result = []; let i = 0; while (i < str.length) { const chr1 = str.charCodeAt(i++); const chr2 = str.charCodeAt(i++); const chr3 = str.charCodeAt(i++); if (Math.max(chr1, chr2, chr3) > 0xFF) { throw new Error('Invalid character!'); } const enc1 = chr1 >> 2; const enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); let enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); let enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = (enc4 = 64); } else if (isNaN(chr3)) { enc4 = 64; } result.push(base64Lookup[enc1]); result.push(base64Lookup[enc2]); result.push(base64Lookup[enc3]); result.push(base64Lookup[enc4]); } return result.join(''); }; return str => rawToBase64(unescape(encodeURIComponent(str))); } })(); const handleLiteral = function(literal) { if (isString(literal)) { return `'${literal}'`; } else if (isNumber(literal)) { // TODO: possibly ensure number cleanliness for sending to the api? sci not? return literal; } else { return literal; } }; const handleOrder = function(order) { if (/( asc$| desc$)/i.test(order)) { return order; } else { return order + ' asc'; } }; const addExpr = (target, args) => Array.from(args).map((arg) => isString(arg) ? target.push(arg) : (() => { const result = []; for (let k in arg) { const v = arg[k]; result.push(target.push(`${k} = ${handleLiteral(v)}`)); } return result; })()); // extern util funcs // convenience functions for building where clauses, if so desired const expr = { and(...clauses) { return (Array.from(clauses).map((clause) => `(${clause})`)).join(' and '); }, or(...clauses) { return (Array.from(clauses).map((clause) => `(${clause})`)).join(' or '); }, gt(column, literal) { return `${column} > ${handleLiteral(literal)}`; }, gte(column, literal) { return `${column} >= ${handleLiteral(literal)}`; }, lt(column, literal) { return `${column} < ${handleLiteral(literal)}`; }, lte(column, literal) { return `${column} <= ${handleLiteral(literal)}`; }, eq(column, literal) { return `${column} = ${handleLiteral(literal)}`; } }; // serialize object to querystring const toQuerystring = function(obj) { str = []; for (let key of Object.keys(obj || {})) { const val = obj[key]; str.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); } return str.join('&'); }; class Connection { constructor(dataSite, sodaOpts)
getDefaultHandler() { // instance variable for easy chaining let emitter, handler; this.emitter = (emitter = new EventEmitter(this.emitterOpts)); // return the handler return handler = function(error, response) { // TODO: possibly more granular handling? if (response.ok) { if (response.accepted) { // handle 202 by remaking request. inform of possible progress. emitter.emit('progress', response.body); setTimeout((function() { return this.consumer.networker(opts)(handler); }), 5000); } else { emitter.emit('success', response.body); } } else { emitter.emit('error', response.body != null ? response.body : response.text); } // just emit the raw superagent obj if they just want complete event return emitter.emit('complete', response); }; } } // main class class Consumer { constructor(dataSite, sodaOpts) { this.dataSite = dataSite; if (sodaOpts == null) { sodaOpts = {}; } this.sodaOpts = sodaOpts; this.connection = new Connection(this.dataSite, this.sodaOpts); } query() { return new Query(this); } getDataset(id) { let emitter; return emitter = new EventEmitter(this.emitterOpts); } } // TODO: implement me // Producer class class Producer { constructor(dataSite, sodaOpts) { this.dataSite = dataSite; if (sodaOpts == null) { sodaOpts = {}; } this.sodaOpts = sodaOpts; this.connection = new Connection(this.dataSite, this.sodaOpts); } operation() { return new Operation(this); } } class Operation { constructor(producer) { this.producer = producer; } withDataset(datasetId) { this._datasetId = datasetId; return this; } // truncate the entire dataset truncate() { const opts = {method: 'delete'}; opts.path = `/resource/${this._datasetId}`; return this._exec(opts); } // add a new row - explicitly avoids upserting (updating/deleting existing rows) add(data) { const opts = {method: 'post'}; opts.path = `/resource/${this._datasetId}`; const _data = JSON.parse(JSON.stringify(data)); delete _data[':id']; delete _data[':delete']; for (let obj of Array.from(_data)) { delete obj[':id']; delete obj[':delete']; } return this._exec(opts, _data); } // modify existing rows delete(id) { const opts = {method: 'delete'}; opts.path = `/resource/${this._datasetId}/${id}`; return this._exec(opts); } update(id, data) { const opts = {method: 'post'}; opts.path = `/resource/${this._datasetId}/${id}`; return this._exec(opts, data); } replace(id, data) { const opts = {method: 'put'}; opts.path = `/resource/${this._datasetId}/${id}`; return this._exec(opts, data); } // add objects, update if existing, delete if :delete=true upsert(data) { const opts = {method: 'post'}; opts.path = `/resource/${this._datasetId}`; return this._exec(opts, data); } _exec(opts, data) { if (this._datasetId == null) { throw new Error('no dataset given to work against!'); } this.producer.connection.networker(opts, data)(); return this.producer.connection.emitter; } } // querybuilder class class Query { constructor(consumer) { this.consumer = consumer; this._select = []; this._where = []; this._group = []; this._having = []; this._order = []; this._offset = (this._limit = (this._q = null)); } withDataset(datasetId) { this._datasetId = datasetId; return this; } // for passing in a fully formed soql query. all other params will be ignored soql(query) { this._soql = query; return this; } select(...selects) { for (let select of Array.from(selects)) { this._select.push(select); } return this; } // args: ('clause', [...]) // ({ column: value1, columnb: value2 }, [...]]) // multiple calls are assumed to be and-chained where(...args) { addExpr(this._where, args); return this; } having(...args) { addExpr(this._having, args); return this; } group(...groups) { for (let group of Array.from(groups)) { this._group.push(group); } return this; } // args: ("column direction", ["column direction", [...]]) order(...orders) { for (let order of Array.from(orders)) { this._order.push(handleOrder(order)); } return this; } offset(offset) { this._offset = offset; return this; } limit(limit) { this._limit = limit; return this; } q(q) { this._q = q; return this; } getOpts() { const opts = {method: 'get'}; if (this._datasetId == null) { throw new Error('no dataset given to work against!'); } opts.path = `/resource/${this._datasetId}.json`; const queryComponents = this._buildQueryComponents(); opts.query = {}; for (let k in queryComponents) { const v = queryComponents[k]; opts.query['$' + k] = v; } return opts; } getURL() { const opts = this.getOpts(); const query = toQuerystring(opts.query); return `https://${this.consumer.dataSite}${opts.path}` + (query ? `?${query}` : ""); } getRows() { const opts = this.getOpts(); this.consumer.connection.networker(opts)(); return this.consumer.connection.emitter; } _buildQueryComponents() { const query = {}; if (this._soql != null) { query.query = this._soql; } else { if (this._select.length > 0) { query.select = this._select.join(', '); } if (this._where.length > 0) { query.where = expr.and.apply(this, this._where); } if (this._group.length > 0) { query.group = this._group.join(', '); } if (this._having.length > 0) { if (!(this._group.length > 0)) { throw new Error('Having provided without group by!'); } query.having = expr.and.apply(this, this._having); } if (this._order.length > 0) { query.order = this._order.join(', '); } if (isNumber(this._offset)) { query.offset = this._offset; } if (isNumber(this._limit)) { query.limit = this._limit; } if (this._q) { query.q = this._q; } } return query; } } class Dataset { constructor(data, client) { this.data = data; this.client = client; } } // TODO: implement me extend(typeof exports !== 'undefined' && exports !== null ? exports : this.soda, { Consumer, Producer, expr, // exported for testing reasons _internal: { Connection, Query, Operation, util: { toBase64, handleLiteral, handleOrder } } } );
{ this.dataSite = dataSite; if (sodaOpts == null) { sodaOpts = {}; } this.sodaOpts = sodaOpts; if (!/^[a-z0-9-_.]+(:[0-9]+)?$/i.test(this.dataSite)) { throw new Error('dataSite does not appear to be valid! Please supply a domain name, eg data.seattle.gov'); } // options passed directly into EventEmitter2 construction this.emitterOpts = this.sodaOpts.emitterOpts != null ? this.sodaOpts.emitterOpts : { wildcard: true, delimiter: '.', maxListeners: 15 }; this.networker = function(opts, data) { const url = `https://${this.dataSite}${opts.path}`; const client = httpClient(opts.method, url); if (data != null) { client.set('Accept', "application/json"); } if (data != null) { client.set('Content-type', "application/json"); } if (this.sodaOpts.apiToken != null) { client.set('X-App-Token', this.sodaOpts.apiToken); } if ((this.sodaOpts.username != null) && (this.sodaOpts.password != null)) { client.set('Authorization', "Basic " + toBase64(`${this.sodaOpts.username}:${this.sodaOpts.password}`)); } if (this.sodaOpts.accessToken != null) { client.set('Authorization', "OAuth " + accessToken); } if (opts.query != null) { client.query(opts.query); } if (data != null) { client.send(data); } return responseHandler => client.end(responseHandler || this.getDefaultHandler()); }; }
identifier_body
soda.js
/* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS203: Remove `|| {}` from converted for-own loops * DS205: Consider reworking code to avoid use of IIFEs * DS207: Consider shorter variations of null checks * DS208: Avoid top-level this * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ // soda.coffee -- chained, evented, buzzworded library for accessing SODA via JS. // sodaOpts options: // username: https basic auth username // password: https basic auth password // apiToken: socrata api token // // emitterOpts: options to override EventEmitter2 declaration options // TODO: // * we're inconsistent about validating query correctness. do we continue with catch-what-we-can, // or do we just back off and leave all failures to the api to return? let str; const eelib = require('eventemitter2'); const EventEmitter = eelib.EventEmitter2 || eelib; const httpClient = require('superagent'); // internal util funcs const isString = obj => typeof obj === 'string'; const isArray = obj => Array.isArray(obj); const isNumber = obj => !isNaN(parseFloat(obj)); const extend = function(target, ...sources) { for (let source of Array.from(sources)) { for (let k in source) { const v = source[k]; target[k] = v; } } return null; }; // it's really, really, really stupid that i have to solve this problem here const toBase64 = (() => { if (typeof Buffer !== 'undefined' && Buffer !== null) { return str => new Buffer(str).toString('base64'); } else { // adapted/modified from https://github.com/rwz/base64.coffee const base64Lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split(''); const rawToBase64 = typeof btoa !== 'undefined' && btoa !== null ? btoa : function(str) { const result = []; let i = 0; while (i < str.length) { const chr1 = str.charCodeAt(i++); const chr2 = str.charCodeAt(i++); const chr3 = str.charCodeAt(i++); if (Math.max(chr1, chr2, chr3) > 0xFF) { throw new Error('Invalid character!'); } const enc1 = chr1 >> 2; const enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); let enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); let enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = (enc4 = 64); } else if (isNaN(chr3)) { enc4 = 64; } result.push(base64Lookup[enc1]); result.push(base64Lookup[enc2]); result.push(base64Lookup[enc3]); result.push(base64Lookup[enc4]); } return result.join(''); }; return str => rawToBase64(unescape(encodeURIComponent(str))); } })(); const handleLiteral = function(literal) { if (isString(literal)) { return `'${literal}'`; } else if (isNumber(literal)) { // TODO: possibly ensure number cleanliness for sending to the api? sci not? return literal; } else { return literal; } }; const handleOrder = function(order) { if (/( asc$| desc$)/i.test(order)) { return order; } else { return order + ' asc'; } }; const addExpr = (target, args) => Array.from(args).map((arg) => isString(arg) ? target.push(arg) : (() => { const result = []; for (let k in arg) { const v = arg[k]; result.push(target.push(`${k} = ${handleLiteral(v)}`)); } return result; })()); // extern util funcs // convenience functions for building where clauses, if so desired const expr = { and(...clauses) { return (Array.from(clauses).map((clause) => `(${clause})`)).join(' and '); }, or(...clauses) { return (Array.from(clauses).map((clause) => `(${clause})`)).join(' or '); }, gt(column, literal) { return `${column} > ${handleLiteral(literal)}`; }, gte(column, literal) { return `${column} >= ${handleLiteral(literal)}`; }, lt(column, literal) { return `${column} < ${handleLiteral(literal)}`; }, lte(column, literal) { return `${column} <= ${handleLiteral(literal)}`; }, eq(column, literal) { return `${column} = ${handleLiteral(literal)}`; } }; // serialize object to querystring const toQuerystring = function(obj) { str = []; for (let key of Object.keys(obj || {})) { const val = obj[key]; str.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); } return str.join('&'); }; class Connection { constructor(dataSite, sodaOpts) { this.dataSite = dataSite; if (sodaOpts == null) { sodaOpts = {}; } this.sodaOpts = sodaOpts; if (!/^[a-z0-9-_.]+(:[0-9]+)?$/i.test(this.dataSite)) { throw new Error('dataSite does not appear to be valid! Please supply a domain name, eg data.seattle.gov'); } // options passed directly into EventEmitter2 construction this.emitterOpts = this.sodaOpts.emitterOpts != null ? this.sodaOpts.emitterOpts : { wildcard: true, delimiter: '.', maxListeners: 15 }; this.networker = function(opts, data) { const url = `https://${this.dataSite}${opts.path}`; const client = httpClient(opts.method, url); if (data != null) { client.set('Accept', "application/json"); } if (data != null) { client.set('Content-type', "application/json"); } if (this.sodaOpts.apiToken != null) { client.set('X-App-Token', this.sodaOpts.apiToken); } if ((this.sodaOpts.username != null) && (this.sodaOpts.password != null)) { client.set('Authorization', "Basic " + toBase64(`${this.sodaOpts.username}:${this.sodaOpts.password}`)); } if (this.sodaOpts.accessToken != null) { client.set('Authorization', "OAuth " + accessToken); } if (opts.query != null) { client.query(opts.query); } if (data != null) { client.send(data); } return responseHandler => client.end(responseHandler || this.getDefaultHandler()); }; } getDefaultHandler() { // instance variable for easy chaining let emitter, handler; this.emitter = (emitter = new EventEmitter(this.emitterOpts)); // return the handler return handler = function(error, response) { // TODO: possibly more granular handling? if (response.ok) { if (response.accepted) { // handle 202 by remaking request. inform of possible progress. emitter.emit('progress', response.body); setTimeout((function() { return this.consumer.networker(opts)(handler); }), 5000); } else { emitter.emit('success', response.body); } } else { emitter.emit('error', response.body != null ? response.body : response.text); } // just emit the raw superagent obj if they just want complete event return emitter.emit('complete', response); }; } } // main class class Consumer { constructor(dataSite, sodaOpts) { this.dataSite = dataSite; if (sodaOpts == null) { sodaOpts = {}; } this.sodaOpts = sodaOpts; this.connection = new Connection(this.dataSite, this.sodaOpts); } query() { return new Query(this); } getDataset(id) { let emitter; return emitter = new EventEmitter(this.emitterOpts); } } // TODO: implement me // Producer class class Producer { constructor(dataSite, sodaOpts) { this.dataSite = dataSite; if (sodaOpts == null) { sodaOpts = {}; } this.sodaOpts = sodaOpts; this.connection = new Connection(this.dataSite, this.sodaOpts); } operation() { return new Operation(this); } } class Operation { constructor(producer) { this.producer = producer; } withDataset(datasetId) { this._datasetId = datasetId; return this; } // truncate the entire dataset truncate() { const opts = {method: 'delete'}; opts.path = `/resource/${this._datasetId}`; return this._exec(opts); } // add a new row - explicitly avoids upserting (updating/deleting existing rows) add(data) { const opts = {method: 'post'}; opts.path = `/resource/${this._datasetId}`; const _data = JSON.parse(JSON.stringify(data)); delete _data[':id']; delete _data[':delete']; for (let obj of Array.from(_data)) { delete obj[':id']; delete obj[':delete']; } return this._exec(opts, _data); } // modify existing rows delete(id) { const opts = {method: 'delete'}; opts.path = `/resource/${this._datasetId}/${id}`; return this._exec(opts); } update(id, data) { const opts = {method: 'post'}; opts.path = `/resource/${this._datasetId}/${id}`; return this._exec(opts, data); }
(id, data) { const opts = {method: 'put'}; opts.path = `/resource/${this._datasetId}/${id}`; return this._exec(opts, data); } // add objects, update if existing, delete if :delete=true upsert(data) { const opts = {method: 'post'}; opts.path = `/resource/${this._datasetId}`; return this._exec(opts, data); } _exec(opts, data) { if (this._datasetId == null) { throw new Error('no dataset given to work against!'); } this.producer.connection.networker(opts, data)(); return this.producer.connection.emitter; } } // querybuilder class class Query { constructor(consumer) { this.consumer = consumer; this._select = []; this._where = []; this._group = []; this._having = []; this._order = []; this._offset = (this._limit = (this._q = null)); } withDataset(datasetId) { this._datasetId = datasetId; return this; } // for passing in a fully formed soql query. all other params will be ignored soql(query) { this._soql = query; return this; } select(...selects) { for (let select of Array.from(selects)) { this._select.push(select); } return this; } // args: ('clause', [...]) // ({ column: value1, columnb: value2 }, [...]]) // multiple calls are assumed to be and-chained where(...args) { addExpr(this._where, args); return this; } having(...args) { addExpr(this._having, args); return this; } group(...groups) { for (let group of Array.from(groups)) { this._group.push(group); } return this; } // args: ("column direction", ["column direction", [...]]) order(...orders) { for (let order of Array.from(orders)) { this._order.push(handleOrder(order)); } return this; } offset(offset) { this._offset = offset; return this; } limit(limit) { this._limit = limit; return this; } q(q) { this._q = q; return this; } getOpts() { const opts = {method: 'get'}; if (this._datasetId == null) { throw new Error('no dataset given to work against!'); } opts.path = `/resource/${this._datasetId}.json`; const queryComponents = this._buildQueryComponents(); opts.query = {}; for (let k in queryComponents) { const v = queryComponents[k]; opts.query['$' + k] = v; } return opts; } getURL() { const opts = this.getOpts(); const query = toQuerystring(opts.query); return `https://${this.consumer.dataSite}${opts.path}` + (query ? `?${query}` : ""); } getRows() { const opts = this.getOpts(); this.consumer.connection.networker(opts)(); return this.consumer.connection.emitter; } _buildQueryComponents() { const query = {}; if (this._soql != null) { query.query = this._soql; } else { if (this._select.length > 0) { query.select = this._select.join(', '); } if (this._where.length > 0) { query.where = expr.and.apply(this, this._where); } if (this._group.length > 0) { query.group = this._group.join(', '); } if (this._having.length > 0) { if (!(this._group.length > 0)) { throw new Error('Having provided without group by!'); } query.having = expr.and.apply(this, this._having); } if (this._order.length > 0) { query.order = this._order.join(', '); } if (isNumber(this._offset)) { query.offset = this._offset; } if (isNumber(this._limit)) { query.limit = this._limit; } if (this._q) { query.q = this._q; } } return query; } } class Dataset { constructor(data, client) { this.data = data; this.client = client; } } // TODO: implement me extend(typeof exports !== 'undefined' && exports !== null ? exports : this.soda, { Consumer, Producer, expr, // exported for testing reasons _internal: { Connection, Query, Operation, util: { toBase64, handleLiteral, handleOrder } } } );
replace
identifier_name
soda.js
/* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS203: Remove `|| {}` from converted for-own loops * DS205: Consider reworking code to avoid use of IIFEs * DS207: Consider shorter variations of null checks * DS208: Avoid top-level this * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ // soda.coffee -- chained, evented, buzzworded library for accessing SODA via JS. // sodaOpts options: // username: https basic auth username // password: https basic auth password // apiToken: socrata api token // // emitterOpts: options to override EventEmitter2 declaration options // TODO: // * we're inconsistent about validating query correctness. do we continue with catch-what-we-can, // or do we just back off and leave all failures to the api to return? let str; const eelib = require('eventemitter2'); const EventEmitter = eelib.EventEmitter2 || eelib; const httpClient = require('superagent'); // internal util funcs const isString = obj => typeof obj === 'string'; const isArray = obj => Array.isArray(obj); const isNumber = obj => !isNaN(parseFloat(obj)); const extend = function(target, ...sources) { for (let source of Array.from(sources)) { for (let k in source) { const v = source[k]; target[k] = v; } } return null; }; // it's really, really, really stupid that i have to solve this problem here const toBase64 = (() => { if (typeof Buffer !== 'undefined' && Buffer !== null) { return str => new Buffer(str).toString('base64'); } else
})(); const handleLiteral = function(literal) { if (isString(literal)) { return `'${literal}'`; } else if (isNumber(literal)) { // TODO: possibly ensure number cleanliness for sending to the api? sci not? return literal; } else { return literal; } }; const handleOrder = function(order) { if (/( asc$| desc$)/i.test(order)) { return order; } else { return order + ' asc'; } }; const addExpr = (target, args) => Array.from(args).map((arg) => isString(arg) ? target.push(arg) : (() => { const result = []; for (let k in arg) { const v = arg[k]; result.push(target.push(`${k} = ${handleLiteral(v)}`)); } return result; })()); // extern util funcs // convenience functions for building where clauses, if so desired const expr = { and(...clauses) { return (Array.from(clauses).map((clause) => `(${clause})`)).join(' and '); }, or(...clauses) { return (Array.from(clauses).map((clause) => `(${clause})`)).join(' or '); }, gt(column, literal) { return `${column} > ${handleLiteral(literal)}`; }, gte(column, literal) { return `${column} >= ${handleLiteral(literal)}`; }, lt(column, literal) { return `${column} < ${handleLiteral(literal)}`; }, lte(column, literal) { return `${column} <= ${handleLiteral(literal)}`; }, eq(column, literal) { return `${column} = ${handleLiteral(literal)}`; } }; // serialize object to querystring const toQuerystring = function(obj) { str = []; for (let key of Object.keys(obj || {})) { const val = obj[key]; str.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); } return str.join('&'); }; class Connection { constructor(dataSite, sodaOpts) { this.dataSite = dataSite; if (sodaOpts == null) { sodaOpts = {}; } this.sodaOpts = sodaOpts; if (!/^[a-z0-9-_.]+(:[0-9]+)?$/i.test(this.dataSite)) { throw new Error('dataSite does not appear to be valid! Please supply a domain name, eg data.seattle.gov'); } // options passed directly into EventEmitter2 construction this.emitterOpts = this.sodaOpts.emitterOpts != null ? this.sodaOpts.emitterOpts : { wildcard: true, delimiter: '.', maxListeners: 15 }; this.networker = function(opts, data) { const url = `https://${this.dataSite}${opts.path}`; const client = httpClient(opts.method, url); if (data != null) { client.set('Accept', "application/json"); } if (data != null) { client.set('Content-type', "application/json"); } if (this.sodaOpts.apiToken != null) { client.set('X-App-Token', this.sodaOpts.apiToken); } if ((this.sodaOpts.username != null) && (this.sodaOpts.password != null)) { client.set('Authorization', "Basic " + toBase64(`${this.sodaOpts.username}:${this.sodaOpts.password}`)); } if (this.sodaOpts.accessToken != null) { client.set('Authorization', "OAuth " + accessToken); } if (opts.query != null) { client.query(opts.query); } if (data != null) { client.send(data); } return responseHandler => client.end(responseHandler || this.getDefaultHandler()); }; } getDefaultHandler() { // instance variable for easy chaining let emitter, handler; this.emitter = (emitter = new EventEmitter(this.emitterOpts)); // return the handler return handler = function(error, response) { // TODO: possibly more granular handling? if (response.ok) { if (response.accepted) { // handle 202 by remaking request. inform of possible progress. emitter.emit('progress', response.body); setTimeout((function() { return this.consumer.networker(opts)(handler); }), 5000); } else { emitter.emit('success', response.body); } } else { emitter.emit('error', response.body != null ? response.body : response.text); } // just emit the raw superagent obj if they just want complete event return emitter.emit('complete', response); }; } } // main class class Consumer { constructor(dataSite, sodaOpts) { this.dataSite = dataSite; if (sodaOpts == null) { sodaOpts = {}; } this.sodaOpts = sodaOpts; this.connection = new Connection(this.dataSite, this.sodaOpts); } query() { return new Query(this); } getDataset(id) { let emitter; return emitter = new EventEmitter(this.emitterOpts); } } // TODO: implement me // Producer class class Producer { constructor(dataSite, sodaOpts) { this.dataSite = dataSite; if (sodaOpts == null) { sodaOpts = {}; } this.sodaOpts = sodaOpts; this.connection = new Connection(this.dataSite, this.sodaOpts); } operation() { return new Operation(this); } } class Operation { constructor(producer) { this.producer = producer; } withDataset(datasetId) { this._datasetId = datasetId; return this; } // truncate the entire dataset truncate() { const opts = {method: 'delete'}; opts.path = `/resource/${this._datasetId}`; return this._exec(opts); } // add a new row - explicitly avoids upserting (updating/deleting existing rows) add(data) { const opts = {method: 'post'}; opts.path = `/resource/${this._datasetId}`; const _data = JSON.parse(JSON.stringify(data)); delete _data[':id']; delete _data[':delete']; for (let obj of Array.from(_data)) { delete obj[':id']; delete obj[':delete']; } return this._exec(opts, _data); } // modify existing rows delete(id) { const opts = {method: 'delete'}; opts.path = `/resource/${this._datasetId}/${id}`; return this._exec(opts); } update(id, data) { const opts = {method: 'post'}; opts.path = `/resource/${this._datasetId}/${id}`; return this._exec(opts, data); } replace(id, data) { const opts = {method: 'put'}; opts.path = `/resource/${this._datasetId}/${id}`; return this._exec(opts, data); } // add objects, update if existing, delete if :delete=true upsert(data) { const opts = {method: 'post'}; opts.path = `/resource/${this._datasetId}`; return this._exec(opts, data); } _exec(opts, data) { if (this._datasetId == null) { throw new Error('no dataset given to work against!'); } this.producer.connection.networker(opts, data)(); return this.producer.connection.emitter; } } // querybuilder class class Query { constructor(consumer) { this.consumer = consumer; this._select = []; this._where = []; this._group = []; this._having = []; this._order = []; this._offset = (this._limit = (this._q = null)); } withDataset(datasetId) { this._datasetId = datasetId; return this; } // for passing in a fully formed soql query. all other params will be ignored soql(query) { this._soql = query; return this; } select(...selects) { for (let select of Array.from(selects)) { this._select.push(select); } return this; } // args: ('clause', [...]) // ({ column: value1, columnb: value2 }, [...]]) // multiple calls are assumed to be and-chained where(...args) { addExpr(this._where, args); return this; } having(...args) { addExpr(this._having, args); return this; } group(...groups) { for (let group of Array.from(groups)) { this._group.push(group); } return this; } // args: ("column direction", ["column direction", [...]]) order(...orders) { for (let order of Array.from(orders)) { this._order.push(handleOrder(order)); } return this; } offset(offset) { this._offset = offset; return this; } limit(limit) { this._limit = limit; return this; } q(q) { this._q = q; return this; } getOpts() { const opts = {method: 'get'}; if (this._datasetId == null) { throw new Error('no dataset given to work against!'); } opts.path = `/resource/${this._datasetId}.json`; const queryComponents = this._buildQueryComponents(); opts.query = {}; for (let k in queryComponents) { const v = queryComponents[k]; opts.query['$' + k] = v; } return opts; } getURL() { const opts = this.getOpts(); const query = toQuerystring(opts.query); return `https://${this.consumer.dataSite}${opts.path}` + (query ? `?${query}` : ""); } getRows() { const opts = this.getOpts(); this.consumer.connection.networker(opts)(); return this.consumer.connection.emitter; } _buildQueryComponents() { const query = {}; if (this._soql != null) { query.query = this._soql; } else { if (this._select.length > 0) { query.select = this._select.join(', '); } if (this._where.length > 0) { query.where = expr.and.apply(this, this._where); } if (this._group.length > 0) { query.group = this._group.join(', '); } if (this._having.length > 0) { if (!(this._group.length > 0)) { throw new Error('Having provided without group by!'); } query.having = expr.and.apply(this, this._having); } if (this._order.length > 0) { query.order = this._order.join(', '); } if (isNumber(this._offset)) { query.offset = this._offset; } if (isNumber(this._limit)) { query.limit = this._limit; } if (this._q) { query.q = this._q; } } return query; } } class Dataset { constructor(data, client) { this.data = data; this.client = client; } } // TODO: implement me extend(typeof exports !== 'undefined' && exports !== null ? exports : this.soda, { Consumer, Producer, expr, // exported for testing reasons _internal: { Connection, Query, Operation, util: { toBase64, handleLiteral, handleOrder } } } );
{ // adapted/modified from https://github.com/rwz/base64.coffee const base64Lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split(''); const rawToBase64 = typeof btoa !== 'undefined' && btoa !== null ? btoa : function(str) { const result = []; let i = 0; while (i < str.length) { const chr1 = str.charCodeAt(i++); const chr2 = str.charCodeAt(i++); const chr3 = str.charCodeAt(i++); if (Math.max(chr1, chr2, chr3) > 0xFF) { throw new Error('Invalid character!'); } const enc1 = chr1 >> 2; const enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); let enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); let enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = (enc4 = 64); } else if (isNaN(chr3)) { enc4 = 64; } result.push(base64Lookup[enc1]); result.push(base64Lookup[enc2]); result.push(base64Lookup[enc3]); result.push(base64Lookup[enc4]); } return result.join(''); }; return str => rawToBase64(unescape(encodeURIComponent(str))); }
conditional_block
soda.js
/* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS203: Remove `|| {}` from converted for-own loops * DS205: Consider reworking code to avoid use of IIFEs * DS207: Consider shorter variations of null checks * DS208: Avoid top-level this * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ // soda.coffee -- chained, evented, buzzworded library for accessing SODA via JS. // sodaOpts options: // username: https basic auth username // password: https basic auth password // apiToken: socrata api token // // emitterOpts: options to override EventEmitter2 declaration options // TODO: // * we're inconsistent about validating query correctness. do we continue with catch-what-we-can, // or do we just back off and leave all failures to the api to return? let str; const eelib = require('eventemitter2'); const EventEmitter = eelib.EventEmitter2 || eelib; const httpClient = require('superagent'); // internal util funcs const isString = obj => typeof obj === 'string'; const isArray = obj => Array.isArray(obj); const isNumber = obj => !isNaN(parseFloat(obj)); const extend = function(target, ...sources) { for (let source of Array.from(sources)) { for (let k in source) { const v = source[k]; target[k] = v; } } return null; }; // it's really, really, really stupid that i have to solve this problem here const toBase64 = (() => { if (typeof Buffer !== 'undefined' && Buffer !== null) { return str => new Buffer(str).toString('base64'); } else { // adapted/modified from https://github.com/rwz/base64.coffee const base64Lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split(''); const rawToBase64 = typeof btoa !== 'undefined' && btoa !== null ? btoa : function(str) { const result = []; let i = 0; while (i < str.length) { const chr1 = str.charCodeAt(i++); const chr2 = str.charCodeAt(i++); const chr3 = str.charCodeAt(i++); if (Math.max(chr1, chr2, chr3) > 0xFF) { throw new Error('Invalid character!'); } const enc1 = chr1 >> 2; const enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); let enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); let enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = (enc4 = 64); } else if (isNaN(chr3)) { enc4 = 64; } result.push(base64Lookup[enc1]); result.push(base64Lookup[enc2]); result.push(base64Lookup[enc3]); result.push(base64Lookup[enc4]); } return result.join(''); }; return str => rawToBase64(unescape(encodeURIComponent(str))); } })(); const handleLiteral = function(literal) { if (isString(literal)) { return `'${literal}'`; } else if (isNumber(literal)) { // TODO: possibly ensure number cleanliness for sending to the api? sci not? return literal; } else { return literal; } }; const handleOrder = function(order) { if (/( asc$| desc$)/i.test(order)) { return order; } else { return order + ' asc'; } }; const addExpr = (target, args) => Array.from(args).map((arg) => isString(arg) ? target.push(arg) : (() => { const result = []; for (let k in arg) { const v = arg[k]; result.push(target.push(`${k} = ${handleLiteral(v)}`)); } return result; })()); // extern util funcs // convenience functions for building where clauses, if so desired const expr = { and(...clauses) { return (Array.from(clauses).map((clause) => `(${clause})`)).join(' and '); }, or(...clauses) { return (Array.from(clauses).map((clause) => `(${clause})`)).join(' or '); }, gt(column, literal) { return `${column} > ${handleLiteral(literal)}`; }, gte(column, literal) { return `${column} >= ${handleLiteral(literal)}`; }, lt(column, literal) { return `${column} < ${handleLiteral(literal)}`; }, lte(column, literal) { return `${column} <= ${handleLiteral(literal)}`; }, eq(column, literal) { return `${column} = ${handleLiteral(literal)}`; }
const toQuerystring = function(obj) { str = []; for (let key of Object.keys(obj || {})) { const val = obj[key]; str.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); } return str.join('&'); }; class Connection { constructor(dataSite, sodaOpts) { this.dataSite = dataSite; if (sodaOpts == null) { sodaOpts = {}; } this.sodaOpts = sodaOpts; if (!/^[a-z0-9-_.]+(:[0-9]+)?$/i.test(this.dataSite)) { throw new Error('dataSite does not appear to be valid! Please supply a domain name, eg data.seattle.gov'); } // options passed directly into EventEmitter2 construction this.emitterOpts = this.sodaOpts.emitterOpts != null ? this.sodaOpts.emitterOpts : { wildcard: true, delimiter: '.', maxListeners: 15 }; this.networker = function(opts, data) { const url = `https://${this.dataSite}${opts.path}`; const client = httpClient(opts.method, url); if (data != null) { client.set('Accept', "application/json"); } if (data != null) { client.set('Content-type', "application/json"); } if (this.sodaOpts.apiToken != null) { client.set('X-App-Token', this.sodaOpts.apiToken); } if ((this.sodaOpts.username != null) && (this.sodaOpts.password != null)) { client.set('Authorization', "Basic " + toBase64(`${this.sodaOpts.username}:${this.sodaOpts.password}`)); } if (this.sodaOpts.accessToken != null) { client.set('Authorization', "OAuth " + accessToken); } if (opts.query != null) { client.query(opts.query); } if (data != null) { client.send(data); } return responseHandler => client.end(responseHandler || this.getDefaultHandler()); }; } getDefaultHandler() { // instance variable for easy chaining let emitter, handler; this.emitter = (emitter = new EventEmitter(this.emitterOpts)); // return the handler return handler = function(error, response) { // TODO: possibly more granular handling? if (response.ok) { if (response.accepted) { // handle 202 by remaking request. inform of possible progress. emitter.emit('progress', response.body); setTimeout((function() { return this.consumer.networker(opts)(handler); }), 5000); } else { emitter.emit('success', response.body); } } else { emitter.emit('error', response.body != null ? response.body : response.text); } // just emit the raw superagent obj if they just want complete event return emitter.emit('complete', response); }; } } // main class class Consumer { constructor(dataSite, sodaOpts) { this.dataSite = dataSite; if (sodaOpts == null) { sodaOpts = {}; } this.sodaOpts = sodaOpts; this.connection = new Connection(this.dataSite, this.sodaOpts); } query() { return new Query(this); } getDataset(id) { let emitter; return emitter = new EventEmitter(this.emitterOpts); } } // TODO: implement me // Producer class class Producer { constructor(dataSite, sodaOpts) { this.dataSite = dataSite; if (sodaOpts == null) { sodaOpts = {}; } this.sodaOpts = sodaOpts; this.connection = new Connection(this.dataSite, this.sodaOpts); } operation() { return new Operation(this); } } class Operation { constructor(producer) { this.producer = producer; } withDataset(datasetId) { this._datasetId = datasetId; return this; } // truncate the entire dataset truncate() { const opts = {method: 'delete'}; opts.path = `/resource/${this._datasetId}`; return this._exec(opts); } // add a new row - explicitly avoids upserting (updating/deleting existing rows) add(data) { const opts = {method: 'post'}; opts.path = `/resource/${this._datasetId}`; const _data = JSON.parse(JSON.stringify(data)); delete _data[':id']; delete _data[':delete']; for (let obj of Array.from(_data)) { delete obj[':id']; delete obj[':delete']; } return this._exec(opts, _data); } // modify existing rows delete(id) { const opts = {method: 'delete'}; opts.path = `/resource/${this._datasetId}/${id}`; return this._exec(opts); } update(id, data) { const opts = {method: 'post'}; opts.path = `/resource/${this._datasetId}/${id}`; return this._exec(opts, data); } replace(id, data) { const opts = {method: 'put'}; opts.path = `/resource/${this._datasetId}/${id}`; return this._exec(opts, data); } // add objects, update if existing, delete if :delete=true upsert(data) { const opts = {method: 'post'}; opts.path = `/resource/${this._datasetId}`; return this._exec(opts, data); } _exec(opts, data) { if (this._datasetId == null) { throw new Error('no dataset given to work against!'); } this.producer.connection.networker(opts, data)(); return this.producer.connection.emitter; } } // querybuilder class class Query { constructor(consumer) { this.consumer = consumer; this._select = []; this._where = []; this._group = []; this._having = []; this._order = []; this._offset = (this._limit = (this._q = null)); } withDataset(datasetId) { this._datasetId = datasetId; return this; } // for passing in a fully formed soql query. all other params will be ignored soql(query) { this._soql = query; return this; } select(...selects) { for (let select of Array.from(selects)) { this._select.push(select); } return this; } // args: ('clause', [...]) // ({ column: value1, columnb: value2 }, [...]]) // multiple calls are assumed to be and-chained where(...args) { addExpr(this._where, args); return this; } having(...args) { addExpr(this._having, args); return this; } group(...groups) { for (let group of Array.from(groups)) { this._group.push(group); } return this; } // args: ("column direction", ["column direction", [...]]) order(...orders) { for (let order of Array.from(orders)) { this._order.push(handleOrder(order)); } return this; } offset(offset) { this._offset = offset; return this; } limit(limit) { this._limit = limit; return this; } q(q) { this._q = q; return this; } getOpts() { const opts = {method: 'get'}; if (this._datasetId == null) { throw new Error('no dataset given to work against!'); } opts.path = `/resource/${this._datasetId}.json`; const queryComponents = this._buildQueryComponents(); opts.query = {}; for (let k in queryComponents) { const v = queryComponents[k]; opts.query['$' + k] = v; } return opts; } getURL() { const opts = this.getOpts(); const query = toQuerystring(opts.query); return `https://${this.consumer.dataSite}${opts.path}` + (query ? `?${query}` : ""); } getRows() { const opts = this.getOpts(); this.consumer.connection.networker(opts)(); return this.consumer.connection.emitter; } _buildQueryComponents() { const query = {}; if (this._soql != null) { query.query = this._soql; } else { if (this._select.length > 0) { query.select = this._select.join(', '); } if (this._where.length > 0) { query.where = expr.and.apply(this, this._where); } if (this._group.length > 0) { query.group = this._group.join(', '); } if (this._having.length > 0) { if (!(this._group.length > 0)) { throw new Error('Having provided without group by!'); } query.having = expr.and.apply(this, this._having); } if (this._order.length > 0) { query.order = this._order.join(', '); } if (isNumber(this._offset)) { query.offset = this._offset; } if (isNumber(this._limit)) { query.limit = this._limit; } if (this._q) { query.q = this._q; } } return query; } } class Dataset { constructor(data, client) { this.data = data; this.client = client; } } // TODO: implement me extend(typeof exports !== 'undefined' && exports !== null ? exports : this.soda, { Consumer, Producer, expr, // exported for testing reasons _internal: { Connection, Query, Operation, util: { toBase64, handleLiteral, handleOrder } } } );
}; // serialize object to querystring
random_line_split
main.rs
use std::collections::HashMap; // To allow me to use the hashmap I created with the menu items. /* This function will remove any newline characters or returns that are read in. In this the string is passed by reference. I created this as an example and initially used both remove, and removed, but for convienence I eneded up just using one throughout.*/ fn remove(string: &mut String){ if let Some('\n')=string.chars().next_back() { string.pop(); } if let Some('\r')=string.chars().next_back() { string.pop(); } } //Same function as remove but passed by value. fn
(mut string: String) -> String { if let Some('\n')=string.chars().next_back() { string.pop(); } if let Some('\r')=string.chars().next_back() { string.pop(); } string } /*This will set up to take input from the keyboard. It will then remove any newline or return characters, by calling removed, and then return the string splice */ fn rdin() -> String{ let mut reader = String::new(); std::io::stdin().read_line(&mut reader).unwrap(); reader = removed(reader.to_lowercase()); // Changes everything to lowercase so it is not a case sensetive program. println!(); return reader; } /*Rounded takes floating point integers and rounds them to two decimal places. With the way that Rust rounds, it first needs to be rounded to three decimal places, and then two, in order to get an accurate rounding. */ fn rounded(mut rounder: f32) -> f32{ rounder = format!("{:.3}", rounder).parse::<f32>().unwrap(); rounder = format!("{:.2}", rounder).parse::<f32>().unwrap(); return rounder; } /*This function was created for checking for correct input when integers were to be used. It is necessary before trying to convert the string to an integer. This is implimented with the tips. */ fn strchecker(mut temp: String) -> String{ while !temp.contains(&"1") && !temp.contains(&"2") && !temp.contains(&"3") && !temp.contains(&"4"){ println!("It seems you entered an unrecognized value.\nYou entered, {}, please try again with either '1', '2', '3', or '4'.", temp); temp = rdin(); } return temp; } /*intchecker will check the input as the actual expected ints. This is a necessary second layer, since the strchecker will allow say 21, or 34 as inputs. If the value is incorrect it will call for a new input, and the strchecker again.*/ fn intchecker(mut tip: i16) -> i16{ let mut temp = String::new(); while tip != 1 && tip !=2 && tip !=3 && tip !=4{ println!("It seems you entered an unrecognized value.\nYou entered, {}, please try again with either '1', '2', '3' or '4'.", tip); temp = rdin(); temp = strchecker(temp); tip = temp.parse::<i16>().unwrap(); } return tip; } /*ynchecker will do everything necessary to check the for the correct input of either a y or a n. It calls the rdin function to get input. Then it will check for empyt string so that there is no broken code. Then it checks the chars and if it is not within the range of acceptable values, it will use recursion to do get a new value and run the checks again. This is done by Reference.*/ fn ynchecker(selector: &mut char){ let mut temp = String::new(); temp = rdin(); //Simply error checks for incorrect values. if temp.is_empty(){ // Will check for an empty string. *selector = ' '; println!("You got an empty sting there"); } else { *selector = temp.chars().nth(0).unwrap(); // Have to convert from a string, to a slice, to a char. } if *selector != 'y' && *selector != 'n'{ println!("It seems you entered an unrecognized value.\nYou entered, {}, please try again with either 'y' or 'n'.", selector); ynchecker(selector); } } //main is necessary to run the code. fn main() { //Constants declared for the tax rate, default tip rates, and special tip cases. const TAX: f32 = 0.06; const FIVE: f32 = 0.05; const TEN: f32 = 0.10; const FTN: f32 = 0.15; const TWN: f32 = 0.20; const QRT: f32 = 0.25; const HALF: f32 = 0.50; const DOLLAR: f32 = 1.00; //use mut to say the variable can be changed. let mut i: u8; let mut selector: char = 'y'; let mut cost: f32 = 0.0; let mut taxes: f32; //Created a hashmap, it then is populated with the menu information let mut items = HashMap::new(); items.insert(String::from("soda"), 1.95); items.insert(String::from("water"), 0.00); items.insert(String::from("burger"), 6.95); items.insert(String::from("pizza"), 2.95); items.insert(String::from("fries"), 1.95); items.insert(String::from("stake"), 9.95); //Creates a vector. It is necessary to specify the data type that will be in the vector. let mut itemPrice: Vec<f32> = Vec::new(); let mut total: f32; let mut fivet: f32; let mut tent: f32; let mut ftnt: f32; let mut twnt: f32; //Cannot initialize a string with values already in it. let mut temp = String::new(); let mut tip: i16; println!("Welcome to the restaurant of Rusty Lake!"); //Do you get the reference here? xD //Loops through the entire body of the code to allow multiple iterations of orders. while selector != 'n'{ //Needs to be cleared from any past iterations. cost = 0.0; i = 0; //Specifically for clearing the vector, instead of wasting memory creating a new one each time. //Will iterate through the length of the vector using .rev, which is basically just a backwards iterator. for i in (0..itemPrice.len()).rev(){ itemPrice.remove(i); } //Will loop through for each item being selected from the menu. while selector != 'n'{ println!("What item from the menu would you like to order?"); //Prints out the entire HashMap for (key, value) in &items { println!("{}: {:.2}", key, value); } temp = rdin(); //If the input does not match with a key we need to get the correct value. while !items.contains_key(&temp){ println!("It seems what you entered did not quite match one of the items from the menu.\nPlease try again."); for (key, value) in &items { println!("{}: {:.2}", key, value); } temp = rdin(); } //Checks that the input really is a key. if items.contains_key(&temp){ /*A little bit of a different descision structure here. The match will compare the given statement to the pattern of the other types. In a way this reminds me of the when statement from Kotlin.*/ match items.get(&temp){ Some(price) => { itemPrice.push(*price); println!("Item price, ${:.2}", price); } None => { println!("Error! Something went wrong!"); } } } println!("Is there another item from the menu you wish to order? (y/n)"); ynchecker(&mut selector); i += 1; } //Will add each item from the vector to the cost. for order in itemPrice.iter(){ //println!("The current item is priced ${}", order); cost += order; } //Calculate the costs with tax and various tips. taxes = cost * TAX; taxes = rounded(taxes); total = taxes + cost; println!("Your taxes will be: ${0:.2}\nYour total with taxes will be ${1:.2}\n", taxes, total); fivet = cost * FIVE; tent = cost * TEN; ftnt = cost * FTN; twnt = cost * TWN; fivet = rounded(fivet); tent = rounded(tent); ftnt = rounded(ftnt); twnt = rounded(twnt); /*First check for if they ordered water, when it would brake the normal code for calculating the tips. If there is a large group of people, considering someone may order 2 items on average, then raise the default tip rate.*/ if total == 0.0{ println!("Please consider being generous today and leave a tip for your waiter.\nSelect one of the following:\n1) $0.25 2) $0.50\n3) $1.00 4) Other"); } else if i < 10{ println!("What would you like your tip to be?\nSelect one of the following:\n1) 5%: ${0:.2} {3:<10}2) 10%: ${1:.2}\n3) 15%: ${2:.2}{3:<10} 4) Other", fivet, tent, ftnt, ""); } else { println!("What would you like your tip to be?\nSelect one of the following:\n1) 10%: ${0:.2}{3:<10} 2) 15%: ${1:.2}\n3) 20%: ${2:.2}{3:<10}4) Other", tent, ftnt, twnt, ""); } temp = rdin(); temp = strchecker(temp); // Use the string checker first to make sure there aren't actually and letters read in. tip = temp.parse::<i16>().unwrap(); // After we have check that there are only integers, we can convert the data type to an int. tip = intchecker(tip); // Then we have to actually check the values for correct integers. // First check for the special only water condition. Then go along with normal tips. if total == 0.0{ if tip == 1{ total += QRT; } else if tip == 2{ total += HALF; } else if tip == 3{ total += DOLLAR; } else if tip == 4{ println!("Please enter a specific amount, including the change. Ex '10.00':"); total += rdin().parse::<f32>().unwrap(); //Will convert the string to a floating point number. Will break if letters are read in. } else{ println!("It appears you got through all my checks. In other words, you broke the code! Way to go!"); } } else { if tip == 1{ total += fivet; } else if tip == 2{ total += tent; } else if tip == 3{ total += ftnt; } else if tip == 4{ println!("Please enter a specific amount, including the change. Ex '10.00':"); total += rdin().parse::<f32>().unwrap(); } else{ // Just a random extra else. I found no situations that would enact this code, but fun for just in case. println!("It appears you got through all my checks. In other words, you broke the code! Way to go!"); } } println!("Your total will be: ${:.2}", total); // The :.2 that I used in a lot of these print statements is to enforce the formatting with two decimal places. println!("Is there another order you wish to enter? (y/n)"); ynchecker(&mut selector); // One final error check. } }
removed
identifier_name
main.rs
use std::collections::HashMap; // To allow me to use the hashmap I created with the menu items. /* This function will remove any newline characters or returns that are read in. In this the string is passed by reference. I created this as an example and initially used both remove, and removed, but for convienence I eneded up just using one throughout.*/ fn remove(string: &mut String){ if let Some('\n')=string.chars().next_back() { string.pop(); } if let Some('\r')=string.chars().next_back() { string.pop(); } } //Same function as remove but passed by value. fn removed(mut string: String) -> String { if let Some('\n')=string.chars().next_back() { string.pop(); } if let Some('\r')=string.chars().next_back() { string.pop(); } string } /*This will set up to take input from the keyboard. It will then remove any newline or return characters, by calling removed, and then return the string splice */ fn rdin() -> String{ let mut reader = String::new(); std::io::stdin().read_line(&mut reader).unwrap(); reader = removed(reader.to_lowercase()); // Changes everything to lowercase so it is not a case sensetive program. println!(); return reader; } /*Rounded takes floating point integers and rounds them to two decimal places. With the way that Rust rounds, it first needs to be rounded to three decimal places, and then two, in order to get an accurate rounding. */ fn rounded(mut rounder: f32) -> f32{ rounder = format!("{:.3}", rounder).parse::<f32>().unwrap(); rounder = format!("{:.2}", rounder).parse::<f32>().unwrap(); return rounder; } /*This function was created for checking for correct input when integers were to be used. It is necessary before trying to convert the string to an integer. This is implimented with the tips. */ fn strchecker(mut temp: String) -> String{ while !temp.contains(&"1") && !temp.contains(&"2") && !temp.contains(&"3") && !temp.contains(&"4"){ println!("It seems you entered an unrecognized value.\nYou entered, {}, please try again with either '1', '2', '3', or '4'.", temp); temp = rdin(); } return temp; } /*intchecker will check the input as the actual expected ints. This is a necessary second layer, since the strchecker will allow say 21, or 34 as inputs. If the value is incorrect it will call for a new input, and the strchecker again.*/ fn intchecker(mut tip: i16) -> i16{ let mut temp = String::new(); while tip != 1 && tip !=2 && tip !=3 && tip !=4{ println!("It seems you entered an unrecognized value.\nYou entered, {}, please try again with either '1', '2', '3' or '4'.", tip); temp = rdin(); temp = strchecker(temp); tip = temp.parse::<i16>().unwrap(); } return tip; } /*ynchecker will do everything necessary to check the for the correct input of either a y or a n. It calls the rdin function to get input. Then it will check for empyt string so that there is no broken code. Then it checks the chars and if it is not within the range of acceptable values, it will use recursion to do get a new value and run the checks again. This is done by Reference.*/ fn ynchecker(selector: &mut char){ let mut temp = String::new(); temp = rdin(); //Simply error checks for incorrect values. if temp.is_empty(){ // Will check for an empty string. *selector = ' '; println!("You got an empty sting there"); } else { *selector = temp.chars().nth(0).unwrap(); // Have to convert from a string, to a slice, to a char. } if *selector != 'y' && *selector != 'n'{ println!("It seems you entered an unrecognized value.\nYou entered, {}, please try again with either 'y' or 'n'.", selector); ynchecker(selector); } } //main is necessary to run the code. fn main() { //Constants declared for the tax rate, default tip rates, and special tip cases. const TAX: f32 = 0.06; const FIVE: f32 = 0.05; const TEN: f32 = 0.10; const FTN: f32 = 0.15; const TWN: f32 = 0.20; const QRT: f32 = 0.25; const HALF: f32 = 0.50; const DOLLAR: f32 = 1.00; //use mut to say the variable can be changed. let mut i: u8; let mut selector: char = 'y'; let mut cost: f32 = 0.0; let mut taxes: f32; //Created a hashmap, it then is populated with the menu information let mut items = HashMap::new(); items.insert(String::from("soda"), 1.95); items.insert(String::from("water"), 0.00); items.insert(String::from("burger"), 6.95); items.insert(String::from("pizza"), 2.95); items.insert(String::from("fries"), 1.95); items.insert(String::from("stake"), 9.95); //Creates a vector. It is necessary to specify the data type that will be in the vector. let mut itemPrice: Vec<f32> = Vec::new(); let mut total: f32; let mut fivet: f32; let mut tent: f32; let mut ftnt: f32; let mut twnt: f32; //Cannot initialize a string with values already in it. let mut temp = String::new(); let mut tip: i16; println!("Welcome to the restaurant of Rusty Lake!"); //Do you get the reference here? xD //Loops through the entire body of the code to allow multiple iterations of orders. while selector != 'n'{ //Needs to be cleared from any past iterations. cost = 0.0; i = 0; //Specifically for clearing the vector, instead of wasting memory creating a new one each time. //Will iterate through the length of the vector using .rev, which is basically just a backwards iterator. for i in (0..itemPrice.len()).rev(){ itemPrice.remove(i); } //Will loop through for each item being selected from the menu. while selector != 'n'{ println!("What item from the menu would you like to order?"); //Prints out the entire HashMap for (key, value) in &items { println!("{}: {:.2}", key, value); } temp = rdin(); //If the input does not match with a key we need to get the correct value. while !items.contains_key(&temp){ println!("It seems what you entered did not quite match one of the items from the menu.\nPlease try again."); for (key, value) in &items { println!("{}: {:.2}", key, value); } temp = rdin(); } //Checks that the input really is a key. if items.contains_key(&temp){ /*A little bit of a different descision structure here. The match will compare the given statement to the pattern of the other types. In a way this reminds me of the when statement from Kotlin.*/ match items.get(&temp){ Some(price) => { itemPrice.push(*price); println!("Item price, ${:.2}", price); } None => { println!("Error! Something went wrong!"); } } } println!("Is there another item from the menu you wish to order? (y/n)"); ynchecker(&mut selector); i += 1; } //Will add each item from the vector to the cost. for order in itemPrice.iter(){ //println!("The current item is priced ${}", order); cost += order; } //Calculate the costs with tax and various tips. taxes = cost * TAX; taxes = rounded(taxes); total = taxes + cost; println!("Your taxes will be: ${0:.2}\nYour total with taxes will be ${1:.2}\n", taxes, total); fivet = cost * FIVE; tent = cost * TEN; ftnt = cost * FTN; twnt = cost * TWN; fivet = rounded(fivet); tent = rounded(tent); ftnt = rounded(ftnt); twnt = rounded(twnt); /*First check for if they ordered water, when it would brake the normal code for calculating the tips. If there is a large group of people, considering someone may order 2 items on average, then raise the default tip rate.*/ if total == 0.0{ println!("Please consider being generous today and leave a tip for your waiter.\nSelect one of the following:\n1) $0.25 2) $0.50\n3) $1.00 4) Other"); } else if i < 10{ println!("What would you like your tip to be?\nSelect one of the following:\n1) 5%: ${0:.2} {3:<10}2) 10%: ${1:.2}\n3) 15%: ${2:.2}{3:<10} 4) Other", fivet, tent, ftnt, ""); } else { println!("What would you like your tip to be?\nSelect one of the following:\n1) 10%: ${0:.2}{3:<10} 2) 15%: ${1:.2}\n3) 20%: ${2:.2}{3:<10}4) Other", tent, ftnt, twnt, ""); } temp = rdin(); temp = strchecker(temp); // Use the string checker first to make sure there aren't actually and letters read in. tip = temp.parse::<i16>().unwrap(); // After we have check that there are only integers, we can convert the data type to an int. tip = intchecker(tip); // Then we have to actually check the values for correct integers. // First check for the special only water condition. Then go along with normal tips. if total == 0.0{ if tip == 1{ total += QRT; } else if tip == 2{ total += HALF;
} else if tip == 4{ println!("Please enter a specific amount, including the change. Ex '10.00':"); total += rdin().parse::<f32>().unwrap(); //Will convert the string to a floating point number. Will break if letters are read in. } else{ println!("It appears you got through all my checks. In other words, you broke the code! Way to go!"); } } else { if tip == 1{ total += fivet; } else if tip == 2{ total += tent; } else if tip == 3{ total += ftnt; } else if tip == 4{ println!("Please enter a specific amount, including the change. Ex '10.00':"); total += rdin().parse::<f32>().unwrap(); } else{ // Just a random extra else. I found no situations that would enact this code, but fun for just in case. println!("It appears you got through all my checks. In other words, you broke the code! Way to go!"); } } println!("Your total will be: ${:.2}", total); // The :.2 that I used in a lot of these print statements is to enforce the formatting with two decimal places. println!("Is there another order you wish to enter? (y/n)"); ynchecker(&mut selector); // One final error check. } }
} else if tip == 3{ total += DOLLAR;
random_line_split
main.rs
use std::collections::HashMap; // To allow me to use the hashmap I created with the menu items. /* This function will remove any newline characters or returns that are read in. In this the string is passed by reference. I created this as an example and initially used both remove, and removed, but for convienence I eneded up just using one throughout.*/ fn remove(string: &mut String){ if let Some('\n')=string.chars().next_back() { string.pop(); } if let Some('\r')=string.chars().next_back() { string.pop(); } } //Same function as remove but passed by value. fn removed(mut string: String) -> String { if let Some('\n')=string.chars().next_back() { string.pop(); } if let Some('\r')=string.chars().next_back() { string.pop(); } string } /*This will set up to take input from the keyboard. It will then remove any newline or return characters, by calling removed, and then return the string splice */ fn rdin() -> String{ let mut reader = String::new(); std::io::stdin().read_line(&mut reader).unwrap(); reader = removed(reader.to_lowercase()); // Changes everything to lowercase so it is not a case sensetive program. println!(); return reader; } /*Rounded takes floating point integers and rounds them to two decimal places. With the way that Rust rounds, it first needs to be rounded to three decimal places, and then two, in order to get an accurate rounding. */ fn rounded(mut rounder: f32) -> f32{ rounder = format!("{:.3}", rounder).parse::<f32>().unwrap(); rounder = format!("{:.2}", rounder).parse::<f32>().unwrap(); return rounder; } /*This function was created for checking for correct input when integers were to be used. It is necessary before trying to convert the string to an integer. This is implimented with the tips. */ fn strchecker(mut temp: String) -> String{ while !temp.contains(&"1") && !temp.contains(&"2") && !temp.contains(&"3") && !temp.contains(&"4"){ println!("It seems you entered an unrecognized value.\nYou entered, {}, please try again with either '1', '2', '3', or '4'.", temp); temp = rdin(); } return temp; } /*intchecker will check the input as the actual expected ints. This is a necessary second layer, since the strchecker will allow say 21, or 34 as inputs. If the value is incorrect it will call for a new input, and the strchecker again.*/ fn intchecker(mut tip: i16) -> i16{ let mut temp = String::new(); while tip != 1 && tip !=2 && tip !=3 && tip !=4{ println!("It seems you entered an unrecognized value.\nYou entered, {}, please try again with either '1', '2', '3' or '4'.", tip); temp = rdin(); temp = strchecker(temp); tip = temp.parse::<i16>().unwrap(); } return tip; } /*ynchecker will do everything necessary to check the for the correct input of either a y or a n. It calls the rdin function to get input. Then it will check for empyt string so that there is no broken code. Then it checks the chars and if it is not within the range of acceptable values, it will use recursion to do get a new value and run the checks again. This is done by Reference.*/ fn ynchecker(selector: &mut char){ let mut temp = String::new(); temp = rdin(); //Simply error checks for incorrect values. if temp.is_empty(){ // Will check for an empty string. *selector = ' '; println!("You got an empty sting there"); } else { *selector = temp.chars().nth(0).unwrap(); // Have to convert from a string, to a slice, to a char. } if *selector != 'y' && *selector != 'n'{ println!("It seems you entered an unrecognized value.\nYou entered, {}, please try again with either 'y' or 'n'.", selector); ynchecker(selector); } } //main is necessary to run the code. fn main()
{ //Constants declared for the tax rate, default tip rates, and special tip cases. const TAX: f32 = 0.06; const FIVE: f32 = 0.05; const TEN: f32 = 0.10; const FTN: f32 = 0.15; const TWN: f32 = 0.20; const QRT: f32 = 0.25; const HALF: f32 = 0.50; const DOLLAR: f32 = 1.00; //use mut to say the variable can be changed. let mut i: u8; let mut selector: char = 'y'; let mut cost: f32 = 0.0; let mut taxes: f32; //Created a hashmap, it then is populated with the menu information let mut items = HashMap::new(); items.insert(String::from("soda"), 1.95); items.insert(String::from("water"), 0.00); items.insert(String::from("burger"), 6.95); items.insert(String::from("pizza"), 2.95); items.insert(String::from("fries"), 1.95); items.insert(String::from("stake"), 9.95); //Creates a vector. It is necessary to specify the data type that will be in the vector. let mut itemPrice: Vec<f32> = Vec::new(); let mut total: f32; let mut fivet: f32; let mut tent: f32; let mut ftnt: f32; let mut twnt: f32; //Cannot initialize a string with values already in it. let mut temp = String::new(); let mut tip: i16; println!("Welcome to the restaurant of Rusty Lake!"); //Do you get the reference here? xD //Loops through the entire body of the code to allow multiple iterations of orders. while selector != 'n'{ //Needs to be cleared from any past iterations. cost = 0.0; i = 0; //Specifically for clearing the vector, instead of wasting memory creating a new one each time. //Will iterate through the length of the vector using .rev, which is basically just a backwards iterator. for i in (0..itemPrice.len()).rev(){ itemPrice.remove(i); } //Will loop through for each item being selected from the menu. while selector != 'n'{ println!("What item from the menu would you like to order?"); //Prints out the entire HashMap for (key, value) in &items { println!("{}: {:.2}", key, value); } temp = rdin(); //If the input does not match with a key we need to get the correct value. while !items.contains_key(&temp){ println!("It seems what you entered did not quite match one of the items from the menu.\nPlease try again."); for (key, value) in &items { println!("{}: {:.2}", key, value); } temp = rdin(); } //Checks that the input really is a key. if items.contains_key(&temp){ /*A little bit of a different descision structure here. The match will compare the given statement to the pattern of the other types. In a way this reminds me of the when statement from Kotlin.*/ match items.get(&temp){ Some(price) => { itemPrice.push(*price); println!("Item price, ${:.2}", price); } None => { println!("Error! Something went wrong!"); } } } println!("Is there another item from the menu you wish to order? (y/n)"); ynchecker(&mut selector); i += 1; } //Will add each item from the vector to the cost. for order in itemPrice.iter(){ //println!("The current item is priced ${}", order); cost += order; } //Calculate the costs with tax and various tips. taxes = cost * TAX; taxes = rounded(taxes); total = taxes + cost; println!("Your taxes will be: ${0:.2}\nYour total with taxes will be ${1:.2}\n", taxes, total); fivet = cost * FIVE; tent = cost * TEN; ftnt = cost * FTN; twnt = cost * TWN; fivet = rounded(fivet); tent = rounded(tent); ftnt = rounded(ftnt); twnt = rounded(twnt); /*First check for if they ordered water, when it would brake the normal code for calculating the tips. If there is a large group of people, considering someone may order 2 items on average, then raise the default tip rate.*/ if total == 0.0{ println!("Please consider being generous today and leave a tip for your waiter.\nSelect one of the following:\n1) $0.25 2) $0.50\n3) $1.00 4) Other"); } else if i < 10{ println!("What would you like your tip to be?\nSelect one of the following:\n1) 5%: ${0:.2} {3:<10}2) 10%: ${1:.2}\n3) 15%: ${2:.2}{3:<10} 4) Other", fivet, tent, ftnt, ""); } else { println!("What would you like your tip to be?\nSelect one of the following:\n1) 10%: ${0:.2}{3:<10} 2) 15%: ${1:.2}\n3) 20%: ${2:.2}{3:<10}4) Other", tent, ftnt, twnt, ""); } temp = rdin(); temp = strchecker(temp); // Use the string checker first to make sure there aren't actually and letters read in. tip = temp.parse::<i16>().unwrap(); // After we have check that there are only integers, we can convert the data type to an int. tip = intchecker(tip); // Then we have to actually check the values for correct integers. // First check for the special only water condition. Then go along with normal tips. if total == 0.0{ if tip == 1{ total += QRT; } else if tip == 2{ total += HALF; } else if tip == 3{ total += DOLLAR; } else if tip == 4{ println!("Please enter a specific amount, including the change. Ex '10.00':"); total += rdin().parse::<f32>().unwrap(); //Will convert the string to a floating point number. Will break if letters are read in. } else{ println!("It appears you got through all my checks. In other words, you broke the code! Way to go!"); } } else { if tip == 1{ total += fivet; } else if tip == 2{ total += tent; } else if tip == 3{ total += ftnt; } else if tip == 4{ println!("Please enter a specific amount, including the change. Ex '10.00':"); total += rdin().parse::<f32>().unwrap(); } else{ // Just a random extra else. I found no situations that would enact this code, but fun for just in case. println!("It appears you got through all my checks. In other words, you broke the code! Way to go!"); } } println!("Your total will be: ${:.2}", total); // The :.2 that I used in a lot of these print statements is to enforce the formatting with two decimal places. println!("Is there another order you wish to enter? (y/n)"); ynchecker(&mut selector); // One final error check. } }
identifier_body
lib.rs
extern crate image; extern crate imageproc; extern crate rustfft; use image::{imageops, GrayImage, ImageBuffer, Luma}; use imageproc::geometric_transformations::Projection; use imageproc::geometric_transformations::{rotate_about_center, warp, Interpolation}; use rustfft::num_complex::Complex; use rustfft::num_traits::Zero; use rustfft::{Fft, FftPlanner}; use std::cmp::Ordering; use std::f32; use std::fmt::Debug; use std::sync::Arc; #[cfg(target_arch = "wasm32")] pub mod wasm; // TODO: use constant declarations wherever possible // TODO: refactor the unwrap statement into match statements wherever we can't be certain a result exists. // TODO: behaviour at edge of frame: target may not leave frame, but filter will screw up anyway due to cropping. Move target coord freely within template? // TODO: improve initial filter quality: additional affine perturbations, like scaling (zooming)? // TODO: 11x11 window around peak for PSR calculation is arbitrary and seems biased towards larger video feeds? // TODO: make k (number of perturbarions) a hyperparameter. k = 0 should not be allowed as it is senseless. // TODO: FFT objects may be thread safe (Arc), but are they blocking during concurrent calls? See https://docs.rs/crate/rustfft/2.1.0/source/examples/concurrency.rs // TODO: Double check: prevent division by zero (everywhere)? Or use div_checked? Inf is not acceptable!! // // OPTIMIZATIONS // TODO: call add_target asynchronously to avoid blocking on the relatively long call to .train()? // TODO: use stack-based variable length data types https://gist.github.com/jFransham/369a86eff00e5f280ed25121454acec1#use-stack-based-variable-length-datatypes // TODO: something stack-allocated like arrayvec = "0.4.7"? // TODO: training: preprocess is called for each perturbation. May be best to have preprocess return an image, or have it modify in place. // TODO: carefully track data dependencies in predict function (but get a working version first!) // TODO: in general: avoid .collect()'ing iterators where possible // TODO: update routine can use more in-place modifications to reduce space complexity and allocs // TODO: update routine: benchmark initialization of Gaussian peak on target coordinates. // TODO: in general: remove allocating functions by reusing buffers where possible (such as self.prev's) fn preprocess(image: &GrayImage) -> Vec<f32> { let mut prepped: Vec<f32> = image .pixels() // convert the pixel to u8 and then to f32 .map(|p| p[0] as f32) // add 1, and take the natural logarithm .map(|p| (p + 1.0).ln()) .collect(); // normalize to mean = 0 (subtract image-wide mean from each pixel) let sum: f32 = prepped.iter().sum(); let mean: f32 = sum / prepped.len() as f32; prepped.iter_mut().for_each(|p| *p = *p - mean); // normalize to norm = 1, if possible let u: f32 = prepped.iter().map(|a| a * a).sum(); let norm = u.sqrt(); if norm != 0.0 { prepped.iter_mut().for_each(|e| *e = *e / norm) } // multiply each pixel by a cosine window let (width, height) = image.dimensions(); let mut position = 0; for i in 0..width { for j in 0..height { let cww = ((f32::consts::PI * i as f32) / (width - 1) as f32).sin(); let cwh = ((f32::consts::PI * j as f32) / (height - 1) as f32).sin(); prepped[position] = cww.min(cwh) * prepped[position]; position += 1; } } return prepped; } type Identifier = u32; #[derive(Debug)] pub struct MultiMosseTracker { // we also store the tracker's numeric ID, and the amount of times it did not make the PSR threshold. trackers: Vec<(Identifier, u32, MosseTracker)>, // the global tracker settings settings: MosseTrackerSettings, // how many times a tracker is allowed to fail the PSR threshold desperation_level: u32, } impl MultiMosseTracker { pub fn new(settings: MosseTrackerSettings, desperation_level: u32) -> MultiMosseTracker { return MultiMosseTracker { trackers: Vec::new(), settings: settings, desperation_level: desperation_level, }; } pub fn add_or_replace_target(&mut self, id: Identifier, coords: (u32, u32), frame: &GrayImage) { // Add a target by specifying its coords and a new ID. // Specify an existing ID to replace an existing tracked target. // create a new tracker for this target and train it let mut new_tracker = MosseTracker::new(&self.settings); new_tracker.train(frame, coords); match self.trackers.iter_mut().find(|tracker| tracker.0 == id) { Some(tuple) => { tuple.1 = 0; tuple.2 = new_tracker; } // add the tracker to the map _ => self.trackers.push((id, 0, new_tracker)), }; } pub fn track(&mut self, frame: &GrayImage) -> Vec<(Identifier, Prediction)> { let mut predictions: Vec<(Identifier, Prediction)> = Vec::new(); for (id, death_watch, tracker) in &mut self.trackers { // compute the location of the object in the new frame and save it let pred = tracker.track_new_frame(frame); predictions.push((*id, pred)); // if the tracker made the PSR threshold, update it. // if not, we increment its death ticker. if tracker.last_psr > self.settings.psr_threshold { tracker.update(frame); *death_watch = 0u32; } else { *death_watch += 1; } } // prune all filters with an expired death ticker let level = &self.desperation_level; self.trackers .retain(|(_id, death_count, _tracker)| death_count < level); return predictions; } pub fn dump_filter_reals(&self) -> Vec<GrayImage> { return self.trackers.iter().map(|t| t.2.dump_filter().0).collect(); } pub fn size(&self) -> usize { self.trackers.len() } } pub struct Prediction { pub location: (u32, u32), pub psr: f32, } pub struct MosseTracker { filter: Vec<Complex<f32>>, // constants frame height frame_width: u32, frame_height: u32, // stores dimensions of tracking window and its center // window is square for now, this variable contains the size of the square edge window_size: u32, current_target_center: (u32, u32), // represents center in frame // the 'target' (G). A single Gaussian peak centered at the tracking window. target: Vec<Complex<f32>>, // constants: learning rate and PSR threshold eta: f32, regularization: f32, // not super important for MOSSE: see paper fig 4. // the previous Ai and Bi last_top: Vec<Complex<f32>>, last_bottom: Vec<Complex<f32>>, // the previous psr pub last_psr: f32, // thread-safe FFT objects containing precomputed parameters for this input data size. fft: Arc<dyn Fft<f32>>, inv_fft: Arc<dyn Fft<f32>>, } impl Debug for MosseTracker { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("MosseTracker") .field("filter", &self.filter) .field("frame_width", &self.frame_width) .field("frame_height", &self.frame_height) .field("window_size", &self.window_size) .field("current_target_center", &self.current_target_center) .field("target", &self.target) .field("eta", &self.eta) .field("regularization", &self.regularization) .field("last_top", &self.last_top) .field("last_bottom", &self.last_bottom) .field("last_psr", &self.last_psr) // These fields don't implement Debug, so I can't use the #[derive(Debug)] impl. // .field("fft", &self.fft) // .field("inv_fft", &self.inv_fft) .finish() } } #[derive(Debug)] pub struct MosseTrackerSettings { pub width: u32, pub height: u32, pub window_size: u32, pub learning_rate: f32, pub psr_threshold: f32, pub regularization: f32, } #[allow(non_snake_case)] impl MosseTracker { pub fn new(settings: &MosseTrackerSettings) -> MosseTracker { // parameterize the FFT objects let mut planner = FftPlanner::new(); let mut inv_planner = FftPlanner::new(); // NOTE: we initialize the FFTs based on the size of the window let length = (settings.window_size * settings.window_size) as usize; let fft = planner.plan_fft_forward(length); let inv_fft = inv_planner.plan_fft_inverse(length); // initialize the filter and its top and bottom parts with zeroes. let filter = vec![Complex::zero(); length]; let top = vec![Complex::zero(); length]; let bottom = vec![Complex::zero(); length]; // initialize the target output map (G), with a compact Gaussian peak centered on the target object. // In the Bolme paper, this map is called gi. let mut target: Vec<Complex<f32>> = build_target(settings.window_size, settings.window_size) .into_iter() .map(|p| Complex::new(p as f32, 0.0)) .collect(); fft.process(&mut target); return MosseTracker { filter, last_top: top, last_bottom: bottom, last_psr: 0.0, eta: settings.learning_rate, regularization: settings.regularization, target, fft, inv_fft, frame_width: settings.width, frame_height: settings.height, window_size: settings.window_size, current_target_center: (0, 0), }; } fn compute_2dfft(&self, imagedata: Vec<f32>) -> Vec<Complex<f32>> { let mut buffer: Vec<Complex<f32>> = imagedata .into_iter() .map(|p| Complex::new(p as f32, 0.0)) .collect(); // fft.process() CONSUMES the input buffer as scratch space, make sure it is not reused self.fft.process(&mut buffer); return buffer; } // Train a new filter on the first frame in which the object occurs pub fn train(&mut self, input_frame: &GrayImage, target_center: (u32, u32)) { // store the target center as the current self.current_target_center = target_center; // cut out the training template by cropping let window = &window_crop( input_frame, self.window_size, self.window_size, target_center, ); #[cfg(debug_assertions)] { window.save("WINDOW.png").unwrap(); } // build an iterator that produces training frames that have been slightly rotated according to a theta value. let rotated_frames = [ 0.02, -0.02, 0.05, -0.05, 0.07, -0.07, 0.09, -0.09, 1.1, -1.1, 1.3, -1.3, 1.5, -1.5, 2.0, -2.0, ] .iter() .map(|rad| { // Rotate an image clockwise about its center by theta radians. let training_frame = rotate_about_center(window, *rad, Interpolation::Nearest, Luma([0])); #[cfg(debug_assertions)] { training_frame .save(format!("training_frame_rotated_theta_{}.png", rad)) .unwrap(); } return training_frame; }); // build an iterator that produces training frames that have been slightly scaled to various degrees ('zoomed') let scaled_frames = [0.8, 0.9, 1.1, 1.2].into_iter().map(|scalefactor| { let scale = Projection::scale(scalefactor, scalefactor); let scaled_training_frame = warp(&window, &scale, Interpolation::Nearest, Luma([0])); #[cfg(debug_assertions)] { scaled_training_frame .save(format!("training_frame_scaled_{}.png", scalefactor)) .unwrap(); } return scaled_training_frame; }); // Chain these iterators together. // Note that we add the initial, unperturbed training frame as first in line. let training_frames = std::iter::once(window) .cloned() .chain(rotated_frames) .chain(scaled_frames); // TODO: scaling is not ready yet // .chain(scaled_frames); let mut training_frame_count = 0; for training_frame in training_frames { // preprocess the training frame using preprocess() let vectorized = preprocess(&training_frame); // calculate the 2D FFT of the preprocessed frame: FFT(fi) = Fi let Fi = self.compute_2dfft(vectorized); // compute the complex conjugate of Fi, Fi*. let Fi_star: Vec<Complex<f32>> = Fi.iter().map(|e| e.conj()).collect(); // compute the initial filter let top = self.target.iter().zip(Fi_star.iter()).map(|(g, f)| g * f); let bottom = Fi.iter().zip(Fi_star.iter()).map(|(f, f_star)| f * f_star); // // add the values to the running sum self.last_top .iter_mut() .zip(top) .for_each(|(running, new)| *running += new); self.last_bottom .iter_mut() .zip(bottom) .for_each(|(running, new)| *running += new); training_frame_count += 1 } // divide the values of the top and bottom filters by the number of training perturbations used self.last_top .iter_mut() .for_each(|e| *e /= training_frame_count as f32); self.last_bottom .iter_mut() .for_each(|e| *e /= training_frame_count as f32); // compute the filter by dividing Ai and Bi elementwise // note that we add a small quantity to avoid dividing by zero, which would yield NaN's. self.filter = self .last_top .iter() .zip(&self.last_bottom) .map(|(a, b)| a / b + self.regularization) .collect(); #[cfg(debug_assertions)] { println!( "current center of target in frame: x={}, y={}", self.current_target_center.0, self.current_target_center.1 ); } } pub fn track_new_frame(&mut self, frame: &GrayImage) -> Prediction { // cut out the training template by cropping let window = window_crop( frame, self.window_size, self.window_size, self.current_target_center, ); // preprocess the image using preprocess() let vectorized = preprocess(&window); // calculate the 2D FFT of the preprocessed image: FFT(fi) = Fi let Fi = self.compute_2dfft(vectorized); // elementwise multiplication of F with filter H gives Gi let mut corr_map_gi: Vec<Complex<f32>> = Fi.iter().zip(&self.filter).map(|(a, b)| a * b).collect(); // NOTE: Gi is garbage after this call self.inv_fft.process(&mut corr_map_gi); // find the max value of the filtered image 'gi', along with the position of the maximum let (maxind, max_complex) = corr_map_gi .iter() .enumerate() .max_by(|a, b| { // filtered (gi) is still complex at this point, we only care about the real part a.1.re.partial_cmp(&b.1.re).unwrap_or(Ordering::Equal) }) .unwrap(); // we can unwrap the result of max_by(), as we are sure filtered.len() > 0 // convert the array index of the max to the coordinates in the window let max_coord_in_window = index_to_coords(self.window_size, maxind as u32); let window_half = (self.window_size / 2) as i32; let x_delta = max_coord_in_window.0 as i32 - window_half; let y_delta = max_coord_in_window.1 as i32 - window_half; let x_max = self.frame_width as i32 - window_half; let y_max = self.frame_height as i32 - window_half; #[cfg(debug_assertions)] { println!( "distance of new in-window max from window center: x = {}, y = {}", x_delta, y_delta, ); } // compute the max coord in the frame by looking at the shift of the window center let new_x = (self.current_target_center.0 as i32 + x_delta) .min(x_max) .max(window_half); let new_y = (self.current_target_center.1 as i32 + y_delta) .min(y_max) .max(window_half); self.current_target_center = (new_x as u32, new_y as u32); // compute PSR // Note that we re-use the computed max and its coordinate for downstream simplicity self.last_psr = compute_psr( &corr_map_gi, self.window_size, self.window_size, max_complex.re, max_coord_in_window, ); return Prediction { location: self.current_target_center, psr: self.last_psr, }; } // update the filter fn update(&mut self, frame: &GrayImage) { // cut out the training template by cropping let window = window_crop( frame, self.window_size, self.window_size, self.current_target_center, ); // preprocess the image using preprocess() let vectorized = preprocess(&window); // calculate the 2D FFT of the preprocessed image: FFT(fi) = Fi let new_Fi = self.compute_2dfft(vectorized); //// Update the filter using the prediction // compute the complex conjugate of Fi, Fi*. let Fi_star: Vec<Complex<f32>> = new_Fi.iter().map(|e| e.conj()).collect(); // compute Ai (top) and Bi (bottom) using F*, G, and the learning rate (see paper) let one_minus_eta = 1.0 - self.eta; // update the 'top' of the filter update equation self.last_top = self .target .iter() .zip(&Fi_star) .zip(&self.last_top) .map(|((g, f), prev)| self.eta * (g * f) + (one_minus_eta * prev)) .collect(); // update the 'bottom' of the filter update equation self.last_bottom = new_Fi .iter() .zip(&Fi_star) .zip(&self.last_bottom) .map(|((f, f_star), prev)| self.eta * (f * f_star) + (one_minus_eta * prev)) .collect(); // compute the new filter H* by dividing Ai and Bi elementwise self.filter = self .last_top .iter() .zip(&self.last_bottom) .map(|(a, b)| a / b) .collect(); } // debug method to dump the latest filter to an inspectable image pub fn dump_filter( &self, ) -> ( ImageBuffer<Luma<u8>, Vec<u8>>, ImageBuffer<Luma<u8>, Vec<u8>>, ) { // get the filter out of fourier space // NOTE: input is garbage after this call to inv_fft.process(), so we clone the filter first. let mut h = self.filter.clone(); self.inv_fft.process(&mut h); // turn the real and imaginary values of the filter into separate grayscale images let realfilter = h.iter().map(|c| c.re).collect(); let imfilter = h.iter().map(|c| c.im).collect(); return ( to_imgbuf(&realfilter, self.window_size, self.window_size), to_imgbuf(&imfilter, self.window_size, self.window_size), ); } } fn window_crop( input_frame: &GrayImage, window_width: u32, window_height: u32, center: (u32, u32), ) -> GrayImage { let window = imageops::crop( &mut input_frame.clone(), center .0 .saturating_sub(window_width / 2) .min(input_frame.width() - window_width), center .1 .saturating_sub(window_height / 2) .min(input_frame.height() - window_height), window_width, window_height, ) .to_image(); return window; } fn build_target(window_width: u32, window_height: u32) -> Vec<f32> { let mut target_gi = vec![0f32; (window_width * window_height) as usize]; // Optional: let the sigma depend on the window size (Galoogahi et al. (2015). Correlation Filters with Limited Boundaries) // let sigma = ((window_width * window_height) as f32).sqrt() / 16.0; // let variance = sigma * sigma; let variance = 2.0; // create gaussian peak at the center coordinates let center_x = window_width / 2; let center_y = window_height / 2; for x in 0..window_width { for y in 0..window_height { let distx: f32 = x as f32 - center_x as f32; let disty: f32 = y as f32 - center_y as f32; // apply a crude univariate Gaussian density function target_gi[((y * window_width) + x) as usize] = (-((distx * distx) + (disty * disty) / variance)).exp() } } return target_gi; } // function for debugging the shape of the target // output only depends on the provided target_coords pub fn dump_target(window_width: u32, window_height: u32) -> ImageBuffer<Luma<u8>, Vec<u8>> { let trgt = build_target(window_width, window_height); let normalized = trgt.iter().map(|a| a * 255.0).collect(); return to_imgbuf(&normalized, window_width, window_height); } fn compute_psr( predicted: &Vec<Complex<f32>>, width: u32, height: u32, max: f32, maxpos: (u32, u32), ) -> f32 { // uses running updates of standard deviation and mean let mut running_sum = 0.0; let mut running_sd = 0.0; for e in predicted { running_sum += e.re; running_sd += e.re * e.re; } // subtract the values of a 11*11 window around the max from the running sd and sum // TODO: look up: why 11*11, and not something simpler like 12*12? let max_x = maxpos.0 as i32; let max_y = maxpos.1 as i32; let window_left = (max_x - 5).max(0); let window_right = (max_x + 6).min(width as i32); let window_top = (max_y - 5).min(0); // note: named according to CG conventions let window_bottom = (max_y + 6).min(height as i32); for x in window_left..window_right { for y in window_bottom..window_top { let ind = (y * width as i32 + x) as usize; let val = predicted[ind].re; running_sd -= val * val; running_sum -= val; } } // we need to subtract 11*11 window from predicted.len() to get the sidelobe_size let sidelobe_size = (predicted.len() - (11 * 11)) as f32; let mean_sl = running_sum / sidelobe_size; let sd_sl = ((running_sd / sidelobe_size) - (mean_sl * mean_sl)).sqrt(); let psr = (max - mean_sl) / sd_sl; return psr; } fn index_to_coords(width: u32, index: u32) -> (u32, u32) { // modulo/remainder ops are theoretically O(1) // checked_rem returns None if rhs == 0, which would indicate an upstream error (width == 0). let x = index.checked_rem(width).unwrap(); // checked sub returns None if overflow occurred, which is also a panicable offense. // checked_div returns None if rhs == 0, which would indicate an upstream error (width == 0). let y = (index.checked_sub(x).unwrap()).checked_div(width).unwrap(); return (x, y); } pub fn to_imgbuf(buf: &Vec<f32>, width: u32, height: u32) -> ImageBuffer<Luma<u8>, Vec<u8>>
// TODO: below tests are used as a scratch pad and for syntax experiments, not serious unit testing. #[cfg(test)] mod tests { use super::*; #[test] fn sanity_test_max_by() { let filtered: Vec<f32> = vec![1.0, 2.0, 3.0, 4.0, 5.0]; let maxel = filtered .iter() .enumerate() .max_by(|a, b| { // filtered (gi) is still complex at this point, we only care about the real part a.1.partial_cmp(&b.1).unwrap_or(Ordering::Equal) }) .unwrap(); assert_eq!(maxel, (4usize, &5.0f32)); } #[test] fn am_i_still_sane() { assert_eq!( Complex::new(1.0, -3.0) * Complex::new(2.0, 5.0), Complex::new(17.0, -1.0) ); } #[test] fn unique_identifier() { let width = 64; let height = 64; let frame = GrayImage::new(width, height); let settings = MosseTrackerSettings { window_size: 16, width, height, regularization: 0.001, learning_rate: 0.05, psr_threshold: 7.0, }; let mut multi_tracker = MultiMosseTracker::new(settings, 3); assert_eq!(multi_tracker.size(), 0); multi_tracker.add_or_replace_target(0, (0, 0), &frame); assert_eq!(multi_tracker.size(), 1); assert_eq!( multi_tracker .trackers .iter() .find(|t| t.0 == 0) .unwrap() .2 .current_target_center, (0, 0) ); multi_tracker.add_or_replace_target(1, (10, 0), &frame); assert_eq!(multi_tracker.size(), 2); multi_tracker.add_or_replace_target(0, (10, 0), &frame); assert_eq!(multi_tracker.size(), 2); assert_eq!( multi_tracker .trackers .iter() .find(|t| t.0 == 0) .unwrap() .2 .current_target_center, (10, 0) ); } }
{ ImageBuffer::from_vec(width, height, buf.iter().map(|c| *c as u8).collect()).unwrap() }
identifier_body
lib.rs
extern crate image; extern crate imageproc; extern crate rustfft; use image::{imageops, GrayImage, ImageBuffer, Luma}; use imageproc::geometric_transformations::Projection; use imageproc::geometric_transformations::{rotate_about_center, warp, Interpolation}; use rustfft::num_complex::Complex; use rustfft::num_traits::Zero; use rustfft::{Fft, FftPlanner}; use std::cmp::Ordering; use std::f32; use std::fmt::Debug; use std::sync::Arc; #[cfg(target_arch = "wasm32")] pub mod wasm; // TODO: use constant declarations wherever possible // TODO: refactor the unwrap statement into match statements wherever we can't be certain a result exists. // TODO: behaviour at edge of frame: target may not leave frame, but filter will screw up anyway due to cropping. Move target coord freely within template? // TODO: improve initial filter quality: additional affine perturbations, like scaling (zooming)? // TODO: 11x11 window around peak for PSR calculation is arbitrary and seems biased towards larger video feeds? // TODO: make k (number of perturbarions) a hyperparameter. k = 0 should not be allowed as it is senseless. // TODO: FFT objects may be thread safe (Arc), but are they blocking during concurrent calls? See https://docs.rs/crate/rustfft/2.1.0/source/examples/concurrency.rs // TODO: Double check: prevent division by zero (everywhere)? Or use div_checked? Inf is not acceptable!! // // OPTIMIZATIONS // TODO: call add_target asynchronously to avoid blocking on the relatively long call to .train()? // TODO: use stack-based variable length data types https://gist.github.com/jFransham/369a86eff00e5f280ed25121454acec1#use-stack-based-variable-length-datatypes // TODO: something stack-allocated like arrayvec = "0.4.7"? // TODO: training: preprocess is called for each perturbation. May be best to have preprocess return an image, or have it modify in place. // TODO: carefully track data dependencies in predict function (but get a working version first!) // TODO: in general: avoid .collect()'ing iterators where possible // TODO: update routine can use more in-place modifications to reduce space complexity and allocs // TODO: update routine: benchmark initialization of Gaussian peak on target coordinates. // TODO: in general: remove allocating functions by reusing buffers where possible (such as self.prev's) fn preprocess(image: &GrayImage) -> Vec<f32> { let mut prepped: Vec<f32> = image .pixels() // convert the pixel to u8 and then to f32 .map(|p| p[0] as f32) // add 1, and take the natural logarithm .map(|p| (p + 1.0).ln()) .collect(); // normalize to mean = 0 (subtract image-wide mean from each pixel) let sum: f32 = prepped.iter().sum(); let mean: f32 = sum / prepped.len() as f32; prepped.iter_mut().for_each(|p| *p = *p - mean); // normalize to norm = 1, if possible let u: f32 = prepped.iter().map(|a| a * a).sum(); let norm = u.sqrt(); if norm != 0.0 { prepped.iter_mut().for_each(|e| *e = *e / norm) } // multiply each pixel by a cosine window let (width, height) = image.dimensions(); let mut position = 0; for i in 0..width { for j in 0..height { let cww = ((f32::consts::PI * i as f32) / (width - 1) as f32).sin(); let cwh = ((f32::consts::PI * j as f32) / (height - 1) as f32).sin(); prepped[position] = cww.min(cwh) * prepped[position]; position += 1; } } return prepped; } type Identifier = u32; #[derive(Debug)] pub struct MultiMosseTracker { // we also store the tracker's numeric ID, and the amount of times it did not make the PSR threshold. trackers: Vec<(Identifier, u32, MosseTracker)>, // the global tracker settings settings: MosseTrackerSettings, // how many times a tracker is allowed to fail the PSR threshold desperation_level: u32, } impl MultiMosseTracker { pub fn new(settings: MosseTrackerSettings, desperation_level: u32) -> MultiMosseTracker { return MultiMosseTracker { trackers: Vec::new(), settings: settings, desperation_level: desperation_level, }; } pub fn add_or_replace_target(&mut self, id: Identifier, coords: (u32, u32), frame: &GrayImage) { // Add a target by specifying its coords and a new ID. // Specify an existing ID to replace an existing tracked target. // create a new tracker for this target and train it let mut new_tracker = MosseTracker::new(&self.settings); new_tracker.train(frame, coords); match self.trackers.iter_mut().find(|tracker| tracker.0 == id) { Some(tuple) => { tuple.1 = 0; tuple.2 = new_tracker; } // add the tracker to the map _ => self.trackers.push((id, 0, new_tracker)), }; } pub fn track(&mut self, frame: &GrayImage) -> Vec<(Identifier, Prediction)> { let mut predictions: Vec<(Identifier, Prediction)> = Vec::new(); for (id, death_watch, tracker) in &mut self.trackers { // compute the location of the object in the new frame and save it let pred = tracker.track_new_frame(frame); predictions.push((*id, pred)); // if the tracker made the PSR threshold, update it. // if not, we increment its death ticker. if tracker.last_psr > self.settings.psr_threshold { tracker.update(frame); *death_watch = 0u32; } else { *death_watch += 1; } } // prune all filters with an expired death ticker let level = &self.desperation_level; self.trackers .retain(|(_id, death_count, _tracker)| death_count < level); return predictions; } pub fn dump_filter_reals(&self) -> Vec<GrayImage> { return self.trackers.iter().map(|t| t.2.dump_filter().0).collect(); } pub fn
(&self) -> usize { self.trackers.len() } } pub struct Prediction { pub location: (u32, u32), pub psr: f32, } pub struct MosseTracker { filter: Vec<Complex<f32>>, // constants frame height frame_width: u32, frame_height: u32, // stores dimensions of tracking window and its center // window is square for now, this variable contains the size of the square edge window_size: u32, current_target_center: (u32, u32), // represents center in frame // the 'target' (G). A single Gaussian peak centered at the tracking window. target: Vec<Complex<f32>>, // constants: learning rate and PSR threshold eta: f32, regularization: f32, // not super important for MOSSE: see paper fig 4. // the previous Ai and Bi last_top: Vec<Complex<f32>>, last_bottom: Vec<Complex<f32>>, // the previous psr pub last_psr: f32, // thread-safe FFT objects containing precomputed parameters for this input data size. fft: Arc<dyn Fft<f32>>, inv_fft: Arc<dyn Fft<f32>>, } impl Debug for MosseTracker { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("MosseTracker") .field("filter", &self.filter) .field("frame_width", &self.frame_width) .field("frame_height", &self.frame_height) .field("window_size", &self.window_size) .field("current_target_center", &self.current_target_center) .field("target", &self.target) .field("eta", &self.eta) .field("regularization", &self.regularization) .field("last_top", &self.last_top) .field("last_bottom", &self.last_bottom) .field("last_psr", &self.last_psr) // These fields don't implement Debug, so I can't use the #[derive(Debug)] impl. // .field("fft", &self.fft) // .field("inv_fft", &self.inv_fft) .finish() } } #[derive(Debug)] pub struct MosseTrackerSettings { pub width: u32, pub height: u32, pub window_size: u32, pub learning_rate: f32, pub psr_threshold: f32, pub regularization: f32, } #[allow(non_snake_case)] impl MosseTracker { pub fn new(settings: &MosseTrackerSettings) -> MosseTracker { // parameterize the FFT objects let mut planner = FftPlanner::new(); let mut inv_planner = FftPlanner::new(); // NOTE: we initialize the FFTs based on the size of the window let length = (settings.window_size * settings.window_size) as usize; let fft = planner.plan_fft_forward(length); let inv_fft = inv_planner.plan_fft_inverse(length); // initialize the filter and its top and bottom parts with zeroes. let filter = vec![Complex::zero(); length]; let top = vec![Complex::zero(); length]; let bottom = vec![Complex::zero(); length]; // initialize the target output map (G), with a compact Gaussian peak centered on the target object. // In the Bolme paper, this map is called gi. let mut target: Vec<Complex<f32>> = build_target(settings.window_size, settings.window_size) .into_iter() .map(|p| Complex::new(p as f32, 0.0)) .collect(); fft.process(&mut target); return MosseTracker { filter, last_top: top, last_bottom: bottom, last_psr: 0.0, eta: settings.learning_rate, regularization: settings.regularization, target, fft, inv_fft, frame_width: settings.width, frame_height: settings.height, window_size: settings.window_size, current_target_center: (0, 0), }; } fn compute_2dfft(&self, imagedata: Vec<f32>) -> Vec<Complex<f32>> { let mut buffer: Vec<Complex<f32>> = imagedata .into_iter() .map(|p| Complex::new(p as f32, 0.0)) .collect(); // fft.process() CONSUMES the input buffer as scratch space, make sure it is not reused self.fft.process(&mut buffer); return buffer; } // Train a new filter on the first frame in which the object occurs pub fn train(&mut self, input_frame: &GrayImage, target_center: (u32, u32)) { // store the target center as the current self.current_target_center = target_center; // cut out the training template by cropping let window = &window_crop( input_frame, self.window_size, self.window_size, target_center, ); #[cfg(debug_assertions)] { window.save("WINDOW.png").unwrap(); } // build an iterator that produces training frames that have been slightly rotated according to a theta value. let rotated_frames = [ 0.02, -0.02, 0.05, -0.05, 0.07, -0.07, 0.09, -0.09, 1.1, -1.1, 1.3, -1.3, 1.5, -1.5, 2.0, -2.0, ] .iter() .map(|rad| { // Rotate an image clockwise about its center by theta radians. let training_frame = rotate_about_center(window, *rad, Interpolation::Nearest, Luma([0])); #[cfg(debug_assertions)] { training_frame .save(format!("training_frame_rotated_theta_{}.png", rad)) .unwrap(); } return training_frame; }); // build an iterator that produces training frames that have been slightly scaled to various degrees ('zoomed') let scaled_frames = [0.8, 0.9, 1.1, 1.2].into_iter().map(|scalefactor| { let scale = Projection::scale(scalefactor, scalefactor); let scaled_training_frame = warp(&window, &scale, Interpolation::Nearest, Luma([0])); #[cfg(debug_assertions)] { scaled_training_frame .save(format!("training_frame_scaled_{}.png", scalefactor)) .unwrap(); } return scaled_training_frame; }); // Chain these iterators together. // Note that we add the initial, unperturbed training frame as first in line. let training_frames = std::iter::once(window) .cloned() .chain(rotated_frames) .chain(scaled_frames); // TODO: scaling is not ready yet // .chain(scaled_frames); let mut training_frame_count = 0; for training_frame in training_frames { // preprocess the training frame using preprocess() let vectorized = preprocess(&training_frame); // calculate the 2D FFT of the preprocessed frame: FFT(fi) = Fi let Fi = self.compute_2dfft(vectorized); // compute the complex conjugate of Fi, Fi*. let Fi_star: Vec<Complex<f32>> = Fi.iter().map(|e| e.conj()).collect(); // compute the initial filter let top = self.target.iter().zip(Fi_star.iter()).map(|(g, f)| g * f); let bottom = Fi.iter().zip(Fi_star.iter()).map(|(f, f_star)| f * f_star); // // add the values to the running sum self.last_top .iter_mut() .zip(top) .for_each(|(running, new)| *running += new); self.last_bottom .iter_mut() .zip(bottom) .for_each(|(running, new)| *running += new); training_frame_count += 1 } // divide the values of the top and bottom filters by the number of training perturbations used self.last_top .iter_mut() .for_each(|e| *e /= training_frame_count as f32); self.last_bottom .iter_mut() .for_each(|e| *e /= training_frame_count as f32); // compute the filter by dividing Ai and Bi elementwise // note that we add a small quantity to avoid dividing by zero, which would yield NaN's. self.filter = self .last_top .iter() .zip(&self.last_bottom) .map(|(a, b)| a / b + self.regularization) .collect(); #[cfg(debug_assertions)] { println!( "current center of target in frame: x={}, y={}", self.current_target_center.0, self.current_target_center.1 ); } } pub fn track_new_frame(&mut self, frame: &GrayImage) -> Prediction { // cut out the training template by cropping let window = window_crop( frame, self.window_size, self.window_size, self.current_target_center, ); // preprocess the image using preprocess() let vectorized = preprocess(&window); // calculate the 2D FFT of the preprocessed image: FFT(fi) = Fi let Fi = self.compute_2dfft(vectorized); // elementwise multiplication of F with filter H gives Gi let mut corr_map_gi: Vec<Complex<f32>> = Fi.iter().zip(&self.filter).map(|(a, b)| a * b).collect(); // NOTE: Gi is garbage after this call self.inv_fft.process(&mut corr_map_gi); // find the max value of the filtered image 'gi', along with the position of the maximum let (maxind, max_complex) = corr_map_gi .iter() .enumerate() .max_by(|a, b| { // filtered (gi) is still complex at this point, we only care about the real part a.1.re.partial_cmp(&b.1.re).unwrap_or(Ordering::Equal) }) .unwrap(); // we can unwrap the result of max_by(), as we are sure filtered.len() > 0 // convert the array index of the max to the coordinates in the window let max_coord_in_window = index_to_coords(self.window_size, maxind as u32); let window_half = (self.window_size / 2) as i32; let x_delta = max_coord_in_window.0 as i32 - window_half; let y_delta = max_coord_in_window.1 as i32 - window_half; let x_max = self.frame_width as i32 - window_half; let y_max = self.frame_height as i32 - window_half; #[cfg(debug_assertions)] { println!( "distance of new in-window max from window center: x = {}, y = {}", x_delta, y_delta, ); } // compute the max coord in the frame by looking at the shift of the window center let new_x = (self.current_target_center.0 as i32 + x_delta) .min(x_max) .max(window_half); let new_y = (self.current_target_center.1 as i32 + y_delta) .min(y_max) .max(window_half); self.current_target_center = (new_x as u32, new_y as u32); // compute PSR // Note that we re-use the computed max and its coordinate for downstream simplicity self.last_psr = compute_psr( &corr_map_gi, self.window_size, self.window_size, max_complex.re, max_coord_in_window, ); return Prediction { location: self.current_target_center, psr: self.last_psr, }; } // update the filter fn update(&mut self, frame: &GrayImage) { // cut out the training template by cropping let window = window_crop( frame, self.window_size, self.window_size, self.current_target_center, ); // preprocess the image using preprocess() let vectorized = preprocess(&window); // calculate the 2D FFT of the preprocessed image: FFT(fi) = Fi let new_Fi = self.compute_2dfft(vectorized); //// Update the filter using the prediction // compute the complex conjugate of Fi, Fi*. let Fi_star: Vec<Complex<f32>> = new_Fi.iter().map(|e| e.conj()).collect(); // compute Ai (top) and Bi (bottom) using F*, G, and the learning rate (see paper) let one_minus_eta = 1.0 - self.eta; // update the 'top' of the filter update equation self.last_top = self .target .iter() .zip(&Fi_star) .zip(&self.last_top) .map(|((g, f), prev)| self.eta * (g * f) + (one_minus_eta * prev)) .collect(); // update the 'bottom' of the filter update equation self.last_bottom = new_Fi .iter() .zip(&Fi_star) .zip(&self.last_bottom) .map(|((f, f_star), prev)| self.eta * (f * f_star) + (one_minus_eta * prev)) .collect(); // compute the new filter H* by dividing Ai and Bi elementwise self.filter = self .last_top .iter() .zip(&self.last_bottom) .map(|(a, b)| a / b) .collect(); } // debug method to dump the latest filter to an inspectable image pub fn dump_filter( &self, ) -> ( ImageBuffer<Luma<u8>, Vec<u8>>, ImageBuffer<Luma<u8>, Vec<u8>>, ) { // get the filter out of fourier space // NOTE: input is garbage after this call to inv_fft.process(), so we clone the filter first. let mut h = self.filter.clone(); self.inv_fft.process(&mut h); // turn the real and imaginary values of the filter into separate grayscale images let realfilter = h.iter().map(|c| c.re).collect(); let imfilter = h.iter().map(|c| c.im).collect(); return ( to_imgbuf(&realfilter, self.window_size, self.window_size), to_imgbuf(&imfilter, self.window_size, self.window_size), ); } } fn window_crop( input_frame: &GrayImage, window_width: u32, window_height: u32, center: (u32, u32), ) -> GrayImage { let window = imageops::crop( &mut input_frame.clone(), center .0 .saturating_sub(window_width / 2) .min(input_frame.width() - window_width), center .1 .saturating_sub(window_height / 2) .min(input_frame.height() - window_height), window_width, window_height, ) .to_image(); return window; } fn build_target(window_width: u32, window_height: u32) -> Vec<f32> { let mut target_gi = vec![0f32; (window_width * window_height) as usize]; // Optional: let the sigma depend on the window size (Galoogahi et al. (2015). Correlation Filters with Limited Boundaries) // let sigma = ((window_width * window_height) as f32).sqrt() / 16.0; // let variance = sigma * sigma; let variance = 2.0; // create gaussian peak at the center coordinates let center_x = window_width / 2; let center_y = window_height / 2; for x in 0..window_width { for y in 0..window_height { let distx: f32 = x as f32 - center_x as f32; let disty: f32 = y as f32 - center_y as f32; // apply a crude univariate Gaussian density function target_gi[((y * window_width) + x) as usize] = (-((distx * distx) + (disty * disty) / variance)).exp() } } return target_gi; } // function for debugging the shape of the target // output only depends on the provided target_coords pub fn dump_target(window_width: u32, window_height: u32) -> ImageBuffer<Luma<u8>, Vec<u8>> { let trgt = build_target(window_width, window_height); let normalized = trgt.iter().map(|a| a * 255.0).collect(); return to_imgbuf(&normalized, window_width, window_height); } fn compute_psr( predicted: &Vec<Complex<f32>>, width: u32, height: u32, max: f32, maxpos: (u32, u32), ) -> f32 { // uses running updates of standard deviation and mean let mut running_sum = 0.0; let mut running_sd = 0.0; for e in predicted { running_sum += e.re; running_sd += e.re * e.re; } // subtract the values of a 11*11 window around the max from the running sd and sum // TODO: look up: why 11*11, and not something simpler like 12*12? let max_x = maxpos.0 as i32; let max_y = maxpos.1 as i32; let window_left = (max_x - 5).max(0); let window_right = (max_x + 6).min(width as i32); let window_top = (max_y - 5).min(0); // note: named according to CG conventions let window_bottom = (max_y + 6).min(height as i32); for x in window_left..window_right { for y in window_bottom..window_top { let ind = (y * width as i32 + x) as usize; let val = predicted[ind].re; running_sd -= val * val; running_sum -= val; } } // we need to subtract 11*11 window from predicted.len() to get the sidelobe_size let sidelobe_size = (predicted.len() - (11 * 11)) as f32; let mean_sl = running_sum / sidelobe_size; let sd_sl = ((running_sd / sidelobe_size) - (mean_sl * mean_sl)).sqrt(); let psr = (max - mean_sl) / sd_sl; return psr; } fn index_to_coords(width: u32, index: u32) -> (u32, u32) { // modulo/remainder ops are theoretically O(1) // checked_rem returns None if rhs == 0, which would indicate an upstream error (width == 0). let x = index.checked_rem(width).unwrap(); // checked sub returns None if overflow occurred, which is also a panicable offense. // checked_div returns None if rhs == 0, which would indicate an upstream error (width == 0). let y = (index.checked_sub(x).unwrap()).checked_div(width).unwrap(); return (x, y); } pub fn to_imgbuf(buf: &Vec<f32>, width: u32, height: u32) -> ImageBuffer<Luma<u8>, Vec<u8>> { ImageBuffer::from_vec(width, height, buf.iter().map(|c| *c as u8).collect()).unwrap() } // TODO: below tests are used as a scratch pad and for syntax experiments, not serious unit testing. #[cfg(test)] mod tests { use super::*; #[test] fn sanity_test_max_by() { let filtered: Vec<f32> = vec![1.0, 2.0, 3.0, 4.0, 5.0]; let maxel = filtered .iter() .enumerate() .max_by(|a, b| { // filtered (gi) is still complex at this point, we only care about the real part a.1.partial_cmp(&b.1).unwrap_or(Ordering::Equal) }) .unwrap(); assert_eq!(maxel, (4usize, &5.0f32)); } #[test] fn am_i_still_sane() { assert_eq!( Complex::new(1.0, -3.0) * Complex::new(2.0, 5.0), Complex::new(17.0, -1.0) ); } #[test] fn unique_identifier() { let width = 64; let height = 64; let frame = GrayImage::new(width, height); let settings = MosseTrackerSettings { window_size: 16, width, height, regularization: 0.001, learning_rate: 0.05, psr_threshold: 7.0, }; let mut multi_tracker = MultiMosseTracker::new(settings, 3); assert_eq!(multi_tracker.size(), 0); multi_tracker.add_or_replace_target(0, (0, 0), &frame); assert_eq!(multi_tracker.size(), 1); assert_eq!( multi_tracker .trackers .iter() .find(|t| t.0 == 0) .unwrap() .2 .current_target_center, (0, 0) ); multi_tracker.add_or_replace_target(1, (10, 0), &frame); assert_eq!(multi_tracker.size(), 2); multi_tracker.add_or_replace_target(0, (10, 0), &frame); assert_eq!(multi_tracker.size(), 2); assert_eq!( multi_tracker .trackers .iter() .find(|t| t.0 == 0) .unwrap() .2 .current_target_center, (10, 0) ); } }
size
identifier_name
lib.rs
extern crate image; extern crate imageproc; extern crate rustfft; use image::{imageops, GrayImage, ImageBuffer, Luma}; use imageproc::geometric_transformations::Projection; use imageproc::geometric_transformations::{rotate_about_center, warp, Interpolation}; use rustfft::num_complex::Complex; use rustfft::num_traits::Zero; use rustfft::{Fft, FftPlanner}; use std::cmp::Ordering; use std::f32; use std::fmt::Debug; use std::sync::Arc; #[cfg(target_arch = "wasm32")] pub mod wasm; // TODO: use constant declarations wherever possible // TODO: refactor the unwrap statement into match statements wherever we can't be certain a result exists. // TODO: behaviour at edge of frame: target may not leave frame, but filter will screw up anyway due to cropping. Move target coord freely within template? // TODO: improve initial filter quality: additional affine perturbations, like scaling (zooming)? // TODO: 11x11 window around peak for PSR calculation is arbitrary and seems biased towards larger video feeds? // TODO: make k (number of perturbarions) a hyperparameter. k = 0 should not be allowed as it is senseless. // TODO: FFT objects may be thread safe (Arc), but are they blocking during concurrent calls? See https://docs.rs/crate/rustfft/2.1.0/source/examples/concurrency.rs // TODO: Double check: prevent division by zero (everywhere)? Or use div_checked? Inf is not acceptable!! // // OPTIMIZATIONS // TODO: call add_target asynchronously to avoid blocking on the relatively long call to .train()? // TODO: use stack-based variable length data types https://gist.github.com/jFransham/369a86eff00e5f280ed25121454acec1#use-stack-based-variable-length-datatypes // TODO: something stack-allocated like arrayvec = "0.4.7"? // TODO: training: preprocess is called for each perturbation. May be best to have preprocess return an image, or have it modify in place. // TODO: carefully track data dependencies in predict function (but get a working version first!) // TODO: in general: avoid .collect()'ing iterators where possible // TODO: update routine can use more in-place modifications to reduce space complexity and allocs // TODO: update routine: benchmark initialization of Gaussian peak on target coordinates. // TODO: in general: remove allocating functions by reusing buffers where possible (such as self.prev's) fn preprocess(image: &GrayImage) -> Vec<f32> { let mut prepped: Vec<f32> = image .pixels() // convert the pixel to u8 and then to f32 .map(|p| p[0] as f32) // add 1, and take the natural logarithm .map(|p| (p + 1.0).ln()) .collect(); // normalize to mean = 0 (subtract image-wide mean from each pixel) let sum: f32 = prepped.iter().sum(); let mean: f32 = sum / prepped.len() as f32; prepped.iter_mut().for_each(|p| *p = *p - mean); // normalize to norm = 1, if possible let u: f32 = prepped.iter().map(|a| a * a).sum(); let norm = u.sqrt(); if norm != 0.0 { prepped.iter_mut().for_each(|e| *e = *e / norm) } // multiply each pixel by a cosine window let (width, height) = image.dimensions(); let mut position = 0; for i in 0..width { for j in 0..height { let cww = ((f32::consts::PI * i as f32) / (width - 1) as f32).sin(); let cwh = ((f32::consts::PI * j as f32) / (height - 1) as f32).sin(); prepped[position] = cww.min(cwh) * prepped[position]; position += 1; } } return prepped; } type Identifier = u32; #[derive(Debug)] pub struct MultiMosseTracker { // we also store the tracker's numeric ID, and the amount of times it did not make the PSR threshold. trackers: Vec<(Identifier, u32, MosseTracker)>, // the global tracker settings settings: MosseTrackerSettings, // how many times a tracker is allowed to fail the PSR threshold desperation_level: u32, } impl MultiMosseTracker { pub fn new(settings: MosseTrackerSettings, desperation_level: u32) -> MultiMosseTracker { return MultiMosseTracker { trackers: Vec::new(), settings: settings, desperation_level: desperation_level, }; } pub fn add_or_replace_target(&mut self, id: Identifier, coords: (u32, u32), frame: &GrayImage) { // Add a target by specifying its coords and a new ID. // Specify an existing ID to replace an existing tracked target. // create a new tracker for this target and train it let mut new_tracker = MosseTracker::new(&self.settings); new_tracker.train(frame, coords); match self.trackers.iter_mut().find(|tracker| tracker.0 == id) { Some(tuple) => { tuple.1 = 0; tuple.2 = new_tracker; } // add the tracker to the map _ => self.trackers.push((id, 0, new_tracker)), }; } pub fn track(&mut self, frame: &GrayImage) -> Vec<(Identifier, Prediction)> { let mut predictions: Vec<(Identifier, Prediction)> = Vec::new(); for (id, death_watch, tracker) in &mut self.trackers { // compute the location of the object in the new frame and save it let pred = tracker.track_new_frame(frame); predictions.push((*id, pred)); // if the tracker made the PSR threshold, update it. // if not, we increment its death ticker. if tracker.last_psr > self.settings.psr_threshold { tracker.update(frame); *death_watch = 0u32; } else { *death_watch += 1; } } // prune all filters with an expired death ticker let level = &self.desperation_level; self.trackers .retain(|(_id, death_count, _tracker)| death_count < level); return predictions; } pub fn dump_filter_reals(&self) -> Vec<GrayImage> { return self.trackers.iter().map(|t| t.2.dump_filter().0).collect(); } pub fn size(&self) -> usize { self.trackers.len() } } pub struct Prediction { pub location: (u32, u32), pub psr: f32, } pub struct MosseTracker { filter: Vec<Complex<f32>>, // constants frame height frame_width: u32, frame_height: u32, // stores dimensions of tracking window and its center // window is square for now, this variable contains the size of the square edge window_size: u32, current_target_center: (u32, u32), // represents center in frame // the 'target' (G). A single Gaussian peak centered at the tracking window. target: Vec<Complex<f32>>, // constants: learning rate and PSR threshold eta: f32, regularization: f32, // not super important for MOSSE: see paper fig 4. // the previous Ai and Bi last_top: Vec<Complex<f32>>, last_bottom: Vec<Complex<f32>>, // the previous psr pub last_psr: f32, // thread-safe FFT objects containing precomputed parameters for this input data size. fft: Arc<dyn Fft<f32>>, inv_fft: Arc<dyn Fft<f32>>, } impl Debug for MosseTracker { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("MosseTracker") .field("filter", &self.filter) .field("frame_width", &self.frame_width) .field("frame_height", &self.frame_height) .field("window_size", &self.window_size) .field("current_target_center", &self.current_target_center) .field("target", &self.target) .field("eta", &self.eta) .field("regularization", &self.regularization) .field("last_top", &self.last_top) .field("last_bottom", &self.last_bottom) .field("last_psr", &self.last_psr) // These fields don't implement Debug, so I can't use the #[derive(Debug)] impl. // .field("fft", &self.fft) // .field("inv_fft", &self.inv_fft) .finish() } } #[derive(Debug)] pub struct MosseTrackerSettings { pub width: u32, pub height: u32, pub window_size: u32, pub learning_rate: f32, pub psr_threshold: f32, pub regularization: f32, } #[allow(non_snake_case)] impl MosseTracker { pub fn new(settings: &MosseTrackerSettings) -> MosseTracker { // parameterize the FFT objects let mut planner = FftPlanner::new(); let mut inv_planner = FftPlanner::new(); // NOTE: we initialize the FFTs based on the size of the window let length = (settings.window_size * settings.window_size) as usize; let fft = planner.plan_fft_forward(length); let inv_fft = inv_planner.plan_fft_inverse(length); // initialize the filter and its top and bottom parts with zeroes. let filter = vec![Complex::zero(); length]; let top = vec![Complex::zero(); length]; let bottom = vec![Complex::zero(); length]; // initialize the target output map (G), with a compact Gaussian peak centered on the target object. // In the Bolme paper, this map is called gi. let mut target: Vec<Complex<f32>> = build_target(settings.window_size, settings.window_size) .into_iter() .map(|p| Complex::new(p as f32, 0.0)) .collect(); fft.process(&mut target); return MosseTracker { filter, last_top: top, last_bottom: bottom, last_psr: 0.0, eta: settings.learning_rate, regularization: settings.regularization, target, fft, inv_fft, frame_width: settings.width, frame_height: settings.height, window_size: settings.window_size, current_target_center: (0, 0), }; } fn compute_2dfft(&self, imagedata: Vec<f32>) -> Vec<Complex<f32>> { let mut buffer: Vec<Complex<f32>> = imagedata .into_iter() .map(|p| Complex::new(p as f32, 0.0)) .collect(); // fft.process() CONSUMES the input buffer as scratch space, make sure it is not reused self.fft.process(&mut buffer); return buffer; } // Train a new filter on the first frame in which the object occurs pub fn train(&mut self, input_frame: &GrayImage, target_center: (u32, u32)) { // store the target center as the current self.current_target_center = target_center; // cut out the training template by cropping let window = &window_crop( input_frame, self.window_size, self.window_size, target_center, ); #[cfg(debug_assertions)] { window.save("WINDOW.png").unwrap(); } // build an iterator that produces training frames that have been slightly rotated according to a theta value. let rotated_frames = [ 0.02, -0.02, 0.05, -0.05, 0.07, -0.07, 0.09, -0.09, 1.1, -1.1, 1.3, -1.3, 1.5, -1.5, 2.0, -2.0, ] .iter() .map(|rad| { // Rotate an image clockwise about its center by theta radians. let training_frame = rotate_about_center(window, *rad, Interpolation::Nearest, Luma([0])); #[cfg(debug_assertions)] { training_frame .save(format!("training_frame_rotated_theta_{}.png", rad)) .unwrap(); } return training_frame; }); // build an iterator that produces training frames that have been slightly scaled to various degrees ('zoomed') let scaled_frames = [0.8, 0.9, 1.1, 1.2].into_iter().map(|scalefactor| { let scale = Projection::scale(scalefactor, scalefactor); let scaled_training_frame = warp(&window, &scale, Interpolation::Nearest, Luma([0])); #[cfg(debug_assertions)] { scaled_training_frame .save(format!("training_frame_scaled_{}.png", scalefactor)) .unwrap(); } return scaled_training_frame; }); // Chain these iterators together. // Note that we add the initial, unperturbed training frame as first in line. let training_frames = std::iter::once(window) .cloned() .chain(rotated_frames) .chain(scaled_frames); // TODO: scaling is not ready yet // .chain(scaled_frames); let mut training_frame_count = 0; for training_frame in training_frames { // preprocess the training frame using preprocess() let vectorized = preprocess(&training_frame); // calculate the 2D FFT of the preprocessed frame: FFT(fi) = Fi let Fi = self.compute_2dfft(vectorized); // compute the complex conjugate of Fi, Fi*. let Fi_star: Vec<Complex<f32>> = Fi.iter().map(|e| e.conj()).collect(); // compute the initial filter let top = self.target.iter().zip(Fi_star.iter()).map(|(g, f)| g * f); let bottom = Fi.iter().zip(Fi_star.iter()).map(|(f, f_star)| f * f_star); // // add the values to the running sum self.last_top .iter_mut() .zip(top) .for_each(|(running, new)| *running += new); self.last_bottom .iter_mut() .zip(bottom) .for_each(|(running, new)| *running += new); training_frame_count += 1 } // divide the values of the top and bottom filters by the number of training perturbations used self.last_top .iter_mut() .for_each(|e| *e /= training_frame_count as f32); self.last_bottom .iter_mut() .for_each(|e| *e /= training_frame_count as f32); // compute the filter by dividing Ai and Bi elementwise // note that we add a small quantity to avoid dividing by zero, which would yield NaN's. self.filter = self .last_top .iter() .zip(&self.last_bottom) .map(|(a, b)| a / b + self.regularization) .collect(); #[cfg(debug_assertions)] { println!( "current center of target in frame: x={}, y={}", self.current_target_center.0, self.current_target_center.1 ); } } pub fn track_new_frame(&mut self, frame: &GrayImage) -> Prediction { // cut out the training template by cropping let window = window_crop( frame, self.window_size, self.window_size, self.current_target_center, ); // preprocess the image using preprocess() let vectorized = preprocess(&window); // calculate the 2D FFT of the preprocessed image: FFT(fi) = Fi let Fi = self.compute_2dfft(vectorized); // elementwise multiplication of F with filter H gives Gi let mut corr_map_gi: Vec<Complex<f32>> = Fi.iter().zip(&self.filter).map(|(a, b)| a * b).collect(); // NOTE: Gi is garbage after this call self.inv_fft.process(&mut corr_map_gi); // find the max value of the filtered image 'gi', along with the position of the maximum let (maxind, max_complex) = corr_map_gi .iter() .enumerate() .max_by(|a, b| { // filtered (gi) is still complex at this point, we only care about the real part a.1.re.partial_cmp(&b.1.re).unwrap_or(Ordering::Equal) }) .unwrap(); // we can unwrap the result of max_by(), as we are sure filtered.len() > 0 // convert the array index of the max to the coordinates in the window let max_coord_in_window = index_to_coords(self.window_size, maxind as u32); let window_half = (self.window_size / 2) as i32; let x_delta = max_coord_in_window.0 as i32 - window_half; let y_delta = max_coord_in_window.1 as i32 - window_half; let x_max = self.frame_width as i32 - window_half; let y_max = self.frame_height as i32 - window_half; #[cfg(debug_assertions)] { println!( "distance of new in-window max from window center: x = {}, y = {}", x_delta, y_delta, ); } // compute the max coord in the frame by looking at the shift of the window center let new_x = (self.current_target_center.0 as i32 + x_delta) .min(x_max) .max(window_half); let new_y = (self.current_target_center.1 as i32 + y_delta) .min(y_max) .max(window_half); self.current_target_center = (new_x as u32, new_y as u32); // compute PSR // Note that we re-use the computed max and its coordinate for downstream simplicity self.last_psr = compute_psr( &corr_map_gi, self.window_size, self.window_size, max_complex.re, max_coord_in_window, ); return Prediction { location: self.current_target_center, psr: self.last_psr, }; } // update the filter fn update(&mut self, frame: &GrayImage) { // cut out the training template by cropping let window = window_crop( frame, self.window_size, self.window_size, self.current_target_center, ); // preprocess the image using preprocess() let vectorized = preprocess(&window); // calculate the 2D FFT of the preprocessed image: FFT(fi) = Fi let new_Fi = self.compute_2dfft(vectorized); //// Update the filter using the prediction // compute the complex conjugate of Fi, Fi*. let Fi_star: Vec<Complex<f32>> = new_Fi.iter().map(|e| e.conj()).collect(); // compute Ai (top) and Bi (bottom) using F*, G, and the learning rate (see paper) let one_minus_eta = 1.0 - self.eta; // update the 'top' of the filter update equation self.last_top = self .target .iter() .zip(&Fi_star) .zip(&self.last_top) .map(|((g, f), prev)| self.eta * (g * f) + (one_minus_eta * prev)) .collect(); // update the 'bottom' of the filter update equation self.last_bottom = new_Fi .iter() .zip(&Fi_star) .zip(&self.last_bottom) .map(|((f, f_star), prev)| self.eta * (f * f_star) + (one_minus_eta * prev)) .collect(); // compute the new filter H* by dividing Ai and Bi elementwise self.filter = self .last_top .iter() .zip(&self.last_bottom) .map(|(a, b)| a / b) .collect(); } // debug method to dump the latest filter to an inspectable image pub fn dump_filter( &self, ) -> ( ImageBuffer<Luma<u8>, Vec<u8>>, ImageBuffer<Luma<u8>, Vec<u8>>, ) { // get the filter out of fourier space // NOTE: input is garbage after this call to inv_fft.process(), so we clone the filter first. let mut h = self.filter.clone(); self.inv_fft.process(&mut h); // turn the real and imaginary values of the filter into separate grayscale images let realfilter = h.iter().map(|c| c.re).collect(); let imfilter = h.iter().map(|c| c.im).collect(); return ( to_imgbuf(&realfilter, self.window_size, self.window_size), to_imgbuf(&imfilter, self.window_size, self.window_size), ); } } fn window_crop( input_frame: &GrayImage, window_width: u32, window_height: u32, center: (u32, u32), ) -> GrayImage { let window = imageops::crop( &mut input_frame.clone(), center .0 .saturating_sub(window_width / 2) .min(input_frame.width() - window_width), center .1 .saturating_sub(window_height / 2) .min(input_frame.height() - window_height), window_width, window_height, ) .to_image(); return window; } fn build_target(window_width: u32, window_height: u32) -> Vec<f32> { let mut target_gi = vec![0f32; (window_width * window_height) as usize]; // Optional: let the sigma depend on the window size (Galoogahi et al. (2015). Correlation Filters with Limited Boundaries) // let sigma = ((window_width * window_height) as f32).sqrt() / 16.0; // let variance = sigma * sigma; let variance = 2.0; // create gaussian peak at the center coordinates let center_x = window_width / 2; let center_y = window_height / 2; for x in 0..window_width { for y in 0..window_height { let distx: f32 = x as f32 - center_x as f32; let disty: f32 = y as f32 - center_y as f32; // apply a crude univariate Gaussian density function target_gi[((y * window_width) + x) as usize] = (-((distx * distx) + (disty * disty) / variance)).exp() } } return target_gi; } // function for debugging the shape of the target // output only depends on the provided target_coords pub fn dump_target(window_width: u32, window_height: u32) -> ImageBuffer<Luma<u8>, Vec<u8>> { let trgt = build_target(window_width, window_height); let normalized = trgt.iter().map(|a| a * 255.0).collect(); return to_imgbuf(&normalized, window_width, window_height); } fn compute_psr( predicted: &Vec<Complex<f32>>, width: u32, height: u32, max: f32, maxpos: (u32, u32), ) -> f32 { // uses running updates of standard deviation and mean let mut running_sum = 0.0; let mut running_sd = 0.0; for e in predicted { running_sum += e.re; running_sd += e.re * e.re; } // subtract the values of a 11*11 window around the max from the running sd and sum // TODO: look up: why 11*11, and not something simpler like 12*12? let max_x = maxpos.0 as i32; let max_y = maxpos.1 as i32; let window_left = (max_x - 5).max(0); let window_right = (max_x + 6).min(width as i32); let window_top = (max_y - 5).min(0); // note: named according to CG conventions let window_bottom = (max_y + 6).min(height as i32); for x in window_left..window_right { for y in window_bottom..window_top { let ind = (y * width as i32 + x) as usize; let val = predicted[ind].re; running_sd -= val * val; running_sum -= val; } } // we need to subtract 11*11 window from predicted.len() to get the sidelobe_size let sidelobe_size = (predicted.len() - (11 * 11)) as f32; let mean_sl = running_sum / sidelobe_size; let sd_sl = ((running_sd / sidelobe_size) - (mean_sl * mean_sl)).sqrt(); let psr = (max - mean_sl) / sd_sl; return psr; }
// checked sub returns None if overflow occurred, which is also a panicable offense. // checked_div returns None if rhs == 0, which would indicate an upstream error (width == 0). let y = (index.checked_sub(x).unwrap()).checked_div(width).unwrap(); return (x, y); } pub fn to_imgbuf(buf: &Vec<f32>, width: u32, height: u32) -> ImageBuffer<Luma<u8>, Vec<u8>> { ImageBuffer::from_vec(width, height, buf.iter().map(|c| *c as u8).collect()).unwrap() } // TODO: below tests are used as a scratch pad and for syntax experiments, not serious unit testing. #[cfg(test)] mod tests { use super::*; #[test] fn sanity_test_max_by() { let filtered: Vec<f32> = vec![1.0, 2.0, 3.0, 4.0, 5.0]; let maxel = filtered .iter() .enumerate() .max_by(|a, b| { // filtered (gi) is still complex at this point, we only care about the real part a.1.partial_cmp(&b.1).unwrap_or(Ordering::Equal) }) .unwrap(); assert_eq!(maxel, (4usize, &5.0f32)); } #[test] fn am_i_still_sane() { assert_eq!( Complex::new(1.0, -3.0) * Complex::new(2.0, 5.0), Complex::new(17.0, -1.0) ); } #[test] fn unique_identifier() { let width = 64; let height = 64; let frame = GrayImage::new(width, height); let settings = MosseTrackerSettings { window_size: 16, width, height, regularization: 0.001, learning_rate: 0.05, psr_threshold: 7.0, }; let mut multi_tracker = MultiMosseTracker::new(settings, 3); assert_eq!(multi_tracker.size(), 0); multi_tracker.add_or_replace_target(0, (0, 0), &frame); assert_eq!(multi_tracker.size(), 1); assert_eq!( multi_tracker .trackers .iter() .find(|t| t.0 == 0) .unwrap() .2 .current_target_center, (0, 0) ); multi_tracker.add_or_replace_target(1, (10, 0), &frame); assert_eq!(multi_tracker.size(), 2); multi_tracker.add_or_replace_target(0, (10, 0), &frame); assert_eq!(multi_tracker.size(), 2); assert_eq!( multi_tracker .trackers .iter() .find(|t| t.0 == 0) .unwrap() .2 .current_target_center, (10, 0) ); } }
fn index_to_coords(width: u32, index: u32) -> (u32, u32) { // modulo/remainder ops are theoretically O(1) // checked_rem returns None if rhs == 0, which would indicate an upstream error (width == 0). let x = index.checked_rem(width).unwrap();
random_line_split
main.rs
#![deny(unused_must_use)] #![type_length_limit = "1340885"] extern crate serenity; extern crate ctrlc; #[macro_use] pub mod logger; pub mod canary_update; pub mod dogebotno; pub mod permissions; pub mod servers; pub mod voice; use canary_update::*; use futures::{Stream, StreamExt}; use lazy_static::*; use logger::get_guild_members; use rand::Rng; use regex::Regex; use serenity::async_trait; use serenity::client::bridge::gateway::GatewayIntents; use serenity::model::channel::GuildChannel; use serenity::{ client::bridge::gateway::ShardManager, framework::standard::{macros::*, *}, model::{ channel::Message, event::{PresenceUpdateEvent, ResumedEvent}, gateway::Ready, id::{ChannelId, GuildId, UserId}, user::OnlineStatus, }, prelude::*, utils::MessageBuilder, Client, }; use std::{ collections::HashSet, ops::DerefMut, sync::{atomic::AtomicBool, Arc}, }; use tokio::{stream, sync::Mutex}; use voice::OofVoice; /// Unwrapping many of the errors in oofbot, mostly api calls, will result in a panic sometimes. /// This is bad. But I also cant ignore the errors in case theres something bad in there. So my /// solution is this trait, which logs the error. If I look in the logs and see something bad, then /// I know to recheck everything trait LogResult { /// If the result is an error, log the error. fn log_err(&self) where Self: std::fmt::Debug, { log_timestamp!("DEBUG", format!("{:?}", self)) } } impl<T: std::fmt::Debug, E: std::fmt::Debug> LogResult for Result<T, E> { /// If the result is an error, log the error. fn log_err(&self) { if self.is_err() { log_timestamp!("DEBUG", format!("{:?}", self)); } } } /// The general command group. May be deleted later #[group] #[commands(test, executeorder66, getdvsstatus)] struct General; /// A testing command that can only be run by me. #[command] async fn test(ctx: &Context, msg: &Message) -> CommandResult { if msg.author.id != 453344368913547265 { msg.channel_id.say(&ctx, "No").await.log_err(); return Ok(()); } //let canary = ctx.data.read().get::<CanaryUpdateHandler>().cloned().unwrap(); //let lock = canary.lock()?; //let res = lock.create_db(); //res.log_err(); //if res.is_ok() { msg.channel_id.say(&ctx, "It seems to have worked").log_err(); //} //else { // msg.channel_id.say(&ctx, "killme").log_err(); //} msg.channel_id.say(&ctx, "@admin").await.log_err(); Ok(()) } #[command] async fn executeorder66(ctx: &Context, msg: &Message) -> CommandResult { msg.channel_id.say(&ctx, "not yet").await.log_err(); Ok(()) } /// The event handler for oofbot pub struct Handler { cancel_tyler_ping: Arc<AtomicBool>, mention_regex: Regex, } impl Default for Handler { fn default() -> Self { Self { cancel_tyler_ping: Arc::default(), mention_regex: Regex::new(r"<@!?468928390917783553>").unwrap(), } } } #[async_trait] impl EventHandler for Handler { async fn presence_update(&self, ctx: Context, data: PresenceUpdateEvent) { // oofbot only handles guild presence updates if data.guild_id.is_none() { return; } // Dogebot is oofbots greatest enemy. We got some checks in here just for him. let is_dogebot = data.presence.user_id == 612070962913083405; // Should never be none because we check that up there let guild_id = data.guild_id.unwrap(); // Checks if dogebot is offline in this guild (the main development guild for dogebot and // oofbot) if is_dogebot && guild_id.0 == 561874457283657728 { dogebotno::dogebot_presence(&ctx, &data, &guild_id, self).await; } else if !is_dogebot && data.presence.status == OnlineStatus::Offline { // Inside joke, memeing on how tiny discord canary updates are and how often we get them let canary = ctx .data .read() .await .get::<CanaryUpdateHandler>() .cloned() .unwrap(); let mut lock = canary.lock().await; lock.add_canary_update(&data.presence.user_id).await; } else if !is_dogebot && data.presence.status == OnlineStatus::Online { canary_update::do_update(&ctx, &data).await; } } async fn resume(&self, _ctx: Context, _data: ResumedEvent)
async fn ready(&self, ctx: Context, _data: Ready) { log_timestamp!("INFO", format!("Shard {} ready", ctx.shard_id)); } async fn cache_ready(&self, ctx: Context, guilds: Vec<GuildId>) { let shard = ctx.shard_id; let rctx = &ctx; // Get all the guilds that this shard is connected to // Not that this bot will ever be big enough for me to bother sharding it let guild_info: Vec<_> = stream::iter(guilds) .filter_map(|guild_id| async move { if guild_id.shard_id(&rctx).await == rctx.shard_id { Some(( guild_id, guild_id.to_guild_cached(&rctx).await.unwrap().name.clone(), )) } else { None } }) .collect() .await; log_timestamp!( "INFO", format!("Shard {} connected to guilds\n{:#?}", shard, guild_info) ); } async fn message(&self, ctx: Context, msg: Message) { log_timestamp!("DEBUG", &msg.content); if msg.author.id == 612070962913083405 { dogebotno::dogebotno(ctx, msg).await; return; } if self.mention_regex.is_match(msg.content.as_str()) { let channel_id: ChannelId = msg.channel_id; channel_id .say( &ctx, "For thousands of years I lay dormant, who has disturbed my slumber", ) .await .log_err(); } if msg.content.contains("@someone") && !msg.author.bot { someone_ping(&ctx, &msg).await; } if (msg.content.contains("@everyone") || msg.content.contains("@here")) && msg.author.id.0 != 468928390917783553 { msg.channel_id .say(&ctx, "https://yeet.kikoho.xyz/files/ping.gif") .await .log_err(); } if msg.author.id == 266345279513427971 && msg.content.contains("https://www.twitch.tv/corporal_q") { msg.channel_id.say(&ctx, "sotp spamming").await.log_err(); } } } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { log_timestamp!("INFO", "Starting oofbot"); log_timestamp!("INFO", "Getting client secret from file"); let mut framework = StandardFramework::new() .configure(|c| c.prefix("/")) .group(&GENERAL_GROUP) .group(&ADMIN_GROUP) .help(&HELP); voice::do_framework(&mut framework); permissions::do_framework(&mut framework); canary_update::do_framework(&mut framework); let secret = std::fs::read_to_string("client_secret") .expect("Client secret needs to be in a file called client_secret"); let mut client = Client::builder(secret) .add_intent(GatewayIntents::all()) .framework(framework) .event_handler(Handler::default()) .await .expect("Failed to create client"); // Voice initialization { // Lock the clients data let mut data = client.data.write().await; // Add the voice manager log_timestamp!("INFO", "Starting oofvoice"); data.insert::<OofVoice>(OofVoice::new(client.voice_manager.clone()).await); log_timestamp!("INFO", "Started oofvoice"); // Add canary update handler log_timestamp!("INFO", "Starting canary update handler"); let sql = permissions::SqlHandler::new(); data.insert::<CanaryUpdateHandler>(Arc::new(Mutex::new(CanaryUpdateHandler::new(sql)))); log_timestamp!("INFO", "Started canary update handler"); } let shard_manager = client.shard_manager.clone(); // Handle ctrl+c cross platform ctrlc::set_handler(move || { log_timestamp!("INFO", "Caught SIGINT, closing oofbot"); //let mut lock = shard_manager.lock().await; //let sm: &mut ShardManager = lock.deref_mut(); //sm.shutdown_all(); std::process::exit(0); }) .log_err(); // Hah you think this bot is big enough to be sharded? Nice joke // But if yours is use .start_autosharded() client.start().await?; Ok(()) } /// Handles the @someone ping. Yes im evil. async fn someone_ping(ctx: &Context, msg: &Message) { let guild_id: Option<GuildId> = msg.guild_id; let channel_id: ChannelId = msg.channel_id; match guild_id { Some(id) => { let mut message = MessageBuilder::new(); { let members = match get_guild_members(&ctx, id).await { Some(m) => m, None => { log_timestamp!("ERROR", format!("Failed to find guild {}", id)); msg.channel_id.say(&ctx, "Internal Error").await.log_err(); return; } }; let mut rng = rand::thread_rng(); message.mention(&msg.author); message.push(" has pinged: "); let someones = msg.content.split("@someone"); let c = someones.count(); if c > 1 { let r = rng.gen_range(0, members.len()); message.mention(&members[r]); } // Randomly select the @someones msg.content.split("@someone").skip(2).for_each(|_| { message.push(", "); let r = rng.gen_range(0, members.len()); message.mention(&members[r]); }); } channel_id.say(&ctx, message).await.log_err(); } None => { // If guild is none then this is a dm channel_id .say(&ctx.http, "Cannot @someone in dms") .await .log_err(); } } } #[help] async fn help( context: &Context, msg: &Message, args: Args, help_options: &'static HelpOptions, groups: &[&'static CommandGroup], owners: HashSet<UserId>, ) -> CommandResult { help_commands::with_embeds(context, msg, args, help_options, groups, owners).await; Ok(()) } #[check] #[name = "ManageMessages"] #[check_in_help(true)] #[display_in_help(true)] async fn manage_messages_check(ctx: &Context, msg: &Message) -> CheckResult { if msg.author.id == 453344368913547265 { return true.into(); } else if let Ok(member) = msg.member(&ctx).await { if let Ok(permissions) = member.permissions(&ctx.cache).await { return (permissions.administrator() || permissions.manage_messages()).into(); } } false.into() } #[check] #[name = "DVS"] #[check_in_help(true)] #[display_in_help(true)] async fn dvs_check(_ctx: &Context, msg: &Message) -> CheckResult { (msg.guild_id.unwrap_or(0.into()) == 693213312099287153).into() } #[group] #[commands(snapbm, snapping, snapbotcommands, snapspam, snapafter, setslowmode)] /// Admin command group /// Get this, it has admin commands, amazing right? struct Admin; #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Scan the last X messages and delete all that are from bots. Messages older than 2 weeks cannot be deleted with this command. Maximum of 500 messages async fn snapbm(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let count = match args.single::<u64>() { Ok(x) if x <= 500 => x, _ => { msg.channel_id .say(&ctx, "Usage: /snapbm <number>") .await .log_err(); return Ok(()); } }; let channel: GuildChannel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let messages = channel .messages(&ctx, |retriever| retriever.before(msg.id).limit(count)) .await?; let mut bot_messages: Vec<&Message> = messages .iter() .filter(|msg| { msg.author.bot && chrono::Utc::now().naive_utc() - msg.timestamp.naive_utc() < chrono::Duration::weeks(2) }) .collect(); bot_messages.push(msg); channel.delete_messages(&ctx, bot_messages).await.log_err(); Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Scan the last X messages and delete all that contain pings. Messages older than 2 weeks cannot be deleted with this command. Maximum of 500 messages async fn snapping(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let ping_regex = Regex::new("<@!?\\d*>").unwrap(); let count = match args.single::<u64>() { Ok(x) if x <= 500 => x, _ => { msg.channel_id .say(&ctx, "Usage: /lazysnapping <number>") .await .log_err(); return Ok(()); } }; let channel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let messages = channel .messages(&ctx, |retriever| retriever.before(msg.id).limit(count)) .await?; let mut bot_messages: Vec<&Message> = messages .iter() .filter(|msg| { ping_regex.is_match(msg.content.as_str()) && chrono::Utc::now().naive_utc() - msg.timestamp.naive_utc() < chrono::Duration::weeks(2) }) .collect(); bot_messages.push(msg); channel.delete_messages(&ctx, bot_messages).await.log_err(); Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Scan the last X messages and delete all that start with /. Messages older than 2 weeks cannot be deleted with this command. Maximum of 500 messages async fn snapbotcommands(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let count = match args.single::<u64>() { Ok(x) if x <= 500 => x, _ => { msg.channel_id .say(&ctx, "Usage: /snapbotcommands <number>") .await .log_err(); return Ok(()); } }; let channel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let messages = channel .messages(&ctx, |retriever| retriever.before(msg.id).limit(count)) .await?; let mut bot_messages: Vec<&Message> = messages .iter() .filter(|msg| { (msg.content.starts_with('/') || msg.content.starts_with('!')) && chrono::Utc::now().naive_utc() - msg.timestamp.naive_utc() < chrono::Duration::weeks(2) }) .collect(); bot_messages.push(msg); channel.delete_messages(&ctx, bot_messages).await.log_err(); Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Murder the last X messages. Messages older than 2 weeks cannot be deleted with this command. Maximum of 500 messages async fn snapspam(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let count = match args.single::<u64>() { Ok(x) if x <= 500 => x, _ => { msg.channel_id .say(&ctx, "Usage: /snapspam <number>") .await .log_err(); return Ok(()); } }; let channel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let mut messages = channel .messages(&ctx, |retriever| retriever.before(msg.id).limit(count)) .await?; messages.push(msg.clone()); let messages = messages.into_iter().filter(|m| { chrono::Utc::now().naive_utc() - m.timestamp.naive_utc() < chrono::Duration::weeks(2) }); channel.delete_messages(&ctx, messages).await.log_err(); Ok(()) } #[command] #[only_in(guilds)] #[checks(DVS)] /// Gets the status of the DVS minecraft server async fn getdvsstatus(ctx: &Context, msg: &Message) -> CommandResult { msg.channel_id.broadcast_typing(&ctx).await.log_err(); let code = std::process::Command::new("sh") .args(&[ "-c", "nmap -4 applesthepi.com -Pn -p 25566 | rg '25566/tcp open'", ]) .status() .unwrap(); if code.success() { let message = MessageBuilder::new() .user(msg.author.id) .push(" Server port appears to be open, so it should be up.") .build(); msg.channel_id.say(&ctx, message).await.log_err(); } else { msg.channel_id .say( &ctx, "Server down indeed, <@324381278600298509> your server is on crack", ) .await .log_err(); } Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Murder all messages after the message with the given id. Message ids can be gotten by enabling /// developer mode in discord setting and right click -> copy id /// Messages older than 2 weeks cannot be deleted with this. /// Usage: /snapuntil messageid async fn snapafter(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let id = args.single::<u64>()?; let channel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let messages = channel .messages(&ctx, |retriever| retriever.after(id)) .await?; let messages = messages.into_iter().filter(|m| { chrono::Utc::now().naive_utc() - m.timestamp.naive_utc() < chrono::Duration::weeks(2) }); channel.delete_messages(&ctx, messages).await.log_err(); Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Sets the slowmode to any second value. This allow more specific slow mode like 1 second. /// Usage: /setslowmode integer async fn setslowmode(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let arg: u64 = args.single()?; msg.channel_id .to_channel(&ctx) .await? .guild() .unwrap() .edit(&ctx, |c| c.slow_mode_rate(arg)) .await .log_err(); Ok(()) }
{ log_timestamp!("INFO", "Reconnected to discord"); }
identifier_body
main.rs
#![deny(unused_must_use)] #![type_length_limit = "1340885"] extern crate serenity; extern crate ctrlc; #[macro_use] pub mod logger; pub mod canary_update; pub mod dogebotno; pub mod permissions; pub mod servers; pub mod voice; use canary_update::*; use futures::{Stream, StreamExt}; use lazy_static::*; use logger::get_guild_members; use rand::Rng; use regex::Regex; use serenity::async_trait; use serenity::client::bridge::gateway::GatewayIntents; use serenity::model::channel::GuildChannel; use serenity::{ client::bridge::gateway::ShardManager, framework::standard::{macros::*, *}, model::{ channel::Message, event::{PresenceUpdateEvent, ResumedEvent}, gateway::Ready, id::{ChannelId, GuildId, UserId}, user::OnlineStatus, }, prelude::*, utils::MessageBuilder, Client, }; use std::{ collections::HashSet, ops::DerefMut, sync::{atomic::AtomicBool, Arc}, }; use tokio::{stream, sync::Mutex}; use voice::OofVoice; /// Unwrapping many of the errors in oofbot, mostly api calls, will result in a panic sometimes. /// This is bad. But I also cant ignore the errors in case theres something bad in there. So my /// solution is this trait, which logs the error. If I look in the logs and see something bad, then /// I know to recheck everything trait LogResult { /// If the result is an error, log the error. fn log_err(&self) where Self: std::fmt::Debug, { log_timestamp!("DEBUG", format!("{:?}", self)) } } impl<T: std::fmt::Debug, E: std::fmt::Debug> LogResult for Result<T, E> { /// If the result is an error, log the error. fn log_err(&self) { if self.is_err() { log_timestamp!("DEBUG", format!("{:?}", self)); } } } /// The general command group. May be deleted later #[group] #[commands(test, executeorder66, getdvsstatus)] struct General; /// A testing command that can only be run by me. #[command] async fn test(ctx: &Context, msg: &Message) -> CommandResult { if msg.author.id != 453344368913547265 { msg.channel_id.say(&ctx, "No").await.log_err(); return Ok(()); } //let canary = ctx.data.read().get::<CanaryUpdateHandler>().cloned().unwrap(); //let lock = canary.lock()?; //let res = lock.create_db(); //res.log_err(); //if res.is_ok() { msg.channel_id.say(&ctx, "It seems to have worked").log_err(); //} //else { // msg.channel_id.say(&ctx, "killme").log_err(); //} msg.channel_id.say(&ctx, "@admin").await.log_err(); Ok(()) } #[command] async fn executeorder66(ctx: &Context, msg: &Message) -> CommandResult { msg.channel_id.say(&ctx, "not yet").await.log_err(); Ok(()) } /// The event handler for oofbot pub struct Handler { cancel_tyler_ping: Arc<AtomicBool>, mention_regex: Regex, } impl Default for Handler { fn default() -> Self { Self { cancel_tyler_ping: Arc::default(), mention_regex: Regex::new(r"<@!?468928390917783553>").unwrap(), } } } #[async_trait] impl EventHandler for Handler { async fn presence_update(&self, ctx: Context, data: PresenceUpdateEvent) { // oofbot only handles guild presence updates if data.guild_id.is_none() { return; } // Dogebot is oofbots greatest enemy. We got some checks in here just for him. let is_dogebot = data.presence.user_id == 612070962913083405; // Should never be none because we check that up there let guild_id = data.guild_id.unwrap(); // Checks if dogebot is offline in this guild (the main development guild for dogebot and // oofbot) if is_dogebot && guild_id.0 == 561874457283657728 { dogebotno::dogebot_presence(&ctx, &data, &guild_id, self).await; } else if !is_dogebot && data.presence.status == OnlineStatus::Offline { // Inside joke, memeing on how tiny discord canary updates are and how often we get them let canary = ctx .data .read() .await .get::<CanaryUpdateHandler>() .cloned() .unwrap(); let mut lock = canary.lock().await; lock.add_canary_update(&data.presence.user_id).await; } else if !is_dogebot && data.presence.status == OnlineStatus::Online { canary_update::do_update(&ctx, &data).await; } } async fn resume(&self, _ctx: Context, _data: ResumedEvent) { log_timestamp!("INFO", "Reconnected to discord"); } async fn ready(&self, ctx: Context, _data: Ready) { log_timestamp!("INFO", format!("Shard {} ready", ctx.shard_id)); } async fn cache_ready(&self, ctx: Context, guilds: Vec<GuildId>) { let shard = ctx.shard_id; let rctx = &ctx; // Get all the guilds that this shard is connected to // Not that this bot will ever be big enough for me to bother sharding it let guild_info: Vec<_> = stream::iter(guilds) .filter_map(|guild_id| async move { if guild_id.shard_id(&rctx).await == rctx.shard_id { Some(( guild_id, guild_id.to_guild_cached(&rctx).await.unwrap().name.clone(), )) } else { None } }) .collect() .await; log_timestamp!( "INFO", format!("Shard {} connected to guilds\n{:#?}", shard, guild_info) ); } async fn message(&self, ctx: Context, msg: Message) { log_timestamp!("DEBUG", &msg.content); if msg.author.id == 612070962913083405 { dogebotno::dogebotno(ctx, msg).await; return; } if self.mention_regex.is_match(msg.content.as_str()) { let channel_id: ChannelId = msg.channel_id; channel_id .say( &ctx, "For thousands of years I lay dormant, who has disturbed my slumber", ) .await .log_err(); } if msg.content.contains("@someone") && !msg.author.bot { someone_ping(&ctx, &msg).await; } if (msg.content.contains("@everyone") || msg.content.contains("@here")) && msg.author.id.0 != 468928390917783553 { msg.channel_id .say(&ctx, "https://yeet.kikoho.xyz/files/ping.gif") .await .log_err(); } if msg.author.id == 266345279513427971 && msg.content.contains("https://www.twitch.tv/corporal_q") { msg.channel_id.say(&ctx, "sotp spamming").await.log_err(); } } } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { log_timestamp!("INFO", "Starting oofbot"); log_timestamp!("INFO", "Getting client secret from file"); let mut framework = StandardFramework::new() .configure(|c| c.prefix("/")) .group(&GENERAL_GROUP) .group(&ADMIN_GROUP) .help(&HELP); voice::do_framework(&mut framework); permissions::do_framework(&mut framework); canary_update::do_framework(&mut framework); let secret = std::fs::read_to_string("client_secret") .expect("Client secret needs to be in a file called client_secret"); let mut client = Client::builder(secret) .add_intent(GatewayIntents::all()) .framework(framework) .event_handler(Handler::default()) .await .expect("Failed to create client"); // Voice initialization { // Lock the clients data let mut data = client.data.write().await; // Add the voice manager log_timestamp!("INFO", "Starting oofvoice"); data.insert::<OofVoice>(OofVoice::new(client.voice_manager.clone()).await); log_timestamp!("INFO", "Started oofvoice"); // Add canary update handler log_timestamp!("INFO", "Starting canary update handler"); let sql = permissions::SqlHandler::new(); data.insert::<CanaryUpdateHandler>(Arc::new(Mutex::new(CanaryUpdateHandler::new(sql)))); log_timestamp!("INFO", "Started canary update handler"); } let shard_manager = client.shard_manager.clone(); // Handle ctrl+c cross platform ctrlc::set_handler(move || { log_timestamp!("INFO", "Caught SIGINT, closing oofbot"); //let mut lock = shard_manager.lock().await; //let sm: &mut ShardManager = lock.deref_mut(); //sm.shutdown_all();
}) .log_err(); // Hah you think this bot is big enough to be sharded? Nice joke // But if yours is use .start_autosharded() client.start().await?; Ok(()) } /// Handles the @someone ping. Yes im evil. async fn someone_ping(ctx: &Context, msg: &Message) { let guild_id: Option<GuildId> = msg.guild_id; let channel_id: ChannelId = msg.channel_id; match guild_id { Some(id) => { let mut message = MessageBuilder::new(); { let members = match get_guild_members(&ctx, id).await { Some(m) => m, None => { log_timestamp!("ERROR", format!("Failed to find guild {}", id)); msg.channel_id.say(&ctx, "Internal Error").await.log_err(); return; } }; let mut rng = rand::thread_rng(); message.mention(&msg.author); message.push(" has pinged: "); let someones = msg.content.split("@someone"); let c = someones.count(); if c > 1 { let r = rng.gen_range(0, members.len()); message.mention(&members[r]); } // Randomly select the @someones msg.content.split("@someone").skip(2).for_each(|_| { message.push(", "); let r = rng.gen_range(0, members.len()); message.mention(&members[r]); }); } channel_id.say(&ctx, message).await.log_err(); } None => { // If guild is none then this is a dm channel_id .say(&ctx.http, "Cannot @someone in dms") .await .log_err(); } } } #[help] async fn help( context: &Context, msg: &Message, args: Args, help_options: &'static HelpOptions, groups: &[&'static CommandGroup], owners: HashSet<UserId>, ) -> CommandResult { help_commands::with_embeds(context, msg, args, help_options, groups, owners).await; Ok(()) } #[check] #[name = "ManageMessages"] #[check_in_help(true)] #[display_in_help(true)] async fn manage_messages_check(ctx: &Context, msg: &Message) -> CheckResult { if msg.author.id == 453344368913547265 { return true.into(); } else if let Ok(member) = msg.member(&ctx).await { if let Ok(permissions) = member.permissions(&ctx.cache).await { return (permissions.administrator() || permissions.manage_messages()).into(); } } false.into() } #[check] #[name = "DVS"] #[check_in_help(true)] #[display_in_help(true)] async fn dvs_check(_ctx: &Context, msg: &Message) -> CheckResult { (msg.guild_id.unwrap_or(0.into()) == 693213312099287153).into() } #[group] #[commands(snapbm, snapping, snapbotcommands, snapspam, snapafter, setslowmode)] /// Admin command group /// Get this, it has admin commands, amazing right? struct Admin; #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Scan the last X messages and delete all that are from bots. Messages older than 2 weeks cannot be deleted with this command. Maximum of 500 messages async fn snapbm(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let count = match args.single::<u64>() { Ok(x) if x <= 500 => x, _ => { msg.channel_id .say(&ctx, "Usage: /snapbm <number>") .await .log_err(); return Ok(()); } }; let channel: GuildChannel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let messages = channel .messages(&ctx, |retriever| retriever.before(msg.id).limit(count)) .await?; let mut bot_messages: Vec<&Message> = messages .iter() .filter(|msg| { msg.author.bot && chrono::Utc::now().naive_utc() - msg.timestamp.naive_utc() < chrono::Duration::weeks(2) }) .collect(); bot_messages.push(msg); channel.delete_messages(&ctx, bot_messages).await.log_err(); Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Scan the last X messages and delete all that contain pings. Messages older than 2 weeks cannot be deleted with this command. Maximum of 500 messages async fn snapping(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let ping_regex = Regex::new("<@!?\\d*>").unwrap(); let count = match args.single::<u64>() { Ok(x) if x <= 500 => x, _ => { msg.channel_id .say(&ctx, "Usage: /lazysnapping <number>") .await .log_err(); return Ok(()); } }; let channel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let messages = channel .messages(&ctx, |retriever| retriever.before(msg.id).limit(count)) .await?; let mut bot_messages: Vec<&Message> = messages .iter() .filter(|msg| { ping_regex.is_match(msg.content.as_str()) && chrono::Utc::now().naive_utc() - msg.timestamp.naive_utc() < chrono::Duration::weeks(2) }) .collect(); bot_messages.push(msg); channel.delete_messages(&ctx, bot_messages).await.log_err(); Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Scan the last X messages and delete all that start with /. Messages older than 2 weeks cannot be deleted with this command. Maximum of 500 messages async fn snapbotcommands(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let count = match args.single::<u64>() { Ok(x) if x <= 500 => x, _ => { msg.channel_id .say(&ctx, "Usage: /snapbotcommands <number>") .await .log_err(); return Ok(()); } }; let channel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let messages = channel .messages(&ctx, |retriever| retriever.before(msg.id).limit(count)) .await?; let mut bot_messages: Vec<&Message> = messages .iter() .filter(|msg| { (msg.content.starts_with('/') || msg.content.starts_with('!')) && chrono::Utc::now().naive_utc() - msg.timestamp.naive_utc() < chrono::Duration::weeks(2) }) .collect(); bot_messages.push(msg); channel.delete_messages(&ctx, bot_messages).await.log_err(); Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Murder the last X messages. Messages older than 2 weeks cannot be deleted with this command. Maximum of 500 messages async fn snapspam(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let count = match args.single::<u64>() { Ok(x) if x <= 500 => x, _ => { msg.channel_id .say(&ctx, "Usage: /snapspam <number>") .await .log_err(); return Ok(()); } }; let channel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let mut messages = channel .messages(&ctx, |retriever| retriever.before(msg.id).limit(count)) .await?; messages.push(msg.clone()); let messages = messages.into_iter().filter(|m| { chrono::Utc::now().naive_utc() - m.timestamp.naive_utc() < chrono::Duration::weeks(2) }); channel.delete_messages(&ctx, messages).await.log_err(); Ok(()) } #[command] #[only_in(guilds)] #[checks(DVS)] /// Gets the status of the DVS minecraft server async fn getdvsstatus(ctx: &Context, msg: &Message) -> CommandResult { msg.channel_id.broadcast_typing(&ctx).await.log_err(); let code = std::process::Command::new("sh") .args(&[ "-c", "nmap -4 applesthepi.com -Pn -p 25566 | rg '25566/tcp open'", ]) .status() .unwrap(); if code.success() { let message = MessageBuilder::new() .user(msg.author.id) .push(" Server port appears to be open, so it should be up.") .build(); msg.channel_id.say(&ctx, message).await.log_err(); } else { msg.channel_id .say( &ctx, "Server down indeed, <@324381278600298509> your server is on crack", ) .await .log_err(); } Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Murder all messages after the message with the given id. Message ids can be gotten by enabling /// developer mode in discord setting and right click -> copy id /// Messages older than 2 weeks cannot be deleted with this. /// Usage: /snapuntil messageid async fn snapafter(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let id = args.single::<u64>()?; let channel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let messages = channel .messages(&ctx, |retriever| retriever.after(id)) .await?; let messages = messages.into_iter().filter(|m| { chrono::Utc::now().naive_utc() - m.timestamp.naive_utc() < chrono::Duration::weeks(2) }); channel.delete_messages(&ctx, messages).await.log_err(); Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Sets the slowmode to any second value. This allow more specific slow mode like 1 second. /// Usage: /setslowmode integer async fn setslowmode(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let arg: u64 = args.single()?; msg.channel_id .to_channel(&ctx) .await? .guild() .unwrap() .edit(&ctx, |c| c.slow_mode_rate(arg)) .await .log_err(); Ok(()) }
std::process::exit(0);
random_line_split
main.rs
#![deny(unused_must_use)] #![type_length_limit = "1340885"] extern crate serenity; extern crate ctrlc; #[macro_use] pub mod logger; pub mod canary_update; pub mod dogebotno; pub mod permissions; pub mod servers; pub mod voice; use canary_update::*; use futures::{Stream, StreamExt}; use lazy_static::*; use logger::get_guild_members; use rand::Rng; use regex::Regex; use serenity::async_trait; use serenity::client::bridge::gateway::GatewayIntents; use serenity::model::channel::GuildChannel; use serenity::{ client::bridge::gateway::ShardManager, framework::standard::{macros::*, *}, model::{ channel::Message, event::{PresenceUpdateEvent, ResumedEvent}, gateway::Ready, id::{ChannelId, GuildId, UserId}, user::OnlineStatus, }, prelude::*, utils::MessageBuilder, Client, }; use std::{ collections::HashSet, ops::DerefMut, sync::{atomic::AtomicBool, Arc}, }; use tokio::{stream, sync::Mutex}; use voice::OofVoice; /// Unwrapping many of the errors in oofbot, mostly api calls, will result in a panic sometimes. /// This is bad. But I also cant ignore the errors in case theres something bad in there. So my /// solution is this trait, which logs the error. If I look in the logs and see something bad, then /// I know to recheck everything trait LogResult { /// If the result is an error, log the error. fn log_err(&self) where Self: std::fmt::Debug, { log_timestamp!("DEBUG", format!("{:?}", self)) } } impl<T: std::fmt::Debug, E: std::fmt::Debug> LogResult for Result<T, E> { /// If the result is an error, log the error. fn log_err(&self) { if self.is_err() { log_timestamp!("DEBUG", format!("{:?}", self)); } } } /// The general command group. May be deleted later #[group] #[commands(test, executeorder66, getdvsstatus)] struct General; /// A testing command that can only be run by me. #[command] async fn
(ctx: &Context, msg: &Message) -> CommandResult { if msg.author.id != 453344368913547265 { msg.channel_id.say(&ctx, "No").await.log_err(); return Ok(()); } //let canary = ctx.data.read().get::<CanaryUpdateHandler>().cloned().unwrap(); //let lock = canary.lock()?; //let res = lock.create_db(); //res.log_err(); //if res.is_ok() { msg.channel_id.say(&ctx, "It seems to have worked").log_err(); //} //else { // msg.channel_id.say(&ctx, "killme").log_err(); //} msg.channel_id.say(&ctx, "@admin").await.log_err(); Ok(()) } #[command] async fn executeorder66(ctx: &Context, msg: &Message) -> CommandResult { msg.channel_id.say(&ctx, "not yet").await.log_err(); Ok(()) } /// The event handler for oofbot pub struct Handler { cancel_tyler_ping: Arc<AtomicBool>, mention_regex: Regex, } impl Default for Handler { fn default() -> Self { Self { cancel_tyler_ping: Arc::default(), mention_regex: Regex::new(r"<@!?468928390917783553>").unwrap(), } } } #[async_trait] impl EventHandler for Handler { async fn presence_update(&self, ctx: Context, data: PresenceUpdateEvent) { // oofbot only handles guild presence updates if data.guild_id.is_none() { return; } // Dogebot is oofbots greatest enemy. We got some checks in here just for him. let is_dogebot = data.presence.user_id == 612070962913083405; // Should never be none because we check that up there let guild_id = data.guild_id.unwrap(); // Checks if dogebot is offline in this guild (the main development guild for dogebot and // oofbot) if is_dogebot && guild_id.0 == 561874457283657728 { dogebotno::dogebot_presence(&ctx, &data, &guild_id, self).await; } else if !is_dogebot && data.presence.status == OnlineStatus::Offline { // Inside joke, memeing on how tiny discord canary updates are and how often we get them let canary = ctx .data .read() .await .get::<CanaryUpdateHandler>() .cloned() .unwrap(); let mut lock = canary.lock().await; lock.add_canary_update(&data.presence.user_id).await; } else if !is_dogebot && data.presence.status == OnlineStatus::Online { canary_update::do_update(&ctx, &data).await; } } async fn resume(&self, _ctx: Context, _data: ResumedEvent) { log_timestamp!("INFO", "Reconnected to discord"); } async fn ready(&self, ctx: Context, _data: Ready) { log_timestamp!("INFO", format!("Shard {} ready", ctx.shard_id)); } async fn cache_ready(&self, ctx: Context, guilds: Vec<GuildId>) { let shard = ctx.shard_id; let rctx = &ctx; // Get all the guilds that this shard is connected to // Not that this bot will ever be big enough for me to bother sharding it let guild_info: Vec<_> = stream::iter(guilds) .filter_map(|guild_id| async move { if guild_id.shard_id(&rctx).await == rctx.shard_id { Some(( guild_id, guild_id.to_guild_cached(&rctx).await.unwrap().name.clone(), )) } else { None } }) .collect() .await; log_timestamp!( "INFO", format!("Shard {} connected to guilds\n{:#?}", shard, guild_info) ); } async fn message(&self, ctx: Context, msg: Message) { log_timestamp!("DEBUG", &msg.content); if msg.author.id == 612070962913083405 { dogebotno::dogebotno(ctx, msg).await; return; } if self.mention_regex.is_match(msg.content.as_str()) { let channel_id: ChannelId = msg.channel_id; channel_id .say( &ctx, "For thousands of years I lay dormant, who has disturbed my slumber", ) .await .log_err(); } if msg.content.contains("@someone") && !msg.author.bot { someone_ping(&ctx, &msg).await; } if (msg.content.contains("@everyone") || msg.content.contains("@here")) && msg.author.id.0 != 468928390917783553 { msg.channel_id .say(&ctx, "https://yeet.kikoho.xyz/files/ping.gif") .await .log_err(); } if msg.author.id == 266345279513427971 && msg.content.contains("https://www.twitch.tv/corporal_q") { msg.channel_id.say(&ctx, "sotp spamming").await.log_err(); } } } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { log_timestamp!("INFO", "Starting oofbot"); log_timestamp!("INFO", "Getting client secret from file"); let mut framework = StandardFramework::new() .configure(|c| c.prefix("/")) .group(&GENERAL_GROUP) .group(&ADMIN_GROUP) .help(&HELP); voice::do_framework(&mut framework); permissions::do_framework(&mut framework); canary_update::do_framework(&mut framework); let secret = std::fs::read_to_string("client_secret") .expect("Client secret needs to be in a file called client_secret"); let mut client = Client::builder(secret) .add_intent(GatewayIntents::all()) .framework(framework) .event_handler(Handler::default()) .await .expect("Failed to create client"); // Voice initialization { // Lock the clients data let mut data = client.data.write().await; // Add the voice manager log_timestamp!("INFO", "Starting oofvoice"); data.insert::<OofVoice>(OofVoice::new(client.voice_manager.clone()).await); log_timestamp!("INFO", "Started oofvoice"); // Add canary update handler log_timestamp!("INFO", "Starting canary update handler"); let sql = permissions::SqlHandler::new(); data.insert::<CanaryUpdateHandler>(Arc::new(Mutex::new(CanaryUpdateHandler::new(sql)))); log_timestamp!("INFO", "Started canary update handler"); } let shard_manager = client.shard_manager.clone(); // Handle ctrl+c cross platform ctrlc::set_handler(move || { log_timestamp!("INFO", "Caught SIGINT, closing oofbot"); //let mut lock = shard_manager.lock().await; //let sm: &mut ShardManager = lock.deref_mut(); //sm.shutdown_all(); std::process::exit(0); }) .log_err(); // Hah you think this bot is big enough to be sharded? Nice joke // But if yours is use .start_autosharded() client.start().await?; Ok(()) } /// Handles the @someone ping. Yes im evil. async fn someone_ping(ctx: &Context, msg: &Message) { let guild_id: Option<GuildId> = msg.guild_id; let channel_id: ChannelId = msg.channel_id; match guild_id { Some(id) => { let mut message = MessageBuilder::new(); { let members = match get_guild_members(&ctx, id).await { Some(m) => m, None => { log_timestamp!("ERROR", format!("Failed to find guild {}", id)); msg.channel_id.say(&ctx, "Internal Error").await.log_err(); return; } }; let mut rng = rand::thread_rng(); message.mention(&msg.author); message.push(" has pinged: "); let someones = msg.content.split("@someone"); let c = someones.count(); if c > 1 { let r = rng.gen_range(0, members.len()); message.mention(&members[r]); } // Randomly select the @someones msg.content.split("@someone").skip(2).for_each(|_| { message.push(", "); let r = rng.gen_range(0, members.len()); message.mention(&members[r]); }); } channel_id.say(&ctx, message).await.log_err(); } None => { // If guild is none then this is a dm channel_id .say(&ctx.http, "Cannot @someone in dms") .await .log_err(); } } } #[help] async fn help( context: &Context, msg: &Message, args: Args, help_options: &'static HelpOptions, groups: &[&'static CommandGroup], owners: HashSet<UserId>, ) -> CommandResult { help_commands::with_embeds(context, msg, args, help_options, groups, owners).await; Ok(()) } #[check] #[name = "ManageMessages"] #[check_in_help(true)] #[display_in_help(true)] async fn manage_messages_check(ctx: &Context, msg: &Message) -> CheckResult { if msg.author.id == 453344368913547265 { return true.into(); } else if let Ok(member) = msg.member(&ctx).await { if let Ok(permissions) = member.permissions(&ctx.cache).await { return (permissions.administrator() || permissions.manage_messages()).into(); } } false.into() } #[check] #[name = "DVS"] #[check_in_help(true)] #[display_in_help(true)] async fn dvs_check(_ctx: &Context, msg: &Message) -> CheckResult { (msg.guild_id.unwrap_or(0.into()) == 693213312099287153).into() } #[group] #[commands(snapbm, snapping, snapbotcommands, snapspam, snapafter, setslowmode)] /// Admin command group /// Get this, it has admin commands, amazing right? struct Admin; #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Scan the last X messages and delete all that are from bots. Messages older than 2 weeks cannot be deleted with this command. Maximum of 500 messages async fn snapbm(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let count = match args.single::<u64>() { Ok(x) if x <= 500 => x, _ => { msg.channel_id .say(&ctx, "Usage: /snapbm <number>") .await .log_err(); return Ok(()); } }; let channel: GuildChannel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let messages = channel .messages(&ctx, |retriever| retriever.before(msg.id).limit(count)) .await?; let mut bot_messages: Vec<&Message> = messages .iter() .filter(|msg| { msg.author.bot && chrono::Utc::now().naive_utc() - msg.timestamp.naive_utc() < chrono::Duration::weeks(2) }) .collect(); bot_messages.push(msg); channel.delete_messages(&ctx, bot_messages).await.log_err(); Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Scan the last X messages and delete all that contain pings. Messages older than 2 weeks cannot be deleted with this command. Maximum of 500 messages async fn snapping(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let ping_regex = Regex::new("<@!?\\d*>").unwrap(); let count = match args.single::<u64>() { Ok(x) if x <= 500 => x, _ => { msg.channel_id .say(&ctx, "Usage: /lazysnapping <number>") .await .log_err(); return Ok(()); } }; let channel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let messages = channel .messages(&ctx, |retriever| retriever.before(msg.id).limit(count)) .await?; let mut bot_messages: Vec<&Message> = messages .iter() .filter(|msg| { ping_regex.is_match(msg.content.as_str()) && chrono::Utc::now().naive_utc() - msg.timestamp.naive_utc() < chrono::Duration::weeks(2) }) .collect(); bot_messages.push(msg); channel.delete_messages(&ctx, bot_messages).await.log_err(); Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Scan the last X messages and delete all that start with /. Messages older than 2 weeks cannot be deleted with this command. Maximum of 500 messages async fn snapbotcommands(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let count = match args.single::<u64>() { Ok(x) if x <= 500 => x, _ => { msg.channel_id .say(&ctx, "Usage: /snapbotcommands <number>") .await .log_err(); return Ok(()); } }; let channel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let messages = channel .messages(&ctx, |retriever| retriever.before(msg.id).limit(count)) .await?; let mut bot_messages: Vec<&Message> = messages .iter() .filter(|msg| { (msg.content.starts_with('/') || msg.content.starts_with('!')) && chrono::Utc::now().naive_utc() - msg.timestamp.naive_utc() < chrono::Duration::weeks(2) }) .collect(); bot_messages.push(msg); channel.delete_messages(&ctx, bot_messages).await.log_err(); Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Murder the last X messages. Messages older than 2 weeks cannot be deleted with this command. Maximum of 500 messages async fn snapspam(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let count = match args.single::<u64>() { Ok(x) if x <= 500 => x, _ => { msg.channel_id .say(&ctx, "Usage: /snapspam <number>") .await .log_err(); return Ok(()); } }; let channel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let mut messages = channel .messages(&ctx, |retriever| retriever.before(msg.id).limit(count)) .await?; messages.push(msg.clone()); let messages = messages.into_iter().filter(|m| { chrono::Utc::now().naive_utc() - m.timestamp.naive_utc() < chrono::Duration::weeks(2) }); channel.delete_messages(&ctx, messages).await.log_err(); Ok(()) } #[command] #[only_in(guilds)] #[checks(DVS)] /// Gets the status of the DVS minecraft server async fn getdvsstatus(ctx: &Context, msg: &Message) -> CommandResult { msg.channel_id.broadcast_typing(&ctx).await.log_err(); let code = std::process::Command::new("sh") .args(&[ "-c", "nmap -4 applesthepi.com -Pn -p 25566 | rg '25566/tcp open'", ]) .status() .unwrap(); if code.success() { let message = MessageBuilder::new() .user(msg.author.id) .push(" Server port appears to be open, so it should be up.") .build(); msg.channel_id.say(&ctx, message).await.log_err(); } else { msg.channel_id .say( &ctx, "Server down indeed, <@324381278600298509> your server is on crack", ) .await .log_err(); } Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Murder all messages after the message with the given id. Message ids can be gotten by enabling /// developer mode in discord setting and right click -> copy id /// Messages older than 2 weeks cannot be deleted with this. /// Usage: /snapuntil messageid async fn snapafter(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let id = args.single::<u64>()?; let channel = msg .channel_id .to_channel(&ctx) .await .unwrap() .guild() .unwrap(); let messages = channel .messages(&ctx, |retriever| retriever.after(id)) .await?; let messages = messages.into_iter().filter(|m| { chrono::Utc::now().naive_utc() - m.timestamp.naive_utc() < chrono::Duration::weeks(2) }); channel.delete_messages(&ctx, messages).await.log_err(); Ok(()) } #[command] #[checks(ManageMessages)] #[only_in(guilds)] /// Sets the slowmode to any second value. This allow more specific slow mode like 1 second. /// Usage: /setslowmode integer async fn setslowmode(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let arg: u64 = args.single()?; msg.channel_id .to_channel(&ctx) .await? .guild() .unwrap() .edit(&ctx, |c| c.slow_mode_rate(arg)) .await .log_err(); Ok(()) }
test
identifier_name
index.ts
import { Match } from 'dimensions-ai/lib/main/Match'; import { MatchWarn } from 'dimensions-ai/lib/main/DimensionError'; import { MatchEngine } from 'dimensions-ai/lib/main/MatchEngine'; import { MoveAction, SpawnAction, Action } from '../Actions'; import { GameMap } from '../GameMap'; import { Replay } from '../Replay'; import { Tile } from '../Tile'; import { Position } from '../Tile/position'; import { AIMatchConfigs } from '../types'; import { Unit } from '../Unit'; export class Game { public replay: Replay; public map: GameMap; public rng: () => number = Math.random; private globalUnitIDCount = 0; public state: Game.State = { turn: 0, teamStates: { [Unit.TEAM.A]: { units: new Map(), points: 0, }, [Unit.TEAM.B]: { units: new Map(), points: 0, }, }, }; constructor(public configs: AIMatchConfigs) { Unit.ALL_TEAMS.forEach((team) => { this.state.teamStates[team].points = configs.parameters.INITIAL_POINTS; }); } validateCommand(cmd: MatchEngine.Command): Action { const strs = cmd.command.split(' '); if (strs.length === 0) { throw new MatchWarn( `Agent ${cmd.agentID} sent malformed command: ${cmd.command}` ); } else { const action = strs[0]; let valid = true; const team: Unit.TEAM = cmd.agentID; let errormsg = `Team ${cmd.agentID} sent invalid command`; switch (action) { case Game.ACTIONS.MOVE: if (strs.length === 3) { const unitid = parseInt(strs[1]); const direction = strs[2]; const teamState = this.state.teamStates[team]; if (!teamState.units.has(unitid)) { valid = false; errormsg = `Team ${cmd.agentID} tried to move unit ${unitid} that it does not own`; break; } const unit = teamState.units.get(unitid); switch (direction) { case Game.DIRECTIONS.NORTH: case Game.DIRECTIONS.EAST: case Game.DIRECTIONS.SOUTH: case Game.DIRECTIONS.WEST: { const newpos = unit.pos.translate(direction, 1); if (!this.map.inMap(newpos)) { errormsg = `Team ${cmd.agentID} tried to move unit ${unitid} off map`; valid = false; } break; } default: errormsg = `Team ${cmd.agentID} tried to move unit ${unitid} in invalid direction ${direction}`; valid = false; break; } if (valid) { return new MoveAction( action, team, unitid, direction as Game.DIRECTIONS ); } } else { valid = false; } break; case Game.ACTIONS.CREATE_UNIT: if (strs.length === 3) { const x = parseInt(strs[1]); const y = parseInt(strs[2]); if (isNaN(x) || isNaN(y)) { valid = false; errormsg = `Team ${cmd.agentID} tried to build unit with invalid coordinates`; break; } // check if tile being built is a owned base const tile = this.map.getTile(x, y); if (!tile.isBaseTile() || tile.baseTeam !== team) { valid = false; errormsg = `Team ${cmd.agentID} tried to build unit on tile (${x}, ${y}) that does not have a base or is not owned`; break; } if (valid) { return new SpawnAction(action, team, x, y); } } else { valid = false; } break; default: valid = false; } if (valid === false) { throw new MatchWarn( errormsg + `; turn ${this.state.turn}; cmd: ${cmd.command}` ); } } } getTeamsUnits(team: Unit.TEAM): Map<Unit.ID, Unit> { return this.state.teamStates[team].units; } getUnit(team: Unit.TEAM, unitid: Unit.ID): Unit
moveUnit(team: Unit.TEAM, unitid: Unit.ID, direction: Game.DIRECTIONS): void { const unit = this.getUnit(team, unitid); // remove unit from old cell and move to new one and update unit pos this.map.getTileByPos(unit.pos).units.delete(unit.id); unit.pos = unit.pos.translate(direction, 1); this.map.getTileByPos(unit.pos).units.set(unit.id, unit); } spawnUnit(team: Unit.TEAM, pos: Position): void { const tile = this.map.getTileByPos(pos); const unit = new Unit(team, this.globalUnitIDCount++, pos); tile.units.set(unit.id, unit); this.state.teamStates[team].units.set(unit.id, unit); } destroyUnit(team: Unit.TEAM, unitid: Unit.ID): void { const unit = this.getUnit(team, unitid); this.map.getTileByPos(unit.pos).units.delete(unitid); this.state.teamStates[team].units.delete(unitid); } // spawn all units asked to be spawn handleSpawnActions(actions: Array<SpawnAction>, match: Match): Set<Tile> { const spawnedPositionsHashes: Set<number> = new Set(); const spawnedPositions: Set<Tile> = new Set(); const UNIT_COST = this.configs.parameters.UNIT_COST; actions.forEach((action) => { // check first if points available to use if (this.state.teamStates[action.team].points >= UNIT_COST) { this.spawnUnit(action.team, action.pos); this.state.teamStates[action.team].points -= UNIT_COST; if (!spawnedPositionsHashes.has(action.pos.hash())) { spawnedPositionsHashes.add(action.pos.hash()); spawnedPositions.add(this.map.getTileByPos(action.pos)); } } else { match.log.warn( `Team ${action.team} does not have enough points to spawn another unit; turn ${this.state.turn}` ); } }); return spawnedPositions; } // move all units and then destroy any that collide handleMovementActions(actions: Array<MoveAction>, match: Match): Set<Tile> { const tilesWithNewUnits: Set<Tile> = new Set(); const idsOfUnitsThatMoved: Set<Unit.ID> = new Set(); actions.forEach((action) => { if (idsOfUnitsThatMoved.has(action.unitid)) { match.log.warn( `Team ${action.team}'s unit ${action.unitid} already moved, cannot move again this turn; turn ${this.state.turn}` ); } else { this.moveUnit(action.team, action.unitid, action.direction); const unit = this.getUnit(action.team, action.unitid); const tile = this.map.getTileByPos(unit.pos); tilesWithNewUnits.add(tile); idsOfUnitsThatMoved.add(action.unitid); } }); return tilesWithNewUnits; } handleCollisions(tilesToCheck: Set<Tile>, match: Match): void { const unitsToRemove: Array<{ unit: Unit; tile: Tile }> = []; tilesToCheck.forEach((tile) => { if (tile.units.size > 1) { // find lowest brokendown unit // remove all units as they collided let lowestBreakdown = 999999; let lowestBreakdownUnits = 1; tile.units.forEach((unit) => { const b = unit.getBreakdownLevel( this.state.turn, this.configs.parameters.BREAKDOWN_TURNS ); if (b < lowestBreakdown) { lowestBreakdown = b; lowestBreakdownUnits = 1; } else if (b == lowestBreakdown) { lowestBreakdownUnits++; } }); tile.units.forEach((unit) => { if (lowestBreakdownUnits > 1) { // all get removed unitsToRemove.push({ unit, tile }); } else { const b = unit.getBreakdownLevel( this.state.turn, this.configs.parameters.BREAKDOWN_TURNS ); if (b > lowestBreakdown) { unitsToRemove.push({ unit, tile }); } } }); } }); for (const { unit, tile } of unitsToRemove) { match.log.warn( `Team ${unit.team}'s unit ${ unit.id } collided at ${tile.pos.toString()} on turn ${this.state.turn}` ); this.destroyUnit(unit.team, unit.id); } } // give all units points depending on their tile handlePointsRelease(): void { Unit.ALL_TEAMS.forEach((team) => { const units = this.getTeamsUnits(team); units.forEach((unit) => { const tile = this.map.getTileByPos(unit.pos); this.state.teamStates[team].points += tile.pointsPerTurn; }); }); } // run after movements and collisions are handled handleRepairs(): void { this.map.bases.forEach((b) => { const tile = this.map.getTileByPos(b.pos); tile.units.forEach((unit) => { if (b.team === unit.team) { unit.lastRepairTurn = this.state.turn; } }); }); } handleBreakdown(match: Match): void { const brokenDownUnits: Array<Unit> = []; Unit.ALL_TEAMS.forEach((team) => { const units = this.getTeamsUnits(team); units.forEach((unit) => { const b = unit.getBreakdownLevel( this.state.turn, this.configs.parameters.BREAKDOWN_TURNS ); if (b >= this.configs.parameters.BREAKDOWN_MAX) { brokenDownUnits.push(unit); } }); }); brokenDownUnits.forEach((unit) => { match.log.warn(`Team ${unit.team}'s unit ${unit.id} broke down`); this.destroyUnit(unit.team, unit.id); }); } } export namespace Game { export interface State { turn: 0; teamStates: { [x in Unit.TEAM]: { units: Map<Unit.ID, Unit>; points: number; }; }; } export enum DIRECTIONS { NORTH = 'n', EAST = 'e', SOUTH = 's', WEST = 'w', } export enum ACTIONS { /** * formatted as `m unitid direction` */ MOVE = 'm', /** * formatted as `c x y` */ CREATE_UNIT = 'c', } }
{ return this.state.teamStates[team].units.get(unitid); }
identifier_body
index.ts
import { Match } from 'dimensions-ai/lib/main/Match'; import { MatchWarn } from 'dimensions-ai/lib/main/DimensionError'; import { MatchEngine } from 'dimensions-ai/lib/main/MatchEngine'; import { MoveAction, SpawnAction, Action } from '../Actions'; import { GameMap } from '../GameMap'; import { Replay } from '../Replay'; import { Tile } from '../Tile'; import { Position } from '../Tile/position'; import { AIMatchConfigs } from '../types'; import { Unit } from '../Unit'; export class Game { public replay: Replay; public map: GameMap; public rng: () => number = Math.random; private globalUnitIDCount = 0; public state: Game.State = { turn: 0, teamStates: { [Unit.TEAM.A]: { units: new Map(), points: 0, }, [Unit.TEAM.B]: { units: new Map(), points: 0, }, }, }; constructor(public configs: AIMatchConfigs) { Unit.ALL_TEAMS.forEach((team) => { this.state.teamStates[team].points = configs.parameters.INITIAL_POINTS; }); } validateCommand(cmd: MatchEngine.Command): Action { const strs = cmd.command.split(' '); if (strs.length === 0) { throw new MatchWarn( `Agent ${cmd.agentID} sent malformed command: ${cmd.command}` ); } else { const action = strs[0]; let valid = true; const team: Unit.TEAM = cmd.agentID; let errormsg = `Team ${cmd.agentID} sent invalid command`; switch (action) { case Game.ACTIONS.MOVE: if (strs.length === 3) { const unitid = parseInt(strs[1]); const direction = strs[2]; const teamState = this.state.teamStates[team]; if (!teamState.units.has(unitid)) { valid = false; errormsg = `Team ${cmd.agentID} tried to move unit ${unitid} that it does not own`; break; } const unit = teamState.units.get(unitid); switch (direction) { case Game.DIRECTIONS.NORTH: case Game.DIRECTIONS.EAST: case Game.DIRECTIONS.SOUTH: case Game.DIRECTIONS.WEST: { const newpos = unit.pos.translate(direction, 1); if (!this.map.inMap(newpos)) { errormsg = `Team ${cmd.agentID} tried to move unit ${unitid} off map`; valid = false; } break; } default: errormsg = `Team ${cmd.agentID} tried to move unit ${unitid} in invalid direction ${direction}`; valid = false; break; } if (valid) { return new MoveAction( action, team, unitid, direction as Game.DIRECTIONS ); } } else { valid = false; } break; case Game.ACTIONS.CREATE_UNIT: if (strs.length === 3) { const x = parseInt(strs[1]); const y = parseInt(strs[2]); if (isNaN(x) || isNaN(y)) { valid = false; errormsg = `Team ${cmd.agentID} tried to build unit with invalid coordinates`; break; } // check if tile being built is a owned base const tile = this.map.getTile(x, y); if (!tile.isBaseTile() || tile.baseTeam !== team) { valid = false; errormsg = `Team ${cmd.agentID} tried to build unit on tile (${x}, ${y}) that does not have a base or is not owned`; break; } if (valid) { return new SpawnAction(action, team, x, y); } } else { valid = false; } break; default: valid = false; } if (valid === false) { throw new MatchWarn( errormsg + `; turn ${this.state.turn}; cmd: ${cmd.command}` ); } } } getTeamsUnits(team: Unit.TEAM): Map<Unit.ID, Unit> { return this.state.teamStates[team].units; } getUnit(team: Unit.TEAM, unitid: Unit.ID): Unit { return this.state.teamStates[team].units.get(unitid); } moveUnit(team: Unit.TEAM, unitid: Unit.ID, direction: Game.DIRECTIONS): void { const unit = this.getUnit(team, unitid); // remove unit from old cell and move to new one and update unit pos this.map.getTileByPos(unit.pos).units.delete(unit.id); unit.pos = unit.pos.translate(direction, 1); this.map.getTileByPos(unit.pos).units.set(unit.id, unit); } spawnUnit(team: Unit.TEAM, pos: Position): void { const tile = this.map.getTileByPos(pos); const unit = new Unit(team, this.globalUnitIDCount++, pos); tile.units.set(unit.id, unit); this.state.teamStates[team].units.set(unit.id, unit); } destroyUnit(team: Unit.TEAM, unitid: Unit.ID): void { const unit = this.getUnit(team, unitid); this.map.getTileByPos(unit.pos).units.delete(unitid); this.state.teamStates[team].units.delete(unitid); } // spawn all units asked to be spawn handleSpawnActions(actions: Array<SpawnAction>, match: Match): Set<Tile> { const spawnedPositionsHashes: Set<number> = new Set(); const spawnedPositions: Set<Tile> = new Set(); const UNIT_COST = this.configs.parameters.UNIT_COST; actions.forEach((action) => { // check first if points available to use if (this.state.teamStates[action.team].points >= UNIT_COST) { this.spawnUnit(action.team, action.pos); this.state.teamStates[action.team].points -= UNIT_COST; if (!spawnedPositionsHashes.has(action.pos.hash())) { spawnedPositionsHashes.add(action.pos.hash()); spawnedPositions.add(this.map.getTileByPos(action.pos)); } } else { match.log.warn( `Team ${action.team} does not have enough points to spawn another unit; turn ${this.state.turn}` ); } }); return spawnedPositions; } // move all units and then destroy any that collide handleMovementActions(actions: Array<MoveAction>, match: Match): Set<Tile> { const tilesWithNewUnits: Set<Tile> = new Set(); const idsOfUnitsThatMoved: Set<Unit.ID> = new Set(); actions.forEach((action) => { if (idsOfUnitsThatMoved.has(action.unitid)) { match.log.warn( `Team ${action.team}'s unit ${action.unitid} already moved, cannot move again this turn; turn ${this.state.turn}` ); } else { this.moveUnit(action.team, action.unitid, action.direction); const unit = this.getUnit(action.team, action.unitid); const tile = this.map.getTileByPos(unit.pos); tilesWithNewUnits.add(tile); idsOfUnitsThatMoved.add(action.unitid); } }); return tilesWithNewUnits; } handleCollisions(tilesToCheck: Set<Tile>, match: Match): void { const unitsToRemove: Array<{ unit: Unit; tile: Tile }> = []; tilesToCheck.forEach((tile) => { if (tile.units.size > 1) { // find lowest brokendown unit // remove all units as they collided let lowestBreakdown = 999999; let lowestBreakdownUnits = 1; tile.units.forEach((unit) => { const b = unit.getBreakdownLevel( this.state.turn, this.configs.parameters.BREAKDOWN_TURNS ); if (b < lowestBreakdown) { lowestBreakdown = b; lowestBreakdownUnits = 1; } else if (b == lowestBreakdown) { lowestBreakdownUnits++; } }); tile.units.forEach((unit) => { if (lowestBreakdownUnits > 1) { // all get removed unitsToRemove.push({ unit, tile }); } else { const b = unit.getBreakdownLevel( this.state.turn, this.configs.parameters.BREAKDOWN_TURNS ); if (b > lowestBreakdown) { unitsToRemove.push({ unit, tile }); } } }); } }); for (const { unit, tile } of unitsToRemove) { match.log.warn( `Team ${unit.team}'s unit ${ unit.id } collided at ${tile.pos.toString()} on turn ${this.state.turn}` ); this.destroyUnit(unit.team, unit.id); } } // give all units points depending on their tile handlePointsRelease(): void { Unit.ALL_TEAMS.forEach((team) => { const units = this.getTeamsUnits(team); units.forEach((unit) => { const tile = this.map.getTileByPos(unit.pos); this.state.teamStates[team].points += tile.pointsPerTurn; }); }); } // run after movements and collisions are handled handleRepairs(): void { this.map.bases.forEach((b) => { const tile = this.map.getTileByPos(b.pos); tile.units.forEach((unit) => { if (b.team === unit.team) { unit.lastRepairTurn = this.state.turn; } }); }); } handleBreakdown(match: Match): void { const brokenDownUnits: Array<Unit> = []; Unit.ALL_TEAMS.forEach((team) => { const units = this.getTeamsUnits(team); units.forEach((unit) => { const b = unit.getBreakdownLevel( this.state.turn, this.configs.parameters.BREAKDOWN_TURNS );
} }); }); brokenDownUnits.forEach((unit) => { match.log.warn(`Team ${unit.team}'s unit ${unit.id} broke down`); this.destroyUnit(unit.team, unit.id); }); } } export namespace Game { export interface State { turn: 0; teamStates: { [x in Unit.TEAM]: { units: Map<Unit.ID, Unit>; points: number; }; }; } export enum DIRECTIONS { NORTH = 'n', EAST = 'e', SOUTH = 's', WEST = 'w', } export enum ACTIONS { /** * formatted as `m unitid direction` */ MOVE = 'm', /** * formatted as `c x y` */ CREATE_UNIT = 'c', } }
if (b >= this.configs.parameters.BREAKDOWN_MAX) { brokenDownUnits.push(unit);
random_line_split
index.ts
import { Match } from 'dimensions-ai/lib/main/Match'; import { MatchWarn } from 'dimensions-ai/lib/main/DimensionError'; import { MatchEngine } from 'dimensions-ai/lib/main/MatchEngine'; import { MoveAction, SpawnAction, Action } from '../Actions'; import { GameMap } from '../GameMap'; import { Replay } from '../Replay'; import { Tile } from '../Tile'; import { Position } from '../Tile/position'; import { AIMatchConfigs } from '../types'; import { Unit } from '../Unit'; export class Game { public replay: Replay; public map: GameMap; public rng: () => number = Math.random; private globalUnitIDCount = 0; public state: Game.State = { turn: 0, teamStates: { [Unit.TEAM.A]: { units: new Map(), points: 0, }, [Unit.TEAM.B]: { units: new Map(), points: 0, }, }, }; constructor(public configs: AIMatchConfigs) { Unit.ALL_TEAMS.forEach((team) => { this.state.teamStates[team].points = configs.parameters.INITIAL_POINTS; }); } validateCommand(cmd: MatchEngine.Command): Action { const strs = cmd.command.split(' '); if (strs.length === 0) { throw new MatchWarn( `Agent ${cmd.agentID} sent malformed command: ${cmd.command}` ); } else { const action = strs[0]; let valid = true; const team: Unit.TEAM = cmd.agentID; let errormsg = `Team ${cmd.agentID} sent invalid command`; switch (action) { case Game.ACTIONS.MOVE: if (strs.length === 3) { const unitid = parseInt(strs[1]); const direction = strs[2]; const teamState = this.state.teamStates[team]; if (!teamState.units.has(unitid)) { valid = false; errormsg = `Team ${cmd.agentID} tried to move unit ${unitid} that it does not own`; break; } const unit = teamState.units.get(unitid); switch (direction) { case Game.DIRECTIONS.NORTH: case Game.DIRECTIONS.EAST: case Game.DIRECTIONS.SOUTH: case Game.DIRECTIONS.WEST: { const newpos = unit.pos.translate(direction, 1); if (!this.map.inMap(newpos)) { errormsg = `Team ${cmd.agentID} tried to move unit ${unitid} off map`; valid = false; } break; } default: errormsg = `Team ${cmd.agentID} tried to move unit ${unitid} in invalid direction ${direction}`; valid = false; break; } if (valid) { return new MoveAction( action, team, unitid, direction as Game.DIRECTIONS ); } } else { valid = false; } break; case Game.ACTIONS.CREATE_UNIT: if (strs.length === 3) { const x = parseInt(strs[1]); const y = parseInt(strs[2]); if (isNaN(x) || isNaN(y)) { valid = false; errormsg = `Team ${cmd.agentID} tried to build unit with invalid coordinates`; break; } // check if tile being built is a owned base const tile = this.map.getTile(x, y); if (!tile.isBaseTile() || tile.baseTeam !== team) { valid = false; errormsg = `Team ${cmd.agentID} tried to build unit on tile (${x}, ${y}) that does not have a base or is not owned`; break; } if (valid) { return new SpawnAction(action, team, x, y); } } else { valid = false; } break; default: valid = false; } if (valid === false) { throw new MatchWarn( errormsg + `; turn ${this.state.turn}; cmd: ${cmd.command}` ); } } } getTeamsUnits(team: Unit.TEAM): Map<Unit.ID, Unit> { return this.state.teamStates[team].units; } getUnit(team: Unit.TEAM, unitid: Unit.ID): Unit { return this.state.teamStates[team].units.get(unitid); } moveUnit(team: Unit.TEAM, unitid: Unit.ID, direction: Game.DIRECTIONS): void { const unit = this.getUnit(team, unitid); // remove unit from old cell and move to new one and update unit pos this.map.getTileByPos(unit.pos).units.delete(unit.id); unit.pos = unit.pos.translate(direction, 1); this.map.getTileByPos(unit.pos).units.set(unit.id, unit); } spawnUnit(team: Unit.TEAM, pos: Position): void { const tile = this.map.getTileByPos(pos); const unit = new Unit(team, this.globalUnitIDCount++, pos); tile.units.set(unit.id, unit); this.state.teamStates[team].units.set(unit.id, unit); } destroyUnit(team: Unit.TEAM, unitid: Unit.ID): void { const unit = this.getUnit(team, unitid); this.map.getTileByPos(unit.pos).units.delete(unitid); this.state.teamStates[team].units.delete(unitid); } // spawn all units asked to be spawn handleSpawnActions(actions: Array<SpawnAction>, match: Match): Set<Tile> { const spawnedPositionsHashes: Set<number> = new Set(); const spawnedPositions: Set<Tile> = new Set(); const UNIT_COST = this.configs.parameters.UNIT_COST; actions.forEach((action) => { // check first if points available to use if (this.state.teamStates[action.team].points >= UNIT_COST) { this.spawnUnit(action.team, action.pos); this.state.teamStates[action.team].points -= UNIT_COST; if (!spawnedPositionsHashes.has(action.pos.hash())) { spawnedPositionsHashes.add(action.pos.hash()); spawnedPositions.add(this.map.getTileByPos(action.pos)); } } else { match.log.warn( `Team ${action.team} does not have enough points to spawn another unit; turn ${this.state.turn}` ); } }); return spawnedPositions; } // move all units and then destroy any that collide handleMovementActions(actions: Array<MoveAction>, match: Match): Set<Tile> { const tilesWithNewUnits: Set<Tile> = new Set(); const idsOfUnitsThatMoved: Set<Unit.ID> = new Set(); actions.forEach((action) => { if (idsOfUnitsThatMoved.has(action.unitid)) { match.log.warn( `Team ${action.team}'s unit ${action.unitid} already moved, cannot move again this turn; turn ${this.state.turn}` ); } else { this.moveUnit(action.team, action.unitid, action.direction); const unit = this.getUnit(action.team, action.unitid); const tile = this.map.getTileByPos(unit.pos); tilesWithNewUnits.add(tile); idsOfUnitsThatMoved.add(action.unitid); } }); return tilesWithNewUnits; }
(tilesToCheck: Set<Tile>, match: Match): void { const unitsToRemove: Array<{ unit: Unit; tile: Tile }> = []; tilesToCheck.forEach((tile) => { if (tile.units.size > 1) { // find lowest brokendown unit // remove all units as they collided let lowestBreakdown = 999999; let lowestBreakdownUnits = 1; tile.units.forEach((unit) => { const b = unit.getBreakdownLevel( this.state.turn, this.configs.parameters.BREAKDOWN_TURNS ); if (b < lowestBreakdown) { lowestBreakdown = b; lowestBreakdownUnits = 1; } else if (b == lowestBreakdown) { lowestBreakdownUnits++; } }); tile.units.forEach((unit) => { if (lowestBreakdownUnits > 1) { // all get removed unitsToRemove.push({ unit, tile }); } else { const b = unit.getBreakdownLevel( this.state.turn, this.configs.parameters.BREAKDOWN_TURNS ); if (b > lowestBreakdown) { unitsToRemove.push({ unit, tile }); } } }); } }); for (const { unit, tile } of unitsToRemove) { match.log.warn( `Team ${unit.team}'s unit ${ unit.id } collided at ${tile.pos.toString()} on turn ${this.state.turn}` ); this.destroyUnit(unit.team, unit.id); } } // give all units points depending on their tile handlePointsRelease(): void { Unit.ALL_TEAMS.forEach((team) => { const units = this.getTeamsUnits(team); units.forEach((unit) => { const tile = this.map.getTileByPos(unit.pos); this.state.teamStates[team].points += tile.pointsPerTurn; }); }); } // run after movements and collisions are handled handleRepairs(): void { this.map.bases.forEach((b) => { const tile = this.map.getTileByPos(b.pos); tile.units.forEach((unit) => { if (b.team === unit.team) { unit.lastRepairTurn = this.state.turn; } }); }); } handleBreakdown(match: Match): void { const brokenDownUnits: Array<Unit> = []; Unit.ALL_TEAMS.forEach((team) => { const units = this.getTeamsUnits(team); units.forEach((unit) => { const b = unit.getBreakdownLevel( this.state.turn, this.configs.parameters.BREAKDOWN_TURNS ); if (b >= this.configs.parameters.BREAKDOWN_MAX) { brokenDownUnits.push(unit); } }); }); brokenDownUnits.forEach((unit) => { match.log.warn(`Team ${unit.team}'s unit ${unit.id} broke down`); this.destroyUnit(unit.team, unit.id); }); } } export namespace Game { export interface State { turn: 0; teamStates: { [x in Unit.TEAM]: { units: Map<Unit.ID, Unit>; points: number; }; }; } export enum DIRECTIONS { NORTH = 'n', EAST = 'e', SOUTH = 's', WEST = 'w', } export enum ACTIONS { /** * formatted as `m unitid direction` */ MOVE = 'm', /** * formatted as `c x y` */ CREATE_UNIT = 'c', } }
handleCollisions
identifier_name
index.ts
import { Match } from 'dimensions-ai/lib/main/Match'; import { MatchWarn } from 'dimensions-ai/lib/main/DimensionError'; import { MatchEngine } from 'dimensions-ai/lib/main/MatchEngine'; import { MoveAction, SpawnAction, Action } from '../Actions'; import { GameMap } from '../GameMap'; import { Replay } from '../Replay'; import { Tile } from '../Tile'; import { Position } from '../Tile/position'; import { AIMatchConfigs } from '../types'; import { Unit } from '../Unit'; export class Game { public replay: Replay; public map: GameMap; public rng: () => number = Math.random; private globalUnitIDCount = 0; public state: Game.State = { turn: 0, teamStates: { [Unit.TEAM.A]: { units: new Map(), points: 0, }, [Unit.TEAM.B]: { units: new Map(), points: 0, }, }, }; constructor(public configs: AIMatchConfigs) { Unit.ALL_TEAMS.forEach((team) => { this.state.teamStates[team].points = configs.parameters.INITIAL_POINTS; }); } validateCommand(cmd: MatchEngine.Command): Action { const strs = cmd.command.split(' '); if (strs.length === 0) { throw new MatchWarn( `Agent ${cmd.agentID} sent malformed command: ${cmd.command}` ); } else { const action = strs[0]; let valid = true; const team: Unit.TEAM = cmd.agentID; let errormsg = `Team ${cmd.agentID} sent invalid command`; switch (action) { case Game.ACTIONS.MOVE: if (strs.length === 3) { const unitid = parseInt(strs[1]); const direction = strs[2]; const teamState = this.state.teamStates[team]; if (!teamState.units.has(unitid))
const unit = teamState.units.get(unitid); switch (direction) { case Game.DIRECTIONS.NORTH: case Game.DIRECTIONS.EAST: case Game.DIRECTIONS.SOUTH: case Game.DIRECTIONS.WEST: { const newpos = unit.pos.translate(direction, 1); if (!this.map.inMap(newpos)) { errormsg = `Team ${cmd.agentID} tried to move unit ${unitid} off map`; valid = false; } break; } default: errormsg = `Team ${cmd.agentID} tried to move unit ${unitid} in invalid direction ${direction}`; valid = false; break; } if (valid) { return new MoveAction( action, team, unitid, direction as Game.DIRECTIONS ); } } else { valid = false; } break; case Game.ACTIONS.CREATE_UNIT: if (strs.length === 3) { const x = parseInt(strs[1]); const y = parseInt(strs[2]); if (isNaN(x) || isNaN(y)) { valid = false; errormsg = `Team ${cmd.agentID} tried to build unit with invalid coordinates`; break; } // check if tile being built is a owned base const tile = this.map.getTile(x, y); if (!tile.isBaseTile() || tile.baseTeam !== team) { valid = false; errormsg = `Team ${cmd.agentID} tried to build unit on tile (${x}, ${y}) that does not have a base or is not owned`; break; } if (valid) { return new SpawnAction(action, team, x, y); } } else { valid = false; } break; default: valid = false; } if (valid === false) { throw new MatchWarn( errormsg + `; turn ${this.state.turn}; cmd: ${cmd.command}` ); } } } getTeamsUnits(team: Unit.TEAM): Map<Unit.ID, Unit> { return this.state.teamStates[team].units; } getUnit(team: Unit.TEAM, unitid: Unit.ID): Unit { return this.state.teamStates[team].units.get(unitid); } moveUnit(team: Unit.TEAM, unitid: Unit.ID, direction: Game.DIRECTIONS): void { const unit = this.getUnit(team, unitid); // remove unit from old cell and move to new one and update unit pos this.map.getTileByPos(unit.pos).units.delete(unit.id); unit.pos = unit.pos.translate(direction, 1); this.map.getTileByPos(unit.pos).units.set(unit.id, unit); } spawnUnit(team: Unit.TEAM, pos: Position): void { const tile = this.map.getTileByPos(pos); const unit = new Unit(team, this.globalUnitIDCount++, pos); tile.units.set(unit.id, unit); this.state.teamStates[team].units.set(unit.id, unit); } destroyUnit(team: Unit.TEAM, unitid: Unit.ID): void { const unit = this.getUnit(team, unitid); this.map.getTileByPos(unit.pos).units.delete(unitid); this.state.teamStates[team].units.delete(unitid); } // spawn all units asked to be spawn handleSpawnActions(actions: Array<SpawnAction>, match: Match): Set<Tile> { const spawnedPositionsHashes: Set<number> = new Set(); const spawnedPositions: Set<Tile> = new Set(); const UNIT_COST = this.configs.parameters.UNIT_COST; actions.forEach((action) => { // check first if points available to use if (this.state.teamStates[action.team].points >= UNIT_COST) { this.spawnUnit(action.team, action.pos); this.state.teamStates[action.team].points -= UNIT_COST; if (!spawnedPositionsHashes.has(action.pos.hash())) { spawnedPositionsHashes.add(action.pos.hash()); spawnedPositions.add(this.map.getTileByPos(action.pos)); } } else { match.log.warn( `Team ${action.team} does not have enough points to spawn another unit; turn ${this.state.turn}` ); } }); return spawnedPositions; } // move all units and then destroy any that collide handleMovementActions(actions: Array<MoveAction>, match: Match): Set<Tile> { const tilesWithNewUnits: Set<Tile> = new Set(); const idsOfUnitsThatMoved: Set<Unit.ID> = new Set(); actions.forEach((action) => { if (idsOfUnitsThatMoved.has(action.unitid)) { match.log.warn( `Team ${action.team}'s unit ${action.unitid} already moved, cannot move again this turn; turn ${this.state.turn}` ); } else { this.moveUnit(action.team, action.unitid, action.direction); const unit = this.getUnit(action.team, action.unitid); const tile = this.map.getTileByPos(unit.pos); tilesWithNewUnits.add(tile); idsOfUnitsThatMoved.add(action.unitid); } }); return tilesWithNewUnits; } handleCollisions(tilesToCheck: Set<Tile>, match: Match): void { const unitsToRemove: Array<{ unit: Unit; tile: Tile }> = []; tilesToCheck.forEach((tile) => { if (tile.units.size > 1) { // find lowest brokendown unit // remove all units as they collided let lowestBreakdown = 999999; let lowestBreakdownUnits = 1; tile.units.forEach((unit) => { const b = unit.getBreakdownLevel( this.state.turn, this.configs.parameters.BREAKDOWN_TURNS ); if (b < lowestBreakdown) { lowestBreakdown = b; lowestBreakdownUnits = 1; } else if (b == lowestBreakdown) { lowestBreakdownUnits++; } }); tile.units.forEach((unit) => { if (lowestBreakdownUnits > 1) { // all get removed unitsToRemove.push({ unit, tile }); } else { const b = unit.getBreakdownLevel( this.state.turn, this.configs.parameters.BREAKDOWN_TURNS ); if (b > lowestBreakdown) { unitsToRemove.push({ unit, tile }); } } }); } }); for (const { unit, tile } of unitsToRemove) { match.log.warn( `Team ${unit.team}'s unit ${ unit.id } collided at ${tile.pos.toString()} on turn ${this.state.turn}` ); this.destroyUnit(unit.team, unit.id); } } // give all units points depending on their tile handlePointsRelease(): void { Unit.ALL_TEAMS.forEach((team) => { const units = this.getTeamsUnits(team); units.forEach((unit) => { const tile = this.map.getTileByPos(unit.pos); this.state.teamStates[team].points += tile.pointsPerTurn; }); }); } // run after movements and collisions are handled handleRepairs(): void { this.map.bases.forEach((b) => { const tile = this.map.getTileByPos(b.pos); tile.units.forEach((unit) => { if (b.team === unit.team) { unit.lastRepairTurn = this.state.turn; } }); }); } handleBreakdown(match: Match): void { const brokenDownUnits: Array<Unit> = []; Unit.ALL_TEAMS.forEach((team) => { const units = this.getTeamsUnits(team); units.forEach((unit) => { const b = unit.getBreakdownLevel( this.state.turn, this.configs.parameters.BREAKDOWN_TURNS ); if (b >= this.configs.parameters.BREAKDOWN_MAX) { brokenDownUnits.push(unit); } }); }); brokenDownUnits.forEach((unit) => { match.log.warn(`Team ${unit.team}'s unit ${unit.id} broke down`); this.destroyUnit(unit.team, unit.id); }); } } export namespace Game { export interface State { turn: 0; teamStates: { [x in Unit.TEAM]: { units: Map<Unit.ID, Unit>; points: number; }; }; } export enum DIRECTIONS { NORTH = 'n', EAST = 'e', SOUTH = 's', WEST = 'w', } export enum ACTIONS { /** * formatted as `m unitid direction` */ MOVE = 'm', /** * formatted as `c x y` */ CREATE_UNIT = 'c', } }
{ valid = false; errormsg = `Team ${cmd.agentID} tried to move unit ${unitid} that it does not own`; break; }
conditional_block
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import CheckBox from './CheckBox'; import './index.css'; class Square extends React.Component { render() { return ( <button className="square" onClick={() => this.props.onClick()}> {this.props.value} </button> ); } } class SquareScores extends React.Component { render() { return ( <button className="square-scores"> {this.props.value} </button> ); } } class Board extends React.Component { constructor(props) { super(props); this.state = { modes: [{id: 1, value: "1 joueur", isChecked: true}, {id: 2, value: "2 joueur", isChecked: false}, {id: 3, value: "vs Random", isChecked: false},], mode: 1, squares: [], squares_print: [], scores: [], nbGames: 0, end: false, //-1 si pas d'information, sinon id de la case //false si mauvaise paire, true si bonne paire result: [-1, -1, false], nbPairs: 2, nbPairsFound: 0, score: [0,0], nickname1: "Hopla", nickname2: "Titeuf", oneIsNext: false, infos: " | Start pour jouer", cXr: 0, //Nombre de cases (Columns * Rows) col: 0, //Nombre de colones }; this.handleFormPairs = this.handleFormPairs.bind(this) this.handleFormNick1 = this.handleFormNick1.bind(this) this.handleFormNick2 = this.handleFormNick2.bind(this) } setGame() { this.setState((prevstate) => { let col = 1 let cXr = 0 let nickname2 = "Titeuf" let mode = this.checkModes(prevstate.modes) console.log("mode: " + mode) if(mode === 1){ nickname2 = "---" } console.log("cXr :" + cXr) // On cherche à avoir un carré peut importe le nombre de paires while (cXr <= prevstate.nbPairs*2) { //tant que colonne * ligne < nombre de cartes col+=1 cXr = Math.pow(col,2) console.log("cXr :" + cXr) } console.log("col: " + col + " | cXr: "+ cXr + " | " + this.state.nbPairs*2) // Création de l'array a affiché rempli de null console.log("nbPairs: " + prevstate.nbPairs) let squares_print = Array(parseInt(prevstate.nbPairs, 10) * 2).fill("?") squares_print = squares_print.concat(Array(cXr-this.state.nbPairs).fill("-")) console.log("squares_print :" + squares_print) // Création de l'array avec les chiffres, rempli aléatoirement let squares = [...Array(parseInt(prevstate.nbPairs, 10)).keys()] squares = shuffle(squares.concat([...Array(parseInt(prevstate.nbPairs, 10)).keys()])) console.log("squares :" + squares) return { squares: squares, squares_print: squares_print, result: [-1, -1, false], nbPairsFound: 0, score: [0,0], infos: "GO !", oneIsNext: true, cXr: cXr, col: col, end: false, mode: mode, nickname2: nickname2, }; }); } checkModes(modes){ //1 joueur if (modes[0].isChecked){ return(modes[0].id) } //2 joueur else if (modes[1].isChecked){ return(modes[1].id) } //random else if (modes[2].isChecked){ return(modes[2].id) } } handleSquareClick(i) { this.setState((prevstate) => { let result = { ...prevstate.result } let squares = { ...prevstate.squares } let squares_print = { ...prevstate.squares_print } let score = prevstate.score let nbPairsFound = prevstate.nbPairsFound let oneIsNext = prevstate.oneIsNext let infos = "GO !" let nbGames = prevstate.nbGames let p = 0 let scores = prevstate.scores let end = true if(prevstate.mode !== 1){ p = oneIsNext ? 0 : 1 } console.log("----NouveauClick----") //2 cartes d'affichés console.log(result) if (result[0] !== -1 && result[1] !== -1) { if (result[2] === false) { squares_print[result[0]] = "?" squares_print[result[1]] = "?" } result = [-1, -1, false] //0 cartes d'affichés } if (result[0] === -1 && result[1] === -1) { if (squares_print[i] === "?") { result[0] = i squares_print[i] = squares[i] } else if (typeof squares[i] === 'undefined'){ infos = "Pas une carte" } else { infos = "Déjà retourné" } //1 cartes d'affichés } else if (result[1] === -1) { if (squares_print[i] === "?") { result[1] = i squares_print[i] = squares[i] console.log("nb cartes affichés: 1") if (result[0] !== result[1] && squares[result[0]] === squares[result[1]]) {
squares_print[result[1]] = squares[result[1]] result[2] = true score[p] = score[p] + 3 nbPairsFound += 1 } else { result[2] = false score[p] = score[p] - 1 } if(prevstate.mode !== 1){ oneIsNext = !oneIsNext } } else if (typeof squares[i] === 'undefined'){ infos = "Pas une carte" } else { infos = "Déjà retourné" } console.log("score : " + score) console.log("oneIsNext: " + oneIsNext) } console.log("nbPairsFound: " + nbPairsFound) console.log("prevstate.nbPairs: " + prevstate.nbPairs) console.log("prevstate.end: " + prevstate.end) if (nbPairsFound === prevstate.nbPairs && prevstate.end) { infos = "Gagné !" console.log("We are in ! ") nbGames += 1 if(prevstate.mode !== 1){ scores.push(prevstate.nickname1, prevstate.score[0]) scores.push(prevstate.nickname2, prevstate.score[1]) console.log("We are in X 2 !!") } else{ scores.push(prevstate.nickname1, prevstate.score[0]) scores.push("_", "_") } } return { squares: squares, squares_print: squares_print, result: result, score: score, nbPairsFound: nbPairsFound, infos: infos, oneIsNext: oneIsNext, nbGames: nbGames, scores: scores, end: end, }; }); } handleFormPairs(event) { this.setState(() => { return{ nbPairs: event.target.value } }) console.log(this.state.nbPairs) } handleFormNick1(event) { this.setState(() => { return{ nickname1: event.target.value } }) console.log(this.state.nickname1) } handleFormNick2(event) { this.setState(() => { return{ nickname2: event.target.value } }) console.log(this.state.nickname2) } handleCheckChieldElement = (event) => { let modes = this.state.modes modes.forEach(mode => { if (mode.value === event.target.value) mode.isChecked = event.target.checked }) this.setState({modes: modes}) } renderSquare(i) { return <Square value={this.state.squares_print[i]} key={i} onClick={() => this.handleSquareClick(i)} />; } renderSquareScores(i) { return <SquareScores value={this.state.scores[i]} key={i}/>; } createTable() { let table = [] let k = 0 let col = this.state.col for (let i = 0; i < col; i++) { let children = [] for (let j = 0; j < col; j++) { children.push(this.renderSquare(k)) k++ } table.push(children) table.push(<div className="board-row" key={i}></div>) } return table } createTableScores() { let table = [] let k = 0 let col = 4 let row = this.state.nbGames console.log("row: " + row) for (let i = 0; i < row; i++) { let children = [] for (let j = 0; j < col; j++) { children.push(this.renderSquareScores(k)) k++ } table.push(children) table.push(<div className="board-row" key={i}></div>) } return table } render() { let tour = "C'est à " + ((this.state.oneIsNext) ? this.state.nickname1 : this.state.nickname2) + " de jouer" let status = this.state.infos let points = "" if (this.state.mode !== 1) { points = this.state.nickname1 + ": " + this.state.score[0] + "pts | " + this.state.nickname2 + ": " + this.state.score[1] + "pts" } else { points = this.state.nickname1 + ": " + this.state.score[0] + "pts " } return ( <div> <div className="titleTHE"> THE </div> <div className="title"> Numbers Memory Game </div> <ul> {this.state.modes.map((mode, index) => { return (<CheckBox key={index} handleCheckChieldElement={this.handleCheckChieldElement} {...mode} />) }) } </ul> <form> <label> Joueur 1: <input className="text-nicknames" value={this.state.nickname1} type="text" name="toto" onChange={this.handleFormNick1} /> </label> </form> <form> <label> Joueur 2: <input className="text-nicknames" value={this.state.nickname2} type="text" onChange={this.handleFormNick2} /> </label> </form> <div className="status">{points}</div> <button className="button" variant="primary" onClick={() => this.setGame()}>Start </button> <div>{" "+status}</div> <div className="status">{tour}</div> <div>{this.createTable()}</div> <form> <label>Paires : <input className="text-paires" value={this.state.nbPairs} type="number" onChange={this.handleFormPairs}/> {" | "} {this.state.nbPairs - this.state.nbPairsFound}{' paires restantes'} </label> </form> <div> {"Tableau des scores"} <br /> {this.createTableScores()} </div> </div> ); } } class Game extends React.Component { render() { return ( <div className="game"> <div className="game-board"> <Board /> </div> <div className="game-info"> <div>{/* status */}</div> <ol>{/* TODO */}</ol> </div> </div> ); } } // ======================================== ReactDOM.render( <Game />, document.getElementById('root') ); //Volé honteusement sur un site radom function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }
squares_print[result[0]] = squares[result[0]]
random_line_split
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import CheckBox from './CheckBox'; import './index.css'; class Square extends React.Component { render() { return ( <button className="square" onClick={() => this.props.onClick()}> {this.props.value} </button> ); } } class SquareScores extends React.Component { render() { return ( <button className="square-scores"> {this.props.value} </button> ); } } class Board extends React.Component { constructor(props) { super(props); this.state = { modes: [{id: 1, value: "1 joueur", isChecked: true}, {id: 2, value: "2 joueur", isChecked: false}, {id: 3, value: "vs Random", isChecked: false},], mode: 1, squares: [], squares_print: [], scores: [], nbGames: 0, end: false, //-1 si pas d'information, sinon id de la case //false si mauvaise paire, true si bonne paire result: [-1, -1, false], nbPairs: 2, nbPairsFound: 0, score: [0,0], nickname1: "Hopla", nickname2: "Titeuf", oneIsNext: false, infos: " | Start pour jouer", cXr: 0, //Nombre de cases (Columns * Rows) col: 0, //Nombre de colones }; this.handleFormPairs = this.handleFormPairs.bind(this) this.handleFormNick1 = this.handleFormNick1.bind(this) this.handleFormNick2 = this.handleFormNick2.bind(this) } setGame()
heckModes(modes){ //1 joueur if (modes[0].isChecked){ return(modes[0].id) } //2 joueur else if (modes[1].isChecked){ return(modes[1].id) } //random else if (modes[2].isChecked){ return(modes[2].id) } } handleSquareClick(i) { this.setState((prevstate) => { let result = { ...prevstate.result } let squares = { ...prevstate.squares } let squares_print = { ...prevstate.squares_print } let score = prevstate.score let nbPairsFound = prevstate.nbPairsFound let oneIsNext = prevstate.oneIsNext let infos = "GO !" let nbGames = prevstate.nbGames let p = 0 let scores = prevstate.scores let end = true if(prevstate.mode !== 1){ p = oneIsNext ? 0 : 1 } console.log("----NouveauClick----") //2 cartes d'affichés console.log(result) if (result[0] !== -1 && result[1] !== -1) { if (result[2] === false) { squares_print[result[0]] = "?" squares_print[result[1]] = "?" } result = [-1, -1, false] //0 cartes d'affichés } if (result[0] === -1 && result[1] === -1) { if (squares_print[i] === "?") { result[0] = i squares_print[i] = squares[i] } else if (typeof squares[i] === 'undefined'){ infos = "Pas une carte" } else { infos = "Déjà retourné" } //1 cartes d'affichés } else if (result[1] === -1) { if (squares_print[i] === "?") { result[1] = i squares_print[i] = squares[i] console.log("nb cartes affichés: 1") if (result[0] !== result[1] && squares[result[0]] === squares[result[1]]) { squares_print[result[0]] = squares[result[0]] squares_print[result[1]] = squares[result[1]] result[2] = true score[p] = score[p] + 3 nbPairsFound += 1 } else { result[2] = false score[p] = score[p] - 1 } if(prevstate.mode !== 1){ oneIsNext = !oneIsNext } } else if (typeof squares[i] === 'undefined'){ infos = "Pas une carte" } else { infos = "Déjà retourné" } console.log("score : " + score) console.log("oneIsNext: " + oneIsNext) } console.log("nbPairsFound: " + nbPairsFound) console.log("prevstate.nbPairs: " + prevstate.nbPairs) console.log("prevstate.end: " + prevstate.end) if (nbPairsFound === prevstate.nbPairs && prevstate.end) { infos = "Gagné !" console.log("We are in ! ") nbGames += 1 if(prevstate.mode !== 1){ scores.push(prevstate.nickname1, prevstate.score[0]) scores.push(prevstate.nickname2, prevstate.score[1]) console.log("We are in X 2 !!") } else{ scores.push(prevstate.nickname1, prevstate.score[0]) scores.push("_", "_") } } return { squares: squares, squares_print: squares_print, result: result, score: score, nbPairsFound: nbPairsFound, infos: infos, oneIsNext: oneIsNext, nbGames: nbGames, scores: scores, end: end, }; }); } handleFormPairs(event) { this.setState(() => { return{ nbPairs: event.target.value } }) console.log(this.state.nbPairs) } handleFormNick1(event) { this.setState(() => { return{ nickname1: event.target.value } }) console.log(this.state.nickname1) } handleFormNick2(event) { this.setState(() => { return{ nickname2: event.target.value } }) console.log(this.state.nickname2) } handleCheckChieldElement = (event) => { let modes = this.state.modes modes.forEach(mode => { if (mode.value === event.target.value) mode.isChecked = event.target.checked }) this.setState({modes: modes}) } renderSquare(i) { return <Square value={this.state.squares_print[i]} key={i} onClick={() => this.handleSquareClick(i)} />; } renderSquareScores(i) { return <SquareScores value={this.state.scores[i]} key={i}/>; } createTable() { let table = [] let k = 0 let col = this.state.col for (let i = 0; i < col; i++) { let children = [] for (let j = 0; j < col; j++) { children.push(this.renderSquare(k)) k++ } table.push(children) table.push(<div className="board-row" key={i}></div>) } return table } createTableScores() { let table = [] let k = 0 let col = 4 let row = this.state.nbGames console.log("row: " + row) for (let i = 0; i < row; i++) { let children = [] for (let j = 0; j < col; j++) { children.push(this.renderSquareScores(k)) k++ } table.push(children) table.push(<div className="board-row" key={i}></div>) } return table } render() { let tour = "C'est à " + ((this.state.oneIsNext) ? this.state.nickname1 : this.state.nickname2) + " de jouer" let status = this.state.infos let points = "" if (this.state.mode !== 1) { points = this.state.nickname1 + ": " + this.state.score[0] + "pts | " + this.state.nickname2 + ": " + this.state.score[1] + "pts" } else { points = this.state.nickname1 + ": " + this.state.score[0] + "pts " } return ( <div> <div className="titleTHE"> THE </div> <div className="title"> Numbers Memory Game </div> <ul> {this.state.modes.map((mode, index) => { return (<CheckBox key={index} handleCheckChieldElement={this.handleCheckChieldElement} {...mode} />) }) } </ul> <form> <label> Joueur 1: <input className="text-nicknames" value={this.state.nickname1} type="text" name="toto" onChange={this.handleFormNick1} /> </label> </form> <form> <label> Joueur 2: <input className="text-nicknames" value={this.state.nickname2} type="text" onChange={this.handleFormNick2} /> </label> </form> <div className="status">{points}</div> <button className="button" variant="primary" onClick={() => this.setGame()}>Start </button> <div>{" "+status}</div> <div className="status">{tour}</div> <div>{this.createTable()}</div> <form> <label>Paires : <input className="text-paires" value={this.state.nbPairs} type="number" onChange={this.handleFormPairs}/> {" | "} {this.state.nbPairs - this.state.nbPairsFound}{' paires restantes'} </label> </form> <div> {"Tableau des scores"} <br /> {this.createTableScores()} </div> </div> ); } } class Game extends React.Component { render() { return ( <div className="game"> <div className="game-board"> <Board /> </div> <div className="game-info"> <div>{/* status */}</div> <ol>{/* TODO */}</ol> </div> </div> ); } } // ======================================== ReactDOM.render( <Game />, document.getElementById('root') ); //Volé honteusement sur un site radom function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }
{ this.setState((prevstate) => { let col = 1 let cXr = 0 let nickname2 = "Titeuf" let mode = this.checkModes(prevstate.modes) console.log("mode: " + mode) if(mode === 1){ nickname2 = "---" } console.log("cXr :" + cXr) // On cherche à avoir un carré peut importe le nombre de paires while (cXr <= prevstate.nbPairs*2) { //tant que colonne * ligne < nombre de cartes col+=1 cXr = Math.pow(col,2) console.log("cXr :" + cXr) } console.log("col: " + col + " | cXr: "+ cXr + " | " + this.state.nbPairs*2) // Création de l'array a affiché rempli de null console.log("nbPairs: " + prevstate.nbPairs) let squares_print = Array(parseInt(prevstate.nbPairs, 10) * 2).fill("?") squares_print = squares_print.concat(Array(cXr-this.state.nbPairs).fill("-")) console.log("squares_print :" + squares_print) // Création de l'array avec les chiffres, rempli aléatoirement let squares = [...Array(parseInt(prevstate.nbPairs, 10)).keys()] squares = shuffle(squares.concat([...Array(parseInt(prevstate.nbPairs, 10)).keys()])) console.log("squares :" + squares) return { squares: squares, squares_print: squares_print, result: [-1, -1, false], nbPairsFound: 0, score: [0,0], infos: "GO !", oneIsNext: true, cXr: cXr, col: col, end: false, mode: mode, nickname2: nickname2, }; }); } c
identifier_body
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import CheckBox from './CheckBox'; import './index.css'; class Square extends React.Component { render() { return ( <button className="square" onClick={() => this.props.onClick()}> {this.props.value} </button> ); } } class SquareScores extends React.Component { render() { return ( <button className="square-scores"> {this.props.value} </button> ); } } class Board extends React.Component { constructor(props) { super(props); this.state = { modes: [{id: 1, value: "1 joueur", isChecked: true}, {id: 2, value: "2 joueur", isChecked: false}, {id: 3, value: "vs Random", isChecked: false},], mode: 1, squares: [], squares_print: [], scores: [], nbGames: 0, end: false, //-1 si pas d'information, sinon id de la case //false si mauvaise paire, true si bonne paire result: [-1, -1, false], nbPairs: 2, nbPairsFound: 0, score: [0,0], nickname1: "Hopla", nickname2: "Titeuf", oneIsNext: false, infos: " | Start pour jouer", cXr: 0, //Nombre de cases (Columns * Rows) col: 0, //Nombre de colones }; this.handleFormPairs = this.handleFormPairs.bind(this) this.handleFormNick1 = this.handleFormNick1.bind(this) this.handleFormNick2 = this.handleFormNick2.bind(this) } setGame() { this.setState((prevstate) => { let col = 1 let cXr = 0 let nickname2 = "Titeuf" let mode = this.checkModes(prevstate.modes) console.log("mode: " + mode) if(mode === 1){ nickname2 = "---" } console.log("cXr :" + cXr) // On cherche à avoir un carré peut importe le nombre de paires while (cXr <= prevstate.nbPairs*2) { //tant que colonne * ligne < nombre de cartes col+=1 cXr = Math.pow(col,2) console.log("cXr :" + cXr) } console.log("col: " + col + " | cXr: "+ cXr + " | " + this.state.nbPairs*2) // Création de l'array a affiché rempli de null console.log("nbPairs: " + prevstate.nbPairs) let squares_print = Array(parseInt(prevstate.nbPairs, 10) * 2).fill("?") squares_print = squares_print.concat(Array(cXr-this.state.nbPairs).fill("-")) console.log("squares_print :" + squares_print) // Création de l'array avec les chiffres, rempli aléatoirement let squares = [...Array(parseInt(prevstate.nbPairs, 10)).keys()] squares = shuffle(squares.concat([...Array(parseInt(prevstate.nbPairs, 10)).keys()])) console.log("squares :" + squares) return { squares: squares, squares_print: squares_print, result: [-1, -1, false], nbPairsFound: 0, score: [0,0], infos: "GO !", oneIsNext: true, cXr: cXr, col: col, end: false, mode: mode, nickname2: nickname2, }; }); } checkM
){ //1 joueur if (modes[0].isChecked){ return(modes[0].id) } //2 joueur else if (modes[1].isChecked){ return(modes[1].id) } //random else if (modes[2].isChecked){ return(modes[2].id) } } handleSquareClick(i) { this.setState((prevstate) => { let result = { ...prevstate.result } let squares = { ...prevstate.squares } let squares_print = { ...prevstate.squares_print } let score = prevstate.score let nbPairsFound = prevstate.nbPairsFound let oneIsNext = prevstate.oneIsNext let infos = "GO !" let nbGames = prevstate.nbGames let p = 0 let scores = prevstate.scores let end = true if(prevstate.mode !== 1){ p = oneIsNext ? 0 : 1 } console.log("----NouveauClick----") //2 cartes d'affichés console.log(result) if (result[0] !== -1 && result[1] !== -1) { if (result[2] === false) { squares_print[result[0]] = "?" squares_print[result[1]] = "?" } result = [-1, -1, false] //0 cartes d'affichés } if (result[0] === -1 && result[1] === -1) { if (squares_print[i] === "?") { result[0] = i squares_print[i] = squares[i] } else if (typeof squares[i] === 'undefined'){ infos = "Pas une carte" } else { infos = "Déjà retourné" } //1 cartes d'affichés } else if (result[1] === -1) { if (squares_print[i] === "?") { result[1] = i squares_print[i] = squares[i] console.log("nb cartes affichés: 1") if (result[0] !== result[1] && squares[result[0]] === squares[result[1]]) { squares_print[result[0]] = squares[result[0]] squares_print[result[1]] = squares[result[1]] result[2] = true score[p] = score[p] + 3 nbPairsFound += 1 } else { result[2] = false score[p] = score[p] - 1 } if(prevstate.mode !== 1){ oneIsNext = !oneIsNext } } else if (typeof squares[i] === 'undefined'){ infos = "Pas une carte" } else { infos = "Déjà retourné" } console.log("score : " + score) console.log("oneIsNext: " + oneIsNext) } console.log("nbPairsFound: " + nbPairsFound) console.log("prevstate.nbPairs: " + prevstate.nbPairs) console.log("prevstate.end: " + prevstate.end) if (nbPairsFound === prevstate.nbPairs && prevstate.end) { infos = "Gagné !" console.log("We are in ! ") nbGames += 1 if(prevstate.mode !== 1){ scores.push(prevstate.nickname1, prevstate.score[0]) scores.push(prevstate.nickname2, prevstate.score[1]) console.log("We are in X 2 !!") } else{ scores.push(prevstate.nickname1, prevstate.score[0]) scores.push("_", "_") } } return { squares: squares, squares_print: squares_print, result: result, score: score, nbPairsFound: nbPairsFound, infos: infos, oneIsNext: oneIsNext, nbGames: nbGames, scores: scores, end: end, }; }); } handleFormPairs(event) { this.setState(() => { return{ nbPairs: event.target.value } }) console.log(this.state.nbPairs) } handleFormNick1(event) { this.setState(() => { return{ nickname1: event.target.value } }) console.log(this.state.nickname1) } handleFormNick2(event) { this.setState(() => { return{ nickname2: event.target.value } }) console.log(this.state.nickname2) } handleCheckChieldElement = (event) => { let modes = this.state.modes modes.forEach(mode => { if (mode.value === event.target.value) mode.isChecked = event.target.checked }) this.setState({modes: modes}) } renderSquare(i) { return <Square value={this.state.squares_print[i]} key={i} onClick={() => this.handleSquareClick(i)} />; } renderSquareScores(i) { return <SquareScores value={this.state.scores[i]} key={i}/>; } createTable() { let table = [] let k = 0 let col = this.state.col for (let i = 0; i < col; i++) { let children = [] for (let j = 0; j < col; j++) { children.push(this.renderSquare(k)) k++ } table.push(children) table.push(<div className="board-row" key={i}></div>) } return table } createTableScores() { let table = [] let k = 0 let col = 4 let row = this.state.nbGames console.log("row: " + row) for (let i = 0; i < row; i++) { let children = [] for (let j = 0; j < col; j++) { children.push(this.renderSquareScores(k)) k++ } table.push(children) table.push(<div className="board-row" key={i}></div>) } return table } render() { let tour = "C'est à " + ((this.state.oneIsNext) ? this.state.nickname1 : this.state.nickname2) + " de jouer" let status = this.state.infos let points = "" if (this.state.mode !== 1) { points = this.state.nickname1 + ": " + this.state.score[0] + "pts | " + this.state.nickname2 + ": " + this.state.score[1] + "pts" } else { points = this.state.nickname1 + ": " + this.state.score[0] + "pts " } return ( <div> <div className="titleTHE"> THE </div> <div className="title"> Numbers Memory Game </div> <ul> {this.state.modes.map((mode, index) => { return (<CheckBox key={index} handleCheckChieldElement={this.handleCheckChieldElement} {...mode} />) }) } </ul> <form> <label> Joueur 1: <input className="text-nicknames" value={this.state.nickname1} type="text" name="toto" onChange={this.handleFormNick1} /> </label> </form> <form> <label> Joueur 2: <input className="text-nicknames" value={this.state.nickname2} type="text" onChange={this.handleFormNick2} /> </label> </form> <div className="status">{points}</div> <button className="button" variant="primary" onClick={() => this.setGame()}>Start </button> <div>{" "+status}</div> <div className="status">{tour}</div> <div>{this.createTable()}</div> <form> <label>Paires : <input className="text-paires" value={this.state.nbPairs} type="number" onChange={this.handleFormPairs}/> {" | "} {this.state.nbPairs - this.state.nbPairsFound}{' paires restantes'} </label> </form> <div> {"Tableau des scores"} <br /> {this.createTableScores()} </div> </div> ); } } class Game extends React.Component { render() { return ( <div className="game"> <div className="game-board"> <Board /> </div> <div className="game-info"> <div>{/* status */}</div> <ol>{/* TODO */}</ol> </div> </div> ); } } // ======================================== ReactDOM.render( <Game />, document.getElementById('root') ); //Volé honteusement sur un site radom function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }
odes(modes
identifier_name
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import CheckBox from './CheckBox'; import './index.css'; class Square extends React.Component { render() { return ( <button className="square" onClick={() => this.props.onClick()}> {this.props.value} </button> ); } } class SquareScores extends React.Component { render() { return ( <button className="square-scores"> {this.props.value} </button> ); } } class Board extends React.Component { constructor(props) { super(props); this.state = { modes: [{id: 1, value: "1 joueur", isChecked: true}, {id: 2, value: "2 joueur", isChecked: false}, {id: 3, value: "vs Random", isChecked: false},], mode: 1, squares: [], squares_print: [], scores: [], nbGames: 0, end: false, //-1 si pas d'information, sinon id de la case //false si mauvaise paire, true si bonne paire result: [-1, -1, false], nbPairs: 2, nbPairsFound: 0, score: [0,0], nickname1: "Hopla", nickname2: "Titeuf", oneIsNext: false, infos: " | Start pour jouer", cXr: 0, //Nombre de cases (Columns * Rows) col: 0, //Nombre de colones }; this.handleFormPairs = this.handleFormPairs.bind(this) this.handleFormNick1 = this.handleFormNick1.bind(this) this.handleFormNick2 = this.handleFormNick2.bind(this) } setGame() { this.setState((prevstate) => { let col = 1 let cXr = 0 let nickname2 = "Titeuf" let mode = this.checkModes(prevstate.modes) console.log("mode: " + mode) if(mode === 1){ nickname2 = "---" } console.log("cXr :" + cXr) // On cherche à avoir un carré peut importe le nombre de paires while (cXr <= prevstate.nbPairs*2) { //tant que colonne * ligne < nombre de cartes col+=1 cXr = Math.pow(col,2) console.log("cXr :" + cXr) } console.log("col: " + col + " | cXr: "+ cXr + " | " + this.state.nbPairs*2) // Création de l'array a affiché rempli de null console.log("nbPairs: " + prevstate.nbPairs) let squares_print = Array(parseInt(prevstate.nbPairs, 10) * 2).fill("?") squares_print = squares_print.concat(Array(cXr-this.state.nbPairs).fill("-")) console.log("squares_print :" + squares_print) // Création de l'array avec les chiffres, rempli aléatoirement let squares = [...Array(parseInt(prevstate.nbPairs, 10)).keys()] squares = shuffle(squares.concat([...Array(parseInt(prevstate.nbPairs, 10)).keys()])) console.log("squares :" + squares) return { squares: squares, squares_print: squares_print, result: [-1, -1, false], nbPairsFound: 0, score: [0,0], infos: "GO !", oneIsNext: true, cXr: cXr, col: col, end: false, mode: mode, nickname2: nickname2, }; }); } checkModes(modes){ //1 joueur if (modes[0].isChecked){ return(modes[0].id) } //2 joueur else if (modes[1].isChecked){ return(modes[1].id) } //random else if (modes[2].isChecked){ return(modes[2].id) } } handleSquareClick(i) { this.setState((prevstate) => { let result = { ...prevstate.result } let squares = { ...prevstate.squares } let squares_print = { ...prevstate.squares_print } let score = prevstate.score let nbPairsFound = prevstate.nbPairsFound let oneIsNext = prevstate.oneIsNext let infos = "GO !" let nbGames = prevstate.nbGames let p = 0 let scores = prevstate.scores let end = true if(prevstate.mode !== 1){ p = oneIsNext ? 0 : 1 } console.log("----NouveauClick----") //2 cartes d'affichés console.log(result) if (result[0] !== -1 && result[1] !== -1) { if (result[2] === false) { squares_print[result[0]] = "?" squares_print[result[1]] = "?" } result = [-1, -1, false] //0 cartes d'affichés } if (result[0] === -1 && result[1] === -1) { if (squares_print[i] === "?") { result[0] = i squares_print[i] = squares[i] } else if (typeof squares[i] === 'undefined'){ infos = "Pas une carte" } else { infos = "Déjà retourné" } //1 cartes d'affichés } else if (result[1] === -1) { if (squares_print[i] === "?") { result[1] = i squares_print[i] = squares[i] console.log("nb cartes affichés: 1") if (result[0] !== result[1] && squares[result[0]] === squares[result[1]]) { squares_print[result[0]] = squares[result[0]] squares_print[result[1]] = squares[result[1]] result[2] = true score[p] = score[p] + 3 nbPairsFound += 1 } else { result[2] = false score[p] = score[p] - 1 } if(prevstate.mode !== 1){ oneIsNext = !oneIsNext } } else if (typeof squares[i] === 'undefined'){ infos = "Pas une carte" } else { infos = "Déjà retourné" } console.log("score : " + score) console.log("oneIsNext: " + oneIsNext) } console.log("nbPairsFound: " + nbPairsFound) console.log("prevstate.nbPairs: " + prevstate.nbPairs) console.log("prevstate.end: " + prevstate.end) if (nbPairsFound === prevstate.nbPairs && prevstate.end) { infos = "Gagné !" console.log("We are in ! ") nbGames += 1 if(prevstate.mode !== 1){ scores.push(prevstate.nickname1, prevstate.score[0]) scores.push(prevstate.nickname2, prevstate.score[1]) console.log("We are in X 2 !!") } else{ scores.push(prevstate.nickname1, prevstate.score[0]) scores.push("_", "_") } } return { squares: squares, squares_print: squares_print, result: result, score: score, nbPairsFound: nbPairsFound, infos: infos, oneIsNext: oneIsNext, nbGames: nbGames, scores: scores, end: end, }; }); } handleFormPairs(event) { this.setState(() => { return{ nbPairs: event.target.value } }) console.log(this.state.nbPairs) } handleFormNick1(event) { this.setState(() => { return{ nickname1: event.target.value } }) console.log(this.state.nickname1) } handleFormNick2(event) { this.setState(() => { return{ nickname2: event.target.value } }) console.log(this.state.nickname2) } handleCheckChieldElement = (event) => { let modes = this.state.modes modes.forEach(mode => { if (mode.value === event.target.value) mode.isChecked = event.target.checked }) this.setState({modes: modes}) } renderSquare(i) { return <Square value={this.state.squares_print[i]} key={i} onClick={() => this.handleSquareClick(i)} />; } renderSquareScores(i) { return <SquareScores value={this.state.scores[i]} key={i}/>; } createTable() { let table = [] let k = 0 let col = this.state.col for (let i = 0; i < col; i++) { let children = [] for (let j = 0; j < col; j++) { children.push(this.renderSquare(k)) k++ } table.push(children) table.push(<div className="board-row" key={i}></div>) } return table } createTableScores() { let table = [] let k = 0 let col = 4 let row = this.state.nbGames console.log("row: " + row) for (let i = 0; i < row; i++) { let children = [] for (let j = 0; j < col; j++) { children.push(this.renderSquareScores(k)) k++ } table.push(children) table.push(<div className="board-row" key={i}></div>) } return table } render() { let tour = "C'est à " + ((this.state.oneIsNext) ? this.state.nickname1 : this.state.nickname2) + " de jouer" let status = this.state.infos let points = "" if (this.state.mode !== 1) { points = this.state.nickname1 + ": " + this.state.score[0] + "pts | " + this.state.nickname2 + ": " + this.state.score[1] + "pts" } else { points = this.state.nickname1 + ": " + this.state.score[0] + "pts " } return ( <div> <div className="titleTHE"> THE </div> <div className="title"> Numbers Memory Game </div> <ul> {this.state.modes.map((mode, index) => { return (<CheckBox key={index} handleCheckChieldElement={this.handleCheckChieldElement} {...mode} />) }) } </ul> <form> <label> Joueur 1: <input className="text-nicknames" value={this.state.nickname1} type="text" name="toto" onChange={this.handleFormNick1} /> </label> </form> <form> <label> Joueur 2: <input className="text-nicknames" value={this.state.nickname2} type="text" onChange={this.handleFormNick2} /> </label> </form> <div className="status">{points}</div> <button className="button" variant="primary" onClick={() => this.setGame()}>Start </button> <div>{" "+status}</div> <div className="status">{tour}</div> <div>{this.createTable()}</div> <form> <label>Paires : <input className="text-paires" value={this.state.nbPairs} type="number" onChange={this.handleFormPairs}/> {" | "} {this.state.nbPairs - this.state.nbPairsFound}{' paires restantes'} </label> </form> <div> {"Tableau des scores"} <br /> {this.createTableScores()} </div> </div> ); } } class Game extends React.Component { render() { return ( <div className="game"> <div className="game-board"> <Board /> </div> <div className="game-info"> <div>{/* status */}</div> <ol>{/* TODO */}</ol> </div> </div> ); } } // ======================================== ReactDOM.render( <Game />, document.getElementById('root') ); //Volé honteusement sur un site radom function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a re
maining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }
conditional_block
backend.rs
use crate::intrinsics::Intrinsics; use inkwell::{ memory_buffer::MemoryBuffer, module::Module, targets::{CodeModel, FileType, InitializationConfig, RelocMode, Target, TargetMachine}, OptimizationLevel, }; use libc::{ c_char, mmap, mprotect, munmap, MAP_ANON, MAP_PRIVATE, PROT_EXEC, PROT_NONE, PROT_READ, PROT_WRITE, }; use std::{ any::Any, ffi::{c_void, CString}, mem, ops::Deref, ptr::{self, NonNull}, slice, str, sync::{Arc, Once}, }; use wasmer_runtime_core::{ backend::{ sys::{Memory, Protect}, CacheGen, RunnableModule, }, cache::Error as CacheError, module::ModuleInfo, structures::TypedIndex, typed_func::{Wasm, WasmTrapInfo}, types::{LocalFuncIndex, SigIndex}, vm, vmcalls, }; #[repr(C)] struct LLVMModule { _private: [u8; 0], } #[allow(non_camel_case_types, dead_code)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[repr(C)] enum
{ NONE, READ, READ_WRITE, READ_EXECUTE, } #[allow(non_camel_case_types, dead_code)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[repr(C)] enum LLVMResult { OK, ALLOCATE_FAILURE, PROTECT_FAILURE, DEALLOC_FAILURE, OBJECT_LOAD_FAILURE, } #[repr(C)] struct Callbacks { alloc_memory: extern "C" fn(usize, MemProtect, &mut *mut u8, &mut usize) -> LLVMResult, protect_memory: extern "C" fn(*mut u8, usize, MemProtect) -> LLVMResult, dealloc_memory: extern "C" fn(*mut u8, usize) -> LLVMResult, lookup_vm_symbol: extern "C" fn(*const c_char, usize) -> *const vm::Func, visit_fde: extern "C" fn(*mut u8, usize, extern "C" fn(*mut u8)), } extern "C" { fn module_load( mem_ptr: *const u8, mem_size: usize, callbacks: Callbacks, module_out: &mut *mut LLVMModule, ) -> LLVMResult; fn module_delete(module: *mut LLVMModule); fn get_func_symbol(module: *mut LLVMModule, name: *const c_char) -> *const vm::Func; fn throw_trap(ty: i32); /// This should be the same as spliting up the fat pointer into two arguments, /// but this is cleaner, I think? #[cfg_attr(nightly, unwind(allowed))] #[allow(improper_ctypes)] fn throw_any(data: *mut dyn Any) -> !; #[allow(improper_ctypes)] fn invoke_trampoline( trampoline: unsafe extern "C" fn(*mut vm::Ctx, NonNull<vm::Func>, *const u64, *mut u64), vmctx_ptr: *mut vm::Ctx, func_ptr: NonNull<vm::Func>, params: *const u64, results: *mut u64, trap_out: *mut WasmTrapInfo, user_error: *mut Option<Box<dyn Any>>, invoke_env: Option<NonNull<c_void>>, ) -> bool; } fn get_callbacks() -> Callbacks { fn round_up_to_page_size(size: usize) -> usize { (size + (4096 - 1)) & !(4096 - 1) } extern "C" fn alloc_memory( size: usize, protect: MemProtect, ptr_out: &mut *mut u8, size_out: &mut usize, ) -> LLVMResult { let size = round_up_to_page_size(size); let ptr = unsafe { mmap( ptr::null_mut(), size, match protect { MemProtect::NONE => PROT_NONE, MemProtect::READ => PROT_READ, MemProtect::READ_WRITE => PROT_READ | PROT_WRITE, MemProtect::READ_EXECUTE => PROT_READ | PROT_EXEC, }, MAP_PRIVATE | MAP_ANON, -1, 0, ) }; if ptr as isize == -1 { return LLVMResult::ALLOCATE_FAILURE; } *ptr_out = ptr as _; *size_out = size; LLVMResult::OK } extern "C" fn protect_memory(ptr: *mut u8, size: usize, protect: MemProtect) -> LLVMResult { let res = unsafe { mprotect( ptr as _, round_up_to_page_size(size), match protect { MemProtect::NONE => PROT_NONE, MemProtect::READ => PROT_READ, MemProtect::READ_WRITE => PROT_READ | PROT_WRITE, MemProtect::READ_EXECUTE => PROT_READ | PROT_EXEC, }, ) }; if res == 0 { LLVMResult::OK } else { LLVMResult::PROTECT_FAILURE } } extern "C" fn dealloc_memory(ptr: *mut u8, size: usize) -> LLVMResult { let res = unsafe { munmap(ptr as _, round_up_to_page_size(size)) }; if res == 0 { LLVMResult::OK } else { LLVMResult::DEALLOC_FAILURE } } extern "C" fn lookup_vm_symbol(name_ptr: *const c_char, length: usize) -> *const vm::Func { #[cfg(target_os = "macos")] macro_rules! fn_name { ($s:literal) => { concat!("_", $s) }; } #[cfg(not(target_os = "macos"))] macro_rules! fn_name { ($s:literal) => { $s }; } let name_slice = unsafe { slice::from_raw_parts(name_ptr as *const u8, length) }; let name = str::from_utf8(name_slice).unwrap(); match name { fn_name!("vm.memory.grow.dynamic.local") => vmcalls::local_dynamic_memory_grow as _, fn_name!("vm.memory.size.dynamic.local") => vmcalls::local_dynamic_memory_size as _, fn_name!("vm.memory.grow.static.local") => vmcalls::local_static_memory_grow as _, fn_name!("vm.memory.size.static.local") => vmcalls::local_static_memory_size as _, fn_name!("vm.exception.trap") => throw_trap as _, _ => ptr::null(), } } extern "C" fn visit_fde(fde: *mut u8, size: usize, visitor: extern "C" fn(*mut u8)) { unsafe { crate::platform::visit_fde(fde, size, visitor); } } Callbacks { alloc_memory, protect_memory, dealloc_memory, lookup_vm_symbol, visit_fde, } } pub enum Buffer { LlvmMemory(MemoryBuffer), Memory(Memory), } impl Deref for Buffer { type Target = [u8]; fn deref(&self) -> &[u8] { match self { Buffer::LlvmMemory(mem_buffer) => mem_buffer.as_slice(), Buffer::Memory(memory) => unsafe { memory.as_slice() }, } } } unsafe impl Send for LLVMBackend {} unsafe impl Sync for LLVMBackend {} pub struct LLVMBackend { module: *mut LLVMModule, #[allow(dead_code)] buffer: Arc<Buffer>, } impl LLVMBackend { pub fn new(module: Module, _intrinsics: Intrinsics) -> (Self, LLVMCache) { Target::initialize_x86(&InitializationConfig { asm_parser: true, asm_printer: true, base: true, disassembler: true, info: true, machine_code: true, }); let triple = TargetMachine::get_default_triple().to_string(); let target = Target::from_triple(&triple).unwrap(); let target_machine = target .create_target_machine( &triple, &TargetMachine::get_host_cpu_name().to_string(), &TargetMachine::get_host_cpu_features().to_string(), OptimizationLevel::Aggressive, RelocMode::PIC, CodeModel::Default, ) .unwrap(); let memory_buffer = target_machine .write_to_memory_buffer(&module, FileType::Object) .unwrap(); let mem_buf_slice = memory_buffer.as_slice(); let callbacks = get_callbacks(); let mut module: *mut LLVMModule = ptr::null_mut(); let res = unsafe { module_load( mem_buf_slice.as_ptr(), mem_buf_slice.len(), callbacks, &mut module, ) }; static SIGNAL_HANDLER_INSTALLED: Once = Once::new(); SIGNAL_HANDLER_INSTALLED.call_once(|| unsafe { crate::platform::install_signal_handler(); }); if res != LLVMResult::OK { panic!("failed to load object") } let buffer = Arc::new(Buffer::LlvmMemory(memory_buffer)); ( Self { module, buffer: Arc::clone(&buffer), }, LLVMCache { buffer }, ) } pub unsafe fn from_buffer(memory: Memory) -> Result<(Self, LLVMCache), String> { let callbacks = get_callbacks(); let mut module: *mut LLVMModule = ptr::null_mut(); let slice = memory.as_slice(); let res = module_load(slice.as_ptr(), slice.len(), callbacks, &mut module); if res != LLVMResult::OK { return Err("failed to load object".to_string()); } static SIGNAL_HANDLER_INSTALLED: Once = Once::new(); SIGNAL_HANDLER_INSTALLED.call_once(|| { crate::platform::install_signal_handler(); }); let buffer = Arc::new(Buffer::Memory(memory)); Ok(( Self { module, buffer: Arc::clone(&buffer), }, LLVMCache { buffer }, )) } } impl Drop for LLVMBackend { fn drop(&mut self) { unsafe { module_delete(self.module) } } } impl RunnableModule for LLVMBackend { fn get_func( &self, info: &ModuleInfo, local_func_index: LocalFuncIndex, ) -> Option<NonNull<vm::Func>> { let index = info.imported_functions.len() + local_func_index.index(); let name = if cfg!(target_os = "macos") { format!("_fn{}", index) } else { format!("fn{}", index) }; let c_str = CString::new(name).ok()?; let ptr = unsafe { get_func_symbol(self.module, c_str.as_ptr()) }; NonNull::new(ptr as _) } fn get_trampoline(&self, _: &ModuleInfo, sig_index: SigIndex) -> Option<Wasm> { let trampoline: unsafe extern "C" fn( *mut vm::Ctx, NonNull<vm::Func>, *const u64, *mut u64, ) = unsafe { let name = if cfg!(target_os = "macos") { format!("_trmp{}", sig_index.index()) } else { format!("trmp{}", sig_index.index()) }; let c_str = CString::new(name).unwrap(); let symbol = get_func_symbol(self.module, c_str.as_ptr()); assert!(!symbol.is_null()); mem::transmute(symbol) }; Some(unsafe { Wasm::from_raw_parts(trampoline, invoke_trampoline, None) }) } unsafe fn do_early_trap(&self, data: Box<dyn Any>) -> ! { throw_any(Box::leak(data)) } } unsafe impl Send for LLVMCache {} unsafe impl Sync for LLVMCache {} pub struct LLVMCache { buffer: Arc<Buffer>, } impl CacheGen for LLVMCache { fn generate_cache(&self) -> Result<(Box<[u8]>, Memory), CacheError> { let mut memory = Memory::with_size_protect(self.buffer.len(), Protect::ReadWrite) .map_err(CacheError::SerializeError)?; let buffer = self.buffer.deref(); unsafe { memory.as_slice_mut()[..buffer.len()].copy_from_slice(buffer); } Ok(([].as_ref().into(), memory)) } } #[cfg(feature = "disasm")] unsafe fn disass_ptr(ptr: *const u8, size: usize, inst_count: usize) { use capstone::arch::BuildsCapstone; let mut cs = capstone::Capstone::new() // Call builder-pattern .x86() // X86 architecture .mode(capstone::arch::x86::ArchMode::Mode64) // 64-bit mode .detail(true) // Generate extra instruction details .build() .expect("Failed to create Capstone object"); // Get disassembled instructions let insns = cs .disasm_count( std::slice::from_raw_parts(ptr, size), ptr as u64, inst_count, ) .expect("Failed to disassemble"); println!("count = {}", insns.len()); for insn in insns.iter() { println!( "0x{:x}: {:6} {}", insn.address(), insn.mnemonic().unwrap_or(""), insn.op_str().unwrap_or("") ); } }
MemProtect
identifier_name
backend.rs
use crate::intrinsics::Intrinsics; use inkwell::{ memory_buffer::MemoryBuffer, module::Module, targets::{CodeModel, FileType, InitializationConfig, RelocMode, Target, TargetMachine}, OptimizationLevel, }; use libc::{ c_char, mmap, mprotect, munmap, MAP_ANON, MAP_PRIVATE, PROT_EXEC, PROT_NONE, PROT_READ, PROT_WRITE, }; use std::{ any::Any, ffi::{c_void, CString}, mem, ops::Deref, ptr::{self, NonNull}, slice, str, sync::{Arc, Once}, }; use wasmer_runtime_core::{ backend::{ sys::{Memory, Protect}, CacheGen, RunnableModule, }, cache::Error as CacheError, module::ModuleInfo, structures::TypedIndex, typed_func::{Wasm, WasmTrapInfo}, types::{LocalFuncIndex, SigIndex}, vm, vmcalls, }; #[repr(C)] struct LLVMModule { _private: [u8; 0], } #[allow(non_camel_case_types, dead_code)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[repr(C)] enum MemProtect { NONE, READ, READ_WRITE, READ_EXECUTE, } #[allow(non_camel_case_types, dead_code)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[repr(C)] enum LLVMResult { OK, ALLOCATE_FAILURE, PROTECT_FAILURE, DEALLOC_FAILURE, OBJECT_LOAD_FAILURE, } #[repr(C)] struct Callbacks { alloc_memory: extern "C" fn(usize, MemProtect, &mut *mut u8, &mut usize) -> LLVMResult, protect_memory: extern "C" fn(*mut u8, usize, MemProtect) -> LLVMResult, dealloc_memory: extern "C" fn(*mut u8, usize) -> LLVMResult, lookup_vm_symbol: extern "C" fn(*const c_char, usize) -> *const vm::Func, visit_fde: extern "C" fn(*mut u8, usize, extern "C" fn(*mut u8)), } extern "C" { fn module_load( mem_ptr: *const u8, mem_size: usize, callbacks: Callbacks, module_out: &mut *mut LLVMModule, ) -> LLVMResult; fn module_delete(module: *mut LLVMModule); fn get_func_symbol(module: *mut LLVMModule, name: *const c_char) -> *const vm::Func; fn throw_trap(ty: i32); /// This should be the same as spliting up the fat pointer into two arguments, /// but this is cleaner, I think? #[cfg_attr(nightly, unwind(allowed))] #[allow(improper_ctypes)] fn throw_any(data: *mut dyn Any) -> !; #[allow(improper_ctypes)] fn invoke_trampoline( trampoline: unsafe extern "C" fn(*mut vm::Ctx, NonNull<vm::Func>, *const u64, *mut u64), vmctx_ptr: *mut vm::Ctx, func_ptr: NonNull<vm::Func>, params: *const u64, results: *mut u64, trap_out: *mut WasmTrapInfo, user_error: *mut Option<Box<dyn Any>>, invoke_env: Option<NonNull<c_void>>, ) -> bool; } fn get_callbacks() -> Callbacks { fn round_up_to_page_size(size: usize) -> usize { (size + (4096 - 1)) & !(4096 - 1) } extern "C" fn alloc_memory( size: usize, protect: MemProtect, ptr_out: &mut *mut u8, size_out: &mut usize, ) -> LLVMResult { let size = round_up_to_page_size(size); let ptr = unsafe { mmap( ptr::null_mut(), size, match protect { MemProtect::NONE => PROT_NONE, MemProtect::READ => PROT_READ, MemProtect::READ_WRITE => PROT_READ | PROT_WRITE, MemProtect::READ_EXECUTE => PROT_READ | PROT_EXEC, }, MAP_PRIVATE | MAP_ANON, -1, 0, ) }; if ptr as isize == -1 { return LLVMResult::ALLOCATE_FAILURE; } *ptr_out = ptr as _; *size_out = size; LLVMResult::OK } extern "C" fn protect_memory(ptr: *mut u8, size: usize, protect: MemProtect) -> LLVMResult { let res = unsafe { mprotect( ptr as _, round_up_to_page_size(size), match protect { MemProtect::NONE => PROT_NONE, MemProtect::READ => PROT_READ, MemProtect::READ_WRITE => PROT_READ | PROT_WRITE, MemProtect::READ_EXECUTE => PROT_READ | PROT_EXEC, }, ) }; if res == 0 { LLVMResult::OK } else { LLVMResult::PROTECT_FAILURE } } extern "C" fn dealloc_memory(ptr: *mut u8, size: usize) -> LLVMResult { let res = unsafe { munmap(ptr as _, round_up_to_page_size(size)) }; if res == 0 { LLVMResult::OK } else { LLVMResult::DEALLOC_FAILURE } } extern "C" fn lookup_vm_symbol(name_ptr: *const c_char, length: usize) -> *const vm::Func { #[cfg(target_os = "macos")] macro_rules! fn_name { ($s:literal) => { concat!("_", $s) }; } #[cfg(not(target_os = "macos"))] macro_rules! fn_name { ($s:literal) => { $s }; }
let name_slice = unsafe { slice::from_raw_parts(name_ptr as *const u8, length) }; let name = str::from_utf8(name_slice).unwrap(); match name { fn_name!("vm.memory.grow.dynamic.local") => vmcalls::local_dynamic_memory_grow as _, fn_name!("vm.memory.size.dynamic.local") => vmcalls::local_dynamic_memory_size as _, fn_name!("vm.memory.grow.static.local") => vmcalls::local_static_memory_grow as _, fn_name!("vm.memory.size.static.local") => vmcalls::local_static_memory_size as _, fn_name!("vm.exception.trap") => throw_trap as _, _ => ptr::null(), } } extern "C" fn visit_fde(fde: *mut u8, size: usize, visitor: extern "C" fn(*mut u8)) { unsafe { crate::platform::visit_fde(fde, size, visitor); } } Callbacks { alloc_memory, protect_memory, dealloc_memory, lookup_vm_symbol, visit_fde, } } pub enum Buffer { LlvmMemory(MemoryBuffer), Memory(Memory), } impl Deref for Buffer { type Target = [u8]; fn deref(&self) -> &[u8] { match self { Buffer::LlvmMemory(mem_buffer) => mem_buffer.as_slice(), Buffer::Memory(memory) => unsafe { memory.as_slice() }, } } } unsafe impl Send for LLVMBackend {} unsafe impl Sync for LLVMBackend {} pub struct LLVMBackend { module: *mut LLVMModule, #[allow(dead_code)] buffer: Arc<Buffer>, } impl LLVMBackend { pub fn new(module: Module, _intrinsics: Intrinsics) -> (Self, LLVMCache) { Target::initialize_x86(&InitializationConfig { asm_parser: true, asm_printer: true, base: true, disassembler: true, info: true, machine_code: true, }); let triple = TargetMachine::get_default_triple().to_string(); let target = Target::from_triple(&triple).unwrap(); let target_machine = target .create_target_machine( &triple, &TargetMachine::get_host_cpu_name().to_string(), &TargetMachine::get_host_cpu_features().to_string(), OptimizationLevel::Aggressive, RelocMode::PIC, CodeModel::Default, ) .unwrap(); let memory_buffer = target_machine .write_to_memory_buffer(&module, FileType::Object) .unwrap(); let mem_buf_slice = memory_buffer.as_slice(); let callbacks = get_callbacks(); let mut module: *mut LLVMModule = ptr::null_mut(); let res = unsafe { module_load( mem_buf_slice.as_ptr(), mem_buf_slice.len(), callbacks, &mut module, ) }; static SIGNAL_HANDLER_INSTALLED: Once = Once::new(); SIGNAL_HANDLER_INSTALLED.call_once(|| unsafe { crate::platform::install_signal_handler(); }); if res != LLVMResult::OK { panic!("failed to load object") } let buffer = Arc::new(Buffer::LlvmMemory(memory_buffer)); ( Self { module, buffer: Arc::clone(&buffer), }, LLVMCache { buffer }, ) } pub unsafe fn from_buffer(memory: Memory) -> Result<(Self, LLVMCache), String> { let callbacks = get_callbacks(); let mut module: *mut LLVMModule = ptr::null_mut(); let slice = memory.as_slice(); let res = module_load(slice.as_ptr(), slice.len(), callbacks, &mut module); if res != LLVMResult::OK { return Err("failed to load object".to_string()); } static SIGNAL_HANDLER_INSTALLED: Once = Once::new(); SIGNAL_HANDLER_INSTALLED.call_once(|| { crate::platform::install_signal_handler(); }); let buffer = Arc::new(Buffer::Memory(memory)); Ok(( Self { module, buffer: Arc::clone(&buffer), }, LLVMCache { buffer }, )) } } impl Drop for LLVMBackend { fn drop(&mut self) { unsafe { module_delete(self.module) } } } impl RunnableModule for LLVMBackend { fn get_func( &self, info: &ModuleInfo, local_func_index: LocalFuncIndex, ) -> Option<NonNull<vm::Func>> { let index = info.imported_functions.len() + local_func_index.index(); let name = if cfg!(target_os = "macos") { format!("_fn{}", index) } else { format!("fn{}", index) }; let c_str = CString::new(name).ok()?; let ptr = unsafe { get_func_symbol(self.module, c_str.as_ptr()) }; NonNull::new(ptr as _) } fn get_trampoline(&self, _: &ModuleInfo, sig_index: SigIndex) -> Option<Wasm> { let trampoline: unsafe extern "C" fn( *mut vm::Ctx, NonNull<vm::Func>, *const u64, *mut u64, ) = unsafe { let name = if cfg!(target_os = "macos") { format!("_trmp{}", sig_index.index()) } else { format!("trmp{}", sig_index.index()) }; let c_str = CString::new(name).unwrap(); let symbol = get_func_symbol(self.module, c_str.as_ptr()); assert!(!symbol.is_null()); mem::transmute(symbol) }; Some(unsafe { Wasm::from_raw_parts(trampoline, invoke_trampoline, None) }) } unsafe fn do_early_trap(&self, data: Box<dyn Any>) -> ! { throw_any(Box::leak(data)) } } unsafe impl Send for LLVMCache {} unsafe impl Sync for LLVMCache {} pub struct LLVMCache { buffer: Arc<Buffer>, } impl CacheGen for LLVMCache { fn generate_cache(&self) -> Result<(Box<[u8]>, Memory), CacheError> { let mut memory = Memory::with_size_protect(self.buffer.len(), Protect::ReadWrite) .map_err(CacheError::SerializeError)?; let buffer = self.buffer.deref(); unsafe { memory.as_slice_mut()[..buffer.len()].copy_from_slice(buffer); } Ok(([].as_ref().into(), memory)) } } #[cfg(feature = "disasm")] unsafe fn disass_ptr(ptr: *const u8, size: usize, inst_count: usize) { use capstone::arch::BuildsCapstone; let mut cs = capstone::Capstone::new() // Call builder-pattern .x86() // X86 architecture .mode(capstone::arch::x86::ArchMode::Mode64) // 64-bit mode .detail(true) // Generate extra instruction details .build() .expect("Failed to create Capstone object"); // Get disassembled instructions let insns = cs .disasm_count( std::slice::from_raw_parts(ptr, size), ptr as u64, inst_count, ) .expect("Failed to disassemble"); println!("count = {}", insns.len()); for insn in insns.iter() { println!( "0x{:x}: {:6} {}", insn.address(), insn.mnemonic().unwrap_or(""), insn.op_str().unwrap_or("") ); } }
random_line_split
algorithm.py
import csv import bisect from explore.models import MovieObj import requests from time import sleep import pprint ratings = {"Passed": 0, "Approved": 0, "Unrated": 0, "Not Rated": 0, "": 0, "TV-Y": 0, "TV-G": 1, "G": 1, "TV-Y7": 2, "GP": 2, "TV-PG": 2, "PG": 2, "TV-14": 3, "PG-13": 3, "TV-MA": 4, "M": 4, "R": 4, "NC-17": 4, "X": 5} common = ["the", "and", "of"] # List of common words to be filtered from titles flag = True class
: def __init__(self): self.title = "" self.titleWords = [] self.year = 0 self.actor1 = "" self.actor2 = "" self.actor3 = "" self.director = "" self.keywords = [] self.genres = [] self.relevance = 0 self.country = "" self.language = "" self.criteria = [] self.rating = 0 self.score = 0 self.ID = "" self.gross = 0 self.fblikes = 0 self.budget = 0 self.numReviews = 0 def __lt__(self, other): return self.relevance > other.relevance # Temp function. Use to make generate input strings for now. Enter names into array. def stringBuilder(name): movies = reader("movieDBbackup.txt") inputs = [name] IDs = [] for j in inputs: for i in movies: if i.title.lower() == j.lower(): IDs.append(i.ID) print(IDs) return " ".join(IDs) # Function Name: reader() # Function Purpose: This block of code reads the entire TSV file and stores each movie in an object # Parameters: # fileName: The name of the TSV file def reader(fileName): global flag movies = [] count = 0 with open(fileName, 'r', encoding="utf8") as csvfile: TSVreader = csv.reader(csvfile, delimiter='\t', quotechar='"', skipinitialspace=True) for row in TSVreader: #print(row[11]) temp = Movie() if count > 0: # Makes sure the headers aren't stored in an object #temp = Movie() # Creates a temp object temp.title = row[11][:-1].lower() # Converts all titles to lower and strips off end char # Puts any non-common title words into a list temp.titleWords = [] for i in row[11][:-1].lower().split(): if i not in common: temp.titleWords.append(i) # Error checks for rows without years if row[23] != '': temp.year = int(row[23]) temp.actor1 = row[10] temp.actor2 = row[6] temp.actor3 = row[14] temp.director = row[1] temp.keywords = row[16].split('|') temp.genres = row[9].split('|') temp.country = row[20] temp.language = row[19] temp.rating = ratings[row[21]] temp.score = float(row[25]) temp.ID = row[28].lower() temp.numCritic = row[2] temp.gross = row[8] temp.fblikes = row[13] temp.budget = row[22] temp.numReviews = row[18] movies.append(temp) #if ((flag) and (count > 0)): #makeMovieObj(temp) #print(temp) # uncomment if you want to repopulate the database from scratch for some reason. Or, load the fixture like a reasonable human. count += 1 #print(count) flag = False return(movies) # Function Name: Related # Function Purpose: Takes an input string of IMDB ID's and returns the top 15 most related films # Parameters: # num_results: The number of results to be returned # ID_string: The string containing IMDB IDs def related(num_results, ID_string, actorWeight, genreWeight, directorWeight, yearWeight, scoreWeight): listIDs = ID_string.split(" ") # Splits inFilm string into list of IDs movies = reader("movieDBbackup.txt") # Populates inputs = [] for i in movies: for j in listIDs: if i.ID == j: inputs.append(i) print(i.titleWords) print(i.genres) print(i.keywords) print() top = [] for i in movies: for inFilm in inputs: # Actor Check if i.actor1 == inFilm.actor1 or i.actor1 == inFilm.actor2 or i.actor1 == inFilm.actor3: i.relevance += (35 * actorWeight) i.criteria.append("Actor: "+i.actor1) if i.actor2 == inFilm.actor1 or i.actor2 == inFilm.actor2 or i.actor2 == inFilm.actor3: i.relevance += (35 * actorWeight) i.criteria.append("Actor: "+i.actor2) if i.actor3 == inFilm.actor1 or i.actor3 == inFilm.actor2 or i.actor3 == inFilm.actor3: i.relevance += (35 * actorWeight) i.criteria.append("Actor: "+i.actor3) # Director Check if i.director == inFilm.director: i.relevance += (35 * directorWeight) i.criteria.append("Director: "+i.director) # Country Check if i.country == inFilm.country: i.relevance += 10 i.criteria.append("country") # Language Check if i.language != inFilm.language: i.relevance -= 50 # Rating Check if i.rating != 0: if i.rating == inFilm.rating: i.relevance += 20 if i.rating == (inFilm.rating + 1) or i.rating == (inFilm.rating - 1): i.relevance += 10 if i.rating == (inFilm.rating + 3) or i.rating == (inFilm.rating - 3): i.relevance -= 200 if i.rating == (inFilm.rating + 4) or i.rating == (inFilm.rating - 4): i.relevance -= 400 # Keyword Check for j in i.keywords: for k in inFilm.keywords: if j == k: i.relevance += 40 i.criteria.append("Keyword: "+j) # Genre Check for j in i.genres: for k in inFilm.genres: if j == k: i.relevance += (30 * genreWeight) i.criteria.append("genre: "+j) # Title Check count = 0 for j in i.titleWords: if not j.isdigit(): for k in inFilm.titleWords: if j == k: count += 1 if count > (len(inFilm.titleWords)/3): i.criteria.append(str(count)+" Title words") i.relevance += 20 # Year Check if (inFilm.year - 5) <= i.year <= (inFilm.year + 5): i.relevance += (10 * yearWeight) i.criteria.append("Year: 10") elif (inFilm.year - 5) <= i.year <= (inFilm.year + 5): i.relevance += (5 * yearWeight) i.criteria.append("Year: 5") # IMDB Score i.relevance += ((3*i.score) * int(scoreWeight)) bisect.insort_right(top, i) topN = [] for i in range(0, num_results): topN.append([top[i].ID, str(top[i].relevance), top[i].criteria, ", ".join(top[i].genres)]) return topN def getTitles(): count = 0 titles = [] with open("movieDBbackup.txt", 'r', encoding="utf8") as csvfile: TSVreader = csv.reader(csvfile, delimiter='\t', quotechar='"', skipinitialspace=True) for row in TSVreader: temp = Movie() if count > 0: # Makes sure the headers aren't stored in an object titles.append([row[11][:-1], row[23]]) count += 1 return titles # makes movie object from models.py for saving into sqlite database out of Movie() class. def makeMovieObj(temp): movie = MovieObj() sleep(0.0001) #print(temp.ID) response = requests.post(str("http://www.omdbapi.com/?i=" + str(temp.ID))) #OMDB API call while response.status_code != 200: sleep(0.0001) print('....................................', end='') response = requests.post(str("http://www.omdbapi.com/?i=" + str(temp.ID))) #OMDB API call try: movie.poster = response.json()['Poster'] except Exception as e: print("no poster") try: movie.plot = response.json()["Plot"] except Exception as e: print("no plot") try: movie.runtime = response.json()["Runtime"].split(' ')[0] except Exception as e: print("no runtime") try: movie.awards = response.json()["Awards"] except Exception as e: print("no awards") try: movie.IMDBScore = response.json()["imdbRating"] except Exception as e: print("no imdb") try: movie.tomatoes = response.json()["Ratings"][1]["Value"].replace("%","") except Exception as e: print("no tomato") try: movie.metascore = response.json()["Metascore"].replace("%","") except Exception as e: print("no Metascore") try: movie.production = response.json()["Production"] except Exception as e: print("no Production") try: movie.boxOffice = response.json()["BoxOffice"] except Exception as e: print("no BoxOffice") #movie.poster = response.json()['Poster'] movie.title = temp.title # movie.titleWords = temp.titleWords movie.year = temp.year movie.actor1 = temp.actor1 movie.actor2 = temp.actor2 movie.actor3 = temp.actor3 movie.director = temp.director movie.keywords = temp.keywords movie.genres = temp.genres movie.country = temp.country movie.language = temp.language movie.rating = temp.rating movie.score = temp.score movie.movieID = temp.ID movie.numCritic = temp.numCritic movie.gross = temp.gross movie.fblikes = temp.fblikes movie.budget = temp.budget movie.numReviews = temp.numReviews print(movie) movie.save()
Movie
identifier_name
algorithm.py
import csv import bisect from explore.models import MovieObj import requests from time import sleep import pprint ratings = {"Passed": 0, "Approved": 0, "Unrated": 0, "Not Rated": 0, "": 0, "TV-Y": 0, "TV-G": 1, "G": 1, "TV-Y7": 2, "GP": 2, "TV-PG": 2, "PG": 2, "TV-14": 3, "PG-13": 3, "TV-MA": 4, "M": 4, "R": 4, "NC-17": 4, "X": 5} common = ["the", "and", "of"] # List of common words to be filtered from titles flag = True class Movie: def __init__(self): self.title = "" self.titleWords = [] self.year = 0 self.actor1 = "" self.actor2 = "" self.actor3 = "" self.director = "" self.keywords = [] self.genres = [] self.relevance = 0 self.country = "" self.language = "" self.criteria = [] self.rating = 0 self.score = 0 self.ID = "" self.gross = 0 self.fblikes = 0 self.budget = 0 self.numReviews = 0 def __lt__(self, other): return self.relevance > other.relevance # Temp function. Use to make generate input strings for now. Enter names into array. def stringBuilder(name): movies = reader("movieDBbackup.txt") inputs = [name] IDs = [] for j in inputs: for i in movies: if i.title.lower() == j.lower(): IDs.append(i.ID) print(IDs) return " ".join(IDs) # Function Name: reader() # Function Purpose: This block of code reads the entire TSV file and stores each movie in an object # Parameters: # fileName: The name of the TSV file def reader(fileName): global flag movies = [] count = 0 with open(fileName, 'r', encoding="utf8") as csvfile: TSVreader = csv.reader(csvfile, delimiter='\t', quotechar='"', skipinitialspace=True) for row in TSVreader: #print(row[11]) temp = Movie() if count > 0: # Makes sure the headers aren't stored in an object #temp = Movie() # Creates a temp object temp.title = row[11][:-1].lower() # Converts all titles to lower and strips off end char # Puts any non-common title words into a list temp.titleWords = [] for i in row[11][:-1].lower().split(): if i not in common: temp.titleWords.append(i) # Error checks for rows without years if row[23] != '': temp.year = int(row[23]) temp.actor1 = row[10] temp.actor2 = row[6] temp.actor3 = row[14] temp.director = row[1] temp.keywords = row[16].split('|') temp.genres = row[9].split('|') temp.country = row[20] temp.language = row[19] temp.rating = ratings[row[21]] temp.score = float(row[25]) temp.ID = row[28].lower() temp.numCritic = row[2] temp.gross = row[8] temp.fblikes = row[13] temp.budget = row[22] temp.numReviews = row[18] movies.append(temp) #if ((flag) and (count > 0)): #makeMovieObj(temp) #print(temp) # uncomment if you want to repopulate the database from scratch for some reason. Or, load the fixture like a reasonable human. count += 1 #print(count) flag = False return(movies) # Function Name: Related # Function Purpose: Takes an input string of IMDB ID's and returns the top 15 most related films # Parameters: # num_results: The number of results to be returned # ID_string: The string containing IMDB IDs def related(num_results, ID_string, actorWeight, genreWeight, directorWeight, yearWeight, scoreWeight):
def getTitles(): count = 0 titles = [] with open("movieDBbackup.txt", 'r', encoding="utf8") as csvfile: TSVreader = csv.reader(csvfile, delimiter='\t', quotechar='"', skipinitialspace=True) for row in TSVreader: temp = Movie() if count > 0: # Makes sure the headers aren't stored in an object titles.append([row[11][:-1], row[23]]) count += 1 return titles # makes movie object from models.py for saving into sqlite database out of Movie() class. def makeMovieObj(temp): movie = MovieObj() sleep(0.0001) #print(temp.ID) response = requests.post(str("http://www.omdbapi.com/?i=" + str(temp.ID))) #OMDB API call while response.status_code != 200: sleep(0.0001) print('....................................', end='') response = requests.post(str("http://www.omdbapi.com/?i=" + str(temp.ID))) #OMDB API call try: movie.poster = response.json()['Poster'] except Exception as e: print("no poster") try: movie.plot = response.json()["Plot"] except Exception as e: print("no plot") try: movie.runtime = response.json()["Runtime"].split(' ')[0] except Exception as e: print("no runtime") try: movie.awards = response.json()["Awards"] except Exception as e: print("no awards") try: movie.IMDBScore = response.json()["imdbRating"] except Exception as e: print("no imdb") try: movie.tomatoes = response.json()["Ratings"][1]["Value"].replace("%","") except Exception as e: print("no tomato") try: movie.metascore = response.json()["Metascore"].replace("%","") except Exception as e: print("no Metascore") try: movie.production = response.json()["Production"] except Exception as e: print("no Production") try: movie.boxOffice = response.json()["BoxOffice"] except Exception as e: print("no BoxOffice") #movie.poster = response.json()['Poster'] movie.title = temp.title # movie.titleWords = temp.titleWords movie.year = temp.year movie.actor1 = temp.actor1 movie.actor2 = temp.actor2 movie.actor3 = temp.actor3 movie.director = temp.director movie.keywords = temp.keywords movie.genres = temp.genres movie.country = temp.country movie.language = temp.language movie.rating = temp.rating movie.score = temp.score movie.movieID = temp.ID movie.numCritic = temp.numCritic movie.gross = temp.gross movie.fblikes = temp.fblikes movie.budget = temp.budget movie.numReviews = temp.numReviews print(movie) movie.save()
listIDs = ID_string.split(" ") # Splits inFilm string into list of IDs movies = reader("movieDBbackup.txt") # Populates inputs = [] for i in movies: for j in listIDs: if i.ID == j: inputs.append(i) print(i.titleWords) print(i.genres) print(i.keywords) print() top = [] for i in movies: for inFilm in inputs: # Actor Check if i.actor1 == inFilm.actor1 or i.actor1 == inFilm.actor2 or i.actor1 == inFilm.actor3: i.relevance += (35 * actorWeight) i.criteria.append("Actor: "+i.actor1) if i.actor2 == inFilm.actor1 or i.actor2 == inFilm.actor2 or i.actor2 == inFilm.actor3: i.relevance += (35 * actorWeight) i.criteria.append("Actor: "+i.actor2) if i.actor3 == inFilm.actor1 or i.actor3 == inFilm.actor2 or i.actor3 == inFilm.actor3: i.relevance += (35 * actorWeight) i.criteria.append("Actor: "+i.actor3) # Director Check if i.director == inFilm.director: i.relevance += (35 * directorWeight) i.criteria.append("Director: "+i.director) # Country Check if i.country == inFilm.country: i.relevance += 10 i.criteria.append("country") # Language Check if i.language != inFilm.language: i.relevance -= 50 # Rating Check if i.rating != 0: if i.rating == inFilm.rating: i.relevance += 20 if i.rating == (inFilm.rating + 1) or i.rating == (inFilm.rating - 1): i.relevance += 10 if i.rating == (inFilm.rating + 3) or i.rating == (inFilm.rating - 3): i.relevance -= 200 if i.rating == (inFilm.rating + 4) or i.rating == (inFilm.rating - 4): i.relevance -= 400 # Keyword Check for j in i.keywords: for k in inFilm.keywords: if j == k: i.relevance += 40 i.criteria.append("Keyword: "+j) # Genre Check for j in i.genres: for k in inFilm.genres: if j == k: i.relevance += (30 * genreWeight) i.criteria.append("genre: "+j) # Title Check count = 0 for j in i.titleWords: if not j.isdigit(): for k in inFilm.titleWords: if j == k: count += 1 if count > (len(inFilm.titleWords)/3): i.criteria.append(str(count)+" Title words") i.relevance += 20 # Year Check if (inFilm.year - 5) <= i.year <= (inFilm.year + 5): i.relevance += (10 * yearWeight) i.criteria.append("Year: 10") elif (inFilm.year - 5) <= i.year <= (inFilm.year + 5): i.relevance += (5 * yearWeight) i.criteria.append("Year: 5") # IMDB Score i.relevance += ((3*i.score) * int(scoreWeight)) bisect.insort_right(top, i) topN = [] for i in range(0, num_results): topN.append([top[i].ID, str(top[i].relevance), top[i].criteria, ", ".join(top[i].genres)]) return topN
identifier_body
algorithm.py
import csv import bisect from explore.models import MovieObj import requests from time import sleep import pprint ratings = {"Passed": 0, "Approved": 0, "Unrated": 0, "Not Rated": 0, "": 0, "TV-Y": 0, "TV-G": 1, "G": 1, "TV-Y7": 2, "GP": 2, "TV-PG": 2, "PG": 2, "TV-14": 3, "PG-13": 3, "TV-MA": 4, "M": 4, "R": 4, "NC-17": 4, "X": 5} common = ["the", "and", "of"] # List of common words to be filtered from titles flag = True class Movie: def __init__(self): self.title = "" self.titleWords = [] self.year = 0 self.actor1 = "" self.actor2 = "" self.actor3 = "" self.director = "" self.keywords = [] self.genres = [] self.relevance = 0 self.country = "" self.language = "" self.criteria = [] self.rating = 0 self.score = 0 self.ID = "" self.gross = 0 self.fblikes = 0 self.budget = 0 self.numReviews = 0 def __lt__(self, other): return self.relevance > other.relevance # Temp function. Use to make generate input strings for now. Enter names into array. def stringBuilder(name): movies = reader("movieDBbackup.txt") inputs = [name] IDs = [] for j in inputs: for i in movies: if i.title.lower() == j.lower(): IDs.append(i.ID) print(IDs) return " ".join(IDs) # Function Name: reader() # Function Purpose: This block of code reads the entire TSV file and stores each movie in an object # Parameters: # fileName: The name of the TSV file def reader(fileName): global flag movies = [] count = 0 with open(fileName, 'r', encoding="utf8") as csvfile: TSVreader = csv.reader(csvfile, delimiter='\t', quotechar='"', skipinitialspace=True) for row in TSVreader: #print(row[11]) temp = Movie() if count > 0: # Makes sure the headers aren't stored in an object #temp = Movie() # Creates a temp object temp.title = row[11][:-1].lower() # Converts all titles to lower and strips off end char # Puts any non-common title words into a list temp.titleWords = [] for i in row[11][:-1].lower().split(): if i not in common: temp.titleWords.append(i) # Error checks for rows without years if row[23] != '': temp.year = int(row[23]) temp.actor1 = row[10] temp.actor2 = row[6] temp.actor3 = row[14] temp.director = row[1] temp.keywords = row[16].split('|') temp.genres = row[9].split('|') temp.country = row[20] temp.language = row[19] temp.rating = ratings[row[21]] temp.score = float(row[25]) temp.ID = row[28].lower() temp.numCritic = row[2] temp.gross = row[8] temp.fblikes = row[13] temp.budget = row[22] temp.numReviews = row[18] movies.append(temp) #if ((flag) and (count > 0)): #makeMovieObj(temp) #print(temp) # uncomment if you want to repopulate the database from scratch for some reason. Or, load the fixture like a reasonable human. count += 1 #print(count) flag = False return(movies) # Function Name: Related # Function Purpose: Takes an input string of IMDB ID's and returns the top 15 most related films # Parameters: # num_results: The number of results to be returned # ID_string: The string containing IMDB IDs def related(num_results, ID_string, actorWeight, genreWeight, directorWeight, yearWeight, scoreWeight): listIDs = ID_string.split(" ") # Splits inFilm string into list of IDs movies = reader("movieDBbackup.txt") # Populates inputs = [] for i in movies: for j in listIDs: if i.ID == j: inputs.append(i) print(i.titleWords) print(i.genres) print(i.keywords) print() top = [] for i in movies: for inFilm in inputs: # Actor Check if i.actor1 == inFilm.actor1 or i.actor1 == inFilm.actor2 or i.actor1 == inFilm.actor3: i.relevance += (35 * actorWeight) i.criteria.append("Actor: "+i.actor1) if i.actor2 == inFilm.actor1 or i.actor2 == inFilm.actor2 or i.actor2 == inFilm.actor3: i.relevance += (35 * actorWeight) i.criteria.append("Actor: "+i.actor2) if i.actor3 == inFilm.actor1 or i.actor3 == inFilm.actor2 or i.actor3 == inFilm.actor3: i.relevance += (35 * actorWeight) i.criteria.append("Actor: "+i.actor3) # Director Check if i.director == inFilm.director: i.relevance += (35 * directorWeight) i.criteria.append("Director: "+i.director) # Country Check if i.country == inFilm.country: i.relevance += 10 i.criteria.append("country") # Language Check if i.language != inFilm.language: i.relevance -= 50 # Rating Check if i.rating != 0: if i.rating == inFilm.rating: i.relevance += 20 if i.rating == (inFilm.rating + 1) or i.rating == (inFilm.rating - 1): i.relevance += 10 if i.rating == (inFilm.rating + 3) or i.rating == (inFilm.rating - 3): i.relevance -= 200 if i.rating == (inFilm.rating + 4) or i.rating == (inFilm.rating - 4): i.relevance -= 400 # Keyword Check for j in i.keywords: for k in inFilm.keywords: if j == k: i.relevance += 40 i.criteria.append("Keyword: "+j) # Genre Check for j in i.genres: for k in inFilm.genres: if j == k: i.relevance += (30 * genreWeight) i.criteria.append("genre: "+j) # Title Check count = 0 for j in i.titleWords: if not j.isdigit(): for k in inFilm.titleWords: if j == k: count += 1 if count > (len(inFilm.titleWords)/3): i.criteria.append(str(count)+" Title words") i.relevance += 20 # Year Check if (inFilm.year - 5) <= i.year <= (inFilm.year + 5): i.relevance += (10 * yearWeight) i.criteria.append("Year: 10") elif (inFilm.year - 5) <= i.year <= (inFilm.year + 5): i.relevance += (5 * yearWeight) i.criteria.append("Year: 5") # IMDB Score i.relevance += ((3*i.score) * int(scoreWeight)) bisect.insort_right(top, i) topN = []
return topN def getTitles(): count = 0 titles = [] with open("movieDBbackup.txt", 'r', encoding="utf8") as csvfile: TSVreader = csv.reader(csvfile, delimiter='\t', quotechar='"', skipinitialspace=True) for row in TSVreader: temp = Movie() if count > 0: # Makes sure the headers aren't stored in an object titles.append([row[11][:-1], row[23]]) count += 1 return titles # makes movie object from models.py for saving into sqlite database out of Movie() class. def makeMovieObj(temp): movie = MovieObj() sleep(0.0001) #print(temp.ID) response = requests.post(str("http://www.omdbapi.com/?i=" + str(temp.ID))) #OMDB API call while response.status_code != 200: sleep(0.0001) print('....................................', end='') response = requests.post(str("http://www.omdbapi.com/?i=" + str(temp.ID))) #OMDB API call try: movie.poster = response.json()['Poster'] except Exception as e: print("no poster") try: movie.plot = response.json()["Plot"] except Exception as e: print("no plot") try: movie.runtime = response.json()["Runtime"].split(' ')[0] except Exception as e: print("no runtime") try: movie.awards = response.json()["Awards"] except Exception as e: print("no awards") try: movie.IMDBScore = response.json()["imdbRating"] except Exception as e: print("no imdb") try: movie.tomatoes = response.json()["Ratings"][1]["Value"].replace("%","") except Exception as e: print("no tomato") try: movie.metascore = response.json()["Metascore"].replace("%","") except Exception as e: print("no Metascore") try: movie.production = response.json()["Production"] except Exception as e: print("no Production") try: movie.boxOffice = response.json()["BoxOffice"] except Exception as e: print("no BoxOffice") #movie.poster = response.json()['Poster'] movie.title = temp.title # movie.titleWords = temp.titleWords movie.year = temp.year movie.actor1 = temp.actor1 movie.actor2 = temp.actor2 movie.actor3 = temp.actor3 movie.director = temp.director movie.keywords = temp.keywords movie.genres = temp.genres movie.country = temp.country movie.language = temp.language movie.rating = temp.rating movie.score = temp.score movie.movieID = temp.ID movie.numCritic = temp.numCritic movie.gross = temp.gross movie.fblikes = temp.fblikes movie.budget = temp.budget movie.numReviews = temp.numReviews print(movie) movie.save()
for i in range(0, num_results): topN.append([top[i].ID, str(top[i].relevance), top[i].criteria, ", ".join(top[i].genres)])
random_line_split
algorithm.py
import csv import bisect from explore.models import MovieObj import requests from time import sleep import pprint ratings = {"Passed": 0, "Approved": 0, "Unrated": 0, "Not Rated": 0, "": 0, "TV-Y": 0, "TV-G": 1, "G": 1, "TV-Y7": 2, "GP": 2, "TV-PG": 2, "PG": 2, "TV-14": 3, "PG-13": 3, "TV-MA": 4, "M": 4, "R": 4, "NC-17": 4, "X": 5} common = ["the", "and", "of"] # List of common words to be filtered from titles flag = True class Movie: def __init__(self): self.title = "" self.titleWords = [] self.year = 0 self.actor1 = "" self.actor2 = "" self.actor3 = "" self.director = "" self.keywords = [] self.genres = [] self.relevance = 0 self.country = "" self.language = "" self.criteria = [] self.rating = 0 self.score = 0 self.ID = "" self.gross = 0 self.fblikes = 0 self.budget = 0 self.numReviews = 0 def __lt__(self, other): return self.relevance > other.relevance # Temp function. Use to make generate input strings for now. Enter names into array. def stringBuilder(name): movies = reader("movieDBbackup.txt") inputs = [name] IDs = [] for j in inputs: for i in movies: if i.title.lower() == j.lower(): IDs.append(i.ID) print(IDs) return " ".join(IDs) # Function Name: reader() # Function Purpose: This block of code reads the entire TSV file and stores each movie in an object # Parameters: # fileName: The name of the TSV file def reader(fileName): global flag movies = [] count = 0 with open(fileName, 'r', encoding="utf8") as csvfile: TSVreader = csv.reader(csvfile, delimiter='\t', quotechar='"', skipinitialspace=True) for row in TSVreader: #print(row[11]) temp = Movie() if count > 0: # Makes sure the headers aren't stored in an object #temp = Movie() # Creates a temp object temp.title = row[11][:-1].lower() # Converts all titles to lower and strips off end char # Puts any non-common title words into a list temp.titleWords = [] for i in row[11][:-1].lower().split(): if i not in common: temp.titleWords.append(i) # Error checks for rows without years if row[23] != '': temp.year = int(row[23]) temp.actor1 = row[10] temp.actor2 = row[6] temp.actor3 = row[14] temp.director = row[1] temp.keywords = row[16].split('|') temp.genres = row[9].split('|') temp.country = row[20] temp.language = row[19] temp.rating = ratings[row[21]] temp.score = float(row[25]) temp.ID = row[28].lower() temp.numCritic = row[2] temp.gross = row[8] temp.fblikes = row[13] temp.budget = row[22] temp.numReviews = row[18] movies.append(temp) #if ((flag) and (count > 0)): #makeMovieObj(temp) #print(temp) # uncomment if you want to repopulate the database from scratch for some reason. Or, load the fixture like a reasonable human. count += 1 #print(count) flag = False return(movies) # Function Name: Related # Function Purpose: Takes an input string of IMDB ID's and returns the top 15 most related films # Parameters: # num_results: The number of results to be returned # ID_string: The string containing IMDB IDs def related(num_results, ID_string, actorWeight, genreWeight, directorWeight, yearWeight, scoreWeight): listIDs = ID_string.split(" ") # Splits inFilm string into list of IDs movies = reader("movieDBbackup.txt") # Populates inputs = [] for i in movies: for j in listIDs:
top = [] for i in movies: for inFilm in inputs: # Actor Check if i.actor1 == inFilm.actor1 or i.actor1 == inFilm.actor2 or i.actor1 == inFilm.actor3: i.relevance += (35 * actorWeight) i.criteria.append("Actor: "+i.actor1) if i.actor2 == inFilm.actor1 or i.actor2 == inFilm.actor2 or i.actor2 == inFilm.actor3: i.relevance += (35 * actorWeight) i.criteria.append("Actor: "+i.actor2) if i.actor3 == inFilm.actor1 or i.actor3 == inFilm.actor2 or i.actor3 == inFilm.actor3: i.relevance += (35 * actorWeight) i.criteria.append("Actor: "+i.actor3) # Director Check if i.director == inFilm.director: i.relevance += (35 * directorWeight) i.criteria.append("Director: "+i.director) # Country Check if i.country == inFilm.country: i.relevance += 10 i.criteria.append("country") # Language Check if i.language != inFilm.language: i.relevance -= 50 # Rating Check if i.rating != 0: if i.rating == inFilm.rating: i.relevance += 20 if i.rating == (inFilm.rating + 1) or i.rating == (inFilm.rating - 1): i.relevance += 10 if i.rating == (inFilm.rating + 3) or i.rating == (inFilm.rating - 3): i.relevance -= 200 if i.rating == (inFilm.rating + 4) or i.rating == (inFilm.rating - 4): i.relevance -= 400 # Keyword Check for j in i.keywords: for k in inFilm.keywords: if j == k: i.relevance += 40 i.criteria.append("Keyword: "+j) # Genre Check for j in i.genres: for k in inFilm.genres: if j == k: i.relevance += (30 * genreWeight) i.criteria.append("genre: "+j) # Title Check count = 0 for j in i.titleWords: if not j.isdigit(): for k in inFilm.titleWords: if j == k: count += 1 if count > (len(inFilm.titleWords)/3): i.criteria.append(str(count)+" Title words") i.relevance += 20 # Year Check if (inFilm.year - 5) <= i.year <= (inFilm.year + 5): i.relevance += (10 * yearWeight) i.criteria.append("Year: 10") elif (inFilm.year - 5) <= i.year <= (inFilm.year + 5): i.relevance += (5 * yearWeight) i.criteria.append("Year: 5") # IMDB Score i.relevance += ((3*i.score) * int(scoreWeight)) bisect.insort_right(top, i) topN = [] for i in range(0, num_results): topN.append([top[i].ID, str(top[i].relevance), top[i].criteria, ", ".join(top[i].genres)]) return topN def getTitles(): count = 0 titles = [] with open("movieDBbackup.txt", 'r', encoding="utf8") as csvfile: TSVreader = csv.reader(csvfile, delimiter='\t', quotechar='"', skipinitialspace=True) for row in TSVreader: temp = Movie() if count > 0: # Makes sure the headers aren't stored in an object titles.append([row[11][:-1], row[23]]) count += 1 return titles # makes movie object from models.py for saving into sqlite database out of Movie() class. def makeMovieObj(temp): movie = MovieObj() sleep(0.0001) #print(temp.ID) response = requests.post(str("http://www.omdbapi.com/?i=" + str(temp.ID))) #OMDB API call while response.status_code != 200: sleep(0.0001) print('....................................', end='') response = requests.post(str("http://www.omdbapi.com/?i=" + str(temp.ID))) #OMDB API call try: movie.poster = response.json()['Poster'] except Exception as e: print("no poster") try: movie.plot = response.json()["Plot"] except Exception as e: print("no plot") try: movie.runtime = response.json()["Runtime"].split(' ')[0] except Exception as e: print("no runtime") try: movie.awards = response.json()["Awards"] except Exception as e: print("no awards") try: movie.IMDBScore = response.json()["imdbRating"] except Exception as e: print("no imdb") try: movie.tomatoes = response.json()["Ratings"][1]["Value"].replace("%","") except Exception as e: print("no tomato") try: movie.metascore = response.json()["Metascore"].replace("%","") except Exception as e: print("no Metascore") try: movie.production = response.json()["Production"] except Exception as e: print("no Production") try: movie.boxOffice = response.json()["BoxOffice"] except Exception as e: print("no BoxOffice") #movie.poster = response.json()['Poster'] movie.title = temp.title # movie.titleWords = temp.titleWords movie.year = temp.year movie.actor1 = temp.actor1 movie.actor2 = temp.actor2 movie.actor3 = temp.actor3 movie.director = temp.director movie.keywords = temp.keywords movie.genres = temp.genres movie.country = temp.country movie.language = temp.language movie.rating = temp.rating movie.score = temp.score movie.movieID = temp.ID movie.numCritic = temp.numCritic movie.gross = temp.gross movie.fblikes = temp.fblikes movie.budget = temp.budget movie.numReviews = temp.numReviews print(movie) movie.save()
if i.ID == j: inputs.append(i) print(i.titleWords) print(i.genres) print(i.keywords) print()
conditional_block
kernel.rs
use crate::api::event::create_and_queue; use crate::api::icd::*; use crate::api::util::*; use crate::core::device::*; use crate::core::event::*; use crate::core::kernel::*; use crate::core::program::*; use mesa_rust_util::ptr::*; use mesa_rust_util::string::*; use rusticl_opencl_gen::*; use std::collections::HashSet; use std::os::raw::c_void; use std::ptr; use std::slice; use std::sync::Arc; impl CLInfo<cl_kernel_info> for cl_kernel { fn query(&self, q: cl_kernel_info, _: &[u8]) -> CLResult<Vec<u8>> { let kernel = self.get_ref()?; Ok(match q { CL_KERNEL_ATTRIBUTES => cl_prop::<&str>(&kernel.attributes_string), CL_KERNEL_CONTEXT => { let ptr = Arc::as_ptr(&kernel.prog.context); cl_prop::<cl_context>(cl_context::from_ptr(ptr)) } CL_KERNEL_FUNCTION_NAME => cl_prop::<&str>(&kernel.name), CL_KERNEL_NUM_ARGS => cl_prop::<cl_uint>(kernel.args.len() as cl_uint), CL_KERNEL_PROGRAM => { let ptr = Arc::as_ptr(&kernel.prog); cl_prop::<cl_program>(cl_program::from_ptr(ptr)) } CL_KERNEL_REFERENCE_COUNT => cl_prop::<cl_uint>(self.refcnt()?), // CL_INVALID_VALUE if param_name is not one of the supported values _ => return Err(CL_INVALID_VALUE), }) } } impl CLInfoObj<cl_kernel_arg_info, cl_uint> for cl_kernel { fn query(&self, idx: cl_uint, q: cl_kernel_arg_info) -> CLResult<Vec<u8>> { let kernel = self.get_ref()?; // CL_INVALID_ARG_INDEX if arg_index is not a valid argument index. if idx as usize >= kernel.args.len() { return Err(CL_INVALID_ARG_INDEX); } Ok(match *q { CL_KERNEL_ARG_ACCESS_QUALIFIER => { cl_prop::<cl_kernel_arg_access_qualifier>(kernel.access_qualifier(idx)) } CL_KERNEL_ARG_ADDRESS_QUALIFIER => { cl_prop::<cl_kernel_arg_address_qualifier>(kernel.address_qualifier(idx)) } CL_KERNEL_ARG_NAME => cl_prop::<&str>(kernel.arg_name(idx)), CL_KERNEL_ARG_TYPE_NAME => cl_prop::<&str>(kernel.arg_type_name(idx)), CL_KERNEL_ARG_TYPE_QUALIFIER => { cl_prop::<cl_kernel_arg_type_qualifier>(kernel.type_qualifier(idx)) } // CL_INVALID_VALUE if param_name is not one of the supported values _ => return Err(CL_INVALID_VALUE), }) } } impl CLInfoObj<cl_kernel_work_group_info, cl_device_id> for cl_kernel { fn query(&self, dev: cl_device_id, q: cl_kernel_work_group_info) -> CLResult<Vec<u8>> { let kernel = self.get_ref()?; // CL_INVALID_DEVICE [..] if device is NULL but there is more than one device associated with kernel. let dev = if dev.is_null() { if kernel.prog.devs.len() > 1 { return Err(CL_INVALID_DEVICE); } else { kernel.prog.devs[0].clone() } } else { dev.get_arc()? }; // CL_INVALID_DEVICE if device is not in the list of devices associated with kernel if !kernel.prog.devs.contains(&dev) { return Err(CL_INVALID_DEVICE); } Ok(match *q { CL_KERNEL_COMPILE_WORK_GROUP_SIZE => cl_prop::<[usize; 3]>(kernel.work_group_size), CL_KERNEL_LOCAL_MEM_SIZE => cl_prop::<cl_ulong>(kernel.local_mem_size(&dev)), CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE => { cl_prop::<usize>(dev.subgroups() as usize) } CL_KERNEL_PRIVATE_MEM_SIZE => cl_prop::<cl_ulong>(kernel.priv_mem_size(&dev)), // TODO CL_KERNEL_WORK_GROUP_SIZE => cl_prop::<usize>(dev.subgroups() as usize), // CL_INVALID_VALUE if param_name is not one of the supported values _ => return Err(CL_INVALID_VALUE), }) } } impl CLInfoObj<cl_kernel_sub_group_info, (cl_device_id, usize, *const c_void)> for cl_kernel { fn query( &self, (d, _input_value_size, _input_value): (cl_device_id, usize, *const c_void), _q: cl_program_build_info, ) -> CLResult<Vec<u8>> { let _kernel = self.get_ref()?; let _dev = d.get_arc()?; Err(CL_INVALID_OPERATION) } } const ZERO_ARR: [usize; 3] = [0; 3]; /// # Safety /// /// This function is only safe when called on an array of `work_dim` length unsafe fn kernel_work_arr_or_default<'a>(arr: *const usize, work_dim: cl_uint) -> &'a [usize] { if !arr.is_null() { slice::from_raw_parts(arr, work_dim as usize) } else { &ZERO_ARR } } fn get_devices_with_valid_build(p: &Arc<Program>) -> CLResult<Vec<&Arc<Device>>> { // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built executable for program. let devs: Vec<_> = p .devs .iter() .filter(|d| p.status(d) == CL_BUILD_SUCCESS as cl_build_status) .collect(); if devs.is_empty() { return Err(CL_INVALID_PROGRAM_EXECUTABLE); } Ok(devs) } pub fn create_kernel( program: cl_program, kernel_name: *const ::std::os::raw::c_char, ) -> CLResult<cl_kernel> { let p = program.get_arc()?; let name = c_string_to_string(kernel_name); // CL_INVALID_VALUE if kernel_name is NULL. if kernel_name.is_null() { return Err(CL_INVALID_VALUE); } // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built executable for program. if p.kernels().is_empty() { return Err(CL_INVALID_PROGRAM_EXECUTABLE); } // CL_INVALID_KERNEL_NAME if kernel_name is not found in program. if !p.kernels().contains(&name) { return Err(CL_INVALID_KERNEL_NAME); } // CL_INVALID_KERNEL_DEFINITION if the function definition for __kernel function given by // kernel_name such as the number of arguments, the argument types are not the same for all // devices for which the program executable has been built. let devs = get_devices_with_valid_build(&p)?; let kernel_args: HashSet<_> = devs.iter().map(|d| p.args(d, &name)).collect(); if kernel_args.len() != 1 { return Err(CL_INVALID_KERNEL_DEFINITION); } Ok(cl_kernel::from_arc(Kernel::new( name, p, kernel_args.into_iter().next().unwrap(), ))) } pub fn create_kernels_in_program( program: cl_program, num_kernels: cl_uint, kernels: *mut cl_kernel, num_kernels_ret: *mut cl_uint, ) -> CLResult<()> { let p = program.get_arc()?; let devs = get_devices_with_valid_build(&p)?; // CL_INVALID_VALUE if kernels is not NULL and num_kernels is less than the number of kernels // in program. if !kernels.is_null() && p.kernels().len() > num_kernels as usize { return Err(CL_INVALID_VALUE); } let mut num_kernels = 0; for name in p.kernels() { let kernel_args: HashSet<_> = devs.iter().map(|d| p.args(d, &name)).collect(); // Kernel objects are not created for any __kernel functions in program that do not have the // same function definition across all devices for which a program executable has been // successfully built. if kernel_args.len() != 1 { continue; } if !kernels.is_null() { // we just assume the client isn't stupid unsafe { kernels .add(num_kernels as usize) .write(cl_kernel::from_arc(Kernel::new( name, p.clone(), kernel_args.into_iter().next().unwrap(), ))); } } num_kernels += 1; } num_kernels_ret.write_checked(num_kernels); Ok(()) } pub fn set_kernel_arg( kernel: cl_kernel, arg_index: cl_uint, arg_size: usize, arg_value: *const ::std::os::raw::c_void, ) -> CLResult<()> { let k = kernel.get_arc()?; // CL_INVALID_ARG_INDEX if arg_index is not a valid argument index. if let Some(arg) = k.args.get(arg_index as usize) { // CL_INVALID_ARG_SIZE if arg_size does not match the size of the data type for an argument // that is not a memory object or if the argument is a memory object and // arg_size != sizeof(cl_mem) or if arg_size is zero and the argument is declared with the // local qualifier or if the argument is a sampler and arg_size != sizeof(cl_sampler). match arg.kind { KernelArgType::MemLocal => { if arg_size == 0 { return Err(CL_INVALID_ARG_SIZE); } } KernelArgType::MemGlobal | KernelArgType::MemConstant | KernelArgType::Image | KernelArgType::RWImage | KernelArgType::Texture => { if arg_size != std::mem::size_of::<cl_mem>() { return Err(CL_INVALID_ARG_SIZE); } } _ => { if arg.size != arg_size { return Err(CL_INVALID_ARG_SIZE); } } } // CL_INVALID_ARG_VALUE if arg_value specified is not a valid value. match arg.kind { // If the argument is declared with the local qualifier, the arg_value entry must be // NULL. KernelArgType::MemLocal => { if !arg_value.is_null() { return Err(CL_INVALID_ARG_VALUE); }
if arg_value.is_null() { return Err(CL_INVALID_ARG_VALUE); } } _ => {} }; // let's create the arg now let arg = unsafe { if arg.dead { KernelArgValue::None } else { match arg.kind { KernelArgType::Constant => KernelArgValue::Constant( slice::from_raw_parts(arg_value.cast(), arg_size).to_vec(), ), KernelArgType::MemConstant | KernelArgType::MemGlobal => { let ptr: *const cl_mem = arg_value.cast(); if ptr.is_null() || (*ptr).is_null() { KernelArgValue::None } else { KernelArgValue::MemObject((*ptr).get_arc()?) } } KernelArgType::MemLocal => KernelArgValue::LocalMem(arg_size), KernelArgType::Image | KernelArgType::RWImage | KernelArgType::Texture => { let img: *const cl_mem = arg_value.cast(); KernelArgValue::MemObject((*img).get_arc()?) } KernelArgType::Sampler => { let ptr: *const cl_sampler = arg_value.cast(); KernelArgValue::Sampler((*ptr).get_arc()?) } } } }; k.values.get(arg_index as usize).unwrap().replace(Some(arg)); Ok(()) } else { Err(CL_INVALID_ARG_INDEX) } //• CL_INVALID_DEVICE_QUEUE for an argument declared to be of type queue_t when the specified arg_value is not a valid device queue object. This error code is missing before version 2.0. //• CL_INVALID_ARG_VALUE if the argument is an image declared with the read_only qualifier and arg_value refers to an image object created with cl_mem_flags of CL_MEM_WRITE_ONLY or if the image argument is declared with the write_only qualifier and arg_value refers to an image object created with cl_mem_flags of CL_MEM_READ_ONLY. //• CL_MAX_SIZE_RESTRICTION_EXCEEDED if the size in bytes of the memory object (if the argument is a memory object) or arg_size (if the argument is declared with local qualifier) exceeds a language- specified maximum size restriction for this argument, such as the MaxByteOffset SPIR-V decoration. This error code is missing before version 2.2. } pub fn enqueue_ndrange_kernel( command_queue: cl_command_queue, kernel: cl_kernel, work_dim: cl_uint, global_work_offset: *const usize, global_work_size: *const usize, local_work_size: *const usize, num_events_in_wait_list: cl_uint, event_wait_list: *const cl_event, event: *mut cl_event, ) -> CLResult<()> { let q = command_queue.get_arc()?; let k = kernel.get_arc()?; let evs = event_list_from_cl(&q, num_events_in_wait_list, event_wait_list)?; // CL_INVALID_CONTEXT if context associated with command_queue and kernel are not the same if q.context != k.prog.context { return Err(CL_INVALID_CONTEXT); } // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built program executable available // for device associated with command_queue. if k.prog.status(&q.device) != CL_BUILD_SUCCESS as cl_build_status { return Err(CL_INVALID_PROGRAM_EXECUTABLE); } // CL_INVALID_KERNEL_ARGS if the kernel argument values have not been specified. if k.values.iter().any(|v| v.borrow().is_none()) { return Err(CL_INVALID_KERNEL_ARGS); } // CL_INVALID_WORK_DIMENSION if work_dim is not a valid value (i.e. a value between 1 and // CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS). if work_dim == 0 || work_dim > q.device.max_grid_dimensions() { return Err(CL_INVALID_WORK_DIMENSION); } // we assume the application gets it right and doesn't pass shorter arrays then actually needed. let global_work_size = unsafe { kernel_work_arr_or_default(global_work_size, work_dim) }; let local_work_size = unsafe { kernel_work_arr_or_default(local_work_size, work_dim) }; let global_work_offset = unsafe { kernel_work_arr_or_default(global_work_offset, work_dim) }; let device_bits = q.device.address_bits(); let device_max = u64::MAX >> (u64::BITS - device_bits); for i in 0..work_dim as usize { let lws = local_work_size[i]; let gws = global_work_size[i]; let gwo = global_work_offset[i]; // CL_INVALID_WORK_ITEM_SIZE if the number of work-items specified in any of // local_work_size[0], … local_work_size[work_dim - 1] is greater than the corresponding // values specified by // CL_DEVICE_MAX_WORK_ITEM_SIZES[0], …, CL_DEVICE_MAX_WORK_ITEM_SIZES[work_dim - 1]. if lws > q.device.max_block_sizes()[i] { return Err(CL_INVALID_WORK_ITEM_SIZE); } // CL_INVALID_WORK_GROUP_SIZE if the work-group size must be uniform and the // local_work_size is not NULL, [...] if the global_work_size is not evenly divisible by // the local_work_size. if lws != 0 && gws % lws != 0 { return Err(CL_INVALID_WORK_GROUP_SIZE); } // CL_INVALID_WORK_GROUP_SIZE if local_work_size is specified and does not match the // required work-group size for kernel in the program source. if lws != 0 && k.work_group_size[i] != 0 && lws != k.work_group_size[i] { return Err(CL_INVALID_WORK_GROUP_SIZE); } // CL_INVALID_GLOBAL_WORK_SIZE if any of the values specified in global_work_size[0], … // global_work_size[work_dim - 1] exceed the maximum value representable by size_t on // the device on which the kernel-instance will be enqueued. if gws as u64 > device_max { return Err(CL_INVALID_GLOBAL_WORK_SIZE); } // CL_INVALID_GLOBAL_OFFSET if the value specified in global_work_size + the // corresponding values in global_work_offset for any dimensions is greater than the // maximum value representable by size t on the device on which the kernel-instance // will be enqueued if u64::checked_add(gws as u64, gwo as u64) .filter(|&x| x <= device_max) .is_none() { return Err(CL_INVALID_GLOBAL_OFFSET); } } // If global_work_size is NULL, or the value in any passed dimension is 0 then the kernel // command will trivially succeed after its event dependencies are satisfied and subsequently // update its completion event. let cb: EventSig = if global_work_size.contains(&0) { Box::new(|_, _| Ok(())) } else { k.launch( &q, work_dim, local_work_size, global_work_size, global_work_offset, )? }; create_and_queue(q, CL_COMMAND_NDRANGE_KERNEL, evs, event, false, cb) //• CL_INVALID_WORK_GROUP_SIZE if local_work_size is specified and is not consistent with the required number of sub-groups for kernel in the program source. //• CL_INVALID_WORK_GROUP_SIZE if local_work_size is specified and the total number of work-items in the work-group computed as local_work_size[0] × … local_work_size[work_dim - 1] is greater than the value specified by CL_KERNEL_WORK_GROUP_SIZE in the Kernel Object Device Queries table. //• CL_MISALIGNED_SUB_BUFFER_OFFSET if a sub-buffer object is specified as the value for an argument that is a buffer object and the offset specified when the sub-buffer object is created is not aligned to CL_DEVICE_MEM_BASE_ADDR_ALIGN value for device associated with queue. This error code //• CL_INVALID_IMAGE_SIZE if an image object is specified as an argument value and the image dimensions (image width, height, specified or compute row and/or slice pitch) are not supported by device associated with queue. //• CL_IMAGE_FORMAT_NOT_SUPPORTED if an image object is specified as an argument value and the image format (image channel order and data type) is not supported by device associated with queue. //• CL_OUT_OF_RESOURCES if there is a failure to queue the execution instance of kernel on the command-queue because of insufficient resources needed to execute the kernel. For example, the explicitly specified local_work_size causes a failure to execute the kernel because of insufficient resources such as registers or local memory. Another example would be the number of read-only image args used in kernel exceed the CL_DEVICE_MAX_READ_IMAGE_ARGS value for device or the number of write-only and read-write image args used in kernel exceed the CL_DEVICE_MAX_READ_WRITE_IMAGE_ARGS value for device or the number of samplers used in kernel exceed CL_DEVICE_MAX_SAMPLERS for device. //• CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with image or buffer objects specified as arguments to kernel. //• CL_INVALID_OPERATION if SVM pointers are passed as arguments to a kernel and the device does not support SVM or if system pointers are passed as arguments to a kernel and/or stored inside SVM allocations passed as kernel arguments and the device does not support fine grain system SVM allocations. } pub fn enqueue_task( command_queue: cl_command_queue, kernel: cl_kernel, num_events_in_wait_list: cl_uint, event_wait_list: *const cl_event, event: *mut cl_event, ) -> CLResult<()> { // clEnqueueTask is equivalent to calling clEnqueueNDRangeKernel with work_dim set to 1, // global_work_offset set to NULL, global_work_size[0] set to 1, and local_work_size[0] set to // 1. enqueue_ndrange_kernel( command_queue, kernel, 1, ptr::null(), [1, 1, 1].as_ptr(), [1, 0, 0].as_ptr(), num_events_in_wait_list, event_wait_list, event, ) } pub fn clone_kernel(source_kernel: cl_kernel) -> CLResult<cl_kernel> { let k = source_kernel.get_ref()?; Ok(cl_kernel::from_arc(Arc::new(k.clone()))) }
} // If the argument is of type sampler_t, the arg_value entry must be a pointer to the // sampler object. KernelArgType::Constant | KernelArgType::Sampler => {
random_line_split
kernel.rs
use crate::api::event::create_and_queue; use crate::api::icd::*; use crate::api::util::*; use crate::core::device::*; use crate::core::event::*; use crate::core::kernel::*; use crate::core::program::*; use mesa_rust_util::ptr::*; use mesa_rust_util::string::*; use rusticl_opencl_gen::*; use std::collections::HashSet; use std::os::raw::c_void; use std::ptr; use std::slice; use std::sync::Arc; impl CLInfo<cl_kernel_info> for cl_kernel { fn query(&self, q: cl_kernel_info, _: &[u8]) -> CLResult<Vec<u8>> { let kernel = self.get_ref()?; Ok(match q { CL_KERNEL_ATTRIBUTES => cl_prop::<&str>(&kernel.attributes_string), CL_KERNEL_CONTEXT => { let ptr = Arc::as_ptr(&kernel.prog.context); cl_prop::<cl_context>(cl_context::from_ptr(ptr)) } CL_KERNEL_FUNCTION_NAME => cl_prop::<&str>(&kernel.name), CL_KERNEL_NUM_ARGS => cl_prop::<cl_uint>(kernel.args.len() as cl_uint), CL_KERNEL_PROGRAM => { let ptr = Arc::as_ptr(&kernel.prog); cl_prop::<cl_program>(cl_program::from_ptr(ptr)) } CL_KERNEL_REFERENCE_COUNT => cl_prop::<cl_uint>(self.refcnt()?), // CL_INVALID_VALUE if param_name is not one of the supported values _ => return Err(CL_INVALID_VALUE), }) } } impl CLInfoObj<cl_kernel_arg_info, cl_uint> for cl_kernel { fn query(&self, idx: cl_uint, q: cl_kernel_arg_info) -> CLResult<Vec<u8>> { let kernel = self.get_ref()?; // CL_INVALID_ARG_INDEX if arg_index is not a valid argument index. if idx as usize >= kernel.args.len() { return Err(CL_INVALID_ARG_INDEX); } Ok(match *q { CL_KERNEL_ARG_ACCESS_QUALIFIER => { cl_prop::<cl_kernel_arg_access_qualifier>(kernel.access_qualifier(idx)) } CL_KERNEL_ARG_ADDRESS_QUALIFIER => { cl_prop::<cl_kernel_arg_address_qualifier>(kernel.address_qualifier(idx)) } CL_KERNEL_ARG_NAME => cl_prop::<&str>(kernel.arg_name(idx)), CL_KERNEL_ARG_TYPE_NAME => cl_prop::<&str>(kernel.arg_type_name(idx)), CL_KERNEL_ARG_TYPE_QUALIFIER => { cl_prop::<cl_kernel_arg_type_qualifier>(kernel.type_qualifier(idx)) } // CL_INVALID_VALUE if param_name is not one of the supported values _ => return Err(CL_INVALID_VALUE), }) } } impl CLInfoObj<cl_kernel_work_group_info, cl_device_id> for cl_kernel { fn query(&self, dev: cl_device_id, q: cl_kernel_work_group_info) -> CLResult<Vec<u8>> { let kernel = self.get_ref()?; // CL_INVALID_DEVICE [..] if device is NULL but there is more than one device associated with kernel. let dev = if dev.is_null() { if kernel.prog.devs.len() > 1 { return Err(CL_INVALID_DEVICE); } else { kernel.prog.devs[0].clone() } } else { dev.get_arc()? }; // CL_INVALID_DEVICE if device is not in the list of devices associated with kernel if !kernel.prog.devs.contains(&dev) { return Err(CL_INVALID_DEVICE); } Ok(match *q { CL_KERNEL_COMPILE_WORK_GROUP_SIZE => cl_prop::<[usize; 3]>(kernel.work_group_size), CL_KERNEL_LOCAL_MEM_SIZE => cl_prop::<cl_ulong>(kernel.local_mem_size(&dev)), CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE => { cl_prop::<usize>(dev.subgroups() as usize) } CL_KERNEL_PRIVATE_MEM_SIZE => cl_prop::<cl_ulong>(kernel.priv_mem_size(&dev)), // TODO CL_KERNEL_WORK_GROUP_SIZE => cl_prop::<usize>(dev.subgroups() as usize), // CL_INVALID_VALUE if param_name is not one of the supported values _ => return Err(CL_INVALID_VALUE), }) } } impl CLInfoObj<cl_kernel_sub_group_info, (cl_device_id, usize, *const c_void)> for cl_kernel { fn query( &self, (d, _input_value_size, _input_value): (cl_device_id, usize, *const c_void), _q: cl_program_build_info, ) -> CLResult<Vec<u8>> { let _kernel = self.get_ref()?; let _dev = d.get_arc()?; Err(CL_INVALID_OPERATION) } } const ZERO_ARR: [usize; 3] = [0; 3]; /// # Safety /// /// This function is only safe when called on an array of `work_dim` length unsafe fn kernel_work_arr_or_default<'a>(arr: *const usize, work_dim: cl_uint) -> &'a [usize] { if !arr.is_null() { slice::from_raw_parts(arr, work_dim as usize) } else { &ZERO_ARR } } fn get_devices_with_valid_build(p: &Arc<Program>) -> CLResult<Vec<&Arc<Device>>> { // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built executable for program. let devs: Vec<_> = p .devs .iter() .filter(|d| p.status(d) == CL_BUILD_SUCCESS as cl_build_status) .collect(); if devs.is_empty() { return Err(CL_INVALID_PROGRAM_EXECUTABLE); } Ok(devs) } pub fn create_kernel( program: cl_program, kernel_name: *const ::std::os::raw::c_char, ) -> CLResult<cl_kernel> { let p = program.get_arc()?; let name = c_string_to_string(kernel_name); // CL_INVALID_VALUE if kernel_name is NULL. if kernel_name.is_null() { return Err(CL_INVALID_VALUE); } // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built executable for program. if p.kernels().is_empty() { return Err(CL_INVALID_PROGRAM_EXECUTABLE); } // CL_INVALID_KERNEL_NAME if kernel_name is not found in program. if !p.kernels().contains(&name) { return Err(CL_INVALID_KERNEL_NAME); } // CL_INVALID_KERNEL_DEFINITION if the function definition for __kernel function given by // kernel_name such as the number of arguments, the argument types are not the same for all // devices for which the program executable has been built. let devs = get_devices_with_valid_build(&p)?; let kernel_args: HashSet<_> = devs.iter().map(|d| p.args(d, &name)).collect(); if kernel_args.len() != 1 { return Err(CL_INVALID_KERNEL_DEFINITION); } Ok(cl_kernel::from_arc(Kernel::new( name, p, kernel_args.into_iter().next().unwrap(), ))) } pub fn create_kernels_in_program( program: cl_program, num_kernels: cl_uint, kernels: *mut cl_kernel, num_kernels_ret: *mut cl_uint, ) -> CLResult<()> { let p = program.get_arc()?; let devs = get_devices_with_valid_build(&p)?; // CL_INVALID_VALUE if kernels is not NULL and num_kernels is less than the number of kernels // in program. if !kernels.is_null() && p.kernels().len() > num_kernels as usize { return Err(CL_INVALID_VALUE); } let mut num_kernels = 0; for name in p.kernels() { let kernel_args: HashSet<_> = devs.iter().map(|d| p.args(d, &name)).collect(); // Kernel objects are not created for any __kernel functions in program that do not have the // same function definition across all devices for which a program executable has been // successfully built. if kernel_args.len() != 1 { continue; } if !kernels.is_null() { // we just assume the client isn't stupid unsafe { kernels .add(num_kernels as usize) .write(cl_kernel::from_arc(Kernel::new( name, p.clone(), kernel_args.into_iter().next().unwrap(), ))); } } num_kernels += 1; } num_kernels_ret.write_checked(num_kernels); Ok(()) } pub fn
( kernel: cl_kernel, arg_index: cl_uint, arg_size: usize, arg_value: *const ::std::os::raw::c_void, ) -> CLResult<()> { let k = kernel.get_arc()?; // CL_INVALID_ARG_INDEX if arg_index is not a valid argument index. if let Some(arg) = k.args.get(arg_index as usize) { // CL_INVALID_ARG_SIZE if arg_size does not match the size of the data type for an argument // that is not a memory object or if the argument is a memory object and // arg_size != sizeof(cl_mem) or if arg_size is zero and the argument is declared with the // local qualifier or if the argument is a sampler and arg_size != sizeof(cl_sampler). match arg.kind { KernelArgType::MemLocal => { if arg_size == 0 { return Err(CL_INVALID_ARG_SIZE); } } KernelArgType::MemGlobal | KernelArgType::MemConstant | KernelArgType::Image | KernelArgType::RWImage | KernelArgType::Texture => { if arg_size != std::mem::size_of::<cl_mem>() { return Err(CL_INVALID_ARG_SIZE); } } _ => { if arg.size != arg_size { return Err(CL_INVALID_ARG_SIZE); } } } // CL_INVALID_ARG_VALUE if arg_value specified is not a valid value. match arg.kind { // If the argument is declared with the local qualifier, the arg_value entry must be // NULL. KernelArgType::MemLocal => { if !arg_value.is_null() { return Err(CL_INVALID_ARG_VALUE); } } // If the argument is of type sampler_t, the arg_value entry must be a pointer to the // sampler object. KernelArgType::Constant | KernelArgType::Sampler => { if arg_value.is_null() { return Err(CL_INVALID_ARG_VALUE); } } _ => {} }; // let's create the arg now let arg = unsafe { if arg.dead { KernelArgValue::None } else { match arg.kind { KernelArgType::Constant => KernelArgValue::Constant( slice::from_raw_parts(arg_value.cast(), arg_size).to_vec(), ), KernelArgType::MemConstant | KernelArgType::MemGlobal => { let ptr: *const cl_mem = arg_value.cast(); if ptr.is_null() || (*ptr).is_null() { KernelArgValue::None } else { KernelArgValue::MemObject((*ptr).get_arc()?) } } KernelArgType::MemLocal => KernelArgValue::LocalMem(arg_size), KernelArgType::Image | KernelArgType::RWImage | KernelArgType::Texture => { let img: *const cl_mem = arg_value.cast(); KernelArgValue::MemObject((*img).get_arc()?) } KernelArgType::Sampler => { let ptr: *const cl_sampler = arg_value.cast(); KernelArgValue::Sampler((*ptr).get_arc()?) } } } }; k.values.get(arg_index as usize).unwrap().replace(Some(arg)); Ok(()) } else { Err(CL_INVALID_ARG_INDEX) } //• CL_INVALID_DEVICE_QUEUE for an argument declared to be of type queue_t when the specified arg_value is not a valid device queue object. This error code is missing before version 2.0. //• CL_INVALID_ARG_VALUE if the argument is an image declared with the read_only qualifier and arg_value refers to an image object created with cl_mem_flags of CL_MEM_WRITE_ONLY or if the image argument is declared with the write_only qualifier and arg_value refers to an image object created with cl_mem_flags of CL_MEM_READ_ONLY. //• CL_MAX_SIZE_RESTRICTION_EXCEEDED if the size in bytes of the memory object (if the argument is a memory object) or arg_size (if the argument is declared with local qualifier) exceeds a language- specified maximum size restriction for this argument, such as the MaxByteOffset SPIR-V decoration. This error code is missing before version 2.2. } pub fn enqueue_ndrange_kernel( command_queue: cl_command_queue, kernel: cl_kernel, work_dim: cl_uint, global_work_offset: *const usize, global_work_size: *const usize, local_work_size: *const usize, num_events_in_wait_list: cl_uint, event_wait_list: *const cl_event, event: *mut cl_event, ) -> CLResult<()> { let q = command_queue.get_arc()?; let k = kernel.get_arc()?; let evs = event_list_from_cl(&q, num_events_in_wait_list, event_wait_list)?; // CL_INVALID_CONTEXT if context associated with command_queue and kernel are not the same if q.context != k.prog.context { return Err(CL_INVALID_CONTEXT); } // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built program executable available // for device associated with command_queue. if k.prog.status(&q.device) != CL_BUILD_SUCCESS as cl_build_status { return Err(CL_INVALID_PROGRAM_EXECUTABLE); } // CL_INVALID_KERNEL_ARGS if the kernel argument values have not been specified. if k.values.iter().any(|v| v.borrow().is_none()) { return Err(CL_INVALID_KERNEL_ARGS); } // CL_INVALID_WORK_DIMENSION if work_dim is not a valid value (i.e. a value between 1 and // CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS). if work_dim == 0 || work_dim > q.device.max_grid_dimensions() { return Err(CL_INVALID_WORK_DIMENSION); } // we assume the application gets it right and doesn't pass shorter arrays then actually needed. let global_work_size = unsafe { kernel_work_arr_or_default(global_work_size, work_dim) }; let local_work_size = unsafe { kernel_work_arr_or_default(local_work_size, work_dim) }; let global_work_offset = unsafe { kernel_work_arr_or_default(global_work_offset, work_dim) }; let device_bits = q.device.address_bits(); let device_max = u64::MAX >> (u64::BITS - device_bits); for i in 0..work_dim as usize { let lws = local_work_size[i]; let gws = global_work_size[i]; let gwo = global_work_offset[i]; // CL_INVALID_WORK_ITEM_SIZE if the number of work-items specified in any of // local_work_size[0], … local_work_size[work_dim - 1] is greater than the corresponding // values specified by // CL_DEVICE_MAX_WORK_ITEM_SIZES[0], …, CL_DEVICE_MAX_WORK_ITEM_SIZES[work_dim - 1]. if lws > q.device.max_block_sizes()[i] { return Err(CL_INVALID_WORK_ITEM_SIZE); } // CL_INVALID_WORK_GROUP_SIZE if the work-group size must be uniform and the // local_work_size is not NULL, [...] if the global_work_size is not evenly divisible by // the local_work_size. if lws != 0 && gws % lws != 0 { return Err(CL_INVALID_WORK_GROUP_SIZE); } // CL_INVALID_WORK_GROUP_SIZE if local_work_size is specified and does not match the // required work-group size for kernel in the program source. if lws != 0 && k.work_group_size[i] != 0 && lws != k.work_group_size[i] { return Err(CL_INVALID_WORK_GROUP_SIZE); } // CL_INVALID_GLOBAL_WORK_SIZE if any of the values specified in global_work_size[0], … // global_work_size[work_dim - 1] exceed the maximum value representable by size_t on // the device on which the kernel-instance will be enqueued. if gws as u64 > device_max { return Err(CL_INVALID_GLOBAL_WORK_SIZE); } // CL_INVALID_GLOBAL_OFFSET if the value specified in global_work_size + the // corresponding values in global_work_offset for any dimensions is greater than the // maximum value representable by size t on the device on which the kernel-instance // will be enqueued if u64::checked_add(gws as u64, gwo as u64) .filter(|&x| x <= device_max) .is_none() { return Err(CL_INVALID_GLOBAL_OFFSET); } } // If global_work_size is NULL, or the value in any passed dimension is 0 then the kernel // command will trivially succeed after its event dependencies are satisfied and subsequently // update its completion event. let cb: EventSig = if global_work_size.contains(&0) { Box::new(|_, _| Ok(())) } else { k.launch( &q, work_dim, local_work_size, global_work_size, global_work_offset, )? }; create_and_queue(q, CL_COMMAND_NDRANGE_KERNEL, evs, event, false, cb) //• CL_INVALID_WORK_GROUP_SIZE if local_work_size is specified and is not consistent with the required number of sub-groups for kernel in the program source. //• CL_INVALID_WORK_GROUP_SIZE if local_work_size is specified and the total number of work-items in the work-group computed as local_work_size[0] × … local_work_size[work_dim - 1] is greater than the value specified by CL_KERNEL_WORK_GROUP_SIZE in the Kernel Object Device Queries table. //• CL_MISALIGNED_SUB_BUFFER_OFFSET if a sub-buffer object is specified as the value for an argument that is a buffer object and the offset specified when the sub-buffer object is created is not aligned to CL_DEVICE_MEM_BASE_ADDR_ALIGN value for device associated with queue. This error code //• CL_INVALID_IMAGE_SIZE if an image object is specified as an argument value and the image dimensions (image width, height, specified or compute row and/or slice pitch) are not supported by device associated with queue. //• CL_IMAGE_FORMAT_NOT_SUPPORTED if an image object is specified as an argument value and the image format (image channel order and data type) is not supported by device associated with queue. //• CL_OUT_OF_RESOURCES if there is a failure to queue the execution instance of kernel on the command-queue because of insufficient resources needed to execute the kernel. For example, the explicitly specified local_work_size causes a failure to execute the kernel because of insufficient resources such as registers or local memory. Another example would be the number of read-only image args used in kernel exceed the CL_DEVICE_MAX_READ_IMAGE_ARGS value for device or the number of write-only and read-write image args used in kernel exceed the CL_DEVICE_MAX_READ_WRITE_IMAGE_ARGS value for device or the number of samplers used in kernel exceed CL_DEVICE_MAX_SAMPLERS for device. //• CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with image or buffer objects specified as arguments to kernel. //• CL_INVALID_OPERATION if SVM pointers are passed as arguments to a kernel and the device does not support SVM or if system pointers are passed as arguments to a kernel and/or stored inside SVM allocations passed as kernel arguments and the device does not support fine grain system SVM allocations. } pub fn enqueue_task( command_queue: cl_command_queue, kernel: cl_kernel, num_events_in_wait_list: cl_uint, event_wait_list: *const cl_event, event: *mut cl_event, ) -> CLResult<()> { // clEnqueueTask is equivalent to calling clEnqueueNDRangeKernel with work_dim set to 1, // global_work_offset set to NULL, global_work_size[0] set to 1, and local_work_size[0] set to // 1. enqueue_ndrange_kernel( command_queue, kernel, 1, ptr::null(), [1, 1, 1].as_ptr(), [1, 0, 0].as_ptr(), num_events_in_wait_list, event_wait_list, event, ) } pub fn clone_kernel(source_kernel: cl_kernel) -> CLResult<cl_kernel> { let k = source_kernel.get_ref()?; Ok(cl_kernel::from_arc(Arc::new(k.clone()))) }
set_kernel_arg
identifier_name
kernel.rs
use crate::api::event::create_and_queue; use crate::api::icd::*; use crate::api::util::*; use crate::core::device::*; use crate::core::event::*; use crate::core::kernel::*; use crate::core::program::*; use mesa_rust_util::ptr::*; use mesa_rust_util::string::*; use rusticl_opencl_gen::*; use std::collections::HashSet; use std::os::raw::c_void; use std::ptr; use std::slice; use std::sync::Arc; impl CLInfo<cl_kernel_info> for cl_kernel { fn query(&self, q: cl_kernel_info, _: &[u8]) -> CLResult<Vec<u8>> { let kernel = self.get_ref()?; Ok(match q { CL_KERNEL_ATTRIBUTES => cl_prop::<&str>(&kernel.attributes_string), CL_KERNEL_CONTEXT => { let ptr = Arc::as_ptr(&kernel.prog.context); cl_prop::<cl_context>(cl_context::from_ptr(ptr)) } CL_KERNEL_FUNCTION_NAME => cl_prop::<&str>(&kernel.name), CL_KERNEL_NUM_ARGS => cl_prop::<cl_uint>(kernel.args.len() as cl_uint), CL_KERNEL_PROGRAM => { let ptr = Arc::as_ptr(&kernel.prog); cl_prop::<cl_program>(cl_program::from_ptr(ptr)) } CL_KERNEL_REFERENCE_COUNT => cl_prop::<cl_uint>(self.refcnt()?), // CL_INVALID_VALUE if param_name is not one of the supported values _ => return Err(CL_INVALID_VALUE), }) } } impl CLInfoObj<cl_kernel_arg_info, cl_uint> for cl_kernel { fn query(&self, idx: cl_uint, q: cl_kernel_arg_info) -> CLResult<Vec<u8>> { let kernel = self.get_ref()?; // CL_INVALID_ARG_INDEX if arg_index is not a valid argument index. if idx as usize >= kernel.args.len() { return Err(CL_INVALID_ARG_INDEX); } Ok(match *q { CL_KERNEL_ARG_ACCESS_QUALIFIER => { cl_prop::<cl_kernel_arg_access_qualifier>(kernel.access_qualifier(idx)) } CL_KERNEL_ARG_ADDRESS_QUALIFIER => { cl_prop::<cl_kernel_arg_address_qualifier>(kernel.address_qualifier(idx)) } CL_KERNEL_ARG_NAME => cl_prop::<&str>(kernel.arg_name(idx)), CL_KERNEL_ARG_TYPE_NAME => cl_prop::<&str>(kernel.arg_type_name(idx)), CL_KERNEL_ARG_TYPE_QUALIFIER => { cl_prop::<cl_kernel_arg_type_qualifier>(kernel.type_qualifier(idx)) } // CL_INVALID_VALUE if param_name is not one of the supported values _ => return Err(CL_INVALID_VALUE), }) } } impl CLInfoObj<cl_kernel_work_group_info, cl_device_id> for cl_kernel { fn query(&self, dev: cl_device_id, q: cl_kernel_work_group_info) -> CLResult<Vec<u8>> { let kernel = self.get_ref()?; // CL_INVALID_DEVICE [..] if device is NULL but there is more than one device associated with kernel. let dev = if dev.is_null() { if kernel.prog.devs.len() > 1 { return Err(CL_INVALID_DEVICE); } else { kernel.prog.devs[0].clone() } } else { dev.get_arc()? }; // CL_INVALID_DEVICE if device is not in the list of devices associated with kernel if !kernel.prog.devs.contains(&dev) { return Err(CL_INVALID_DEVICE); } Ok(match *q { CL_KERNEL_COMPILE_WORK_GROUP_SIZE => cl_prop::<[usize; 3]>(kernel.work_group_size), CL_KERNEL_LOCAL_MEM_SIZE => cl_prop::<cl_ulong>(kernel.local_mem_size(&dev)), CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE => { cl_prop::<usize>(dev.subgroups() as usize) } CL_KERNEL_PRIVATE_MEM_SIZE => cl_prop::<cl_ulong>(kernel.priv_mem_size(&dev)), // TODO CL_KERNEL_WORK_GROUP_SIZE => cl_prop::<usize>(dev.subgroups() as usize), // CL_INVALID_VALUE if param_name is not one of the supported values _ => return Err(CL_INVALID_VALUE), }) } } impl CLInfoObj<cl_kernel_sub_group_info, (cl_device_id, usize, *const c_void)> for cl_kernel { fn query( &self, (d, _input_value_size, _input_value): (cl_device_id, usize, *const c_void), _q: cl_program_build_info, ) -> CLResult<Vec<u8>> { let _kernel = self.get_ref()?; let _dev = d.get_arc()?; Err(CL_INVALID_OPERATION) } } const ZERO_ARR: [usize; 3] = [0; 3]; /// # Safety /// /// This function is only safe when called on an array of `work_dim` length unsafe fn kernel_work_arr_or_default<'a>(arr: *const usize, work_dim: cl_uint) -> &'a [usize] { if !arr.is_null() { slice::from_raw_parts(arr, work_dim as usize) } else { &ZERO_ARR } } fn get_devices_with_valid_build(p: &Arc<Program>) -> CLResult<Vec<&Arc<Device>>> { // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built executable for program. let devs: Vec<_> = p .devs .iter() .filter(|d| p.status(d) == CL_BUILD_SUCCESS as cl_build_status) .collect(); if devs.is_empty() { return Err(CL_INVALID_PROGRAM_EXECUTABLE); } Ok(devs) } pub fn create_kernel( program: cl_program, kernel_name: *const ::std::os::raw::c_char, ) -> CLResult<cl_kernel>
pub fn create_kernels_in_program( program: cl_program, num_kernels: cl_uint, kernels: *mut cl_kernel, num_kernels_ret: *mut cl_uint, ) -> CLResult<()> { let p = program.get_arc()?; let devs = get_devices_with_valid_build(&p)?; // CL_INVALID_VALUE if kernels is not NULL and num_kernels is less than the number of kernels // in program. if !kernels.is_null() && p.kernels().len() > num_kernels as usize { return Err(CL_INVALID_VALUE); } let mut num_kernels = 0; for name in p.kernels() { let kernel_args: HashSet<_> = devs.iter().map(|d| p.args(d, &name)).collect(); // Kernel objects are not created for any __kernel functions in program that do not have the // same function definition across all devices for which a program executable has been // successfully built. if kernel_args.len() != 1 { continue; } if !kernels.is_null() { // we just assume the client isn't stupid unsafe { kernels .add(num_kernels as usize) .write(cl_kernel::from_arc(Kernel::new( name, p.clone(), kernel_args.into_iter().next().unwrap(), ))); } } num_kernels += 1; } num_kernels_ret.write_checked(num_kernels); Ok(()) } pub fn set_kernel_arg( kernel: cl_kernel, arg_index: cl_uint, arg_size: usize, arg_value: *const ::std::os::raw::c_void, ) -> CLResult<()> { let k = kernel.get_arc()?; // CL_INVALID_ARG_INDEX if arg_index is not a valid argument index. if let Some(arg) = k.args.get(arg_index as usize) { // CL_INVALID_ARG_SIZE if arg_size does not match the size of the data type for an argument // that is not a memory object or if the argument is a memory object and // arg_size != sizeof(cl_mem) or if arg_size is zero and the argument is declared with the // local qualifier or if the argument is a sampler and arg_size != sizeof(cl_sampler). match arg.kind { KernelArgType::MemLocal => { if arg_size == 0 { return Err(CL_INVALID_ARG_SIZE); } } KernelArgType::MemGlobal | KernelArgType::MemConstant | KernelArgType::Image | KernelArgType::RWImage | KernelArgType::Texture => { if arg_size != std::mem::size_of::<cl_mem>() { return Err(CL_INVALID_ARG_SIZE); } } _ => { if arg.size != arg_size { return Err(CL_INVALID_ARG_SIZE); } } } // CL_INVALID_ARG_VALUE if arg_value specified is not a valid value. match arg.kind { // If the argument is declared with the local qualifier, the arg_value entry must be // NULL. KernelArgType::MemLocal => { if !arg_value.is_null() { return Err(CL_INVALID_ARG_VALUE); } } // If the argument is of type sampler_t, the arg_value entry must be a pointer to the // sampler object. KernelArgType::Constant | KernelArgType::Sampler => { if arg_value.is_null() { return Err(CL_INVALID_ARG_VALUE); } } _ => {} }; // let's create the arg now let arg = unsafe { if arg.dead { KernelArgValue::None } else { match arg.kind { KernelArgType::Constant => KernelArgValue::Constant( slice::from_raw_parts(arg_value.cast(), arg_size).to_vec(), ), KernelArgType::MemConstant | KernelArgType::MemGlobal => { let ptr: *const cl_mem = arg_value.cast(); if ptr.is_null() || (*ptr).is_null() { KernelArgValue::None } else { KernelArgValue::MemObject((*ptr).get_arc()?) } } KernelArgType::MemLocal => KernelArgValue::LocalMem(arg_size), KernelArgType::Image | KernelArgType::RWImage | KernelArgType::Texture => { let img: *const cl_mem = arg_value.cast(); KernelArgValue::MemObject((*img).get_arc()?) } KernelArgType::Sampler => { let ptr: *const cl_sampler = arg_value.cast(); KernelArgValue::Sampler((*ptr).get_arc()?) } } } }; k.values.get(arg_index as usize).unwrap().replace(Some(arg)); Ok(()) } else { Err(CL_INVALID_ARG_INDEX) } //• CL_INVALID_DEVICE_QUEUE for an argument declared to be of type queue_t when the specified arg_value is not a valid device queue object. This error code is missing before version 2.0. //• CL_INVALID_ARG_VALUE if the argument is an image declared with the read_only qualifier and arg_value refers to an image object created with cl_mem_flags of CL_MEM_WRITE_ONLY or if the image argument is declared with the write_only qualifier and arg_value refers to an image object created with cl_mem_flags of CL_MEM_READ_ONLY. //• CL_MAX_SIZE_RESTRICTION_EXCEEDED if the size in bytes of the memory object (if the argument is a memory object) or arg_size (if the argument is declared with local qualifier) exceeds a language- specified maximum size restriction for this argument, such as the MaxByteOffset SPIR-V decoration. This error code is missing before version 2.2. } pub fn enqueue_ndrange_kernel( command_queue: cl_command_queue, kernel: cl_kernel, work_dim: cl_uint, global_work_offset: *const usize, global_work_size: *const usize, local_work_size: *const usize, num_events_in_wait_list: cl_uint, event_wait_list: *const cl_event, event: *mut cl_event, ) -> CLResult<()> { let q = command_queue.get_arc()?; let k = kernel.get_arc()?; let evs = event_list_from_cl(&q, num_events_in_wait_list, event_wait_list)?; // CL_INVALID_CONTEXT if context associated with command_queue and kernel are not the same if q.context != k.prog.context { return Err(CL_INVALID_CONTEXT); } // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built program executable available // for device associated with command_queue. if k.prog.status(&q.device) != CL_BUILD_SUCCESS as cl_build_status { return Err(CL_INVALID_PROGRAM_EXECUTABLE); } // CL_INVALID_KERNEL_ARGS if the kernel argument values have not been specified. if k.values.iter().any(|v| v.borrow().is_none()) { return Err(CL_INVALID_KERNEL_ARGS); } // CL_INVALID_WORK_DIMENSION if work_dim is not a valid value (i.e. a value between 1 and // CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS). if work_dim == 0 || work_dim > q.device.max_grid_dimensions() { return Err(CL_INVALID_WORK_DIMENSION); } // we assume the application gets it right and doesn't pass shorter arrays then actually needed. let global_work_size = unsafe { kernel_work_arr_or_default(global_work_size, work_dim) }; let local_work_size = unsafe { kernel_work_arr_or_default(local_work_size, work_dim) }; let global_work_offset = unsafe { kernel_work_arr_or_default(global_work_offset, work_dim) }; let device_bits = q.device.address_bits(); let device_max = u64::MAX >> (u64::BITS - device_bits); for i in 0..work_dim as usize { let lws = local_work_size[i]; let gws = global_work_size[i]; let gwo = global_work_offset[i]; // CL_INVALID_WORK_ITEM_SIZE if the number of work-items specified in any of // local_work_size[0], … local_work_size[work_dim - 1] is greater than the corresponding // values specified by // CL_DEVICE_MAX_WORK_ITEM_SIZES[0], …, CL_DEVICE_MAX_WORK_ITEM_SIZES[work_dim - 1]. if lws > q.device.max_block_sizes()[i] { return Err(CL_INVALID_WORK_ITEM_SIZE); } // CL_INVALID_WORK_GROUP_SIZE if the work-group size must be uniform and the // local_work_size is not NULL, [...] if the global_work_size is not evenly divisible by // the local_work_size. if lws != 0 && gws % lws != 0 { return Err(CL_INVALID_WORK_GROUP_SIZE); } // CL_INVALID_WORK_GROUP_SIZE if local_work_size is specified and does not match the // required work-group size for kernel in the program source. if lws != 0 && k.work_group_size[i] != 0 && lws != k.work_group_size[i] { return Err(CL_INVALID_WORK_GROUP_SIZE); } // CL_INVALID_GLOBAL_WORK_SIZE if any of the values specified in global_work_size[0], … // global_work_size[work_dim - 1] exceed the maximum value representable by size_t on // the device on which the kernel-instance will be enqueued. if gws as u64 > device_max { return Err(CL_INVALID_GLOBAL_WORK_SIZE); } // CL_INVALID_GLOBAL_OFFSET if the value specified in global_work_size + the // corresponding values in global_work_offset for any dimensions is greater than the // maximum value representable by size t on the device on which the kernel-instance // will be enqueued if u64::checked_add(gws as u64, gwo as u64) .filter(|&x| x <= device_max) .is_none() { return Err(CL_INVALID_GLOBAL_OFFSET); } } // If global_work_size is NULL, or the value in any passed dimension is 0 then the kernel // command will trivially succeed after its event dependencies are satisfied and subsequently // update its completion event. let cb: EventSig = if global_work_size.contains(&0) { Box::new(|_, _| Ok(())) } else { k.launch( &q, work_dim, local_work_size, global_work_size, global_work_offset, )? }; create_and_queue(q, CL_COMMAND_NDRANGE_KERNEL, evs, event, false, cb) //• CL_INVALID_WORK_GROUP_SIZE if local_work_size is specified and is not consistent with the required number of sub-groups for kernel in the program source. //• CL_INVALID_WORK_GROUP_SIZE if local_work_size is specified and the total number of work-items in the work-group computed as local_work_size[0] × … local_work_size[work_dim - 1] is greater than the value specified by CL_KERNEL_WORK_GROUP_SIZE in the Kernel Object Device Queries table. //• CL_MISALIGNED_SUB_BUFFER_OFFSET if a sub-buffer object is specified as the value for an argument that is a buffer object and the offset specified when the sub-buffer object is created is not aligned to CL_DEVICE_MEM_BASE_ADDR_ALIGN value for device associated with queue. This error code //• CL_INVALID_IMAGE_SIZE if an image object is specified as an argument value and the image dimensions (image width, height, specified or compute row and/or slice pitch) are not supported by device associated with queue. //• CL_IMAGE_FORMAT_NOT_SUPPORTED if an image object is specified as an argument value and the image format (image channel order and data type) is not supported by device associated with queue. //• CL_OUT_OF_RESOURCES if there is a failure to queue the execution instance of kernel on the command-queue because of insufficient resources needed to execute the kernel. For example, the explicitly specified local_work_size causes a failure to execute the kernel because of insufficient resources such as registers or local memory. Another example would be the number of read-only image args used in kernel exceed the CL_DEVICE_MAX_READ_IMAGE_ARGS value for device or the number of write-only and read-write image args used in kernel exceed the CL_DEVICE_MAX_READ_WRITE_IMAGE_ARGS value for device or the number of samplers used in kernel exceed CL_DEVICE_MAX_SAMPLERS for device. //• CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with image or buffer objects specified as arguments to kernel. //• CL_INVALID_OPERATION if SVM pointers are passed as arguments to a kernel and the device does not support SVM or if system pointers are passed as arguments to a kernel and/or stored inside SVM allocations passed as kernel arguments and the device does not support fine grain system SVM allocations. } pub fn enqueue_task( command_queue: cl_command_queue, kernel: cl_kernel, num_events_in_wait_list: cl_uint, event_wait_list: *const cl_event, event: *mut cl_event, ) -> CLResult<()> { // clEnqueueTask is equivalent to calling clEnqueueNDRangeKernel with work_dim set to 1, // global_work_offset set to NULL, global_work_size[0] set to 1, and local_work_size[0] set to // 1. enqueue_ndrange_kernel( command_queue, kernel, 1, ptr::null(), [1, 1, 1].as_ptr(), [1, 0, 0].as_ptr(), num_events_in_wait_list, event_wait_list, event, ) } pub fn clone_kernel(source_kernel: cl_kernel) -> CLResult<cl_kernel> { let k = source_kernel.get_ref()?; Ok(cl_kernel::from_arc(Arc::new(k.clone()))) }
{ let p = program.get_arc()?; let name = c_string_to_string(kernel_name); // CL_INVALID_VALUE if kernel_name is NULL. if kernel_name.is_null() { return Err(CL_INVALID_VALUE); } // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built executable for program. if p.kernels().is_empty() { return Err(CL_INVALID_PROGRAM_EXECUTABLE); } // CL_INVALID_KERNEL_NAME if kernel_name is not found in program. if !p.kernels().contains(&name) { return Err(CL_INVALID_KERNEL_NAME); } // CL_INVALID_KERNEL_DEFINITION if the function definition for __kernel function given by // kernel_name such as the number of arguments, the argument types are not the same for all // devices for which the program executable has been built. let devs = get_devices_with_valid_build(&p)?; let kernel_args: HashSet<_> = devs.iter().map(|d| p.args(d, &name)).collect(); if kernel_args.len() != 1 { return Err(CL_INVALID_KERNEL_DEFINITION); } Ok(cl_kernel::from_arc(Kernel::new( name, p, kernel_args.into_iter().next().unwrap(), ))) }
identifier_body
kernel.rs
use crate::api::event::create_and_queue; use crate::api::icd::*; use crate::api::util::*; use crate::core::device::*; use crate::core::event::*; use crate::core::kernel::*; use crate::core::program::*; use mesa_rust_util::ptr::*; use mesa_rust_util::string::*; use rusticl_opencl_gen::*; use std::collections::HashSet; use std::os::raw::c_void; use std::ptr; use std::slice; use std::sync::Arc; impl CLInfo<cl_kernel_info> for cl_kernel { fn query(&self, q: cl_kernel_info, _: &[u8]) -> CLResult<Vec<u8>> { let kernel = self.get_ref()?; Ok(match q { CL_KERNEL_ATTRIBUTES => cl_prop::<&str>(&kernel.attributes_string), CL_KERNEL_CONTEXT => { let ptr = Arc::as_ptr(&kernel.prog.context); cl_prop::<cl_context>(cl_context::from_ptr(ptr)) } CL_KERNEL_FUNCTION_NAME => cl_prop::<&str>(&kernel.name), CL_KERNEL_NUM_ARGS => cl_prop::<cl_uint>(kernel.args.len() as cl_uint), CL_KERNEL_PROGRAM => { let ptr = Arc::as_ptr(&kernel.prog); cl_prop::<cl_program>(cl_program::from_ptr(ptr)) } CL_KERNEL_REFERENCE_COUNT => cl_prop::<cl_uint>(self.refcnt()?), // CL_INVALID_VALUE if param_name is not one of the supported values _ => return Err(CL_INVALID_VALUE), }) } } impl CLInfoObj<cl_kernel_arg_info, cl_uint> for cl_kernel { fn query(&self, idx: cl_uint, q: cl_kernel_arg_info) -> CLResult<Vec<u8>> { let kernel = self.get_ref()?; // CL_INVALID_ARG_INDEX if arg_index is not a valid argument index. if idx as usize >= kernel.args.len() { return Err(CL_INVALID_ARG_INDEX); } Ok(match *q { CL_KERNEL_ARG_ACCESS_QUALIFIER => { cl_prop::<cl_kernel_arg_access_qualifier>(kernel.access_qualifier(idx)) } CL_KERNEL_ARG_ADDRESS_QUALIFIER => { cl_prop::<cl_kernel_arg_address_qualifier>(kernel.address_qualifier(idx)) } CL_KERNEL_ARG_NAME => cl_prop::<&str>(kernel.arg_name(idx)), CL_KERNEL_ARG_TYPE_NAME => cl_prop::<&str>(kernel.arg_type_name(idx)), CL_KERNEL_ARG_TYPE_QUALIFIER => { cl_prop::<cl_kernel_arg_type_qualifier>(kernel.type_qualifier(idx)) } // CL_INVALID_VALUE if param_name is not one of the supported values _ => return Err(CL_INVALID_VALUE), }) } } impl CLInfoObj<cl_kernel_work_group_info, cl_device_id> for cl_kernel { fn query(&self, dev: cl_device_id, q: cl_kernel_work_group_info) -> CLResult<Vec<u8>> { let kernel = self.get_ref()?; // CL_INVALID_DEVICE [..] if device is NULL but there is more than one device associated with kernel. let dev = if dev.is_null() { if kernel.prog.devs.len() > 1 { return Err(CL_INVALID_DEVICE); } else { kernel.prog.devs[0].clone() } } else { dev.get_arc()? }; // CL_INVALID_DEVICE if device is not in the list of devices associated with kernel if !kernel.prog.devs.contains(&dev) { return Err(CL_INVALID_DEVICE); } Ok(match *q { CL_KERNEL_COMPILE_WORK_GROUP_SIZE => cl_prop::<[usize; 3]>(kernel.work_group_size), CL_KERNEL_LOCAL_MEM_SIZE => cl_prop::<cl_ulong>(kernel.local_mem_size(&dev)), CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE => { cl_prop::<usize>(dev.subgroups() as usize) } CL_KERNEL_PRIVATE_MEM_SIZE => cl_prop::<cl_ulong>(kernel.priv_mem_size(&dev)), // TODO CL_KERNEL_WORK_GROUP_SIZE => cl_prop::<usize>(dev.subgroups() as usize), // CL_INVALID_VALUE if param_name is not one of the supported values _ => return Err(CL_INVALID_VALUE), }) } } impl CLInfoObj<cl_kernel_sub_group_info, (cl_device_id, usize, *const c_void)> for cl_kernel { fn query( &self, (d, _input_value_size, _input_value): (cl_device_id, usize, *const c_void), _q: cl_program_build_info, ) -> CLResult<Vec<u8>> { let _kernel = self.get_ref()?; let _dev = d.get_arc()?; Err(CL_INVALID_OPERATION) } } const ZERO_ARR: [usize; 3] = [0; 3]; /// # Safety /// /// This function is only safe when called on an array of `work_dim` length unsafe fn kernel_work_arr_or_default<'a>(arr: *const usize, work_dim: cl_uint) -> &'a [usize] { if !arr.is_null() { slice::from_raw_parts(arr, work_dim as usize) } else { &ZERO_ARR } } fn get_devices_with_valid_build(p: &Arc<Program>) -> CLResult<Vec<&Arc<Device>>> { // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built executable for program. let devs: Vec<_> = p .devs .iter() .filter(|d| p.status(d) == CL_BUILD_SUCCESS as cl_build_status) .collect(); if devs.is_empty() { return Err(CL_INVALID_PROGRAM_EXECUTABLE); } Ok(devs) } pub fn create_kernel( program: cl_program, kernel_name: *const ::std::os::raw::c_char, ) -> CLResult<cl_kernel> { let p = program.get_arc()?; let name = c_string_to_string(kernel_name); // CL_INVALID_VALUE if kernel_name is NULL. if kernel_name.is_null() { return Err(CL_INVALID_VALUE); } // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built executable for program. if p.kernels().is_empty() { return Err(CL_INVALID_PROGRAM_EXECUTABLE); } // CL_INVALID_KERNEL_NAME if kernel_name is not found in program. if !p.kernels().contains(&name) { return Err(CL_INVALID_KERNEL_NAME); } // CL_INVALID_KERNEL_DEFINITION if the function definition for __kernel function given by // kernel_name such as the number of arguments, the argument types are not the same for all // devices for which the program executable has been built. let devs = get_devices_with_valid_build(&p)?; let kernel_args: HashSet<_> = devs.iter().map(|d| p.args(d, &name)).collect(); if kernel_args.len() != 1 { return Err(CL_INVALID_KERNEL_DEFINITION); } Ok(cl_kernel::from_arc(Kernel::new( name, p, kernel_args.into_iter().next().unwrap(), ))) } pub fn create_kernels_in_program( program: cl_program, num_kernels: cl_uint, kernels: *mut cl_kernel, num_kernels_ret: *mut cl_uint, ) -> CLResult<()> { let p = program.get_arc()?; let devs = get_devices_with_valid_build(&p)?; // CL_INVALID_VALUE if kernels is not NULL and num_kernels is less than the number of kernels // in program. if !kernels.is_null() && p.kernels().len() > num_kernels as usize { return Err(CL_INVALID_VALUE); } let mut num_kernels = 0; for name in p.kernels() { let kernel_args: HashSet<_> = devs.iter().map(|d| p.args(d, &name)).collect(); // Kernel objects are not created for any __kernel functions in program that do not have the // same function definition across all devices for which a program executable has been // successfully built. if kernel_args.len() != 1 { continue; } if !kernels.is_null() { // we just assume the client isn't stupid unsafe { kernels .add(num_kernels as usize) .write(cl_kernel::from_arc(Kernel::new( name, p.clone(), kernel_args.into_iter().next().unwrap(), ))); } } num_kernels += 1; } num_kernels_ret.write_checked(num_kernels); Ok(()) } pub fn set_kernel_arg( kernel: cl_kernel, arg_index: cl_uint, arg_size: usize, arg_value: *const ::std::os::raw::c_void, ) -> CLResult<()> { let k = kernel.get_arc()?; // CL_INVALID_ARG_INDEX if arg_index is not a valid argument index. if let Some(arg) = k.args.get(arg_index as usize) { // CL_INVALID_ARG_SIZE if arg_size does not match the size of the data type for an argument // that is not a memory object or if the argument is a memory object and // arg_size != sizeof(cl_mem) or if arg_size is zero and the argument is declared with the // local qualifier or if the argument is a sampler and arg_size != sizeof(cl_sampler). match arg.kind { KernelArgType::MemLocal => { if arg_size == 0 { return Err(CL_INVALID_ARG_SIZE); } } KernelArgType::MemGlobal | KernelArgType::MemConstant | KernelArgType::Image | KernelArgType::RWImage | KernelArgType::Texture =>
_ => { if arg.size != arg_size { return Err(CL_INVALID_ARG_SIZE); } } } // CL_INVALID_ARG_VALUE if arg_value specified is not a valid value. match arg.kind { // If the argument is declared with the local qualifier, the arg_value entry must be // NULL. KernelArgType::MemLocal => { if !arg_value.is_null() { return Err(CL_INVALID_ARG_VALUE); } } // If the argument is of type sampler_t, the arg_value entry must be a pointer to the // sampler object. KernelArgType::Constant | KernelArgType::Sampler => { if arg_value.is_null() { return Err(CL_INVALID_ARG_VALUE); } } _ => {} }; // let's create the arg now let arg = unsafe { if arg.dead { KernelArgValue::None } else { match arg.kind { KernelArgType::Constant => KernelArgValue::Constant( slice::from_raw_parts(arg_value.cast(), arg_size).to_vec(), ), KernelArgType::MemConstant | KernelArgType::MemGlobal => { let ptr: *const cl_mem = arg_value.cast(); if ptr.is_null() || (*ptr).is_null() { KernelArgValue::None } else { KernelArgValue::MemObject((*ptr).get_arc()?) } } KernelArgType::MemLocal => KernelArgValue::LocalMem(arg_size), KernelArgType::Image | KernelArgType::RWImage | KernelArgType::Texture => { let img: *const cl_mem = arg_value.cast(); KernelArgValue::MemObject((*img).get_arc()?) } KernelArgType::Sampler => { let ptr: *const cl_sampler = arg_value.cast(); KernelArgValue::Sampler((*ptr).get_arc()?) } } } }; k.values.get(arg_index as usize).unwrap().replace(Some(arg)); Ok(()) } else { Err(CL_INVALID_ARG_INDEX) } //• CL_INVALID_DEVICE_QUEUE for an argument declared to be of type queue_t when the specified arg_value is not a valid device queue object. This error code is missing before version 2.0. //• CL_INVALID_ARG_VALUE if the argument is an image declared with the read_only qualifier and arg_value refers to an image object created with cl_mem_flags of CL_MEM_WRITE_ONLY or if the image argument is declared with the write_only qualifier and arg_value refers to an image object created with cl_mem_flags of CL_MEM_READ_ONLY. //• CL_MAX_SIZE_RESTRICTION_EXCEEDED if the size in bytes of the memory object (if the argument is a memory object) or arg_size (if the argument is declared with local qualifier) exceeds a language- specified maximum size restriction for this argument, such as the MaxByteOffset SPIR-V decoration. This error code is missing before version 2.2. } pub fn enqueue_ndrange_kernel( command_queue: cl_command_queue, kernel: cl_kernel, work_dim: cl_uint, global_work_offset: *const usize, global_work_size: *const usize, local_work_size: *const usize, num_events_in_wait_list: cl_uint, event_wait_list: *const cl_event, event: *mut cl_event, ) -> CLResult<()> { let q = command_queue.get_arc()?; let k = kernel.get_arc()?; let evs = event_list_from_cl(&q, num_events_in_wait_list, event_wait_list)?; // CL_INVALID_CONTEXT if context associated with command_queue and kernel are not the same if q.context != k.prog.context { return Err(CL_INVALID_CONTEXT); } // CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built program executable available // for device associated with command_queue. if k.prog.status(&q.device) != CL_BUILD_SUCCESS as cl_build_status { return Err(CL_INVALID_PROGRAM_EXECUTABLE); } // CL_INVALID_KERNEL_ARGS if the kernel argument values have not been specified. if k.values.iter().any(|v| v.borrow().is_none()) { return Err(CL_INVALID_KERNEL_ARGS); } // CL_INVALID_WORK_DIMENSION if work_dim is not a valid value (i.e. a value between 1 and // CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS). if work_dim == 0 || work_dim > q.device.max_grid_dimensions() { return Err(CL_INVALID_WORK_DIMENSION); } // we assume the application gets it right and doesn't pass shorter arrays then actually needed. let global_work_size = unsafe { kernel_work_arr_or_default(global_work_size, work_dim) }; let local_work_size = unsafe { kernel_work_arr_or_default(local_work_size, work_dim) }; let global_work_offset = unsafe { kernel_work_arr_or_default(global_work_offset, work_dim) }; let device_bits = q.device.address_bits(); let device_max = u64::MAX >> (u64::BITS - device_bits); for i in 0..work_dim as usize { let lws = local_work_size[i]; let gws = global_work_size[i]; let gwo = global_work_offset[i]; // CL_INVALID_WORK_ITEM_SIZE if the number of work-items specified in any of // local_work_size[0], … local_work_size[work_dim - 1] is greater than the corresponding // values specified by // CL_DEVICE_MAX_WORK_ITEM_SIZES[0], …, CL_DEVICE_MAX_WORK_ITEM_SIZES[work_dim - 1]. if lws > q.device.max_block_sizes()[i] { return Err(CL_INVALID_WORK_ITEM_SIZE); } // CL_INVALID_WORK_GROUP_SIZE if the work-group size must be uniform and the // local_work_size is not NULL, [...] if the global_work_size is not evenly divisible by // the local_work_size. if lws != 0 && gws % lws != 0 { return Err(CL_INVALID_WORK_GROUP_SIZE); } // CL_INVALID_WORK_GROUP_SIZE if local_work_size is specified and does not match the // required work-group size for kernel in the program source. if lws != 0 && k.work_group_size[i] != 0 && lws != k.work_group_size[i] { return Err(CL_INVALID_WORK_GROUP_SIZE); } // CL_INVALID_GLOBAL_WORK_SIZE if any of the values specified in global_work_size[0], … // global_work_size[work_dim - 1] exceed the maximum value representable by size_t on // the device on which the kernel-instance will be enqueued. if gws as u64 > device_max { return Err(CL_INVALID_GLOBAL_WORK_SIZE); } // CL_INVALID_GLOBAL_OFFSET if the value specified in global_work_size + the // corresponding values in global_work_offset for any dimensions is greater than the // maximum value representable by size t on the device on which the kernel-instance // will be enqueued if u64::checked_add(gws as u64, gwo as u64) .filter(|&x| x <= device_max) .is_none() { return Err(CL_INVALID_GLOBAL_OFFSET); } } // If global_work_size is NULL, or the value in any passed dimension is 0 then the kernel // command will trivially succeed after its event dependencies are satisfied and subsequently // update its completion event. let cb: EventSig = if global_work_size.contains(&0) { Box::new(|_, _| Ok(())) } else { k.launch( &q, work_dim, local_work_size, global_work_size, global_work_offset, )? }; create_and_queue(q, CL_COMMAND_NDRANGE_KERNEL, evs, event, false, cb) //• CL_INVALID_WORK_GROUP_SIZE if local_work_size is specified and is not consistent with the required number of sub-groups for kernel in the program source. //• CL_INVALID_WORK_GROUP_SIZE if local_work_size is specified and the total number of work-items in the work-group computed as local_work_size[0] × … local_work_size[work_dim - 1] is greater than the value specified by CL_KERNEL_WORK_GROUP_SIZE in the Kernel Object Device Queries table. //• CL_MISALIGNED_SUB_BUFFER_OFFSET if a sub-buffer object is specified as the value for an argument that is a buffer object and the offset specified when the sub-buffer object is created is not aligned to CL_DEVICE_MEM_BASE_ADDR_ALIGN value for device associated with queue. This error code //• CL_INVALID_IMAGE_SIZE if an image object is specified as an argument value and the image dimensions (image width, height, specified or compute row and/or slice pitch) are not supported by device associated with queue. //• CL_IMAGE_FORMAT_NOT_SUPPORTED if an image object is specified as an argument value and the image format (image channel order and data type) is not supported by device associated with queue. //• CL_OUT_OF_RESOURCES if there is a failure to queue the execution instance of kernel on the command-queue because of insufficient resources needed to execute the kernel. For example, the explicitly specified local_work_size causes a failure to execute the kernel because of insufficient resources such as registers or local memory. Another example would be the number of read-only image args used in kernel exceed the CL_DEVICE_MAX_READ_IMAGE_ARGS value for device or the number of write-only and read-write image args used in kernel exceed the CL_DEVICE_MAX_READ_WRITE_IMAGE_ARGS value for device or the number of samplers used in kernel exceed CL_DEVICE_MAX_SAMPLERS for device. //• CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for data store associated with image or buffer objects specified as arguments to kernel. //• CL_INVALID_OPERATION if SVM pointers are passed as arguments to a kernel and the device does not support SVM or if system pointers are passed as arguments to a kernel and/or stored inside SVM allocations passed as kernel arguments and the device does not support fine grain system SVM allocations. } pub fn enqueue_task( command_queue: cl_command_queue, kernel: cl_kernel, num_events_in_wait_list: cl_uint, event_wait_list: *const cl_event, event: *mut cl_event, ) -> CLResult<()> { // clEnqueueTask is equivalent to calling clEnqueueNDRangeKernel with work_dim set to 1, // global_work_offset set to NULL, global_work_size[0] set to 1, and local_work_size[0] set to // 1. enqueue_ndrange_kernel( command_queue, kernel, 1, ptr::null(), [1, 1, 1].as_ptr(), [1, 0, 0].as_ptr(), num_events_in_wait_list, event_wait_list, event, ) } pub fn clone_kernel(source_kernel: cl_kernel) -> CLResult<cl_kernel> { let k = source_kernel.get_ref()?; Ok(cl_kernel::from_arc(Arc::new(k.clone()))) }
{ if arg_size != std::mem::size_of::<cl_mem>() { return Err(CL_INVALID_ARG_SIZE); } }
conditional_block
Faces.py
# -*- coding: utf-8 -*- from math import atan, cos, degrees, radians, sin import cv2 import dlib import face_recognition_models import numpy as np from PIL import Image # 当检测不到人脸时对人脸进行旋转的 按照如下列表的角度逐个尝试 ANGLE_LIST = [0, -45, 45] # 加载Dlib库中的人脸检测算子、ResNet模型 face_detector = dlib.get_frontal_face_detector() predictor_68_point_model = face_recognition_models.pose_predictor_model_location() pose_predictor_68_point = dlib.shape_predictor(predictor_68_point_model) predictor_5_point_model = face_recognition_models.pose_predictor_five_point_model_location() pose_predictor_5_point = dlib.shape_predictor(predictor_5_point_model) face_recognition_model = face_recognition_models.face_recognition_model_location() face_encoder = dlib.face_recognition_model_v1(face_recognition_model) class Vector(object): """ 定义2D平面的向量类 """ def __init__(self, x, y): """ 向量初始化 :param x: X值 :param y: Y值 """ self.x = x self.y = y def rotate(self, alpha): """ 将向量旋转一定的角度 无返回值 :param alpha: 要旋转的角度 :return: 无返回值 """ # print("cos:{:.2f} sin:{:.2f}".format(cos(alpha), sin(alpha))) rad_alpha = radians(alpha) x_new = self.x * cos(rad_alpha) - self.y * sin(rad_alpha) y_new = self.y * cos(rad_alpha) + self.x * sin(rad_alpha) self.x = x_new self.y = y_new return def get_point(self, center_x, center_y): result_x = center_x + self.x result_y = center_y + self.y return [result_x, result_y] def rect2css(rect): """ 将Dlib库中rect转换为(top, right, bottom, left) :param rect:Dlib库中的rect :return:(top, right, bottom, left) """ return rect.top(), rect.right(), rect.bottom(), rect.left() def css2rect(css): """ 将(top, right, bottom, left)转换为Dlib的rect对象 :param css:(top, right, bottom, left) :return:Dlib中rect对象 """ return dlib.rectangle(css[3], css[0], css[1], css[2]) def trim_css_to_bounds(css, image_shape): """ :return: 返回经过调整后的(top, right, bottom, left) """ return max(css[0], 0), min(css[1], image_shape[1]), min(css[2], image_shape[0]), max(css[3], 0) def raw_face_locations(img, number_of_times_to_upsample=1): return face_detector(img, number_of_times_to_upsample) def raw_face_landmarks(face_image, face_locations_=None, model="large"): if face_locations_ is None: face_locations_ = raw_face_locations(face_image) else: face_locations_ = [css2rect(face_location) for face_location in face_locations_] pose_predictor = pose_predictor_68_point if model == "small": pose_predictor = pose_predictor_5_point return [pose_predictor(face_image, face_location) for face_location in face_locations_] def rgb2bgr(rgb_image): """ (ndarray)将rgb通道转换为bgr通道 """ return rgb_image[..., ::-1] def bgr2rgb(bgr_image): """ (ndarray)将bgr通道转换为rgb通道 """ return bgr_image[..., ::-1] def face_encodings(face_image, known_face_locations=None, num_jitters=0): """ 得到图像中的人脸128维编码 :param face_image: RGB三通道图像(ndarray) :param known_face_locations: 已知人脸的位置 图像编码会与已知图像位置有相同序号 :param num_jitters: 计算编码时的抖动次数 较高的抖动次数会获得更稳定的编码 :return: 返回(n, 128)的ndarray数组 n为图片中人脸数量 """ raw_landmarks = raw_face_landmarks(face_image, known_face_locations, model="small") return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_jitters)) for raw_landmark_set in raw_landmarks] def face_locations(img, number_of_times_to_upsample=1): """ 返回图像中人脸的bounding boxes :param img: RGB三通道图像(ndarray) :param number_of_times_to_upsample: 对图像的上采样次数 :return: 返回包含n个人脸位置(top, right, bottom, left)的列表 """ return [trim_css_to_bounds(rect2css(face), img.shape) for face in raw_face_locations(img, number_of_times_to_upsample)] def face_distance(face_encodings_, face_to_compare): """ 求待检测的人脸编码和一组已知人脸编码的距离 返回待检测编码和已知编码一一比较得到的距离列表 :param face_encodings_:已知编码 :param face_to_compare:待比较编码 :return:待检测编码和已知编码一一比较得到的距离列表 """ if len(face_encodings_) == 0: return np.empty(0) # 欧氏距离 return np.linalg.norm(face_encodings_ - face_to_compare, axis=1) def load_image_file(file_location): """ 加载一张图片 返回一个RGB三通道的ndarray数组 :param file_location: 文件位置 """ image = Image.open(file_location) image = image.convert('RGB') scale = image.size[1] / image.size[0] image = image.resize((400, int(400 * scale)), Image.ANTIALIAS) return np.array(image) def save_image_file(file_location, image): """ 保存一张RGB通道图片 :param file_location: 保存路径 :param image: 图像矩阵 :return: """ bgr_image = rgb2bgr(image) cv2.imwrite(file_location, bgr_image) # 定义旋转rotate函数 def image_rotate(image, angle, center=None, scale=1.0): """ 对图片进行旋转 正值时顺时针旋转 负值时逆时针旋转 :param image:原图 :param angle:旋转角度 正值为顺时针旋转 负值为逆时针旋转 :param center:旋转中心 不指定时为图像中心 :param scale:图像尺度变化比率 :return:旋转过的图像 """ # 获取图像尺寸 (h, w) = image.shape[:2] # 若未指定旋转中心,则将图像中心设为旋转中心 if center is None: center = (w / 2, h / 2) # 使用opencv库中的仿射变换对图像进行旋转 transform_matrix = cv2.getRotationMatrix2D(center, -1 * angle, scale) rotated = cv2.warpAffine(image, transform_matrix, (w, h)) return rotated def get_only_face(image, min_face_area=0, upsample=0, rotate=False): """ 获取图像中像素面积最大的人脸位置(比赛场景特殊 一张图片只有一个主体) :param image:图像 :param min_face_area:最小像素面积 :param upsample: 对图像上采样的次数 :param rotate: 是否尝试对图像进行旋转 :return: 返回像素面积最大的人脸的位置(top, right, bottom, left) :return: 如果rotate为True 返回(rotated_image, alpha, top, right, bottom, left) alpha为旋转角度 :return: 检测不到人脸的时候top right bottom left的返回值都为-1 """ # 进行旋转时 if rotate: rotated_image = image # 遍历旋转角度列表 尝试从不同角度对图像进行旋转 for angle in ANGLE_LIST: if angle != 0: # 角度不为0时对图像进行旋转 rotated_image = image_rotate(image, angle) # 获取图像中所有人脸的位置 locations = face_locations(rotated_image, upsample) # 统计人脸个数,并得到像素面积最大的人脸的位置 max_pixel_area = 0 number_of_faces = len(locations) result_top, result_right, result_bottom, result_left = 0, 0, 0, 0 for location in locations: top, right, bottom, left = location pixel_area = (bottom - top) * (right - left) # 忽略面积小于min_face_area的脸 if pixel_area < min_face_area: number_of_faces -= 1 continue # 更新像素面积最大值 if pixel_area > max_pixel_area: max_pixel_area = pixel_area result_top, result_right, result_bottom, result_left = top, right, bottom, left # 检测到的人脸后 返回像素面积最大的人脸的位置 函数结束 if number_of_faces > 0: if angle != 0: print("[!]图像旋转{}°后检测到人脸".format(angle)) return rotated_image, angle, result_top, result_right, result_bottom, result_left # 多个角度旋转后仍未检测到人脸 返回(-1, -1, -1, -1) print("[-]Warning: 多角度旋转后仍未检测到人脸") return image, 0, -1, -1, -1, -1 # 不进行旋转时 else: # 得到所有人脸的位置 locations = face_locations(image, upsample) # 统计人脸个数,并得到像素面积最大的人脸的位置 max_pixel_area = 0 number_of_faces = len(locations) result_top, result_right, result_bottom, result_left = -1, -1, -1, -1 for location in locations: top, right, bottom, left = location pixel_area = (bottom - top) * (right - left) # 忽略面积小于min_face_area的脸 if pixel_area < min_face_area: number_of_faces -= 1 continue # 更新像素面积最大值 if pixel_area > max_pixel_area: max_pixel_area = pixel_area result_top, result_right, result_bottom, result_left = top, right, bottom, left return result_top, result_right, result_bottom, result_left def get_angle(point_x, point_y): """ 获取像素空间下两点斜率的角度 point_x在左边 point_y在右边的情况 :param point_x: 左边的点 :param point_y: 右边的点 :return: 角度 """ if abs(point_y[0] - point_x[0]) < 0.000001: return 90
return degrees(atan((point_x[1] - point_y[1]) / (point_y[0] - point_x[0]))) def get_stdface(image, detection_save_path=None, stdface_save_path=None): """ 输入一张RGB三通道图片 返回经过摆正并裁剪的256*256的人脸图像 检测不到的时候返回空值None :param image: 原图 :param detection_save_path: 如果需要将检测结果保存下来 请传入本值 :param stdface_save_path: 如果需要将stdface结果保存下来 请传入本值 :return: 返回stdface 检测不到时返回None """ # 拷贝一份原图用于绘制带有角度的bounding box(后续过程可能对原图进行旋转) image_copy = image.copy() # alpha是图像第一次旋转的角度 alpha = 0 # 尝试不旋转、不进行上采样的情况下获取图片上的人脸 top, right, bottom, left = get_only_face(image) # 无法检测到人脸时的自适应调整:尝试将上采样次数加大1 并允许对图像进行旋转操作 if top == -1: image, alpha, top, right, bottom, left = get_only_face(image, upsample=1, rotate=True) # 检测不到人脸 报错并返回 if top == -1: print("[-]检测不到人像") return None location = (top, right, bottom, left) # 根据人脸位置获取人脸的特征点的位置 face_landmark = face_landmarks(image, [location])[0] # 根据左眼、右眼的位置对人脸进行校正 left_eye = face_landmark['left_eye'] right_eye = face_landmark['right_eye'] # 眼睛部位六个对称点的倾斜角度 angle_list = [0, 0, 0, 0, 0, 0] for i in range(6): if i < 4: angle_list[i] = get_angle(left_eye[i], right_eye[3 - i]) elif i == 4: angle_list[i] = get_angle(left_eye[i], right_eye[5]) elif i == 5: angle_list[i] = get_angle(left_eye[i], right_eye[4]) # 六个对称点倾斜角度取平均 beta = sum(angle_list) / 6.0 # 根据beta对图像再次校正 rotated_img = image_rotate(image, beta) # 对摆正的图片再次进行人脸检测 并将人像进行裁剪 此时不需要进行旋转 top, right, bottom, left = get_only_face(rotated_img) # 由于旋转会一定比例缩小图像 需要进行上采样才能得到所有的脸 不进行旋转 if top == -1: top, right, bottom, left = get_only_face(rotated_img, upsample=1) # 如果仍然检测不到人脸 返回空值 if top == -1: return None cut_area = rotated_img[top:bottom, left:right] stdface = cv2.resize(cut_area, (256, 256), interpolation=cv2.INTER_CUBIC) # 保存stdface if stdface_save_path is not None: cv2.imwrite(stdface_save_path, rgb2bgr(stdface)) print("[+]stdface保存成功:{}".format(stdface_save_path)) # 保存人像检测结果 if detection_save_path is not None: # 保存带有角度的人脸检测图像 height, weight = image.shape[:2] # 图像尺寸 anti_angle = -1 * (alpha + beta) # 反向旋转角度 center_x, center_y = (weight // 2, height // 2) # 旋转中心坐标 # 图像中心到四个顶点的向量 vector_left_top = Vector((left - center_x), (top - center_y)) vector_right_top = Vector((right - center_x), (top - center_y)) vector_left_bottom = Vector((left - center_x), (bottom - center_y)) vector_right_bottom = Vector((right - center_x), (bottom - center_y)) # 对向量进行旋转 vector_left_top.rotate(anti_angle) vector_right_top.rotate(anti_angle) vector_left_bottom.rotate(anti_angle) vector_right_bottom.rotate(anti_angle) # 带有角度的bounding box的边缘点 point_left_top = vector_left_top.get_point(center_x, center_y) point_right_top = vector_right_top.get_point(center_x, center_y) point_left_bottom = vector_left_bottom.get_point(center_x, center_y) point_right_bottom = vector_right_bottom.get_point(center_x, center_y) # 组建要绘制的点的序列 points = np.array([point_left_top, point_right_top, point_right_bottom, point_left_bottom], np.int32) points = points.reshape((-1, 1, 2)) # 在克隆出来的图像上进行绘制 cv2.polylines(image_copy, [points], True, (15, 158, 254), 2, cv2.LINE_AA) save_image_file(detection_save_path, image_copy) return stdface def face_landmarks(face_image, face_locations_=None, model="large"): """ 输入一张图片 返回包含人脸特征点的字典的集合 人脸关键点的顺序 请查看landmark.png文件 :return: A list of dicts of face feature locations (eyes, nose, etc) """ landmarks = raw_face_landmarks(face_image, face_locations_, model) landmarks_as_tuples = [[(p.x, p.y) for p in landmark.parts()] for landmark in landmarks] if model == 'large': return [{ "chin": points[0:17], "left_eyebrow": points[17:22], "right_eyebrow": points[22:27], "nose_bridge": points[27:31], "nose_tip": points[31:36], "left_eye": points[36:42], "right_eye": points[42:48], "top_lip": points[48:55] + [points[64]] + [points[63]] + [points[62]] + [points[61]] + [points[60]], "bottom_lip": points[54:60] + [points[48]] + [points[60]] + [points[67]] + [points[66]] + [points[65]] + [ points[64]] } for points in landmarks_as_tuples] elif model == 'small': return [{ "nose_tip": [points[4]], "left_eye": points[2:4], "right_eye": points[0:2], } for points in landmarks_as_tuples] def get_similarity(distance): """ 自己拟合的从欧氏距离→相似度的函数 """ similarity = 99.0 if distance <= 0.3: dy = distance * 13.33 similarity -= dy elif distance <= 0.35: dx = distance - 0.3 dy = 100 * dx similarity = 95.0 - dy else: dx = distance - 0.5 dy = 160 * dx similarity = 90.0 - dy # 对相似度的限制 similarity = min(99.0, similarity) similarity = max(31.4, similarity) print("[ ]欧式距离:{:.4f} 拟合后相似度:{:.4f}".format(distance, similarity)) return similarity
random_line_split
Faces.py
# -*- coding: utf-8 -*- from math import atan, cos, degrees, radians, sin import cv2 import dlib import face_recognition_models import numpy as np from PIL import Image # 当检测不到人脸时对人脸进行旋转的 按照如下列表的角度逐个尝试 ANGLE_LIST = [0, -45, 45] # 加载Dlib库中的人脸检测算子、ResNet模型 face_detector = dlib.get_frontal_face_detector() predictor_68_point_model = face_recognition_models.pose_predictor_model_location() pose_predictor_68_point = dlib.shape_predictor(predictor_68_point_model) predictor_5_point_model = face_recognition_models.pose_predictor_five_point_model_location() pose_predictor_5_point = dlib.shape_predictor(predictor_5_point_model) face_recognition_model = face_recognition_models.face_recognition_model_location() face_encoder = dlib.face_recognition_model_v1(face_recognition_model) class Vector(object): """ 定义2D平面的向量类 """ def __init__(self, x, y): """ 向量初始化 :param x: X值 :param y: Y值 """ self.x = x self.y = y def rotate(self, alpha): """ 将向量旋转一定的角度 无返回值 :param alpha: 要旋转的角度 :return: 无返回值 """ # print("cos:{:.2f} sin:{:.2f}".format(cos(alpha), sin(alpha))) rad_alpha = radians(alpha) x_new = self.x * cos(rad_alpha) - self.y * sin(rad_alpha) y_new = self.y * cos(rad_alpha) + self.x * sin(rad_alpha) self.x = x_new self.y = y_new return def get_point(self, center_x, center_y): result_x = center_x + self.x result_y = center_y + self.y return [result_x, result_y] def rect2css(rect): """ 将Dlib库中rect转换为(top, right, bottom, left) :param rect:Dlib库中的rect :return:(top, right, bottom, left) """ return rect.top(), rect.right(), rect.bottom(), rect.left() def css2rect(css): """ 将(top, right, bottom, left)转换为Dlib的rect对象 :param css:(top, right, bottom, left) :return:Dlib中rect对象 """ return dlib.rectangle(css[3], css[0], css[1], css[2]) def trim_css_to_bounds(css, image_shape): """ :return: 返回经过调整后的(top, right, bottom, left) """ return max(css[0], 0), min(css[1], image_shape[1]), min(css[2], image_shape[0]), max(css[3], 0) def raw_face_locations(img, number_of_times_to_upsample=1): return face_detector(img, number_of_times_to_upsample) def raw_face_landmarks(face_image, face_locations_=None, model="large"): if face_locations_ is None: face_locations_ = raw_face_locations(face_image) else: face_locations_ = [css2rect(face_location) for face_location in face_locations_] pose_predictor = pose_predictor_68_point if model == "small": pose_predictor = pose_predictor_5_point return [pose_predictor(face_image, face_location) for face_location in face_locations_] def rgb2bgr(rgb_image): """ (ndarray)将rgb通道转换为bgr通道 """ return rgb_image[..., ::-1] def bgr2rgb(bgr_image): """ (ndarray)将bgr通道转换为rgb通道 """ return bgr_image[..., ::-1] def face_encodings(face_image, known_face_locations=None, num_jitters=0): """ 得到图像中的人脸128维编码 :param face_image: RGB三通道图像(ndarray) :param known_face_locations: 已知人脸的位置 图像编码会与已知图像位置有相同序号 :param num_jitters: 计算编码时的抖动次数 较高的抖动次数会获得更稳定的编码 :return: 返回(n, 128)的ndarray数组 n为图片中人脸数量 """ raw_landmarks = raw_face_landmarks(face_image, known_face_locations, model="small") return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_jitters)) for raw_landmark_set in raw_landmarks] def face_locations(img, number_of_times_to_upsample=1): """ 返回图像中人脸的bounding boxes :param img: RGB三通道图像(ndarray) :param number_of_times_to_upsample: 对图像的上采样次数 :return: 返回包含n个人脸位置(top, right, bottom, left)的列表 """ return [trim_css_to_bounds(rect2css(face), img.shape) for face in raw_face_locations(img, number_of_times_to_upsample)] def face_distance(face_encodings_, face_to_compare): """ 求待检测的人脸编码和一组已知人脸编码的距离 返回待检测编码和已知编码一一比较得到的距离列表 :param face_encodings_:已知编码 :param face_to_compare:待比较编码 :return:待检测编码和已知编码一一比较得到的距离列表 """ if len(face_encodings_) == 0: return np.empty(0) # 欧氏距离 return np.linalg.norm(face_encodings_ - face_to_compare, axis=1) def load_image_file(file_location): """ 加载一张图片 返回一个RGB三通道的ndarray数组 :param file_location: 文件位置 """ image = Image.open(file_location) image = image.convert('RGB') scale = image.size[1] / image.size[0] image = image.resize((400, int(400 * scale)), Image.ANTIALIAS) return np.array(image) def save_image_file(file_location, image): """ 保存一张RGB通道图片 :param file_location: 保存路径 :param image: 图像矩阵 :return: """ bgr_image = rgb2bgr(image) cv2.imwrite(file_location, bgr_image) # 定义旋转rotate函数 def image_rotate(image, angle, center=None, scale=1.0): """ 对图片进行旋转 正值时顺时针旋转 负值时逆时针旋转 :param image:原图 :param angle:旋转角度 正值为顺时针旋转 负值为逆时针旋转 :param center:旋转中心 不指定时为图像中心 :param scale:图像尺度变化比率 :return:旋转过的图像 """ # 获取图像尺寸 (h, w) = image.shape[:2] # 若未指定旋转中心,则将图像中心设为旋转中心 if center is None: center = (w / 2, h / 2) # 使用opencv库中的仿射变换对图像进行旋转 transform_matrix = cv2.getRotationMatrix2D(center, -1 * angle, scale) rotated = cv2.warpAffine(image, transform_matrix, (w, h)) return rotated def get_only_face(image, min_face_area=0, upsample=0, rotate=False): """ 获取图像中像素面积最大的人脸位置(比赛场景特殊 一张图片只有一个主体) :param image:图像 :param min_face_area:最小像素面积 :param upsample: 对图像上采样的次数 :param rotate: 是否尝试对图像进行旋转 :return: 返回像素面积最大的人脸的位置(top, right, bottom, left) :return: 如果rotate为True 返回(rotated_image, alpha, top, right, bottom, left) alpha为旋转角度 :return: 检测不到人脸的时候top right bottom left的返回值都为-1 """ # 进行旋转时 if rotate: rotated_image = image # 遍历旋转角度列表 尝试从不同角度对图像进行旋转 for angle in ANGLE_LIST: if angle != 0: # 角度不为0时对图像进行旋转 rotated_image = image_rotate(image, angle) # 获取图像中所有人脸的位置 locations = face_locations(rotated_image, upsample) # 统计人脸个数,并得到像素面积最大的人脸的位置 max_pixel_area = 0 number_of_faces = len(locations) result_top, result_right, result_bottom, result_left = 0, 0, 0, 0 for location in locations: top, right, bottom, left = location pixel_area = (bottom - top) * (right - left) # 忽略面积小于min_face_area的脸 if pixel_area < min_face_area: number_of_faces -= 1 continue # 更新像素面积最大值 if pixel_area > max_pixel_area: max_pixel_area = pixel_area result_top, result_right, result_bottom, result_left = top, right, bottom, left # 检测到的人脸后 返回像素面积最大的人脸的位置 函数结束 if number_of_faces > 0: if angle != 0: print("[!]图像旋转{}°后检测到人脸".format(angle)) return rotated_image, angle, result_top, result_right, result_bottom, result_left # 多个角度旋转后仍未检测到人脸 返回(-1, -1, -1, -1) print("[-]Warning: 多角度旋转后仍未检测到人脸")
不进行旋转时 else: # 得到所有人脸的位置 locations = face_locations(image, upsample) # 统计人脸个数,并得到像素面积最大的人脸的位置 max_pixel_area = 0 number_of_faces = len(locations) result_top, result_right, result_bottom, result_left = -1, -1, -1, -1 for location in locations: top, right, bottom, left = location pixel_area = (bottom - top) * (right - left) # 忽略面积小于min_face_area的脸 if pixel_area < min_face_area: number_of_faces -= 1 continue # 更新像素面积最大值 if pixel_area > max_pixel_area: max_pixel_area = pixel_area result_top, result_right, result_bottom, result_left = top, right, bottom, left return result_top, result_right, result_bottom, result_left def get_angle(point_x, point_y): """ 获取像素空间下两点斜率的角度 point_x在左边 point_y在右边的情况 :param point_x: 左边的点 :param point_y: 右边的点 :return: 角度 """ if abs(point_y[0] - point_x[0]) < 0.000001: return 90 return degrees(atan((point_x[1] - point_y[1]) / (point_y[0] - point_x[0]))) def get_stdface(image, detection_save_path=None, stdface_save_path=None): """ 输入一张RGB三通道图片 返回经过摆正并裁剪的256*256的人脸图像 检测不到的时候返回空值None :param image: 原图 :param detection_save_path: 如果需要将检测结果保存下来 请传入本值 :param stdface_save_path: 如果需要将stdface结果保存下来 请传入本值 :return: 返回stdface 检测不到时返回None """ # 拷贝一份原图用于绘制带有角度的bounding box(后续过程可能对原图进行旋转) image_copy = image.copy() # alpha是图像第一次旋转的角度 alpha = 0 # 尝试不旋转、不进行上采样的情况下获取图片上的人脸 top, right, bottom, left = get_only_face(image) # 无法检测到人脸时的自适应调整:尝试将上采样次数加大1 并允许对图像进行旋转操作 if top == -1: image, alpha, top, right, bottom, left = get_only_face(image, upsample=1, rotate=True) # 检测不到人脸 报错并返回 if top == -1: print("[-]检测不到人像") return None location = (top, right, bottom, left) # 根据人脸位置获取人脸的特征点的位置 face_landmark = face_landmarks(image, [location])[0] # 根据左眼、右眼的位置对人脸进行校正 left_eye = face_landmark['left_eye'] right_eye = face_landmark['right_eye'] # 眼睛部位六个对称点的倾斜角度 angle_list = [0, 0, 0, 0, 0, 0] for i in range(6): if i < 4: angle_list[i] = get_angle(left_eye[i], right_eye[3 - i]) elif i == 4: angle_list[i] = get_angle(left_eye[i], right_eye[5]) elif i == 5: angle_list[i] = get_angle(left_eye[i], right_eye[4]) # 六个对称点倾斜角度取平均 beta = sum(angle_list) / 6.0 # 根据beta对图像再次校正 rotated_img = image_rotate(image, beta) # 对摆正的图片再次进行人脸检测 并将人像进行裁剪 此时不需要进行旋转 top, right, bottom, left = get_only_face(rotated_img) # 由于旋转会一定比例缩小图像 需要进行上采样才能得到所有的脸 不进行旋转 if top == -1: top, right, bottom, left = get_only_face(rotated_img, upsample=1) # 如果仍然检测不到人脸 返回空值 if top == -1: return None cut_area = rotated_img[top:bottom, left:right] stdface = cv2.resize(cut_area, (256, 256), interpolation=cv2.INTER_CUBIC) # 保存stdface if stdface_save_path is not None: cv2.imwrite(stdface_save_path, rgb2bgr(stdface)) print("[+]stdface保存成功:{}".format(stdface_save_path)) # 保存人像检测结果 if detection_save_path is not None: # 保存带有角度的人脸检测图像 height, weight = image.shape[:2] # 图像尺寸 anti_angle = -1 * (alpha + beta) # 反向旋转角度 center_x, center_y = (weight // 2, height // 2) # 旋转中心坐标 # 图像中心到四个顶点的向量 vector_left_top = Vector((left - center_x), (top - center_y)) vector_right_top = Vector((right - center_x), (top - center_y)) vector_left_bottom = Vector((left - center_x), (bottom - center_y)) vector_right_bottom = Vector((right - center_x), (bottom - center_y)) # 对向量进行旋转 vector_left_top.rotate(anti_angle) vector_right_top.rotate(anti_angle) vector_left_bottom.rotate(anti_angle) vector_right_bottom.rotate(anti_angle) # 带有角度的bounding box的边缘点 point_left_top = vector_left_top.get_point(center_x, center_y) point_right_top = vector_right_top.get_point(center_x, center_y) point_left_bottom = vector_left_bottom.get_point(center_x, center_y) point_right_bottom = vector_right_bottom.get_point(center_x, center_y) # 组建要绘制的点的序列 points = np.array([point_left_top, point_right_top, point_right_bottom, point_left_bottom], np.int32) points = points.reshape((-1, 1, 2)) # 在克隆出来的图像上进行绘制 cv2.polylines(image_copy, [points], True, (15, 158, 254), 2, cv2.LINE_AA) save_image_file(detection_save_path, image_copy) return stdface def face_landmarks(face_image, face_locations_=None, model="large"): """ 输入一张图片 返回包含人脸特征点的字典的集合 人脸关键点的顺序 请查看landmark.png文件 :return: A list of dicts of face feature locations (eyes, nose, etc) """ landmarks = raw_face_landmarks(face_image, face_locations_, model) landmarks_as_tuples = [[(p.x, p.y) for p in landmark.parts()] for landmark in landmarks] if model == 'large': return [{ "chin": points[0:17], "left_eyebrow": points[17:22], "right_eyebrow": points[22:27], "nose_bridge": points[27:31], "nose_tip": points[31:36], "left_eye": points[36:42], "right_eye": points[42:48], "top_lip": points[48:55] + [points[64]] + [points[63]] + [points[62]] + [points[61]] + [points[60]], "bottom_lip": points[54:60] + [points[48]] + [points[60]] + [points[67]] + [points[66]] + [points[65]] + [ points[64]] } for points in landmarks_as_tuples] elif model == 'small': return [{ "nose_tip": [points[4]], "left_eye": points[2:4], "right_eye": points[0:2], } for points in landmarks_as_tuples] def get_similarity(distance): """ 自己拟合的从欧氏距离→相似度的函数 """ similarity = 99.0 if distance <= 0.3: dy = distance * 13.33 similarity -= dy elif distance <= 0.35: dx = distance - 0.3 dy = 100 * dx similarity = 95.0 - dy else: dx = distance - 0.5 dy = 160 * dx similarity = 90.0 - dy # 对相似度的限制 similarity = min(99.0, similarity) similarity = max(31.4, similarity) print("[ ]欧式距离:{:.4f} 拟合后相似度:{:.4f}".format(distance, similarity)) return similarity
return image, 0, -1, -1, -1, -1 #
conditional_block
Faces.py
# -*- coding: utf-8 -*- from math import atan, cos, degrees, radians, sin import cv2 import dlib import face_recognition_models import numpy as np from PIL import Image # 当检测不到人脸时对人脸进行旋转的 按照如下列表的角度逐个尝试 ANGLE_LIST = [0, -45, 45] # 加载Dlib库中的人脸检测算子、ResNet模型 face_detector = dlib.get_frontal_face_detector() predictor_68_point_model = face_recognition_models.pose_predictor_model_location() pose_predictor_68_point = dlib.shape_predictor(predictor_68_point_model) predictor_5_point_model = face_recognition_models.pose_predictor_five_point_model_location() pose_predictor_5_point = dlib.shape_predictor(predictor_5_point_model) face_recognition_model = face_recognition_models.face_recognition_model_location() face_encoder = dlib.face_recognition_model_v1(face_recognition_model) class Vector(object): """ 定义2D平面的向量类 """ def __init__(self, x, y): """ 向量初始化 :param x: X值 :param y: Y值 """ self.x = x self.y = y def rotate(self, alpha): """ 将向量旋转一定的角度 无返回值 :param alpha: 要旋转的角度 :return: 无返回值 """ # print("cos:{:.2f} sin:{:.2f}".format(cos(alpha), sin(alpha))) rad_alpha = radians(alpha) x_new = self.x * cos(rad_alpha) - self.y * sin(rad_alpha) y_new = self.y * cos(rad_alpha) + self.x * sin(rad_alpha) self.x = x_new self.y = y_new return def get_point(self, center_x, center_y): result_x = center_x + self.x result_y = center_y + self.y return [result_x, result_y] def rect2css(rect): """ 将Dlib库中rect转换为(top, right, bottom, left) :param rect:Dlib库中的rect :return:(top, right, bottom, left) """ return rect.top(), rect.right(), rect.bottom(), rect.left() def css2rect(css): """ 将(top, right, bottom, left)转换为Dlib的rect对象 :param css:(top, right, bottom, left) :return:Dlib中rect对象 """ return dlib.rectangle(css[3], css[0], css[1], css[2]) def trim_css_to_bounds(css, image_shape): """ :return: 返回经过调整后的(top, right, bottom, left) """ return max(css[0], 0), min(css[1], image_shape[1]), min(css[2], image_shape[0]), max(css[3], 0) def raw_face_locations(img, number_of_times_to_upsample=1): return face_detector(img, number_of_times_to_upsample) def raw_face_landmarks(face_image, face_locations_=None, model="large"): if face_locations_ is None: face_locations_ = raw_face_locations(face_image)
cation) for face_location in face_locations_] pose_predictor = pose_predictor_68_point if model == "small": pose_predictor = pose_predictor_5_point return [pose_predictor(face_image, face_location) for face_location in face_locations_] def rgb2bgr(rgb_image): """ (ndarray)将rgb通道转换为bgr通道 """ return rgb_image[..., ::-1] def bgr2rgb(bgr_image): """ (ndarray)将bgr通道转换为rgb通道 """ return bgr_image[..., ::-1] def face_encodings(face_image, known_face_locations=None, num_jitters=0): """ 得到图像中的人脸128维编码 :param face_image: RGB三通道图像(ndarray) :param known_face_locations: 已知人脸的位置 图像编码会与已知图像位置有相同序号 :param num_jitters: 计算编码时的抖动次数 较高的抖动次数会获得更稳定的编码 :return: 返回(n, 128)的ndarray数组 n为图片中人脸数量 """ raw_landmarks = raw_face_landmarks(face_image, known_face_locations, model="small") return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_jitters)) for raw_landmark_set in raw_landmarks] def face_locations(img, number_of_times_to_upsample=1): """ 返回图像中人脸的bounding boxes :param img: RGB三通道图像(ndarray) :param number_of_times_to_upsample: 对图像的上采样次数 :return: 返回包含n个人脸位置(top, right, bottom, left)的列表 """ return [trim_css_to_bounds(rect2css(face), img.shape) for face in raw_face_locations(img, number_of_times_to_upsample)] def face_distance(face_encodings_, face_to_compare): """ 求待检测的人脸编码和一组已知人脸编码的距离 返回待检测编码和已知编码一一比较得到的距离列表 :param face_encodings_:已知编码 :param face_to_compare:待比较编码 :return:待检测编码和已知编码一一比较得到的距离列表 """ if len(face_encodings_) == 0: return np.empty(0) # 欧氏距离 return np.linalg.norm(face_encodings_ - face_to_compare, axis=1) def load_image_file(file_location): """ 加载一张图片 返回一个RGB三通道的ndarray数组 :param file_location: 文件位置 """ image = Image.open(file_location) image = image.convert('RGB') scale = image.size[1] / image.size[0] image = image.resize((400, int(400 * scale)), Image.ANTIALIAS) return np.array(image) def save_image_file(file_location, image): """ 保存一张RGB通道图片 :param file_location: 保存路径 :param image: 图像矩阵 :return: """ bgr_image = rgb2bgr(image) cv2.imwrite(file_location, bgr_image) # 定义旋转rotate函数 def image_rotate(image, angle, center=None, scale=1.0): """ 对图片进行旋转 正值时顺时针旋转 负值时逆时针旋转 :param image:原图 :param angle:旋转角度 正值为顺时针旋转 负值为逆时针旋转 :param center:旋转中心 不指定时为图像中心 :param scale:图像尺度变化比率 :return:旋转过的图像 """ # 获取图像尺寸 (h, w) = image.shape[:2] # 若未指定旋转中心,则将图像中心设为旋转中心 if center is None: center = (w / 2, h / 2) # 使用opencv库中的仿射变换对图像进行旋转 transform_matrix = cv2.getRotationMatrix2D(center, -1 * angle, scale) rotated = cv2.warpAffine(image, transform_matrix, (w, h)) return rotated def get_only_face(image, min_face_area=0, upsample=0, rotate=False): """ 获取图像中像素面积最大的人脸位置(比赛场景特殊 一张图片只有一个主体) :param image:图像 :param min_face_area:最小像素面积 :param upsample: 对图像上采样的次数 :param rotate: 是否尝试对图像进行旋转 :return: 返回像素面积最大的人脸的位置(top, right, bottom, left) :return: 如果rotate为True 返回(rotated_image, alpha, top, right, bottom, left) alpha为旋转角度 :return: 检测不到人脸的时候top right bottom left的返回值都为-1 """ # 进行旋转时 if rotate: rotated_image = image # 遍历旋转角度列表 尝试从不同角度对图像进行旋转 for angle in ANGLE_LIST: if angle != 0: # 角度不为0时对图像进行旋转 rotated_image = image_rotate(image, angle) # 获取图像中所有人脸的位置 locations = face_locations(rotated_image, upsample) # 统计人脸个数,并得到像素面积最大的人脸的位置 max_pixel_area = 0 number_of_faces = len(locations) result_top, result_right, result_bottom, result_left = 0, 0, 0, 0 for location in locations: top, right, bottom, left = location pixel_area = (bottom - top) * (right - left) # 忽略面积小于min_face_area的脸 if pixel_area < min_face_area: number_of_faces -= 1 continue # 更新像素面积最大值 if pixel_area > max_pixel_area: max_pixel_area = pixel_area result_top, result_right, result_bottom, result_left = top, right, bottom, left # 检测到的人脸后 返回像素面积最大的人脸的位置 函数结束 if number_of_faces > 0: if angle != 0: print("[!]图像旋转{}°后检测到人脸".format(angle)) return rotated_image, angle, result_top, result_right, result_bottom, result_left # 多个角度旋转后仍未检测到人脸 返回(-1, -1, -1, -1) print("[-]Warning: 多角度旋转后仍未检测到人脸") return image, 0, -1, -1, -1, -1 # 不进行旋转时 else: # 得到所有人脸的位置 locations = face_locations(image, upsample) # 统计人脸个数,并得到像素面积最大的人脸的位置 max_pixel_area = 0 number_of_faces = len(locations) result_top, result_right, result_bottom, result_left = -1, -1, -1, -1 for location in locations: top, right, bottom, left = location pixel_area = (bottom - top) * (right - left) # 忽略面积小于min_face_area的脸 if pixel_area < min_face_area: number_of_faces -= 1 continue # 更新像素面积最大值 if pixel_area > max_pixel_area: max_pixel_area = pixel_area result_top, result_right, result_bottom, result_left = top, right, bottom, left return result_top, result_right, result_bottom, result_left def get_angle(point_x, point_y): """ 获取像素空间下两点斜率的角度 point_x在左边 point_y在右边的情况 :param point_x: 左边的点 :param point_y: 右边的点 :return: 角度 """ if abs(point_y[0] - point_x[0]) < 0.000001: return 90 return degrees(atan((point_x[1] - point_y[1]) / (point_y[0] - point_x[0]))) def get_stdface(image, detection_save_path=None, stdface_save_path=None): """ 输入一张RGB三通道图片 返回经过摆正并裁剪的256*256的人脸图像 检测不到的时候返回空值None :param image: 原图 :param detection_save_path: 如果需要将检测结果保存下来 请传入本值 :param stdface_save_path: 如果需要将stdface结果保存下来 请传入本值 :return: 返回stdface 检测不到时返回None """ # 拷贝一份原图用于绘制带有角度的bounding box(后续过程可能对原图进行旋转) image_copy = image.copy() # alpha是图像第一次旋转的角度 alpha = 0 # 尝试不旋转、不进行上采样的情况下获取图片上的人脸 top, right, bottom, left = get_only_face(image) # 无法检测到人脸时的自适应调整:尝试将上采样次数加大1 并允许对图像进行旋转操作 if top == -1: image, alpha, top, right, bottom, left = get_only_face(image, upsample=1, rotate=True) # 检测不到人脸 报错并返回 if top == -1: print("[-]检测不到人像") return None location = (top, right, bottom, left) # 根据人脸位置获取人脸的特征点的位置 face_landmark = face_landmarks(image, [location])[0] # 根据左眼、右眼的位置对人脸进行校正 left_eye = face_landmark['left_eye'] right_eye = face_landmark['right_eye'] # 眼睛部位六个对称点的倾斜角度 angle_list = [0, 0, 0, 0, 0, 0] for i in range(6): if i < 4: angle_list[i] = get_angle(left_eye[i], right_eye[3 - i]) elif i == 4: angle_list[i] = get_angle(left_eye[i], right_eye[5]) elif i == 5: angle_list[i] = get_angle(left_eye[i], right_eye[4]) # 六个对称点倾斜角度取平均 beta = sum(angle_list) / 6.0 # 根据beta对图像再次校正 rotated_img = image_rotate(image, beta) # 对摆正的图片再次进行人脸检测 并将人像进行裁剪 此时不需要进行旋转 top, right, bottom, left = get_only_face(rotated_img) # 由于旋转会一定比例缩小图像 需要进行上采样才能得到所有的脸 不进行旋转 if top == -1: top, right, bottom, left = get_only_face(rotated_img, upsample=1) # 如果仍然检测不到人脸 返回空值 if top == -1: return None cut_area = rotated_img[top:bottom, left:right] stdface = cv2.resize(cut_area, (256, 256), interpolation=cv2.INTER_CUBIC) # 保存stdface if stdface_save_path is not None: cv2.imwrite(stdface_save_path, rgb2bgr(stdface)) print("[+]stdface保存成功:{}".format(stdface_save_path)) # 保存人像检测结果 if detection_save_path is not None: # 保存带有角度的人脸检测图像 height, weight = image.shape[:2] # 图像尺寸 anti_angle = -1 * (alpha + beta) # 反向旋转角度 center_x, center_y = (weight // 2, height // 2) # 旋转中心坐标 # 图像中心到四个顶点的向量 vector_left_top = Vector((left - center_x), (top - center_y)) vector_right_top = Vector((right - center_x), (top - center_y)) vector_left_bottom = Vector((left - center_x), (bottom - center_y)) vector_right_bottom = Vector((right - center_x), (bottom - center_y)) # 对向量进行旋转 vector_left_top.rotate(anti_angle) vector_right_top.rotate(anti_angle) vector_left_bottom.rotate(anti_angle) vector_right_bottom.rotate(anti_angle) # 带有角度的bounding box的边缘点 point_left_top = vector_left_top.get_point(center_x, center_y) point_right_top = vector_right_top.get_point(center_x, center_y) point_left_bottom = vector_left_bottom.get_point(center_x, center_y) point_right_bottom = vector_right_bottom.get_point(center_x, center_y) # 组建要绘制的点的序列 points = np.array([point_left_top, point_right_top, point_right_bottom, point_left_bottom], np.int32) points = points.reshape((-1, 1, 2)) # 在克隆出来的图像上进行绘制 cv2.polylines(image_copy, [points], True, (15, 158, 254), 2, cv2.LINE_AA) save_image_file(detection_save_path, image_copy) return stdface def face_landmarks(face_image, face_locations_=None, model="large"): """ 输入一张图片 返回包含人脸特征点的字典的集合 人脸关键点的顺序 请查看landmark.png文件 :return: A list of dicts of face feature locations (eyes, nose, etc) """ landmarks = raw_face_landmarks(face_image, face_locations_, model) landmarks_as_tuples = [[(p.x, p.y) for p in landmark.parts()] for landmark in landmarks] if model == 'large': return [{ "chin": points[0:17], "left_eyebrow": points[17:22], "right_eyebrow": points[22:27], "nose_bridge": points[27:31], "nose_tip": points[31:36], "left_eye": points[36:42], "right_eye": points[42:48], "top_lip": points[48:55] + [points[64]] + [points[63]] + [points[62]] + [points[61]] + [points[60]], "bottom_lip": points[54:60] + [points[48]] + [points[60]] + [points[67]] + [points[66]] + [points[65]] + [ points[64]] } for points in landmarks_as_tuples] elif model == 'small': return [{ "nose_tip": [points[4]], "left_eye": points[2:4], "right_eye": points[0:2], } for points in landmarks_as_tuples] def get_similarity(distance): """ 自己拟合的从欧氏距离→相似度的函数 """ similarity = 99.0 if distance <= 0.3: dy = distance * 13.33 similarity -= dy elif distance <= 0.35: dx = distance - 0.3 dy = 100 * dx similarity = 95.0 - dy else: dx = distance - 0.5 dy = 160 * dx similarity = 90.0 - dy # 对相似度的限制 similarity = min(99.0, similarity) similarity = max(31.4, similarity) print("[ ]欧式距离:{:.4f} 拟合后相似度:{:.4f}".format(distance, similarity)) return similarity
else: face_locations_ = [css2rect(face_lo
identifier_body
Faces.py
# -*- coding: utf-8 -*- from math import atan, cos, degrees, radians, sin import cv2 import dlib import face_recognition_models import numpy as np from PIL import Image # 当检测不到人脸时对人脸进行旋转的 按照如下列表的角度逐个尝试 ANGLE_LIST = [0, -45, 45] # 加载Dlib库中的人脸检测算子、ResNet模型 face_detector = dlib.get_frontal_face_detector() predictor_68_point_model = face_recognition_models.pose_predictor_model_location() pose_predictor_68_point = dlib.shape_predictor(predictor_68_point_model) predictor_5_point_model = face_recognition_models.pose_predictor_five_point_model_location() pose_predictor_5_point = dlib.shape_predictor(predictor_5_point_model) face_recognition_model = face_recognition_models.face_recognition_model_location() face_encoder = dlib.face_recognition_model_v1(face_recognition_model) class Vector(object): """ 定义2D平面的向量类 """ def __init__(self, x, y):
向量初始化 :param x: X值 :param y: Y值 """ self.x = x self.y = y def rotate(self, alpha): """ 将向量旋转一定的角度 无返回值 :param alpha: 要旋转的角度 :return: 无返回值 """ # print("cos:{:.2f} sin:{:.2f}".format(cos(alpha), sin(alpha))) rad_alpha = radians(alpha) x_new = self.x * cos(rad_alpha) - self.y * sin(rad_alpha) y_new = self.y * cos(rad_alpha) + self.x * sin(rad_alpha) self.x = x_new self.y = y_new return def get_point(self, center_x, center_y): result_x = center_x + self.x result_y = center_y + self.y return [result_x, result_y] def rect2css(rect): """ 将Dlib库中rect转换为(top, right, bottom, left) :param rect:Dlib库中的rect :return:(top, right, bottom, left) """ return rect.top(), rect.right(), rect.bottom(), rect.left() def css2rect(css): """ 将(top, right, bottom, left)转换为Dlib的rect对象 :param css:(top, right, bottom, left) :return:Dlib中rect对象 """ return dlib.rectangle(css[3], css[0], css[1], css[2]) def trim_css_to_bounds(css, image_shape): """ :return: 返回经过调整后的(top, right, bottom, left) """ return max(css[0], 0), min(css[1], image_shape[1]), min(css[2], image_shape[0]), max(css[3], 0) def raw_face_locations(img, number_of_times_to_upsample=1): return face_detector(img, number_of_times_to_upsample) def raw_face_landmarks(face_image, face_locations_=None, model="large"): if face_locations_ is None: face_locations_ = raw_face_locations(face_image) else: face_locations_ = [css2rect(face_location) for face_location in face_locations_] pose_predictor = pose_predictor_68_point if model == "small": pose_predictor = pose_predictor_5_point return [pose_predictor(face_image, face_location) for face_location in face_locations_] def rgb2bgr(rgb_image): """ (ndarray)将rgb通道转换为bgr通道 """ return rgb_image[..., ::-1] def bgr2rgb(bgr_image): """ (ndarray)将bgr通道转换为rgb通道 """ return bgr_image[..., ::-1] def face_encodings(face_image, known_face_locations=None, num_jitters=0): """ 得到图像中的人脸128维编码 :param face_image: RGB三通道图像(ndarray) :param known_face_locations: 已知人脸的位置 图像编码会与已知图像位置有相同序号 :param num_jitters: 计算编码时的抖动次数 较高的抖动次数会获得更稳定的编码 :return: 返回(n, 128)的ndarray数组 n为图片中人脸数量 """ raw_landmarks = raw_face_landmarks(face_image, known_face_locations, model="small") return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_jitters)) for raw_landmark_set in raw_landmarks] def face_locations(img, number_of_times_to_upsample=1): """ 返回图像中人脸的bounding boxes :param img: RGB三通道图像(ndarray) :param number_of_times_to_upsample: 对图像的上采样次数 :return: 返回包含n个人脸位置(top, right, bottom, left)的列表 """ return [trim_css_to_bounds(rect2css(face), img.shape) for face in raw_face_locations(img, number_of_times_to_upsample)] def face_distance(face_encodings_, face_to_compare): """ 求待检测的人脸编码和一组已知人脸编码的距离 返回待检测编码和已知编码一一比较得到的距离列表 :param face_encodings_:已知编码 :param face_to_compare:待比较编码 :return:待检测编码和已知编码一一比较得到的距离列表 """ if len(face_encodings_) == 0: return np.empty(0) # 欧氏距离 return np.linalg.norm(face_encodings_ - face_to_compare, axis=1) def load_image_file(file_location): """ 加载一张图片 返回一个RGB三通道的ndarray数组 :param file_location: 文件位置 """ image = Image.open(file_location) image = image.convert('RGB') scale = image.size[1] / image.size[0] image = image.resize((400, int(400 * scale)), Image.ANTIALIAS) return np.array(image) def save_image_file(file_location, image): """ 保存一张RGB通道图片 :param file_location: 保存路径 :param image: 图像矩阵 :return: """ bgr_image = rgb2bgr(image) cv2.imwrite(file_location, bgr_image) # 定义旋转rotate函数 def image_rotate(image, angle, center=None, scale=1.0): """ 对图片进行旋转 正值时顺时针旋转 负值时逆时针旋转 :param image:原图 :param angle:旋转角度 正值为顺时针旋转 负值为逆时针旋转 :param center:旋转中心 不指定时为图像中心 :param scale:图像尺度变化比率 :return:旋转过的图像 """ # 获取图像尺寸 (h, w) = image.shape[:2] # 若未指定旋转中心,则将图像中心设为旋转中心 if center is None: center = (w / 2, h / 2) # 使用opencv库中的仿射变换对图像进行旋转 transform_matrix = cv2.getRotationMatrix2D(center, -1 * angle, scale) rotated = cv2.warpAffine(image, transform_matrix, (w, h)) return rotated def get_only_face(image, min_face_area=0, upsample=0, rotate=False): """ 获取图像中像素面积最大的人脸位置(比赛场景特殊 一张图片只有一个主体) :param image:图像 :param min_face_area:最小像素面积 :param upsample: 对图像上采样的次数 :param rotate: 是否尝试对图像进行旋转 :return: 返回像素面积最大的人脸的位置(top, right, bottom, left) :return: 如果rotate为True 返回(rotated_image, alpha, top, right, bottom, left) alpha为旋转角度 :return: 检测不到人脸的时候top right bottom left的返回值都为-1 """ # 进行旋转时 if rotate: rotated_image = image # 遍历旋转角度列表 尝试从不同角度对图像进行旋转 for angle in ANGLE_LIST: if angle != 0: # 角度不为0时对图像进行旋转 rotated_image = image_rotate(image, angle) # 获取图像中所有人脸的位置 locations = face_locations(rotated_image, upsample) # 统计人脸个数,并得到像素面积最大的人脸的位置 max_pixel_area = 0 number_of_faces = len(locations) result_top, result_right, result_bottom, result_left = 0, 0, 0, 0 for location in locations: top, right, bottom, left = location pixel_area = (bottom - top) * (right - left) # 忽略面积小于min_face_area的脸 if pixel_area < min_face_area: number_of_faces -= 1 continue # 更新像素面积最大值 if pixel_area > max_pixel_area: max_pixel_area = pixel_area result_top, result_right, result_bottom, result_left = top, right, bottom, left # 检测到的人脸后 返回像素面积最大的人脸的位置 函数结束 if number_of_faces > 0: if angle != 0: print("[!]图像旋转{}°后检测到人脸".format(angle)) return rotated_image, angle, result_top, result_right, result_bottom, result_left # 多个角度旋转后仍未检测到人脸 返回(-1, -1, -1, -1) print("[-]Warning: 多角度旋转后仍未检测到人脸") return image, 0, -1, -1, -1, -1 # 不进行旋转时 else: # 得到所有人脸的位置 locations = face_locations(image, upsample) # 统计人脸个数,并得到像素面积最大的人脸的位置 max_pixel_area = 0 number_of_faces = len(locations) result_top, result_right, result_bottom, result_left = -1, -1, -1, -1 for location in locations: top, right, bottom, left = location pixel_area = (bottom - top) * (right - left) # 忽略面积小于min_face_area的脸 if pixel_area < min_face_area: number_of_faces -= 1 continue # 更新像素面积最大值 if pixel_area > max_pixel_area: max_pixel_area = pixel_area result_top, result_right, result_bottom, result_left = top, right, bottom, left return result_top, result_right, result_bottom, result_left def get_angle(point_x, point_y): """ 获取像素空间下两点斜率的角度 point_x在左边 point_y在右边的情况 :param point_x: 左边的点 :param point_y: 右边的点 :return: 角度 """ if abs(point_y[0] - point_x[0]) < 0.000001: return 90 return degrees(atan((point_x[1] - point_y[1]) / (point_y[0] - point_x[0]))) def get_stdface(image, detection_save_path=None, stdface_save_path=None): """ 输入一张RGB三通道图片 返回经过摆正并裁剪的256*256的人脸图像 检测不到的时候返回空值None :param image: 原图 :param detection_save_path: 如果需要将检测结果保存下来 请传入本值 :param stdface_save_path: 如果需要将stdface结果保存下来 请传入本值 :return: 返回stdface 检测不到时返回None """ # 拷贝一份原图用于绘制带有角度的bounding box(后续过程可能对原图进行旋转) image_copy = image.copy() # alpha是图像第一次旋转的角度 alpha = 0 # 尝试不旋转、不进行上采样的情况下获取图片上的人脸 top, right, bottom, left = get_only_face(image) # 无法检测到人脸时的自适应调整:尝试将上采样次数加大1 并允许对图像进行旋转操作 if top == -1: image, alpha, top, right, bottom, left = get_only_face(image, upsample=1, rotate=True) # 检测不到人脸 报错并返回 if top == -1: print("[-]检测不到人像") return None location = (top, right, bottom, left) # 根据人脸位置获取人脸的特征点的位置 face_landmark = face_landmarks(image, [location])[0] # 根据左眼、右眼的位置对人脸进行校正 left_eye = face_landmark['left_eye'] right_eye = face_landmark['right_eye'] # 眼睛部位六个对称点的倾斜角度 angle_list = [0, 0, 0, 0, 0, 0] for i in range(6): if i < 4: angle_list[i] = get_angle(left_eye[i], right_eye[3 - i]) elif i == 4: angle_list[i] = get_angle(left_eye[i], right_eye[5]) elif i == 5: angle_list[i] = get_angle(left_eye[i], right_eye[4]) # 六个对称点倾斜角度取平均 beta = sum(angle_list) / 6.0 # 根据beta对图像再次校正 rotated_img = image_rotate(image, beta) # 对摆正的图片再次进行人脸检测 并将人像进行裁剪 此时不需要进行旋转 top, right, bottom, left = get_only_face(rotated_img) # 由于旋转会一定比例缩小图像 需要进行上采样才能得到所有的脸 不进行旋转 if top == -1: top, right, bottom, left = get_only_face(rotated_img, upsample=1) # 如果仍然检测不到人脸 返回空值 if top == -1: return None cut_area = rotated_img[top:bottom, left:right] stdface = cv2.resize(cut_area, (256, 256), interpolation=cv2.INTER_CUBIC) # 保存stdface if stdface_save_path is not None: cv2.imwrite(stdface_save_path, rgb2bgr(stdface)) print("[+]stdface保存成功:{}".format(stdface_save_path)) # 保存人像检测结果 if detection_save_path is not None: # 保存带有角度的人脸检测图像 height, weight = image.shape[:2] # 图像尺寸 anti_angle = -1 * (alpha + beta) # 反向旋转角度 center_x, center_y = (weight // 2, height // 2) # 旋转中心坐标 # 图像中心到四个顶点的向量 vector_left_top = Vector((left - center_x), (top - center_y)) vector_right_top = Vector((right - center_x), (top - center_y)) vector_left_bottom = Vector((left - center_x), (bottom - center_y)) vector_right_bottom = Vector((right - center_x), (bottom - center_y)) # 对向量进行旋转 vector_left_top.rotate(anti_angle) vector_right_top.rotate(anti_angle) vector_left_bottom.rotate(anti_angle) vector_right_bottom.rotate(anti_angle) # 带有角度的bounding box的边缘点 point_left_top = vector_left_top.get_point(center_x, center_y) point_right_top = vector_right_top.get_point(center_x, center_y) point_left_bottom = vector_left_bottom.get_point(center_x, center_y) point_right_bottom = vector_right_bottom.get_point(center_x, center_y) # 组建要绘制的点的序列 points = np.array([point_left_top, point_right_top, point_right_bottom, point_left_bottom], np.int32) points = points.reshape((-1, 1, 2)) # 在克隆出来的图像上进行绘制 cv2.polylines(image_copy, [points], True, (15, 158, 254), 2, cv2.LINE_AA) save_image_file(detection_save_path, image_copy) return stdface def face_landmarks(face_image, face_locations_=None, model="large"): """ 输入一张图片 返回包含人脸特征点的字典的集合 人脸关键点的顺序 请查看landmark.png文件 :return: A list of dicts of face feature locations (eyes, nose, etc) """ landmarks = raw_face_landmarks(face_image, face_locations_, model) landmarks_as_tuples = [[(p.x, p.y) for p in landmark.parts()] for landmark in landmarks] if model == 'large': return [{ "chin": points[0:17], "left_eyebrow": points[17:22], "right_eyebrow": points[22:27], "nose_bridge": points[27:31], "nose_tip": points[31:36], "left_eye": points[36:42], "right_eye": points[42:48], "top_lip": points[48:55] + [points[64]] + [points[63]] + [points[62]] + [points[61]] + [points[60]], "bottom_lip": points[54:60] + [points[48]] + [points[60]] + [points[67]] + [points[66]] + [points[65]] + [ points[64]] } for points in landmarks_as_tuples] elif model == 'small': return [{ "nose_tip": [points[4]], "left_eye": points[2:4], "right_eye": points[0:2], } for points in landmarks_as_tuples] def get_similarity(distance): """ 自己拟合的从欧氏距离→相似度的函数 """ similarity = 99.0 if distance <= 0.3: dy = distance * 13.33 similarity -= dy elif distance <= 0.35: dx = distance - 0.3 dy = 100 * dx similarity = 95.0 - dy else: dx = distance - 0.5 dy = 160 * dx similarity = 90.0 - dy # 对相似度的限制 similarity = min(99.0, similarity) similarity = max(31.4, similarity) print("[ ]欧式距离:{:.4f} 拟合后相似度:{:.4f}".format(distance, similarity)) return similarity
"""
identifier_name
view.rs
use clap::Clap; use io::Write; use json::JsonValue; use log::{info, warn}; use num_format::{Locale, ToFormattedString}; use rusqlite::types::ValueRef; use rusqlite::{params, OpenFlags, OptionalExtension}; use std::{env, fs, io, path, process}; use crate::bad_command; use crate::util; use crate::util::Result; #[derive(Clap)] pub struct Opts { /// gfab filename or http[s] URL pub input_gfab: String, /// output GFA filename [omit or - for standard output] #[clap(short, default_value = "-")] pub output_gfa: String, /// Omit segment sequences #[clap(long)] pub no_sequences: bool, /// Launch Bandage on output file (temporary file, if unspecified) #[clap(long)] pub bandage: bool, /// For each segment with reference mappings, set gr:Z tag with one guessed range summarizing the mappings #[clap(long)] pub guess_ranges: bool, /// log extra progress reports #[clap(short, long)] pub verbose: bool, /// log errors only #[clap(short, long)] pub quiet: bool, } pub fn main(opts: &Opts) -> Result<()> { // formulate GenomicSQLite configuration JSON let mut dbopts = json::object::Object::new(); dbopts.insert("immutable", json::JsonValue::from(true)); // open db let (_gfab_version, mut db) = util::open_gfab( &opts.input_gfab, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX, &dbopts, )?; { let txn = db.transaction()?; let mut maybe_guesser = if opts.guess_ranges { Some(SegmentRangeGuesser::new(&txn, "")?) } else { None }; let mut tag_editor = |segment_id: i64, tags: &mut json::JsonValue| -> Result<()> { if let Some(ref mut guesser) = maybe_guesser { if let Some(gr) = guesser.get(segment_id)? { tags.insert("gr:Z", gr).unwrap() } } Ok(()) }; if opts.output_gfa == "-" && !opts.bandage && atty::is(atty::Stream::Stdout) { // interactive mode: pipe into less -S less(|less_in| { write_header(&txn, less_in) .and_then(|_| { write_segments(&txn, "", !opts.no_sequences, &mut tag_editor, less_in) }) .and_then(|_| write_links(&txn, "", less_in)) .and_then(|_| write_paths(&txn, "", less_in)) })? } else { let mut output_gfa = String::from(&opts.output_gfa); if opts.bandage && output_gfa == "-" { output_gfa = bandage_temp_filename()? } { let mut writer_box = writer(&output_gfa)?; let out = &mut *writer_box; write_header(&txn, out)?; write_segments(&txn, "", !opts.no_sequences, &mut tag_editor, out)?; write_links(&txn, "", out)?; write_paths(&txn, "", out)?; write_walks(&txn, "", out)? } if opts.bandage { if let Some(ref mut guesser) = maybe_guesser { guesser.write_bandage_csv(&output_gfa)? } bandage(&output_gfa)? } } } Ok(()) } pub fn writer(gfa_filename: &str) -> Result<Box<dyn io::Write>> { if gfa_filename.is_empty() || gfa_filename == "-" { return Ok(Box::new(io::BufWriter::new(io::stdout()))); } if !gfa_filename.ends_with(".gfa") { warn!("output filename should end with .gfa") } Ok(Box::new(io::BufWriter::new(fs::File::create( gfa_filename, )?))) } /// Start `less -S` and call `write` with its standard input pipe. /// Tolerate BrokenPipe errors (user exited before viewing all data) pub fn less<F>(write: F) -> Result<()> where F: FnOnce(&mut dyn io::Write) -> Result<()>, { if which::which("less").is_err() { return write(&mut io::stdout()); } let mut child = process::Command::new("less") .arg("-S") .stdin(process::Stdio::piped()) .spawn()?; { let mut less_in = child.stdin.take().unwrap(); match write(&mut less_in) { Ok(()) => (), Err(util::Error::IoError(err)) if err.kind() == io::ErrorKind::BrokenPipe => (), Err(e) => return Err(e), } } child.wait()?; Ok(()) } pub fn bandage(gfa: &str) -> Result<()> { info!("Bandage load {} --draw", gfa); if process::Command::new("Bandage") .arg("load") .arg(gfa) .arg("--draw") .spawn() .is_err() { bad_command!("failed to launch Bandage; make sure it's in PATH") } Ok(()) } pub fn bandage_temp_filename() -> Result<String> { if !atty::is(atty::Stream::Stdout) { bad_command!("supply -o filename.gfa on which to launch Bandage") } Ok(String::from( path::Path::new(&env::var("TMPDIR").unwrap_or(String::from("/tmp"))) .join(format!( "gfabase-bandage-{}.gfa", chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Micros, true) )) .to_str() .unwrap(), )) } pub fn write_header(db: &rusqlite::Connection, writer: &mut dyn io::Write) -> Result<()> { let tags_json: String = db.query_row( "SELECT tags_json FROM gfa1_header WHERE _rowid_ = 1", [], |row| row.get(0), )?; writer.write(b"H")?; write_tags("gfa1_header", 1, &tags_json, writer)?; writer.write(b"\n")?; Ok(()) } pub fn write_segments( db: &rusqlite::Connection, where_clause: &str, with_sequences: bool, mut tag_editor: impl FnMut(i64, &mut json::JsonValue) -> Result<()>, writer: &mut dyn io::Write, ) -> Result<()> { let segments_query_sql = String::from(if with_sequences { "SELECT segment_id, coalesce(name, cast(segment_id AS TEXT)), sequence_length, coalesce(tags_json, '{}'), sequence FROM gfa1_segment " } else { "SELECT segment_id, coalesce(name, cast(segment_id AS TEXT)), sequence_length, coalesce(tags_json, '{}') FROM gfa1_segment_meta " }) + where_clause; let mut segments_query = db.prepare(&segments_query_sql)?; let mut segments_cursor = segments_query.query([])?; while let Some(segrow) = segments_cursor.next()? { let rowid: i64 = segrow.get(0)?; let name: String = segrow.get(1)?; let maybe_sequence_length: Option<i64> = segrow.get(2)?; let tags_json: String = segrow.get(3)?; writer.write_fmt(format_args!("S\t{}\t", name))?; if with_sequences { match segrow.get_ref(4)? { ValueRef::Text(sequence) => writer.write(sequence)?, ValueRef::Null => writer.write(b"*")?, _ => { return Err(util::Error::InvalidGfab { message: String::from("segment row has invalid sequence value type"), table: String::from("gfa1_segment_sequence"), rowid: rowid, }) } }; } else { writer.write(b"*")?; } if let Some(sequence_length) = maybe_sequence_length { writer.write_fmt(format_args!("\tLN:i:{}", sequence_length))?; } write_tags_with_editor( "gfa1_segments_meta", rowid, &tags_json, &mut tag_editor, writer, )?; writer.write(b"\n")?; } Ok(()) } pub fn write_links( db: &rusqlite::Connection, where_clause: &str, writer: &mut dyn io::Write, ) -> Result<()> { let links_query_sql = format!( // this two-layer join resolves the two segment IDs to names (if any) "SELECT link_id, from_segment_name, from_reverse, coalesce(gfa1_segment_meta.name, cast(to_segment AS TEXT)) AS to_segment_name, to_reverse, cigar, link_tags_json FROM (SELECT gfa1_link._rowid_ AS link_id, coalesce(gfa1_segment_meta.name, cast(from_segment AS TEXT)) AS from_segment_name, from_reverse, to_segment, to_reverse, coalesce(cigar, '*') AS cigar, coalesce(gfa1_link.tags_json, '{{}}') AS link_tags_json FROM gfa1_link LEFT JOIN gfa1_segment_meta ON from_segment = segment_id {} ORDER BY from_segment, to_segment) LEFT JOIN gfa1_segment_meta ON to_segment = segment_id", where_clause ); let mut links_query = db.prepare(&links_query_sql)?; let mut links_cursor = links_query.query([])?; while let Some(linkrow) = links_cursor.next()? { let link_id: i64 = linkrow.get(0)?; let from_segment: String = linkrow.get(1)?; let from_reverse: i8 = linkrow.get(2)?; let to_segment: String = linkrow.get(3)?; let to_reverse: i8 = linkrow.get(4)?; let cigar: String = linkrow.get(5)?; let tags_json: String = linkrow.get(6)?; writer.write_fmt(format_args!( "L\t{}\t{}\t{}\t{}\t{}", from_segment, if from_reverse == 0 { '+' } else { '-' }, to_segment, if to_reverse == 0 { '+' } else { '-' }, cigar ))?; write_tags("gfa1_link", link_id, &tags_json, writer)?; writer.write(b"\n")?; } Ok(()) } pub fn write_paths( db: &rusqlite::Connection, where_clause: &str, writer: &mut dyn io::Write, ) -> Result<()> { let paths_query_sql = format!( "SELECT path_id, coalesce(name, cast(path_id AS TEXT)), coalesce(tags_json, '{{}}') FROM gfa1_path {} ORDER BY path_id", where_clause ); let mut paths_query = db.prepare(&paths_query_sql)?; let mut elements_query = db.prepare( "SELECT coalesce(name, cast(segment_id AS TEXT)) AS segment_name, reverse, cigar_vs_previous FROM gfa1_path_element LEFT JOIN gfa1_segment_meta USING(segment_id) WHERE path_id=? ORDER BY path_id, ordinal", )?; let mut paths_cursor = paths_query.query([])?; while let Some(pathrow) = paths_cursor.next()? { let path_id: i64 = pathrow.get(0)?; let name: String = pathrow.get(1)?; let tags_json: String = pathrow.get(2)?; let mut elts_csv = Vec::new(); let mut cigars_csv = Vec::new(); let mut elts_cursor = elements_query.query(params![path_id])?; while let Some(eltrow) = elts_cursor.next()? { let segment_name: String = eltrow.get(0)?; let reverse: i64 = eltrow.get(1)?; let maybe_cigar: Option<String> = eltrow.get(2)?; elts_csv.push(segment_name + if reverse == 0 { "+" } else { "-" }); if let Some(cigar) = maybe_cigar { cigars_csv.push(cigar); } } writer.write_fmt(format_args!( "P\t{}\t{}\t{}", &name, &elts_csv.join(","), if cigars_csv.len() > 0 { cigars_csv.join(",") } else { String::from("*") } ))?; write_tags("gfa1_path", path_id, &tags_json, writer)?; writer.write(b"\n")?; } Ok(()) } pub fn write_walks( db: &rusqlite::Connection, where_clause: &str, writer: &mut dyn io::Write, ) -> Result<()> { let fwd = ">".as_bytes(); let rev = "<".as_bytes(); let mut iter_walk_query = prepare_iter_walk(db)?; let walks_query_sql = format!( "SELECT walk_id, sample, hap_idx, refseq_name, refseq_begin, refseq_end, coalesce(tags_json, '{{}}') FROM gfa1_walk {} ORDER BY sample, refseq_name, hap_idx, refseq_begin", where_clause); let mut walks_query = db.prepare(&walks_query_sql)?; let mut walks_cursor = walks_query.query([])?; while let Some(row) = walks_cursor.next()? { let walk_id: i64 = row.get(0)?; let sample: String = row.get(1)?; let hap_idx: i64 = row.get(2)?; let refseq_name: String = row.get(3)?; let refseq_begin: i64 = row.get(4)?; let refseq_end: i64 = row.get(5)?; let tags_json: String = row.get(6)?; writer.write_fmt(format_args!( "W\t{}\t{}\t{}\t{}\t{}\t", sample, hap_idx, refseq_name, refseq_begin, refseq_end ))?; iter_walk(&mut iter_walk_query, walk_id, |segment_id, reverse| { writer.write(if reverse { rev } else { fwd })?; writer.write(segment_id.to_string().as_bytes())?; Ok(true) })?; write_tags("gfa1_walk", walk_id, &tags_json, writer)?; writer.write(b"\n")?; } Ok(()) } fn write_tags_with_editor( table: &str, rowid: i64, tags_json: &str, mut editor: impl FnMut(i64, &mut json::JsonValue) -> Result<()>, writer: &mut dyn io::Write, ) -> Result<()> { let invalid = || util::Error::InvalidGfab { message: String::from("invalid tags_json"), table: String::from(table), rowid: rowid, }; let mut tags = json::parse(&tags_json).map_err(|_| invalid())?; editor(rowid, &mut tags)?; for (k, v) in tags.entries() { let kfields: Vec<&str> = k.split(':').collect(); if kfields.len() != 2 { return Err(invalid()); } let vstr = match kfields[1] { "A" | "Z" | "H" => JsonValue::as_str(v).ok_or_else(invalid)?.to_string(), "i" => JsonValue::as_i64(v).ok_or_else(invalid)?.to_string(), "f" => JsonValue::as_f64(v).ok_or_else(invalid)?.to_string(), // TODO: B & J _ => return Err(invalid()), }; writer.write_fmt(format_args!("\t{}:{}", k, vstr))?; } Ok(()) } fn write_tags(table: &str, rowid: i64, tags_json: &str, writer: &mut dyn io::Write) -> Result<()> { write_tags_with_editor(table, rowid, tags_json, |_, _| Ok(()), writer) } // Helpers roughly guessing a genomic range for a segment based on its PAF mappings. Selects the // chromosome with the most coverage in the mappings, then the min and max mapped position on that // chromosome. pub struct SegmentRangeGuesser<'a> { getter: rusqlite::Statement<'a>, csv_query: rusqlite::Statement<'a>, } impl<'a> SegmentRangeGuesser<'_> { pub fn new( db: &'a rusqlite::Connection, where_clause: &str, ) -> Result<SegmentRangeGuesser<'a>> { // analyze mappings to generate temp.segment_range_guess db.execute( "CREATE TABLE temp.segment_range_guess( segment_id INTEGER PRIMARY KEY, refseq_name TEXT NOT NULL, refseq_begin INTEGER NOT NULL, refseq_end INTEGER NOT NULL)", [], )?; let sql = format!( "WITH summary AS (SELECT segment_id, refseq_name, min(refseq_begin) AS min_begin, max(refseq_end) AS max_end, max(refseq_end) - min(refseq_begin) AS coverage, sum(refseq_end - refseq_begin) AS coverage2 FROM gfa1_segment_mapping {} GROUP BY segment_id, refseq_name) INSERT INTO temp.segment_range_guess(segment_id, refseq_name, refseq_begin, refseq_end) SELECT segment_id, refseq_name, min_begin, max_end FROM (SELECT segment_id, refseq_name, min_begin, max_end, row_number() OVER (PARTITION BY segment_id ORDER BY coverage DESC, coverage2 DESC) AS coverage_rank FROM summary) WHERE coverage_rank = 1", where_clause ); let n = db.execute(&sql, [])?; info!("guessed ranges for {} segments", n); // prepare queries on temp.segment_range_guess Ok(SegmentRangeGuesser { getter: db.prepare( "SELECT refseq_name, refseq_begin, refseq_end FROM temp.segment_range_guess WHERE segment_id = ?", )?, csv_query: db.prepare( "SELECT coalesce(name, cast(segment_id AS TEXT)), refseq_name, refseq_begin, refseq_end FROM temp.segment_range_guess LEFT JOIN gfa1_segment_meta USING(segment_id)", )?, }) } pub fn get(&mut self, segment_id: i64) -> Result<Option<String>> { let maybe_row: Option<(String, i64, i64)> = self .getter .query_row(params![segment_id], |row| { Ok((row.get(0)?, row.get(1)?, row.get(2)?)) }) .optional()?; if let Some((refseq_name, refseq_begin, refseq_end)) = maybe_row { return Ok(Some(format!( "~{}:{}-{}", refseq_name, (refseq_begin + 1).to_formatted_string(&Locale::en), refseq_end.to_formatted_string(&Locale::en) ))); } Ok(None) } pub fn write_bandage_csv(&mut self, gfa_filename: &str) -> Result<()> { // write a CSV file with the guessed ranges that Bandage can show as labels let csv_filename = String::from(gfa_filename.strip_suffix(".gfa").unwrap_or(gfa_filename)) + ".guessed_ranges.csv"; { let mut writer = io::BufWriter::new(fs::File::create(&csv_filename)?); writer.write_fmt(format_args!("Name,Guessed range\n"))?; let mut cursor = self.csv_query.query([])?; while let Some(row) = cursor.next()? { let name: String = row.get(0)?; let refseq_name: String = row.get(1)?; let refseq_begin: i64 = row.get(2)?; let refseq_end: i64 = row.get(3)?;
refseq_name, (refseq_begin + 1).to_formatted_string(&Locale::en), refseq_end.to_formatted_string(&Locale::en) ))?; } } info!("wrote CSV with guessed segment ranges to {}", csv_filename); Ok(()) } } // Helpers for iterating over steps of a GFA Walk, automatically decoding any stored deltas to // produce a sequence of (segment_id: i64, reverse_orientation: bool). // First, a query preparation amortized over multiple Walks if needed. pub fn prepare_iter_walk<'a>(db: &'a rusqlite::Connection) -> Result<rusqlite::Statement<'a>> { match db.prepare( "SELECT json_extract(json_each.value,'$.s'), json_extract(json_each.value,'$.+'), json_extract(json_each.value,'$.-'), json_extract(json_each.value,'$.r') FROM gfa1_walk_steps, json_each(gfa1_walk_steps.steps_jsarray) WHERE walk_id = ?", ) { Ok(stmt) => Ok(stmt), Err(e) => Err(util::Error::DbError(e)), } } // Then, the iteration function taking your callback, which may return false to stop the walk // (without indicating an error). pub fn iter_walk<F>(query: &mut rusqlite::Statement, walk_id: i64, mut f: F) -> Result<()> where F: FnMut(i64, bool) -> Result<bool>, { let mut prev_segment = i64::MIN; let mut prev_reverse = false; let mut cursor = query.query(params![walk_id])?; while let Some(row) = cursor.next()? { let maybe_segment_id: Option<i64> = row.get(0)?; let maybe_plus: Option<i64> = row.get(1)?; let maybe_minus: Option<i64> = row.get(2)?; let maybe_reverse: Option<i64> = row.get(3)?; let segment_id = if maybe_segment_id.is_some() { maybe_segment_id.unwrap() } else if maybe_plus.is_some() { prev_segment + maybe_plus.unwrap() } else if maybe_minus.is_some() { prev_segment - maybe_minus.unwrap() } else { return Err(util::Error::InvalidGfab { message: String::from("Walk has invalid delta-encoding"), table: String::from("gfa1_walk_steps"), rowid: walk_id, }); }; let reverse = maybe_reverse.map_or(prev_reverse, |r| r != 0); if !f(segment_id, reverse)? { break; } prev_segment = segment_id; prev_reverse = reverse; } Ok(()) }
writer.write_fmt(format_args!( "\"{}\",\"~{}:{}-{}\"\n", name,
random_line_split
view.rs
use clap::Clap; use io::Write; use json::JsonValue; use log::{info, warn}; use num_format::{Locale, ToFormattedString}; use rusqlite::types::ValueRef; use rusqlite::{params, OpenFlags, OptionalExtension}; use std::{env, fs, io, path, process}; use crate::bad_command; use crate::util; use crate::util::Result; #[derive(Clap)] pub struct Opts { /// gfab filename or http[s] URL pub input_gfab: String, /// output GFA filename [omit or - for standard output] #[clap(short, default_value = "-")] pub output_gfa: String, /// Omit segment sequences #[clap(long)] pub no_sequences: bool, /// Launch Bandage on output file (temporary file, if unspecified) #[clap(long)] pub bandage: bool, /// For each segment with reference mappings, set gr:Z tag with one guessed range summarizing the mappings #[clap(long)] pub guess_ranges: bool, /// log extra progress reports #[clap(short, long)] pub verbose: bool, /// log errors only #[clap(short, long)] pub quiet: bool, } pub fn main(opts: &Opts) -> Result<()> { // formulate GenomicSQLite configuration JSON let mut dbopts = json::object::Object::new(); dbopts.insert("immutable", json::JsonValue::from(true)); // open db let (_gfab_version, mut db) = util::open_gfab( &opts.input_gfab, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX, &dbopts, )?; { let txn = db.transaction()?; let mut maybe_guesser = if opts.guess_ranges { Some(SegmentRangeGuesser::new(&txn, "")?) } else { None }; let mut tag_editor = |segment_id: i64, tags: &mut json::JsonValue| -> Result<()> { if let Some(ref mut guesser) = maybe_guesser { if let Some(gr) = guesser.get(segment_id)? { tags.insert("gr:Z", gr).unwrap() } } Ok(()) }; if opts.output_gfa == "-" && !opts.bandage && atty::is(atty::Stream::Stdout) { // interactive mode: pipe into less -S less(|less_in| { write_header(&txn, less_in) .and_then(|_| { write_segments(&txn, "", !opts.no_sequences, &mut tag_editor, less_in) }) .and_then(|_| write_links(&txn, "", less_in)) .and_then(|_| write_paths(&txn, "", less_in)) })? } else { let mut output_gfa = String::from(&opts.output_gfa); if opts.bandage && output_gfa == "-" { output_gfa = bandage_temp_filename()? } { let mut writer_box = writer(&output_gfa)?; let out = &mut *writer_box; write_header(&txn, out)?; write_segments(&txn, "", !opts.no_sequences, &mut tag_editor, out)?; write_links(&txn, "", out)?; write_paths(&txn, "", out)?; write_walks(&txn, "", out)? } if opts.bandage { if let Some(ref mut guesser) = maybe_guesser { guesser.write_bandage_csv(&output_gfa)? } bandage(&output_gfa)? } } } Ok(()) } pub fn writer(gfa_filename: &str) -> Result<Box<dyn io::Write>> { if gfa_filename.is_empty() || gfa_filename == "-" { return Ok(Box::new(io::BufWriter::new(io::stdout()))); } if !gfa_filename.ends_with(".gfa") { warn!("output filename should end with .gfa") } Ok(Box::new(io::BufWriter::new(fs::File::create( gfa_filename, )?))) } /// Start `less -S` and call `write` with its standard input pipe. /// Tolerate BrokenPipe errors (user exited before viewing all data) pub fn less<F>(write: F) -> Result<()> where F: FnOnce(&mut dyn io::Write) -> Result<()>, { if which::which("less").is_err() { return write(&mut io::stdout()); } let mut child = process::Command::new("less") .arg("-S") .stdin(process::Stdio::piped()) .spawn()?; { let mut less_in = child.stdin.take().unwrap(); match write(&mut less_in) { Ok(()) => (), Err(util::Error::IoError(err)) if err.kind() == io::ErrorKind::BrokenPipe => (), Err(e) => return Err(e), } } child.wait()?; Ok(()) } pub fn bandage(gfa: &str) -> Result<()> { info!("Bandage load {} --draw", gfa); if process::Command::new("Bandage") .arg("load") .arg(gfa) .arg("--draw") .spawn() .is_err() { bad_command!("failed to launch Bandage; make sure it's in PATH") } Ok(()) } pub fn bandage_temp_filename() -> Result<String> { if !atty::is(atty::Stream::Stdout) { bad_command!("supply -o filename.gfa on which to launch Bandage") } Ok(String::from( path::Path::new(&env::var("TMPDIR").unwrap_or(String::from("/tmp"))) .join(format!( "gfabase-bandage-{}.gfa", chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Micros, true) )) .to_str() .unwrap(), )) } pub fn
(db: &rusqlite::Connection, writer: &mut dyn io::Write) -> Result<()> { let tags_json: String = db.query_row( "SELECT tags_json FROM gfa1_header WHERE _rowid_ = 1", [], |row| row.get(0), )?; writer.write(b"H")?; write_tags("gfa1_header", 1, &tags_json, writer)?; writer.write(b"\n")?; Ok(()) } pub fn write_segments( db: &rusqlite::Connection, where_clause: &str, with_sequences: bool, mut tag_editor: impl FnMut(i64, &mut json::JsonValue) -> Result<()>, writer: &mut dyn io::Write, ) -> Result<()> { let segments_query_sql = String::from(if with_sequences { "SELECT segment_id, coalesce(name, cast(segment_id AS TEXT)), sequence_length, coalesce(tags_json, '{}'), sequence FROM gfa1_segment " } else { "SELECT segment_id, coalesce(name, cast(segment_id AS TEXT)), sequence_length, coalesce(tags_json, '{}') FROM gfa1_segment_meta " }) + where_clause; let mut segments_query = db.prepare(&segments_query_sql)?; let mut segments_cursor = segments_query.query([])?; while let Some(segrow) = segments_cursor.next()? { let rowid: i64 = segrow.get(0)?; let name: String = segrow.get(1)?; let maybe_sequence_length: Option<i64> = segrow.get(2)?; let tags_json: String = segrow.get(3)?; writer.write_fmt(format_args!("S\t{}\t", name))?; if with_sequences { match segrow.get_ref(4)? { ValueRef::Text(sequence) => writer.write(sequence)?, ValueRef::Null => writer.write(b"*")?, _ => { return Err(util::Error::InvalidGfab { message: String::from("segment row has invalid sequence value type"), table: String::from("gfa1_segment_sequence"), rowid: rowid, }) } }; } else { writer.write(b"*")?; } if let Some(sequence_length) = maybe_sequence_length { writer.write_fmt(format_args!("\tLN:i:{}", sequence_length))?; } write_tags_with_editor( "gfa1_segments_meta", rowid, &tags_json, &mut tag_editor, writer, )?; writer.write(b"\n")?; } Ok(()) } pub fn write_links( db: &rusqlite::Connection, where_clause: &str, writer: &mut dyn io::Write, ) -> Result<()> { let links_query_sql = format!( // this two-layer join resolves the two segment IDs to names (if any) "SELECT link_id, from_segment_name, from_reverse, coalesce(gfa1_segment_meta.name, cast(to_segment AS TEXT)) AS to_segment_name, to_reverse, cigar, link_tags_json FROM (SELECT gfa1_link._rowid_ AS link_id, coalesce(gfa1_segment_meta.name, cast(from_segment AS TEXT)) AS from_segment_name, from_reverse, to_segment, to_reverse, coalesce(cigar, '*') AS cigar, coalesce(gfa1_link.tags_json, '{{}}') AS link_tags_json FROM gfa1_link LEFT JOIN gfa1_segment_meta ON from_segment = segment_id {} ORDER BY from_segment, to_segment) LEFT JOIN gfa1_segment_meta ON to_segment = segment_id", where_clause ); let mut links_query = db.prepare(&links_query_sql)?; let mut links_cursor = links_query.query([])?; while let Some(linkrow) = links_cursor.next()? { let link_id: i64 = linkrow.get(0)?; let from_segment: String = linkrow.get(1)?; let from_reverse: i8 = linkrow.get(2)?; let to_segment: String = linkrow.get(3)?; let to_reverse: i8 = linkrow.get(4)?; let cigar: String = linkrow.get(5)?; let tags_json: String = linkrow.get(6)?; writer.write_fmt(format_args!( "L\t{}\t{}\t{}\t{}\t{}", from_segment, if from_reverse == 0 { '+' } else { '-' }, to_segment, if to_reverse == 0 { '+' } else { '-' }, cigar ))?; write_tags("gfa1_link", link_id, &tags_json, writer)?; writer.write(b"\n")?; } Ok(()) } pub fn write_paths( db: &rusqlite::Connection, where_clause: &str, writer: &mut dyn io::Write, ) -> Result<()> { let paths_query_sql = format!( "SELECT path_id, coalesce(name, cast(path_id AS TEXT)), coalesce(tags_json, '{{}}') FROM gfa1_path {} ORDER BY path_id", where_clause ); let mut paths_query = db.prepare(&paths_query_sql)?; let mut elements_query = db.prepare( "SELECT coalesce(name, cast(segment_id AS TEXT)) AS segment_name, reverse, cigar_vs_previous FROM gfa1_path_element LEFT JOIN gfa1_segment_meta USING(segment_id) WHERE path_id=? ORDER BY path_id, ordinal", )?; let mut paths_cursor = paths_query.query([])?; while let Some(pathrow) = paths_cursor.next()? { let path_id: i64 = pathrow.get(0)?; let name: String = pathrow.get(1)?; let tags_json: String = pathrow.get(2)?; let mut elts_csv = Vec::new(); let mut cigars_csv = Vec::new(); let mut elts_cursor = elements_query.query(params![path_id])?; while let Some(eltrow) = elts_cursor.next()? { let segment_name: String = eltrow.get(0)?; let reverse: i64 = eltrow.get(1)?; let maybe_cigar: Option<String> = eltrow.get(2)?; elts_csv.push(segment_name + if reverse == 0 { "+" } else { "-" }); if let Some(cigar) = maybe_cigar { cigars_csv.push(cigar); } } writer.write_fmt(format_args!( "P\t{}\t{}\t{}", &name, &elts_csv.join(","), if cigars_csv.len() > 0 { cigars_csv.join(",") } else { String::from("*") } ))?; write_tags("gfa1_path", path_id, &tags_json, writer)?; writer.write(b"\n")?; } Ok(()) } pub fn write_walks( db: &rusqlite::Connection, where_clause: &str, writer: &mut dyn io::Write, ) -> Result<()> { let fwd = ">".as_bytes(); let rev = "<".as_bytes(); let mut iter_walk_query = prepare_iter_walk(db)?; let walks_query_sql = format!( "SELECT walk_id, sample, hap_idx, refseq_name, refseq_begin, refseq_end, coalesce(tags_json, '{{}}') FROM gfa1_walk {} ORDER BY sample, refseq_name, hap_idx, refseq_begin", where_clause); let mut walks_query = db.prepare(&walks_query_sql)?; let mut walks_cursor = walks_query.query([])?; while let Some(row) = walks_cursor.next()? { let walk_id: i64 = row.get(0)?; let sample: String = row.get(1)?; let hap_idx: i64 = row.get(2)?; let refseq_name: String = row.get(3)?; let refseq_begin: i64 = row.get(4)?; let refseq_end: i64 = row.get(5)?; let tags_json: String = row.get(6)?; writer.write_fmt(format_args!( "W\t{}\t{}\t{}\t{}\t{}\t", sample, hap_idx, refseq_name, refseq_begin, refseq_end ))?; iter_walk(&mut iter_walk_query, walk_id, |segment_id, reverse| { writer.write(if reverse { rev } else { fwd })?; writer.write(segment_id.to_string().as_bytes())?; Ok(true) })?; write_tags("gfa1_walk", walk_id, &tags_json, writer)?; writer.write(b"\n")?; } Ok(()) } fn write_tags_with_editor( table: &str, rowid: i64, tags_json: &str, mut editor: impl FnMut(i64, &mut json::JsonValue) -> Result<()>, writer: &mut dyn io::Write, ) -> Result<()> { let invalid = || util::Error::InvalidGfab { message: String::from("invalid tags_json"), table: String::from(table), rowid: rowid, }; let mut tags = json::parse(&tags_json).map_err(|_| invalid())?; editor(rowid, &mut tags)?; for (k, v) in tags.entries() { let kfields: Vec<&str> = k.split(':').collect(); if kfields.len() != 2 { return Err(invalid()); } let vstr = match kfields[1] { "A" | "Z" | "H" => JsonValue::as_str(v).ok_or_else(invalid)?.to_string(), "i" => JsonValue::as_i64(v).ok_or_else(invalid)?.to_string(), "f" => JsonValue::as_f64(v).ok_or_else(invalid)?.to_string(), // TODO: B & J _ => return Err(invalid()), }; writer.write_fmt(format_args!("\t{}:{}", k, vstr))?; } Ok(()) } fn write_tags(table: &str, rowid: i64, tags_json: &str, writer: &mut dyn io::Write) -> Result<()> { write_tags_with_editor(table, rowid, tags_json, |_, _| Ok(()), writer) } // Helpers roughly guessing a genomic range for a segment based on its PAF mappings. Selects the // chromosome with the most coverage in the mappings, then the min and max mapped position on that // chromosome. pub struct SegmentRangeGuesser<'a> { getter: rusqlite::Statement<'a>, csv_query: rusqlite::Statement<'a>, } impl<'a> SegmentRangeGuesser<'_> { pub fn new( db: &'a rusqlite::Connection, where_clause: &str, ) -> Result<SegmentRangeGuesser<'a>> { // analyze mappings to generate temp.segment_range_guess db.execute( "CREATE TABLE temp.segment_range_guess( segment_id INTEGER PRIMARY KEY, refseq_name TEXT NOT NULL, refseq_begin INTEGER NOT NULL, refseq_end INTEGER NOT NULL)", [], )?; let sql = format!( "WITH summary AS (SELECT segment_id, refseq_name, min(refseq_begin) AS min_begin, max(refseq_end) AS max_end, max(refseq_end) - min(refseq_begin) AS coverage, sum(refseq_end - refseq_begin) AS coverage2 FROM gfa1_segment_mapping {} GROUP BY segment_id, refseq_name) INSERT INTO temp.segment_range_guess(segment_id, refseq_name, refseq_begin, refseq_end) SELECT segment_id, refseq_name, min_begin, max_end FROM (SELECT segment_id, refseq_name, min_begin, max_end, row_number() OVER (PARTITION BY segment_id ORDER BY coverage DESC, coverage2 DESC) AS coverage_rank FROM summary) WHERE coverage_rank = 1", where_clause ); let n = db.execute(&sql, [])?; info!("guessed ranges for {} segments", n); // prepare queries on temp.segment_range_guess Ok(SegmentRangeGuesser { getter: db.prepare( "SELECT refseq_name, refseq_begin, refseq_end FROM temp.segment_range_guess WHERE segment_id = ?", )?, csv_query: db.prepare( "SELECT coalesce(name, cast(segment_id AS TEXT)), refseq_name, refseq_begin, refseq_end FROM temp.segment_range_guess LEFT JOIN gfa1_segment_meta USING(segment_id)", )?, }) } pub fn get(&mut self, segment_id: i64) -> Result<Option<String>> { let maybe_row: Option<(String, i64, i64)> = self .getter .query_row(params![segment_id], |row| { Ok((row.get(0)?, row.get(1)?, row.get(2)?)) }) .optional()?; if let Some((refseq_name, refseq_begin, refseq_end)) = maybe_row { return Ok(Some(format!( "~{}:{}-{}", refseq_name, (refseq_begin + 1).to_formatted_string(&Locale::en), refseq_end.to_formatted_string(&Locale::en) ))); } Ok(None) } pub fn write_bandage_csv(&mut self, gfa_filename: &str) -> Result<()> { // write a CSV file with the guessed ranges that Bandage can show as labels let csv_filename = String::from(gfa_filename.strip_suffix(".gfa").unwrap_or(gfa_filename)) + ".guessed_ranges.csv"; { let mut writer = io::BufWriter::new(fs::File::create(&csv_filename)?); writer.write_fmt(format_args!("Name,Guessed range\n"))?; let mut cursor = self.csv_query.query([])?; while let Some(row) = cursor.next()? { let name: String = row.get(0)?; let refseq_name: String = row.get(1)?; let refseq_begin: i64 = row.get(2)?; let refseq_end: i64 = row.get(3)?; writer.write_fmt(format_args!( "\"{}\",\"~{}:{}-{}\"\n", name, refseq_name, (refseq_begin + 1).to_formatted_string(&Locale::en), refseq_end.to_formatted_string(&Locale::en) ))?; } } info!("wrote CSV with guessed segment ranges to {}", csv_filename); Ok(()) } } // Helpers for iterating over steps of a GFA Walk, automatically decoding any stored deltas to // produce a sequence of (segment_id: i64, reverse_orientation: bool). // First, a query preparation amortized over multiple Walks if needed. pub fn prepare_iter_walk<'a>(db: &'a rusqlite::Connection) -> Result<rusqlite::Statement<'a>> { match db.prepare( "SELECT json_extract(json_each.value,'$.s'), json_extract(json_each.value,'$.+'), json_extract(json_each.value,'$.-'), json_extract(json_each.value,'$.r') FROM gfa1_walk_steps, json_each(gfa1_walk_steps.steps_jsarray) WHERE walk_id = ?", ) { Ok(stmt) => Ok(stmt), Err(e) => Err(util::Error::DbError(e)), } } // Then, the iteration function taking your callback, which may return false to stop the walk // (without indicating an error). pub fn iter_walk<F>(query: &mut rusqlite::Statement, walk_id: i64, mut f: F) -> Result<()> where F: FnMut(i64, bool) -> Result<bool>, { let mut prev_segment = i64::MIN; let mut prev_reverse = false; let mut cursor = query.query(params![walk_id])?; while let Some(row) = cursor.next()? { let maybe_segment_id: Option<i64> = row.get(0)?; let maybe_plus: Option<i64> = row.get(1)?; let maybe_minus: Option<i64> = row.get(2)?; let maybe_reverse: Option<i64> = row.get(3)?; let segment_id = if maybe_segment_id.is_some() { maybe_segment_id.unwrap() } else if maybe_plus.is_some() { prev_segment + maybe_plus.unwrap() } else if maybe_minus.is_some() { prev_segment - maybe_minus.unwrap() } else { return Err(util::Error::InvalidGfab { message: String::from("Walk has invalid delta-encoding"), table: String::from("gfa1_walk_steps"), rowid: walk_id, }); }; let reverse = maybe_reverse.map_or(prev_reverse, |r| r != 0); if !f(segment_id, reverse)? { break; } prev_segment = segment_id; prev_reverse = reverse; } Ok(()) }
write_header
identifier_name
view.rs
use clap::Clap; use io::Write; use json::JsonValue; use log::{info, warn}; use num_format::{Locale, ToFormattedString}; use rusqlite::types::ValueRef; use rusqlite::{params, OpenFlags, OptionalExtension}; use std::{env, fs, io, path, process}; use crate::bad_command; use crate::util; use crate::util::Result; #[derive(Clap)] pub struct Opts { /// gfab filename or http[s] URL pub input_gfab: String, /// output GFA filename [omit or - for standard output] #[clap(short, default_value = "-")] pub output_gfa: String, /// Omit segment sequences #[clap(long)] pub no_sequences: bool, /// Launch Bandage on output file (temporary file, if unspecified) #[clap(long)] pub bandage: bool, /// For each segment with reference mappings, set gr:Z tag with one guessed range summarizing the mappings #[clap(long)] pub guess_ranges: bool, /// log extra progress reports #[clap(short, long)] pub verbose: bool, /// log errors only #[clap(short, long)] pub quiet: bool, } pub fn main(opts: &Opts) -> Result<()> { // formulate GenomicSQLite configuration JSON let mut dbopts = json::object::Object::new(); dbopts.insert("immutable", json::JsonValue::from(true)); // open db let (_gfab_version, mut db) = util::open_gfab( &opts.input_gfab, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX, &dbopts, )?; { let txn = db.transaction()?; let mut maybe_guesser = if opts.guess_ranges { Some(SegmentRangeGuesser::new(&txn, "")?) } else { None }; let mut tag_editor = |segment_id: i64, tags: &mut json::JsonValue| -> Result<()> { if let Some(ref mut guesser) = maybe_guesser { if let Some(gr) = guesser.get(segment_id)? { tags.insert("gr:Z", gr).unwrap() } } Ok(()) }; if opts.output_gfa == "-" && !opts.bandage && atty::is(atty::Stream::Stdout) { // interactive mode: pipe into less -S less(|less_in| { write_header(&txn, less_in) .and_then(|_| { write_segments(&txn, "", !opts.no_sequences, &mut tag_editor, less_in) }) .and_then(|_| write_links(&txn, "", less_in)) .and_then(|_| write_paths(&txn, "", less_in)) })? } else { let mut output_gfa = String::from(&opts.output_gfa); if opts.bandage && output_gfa == "-" { output_gfa = bandage_temp_filename()? } { let mut writer_box = writer(&output_gfa)?; let out = &mut *writer_box; write_header(&txn, out)?; write_segments(&txn, "", !opts.no_sequences, &mut tag_editor, out)?; write_links(&txn, "", out)?; write_paths(&txn, "", out)?; write_walks(&txn, "", out)? } if opts.bandage { if let Some(ref mut guesser) = maybe_guesser { guesser.write_bandage_csv(&output_gfa)? } bandage(&output_gfa)? } } } Ok(()) } pub fn writer(gfa_filename: &str) -> Result<Box<dyn io::Write>> { if gfa_filename.is_empty() || gfa_filename == "-"
if !gfa_filename.ends_with(".gfa") { warn!("output filename should end with .gfa") } Ok(Box::new(io::BufWriter::new(fs::File::create( gfa_filename, )?))) } /// Start `less -S` and call `write` with its standard input pipe. /// Tolerate BrokenPipe errors (user exited before viewing all data) pub fn less<F>(write: F) -> Result<()> where F: FnOnce(&mut dyn io::Write) -> Result<()>, { if which::which("less").is_err() { return write(&mut io::stdout()); } let mut child = process::Command::new("less") .arg("-S") .stdin(process::Stdio::piped()) .spawn()?; { let mut less_in = child.stdin.take().unwrap(); match write(&mut less_in) { Ok(()) => (), Err(util::Error::IoError(err)) if err.kind() == io::ErrorKind::BrokenPipe => (), Err(e) => return Err(e), } } child.wait()?; Ok(()) } pub fn bandage(gfa: &str) -> Result<()> { info!("Bandage load {} --draw", gfa); if process::Command::new("Bandage") .arg("load") .arg(gfa) .arg("--draw") .spawn() .is_err() { bad_command!("failed to launch Bandage; make sure it's in PATH") } Ok(()) } pub fn bandage_temp_filename() -> Result<String> { if !atty::is(atty::Stream::Stdout) { bad_command!("supply -o filename.gfa on which to launch Bandage") } Ok(String::from( path::Path::new(&env::var("TMPDIR").unwrap_or(String::from("/tmp"))) .join(format!( "gfabase-bandage-{}.gfa", chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Micros, true) )) .to_str() .unwrap(), )) } pub fn write_header(db: &rusqlite::Connection, writer: &mut dyn io::Write) -> Result<()> { let tags_json: String = db.query_row( "SELECT tags_json FROM gfa1_header WHERE _rowid_ = 1", [], |row| row.get(0), )?; writer.write(b"H")?; write_tags("gfa1_header", 1, &tags_json, writer)?; writer.write(b"\n")?; Ok(()) } pub fn write_segments( db: &rusqlite::Connection, where_clause: &str, with_sequences: bool, mut tag_editor: impl FnMut(i64, &mut json::JsonValue) -> Result<()>, writer: &mut dyn io::Write, ) -> Result<()> { let segments_query_sql = String::from(if with_sequences { "SELECT segment_id, coalesce(name, cast(segment_id AS TEXT)), sequence_length, coalesce(tags_json, '{}'), sequence FROM gfa1_segment " } else { "SELECT segment_id, coalesce(name, cast(segment_id AS TEXT)), sequence_length, coalesce(tags_json, '{}') FROM gfa1_segment_meta " }) + where_clause; let mut segments_query = db.prepare(&segments_query_sql)?; let mut segments_cursor = segments_query.query([])?; while let Some(segrow) = segments_cursor.next()? { let rowid: i64 = segrow.get(0)?; let name: String = segrow.get(1)?; let maybe_sequence_length: Option<i64> = segrow.get(2)?; let tags_json: String = segrow.get(3)?; writer.write_fmt(format_args!("S\t{}\t", name))?; if with_sequences { match segrow.get_ref(4)? { ValueRef::Text(sequence) => writer.write(sequence)?, ValueRef::Null => writer.write(b"*")?, _ => { return Err(util::Error::InvalidGfab { message: String::from("segment row has invalid sequence value type"), table: String::from("gfa1_segment_sequence"), rowid: rowid, }) } }; } else { writer.write(b"*")?; } if let Some(sequence_length) = maybe_sequence_length { writer.write_fmt(format_args!("\tLN:i:{}", sequence_length))?; } write_tags_with_editor( "gfa1_segments_meta", rowid, &tags_json, &mut tag_editor, writer, )?; writer.write(b"\n")?; } Ok(()) } pub fn write_links( db: &rusqlite::Connection, where_clause: &str, writer: &mut dyn io::Write, ) -> Result<()> { let links_query_sql = format!( // this two-layer join resolves the two segment IDs to names (if any) "SELECT link_id, from_segment_name, from_reverse, coalesce(gfa1_segment_meta.name, cast(to_segment AS TEXT)) AS to_segment_name, to_reverse, cigar, link_tags_json FROM (SELECT gfa1_link._rowid_ AS link_id, coalesce(gfa1_segment_meta.name, cast(from_segment AS TEXT)) AS from_segment_name, from_reverse, to_segment, to_reverse, coalesce(cigar, '*') AS cigar, coalesce(gfa1_link.tags_json, '{{}}') AS link_tags_json FROM gfa1_link LEFT JOIN gfa1_segment_meta ON from_segment = segment_id {} ORDER BY from_segment, to_segment) LEFT JOIN gfa1_segment_meta ON to_segment = segment_id", where_clause ); let mut links_query = db.prepare(&links_query_sql)?; let mut links_cursor = links_query.query([])?; while let Some(linkrow) = links_cursor.next()? { let link_id: i64 = linkrow.get(0)?; let from_segment: String = linkrow.get(1)?; let from_reverse: i8 = linkrow.get(2)?; let to_segment: String = linkrow.get(3)?; let to_reverse: i8 = linkrow.get(4)?; let cigar: String = linkrow.get(5)?; let tags_json: String = linkrow.get(6)?; writer.write_fmt(format_args!( "L\t{}\t{}\t{}\t{}\t{}", from_segment, if from_reverse == 0 { '+' } else { '-' }, to_segment, if to_reverse == 0 { '+' } else { '-' }, cigar ))?; write_tags("gfa1_link", link_id, &tags_json, writer)?; writer.write(b"\n")?; } Ok(()) } pub fn write_paths( db: &rusqlite::Connection, where_clause: &str, writer: &mut dyn io::Write, ) -> Result<()> { let paths_query_sql = format!( "SELECT path_id, coalesce(name, cast(path_id AS TEXT)), coalesce(tags_json, '{{}}') FROM gfa1_path {} ORDER BY path_id", where_clause ); let mut paths_query = db.prepare(&paths_query_sql)?; let mut elements_query = db.prepare( "SELECT coalesce(name, cast(segment_id AS TEXT)) AS segment_name, reverse, cigar_vs_previous FROM gfa1_path_element LEFT JOIN gfa1_segment_meta USING(segment_id) WHERE path_id=? ORDER BY path_id, ordinal", )?; let mut paths_cursor = paths_query.query([])?; while let Some(pathrow) = paths_cursor.next()? { let path_id: i64 = pathrow.get(0)?; let name: String = pathrow.get(1)?; let tags_json: String = pathrow.get(2)?; let mut elts_csv = Vec::new(); let mut cigars_csv = Vec::new(); let mut elts_cursor = elements_query.query(params![path_id])?; while let Some(eltrow) = elts_cursor.next()? { let segment_name: String = eltrow.get(0)?; let reverse: i64 = eltrow.get(1)?; let maybe_cigar: Option<String> = eltrow.get(2)?; elts_csv.push(segment_name + if reverse == 0 { "+" } else { "-" }); if let Some(cigar) = maybe_cigar { cigars_csv.push(cigar); } } writer.write_fmt(format_args!( "P\t{}\t{}\t{}", &name, &elts_csv.join(","), if cigars_csv.len() > 0 { cigars_csv.join(",") } else { String::from("*") } ))?; write_tags("gfa1_path", path_id, &tags_json, writer)?; writer.write(b"\n")?; } Ok(()) } pub fn write_walks( db: &rusqlite::Connection, where_clause: &str, writer: &mut dyn io::Write, ) -> Result<()> { let fwd = ">".as_bytes(); let rev = "<".as_bytes(); let mut iter_walk_query = prepare_iter_walk(db)?; let walks_query_sql = format!( "SELECT walk_id, sample, hap_idx, refseq_name, refseq_begin, refseq_end, coalesce(tags_json, '{{}}') FROM gfa1_walk {} ORDER BY sample, refseq_name, hap_idx, refseq_begin", where_clause); let mut walks_query = db.prepare(&walks_query_sql)?; let mut walks_cursor = walks_query.query([])?; while let Some(row) = walks_cursor.next()? { let walk_id: i64 = row.get(0)?; let sample: String = row.get(1)?; let hap_idx: i64 = row.get(2)?; let refseq_name: String = row.get(3)?; let refseq_begin: i64 = row.get(4)?; let refseq_end: i64 = row.get(5)?; let tags_json: String = row.get(6)?; writer.write_fmt(format_args!( "W\t{}\t{}\t{}\t{}\t{}\t", sample, hap_idx, refseq_name, refseq_begin, refseq_end ))?; iter_walk(&mut iter_walk_query, walk_id, |segment_id, reverse| { writer.write(if reverse { rev } else { fwd })?; writer.write(segment_id.to_string().as_bytes())?; Ok(true) })?; write_tags("gfa1_walk", walk_id, &tags_json, writer)?; writer.write(b"\n")?; } Ok(()) } fn write_tags_with_editor( table: &str, rowid: i64, tags_json: &str, mut editor: impl FnMut(i64, &mut json::JsonValue) -> Result<()>, writer: &mut dyn io::Write, ) -> Result<()> { let invalid = || util::Error::InvalidGfab { message: String::from("invalid tags_json"), table: String::from(table), rowid: rowid, }; let mut tags = json::parse(&tags_json).map_err(|_| invalid())?; editor(rowid, &mut tags)?; for (k, v) in tags.entries() { let kfields: Vec<&str> = k.split(':').collect(); if kfields.len() != 2 { return Err(invalid()); } let vstr = match kfields[1] { "A" | "Z" | "H" => JsonValue::as_str(v).ok_or_else(invalid)?.to_string(), "i" => JsonValue::as_i64(v).ok_or_else(invalid)?.to_string(), "f" => JsonValue::as_f64(v).ok_or_else(invalid)?.to_string(), // TODO: B & J _ => return Err(invalid()), }; writer.write_fmt(format_args!("\t{}:{}", k, vstr))?; } Ok(()) } fn write_tags(table: &str, rowid: i64, tags_json: &str, writer: &mut dyn io::Write) -> Result<()> { write_tags_with_editor(table, rowid, tags_json, |_, _| Ok(()), writer) } // Helpers roughly guessing a genomic range for a segment based on its PAF mappings. Selects the // chromosome with the most coverage in the mappings, then the min and max mapped position on that // chromosome. pub struct SegmentRangeGuesser<'a> { getter: rusqlite::Statement<'a>, csv_query: rusqlite::Statement<'a>, } impl<'a> SegmentRangeGuesser<'_> { pub fn new( db: &'a rusqlite::Connection, where_clause: &str, ) -> Result<SegmentRangeGuesser<'a>> { // analyze mappings to generate temp.segment_range_guess db.execute( "CREATE TABLE temp.segment_range_guess( segment_id INTEGER PRIMARY KEY, refseq_name TEXT NOT NULL, refseq_begin INTEGER NOT NULL, refseq_end INTEGER NOT NULL)", [], )?; let sql = format!( "WITH summary AS (SELECT segment_id, refseq_name, min(refseq_begin) AS min_begin, max(refseq_end) AS max_end, max(refseq_end) - min(refseq_begin) AS coverage, sum(refseq_end - refseq_begin) AS coverage2 FROM gfa1_segment_mapping {} GROUP BY segment_id, refseq_name) INSERT INTO temp.segment_range_guess(segment_id, refseq_name, refseq_begin, refseq_end) SELECT segment_id, refseq_name, min_begin, max_end FROM (SELECT segment_id, refseq_name, min_begin, max_end, row_number() OVER (PARTITION BY segment_id ORDER BY coverage DESC, coverage2 DESC) AS coverage_rank FROM summary) WHERE coverage_rank = 1", where_clause ); let n = db.execute(&sql, [])?; info!("guessed ranges for {} segments", n); // prepare queries on temp.segment_range_guess Ok(SegmentRangeGuesser { getter: db.prepare( "SELECT refseq_name, refseq_begin, refseq_end FROM temp.segment_range_guess WHERE segment_id = ?", )?, csv_query: db.prepare( "SELECT coalesce(name, cast(segment_id AS TEXT)), refseq_name, refseq_begin, refseq_end FROM temp.segment_range_guess LEFT JOIN gfa1_segment_meta USING(segment_id)", )?, }) } pub fn get(&mut self, segment_id: i64) -> Result<Option<String>> { let maybe_row: Option<(String, i64, i64)> = self .getter .query_row(params![segment_id], |row| { Ok((row.get(0)?, row.get(1)?, row.get(2)?)) }) .optional()?; if let Some((refseq_name, refseq_begin, refseq_end)) = maybe_row { return Ok(Some(format!( "~{}:{}-{}", refseq_name, (refseq_begin + 1).to_formatted_string(&Locale::en), refseq_end.to_formatted_string(&Locale::en) ))); } Ok(None) } pub fn write_bandage_csv(&mut self, gfa_filename: &str) -> Result<()> { // write a CSV file with the guessed ranges that Bandage can show as labels let csv_filename = String::from(gfa_filename.strip_suffix(".gfa").unwrap_or(gfa_filename)) + ".guessed_ranges.csv"; { let mut writer = io::BufWriter::new(fs::File::create(&csv_filename)?); writer.write_fmt(format_args!("Name,Guessed range\n"))?; let mut cursor = self.csv_query.query([])?; while let Some(row) = cursor.next()? { let name: String = row.get(0)?; let refseq_name: String = row.get(1)?; let refseq_begin: i64 = row.get(2)?; let refseq_end: i64 = row.get(3)?; writer.write_fmt(format_args!( "\"{}\",\"~{}:{}-{}\"\n", name, refseq_name, (refseq_begin + 1).to_formatted_string(&Locale::en), refseq_end.to_formatted_string(&Locale::en) ))?; } } info!("wrote CSV with guessed segment ranges to {}", csv_filename); Ok(()) } } // Helpers for iterating over steps of a GFA Walk, automatically decoding any stored deltas to // produce a sequence of (segment_id: i64, reverse_orientation: bool). // First, a query preparation amortized over multiple Walks if needed. pub fn prepare_iter_walk<'a>(db: &'a rusqlite::Connection) -> Result<rusqlite::Statement<'a>> { match db.prepare( "SELECT json_extract(json_each.value,'$.s'), json_extract(json_each.value,'$.+'), json_extract(json_each.value,'$.-'), json_extract(json_each.value,'$.r') FROM gfa1_walk_steps, json_each(gfa1_walk_steps.steps_jsarray) WHERE walk_id = ?", ) { Ok(stmt) => Ok(stmt), Err(e) => Err(util::Error::DbError(e)), } } // Then, the iteration function taking your callback, which may return false to stop the walk // (without indicating an error). pub fn iter_walk<F>(query: &mut rusqlite::Statement, walk_id: i64, mut f: F) -> Result<()> where F: FnMut(i64, bool) -> Result<bool>, { let mut prev_segment = i64::MIN; let mut prev_reverse = false; let mut cursor = query.query(params![walk_id])?; while let Some(row) = cursor.next()? { let maybe_segment_id: Option<i64> = row.get(0)?; let maybe_plus: Option<i64> = row.get(1)?; let maybe_minus: Option<i64> = row.get(2)?; let maybe_reverse: Option<i64> = row.get(3)?; let segment_id = if maybe_segment_id.is_some() { maybe_segment_id.unwrap() } else if maybe_plus.is_some() { prev_segment + maybe_plus.unwrap() } else if maybe_minus.is_some() { prev_segment - maybe_minus.unwrap() } else { return Err(util::Error::InvalidGfab { message: String::from("Walk has invalid delta-encoding"), table: String::from("gfa1_walk_steps"), rowid: walk_id, }); }; let reverse = maybe_reverse.map_or(prev_reverse, |r| r != 0); if !f(segment_id, reverse)? { break; } prev_segment = segment_id; prev_reverse = reverse; } Ok(()) }
{ return Ok(Box::new(io::BufWriter::new(io::stdout()))); }
conditional_block
do.go
/** * (Probably) the world's first one file RPA tool impremented by Golang! * * @author yasutakatou * @copyright 2020 yasutakatou * @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 , 3-clause BSD License */ package main import ( "bufio" "crypto/md5" "encoding/hex" "flag" "fmt" "image" "io" "log" "math/rand" "os" "path/filepath" "strconv" "strings" "syscall" "time" "unsafe" "github.com/go-vgo/robotgo" "github.com/kbinani/screenshot" hook "github.com/robotn/gohook" "github.com/yasutakatou/string2keyboard" "gocv.io/x/gocv" "golang.org/x/image/bmp" ) type ( HANDLE uintptr HWND HANDLE ) type RECTdata struct { Left int32 Top int32 Right int32 Bottom int32 } var ( user32 = syscall.MustLoadDLL("user32.dll") procEnumWindows = user32.MustFindProc("EnumWindows") procGetWindowTextW = user32.MustFindProc("GetWindowTextW") procSetActiveWindow = user32.MustFindProc("SetActiveWindow") procSetForegroundWindow = user32.MustFindProc("SetForegroundWindow") procGetForegroundWindow = user32.MustFindProc("GetForegroundWindow") procGetWindowRect = user32.MustFindProc("GetWindowRect") rs1Letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") History = []historyData{} Hashs = []hashData{} Debug bool LiveExitAsciiCode int preWindow string aftWindow string LiveRawcodeChar string sameThreshold float32 tryCounter int waitSeconds int TEMPDir string prevDir string tempX int tempY int moveThreshold int ) type historyData struct { Device string `json:"Device"` Pre string `json:"Pre"` Aft string `json:"Aft"` Params string `json:"Params"` } type hashData struct { Filename string `json:"Filename"` Hash string `json:"Hash"` } func init() { rand.Seed(time.Now().UnixNano()) LiveRawcodeChar = "~" preWindow = "" aftWindow = "" } func main() { _List := flag.Bool("list", false, "[-list=listing window titiles and exit]") _Replay := flag.Bool("replay", false, "[-replay=replay mode (true is enable)]") _Record := flag.Bool("record", true, "[-record=recording mode (true is enable)]") _exportFile := flag.String("export", "output.tsv", "[-export=export file name]") _importFile := flag.String("import", "input.tsv", "[-import=import file name]") _DEBUG := flag.Bool("debug", false, "[-debug=debug mode (true is enable)]") _threshold := flag.Float64("threshold", 0.1, "[-threshold=same window threshold]") _move := flag.Float64("move", 50, "[-move=mouse move record threshold]") _try := flag.Int("try", 10, "[-try=error and try counter]") _wait := flag.Int("wait", 250, "[-wait=loop wait Millisecond]") _exitCode := flag.Int("exitCode", 27, "[-exitCode=recording mode to exit ascii key code]") _tmpDir := flag.String("tmpDir", "tmp", "[-tmpDir=temporary directory name]") flag.Parse() if *_List == true { getHwndToTitle(0, true) os.Exit(0) } Debug = bool(*_DEBUG) sameThreshold = float32(*_threshold) tryCounter = int(*_try) waitSeconds = int(*_wait) LiveExitAsciiCode = int(*_exitCode) moveThreshold = int(*_move) prevDir, _ = filepath.Abs(".") TEMPDir = prevDir + "\\" + string(*_tmpDir) + "\\" if Exists(TEMPDir) == true { if *_Record == true && *_Replay == false { if err := os.RemoveAll(TEMPDir); err != nil { fmt.Println(err) } } } if err := os.MkdirAll(TEMPDir, 0777); err != nil { fmt.Println(err) } os.Chdir(TEMPDir) if *_DEBUG == true { fmt.Println(" - - - options - - - ") fmt.Println("list: ", *_List) fmt.Println("replay: ", *_Replay) fmt.Println("record: ", *_Record) fmt.Println("export: ", *_exportFile) fmt.Println("import: ", *_importFile) fmt.Println("debug: ", Debug) fmt.Println("threshold: ", sameThreshold) fmt.Println("move: ", moveThreshold) fmt.Println("try: ", tryCounter) fmt.Println("wait: ", waitSeconds) fmt.Println("exitCode: ", LiveExitAsciiCode) fmt.Println("tmpDir: ", TEMPDir) fmt.Println(" - - - - - - - - - ") } switch *_Record { case true: if *_Replay == true { replayMode(prevDir + "\\" + *_importFile) } else { recordingMode(*_exportFile) } case false: if *_Replay == false { recordingMode(*_exportFile) } else { replayMode(prevDir + "\\" + *_importFile) } } os.Chdir(prevDir) os.Exit(0) } func Exists(filename string) bool { _, err := os.Stat(filename) return err == nil } func ImportHistory(params string) bool { if len(params) == 0 { return false } file, err := os.Open(params) if err != nil { fmt.Println(err) return false } defer file.Close() History = nil s := bufio.NewScanner(file) for s.Scan() { strs := strings.Split(s.Text(), "\t") if len(strs) != 4 { fmt.Println("Error: your tsv file broken") History = nil return false } History = append(History, historyData{Device: strs[0], Pre: strs[1], Aft: strs[2], Params: strs[3]}) } fmt.Println("importFile: ", params) return true } func replayMode(importFile string) { if Exists(importFile) == false { fmt.Println("not found: ", importFile) } ImportHistory(importFile) for i := 0; i < len(History); i++ { fmt.Println("Device: ", History[i].Device, "Pre: ", History[i].Pre, "Aft: ", History[i].Aft, "Params: ", History[i].Params) if setTargetWindow(i) == false { return } switch History[i].Device { case "key": SendKey(History[i].Params) case "click", "move": strs := strings.Split(History[i].Params, ";") origFilename := getNowFilename() if Exists(origFilename) == false { break } matImage := gocv.IMRead(origFilename, gocv.IMReadGrayScale) targetX := 0 targetY := 0 partImage := "" if History[i].Device == "click" { partImage = strs[1] targetX, _ = strconv.Atoi(strs[2]) targetY, _ = strconv.Atoi(strs[3]) } else { partImage = strs[0] targetX, _ = strconv.Atoi(strs[1]) targetY, _ = strconv.Atoi(strs[2]) } if Debug == true { fmt.Println("origFilename: ", origFilename, " partImage: ", partImage) } if Exists(partImage) == false { break } matTemplate := gocv.IMRead(partImage, gocv.IMReadGrayScale) matResult := gocv.NewMat() mask := gocv.NewMat() gocv.MatchTemplate(matImage, matTemplate, &matResult, gocv.TmCcoeffNormed, mask) mask.Close() minConfidence, maxConfidence, minLoc, maxLoc := gocv.MinMaxLoc(matResult) if Debug == true { fmt.Println("mouseLocate: ", minConfidence, maxConfidence, minLoc, maxLoc) } if err := os.Remove(origFilename); err != nil { fmt.Println(err) } if maxConfidence > sameThreshold { actionX := maxLoc.X + targetX actionY := maxLoc.Y + targetY robotgo.MoveMouseSmooth(actionX, actionY, 0.01, 0.01) if History[i].Device == "click" { if strs[4] == "1" { robotgo.MouseClick("left", false) } else { robotgo.MouseClick("right", false) } } } else { if Debug == true { fmt.Println("under same Threshold: ", sameThreshold, " > ", maxConfidence) } } } time.Sleep(time.Duration(waitSeconds) * time.Millisecond) } } func setTargetWindow(i int) bool { if len(History[i].Pre) > 0 { if targetHwnd := FocusWindow(History[i].Pre, Debug); ChangeTarget(targetHwnd) == false { fmt.Println("not found title: ", History[i].Pre) if len(History[i].Aft) > 0 { if targetHwnd := FocusWindow(History[i].Aft, Debug); ChangeTarget(targetHwnd) == false { fmt.Println("not found title: ", History[i].Aft) return false } } } } return true } func getNowFilename() string { origFilename := "" nowFilename := RandStr(8) + ".bmp" n := screenshot.NumActiveDisplays() if n <= 0 { panic("Active display not found") } var all image.Rectangle = image.Rect(0, 0, 0, 0) for i := 0; i < n; i++ { bounds := screenshot.GetDisplayBounds(i) all = bounds.Union(all) } bitmap := robotgo.CaptureScreen(all.Min.X, all.Min.Y, all.Dx(), all.Dy()) robotgo.SaveBitmap(bitmap, nowFilename) tmpHash := calcHash(nowFilename) hFlag := -1 for i := 0; i < len(Hashs); i++ { if Hashs[i].Hash == tmpHash { hFlag = i break } } if hFlag == -1 { Hashs = append(Hashs, hashData{Filename: nowFilename, Hash: tmpHash}) origFilename = nowFilename } else { origFilename = Hashs[hFlag].Filename if err := os.Remove(origFilename); err != nil { fmt.Println(err) } } return origFilename } func SendKey(doCmd string) bool { if Debug == true { fmt.Printf("KeyInput: ") } cCtrl := false cAlt := false if strings.Index(doCmd, "ctrl+") != -1 { cCtrl = true doCmd = strings.Replace(doCmd, "ctrl+", "", 1) if Debug == true { fmt.Printf("ctrl+") } } if strings.Index(doCmd, "alt+") != -1 { cAlt = true doCmd = strings.Replace(doCmd, "alt+", "", 1) if Debug == true { fmt.Printf("alt+") } } string2keyboard.KeyboardWrite(doCmd, cCtrl, cAlt, LiveRawcodeChar) if Debug == true { fmt.Println(doCmd, cCtrl, cAlt) } return true } func saveToBmp(img *image.RGBA, filePath string) { file, err := os.Create(filePath) if err != nil { panic(err) } defer file.Close() bmp.Encode(file, img) } func searchHash(targetHash string, allPartFlag bool) (string, string) { //all: 1, part 3, move 1 for i := 0; i < len(History); i++ { if History[i].Device == "click" || History[i].Device == "move" { strs := strings.Split(History[i].Params, ";") if allPartFlag == true && targetHash == strs[1] { return strs[0], strs[1] } if allPartFlag == false && targetHash == strs[3] { return strs[2], strs[3] } } } return "", "" } func CaptureCase(filename, target string, setHwnd uintptr, hFlag bool) (string, string) { var rect RECTdata if target == "" && setHwnd == 0 { n := screenshot.NumActiveDisplays() if n <= 0 { panic("Active display not found") } var all image.Rectangle = image.Rect(0, 0, 0, 0) for i := 0; i < n; i++ { bounds := screenshot.GetDisplayBounds(i) all = bounds.Union(all) } bitmap := robotgo.CaptureScreen(all.Min.X, all.Min.Y, all.Dx(), all.Dy()) robotgo.SaveBitmap(bitmap, filename) } else { ChangeTarget(setHwnd) GetWindowRect(HWND(setHwnd), &rect, Debug) bitmap := robotgo.CaptureScreen(int(rect.Left), int(rect.Top), int(rect.Right-rect.Left), int(rect.Bottom-rect.Top)) robotgo.SaveBitmap(bitmap, filename) } tmpHash := calcHash(filename) if _, Hash := searchHash(tmpHash, hFlag); Hash == "" { return filename, tmpHash } if err := os.Remove(filename); err != nil { fmt.Println(err) } return "", tmpHash } func calcHash(filename string) string { f, err := os.Open(filename) if err != nil { log.Fatal(err) } defer f.Close() h := md5.New() if _, err := io.Copy(h, f); err != nil { log.Fatal(err) } return fmt.Sprintf("%x", h.Sum(nil)) } func getHwndToTitle(targetHwnd uintptr, listMode bool) string { lists := ListWindow(Debug) for i := 0; i < len(lists); i++ { if listMode == true { fmt.Println(lists[i]) } else { strs := strings.Split(lists[i], " : ") if strings.Index(fmt.Sprintf("%x", targetHwnd), strs[1]) != -1 { return strs[0] } } } return "" } func ChangeTarget(setHwnd uintptr) bool { breakCounter := tryCounter for { if Debug == true { fmt.Printf("tryCounter: %d\n", breakCounter) } if setHwnd != GetWindow("GetForegroundWindow", Debug)
else { return true } breakCounter = breakCounter - 1 if breakCounter < 0 { return false } time.Sleep(time.Duration(waitSeconds) * time.Millisecond) } } func recordingMode(exportFile string) { fmt.Printf(" - - recording start! you want to end this mode, key press ascii code (%d) - - \n", LiveExitAsciiCode) altFlag := 0 actFlag := false var bufStrs uint16 bufStrs = 0 EvChan := hook.Start() defer hook.End() for ev := range EvChan { strs := "" if actFlag == true { if ev.Kind == 3 { //KeyDown = 3 bufStrs, strs = keyDown(altFlag, int(ev.Rawcode), strs, string(ev.Keychar), bufStrs) preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } if ev.Kind == 4 || ev.Kind == 5 { //KeyHold = 4,KeyUp = 5 altFlag = keyHoldUp(int(ev.Rawcode), int(ev.Kind), bufStrs, exportFile) if altFlag == 256 { return } preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } if ev.Kind == 9 { //MouseMove = 9 if moveValCheck(int(ev.X), int(ev.Y)) == true { addMouseMove(int(ev.X), int(ev.Y)) } preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } } if ev.Kind == 7 { //MouseHold if actFlag == false { actFlag = true aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } addMouseAction(int(ev.Button), int(ev.X), int(ev.Y)) preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } } } func moveValCheck(evX, evY int) bool { if tempX-int(evX) > moveThreshold { return true } if tempY-int(evY) > (moveThreshold / 2) { return true } if int(evX)-tempX > moveThreshold { return true } if int(evY)-tempY > (moveThreshold / 2) { return true } return false } func keyDown(altFlag, Rawcode int, strs, keyChar string, bufStrs uint16) (uint16, string) { if altFlag == 0 { switch Rawcode { case 8: strs = "\\b" case 9: strs = "\\t" case 13: strs = "\\n" default: strs = keyChar } } else { switch altFlag { case 162: strs = "ctrl+" + keyChar case 164: strs = "alt+" + keyChar } } bufStrs = uint16(Rawcode) addHistory("key", strs) return bufStrs, strs } func keyHoldUp(Rawcode, Kind int, bufStrs uint16, exportFile string) int { altFlag := 0 switch Rawcode { case 162, 164: //Ctrl,Alt if Kind == 4 { altFlag = Rawcode } else { altFlag = 0 } case LiveExitAsciiCode: //Default Escape ExportHistory(exportFile) return 256 case 160: default: if Kind == 5 && int(bufStrs) != Rawcode { addHistory("key", "\\"+LiveRawcodeChar+strconv.Itoa(Rawcode)+LiveRawcodeChar) } } return altFlag } func addMouseMove(evX, evY int) { var rect RECTdata moveFileName := RandStr(8) + ".bmp" currentHwnd := GetWindow("GetForegroundWindow", false) GetWindowRect(HWND(currentHwnd), &rect, false) moveFileName, moveHash := CaptureCase(moveFileName, "", currentHwnd, true) if moveFileName == "" { moveFileName, _ = searchHash(moveHash, true) } if evX > 0 && evX > int(rect.Left) && evX < int(rect.Right) { if evY > 0 && evX > int(rect.Top) && evY < int(rect.Bottom) { targetX := int(evX) - int(rect.Left) targetY := int(evY) - int(rect.Top) //targetImg,targetImgHash,x,y addHistory("move", moveFileName+";"+moveHash+";"+strconv.Itoa(targetX)+";"+strconv.Itoa(targetY)) tempX = evX tempY = evY } } } func addMouseAction(evButton, evX, evY int) { targetX := 0 targetY := 0 allFilename := RandStr(8) + ".bmp" allFilename, allHash := CaptureCase(allFilename, "", 0, true) if allFilename == "" { allFilename, _ = searchHash(allHash, true) } partFileName := RandStr(8) + ".bmp" currentHwnd := GetWindow("GetForegroundWindow", Debug) partFileName, partHash := CaptureCase(partFileName, "", currentHwnd, false) if partFileName == "" { partFileName, _ = searchHash(partHash, false) } if Exists(allFilename) == false { return } matImage := gocv.IMRead(allFilename, gocv.IMReadGrayScale) if Exists(partFileName) == false { return } matTemplate := gocv.IMRead(partFileName, gocv.IMReadGrayScale) matResult := gocv.NewMat() mask := gocv.NewMat() gocv.MatchTemplate(matImage, matTemplate, &matResult, gocv.TmCcoeffNormed, mask) mask.Close() minConfidence, maxConfidence, minLoc, maxLoc := gocv.MinMaxLoc(matResult) if Debug == true { fmt.Println(minConfidence, maxConfidence, minLoc, maxLoc) } targetX = int(evX) - maxLoc.X targetY = int(evY) - maxLoc.Y tempX = evX tempY = evY //allImg,allImageHash,targetImg,targetImgHash,x,y,clickType addHistory("click", allFilename+";"+allHash+";"+partFileName+";"+partHash+";"+strconv.Itoa(targetX)+";"+strconv.Itoa(targetY)+";"+strconv.Itoa(evButton)) } func GetMD5Hash(text string) string { hasher := md5.New() hasher.Write([]byte(text)) return hex.EncodeToString(hasher.Sum(nil)) } func addHistory(device, strs string) { if len(strs) > 0 { History = append(History, historyData{Device: device, Pre: preWindow, Aft: aftWindow, Params: strs}) if Debug == true { fmt.Println("liveRecord: ", strs) } } } func ListWindow(Debug bool) []string { var rect RECTdata ret := []string{} cb := syscall.NewCallback(func(h syscall.Handle, p uintptr) uintptr { b := make([]uint16, 200) _, err := GetWindowText(h, &b[0], int32(len(b))) if err != nil { return 1 } GetWindowRect(HWND(h), &rect, Debug) if rect.Left != 0 || rect.Top != 0 || rect.Right != 0 || rect.Bottom != 0 { if Debug == true { fmt.Printf("Window Title '%s' window: handle=0x%x\n", syscall.UTF16ToString(b), h) if rect.Left != 0 || rect.Top != 0 || rect.Right != 0 || rect.Bottom != 0 { fmt.Printf("window rect: ") fmt.Println(rect) } } ret = append(ret, fmt.Sprintf("%s : %x", syscall.UTF16ToString(b), h)) } return 1 }) EnumWindows(cb, 0) return ret } func matchCheck(stra, strb string) bool { if strings.Index(strb, stra) != -1 { return true } else { if strings.Index(stra, strb) != -1 { return true } } return false } func FocusWindow(title string, Debug bool) uintptr { var hwnd syscall.Handle var rect RECTdata cb := syscall.NewCallback(func(h syscall.Handle, p uintptr) uintptr { b := make([]uint16, 200) _, err := GetWindowText(h, &b[0], int32(len(b))) if err != nil { return 1 } if Debug == true { fmt.Printf("EnumWindows Search '%s' window: handle=0x%x\n", syscall.UTF16ToString(b), h) } if matchCheck(title, syscall.UTF16ToString(b)) == true { if Debug == true { fmt.Printf("Found! window: '%s' handle=0x%x\n", syscall.UTF16ToString(b), h) } GetWindowRect(HWND(h), &rect, Debug) fmt.Println() if int(rect.Right-rect.Left) > 0 && int(rect.Bottom-rect.Top) > 0 { hwnd = h return 0 } } return 1 }) EnumWindows(cb, 0) return uintptr(hwnd) } func GetWindow(funcName string, Debug bool) uintptr { hwnd, _, _ := syscall.Syscall(procGetForegroundWindow.Addr(), 6, 0, 0, 0) if Debug == true { fmt.Printf("currentWindow: handle=0x%x.\n", hwnd) } return hwnd } func SetActiveWindow(hwnd HWND, Debug bool) { if Debug == true { fmt.Printf("SetActiveWindow: handle=0x%x.\n", hwnd) } syscall.Syscall(procSetActiveWindow.Addr(), 4, uintptr(hwnd), 0, 0) syscall.Syscall(procSetForegroundWindow.Addr(), 5, uintptr(hwnd), 0, 0) } func GetWindowRect(hwnd HWND, rect *RECTdata, Debug bool) (err error) { r1, _, e1 := syscall.Syscall(procGetWindowRect.Addr(), 7, uintptr(hwnd), uintptr(unsafe.Pointer(rect)), 0) if r1 == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } func GetWindowText(hwnd syscall.Handle, str *uint16, maxCount int32) (len int32, err error) { r0, _, e1 := syscall.Syscall(procGetWindowTextW.Addr(), 3, uintptr(hwnd), uintptr(unsafe.Pointer(str)), uintptr(maxCount)) if len = int32(r0); len == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } func EnumWindows(enumFunc uintptr, lparam uintptr) (err error) { r1, _, e1 := syscall.Syscall(procEnumWindows.Addr(), 2, uintptr(enumFunc), uintptr(lparam), 0) if r1 == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } func RandStr(n int) string { b := make([]rune, n) for i := range b { b[i] = rs1Letters[rand.Intn(len(rs1Letters))] } return string(b) } func ExportHistory(filename string) bool { file, err := os.Create(prevDir + "\\" + filename) if err != nil { fmt.Println(err) return false } defer file.Close() for i := 0; i < len(History); i++ { strs := "" if History[i].Device == "click" { stra := strings.Split(History[i].Params, ";") strs = History[i].Device + "\t" + History[i].Pre + "\t" + History[i].Aft + "\t" + stra[0] + ";" + stra[2] + ";" + stra[4] + ";" + stra[5] + ";" + stra[6] } else if History[i].Device == "move" { stra := strings.Split(History[i].Params, ";") strs = History[i].Device + "\t" + History[i].Pre + "\t" + History[i].Aft + "\t" + stra[0] + ";" + stra[2] + ";" + stra[3] } else { strs = History[i].Device + "\t" + History[i].Pre + "\t" + History[i].Aft + "\t" + History[i].Params } if Debug == true { fmt.Printf("[%3d]: %s\n", i+1, strs) } if _, err = file.WriteString(strs + "\n"); err != nil { fmt.Println(err) return false } } fmt.Println("exportFile: ", filename) return true }
{ SetActiveWindow(HWND(setHwnd), Debug) }
conditional_block
do.go
/** * (Probably) the world's first one file RPA tool impremented by Golang! * * @author yasutakatou * @copyright 2020 yasutakatou * @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 , 3-clause BSD License */ package main import ( "bufio" "crypto/md5" "encoding/hex" "flag" "fmt" "image" "io" "log" "math/rand" "os" "path/filepath" "strconv" "strings" "syscall" "time" "unsafe" "github.com/go-vgo/robotgo" "github.com/kbinani/screenshot" hook "github.com/robotn/gohook" "github.com/yasutakatou/string2keyboard" "gocv.io/x/gocv" "golang.org/x/image/bmp" ) type ( HANDLE uintptr HWND HANDLE ) type RECTdata struct { Left int32 Top int32 Right int32 Bottom int32 } var ( user32 = syscall.MustLoadDLL("user32.dll") procEnumWindows = user32.MustFindProc("EnumWindows") procGetWindowTextW = user32.MustFindProc("GetWindowTextW") procSetActiveWindow = user32.MustFindProc("SetActiveWindow") procSetForegroundWindow = user32.MustFindProc("SetForegroundWindow") procGetForegroundWindow = user32.MustFindProc("GetForegroundWindow") procGetWindowRect = user32.MustFindProc("GetWindowRect") rs1Letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") History = []historyData{} Hashs = []hashData{} Debug bool LiveExitAsciiCode int preWindow string aftWindow string LiveRawcodeChar string sameThreshold float32 tryCounter int waitSeconds int TEMPDir string prevDir string tempX int tempY int moveThreshold int ) type historyData struct { Device string `json:"Device"` Pre string `json:"Pre"` Aft string `json:"Aft"` Params string `json:"Params"` } type hashData struct { Filename string `json:"Filename"` Hash string `json:"Hash"` } func init() { rand.Seed(time.Now().UnixNano()) LiveRawcodeChar = "~" preWindow = "" aftWindow = "" } func main() { _List := flag.Bool("list", false, "[-list=listing window titiles and exit]") _Replay := flag.Bool("replay", false, "[-replay=replay mode (true is enable)]") _Record := flag.Bool("record", true, "[-record=recording mode (true is enable)]") _exportFile := flag.String("export", "output.tsv", "[-export=export file name]") _importFile := flag.String("import", "input.tsv", "[-import=import file name]") _DEBUG := flag.Bool("debug", false, "[-debug=debug mode (true is enable)]") _threshold := flag.Float64("threshold", 0.1, "[-threshold=same window threshold]") _move := flag.Float64("move", 50, "[-move=mouse move record threshold]") _try := flag.Int("try", 10, "[-try=error and try counter]") _wait := flag.Int("wait", 250, "[-wait=loop wait Millisecond]") _exitCode := flag.Int("exitCode", 27, "[-exitCode=recording mode to exit ascii key code]") _tmpDir := flag.String("tmpDir", "tmp", "[-tmpDir=temporary directory name]") flag.Parse() if *_List == true { getHwndToTitle(0, true) os.Exit(0) } Debug = bool(*_DEBUG) sameThreshold = float32(*_threshold) tryCounter = int(*_try) waitSeconds = int(*_wait) LiveExitAsciiCode = int(*_exitCode) moveThreshold = int(*_move) prevDir, _ = filepath.Abs(".") TEMPDir = prevDir + "\\" + string(*_tmpDir) + "\\" if Exists(TEMPDir) == true { if *_Record == true && *_Replay == false { if err := os.RemoveAll(TEMPDir); err != nil { fmt.Println(err) } } } if err := os.MkdirAll(TEMPDir, 0777); err != nil { fmt.Println(err) } os.Chdir(TEMPDir) if *_DEBUG == true { fmt.Println(" - - - options - - - ") fmt.Println("list: ", *_List) fmt.Println("replay: ", *_Replay) fmt.Println("record: ", *_Record) fmt.Println("export: ", *_exportFile) fmt.Println("import: ", *_importFile) fmt.Println("debug: ", Debug) fmt.Println("threshold: ", sameThreshold) fmt.Println("move: ", moveThreshold) fmt.Println("try: ", tryCounter) fmt.Println("wait: ", waitSeconds) fmt.Println("exitCode: ", LiveExitAsciiCode) fmt.Println("tmpDir: ", TEMPDir) fmt.Println(" - - - - - - - - - ") } switch *_Record { case true: if *_Replay == true { replayMode(prevDir + "\\" + *_importFile) } else { recordingMode(*_exportFile) } case false: if *_Replay == false { recordingMode(*_exportFile) } else { replayMode(prevDir + "\\" + *_importFile) } } os.Chdir(prevDir) os.Exit(0) } func Exists(filename string) bool { _, err := os.Stat(filename) return err == nil } func ImportHistory(params string) bool { if len(params) == 0 { return false } file, err := os.Open(params) if err != nil { fmt.Println(err) return false } defer file.Close() History = nil s := bufio.NewScanner(file) for s.Scan() { strs := strings.Split(s.Text(), "\t") if len(strs) != 4 { fmt.Println("Error: your tsv file broken") History = nil return false } History = append(History, historyData{Device: strs[0], Pre: strs[1], Aft: strs[2], Params: strs[3]}) } fmt.Println("importFile: ", params) return true } func replayMode(importFile string) { if Exists(importFile) == false { fmt.Println("not found: ", importFile) } ImportHistory(importFile) for i := 0; i < len(History); i++ { fmt.Println("Device: ", History[i].Device, "Pre: ", History[i].Pre, "Aft: ", History[i].Aft, "Params: ", History[i].Params) if setTargetWindow(i) == false { return } switch History[i].Device { case "key": SendKey(History[i].Params) case "click", "move": strs := strings.Split(History[i].Params, ";") origFilename := getNowFilename() if Exists(origFilename) == false { break } matImage := gocv.IMRead(origFilename, gocv.IMReadGrayScale) targetX := 0 targetY := 0 partImage := "" if History[i].Device == "click" { partImage = strs[1] targetX, _ = strconv.Atoi(strs[2]) targetY, _ = strconv.Atoi(strs[3]) } else { partImage = strs[0] targetX, _ = strconv.Atoi(strs[1]) targetY, _ = strconv.Atoi(strs[2]) } if Debug == true { fmt.Println("origFilename: ", origFilename, " partImage: ", partImage) } if Exists(partImage) == false { break } matTemplate := gocv.IMRead(partImage, gocv.IMReadGrayScale) matResult := gocv.NewMat() mask := gocv.NewMat() gocv.MatchTemplate(matImage, matTemplate, &matResult, gocv.TmCcoeffNormed, mask) mask.Close() minConfidence, maxConfidence, minLoc, maxLoc := gocv.MinMaxLoc(matResult) if Debug == true { fmt.Println("mouseLocate: ", minConfidence, maxConfidence, minLoc, maxLoc) } if err := os.Remove(origFilename); err != nil { fmt.Println(err) } if maxConfidence > sameThreshold { actionX := maxLoc.X + targetX actionY := maxLoc.Y + targetY robotgo.MoveMouseSmooth(actionX, actionY, 0.01, 0.01) if History[i].Device == "click" { if strs[4] == "1" { robotgo.MouseClick("left", false) } else { robotgo.MouseClick("right", false) } } } else { if Debug == true { fmt.Println("under same Threshold: ", sameThreshold, " > ", maxConfidence) } } } time.Sleep(time.Duration(waitSeconds) * time.Millisecond) } } func setTargetWindow(i int) bool { if len(History[i].Pre) > 0 { if targetHwnd := FocusWindow(History[i].Pre, Debug); ChangeTarget(targetHwnd) == false { fmt.Println("not found title: ", History[i].Pre) if len(History[i].Aft) > 0 { if targetHwnd := FocusWindow(History[i].Aft, Debug); ChangeTarget(targetHwnd) == false { fmt.Println("not found title: ", History[i].Aft) return false } } } } return true } func getNowFilename() string { origFilename := "" nowFilename := RandStr(8) + ".bmp" n := screenshot.NumActiveDisplays() if n <= 0 { panic("Active display not found") } var all image.Rectangle = image.Rect(0, 0, 0, 0) for i := 0; i < n; i++ { bounds := screenshot.GetDisplayBounds(i) all = bounds.Union(all) } bitmap := robotgo.CaptureScreen(all.Min.X, all.Min.Y, all.Dx(), all.Dy()) robotgo.SaveBitmap(bitmap, nowFilename) tmpHash := calcHash(nowFilename) hFlag := -1 for i := 0; i < len(Hashs); i++ { if Hashs[i].Hash == tmpHash { hFlag = i break } } if hFlag == -1 { Hashs = append(Hashs, hashData{Filename: nowFilename, Hash: tmpHash}) origFilename = nowFilename } else { origFilename = Hashs[hFlag].Filename if err := os.Remove(origFilename); err != nil { fmt.Println(err) } } return origFilename } func SendKey(doCmd string) bool { if Debug == true { fmt.Printf("KeyInput: ") } cCtrl := false cAlt := false if strings.Index(doCmd, "ctrl+") != -1 { cCtrl = true doCmd = strings.Replace(doCmd, "ctrl+", "", 1) if Debug == true { fmt.Printf("ctrl+") } } if strings.Index(doCmd, "alt+") != -1 { cAlt = true doCmd = strings.Replace(doCmd, "alt+", "", 1) if Debug == true { fmt.Printf("alt+") } } string2keyboard.KeyboardWrite(doCmd, cCtrl, cAlt, LiveRawcodeChar) if Debug == true { fmt.Println(doCmd, cCtrl, cAlt) } return true } func saveToBmp(img *image.RGBA, filePath string) { file, err := os.Create(filePath) if err != nil { panic(err) } defer file.Close() bmp.Encode(file, img) } func searchHash(targetHash string, allPartFlag bool) (string, string) { //all: 1, part 3, move 1 for i := 0; i < len(History); i++ { if History[i].Device == "click" || History[i].Device == "move" { strs := strings.Split(History[i].Params, ";") if allPartFlag == true && targetHash == strs[1] { return strs[0], strs[1] } if allPartFlag == false && targetHash == strs[3] { return strs[2], strs[3] } } } return "", "" } func CaptureCase(filename, target string, setHwnd uintptr, hFlag bool) (string, string) { var rect RECTdata if target == "" && setHwnd == 0 { n := screenshot.NumActiveDisplays() if n <= 0 { panic("Active display not found") } var all image.Rectangle = image.Rect(0, 0, 0, 0) for i := 0; i < n; i++ { bounds := screenshot.GetDisplayBounds(i) all = bounds.Union(all) } bitmap := robotgo.CaptureScreen(all.Min.X, all.Min.Y, all.Dx(), all.Dy()) robotgo.SaveBitmap(bitmap, filename) } else { ChangeTarget(setHwnd) GetWindowRect(HWND(setHwnd), &rect, Debug) bitmap := robotgo.CaptureScreen(int(rect.Left), int(rect.Top), int(rect.Right-rect.Left), int(rect.Bottom-rect.Top)) robotgo.SaveBitmap(bitmap, filename) } tmpHash := calcHash(filename) if _, Hash := searchHash(tmpHash, hFlag); Hash == "" { return filename, tmpHash } if err := os.Remove(filename); err != nil { fmt.Println(err) } return "", tmpHash } func calcHash(filename string) string { f, err := os.Open(filename) if err != nil { log.Fatal(err) } defer f.Close() h := md5.New() if _, err := io.Copy(h, f); err != nil { log.Fatal(err) } return fmt.Sprintf("%x", h.Sum(nil)) } func getHwndToTitle(targetHwnd uintptr, listMode bool) string { lists := ListWindow(Debug) for i := 0; i < len(lists); i++ { if listMode == true { fmt.Println(lists[i]) } else { strs := strings.Split(lists[i], " : ") if strings.Index(fmt.Sprintf("%x", targetHwnd), strs[1]) != -1 { return strs[0] } } } return "" } func ChangeTarget(setHwnd uintptr) bool { breakCounter := tryCounter for { if Debug == true { fmt.Printf("tryCounter: %d\n", breakCounter) } if setHwnd != GetWindow("GetForegroundWindow", Debug) { SetActiveWindow(HWND(setHwnd), Debug) } else { return true } breakCounter = breakCounter - 1 if breakCounter < 0 { return false } time.Sleep(time.Duration(waitSeconds) * time.Millisecond) } } func recordingMode(exportFile string) { fmt.Printf(" - - recording start! you want to end this mode, key press ascii code (%d) - - \n", LiveExitAsciiCode) altFlag := 0 actFlag := false var bufStrs uint16 bufStrs = 0 EvChan := hook.Start() defer hook.End() for ev := range EvChan { strs := "" if actFlag == true { if ev.Kind == 3 { //KeyDown = 3 bufStrs, strs = keyDown(altFlag, int(ev.Rawcode), strs, string(ev.Keychar), bufStrs) preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } if ev.Kind == 4 || ev.Kind == 5 { //KeyHold = 4,KeyUp = 5 altFlag = keyHoldUp(int(ev.Rawcode), int(ev.Kind), bufStrs, exportFile) if altFlag == 256 { return } preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } if ev.Kind == 9 { //MouseMove = 9 if moveValCheck(int(ev.X), int(ev.Y)) == true { addMouseMove(int(ev.X), int(ev.Y)) } preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } } if ev.Kind == 7 { //MouseHold if actFlag == false { actFlag = true aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } addMouseAction(int(ev.Button), int(ev.X), int(ev.Y)) preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } } } func moveValCheck(evX, evY int) bool { if tempX-int(evX) > moveThreshold { return true } if tempY-int(evY) > (moveThreshold / 2) { return true } if int(evX)-tempX > moveThreshold { return true } if int(evY)-tempY > (moveThreshold / 2) { return true } return false } func keyDown(altFlag, Rawcode int, strs, keyChar string, bufStrs uint16) (uint16, string) { if altFlag == 0 { switch Rawcode { case 8: strs = "\\b" case 9: strs = "\\t" case 13: strs = "\\n" default: strs = keyChar } } else { switch altFlag { case 162: strs = "ctrl+" + keyChar case 164: strs = "alt+" + keyChar } } bufStrs = uint16(Rawcode) addHistory("key", strs) return bufStrs, strs } func keyHoldUp(Rawcode, Kind int, bufStrs uint16, exportFile string) int { altFlag := 0 switch Rawcode { case 162, 164: //Ctrl,Alt if Kind == 4 { altFlag = Rawcode } else { altFlag = 0 } case LiveExitAsciiCode: //Default Escape ExportHistory(exportFile) return 256 case 160: default: if Kind == 5 && int(bufStrs) != Rawcode { addHistory("key", "\\"+LiveRawcodeChar+strconv.Itoa(Rawcode)+LiveRawcodeChar) } } return altFlag } func addMouseMove(evX, evY int) { var rect RECTdata moveFileName := RandStr(8) + ".bmp" currentHwnd := GetWindow("GetForegroundWindow", false) GetWindowRect(HWND(currentHwnd), &rect, false) moveFileName, moveHash := CaptureCase(moveFileName, "", currentHwnd, true) if moveFileName == "" { moveFileName, _ = searchHash(moveHash, true) } if evX > 0 && evX > int(rect.Left) && evX < int(rect.Right) { if evY > 0 && evX > int(rect.Top) && evY < int(rect.Bottom) { targetX := int(evX) - int(rect.Left) targetY := int(evY) - int(rect.Top) //targetImg,targetImgHash,x,y addHistory("move", moveFileName+";"+moveHash+";"+strconv.Itoa(targetX)+";"+strconv.Itoa(targetY)) tempX = evX tempY = evY } } } func addMouseAction(evButton, evX, evY int) { targetX := 0 targetY := 0 allFilename := RandStr(8) + ".bmp" allFilename, allHash := CaptureCase(allFilename, "", 0, true) if allFilename == "" { allFilename, _ = searchHash(allHash, true) } partFileName := RandStr(8) + ".bmp" currentHwnd := GetWindow("GetForegroundWindow", Debug) partFileName, partHash := CaptureCase(partFileName, "", currentHwnd, false) if partFileName == "" { partFileName, _ = searchHash(partHash, false) } if Exists(allFilename) == false { return } matImage := gocv.IMRead(allFilename, gocv.IMReadGrayScale) if Exists(partFileName) == false { return } matTemplate := gocv.IMRead(partFileName, gocv.IMReadGrayScale) matResult := gocv.NewMat() mask := gocv.NewMat() gocv.MatchTemplate(matImage, matTemplate, &matResult, gocv.TmCcoeffNormed, mask) mask.Close() minConfidence, maxConfidence, minLoc, maxLoc := gocv.MinMaxLoc(matResult) if Debug == true { fmt.Println(minConfidence, maxConfidence, minLoc, maxLoc) } targetX = int(evX) - maxLoc.X targetY = int(evY) - maxLoc.Y tempX = evX tempY = evY //allImg,allImageHash,targetImg,targetImgHash,x,y,clickType addHistory("click", allFilename+";"+allHash+";"+partFileName+";"+partHash+";"+strconv.Itoa(targetX)+";"+strconv.Itoa(targetY)+";"+strconv.Itoa(evButton)) } func GetMD5Hash(text string) string { hasher := md5.New() hasher.Write([]byte(text)) return hex.EncodeToString(hasher.Sum(nil)) } func addHistory(device, strs string) { if len(strs) > 0 { History = append(History, historyData{Device: device, Pre: preWindow, Aft: aftWindow, Params: strs}) if Debug == true { fmt.Println("liveRecord: ", strs) } } } func ListWindow(Debug bool) []string { var rect RECTdata ret := []string{} cb := syscall.NewCallback(func(h syscall.Handle, p uintptr) uintptr { b := make([]uint16, 200) _, err := GetWindowText(h, &b[0], int32(len(b))) if err != nil { return 1 } GetWindowRect(HWND(h), &rect, Debug) if rect.Left != 0 || rect.Top != 0 || rect.Right != 0 || rect.Bottom != 0 { if Debug == true { fmt.Printf("Window Title '%s' window: handle=0x%x\n", syscall.UTF16ToString(b), h) if rect.Left != 0 || rect.Top != 0 || rect.Right != 0 || rect.Bottom != 0 { fmt.Printf("window rect: ") fmt.Println(rect) } } ret = append(ret, fmt.Sprintf("%s : %x", syscall.UTF16ToString(b), h)) } return 1 }) EnumWindows(cb, 0) return ret } func matchCheck(stra, strb string) bool { if strings.Index(strb, stra) != -1 { return true } else { if strings.Index(stra, strb) != -1 { return true } } return false } func FocusWindow(title string, Debug bool) uintptr { var hwnd syscall.Handle var rect RECTdata cb := syscall.NewCallback(func(h syscall.Handle, p uintptr) uintptr { b := make([]uint16, 200) _, err := GetWindowText(h, &b[0], int32(len(b))) if err != nil { return 1 } if Debug == true { fmt.Printf("EnumWindows Search '%s' window: handle=0x%x\n", syscall.UTF16ToString(b), h) } if matchCheck(title, syscall.UTF16ToString(b)) == true { if Debug == true { fmt.Printf("Found! window: '%s' handle=0x%x\n", syscall.UTF16ToString(b), h) } GetWindowRect(HWND(h), &rect, Debug) fmt.Println() if int(rect.Right-rect.Left) > 0 && int(rect.Bottom-rect.Top) > 0 { hwnd = h return 0 } }
} func GetWindow(funcName string, Debug bool) uintptr { hwnd, _, _ := syscall.Syscall(procGetForegroundWindow.Addr(), 6, 0, 0, 0) if Debug == true { fmt.Printf("currentWindow: handle=0x%x.\n", hwnd) } return hwnd } func SetActiveWindow(hwnd HWND, Debug bool) { if Debug == true { fmt.Printf("SetActiveWindow: handle=0x%x.\n", hwnd) } syscall.Syscall(procSetActiveWindow.Addr(), 4, uintptr(hwnd), 0, 0) syscall.Syscall(procSetForegroundWindow.Addr(), 5, uintptr(hwnd), 0, 0) } func GetWindowRect(hwnd HWND, rect *RECTdata, Debug bool) (err error) { r1, _, e1 := syscall.Syscall(procGetWindowRect.Addr(), 7, uintptr(hwnd), uintptr(unsafe.Pointer(rect)), 0) if r1 == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } func GetWindowText(hwnd syscall.Handle, str *uint16, maxCount int32) (len int32, err error) { r0, _, e1 := syscall.Syscall(procGetWindowTextW.Addr(), 3, uintptr(hwnd), uintptr(unsafe.Pointer(str)), uintptr(maxCount)) if len = int32(r0); len == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } func EnumWindows(enumFunc uintptr, lparam uintptr) (err error) { r1, _, e1 := syscall.Syscall(procEnumWindows.Addr(), 2, uintptr(enumFunc), uintptr(lparam), 0) if r1 == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } func RandStr(n int) string { b := make([]rune, n) for i := range b { b[i] = rs1Letters[rand.Intn(len(rs1Letters))] } return string(b) } func ExportHistory(filename string) bool { file, err := os.Create(prevDir + "\\" + filename) if err != nil { fmt.Println(err) return false } defer file.Close() for i := 0; i < len(History); i++ { strs := "" if History[i].Device == "click" { stra := strings.Split(History[i].Params, ";") strs = History[i].Device + "\t" + History[i].Pre + "\t" + History[i].Aft + "\t" + stra[0] + ";" + stra[2] + ";" + stra[4] + ";" + stra[5] + ";" + stra[6] } else if History[i].Device == "move" { stra := strings.Split(History[i].Params, ";") strs = History[i].Device + "\t" + History[i].Pre + "\t" + History[i].Aft + "\t" + stra[0] + ";" + stra[2] + ";" + stra[3] } else { strs = History[i].Device + "\t" + History[i].Pre + "\t" + History[i].Aft + "\t" + History[i].Params } if Debug == true { fmt.Printf("[%3d]: %s\n", i+1, strs) } if _, err = file.WriteString(strs + "\n"); err != nil { fmt.Println(err) return false } } fmt.Println("exportFile: ", filename) return true }
return 1 }) EnumWindows(cb, 0) return uintptr(hwnd)
random_line_split
do.go
/** * (Probably) the world's first one file RPA tool impremented by Golang! * * @author yasutakatou * @copyright 2020 yasutakatou * @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 , 3-clause BSD License */ package main import ( "bufio" "crypto/md5" "encoding/hex" "flag" "fmt" "image" "io" "log" "math/rand" "os" "path/filepath" "strconv" "strings" "syscall" "time" "unsafe" "github.com/go-vgo/robotgo" "github.com/kbinani/screenshot" hook "github.com/robotn/gohook" "github.com/yasutakatou/string2keyboard" "gocv.io/x/gocv" "golang.org/x/image/bmp" ) type ( HANDLE uintptr HWND HANDLE ) type RECTdata struct { Left int32 Top int32 Right int32 Bottom int32 } var ( user32 = syscall.MustLoadDLL("user32.dll") procEnumWindows = user32.MustFindProc("EnumWindows") procGetWindowTextW = user32.MustFindProc("GetWindowTextW") procSetActiveWindow = user32.MustFindProc("SetActiveWindow") procSetForegroundWindow = user32.MustFindProc("SetForegroundWindow") procGetForegroundWindow = user32.MustFindProc("GetForegroundWindow") procGetWindowRect = user32.MustFindProc("GetWindowRect") rs1Letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") History = []historyData{} Hashs = []hashData{} Debug bool LiveExitAsciiCode int preWindow string aftWindow string LiveRawcodeChar string sameThreshold float32 tryCounter int waitSeconds int TEMPDir string prevDir string tempX int tempY int moveThreshold int ) type historyData struct { Device string `json:"Device"` Pre string `json:"Pre"` Aft string `json:"Aft"` Params string `json:"Params"` } type hashData struct { Filename string `json:"Filename"` Hash string `json:"Hash"` } func init() { rand.Seed(time.Now().UnixNano()) LiveRawcodeChar = "~" preWindow = "" aftWindow = "" } func main() { _List := flag.Bool("list", false, "[-list=listing window titiles and exit]") _Replay := flag.Bool("replay", false, "[-replay=replay mode (true is enable)]") _Record := flag.Bool("record", true, "[-record=recording mode (true is enable)]") _exportFile := flag.String("export", "output.tsv", "[-export=export file name]") _importFile := flag.String("import", "input.tsv", "[-import=import file name]") _DEBUG := flag.Bool("debug", false, "[-debug=debug mode (true is enable)]") _threshold := flag.Float64("threshold", 0.1, "[-threshold=same window threshold]") _move := flag.Float64("move", 50, "[-move=mouse move record threshold]") _try := flag.Int("try", 10, "[-try=error and try counter]") _wait := flag.Int("wait", 250, "[-wait=loop wait Millisecond]") _exitCode := flag.Int("exitCode", 27, "[-exitCode=recording mode to exit ascii key code]") _tmpDir := flag.String("tmpDir", "tmp", "[-tmpDir=temporary directory name]") flag.Parse() if *_List == true { getHwndToTitle(0, true) os.Exit(0) } Debug = bool(*_DEBUG) sameThreshold = float32(*_threshold) tryCounter = int(*_try) waitSeconds = int(*_wait) LiveExitAsciiCode = int(*_exitCode) moveThreshold = int(*_move) prevDir, _ = filepath.Abs(".") TEMPDir = prevDir + "\\" + string(*_tmpDir) + "\\" if Exists(TEMPDir) == true { if *_Record == true && *_Replay == false { if err := os.RemoveAll(TEMPDir); err != nil { fmt.Println(err) } } } if err := os.MkdirAll(TEMPDir, 0777); err != nil { fmt.Println(err) } os.Chdir(TEMPDir) if *_DEBUG == true { fmt.Println(" - - - options - - - ") fmt.Println("list: ", *_List) fmt.Println("replay: ", *_Replay) fmt.Println("record: ", *_Record) fmt.Println("export: ", *_exportFile) fmt.Println("import: ", *_importFile) fmt.Println("debug: ", Debug) fmt.Println("threshold: ", sameThreshold) fmt.Println("move: ", moveThreshold) fmt.Println("try: ", tryCounter) fmt.Println("wait: ", waitSeconds) fmt.Println("exitCode: ", LiveExitAsciiCode) fmt.Println("tmpDir: ", TEMPDir) fmt.Println(" - - - - - - - - - ") } switch *_Record { case true: if *_Replay == true { replayMode(prevDir + "\\" + *_importFile) } else { recordingMode(*_exportFile) } case false: if *_Replay == false { recordingMode(*_exportFile) } else { replayMode(prevDir + "\\" + *_importFile) } } os.Chdir(prevDir) os.Exit(0) } func Exists(filename string) bool { _, err := os.Stat(filename) return err == nil } func ImportHistory(params string) bool { if len(params) == 0 { return false } file, err := os.Open(params) if err != nil { fmt.Println(err) return false } defer file.Close() History = nil s := bufio.NewScanner(file) for s.Scan() { strs := strings.Split(s.Text(), "\t") if len(strs) != 4 { fmt.Println("Error: your tsv file broken") History = nil return false } History = append(History, historyData{Device: strs[0], Pre: strs[1], Aft: strs[2], Params: strs[3]}) } fmt.Println("importFile: ", params) return true } func replayMode(importFile string) { if Exists(importFile) == false { fmt.Println("not found: ", importFile) } ImportHistory(importFile) for i := 0; i < len(History); i++ { fmt.Println("Device: ", History[i].Device, "Pre: ", History[i].Pre, "Aft: ", History[i].Aft, "Params: ", History[i].Params) if setTargetWindow(i) == false { return } switch History[i].Device { case "key": SendKey(History[i].Params) case "click", "move": strs := strings.Split(History[i].Params, ";") origFilename := getNowFilename() if Exists(origFilename) == false { break } matImage := gocv.IMRead(origFilename, gocv.IMReadGrayScale) targetX := 0 targetY := 0 partImage := "" if History[i].Device == "click" { partImage = strs[1] targetX, _ = strconv.Atoi(strs[2]) targetY, _ = strconv.Atoi(strs[3]) } else { partImage = strs[0] targetX, _ = strconv.Atoi(strs[1]) targetY, _ = strconv.Atoi(strs[2]) } if Debug == true { fmt.Println("origFilename: ", origFilename, " partImage: ", partImage) } if Exists(partImage) == false { break } matTemplate := gocv.IMRead(partImage, gocv.IMReadGrayScale) matResult := gocv.NewMat() mask := gocv.NewMat() gocv.MatchTemplate(matImage, matTemplate, &matResult, gocv.TmCcoeffNormed, mask) mask.Close() minConfidence, maxConfidence, minLoc, maxLoc := gocv.MinMaxLoc(matResult) if Debug == true { fmt.Println("mouseLocate: ", minConfidence, maxConfidence, minLoc, maxLoc) } if err := os.Remove(origFilename); err != nil { fmt.Println(err) } if maxConfidence > sameThreshold { actionX := maxLoc.X + targetX actionY := maxLoc.Y + targetY robotgo.MoveMouseSmooth(actionX, actionY, 0.01, 0.01) if History[i].Device == "click" { if strs[4] == "1" { robotgo.MouseClick("left", false) } else { robotgo.MouseClick("right", false) } } } else { if Debug == true { fmt.Println("under same Threshold: ", sameThreshold, " > ", maxConfidence) } } } time.Sleep(time.Duration(waitSeconds) * time.Millisecond) } } func setTargetWindow(i int) bool { if len(History[i].Pre) > 0 { if targetHwnd := FocusWindow(History[i].Pre, Debug); ChangeTarget(targetHwnd) == false { fmt.Println("not found title: ", History[i].Pre) if len(History[i].Aft) > 0 { if targetHwnd := FocusWindow(History[i].Aft, Debug); ChangeTarget(targetHwnd) == false { fmt.Println("not found title: ", History[i].Aft) return false } } } } return true } func getNowFilename() string { origFilename := "" nowFilename := RandStr(8) + ".bmp" n := screenshot.NumActiveDisplays() if n <= 0 { panic("Active display not found") } var all image.Rectangle = image.Rect(0, 0, 0, 0) for i := 0; i < n; i++ { bounds := screenshot.GetDisplayBounds(i) all = bounds.Union(all) } bitmap := robotgo.CaptureScreen(all.Min.X, all.Min.Y, all.Dx(), all.Dy()) robotgo.SaveBitmap(bitmap, nowFilename) tmpHash := calcHash(nowFilename) hFlag := -1 for i := 0; i < len(Hashs); i++ { if Hashs[i].Hash == tmpHash { hFlag = i break } } if hFlag == -1 { Hashs = append(Hashs, hashData{Filename: nowFilename, Hash: tmpHash}) origFilename = nowFilename } else { origFilename = Hashs[hFlag].Filename if err := os.Remove(origFilename); err != nil { fmt.Println(err) } } return origFilename } func SendKey(doCmd string) bool { if Debug == true { fmt.Printf("KeyInput: ") } cCtrl := false cAlt := false if strings.Index(doCmd, "ctrl+") != -1 { cCtrl = true doCmd = strings.Replace(doCmd, "ctrl+", "", 1) if Debug == true { fmt.Printf("ctrl+") } } if strings.Index(doCmd, "alt+") != -1 { cAlt = true doCmd = strings.Replace(doCmd, "alt+", "", 1) if Debug == true { fmt.Printf("alt+") } } string2keyboard.KeyboardWrite(doCmd, cCtrl, cAlt, LiveRawcodeChar) if Debug == true { fmt.Println(doCmd, cCtrl, cAlt) } return true } func saveToBmp(img *image.RGBA, filePath string) { file, err := os.Create(filePath) if err != nil { panic(err) } defer file.Close() bmp.Encode(file, img) } func searchHash(targetHash string, allPartFlag bool) (string, string) { //all: 1, part 3, move 1 for i := 0; i < len(History); i++ { if History[i].Device == "click" || History[i].Device == "move" { strs := strings.Split(History[i].Params, ";") if allPartFlag == true && targetHash == strs[1] { return strs[0], strs[1] } if allPartFlag == false && targetHash == strs[3] { return strs[2], strs[3] } } } return "", "" } func CaptureCase(filename, target string, setHwnd uintptr, hFlag bool) (string, string) { var rect RECTdata if target == "" && setHwnd == 0 { n := screenshot.NumActiveDisplays() if n <= 0 { panic("Active display not found") } var all image.Rectangle = image.Rect(0, 0, 0, 0) for i := 0; i < n; i++ { bounds := screenshot.GetDisplayBounds(i) all = bounds.Union(all) } bitmap := robotgo.CaptureScreen(all.Min.X, all.Min.Y, all.Dx(), all.Dy()) robotgo.SaveBitmap(bitmap, filename) } else { ChangeTarget(setHwnd) GetWindowRect(HWND(setHwnd), &rect, Debug) bitmap := robotgo.CaptureScreen(int(rect.Left), int(rect.Top), int(rect.Right-rect.Left), int(rect.Bottom-rect.Top)) robotgo.SaveBitmap(bitmap, filename) } tmpHash := calcHash(filename) if _, Hash := searchHash(tmpHash, hFlag); Hash == "" { return filename, tmpHash } if err := os.Remove(filename); err != nil { fmt.Println(err) } return "", tmpHash } func calcHash(filename string) string { f, err := os.Open(filename) if err != nil { log.Fatal(err) } defer f.Close() h := md5.New() if _, err := io.Copy(h, f); err != nil { log.Fatal(err) } return fmt.Sprintf("%x", h.Sum(nil)) } func getHwndToTitle(targetHwnd uintptr, listMode bool) string { lists := ListWindow(Debug) for i := 0; i < len(lists); i++ { if listMode == true { fmt.Println(lists[i]) } else { strs := strings.Split(lists[i], " : ") if strings.Index(fmt.Sprintf("%x", targetHwnd), strs[1]) != -1 { return strs[0] } } } return "" } func ChangeTarget(setHwnd uintptr) bool { breakCounter := tryCounter for { if Debug == true { fmt.Printf("tryCounter: %d\n", breakCounter) } if setHwnd != GetWindow("GetForegroundWindow", Debug) { SetActiveWindow(HWND(setHwnd), Debug) } else { return true } breakCounter = breakCounter - 1 if breakCounter < 0 { return false } time.Sleep(time.Duration(waitSeconds) * time.Millisecond) } } func recordingMode(exportFile string) { fmt.Printf(" - - recording start! you want to end this mode, key press ascii code (%d) - - \n", LiveExitAsciiCode) altFlag := 0 actFlag := false var bufStrs uint16 bufStrs = 0 EvChan := hook.Start() defer hook.End() for ev := range EvChan { strs := "" if actFlag == true { if ev.Kind == 3 { //KeyDown = 3 bufStrs, strs = keyDown(altFlag, int(ev.Rawcode), strs, string(ev.Keychar), bufStrs) preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } if ev.Kind == 4 || ev.Kind == 5 { //KeyHold = 4,KeyUp = 5 altFlag = keyHoldUp(int(ev.Rawcode), int(ev.Kind), bufStrs, exportFile) if altFlag == 256 { return } preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } if ev.Kind == 9 { //MouseMove = 9 if moveValCheck(int(ev.X), int(ev.Y)) == true { addMouseMove(int(ev.X), int(ev.Y)) } preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } } if ev.Kind == 7 { //MouseHold if actFlag == false { actFlag = true aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } addMouseAction(int(ev.Button), int(ev.X), int(ev.Y)) preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } } } func moveValCheck(evX, evY int) bool { if tempX-int(evX) > moveThreshold { return true } if tempY-int(evY) > (moveThreshold / 2) { return true } if int(evX)-tempX > moveThreshold { return true } if int(evY)-tempY > (moveThreshold / 2) { return true } return false } func keyDown(altFlag, Rawcode int, strs, keyChar string, bufStrs uint16) (uint16, string) { if altFlag == 0 { switch Rawcode { case 8: strs = "\\b" case 9: strs = "\\t" case 13: strs = "\\n" default: strs = keyChar } } else { switch altFlag { case 162: strs = "ctrl+" + keyChar case 164: strs = "alt+" + keyChar } } bufStrs = uint16(Rawcode) addHistory("key", strs) return bufStrs, strs } func
(Rawcode, Kind int, bufStrs uint16, exportFile string) int { altFlag := 0 switch Rawcode { case 162, 164: //Ctrl,Alt if Kind == 4 { altFlag = Rawcode } else { altFlag = 0 } case LiveExitAsciiCode: //Default Escape ExportHistory(exportFile) return 256 case 160: default: if Kind == 5 && int(bufStrs) != Rawcode { addHistory("key", "\\"+LiveRawcodeChar+strconv.Itoa(Rawcode)+LiveRawcodeChar) } } return altFlag } func addMouseMove(evX, evY int) { var rect RECTdata moveFileName := RandStr(8) + ".bmp" currentHwnd := GetWindow("GetForegroundWindow", false) GetWindowRect(HWND(currentHwnd), &rect, false) moveFileName, moveHash := CaptureCase(moveFileName, "", currentHwnd, true) if moveFileName == "" { moveFileName, _ = searchHash(moveHash, true) } if evX > 0 && evX > int(rect.Left) && evX < int(rect.Right) { if evY > 0 && evX > int(rect.Top) && evY < int(rect.Bottom) { targetX := int(evX) - int(rect.Left) targetY := int(evY) - int(rect.Top) //targetImg,targetImgHash,x,y addHistory("move", moveFileName+";"+moveHash+";"+strconv.Itoa(targetX)+";"+strconv.Itoa(targetY)) tempX = evX tempY = evY } } } func addMouseAction(evButton, evX, evY int) { targetX := 0 targetY := 0 allFilename := RandStr(8) + ".bmp" allFilename, allHash := CaptureCase(allFilename, "", 0, true) if allFilename == "" { allFilename, _ = searchHash(allHash, true) } partFileName := RandStr(8) + ".bmp" currentHwnd := GetWindow("GetForegroundWindow", Debug) partFileName, partHash := CaptureCase(partFileName, "", currentHwnd, false) if partFileName == "" { partFileName, _ = searchHash(partHash, false) } if Exists(allFilename) == false { return } matImage := gocv.IMRead(allFilename, gocv.IMReadGrayScale) if Exists(partFileName) == false { return } matTemplate := gocv.IMRead(partFileName, gocv.IMReadGrayScale) matResult := gocv.NewMat() mask := gocv.NewMat() gocv.MatchTemplate(matImage, matTemplate, &matResult, gocv.TmCcoeffNormed, mask) mask.Close() minConfidence, maxConfidence, minLoc, maxLoc := gocv.MinMaxLoc(matResult) if Debug == true { fmt.Println(minConfidence, maxConfidence, minLoc, maxLoc) } targetX = int(evX) - maxLoc.X targetY = int(evY) - maxLoc.Y tempX = evX tempY = evY //allImg,allImageHash,targetImg,targetImgHash,x,y,clickType addHistory("click", allFilename+";"+allHash+";"+partFileName+";"+partHash+";"+strconv.Itoa(targetX)+";"+strconv.Itoa(targetY)+";"+strconv.Itoa(evButton)) } func GetMD5Hash(text string) string { hasher := md5.New() hasher.Write([]byte(text)) return hex.EncodeToString(hasher.Sum(nil)) } func addHistory(device, strs string) { if len(strs) > 0 { History = append(History, historyData{Device: device, Pre: preWindow, Aft: aftWindow, Params: strs}) if Debug == true { fmt.Println("liveRecord: ", strs) } } } func ListWindow(Debug bool) []string { var rect RECTdata ret := []string{} cb := syscall.NewCallback(func(h syscall.Handle, p uintptr) uintptr { b := make([]uint16, 200) _, err := GetWindowText(h, &b[0], int32(len(b))) if err != nil { return 1 } GetWindowRect(HWND(h), &rect, Debug) if rect.Left != 0 || rect.Top != 0 || rect.Right != 0 || rect.Bottom != 0 { if Debug == true { fmt.Printf("Window Title '%s' window: handle=0x%x\n", syscall.UTF16ToString(b), h) if rect.Left != 0 || rect.Top != 0 || rect.Right != 0 || rect.Bottom != 0 { fmt.Printf("window rect: ") fmt.Println(rect) } } ret = append(ret, fmt.Sprintf("%s : %x", syscall.UTF16ToString(b), h)) } return 1 }) EnumWindows(cb, 0) return ret } func matchCheck(stra, strb string) bool { if strings.Index(strb, stra) != -1 { return true } else { if strings.Index(stra, strb) != -1 { return true } } return false } func FocusWindow(title string, Debug bool) uintptr { var hwnd syscall.Handle var rect RECTdata cb := syscall.NewCallback(func(h syscall.Handle, p uintptr) uintptr { b := make([]uint16, 200) _, err := GetWindowText(h, &b[0], int32(len(b))) if err != nil { return 1 } if Debug == true { fmt.Printf("EnumWindows Search '%s' window: handle=0x%x\n", syscall.UTF16ToString(b), h) } if matchCheck(title, syscall.UTF16ToString(b)) == true { if Debug == true { fmt.Printf("Found! window: '%s' handle=0x%x\n", syscall.UTF16ToString(b), h) } GetWindowRect(HWND(h), &rect, Debug) fmt.Println() if int(rect.Right-rect.Left) > 0 && int(rect.Bottom-rect.Top) > 0 { hwnd = h return 0 } } return 1 }) EnumWindows(cb, 0) return uintptr(hwnd) } func GetWindow(funcName string, Debug bool) uintptr { hwnd, _, _ := syscall.Syscall(procGetForegroundWindow.Addr(), 6, 0, 0, 0) if Debug == true { fmt.Printf("currentWindow: handle=0x%x.\n", hwnd) } return hwnd } func SetActiveWindow(hwnd HWND, Debug bool) { if Debug == true { fmt.Printf("SetActiveWindow: handle=0x%x.\n", hwnd) } syscall.Syscall(procSetActiveWindow.Addr(), 4, uintptr(hwnd), 0, 0) syscall.Syscall(procSetForegroundWindow.Addr(), 5, uintptr(hwnd), 0, 0) } func GetWindowRect(hwnd HWND, rect *RECTdata, Debug bool) (err error) { r1, _, e1 := syscall.Syscall(procGetWindowRect.Addr(), 7, uintptr(hwnd), uintptr(unsafe.Pointer(rect)), 0) if r1 == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } func GetWindowText(hwnd syscall.Handle, str *uint16, maxCount int32) (len int32, err error) { r0, _, e1 := syscall.Syscall(procGetWindowTextW.Addr(), 3, uintptr(hwnd), uintptr(unsafe.Pointer(str)), uintptr(maxCount)) if len = int32(r0); len == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } func EnumWindows(enumFunc uintptr, lparam uintptr) (err error) { r1, _, e1 := syscall.Syscall(procEnumWindows.Addr(), 2, uintptr(enumFunc), uintptr(lparam), 0) if r1 == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } func RandStr(n int) string { b := make([]rune, n) for i := range b { b[i] = rs1Letters[rand.Intn(len(rs1Letters))] } return string(b) } func ExportHistory(filename string) bool { file, err := os.Create(prevDir + "\\" + filename) if err != nil { fmt.Println(err) return false } defer file.Close() for i := 0; i < len(History); i++ { strs := "" if History[i].Device == "click" { stra := strings.Split(History[i].Params, ";") strs = History[i].Device + "\t" + History[i].Pre + "\t" + History[i].Aft + "\t" + stra[0] + ";" + stra[2] + ";" + stra[4] + ";" + stra[5] + ";" + stra[6] } else if History[i].Device == "move" { stra := strings.Split(History[i].Params, ";") strs = History[i].Device + "\t" + History[i].Pre + "\t" + History[i].Aft + "\t" + stra[0] + ";" + stra[2] + ";" + stra[3] } else { strs = History[i].Device + "\t" + History[i].Pre + "\t" + History[i].Aft + "\t" + History[i].Params } if Debug == true { fmt.Printf("[%3d]: %s\n", i+1, strs) } if _, err = file.WriteString(strs + "\n"); err != nil { fmt.Println(err) return false } } fmt.Println("exportFile: ", filename) return true }
keyHoldUp
identifier_name
do.go
/** * (Probably) the world's first one file RPA tool impremented by Golang! * * @author yasutakatou * @copyright 2020 yasutakatou * @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 , 3-clause BSD License */ package main import ( "bufio" "crypto/md5" "encoding/hex" "flag" "fmt" "image" "io" "log" "math/rand" "os" "path/filepath" "strconv" "strings" "syscall" "time" "unsafe" "github.com/go-vgo/robotgo" "github.com/kbinani/screenshot" hook "github.com/robotn/gohook" "github.com/yasutakatou/string2keyboard" "gocv.io/x/gocv" "golang.org/x/image/bmp" ) type ( HANDLE uintptr HWND HANDLE ) type RECTdata struct { Left int32 Top int32 Right int32 Bottom int32 } var ( user32 = syscall.MustLoadDLL("user32.dll") procEnumWindows = user32.MustFindProc("EnumWindows") procGetWindowTextW = user32.MustFindProc("GetWindowTextW") procSetActiveWindow = user32.MustFindProc("SetActiveWindow") procSetForegroundWindow = user32.MustFindProc("SetForegroundWindow") procGetForegroundWindow = user32.MustFindProc("GetForegroundWindow") procGetWindowRect = user32.MustFindProc("GetWindowRect") rs1Letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") History = []historyData{} Hashs = []hashData{} Debug bool LiveExitAsciiCode int preWindow string aftWindow string LiveRawcodeChar string sameThreshold float32 tryCounter int waitSeconds int TEMPDir string prevDir string tempX int tempY int moveThreshold int ) type historyData struct { Device string `json:"Device"` Pre string `json:"Pre"` Aft string `json:"Aft"` Params string `json:"Params"` } type hashData struct { Filename string `json:"Filename"` Hash string `json:"Hash"` } func init() { rand.Seed(time.Now().UnixNano()) LiveRawcodeChar = "~" preWindow = "" aftWindow = "" } func main() { _List := flag.Bool("list", false, "[-list=listing window titiles and exit]") _Replay := flag.Bool("replay", false, "[-replay=replay mode (true is enable)]") _Record := flag.Bool("record", true, "[-record=recording mode (true is enable)]") _exportFile := flag.String("export", "output.tsv", "[-export=export file name]") _importFile := flag.String("import", "input.tsv", "[-import=import file name]") _DEBUG := flag.Bool("debug", false, "[-debug=debug mode (true is enable)]") _threshold := flag.Float64("threshold", 0.1, "[-threshold=same window threshold]") _move := flag.Float64("move", 50, "[-move=mouse move record threshold]") _try := flag.Int("try", 10, "[-try=error and try counter]") _wait := flag.Int("wait", 250, "[-wait=loop wait Millisecond]") _exitCode := flag.Int("exitCode", 27, "[-exitCode=recording mode to exit ascii key code]") _tmpDir := flag.String("tmpDir", "tmp", "[-tmpDir=temporary directory name]") flag.Parse() if *_List == true { getHwndToTitle(0, true) os.Exit(0) } Debug = bool(*_DEBUG) sameThreshold = float32(*_threshold) tryCounter = int(*_try) waitSeconds = int(*_wait) LiveExitAsciiCode = int(*_exitCode) moveThreshold = int(*_move) prevDir, _ = filepath.Abs(".") TEMPDir = prevDir + "\\" + string(*_tmpDir) + "\\" if Exists(TEMPDir) == true { if *_Record == true && *_Replay == false { if err := os.RemoveAll(TEMPDir); err != nil { fmt.Println(err) } } } if err := os.MkdirAll(TEMPDir, 0777); err != nil { fmt.Println(err) } os.Chdir(TEMPDir) if *_DEBUG == true { fmt.Println(" - - - options - - - ") fmt.Println("list: ", *_List) fmt.Println("replay: ", *_Replay) fmt.Println("record: ", *_Record) fmt.Println("export: ", *_exportFile) fmt.Println("import: ", *_importFile) fmt.Println("debug: ", Debug) fmt.Println("threshold: ", sameThreshold) fmt.Println("move: ", moveThreshold) fmt.Println("try: ", tryCounter) fmt.Println("wait: ", waitSeconds) fmt.Println("exitCode: ", LiveExitAsciiCode) fmt.Println("tmpDir: ", TEMPDir) fmt.Println(" - - - - - - - - - ") } switch *_Record { case true: if *_Replay == true { replayMode(prevDir + "\\" + *_importFile) } else { recordingMode(*_exportFile) } case false: if *_Replay == false { recordingMode(*_exportFile) } else { replayMode(prevDir + "\\" + *_importFile) } } os.Chdir(prevDir) os.Exit(0) } func Exists(filename string) bool { _, err := os.Stat(filename) return err == nil } func ImportHistory(params string) bool { if len(params) == 0 { return false } file, err := os.Open(params) if err != nil { fmt.Println(err) return false } defer file.Close() History = nil s := bufio.NewScanner(file) for s.Scan() { strs := strings.Split(s.Text(), "\t") if len(strs) != 4 { fmt.Println("Error: your tsv file broken") History = nil return false } History = append(History, historyData{Device: strs[0], Pre: strs[1], Aft: strs[2], Params: strs[3]}) } fmt.Println("importFile: ", params) return true } func replayMode(importFile string) { if Exists(importFile) == false { fmt.Println("not found: ", importFile) } ImportHistory(importFile) for i := 0; i < len(History); i++ { fmt.Println("Device: ", History[i].Device, "Pre: ", History[i].Pre, "Aft: ", History[i].Aft, "Params: ", History[i].Params) if setTargetWindow(i) == false { return } switch History[i].Device { case "key": SendKey(History[i].Params) case "click", "move": strs := strings.Split(History[i].Params, ";") origFilename := getNowFilename() if Exists(origFilename) == false { break } matImage := gocv.IMRead(origFilename, gocv.IMReadGrayScale) targetX := 0 targetY := 0 partImage := "" if History[i].Device == "click" { partImage = strs[1] targetX, _ = strconv.Atoi(strs[2]) targetY, _ = strconv.Atoi(strs[3]) } else { partImage = strs[0] targetX, _ = strconv.Atoi(strs[1]) targetY, _ = strconv.Atoi(strs[2]) } if Debug == true { fmt.Println("origFilename: ", origFilename, " partImage: ", partImage) } if Exists(partImage) == false { break } matTemplate := gocv.IMRead(partImage, gocv.IMReadGrayScale) matResult := gocv.NewMat() mask := gocv.NewMat() gocv.MatchTemplate(matImage, matTemplate, &matResult, gocv.TmCcoeffNormed, mask) mask.Close() minConfidence, maxConfidence, minLoc, maxLoc := gocv.MinMaxLoc(matResult) if Debug == true { fmt.Println("mouseLocate: ", minConfidence, maxConfidence, minLoc, maxLoc) } if err := os.Remove(origFilename); err != nil { fmt.Println(err) } if maxConfidence > sameThreshold { actionX := maxLoc.X + targetX actionY := maxLoc.Y + targetY robotgo.MoveMouseSmooth(actionX, actionY, 0.01, 0.01) if History[i].Device == "click" { if strs[4] == "1" { robotgo.MouseClick("left", false) } else { robotgo.MouseClick("right", false) } } } else { if Debug == true { fmt.Println("under same Threshold: ", sameThreshold, " > ", maxConfidence) } } } time.Sleep(time.Duration(waitSeconds) * time.Millisecond) } } func setTargetWindow(i int) bool { if len(History[i].Pre) > 0 { if targetHwnd := FocusWindow(History[i].Pre, Debug); ChangeTarget(targetHwnd) == false { fmt.Println("not found title: ", History[i].Pre) if len(History[i].Aft) > 0 { if targetHwnd := FocusWindow(History[i].Aft, Debug); ChangeTarget(targetHwnd) == false { fmt.Println("not found title: ", History[i].Aft) return false } } } } return true } func getNowFilename() string { origFilename := "" nowFilename := RandStr(8) + ".bmp" n := screenshot.NumActiveDisplays() if n <= 0 { panic("Active display not found") } var all image.Rectangle = image.Rect(0, 0, 0, 0) for i := 0; i < n; i++ { bounds := screenshot.GetDisplayBounds(i) all = bounds.Union(all) } bitmap := robotgo.CaptureScreen(all.Min.X, all.Min.Y, all.Dx(), all.Dy()) robotgo.SaveBitmap(bitmap, nowFilename) tmpHash := calcHash(nowFilename) hFlag := -1 for i := 0; i < len(Hashs); i++ { if Hashs[i].Hash == tmpHash { hFlag = i break } } if hFlag == -1 { Hashs = append(Hashs, hashData{Filename: nowFilename, Hash: tmpHash}) origFilename = nowFilename } else { origFilename = Hashs[hFlag].Filename if err := os.Remove(origFilename); err != nil { fmt.Println(err) } } return origFilename } func SendKey(doCmd string) bool { if Debug == true { fmt.Printf("KeyInput: ") } cCtrl := false cAlt := false if strings.Index(doCmd, "ctrl+") != -1 { cCtrl = true doCmd = strings.Replace(doCmd, "ctrl+", "", 1) if Debug == true { fmt.Printf("ctrl+") } } if strings.Index(doCmd, "alt+") != -1 { cAlt = true doCmd = strings.Replace(doCmd, "alt+", "", 1) if Debug == true { fmt.Printf("alt+") } } string2keyboard.KeyboardWrite(doCmd, cCtrl, cAlt, LiveRawcodeChar) if Debug == true { fmt.Println(doCmd, cCtrl, cAlt) } return true } func saveToBmp(img *image.RGBA, filePath string) { file, err := os.Create(filePath) if err != nil { panic(err) } defer file.Close() bmp.Encode(file, img) } func searchHash(targetHash string, allPartFlag bool) (string, string) { //all: 1, part 3, move 1 for i := 0; i < len(History); i++ { if History[i].Device == "click" || History[i].Device == "move" { strs := strings.Split(History[i].Params, ";") if allPartFlag == true && targetHash == strs[1] { return strs[0], strs[1] } if allPartFlag == false && targetHash == strs[3] { return strs[2], strs[3] } } } return "", "" } func CaptureCase(filename, target string, setHwnd uintptr, hFlag bool) (string, string) { var rect RECTdata if target == "" && setHwnd == 0 { n := screenshot.NumActiveDisplays() if n <= 0 { panic("Active display not found") } var all image.Rectangle = image.Rect(0, 0, 0, 0) for i := 0; i < n; i++ { bounds := screenshot.GetDisplayBounds(i) all = bounds.Union(all) } bitmap := robotgo.CaptureScreen(all.Min.X, all.Min.Y, all.Dx(), all.Dy()) robotgo.SaveBitmap(bitmap, filename) } else { ChangeTarget(setHwnd) GetWindowRect(HWND(setHwnd), &rect, Debug) bitmap := robotgo.CaptureScreen(int(rect.Left), int(rect.Top), int(rect.Right-rect.Left), int(rect.Bottom-rect.Top)) robotgo.SaveBitmap(bitmap, filename) } tmpHash := calcHash(filename) if _, Hash := searchHash(tmpHash, hFlag); Hash == "" { return filename, tmpHash } if err := os.Remove(filename); err != nil { fmt.Println(err) } return "", tmpHash } func calcHash(filename string) string { f, err := os.Open(filename) if err != nil { log.Fatal(err) } defer f.Close() h := md5.New() if _, err := io.Copy(h, f); err != nil { log.Fatal(err) } return fmt.Sprintf("%x", h.Sum(nil)) } func getHwndToTitle(targetHwnd uintptr, listMode bool) string { lists := ListWindow(Debug) for i := 0; i < len(lists); i++ { if listMode == true { fmt.Println(lists[i]) } else { strs := strings.Split(lists[i], " : ") if strings.Index(fmt.Sprintf("%x", targetHwnd), strs[1]) != -1 { return strs[0] } } } return "" } func ChangeTarget(setHwnd uintptr) bool { breakCounter := tryCounter for { if Debug == true { fmt.Printf("tryCounter: %d\n", breakCounter) } if setHwnd != GetWindow("GetForegroundWindow", Debug) { SetActiveWindow(HWND(setHwnd), Debug) } else { return true } breakCounter = breakCounter - 1 if breakCounter < 0 { return false } time.Sleep(time.Duration(waitSeconds) * time.Millisecond) } } func recordingMode(exportFile string) { fmt.Printf(" - - recording start! you want to end this mode, key press ascii code (%d) - - \n", LiveExitAsciiCode) altFlag := 0 actFlag := false var bufStrs uint16 bufStrs = 0 EvChan := hook.Start() defer hook.End() for ev := range EvChan { strs := "" if actFlag == true { if ev.Kind == 3 { //KeyDown = 3 bufStrs, strs = keyDown(altFlag, int(ev.Rawcode), strs, string(ev.Keychar), bufStrs) preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } if ev.Kind == 4 || ev.Kind == 5 { //KeyHold = 4,KeyUp = 5 altFlag = keyHoldUp(int(ev.Rawcode), int(ev.Kind), bufStrs, exportFile) if altFlag == 256 { return } preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } if ev.Kind == 9 { //MouseMove = 9 if moveValCheck(int(ev.X), int(ev.Y)) == true { addMouseMove(int(ev.X), int(ev.Y)) } preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } } if ev.Kind == 7 { //MouseHold if actFlag == false { actFlag = true aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } addMouseAction(int(ev.Button), int(ev.X), int(ev.Y)) preWindow = aftWindow aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false) } } } func moveValCheck(evX, evY int) bool { if tempX-int(evX) > moveThreshold { return true } if tempY-int(evY) > (moveThreshold / 2) { return true } if int(evX)-tempX > moveThreshold { return true } if int(evY)-tempY > (moveThreshold / 2) { return true } return false } func keyDown(altFlag, Rawcode int, strs, keyChar string, bufStrs uint16) (uint16, string) { if altFlag == 0 { switch Rawcode { case 8: strs = "\\b" case 9: strs = "\\t" case 13: strs = "\\n" default: strs = keyChar } } else { switch altFlag { case 162: strs = "ctrl+" + keyChar case 164: strs = "alt+" + keyChar } } bufStrs = uint16(Rawcode) addHistory("key", strs) return bufStrs, strs } func keyHoldUp(Rawcode, Kind int, bufStrs uint16, exportFile string) int { altFlag := 0 switch Rawcode { case 162, 164: //Ctrl,Alt if Kind == 4 { altFlag = Rawcode } else { altFlag = 0 } case LiveExitAsciiCode: //Default Escape ExportHistory(exportFile) return 256 case 160: default: if Kind == 5 && int(bufStrs) != Rawcode { addHistory("key", "\\"+LiveRawcodeChar+strconv.Itoa(Rawcode)+LiveRawcodeChar) } } return altFlag } func addMouseMove(evX, evY int) { var rect RECTdata moveFileName := RandStr(8) + ".bmp" currentHwnd := GetWindow("GetForegroundWindow", false) GetWindowRect(HWND(currentHwnd), &rect, false) moveFileName, moveHash := CaptureCase(moveFileName, "", currentHwnd, true) if moveFileName == "" { moveFileName, _ = searchHash(moveHash, true) } if evX > 0 && evX > int(rect.Left) && evX < int(rect.Right) { if evY > 0 && evX > int(rect.Top) && evY < int(rect.Bottom) { targetX := int(evX) - int(rect.Left) targetY := int(evY) - int(rect.Top) //targetImg,targetImgHash,x,y addHistory("move", moveFileName+";"+moveHash+";"+strconv.Itoa(targetX)+";"+strconv.Itoa(targetY)) tempX = evX tempY = evY } } } func addMouseAction(evButton, evX, evY int) { targetX := 0 targetY := 0 allFilename := RandStr(8) + ".bmp" allFilename, allHash := CaptureCase(allFilename, "", 0, true) if allFilename == "" { allFilename, _ = searchHash(allHash, true) } partFileName := RandStr(8) + ".bmp" currentHwnd := GetWindow("GetForegroundWindow", Debug) partFileName, partHash := CaptureCase(partFileName, "", currentHwnd, false) if partFileName == "" { partFileName, _ = searchHash(partHash, false) } if Exists(allFilename) == false { return } matImage := gocv.IMRead(allFilename, gocv.IMReadGrayScale) if Exists(partFileName) == false { return } matTemplate := gocv.IMRead(partFileName, gocv.IMReadGrayScale) matResult := gocv.NewMat() mask := gocv.NewMat() gocv.MatchTemplate(matImage, matTemplate, &matResult, gocv.TmCcoeffNormed, mask) mask.Close() minConfidence, maxConfidence, minLoc, maxLoc := gocv.MinMaxLoc(matResult) if Debug == true { fmt.Println(minConfidence, maxConfidence, minLoc, maxLoc) } targetX = int(evX) - maxLoc.X targetY = int(evY) - maxLoc.Y tempX = evX tempY = evY //allImg,allImageHash,targetImg,targetImgHash,x,y,clickType addHistory("click", allFilename+";"+allHash+";"+partFileName+";"+partHash+";"+strconv.Itoa(targetX)+";"+strconv.Itoa(targetY)+";"+strconv.Itoa(evButton)) } func GetMD5Hash(text string) string { hasher := md5.New() hasher.Write([]byte(text)) return hex.EncodeToString(hasher.Sum(nil)) } func addHistory(device, strs string) { if len(strs) > 0 { History = append(History, historyData{Device: device, Pre: preWindow, Aft: aftWindow, Params: strs}) if Debug == true { fmt.Println("liveRecord: ", strs) } } } func ListWindow(Debug bool) []string { var rect RECTdata ret := []string{} cb := syscall.NewCallback(func(h syscall.Handle, p uintptr) uintptr { b := make([]uint16, 200) _, err := GetWindowText(h, &b[0], int32(len(b))) if err != nil { return 1 } GetWindowRect(HWND(h), &rect, Debug) if rect.Left != 0 || rect.Top != 0 || rect.Right != 0 || rect.Bottom != 0 { if Debug == true { fmt.Printf("Window Title '%s' window: handle=0x%x\n", syscall.UTF16ToString(b), h) if rect.Left != 0 || rect.Top != 0 || rect.Right != 0 || rect.Bottom != 0 { fmt.Printf("window rect: ") fmt.Println(rect) } } ret = append(ret, fmt.Sprintf("%s : %x", syscall.UTF16ToString(b), h)) } return 1 }) EnumWindows(cb, 0) return ret } func matchCheck(stra, strb string) bool { if strings.Index(strb, stra) != -1 { return true } else { if strings.Index(stra, strb) != -1 { return true } } return false } func FocusWindow(title string, Debug bool) uintptr { var hwnd syscall.Handle var rect RECTdata cb := syscall.NewCallback(func(h syscall.Handle, p uintptr) uintptr { b := make([]uint16, 200) _, err := GetWindowText(h, &b[0], int32(len(b))) if err != nil { return 1 } if Debug == true { fmt.Printf("EnumWindows Search '%s' window: handle=0x%x\n", syscall.UTF16ToString(b), h) } if matchCheck(title, syscall.UTF16ToString(b)) == true { if Debug == true { fmt.Printf("Found! window: '%s' handle=0x%x\n", syscall.UTF16ToString(b), h) } GetWindowRect(HWND(h), &rect, Debug) fmt.Println() if int(rect.Right-rect.Left) > 0 && int(rect.Bottom-rect.Top) > 0 { hwnd = h return 0 } } return 1 }) EnumWindows(cb, 0) return uintptr(hwnd) } func GetWindow(funcName string, Debug bool) uintptr { hwnd, _, _ := syscall.Syscall(procGetForegroundWindow.Addr(), 6, 0, 0, 0) if Debug == true { fmt.Printf("currentWindow: handle=0x%x.\n", hwnd) } return hwnd } func SetActiveWindow(hwnd HWND, Debug bool) { if Debug == true { fmt.Printf("SetActiveWindow: handle=0x%x.\n", hwnd) } syscall.Syscall(procSetActiveWindow.Addr(), 4, uintptr(hwnd), 0, 0) syscall.Syscall(procSetForegroundWindow.Addr(), 5, uintptr(hwnd), 0, 0) } func GetWindowRect(hwnd HWND, rect *RECTdata, Debug bool) (err error)
func GetWindowText(hwnd syscall.Handle, str *uint16, maxCount int32) (len int32, err error) { r0, _, e1 := syscall.Syscall(procGetWindowTextW.Addr(), 3, uintptr(hwnd), uintptr(unsafe.Pointer(str)), uintptr(maxCount)) if len = int32(r0); len == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } func EnumWindows(enumFunc uintptr, lparam uintptr) (err error) { r1, _, e1 := syscall.Syscall(procEnumWindows.Addr(), 2, uintptr(enumFunc), uintptr(lparam), 0) if r1 == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } func RandStr(n int) string { b := make([]rune, n) for i := range b { b[i] = rs1Letters[rand.Intn(len(rs1Letters))] } return string(b) } func ExportHistory(filename string) bool { file, err := os.Create(prevDir + "\\" + filename) if err != nil { fmt.Println(err) return false } defer file.Close() for i := 0; i < len(History); i++ { strs := "" if History[i].Device == "click" { stra := strings.Split(History[i].Params, ";") strs = History[i].Device + "\t" + History[i].Pre + "\t" + History[i].Aft + "\t" + stra[0] + ";" + stra[2] + ";" + stra[4] + ";" + stra[5] + ";" + stra[6] } else if History[i].Device == "move" { stra := strings.Split(History[i].Params, ";") strs = History[i].Device + "\t" + History[i].Pre + "\t" + History[i].Aft + "\t" + stra[0] + ";" + stra[2] + ";" + stra[3] } else { strs = History[i].Device + "\t" + History[i].Pre + "\t" + History[i].Aft + "\t" + History[i].Params } if Debug == true { fmt.Printf("[%3d]: %s\n", i+1, strs) } if _, err = file.WriteString(strs + "\n"); err != nil { fmt.Println(err) return false } } fmt.Println("exportFile: ", filename) return true }
{ r1, _, e1 := syscall.Syscall(procGetWindowRect.Addr(), 7, uintptr(hwnd), uintptr(unsafe.Pointer(rect)), 0) if r1 == 0 { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return }
identifier_body
server.go
package server import ( "bufio" "fmt" "io" "net" "os" "time" // "github.com/pkg/profile" //uncomment to enable "sync/atomic" ) /* Constants for server connection. */ const ( ConnHost = "localhost" ConnPort = "3333" ConnType = "tcp" ) // RequestHeader is for representing a request header structure in Binary protocol. type RequestHeader struct { Magic uint8 Opcode uint8 KeyLength uint16 ExtraLength uint8 DataType uint8 VBucketID uint16 TotalBodyLength uint32 Opaque uint32 CAS uint64 } // ResponseHeader is for representing a response header structure in Binary protocol. type ResponseHeader struct { Magic uint8 Opcode uint8 KeyLength uint16 ExtraLength uint8 DataType uint8 Status uint16 TotalBodyLength uint32 Opaque uint32 CAS uint64 } // ConnectionContext is used as a context object during the life time of a connection. // It contains re-usable buffer across commands, keeps track of connection information, and provided access to read/write network channel. type ConnectionContext struct { RW *bufio.ReadWriter ConnHandle net.Conn ConnID uint64 // Internal debug purpose StartTime time.Time LastReqTime time.Time // For measuring how long a connection has been idle. CommandSeq uint64 // Every connection starts counting command from 0 ReadBuf []byte // Local to the goroutine handling a connection. Better utilizing memory. } /* 0x0000 No error 0x0001 Key not found 0x0002 Key exists 0x0003 Value too large 0x0004 Invalid arguments 0x0005 Item not stored 0x0006 Incr/Decr on non-numeric value. 0x0007 The vbucket belongs to another server 0x0008 Authentication error 0x0009 Authentication continue 0x0081 Unknown command 0x0082 Out of memory 0x0083 Not supported 0x0084 Internal error 0x0085 Busy 0x0086 Temporary failure */ const ( CodeNoError = 0x0000 CodeKeyNotFound = 0x0001 CodeKeyExists = 0X0002 ) /* 0x00 Get 0x01 Set 0x02 Add 0x03 Replace 0x04 Delete 0x05 Increment 0x06 Decrement 0x07 Quit 0x08 Flush 0x09 GetQ 0x0a No-op 0x0b Version 0x0c GetK 0x0d GetKQ 0x0e Append 0x0f Prepend 0x10 Stat 0x11 SetQ 0x12 AddQ 0x13 ReplaceQ 0x14 DeleteQ 0x15 IncrementQ 0x16 DecrementQ 0x17 QuitQ 0x18 FlushQ 0x19 AppendQ 0x1a PrependQ 0x1b Verbosity * 0x1c Touch * 0x1d GAT * 0x1e GATQ * 0x20 SASL list mechs 0x21 SASL Auth 0x22 SASL Step 0x30 RGet 0x31 RSet 0x32 RSetQ 0x33 RAppend 0x34 RAppendQ 0x35 RPrepend 0x36 RPrependQ 0x37 RDelete 0x38 RDeleteQ 0x39 RIncr 0x3a RIncrQ 0x3b RDecr 0x3c RDecrQ 0x3d Set VBucket * 0x3e Get VBucket * 0x3f Del VBucket * 0x40 TAP Connect * 0x41 TAP Mutation * 0x42 TAP Delete * 0x43 TAP Flush * 0x44 TAP Opaque * 0x45 TAP VBucket Set * 0x46 TAP Checkpoint Start * 0x47 TAP Checkpoint End * */ const ( OpGet = 0x00 OpSet = 0x01 OpAdd = 0x02 OpReplace = 0x03 OpQuit = 0x07 OpGetQ = 0x09 OpNoOp = 0x0a OpVersion = 0x0b OpGetK = 0x0c OpGetKQ = 0x0d OpSetQ = 0x11 OpAddQ = 0x12 OpReplaceQ = 0x13 ) /* Magic 0x80 Request 0x81 Response */ const ( MagicRequest = 0x80 MagicResponse = 0x81 ) // MaxReqLen is the max body length of a request. const MaxReqLen = 1024 * 1024 * 1024 // 1MB max request size var connSeq uint64 var casID uint64 /* Byte/ 0 | 1 | 2 | 3 | / | | | | |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| +---------------+---------------+---------------+---------------+ 0| Magic | Opcode | Key length | +---------------+---------------+---------------+---------------+ 4| Extras length | Data type | vbucket id | +---------------+---------------+---------------+---------------+ 8| Total body length | +---------------+---------------+---------------+---------------+ 12| Opaque | +---------------+---------------+---------------+---------------+ 16| CAS | | | +---------------+---------------+---------------+---------------+ Total 24 bytes */ func parseRequestHeader(bufHeader []byte) (RequestHeader, error) { ret := RequestHeader{} buf := bufHeader ret.Magic = uint8(buf[0]) if ret.Magic != MagicRequest { return RequestHeader{}, fmt.Errorf("Magic byte is not 0x80: %x", ret.Magic) } buf = buf[1:] ret.Opcode = uint8(buf[0]) _, ok := OpHandler[ret.Opcode] if !ok { return RequestHeader{}, fmt.Errorf("Opcode byte is not recognized: %x", ret.Opcode) } buf = buf[1:] ret.KeyLength = GetUint16(buf) buf = buf[2:] ret.ExtraLength = uint8(buf[0]) buf = buf[1:] ret.DataType = uint8(buf[0]) if ret.DataType != 0x00 { return RequestHeader{}, fmt.Errorf("DataType byte is supposed to be 0x00: %x", ret.DataType) } buf = buf[1:] ret.VBucketID = GetUint16(buf) buf = buf[2:] ret.TotalBodyLength = GetUint32(buf) if uint64(ret.TotalBodyLength) < uint64(ret.KeyLength)+uint64(ret.ExtraLength) { return RequestHeader{}, fmt.Errorf("TotaoBodyLength is supposed to be no less than KeyLength + ExtraLength: total: %d key: %d extra %d", ret.TotalBodyLength, ret.KeyLength, ret.ExtraLength) } buf = buf[4:] ret.Opaque = GetUint32(buf) buf = buf[4:] ret.CAS = GetUint64(buf) return ret, nil } /* Byte/ 0 | 1 | 2 | 3 | / | | | | |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| +---------------+---------------+---------------+---------------+ 0| Magic | Opcode | Key Length | +---------------+---------------+---------------+---------------+ 4| Extras length | Data type | Status | +---------------+---------------+---------------+---------------+ 8| Total body length | +---------------+---------------+---------------+---------------+ 12| Opaque | +---------------+---------------+---------------+---------------+ 16| CAS | | | +---------------+---------------+---------------+---------------+ Total 24 bytes */ func writeResponseHeader(header ResponseHeader, rw *bufio.ReadWriter) error { err := rw.WriteByte(header.Magic) if err != nil { return err } err = rw.WriteByte(header.Opcode) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.KeyLength, 0)) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.KeyLength, 1)) if err != nil { return err } err = rw.WriteByte(header.ExtraLength) if err != nil { return err } err = rw.WriteByte(header.DataType) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.Status, 0)) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.Status, 1)) if err != nil { return err } for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(header.TotalBodyLength, pos)) if err != nil { return err } } for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(header.Opaque, pos)) if err != nil { return err } } l := uint32(header.CAS >> 32) r := uint32(header.CAS & 0x00000000ffffffff) for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(l, pos)) if err != nil { return err } } for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(r, pos)) if err != nil { return err } } return nil } func handleCommand(context *ConnectionContext) error { // Make a buffer to hold incoming data. bufHeader := context.ReadBuf[:24] readLen := 0 for readLen < len(bufHeader) { reqLen, err := context.RW.Read(bufHeader[readLen:]) if err != nil { return err } readLen += reqLen } context.CommandSeq++ context.LastReqTime = time.Now() // fmt.Printf("Request header: %v\n", bufHeader) reqHeader, err := parseRequestHeader(bufHeader) if err != nil { fmt.Printf("Error parsing header: %s | % 20x\n", err, bufHeader) fmt.Fprintf(context.RW, "Error %s\n", err) return err } err = OpHandler[reqHeader.Opcode].Handle(reqHeader, context) return err } // Handles incoming requests. func handleRequest(conn net.Conn) { defer conn.Close() rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn)) context := &ConnectionContext{ ConnID: atomic.AddUint64(&connSeq, 1), ConnHandle: conn, StartTime: time.Now(), LastReqTime: time.Now(), CommandSeq: 0, RW: rw, ReadBuf: make([]byte, 4096), // 4KB initial read buffer } defer rw.Flush() for { err := handleCommand(context) switch err { case nil: break case io.EOF: fmt.Printf("Client %s closed connection %d: connected at %s, handled %d commands.\n", context.ConnHandle.RemoteAddr().String(), context.ConnID, context.StartTime.String(), context.CommandSeq) return default: fmt.Println("Error reading:", err.Error()) return } // force sending down a response rw.Flush() } } // Start starts the memcache server listening on TCP with Binary protocol support func
() { // defer profile.Start().Stop() // uncomment to enable profiler // Listen for incoming connections. l, err := net.Listen(ConnType, ConnHost+":"+ConnPort) if err != nil { fmt.Println("Error listening:", err.Error()) os.Exit(1) } // Close the listener when the application closes. defer l.Close() fmt.Println("Listening on " + ConnHost + ":" + ConnPort) for { // Listen for an incoming connection. conn, err := l.Accept() if err != nil { fmt.Println("Error accepting: ", err.Error()) os.Exit(1) } // Handle connections in a new goroutine. go handleRequest(conn) } }
Start
identifier_name
server.go
package server import ( "bufio" "fmt" "io" "net" "os" "time" // "github.com/pkg/profile" //uncomment to enable "sync/atomic" ) /* Constants for server connection. */ const ( ConnHost = "localhost" ConnPort = "3333" ConnType = "tcp" ) // RequestHeader is for representing a request header structure in Binary protocol. type RequestHeader struct { Magic uint8 Opcode uint8 KeyLength uint16 ExtraLength uint8 DataType uint8 VBucketID uint16 TotalBodyLength uint32 Opaque uint32 CAS uint64 } // ResponseHeader is for representing a response header structure in Binary protocol. type ResponseHeader struct { Magic uint8 Opcode uint8 KeyLength uint16 ExtraLength uint8 DataType uint8 Status uint16 TotalBodyLength uint32 Opaque uint32 CAS uint64 } // ConnectionContext is used as a context object during the life time of a connection. // It contains re-usable buffer across commands, keeps track of connection information, and provided access to read/write network channel. type ConnectionContext struct { RW *bufio.ReadWriter ConnHandle net.Conn ConnID uint64 // Internal debug purpose StartTime time.Time LastReqTime time.Time // For measuring how long a connection has been idle. CommandSeq uint64 // Every connection starts counting command from 0 ReadBuf []byte // Local to the goroutine handling a connection. Better utilizing memory. } /* 0x0000 No error 0x0001 Key not found 0x0002 Key exists 0x0003 Value too large 0x0004 Invalid arguments 0x0005 Item not stored 0x0006 Incr/Decr on non-numeric value. 0x0007 The vbucket belongs to another server 0x0008 Authentication error 0x0009 Authentication continue 0x0081 Unknown command 0x0082 Out of memory 0x0083 Not supported 0x0084 Internal error 0x0085 Busy 0x0086 Temporary failure */ const ( CodeNoError = 0x0000 CodeKeyNotFound = 0x0001 CodeKeyExists = 0X0002 ) /* 0x00 Get 0x01 Set 0x02 Add 0x03 Replace 0x04 Delete 0x05 Increment 0x06 Decrement 0x07 Quit 0x08 Flush 0x09 GetQ 0x0a No-op 0x0b Version 0x0c GetK 0x0d GetKQ 0x0e Append 0x0f Prepend 0x10 Stat 0x11 SetQ 0x12 AddQ 0x13 ReplaceQ 0x14 DeleteQ 0x15 IncrementQ 0x16 DecrementQ 0x17 QuitQ 0x18 FlushQ 0x19 AppendQ 0x1a PrependQ 0x1b Verbosity * 0x1c Touch * 0x1d GAT * 0x1e GATQ * 0x20 SASL list mechs 0x21 SASL Auth 0x22 SASL Step 0x30 RGet 0x31 RSet 0x32 RSetQ 0x33 RAppend 0x34 RAppendQ 0x35 RPrepend 0x36 RPrependQ 0x37 RDelete 0x38 RDeleteQ 0x39 RIncr 0x3a RIncrQ 0x3b RDecr 0x3c RDecrQ 0x3d Set VBucket * 0x3e Get VBucket * 0x3f Del VBucket * 0x40 TAP Connect * 0x41 TAP Mutation * 0x42 TAP Delete * 0x43 TAP Flush * 0x44 TAP Opaque * 0x45 TAP VBucket Set * 0x46 TAP Checkpoint Start * 0x47 TAP Checkpoint End * */ const ( OpGet = 0x00 OpSet = 0x01 OpAdd = 0x02 OpReplace = 0x03 OpQuit = 0x07 OpGetQ = 0x09 OpNoOp = 0x0a OpVersion = 0x0b OpGetK = 0x0c OpGetKQ = 0x0d OpSetQ = 0x11 OpAddQ = 0x12 OpReplaceQ = 0x13 ) /* Magic 0x80 Request 0x81 Response */ const ( MagicRequest = 0x80 MagicResponse = 0x81 ) // MaxReqLen is the max body length of a request. const MaxReqLen = 1024 * 1024 * 1024 // 1MB max request size var connSeq uint64 var casID uint64 /* Byte/ 0 | 1 | 2 | 3 | / | | | | |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| +---------------+---------------+---------------+---------------+ 0| Magic | Opcode | Key length | +---------------+---------------+---------------+---------------+ 4| Extras length | Data type | vbucket id | +---------------+---------------+---------------+---------------+ 8| Total body length | +---------------+---------------+---------------+---------------+ 12| Opaque | +---------------+---------------+---------------+---------------+ 16| CAS | | | +---------------+---------------+---------------+---------------+ Total 24 bytes */ func parseRequestHeader(bufHeader []byte) (RequestHeader, error) { ret := RequestHeader{} buf := bufHeader ret.Magic = uint8(buf[0]) if ret.Magic != MagicRequest { return RequestHeader{}, fmt.Errorf("Magic byte is not 0x80: %x", ret.Magic) } buf = buf[1:] ret.Opcode = uint8(buf[0]) _, ok := OpHandler[ret.Opcode] if !ok { return RequestHeader{}, fmt.Errorf("Opcode byte is not recognized: %x", ret.Opcode) } buf = buf[1:] ret.KeyLength = GetUint16(buf) buf = buf[2:] ret.ExtraLength = uint8(buf[0]) buf = buf[1:] ret.DataType = uint8(buf[0]) if ret.DataType != 0x00 { return RequestHeader{}, fmt.Errorf("DataType byte is supposed to be 0x00: %x", ret.DataType) } buf = buf[1:] ret.VBucketID = GetUint16(buf) buf = buf[2:] ret.TotalBodyLength = GetUint32(buf) if uint64(ret.TotalBodyLength) < uint64(ret.KeyLength)+uint64(ret.ExtraLength) { return RequestHeader{}, fmt.Errorf("TotaoBodyLength is supposed to be no less than KeyLength + ExtraLength: total: %d key: %d extra %d", ret.TotalBodyLength, ret.KeyLength, ret.ExtraLength) } buf = buf[4:] ret.Opaque = GetUint32(buf) buf = buf[4:] ret.CAS = GetUint64(buf) return ret, nil } /* Byte/ 0 | 1 | 2 | 3 | / | | | | |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| +---------------+---------------+---------------+---------------+ 0| Magic | Opcode | Key Length | +---------------+---------------+---------------+---------------+ 4| Extras length | Data type | Status | +---------------+---------------+---------------+---------------+ 8| Total body length | +---------------+---------------+---------------+---------------+ 12| Opaque | +---------------+---------------+---------------+---------------+ 16| CAS | | | +---------------+---------------+---------------+---------------+ Total 24 bytes */ func writeResponseHeader(header ResponseHeader, rw *bufio.ReadWriter) error
func handleCommand(context *ConnectionContext) error { // Make a buffer to hold incoming data. bufHeader := context.ReadBuf[:24] readLen := 0 for readLen < len(bufHeader) { reqLen, err := context.RW.Read(bufHeader[readLen:]) if err != nil { return err } readLen += reqLen } context.CommandSeq++ context.LastReqTime = time.Now() // fmt.Printf("Request header: %v\n", bufHeader) reqHeader, err := parseRequestHeader(bufHeader) if err != nil { fmt.Printf("Error parsing header: %s | % 20x\n", err, bufHeader) fmt.Fprintf(context.RW, "Error %s\n", err) return err } err = OpHandler[reqHeader.Opcode].Handle(reqHeader, context) return err } // Handles incoming requests. func handleRequest(conn net.Conn) { defer conn.Close() rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn)) context := &ConnectionContext{ ConnID: atomic.AddUint64(&connSeq, 1), ConnHandle: conn, StartTime: time.Now(), LastReqTime: time.Now(), CommandSeq: 0, RW: rw, ReadBuf: make([]byte, 4096), // 4KB initial read buffer } defer rw.Flush() for { err := handleCommand(context) switch err { case nil: break case io.EOF: fmt.Printf("Client %s closed connection %d: connected at %s, handled %d commands.\n", context.ConnHandle.RemoteAddr().String(), context.ConnID, context.StartTime.String(), context.CommandSeq) return default: fmt.Println("Error reading:", err.Error()) return } // force sending down a response rw.Flush() } } // Start starts the memcache server listening on TCP with Binary protocol support func Start() { // defer profile.Start().Stop() // uncomment to enable profiler // Listen for incoming connections. l, err := net.Listen(ConnType, ConnHost+":"+ConnPort) if err != nil { fmt.Println("Error listening:", err.Error()) os.Exit(1) } // Close the listener when the application closes. defer l.Close() fmt.Println("Listening on " + ConnHost + ":" + ConnPort) for { // Listen for an incoming connection. conn, err := l.Accept() if err != nil { fmt.Println("Error accepting: ", err.Error()) os.Exit(1) } // Handle connections in a new goroutine. go handleRequest(conn) } }
{ err := rw.WriteByte(header.Magic) if err != nil { return err } err = rw.WriteByte(header.Opcode) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.KeyLength, 0)) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.KeyLength, 1)) if err != nil { return err } err = rw.WriteByte(header.ExtraLength) if err != nil { return err } err = rw.WriteByte(header.DataType) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.Status, 0)) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.Status, 1)) if err != nil { return err } for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(header.TotalBodyLength, pos)) if err != nil { return err } } for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(header.Opaque, pos)) if err != nil { return err } } l := uint32(header.CAS >> 32) r := uint32(header.CAS & 0x00000000ffffffff) for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(l, pos)) if err != nil { return err } } for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(r, pos)) if err != nil { return err } } return nil }
identifier_body
server.go
package server import ( "bufio" "fmt" "io" "net" "os" "time" // "github.com/pkg/profile" //uncomment to enable "sync/atomic" ) /* Constants for server connection. */ const ( ConnHost = "localhost" ConnPort = "3333" ConnType = "tcp" ) // RequestHeader is for representing a request header structure in Binary protocol. type RequestHeader struct { Magic uint8 Opcode uint8 KeyLength uint16 ExtraLength uint8 DataType uint8 VBucketID uint16 TotalBodyLength uint32 Opaque uint32 CAS uint64 } // ResponseHeader is for representing a response header structure in Binary protocol. type ResponseHeader struct { Magic uint8 Opcode uint8 KeyLength uint16 ExtraLength uint8 DataType uint8 Status uint16 TotalBodyLength uint32 Opaque uint32 CAS uint64 } // ConnectionContext is used as a context object during the life time of a connection. // It contains re-usable buffer across commands, keeps track of connection information, and provided access to read/write network channel. type ConnectionContext struct { RW *bufio.ReadWriter ConnHandle net.Conn ConnID uint64 // Internal debug purpose StartTime time.Time LastReqTime time.Time // For measuring how long a connection has been idle. CommandSeq uint64 // Every connection starts counting command from 0 ReadBuf []byte // Local to the goroutine handling a connection. Better utilizing memory. } /* 0x0000 No error 0x0001 Key not found 0x0002 Key exists 0x0003 Value too large 0x0004 Invalid arguments 0x0005 Item not stored 0x0006 Incr/Decr on non-numeric value. 0x0007 The vbucket belongs to another server 0x0008 Authentication error 0x0009 Authentication continue 0x0081 Unknown command 0x0082 Out of memory 0x0083 Not supported 0x0084 Internal error 0x0085 Busy 0x0086 Temporary failure */ const ( CodeNoError = 0x0000 CodeKeyNotFound = 0x0001 CodeKeyExists = 0X0002 ) /* 0x00 Get 0x01 Set 0x02 Add 0x03 Replace 0x04 Delete 0x05 Increment 0x06 Decrement 0x07 Quit 0x08 Flush 0x09 GetQ 0x0a No-op 0x0b Version 0x0c GetK 0x0d GetKQ 0x0e Append 0x0f Prepend 0x10 Stat 0x11 SetQ 0x12 AddQ 0x13 ReplaceQ 0x14 DeleteQ 0x15 IncrementQ 0x16 DecrementQ 0x17 QuitQ 0x18 FlushQ 0x19 AppendQ 0x1a PrependQ 0x1b Verbosity * 0x1c Touch * 0x1d GAT * 0x1e GATQ * 0x20 SASL list mechs 0x21 SASL Auth 0x22 SASL Step 0x30 RGet 0x31 RSet 0x32 RSetQ 0x33 RAppend 0x34 RAppendQ 0x35 RPrepend 0x36 RPrependQ 0x37 RDelete 0x38 RDeleteQ 0x39 RIncr 0x3a RIncrQ 0x3b RDecr 0x3c RDecrQ 0x3d Set VBucket * 0x3e Get VBucket * 0x3f Del VBucket * 0x40 TAP Connect * 0x41 TAP Mutation * 0x42 TAP Delete * 0x43 TAP Flush * 0x44 TAP Opaque * 0x45 TAP VBucket Set * 0x46 TAP Checkpoint Start * 0x47 TAP Checkpoint End * */ const ( OpGet = 0x00 OpSet = 0x01 OpAdd = 0x02 OpReplace = 0x03 OpQuit = 0x07 OpGetQ = 0x09 OpNoOp = 0x0a OpVersion = 0x0b OpGetK = 0x0c OpGetKQ = 0x0d OpSetQ = 0x11 OpAddQ = 0x12 OpReplaceQ = 0x13 ) /* Magic 0x80 Request 0x81 Response */ const ( MagicRequest = 0x80 MagicResponse = 0x81 ) // MaxReqLen is the max body length of a request. const MaxReqLen = 1024 * 1024 * 1024 // 1MB max request size var connSeq uint64 var casID uint64 /* Byte/ 0 | 1 | 2 | 3 | / | | | | |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| +---------------+---------------+---------------+---------------+ 0| Magic | Opcode | Key length | +---------------+---------------+---------------+---------------+ 4| Extras length | Data type | vbucket id | +---------------+---------------+---------------+---------------+ 8| Total body length | +---------------+---------------+---------------+---------------+ 12| Opaque | +---------------+---------------+---------------+---------------+ 16| CAS | | | +---------------+---------------+---------------+---------------+ Total 24 bytes */ func parseRequestHeader(bufHeader []byte) (RequestHeader, error) { ret := RequestHeader{} buf := bufHeader ret.Magic = uint8(buf[0]) if ret.Magic != MagicRequest { return RequestHeader{}, fmt.Errorf("Magic byte is not 0x80: %x", ret.Magic) } buf = buf[1:] ret.Opcode = uint8(buf[0]) _, ok := OpHandler[ret.Opcode] if !ok { return RequestHeader{}, fmt.Errorf("Opcode byte is not recognized: %x", ret.Opcode) } buf = buf[1:] ret.KeyLength = GetUint16(buf) buf = buf[2:] ret.ExtraLength = uint8(buf[0]) buf = buf[1:] ret.DataType = uint8(buf[0]) if ret.DataType != 0x00 { return RequestHeader{}, fmt.Errorf("DataType byte is supposed to be 0x00: %x", ret.DataType) } buf = buf[1:] ret.VBucketID = GetUint16(buf) buf = buf[2:] ret.TotalBodyLength = GetUint32(buf) if uint64(ret.TotalBodyLength) < uint64(ret.KeyLength)+uint64(ret.ExtraLength) { return RequestHeader{}, fmt.Errorf("TotaoBodyLength is supposed to be no less than KeyLength + ExtraLength: total: %d key: %d extra %d", ret.TotalBodyLength, ret.KeyLength, ret.ExtraLength) } buf = buf[4:] ret.Opaque = GetUint32(buf) buf = buf[4:] ret.CAS = GetUint64(buf) return ret, nil } /* Byte/ 0 | 1 | 2 | 3 | / | | | | |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| +---------------+---------------+---------------+---------------+ 0| Magic | Opcode | Key Length | +---------------+---------------+---------------+---------------+ 4| Extras length | Data type | Status | +---------------+---------------+---------------+---------------+ 8| Total body length | +---------------+---------------+---------------+---------------+ 12| Opaque | +---------------+---------------+---------------+---------------+ 16| CAS | | | +---------------+---------------+---------------+---------------+ Total 24 bytes */ func writeResponseHeader(header ResponseHeader, rw *bufio.ReadWriter) error { err := rw.WriteByte(header.Magic) if err != nil { return err } err = rw.WriteByte(header.Opcode) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.KeyLength, 0)) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.KeyLength, 1)) if err != nil { return err } err = rw.WriteByte(header.ExtraLength) if err != nil { return err } err = rw.WriteByte(header.DataType) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.Status, 0)) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.Status, 1)) if err != nil
for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(header.TotalBodyLength, pos)) if err != nil { return err } } for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(header.Opaque, pos)) if err != nil { return err } } l := uint32(header.CAS >> 32) r := uint32(header.CAS & 0x00000000ffffffff) for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(l, pos)) if err != nil { return err } } for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(r, pos)) if err != nil { return err } } return nil } func handleCommand(context *ConnectionContext) error { // Make a buffer to hold incoming data. bufHeader := context.ReadBuf[:24] readLen := 0 for readLen < len(bufHeader) { reqLen, err := context.RW.Read(bufHeader[readLen:]) if err != nil { return err } readLen += reqLen } context.CommandSeq++ context.LastReqTime = time.Now() // fmt.Printf("Request header: %v\n", bufHeader) reqHeader, err := parseRequestHeader(bufHeader) if err != nil { fmt.Printf("Error parsing header: %s | % 20x\n", err, bufHeader) fmt.Fprintf(context.RW, "Error %s\n", err) return err } err = OpHandler[reqHeader.Opcode].Handle(reqHeader, context) return err } // Handles incoming requests. func handleRequest(conn net.Conn) { defer conn.Close() rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn)) context := &ConnectionContext{ ConnID: atomic.AddUint64(&connSeq, 1), ConnHandle: conn, StartTime: time.Now(), LastReqTime: time.Now(), CommandSeq: 0, RW: rw, ReadBuf: make([]byte, 4096), // 4KB initial read buffer } defer rw.Flush() for { err := handleCommand(context) switch err { case nil: break case io.EOF: fmt.Printf("Client %s closed connection %d: connected at %s, handled %d commands.\n", context.ConnHandle.RemoteAddr().String(), context.ConnID, context.StartTime.String(), context.CommandSeq) return default: fmt.Println("Error reading:", err.Error()) return } // force sending down a response rw.Flush() } } // Start starts the memcache server listening on TCP with Binary protocol support func Start() { // defer profile.Start().Stop() // uncomment to enable profiler // Listen for incoming connections. l, err := net.Listen(ConnType, ConnHost+":"+ConnPort) if err != nil { fmt.Println("Error listening:", err.Error()) os.Exit(1) } // Close the listener when the application closes. defer l.Close() fmt.Println("Listening on " + ConnHost + ":" + ConnPort) for { // Listen for an incoming connection. conn, err := l.Accept() if err != nil { fmt.Println("Error accepting: ", err.Error()) os.Exit(1) } // Handle connections in a new goroutine. go handleRequest(conn) } }
{ return err }
conditional_block
server.go
package server import ( "bufio" "fmt" "io" "net" "os" "time" // "github.com/pkg/profile" //uncomment to enable "sync/atomic" ) /* Constants for server connection. */ const ( ConnHost = "localhost" ConnPort = "3333" ConnType = "tcp" ) // RequestHeader is for representing a request header structure in Binary protocol. type RequestHeader struct { Magic uint8 Opcode uint8 KeyLength uint16 ExtraLength uint8 DataType uint8 VBucketID uint16 TotalBodyLength uint32 Opaque uint32 CAS uint64 } // ResponseHeader is for representing a response header structure in Binary protocol. type ResponseHeader struct { Magic uint8 Opcode uint8 KeyLength uint16 ExtraLength uint8 DataType uint8 Status uint16 TotalBodyLength uint32 Opaque uint32 CAS uint64 } // ConnectionContext is used as a context object during the life time of a connection. // It contains re-usable buffer across commands, keeps track of connection information, and provided access to read/write network channel. type ConnectionContext struct { RW *bufio.ReadWriter ConnHandle net.Conn ConnID uint64 // Internal debug purpose StartTime time.Time LastReqTime time.Time // For measuring how long a connection has been idle. CommandSeq uint64 // Every connection starts counting command from 0 ReadBuf []byte // Local to the goroutine handling a connection. Better utilizing memory. } /* 0x0000 No error 0x0001 Key not found 0x0002 Key exists 0x0003 Value too large 0x0004 Invalid arguments 0x0005 Item not stored 0x0006 Incr/Decr on non-numeric value. 0x0007 The vbucket belongs to another server 0x0008 Authentication error 0x0009 Authentication continue 0x0081 Unknown command 0x0082 Out of memory 0x0083 Not supported 0x0084 Internal error 0x0085 Busy 0x0086 Temporary failure */ const ( CodeNoError = 0x0000 CodeKeyNotFound = 0x0001 CodeKeyExists = 0X0002 ) /* 0x00 Get 0x01 Set 0x02 Add 0x03 Replace 0x04 Delete 0x05 Increment 0x06 Decrement 0x07 Quit 0x08 Flush 0x09 GetQ 0x0a No-op 0x0b Version 0x0c GetK 0x0d GetKQ 0x0e Append 0x0f Prepend 0x10 Stat 0x11 SetQ 0x12 AddQ 0x13 ReplaceQ 0x14 DeleteQ 0x15 IncrementQ 0x16 DecrementQ 0x17 QuitQ 0x18 FlushQ 0x19 AppendQ 0x1a PrependQ 0x1b Verbosity * 0x1c Touch * 0x1d GAT * 0x1e GATQ * 0x20 SASL list mechs 0x21 SASL Auth 0x22 SASL Step 0x30 RGet 0x31 RSet 0x32 RSetQ 0x33 RAppend 0x34 RAppendQ 0x35 RPrepend 0x36 RPrependQ 0x37 RDelete 0x38 RDeleteQ 0x39 RIncr 0x3a RIncrQ 0x3b RDecr 0x3c RDecrQ 0x3d Set VBucket * 0x3e Get VBucket * 0x3f Del VBucket * 0x40 TAP Connect * 0x41 TAP Mutation * 0x42 TAP Delete * 0x43 TAP Flush * 0x44 TAP Opaque * 0x45 TAP VBucket Set * 0x46 TAP Checkpoint Start * 0x47 TAP Checkpoint End * */ const ( OpGet = 0x00 OpSet = 0x01 OpAdd = 0x02 OpReplace = 0x03 OpQuit = 0x07 OpGetQ = 0x09 OpNoOp = 0x0a OpVersion = 0x0b OpGetK = 0x0c OpGetKQ = 0x0d OpSetQ = 0x11 OpAddQ = 0x12 OpReplaceQ = 0x13 ) /* Magic 0x80 Request 0x81 Response */ const ( MagicRequest = 0x80 MagicResponse = 0x81 ) // MaxReqLen is the max body length of a request. const MaxReqLen = 1024 * 1024 * 1024 // 1MB max request size var connSeq uint64 var casID uint64 /* Byte/ 0 | 1 | 2 | 3 | / | | | | |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| +---------------+---------------+---------------+---------------+ 0| Magic | Opcode | Key length | +---------------+---------------+---------------+---------------+ 4| Extras length | Data type | vbucket id | +---------------+---------------+---------------+---------------+ 8| Total body length | +---------------+---------------+---------------+---------------+ 12| Opaque | +---------------+---------------+---------------+---------------+ 16| CAS | | | +---------------+---------------+---------------+---------------+ Total 24 bytes */ func parseRequestHeader(bufHeader []byte) (RequestHeader, error) { ret := RequestHeader{} buf := bufHeader ret.Magic = uint8(buf[0]) if ret.Magic != MagicRequest { return RequestHeader{}, fmt.Errorf("Magic byte is not 0x80: %x", ret.Magic) } buf = buf[1:] ret.Opcode = uint8(buf[0]) _, ok := OpHandler[ret.Opcode] if !ok { return RequestHeader{}, fmt.Errorf("Opcode byte is not recognized: %x", ret.Opcode) } buf = buf[1:] ret.KeyLength = GetUint16(buf) buf = buf[2:] ret.ExtraLength = uint8(buf[0]) buf = buf[1:] ret.DataType = uint8(buf[0]) if ret.DataType != 0x00 { return RequestHeader{}, fmt.Errorf("DataType byte is supposed to be 0x00: %x", ret.DataType) } buf = buf[1:] ret.VBucketID = GetUint16(buf) buf = buf[2:] ret.TotalBodyLength = GetUint32(buf) if uint64(ret.TotalBodyLength) < uint64(ret.KeyLength)+uint64(ret.ExtraLength) { return RequestHeader{}, fmt.Errorf("TotaoBodyLength is supposed to be no less than KeyLength + ExtraLength: total: %d key: %d extra %d", ret.TotalBodyLength, ret.KeyLength, ret.ExtraLength) } buf = buf[4:] ret.Opaque = GetUint32(buf) buf = buf[4:]
return ret, nil } /* Byte/ 0 | 1 | 2 | 3 | / | | | | |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| +---------------+---------------+---------------+---------------+ 0| Magic | Opcode | Key Length | +---------------+---------------+---------------+---------------+ 4| Extras length | Data type | Status | +---------------+---------------+---------------+---------------+ 8| Total body length | +---------------+---------------+---------------+---------------+ 12| Opaque | +---------------+---------------+---------------+---------------+ 16| CAS | | | +---------------+---------------+---------------+---------------+ Total 24 bytes */ func writeResponseHeader(header ResponseHeader, rw *bufio.ReadWriter) error { err := rw.WriteByte(header.Magic) if err != nil { return err } err = rw.WriteByte(header.Opcode) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.KeyLength, 0)) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.KeyLength, 1)) if err != nil { return err } err = rw.WriteByte(header.ExtraLength) if err != nil { return err } err = rw.WriteByte(header.DataType) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.Status, 0)) if err != nil { return err } err = rw.WriteByte(GetNthByteFromUint16(header.Status, 1)) if err != nil { return err } for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(header.TotalBodyLength, pos)) if err != nil { return err } } for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(header.Opaque, pos)) if err != nil { return err } } l := uint32(header.CAS >> 32) r := uint32(header.CAS & 0x00000000ffffffff) for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(l, pos)) if err != nil { return err } } for pos := 0; pos < 4; pos++ { err = rw.WriteByte(GetNthByteFromUint32(r, pos)) if err != nil { return err } } return nil } func handleCommand(context *ConnectionContext) error { // Make a buffer to hold incoming data. bufHeader := context.ReadBuf[:24] readLen := 0 for readLen < len(bufHeader) { reqLen, err := context.RW.Read(bufHeader[readLen:]) if err != nil { return err } readLen += reqLen } context.CommandSeq++ context.LastReqTime = time.Now() // fmt.Printf("Request header: %v\n", bufHeader) reqHeader, err := parseRequestHeader(bufHeader) if err != nil { fmt.Printf("Error parsing header: %s | % 20x\n", err, bufHeader) fmt.Fprintf(context.RW, "Error %s\n", err) return err } err = OpHandler[reqHeader.Opcode].Handle(reqHeader, context) return err } // Handles incoming requests. func handleRequest(conn net.Conn) { defer conn.Close() rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn)) context := &ConnectionContext{ ConnID: atomic.AddUint64(&connSeq, 1), ConnHandle: conn, StartTime: time.Now(), LastReqTime: time.Now(), CommandSeq: 0, RW: rw, ReadBuf: make([]byte, 4096), // 4KB initial read buffer } defer rw.Flush() for { err := handleCommand(context) switch err { case nil: break case io.EOF: fmt.Printf("Client %s closed connection %d: connected at %s, handled %d commands.\n", context.ConnHandle.RemoteAddr().String(), context.ConnID, context.StartTime.String(), context.CommandSeq) return default: fmt.Println("Error reading:", err.Error()) return } // force sending down a response rw.Flush() } } // Start starts the memcache server listening on TCP with Binary protocol support func Start() { // defer profile.Start().Stop() // uncomment to enable profiler // Listen for incoming connections. l, err := net.Listen(ConnType, ConnHost+":"+ConnPort) if err != nil { fmt.Println("Error listening:", err.Error()) os.Exit(1) } // Close the listener when the application closes. defer l.Close() fmt.Println("Listening on " + ConnHost + ":" + ConnPort) for { // Listen for an incoming connection. conn, err := l.Accept() if err != nil { fmt.Println("Error accepting: ", err.Error()) os.Exit(1) } // Handle connections in a new goroutine. go handleRequest(conn) } }
ret.CAS = GetUint64(buf)
random_line_split
gitiles.go
// Copyright 2016 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gitiles import ( "fmt" "net/url" "sort" "strings" "sync" "time" "github.com/golang/protobuf/proto" "golang.org/x/net/context" "google.golang.org/api/pubsub/v1" "go.chromium.org/luci/common/api/gitiles" "go.chromium.org/luci/common/data/stringset" "go.chromium.org/luci/common/errors" "go.chromium.org/luci/common/logging" gitilespb "go.chromium.org/luci/common/proto/gitiles" "go.chromium.org/luci/config/validation" "go.chromium.org/luci/server/auth" api "go.chromium.org/luci/scheduler/api/scheduler/v1" "go.chromium.org/luci/scheduler/appengine/internal" "go.chromium.org/luci/scheduler/appengine/messages" "go.chromium.org/luci/scheduler/appengine/task" ) // defaultMaxTriggersPerInvocation limits number of triggers emitted per one // invocation. const defaultMaxTriggersPerInvocation = 100 // TaskManager implements task.Manager interface for tasks defined with // GitilesTask proto message. type TaskManager struct { mockGitilesClient gitilespb.GitilesClient // Used for testing only. maxTriggersPerInvocation int // Avoid choking on DS or runtime limits. } // Name is part of Manager interface. func (m TaskManager) Name() string { return "gitiles" } // ProtoMessageType is part of Manager interface. func (m TaskManager) ProtoMessageType() proto.Message { return (*messages.GitilesTask)(nil) } // Traits is part of Manager interface. func (m TaskManager) Traits() task.Traits { return task.Traits{ Multistage: false, // we don't use task.StatusRunning state } } // ValidateProtoMessage is part of Manager interface. func (m TaskManager) ValidateProtoMessage(c *validation.Context, msg proto.Message) { cfg, ok := msg.(*messages.GitilesTask) if !ok { c.Errorf("wrong type %T, expecting *messages.GitilesTask", msg) return } // Validate 'repo' field. c.Enter("repo") if cfg.Repo == "" { c.Errorf("field 'repository' is required") } else { u, err := url.Parse(cfg.Repo) if err != nil { c.Errorf("invalid URL %q: %s", cfg.Repo, err) } else if !u.IsAbs() { c.Errorf("not an absolute url: %q", cfg.Repo) } } c.Exit() c.Enter("refs") for _, ref := range cfg.Refs { if !strings.HasPrefix(ref, "refs/") { c.Errorf("ref must start with 'refs/' not %q", ref) } cnt := strings.Count(ref, "*") if cnt > 1 || (cnt == 1 && !strings.HasSuffix(ref, "/*")) { c.Errorf("only trailing (e.g. refs/blah/*) globs are supported, not %q", ref) } } c.Exit() } // LaunchTask is part of Manager interface. func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error { cfg := ctl.Task().(*messages.GitilesTask) ctl.DebugLog("Repo: %s, Refs: %s", cfg.Repo, cfg.Refs) u, err := url.Parse(cfg.Repo) if err != nil { return err } watchedRefs := watchedRefs{} watchedRefs.init(cfg.GetRefs()) var wg sync.WaitGroup var heads map[string]string var headsErr error wg.Add(1) go func() { defer wg.Done() heads, headsErr = loadState(c, ctl.JobID(), u) }() var refs map[string]string var refsErr error wg.Add(1) go func() { defer wg.Done() refs, refsErr = m.getRefsTips(c, ctl, cfg.Repo, watchedRefs) }() wg.Wait() if headsErr != nil { ctl.DebugLog("Failed to fetch heads - %s", headsErr) return fmt.Errorf("failed to fetch heads: %v", headsErr) } if refsErr != nil { ctl.DebugLog("Failed to fetch refs - %s", refsErr) return fmt.Errorf("failed to fetch refs: %v", refsErr) } refsChanged := 0 // Delete all previously known refs which are either no longer watched or no // longer exist in repo. for ref := range heads { switch { case !watchedRefs.hasRef(ref): ctl.DebugLog("Ref %s is no longer watched", ref) delete(heads, ref) refsChanged++ case refs[ref] == "": ctl.DebugLog("Ref %s deleted", ref) delete(heads, ref) refsChanged++ } } // For determinism, sort keys of current refs. sortedRefs := make([]string, 0, len(refs)) for ref := range refs { sortedRefs = append(sortedRefs, ref) } sort.Strings(sortedRefs) emittedTriggers := 0 maxTriggersPerInvocation := m.maxTriggersPerInvocation if maxTriggersPerInvocation == 0 { maxTriggersPerInvocation = defaultMaxTriggersPerInvocation } // Note, that current `refs` contain only watched refs (see getRefsTips). for _, ref := range sortedRefs { newHead := refs[ref] oldHead, existed := heads[ref] switch { case !existed: ctl.DebugLog("Ref %s is new: %s", ref, newHead) case oldHead != newHead: ctl.DebugLog("Ref %s updated: %s => %s", ref, oldHead, newHead) default: // No change. continue } heads[ref] = newHead refsChanged++ emittedTriggers++ // TODO(tandrii): actually look at commits between current and previously // known tips of each ref. // In current (v1) engine, all triggers emitted around the same time will // result in just 1 invocation of each triggered job. Therefore, // passing just HEAD's revision is good enough. // For the same reason, only 1 of the refs will actually be processed if // several refs changed at the same time. ctl.EmitTrigger(c, &internal.Trigger{ Id: fmt.Sprintf("%s/+/%s@%s", cfg.Repo, ref, newHead), Title: newHead, Url: fmt.Sprintf("%s/+/%s", cfg.Repo, newHead), Payload: &internal.Trigger_Gitiles{ Gitiles: &api.GitilesTrigger{Repo: cfg.Repo, Ref: ref, Revision: newHead}, }, }) // Safeguard against too many changes such as the first run after // config change to watch many more refs than before. if emittedTriggers >= maxTriggersPerInvocation { ctl.DebugLog("Emitted %d triggers, postponing the rest", emittedTriggers) break } } if refsChanged == 0
else { ctl.DebugLog("%d refs changed", refsChanged) // Force save to ensure triggers are actually emitted. if err := ctl.Save(c); err != nil { // At this point, triggers have not been sent, so bail now and don't save // the refs' heads newest values. return err } if err := saveState(c, ctl.JobID(), u, heads); err != nil { return err } ctl.DebugLog("Saved %d known refs", len(heads)) } ctl.State().Status = task.StatusSucceeded return nil } // AbortTask is part of Manager interface. func (m TaskManager) AbortTask(c context.Context, ctl task.Controller) error { return nil } // HandleNotification is part of Manager interface. func (m TaskManager) HandleNotification(c context.Context, ctl task.Controller, msg *pubsub.PubsubMessage) error { return errors.New("not implemented") } // HandleTimer is part of Manager interface. func (m TaskManager) HandleTimer(c context.Context, ctl task.Controller, name string, payload []byte) error { return errors.New("not implemented") } // getRefsTips returns tip for each ref being watched. func (m TaskManager) getRefsTips(c context.Context, ctl task.Controller, repoURL string, watched watchedRefs) (map[string]string, error) { host, project, err := gitiles.ParseRepoURL(repoURL) if err != nil { return nil, errors.Annotate(err, "invalid repo URL %q", repoURL).Err() } g, err := m.getGitilesClient(c, ctl, host) if err != nil { return nil, err } // Query gitiles for each namespace in parallel. var wg sync.WaitGroup var lock sync.Mutex errs := []error{} allTips := map[string]string{} // Group all refs by their namespace to reduce # of RPCs. for _, wrs := range watched.namespaces { wg.Add(1) go func(wrs *watchedRefNamespace) { defer wg.Done() res, err := g.Refs(c, &gitilespb.RefsRequest{ Project: project, RefsPath: wrs.namespace, }) lock.Lock() defer lock.Unlock() if err != nil { ctl.DebugLog("failed to fetch %q namespace tips for %q: %q", wrs.namespace, err) errs = append(errs, err) return } for ref, tip := range res.Revisions { if watched.hasRef(ref) { allTips[ref] = tip } } }(wrs) } wg.Wait() if len(errs) > 0 { return nil, errors.NewMultiError(errs...) } return allTips, nil } func (m TaskManager) getGitilesClient(c context.Context, ctl task.Controller, host string) (gitilespb.GitilesClient, error) { if m.mockGitilesClient != nil { // Used for testing only. logging.Infof(c, "using mockGitilesClient") return m.mockGitilesClient, nil } httpClient, err := ctl.GetClient(c, time.Minute, auth.WithScopes(gitiles.OAuthScope)) if err != nil { return nil, err } return gitiles.NewRESTClient(httpClient, host, true) } type watchedRefNamespace struct { namespace string // no trailing "/". allChildren bool // if true, someChildren is ignored. someChildren stringset.Set } func (w watchedRefNamespace) hasSuffix(suffix string) bool { switch { case suffix == "*": panic(fmt.Errorf("watchedRefNamespace membership should only be checked for refs, not ref glob %s", suffix)) case w.allChildren: return true case w.someChildren == nil: return false default: return w.someChildren.Has(suffix) } } func (w *watchedRefNamespace) addSuffix(suffix string) { switch { case w.allChildren: return case suffix == "*": w.allChildren = true w.someChildren = nil return case w.someChildren == nil: w.someChildren = stringset.New(1) } w.someChildren.Add(suffix) } type watchedRefs struct { namespaces map[string]*watchedRefNamespace } func (w *watchedRefs) init(refsConfig []string) { w.namespaces = map[string]*watchedRefNamespace{} for _, ref := range refsConfig { ns, suffix := splitRef(ref) if _, exists := w.namespaces[ns]; !exists { w.namespaces[ns] = &watchedRefNamespace{namespace: ns} } w.namespaces[ns].addSuffix(suffix) } } func (w *watchedRefs) hasRef(ref string) bool { ns, suffix := splitRef(ref) if wrn, exists := w.namespaces[ns]; exists { return wrn.hasSuffix(suffix) } return false } func splitRef(s string) (string, string) { if i := strings.LastIndex(s, "/"); i <= 0 { return s, "" } else { return s[:i], s[i+1:] } }
{ ctl.DebugLog("No changes detected") }
conditional_block
gitiles.go
// Copyright 2016 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gitiles import ( "fmt" "net/url" "sort" "strings" "sync" "time" "github.com/golang/protobuf/proto" "golang.org/x/net/context" "google.golang.org/api/pubsub/v1" "go.chromium.org/luci/common/api/gitiles" "go.chromium.org/luci/common/data/stringset" "go.chromium.org/luci/common/errors" "go.chromium.org/luci/common/logging" gitilespb "go.chromium.org/luci/common/proto/gitiles" "go.chromium.org/luci/config/validation" "go.chromium.org/luci/server/auth" api "go.chromium.org/luci/scheduler/api/scheduler/v1" "go.chromium.org/luci/scheduler/appengine/internal" "go.chromium.org/luci/scheduler/appengine/messages" "go.chromium.org/luci/scheduler/appengine/task" ) // defaultMaxTriggersPerInvocation limits number of triggers emitted per one // invocation. const defaultMaxTriggersPerInvocation = 100 // TaskManager implements task.Manager interface for tasks defined with // GitilesTask proto message. type TaskManager struct { mockGitilesClient gitilespb.GitilesClient // Used for testing only. maxTriggersPerInvocation int // Avoid choking on DS or runtime limits. } // Name is part of Manager interface. func (m TaskManager) Name() string { return "gitiles" } // ProtoMessageType is part of Manager interface. func (m TaskManager) ProtoMessageType() proto.Message { return (*messages.GitilesTask)(nil) } // Traits is part of Manager interface. func (m TaskManager) Traits() task.Traits { return task.Traits{ Multistage: false, // we don't use task.StatusRunning state } } // ValidateProtoMessage is part of Manager interface. func (m TaskManager) ValidateProtoMessage(c *validation.Context, msg proto.Message) { cfg, ok := msg.(*messages.GitilesTask) if !ok { c.Errorf("wrong type %T, expecting *messages.GitilesTask", msg) return } // Validate 'repo' field. c.Enter("repo") if cfg.Repo == "" { c.Errorf("field 'repository' is required") } else { u, err := url.Parse(cfg.Repo) if err != nil { c.Errorf("invalid URL %q: %s", cfg.Repo, err) } else if !u.IsAbs() { c.Errorf("not an absolute url: %q", cfg.Repo) } } c.Exit() c.Enter("refs") for _, ref := range cfg.Refs { if !strings.HasPrefix(ref, "refs/") { c.Errorf("ref must start with 'refs/' not %q", ref) } cnt := strings.Count(ref, "*") if cnt > 1 || (cnt == 1 && !strings.HasSuffix(ref, "/*")) { c.Errorf("only trailing (e.g. refs/blah/*) globs are supported, not %q", ref) } } c.Exit() } // LaunchTask is part of Manager interface. func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error { cfg := ctl.Task().(*messages.GitilesTask) ctl.DebugLog("Repo: %s, Refs: %s", cfg.Repo, cfg.Refs) u, err := url.Parse(cfg.Repo) if err != nil { return err } watchedRefs := watchedRefs{} watchedRefs.init(cfg.GetRefs()) var wg sync.WaitGroup var heads map[string]string var headsErr error wg.Add(1) go func() { defer wg.Done() heads, headsErr = loadState(c, ctl.JobID(), u) }() var refs map[string]string var refsErr error wg.Add(1) go func() { defer wg.Done() refs, refsErr = m.getRefsTips(c, ctl, cfg.Repo, watchedRefs) }() wg.Wait() if headsErr != nil { ctl.DebugLog("Failed to fetch heads - %s", headsErr) return fmt.Errorf("failed to fetch heads: %v", headsErr) } if refsErr != nil { ctl.DebugLog("Failed to fetch refs - %s", refsErr) return fmt.Errorf("failed to fetch refs: %v", refsErr) } refsChanged := 0 // Delete all previously known refs which are either no longer watched or no // longer exist in repo. for ref := range heads { switch { case !watchedRefs.hasRef(ref): ctl.DebugLog("Ref %s is no longer watched", ref) delete(heads, ref) refsChanged++ case refs[ref] == "": ctl.DebugLog("Ref %s deleted", ref) delete(heads, ref) refsChanged++ } } // For determinism, sort keys of current refs. sortedRefs := make([]string, 0, len(refs)) for ref := range refs { sortedRefs = append(sortedRefs, ref) } sort.Strings(sortedRefs) emittedTriggers := 0 maxTriggersPerInvocation := m.maxTriggersPerInvocation if maxTriggersPerInvocation == 0 { maxTriggersPerInvocation = defaultMaxTriggersPerInvocation } // Note, that current `refs` contain only watched refs (see getRefsTips). for _, ref := range sortedRefs { newHead := refs[ref] oldHead, existed := heads[ref] switch { case !existed: ctl.DebugLog("Ref %s is new: %s", ref, newHead) case oldHead != newHead: ctl.DebugLog("Ref %s updated: %s => %s", ref, oldHead, newHead) default: // No change. continue } heads[ref] = newHead refsChanged++ emittedTriggers++ // TODO(tandrii): actually look at commits between current and previously // known tips of each ref. // In current (v1) engine, all triggers emitted around the same time will // result in just 1 invocation of each triggered job. Therefore, // passing just HEAD's revision is good enough. // For the same reason, only 1 of the refs will actually be processed if // several refs changed at the same time. ctl.EmitTrigger(c, &internal.Trigger{ Id: fmt.Sprintf("%s/+/%s@%s", cfg.Repo, ref, newHead), Title: newHead, Url: fmt.Sprintf("%s/+/%s", cfg.Repo, newHead), Payload: &internal.Trigger_Gitiles{ Gitiles: &api.GitilesTrigger{Repo: cfg.Repo, Ref: ref, Revision: newHead}, }, }) // Safeguard against too many changes such as the first run after // config change to watch many more refs than before. if emittedTriggers >= maxTriggersPerInvocation { ctl.DebugLog("Emitted %d triggers, postponing the rest", emittedTriggers) break } } if refsChanged == 0 { ctl.DebugLog("No changes detected") } else { ctl.DebugLog("%d refs changed", refsChanged) // Force save to ensure triggers are actually emitted. if err := ctl.Save(c); err != nil { // At this point, triggers have not been sent, so bail now and don't save // the refs' heads newest values. return err } if err := saveState(c, ctl.JobID(), u, heads); err != nil { return err } ctl.DebugLog("Saved %d known refs", len(heads)) } ctl.State().Status = task.StatusSucceeded return nil } // AbortTask is part of Manager interface. func (m TaskManager)
(c context.Context, ctl task.Controller) error { return nil } // HandleNotification is part of Manager interface. func (m TaskManager) HandleNotification(c context.Context, ctl task.Controller, msg *pubsub.PubsubMessage) error { return errors.New("not implemented") } // HandleTimer is part of Manager interface. func (m TaskManager) HandleTimer(c context.Context, ctl task.Controller, name string, payload []byte) error { return errors.New("not implemented") } // getRefsTips returns tip for each ref being watched. func (m TaskManager) getRefsTips(c context.Context, ctl task.Controller, repoURL string, watched watchedRefs) (map[string]string, error) { host, project, err := gitiles.ParseRepoURL(repoURL) if err != nil { return nil, errors.Annotate(err, "invalid repo URL %q", repoURL).Err() } g, err := m.getGitilesClient(c, ctl, host) if err != nil { return nil, err } // Query gitiles for each namespace in parallel. var wg sync.WaitGroup var lock sync.Mutex errs := []error{} allTips := map[string]string{} // Group all refs by their namespace to reduce # of RPCs. for _, wrs := range watched.namespaces { wg.Add(1) go func(wrs *watchedRefNamespace) { defer wg.Done() res, err := g.Refs(c, &gitilespb.RefsRequest{ Project: project, RefsPath: wrs.namespace, }) lock.Lock() defer lock.Unlock() if err != nil { ctl.DebugLog("failed to fetch %q namespace tips for %q: %q", wrs.namespace, err) errs = append(errs, err) return } for ref, tip := range res.Revisions { if watched.hasRef(ref) { allTips[ref] = tip } } }(wrs) } wg.Wait() if len(errs) > 0 { return nil, errors.NewMultiError(errs...) } return allTips, nil } func (m TaskManager) getGitilesClient(c context.Context, ctl task.Controller, host string) (gitilespb.GitilesClient, error) { if m.mockGitilesClient != nil { // Used for testing only. logging.Infof(c, "using mockGitilesClient") return m.mockGitilesClient, nil } httpClient, err := ctl.GetClient(c, time.Minute, auth.WithScopes(gitiles.OAuthScope)) if err != nil { return nil, err } return gitiles.NewRESTClient(httpClient, host, true) } type watchedRefNamespace struct { namespace string // no trailing "/". allChildren bool // if true, someChildren is ignored. someChildren stringset.Set } func (w watchedRefNamespace) hasSuffix(suffix string) bool { switch { case suffix == "*": panic(fmt.Errorf("watchedRefNamespace membership should only be checked for refs, not ref glob %s", suffix)) case w.allChildren: return true case w.someChildren == nil: return false default: return w.someChildren.Has(suffix) } } func (w *watchedRefNamespace) addSuffix(suffix string) { switch { case w.allChildren: return case suffix == "*": w.allChildren = true w.someChildren = nil return case w.someChildren == nil: w.someChildren = stringset.New(1) } w.someChildren.Add(suffix) } type watchedRefs struct { namespaces map[string]*watchedRefNamespace } func (w *watchedRefs) init(refsConfig []string) { w.namespaces = map[string]*watchedRefNamespace{} for _, ref := range refsConfig { ns, suffix := splitRef(ref) if _, exists := w.namespaces[ns]; !exists { w.namespaces[ns] = &watchedRefNamespace{namespace: ns} } w.namespaces[ns].addSuffix(suffix) } } func (w *watchedRefs) hasRef(ref string) bool { ns, suffix := splitRef(ref) if wrn, exists := w.namespaces[ns]; exists { return wrn.hasSuffix(suffix) } return false } func splitRef(s string) (string, string) { if i := strings.LastIndex(s, "/"); i <= 0 { return s, "" } else { return s[:i], s[i+1:] } }
AbortTask
identifier_name
gitiles.go
// Copyright 2016 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gitiles import ( "fmt" "net/url" "sort" "strings" "sync" "time" "github.com/golang/protobuf/proto" "golang.org/x/net/context" "google.golang.org/api/pubsub/v1" "go.chromium.org/luci/common/api/gitiles" "go.chromium.org/luci/common/data/stringset" "go.chromium.org/luci/common/errors" "go.chromium.org/luci/common/logging" gitilespb "go.chromium.org/luci/common/proto/gitiles" "go.chromium.org/luci/config/validation" "go.chromium.org/luci/server/auth" api "go.chromium.org/luci/scheduler/api/scheduler/v1" "go.chromium.org/luci/scheduler/appengine/internal" "go.chromium.org/luci/scheduler/appengine/messages" "go.chromium.org/luci/scheduler/appengine/task" ) // defaultMaxTriggersPerInvocation limits number of triggers emitted per one // invocation.
mockGitilesClient gitilespb.GitilesClient // Used for testing only. maxTriggersPerInvocation int // Avoid choking on DS or runtime limits. } // Name is part of Manager interface. func (m TaskManager) Name() string { return "gitiles" } // ProtoMessageType is part of Manager interface. func (m TaskManager) ProtoMessageType() proto.Message { return (*messages.GitilesTask)(nil) } // Traits is part of Manager interface. func (m TaskManager) Traits() task.Traits { return task.Traits{ Multistage: false, // we don't use task.StatusRunning state } } // ValidateProtoMessage is part of Manager interface. func (m TaskManager) ValidateProtoMessage(c *validation.Context, msg proto.Message) { cfg, ok := msg.(*messages.GitilesTask) if !ok { c.Errorf("wrong type %T, expecting *messages.GitilesTask", msg) return } // Validate 'repo' field. c.Enter("repo") if cfg.Repo == "" { c.Errorf("field 'repository' is required") } else { u, err := url.Parse(cfg.Repo) if err != nil { c.Errorf("invalid URL %q: %s", cfg.Repo, err) } else if !u.IsAbs() { c.Errorf("not an absolute url: %q", cfg.Repo) } } c.Exit() c.Enter("refs") for _, ref := range cfg.Refs { if !strings.HasPrefix(ref, "refs/") { c.Errorf("ref must start with 'refs/' not %q", ref) } cnt := strings.Count(ref, "*") if cnt > 1 || (cnt == 1 && !strings.HasSuffix(ref, "/*")) { c.Errorf("only trailing (e.g. refs/blah/*) globs are supported, not %q", ref) } } c.Exit() } // LaunchTask is part of Manager interface. func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error { cfg := ctl.Task().(*messages.GitilesTask) ctl.DebugLog("Repo: %s, Refs: %s", cfg.Repo, cfg.Refs) u, err := url.Parse(cfg.Repo) if err != nil { return err } watchedRefs := watchedRefs{} watchedRefs.init(cfg.GetRefs()) var wg sync.WaitGroup var heads map[string]string var headsErr error wg.Add(1) go func() { defer wg.Done() heads, headsErr = loadState(c, ctl.JobID(), u) }() var refs map[string]string var refsErr error wg.Add(1) go func() { defer wg.Done() refs, refsErr = m.getRefsTips(c, ctl, cfg.Repo, watchedRefs) }() wg.Wait() if headsErr != nil { ctl.DebugLog("Failed to fetch heads - %s", headsErr) return fmt.Errorf("failed to fetch heads: %v", headsErr) } if refsErr != nil { ctl.DebugLog("Failed to fetch refs - %s", refsErr) return fmt.Errorf("failed to fetch refs: %v", refsErr) } refsChanged := 0 // Delete all previously known refs which are either no longer watched or no // longer exist in repo. for ref := range heads { switch { case !watchedRefs.hasRef(ref): ctl.DebugLog("Ref %s is no longer watched", ref) delete(heads, ref) refsChanged++ case refs[ref] == "": ctl.DebugLog("Ref %s deleted", ref) delete(heads, ref) refsChanged++ } } // For determinism, sort keys of current refs. sortedRefs := make([]string, 0, len(refs)) for ref := range refs { sortedRefs = append(sortedRefs, ref) } sort.Strings(sortedRefs) emittedTriggers := 0 maxTriggersPerInvocation := m.maxTriggersPerInvocation if maxTriggersPerInvocation == 0 { maxTriggersPerInvocation = defaultMaxTriggersPerInvocation } // Note, that current `refs` contain only watched refs (see getRefsTips). for _, ref := range sortedRefs { newHead := refs[ref] oldHead, existed := heads[ref] switch { case !existed: ctl.DebugLog("Ref %s is new: %s", ref, newHead) case oldHead != newHead: ctl.DebugLog("Ref %s updated: %s => %s", ref, oldHead, newHead) default: // No change. continue } heads[ref] = newHead refsChanged++ emittedTriggers++ // TODO(tandrii): actually look at commits between current and previously // known tips of each ref. // In current (v1) engine, all triggers emitted around the same time will // result in just 1 invocation of each triggered job. Therefore, // passing just HEAD's revision is good enough. // For the same reason, only 1 of the refs will actually be processed if // several refs changed at the same time. ctl.EmitTrigger(c, &internal.Trigger{ Id: fmt.Sprintf("%s/+/%s@%s", cfg.Repo, ref, newHead), Title: newHead, Url: fmt.Sprintf("%s/+/%s", cfg.Repo, newHead), Payload: &internal.Trigger_Gitiles{ Gitiles: &api.GitilesTrigger{Repo: cfg.Repo, Ref: ref, Revision: newHead}, }, }) // Safeguard against too many changes such as the first run after // config change to watch many more refs than before. if emittedTriggers >= maxTriggersPerInvocation { ctl.DebugLog("Emitted %d triggers, postponing the rest", emittedTriggers) break } } if refsChanged == 0 { ctl.DebugLog("No changes detected") } else { ctl.DebugLog("%d refs changed", refsChanged) // Force save to ensure triggers are actually emitted. if err := ctl.Save(c); err != nil { // At this point, triggers have not been sent, so bail now and don't save // the refs' heads newest values. return err } if err := saveState(c, ctl.JobID(), u, heads); err != nil { return err } ctl.DebugLog("Saved %d known refs", len(heads)) } ctl.State().Status = task.StatusSucceeded return nil } // AbortTask is part of Manager interface. func (m TaskManager) AbortTask(c context.Context, ctl task.Controller) error { return nil } // HandleNotification is part of Manager interface. func (m TaskManager) HandleNotification(c context.Context, ctl task.Controller, msg *pubsub.PubsubMessage) error { return errors.New("not implemented") } // HandleTimer is part of Manager interface. func (m TaskManager) HandleTimer(c context.Context, ctl task.Controller, name string, payload []byte) error { return errors.New("not implemented") } // getRefsTips returns tip for each ref being watched. func (m TaskManager) getRefsTips(c context.Context, ctl task.Controller, repoURL string, watched watchedRefs) (map[string]string, error) { host, project, err := gitiles.ParseRepoURL(repoURL) if err != nil { return nil, errors.Annotate(err, "invalid repo URL %q", repoURL).Err() } g, err := m.getGitilesClient(c, ctl, host) if err != nil { return nil, err } // Query gitiles for each namespace in parallel. var wg sync.WaitGroup var lock sync.Mutex errs := []error{} allTips := map[string]string{} // Group all refs by their namespace to reduce # of RPCs. for _, wrs := range watched.namespaces { wg.Add(1) go func(wrs *watchedRefNamespace) { defer wg.Done() res, err := g.Refs(c, &gitilespb.RefsRequest{ Project: project, RefsPath: wrs.namespace, }) lock.Lock() defer lock.Unlock() if err != nil { ctl.DebugLog("failed to fetch %q namespace tips for %q: %q", wrs.namespace, err) errs = append(errs, err) return } for ref, tip := range res.Revisions { if watched.hasRef(ref) { allTips[ref] = tip } } }(wrs) } wg.Wait() if len(errs) > 0 { return nil, errors.NewMultiError(errs...) } return allTips, nil } func (m TaskManager) getGitilesClient(c context.Context, ctl task.Controller, host string) (gitilespb.GitilesClient, error) { if m.mockGitilesClient != nil { // Used for testing only. logging.Infof(c, "using mockGitilesClient") return m.mockGitilesClient, nil } httpClient, err := ctl.GetClient(c, time.Minute, auth.WithScopes(gitiles.OAuthScope)) if err != nil { return nil, err } return gitiles.NewRESTClient(httpClient, host, true) } type watchedRefNamespace struct { namespace string // no trailing "/". allChildren bool // if true, someChildren is ignored. someChildren stringset.Set } func (w watchedRefNamespace) hasSuffix(suffix string) bool { switch { case suffix == "*": panic(fmt.Errorf("watchedRefNamespace membership should only be checked for refs, not ref glob %s", suffix)) case w.allChildren: return true case w.someChildren == nil: return false default: return w.someChildren.Has(suffix) } } func (w *watchedRefNamespace) addSuffix(suffix string) { switch { case w.allChildren: return case suffix == "*": w.allChildren = true w.someChildren = nil return case w.someChildren == nil: w.someChildren = stringset.New(1) } w.someChildren.Add(suffix) } type watchedRefs struct { namespaces map[string]*watchedRefNamespace } func (w *watchedRefs) init(refsConfig []string) { w.namespaces = map[string]*watchedRefNamespace{} for _, ref := range refsConfig { ns, suffix := splitRef(ref) if _, exists := w.namespaces[ns]; !exists { w.namespaces[ns] = &watchedRefNamespace{namespace: ns} } w.namespaces[ns].addSuffix(suffix) } } func (w *watchedRefs) hasRef(ref string) bool { ns, suffix := splitRef(ref) if wrn, exists := w.namespaces[ns]; exists { return wrn.hasSuffix(suffix) } return false } func splitRef(s string) (string, string) { if i := strings.LastIndex(s, "/"); i <= 0 { return s, "" } else { return s[:i], s[i+1:] } }
const defaultMaxTriggersPerInvocation = 100 // TaskManager implements task.Manager interface for tasks defined with // GitilesTask proto message. type TaskManager struct {
random_line_split
gitiles.go
// Copyright 2016 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gitiles import ( "fmt" "net/url" "sort" "strings" "sync" "time" "github.com/golang/protobuf/proto" "golang.org/x/net/context" "google.golang.org/api/pubsub/v1" "go.chromium.org/luci/common/api/gitiles" "go.chromium.org/luci/common/data/stringset" "go.chromium.org/luci/common/errors" "go.chromium.org/luci/common/logging" gitilespb "go.chromium.org/luci/common/proto/gitiles" "go.chromium.org/luci/config/validation" "go.chromium.org/luci/server/auth" api "go.chromium.org/luci/scheduler/api/scheduler/v1" "go.chromium.org/luci/scheduler/appengine/internal" "go.chromium.org/luci/scheduler/appengine/messages" "go.chromium.org/luci/scheduler/appengine/task" ) // defaultMaxTriggersPerInvocation limits number of triggers emitted per one // invocation. const defaultMaxTriggersPerInvocation = 100 // TaskManager implements task.Manager interface for tasks defined with // GitilesTask proto message. type TaskManager struct { mockGitilesClient gitilespb.GitilesClient // Used for testing only. maxTriggersPerInvocation int // Avoid choking on DS or runtime limits. } // Name is part of Manager interface. func (m TaskManager) Name() string { return "gitiles" } // ProtoMessageType is part of Manager interface. func (m TaskManager) ProtoMessageType() proto.Message { return (*messages.GitilesTask)(nil) } // Traits is part of Manager interface. func (m TaskManager) Traits() task.Traits { return task.Traits{ Multistage: false, // we don't use task.StatusRunning state } } // ValidateProtoMessage is part of Manager interface. func (m TaskManager) ValidateProtoMessage(c *validation.Context, msg proto.Message) { cfg, ok := msg.(*messages.GitilesTask) if !ok { c.Errorf("wrong type %T, expecting *messages.GitilesTask", msg) return } // Validate 'repo' field. c.Enter("repo") if cfg.Repo == "" { c.Errorf("field 'repository' is required") } else { u, err := url.Parse(cfg.Repo) if err != nil { c.Errorf("invalid URL %q: %s", cfg.Repo, err) } else if !u.IsAbs() { c.Errorf("not an absolute url: %q", cfg.Repo) } } c.Exit() c.Enter("refs") for _, ref := range cfg.Refs { if !strings.HasPrefix(ref, "refs/") { c.Errorf("ref must start with 'refs/' not %q", ref) } cnt := strings.Count(ref, "*") if cnt > 1 || (cnt == 1 && !strings.HasSuffix(ref, "/*")) { c.Errorf("only trailing (e.g. refs/blah/*) globs are supported, not %q", ref) } } c.Exit() } // LaunchTask is part of Manager interface. func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error { cfg := ctl.Task().(*messages.GitilesTask) ctl.DebugLog("Repo: %s, Refs: %s", cfg.Repo, cfg.Refs) u, err := url.Parse(cfg.Repo) if err != nil { return err } watchedRefs := watchedRefs{} watchedRefs.init(cfg.GetRefs()) var wg sync.WaitGroup var heads map[string]string var headsErr error wg.Add(1) go func() { defer wg.Done() heads, headsErr = loadState(c, ctl.JobID(), u) }() var refs map[string]string var refsErr error wg.Add(1) go func() { defer wg.Done() refs, refsErr = m.getRefsTips(c, ctl, cfg.Repo, watchedRefs) }() wg.Wait() if headsErr != nil { ctl.DebugLog("Failed to fetch heads - %s", headsErr) return fmt.Errorf("failed to fetch heads: %v", headsErr) } if refsErr != nil { ctl.DebugLog("Failed to fetch refs - %s", refsErr) return fmt.Errorf("failed to fetch refs: %v", refsErr) } refsChanged := 0 // Delete all previously known refs which are either no longer watched or no // longer exist in repo. for ref := range heads { switch { case !watchedRefs.hasRef(ref): ctl.DebugLog("Ref %s is no longer watched", ref) delete(heads, ref) refsChanged++ case refs[ref] == "": ctl.DebugLog("Ref %s deleted", ref) delete(heads, ref) refsChanged++ } } // For determinism, sort keys of current refs. sortedRefs := make([]string, 0, len(refs)) for ref := range refs { sortedRefs = append(sortedRefs, ref) } sort.Strings(sortedRefs) emittedTriggers := 0 maxTriggersPerInvocation := m.maxTriggersPerInvocation if maxTriggersPerInvocation == 0 { maxTriggersPerInvocation = defaultMaxTriggersPerInvocation } // Note, that current `refs` contain only watched refs (see getRefsTips). for _, ref := range sortedRefs { newHead := refs[ref] oldHead, existed := heads[ref] switch { case !existed: ctl.DebugLog("Ref %s is new: %s", ref, newHead) case oldHead != newHead: ctl.DebugLog("Ref %s updated: %s => %s", ref, oldHead, newHead) default: // No change. continue } heads[ref] = newHead refsChanged++ emittedTriggers++ // TODO(tandrii): actually look at commits between current and previously // known tips of each ref. // In current (v1) engine, all triggers emitted around the same time will // result in just 1 invocation of each triggered job. Therefore, // passing just HEAD's revision is good enough. // For the same reason, only 1 of the refs will actually be processed if // several refs changed at the same time. ctl.EmitTrigger(c, &internal.Trigger{ Id: fmt.Sprintf("%s/+/%s@%s", cfg.Repo, ref, newHead), Title: newHead, Url: fmt.Sprintf("%s/+/%s", cfg.Repo, newHead), Payload: &internal.Trigger_Gitiles{ Gitiles: &api.GitilesTrigger{Repo: cfg.Repo, Ref: ref, Revision: newHead}, }, }) // Safeguard against too many changes such as the first run after // config change to watch many more refs than before. if emittedTriggers >= maxTriggersPerInvocation { ctl.DebugLog("Emitted %d triggers, postponing the rest", emittedTriggers) break } } if refsChanged == 0 { ctl.DebugLog("No changes detected") } else { ctl.DebugLog("%d refs changed", refsChanged) // Force save to ensure triggers are actually emitted. if err := ctl.Save(c); err != nil { // At this point, triggers have not been sent, so bail now and don't save // the refs' heads newest values. return err } if err := saveState(c, ctl.JobID(), u, heads); err != nil { return err } ctl.DebugLog("Saved %d known refs", len(heads)) } ctl.State().Status = task.StatusSucceeded return nil } // AbortTask is part of Manager interface. func (m TaskManager) AbortTask(c context.Context, ctl task.Controller) error { return nil } // HandleNotification is part of Manager interface. func (m TaskManager) HandleNotification(c context.Context, ctl task.Controller, msg *pubsub.PubsubMessage) error
// HandleTimer is part of Manager interface. func (m TaskManager) HandleTimer(c context.Context, ctl task.Controller, name string, payload []byte) error { return errors.New("not implemented") } // getRefsTips returns tip for each ref being watched. func (m TaskManager) getRefsTips(c context.Context, ctl task.Controller, repoURL string, watched watchedRefs) (map[string]string, error) { host, project, err := gitiles.ParseRepoURL(repoURL) if err != nil { return nil, errors.Annotate(err, "invalid repo URL %q", repoURL).Err() } g, err := m.getGitilesClient(c, ctl, host) if err != nil { return nil, err } // Query gitiles for each namespace in parallel. var wg sync.WaitGroup var lock sync.Mutex errs := []error{} allTips := map[string]string{} // Group all refs by their namespace to reduce # of RPCs. for _, wrs := range watched.namespaces { wg.Add(1) go func(wrs *watchedRefNamespace) { defer wg.Done() res, err := g.Refs(c, &gitilespb.RefsRequest{ Project: project, RefsPath: wrs.namespace, }) lock.Lock() defer lock.Unlock() if err != nil { ctl.DebugLog("failed to fetch %q namespace tips for %q: %q", wrs.namespace, err) errs = append(errs, err) return } for ref, tip := range res.Revisions { if watched.hasRef(ref) { allTips[ref] = tip } } }(wrs) } wg.Wait() if len(errs) > 0 { return nil, errors.NewMultiError(errs...) } return allTips, nil } func (m TaskManager) getGitilesClient(c context.Context, ctl task.Controller, host string) (gitilespb.GitilesClient, error) { if m.mockGitilesClient != nil { // Used for testing only. logging.Infof(c, "using mockGitilesClient") return m.mockGitilesClient, nil } httpClient, err := ctl.GetClient(c, time.Minute, auth.WithScopes(gitiles.OAuthScope)) if err != nil { return nil, err } return gitiles.NewRESTClient(httpClient, host, true) } type watchedRefNamespace struct { namespace string // no trailing "/". allChildren bool // if true, someChildren is ignored. someChildren stringset.Set } func (w watchedRefNamespace) hasSuffix(suffix string) bool { switch { case suffix == "*": panic(fmt.Errorf("watchedRefNamespace membership should only be checked for refs, not ref glob %s", suffix)) case w.allChildren: return true case w.someChildren == nil: return false default: return w.someChildren.Has(suffix) } } func (w *watchedRefNamespace) addSuffix(suffix string) { switch { case w.allChildren: return case suffix == "*": w.allChildren = true w.someChildren = nil return case w.someChildren == nil: w.someChildren = stringset.New(1) } w.someChildren.Add(suffix) } type watchedRefs struct { namespaces map[string]*watchedRefNamespace } func (w *watchedRefs) init(refsConfig []string) { w.namespaces = map[string]*watchedRefNamespace{} for _, ref := range refsConfig { ns, suffix := splitRef(ref) if _, exists := w.namespaces[ns]; !exists { w.namespaces[ns] = &watchedRefNamespace{namespace: ns} } w.namespaces[ns].addSuffix(suffix) } } func (w *watchedRefs) hasRef(ref string) bool { ns, suffix := splitRef(ref) if wrn, exists := w.namespaces[ns]; exists { return wrn.hasSuffix(suffix) } return false } func splitRef(s string) (string, string) { if i := strings.LastIndex(s, "/"); i <= 0 { return s, "" } else { return s[:i], s[i+1:] } }
{ return errors.New("not implemented") }
identifier_body
settings.go
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and package pscompat import ( "log" "time" "cloud.google.com/go/internal/optional" "cloud.google.com/go/pubsub" "cloud.google.com/go/pubsublite/internal/wire" pb "cloud.google.com/go/pubsublite/apiv1/pubsublitepb" ) const ( // MaxPublishRequestCount is the maximum number of messages that can be // batched in a single publish request. MaxPublishRequestCount = wire.MaxPublishRequestCount // MaxPublishRequestBytes is the maximum allowed serialized size of a single // publish request (containing a batch of messages) in bytes. MaxPublishRequestBytes = wire.MaxPublishRequestBytes ) // KeyExtractorFunc is a function that extracts an ordering key from a Message. type KeyExtractorFunc func(*pubsub.Message) []byte // PublishMessageTransformerFunc transforms a pubsub.Message to a Pub/Sub Lite // PubSubMessage API proto. If this returns an error, the pubsub.PublishResult // will be errored and the PublisherClient will consider this a fatal error and // terminate. type PublishMessageTransformerFunc func(*pubsub.Message, *pb.PubSubMessage) error // PublishSettings configure the PublisherClient. Batching settings // (DelayThreshold, CountThreshold, ByteThreshold, BufferedByteLimit) apply per // partition. // // A zero PublishSettings will result in values equivalent to // DefaultPublishSettings. type PublishSettings struct { // Publish a non-empty batch after this delay has passed. If DelayThreshold is // 0, it will be treated as DefaultPublishSettings.DelayThreshold. Otherwise // must be > 0. DelayThreshold time.Duration // Publish a batch when it has this many messages. The maximum is // MaxPublishRequestCount. If CountThreshold is 0, it will be treated as // DefaultPublishSettings.CountThreshold. Otherwise must be > 0. CountThreshold int // Publish a batch when its size in bytes reaches this value. The maximum is // MaxPublishRequestBytes. If ByteThreshold is 0, it will be treated as // DefaultPublishSettings.ByteThreshold. Otherwise must be > 0. ByteThreshold int // The maximum time that the client will attempt to open a publish stream // to the server. If Timeout is 0, it will be treated as // DefaultPublishSettings.Timeout, otherwise will be clamped to 2 minutes. In // the future, setting Timeout to less than 2 minutes will result in an error. // // If your application has a low tolerance to backend unavailability, set // Timeout to a lower duration to detect and handle. When the timeout is // exceeded, the PublisherClient will terminate with ErrBackendUnavailable and // details of the last error that occurred while trying to reconnect to // backends. Note that if the timeout duration is long, ErrOverflow may occur // first. // // If no failover operations need to be performed by the application, it is // recommended to just use the default timeout value to avoid the // PublisherClient terminating during short periods of backend unavailability. Timeout time.Duration // The maximum number of bytes that the publisher will keep in memory before // returning ErrOverflow. If BufferedByteLimit is 0, it will be treated as // DefaultPublishSettings.BufferedByteLimit. Otherwise must be > 0. // // Note that this setting applies per partition. If BufferedByteLimit is being // used to bound memory usage, keep in mind the number of partitions in the // topic. // // Note that Pub/Sub Lite topics are provisioned a publishing throughput // capacity, per partition, shared by all publisher clients. Setting a large // buffer size can mitigate transient publish spikes. However, consistently // attempting to publish messages at a much higher rate than the publishing // throughput capacity can cause the buffers to overflow. For more // information, see https://cloud.google.com/pubsub/lite/docs/topics. BufferedByteLimit int // Whether idempotence is enabled, where the server will ensure that unique // messages within a single publisher session are stored only once. Default // true. EnableIdempotence optional.Bool // Optional custom function that extracts an ordering key from a Message. The // default implementation extracts the key from Message.OrderingKey. KeyExtractor KeyExtractorFunc // Optional custom function that transforms a pubsub.Message to a // PubSubMessage API proto. MessageTransformer PublishMessageTransformerFunc // The polling interval to watch for topic partition count updates. // Currently internal only and overridden in tests. configPollPeriod time.Duration } // DefaultPublishSettings holds the default values for PublishSettings. var DefaultPublishSettings = PublishSettings{ DelayThreshold: 10 * time.Millisecond, CountThreshold: 100, ByteThreshold: 1e6, Timeout: 7 * 24 * time.Hour, BufferedByteLimit: 1e10, EnableIdempotence: true, } func (s *PublishSettings) toWireSettings() wire.PublishSettings { wireSettings := wire.PublishSettings{ DelayThreshold: DefaultPublishSettings.DelayThreshold, CountThreshold: DefaultPublishSettings.CountThreshold, ByteThreshold: DefaultPublishSettings.ByteThreshold, Timeout: DefaultPublishSettings.Timeout, BufferedByteLimit: DefaultPublishSettings.BufferedByteLimit, EnableIdempotence: wire.DefaultPublishSettings.EnableIdempotence, ConfigPollPeriod: wire.DefaultPublishSettings.ConfigPollPeriod, Framework: wire.FrameworkCloudPubSubShim, } // Negative values preserved, but will fail validation in wire package. if s.DelayThreshold != 0 { wireSettings.DelayThreshold = s.DelayThreshold } if s.CountThreshold != 0 { wireSettings.CountThreshold = s.CountThreshold } if s.ByteThreshold != 0 { wireSettings.ByteThreshold = s.ByteThreshold } if s.Timeout != 0 { if s.Timeout >= wire.MinTimeout { wireSettings.Timeout = s.Timeout } else { log.Println("WARNING: PublishSettings.Timeout has been overridden to 2 minutes (the minimum value). A lower value will cause an error in the future.") wireSettings.Timeout = wire.MinTimeout } } if s.BufferedByteLimit != 0 { wireSettings.BufferedByteLimit = s.BufferedByteLimit } if s.EnableIdempotence != nil { wireSettings.EnableIdempotence = optional.ToBool(s.EnableIdempotence) } if s.configPollPeriod != 0 { wireSettings.ConfigPollPeriod = s.configPollPeriod } return wireSettings } // NackHandler is invoked when pubsub.Message.Nack() is called. Pub/Sub Lite // does not have a concept of 'nack'. If the nack handler implementation returns // nil, the message is acknowledged. If an error is returned, the // SubscriberClient will consider this a fatal error and terminate. // // In Pub/Sub Lite, only a single subscriber for a given subscription is // connected to any partition at a time, and there is no other client that may // be able to handle messages. type NackHandler func(*pubsub.Message) error // ReceiveMessageTransformerFunc transforms a Pub/Sub Lite SequencedMessage API // proto to a pubsub.Message. The implementation must not set pubsub.Message.ID. // // If this returns an error, the SubscriberClient will consider this a fatal // error and terminate. type ReceiveMessageTransformerFunc func(*pb.SequencedMessage, *pubsub.Message) error // ReassignmentHandlerFunc is called any time a new partition assignment is // received from the server. It will be called with both the previous and new // partition numbers as decided by the server. Both slices of partition numbers // are sorted in ascending order. // // When this handler is called, partitions that are being assigned away are // stopping and new partitions are starting. Acks and nacks for messages from // partitions that are being assigned away will have no effect, but message // deliveries may still be in flight. // // The client library will not acknowledge the assignment until this handler // returns. The server will not assign any of the partitions in // `previousPartitions` to another client unless the assignment is acknowledged, // or a client takes too long to acknowledge (currently 30 seconds from the time // the assignment is sent from server's point of view). // // Because of the above, as long as reassignment handling is processed quickly, // it can be used to abort outstanding operations on partitions which are being // assigned away from this client. // // If this handler returns an error, the SubscriberClient will consider this a // fatal error and terminate. type ReassignmentHandlerFunc func(previousPartitions, nextPartitions []int) error // ReceiveSettings configure the SubscriberClient. Flow control settings // (MaxOutstandingMessages, MaxOutstandingBytes) apply per partition. // // A zero ReceiveSettings will result in values equivalent to // DefaultReceiveSettings. type ReceiveSettings struct { // MaxOutstandingMessages is the maximum number of unacknowledged messages. // If MaxOutstandingMessages is 0, it will be treated as // DefaultReceiveSettings.MaxOutstandingMessages. Otherwise must be > 0. MaxOutstandingMessages int // MaxOutstandingBytes is the maximum size (in quota bytes) of unacknowledged // messages. If MaxOutstandingBytes is 0, it will be treated as // DefaultReceiveSettings.MaxOutstandingBytes. Otherwise must be > 0. // // Note that this setting applies per partition. If MaxOutstandingBytes is // being used to bound memory usage, keep in mind the number of partitions in // the associated topic. MaxOutstandingBytes int // The maximum time that the client will attempt to open a subscribe stream // to the server. If Timeout is 0, it will be treated as // DefaultReceiveSettings.Timeout, otherwise will be clamped to 2 minutes. In // the future, setting Timeout to less than 2 minutes will result in an error. // // If your application has a low tolerance to backend unavailability, set // Timeout to a lower duration to detect and handle. When the timeout is // exceeded, the SubscriberClient will terminate with ErrBackendUnavailable // and details of the last error that occurred while trying to reconnect to // backends. // // If no failover operations need to be performed by the application, it is // recommended to just use the default timeout value to avoid the // SubscriberClient terminating during short periods of backend // unavailability. Timeout time.Duration // The topic partition numbers (zero-indexed) to receive messages from. // Values must be less than the number of partitions for the topic. If not // specified, the SubscriberClient will use the partition assignment service // to determine which partitions it should connect to. Partitions []int // Optional custom function to handle pubsub.Message.Nack() calls. If not set, // the default behavior is to terminate the SubscriberClient. NackHandler NackHandler // Optional custom function that transforms a SequencedMessage API proto to a // pubsub.Message. MessageTransformer ReceiveMessageTransformerFunc // Optional custom function that is called when a new partition assignment has // been delivered to the client. ReassignmentHandler ReassignmentHandlerFunc } // DefaultReceiveSettings holds the default values for ReceiveSettings. var DefaultReceiveSettings = ReceiveSettings{ MaxOutstandingMessages: 1000, MaxOutstandingBytes: 1e9, Timeout: 7 * 24 * time.Hour, } func (s *ReceiveSettings) toWireSettings() wire.ReceiveSettings
{ wireSettings := wire.ReceiveSettings{ MaxOutstandingMessages: DefaultReceiveSettings.MaxOutstandingMessages, MaxOutstandingBytes: DefaultReceiveSettings.MaxOutstandingBytes, Timeout: DefaultReceiveSettings.Timeout, Partitions: s.Partitions, Framework: wire.FrameworkCloudPubSubShim, } // Negative values preserved, but will fail validation in wire package. if s.MaxOutstandingMessages != 0 { wireSettings.MaxOutstandingMessages = s.MaxOutstandingMessages } if s.MaxOutstandingBytes != 0 { wireSettings.MaxOutstandingBytes = s.MaxOutstandingBytes } if s.Timeout != 0 { if s.Timeout >= wire.MinTimeout { wireSettings.Timeout = s.Timeout } else { log.Println("WARNING: ReceiveSettings.Timeout has been overridden to 2 minutes (the minimum value). A lower value will cause an error in the future.") wireSettings.Timeout = wire.MinTimeout } } return wireSettings }
identifier_body
settings.go
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and package pscompat import ( "log" "time" "cloud.google.com/go/internal/optional" "cloud.google.com/go/pubsub" "cloud.google.com/go/pubsublite/internal/wire" pb "cloud.google.com/go/pubsublite/apiv1/pubsublitepb" ) const ( // MaxPublishRequestCount is the maximum number of messages that can be // batched in a single publish request. MaxPublishRequestCount = wire.MaxPublishRequestCount // MaxPublishRequestBytes is the maximum allowed serialized size of a single // publish request (containing a batch of messages) in bytes. MaxPublishRequestBytes = wire.MaxPublishRequestBytes ) // KeyExtractorFunc is a function that extracts an ordering key from a Message. type KeyExtractorFunc func(*pubsub.Message) []byte // PublishMessageTransformerFunc transforms a pubsub.Message to a Pub/Sub Lite // PubSubMessage API proto. If this returns an error, the pubsub.PublishResult // will be errored and the PublisherClient will consider this a fatal error and // terminate. type PublishMessageTransformerFunc func(*pubsub.Message, *pb.PubSubMessage) error // PublishSettings configure the PublisherClient. Batching settings // (DelayThreshold, CountThreshold, ByteThreshold, BufferedByteLimit) apply per // partition. // // A zero PublishSettings will result in values equivalent to // DefaultPublishSettings. type PublishSettings struct { // Publish a non-empty batch after this delay has passed. If DelayThreshold is // 0, it will be treated as DefaultPublishSettings.DelayThreshold. Otherwise // must be > 0. DelayThreshold time.Duration // Publish a batch when it has this many messages. The maximum is // MaxPublishRequestCount. If CountThreshold is 0, it will be treated as // DefaultPublishSettings.CountThreshold. Otherwise must be > 0. CountThreshold int // Publish a batch when its size in bytes reaches this value. The maximum is // MaxPublishRequestBytes. If ByteThreshold is 0, it will be treated as // DefaultPublishSettings.ByteThreshold. Otherwise must be > 0. ByteThreshold int // The maximum time that the client will attempt to open a publish stream // to the server. If Timeout is 0, it will be treated as // DefaultPublishSettings.Timeout, otherwise will be clamped to 2 minutes. In // the future, setting Timeout to less than 2 minutes will result in an error. // // If your application has a low tolerance to backend unavailability, set // Timeout to a lower duration to detect and handle. When the timeout is // exceeded, the PublisherClient will terminate with ErrBackendUnavailable and // details of the last error that occurred while trying to reconnect to // backends. Note that if the timeout duration is long, ErrOverflow may occur // first. // // If no failover operations need to be performed by the application, it is // recommended to just use the default timeout value to avoid the // PublisherClient terminating during short periods of backend unavailability. Timeout time.Duration // The maximum number of bytes that the publisher will keep in memory before // returning ErrOverflow. If BufferedByteLimit is 0, it will be treated as // DefaultPublishSettings.BufferedByteLimit. Otherwise must be > 0. // // Note that this setting applies per partition. If BufferedByteLimit is being // used to bound memory usage, keep in mind the number of partitions in the // topic. // // Note that Pub/Sub Lite topics are provisioned a publishing throughput // capacity, per partition, shared by all publisher clients. Setting a large // buffer size can mitigate transient publish spikes. However, consistently // attempting to publish messages at a much higher rate than the publishing // throughput capacity can cause the buffers to overflow. For more // information, see https://cloud.google.com/pubsub/lite/docs/topics. BufferedByteLimit int // Whether idempotence is enabled, where the server will ensure that unique // messages within a single publisher session are stored only once. Default // true. EnableIdempotence optional.Bool // Optional custom function that extracts an ordering key from a Message. The // default implementation extracts the key from Message.OrderingKey. KeyExtractor KeyExtractorFunc // Optional custom function that transforms a pubsub.Message to a // PubSubMessage API proto. MessageTransformer PublishMessageTransformerFunc // The polling interval to watch for topic partition count updates. // Currently internal only and overridden in tests. configPollPeriod time.Duration } // DefaultPublishSettings holds the default values for PublishSettings. var DefaultPublishSettings = PublishSettings{ DelayThreshold: 10 * time.Millisecond, CountThreshold: 100, ByteThreshold: 1e6, Timeout: 7 * 24 * time.Hour, BufferedByteLimit: 1e10, EnableIdempotence: true, } func (s *PublishSettings) toWireSettings() wire.PublishSettings { wireSettings := wire.PublishSettings{ DelayThreshold: DefaultPublishSettings.DelayThreshold, CountThreshold: DefaultPublishSettings.CountThreshold, ByteThreshold: DefaultPublishSettings.ByteThreshold, Timeout: DefaultPublishSettings.Timeout, BufferedByteLimit: DefaultPublishSettings.BufferedByteLimit, EnableIdempotence: wire.DefaultPublishSettings.EnableIdempotence, ConfigPollPeriod: wire.DefaultPublishSettings.ConfigPollPeriod, Framework: wire.FrameworkCloudPubSubShim, } // Negative values preserved, but will fail validation in wire package. if s.DelayThreshold != 0 { wireSettings.DelayThreshold = s.DelayThreshold } if s.CountThreshold != 0 { wireSettings.CountThreshold = s.CountThreshold } if s.ByteThreshold != 0 { wireSettings.ByteThreshold = s.ByteThreshold }
if s.Timeout != 0 { if s.Timeout >= wire.MinTimeout { wireSettings.Timeout = s.Timeout } else { log.Println("WARNING: PublishSettings.Timeout has been overridden to 2 minutes (the minimum value). A lower value will cause an error in the future.") wireSettings.Timeout = wire.MinTimeout } } if s.BufferedByteLimit != 0 { wireSettings.BufferedByteLimit = s.BufferedByteLimit } if s.EnableIdempotence != nil { wireSettings.EnableIdempotence = optional.ToBool(s.EnableIdempotence) } if s.configPollPeriod != 0 { wireSettings.ConfigPollPeriod = s.configPollPeriod } return wireSettings } // NackHandler is invoked when pubsub.Message.Nack() is called. Pub/Sub Lite // does not have a concept of 'nack'. If the nack handler implementation returns // nil, the message is acknowledged. If an error is returned, the // SubscriberClient will consider this a fatal error and terminate. // // In Pub/Sub Lite, only a single subscriber for a given subscription is // connected to any partition at a time, and there is no other client that may // be able to handle messages. type NackHandler func(*pubsub.Message) error // ReceiveMessageTransformerFunc transforms a Pub/Sub Lite SequencedMessage API // proto to a pubsub.Message. The implementation must not set pubsub.Message.ID. // // If this returns an error, the SubscriberClient will consider this a fatal // error and terminate. type ReceiveMessageTransformerFunc func(*pb.SequencedMessage, *pubsub.Message) error // ReassignmentHandlerFunc is called any time a new partition assignment is // received from the server. It will be called with both the previous and new // partition numbers as decided by the server. Both slices of partition numbers // are sorted in ascending order. // // When this handler is called, partitions that are being assigned away are // stopping and new partitions are starting. Acks and nacks for messages from // partitions that are being assigned away will have no effect, but message // deliveries may still be in flight. // // The client library will not acknowledge the assignment until this handler // returns. The server will not assign any of the partitions in // `previousPartitions` to another client unless the assignment is acknowledged, // or a client takes too long to acknowledge (currently 30 seconds from the time // the assignment is sent from server's point of view). // // Because of the above, as long as reassignment handling is processed quickly, // it can be used to abort outstanding operations on partitions which are being // assigned away from this client. // // If this handler returns an error, the SubscriberClient will consider this a // fatal error and terminate. type ReassignmentHandlerFunc func(previousPartitions, nextPartitions []int) error // ReceiveSettings configure the SubscriberClient. Flow control settings // (MaxOutstandingMessages, MaxOutstandingBytes) apply per partition. // // A zero ReceiveSettings will result in values equivalent to // DefaultReceiveSettings. type ReceiveSettings struct { // MaxOutstandingMessages is the maximum number of unacknowledged messages. // If MaxOutstandingMessages is 0, it will be treated as // DefaultReceiveSettings.MaxOutstandingMessages. Otherwise must be > 0. MaxOutstandingMessages int // MaxOutstandingBytes is the maximum size (in quota bytes) of unacknowledged // messages. If MaxOutstandingBytes is 0, it will be treated as // DefaultReceiveSettings.MaxOutstandingBytes. Otherwise must be > 0. // // Note that this setting applies per partition. If MaxOutstandingBytes is // being used to bound memory usage, keep in mind the number of partitions in // the associated topic. MaxOutstandingBytes int // The maximum time that the client will attempt to open a subscribe stream // to the server. If Timeout is 0, it will be treated as // DefaultReceiveSettings.Timeout, otherwise will be clamped to 2 minutes. In // the future, setting Timeout to less than 2 minutes will result in an error. // // If your application has a low tolerance to backend unavailability, set // Timeout to a lower duration to detect and handle. When the timeout is // exceeded, the SubscriberClient will terminate with ErrBackendUnavailable // and details of the last error that occurred while trying to reconnect to // backends. // // If no failover operations need to be performed by the application, it is // recommended to just use the default timeout value to avoid the // SubscriberClient terminating during short periods of backend // unavailability. Timeout time.Duration // The topic partition numbers (zero-indexed) to receive messages from. // Values must be less than the number of partitions for the topic. If not // specified, the SubscriberClient will use the partition assignment service // to determine which partitions it should connect to. Partitions []int // Optional custom function to handle pubsub.Message.Nack() calls. If not set, // the default behavior is to terminate the SubscriberClient. NackHandler NackHandler // Optional custom function that transforms a SequencedMessage API proto to a // pubsub.Message. MessageTransformer ReceiveMessageTransformerFunc // Optional custom function that is called when a new partition assignment has // been delivered to the client. ReassignmentHandler ReassignmentHandlerFunc } // DefaultReceiveSettings holds the default values for ReceiveSettings. var DefaultReceiveSettings = ReceiveSettings{ MaxOutstandingMessages: 1000, MaxOutstandingBytes: 1e9, Timeout: 7 * 24 * time.Hour, } func (s *ReceiveSettings) toWireSettings() wire.ReceiveSettings { wireSettings := wire.ReceiveSettings{ MaxOutstandingMessages: DefaultReceiveSettings.MaxOutstandingMessages, MaxOutstandingBytes: DefaultReceiveSettings.MaxOutstandingBytes, Timeout: DefaultReceiveSettings.Timeout, Partitions: s.Partitions, Framework: wire.FrameworkCloudPubSubShim, } // Negative values preserved, but will fail validation in wire package. if s.MaxOutstandingMessages != 0 { wireSettings.MaxOutstandingMessages = s.MaxOutstandingMessages } if s.MaxOutstandingBytes != 0 { wireSettings.MaxOutstandingBytes = s.MaxOutstandingBytes } if s.Timeout != 0 { if s.Timeout >= wire.MinTimeout { wireSettings.Timeout = s.Timeout } else { log.Println("WARNING: ReceiveSettings.Timeout has been overridden to 2 minutes (the minimum value). A lower value will cause an error in the future.") wireSettings.Timeout = wire.MinTimeout } } return wireSettings }
random_line_split
settings.go
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and package pscompat import ( "log" "time" "cloud.google.com/go/internal/optional" "cloud.google.com/go/pubsub" "cloud.google.com/go/pubsublite/internal/wire" pb "cloud.google.com/go/pubsublite/apiv1/pubsublitepb" ) const ( // MaxPublishRequestCount is the maximum number of messages that can be // batched in a single publish request. MaxPublishRequestCount = wire.MaxPublishRequestCount // MaxPublishRequestBytes is the maximum allowed serialized size of a single // publish request (containing a batch of messages) in bytes. MaxPublishRequestBytes = wire.MaxPublishRequestBytes ) // KeyExtractorFunc is a function that extracts an ordering key from a Message. type KeyExtractorFunc func(*pubsub.Message) []byte // PublishMessageTransformerFunc transforms a pubsub.Message to a Pub/Sub Lite // PubSubMessage API proto. If this returns an error, the pubsub.PublishResult // will be errored and the PublisherClient will consider this a fatal error and // terminate. type PublishMessageTransformerFunc func(*pubsub.Message, *pb.PubSubMessage) error // PublishSettings configure the PublisherClient. Batching settings // (DelayThreshold, CountThreshold, ByteThreshold, BufferedByteLimit) apply per // partition. // // A zero PublishSettings will result in values equivalent to // DefaultPublishSettings. type PublishSettings struct { // Publish a non-empty batch after this delay has passed. If DelayThreshold is // 0, it will be treated as DefaultPublishSettings.DelayThreshold. Otherwise // must be > 0. DelayThreshold time.Duration // Publish a batch when it has this many messages. The maximum is // MaxPublishRequestCount. If CountThreshold is 0, it will be treated as // DefaultPublishSettings.CountThreshold. Otherwise must be > 0. CountThreshold int // Publish a batch when its size in bytes reaches this value. The maximum is // MaxPublishRequestBytes. If ByteThreshold is 0, it will be treated as // DefaultPublishSettings.ByteThreshold. Otherwise must be > 0. ByteThreshold int // The maximum time that the client will attempt to open a publish stream // to the server. If Timeout is 0, it will be treated as // DefaultPublishSettings.Timeout, otherwise will be clamped to 2 minutes. In // the future, setting Timeout to less than 2 minutes will result in an error. // // If your application has a low tolerance to backend unavailability, set // Timeout to a lower duration to detect and handle. When the timeout is // exceeded, the PublisherClient will terminate with ErrBackendUnavailable and // details of the last error that occurred while trying to reconnect to // backends. Note that if the timeout duration is long, ErrOverflow may occur // first. // // If no failover operations need to be performed by the application, it is // recommended to just use the default timeout value to avoid the // PublisherClient terminating during short periods of backend unavailability. Timeout time.Duration // The maximum number of bytes that the publisher will keep in memory before // returning ErrOverflow. If BufferedByteLimit is 0, it will be treated as // DefaultPublishSettings.BufferedByteLimit. Otherwise must be > 0. // // Note that this setting applies per partition. If BufferedByteLimit is being // used to bound memory usage, keep in mind the number of partitions in the // topic. // // Note that Pub/Sub Lite topics are provisioned a publishing throughput // capacity, per partition, shared by all publisher clients. Setting a large // buffer size can mitigate transient publish spikes. However, consistently // attempting to publish messages at a much higher rate than the publishing // throughput capacity can cause the buffers to overflow. For more // information, see https://cloud.google.com/pubsub/lite/docs/topics. BufferedByteLimit int // Whether idempotence is enabled, where the server will ensure that unique // messages within a single publisher session are stored only once. Default // true. EnableIdempotence optional.Bool // Optional custom function that extracts an ordering key from a Message. The // default implementation extracts the key from Message.OrderingKey. KeyExtractor KeyExtractorFunc // Optional custom function that transforms a pubsub.Message to a // PubSubMessage API proto. MessageTransformer PublishMessageTransformerFunc // The polling interval to watch for topic partition count updates. // Currently internal only and overridden in tests. configPollPeriod time.Duration } // DefaultPublishSettings holds the default values for PublishSettings. var DefaultPublishSettings = PublishSettings{ DelayThreshold: 10 * time.Millisecond, CountThreshold: 100, ByteThreshold: 1e6, Timeout: 7 * 24 * time.Hour, BufferedByteLimit: 1e10, EnableIdempotence: true, } func (s *PublishSettings) toWireSettings() wire.PublishSettings { wireSettings := wire.PublishSettings{ DelayThreshold: DefaultPublishSettings.DelayThreshold, CountThreshold: DefaultPublishSettings.CountThreshold, ByteThreshold: DefaultPublishSettings.ByteThreshold, Timeout: DefaultPublishSettings.Timeout, BufferedByteLimit: DefaultPublishSettings.BufferedByteLimit, EnableIdempotence: wire.DefaultPublishSettings.EnableIdempotence, ConfigPollPeriod: wire.DefaultPublishSettings.ConfigPollPeriod, Framework: wire.FrameworkCloudPubSubShim, } // Negative values preserved, but will fail validation in wire package. if s.DelayThreshold != 0 { wireSettings.DelayThreshold = s.DelayThreshold } if s.CountThreshold != 0 { wireSettings.CountThreshold = s.CountThreshold } if s.ByteThreshold != 0 { wireSettings.ByteThreshold = s.ByteThreshold } if s.Timeout != 0 { if s.Timeout >= wire.MinTimeout { wireSettings.Timeout = s.Timeout } else { log.Println("WARNING: PublishSettings.Timeout has been overridden to 2 minutes (the minimum value). A lower value will cause an error in the future.") wireSettings.Timeout = wire.MinTimeout } } if s.BufferedByteLimit != 0 { wireSettings.BufferedByteLimit = s.BufferedByteLimit } if s.EnableIdempotence != nil { wireSettings.EnableIdempotence = optional.ToBool(s.EnableIdempotence) } if s.configPollPeriod != 0 { wireSettings.ConfigPollPeriod = s.configPollPeriod } return wireSettings } // NackHandler is invoked when pubsub.Message.Nack() is called. Pub/Sub Lite // does not have a concept of 'nack'. If the nack handler implementation returns // nil, the message is acknowledged. If an error is returned, the // SubscriberClient will consider this a fatal error and terminate. // // In Pub/Sub Lite, only a single subscriber for a given subscription is // connected to any partition at a time, and there is no other client that may // be able to handle messages. type NackHandler func(*pubsub.Message) error // ReceiveMessageTransformerFunc transforms a Pub/Sub Lite SequencedMessage API // proto to a pubsub.Message. The implementation must not set pubsub.Message.ID. // // If this returns an error, the SubscriberClient will consider this a fatal // error and terminate. type ReceiveMessageTransformerFunc func(*pb.SequencedMessage, *pubsub.Message) error // ReassignmentHandlerFunc is called any time a new partition assignment is // received from the server. It will be called with both the previous and new // partition numbers as decided by the server. Both slices of partition numbers // are sorted in ascending order. // // When this handler is called, partitions that are being assigned away are // stopping and new partitions are starting. Acks and nacks for messages from // partitions that are being assigned away will have no effect, but message // deliveries may still be in flight. // // The client library will not acknowledge the assignment until this handler // returns. The server will not assign any of the partitions in // `previousPartitions` to another client unless the assignment is acknowledged, // or a client takes too long to acknowledge (currently 30 seconds from the time // the assignment is sent from server's point of view). // // Because of the above, as long as reassignment handling is processed quickly, // it can be used to abort outstanding operations on partitions which are being // assigned away from this client. // // If this handler returns an error, the SubscriberClient will consider this a // fatal error and terminate. type ReassignmentHandlerFunc func(previousPartitions, nextPartitions []int) error // ReceiveSettings configure the SubscriberClient. Flow control settings // (MaxOutstandingMessages, MaxOutstandingBytes) apply per partition. // // A zero ReceiveSettings will result in values equivalent to // DefaultReceiveSettings. type ReceiveSettings struct { // MaxOutstandingMessages is the maximum number of unacknowledged messages. // If MaxOutstandingMessages is 0, it will be treated as // DefaultReceiveSettings.MaxOutstandingMessages. Otherwise must be > 0. MaxOutstandingMessages int // MaxOutstandingBytes is the maximum size (in quota bytes) of unacknowledged // messages. If MaxOutstandingBytes is 0, it will be treated as // DefaultReceiveSettings.MaxOutstandingBytes. Otherwise must be > 0. // // Note that this setting applies per partition. If MaxOutstandingBytes is // being used to bound memory usage, keep in mind the number of partitions in // the associated topic. MaxOutstandingBytes int // The maximum time that the client will attempt to open a subscribe stream // to the server. If Timeout is 0, it will be treated as // DefaultReceiveSettings.Timeout, otherwise will be clamped to 2 minutes. In // the future, setting Timeout to less than 2 minutes will result in an error. // // If your application has a low tolerance to backend unavailability, set // Timeout to a lower duration to detect and handle. When the timeout is // exceeded, the SubscriberClient will terminate with ErrBackendUnavailable // and details of the last error that occurred while trying to reconnect to // backends. // // If no failover operations need to be performed by the application, it is // recommended to just use the default timeout value to avoid the // SubscriberClient terminating during short periods of backend // unavailability. Timeout time.Duration // The topic partition numbers (zero-indexed) to receive messages from. // Values must be less than the number of partitions for the topic. If not // specified, the SubscriberClient will use the partition assignment service // to determine which partitions it should connect to. Partitions []int // Optional custom function to handle pubsub.Message.Nack() calls. If not set, // the default behavior is to terminate the SubscriberClient. NackHandler NackHandler // Optional custom function that transforms a SequencedMessage API proto to a // pubsub.Message. MessageTransformer ReceiveMessageTransformerFunc // Optional custom function that is called when a new partition assignment has // been delivered to the client. ReassignmentHandler ReassignmentHandlerFunc } // DefaultReceiveSettings holds the default values for ReceiveSettings. var DefaultReceiveSettings = ReceiveSettings{ MaxOutstandingMessages: 1000, MaxOutstandingBytes: 1e9, Timeout: 7 * 24 * time.Hour, } func (s *ReceiveSettings) toWireSettings() wire.ReceiveSettings { wireSettings := wire.ReceiveSettings{ MaxOutstandingMessages: DefaultReceiveSettings.MaxOutstandingMessages, MaxOutstandingBytes: DefaultReceiveSettings.MaxOutstandingBytes, Timeout: DefaultReceiveSettings.Timeout, Partitions: s.Partitions, Framework: wire.FrameworkCloudPubSubShim, } // Negative values preserved, but will fail validation in wire package. if s.MaxOutstandingMessages != 0 { wireSettings.MaxOutstandingMessages = s.MaxOutstandingMessages } if s.MaxOutstandingBytes != 0
if s.Timeout != 0 { if s.Timeout >= wire.MinTimeout { wireSettings.Timeout = s.Timeout } else { log.Println("WARNING: ReceiveSettings.Timeout has been overridden to 2 minutes (the minimum value). A lower value will cause an error in the future.") wireSettings.Timeout = wire.MinTimeout } } return wireSettings }
{ wireSettings.MaxOutstandingBytes = s.MaxOutstandingBytes }
conditional_block
settings.go
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and package pscompat import ( "log" "time" "cloud.google.com/go/internal/optional" "cloud.google.com/go/pubsub" "cloud.google.com/go/pubsublite/internal/wire" pb "cloud.google.com/go/pubsublite/apiv1/pubsublitepb" ) const ( // MaxPublishRequestCount is the maximum number of messages that can be // batched in a single publish request. MaxPublishRequestCount = wire.MaxPublishRequestCount // MaxPublishRequestBytes is the maximum allowed serialized size of a single // publish request (containing a batch of messages) in bytes. MaxPublishRequestBytes = wire.MaxPublishRequestBytes ) // KeyExtractorFunc is a function that extracts an ordering key from a Message. type KeyExtractorFunc func(*pubsub.Message) []byte // PublishMessageTransformerFunc transforms a pubsub.Message to a Pub/Sub Lite // PubSubMessage API proto. If this returns an error, the pubsub.PublishResult // will be errored and the PublisherClient will consider this a fatal error and // terminate. type PublishMessageTransformerFunc func(*pubsub.Message, *pb.PubSubMessage) error // PublishSettings configure the PublisherClient. Batching settings // (DelayThreshold, CountThreshold, ByteThreshold, BufferedByteLimit) apply per // partition. // // A zero PublishSettings will result in values equivalent to // DefaultPublishSettings. type PublishSettings struct { // Publish a non-empty batch after this delay has passed. If DelayThreshold is // 0, it will be treated as DefaultPublishSettings.DelayThreshold. Otherwise // must be > 0. DelayThreshold time.Duration // Publish a batch when it has this many messages. The maximum is // MaxPublishRequestCount. If CountThreshold is 0, it will be treated as // DefaultPublishSettings.CountThreshold. Otherwise must be > 0. CountThreshold int // Publish a batch when its size in bytes reaches this value. The maximum is // MaxPublishRequestBytes. If ByteThreshold is 0, it will be treated as // DefaultPublishSettings.ByteThreshold. Otherwise must be > 0. ByteThreshold int // The maximum time that the client will attempt to open a publish stream // to the server. If Timeout is 0, it will be treated as // DefaultPublishSettings.Timeout, otherwise will be clamped to 2 minutes. In // the future, setting Timeout to less than 2 minutes will result in an error. // // If your application has a low tolerance to backend unavailability, set // Timeout to a lower duration to detect and handle. When the timeout is // exceeded, the PublisherClient will terminate with ErrBackendUnavailable and // details of the last error that occurred while trying to reconnect to // backends. Note that if the timeout duration is long, ErrOverflow may occur // first. // // If no failover operations need to be performed by the application, it is // recommended to just use the default timeout value to avoid the // PublisherClient terminating during short periods of backend unavailability. Timeout time.Duration // The maximum number of bytes that the publisher will keep in memory before // returning ErrOverflow. If BufferedByteLimit is 0, it will be treated as // DefaultPublishSettings.BufferedByteLimit. Otherwise must be > 0. // // Note that this setting applies per partition. If BufferedByteLimit is being // used to bound memory usage, keep in mind the number of partitions in the // topic. // // Note that Pub/Sub Lite topics are provisioned a publishing throughput // capacity, per partition, shared by all publisher clients. Setting a large // buffer size can mitigate transient publish spikes. However, consistently // attempting to publish messages at a much higher rate than the publishing // throughput capacity can cause the buffers to overflow. For more // information, see https://cloud.google.com/pubsub/lite/docs/topics. BufferedByteLimit int // Whether idempotence is enabled, where the server will ensure that unique // messages within a single publisher session are stored only once. Default // true. EnableIdempotence optional.Bool // Optional custom function that extracts an ordering key from a Message. The // default implementation extracts the key from Message.OrderingKey. KeyExtractor KeyExtractorFunc // Optional custom function that transforms a pubsub.Message to a // PubSubMessage API proto. MessageTransformer PublishMessageTransformerFunc // The polling interval to watch for topic partition count updates. // Currently internal only and overridden in tests. configPollPeriod time.Duration } // DefaultPublishSettings holds the default values for PublishSettings. var DefaultPublishSettings = PublishSettings{ DelayThreshold: 10 * time.Millisecond, CountThreshold: 100, ByteThreshold: 1e6, Timeout: 7 * 24 * time.Hour, BufferedByteLimit: 1e10, EnableIdempotence: true, } func (s *PublishSettings)
() wire.PublishSettings { wireSettings := wire.PublishSettings{ DelayThreshold: DefaultPublishSettings.DelayThreshold, CountThreshold: DefaultPublishSettings.CountThreshold, ByteThreshold: DefaultPublishSettings.ByteThreshold, Timeout: DefaultPublishSettings.Timeout, BufferedByteLimit: DefaultPublishSettings.BufferedByteLimit, EnableIdempotence: wire.DefaultPublishSettings.EnableIdempotence, ConfigPollPeriod: wire.DefaultPublishSettings.ConfigPollPeriod, Framework: wire.FrameworkCloudPubSubShim, } // Negative values preserved, but will fail validation in wire package. if s.DelayThreshold != 0 { wireSettings.DelayThreshold = s.DelayThreshold } if s.CountThreshold != 0 { wireSettings.CountThreshold = s.CountThreshold } if s.ByteThreshold != 0 { wireSettings.ByteThreshold = s.ByteThreshold } if s.Timeout != 0 { if s.Timeout >= wire.MinTimeout { wireSettings.Timeout = s.Timeout } else { log.Println("WARNING: PublishSettings.Timeout has been overridden to 2 minutes (the minimum value). A lower value will cause an error in the future.") wireSettings.Timeout = wire.MinTimeout } } if s.BufferedByteLimit != 0 { wireSettings.BufferedByteLimit = s.BufferedByteLimit } if s.EnableIdempotence != nil { wireSettings.EnableIdempotence = optional.ToBool(s.EnableIdempotence) } if s.configPollPeriod != 0 { wireSettings.ConfigPollPeriod = s.configPollPeriod } return wireSettings } // NackHandler is invoked when pubsub.Message.Nack() is called. Pub/Sub Lite // does not have a concept of 'nack'. If the nack handler implementation returns // nil, the message is acknowledged. If an error is returned, the // SubscriberClient will consider this a fatal error and terminate. // // In Pub/Sub Lite, only a single subscriber for a given subscription is // connected to any partition at a time, and there is no other client that may // be able to handle messages. type NackHandler func(*pubsub.Message) error // ReceiveMessageTransformerFunc transforms a Pub/Sub Lite SequencedMessage API // proto to a pubsub.Message. The implementation must not set pubsub.Message.ID. // // If this returns an error, the SubscriberClient will consider this a fatal // error and terminate. type ReceiveMessageTransformerFunc func(*pb.SequencedMessage, *pubsub.Message) error // ReassignmentHandlerFunc is called any time a new partition assignment is // received from the server. It will be called with both the previous and new // partition numbers as decided by the server. Both slices of partition numbers // are sorted in ascending order. // // When this handler is called, partitions that are being assigned away are // stopping and new partitions are starting. Acks and nacks for messages from // partitions that are being assigned away will have no effect, but message // deliveries may still be in flight. // // The client library will not acknowledge the assignment until this handler // returns. The server will not assign any of the partitions in // `previousPartitions` to another client unless the assignment is acknowledged, // or a client takes too long to acknowledge (currently 30 seconds from the time // the assignment is sent from server's point of view). // // Because of the above, as long as reassignment handling is processed quickly, // it can be used to abort outstanding operations on partitions which are being // assigned away from this client. // // If this handler returns an error, the SubscriberClient will consider this a // fatal error and terminate. type ReassignmentHandlerFunc func(previousPartitions, nextPartitions []int) error // ReceiveSettings configure the SubscriberClient. Flow control settings // (MaxOutstandingMessages, MaxOutstandingBytes) apply per partition. // // A zero ReceiveSettings will result in values equivalent to // DefaultReceiveSettings. type ReceiveSettings struct { // MaxOutstandingMessages is the maximum number of unacknowledged messages. // If MaxOutstandingMessages is 0, it will be treated as // DefaultReceiveSettings.MaxOutstandingMessages. Otherwise must be > 0. MaxOutstandingMessages int // MaxOutstandingBytes is the maximum size (in quota bytes) of unacknowledged // messages. If MaxOutstandingBytes is 0, it will be treated as // DefaultReceiveSettings.MaxOutstandingBytes. Otherwise must be > 0. // // Note that this setting applies per partition. If MaxOutstandingBytes is // being used to bound memory usage, keep in mind the number of partitions in // the associated topic. MaxOutstandingBytes int // The maximum time that the client will attempt to open a subscribe stream // to the server. If Timeout is 0, it will be treated as // DefaultReceiveSettings.Timeout, otherwise will be clamped to 2 minutes. In // the future, setting Timeout to less than 2 minutes will result in an error. // // If your application has a low tolerance to backend unavailability, set // Timeout to a lower duration to detect and handle. When the timeout is // exceeded, the SubscriberClient will terminate with ErrBackendUnavailable // and details of the last error that occurred while trying to reconnect to // backends. // // If no failover operations need to be performed by the application, it is // recommended to just use the default timeout value to avoid the // SubscriberClient terminating during short periods of backend // unavailability. Timeout time.Duration // The topic partition numbers (zero-indexed) to receive messages from. // Values must be less than the number of partitions for the topic. If not // specified, the SubscriberClient will use the partition assignment service // to determine which partitions it should connect to. Partitions []int // Optional custom function to handle pubsub.Message.Nack() calls. If not set, // the default behavior is to terminate the SubscriberClient. NackHandler NackHandler // Optional custom function that transforms a SequencedMessage API proto to a // pubsub.Message. MessageTransformer ReceiveMessageTransformerFunc // Optional custom function that is called when a new partition assignment has // been delivered to the client. ReassignmentHandler ReassignmentHandlerFunc } // DefaultReceiveSettings holds the default values for ReceiveSettings. var DefaultReceiveSettings = ReceiveSettings{ MaxOutstandingMessages: 1000, MaxOutstandingBytes: 1e9, Timeout: 7 * 24 * time.Hour, } func (s *ReceiveSettings) toWireSettings() wire.ReceiveSettings { wireSettings := wire.ReceiveSettings{ MaxOutstandingMessages: DefaultReceiveSettings.MaxOutstandingMessages, MaxOutstandingBytes: DefaultReceiveSettings.MaxOutstandingBytes, Timeout: DefaultReceiveSettings.Timeout, Partitions: s.Partitions, Framework: wire.FrameworkCloudPubSubShim, } // Negative values preserved, but will fail validation in wire package. if s.MaxOutstandingMessages != 0 { wireSettings.MaxOutstandingMessages = s.MaxOutstandingMessages } if s.MaxOutstandingBytes != 0 { wireSettings.MaxOutstandingBytes = s.MaxOutstandingBytes } if s.Timeout != 0 { if s.Timeout >= wire.MinTimeout { wireSettings.Timeout = s.Timeout } else { log.Println("WARNING: ReceiveSettings.Timeout has been overridden to 2 minutes (the minimum value). A lower value will cause an error in the future.") wireSettings.Timeout = wire.MinTimeout } } return wireSettings }
toWireSettings
identifier_name
honeyproxyserver.py
from wsgiref.simple_server import make_server import bottle, json, threading, time, subprocess, collections, sys, os, datetime, IPy, re, time, urllib from bottle import Bottle, static_file, request, redirect, PasteServer as wsgiserver, response from bottle.ext import sqlalchemy as bottlealchemy from jinja2 import Environment, FileSystemLoader from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, Column, DateTime, String, Boolean, Integer, Enum from sqlalchemy.orm import sessionmaker from sqlalchemy.orm.session import object_session from sqlalchemy.pool import QueuePool from recaptcha.client import captcha from subprocess import PIPE, STDOUT with open("config.json","r") as f: config = json.loads(f.read()) if not os.path.isdir(config["logdir"]): os.makedirs(config["logdir"]) engine = create_engine('sqlite:///honeyproxy.sqlite', echo=False) Session = sessionmaker(bind=engine) #session = Session() Base = declarative_base() class Analysis(Base): __tablename__ = 'analysis' id = Column(String, primary_key=True, default=lambda: os.urandom(8).encode('hex')) url = Column(String, nullable=False) request_count = Column(Integer) submit_time = Column(DateTime, default=datetime.datetime.now) status = Column(Enum("QUEUE","ACTIVE","FINISHED"), default="QUEUE") @property def analysis_size(self): if self.status == "QUEUE" or not os.path.isfile(self.getDumpfileLocation()): return 0 else: return os.path.getsize(self.getDumpfileLocation()) @property def queue_position(self): if self.status != "QUEUE": return -1 return 1 + object_session(self).query(Analysis).filter_by(status="QUEUE").filter(Analysis.submit_time < self.submit_time).count() def getDumpfileLocation(self): return os.path.join(config["dumpdir"],self.id) def __repr__(self): return "<Analysis('%s','%s','%s')>" % (self.id,self.url,str(self.status)) def as_dict(self): ret = {c.name: getattr(self, c.name) for c in self.__table__.columns} ret["analysis_size"] = self.analysis_size ret["queue_position"] = self.queue_position return ret def as_htmlsafe_dict(self): ret = self.as_dict() ret["submit_time"] = ret["submit_time"].isoformat() ret["url"] = urllib.quote(ret["url"],safe='~@#$&()*!+=:;,.?/\'') return ret __mapper_args__ = { 'order_by' :[submit_time.desc()] } Base.metadata.create_all(engine) bottle.debug(config["debug"]) app = Bottle() app.install(bottlealchemy.Plugin(engine,keyword='session')) template_env = Environment(loader=FileSystemLoader("./templates")) @app.route('/static/<filepath:path>') def serve_static(filepath): resp = static_file(filepath, root='./static') resp.set_header('Cache-Control','public, max-age=3600') return resp @app.route('/favicon.ico') def favicon(): return static_file('/favicon.ico', root='./static') @app.route('/') def main(session): analyses = session.query(Analysis).filter(Analysis.status != "QUEUE").slice(0,20).all() analyses = json.dumps(list(a.as_htmlsafe_dict() for a in analyses)) template = template_env.get_template('index.html') return template.render(analyses=analyses) @app.route('/analysis/<analysis_id:re:[a-z0-9]+>') def analysis(analysis_id,session): analysis = session.query(Analysis).get(analysis_id) if not analysis: abort(404, "No such analysis.") if analysis.status == "QUEUE": template = template_env.get_template('queue.html') return template.render(data=json.dumps(api_analysis(analysis_id))) else: instance = instanceManager.getInstance(analysis) template = template_env.get_template('appframe.html') return template.render( url="http://"+request.urlparts.netloc.split(":")[0]+":"+str(instance.guiport)+"/app/", analysis_url=analysis.url) @app.post('/api/search') def api_search(session): url = request.forms.get('url') if url: matches = session.query(Analysis).filter( Analysis.url.like("%"+request.forms.get('url')+"%")).slice(0,50).all() return {"results": list(a.as_htmlsafe_dict() for a in matches)} else: return{"error":"no url specified"} @app.route('/api/analysis/<analysis_id:re:[a-z0-9]+>') def
(analysis_id,session): analysis = session.query(Analysis).get(analysis_id) if not analysis: return {"error":"not found"} else: return analysis.as_htmlsafe_dict() @app.post('/api/analyze') def api_analyze(session): response = captcha.submit( request.forms.get(r'recaptcha_challenge_field'), request.forms.get('recaptcha_response_field'), config["recaptcha"]["privatekey"], request.environ.get('REMOTE_ADDR') ) if not response.is_valid: return {"success": False, "msg": "invalid captcha"} else: url = request.forms.get("url") if not re.match("^(https?://)?[a-zA-Z0-9_\\-\\.]+\\.[a-zA-Z0-9]+(:\d+)?(/.*)?$",url): return {"success": False, "msg": "invalid url"} if not url.lower().startswith("http"): url = "http://"+url analysis = Analysis(url=url) session.add(analysis) session.commit() return analysis.as_htmlsafe_dict() # Notice: The code below is a proof of concept. # It is incredibly hacky and badly designed. Spawning N instances of HoneyProxy is downright silly. # So, why did I commit this crime? # The HoneyProxy dump format will get a complete overhaul very soon. # Anything I implemented here will get obsolete with these changes, # so this code just serves us as a bad PoC. Not as a base to build on. class InstanceInfo(object): def __init__(self, instance_type, handle, apiport, guiport): self.instance_type = instance_type self.handle = handle self.apiport = apiport self.guiport = guiport self.starttime = time.time() self.last_access = self.starttime def __repr__(self): return "Instance<%s,%d,%d,%d>" % (self.instance_type, self.apiport, self.guiport, self.starttime) class HoneyProxyInstanceManager(object): def __init__(self): self.active = {} self.ports = set((8200+i for i in range(0,800))) def getInstance(self, analysis): if analysis.id in self.active: instanceInfo = self.active[analysis.id] instanceInfo.last_access = time.time() return instanceInfo return self.spawnInstance(analysis,"result") def _getPorts(self, apiport=None, guiport=None): if apiport: self.ports.remove(apiport) else: apiport = self.ports.pop() if guiport: self.ports.remove(guiport) else: guiport = self.ports.pop() return apiport, guiport def spawnInstance(self, analysis, instance_type, apiport=None, guiport=None): apiport, guiport = self._getPorts(apiport, guiport) print "Spawn %s instance(%d, %d)..." % (instance_type, apiport, guiport) args = (config["HoneyProxy"] + [ "--api-auth", "NO_AUTH", "--apiport", str(apiport), "--guiport", str(guiport), "--no-gui", "--readonly" ]) if instance_type == "listener": args.extend( [ "-w", analysis.getDumpfileLocation(), "-p","8100", "-T", "-s","./resources/suppresswinupdate.py", "-Z","5m"]) else: args.extend( [ "-r", analysis.getDumpfileLocation(), "-n", "--readonly"]) p = subprocess.Popen(args, stdout=PIPE, stderr=STDOUT) out = p.stdout.readline() if out != "HoneyProxy has been started!\n": raise RuntimeError("Couldn't start HoneyProxy: %s" % out+p.stdout.read()) self.active[analysis.id] = InstanceInfo(instance_type, p, apiport, guiport) return self.active[analysis.id] def terminateProcess(self, analysis): data = self.active[analysis.id] logfile = os.path.join(config["logdir"], analysis.id + ".log") data.handle.terminate() with open(logfile, "a") as f: f.write("\n\n"+str(data)+"\n\n") f.write(data.handle.stdout.read()) self.ports.add(data.apiport) self.ports.add(data.guiport) del self.active[analysis.id] class RequestHandler(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.session = Session() self.daemon = True def run(self): while True: last_allowed_timestamp = time.time() - config["instance_lifetime"] for analysis_id, instanceInfo in instanceManager.active.items(): if instanceInfo.last_access < last_allowed_timestamp and instanceInfo.instance_type == "result": print "Terminating result instance %s" % analysis_id analysis = self.session.query(Analysis).get(analysis_id) instanceManager.terminateProcess(analysis) analysis = self.session.query(Analysis).filter_by(status="QUEUE").order_by(Analysis.submit_time).first() if analysis == None: time.sleep(1) else: #Launch HoneyProxy instanceManager.spawnInstance(analysis,"listener") analysis.status = "ACTIVE" self.session.commit() # Reset VM and start it try: subprocess.call(config["VBoxManage"] + ["controlvm", config["VMName"], "poweroff"]) except: pass subprocess.call(config["VBoxManage"] + ["snapshot", config["VMName"], "restorecurrent"]) subprocess.check_call(config["VBoxManage"] + ["startvm", config["VMName"],"--type","headless"]) #Launch URL params = (config["VBoxManage"] + ["guestcontrol", config["VMName"], "exec"] + config["VMStart"] + [analysis.url]) subprocess.call(params) print "Site opened." time.sleep(config["analysis_duration"]) #Shut down VM subprocess.call(config["VBoxManage"] + ["controlvm", config["VMName"], "poweroff"]) #Finish HoneyProxy # dirty workaround: terminate the instance to free up the proxy server. # restart a resultinstance on the same ports afterwards instanceInfo = instanceManager.getInstance(analysis) instanceManager.terminateProcess(analysis) instanceManager.spawnInstance(analysis, "result", instanceInfo.apiport, instanceInfo.guiport) analysis.status = "FINISHED" self.session.commit() instanceManager = HoneyProxyInstanceManager() request_queue = collections.deque(maxlen=50) requesthandler = RequestHandler().start() if __name__ == "__main__": app.run(reloader=config["debug"],server=wsgiserver, port=config["port"],host="0.0.0.0")
api_analysis
identifier_name
honeyproxyserver.py
from wsgiref.simple_server import make_server import bottle, json, threading, time, subprocess, collections, sys, os, datetime, IPy, re, time, urllib from bottle import Bottle, static_file, request, redirect, PasteServer as wsgiserver, response from bottle.ext import sqlalchemy as bottlealchemy from jinja2 import Environment, FileSystemLoader from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, Column, DateTime, String, Boolean, Integer, Enum from sqlalchemy.orm import sessionmaker from sqlalchemy.orm.session import object_session from sqlalchemy.pool import QueuePool from recaptcha.client import captcha from subprocess import PIPE, STDOUT with open("config.json","r") as f: config = json.loads(f.read()) if not os.path.isdir(config["logdir"]): os.makedirs(config["logdir"]) engine = create_engine('sqlite:///honeyproxy.sqlite', echo=False) Session = sessionmaker(bind=engine) #session = Session() Base = declarative_base() class Analysis(Base): __tablename__ = 'analysis' id = Column(String, primary_key=True, default=lambda: os.urandom(8).encode('hex')) url = Column(String, nullable=False) request_count = Column(Integer) submit_time = Column(DateTime, default=datetime.datetime.now) status = Column(Enum("QUEUE","ACTIVE","FINISHED"), default="QUEUE") @property def analysis_size(self): if self.status == "QUEUE" or not os.path.isfile(self.getDumpfileLocation()): return 0 else: return os.path.getsize(self.getDumpfileLocation()) @property def queue_position(self): if self.status != "QUEUE": return -1 return 1 + object_session(self).query(Analysis).filter_by(status="QUEUE").filter(Analysis.submit_time < self.submit_time).count() def getDumpfileLocation(self): return os.path.join(config["dumpdir"],self.id) def __repr__(self): return "<Analysis('%s','%s','%s')>" % (self.id,self.url,str(self.status)) def as_dict(self): ret = {c.name: getattr(self, c.name) for c in self.__table__.columns} ret["analysis_size"] = self.analysis_size ret["queue_position"] = self.queue_position return ret def as_htmlsafe_dict(self): ret = self.as_dict() ret["submit_time"] = ret["submit_time"].isoformat() ret["url"] = urllib.quote(ret["url"],safe='~@#$&()*!+=:;,.?/\'') return ret __mapper_args__ = { 'order_by' :[submit_time.desc()] } Base.metadata.create_all(engine) bottle.debug(config["debug"]) app = Bottle() app.install(bottlealchemy.Plugin(engine,keyword='session')) template_env = Environment(loader=FileSystemLoader("./templates")) @app.route('/static/<filepath:path>') def serve_static(filepath): resp = static_file(filepath, root='./static') resp.set_header('Cache-Control','public, max-age=3600') return resp @app.route('/favicon.ico') def favicon(): return static_file('/favicon.ico', root='./static') @app.route('/') def main(session): analyses = session.query(Analysis).filter(Analysis.status != "QUEUE").slice(0,20).all() analyses = json.dumps(list(a.as_htmlsafe_dict() for a in analyses)) template = template_env.get_template('index.html') return template.render(analyses=analyses) @app.route('/analysis/<analysis_id:re:[a-z0-9]+>') def analysis(analysis_id,session): analysis = session.query(Analysis).get(analysis_id) if not analysis: abort(404, "No such analysis.") if analysis.status == "QUEUE": template = template_env.get_template('queue.html') return template.render(data=json.dumps(api_analysis(analysis_id))) else: instance = instanceManager.getInstance(analysis) template = template_env.get_template('appframe.html') return template.render( url="http://"+request.urlparts.netloc.split(":")[0]+":"+str(instance.guiport)+"/app/", analysis_url=analysis.url) @app.post('/api/search') def api_search(session): url = request.forms.get('url') if url: matches = session.query(Analysis).filter( Analysis.url.like("%"+request.forms.get('url')+"%")).slice(0,50).all() return {"results": list(a.as_htmlsafe_dict() for a in matches)} else: return{"error":"no url specified"} @app.route('/api/analysis/<analysis_id:re:[a-z0-9]+>') def api_analysis(analysis_id,session): analysis = session.query(Analysis).get(analysis_id) if not analysis: return {"error":"not found"} else: return analysis.as_htmlsafe_dict() @app.post('/api/analyze') def api_analyze(session): response = captcha.submit( request.forms.get(r'recaptcha_challenge_field'), request.forms.get('recaptcha_response_field'), config["recaptcha"]["privatekey"], request.environ.get('REMOTE_ADDR') ) if not response.is_valid: return {"success": False, "msg": "invalid captcha"} else: url = request.forms.get("url") if not re.match("^(https?://)?[a-zA-Z0-9_\\-\\.]+\\.[a-zA-Z0-9]+(:\d+)?(/.*)?$",url): return {"success": False, "msg": "invalid url"} if not url.lower().startswith("http"): url = "http://"+url analysis = Analysis(url=url) session.add(analysis) session.commit() return analysis.as_htmlsafe_dict() # Notice: The code below is a proof of concept. # It is incredibly hacky and badly designed. Spawning N instances of HoneyProxy is downright silly. # So, why did I commit this crime? # The HoneyProxy dump format will get a complete overhaul very soon. # Anything I implemented here will get obsolete with these changes, # so this code just serves us as a bad PoC. Not as a base to build on. class InstanceInfo(object): def __init__(self, instance_type, handle, apiport, guiport): self.instance_type = instance_type self.handle = handle self.apiport = apiport self.guiport = guiport self.starttime = time.time() self.last_access = self.starttime def __repr__(self): return "Instance<%s,%d,%d,%d>" % (self.instance_type, self.apiport, self.guiport, self.starttime) class HoneyProxyInstanceManager(object): def __init__(self): self.active = {} self.ports = set((8200+i for i in range(0,800))) def getInstance(self, analysis): if analysis.id in self.active: instanceInfo = self.active[analysis.id] instanceInfo.last_access = time.time() return instanceInfo return self.spawnInstance(analysis,"result") def _getPorts(self, apiport=None, guiport=None):
def spawnInstance(self, analysis, instance_type, apiport=None, guiport=None): apiport, guiport = self._getPorts(apiport, guiport) print "Spawn %s instance(%d, %d)..." % (instance_type, apiport, guiport) args = (config["HoneyProxy"] + [ "--api-auth", "NO_AUTH", "--apiport", str(apiport), "--guiport", str(guiport), "--no-gui", "--readonly" ]) if instance_type == "listener": args.extend( [ "-w", analysis.getDumpfileLocation(), "-p","8100", "-T", "-s","./resources/suppresswinupdate.py", "-Z","5m"]) else: args.extend( [ "-r", analysis.getDumpfileLocation(), "-n", "--readonly"]) p = subprocess.Popen(args, stdout=PIPE, stderr=STDOUT) out = p.stdout.readline() if out != "HoneyProxy has been started!\n": raise RuntimeError("Couldn't start HoneyProxy: %s" % out+p.stdout.read()) self.active[analysis.id] = InstanceInfo(instance_type, p, apiport, guiport) return self.active[analysis.id] def terminateProcess(self, analysis): data = self.active[analysis.id] logfile = os.path.join(config["logdir"], analysis.id + ".log") data.handle.terminate() with open(logfile, "a") as f: f.write("\n\n"+str(data)+"\n\n") f.write(data.handle.stdout.read()) self.ports.add(data.apiport) self.ports.add(data.guiport) del self.active[analysis.id] class RequestHandler(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.session = Session() self.daemon = True def run(self): while True: last_allowed_timestamp = time.time() - config["instance_lifetime"] for analysis_id, instanceInfo in instanceManager.active.items(): if instanceInfo.last_access < last_allowed_timestamp and instanceInfo.instance_type == "result": print "Terminating result instance %s" % analysis_id analysis = self.session.query(Analysis).get(analysis_id) instanceManager.terminateProcess(analysis) analysis = self.session.query(Analysis).filter_by(status="QUEUE").order_by(Analysis.submit_time).first() if analysis == None: time.sleep(1) else: #Launch HoneyProxy instanceManager.spawnInstance(analysis,"listener") analysis.status = "ACTIVE" self.session.commit() # Reset VM and start it try: subprocess.call(config["VBoxManage"] + ["controlvm", config["VMName"], "poweroff"]) except: pass subprocess.call(config["VBoxManage"] + ["snapshot", config["VMName"], "restorecurrent"]) subprocess.check_call(config["VBoxManage"] + ["startvm", config["VMName"],"--type","headless"]) #Launch URL params = (config["VBoxManage"] + ["guestcontrol", config["VMName"], "exec"] + config["VMStart"] + [analysis.url]) subprocess.call(params) print "Site opened." time.sleep(config["analysis_duration"]) #Shut down VM subprocess.call(config["VBoxManage"] + ["controlvm", config["VMName"], "poweroff"]) #Finish HoneyProxy # dirty workaround: terminate the instance to free up the proxy server. # restart a resultinstance on the same ports afterwards instanceInfo = instanceManager.getInstance(analysis) instanceManager.terminateProcess(analysis) instanceManager.spawnInstance(analysis, "result", instanceInfo.apiport, instanceInfo.guiport) analysis.status = "FINISHED" self.session.commit() instanceManager = HoneyProxyInstanceManager() request_queue = collections.deque(maxlen=50) requesthandler = RequestHandler().start() if __name__ == "__main__": app.run(reloader=config["debug"],server=wsgiserver, port=config["port"],host="0.0.0.0")
if apiport: self.ports.remove(apiport) else: apiport = self.ports.pop() if guiport: self.ports.remove(guiport) else: guiport = self.ports.pop() return apiport, guiport
identifier_body
honeyproxyserver.py
from wsgiref.simple_server import make_server import bottle, json, threading, time, subprocess, collections, sys, os, datetime, IPy, re, time, urllib from bottle import Bottle, static_file, request, redirect, PasteServer as wsgiserver, response from bottle.ext import sqlalchemy as bottlealchemy from jinja2 import Environment, FileSystemLoader from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, Column, DateTime, String, Boolean, Integer, Enum from sqlalchemy.orm import sessionmaker from sqlalchemy.orm.session import object_session from sqlalchemy.pool import QueuePool from recaptcha.client import captcha from subprocess import PIPE, STDOUT with open("config.json","r") as f: config = json.loads(f.read()) if not os.path.isdir(config["logdir"]): os.makedirs(config["logdir"]) engine = create_engine('sqlite:///honeyproxy.sqlite', echo=False) Session = sessionmaker(bind=engine) #session = Session() Base = declarative_base() class Analysis(Base): __tablename__ = 'analysis' id = Column(String, primary_key=True, default=lambda: os.urandom(8).encode('hex')) url = Column(String, nullable=False) request_count = Column(Integer) submit_time = Column(DateTime, default=datetime.datetime.now) status = Column(Enum("QUEUE","ACTIVE","FINISHED"), default="QUEUE") @property def analysis_size(self): if self.status == "QUEUE" or not os.path.isfile(self.getDumpfileLocation()): return 0 else: return os.path.getsize(self.getDumpfileLocation()) @property def queue_position(self): if self.status != "QUEUE": return -1 return 1 + object_session(self).query(Analysis).filter_by(status="QUEUE").filter(Analysis.submit_time < self.submit_time).count() def getDumpfileLocation(self): return os.path.join(config["dumpdir"],self.id) def __repr__(self): return "<Analysis('%s','%s','%s')>" % (self.id,self.url,str(self.status)) def as_dict(self): ret = {c.name: getattr(self, c.name) for c in self.__table__.columns} ret["analysis_size"] = self.analysis_size ret["queue_position"] = self.queue_position return ret def as_htmlsafe_dict(self): ret = self.as_dict() ret["submit_time"] = ret["submit_time"].isoformat() ret["url"] = urllib.quote(ret["url"],safe='~@#$&()*!+=:;,.?/\'') return ret __mapper_args__ = { 'order_by' :[submit_time.desc()] } Base.metadata.create_all(engine) bottle.debug(config["debug"]) app = Bottle() app.install(bottlealchemy.Plugin(engine,keyword='session')) template_env = Environment(loader=FileSystemLoader("./templates")) @app.route('/static/<filepath:path>') def serve_static(filepath): resp = static_file(filepath, root='./static') resp.set_header('Cache-Control','public, max-age=3600') return resp @app.route('/favicon.ico') def favicon(): return static_file('/favicon.ico', root='./static') @app.route('/') def main(session): analyses = session.query(Analysis).filter(Analysis.status != "QUEUE").slice(0,20).all() analyses = json.dumps(list(a.as_htmlsafe_dict() for a in analyses)) template = template_env.get_template('index.html') return template.render(analyses=analyses) @app.route('/analysis/<analysis_id:re:[a-z0-9]+>') def analysis(analysis_id,session): analysis = session.query(Analysis).get(analysis_id) if not analysis: abort(404, "No such analysis.") if analysis.status == "QUEUE": template = template_env.get_template('queue.html') return template.render(data=json.dumps(api_analysis(analysis_id))) else: instance = instanceManager.getInstance(analysis) template = template_env.get_template('appframe.html') return template.render( url="http://"+request.urlparts.netloc.split(":")[0]+":"+str(instance.guiport)+"/app/", analysis_url=analysis.url) @app.post('/api/search') def api_search(session): url = request.forms.get('url') if url: matches = session.query(Analysis).filter( Analysis.url.like("%"+request.forms.get('url')+"%")).slice(0,50).all() return {"results": list(a.as_htmlsafe_dict() for a in matches)} else: return{"error":"no url specified"} @app.route('/api/analysis/<analysis_id:re:[a-z0-9]+>') def api_analysis(analysis_id,session): analysis = session.query(Analysis).get(analysis_id) if not analysis: return {"error":"not found"} else: return analysis.as_htmlsafe_dict() @app.post('/api/analyze') def api_analyze(session): response = captcha.submit( request.forms.get(r'recaptcha_challenge_field'), request.forms.get('recaptcha_response_field'), config["recaptcha"]["privatekey"], request.environ.get('REMOTE_ADDR') ) if not response.is_valid: return {"success": False, "msg": "invalid captcha"} else: url = request.forms.get("url") if not re.match("^(https?://)?[a-zA-Z0-9_\\-\\.]+\\.[a-zA-Z0-9]+(:\d+)?(/.*)?$",url): return {"success": False, "msg": "invalid url"} if not url.lower().startswith("http"): url = "http://"+url analysis = Analysis(url=url) session.add(analysis) session.commit() return analysis.as_htmlsafe_dict() # Notice: The code below is a proof of concept. # It is incredibly hacky and badly designed. Spawning N instances of HoneyProxy is downright silly. # So, why did I commit this crime? # The HoneyProxy dump format will get a complete overhaul very soon. # Anything I implemented here will get obsolete with these changes, # so this code just serves us as a bad PoC. Not as a base to build on. class InstanceInfo(object): def __init__(self, instance_type, handle, apiport, guiport): self.instance_type = instance_type self.handle = handle self.apiport = apiport self.guiport = guiport self.starttime = time.time() self.last_access = self.starttime def __repr__(self): return "Instance<%s,%d,%d,%d>" % (self.instance_type, self.apiport, self.guiport, self.starttime) class HoneyProxyInstanceManager(object): def __init__(self): self.active = {} self.ports = set((8200+i for i in range(0,800))) def getInstance(self, analysis): if analysis.id in self.active: instanceInfo = self.active[analysis.id] instanceInfo.last_access = time.time() return instanceInfo return self.spawnInstance(analysis,"result") def _getPorts(self, apiport=None, guiport=None): if apiport: self.ports.remove(apiport) else: apiport = self.ports.pop() if guiport: self.ports.remove(guiport) else: guiport = self.ports.pop() return apiport, guiport def spawnInstance(self, analysis, instance_type, apiport=None, guiport=None): apiport, guiport = self._getPorts(apiport, guiport) print "Spawn %s instance(%d, %d)..." % (instance_type, apiport, guiport) args = (config["HoneyProxy"] + [ "--api-auth", "NO_AUTH", "--apiport", str(apiport), "--guiport", str(guiport), "--no-gui", "--readonly" ]) if instance_type == "listener": args.extend( [ "-w", analysis.getDumpfileLocation(), "-p","8100", "-T",
"-Z","5m"]) else: args.extend( [ "-r", analysis.getDumpfileLocation(), "-n", "--readonly"]) p = subprocess.Popen(args, stdout=PIPE, stderr=STDOUT) out = p.stdout.readline() if out != "HoneyProxy has been started!\n": raise RuntimeError("Couldn't start HoneyProxy: %s" % out+p.stdout.read()) self.active[analysis.id] = InstanceInfo(instance_type, p, apiport, guiport) return self.active[analysis.id] def terminateProcess(self, analysis): data = self.active[analysis.id] logfile = os.path.join(config["logdir"], analysis.id + ".log") data.handle.terminate() with open(logfile, "a") as f: f.write("\n\n"+str(data)+"\n\n") f.write(data.handle.stdout.read()) self.ports.add(data.apiport) self.ports.add(data.guiport) del self.active[analysis.id] class RequestHandler(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.session = Session() self.daemon = True def run(self): while True: last_allowed_timestamp = time.time() - config["instance_lifetime"] for analysis_id, instanceInfo in instanceManager.active.items(): if instanceInfo.last_access < last_allowed_timestamp and instanceInfo.instance_type == "result": print "Terminating result instance %s" % analysis_id analysis = self.session.query(Analysis).get(analysis_id) instanceManager.terminateProcess(analysis) analysis = self.session.query(Analysis).filter_by(status="QUEUE").order_by(Analysis.submit_time).first() if analysis == None: time.sleep(1) else: #Launch HoneyProxy instanceManager.spawnInstance(analysis,"listener") analysis.status = "ACTIVE" self.session.commit() # Reset VM and start it try: subprocess.call(config["VBoxManage"] + ["controlvm", config["VMName"], "poweroff"]) except: pass subprocess.call(config["VBoxManage"] + ["snapshot", config["VMName"], "restorecurrent"]) subprocess.check_call(config["VBoxManage"] + ["startvm", config["VMName"],"--type","headless"]) #Launch URL params = (config["VBoxManage"] + ["guestcontrol", config["VMName"], "exec"] + config["VMStart"] + [analysis.url]) subprocess.call(params) print "Site opened." time.sleep(config["analysis_duration"]) #Shut down VM subprocess.call(config["VBoxManage"] + ["controlvm", config["VMName"], "poweroff"]) #Finish HoneyProxy # dirty workaround: terminate the instance to free up the proxy server. # restart a resultinstance on the same ports afterwards instanceInfo = instanceManager.getInstance(analysis) instanceManager.terminateProcess(analysis) instanceManager.spawnInstance(analysis, "result", instanceInfo.apiport, instanceInfo.guiport) analysis.status = "FINISHED" self.session.commit() instanceManager = HoneyProxyInstanceManager() request_queue = collections.deque(maxlen=50) requesthandler = RequestHandler().start() if __name__ == "__main__": app.run(reloader=config["debug"],server=wsgiserver, port=config["port"],host="0.0.0.0")
"-s","./resources/suppresswinupdate.py",
random_line_split
honeyproxyserver.py
from wsgiref.simple_server import make_server import bottle, json, threading, time, subprocess, collections, sys, os, datetime, IPy, re, time, urllib from bottle import Bottle, static_file, request, redirect, PasteServer as wsgiserver, response from bottle.ext import sqlalchemy as bottlealchemy from jinja2 import Environment, FileSystemLoader from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, Column, DateTime, String, Boolean, Integer, Enum from sqlalchemy.orm import sessionmaker from sqlalchemy.orm.session import object_session from sqlalchemy.pool import QueuePool from recaptcha.client import captcha from subprocess import PIPE, STDOUT with open("config.json","r") as f: config = json.loads(f.read()) if not os.path.isdir(config["logdir"]): os.makedirs(config["logdir"]) engine = create_engine('sqlite:///honeyproxy.sqlite', echo=False) Session = sessionmaker(bind=engine) #session = Session() Base = declarative_base() class Analysis(Base): __tablename__ = 'analysis' id = Column(String, primary_key=True, default=lambda: os.urandom(8).encode('hex')) url = Column(String, nullable=False) request_count = Column(Integer) submit_time = Column(DateTime, default=datetime.datetime.now) status = Column(Enum("QUEUE","ACTIVE","FINISHED"), default="QUEUE") @property def analysis_size(self): if self.status == "QUEUE" or not os.path.isfile(self.getDumpfileLocation()): return 0 else: return os.path.getsize(self.getDumpfileLocation()) @property def queue_position(self): if self.status != "QUEUE": return -1 return 1 + object_session(self).query(Analysis).filter_by(status="QUEUE").filter(Analysis.submit_time < self.submit_time).count() def getDumpfileLocation(self): return os.path.join(config["dumpdir"],self.id) def __repr__(self): return "<Analysis('%s','%s','%s')>" % (self.id,self.url,str(self.status)) def as_dict(self): ret = {c.name: getattr(self, c.name) for c in self.__table__.columns} ret["analysis_size"] = self.analysis_size ret["queue_position"] = self.queue_position return ret def as_htmlsafe_dict(self): ret = self.as_dict() ret["submit_time"] = ret["submit_time"].isoformat() ret["url"] = urllib.quote(ret["url"],safe='~@#$&()*!+=:;,.?/\'') return ret __mapper_args__ = { 'order_by' :[submit_time.desc()] } Base.metadata.create_all(engine) bottle.debug(config["debug"]) app = Bottle() app.install(bottlealchemy.Plugin(engine,keyword='session')) template_env = Environment(loader=FileSystemLoader("./templates")) @app.route('/static/<filepath:path>') def serve_static(filepath): resp = static_file(filepath, root='./static') resp.set_header('Cache-Control','public, max-age=3600') return resp @app.route('/favicon.ico') def favicon(): return static_file('/favicon.ico', root='./static') @app.route('/') def main(session): analyses = session.query(Analysis).filter(Analysis.status != "QUEUE").slice(0,20).all() analyses = json.dumps(list(a.as_htmlsafe_dict() for a in analyses)) template = template_env.get_template('index.html') return template.render(analyses=analyses) @app.route('/analysis/<analysis_id:re:[a-z0-9]+>') def analysis(analysis_id,session): analysis = session.query(Analysis).get(analysis_id) if not analysis: abort(404, "No such analysis.") if analysis.status == "QUEUE": template = template_env.get_template('queue.html') return template.render(data=json.dumps(api_analysis(analysis_id))) else: instance = instanceManager.getInstance(analysis) template = template_env.get_template('appframe.html') return template.render( url="http://"+request.urlparts.netloc.split(":")[0]+":"+str(instance.guiport)+"/app/", analysis_url=analysis.url) @app.post('/api/search') def api_search(session): url = request.forms.get('url') if url: matches = session.query(Analysis).filter( Analysis.url.like("%"+request.forms.get('url')+"%")).slice(0,50).all() return {"results": list(a.as_htmlsafe_dict() for a in matches)} else: return{"error":"no url specified"} @app.route('/api/analysis/<analysis_id:re:[a-z0-9]+>') def api_analysis(analysis_id,session): analysis = session.query(Analysis).get(analysis_id) if not analysis: return {"error":"not found"} else:
@app.post('/api/analyze') def api_analyze(session): response = captcha.submit( request.forms.get(r'recaptcha_challenge_field'), request.forms.get('recaptcha_response_field'), config["recaptcha"]["privatekey"], request.environ.get('REMOTE_ADDR') ) if not response.is_valid: return {"success": False, "msg": "invalid captcha"} else: url = request.forms.get("url") if not re.match("^(https?://)?[a-zA-Z0-9_\\-\\.]+\\.[a-zA-Z0-9]+(:\d+)?(/.*)?$",url): return {"success": False, "msg": "invalid url"} if not url.lower().startswith("http"): url = "http://"+url analysis = Analysis(url=url) session.add(analysis) session.commit() return analysis.as_htmlsafe_dict() # Notice: The code below is a proof of concept. # It is incredibly hacky and badly designed. Spawning N instances of HoneyProxy is downright silly. # So, why did I commit this crime? # The HoneyProxy dump format will get a complete overhaul very soon. # Anything I implemented here will get obsolete with these changes, # so this code just serves us as a bad PoC. Not as a base to build on. class InstanceInfo(object): def __init__(self, instance_type, handle, apiport, guiport): self.instance_type = instance_type self.handle = handle self.apiport = apiport self.guiport = guiport self.starttime = time.time() self.last_access = self.starttime def __repr__(self): return "Instance<%s,%d,%d,%d>" % (self.instance_type, self.apiport, self.guiport, self.starttime) class HoneyProxyInstanceManager(object): def __init__(self): self.active = {} self.ports = set((8200+i for i in range(0,800))) def getInstance(self, analysis): if analysis.id in self.active: instanceInfo = self.active[analysis.id] instanceInfo.last_access = time.time() return instanceInfo return self.spawnInstance(analysis,"result") def _getPorts(self, apiport=None, guiport=None): if apiport: self.ports.remove(apiport) else: apiport = self.ports.pop() if guiport: self.ports.remove(guiport) else: guiport = self.ports.pop() return apiport, guiport def spawnInstance(self, analysis, instance_type, apiport=None, guiport=None): apiport, guiport = self._getPorts(apiport, guiport) print "Spawn %s instance(%d, %d)..." % (instance_type, apiport, guiport) args = (config["HoneyProxy"] + [ "--api-auth", "NO_AUTH", "--apiport", str(apiport), "--guiport", str(guiport), "--no-gui", "--readonly" ]) if instance_type == "listener": args.extend( [ "-w", analysis.getDumpfileLocation(), "-p","8100", "-T", "-s","./resources/suppresswinupdate.py", "-Z","5m"]) else: args.extend( [ "-r", analysis.getDumpfileLocation(), "-n", "--readonly"]) p = subprocess.Popen(args, stdout=PIPE, stderr=STDOUT) out = p.stdout.readline() if out != "HoneyProxy has been started!\n": raise RuntimeError("Couldn't start HoneyProxy: %s" % out+p.stdout.read()) self.active[analysis.id] = InstanceInfo(instance_type, p, apiport, guiport) return self.active[analysis.id] def terminateProcess(self, analysis): data = self.active[analysis.id] logfile = os.path.join(config["logdir"], analysis.id + ".log") data.handle.terminate() with open(logfile, "a") as f: f.write("\n\n"+str(data)+"\n\n") f.write(data.handle.stdout.read()) self.ports.add(data.apiport) self.ports.add(data.guiport) del self.active[analysis.id] class RequestHandler(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.session = Session() self.daemon = True def run(self): while True: last_allowed_timestamp = time.time() - config["instance_lifetime"] for analysis_id, instanceInfo in instanceManager.active.items(): if instanceInfo.last_access < last_allowed_timestamp and instanceInfo.instance_type == "result": print "Terminating result instance %s" % analysis_id analysis = self.session.query(Analysis).get(analysis_id) instanceManager.terminateProcess(analysis) analysis = self.session.query(Analysis).filter_by(status="QUEUE").order_by(Analysis.submit_time).first() if analysis == None: time.sleep(1) else: #Launch HoneyProxy instanceManager.spawnInstance(analysis,"listener") analysis.status = "ACTIVE" self.session.commit() # Reset VM and start it try: subprocess.call(config["VBoxManage"] + ["controlvm", config["VMName"], "poweroff"]) except: pass subprocess.call(config["VBoxManage"] + ["snapshot", config["VMName"], "restorecurrent"]) subprocess.check_call(config["VBoxManage"] + ["startvm", config["VMName"],"--type","headless"]) #Launch URL params = (config["VBoxManage"] + ["guestcontrol", config["VMName"], "exec"] + config["VMStart"] + [analysis.url]) subprocess.call(params) print "Site opened." time.sleep(config["analysis_duration"]) #Shut down VM subprocess.call(config["VBoxManage"] + ["controlvm", config["VMName"], "poweroff"]) #Finish HoneyProxy # dirty workaround: terminate the instance to free up the proxy server. # restart a resultinstance on the same ports afterwards instanceInfo = instanceManager.getInstance(analysis) instanceManager.terminateProcess(analysis) instanceManager.spawnInstance(analysis, "result", instanceInfo.apiport, instanceInfo.guiport) analysis.status = "FINISHED" self.session.commit() instanceManager = HoneyProxyInstanceManager() request_queue = collections.deque(maxlen=50) requesthandler = RequestHandler().start() if __name__ == "__main__": app.run(reloader=config["debug"],server=wsgiserver, port=config["port"],host="0.0.0.0")
return analysis.as_htmlsafe_dict()
conditional_block
file_test.go
// Copyright 2016 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package file import ( "context" "encoding/json" "io" "os" "path/filepath" "sort" "sync" "testing" "time" "github.com/prometheus/common/model" "github.com/stretchr/testify/require" "go.uber.org/goleak" "github.com/prometheus/prometheus/discovery/targetgroup" ) func TestMain(m *testing.M) { goleak.VerifyTestMain(m) } const defaultWait = time.Second type testRunner struct { *testing.T dir string ch chan []*targetgroup.Group done, stopped chan struct{} cancelSD context.CancelFunc mtx sync.Mutex tgs map[string]*targetgroup.Group receivedAt time.Time } func newTestRunner(t *testing.T) *testRunner { t.Helper() return &testRunner{ T: t, dir: t.TempDir(), ch: make(chan []*targetgroup.Group), done: make(chan struct{}), stopped: make(chan struct{}), tgs: make(map[string]*targetgroup.Group), } } // copyFile atomically copies a file to the runner's directory. func (t *testRunner) copyFile(src string) string { t.Helper() return t.copyFileTo(src, filepath.Base(src)) } // copyFileTo atomically copies a file with a different name to the runner's directory. func (t *testRunner) copyFileTo(src, name string) string { t.Helper() newf, err := os.CreateTemp(t.dir, "") require.NoError(t, err) f, err := os.Open(src) require.NoError(t, err) _, err = io.Copy(newf, f) require.NoError(t, err) require.NoError(t, f.Close()) require.NoError(t, newf.Close()) dst := filepath.Join(t.dir, name) err = os.Rename(newf.Name(), dst) require.NoError(t, err) return dst } // writeString writes atomically a string to a file. func (t *testRunner) writeString(file, data string) { t.Helper() newf, err := os.CreateTemp(t.dir, "") require.NoError(t, err) _, err = newf.WriteString(data) require.NoError(t, err) require.NoError(t, newf.Close()) err = os.Rename(newf.Name(), file) require.NoError(t, err) } // appendString appends a string to a file. func (t *testRunner) appendString(file, data string) { t.Helper() f, err := os.OpenFile(file, os.O_WRONLY|os.O_APPEND, 0) require.NoError(t, err) defer f.Close() _, err = f.WriteString(data) require.NoError(t, err) } // run starts the file SD and the loop receiving target groups updates. func (t *testRunner) run(files ...string) { go func() { defer close(t.stopped) for { select { case <-t.done: os.RemoveAll(t.dir) return case tgs := <-t.ch: t.mtx.Lock() t.receivedAt = time.Now() for _, tg := range tgs { t.tgs[tg.Source] = tg } t.mtx.Unlock() } } }() for i := range files { files[i] = filepath.Join(t.dir, files[i]) } ctx, cancel := context.WithCancel(context.Background()) t.cancelSD = cancel go func() { NewDiscovery( &SDConfig{ Files: files, // Setting a high refresh interval to make sure that the tests only // rely on file watches. RefreshInterval: model.Duration(1 * time.Hour), }, nil, ).Run(ctx, t.ch) }() } func (t *testRunner) stop() { t.cancelSD() close(t.done) <-t.stopped } func (t *testRunner) lastReceive() time.Time { t.mtx.Lock() defer t.mtx.Unlock() return t.receivedAt } func (t *testRunner) targets() []*targetgroup.Group { t.mtx.Lock() defer t.mtx.Unlock() var ( keys []string tgs []*targetgroup.Group ) for k := range t.tgs { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { tgs = append(tgs, t.tgs[k]) } return tgs } func (t *testRunner) requireUpdate(ref time.Time, expected []*targetgroup.Group) { t.Helper() for { select { case <-time.After(defaultWait): t.Fatalf("Expected update but got none") return case <-time.After(defaultWait / 10): if ref.Equal(t.lastReceive()) { // No update received. break } // We can receive partial updates so only check the result when the // expected number of groups is reached. tgs := t.targets() if len(tgs) != len(expected) { t.Logf("skipping update: expected %d targets, got %d", len(expected), len(tgs)) break } t.requireTargetGroups(expected, tgs) if ref.After(time.Time{}) { t.Logf("update received after %v", t.lastReceive().Sub(ref)) } return } } } func (t *testRunner) requireTargetGroups(expected, got []*targetgroup.Group) { t.Helper() b1, err := json.Marshal(expected) if err != nil { panic(err) } b2, err := json.Marshal(got) if err != nil { panic(err) } require.Equal(t, string(b1), string(b2)) } // validTg() maps to fixtures/valid.{json,yml}. func validTg(file string) []*targetgroup.Group { return []*targetgroup.Group{ { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("localhost:9090"), }, { model.AddressLabel: model.LabelValue("example.org:443"), }, }, Labels: model.LabelSet{ model.LabelName("foo"): model.LabelValue("bar"), fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 0), }, { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("my.domain"), }, }, Labels: model.LabelSet{ fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 1), }, } } // valid2Tg() maps to fixtures/valid2.{json,yml}. func
(file string) []*targetgroup.Group { return []*targetgroup.Group{ { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("my.domain"), }, }, Labels: model.LabelSet{ fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 0), }, { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("localhost:9090"), }, }, Labels: model.LabelSet{ model.LabelName("foo"): model.LabelValue("bar"), model.LabelName("fred"): model.LabelValue("baz"), fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 1), }, { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("example.org:443"), }, }, Labels: model.LabelSet{ model.LabelName("scheme"): model.LabelValue("https"), fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 2), }, } } func TestInitialUpdate(t *testing.T) { for _, tc := range []string{ "fixtures/valid.yml", "fixtures/valid.json", } { tc := tc t.Run(tc, func(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile(tc) runner.run("*" + filepath.Ext(tc)) defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) }) } } func TestInvalidFile(t *testing.T) { for _, tc := range []string{ "fixtures/invalid_nil.yml", "fixtures/invalid_nil.json", } { tc := tc t.Run(tc, func(t *testing.T) { t.Parallel() now := time.Now() runner := newTestRunner(t) runner.copyFile(tc) runner.run("*" + filepath.Ext(tc)) defer runner.stop() // Verify that we've received nothing. time.Sleep(defaultWait) if runner.lastReceive().After(now) { t.Fatalf("unexpected targets received: %v", runner.targets()) } }) } } func TestNoopFileUpdate(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Verify that we receive an update with the same target groups. ref := runner.lastReceive() runner.copyFileTo("fixtures/valid3.yml", "valid.yml") runner.requireUpdate(ref, validTg(sdFile)) } func TestFileUpdate(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Verify that we receive an update with the new target groups. ref := runner.lastReceive() runner.copyFileTo("fixtures/valid2.yml", "valid.yml") runner.requireUpdate(ref, valid2Tg(sdFile)) } func TestInvalidFileUpdate(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) ref := runner.lastReceive() runner.writeString(sdFile, "]gibberish\n][") // Verify that we receive nothing or the same targets as before. time.Sleep(defaultWait) if runner.lastReceive().After(ref) { runner.requireTargetGroups(validTg(sdFile), runner.targets()) } } func TestUpdateFileWithPartialWrites(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Do a partial write operation. ref := runner.lastReceive() runner.writeString(sdFile, "- targets") time.Sleep(defaultWait) // Verify that we receive nothing or the same target groups as before. if runner.lastReceive().After(ref) { runner.requireTargetGroups(validTg(sdFile), runner.targets()) } // Verify that we receive the update target groups once the file is a valid YAML payload. ref = runner.lastReceive() runner.appendString(sdFile, `: ["localhost:9091"]`) runner.requireUpdate(ref, []*targetgroup.Group{ { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("localhost:9091"), }, }, Labels: model.LabelSet{ fileSDFilepathLabel: model.LabelValue(sdFile), }, Source: fileSource(sdFile, 0), }, { Source: fileSource(sdFile, 1), }, }, ) } func TestRemoveFile(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Verify that we receive the update about the target groups being removed. ref := runner.lastReceive() require.NoError(t, os.Remove(sdFile)) runner.requireUpdate( ref, []*targetgroup.Group{ { Source: fileSource(sdFile, 0), }, { Source: fileSource(sdFile, 1), }, }, ) }
valid2Tg
identifier_name
file_test.go
// Copyright 2016 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package file import ( "context" "encoding/json" "io" "os" "path/filepath" "sort" "sync" "testing" "time" "github.com/prometheus/common/model" "github.com/stretchr/testify/require" "go.uber.org/goleak" "github.com/prometheus/prometheus/discovery/targetgroup" ) func TestMain(m *testing.M) { goleak.VerifyTestMain(m) } const defaultWait = time.Second type testRunner struct { *testing.T dir string ch chan []*targetgroup.Group done, stopped chan struct{} cancelSD context.CancelFunc mtx sync.Mutex tgs map[string]*targetgroup.Group receivedAt time.Time } func newTestRunner(t *testing.T) *testRunner { t.Helper() return &testRunner{ T: t, dir: t.TempDir(), ch: make(chan []*targetgroup.Group), done: make(chan struct{}), stopped: make(chan struct{}), tgs: make(map[string]*targetgroup.Group), } } // copyFile atomically copies a file to the runner's directory. func (t *testRunner) copyFile(src string) string { t.Helper() return t.copyFileTo(src, filepath.Base(src)) } // copyFileTo atomically copies a file with a different name to the runner's directory. func (t *testRunner) copyFileTo(src, name string) string { t.Helper() newf, err := os.CreateTemp(t.dir, "") require.NoError(t, err) f, err := os.Open(src) require.NoError(t, err) _, err = io.Copy(newf, f) require.NoError(t, err) require.NoError(t, f.Close()) require.NoError(t, newf.Close()) dst := filepath.Join(t.dir, name) err = os.Rename(newf.Name(), dst) require.NoError(t, err) return dst } // writeString writes atomically a string to a file. func (t *testRunner) writeString(file, data string) { t.Helper() newf, err := os.CreateTemp(t.dir, "") require.NoError(t, err) _, err = newf.WriteString(data) require.NoError(t, err) require.NoError(t, newf.Close()) err = os.Rename(newf.Name(), file) require.NoError(t, err) } // appendString appends a string to a file. func (t *testRunner) appendString(file, data string) { t.Helper() f, err := os.OpenFile(file, os.O_WRONLY|os.O_APPEND, 0) require.NoError(t, err) defer f.Close() _, err = f.WriteString(data) require.NoError(t, err) } // run starts the file SD and the loop receiving target groups updates. func (t *testRunner) run(files ...string) { go func() { defer close(t.stopped) for { select { case <-t.done: os.RemoveAll(t.dir) return case tgs := <-t.ch: t.mtx.Lock() t.receivedAt = time.Now() for _, tg := range tgs { t.tgs[tg.Source] = tg } t.mtx.Unlock() } } }() for i := range files { files[i] = filepath.Join(t.dir, files[i]) } ctx, cancel := context.WithCancel(context.Background()) t.cancelSD = cancel go func() { NewDiscovery( &SDConfig{ Files: files, // Setting a high refresh interval to make sure that the tests only // rely on file watches. RefreshInterval: model.Duration(1 * time.Hour), }, nil, ).Run(ctx, t.ch) }() } func (t *testRunner) stop() { t.cancelSD() close(t.done) <-t.stopped } func (t *testRunner) lastReceive() time.Time { t.mtx.Lock() defer t.mtx.Unlock() return t.receivedAt } func (t *testRunner) targets() []*targetgroup.Group { t.mtx.Lock() defer t.mtx.Unlock() var ( keys []string tgs []*targetgroup.Group ) for k := range t.tgs { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { tgs = append(tgs, t.tgs[k]) } return tgs } func (t *testRunner) requireUpdate(ref time.Time, expected []*targetgroup.Group) { t.Helper() for { select { case <-time.After(defaultWait): t.Fatalf("Expected update but got none") return case <-time.After(defaultWait / 10): if ref.Equal(t.lastReceive()) { // No update received. break } // We can receive partial updates so only check the result when the // expected number of groups is reached. tgs := t.targets() if len(tgs) != len(expected) { t.Logf("skipping update: expected %d targets, got %d", len(expected), len(tgs)) break } t.requireTargetGroups(expected, tgs) if ref.After(time.Time{}) { t.Logf("update received after %v", t.lastReceive().Sub(ref)) } return } } } func (t *testRunner) requireTargetGroups(expected, got []*targetgroup.Group) { t.Helper() b1, err := json.Marshal(expected) if err != nil { panic(err) } b2, err := json.Marshal(got) if err != nil { panic(err) } require.Equal(t, string(b1), string(b2)) } // validTg() maps to fixtures/valid.{json,yml}. func validTg(file string) []*targetgroup.Group { return []*targetgroup.Group{ { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("localhost:9090"), }, { model.AddressLabel: model.LabelValue("example.org:443"), }, }, Labels: model.LabelSet{ model.LabelName("foo"): model.LabelValue("bar"), fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 0), }, { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("my.domain"), }, }, Labels: model.LabelSet{ fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 1), }, } } // valid2Tg() maps to fixtures/valid2.{json,yml}. func valid2Tg(file string) []*targetgroup.Group { return []*targetgroup.Group{ { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("my.domain"), }, }, Labels: model.LabelSet{ fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 0), }, { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("localhost:9090"), }, }, Labels: model.LabelSet{ model.LabelName("foo"): model.LabelValue("bar"), model.LabelName("fred"): model.LabelValue("baz"), fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 1), }, { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("example.org:443"), }, }, Labels: model.LabelSet{ model.LabelName("scheme"): model.LabelValue("https"), fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 2), }, } } func TestInitialUpdate(t *testing.T) { for _, tc := range []string{ "fixtures/valid.yml", "fixtures/valid.json", } { tc := tc t.Run(tc, func(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile(tc) runner.run("*" + filepath.Ext(tc)) defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) }) } } func TestInvalidFile(t *testing.T) { for _, tc := range []string{ "fixtures/invalid_nil.yml", "fixtures/invalid_nil.json", } { tc := tc t.Run(tc, func(t *testing.T) { t.Parallel() now := time.Now() runner := newTestRunner(t) runner.copyFile(tc) runner.run("*" + filepath.Ext(tc)) defer runner.stop() // Verify that we've received nothing. time.Sleep(defaultWait) if runner.lastReceive().After(now) {
} } func TestNoopFileUpdate(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Verify that we receive an update with the same target groups. ref := runner.lastReceive() runner.copyFileTo("fixtures/valid3.yml", "valid.yml") runner.requireUpdate(ref, validTg(sdFile)) } func TestFileUpdate(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Verify that we receive an update with the new target groups. ref := runner.lastReceive() runner.copyFileTo("fixtures/valid2.yml", "valid.yml") runner.requireUpdate(ref, valid2Tg(sdFile)) } func TestInvalidFileUpdate(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) ref := runner.lastReceive() runner.writeString(sdFile, "]gibberish\n][") // Verify that we receive nothing or the same targets as before. time.Sleep(defaultWait) if runner.lastReceive().After(ref) { runner.requireTargetGroups(validTg(sdFile), runner.targets()) } } func TestUpdateFileWithPartialWrites(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Do a partial write operation. ref := runner.lastReceive() runner.writeString(sdFile, "- targets") time.Sleep(defaultWait) // Verify that we receive nothing or the same target groups as before. if runner.lastReceive().After(ref) { runner.requireTargetGroups(validTg(sdFile), runner.targets()) } // Verify that we receive the update target groups once the file is a valid YAML payload. ref = runner.lastReceive() runner.appendString(sdFile, `: ["localhost:9091"]`) runner.requireUpdate(ref, []*targetgroup.Group{ { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("localhost:9091"), }, }, Labels: model.LabelSet{ fileSDFilepathLabel: model.LabelValue(sdFile), }, Source: fileSource(sdFile, 0), }, { Source: fileSource(sdFile, 1), }, }, ) } func TestRemoveFile(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Verify that we receive the update about the target groups being removed. ref := runner.lastReceive() require.NoError(t, os.Remove(sdFile)) runner.requireUpdate( ref, []*targetgroup.Group{ { Source: fileSource(sdFile, 0), }, { Source: fileSource(sdFile, 1), }, }, ) }
t.Fatalf("unexpected targets received: %v", runner.targets()) } })
random_line_split
file_test.go
// Copyright 2016 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package file import ( "context" "encoding/json" "io" "os" "path/filepath" "sort" "sync" "testing" "time" "github.com/prometheus/common/model" "github.com/stretchr/testify/require" "go.uber.org/goleak" "github.com/prometheus/prometheus/discovery/targetgroup" ) func TestMain(m *testing.M) { goleak.VerifyTestMain(m) } const defaultWait = time.Second type testRunner struct { *testing.T dir string ch chan []*targetgroup.Group done, stopped chan struct{} cancelSD context.CancelFunc mtx sync.Mutex tgs map[string]*targetgroup.Group receivedAt time.Time } func newTestRunner(t *testing.T) *testRunner { t.Helper() return &testRunner{ T: t, dir: t.TempDir(), ch: make(chan []*targetgroup.Group), done: make(chan struct{}), stopped: make(chan struct{}), tgs: make(map[string]*targetgroup.Group), } } // copyFile atomically copies a file to the runner's directory. func (t *testRunner) copyFile(src string) string { t.Helper() return t.copyFileTo(src, filepath.Base(src)) } // copyFileTo atomically copies a file with a different name to the runner's directory. func (t *testRunner) copyFileTo(src, name string) string { t.Helper() newf, err := os.CreateTemp(t.dir, "") require.NoError(t, err) f, err := os.Open(src) require.NoError(t, err) _, err = io.Copy(newf, f) require.NoError(t, err) require.NoError(t, f.Close()) require.NoError(t, newf.Close()) dst := filepath.Join(t.dir, name) err = os.Rename(newf.Name(), dst) require.NoError(t, err) return dst } // writeString writes atomically a string to a file. func (t *testRunner) writeString(file, data string) { t.Helper() newf, err := os.CreateTemp(t.dir, "") require.NoError(t, err) _, err = newf.WriteString(data) require.NoError(t, err) require.NoError(t, newf.Close()) err = os.Rename(newf.Name(), file) require.NoError(t, err) } // appendString appends a string to a file. func (t *testRunner) appendString(file, data string) { t.Helper() f, err := os.OpenFile(file, os.O_WRONLY|os.O_APPEND, 0) require.NoError(t, err) defer f.Close() _, err = f.WriteString(data) require.NoError(t, err) } // run starts the file SD and the loop receiving target groups updates. func (t *testRunner) run(files ...string) { go func() { defer close(t.stopped) for
}() for i := range files { files[i] = filepath.Join(t.dir, files[i]) } ctx, cancel := context.WithCancel(context.Background()) t.cancelSD = cancel go func() { NewDiscovery( &SDConfig{ Files: files, // Setting a high refresh interval to make sure that the tests only // rely on file watches. RefreshInterval: model.Duration(1 * time.Hour), }, nil, ).Run(ctx, t.ch) }() } func (t *testRunner) stop() { t.cancelSD() close(t.done) <-t.stopped } func (t *testRunner) lastReceive() time.Time { t.mtx.Lock() defer t.mtx.Unlock() return t.receivedAt } func (t *testRunner) targets() []*targetgroup.Group { t.mtx.Lock() defer t.mtx.Unlock() var ( keys []string tgs []*targetgroup.Group ) for k := range t.tgs { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { tgs = append(tgs, t.tgs[k]) } return tgs } func (t *testRunner) requireUpdate(ref time.Time, expected []*targetgroup.Group) { t.Helper() for { select { case <-time.After(defaultWait): t.Fatalf("Expected update but got none") return case <-time.After(defaultWait / 10): if ref.Equal(t.lastReceive()) { // No update received. break } // We can receive partial updates so only check the result when the // expected number of groups is reached. tgs := t.targets() if len(tgs) != len(expected) { t.Logf("skipping update: expected %d targets, got %d", len(expected), len(tgs)) break } t.requireTargetGroups(expected, tgs) if ref.After(time.Time{}) { t.Logf("update received after %v", t.lastReceive().Sub(ref)) } return } } } func (t *testRunner) requireTargetGroups(expected, got []*targetgroup.Group) { t.Helper() b1, err := json.Marshal(expected) if err != nil { panic(err) } b2, err := json.Marshal(got) if err != nil { panic(err) } require.Equal(t, string(b1), string(b2)) } // validTg() maps to fixtures/valid.{json,yml}. func validTg(file string) []*targetgroup.Group { return []*targetgroup.Group{ { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("localhost:9090"), }, { model.AddressLabel: model.LabelValue("example.org:443"), }, }, Labels: model.LabelSet{ model.LabelName("foo"): model.LabelValue("bar"), fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 0), }, { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("my.domain"), }, }, Labels: model.LabelSet{ fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 1), }, } } // valid2Tg() maps to fixtures/valid2.{json,yml}. func valid2Tg(file string) []*targetgroup.Group { return []*targetgroup.Group{ { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("my.domain"), }, }, Labels: model.LabelSet{ fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 0), }, { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("localhost:9090"), }, }, Labels: model.LabelSet{ model.LabelName("foo"): model.LabelValue("bar"), model.LabelName("fred"): model.LabelValue("baz"), fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 1), }, { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("example.org:443"), }, }, Labels: model.LabelSet{ model.LabelName("scheme"): model.LabelValue("https"), fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 2), }, } } func TestInitialUpdate(t *testing.T) { for _, tc := range []string{ "fixtures/valid.yml", "fixtures/valid.json", } { tc := tc t.Run(tc, func(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile(tc) runner.run("*" + filepath.Ext(tc)) defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) }) } } func TestInvalidFile(t *testing.T) { for _, tc := range []string{ "fixtures/invalid_nil.yml", "fixtures/invalid_nil.json", } { tc := tc t.Run(tc, func(t *testing.T) { t.Parallel() now := time.Now() runner := newTestRunner(t) runner.copyFile(tc) runner.run("*" + filepath.Ext(tc)) defer runner.stop() // Verify that we've received nothing. time.Sleep(defaultWait) if runner.lastReceive().After(now) { t.Fatalf("unexpected targets received: %v", runner.targets()) } }) } } func TestNoopFileUpdate(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Verify that we receive an update with the same target groups. ref := runner.lastReceive() runner.copyFileTo("fixtures/valid3.yml", "valid.yml") runner.requireUpdate(ref, validTg(sdFile)) } func TestFileUpdate(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Verify that we receive an update with the new target groups. ref := runner.lastReceive() runner.copyFileTo("fixtures/valid2.yml", "valid.yml") runner.requireUpdate(ref, valid2Tg(sdFile)) } func TestInvalidFileUpdate(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) ref := runner.lastReceive() runner.writeString(sdFile, "]gibberish\n][") // Verify that we receive nothing or the same targets as before. time.Sleep(defaultWait) if runner.lastReceive().After(ref) { runner.requireTargetGroups(validTg(sdFile), runner.targets()) } } func TestUpdateFileWithPartialWrites(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Do a partial write operation. ref := runner.lastReceive() runner.writeString(sdFile, "- targets") time.Sleep(defaultWait) // Verify that we receive nothing or the same target groups as before. if runner.lastReceive().After(ref) { runner.requireTargetGroups(validTg(sdFile), runner.targets()) } // Verify that we receive the update target groups once the file is a valid YAML payload. ref = runner.lastReceive() runner.appendString(sdFile, `: ["localhost:9091"]`) runner.requireUpdate(ref, []*targetgroup.Group{ { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("localhost:9091"), }, }, Labels: model.LabelSet{ fileSDFilepathLabel: model.LabelValue(sdFile), }, Source: fileSource(sdFile, 0), }, { Source: fileSource(sdFile, 1), }, }, ) } func TestRemoveFile(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Verify that we receive the update about the target groups being removed. ref := runner.lastReceive() require.NoError(t, os.Remove(sdFile)) runner.requireUpdate( ref, []*targetgroup.Group{ { Source: fileSource(sdFile, 0), }, { Source: fileSource(sdFile, 1), }, }, ) }
{ select { case <-t.done: os.RemoveAll(t.dir) return case tgs := <-t.ch: t.mtx.Lock() t.receivedAt = time.Now() for _, tg := range tgs { t.tgs[tg.Source] = tg } t.mtx.Unlock() } }
conditional_block
file_test.go
// Copyright 2016 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package file import ( "context" "encoding/json" "io" "os" "path/filepath" "sort" "sync" "testing" "time" "github.com/prometheus/common/model" "github.com/stretchr/testify/require" "go.uber.org/goleak" "github.com/prometheus/prometheus/discovery/targetgroup" ) func TestMain(m *testing.M) { goleak.VerifyTestMain(m) } const defaultWait = time.Second type testRunner struct { *testing.T dir string ch chan []*targetgroup.Group done, stopped chan struct{} cancelSD context.CancelFunc mtx sync.Mutex tgs map[string]*targetgroup.Group receivedAt time.Time } func newTestRunner(t *testing.T) *testRunner { t.Helper() return &testRunner{ T: t, dir: t.TempDir(), ch: make(chan []*targetgroup.Group), done: make(chan struct{}), stopped: make(chan struct{}), tgs: make(map[string]*targetgroup.Group), } } // copyFile atomically copies a file to the runner's directory. func (t *testRunner) copyFile(src string) string { t.Helper() return t.copyFileTo(src, filepath.Base(src)) } // copyFileTo atomically copies a file with a different name to the runner's directory. func (t *testRunner) copyFileTo(src, name string) string { t.Helper() newf, err := os.CreateTemp(t.dir, "") require.NoError(t, err) f, err := os.Open(src) require.NoError(t, err) _, err = io.Copy(newf, f) require.NoError(t, err) require.NoError(t, f.Close()) require.NoError(t, newf.Close()) dst := filepath.Join(t.dir, name) err = os.Rename(newf.Name(), dst) require.NoError(t, err) return dst } // writeString writes atomically a string to a file. func (t *testRunner) writeString(file, data string) { t.Helper() newf, err := os.CreateTemp(t.dir, "") require.NoError(t, err) _, err = newf.WriteString(data) require.NoError(t, err) require.NoError(t, newf.Close()) err = os.Rename(newf.Name(), file) require.NoError(t, err) } // appendString appends a string to a file. func (t *testRunner) appendString(file, data string) { t.Helper() f, err := os.OpenFile(file, os.O_WRONLY|os.O_APPEND, 0) require.NoError(t, err) defer f.Close() _, err = f.WriteString(data) require.NoError(t, err) } // run starts the file SD and the loop receiving target groups updates. func (t *testRunner) run(files ...string) { go func() { defer close(t.stopped) for { select { case <-t.done: os.RemoveAll(t.dir) return case tgs := <-t.ch: t.mtx.Lock() t.receivedAt = time.Now() for _, tg := range tgs { t.tgs[tg.Source] = tg } t.mtx.Unlock() } } }() for i := range files { files[i] = filepath.Join(t.dir, files[i]) } ctx, cancel := context.WithCancel(context.Background()) t.cancelSD = cancel go func() { NewDiscovery( &SDConfig{ Files: files, // Setting a high refresh interval to make sure that the tests only // rely on file watches. RefreshInterval: model.Duration(1 * time.Hour), }, nil, ).Run(ctx, t.ch) }() } func (t *testRunner) stop() { t.cancelSD() close(t.done) <-t.stopped } func (t *testRunner) lastReceive() time.Time { t.mtx.Lock() defer t.mtx.Unlock() return t.receivedAt } func (t *testRunner) targets() []*targetgroup.Group { t.mtx.Lock() defer t.mtx.Unlock() var ( keys []string tgs []*targetgroup.Group ) for k := range t.tgs { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { tgs = append(tgs, t.tgs[k]) } return tgs } func (t *testRunner) requireUpdate(ref time.Time, expected []*targetgroup.Group) { t.Helper() for { select { case <-time.After(defaultWait): t.Fatalf("Expected update but got none") return case <-time.After(defaultWait / 10): if ref.Equal(t.lastReceive()) { // No update received. break } // We can receive partial updates so only check the result when the // expected number of groups is reached. tgs := t.targets() if len(tgs) != len(expected) { t.Logf("skipping update: expected %d targets, got %d", len(expected), len(tgs)) break } t.requireTargetGroups(expected, tgs) if ref.After(time.Time{}) { t.Logf("update received after %v", t.lastReceive().Sub(ref)) } return } } } func (t *testRunner) requireTargetGroups(expected, got []*targetgroup.Group) { t.Helper() b1, err := json.Marshal(expected) if err != nil { panic(err) } b2, err := json.Marshal(got) if err != nil { panic(err) } require.Equal(t, string(b1), string(b2)) } // validTg() maps to fixtures/valid.{json,yml}. func validTg(file string) []*targetgroup.Group { return []*targetgroup.Group{ { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("localhost:9090"), }, { model.AddressLabel: model.LabelValue("example.org:443"), }, }, Labels: model.LabelSet{ model.LabelName("foo"): model.LabelValue("bar"), fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 0), }, { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("my.domain"), }, }, Labels: model.LabelSet{ fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 1), }, } } // valid2Tg() maps to fixtures/valid2.{json,yml}. func valid2Tg(file string) []*targetgroup.Group { return []*targetgroup.Group{ { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("my.domain"), }, }, Labels: model.LabelSet{ fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 0), }, { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("localhost:9090"), }, }, Labels: model.LabelSet{ model.LabelName("foo"): model.LabelValue("bar"), model.LabelName("fred"): model.LabelValue("baz"), fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 1), }, { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("example.org:443"), }, }, Labels: model.LabelSet{ model.LabelName("scheme"): model.LabelValue("https"), fileSDFilepathLabel: model.LabelValue(file), }, Source: fileSource(file, 2), }, } } func TestInitialUpdate(t *testing.T)
func TestInvalidFile(t *testing.T) { for _, tc := range []string{ "fixtures/invalid_nil.yml", "fixtures/invalid_nil.json", } { tc := tc t.Run(tc, func(t *testing.T) { t.Parallel() now := time.Now() runner := newTestRunner(t) runner.copyFile(tc) runner.run("*" + filepath.Ext(tc)) defer runner.stop() // Verify that we've received nothing. time.Sleep(defaultWait) if runner.lastReceive().After(now) { t.Fatalf("unexpected targets received: %v", runner.targets()) } }) } } func TestNoopFileUpdate(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Verify that we receive an update with the same target groups. ref := runner.lastReceive() runner.copyFileTo("fixtures/valid3.yml", "valid.yml") runner.requireUpdate(ref, validTg(sdFile)) } func TestFileUpdate(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Verify that we receive an update with the new target groups. ref := runner.lastReceive() runner.copyFileTo("fixtures/valid2.yml", "valid.yml") runner.requireUpdate(ref, valid2Tg(sdFile)) } func TestInvalidFileUpdate(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) ref := runner.lastReceive() runner.writeString(sdFile, "]gibberish\n][") // Verify that we receive nothing or the same targets as before. time.Sleep(defaultWait) if runner.lastReceive().After(ref) { runner.requireTargetGroups(validTg(sdFile), runner.targets()) } } func TestUpdateFileWithPartialWrites(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Do a partial write operation. ref := runner.lastReceive() runner.writeString(sdFile, "- targets") time.Sleep(defaultWait) // Verify that we receive nothing or the same target groups as before. if runner.lastReceive().After(ref) { runner.requireTargetGroups(validTg(sdFile), runner.targets()) } // Verify that we receive the update target groups once the file is a valid YAML payload. ref = runner.lastReceive() runner.appendString(sdFile, `: ["localhost:9091"]`) runner.requireUpdate(ref, []*targetgroup.Group{ { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("localhost:9091"), }, }, Labels: model.LabelSet{ fileSDFilepathLabel: model.LabelValue(sdFile), }, Source: fileSource(sdFile, 0), }, { Source: fileSource(sdFile, 1), }, }, ) } func TestRemoveFile(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile("fixtures/valid.yml") runner.run("*.yml") defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) // Verify that we receive the update about the target groups being removed. ref := runner.lastReceive() require.NoError(t, os.Remove(sdFile)) runner.requireUpdate( ref, []*targetgroup.Group{ { Source: fileSource(sdFile, 0), }, { Source: fileSource(sdFile, 1), }, }, ) }
{ for _, tc := range []string{ "fixtures/valid.yml", "fixtures/valid.json", } { tc := tc t.Run(tc, func(t *testing.T) { t.Parallel() runner := newTestRunner(t) sdFile := runner.copyFile(tc) runner.run("*" + filepath.Ext(tc)) defer runner.stop() // Verify that we receive the initial target groups. runner.requireUpdate(time.Time{}, validTg(sdFile)) }) } }
identifier_body
main.rs
use std::fs::File; use std::io::Write; use std::str; use std::collections::HashMap; use std::mem; use std::fmt; use std::thread; use std::sync::mpsc; use std::sync::{Mutex, Arc}; use std::time::Duration; use std::io::Read; use std::collections::HashSet; extern crate bio; extern crate clap; extern crate flate2; extern crate log; extern crate simple_logger; use clap::{Arg, App}; use bio::alignment::pairwise::Aligner; use bio::alignment::Alignment; use bio::io::fastq; use bio::alphabets::dna::revcomp; use log::{info}; use flate2::read::GzDecoder; const SEQ_NT4_TABLE: [u64; 256] = [ 0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ]; const IDX_TABLE: [u8; 4] = [ b'A', b'C', b'G', b'T' ]; fn
(seq: &[u8]) -> Result<u64, &str> { let mut res: u64 = 0; let mut res_rc: u64 = 0; let end = seq.len() - 1; for i in 0..seq.len() { if i >= 32 { return Err("Seq can't longer than 32.") } let m = SEQ_NT4_TABLE[seq[i] as usize]; res |= m << i*2; res_rc |= (3 - m) << (end - i)*2; } if res > res_rc { mem::swap(&mut res, &mut res_rc) }; Ok(res) } fn recover_seq(code: u64, k: u8) -> String { let mut chars: Vec<u8> = Vec::with_capacity(k as usize); for i in 0..k { let mask: u64 = 3 << (i*2); let idx = (code & mask) >> (i*2); let b = IDX_TABLE[idx as usize]; chars.push(b); } String::from_utf8(chars).unwrap() } enum ExtractRes { Ok(String, String), ScoreTooLow, LeftTooShort, RightTooShort, } fn extract_pet(seq: &[u8], pattern: &[u8], flanking: u8, score_ratio_thresh: f32) -> (ExtractRes, Alignment) { // align linker to read let score = |a: u8, b: u8| if a == b {1i32} else {-1i32}; let mut aligner = Aligner::with_capacity(seq.len(), pattern.len(), -1, -1, score); let alignment = aligner.semiglobal(pattern, seq); // filter out non matched reads if (alignment.score as f32) < pattern.len() as f32 * score_ratio_thresh { return (ExtractRes::ScoreTooLow, alignment) } // filter out incomplete flanking if (alignment.ystart as u8) < flanking { return (ExtractRes::LeftTooShort, alignment) } let s = alignment.ystart - flanking as usize; let left = String::from_utf8(seq[s..alignment.ystart].to_vec()).unwrap(); let e = alignment.yend + flanking as usize; if e > alignment.ylen { return (ExtractRes::RightTooShort, alignment) } let right = String::from_utf8(seq[alignment.yend..e].to_vec()).unwrap(); (ExtractRes::Ok(left, right), alignment) } struct ResCounter { linker_reads: u64, score_too_low: u64, left_too_short: u64, right_too_short: u64, } impl ResCounter { fn new() -> Self { Self { linker_reads: 0, score_too_low: 0, left_too_short: 0, right_too_short: 0, } } fn count(&mut self, res: &ExtractRes) { match res{ ExtractRes::Ok(_, _) =>{ self.linker_reads += 1 }, ExtractRes::ScoreTooLow =>{ self.score_too_low += 1 }, ExtractRes::LeftTooShort =>{ self.left_too_short += 1 }, ExtractRes::RightTooShort =>{ self.right_too_short += 1 }, } } } impl fmt::Display for ResCounter { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let total = self.linker_reads + self.score_too_low + self.left_too_short + self.right_too_short; let ratio = |c| { if total == 0 { return format!("0%"); } format!("{:.2}%", ((c*100) as f64) / (total as f64)) }; write!(f, "Count result: linker reads\t{}\t{} score too low\t{}\t{} left too short\t{}\t{} right too short\t{}\t{} total reads: {}\n", self.linker_reads, ratio(self.linker_reads), self.score_too_low, ratio(self.score_too_low), self.left_too_short, ratio(self.left_too_short), self.right_too_short, ratio(self.right_too_short), total, ) } } fn main() { simple_logger::init().unwrap(); let matches = App::new("Extract and counting seq pairs.") .arg(Arg::with_name("fq") .required(true) .help("Fastq file of reads 1.")) .arg(Arg::with_name("linker") .short("l") .long("linker") .required(true) .takes_value(true) .help("The linker sequence(Not incluede enzyme).")) .arg(Arg::with_name("enzyme") .short("e") .long("enzyme") .required(true) .takes_value(true) .help("Enzyme recognize site.") ) .arg(Arg::with_name("output_prefix") .short("o") .long("output_prefix") .required(true) .takes_value(true) .help("Prefix of output files.")) .arg(Arg::with_name("flanking") .short("f") .long("flanking") .takes_value(true) .help("Flanking length.")) .arg(Arg::with_name("score_ratio_thresh") .short("s") .long("score_ratio_thresh") .takes_value(true) .help("Threshold of (align score / pattern length)")) .arg(Arg::with_name("align_detail") .short("d") .long("detail") .takes_value(true) .help("Output the align detail.")) .arg(Arg::with_name("threads") .short("t") .long("threads") .takes_value(true) .help("Number of threads used for processing reads.")) .arg(Arg::with_name("wait_timeout") .long("wait_timeout") .takes_value(true) .help("Wait time for end channel timeout.")) .get_matches(); let fq_path = matches.value_of("fq").unwrap(); let out_prefix = matches.value_of("output_prefix").unwrap(); let linker = matches.value_of("linker").unwrap(); let enzyme = matches.value_of("enzyme").unwrap_or("GTTGGA"); let flanking = matches.value_of("flanking").unwrap_or("13"); let flanking: u8 = flanking.parse().unwrap(); let score_ratio_thresh = matches.value_of("score_ratio_thresh").unwrap_or("0.6"); let score_ratio_thresh: f32 = score_ratio_thresh.parse().unwrap(); let threads = matches.value_of("threads").unwrap_or("1"); let threads: u8 = threads.parse().unwrap(); let wait_t = matches.value_of("wait_timeout").unwrap_or("500"); let wait_t: u64 = wait_t.parse().unwrap(); let mut detail_file = match matches.value_of("align_detail") { Some(p) => Some(File::create(p).unwrap()), None => None, }; let fq_file: Box<dyn Read + Send + Sync> = if fq_path.ends_with(".gz") { Box::new(GzDecoder::new(File::open(fq_path).unwrap())) } else { Box::new(File::open(fq_path).unwrap()) }; let fq = fastq::Reader::new(fq_file); let records = fq.records(); let mut freq: HashMap<(u64, u64), u64> = HashMap::new(); let l_vec = linker.as_bytes().to_vec(); let e_vec = enzyme.as_bytes().to_vec(); let e_rc = revcomp(&e_vec); let l_rc = revcomp(&l_vec); let patterns = [ [&e_vec[..], &l_vec[..], &e_rc].concat(), [&e_vec[..], &l_rc[..], &e_rc].concat(), ]; info!("patterns:\n {}\n {}", str::from_utf8(&patterns[0]).unwrap(), str::from_utf8(&patterns[1]).unwrap(), ); let mut counter = ResCounter::new(); let records = Arc::new(Mutex::new(records)); let patterns = Arc::new(patterns); let mut handles = vec![]; let (tx, rx) = mpsc::channel(); info!("Run with {} threads.", threads); for _ in 0..threads { let records = Arc::clone(&records); let patterns = Arc::clone(&patterns); let tx1 = mpsc::Sender::clone(&tx); let handle = thread::spawn(move || { loop { // read seq from fq file let rec = { let mut records = records.lock().unwrap(); match records.next() { Some(r) => match r { Ok(r_) => r_, Err(e) => panic!("{:?}", e), }, None => break } }; let seq = String::from_utf8(rec.seq().to_vec()).unwrap(); let mut align_res: Vec<(ExtractRes, Alignment)> = Vec::with_capacity(2); for pattern in patterns.iter() { align_res.push(extract_pet(seq.as_bytes(), &pattern, flanking, score_ratio_thresh)); let res = &align_res[align_res.len()-1].0; match res { ExtractRes::Ok(_, _) => { break }, _ => { continue }, } } let rec_id = String::from(rec.id()); tx1.send((align_res, rec_id)).unwrap(); } }); handles.push(handle); } loop { match rx.recv_timeout(Duration::from_millis(wait_t)) { Ok((align_res, rec_id)) => { let res = &align_res[align_res.len()-1]; let alignment = &res.1; if let Some(mut f) = detail_file { // write align detail let _ = writeln!(f, "{}\t{}\t{}\t{}\t{}", rec_id, align_res.len(), alignment.score, alignment.ystart, alignment.yend, ); detail_file = Some(f); } // count left-right pair if let ExtractRes::Ok(left, right) = &res.0 { let mut key: (u64, u64) = (compress_seq(left.as_bytes()).unwrap(), compress_seq(right.as_bytes()).unwrap()); if key.0 > key.1 { mem::swap(&mut key.0, &mut key.1) }; *freq.entry(key).or_insert(0) += 1; } counter.count(&res.0); }, _ => { info!("End processing."); break; } } } for handle in handles { // wait all threads fishish handle.join().unwrap(); } let cnt_path = format!("{}.cnt", out_prefix); let fq_out_path = format!("{}.cnt.fq", out_prefix); let mut cnt_file = File::create(cnt_path.clone()).unwrap(); let fq_out_file = File::create(fq_out_path.clone()).unwrap(); let mut fq_out = fastq::Writer::new(fq_out_file); let mut key_set = HashSet::new(); let mut kv_vec = vec![]; for (k, v) in &freq { key_set.insert(k.0); key_set.insert(k.1); kv_vec.push((k.0, k.1, v)); } info!("Totally {} kinds of pairs and {} kinds of sequences were founded.", freq.len(), key_set.len()); kv_vec.sort_by(|a, b| b.2.cmp(a.2)); info!("Write pair counts to tsv file: {}", cnt_path); for (k0, k1, v) in kv_vec { let _ = writeln!(cnt_file, "{}\t{}\t{}", k0, k1, v); } info!("Write sequences to fastq file: {}", fq_out_path); let mut key_vec = key_set.into_iter().collect::<Vec<u64>>(); key_vec.sort(); for k in key_vec { let seq = recover_seq(k, flanking); let id = format!("{}", k); let qual = vec![b'~'; seq.len()]; let _ = fq_out.write( &id, Option::None, seq.as_bytes(), &qual, ); } info!("{}", counter); }
compress_seq
identifier_name
main.rs
use std::fs::File; use std::io::Write; use std::str; use std::collections::HashMap; use std::mem; use std::fmt; use std::thread; use std::sync::mpsc; use std::sync::{Mutex, Arc}; use std::time::Duration; use std::io::Read; use std::collections::HashSet; extern crate bio; extern crate clap; extern crate flate2; extern crate log; extern crate simple_logger; use clap::{Arg, App}; use bio::alignment::pairwise::Aligner; use bio::alignment::Alignment; use bio::io::fastq; use bio::alphabets::dna::revcomp; use log::{info}; use flate2::read::GzDecoder; const SEQ_NT4_TABLE: [u64; 256] = [ 0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ]; const IDX_TABLE: [u8; 4] = [ b'A', b'C', b'G', b'T' ]; fn compress_seq(seq: &[u8]) -> Result<u64, &str> { let mut res: u64 = 0; let mut res_rc: u64 = 0; let end = seq.len() - 1; for i in 0..seq.len() { if i >= 32 { return Err("Seq can't longer than 32.") } let m = SEQ_NT4_TABLE[seq[i] as usize]; res |= m << i*2; res_rc |= (3 - m) << (end - i)*2; } if res > res_rc { mem::swap(&mut res, &mut res_rc) }; Ok(res) } fn recover_seq(code: u64, k: u8) -> String { let mut chars: Vec<u8> = Vec::with_capacity(k as usize); for i in 0..k { let mask: u64 = 3 << (i*2); let idx = (code & mask) >> (i*2); let b = IDX_TABLE[idx as usize]; chars.push(b); } String::from_utf8(chars).unwrap() } enum ExtractRes { Ok(String, String), ScoreTooLow, LeftTooShort, RightTooShort, } fn extract_pet(seq: &[u8], pattern: &[u8], flanking: u8, score_ratio_thresh: f32) -> (ExtractRes, Alignment) { // align linker to read let score = |a: u8, b: u8| if a == b {1i32} else {-1i32}; let mut aligner = Aligner::with_capacity(seq.len(), pattern.len(), -1, -1, score); let alignment = aligner.semiglobal(pattern, seq); // filter out non matched reads if (alignment.score as f32) < pattern.len() as f32 * score_ratio_thresh { return (ExtractRes::ScoreTooLow, alignment) } // filter out incomplete flanking if (alignment.ystart as u8) < flanking { return (ExtractRes::LeftTooShort, alignment) } let s = alignment.ystart - flanking as usize; let left = String::from_utf8(seq[s..alignment.ystart].to_vec()).unwrap(); let e = alignment.yend + flanking as usize; if e > alignment.ylen { return (ExtractRes::RightTooShort, alignment) } let right = String::from_utf8(seq[alignment.yend..e].to_vec()).unwrap(); (ExtractRes::Ok(left, right), alignment) } struct ResCounter { linker_reads: u64, score_too_low: u64, left_too_short: u64, right_too_short: u64, } impl ResCounter { fn new() -> Self { Self { linker_reads: 0, score_too_low: 0, left_too_short: 0, right_too_short: 0, } } fn count(&mut self, res: &ExtractRes) { match res{ ExtractRes::Ok(_, _) =>{ self.linker_reads += 1 }, ExtractRes::ScoreTooLow =>{ self.score_too_low += 1 }, ExtractRes::LeftTooShort =>{ self.left_too_short += 1 }, ExtractRes::RightTooShort =>{ self.right_too_short += 1 }, } } } impl fmt::Display for ResCounter { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let total = self.linker_reads + self.score_too_low + self.left_too_short + self.right_too_short; let ratio = |c| { if total == 0 { return format!("0%"); } format!("{:.2}%", ((c*100) as f64) / (total as f64)) }; write!(f, "Count result: linker reads\t{}\t{} score too low\t{}\t{} left too short\t{}\t{} right too short\t{}\t{} total reads: {}\n", self.linker_reads, ratio(self.linker_reads), self.score_too_low, ratio(self.score_too_low), self.left_too_short, ratio(self.left_too_short), self.right_too_short, ratio(self.right_too_short), total, ) } } fn main() { simple_logger::init().unwrap(); let matches = App::new("Extract and counting seq pairs.") .arg(Arg::with_name("fq") .required(true) .help("Fastq file of reads 1.")) .arg(Arg::with_name("linker") .short("l") .long("linker") .required(true) .takes_value(true) .help("The linker sequence(Not incluede enzyme).")) .arg(Arg::with_name("enzyme") .short("e") .long("enzyme") .required(true) .takes_value(true) .help("Enzyme recognize site.") ) .arg(Arg::with_name("output_prefix") .short("o") .long("output_prefix") .required(true) .takes_value(true) .help("Prefix of output files.")) .arg(Arg::with_name("flanking") .short("f") .long("flanking") .takes_value(true) .help("Flanking length.")) .arg(Arg::with_name("score_ratio_thresh") .short("s") .long("score_ratio_thresh") .takes_value(true) .help("Threshold of (align score / pattern length)")) .arg(Arg::with_name("align_detail") .short("d") .long("detail") .takes_value(true) .help("Output the align detail.")) .arg(Arg::with_name("threads") .short("t") .long("threads") .takes_value(true) .help("Number of threads used for processing reads.")) .arg(Arg::with_name("wait_timeout") .long("wait_timeout") .takes_value(true) .help("Wait time for end channel timeout.")) .get_matches(); let fq_path = matches.value_of("fq").unwrap(); let out_prefix = matches.value_of("output_prefix").unwrap(); let linker = matches.value_of("linker").unwrap(); let enzyme = matches.value_of("enzyme").unwrap_or("GTTGGA"); let flanking = matches.value_of("flanking").unwrap_or("13"); let flanking: u8 = flanking.parse().unwrap(); let score_ratio_thresh = matches.value_of("score_ratio_thresh").unwrap_or("0.6"); let score_ratio_thresh: f32 = score_ratio_thresh.parse().unwrap(); let threads = matches.value_of("threads").unwrap_or("1"); let threads: u8 = threads.parse().unwrap(); let wait_t = matches.value_of("wait_timeout").unwrap_or("500"); let wait_t: u64 = wait_t.parse().unwrap(); let mut detail_file = match matches.value_of("align_detail") { Some(p) => Some(File::create(p).unwrap()), None => None, }; let fq_file: Box<dyn Read + Send + Sync> = if fq_path.ends_with(".gz") { Box::new(GzDecoder::new(File::open(fq_path).unwrap())) } else { Box::new(File::open(fq_path).unwrap()) }; let fq = fastq::Reader::new(fq_file); let records = fq.records(); let mut freq: HashMap<(u64, u64), u64> = HashMap::new(); let l_vec = linker.as_bytes().to_vec(); let e_vec = enzyme.as_bytes().to_vec(); let e_rc = revcomp(&e_vec); let l_rc = revcomp(&l_vec); let patterns = [ [&e_vec[..], &l_vec[..], &e_rc].concat(), [&e_vec[..], &l_rc[..], &e_rc].concat(), ]; info!("patterns:\n {}\n {}", str::from_utf8(&patterns[0]).unwrap(), str::from_utf8(&patterns[1]).unwrap(), ); let mut counter = ResCounter::new(); let records = Arc::new(Mutex::new(records)); let patterns = Arc::new(patterns); let mut handles = vec![]; let (tx, rx) = mpsc::channel(); info!("Run with {} threads.", threads); for _ in 0..threads { let records = Arc::clone(&records); let patterns = Arc::clone(&patterns); let tx1 = mpsc::Sender::clone(&tx); let handle = thread::spawn(move || { loop { // read seq from fq file let rec = { let mut records = records.lock().unwrap(); match records.next() { Some(r) => match r { Ok(r_) => r_, Err(e) => panic!("{:?}", e), }, None => break } }; let seq = String::from_utf8(rec.seq().to_vec()).unwrap(); let mut align_res: Vec<(ExtractRes, Alignment)> = Vec::with_capacity(2); for pattern in patterns.iter() { align_res.push(extract_pet(seq.as_bytes(), &pattern, flanking, score_ratio_thresh)); let res = &align_res[align_res.len()-1].0; match res { ExtractRes::Ok(_, _) => { break }, _ => { continue }, } } let rec_id = String::from(rec.id()); tx1.send((align_res, rec_id)).unwrap(); } }); handles.push(handle); } loop { match rx.recv_timeout(Duration::from_millis(wait_t)) { Ok((align_res, rec_id)) => { let res = &align_res[align_res.len()-1]; let alignment = &res.1; if let Some(mut f) = detail_file { // write align detail let _ = writeln!(f, "{}\t{}\t{}\t{}\t{}", rec_id, align_res.len(), alignment.score, alignment.ystart, alignment.yend, ); detail_file = Some(f); } // count left-right pair if let ExtractRes::Ok(left, right) = &res.0 { let mut key: (u64, u64) = (compress_seq(left.as_bytes()).unwrap(), compress_seq(right.as_bytes()).unwrap()); if key.0 > key.1 { mem::swap(&mut key.0, &mut key.1) }; *freq.entry(key).or_insert(0) += 1; } counter.count(&res.0); }, _ => { info!("End processing."); break; } } } for handle in handles { // wait all threads fishish handle.join().unwrap(); } let cnt_path = format!("{}.cnt", out_prefix); let fq_out_path = format!("{}.cnt.fq", out_prefix); let mut cnt_file = File::create(cnt_path.clone()).unwrap(); let fq_out_file = File::create(fq_out_path.clone()).unwrap(); let mut fq_out = fastq::Writer::new(fq_out_file); let mut key_set = HashSet::new(); let mut kv_vec = vec![]; for (k, v) in &freq { key_set.insert(k.0); key_set.insert(k.1); kv_vec.push((k.0, k.1, v)); } info!("Totally {} kinds of pairs and {} kinds of sequences were founded.", freq.len(), key_set.len()); kv_vec.sort_by(|a, b| b.2.cmp(a.2)); info!("Write pair counts to tsv file: {}", cnt_path);
for (k0, k1, v) in kv_vec { let _ = writeln!(cnt_file, "{}\t{}\t{}", k0, k1, v); } info!("Write sequences to fastq file: {}", fq_out_path); let mut key_vec = key_set.into_iter().collect::<Vec<u64>>(); key_vec.sort(); for k in key_vec { let seq = recover_seq(k, flanking); let id = format!("{}", k); let qual = vec![b'~'; seq.len()]; let _ = fq_out.write( &id, Option::None, seq.as_bytes(), &qual, ); } info!("{}", counter); }
random_line_split
qcloud.py
#!/usr/bin/python # -*- coding: utf-8 -*- from api.QcloudApi.qcloudapi import QcloudApi import json import sys import datetime import traceback import logging import re from utils import send_alarm from models import ServersModel, RdsModel, ServerConf from Free.settings import QCLOUD_KEY, QCLOUD_VALUE reload(sys) sys.setdefaultencoding('utf-8') logger = logging.getLogger("free") STATUS_CH = {'1': '故障', '2': '运行中', '3': '创建中', '4': '已关机', '5': '已退还', '6': '退还中', '7': '重启中', '8': '开机中', '9': '关机中', '10': '密码重置中', '11': '格式化中', '12': '镜像制作中', '13': '带宽设置中', '14': '重装系统中', '15': '域名绑定中', '16': '域名解绑中', '17': '负载均衡绑定中', '18': '负载均衡解绑中', '19': '升级中', '20': '秘钥下发中', '21': '维护中'} PAY_TYPE = {'0': '按月结算的后付费', '1': "包年包月", "2": '按量计费'} NET_PAY = {'0': '按月结算的后付费', '1': '包年包月', '2': '按流量', '3': "按带宽"} #腾讯给的调用api的SDK def qcloud(module, action, region, params): config = { 'Region': region, 'secretId': QCLOUD_KEY, 'secretKey': QCLOUD_VALUE, 'method': 'post' } try: service = QcloudApi(module, config) response = service.call(action, params) obj = json.loads(response) return obj except Exception, e: print 'exception:', e #获取上海,广州,北京的服务器信息,且存入数据库 def deal_qcloud(): all_keys = [] for regi in ("sh", "gz", "bj"): result = qcloud('cvm', 'DescribeInstances', regi, {'limit': 99}) if 'instanceSet' in result: result = result.pop('instanceSet') else: continue for item in result: all_keys.append(item['unInstanceId']) one = {} for key in item.keys(): if isinstance(item[key], dict): for n_key in item[key].keys(): one.update({str(key) + '_' + str(n_key): str(item[key][n_key])}) else: if key == "status": item[key] = STATUS_CH[str(item[key])] if isinstance(item[key], list): item[key] = item[key][0] try: one.update({str(key): str(item[key])}) except Exception, e: one.update({str(key): item[key]}) change = {"status": STATUS_CH, "cvmPayMode": PAY_TYPE, "networkPayMode": NET_PAY} for t_name, t_value in change.items(): try: one[t_name] = t_value[one[t_name]] except Exception, e: continue atime = one["deadlineTime"].split(' ') atime = atime[0].split('-') d3 = datetime.datetime(int(atime[0]), int(atime[1]), int(atime[2])) if 0 <= (d3 - datetime.datetime.now()).days < 10: date_color = 'red' elif (d3 - datetime.datetime.now()).days < 0: date_color = 'black' else: date_color = 'green' server = ServersModel.objects.filter(instanceid=one["unInstanceId"]) if server: try: server.update(server_from='qcloud', dick_root=one["diskInfo_rootSize"], dick_storage=one["diskInfo_storageSize"], create_time = one["createTime"], expired_time = one["deadlineTime"], eip_intercharge_type = one["networkPayMode"], internet_charge_type = one["networkPayMode"], image_id = one["os"], instance_name = one["instanceName"], status = one["status"], instanceid = one["unInstanceId"],zone_id = one["zoneName"], cpu = one["cpu"], instance_charge_type = one["cvmPayMode"], memory = one["mem"], public_ip = one["wanIpSet"], region_id = one["Region"], eip_bandwidth = one["bandwidth"], inner_ip = one["lanIp"], status_color= date_color) except Exception, e: logger.error(traceback.format_exc()) else: one = ServersModel.objects.create(server_from='qcloud', dick_root=one["diskInfo_rootSize"], dick_storage=one["diskInfo_storageSize"], create_time = one["createTime"], expired_time = one["deadlineTime"], eip_intercharge_type = one["networkPayMode"], internet_charge_type = one["networkPayMode"], image_id = one["os"], instance_name = one["instanceName"], status = one["status"], instanceid = one["unInstanceId"],zone_id = one["zoneName"], cpu = one["cpu"], instance_charge_type = one["cvmPayMode"], memory = one["mem"], public_ip = one["wanIpSet"], region_id = one["Region"], eip_bandwidth = one["bandwidth"], inner_ip = one["lanIp"], status_color= date_color) one.save() all_servers = ServersModel.objects.filter(server_from="qcloud") for one in all_servers: if one.instanceid not in all_keys: one.delete() # 对腾讯云服务器的操作:包括启动,停止和重启。这个api允许一次执行多个实例的,但页面上没有实现 def op_server(instanceid, action, region): result = qcloud("cvm", action, region, {"instanceIds.1": instanceid}) return result #修改腾讯云服务器名称 def qcloud_change_name(instanceid, action, region, new_name): result = qcloud("cvm", action, region, {"instanceId": instanceid, "instanceName": new_name}) return result #购买腾讯云服务器实例 def create_qcloud(data): region =
("change_region_cvm") params = {"wanlp": "1", "needSecurityAgent": "1", "needMonitorAgent": "1", "storageType": '2'} passwd = data['passwd1'] match = re.match(ur'^([a-z,A-z,0-9]{8,16}|[0-9,\W]{8,16}|[a-z,A-Z,\W]{8,16}|[a-z,A-Z,0-9,\W]{8,16})$', passwd) if not match: return "密码格式有误,请按要求输入" else: params.update({"password": passwd}) for key, value in {"100002": "region_g2", "100003": "region_g3", "200001": "region_s1", "800001": "region_b1", "300001": "region_x1"}.items(): if region == key: config = data[value] config = config.split("-") params.update({"cpu": config[0]}) params.update({"mem": config[1]}) params.update({"zoneId": region}) break region_change = {"100002": "gz", "100003": "gz", "200001": "sh", "800001": "bj", "300001": 'xg'} for key, value in data.items(): if key in ("region_g2", 'region_g3', "region_s1", "region_b1", "region_x1", "passwd1", "passwd2", "csrfmiddlewaretoken"): continue params.update({key: value}) logger.error('购买腾讯云服务器,参数: ' + json.dumps(params)) result = qcloud("cvm", "RunInstances", region_change[region], params) logger.error('购买完成,result is : ' + json.dumps(result)) if result["message"] == "": result = "购买成功" else: result = result["message"] return result #获取服务器信息 def get_rds(): try: result = qcloud('cdb', 'DescribeCdbInstances', 'sh', {}) TAST_TRAN = {'0': '没有任务', '1': '升级中', '2': '数据导入中', '3': '开放Slave中', '4': '外网访问开通中', '5': '批量操作执行中', '6': '回档中', '7':'外网访问关闭中', '8': '密码修改中', '9': '实例名修改中', '10': '重启中', '12': '自建迁移中', '13': '删除库表中','14': '灾备实例创建同步中'} PAY_TRAN = {'0': '包年包月', '1': '按量计费', '2': '后付费月结'} results = result['cdbInstanceSet'] all_keys = [] for one in results: all_keys.append(one["uInstanceId"]) one['taskStatus'] = TAST_TRAN[str(one['taskStatus'])] one['payType'] = PAY_TRAN[str(one['payType'])] zone = ServerConf.objects.get(server_type='qcloud', info_type='zone', key=one['zoneId']) one['zoneId'] = zone.value if one['status'] == 1: one['status'] ='运行中' else: one['status'] = '创建中' for key,value in one.items(): one[key] = str(value) atime = one["cdbInstanceDeadlineTime"].split(' ') atime = atime[0].split('-') d3 = datetime.datetime(int(atime[0]), int(atime[1]), int(atime[2])) if 0 <= (d3 - datetime.datetime.now()).days < 10: date_color = 'red' elif (d3 - datetime.datetime.now()).days < 0: date_color = 'black' else: date_color = 'green' rds = RdsModel.objects.filter(instanceid=one['uInstanceId']) if rds: new_rds = rds.update(instanceid=one['uInstanceId'], engine_version= 'mysql' + one['engineVersion'], instance_type=one['cdbType'], instance_name=one['cdbInstanceName'], vpcid=one['vpcId'], instance_vpcid=one['cdbInstanceVip'], status=one['status'], task_status=one['taskStatus'], pay_type=one['payType'], zone_id=one['zoneId'], storage_size=one['storageSize'], mem=one['memory'], volume=one['volume'], autoRenew=one['autoRenew'], max_query=one['maxQueryCount'], type_set=one['cdbTypeSet'], vport=one['cdbInstanceVport'], deadline_time=one['cdbInstanceDeadlineTime'], create_time=one['cdbInstanceCreateTime'],status_color=date_color) else: new_rds = RdsModel.objects.create(instanceid=one['uInstanceId'], engine_version= 'mysql' + one['engineVersion'], instance_type=one['cdbType'], instance_name=one['cdbInstanceName'], vpcid=one['vpcId'], instance_vpcid=one['cdbInstanceVip'], status=one['status'], task_status=one['taskStatus'], pay_type=one['payType'], zone_id=one['zoneId'], storage_size=one['storageSize'], mem=str(one['memory']), volume=one['volume'], autoRenew=one['autoRenew'], max_query=one['maxQueryCount'], type_set=one['cdbTypeSet'], vport=one['cdbInstanceVport'], deadline_time=one['cdbInstanceDeadlineTime'], create_time=one['cdbInstanceCreateTime'], status_color=date_color) new_rds.save() all_servers = RdsModel.objects.filter(server_type='qcloud') for one in all_servers: if one.instanceid not in all_keys: one.delete() except Exception, e: print traceback.format_exc() #购买数据库 def create_qcloud_rds(months, num, mem, volume, zone): params = {'cdbType': 'CUSTOM', 'engineVersion': '5.6', 'period': months, 'goodsNum': num, 'memory': mem, 'volume': volume, 'zoneId': zone} result = qcloud('cdb', 'CreateCdb', 'sh', params) #result = {'message': 'just try'} logger.error('购买腾讯云数据库,参数为: ' + json.dumps(params)) logger.error('购买结果为: ' + json.dumps(result)) if 'Success' in json.dumps(result): return '购买成功' else: return '可能出错了,请联系管理员.'
data.pop
identifier_name
qcloud.py
#!/usr/bin/python # -*- coding: utf-8 -*- from api.QcloudApi.qcloudapi import QcloudApi import json import sys import datetime import traceback import logging import re from utils import send_alarm from models import ServersModel, RdsModel, ServerConf from Free.settings import QCLOUD_KEY, QCLOUD_VALUE reload(sys) sys.setdefaultencoding('utf-8') logger = logging.getLogger("free") STATUS_CH = {'1': '故障', '2': '运行中', '3': '创建中', '4': '已关机', '5': '已退还', '6': '退还中', '7': '重启中', '8': '开机中', '9': '关机中', '10': '密码重置中', '11': '格式化中', '12': '镜像制作中', '13': '带宽设置中', '14': '重装系统中', '15': '域名绑定中', '16': '域名解绑中', '17': '负载均衡绑定中', '18': '负载均衡解绑中', '19': '升级中', '20': '秘钥下发中', '21': '维护中'} PAY_TYPE = {'0': '按月结算的后付费', '1': "包年包月", "2": '按量计费'} NET_PAY = {'0': '按月结算的后付费', '1': '包年包月', '2': '按流量', '3': "按带宽"} #腾讯给的调用api的SDK def qcloud(module, action, region, params): config = { 'Region': region, 'secretId': QCLOUD_KEY, 'secretKey': QCLOUD_VALUE, 'method': 'post' } try: service = QcloudApi(module, config) response = service.call(action, params) obj = json.loads(response) return obj except Exception, e: print 'exception:', e #获取上海,广州,北京的服务器信息,且存入数据库 def deal_qcloud(): all_keys = [] for regi in ("sh", "gz", "bj"): result = qcloud('cvm', 'DescribeInstances', regi, {'limit': 99}) if 'instanceSet' in result: result = result.pop('instanceSet') else: continue for item in result: all_keys.append(item['unInstanceId']) one = {} for key in item.keys(): if isinstance(item[key], dict): for n_key in item[key].keys(): one.update({str(key) + '_' + str(n_key): str(item[key][n_key])}) else: if key == "status": item[key] = STATUS_CH[str(item[key])] if isinstance(item[key], list): item[key] = item[key][0] try: one.update({str(key): str(item[key])}) except Exception, e: one.update({str(key): item[key]}) change = {"status": STATUS_CH, "cvmPayMode": PAY_TYPE, "networkPayMode": NET_PAY} for t_name, t_value in change.items(): try: one[t_name] = t_value[one[t_name]] except Exception, e: continue atime = one["deadlineTime"].split(' ') atime = atime[0].split('-') d3 = datetime.datetime(int(atime[0]), int(atime[1]), int(atime[2])) if 0 <= (d3 - datetime.datetime.now()).days < 10: date_color = 'red' elif (d3 - datetime.datetime.now()).days < 0: date_color = 'black' else: date_color = 'green' server = ServersModel.objects.filter(instanceid=one["unInstanceId"]) if server: try: server.update(server_from='qcloud', dick_root=one["diskInfo_rootSize"], dick_storage=one["diskInfo_storageSize"], create_time = one["createTime"], expired_time = one["deadlineTime"], eip_intercharge_type = one["networkPayMode"], internet_charge_type = one["networkPayMode"], image_id = one["os"], instance_name = one["instanceName"], status = one["status"], instanceid = one["unInstanceId"],zone_id = one["zoneName"], cpu = one["cpu"], instance_charge_type = one["cvmPayMode"], memory = one["mem"], public_ip = one["wanIpSet"], region_id = one["Region"], eip_bandwidth = one["bandwidth"], inner_ip = one["lanIp"], status_color= date_color) except Exception, e: logger.error(traceback.format_exc()) else: one = ServersModel.objects.create(server_from='qcloud', dick_root=one["diskInfo_rootSize"], dick_storage=one["diskInfo_storageSize"], create_time = one["createTime"], expired_time = one["deadlineTime"], eip_intercharge_type = one["networkPayMode"], internet_charge_type = one["networkPayMode"], image_id = one["os"], instance_name = one["instanceName"], status = one["status"], instanceid = one["unInstanceId"],zone_id = one["zoneName"], cpu = one["cpu"], instance_charge_type = one["cvmPayMode"], memory = one["mem"], public_ip = one["wanIpSet"], region_id = one["Region"], eip_bandwidth = one["bandwidth"], inner_ip = one["lanIp"], status_color= date_color) one.save() all_servers = ServersModel.objects.filter(server_from="qcloud") for one in all_servers: if one.instanceid not in all_keys: one.delete() # 对腾讯云服务器的操作:包括启动,停止和重启。这个api允许一次执行多个实例的,但页面上没有实现 def op_server(instanceid, action, region): result = qcloud("cvm", action, region, {"instanceIds.1": instanceid}) return result #修改腾讯云服务器名称 def qcloud_change_name(instanceid, action, region, new_name): result = qcloud("cvm", action, region, {"instanceId": instanceid, "instanceName": new_name}) return result #购买腾讯云服务器实例 def create_qcloud(data): region = data.pop("change_region_cvm") params =
passwd = data['passwd1'] match = re.match(ur'^([a-z,A-z,0-9]{8,16}|[0-9,\W]{8,16}|[a-z,A-Z,\W]{8,16}|[a-z,A-Z,0-9,\W]{8,16})$', passwd) if not match: return "密码格式有误,请按要求输入" else: params.update({"password": passwd}) for key, value in {"100002": "region_g2", "100003": "region_g3", "200001": "region_s1", "800001": "region_b1", "300001": "region_x1"}.items(): if region == key: config = data[value] config = config.split("-") params.update({"cpu": config[0]}) params.update({"mem": config[1]}) params.update({"zoneId": region}) break region_change = {"100002": "gz", "100003": "gz", "200001": "sh", "800001": "bj", "300001": 'xg'} for key, value in data.items(): if key in ("region_g2", 'region_g3', "region_s1", "region_b1", "region_x1", "passwd1", "passwd2", "csrfmiddlewaretoken"): continue params.update({key: value}) logger.error('购买腾讯云服务器,参数: ' + json.dumps(params)) result = qcloud("cvm", "RunInstances", region_change[region], params) logger.error('购买完成,result is : ' + json.dumps(result)) if result["message"] == "": result = "购买成功" else: result = result["message"] return result #获取服务器信息 def get_rds(): try: result = qcloud('cdb', 'DescribeCdbInstances', 'sh', {}) TAST_TRAN = {'0': '没有任务', '1': '升级中', '2': '数据导入中', '3': '开放Slave中', '4': '外网访问开通中', '5': '批量操作执行中', '6': '回档中', '7':'外网访问关闭中', '8': '密码修改中', '9': '实例名修改中', '10': '重启中', '12': '自建迁移中', '13': '删除库表中','14': '灾备实例创建同步中'} PAY_TRAN = {'0': '包年包月', '1': '按量计费', '2': '后付费月结'} results = result['cdbInstanceSet'] all_keys = [] for one in results: all_keys.append(one["uInstanceId"]) one['taskStatus'] = TAST_TRAN[str(one['taskStatus'])] one['payType'] = PAY_TRAN[str(one['payType'])] zone = ServerConf.objects.get(server_type='qcloud', info_type='zone', key=one['zoneId']) one['zoneId'] = zone.value if one['status'] == 1: one['status'] ='运行中' else: one['status'] = '创建中' for key,value in one.items(): one[key] = str(value) atime = one["cdbInstanceDeadlineTime"].split(' ') atime = atime[0].split('-') d3 = datetime.datetime(int(atime[0]), int(atime[1]), int(atime[2])) if 0 <= (d3 - datetime.datetime.now()).days < 10: date_color = 'red' elif (d3 - datetime.datetime.now()).days < 0: date_color = 'black' else: date_color = 'green' rds = RdsModel.objects.filter(instanceid=one['uInstanceId']) if rds: new_rds = rds.update(instanceid=one['uInstanceId'], engine_version= 'mysql' + one['engineVersion'], instance_type=one['cdbType'], instance_name=one['cdbInstanceName'], vpcid=one['vpcId'], instance_vpcid=one['cdbInstanceVip'], status=one['status'], task_status=one['taskStatus'], pay_type=one['payType'], zone_id=one['zoneId'], storage_size=one['storageSize'], mem=one['memory'], volume=one['volume'], autoRenew=one['autoRenew'], max_query=one['maxQueryCount'], type_set=one['cdbTypeSet'], vport=one['cdbInstanceVport'], deadline_time=one['cdbInstanceDeadlineTime'], create_time=one['cdbInstanceCreateTime'],status_color=date_color) else: new_rds = RdsModel.objects.create(instanceid=one['uInstanceId'], engine_version= 'mysql' + one['engineVersion'], instance_type=one['cdbType'], instance_name=one['cdbInstanceName'], vpcid=one['vpcId'], instance_vpcid=one['cdbInstanceVip'], status=one['status'], task_status=one['taskStatus'], pay_type=one['payType'], zone_id=one['zoneId'], storage_size=one['storageSize'], mem=str(one['memory']), volume=one['volume'], autoRenew=one['autoRenew'], max_query=one['maxQueryCount'], type_set=one['cdbTypeSet'], vport=one['cdbInstanceVport'], deadline_time=one['cdbInstanceDeadlineTime'], create_time=one['cdbInstanceCreateTime'], status_color=date_color) new_rds.save() all_servers = RdsModel.objects.filter(server_type='qcloud') for one in all_servers: if one.instanceid not in all_keys: one.delete() except Exception, e: print traceback.format_exc() #购买数据库 def create_qcloud_rds(months, num, mem, volume, zone): params = {'cdbType': 'CUSTOM', 'engineVersion': '5.6', 'period': months, 'goodsNum': num, 'memory': mem, 'volume': volume, 'zoneId': zone} result = qcloud('cdb', 'CreateCdb', 'sh', params) #result = {'message': 'just try'} logger.error('购买腾讯云数据库,参数为: ' + json.dumps(params)) logger.error('购买结果为: ' + json.dumps(result)) if 'Success' in json.dumps(result): return '购买成功' else: return '可能出错了,请联系管理员.'
{"wanlp": "1", "needSecurityAgent": "1", "needMonitorAgent": "1", "storageType": '2'}
identifier_body
qcloud.py
#!/usr/bin/python # -*- coding: utf-8 -*- from api.QcloudApi.qcloudapi import QcloudApi import json import sys import datetime import traceback import logging import re from utils import send_alarm from models import ServersModel, RdsModel, ServerConf from Free.settings import QCLOUD_KEY, QCLOUD_VALUE reload(sys) sys.setdefaultencoding('utf-8') logger = logging.getLogger("free") STATUS_CH = {'1': '故障', '2': '运行中', '3': '创建中', '4': '已关机', '5': '已退还', '6': '退还中', '7': '重启中', '8': '开机中', '9': '关机中', '10': '密码重置中', '11': '格式化中', '12': '镜像制作中', '13': '带宽设置中', '14': '重装系统中', '15': '域名绑定中', '16': '域名解绑中', '17': '负载均衡绑定中', '18': '负载均衡解绑中', '19': '升级中', '20': '秘钥下发中', '21': '维护中'} PAY_TYPE = {'0': '按月结算的后付费', '1': "包年包月", "2": '按量计费'} NET_PAY = {'0': '按月结算的后付费', '1': '包年包月', '2': '按流量', '3': "按带宽"} #腾讯给的调用api的SDK def qcloud(module, action, region, params): config = { 'Region': region, 'secretId': QCLOUD_KEY, 'secretKey': QCLOUD_VALUE, 'method': 'post' } try: service = QcloudApi(module, config) response = service.call(action, params) obj = json.loads(response) return obj except Exception, e: print 'exception:', e #获取上海,广州,北京的服务器信息,且存入数据库 def deal_qcloud(): all_keys = [] for regi in ("sh", "gz", "bj"): result = qcloud('cvm', 'DescribeInstances', regi, {'limit': 99}) if 'instanceSet' in result: result = result.pop('instanceSet') else: continue for item in result: all_keys.append(item['unInstanceId']) one = {} for key in item.keys(): if isinstance(item[key], dict): for n_key in item[key].keys(): one.update({str(key) + '_' + str(n_key): str(item[key][n_key])}) else: if key == "status": item[key] = STATUS_CH[str(item[key])] if isinstance(item[key], list): item[key] = item[key][0] try: one.update({str(key): str(item[key])}) except Exception, e: one.update({str(key): item[key]}) change = {"status": STATUS_CH, "cvmPayMode": PAY_TYPE, "networkPayMode": NET_PAY} for t_name, t_value in change.items(): try: one[t_name] = t_value[one[t_name]] except Exception, e: continue atime = one["deadlineTime"].split(' ') atime = atime[0].split('-') d3 = datetime.datetime(int(atime[0]), int(atime[1]), int(atime[2])) if 0 <= (d3 - datetime.datetime.now()).days < 10: date_color = 'red' elif (d3 - datetime.datetime.now()).days < 0: date_color = 'black' else: date_color = 'green' server = ServersModel.objects.filter(instanceid=one["unInstanceId"]) if server: try: server.update(server_from='qcloud', dick_root=one["diskInfo_rootSize"], dick_storage=one["diskInfo_storageSize"], create_time = one["createTime"], expired_time = one["deadlineTime"], eip_intercharge_type = one["networkPayMode"], internet_charge_type = one["networkPayMode"], image_id = one["os"], instance_name = one["instanceName"], status = one["status"], instanceid = one["unInstanceId"],zone_id = one["zoneName"], cpu = one["cpu"], instance_charge_type = one["cvmPayMode"], memory = one["mem"], public_ip = one["wanIpSet"], region_id = one["Region"], eip_bandwidth = one["bandwidth"], inner_ip = one["lanIp"], status_color= date_color) except Exception, e: logger.error(traceback.format_exc()) else: one = ServersModel.objects.create(server_from='qcloud', dick_root=one["diskInfo_rootSize"], dick_storage=one["diskInfo_storageSize"], create_time = one["createTime"], expired_time = one["deadlineTime"], eip_intercharge_type = one["networkPayMode"], internet_charge_type = one["networkPayMode"], image_id = one["os"], instance_name = one["instanceName"], status = one["status"], instanceid = one["unInstanceId"],zone_id = one["zoneName"], cpu = one["cpu"], instance_charge_type = one["cvmPayMode"], memory = one["mem"], public_ip = one["wanIpSet"], region_id = one["Region"], eip_bandwidth = one["bandwidth"], inner_ip = one["lanIp"], status_color= date_color) one.save() all_servers = ServersModel.objects.filter(server_from="qcloud") for one in all_servers: if one.instanceid not in all_keys: one.delete() # 对腾讯云服务器的操作:包括启动,停止和重启。这个api允许一次执行多个实例的,但页面上没有实现 def op_server(instanceid, action, region): result = qcloud("cvm", action, region, {"instanceIds.1": instanceid}) return result #修改腾讯云服务器名称 def qcloud_change_name(instanceid, action, region, new_name): result = qcloud("cvm", action, region, {"instanceId": instanceid, "instanceName": new_name}) return result #购买腾讯云服务器实例 def create_qcloud(data): region = data.pop("change_region_cvm") params = {"wanlp": "1", "needSecurityAgent": "1", "needMonitorAgent": "1", "storageType": '2'} passwd = data['passwd1'] match = re.match(ur'^([a-z,A-z,0-9]{8,16}|[0-9,\W]{8,16}|[a-z,A-Z,\W]{8,16}|[a-z,A-Z,0-9,\W]{8,16})$', passwd) if not match: return "密码格式有误,请按要求输入" else: params.update({"password": passwd}) for key, value in {"100002": "region_g2", "100003": "region_g3", "200001": "region_s1", "800001": "region_b1", "300001": "region_x1"}.items(): if region == key: config = data[value] config = config.split("-") params.update({"cpu": config[0]}) params.update({"mem": config[1]})
break region_change = {"100002": "gz", "100003": "gz", "200001": "sh", "800001": "bj", "300001": 'xg'} for key, value in data.items(): if key in ("region_g2", 'region_g3', "region_s1", "region_b1", "region_x1", "passwd1", "passwd2", "csrfmiddlewaretoken"): continue params.update({key: value}) logger.error('购买腾讯云服务器,参数: ' + json.dumps(params)) result = qcloud("cvm", "RunInstances", region_change[region], params) logger.error('购买完成,result is : ' + json.dumps(result)) if result["message"] == "": result = "购买成功" else: result = result["message"] return result #获取服务器信息 def get_rds(): try: result = qcloud('cdb', 'DescribeCdbInstances', 'sh', {}) TAST_TRAN = {'0': '没有任务', '1': '升级中', '2': '数据导入中', '3': '开放Slave中', '4': '外网访问开通中', '5': '批量操作执行中', '6': '回档中', '7':'外网访问关闭中', '8': '密码修改中', '9': '实例名修改中', '10': '重启中', '12': '自建迁移中', '13': '删除库表中','14': '灾备实例创建同步中'} PAY_TRAN = {'0': '包年包月', '1': '按量计费', '2': '后付费月结'} results = result['cdbInstanceSet'] all_keys = [] for one in results: all_keys.append(one["uInstanceId"]) one['taskStatus'] = TAST_TRAN[str(one['taskStatus'])] one['payType'] = PAY_TRAN[str(one['payType'])] zone = ServerConf.objects.get(server_type='qcloud', info_type='zone', key=one['zoneId']) one['zoneId'] = zone.value if one['status'] == 1: one['status'] ='运行中' else: one['status'] = '创建中' for key,value in one.items(): one[key] = str(value) atime = one["cdbInstanceDeadlineTime"].split(' ') atime = atime[0].split('-') d3 = datetime.datetime(int(atime[0]), int(atime[1]), int(atime[2])) if 0 <= (d3 - datetime.datetime.now()).days < 10: date_color = 'red' elif (d3 - datetime.datetime.now()).days < 0: date_color = 'black' else: date_color = 'green' rds = RdsModel.objects.filter(instanceid=one['uInstanceId']) if rds: new_rds = rds.update(instanceid=one['uInstanceId'], engine_version= 'mysql' + one['engineVersion'], instance_type=one['cdbType'], instance_name=one['cdbInstanceName'], vpcid=one['vpcId'], instance_vpcid=one['cdbInstanceVip'], status=one['status'], task_status=one['taskStatus'], pay_type=one['payType'], zone_id=one['zoneId'], storage_size=one['storageSize'], mem=one['memory'], volume=one['volume'], autoRenew=one['autoRenew'], max_query=one['maxQueryCount'], type_set=one['cdbTypeSet'], vport=one['cdbInstanceVport'], deadline_time=one['cdbInstanceDeadlineTime'], create_time=one['cdbInstanceCreateTime'],status_color=date_color) else: new_rds = RdsModel.objects.create(instanceid=one['uInstanceId'], engine_version= 'mysql' + one['engineVersion'], instance_type=one['cdbType'], instance_name=one['cdbInstanceName'], vpcid=one['vpcId'], instance_vpcid=one['cdbInstanceVip'], status=one['status'], task_status=one['taskStatus'], pay_type=one['payType'], zone_id=one['zoneId'], storage_size=one['storageSize'], mem=str(one['memory']), volume=one['volume'], autoRenew=one['autoRenew'], max_query=one['maxQueryCount'], type_set=one['cdbTypeSet'], vport=one['cdbInstanceVport'], deadline_time=one['cdbInstanceDeadlineTime'], create_time=one['cdbInstanceCreateTime'], status_color=date_color) new_rds.save() all_servers = RdsModel.objects.filter(server_type='qcloud') for one in all_servers: if one.instanceid not in all_keys: one.delete() except Exception, e: print traceback.format_exc() #购买数据库 def create_qcloud_rds(months, num, mem, volume, zone): params = {'cdbType': 'CUSTOM', 'engineVersion': '5.6', 'period': months, 'goodsNum': num, 'memory': mem, 'volume': volume, 'zoneId': zone} result = qcloud('cdb', 'CreateCdb', 'sh', params) #result = {'message': 'just try'} logger.error('购买腾讯云数据库,参数为: ' + json.dumps(params)) logger.error('购买结果为: ' + json.dumps(result)) if 'Success' in json.dumps(result): return '购买成功' else: return '可能出错了,请联系管理员.'
params.update({"zoneId": region})
conditional_block
qcloud.py
#!/usr/bin/python # -*- coding: utf-8 -*- from api.QcloudApi.qcloudapi import QcloudApi import json import sys import datetime import traceback import logging import re from utils import send_alarm from models import ServersModel, RdsModel, ServerConf from Free.settings import QCLOUD_KEY, QCLOUD_VALUE reload(sys) sys.setdefaultencoding('utf-8') logger = logging.getLogger("free") STATUS_CH = {'1': '故障', '2': '运行中', '3': '创建中', '4': '已关机', '5': '已退还', '6': '退还中', '7': '重启中', '8': '开机中', '9': '关机中', '10': '密码重置中', '11': '格式化中', '12': '镜像制作中', '13': '带宽设置中', '14': '重装系统中', '15': '域名绑定中', '16': '域名解绑中', '17': '负载均衡绑定中', '18': '负载均衡解绑中', '19': '升级中', '20': '秘钥下发中', '21': '维护中'} PAY_TYPE = {'0': '按月结算的后付费', '1': "包年包月", "2": '按量计费'} NET_PAY = {'0': '按月结算的后付费', '1': '包年包月', '2': '按流量', '3': "按带宽"} #腾讯给的调用api的SDK def qcloud(module, action, region, params): config = { 'Region': region, 'secretId': QCLOUD_KEY, 'secretKey': QCLOUD_VALUE, 'method': 'post' } try: service = QcloudApi(module, config) response = service.call(action, params) obj = json.loads(response) return obj except Exception, e: print 'exception:', e #获取上海,广州,北京的服务器信息,且存入数据库 def deal_qcloud(): all_keys = [] for regi in ("sh", "gz", "bj"): result = qcloud('cvm', 'DescribeInstances', regi, {'limit': 99}) if 'instanceSet' in result: result = result.pop('instanceSet') else: continue for item in result: all_keys.append(item['unInstanceId']) one = {} for key in item.keys(): if isinstance(item[key], dict): for n_key in item[key].keys(): one.update({str(key) + '_' + str(n_key): str(item[key][n_key])}) else: if key == "status": item[key] = STATUS_CH[str(item[key])] if isinstance(item[key], list): item[key] = item[key][0] try: one.update({str(key): str(item[key])}) except Exception, e: one.update({str(key): item[key]}) change = {"status": STATUS_CH, "cvmPayMode": PAY_TYPE, "networkPayMode": NET_PAY} for t_name, t_value in change.items(): try: one[t_name] = t_value[one[t_name]] except Exception, e: continue atime = one["deadlineTime"].split(' ') atime = atime[0].split('-') d3 = datetime.datetime(int(atime[0]), int(atime[1]), int(atime[2])) if 0 <= (d3 - datetime.datetime.now()).days < 10: date_color = 'red' elif (d3 - datetime.datetime.now()).days < 0: date_color = 'black' else: date_color = 'green' server = ServersModel.objects.filter(instanceid=one["unInstanceId"]) if server: try: server.update(server_from='qcloud', dick_root=one["diskInfo_rootSize"], dick_storage=one["diskInfo_storageSize"], create_time = one["createTime"], expired_time = one["deadlineTime"], eip_intercharge_type = one["networkPayMode"], internet_charge_type = one["networkPayMode"], image_id = one["os"], instance_name = one["instanceName"], status = one["status"], instanceid = one["unInstanceId"],zone_id = one["zoneName"], cpu = one["cpu"], instance_charge_type = one["cvmPayMode"], memory = one["mem"], public_ip = one["wanIpSet"], region_id = one["Region"], eip_bandwidth = one["bandwidth"], inner_ip = one["lanIp"], status_color= date_color) except Exception, e: logger.error(traceback.format_exc()) else: one = ServersModel.objects.create(server_from='qcloud', dick_root=one["diskInfo_rootSize"], dick_storage=one["diskInfo_storageSize"], create_time = one["createTime"], expired_time = one["deadlineTime"], eip_intercharge_type = one["networkPayMode"], internet_charge_type = one["networkPayMode"], image_id = one["os"], instance_name = one["instanceName"], status = one["status"], instanceid = one["unInstanceId"],zone_id = one["zoneName"], cpu = one["cpu"], instance_charge_type = one["cvmPayMode"], memory = one["mem"], public_ip = one["wanIpSet"], region_id = one["Region"], eip_bandwidth = one["bandwidth"], inner_ip = one["lanIp"], status_color= date_color) one.save() all_servers = ServersModel.objects.filter(server_from="qcloud") for one in all_servers: if one.instanceid not in all_keys: one.delete() # 对腾讯云服务器的操作:包括启动,停止和重启。这个api允许一次执行多个实例的,但页面上没有实现 def op_server(instanceid, action, region): result = qcloud("cvm", action, region, {"instanceIds.1": instanceid}) return result #修改腾讯云服务器名称 def qcloud_change_name(instanceid, action, region, new_name): result = qcloud("cvm", action, region, {"instanceId": instanceid, "instanceName": new_name}) return result #购买腾讯云服务器实例 def create_qcloud(data): region = data.pop("change_region_cvm") params = {"wanlp": "1", "needSecurityAgent": "1", "needMonitorAgent": "1", "storageType": '2'} passwd = data['passwd1'] match = re.match(ur'^([a-z,A-z,0-9]{8,16}|[0-9,\W]{8,16}|[a-z,A-Z,\W]{8,16}|[a-z,A-Z,0-9,\W]{8,16})$', passwd) if not match: return "密码格式有误,请按要求输入" else: params.update({"password": passwd}) for key, value in {"100002": "region_g2", "100003": "region_g3", "200001": "region_s1", "800001": "region_b1", "300001": "region_x1"}.items(): if region == key: config = data[value] config = config.split("-") params.update({"cpu": config[0]}) params.update({"mem": config[1]}) params.update({"zoneId": region}) break region_change = {"100002": "gz", "100003": "gz", "200001": "sh", "800001": "bj", "300001": 'xg'} for key, value in data.items(): if key in ("region_g2", 'region_g3', "region_s1", "region_b1", "region_x1", "passwd1", "passwd2", "csrfmiddlewaretoken"): continue params.update({key: value}) logger.error('购买腾讯云服务器,参数: ' + json.dumps(params)) result = qcloud("cvm", "RunInstances", region_change[region], params) logger.error('购买完成,result is : ' + json.dumps(result)) if result["message"] == "": result = "购买成功" else: result = result["message"] return result #获取服务器信息 def get_rds(): try: result = qcloud('cdb', 'DescribeCdbInstances', 'sh', {}) TAST_TRAN = {'0': '没有任务', '1': '升级中', '2': '数据导入中', '3': '开放Slave中', '4': '外网访问开通中', '5': '批量操作执行中', '6': '回档中', '7':'外网访问关闭中', '8': '密码修改中', '9': '实例名修改中', '10': '重启中', '12': '自建迁移中', '13': '删除库表中','14': '灾备实例创建同步中'} PAY_TRAN = {'0': '包年包月', '1': '按量计费', '2': '后付费月结'} results = result['cdbInstanceSet'] all_keys = [] for one in results: all_keys.append(one["uInstanceId"]) one['taskStatus'] = TAST_TRAN[str(one['taskStatus'])] one['payType'] = PAY_TRAN[str(one['payType'])] zone = ServerConf.objects.get(server_type='qcloud', info_type='zone', key=one['zoneId'])
one['status'] ='运行中' else: one['status'] = '创建中' for key,value in one.items(): one[key] = str(value) atime = one["cdbInstanceDeadlineTime"].split(' ') atime = atime[0].split('-') d3 = datetime.datetime(int(atime[0]), int(atime[1]), int(atime[2])) if 0 <= (d3 - datetime.datetime.now()).days < 10: date_color = 'red' elif (d3 - datetime.datetime.now()).days < 0: date_color = 'black' else: date_color = 'green' rds = RdsModel.objects.filter(instanceid=one['uInstanceId']) if rds: new_rds = rds.update(instanceid=one['uInstanceId'], engine_version= 'mysql' + one['engineVersion'], instance_type=one['cdbType'], instance_name=one['cdbInstanceName'], vpcid=one['vpcId'], instance_vpcid=one['cdbInstanceVip'], status=one['status'], task_status=one['taskStatus'], pay_type=one['payType'], zone_id=one['zoneId'], storage_size=one['storageSize'], mem=one['memory'], volume=one['volume'], autoRenew=one['autoRenew'], max_query=one['maxQueryCount'], type_set=one['cdbTypeSet'], vport=one['cdbInstanceVport'], deadline_time=one['cdbInstanceDeadlineTime'], create_time=one['cdbInstanceCreateTime'],status_color=date_color) else: new_rds = RdsModel.objects.create(instanceid=one['uInstanceId'], engine_version= 'mysql' + one['engineVersion'], instance_type=one['cdbType'], instance_name=one['cdbInstanceName'], vpcid=one['vpcId'], instance_vpcid=one['cdbInstanceVip'], status=one['status'], task_status=one['taskStatus'], pay_type=one['payType'], zone_id=one['zoneId'], storage_size=one['storageSize'], mem=str(one['memory']), volume=one['volume'], autoRenew=one['autoRenew'], max_query=one['maxQueryCount'], type_set=one['cdbTypeSet'], vport=one['cdbInstanceVport'], deadline_time=one['cdbInstanceDeadlineTime'], create_time=one['cdbInstanceCreateTime'], status_color=date_color) new_rds.save() all_servers = RdsModel.objects.filter(server_type='qcloud') for one in all_servers: if one.instanceid not in all_keys: one.delete() except Exception, e: print traceback.format_exc() #购买数据库 def create_qcloud_rds(months, num, mem, volume, zone): params = {'cdbType': 'CUSTOM', 'engineVersion': '5.6', 'period': months, 'goodsNum': num, 'memory': mem, 'volume': volume, 'zoneId': zone} result = qcloud('cdb', 'CreateCdb', 'sh', params) #result = {'message': 'just try'} logger.error('购买腾讯云数据库,参数为: ' + json.dumps(params)) logger.error('购买结果为: ' + json.dumps(result)) if 'Success' in json.dumps(result): return '购买成功' else: return '可能出错了,请联系管理员.'
one['zoneId'] = zone.value if one['status'] == 1:
random_line_split
views.py
from django.core.paginator import Paginator, EmptyPage from django.shortcuts import render from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from logging import getLogger from django_redis import get_redis_connection from decimal import Decimal import json from django import http from django.utils import timezone from django.db import transaction from users.models import Address from goods.models import SKU from meiduo_mall.utils import constants from meiduo_mall.utils.auth_backend import LoginRequiredJsonMixin from .models import OrderInfo, OrderGoods from meiduo_mall.utils.response_code import RETCODE, err_msg logger = getLogger('django') class GoodsCommentView(View): """订单商品评价信息""" def get(self, request, sku_id): # 获取被评价的订单商品信息 order_goods_list = OrderGoods.objects.filter(sku_id=sku_id, is_commented=True).order_by('-create_time')[:constants.COMMENTS_LIST_LIMIT] # 序列化 comment_list = [] for order_goods in order_goods_list: username = order_goods.order.user.username comment_list.append({ 'username': username[0] + '***' + username[-1] if order_goods.is_anonymous else username, 'comment': order_goods.comment, 'score': order_goods.score, }) return http.JsonResponse({'code': RETCODE.OK, 'errmsg': err_msg[RETCODE.OK], 'comment_list': comment_list}) class OrderCommentView(LoginRequiredMixin, View): """订单商品评价""" def get(self, request): """展示商品评价页面""" # 接收参数 order_id = request.GET.get('order_id') # 校验参数 try: OrderInfo.objects.get(order_id=order_id, user=request.user) except OrderInfo.DoesNotExist: return http.HttpResponseNotFound('订单不存在') # 查询订单中未被评价的商品信息 try: uncomment_goods = OrderGoods.objects.filter(order_id=order_id, is_commented=False) except Exception as e: logger.error(e) return http.HttpResponseServerError('订单商品信息出错') # 构造待评价商品数据 uncomment_goods_list = [] for goods in uncomment_goods: uncomment_goods_list.append({ 'order_id': goods.order.order_id, 'sku_id': goods.sku.id, 'name': goods.sku.name, 'price': str(goods.price), 'default_image_url': goods.sku.default_image.url, 'comment': goods.comment, 'score': goods.score, 'is_anonymous': str(goods.is_anonymous), }) # 渲染模板 context = { 'uncomment_goods_list': uncomment_goods_list } return render(request, 'goods_judge.html', context) def post(self, request): """评价订单商品""" # 接收参数 json_dict = json.loads(request.body.decode()) order_id = json_dict.get('order_id') sku_id = json_dict.get('sku_id') score = json_dict.get('score') comment = json_dict.get('comment') is_anonymous = json_dict.get('is_anonymous') # 校验参数 if not all([order_id, sku_id, score, comment]): return http.HttpResponseForbidden('缺少必传参数') try: OrderInfo.objects.filter(order_id=order_id, user=request.user, status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']) except OrderInfo.DoesNotExist: return http.HttpResponseForbidden('参数order_id错误') try: sku = SKU.objects.get(id=sku_id) except SKU.DoesNotExist: return http.HttpResponseForbidden('参数sku_id错误') if is_anonymous: if not isinstance(is_anonymous, bool): return http.HttpResponseForbidden('参数is_anonymous错误') # 以下操作数据库的操作,开启作为一次事务 with transaction.atomic(): # 在数据库操作前,创建保存点(数据库最初的状态) save_id = transaction.savepoint() try: # 保存订单商品评价数据 OrderGoods.objects.filter(order_id=order_id, sku_id=sku_id, is_commented=False).update( comment=comment, score=score, is_anonymous=is_anonymous, is_commented=True ) # 累计评论数据 sku.comments += 1 sku.save() sku.spu.comments += 1 sku.spu.save() # 如果所有订单商品都已评价,则修改订单状态为已完成 if OrderGoods.objects.filter(order_id=order_id, is_commented=False).count() == 0: OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['FINISHED']) # 对于未知的数据库错误,暴力回滚 except Exception as e: logger.error(e) transaction.savepoint_rollback(save_id) return http.JsonResponse({'code': RETCODE.COMMITMENTERR, 'errmsg': err_msg[RETCODE.COMMITMENTERR]}) else: # 提交事务 transaction.savepoint_commit(save_id) return http.JsonResponse({'code': RETCODE.OK, 'errmsg': err_msg[RETCODE.OK]}) class UserOrderInfoView(LoginRequiredMixin, View): """我的订单""" def get(self, request, page_num): """提供我的订单页面""" user = request.user # 查询订单 orders = user.orderinfo_set.all().order_by("-create_time") # 遍历所有订单 for order in orders: # 绑定订单状态 order.status_name = OrderInfo.ORDER_STATUS_CHOICES[order.status-1][1] # 绑定支付方式 order.pay_method_name = OrderInfo.PAY_METHOD_CHOICES[order.pay_method-1][1] order.sku_list = [] # 查询订单商品 order_goods = order.skus.all() # 遍历订单商品 for order_good in order_goods: sku = order_good.sku sku.count = order_good.count sku.amount = sku.price * sku.count order.sku_list.append(sku) # 分页 page_num = int(page_num) try: paginator = Paginator(orders, constants.ORDERS_LIST_LIMIT) page_orders = paginator.page(page_num) total_page = paginator.num_pages except EmptyPage: return http.HttpResponseNotFound('订单不存在') context = { "page_orders": page_orders, 'total_page': total_page, 'page_num': page_num, } return render(request, "user_center_order.html", context) class OrderSuccessView(LoginRequiredMixin, View): """订单成功页面""" def get(self, request): """提供订单成功页面""" # 接受参数 order_id = request.GET.get('order_id') payment_amount = request.GET.get('payment_amount') pay_method = request.GET.get('pay_method') # 构造上下文 context = { 'order_id': order_id, 'payment_amount': payment_amount, 'pay_method': pay_method } return render(request, 'order_success.html', context) class OrderCommitView(LoginRequiredJsonMixin, View): """提交订单""" def post(self, request): """保存订单基本信息和订单商品信息""" # 接收参数 json_dict = json.loads(request.body.decode()) address_id = json_dict.get('address_id') pay_method = json_dict.get('pay_method') # 校验参数 if not all([address_id, pay_method]): return http.HttpResponseForbidden('缺少必传参数') # 判断address_id是否合法 try: address = Address.objects.get(id=address_id) except Exception as e: logger.error(e) return http.HttpResponseForbidden('参数address_id错误') # 判断pay_method是否合法 if pay_method not in [OrderInfo.PAY_METHODS_ENUM['CASH'], OrderInfo.PAY_METHODS_ENUM['ALIPAY']]: return http.HttpResponseForbidden('参数pay_method错误') # 以下操作数据库的操作,开启作为一次事务 with transaction.atomic(): # 在数据库操作前,创建保存点(数据库最初的状态) save_id = transaction.savepoint() # 获取登录用户 user = request.user # 获取订单编号:时间 + user_id == '2020123113041200000001' order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') + '{:0>9d}'.format(user.id) try: # 保存订单基本信息(一) order = OrderInfo.objects.create( order_id=order_id, user=user, address=address, total_count=0, # 仅用来初始化,后面根据订单中的商品进行更新 total_amount=Decimal('0.00'), # 仅用来初始化,后面根据订单中的商品进行更新 freight=Decimal(constants.ORDERS_FREIGHT_COST), pay_method=pay_method, # 如果支付方式为支付宝,支付状态为未付款,如果支付方式是货到付款,支付状态为未发货 status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'] if pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY'] else OrderInfo.ORDER_STATUS_ENUM['UNSEND'] ) # 保存订单商品信息(多) # 查询redis中购物车被勾选的商品 redis_conn = get_redis_connection('carts') # 购物车中商品的数量 redis_cart = redis_conn.hgetall('carts_%s' % user.id) # 被勾选的商品sku_id redis_selected = redis_conn.smembers('selected_{}'.format(user.id)) # 构造购物车中被勾选商品的数据 new_cart_dict,{sku_id: 2, sku_id: 1} new_cart_dict = {} for sku_id in redis_selected: new_cart_dict[int(sku_id)] = int(redis_cart[sku_id]) # 获取被勾选商品的sku_id sku_ids = new_cart_dict.keys() for sku_id in sku_ids: # 每个商品都有多次下单的机会,直到库存不足 while True: # 读取商品的sku信息 sku = SKU.objects.get(id=sku_id) # 查询商品和库存信息时,不能出现缓存,所有不用 filter(id__in=sku_ids) # 获取当前被勾选商品的库存 sku_count = new_cart_dict[sku.id] # 获取sku商品原始的库存stock和销量sales origin_stock = sku.stock origin_sales = sku.sales # # 模型网络延迟 # import time # time.sleep(5) # 如果订单中的商品数量大于库存,响应库存不足 if sku_count > origin_stock: # 库存不足,回滚 transaction.savepoint_rollback(save_id) print(request.user, '库存不足') return http.JsonResponse({'code': RETCODE.STOCKERR, 'errmsg': err_msg[RETCODE.STOCKERR]}) # 如果库存满足,SKU 减库存,加销量 new_stock = origin_stock - sku_count new_sales = origin_sales + sku_count result = SKU.objects.filter(id=sku_id, stock=origin_stock).update(stock=new_stock, sales=new_sales) # 如果在更新数据时,原始数据变化了,那么返回0,表示有资源抢夺 if result == 0: # 由于其他用户提前对该商品完成下单,该商品此次下单失败,重新进行下单 continue # SPU 加销量 sku.spu.sales += sku_count sku.spu.save() OrderGoods.objects.create( order=order, sku=sku, count=sku_count, price=sku.price, ) # 累加订单中商品的总价和总数量 order.total_count += sku_count order.total_amount += (sku_count * sku.price) # 该件商品下单成功,退出循环 break # 添加邮费和保存订单信息 order.total_amount += order.freight order.save() # 对于未知的数据库错误,暴力回滚 except Exception as e: logger.error(e) transaction.savepoint_rollback(save_id) return http.JsonResponse({'code': RETCODE.ORDEROPERATEERR, 'errmsg': err_msg[RETCODE.ORDEROPERATEERR]}) else: # 提交事务 transaction.savepoint_commit(save_id) # 清除购物车中已结算的商品 pl = redis_conn.pipeline() pl.hdel('carts_%s' % user.id, *redis_selected) pl.srem('selected_%s' % user.id, *redis_selected) try: pl.execute() except Exception as e: logger.error(e) return http.JsonResponse({'code': RETCODE.DUPLICATEORDERERR, 'errmsg': err_msg[RETCODE.DUPLICATEORDERERR]}) else: # 返回响应 return http.JsonResponse({'code': RETCODE.OK, 'errmsg': err_msg[RETCODE.OK], 'order_id': order_id}) class OrderSettlementView(LoginRequiredMixin, View): """结算订单""" def get(self, request): """查询并展示要结算的订单数据""" # 获取登录用户 user = request.user # 查询用户收货地址,没有被删除的收货地址 try: addresses = Address.objects.filter(user=user, is_deleted=False) except Exception as e: logger.error(e) # 如果没有查询出收货地址,可以去编辑收货地址 addresses = None # 查询redis中购物车被勾选的商品 redis_conn = get_redis_connection('carts') # 购物车中商品的数量
# 构造购物车中被勾选商品的数据 new_cart_dict,{sku_id: 2, sku_id: 1} new_cart_dict = {} for sku_id in redis_selected: new_cart_dict[int(sku_id)] = int(redis_cart[sku_id]) # 获取被勾选商品的sku_id sku_ids = new_cart_dict.keys() # 获取被勾选商品的sku信息 skus = SKU.objects.filter(id__in=sku_ids) # 商品总数量与商品总金额 total_count = 0 total_amount = Decimal(0.00) # 或 Decimal('0.00') for sku in skus: # 遍历skus,给每个sku补充count(数量)和amount(小计)字段 sku.count = new_cart_dict[sku.id] sku.amount = sku.price * sku.count # Decimal类型 # 累加商品数量和金额 total_count += sku.count total_amount += sku.amount # 构造上下文 context = { 'addresses': addresses, 'skus': skus, 'total_count': total_count, 'total_amount': total_amount, 'freight': constants.ORDERS_FREIGHT_COST, # 运费 'payment_amount': Decimal(constants.ORDERS_FREIGHT_COST) + total_amount, } return render(request, 'place_order.html', context)
redis_cart = redis_conn.hgetall('carts_%s' % user.id) # 被勾选的商品sku_id redis_selected = redis_conn.smembers('selected_{}'.format(user.id))
random_line_split
views.py
from django.core.paginator import Paginator, EmptyPage from django.shortcuts import render from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from logging import getLogger from django_redis import get_redis_connection from decimal import Decimal import json from django import http from django.utils import timezone from django.db import transaction from users.models import Address from goods.models import SKU from meiduo_mall.utils import constants from meiduo_mall.utils.auth_backend import LoginRequiredJsonMixin from .models import OrderInfo, OrderGoods from meiduo_mall.utils.response_code import RETCODE, err_msg logger = getLogger('django') class GoodsCommentView(View): """订单商品评价信息""" def get(self, request, sku_id): # 获取被评价的订单商品信息 order_goods_list = OrderGoods.objects.filter(sku_id=sku_id, is_commented=True).order_by('-create_time')[:constants.COMMENTS_LIST_LIMIT] # 序列化 comment_list = [] for order_goods in order_goods_list: username = order_goods.order.user.username comment_list.append({ 'username': username[0] + '***' + username[-1] if order_goods.is_anonymous else username, 'comment': order_goods.comment, 'score': order_goods.score, }) return http.JsonResponse({'code': RETCODE.OK, 'errmsg': err_msg[RETCODE.OK], 'comment_list': comment_list}) class OrderCommentView(LoginRequiredMixin, View): """订单商品评价""" def get(self, request): """展示商品评价页面""" # 接收参数 order_id = request.GET.get('order_id') # 校验参数 try: OrderInfo.objects.get(order_id=order_id, user=request.user) except OrderInfo.DoesNotExist: return http.HttpResponseNotFound('订单不存在') # 查询订单中未被评价的商品信息 try: uncomment_goods = OrderGoods.objects.filter(order_id=order_id, is_commented=False) except Exception as e: logger.error(e) return http.HttpResponseServerError('订单商品信息出错') # 构造待评价商品数据 uncomment_goods_list = [] for goods in uncomment_goods: uncomment_goods_list.append({ 'order_id': goods.order.order_id, 'sku_id': goods.sku.id, 'name': goods.sku.name, 'price': str(goods.price), 'default_image_url': goods.sku.default_image.url, 'comment': goods.comment, 'score': goods.score, 'is_anonymous': str(goods.is_anonymous), }) # 渲染模板 context = { 'uncomment_goods_list': uncomment_goods_list } return render(request, 'goods_judge.html', context) def post(self, request): """评价订单商品""" # 接收参数 json_dict = json.loads(request.body.decode()) order_id = json_dict.get('order_id') sku_id = json_dict.get('sku_id') score = json_dict.get('score') comment = json_dict.get('comment') is_anonymous = json_dict.get('is_anonymous') # 校验参数 if not all([order_id, sku_id, score, comment]): return http.HttpResponseForbidden('缺少必传参数') try: OrderInfo.objects.filter(order_id=order_id, user=request.user, status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']) except OrderInfo.DoesNotExist: return http.HttpResponseForbidden('参数order_id错误') try: sku = SKU.objects.get(id=sku_id) except SKU.DoesNotExist: return http.HttpResponseForbidden('参数sku_id错误') if is_anonymous: if not isinstance(is_anonymous, bool): return http.HttpResponseForbidden('参数is_anonymous错误') # 以下操作数据库的操作,开启作为一次事务 with transaction.atomic(): # 在数据库操作前,创建保存点(数据库最初的状态) save_id = transaction.savepoint() try: # 保存订单商品评价数据 OrderGoods.objects.filter(order_id=order_id, sku_id=sku_id, is_commented=False).update( comment=comment, score=score, is_anonymous=is_anonymous, is_commented=True ) # 累计评论数据 sku.comments += 1 sku.save() sku.spu.comments += 1 sku.spu.save() # 如果所有订单商品都已评价,则修改订单状态为已完成 if OrderGoods.objects.filter(order_id=order_id, is_commented=False).count() == 0: OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['FINISHED']) # 对于未知的数据库错误,暴力回滚 except Exception as e: logger.error(e) transaction.savepoint_rollback(save_id) return http.JsonResponse({'code': RETCODE.COMMITMENTERR, 'errmsg': err_msg[RETCODE.COMMITMENTERR]}) else: # 提交事务 transaction.savepoint_commit(save_id) return http.JsonResponse({'code': RETCODE.OK, 'errmsg': err_msg[RETCODE.OK]}) class UserOrderInfoView(LoginRequiredMixin, View): """我的订单""" def get(self, request, page_num): """提供我的订单页面""" user = request.user # 查询订单 orders = user.orderinfo_set.all().order_by("-create_time") # 遍历所有订单 for order in orders: # 绑定订单状态 order.status_name = OrderInfo.ORDER_STATUS_CHOICES[order.status-1][1] # 绑定支付方式 order.pay_method_name = OrderInfo.PAY_METHOD_CHOICES[order.pay_method-1][1] order.sku_list = [] # 查询订单商品 order_goods = order.skus.all() # 遍历订单商品 for order_good in order_goods: sku = order_good.sku sku.count = order_good.count sku.amount = sku.price * sku.count order.sku_list.append(sku) # 分页 page_num = int(page_num) try: paginator = Paginator(orders, constants.ORDERS_LIST_LIMIT) page_orders = paginator.page(page_num) total_page = paginator.num_pages except EmptyPage: return http.HttpResponseNotFound('订单不存在') context = { "page_orders": page_orders, 'total_page': total_page, 'page_num': page_num, } return render(request, "user_center_order.html", context) class OrderSuccessView(LoginRequiredMixin, View): """订单成功页面""" def get(self, request): """提供订单成功页面""" # 接受参数 order_id = request.GET.get('order_id') payment_amount = request.GET.get('payment_amount') pay_method = request.GET.get('pay_method') # 构造上下文 context = { 'order_id': order_id, 'payment_amount': payment_amount, 'pay_method': pay_method } return render(request, 'order_success.html', context) class OrderCommitView(LoginRequiredJsonMixin, View): """提交订单""" def post(self, request): """保存订单基本信息和订单商品信息""" # 接收参数 json_dict = json.loads(request.body.decode()) address_id = json_dict.get('address_id') pay_method = json_dict.get('pay_method') # 校验参数 if not all([address_id, pay_method]): return http.HttpResponseForbidden('缺少必传参数') # 判断address_id是否合法 try: address = Address.objects.get(id=address_id) except Exception as e: logger.error(e) return http.HttpResponseForbidden('参数address_id错误') # 判断pay_method是否合法 if pay_method not in [OrderInfo.PAY_METHODS_ENUM['CASH'], OrderInfo.PAY_METHODS_ENUM['ALIPAY']]: return http.HttpResponseForbidden('参数pay_method错误') # 以下操作数据库的操作,开启作为一次事务 with transaction.atomic(): # 在数据库操作前,创建保存点(数据库最初的状态) save_id = transaction.savepoint() # 获取登录用户 user = request.user # 获取订单编号:时间 + user_id == '2020123113041200000001' order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') + '{:0>9d}'.format(user.id) try: # 保存订单基本信息(一) order = OrderInfo.objects.create( order_id=order_id, user=user, address=address, total_count=0, # 仅用来初始化,后面根据订单中的商品进行更新 total_amount=Decimal('0.00'), # 仅用来初始化,后面根据订单中的商品进行更新 freight=Decimal(constants.ORDERS_FREIGHT_COST), pay_method=pay_method, # 如果支付方式为支付宝,支付状态为未付款,如果支付方式是货到付款,支付状态为未发货 status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'] if pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY'] else OrderInfo.ORDER_STATUS_ENUM['UNSEND'] ) # 保存订单商品信息(多) # 查询redis中购物车被勾选的商品 redis_conn = get_redis_connection('carts') # 购物车中商品的数量 redis_cart = redis_conn.hgetall('carts_%s' % user.id) # 被勾选的商品sku_id redis_selected = redis_conn.smembers('selected_{}'.format(user.id)) # 构造购物车中被勾选商品的数据 new_cart_dict,{sku_id: 2, sku_id: 1} new_cart_dict = {} for sku_id in redis_selected: new_cart_dict[int(sku_id)] = int(redis_cart[sku_id]) # 获取被勾选商品的sku_id sku_ids = new_cart_dict.keys() for sku_id in sku_ids: # 每个商品都有多次下单的机会,直到库存不足 while True: # 读取商品的sku信息 sku = SKU.objects.get(id=sku_id) # 查询商品和库存信息时,不能出现缓存,所有不用 filter(id__in=sku_ids) # 获取当前被勾选商品的库存 sku_count = new_cart_dict[sku.id] # 获取sku商品原始的库存stock和销量sales origin_stock = sku.stock origin_sales = sku.sales # # 模型网络延迟 # import time # time.sleep(5) # 如果订单中的商品数量大于库存,响应库存不足 if sku_count > origin_stock: # 库存不足,回滚 transaction.savepoint_rollback(save_id) print(request.user, '库存不足') return http.JsonResponse({'code': RETCODE.STOCKERR, 'errmsg': err_msg[RETCODE.STOCKERR]}) # 如果库存满足,SKU 减库存,加销量 new_stock = origin_stock - sku_count new_sales = origin_sales + sku_count result = SKU.objects.filter(id=sku_id, stock=origin_stock).update(stock=new_stock, sales=new_sales) # 如果在更新数据时,原始数据变化了,那么返回0,表示有资源抢夺 if result == 0: # 由于其他用户提前对该商品完成下单,该商品此次下单失败,重新进行下单 continue # SPU 加销量 sku.spu.sales += sku_count sku.spu.save() OrderGoods.objects.create( order=order, sku=sku, count=sku_count, price=sku.price, ) # 累加订单中商品的总价和总数量 order.total_count += sku_count order.total_amount += (sku_count * sku.price) # 该件商品下单成功,退出循环 break # 添加邮费和保存订单信息 order.total_amount += order.freight order.save() # 对于未知的数据库错误,暴力回滚 except Exception as e: logger.error(e) transaction.savepoint_rollback(save_id) return http.JsonResponse({'code': RETCODE.ORDEROPERATEERR, 'errmsg': err_msg[RETCODE.ORDEROPERATEERR]}) else: # 提交事务 transaction.savepoint_commit(save_id) # 清除购物车中已结算的商品 pl = redis_conn.pipeline() pl.hdel('carts_%s' % user.id, *redis_selected) pl.srem('selected_%s' % user.id, *redis_selected) try: pl.execute() except Exception as e: logger.error(e) return http.JsonResponse({'code': RETCODE.DUPLICATEORDERERR, 'errmsg': err_msg[RETCODE.DUPLICATEORDERERR]})
lse: # 返回响应 return http.JsonResponse({'code': RETCODE.OK, 'errmsg': err_msg[RETCODE.OK], 'order_id': order_id}) class OrderSettlementView(LoginRequiredMixin, View): """结算订单""" def get(self, request): """查询并展示要结算的订单数据""" # 获取登录用户 user = request.user # 查询用户收货地址,没有被删除的收货地址 try: addresses = Address.objects.filter(user=user, is_deleted=False) except Exception as e: logger.error(e) # 如果没有查询出收货地址,可以去编辑收货地址 addresses = None # 查询redis中购物车被勾选的商品 redis_conn = get_redis_connection('carts') # 购物车中商品的数量 redis_cart = redis_conn.hgetall('carts_%s' % user.id) # 被勾选的商品sku_id redis_selected = redis_conn.smembers('selected_{}'.format(user.id)) # 构造购物车中被勾选商品的数据 new_cart_dict,{sku_id: 2, sku_id: 1} new_cart_dict = {} for sku_id in redis_selected: new_cart_dict[int(sku_id)] = int(redis_cart[sku_id]) # 获取被勾选商品的sku_id sku_ids = new_cart_dict.keys() # 获取被勾选商品的sku信息 skus = SKU.objects.filter(id__in=sku_ids) # 商品总数量与商品总金额 total_count = 0 total_amount = Decimal(0.00) # 或 Decimal('0.00') for sku in skus: # 遍历skus,给每个sku补充count(数量)和amount(小计)字段 sku.count = new_cart_dict[sku.id] sku.amount = sku.price * sku.count # Decimal类型 # 累加商品数量和金额 total_count += sku.count total_amount += sku.amount # 构造上下文 context = { 'addresses': addresses, 'skus': skus, 'total_count': total_count, 'total_amount': total_amount, 'freight': constants.ORDERS_FREIGHT_COST, # 运费 'payment_amount': Decimal(constants.ORDERS_FREIGHT_COST) + total_amount, } return render(request, 'place_order.html', context)
e
conditional_block
views.py
from django.core.paginator import Paginator, EmptyPage from django.shortcuts import render from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from logging import getLogger from django_redis import get_redis_connection from decimal import Decimal import json from django import http from django.utils import timezone from django.db import transaction from users.models import Address from goods.models import SKU from meiduo_mall.utils import constants from meiduo_mall.utils.auth_backend import LoginRequiredJsonMixin from .models import OrderInfo, OrderGoods from meiduo_mall.utils.response_code import RETCODE, err_msg logger = getLogger('django') class GoodsCommentView(View): """订单商品评价信息""" def get(self, request, sku_id): # 获取被评价的订单商品信息 order_goods_list = OrderGoods.objects.filter(sku_id=sku_id, is_commented=True).order_by('-create_time')[:constants.COMMENTS_LIST_LIMIT] # 序列化 comment_list = [] for order_goods in order_goods_list: username = order_goods.order.user.username comment_list.append({ 'username': username[0] + '***' + username[-1] if order_goods.is_anonymous else username, 'comment': order_goods.comment, 'score': order_goods.score, }) return http.JsonResponse({'code': RETCODE.OK, 'errmsg': err_msg[RETCODE.OK], 'comment_list': comment_list}) class OrderCommentView(LoginRequiredMixin, View): """订单商品评价""" def get(self, request): """展示商品评价页面""" # 接收参数 order_id = request.GET.get('order_id') # 校验参数 try: OrderInfo.objects.get(order_id=order_id, user=request.user) except OrderInfo.DoesNotExist: return http.HttpResponseNotFound('订单不存在') # 查询订单中未被评价的商品信息 try: uncomment_goods = OrderGoods.objects.filter(order_id=order_id, is_commented=False) except Exception as e: logger.error(e) return http.HttpResponseServerError('订单商品信息出错') # 构造待评价商品数据 uncomment_goods_list = [] for goods in uncomment_goods: uncomment_goods_list.append({ 'order_id': goods.order.order_id, 'sku_id': goods.sku.id, 'name': goods.sku.name, 'price': str(goods.price), 'default_image_url': goods.sku.default_image.url, 'comment': goods.comment, 'score': goods.score, 'is_anonymous': str(goods.is_anonymous), }) # 渲染模板 context = { 'uncomment_goods_list': uncomment_goods_list } return render(request, 'goods_judge.html', context) def post(self, request): """评价订单商品""" # 接收参数 json_dict = json.loads(request.body.decode()) order_id = json_dict.get('order_id') sku_id = json_dict.get('sku_id') score = json_dict.get('score') comment = json_dict.get('comment') is_anonymous = json_dict.get('is_anonymous') # 校验参数 if not all([order_id, sku_id, score, comment]): return http.HttpResponseForbidden('缺少必传参数') try: OrderInfo.objects.filter(order_id=order_id, user=request.user, status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']) except OrderInfo.DoesNotExist: return http.HttpResponseForbidden('参数order_id错误') try: sku = SKU.objects.get(id=sku_id) except SKU.DoesNotExist: return http.HttpResponseForbidden('参数sku_id错误') if is_anonymous: if not isinstance(is_anonymous, bool): return http.HttpResponseForbidden('参数is_anonymous错误') # 以下操作数据库的操作,开启作为一次事务 with transaction.atomic(): # 在数据库操作前,创建保存点(数据库最初的状态) save_id = transaction.savepoint() try: # 保存订单商品评价数据 OrderGoods.objects.filter(order_id=order_id, sku_id=sku_id, is_commented=False).update( comment=comment, score=score, is_anonymous=is_anonymous, is_commented=True ) # 累计评论数据 sku.comments += 1 sku.save() sku.spu.comments += 1 sku.spu.save() # 如果所有订单商品都已评价,则修改订单状态为已完成 if OrderGoods.objects.filter(order_id=order_id, is_commented=False).count() == 0: OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['FINISHED']) # 对于未知的数据库错误,暴力回滚 except Exception as e: logger.error(e) transaction.savepoint_rollback(save_id) return http.JsonResponse({'code': RETCODE.COMMITMENTERR, 'errmsg': err_msg[RETCODE.COMMITMENTERR]}) else: # 提交事务 transaction.savepoint_commit(save_id) return http.JsonResponse({'code': RETCODE.OK, 'errmsg': err_msg[RETCODE.OK]}) class UserOrderInfoView(LoginRequiredMixin, View): """我的订单""" def get(self, request, page_num): """提供我的订单页面""" user = request.user # 查询订单 orders = user.orderinfo_set.all().order_by("-create_time") # 遍历所有订单 for order in orders: # 绑定订单状态 order.status_name = OrderInfo.ORDER_STATUS_CHOICES[order.status-1][1] # 绑定支付方式 order.pay_method_name = OrderInfo.PAY_METHOD_CHOICES[order.pay_method-1][1] order.sku_list = [] # 查询订单商品 order_goods = order.skus.all() # 遍历订单商品 for order_good in order_goods: sku = order_good.sku sku.count = order_good.count sku.amount = sku.price * sku.count order.sku_list.append(sku) # 分页 page_num = int(page_num) try: paginator = Paginator(orders, constants.ORDERS_LIST_LIMIT) page_orders = paginator.page(page_num) total_page = paginator.num_pages except EmptyPage: return http.HttpResponseNotFound('订单不存在') context = { "page_orders": page_orders, 'total_page': total_page, 'page_num': page_num, } return render(request, "user_center_order.html", context) class OrderSuccessView(LoginRequiredMixin, View): """订单成功页面""" def get(self, request): """提供订单成功页面""" # 接受参数 order_id = request.GET.get('order_id') payment_amount = request.GET.get('payment_amount') pay_method = request.GET.get('pay_method') # 构造上下文 context = { 'order_id': order_id, 'payment_amount': payment_amount, 'pay_method': pay_method } return render(request, 'order_success.html', context) class OrderCommitView(LoginRequ
iew): """提交订单""" def post(self, request): """保存订单基本信息和订单商品信息""" # 接收参数 json_dict = json.loads(request.body.decode()) address_id = json_dict.get('address_id') pay_method = json_dict.get('pay_method') # 校验参数 if not all([address_id, pay_method]): return http.HttpResponseForbidden('缺少必传参数') # 判断address_id是否合法 try: address = Address.objects.get(id=address_id) except Exception as e: logger.error(e) return http.HttpResponseForbidden('参数address_id错误') # 判断pay_method是否合法 if pay_method not in [OrderInfo.PAY_METHODS_ENUM['CASH'], OrderInfo.PAY_METHODS_ENUM['ALIPAY']]: return http.HttpResponseForbidden('参数pay_method错误') # 以下操作数据库的操作,开启作为一次事务 with transaction.atomic(): # 在数据库操作前,创建保存点(数据库最初的状态) save_id = transaction.savepoint() # 获取登录用户 user = request.user # 获取订单编号:时间 + user_id == '2020123113041200000001' order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') + '{:0>9d}'.format(user.id) try: # 保存订单基本信息(一) order = OrderInfo.objects.create( order_id=order_id, user=user, address=address, total_count=0, # 仅用来初始化,后面根据订单中的商品进行更新 total_amount=Decimal('0.00'), # 仅用来初始化,后面根据订单中的商品进行更新 freight=Decimal(constants.ORDERS_FREIGHT_COST), pay_method=pay_method, # 如果支付方式为支付宝,支付状态为未付款,如果支付方式是货到付款,支付状态为未发货 status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'] if pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY'] else OrderInfo.ORDER_STATUS_ENUM['UNSEND'] ) # 保存订单商品信息(多) # 查询redis中购物车被勾选的商品 redis_conn = get_redis_connection('carts') # 购物车中商品的数量 redis_cart = redis_conn.hgetall('carts_%s' % user.id) # 被勾选的商品sku_id redis_selected = redis_conn.smembers('selected_{}'.format(user.id)) # 构造购物车中被勾选商品的数据 new_cart_dict,{sku_id: 2, sku_id: 1} new_cart_dict = {} for sku_id in redis_selected: new_cart_dict[int(sku_id)] = int(redis_cart[sku_id]) # 获取被勾选商品的sku_id sku_ids = new_cart_dict.keys() for sku_id in sku_ids: # 每个商品都有多次下单的机会,直到库存不足 while True: # 读取商品的sku信息 sku = SKU.objects.get(id=sku_id) # 查询商品和库存信息时,不能出现缓存,所有不用 filter(id__in=sku_ids) # 获取当前被勾选商品的库存 sku_count = new_cart_dict[sku.id] # 获取sku商品原始的库存stock和销量sales origin_stock = sku.stock origin_sales = sku.sales # # 模型网络延迟 # import time # time.sleep(5) # 如果订单中的商品数量大于库存,响应库存不足 if sku_count > origin_stock: # 库存不足,回滚 transaction.savepoint_rollback(save_id) print(request.user, '库存不足') return http.JsonResponse({'code': RETCODE.STOCKERR, 'errmsg': err_msg[RETCODE.STOCKERR]}) # 如果库存满足,SKU 减库存,加销量 new_stock = origin_stock - sku_count new_sales = origin_sales + sku_count result = SKU.objects.filter(id=sku_id, stock=origin_stock).update(stock=new_stock, sales=new_sales) # 如果在更新数据时,原始数据变化了,那么返回0,表示有资源抢夺 if result == 0: # 由于其他用户提前对该商品完成下单,该商品此次下单失败,重新进行下单 continue # SPU 加销量 sku.spu.sales += sku_count sku.spu.save() OrderGoods.objects.create( order=order, sku=sku, count=sku_count, price=sku.price, ) # 累加订单中商品的总价和总数量 order.total_count += sku_count order.total_amount += (sku_count * sku.price) # 该件商品下单成功,退出循环 break # 添加邮费和保存订单信息 order.total_amount += order.freight order.save() # 对于未知的数据库错误,暴力回滚 except Exception as e: logger.error(e) transaction.savepoint_rollback(save_id) return http.JsonResponse({'code': RETCODE.ORDEROPERATEERR, 'errmsg': err_msg[RETCODE.ORDEROPERATEERR]}) else: # 提交事务 transaction.savepoint_commit(save_id) # 清除购物车中已结算的商品 pl = redis_conn.pipeline() pl.hdel('carts_%s' % user.id, *redis_selected) pl.srem('selected_%s' % user.id, *redis_selected) try: pl.execute() except Exception as e: logger.error(e) return http.JsonResponse({'code': RETCODE.DUPLICATEORDERERR, 'errmsg': err_msg[RETCODE.DUPLICATEORDERERR]}) else: # 返回响应 return http.JsonResponse({'code': RETCODE.OK, 'errmsg': err_msg[RETCODE.OK], 'order_id': order_id}) class OrderSettlementView(LoginRequiredMixin, View): """结算订单""" def get(self, request): """查询并展示要结算的订单数据""" # 获取登录用户 user = request.user # 查询用户收货地址,没有被删除的收货地址 try: addresses = Address.objects.filter(user=user, is_deleted=False) except Exception as e: logger.error(e) # 如果没有查询出收货地址,可以去编辑收货地址 addresses = None # 查询redis中购物车被勾选的商品 redis_conn = get_redis_connection('carts') # 购物车中商品的数量 redis_cart = redis_conn.hgetall('carts_%s' % user.id) # 被勾选的商品sku_id redis_selected = redis_conn.smembers('selected_{}'.format(user.id)) # 构造购物车中被勾选商品的数据 new_cart_dict,{sku_id: 2, sku_id: 1} new_cart_dict = {} for sku_id in redis_selected: new_cart_dict[int(sku_id)] = int(redis_cart[sku_id]) # 获取被勾选商品的sku_id sku_ids = new_cart_dict.keys() # 获取被勾选商品的sku信息 skus = SKU.objects.filter(id__in=sku_ids) # 商品总数量与商品总金额 total_count = 0 total_amount = Decimal(0.00) # 或 Decimal('0.00') for sku in skus: # 遍历skus,给每个sku补充count(数量)和amount(小计)字段 sku.count = new_cart_dict[sku.id] sku.amount = sku.price * sku.count # Decimal类型 # 累加商品数量和金额 total_count += sku.count total_amount += sku.amount # 构造上下文 context = { 'addresses': addresses, 'skus': skus, 'total_count': total_count, 'total_amount': total_amount, 'freight': constants.ORDERS_FREIGHT_COST, # 运费 'payment_amount': Decimal(constants.ORDERS_FREIGHT_COST) + total_amount, } return render(request, 'place_order.html', context)
iredJsonMixin, V
identifier_name
views.py
from django.core.paginator import Paginator, EmptyPage from django.shortcuts import render from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from logging import getLogger from django_redis import get_redis_connection from decimal import Decimal import json from django import http from django.utils import timezone from django.db import transaction from users.models import Address from goods.models import SKU from meiduo_mall.utils import constants from meiduo_mall.utils.auth_backend import LoginRequiredJsonMixin from .models import OrderInfo, OrderGoods from meiduo_mall.utils.response_code import RETCODE, err_msg logger = getLogger('django') class GoodsCommentView(View): """订单商品评价信息""" def get(self, request, sku_id): # 获取被评价的订单商品信息 order_goods_list = OrderGoods.objects.filter(sku_id=sku_id, is_commented=True).order_by('-create_time')[:constants.COMMENTS_LIST_LIMIT] # 序列化 comment_list = [] for order_goods in order_goods_list: username = order_goods.order.user.username comment_list.append({ 'username': username[0] + '***' + username[-1] if order_goods.is_anonymous else username, 'comment': order_goods.comment, 'score': order_goods.score, }) return http.JsonResponse({'code': RETCODE.OK, 'errmsg': err_msg[RETCODE.OK], 'comment_list': comment_list}) class OrderCommentView(LoginRequiredMixin, View): """订单商品评价""" def get(self, request): """展示商品评价页面""" # 接收参数 order_id = request.GET.get('order_id') # 校验参数 try: OrderInfo.objects.get(order_id=order_id, user=request.user) except OrderInfo.DoesNotExist: return http.HttpResponseNotFound('订单不存在') # 查询订单中未被评价的商品信息 try: uncomment_goods = OrderGoods.objects.filter(order_id=order_id, is_commented=False) except Exception as e: logger.error(e) return http.HttpResponseServerError('订单商品信息出错') # 构造待评价商品数据 uncomment_goods_list = [] for goods in uncomment_goods: uncomment_goods_list.append({ 'order_id': goods.order.order_id, 'sku_id': goods.sku.id, 'name': goods.sku.name, 'price': str(goods.price), 'default_image_url': goods.sku.default_image.url, 'comment': goods.comment, 'score': goods.score, 'is_anonymous': str(goods.is_anonymous), }) # 渲染模板 context = { 'uncomment_goods_list': uncomment_goods_list } return render(request, 'goods_judge.html', context) def post(self, request): """评价订单商品""" # 接收参数 json_dict = json.loads(request.body.decode()) order_id = json_dict.get('order_id') sku_id = json_dict.get('sku_id')
hod_name = OrderInfo.PAY_METHOD_CHOICES[order.pay_method-1][1] order.sku_list = [] # 查询订单商品 order_goods = order.skus.all() # 遍历订单商品 for order_good in order_goods: sku = order_good.sku sku.count = order_good.count sku.amount = sku.price * sku.count order.sku_list.append(sku) # 分页 page_num = int(page_num) try: paginator = Paginator(orders, constants.ORDERS_LIST_LIMIT) page_orders = paginator.page(page_num) total_page = paginator.num_pages except EmptyPage: return http.HttpResponseNotFound('订单不存在') context = { "page_orders": page_orders, 'total_page': total_page, 'page_num': page_num, } return render(request, "user_center_order.html", context) class OrderSuccessView(LoginRequiredMixin, View): """订单成功页面""" def get(self, request): """提供订单成功页面""" # 接受参数 order_id = request.GET.get('order_id') payment_amount = request.GET.get('payment_amount') pay_method = request.GET.get('pay_method') # 构造上下文 context = { 'order_id': order_id, 'payment_amount': payment_amount, 'pay_method': pay_method } return render(request, 'order_success.html', context) class OrderCommitView(LoginRequiredJsonMixin, View): """提交订单""" def post(self, request): """保存订单基本信息和订单商品信息""" # 接收参数 json_dict = json.loads(request.body.decode()) address_id = json_dict.get('address_id') pay_method = json_dict.get('pay_method') # 校验参数 if not all([address_id, pay_method]): return http.HttpResponseForbidden('缺少必传参数') # 判断address_id是否合法 try: address = Address.objects.get(id=address_id) except Exception as e: logger.error(e) return http.HttpResponseForbidden('参数address_id错误') # 判断pay_method是否合法 if pay_method not in [OrderInfo.PAY_METHODS_ENUM['CASH'], OrderInfo.PAY_METHODS_ENUM['ALIPAY']]: return http.HttpResponseForbidden('参数pay_method错误') # 以下操作数据库的操作,开启作为一次事务 with transaction.atomic(): # 在数据库操作前,创建保存点(数据库最初的状态) save_id = transaction.savepoint() # 获取登录用户 user = request.user # 获取订单编号:时间 + user_id == '2020123113041200000001' order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') + '{:0>9d}'.format(user.id) try: # 保存订单基本信息(一) order = OrderInfo.objects.create( order_id=order_id, user=user, address=address, total_count=0, # 仅用来初始化,后面根据订单中的商品进行更新 total_amount=Decimal('0.00'), # 仅用来初始化,后面根据订单中的商品进行更新 freight=Decimal(constants.ORDERS_FREIGHT_COST), pay_method=pay_method, # 如果支付方式为支付宝,支付状态为未付款,如果支付方式是货到付款,支付状态为未发货 status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'] if pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY'] else OrderInfo.ORDER_STATUS_ENUM['UNSEND'] ) # 保存订单商品信息(多) # 查询redis中购物车被勾选的商品 redis_conn = get_redis_connection('carts') # 购物车中商品的数量 redis_cart = redis_conn.hgetall('carts_%s' % user.id) # 被勾选的商品sku_id redis_selected = redis_conn.smembers('selected_{}'.format(user.id)) # 构造购物车中被勾选商品的数据 new_cart_dict,{sku_id: 2, sku_id: 1} new_cart_dict = {} for sku_id in redis_selected: new_cart_dict[int(sku_id)] = int(redis_cart[sku_id]) # 获取被勾选商品的sku_id sku_ids = new_cart_dict.keys() for sku_id in sku_ids: # 每个商品都有多次下单的机会,直到库存不足 while True: # 读取商品的sku信息 sku = SKU.objects.get(id=sku_id) # 查询商品和库存信息时,不能出现缓存,所有不用 filter(id__in=sku_ids) # 获取当前被勾选商品的库存 sku_count = new_cart_dict[sku.id] # 获取sku商品原始的库存stock和销量sales origin_stock = sku.stock origin_sales = sku.sales # # 模型网络延迟 # import time # time.sleep(5) # 如果订单中的商品数量大于库存,响应库存不足 if sku_count > origin_stock: # 库存不足,回滚 transaction.savepoint_rollback(save_id) print(request.user, '库存不足') return http.JsonResponse({'code': RETCODE.STOCKERR, 'errmsg': err_msg[RETCODE.STOCKERR]}) # 如果库存满足,SKU 减库存,加销量 new_stock = origin_stock - sku_count new_sales = origin_sales + sku_count result = SKU.objects.filter(id=sku_id, stock=origin_stock).update(stock=new_stock, sales=new_sales) # 如果在更新数据时,原始数据变化了,那么返回0,表示有资源抢夺 if result == 0: # 由于其他用户提前对该商品完成下单,该商品此次下单失败,重新进行下单 continue # SPU 加销量 sku.spu.sales += sku_count sku.spu.save() OrderGoods.objects.create( order=order, sku=sku, count=sku_count, price=sku.price, ) # 累加订单中商品的总价和总数量 order.total_count += sku_count order.total_amount += (sku_count * sku.price) # 该件商品下单成功,退出循环 break # 添加邮费和保存订单信息 order.total_amount += order.freight order.save() # 对于未知的数据库错误,暴力回滚 except Exception as e: logger.error(e) transaction.savepoint_rollback(save_id) return http.JsonResponse({'code': RETCODE.ORDEROPERATEERR, 'errmsg': err_msg[RETCODE.ORDEROPERATEERR]}) else: # 提交事务 transaction.savepoint_commit(save_id) # 清除购物车中已结算的商品 pl = redis_conn.pipeline() pl.hdel('carts_%s' % user.id, *redis_selected) pl.srem('selected_%s' % user.id, *redis_selected) try: pl.execute() except Exception as e: logger.error(e) return http.JsonResponse({'code': RETCODE.DUPLICATEORDERERR, 'errmsg': err_msg[RETCODE.DUPLICATEORDERERR]}) else: # 返回响应 return http.JsonResponse({'code': RETCODE.OK, 'errmsg': err_msg[RETCODE.OK], 'order_id': order_id}) class OrderSettlementView(LoginRequiredMixin, View): """结算订单""" def get(self, request): """查询并展示要结算的订单数据""" # 获取登录用户 user = request.user # 查询用户收货地址,没有被删除的收货地址 try: addresses = Address.objects.filter(user=user, is_deleted=False) except Exception as e: logger.error(e) # 如果没有查询出收货地址,可以去编辑收货地址 addresses = None # 查询redis中购物车被勾选的商品 redis_conn = get_redis_connection('carts') # 购物车中商品的数量 redis_cart = redis_conn.hgetall('carts_%s' % user.id) # 被勾选的商品sku_id redis_selected = redis_conn.smembers('selected_{}'.format(user.id)) # 构造购物车中被勾选商品的数据 new_cart_dict,{sku_id: 2, sku_id: 1} new_cart_dict = {} for sku_id in redis_selected: new_cart_dict[int(sku_id)] = int(redis_cart[sku_id]) # 获取被勾选商品的sku_id sku_ids = new_cart_dict.keys() # 获取被勾选商品的sku信息 skus = SKU.objects.filter(id__in=sku_ids) # 商品总数量与商品总金额 total_count = 0 total_amount = Decimal(0.00) # 或 Decimal('0.00') for sku in skus: # 遍历skus,给每个sku补充count(数量)和amount(小计)字段 sku.count = new_cart_dict[sku.id] sku.amount = sku.price * sku.count # Decimal类型 # 累加商品数量和金额 total_count += sku.count total_amount += sku.amount # 构造上下文 context = { 'addresses': addresses, 'skus': skus, 'total_count': total_count, 'total_amount': total_amount, 'freight': constants.ORDERS_FREIGHT_COST, # 运费 'payment_amount': Decimal(constants.ORDERS_FREIGHT_COST) + total_amount, } return render(request, 'place_order.html', context)
score = json_dict.get('score') comment = json_dict.get('comment') is_anonymous = json_dict.get('is_anonymous') # 校验参数 if not all([order_id, sku_id, score, comment]): return http.HttpResponseForbidden('缺少必传参数') try: OrderInfo.objects.filter(order_id=order_id, user=request.user, status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']) except OrderInfo.DoesNotExist: return http.HttpResponseForbidden('参数order_id错误') try: sku = SKU.objects.get(id=sku_id) except SKU.DoesNotExist: return http.HttpResponseForbidden('参数sku_id错误') if is_anonymous: if not isinstance(is_anonymous, bool): return http.HttpResponseForbidden('参数is_anonymous错误') # 以下操作数据库的操作,开启作为一次事务 with transaction.atomic(): # 在数据库操作前,创建保存点(数据库最初的状态) save_id = transaction.savepoint() try: # 保存订单商品评价数据 OrderGoods.objects.filter(order_id=order_id, sku_id=sku_id, is_commented=False).update( comment=comment, score=score, is_anonymous=is_anonymous, is_commented=True ) # 累计评论数据 sku.comments += 1 sku.save() sku.spu.comments += 1 sku.spu.save() # 如果所有订单商品都已评价,则修改订单状态为已完成 if OrderGoods.objects.filter(order_id=order_id, is_commented=False).count() == 0: OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['FINISHED']) # 对于未知的数据库错误,暴力回滚 except Exception as e: logger.error(e) transaction.savepoint_rollback(save_id) return http.JsonResponse({'code': RETCODE.COMMITMENTERR, 'errmsg': err_msg[RETCODE.COMMITMENTERR]}) else: # 提交事务 transaction.savepoint_commit(save_id) return http.JsonResponse({'code': RETCODE.OK, 'errmsg': err_msg[RETCODE.OK]}) class UserOrderInfoView(LoginRequiredMixin, View): """我的订单""" def get(self, request, page_num): """提供我的订单页面""" user = request.user # 查询订单 orders = user.orderinfo_set.all().order_by("-create_time") # 遍历所有订单 for order in orders: # 绑定订单状态 order.status_name = OrderInfo.ORDER_STATUS_CHOICES[order.status-1][1] # 绑定支付方式 order.pay_met
identifier_body
test1.go
// Copyright 2018 Alexander S.Kresin <alex@kresin.ru>, http://www.kresin.ru // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "fmt" egui "github.com/alkresin/external" "io/ioutil" "strconv" "time" ) const ( CLR_LBLUE = 16759929 CLR_LBLUE0 = 12164479 CLR_LBLUE2 = 16770002 CLR_LBLUE3 = 16772062 CLR_LBLUE4 = 16775920 CLR_GRAY = 0x333333 CLR_LGRAY1 = 0xeeeeee ) var arr = [][]string{{"Alex", "17", "1200", "f", "1"}, {"Victor", "42", "1600", "f", "2"}, {"John", "31", "1000", "f", "3"}} func main() { var sInit string { b, err := ioutil.ReadFile("test.ini") if err != nil { sInit = "" } else { sInit = string(b) } } if egui.Init(sInit) != 0 { return } egui.CreateStyle(&(egui.Style{Name: "st1", Orient: 1, Colors: []int32{CLR_LBLUE, CLR_LBLUE3}})) egui.CreateStyle(&(egui.Style{Name: "st2", Colors: []int32{CLR_LBLUE}, BorderW: 3})) egui.CreateStyle(&(egui.Style{Name: "st3", Colors: []int32{CLR_LBLUE}, BorderW: 2, BorderClr: CLR_LBLUE0})) egui.CreateStyle(&(egui.Style{Name: "st4", Colors: []int32{CLR_LBLUE2, CLR_LBLUE3}, BorderW: 1, BorderClr: CLR_LBLUE})) pWindow := &egui.Widget{X: 100, Y: 100, W: 400, H: 280, Title: "External"} egui.InitMainWindow(pWindow) egui.Menu("") { egui.Menu("File") { egui.AddMenuItem("Set text to label", 0, func(p []string) string { egui.Widg("main.l1").SetText(p[1]); return "" }, "fsett2", "Bye...1") egui.AddMenuSeparator() egui.AddMenuItem("Printing", 0, fprint, "fprint") egui.AddMenuSeparator() egui.AddMenuItem("Exit", 0, nil, "hwg_EndWindow()") } egui.EndMenu() egui.Menu("Dialogs") { egui.AddMenuItem("Open dialog", 0, fsett3, "fsett3") egui.AddMenuItem("Test Tab", 0, ftab, "ftab") egui.AddMenuItem("Test browse", 0, fbrowse, "fbrowse") } egui.EndMenu() egui.Menu("Standard dialogs") { egui.AddMenuItem("Message boxes", 0, fmbox1, "fmbox1") egui.AddMenuItem("MsgGet box", 0, fmbox2, "fmbox2") egui.AddMenuItem("Choice", 0, fmbox3, "fmbox3") egui.AddMenuItem("Select color", 0, fsele_color, "fsele_color") egui.AddMenuItem("Select font", 0, fsele_font, "fsele_font") egui.AddMenuItem("Select file", 0, fsele_file, "fsele_file") } egui.EndMenu() egui.Menu("Help") { egui.AddMenuItem("About", 0, nil, "hwg_MsgInfo(hb_version()+chr(10)+chr(13)+hwg_version(),\"About\")") } egui.EndMenu() } egui.EndMenu() pPanel := pWindow.AddWidget(&egui.Widget{Type: "paneltop", H: 40, AProps: map[string]string{"HStyle": "st1"}}) pPanel.AddWidget(&egui.Widget{Type: "ownbtn", X: 0, Y: 0, W: 56, H: 40, Title: "Date", AProps: map[string]string{"HStyles": egui.ToString("st1", "st2", "st3")}}) egui.PLastWidget.SetCallBackProc("onclick", nil, "hwg_WriteStatus(HWindow():GetMain(),1,Dtoc(Date()),.T.)") pPanel.AddWidget(&egui.Widget{Type: "ownbtn", X: 56, Y: 0, W: 56, H: 40, Title: "Time", AProps: map[string]string{"HStyles": egui.ToString("st1", "st2", "st3")}}) egui.PLastWidget.SetCallBackProc("onclick", nil, "hwg_WriteStatus(HWindow():GetMain(),2,Time(),.T.)") pPanel.AddWidget(&egui.Widget{Type: "ownbtn", X: 112, Y: 0, W: 56, H: 40, Title: "Get", AProps: map[string]string{"HStyles": egui.ToString("st1", "st2", "st3")}}) egui.PLastWidget.SetCallBackProc("onclick", fsett3, "fsett3") pWindow.AddWidget(&egui.Widget{Type: "label", Name: "l1", X: 20, Y: 60, W: 180, H: 24, Title: "Test of a label", AProps: map[string]string{"Transpa": "t"}}) pWindow.AddWidget(&egui.Widget{Type: "button", X: 200, Y: 56, W: 100, H: 32, Title: "SetText"}) egui.PLastWidget.SetCallBackProc("onclick", fsett1, "fsett1", "first parameter") pWindow.AddWidget(&egui.Widget{Type: "panelbot", H: 32, AProps: map[string]string{"HStyle": "st4", "AParts": egui.ToString(120, 120, 0)}}) pWindow.Activate() egui.Exit() } func fsett1(p []string) string { pLabel := egui.Widg("main.l1") fmt.Println(pLabel.GetText()) pLabel.SetText(p[1]) return "" } func fsett3([]string) string { egui.BeginPacket() egui.SetDateFormat("DD.MM.YYYY") pFont := egui.CreateFont(&egui.Font{Name: "f1", Family: "Georgia", Height: 16}) pDlg := &egui.Widget{Name: "dlg", X: 300, Y: 200, W: 400, H: 260, Title: "Dialog Test", Font: pFont} egui.InitDialog(pDlg) pDlg.AddWidget(&egui.Widget{Type: "label", X: 20, Y: 10, W: 160, H: 24, Title: "Identifier:"}) pDlg.AddWidget(&egui.Widget{Type: "edit", Name: "edi1", X: 20, Y: 32, W: 160, H: 24, AProps: map[string]string{"Picture": "@!R /XXX:XXX/"}}) pDlg.AddWidget(&egui.Widget{Type: "label", X: 220, Y: 10, W: 160, H: 24, Title: "Date:"}) pDlg.AddWidget(&egui.Widget{Type: "edit", Name: "edi2", X: 220, Y: 32, W: 120, H: 24, Title: time.Now().Format("20060102"), AProps: map[string]string{"Picture": "D@D"}}) pDlg.AddWidget(&egui.Widget{Type: "combo", Name: "comb", X: 20, Y: 68, W: 160, H: 24, AProps: map[string]string{"AItems": egui.ToString("first", "second", "third")}}) pDlg.AddWidget(&egui.Widget{Type: "label", X: 220, Y: 68, W: 80, H: 24, Title: "Age:"}) pDlg.AddWidget(&egui.Widget{Type: "updown", Name: "upd1", X: 280, Y: 68, W: 60, H: 24}) pDlg.AddWidget(&egui.Widget{Type: "group", X: 10, Y: 110, W: 180, H: 76, Title: "Check"}) pDlg.AddWidget(&egui.Widget{Type: "check", Name: "chk1", X: 24, Y: 124, W: 150, H: 24, Title: "Married"}) pDlg.AddWidget(&egui.Widget{Type: "check", Name: "chk2", X: 24, Y: 148, W: 150, H: 24, Title: "Has children"}) pGroup := pDlg.AddWidget(&egui.Widget{Type: "radiogr", Name: "rg", X: 200, Y: 110, W: 180, H: 76, Title: "Radio"}) pDlg.AddWidget(&egui.Widget{Type: "radio", X: 224, Y: 124, W: 150, H: 24, Title: "Male"}) pDlg.AddWidget(&egui.Widget{Type: "radio", X: 224, Y: 148, W: 150, H: 24, Title: "Female"}) egui.RadioEnd(pGroup, 1) pDlg.AddWidget(&egui.Widget{Type: "button", X: 150, Y: 220, W: 100, H: 32, Title: "Ok"}) egui.PLastWidget.SetCallBackProc("onclick", fsett4, "fsett4") pDlg.Activate() egui.EndPacket() return "" } func fsett4([]string) string
func ftab([]string) string { egui.BeginPacket() pFont := egui.CreateFont(&egui.Font{Name: "f1", Family: "Georgia", Height: 16}) pDlg := &egui.Widget{Name: "dlg2", X: 300, Y: 200, W: 200, H: 340, Title: "Tab", Font: pFont, AProps: map[string]string{"NoExitOnEsc": "t","NoCloseAble": "t"}} egui.InitDialog(pDlg) pTab := pDlg.AddWidget(&egui.Widget{Type: "tab", X: 10, Y: 10, W: 180, H: 280}) egui.TabPage(pTab, "First") pTab.AddWidget(&egui.Widget{Type: "label", X: 20, Y: 30, W: 140, H: 24, Title: "Name:"}) pTab.AddWidget(&egui.Widget{Type: "edit", X: 20, Y: 52, W: 140, H: 24}) pTab.AddWidget(&egui.Widget{Type: "label", X: 20, Y: 84, W: 140, H: 24, Title: "Surname:"}) pTab.AddWidget(&egui.Widget{Type: "edit", X: 20, Y: 106, W: 140, H: 24}) egui.TabPageEnd(pTab) egui.TabPage(pTab, "Second") pTab.AddWidget(&egui.Widget{Type: "label", X: 20, Y: 40, W: 140, H: 24, Title: "Age:"}) pTab.AddWidget(&egui.Widget{Type: "edit", X: 20, Y: 62, W: 140, H: 24}) pTab.AddWidget(&egui.Widget{Type: "label", X: 20, Y: 94, W: 140, H: 24, Title: "Profession:"}) pTab.AddWidget(&egui.Widget{Type: "edit", X: 20, Y: 116, W: 140, H: 24}) egui.TabPageEnd(pTab) pDlg.AddWidget(&egui.Widget{Type: "button", X: 60, Y: 300, W: 100, H: 32, Title: "Ok"}) egui.PLastWidget.SetCallBackProc("onclick", ftabclose, "ftabclose") pDlg.Activate() egui.EndPacket() return "" } func ftabclose([]string) string { egui.PLastWindow.Close() return "" } func fbrowse([]string) string { egui.BeginPacket() pFont := egui.CreateFont(&egui.Font{Name: "f1", Family: "Georgia", Height: 16}) pDlg := &egui.Widget{Name: "dlg2", X: 300, Y: 200, W: 280, H: 240, Title: "browse", Font: pFont} egui.InitDialog(pDlg) pBrw := pDlg.AddWidget(&egui.Widget{Type: "browse", Name: "brw", X: 10, Y: 10, W: 260, H: 140}) pBrw.SetParam("oStyleHead", egui.GetStyle("st1")) pBrw.SetParam("tColor", CLR_GRAY) pBrw.SetParam("bColorSel", CLR_LGRAY1) pBrw.SetParam("htbColor", CLR_LGRAY1) pBrw.SetParam("tColorSel", 0) pBrw.SetParam("httColor", 0) pBrw.SetParam("lInFocus", true) egui.BrwSetArray(pBrw, &arr) egui.BrwDelColumn(pBrw, 5) egui.BrwSetColumn(pBrw, 1, "Name", 1, 0, false, 0) egui.BrwSetColumn(pBrw, 2, "Age", 1, 0, false, 0) egui.BrwSetColumn(pBrw, 3, "Salary", 1, 0, true, 0) egui.BrwSetColumnEx(pBrw, 2, "bColor", CLR_LBLUE3) egui.BrwSetColumnEx(pBrw, 2, "lResizable", false) pBrw.SetCallBackProc("onposchanged", fbrwpc, "fbrwpc") pBrw.SetCallBackProc("onrclick", fbrwrc, "fbrwrc") pDlg.AddWidget(&egui.Widget{Type: "label", Name: "l1", X: 90, Y: 160, W: 100, H: 24, Winstyle: egui.DT_CENTER}) pDlg.AddWidget(&egui.Widget{Type: "button", X: 90, Y: 200, W: 100, H: 32, Title: "Ok"}) egui.PLastWidget.SetCallBackProc("onclick", fbrwclose, "fbrwclose") pDlg.Activate() egui.EndPacket() return "" } func fbrwclose([]string) string { arrNew := egui.BrwGetArray(egui.Widg("dlg2.brw")) egui.PLastWindow.Close() s := "" for i, a := range arrNew { if a[2] != arr[i][2] { s += a[0] + " => " + a[2] + "\r\n" } } if s != "" { egui.MsgInfo(s, "Changes", nil, "", "") } return "" } func fbrwpc(p []string) string { pLabel := egui.Widg("dlg2.l1") if len(p) > 1 { i, _ := strconv.Atoi(p[1]) if i > 0 && i <= 3 { pLabel.SetText(arr[i-1][0]) } } return "" } func fbrwrc(p []string) string { if len(p) > 2 { egui.MsgInfo(p[0]+" Row: "+p[2]+" Col: "+p[1], "Right click position", nil, "", "") } return "" } func fmbox1(p []string) string { if p[0] == "menu" { egui.MsgYesNo("Yes or No???", "MsgBox", fmbox1, "fmbox1", "mm1") } else if p[0] == "mm1" { if p[1] == "t" { egui.MsgInfo("Yes!", "Answer", nil, "", "") } else { egui.MsgInfo("No...", "Answer", nil, "", "") } } return "" } func fmbox2(p []string) string { if p[0] == "menu" { egui.MsgGet("Input something:", "MsgGet", 0, fmbox2, "fmbox2", "mm1") } else if p[0] == "mm1" { egui.MsgInfo(p[1], "Answer", nil, "", "") } return "" } func fmbox3(p []string) string { if p[0] == "menu" { arr := []string{"Alex Petrov", "Serg Lama", "Jimmy Hendrix", "Dorian Gray", "Victor Peti"} egui.Choice(arr, "Select from a list", fmbox3, "fmbox3", "mm1") } else if p[0] == "mm1" { egui.MsgInfo(p[1], "Answer", nil, "", "") } return "" } func fsele_color(p []string) string { if p[0] == "menu" { egui.SelectColor(0, fsele_color, "fsele_color", "mm1") } else { iColor, _ := strconv.Atoi(p[1]) egui.Widg("main.l1").SetColor(int32(iColor), -1) } return "" } func fsele_font(p []string) string { if p[0] == "menu" { egui.SelectFont(fsele_font, "fsele_font", "") } else { fmt.Println("font id: ", p[0]) if pFont := egui.GetFont(p[0]); pFont != nil { if len(p) < 8 { } else { fmt.Println("font fam: ", p[1]) } egui.Widg("main.l1").SetFont( pFont ); } } return "" } func fsele_file(p []string) string { if p[0] == "menu" { egui.SelectFile("", fsele_file, "fsele_file", "mm1") } else { if p[1] == "" { egui.MsgInfo("Nothing selected", "Result", nil, "", "") } else { egui.MsgInfo(p[1], "File selected", nil, "", "") } } return "" } func fprint(p []string) string { if p[0] == "menu" { egui.InitPrinter(&egui.Printer{SPrinter: "...", BPreview: true}, "fprint", fprint, "mm1") } else { pPrinter := egui.PLastPrinter pFont := pPrinter.AddFont(&egui.Font{Family: "Times New Roman", Height: 10}) pPrinter.StartPage() pPrinter.SetFont(pFont) pPrinter.Box(5, 5, 200, 282) pPrinter.Say(50, 10, 165, 26, "Printing first sample !", egui.DT_CENTER) pPrinter.Line(45, 30, 170, 30) pPrinter.Line(45, 5, 45, 30) pPrinter.Line(170, 5, 170, 30) pPrinter.Say(50, 120, 150, 132, "----------", egui.DT_CENTER) pPrinter.Box(50, 134, 160, 146) pPrinter.Say(50, 135, 160, 146, "End Of Report", egui.DT_CENTER) pPrinter.EndPage() pPrinter.End() } return "" }
{ arr := egui.GetValues(egui.Wnd("dlg"), []string{"edi1", "edi2", "comb", "chk1", "chk2", "rg", "upd1"}) egui.PLastWindow.Close() egui.MsgInfo("Id: "+arr[0]+"\r\n"+"Date: "+arr[1]+"\r\n"+"Combo: "+arr[2]+"\r\n"+ "Married: "+arr[3]+"\r\n"+"Has children: "+arr[4]+"\r\n"+"Sex: "+arr[5]+"\r\n"+ "Age: "+arr[6], "Result", nil, "", "") return "" }
identifier_body